file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
sr_mulher.py | # !/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
ERP+
"""
__author__ = 'CVtek dev'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "CVTek dev"
__status__ = "Development"
__model_name__ = 'sr_mulher.SRMulher'
import auth, base_models
from orm import *
from form import *
class SRMulher(Model, View):
| def __init__(self, **kargs):
Model.__init__(self, **kargs)
self.__name__ = 'sr_mulher'
self.__title__ ='Inscrição e Identificação da Mulher'
self.__model_name__ = __model_name__
self.__list_edit_mode__ = 'edit'
self.__get_options__ = ['nome'] # define tambem o campo a ser... | identifier_body | |
sr_mulher.py | # !/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
ERP+
"""
__author__ = 'CVtek dev'
__credits__ = [] | __status__ = "Development"
__model_name__ = 'sr_mulher.SRMulher'
import auth, base_models
from orm import *
from form import *
class SRMulher(Model, View):
def __init__(self, **kargs):
Model.__init__(self, **kargs)
self.__name__ = 'sr_mulher'
self.__title__ ='Inscrição e Identificação da Mul... | __version__ = "1.0"
__maintainer__ = "CVTek dev" | random_line_split |
crypto.ts | import crypto from 'crypto';
import { Faker } from '../faker';
export class Crypto {
private CHARACTERS: string = '0123456789abcdefghijklmnopqrstuvwxyz';
private readonly faker: Faker;
constructor(faker: Faker) {
this.faker = faker;
}
public md5(): string {
const hash = crypto.createHash('md5');
... | (): string {
const hash = crypto.createHash('sha256');
const array = this.CHARACTERS.split('');
const characters = this.faker.Random.assortment(array, 255).join('');
hash.update(characters);
return hash.digest('hex');
}
}
| sha256 | identifier_name |
crypto.ts | import crypto from 'crypto';
import { Faker } from '../faker';
export class Crypto {
private CHARACTERS: string = '0123456789abcdefghijklmnopqrstuvwxyz';
private readonly faker: Faker;
constructor(faker: Faker) {
this.faker = faker;
}
public md5(): string {
const hash = crypto.createHash('md5');
... |
}
| {
const hash = crypto.createHash('sha256');
const array = this.CHARACTERS.split('');
const characters = this.faker.Random.assortment(array, 255).join('');
hash.update(characters);
return hash.digest('hex');
} | identifier_body |
crypto.ts | import crypto from 'crypto';
import { Faker } from '../faker';
export class Crypto {
private CHARACTERS: string = '0123456789abcdefghijklmnopqrstuvwxyz';
| constructor(faker: Faker) {
this.faker = faker;
}
public md5(): string {
const hash = crypto.createHash('md5');
const array = this.CHARACTERS.split('');
const characters = this.faker.Random.assortment(array, 255).join('');
hash.update(characters);
return hash.digest('hex');
}
public ... | private readonly faker: Faker;
| random_line_split |
codeBlockSelectLang.element.tsx | import { EG, p } from '@web-companions/gfc';
import { render } from 'lit-html2';
import { HLJS_LANGUAGES } from './utils';
export const codeBlockSelectLangElement = EG({
props: {
domCodeEl: p.req<HTMLElement>(),
selectedLanguage: p.req<string>(),
onChange: p.req<(language: string | null) => void>(),
},... | }
}); | random_line_split | |
codeBlockSelectLang.element.tsx | import { EG, p } from '@web-companions/gfc';
import { render } from 'lit-html2';
import { HLJS_LANGUAGES } from './utils';
export const codeBlockSelectLangElement = EG({
props: {
domCodeEl: p.req<HTMLElement>(),
selectedLanguage: p.req<string>(),
onChange: p.req<(language: string | null) => void>(),
},... | );
| {
yield render(
<>
<pre>{params.domCodeEl}</pre>
<select class='hljs-codeblock__select' contentEditable={false} value={params.selectedLanguage} onchange={updateAttributes}>
<option value="null" selected={params.selectedLanguage == null}>
auto
</option>
... | conditional_block |
profile-link-text.component.ts | // Copyright 2014 The Oppia 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 required by ap... |
}
angular.module('oppia').directive(
'profileLinkText', downgradeComponent(
{component: ProfileLinkTextComponent}));
| {
return ['admin', 'OppiaMigrationBot'].indexOf(username) === -1;
} | identifier_body |
profile-link-text.component.ts | // Copyright 2014 The Oppia 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 required by ap... | (username: string): boolean {
return ['admin', 'OppiaMigrationBot'].indexOf(username) === -1;
}
}
angular.module('oppia').directive(
'profileLinkText', downgradeComponent(
{component: ProfileLinkTextComponent}));
| isUsernameLinkable | identifier_name |
profile-link-text.component.ts | // Copyright 2014 The Oppia 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 required by ap... | */
import { Component, Input } from '@angular/core';
import { downgradeComponent } from '@angular/upgrade/static';
import { AppConstants } from 'app.constants';
@Component({
selector: 'profile-link-text',
templateUrl: './profile-link-text.component.html',
styleUrls: []
})
export class ProfileLinkTextComponent ... | * @fileoverview Component for creating text links to a user's profile page. | random_line_split |
block_header.rs | use Encode;
use VarInt;
#[derive(Debug, Encode, PartialEq)]
/// 4 version int32_t Block version information (note, this is signed)
/// 32 prev_block char[32] The hash value of the previous block this particular block references
/// 32 merkle_root char[32] The reference to a Merkle tree collection which is a hash of al... |
pub version: i32,
pub prev_block: [u8; 32],
pub merkle_root: [u8; 32],
pub timestamp: u32,
pub bits: u32,
pub nonce: u32,
/// txn_count is a var_int on the wire
pub txn_count: VarInt,
}
| ockHeader { | identifier_name |
block_header.rs | use Encode;
use VarInt;
#[derive(Debug, Encode, PartialEq)]
/// 4 version int32_t Block version information (note, this is signed)
/// 32 prev_block char[32] The hash value of the previous block this particular block references
/// 32 merkle_root char[32] The reference to a Merkle tree collection which is a hash of al... | } | pub txn_count: VarInt, | random_line_split |
__init__.py | #!/usr/bin/python
#-*- coding:utf-8 -*-
__author__ = 'david'
import numpy as np
import nibabel as nib
import resources as rs
# from vispy import app
from plot import Canvas
import matplotlib.pyplot as plt
import gc
np.random.seed()
class Clarity(object):
def __init__(self,token,imgfile=None,pointsfile=None):
... | self._pointsfile = pointsfile
self._img = None # img data
self._points = None # [[x],[y],[z],[v]]
self._shape = None # (x,y,z)
self._max = None # max value
def loadImg(self, path=None, info=False):
if path is None:
path = rs.RAW_DATA_PATH
... |
self._token = token
self._imgfile = imgfile | random_line_split |
__init__.py | #!/usr/bin/python
#-*- coding:utf-8 -*-
__author__ = 'david'
import numpy as np
import nibabel as nib
import resources as rs
# from vispy import app
from plot import Canvas
import matplotlib.pyplot as plt
import gc
np.random.seed()
class Clarity(object):
def __init__(self,token,imgfile=None,pointsfile=None):
... |
def loadPoints(self,path=None):
if path is None:
path = rs.POINTS_DATA_PATH
pathname = path+self._token+".csv"
self._points = np.loadtxt(pathname,dtype=np.int16,delimiter=',')
print("Points Loaded: %s"%(pathname))
return self
def savePoints(self,path=None):... | if not 0 <= threshold < 1:
raise ValueError("Threshold should be within [0,1).")
if not 0 < sample <= 1:
raise ValueError("Sample rate should be within (0,1].")
if self._img is None:
raise ValueError("Img haven't loaded, please call loadImg() first.")
total =... | identifier_body |
__init__.py | #!/usr/bin/python
#-*- coding:utf-8 -*-
__author__ = 'david'
import numpy as np
import nibabel as nib
import resources as rs
# from vispy import app
from plot import Canvas
import matplotlib.pyplot as plt
import gc
np.random.seed()
class Clarity(object):
def __init__(self,token,imgfile=None,pointsfile=None):
... | (self,scale=30):
# get image histogram
imhist, bins = np.histogram(self._points[:,3],256,density=True)
cdf = imhist.cumsum() # cumulative distribution function
cdf = scale * cdf / cdf[-1] # normalize
# use linear interpolation of cdf to find new pixel values
ret... | histogramEqualize | identifier_name |
__init__.py | #!/usr/bin/python
#-*- coding:utf-8 -*-
__author__ = 'david'
import numpy as np
import nibabel as nib
import resources as rs
# from vispy import app
from plot import Canvas
import matplotlib.pyplot as plt
import gc
np.random.seed()
class Clarity(object):
def __init__(self,token,imgfile=None,pointsfile=None):
... |
return np.histogram(self._img.flatten(), bins=bins, range=range, density=density)
def imgToPoints(self, threshold=0.1, sample=0.5, optimize=True):
if not 0 <= threshold < 1:
raise ValueError("Threshold should be within [0,1).")
if not 0 < sample <= 1:
raise ValueEr... | raise ValueError("Img haven't loaded, please call loadImg() first.") | conditional_block |
test_universe.py | import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set... |
u.remove_cell(c3)
cells = set(u.cells.values())
assert not (cells ^ {c1, c2})
u.clear_cells()
assert not set(u.cells)
def test_bounding_box():
cyl1 = openmc.ZCylinder(r=1.0)
cyl2 = openmc.ZCylinder(r=2.0)
c1 = openmc.Cell(region=-cyl1)
c2 = openmc.Cell(region=+cyl1 & -cyl2)
... | u.add_cells(c1) | random_line_split |
test_universe.py | import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set... |
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=... | m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
) | identifier_body |
test_universe.py | import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set... |
def test_get_nuclides(uo2):
c = openmc.Cell(fill=uo2)
univ = openmc.Universe(cells=[c])
nucs = univ.get_nuclides()
assert nucs == ['U235', 'O16']
def test_cells():
cells = [openmc.Cell() for i in range(5)]
cells2 = [openmc.Cell() for i in range(3)]
cells[0].fill = openmc.Universe(cells=... | univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
) | conditional_block |
test_universe.py | import xml.etree.ElementTree as ET
import numpy as np
import openmc
import pytest
from tests.unit_tests import assert_unbounded
def test_basic():
c1 = openmc.Cell()
c2 = openmc.Cell()
c3 = openmc.Cell()
u = openmc.Universe(name='cool', cells=(c1, c2, c3))
assert u.name == 'cool'
cells = set... | (run_in_tmpdir, sphere_model):
m = sphere_model.materials[0]
univ = sphere_model.geometry.root_universe
colors = {m: 'limegreen'}
for basis in ('xy', 'yz', 'xz'):
univ.plot(
basis=basis,
pixels=(10, 10),
color_by='material',
colors=colors,
... | test_plot | identifier_name |
input-names.ts | /**
* @license
* Copyright Google LLC 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 {WorkspacePath} from '../../update-tool/file-system';
import {findInputsOnElementWithAttr, findInputsOnElement... |
visitTemplate(template: ResolvedResource): void {
this.data.forEach(name => {
const limitedTo = name.limitedTo;
const relativeOffsets: number[] = [];
if (limitedTo.attributes) {
relativeOffsets.push(
...findInputsOnElementWithAttr(template.content, name.replace, limitedTo.a... | start => this._replaceInputName(
stylesheet.filePath, start, currentSelector.length, updatedSelector));
});
} | random_line_split |
input-names.ts | /**
* @license
* Copyright Google LLC 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 {WorkspacePath} from '../../update-tool/file-system';
import {findInputsOnElementWithAttr, findInputsOnElement... | (template: ResolvedResource): void {
this.data.forEach(name => {
const limitedTo = name.limitedTo;
const relativeOffsets: number[] = [];
if (limitedTo.attributes) {
relativeOffsets.push(
...findInputsOnElementWithAttr(template.content, name.replace, limitedTo.attributes));
... | visitTemplate | identifier_name |
input-names.ts | /**
* @license
* Copyright Google LLC 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 {WorkspacePath} from '../../update-tool/file-system';
import {findInputsOnElementWithAttr, findInputsOnElement... |
relativeOffsets.map(offset => template.start + offset)
.forEach(
start => this._replaceInputName(
template.filePath, start, name.replace.length, name.replaceWith));
});
}
private _replaceInputName(filePath: WorkspacePath, start: number, width: number,
... | {
relativeOffsets.push(
...findInputsOnElementWithTag(template.content, name.replace, limitedTo.elements));
} | conditional_block |
util.d.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 | export declare function normalizeGenFileSuffix(srcFileSuffix: string): string;
export declare function summaryFileName(fileName: string): string;
export declare function summaryForJitFileName(fileName: string, forceSourceFile?: boolean): string;
export declare function stripSummaryForJitFileSuffix(filePath: string): st... | */
export declare function ngfactoryFilePath(filePath: string, forceSourceFile?: boolean): string;
export declare function stripGeneratedFileSuffix(filePath: string): string;
export declare function isGeneratedFile(filePath: string): boolean;
export declare function splitTypescriptSuffix(path: string, forceSourceFile?... | random_line_split |
mod.rs | use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC};
use std::rc::{Rc, Weak};
/// X = Y
pub struct EqXY;
impl EqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
// TODO merge or at least intersect domains
LeXY::new(model.clone(), x.clone(), y.c... |
fn x(&self) -> Rc<FDVar> {
self.vars.get(0).clone()
}
fn y(&self) -> Rc<FDVar> {
self.vars.get(1).clone()
}
}
impl Propagator for NeqXYCxy {
fn id(&self) -> uint {
self.id
}
fn model(&self) -> Weak<Mod> {
self.model.clone()
}
fn events(&self) -> V... | {
let id = model.propagators.borrow().len();
let this = NeqXYCxy { model: model.downgrade(), id: id, vars: vec![x, y], c: c};
let p = Rc::new((box this) as Box<Propagator>);
model.add_prop(p);
} | identifier_body |
mod.rs | use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC};
use std::rc::{Rc, Weak};
/// X = Y
pub struct EqXY;
impl EqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
// TODO merge or at least intersect domains
LeXY::new(model.clone(), x.clone(), y.c... |
else if self.y().is_instanciated() {
self.unregister();
self.x().remove(self.y().min() + self.c)
} else {
vec![]
}
}
}
#[cfg(test)]
mod tests;
| {
self.unregister();
self.y().remove(self.x().min() - self.c)
} | conditional_block |
mod.rs | use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC};
use std::rc::{Rc, Weak};
/// X = Y
pub struct EqXY;
impl EqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
// TODO merge or at least intersect domains
LeXY::new(model.clone(), x.clone(), y.c... | (model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) {
NeqXYCxy::new(model, x, y, c);
}
}
/// X != C
pub struct NeqXC;
#[allow(unused_variable)]
impl NeqXC {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, c: int) {
x.remove(c);
}
}
struct NeqXYCxy : Prop {
c: int
}
impl NeqXYCxy {
fn n... | new | identifier_name |
mod.rs | use super::{Event, Ins, Prop, Mod, FDVar, Propagator, LeXY, GeXY, LeXYC, GeXYC, LeXC, GeXC};
use std::rc::{Rc, Weak};
/// X = Y
pub struct EqXY;
impl EqXY {
pub fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>) {
// TODO merge or at least intersect domains
LeXY::new(model.clone(), x.clone(), y.c... | let p = Rc::new((box this) as Box<Propagator>);
model.add_prop(p);
}
fn x(&self) -> Rc<FDVar> {
self.vars.get(0).clone()
}
fn y(&self) -> Rc<FDVar> {
self.vars.get(1).clone()
}
}
impl Propagator for NeqXYCxy {
fn id(&self) -> uint {
self.id
}
fn... | fn new(model: Rc<Mod>, x: Rc<FDVar>, y: Rc<FDVar>, c: int) {
let id = model.propagators.borrow().len();
let this = NeqXYCxy { model: model.downgrade(), id: id, vars: vec![x, y], c: c}; | random_line_split |
unit-test.ts | import gulp = require('gulp');
import path = require('path');
import gulpMerge = require('merge2');
import {PROJECT_ROOT} from '../constants';
import {sequenceTask} from '../task_helpers';
const karma = require('karma');
/** Copies deps for unit tests to the build output. */
gulp.task(':build:test:vendor', function(... | (doneFn: (error?: Error) => void) {
return (exitCode: number) => {
// Immediately exit the process if Karma reported errors, because due to
// potential running Saucelabs browsers gulp won't exit properly.
exitCode === 0 ? doneFn() : process.exit(exitCode);
};
}
| onKarmaFinished | identifier_name |
unit-test.ts | import gulp = require('gulp');
import path = require('path');
import gulpMerge = require('merge2');
import {PROJECT_ROOT} from '../constants';
import {sequenceTask} from '../task_helpers';
const karma = require('karma');
/** Copies deps for unit tests to the build output. */
gulp.task(':build:test:vendor', function(... | {
return (exitCode: number) => {
// Immediately exit the process if Karma reported errors, because due to
// potential running Saucelabs browsers gulp won't exit properly.
exitCode === 0 ? doneFn() : process.exit(exitCode);
};
} | identifier_body | |
unit-test.ts | import gulp = require('gulp');
import path = require('path');
import gulpMerge = require('merge2');
import {PROJECT_ROOT} from '../constants';
import {sequenceTask} from '../task_helpers';
const karma = require('karma');
/** Copies deps for unit tests to the build output. */
gulp.task(':build:test:vendor', function(... | ':build:components:spec'
]
));
/**
* [Watch task] Build unit test dependencies, and rebuild whenever sources are changed.
* This should only be used when running tests locally.
*/
gulp.task(':test:watch', sequenceTask(':test:deps', ':watch:components:spec'));
/** Build unit test dependencies and then inlines... | gulp.task(':test:deps', sequenceTask(
'clean',
[
':build:test:vendor', | random_line_split |
goodsDetails.js | /**
* Created by 殿麒 on 2015/11/3.
*/
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
purchase.controller('goodsDetails',function($rootScope,$scope,$location,$cookieS... | console.log(data);
$scope.goodsInfo = data.productInfo;
});
$scope.addGoodscart = function(){
var goodscart_list = $cookieStore.get('goodscart_list');
$rootScope.GOODSCART_NUM += 1;
$rootScope.GOODSCART_MONEY += $scope.goodsInfo.price;
// 添加cookie
goodsCa... | $scope.saleNum = data.productInfo.salesCnt;
$scope.limitBuy = data.productInfo.subTitle;
$scope.nowSale = data.productInfo.price;
$scope.originSale = data.productInfo.marketPrice || $scope.nowSale; | random_line_split |
goodsDetails.js | /**
* Created by 殿麒 on 2015/11/3.
*/
function GetQueryString(name)
{
| chase.controller('goodsDetails',function($rootScope,$scope,$location,$cookieStore,goodsCartcookie,purchasePost,getAccessInfo){
var self_url = GetQueryString("productId");
if(self_url!= undefined){
var productId = self_url;
}else{
var productId = $rootScope.GOODSINFO.productId;
}
var... | var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
pur | identifier_body |
goodsDetails.js | /**
* Created by 殿麒 on 2015/11/3.
*/
function GetQ | e)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
purchase.controller('goodsDetails',function($rootScope,$scope,$location,$cookieStore,goodsCartcookie,purchasePost,getAccessInfo){
var self_url... | ueryString(nam | identifier_name |
goodsDetails.js | /**
* Created by 殿麒 on 2015/11/3.
*/
function GetQueryString(name)
{
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
purchase.controller('goodsDetails',function($rootScope,$scope,$location,$cookieS... | var data = {
productId:productId,
sign:'sign',
accessInfo:getAccessInfo.accessInfo
}
var path = 'product/detail';
purchasePost.postData(data,path).success(function(data){
var imgs = data.productInfo.images;
// 这里因为数组中是字符串不是对象所以需要想将字符串变为对象
var imgArr = [];
... | var productId = $rootScope.GOODSINFO.productId;
}
| conditional_block |
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)
class PyAzureMgmtDeploymentmanager(PythonPackage):
"""Microsoft Azure Deployment Manager Client Library for Python.""... | depends_on('py-azure-common@1.1:1', type=('build', 'run'))
depends_on('py-azure-mgmt-nspkg', when='^python@:2', type=('build', 'run')) | 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)
class PyAzureMgmtDeploymentmanager(PythonPackage):
| """Microsoft Azure Deployment Manager Client Library for Python."""
homepage = "https://github.com/Azure/azure-sdk-for-python"
pypi = "azure-mgmt-deploymentmanager/azure-mgmt-deploymentmanager-0.2.0.zip"
version('0.2.0', sha256='46e342227993fc9acab1dda42f2eb566b522a8c945ab9d0eea56276b46f6d730')
depen... | 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)
class | (PythonPackage):
"""Microsoft Azure Deployment Manager Client Library for Python."""
homepage = "https://github.com/Azure/azure-sdk-for-python"
pypi = "azure-mgmt-deploymentmanager/azure-mgmt-deploymentmanager-0.2.0.zip"
version('0.2.0', sha256='46e342227993fc9acab1dda42f2eb566b522a8c945ab9d0eea56276b... | PyAzureMgmtDeploymentmanager | identifier_name |
tabs.py | """
This module is essentially a broker to xmodule/tabs.py -- it was originally introduced to
perform some LMS-specific tab display gymnastics for the Entrance Exams feature
"""
from django.conf import settings
from django.utils.translation import ugettext as _, ugettext_noop
from courseware.access import has_access
f... |
dynamic_tabs.sort(key=lambda dynamic_tab: dynamic_tab.name)
return dynamic_tabs
| tab = tab_type(dict())
if tab.is_enabled(course, user=user):
dynamic_tabs.append(tab) | conditional_block |
tabs.py | """
This module is essentially a broker to xmodule/tabs.py -- it was originally introduced to
perform some LMS-specific tab display gymnastics for the Entrance Exams feature
"""
from django.conf import settings
from django.utils.translation import ugettext as _, ugettext_noop
from courseware.access import has_access
f... |
class SingleTextbookTab(CourseTab):
"""
A tab representing a single textbook. It is created temporarily when enumerating all textbooks within a
Textbook collection tab. It should not be serialized or persisted.
"""
type = 'single_textbook'
is_movable = False
is_collection_item = True
... | """
A course tab containing an external link.
"""
type = 'external_link'
priority = None
is_default = False # An external link tab is not added to a course by default
allow_multiple = True
@classmethod
def validate(cls, tab_dict, raise_error=True):
""" Validate that the tab_d... | identifier_body |
tabs.py | """
This module is essentially a broker to xmodule/tabs.py -- it was originally introduced to
perform some LMS-specific tab display gymnastics for the Entrance Exams feature
"""
from django.conf import settings
from django.utils.translation import ugettext as _, ugettext_noop
from courseware.access import has_access
f... | (cls, course, user=None):
return True
class SyllabusTab(EnrolledTab):
"""
A tab for the course syllabus.
"""
type = 'syllabus'
title = ugettext_noop('Syllabus')
priority = 30
view_name = 'syllabus'
allow_multiple = True
is_default = False
is_visible_to_sneak_peek = True... | is_enabled | identifier_name |
tabs.py | """
This module is essentially a broker to xmodule/tabs.py -- it was originally introduced to
perform some LMS-specific tab display gymnastics for the Entrance Exams feature
"""
from django.conf import settings
from django.utils.translation import ugettext as _, ugettext_noop
from courseware.access import has_access
f... | # Rename 'Courseware' tab to 'Entrance Exam'
if tab.type is not 'courseware':
continue
tab.name = _("Entrance Exam")
course_tab_list.append(tab)
# Add in any dynamic tabs, i.e. those that are not persisted
course_tab_list += _get_dynamic_tabs(course, ... | if user_must_complete_entrance_exam(request, user, course):
# Hide all of the tabs except for 'Courseware' | random_line_split |
ModelSpec.js | var Model = require('../lib/Model');
var Properties = require('../lib/Properties');
describe('Model', function() {
it('should assign properties to the object', function () {
var aModel = new Model('test', {
a: Properties.string
}, {a: 'test'});
expect(aModel.a).toEqual('test');
});
it('should rename pr... | }); | random_line_split | |
get-with-headers.py | #!/usr/bin/env python
"""This does HTTP GET requests given a host:port and path and returns
a subset of the headers plus the body of the result."""
from __future__ import absolute_import, print_function
import json
import os
import sys
from edenscm.mercurial import util
httplib = util.httplib
try:
import msv... | (host, path, show):
assert not path.startswith("/"), path
global tag
headers = {}
if tag:
headers["If-None-Match"] = tag
if hgproto:
headers["X-HgProto-1"] = hgproto
conn = httplib.HTTPConnection(host)
conn.request("GET", "/" + path, None, headers)
response = conn.getres... | request | identifier_name |
get-with-headers.py | #!/usr/bin/env python
"""This does HTTP GET requests given a host:port and path and returns
a subset of the headers plus the body of the result."""
from __future__ import absolute_import, print_function
import json
import os
import sys
from edenscm.mercurial import util
httplib = util.httplib
try:
import msv... |
status = request(sys.argv[1], sys.argv[2], sys.argv[3:])
if twice:
status = request(sys.argv[1], sys.argv[2], sys.argv[3:])
if 200 <= status <= 305:
sys.exit(0)
sys.exit(1)
| assert not path.startswith("/"), path
global tag
headers = {}
if tag:
headers["If-None-Match"] = tag
if hgproto:
headers["X-HgProto-1"] = hgproto
conn = httplib.HTTPConnection(host)
conn.request("GET", "/" + path, None, headers)
response = conn.getresponse()
print(respon... | identifier_body |
get-with-headers.py | #!/usr/bin/env python
"""This does HTTP GET requests given a host:port and path and returns
a subset of the headers plus the body of the result."""
from __future__ import absolute_import, print_function
import json
import os
import sys
from edenscm.mercurial import util
httplib = util.httplib
try:
import msv... | if "--headeronly" in sys.argv:
sys.argv.remove("--headeronly")
headeronly = True
formatjson = False
if "--json" in sys.argv:
sys.argv.remove("--json")
formatjson = True
hgproto = None
if "--hgproto" in sys.argv:
idx = sys.argv.index("--hgproto")
hgproto = sys.argv[idx + 1]
sys.argv.pop(idx)... | twice = True
headeronly = False | random_line_split |
get-with-headers.py | #!/usr/bin/env python
"""This does HTTP GET requests given a host:port and path and returns
a subset of the headers plus the body of the result."""
from __future__ import absolute_import, print_function
import json
import os
import sys
from edenscm.mercurial import util
httplib = util.httplib
try:
import msv... |
else:
sys.stdout.write(data)
if twice and response.getheader("ETag", None):
tag = response.getheader("ETag")
return response.status
status = request(sys.argv[1], sys.argv[2], sys.argv[3:])
if twice:
status = request(sys.argv[1], sys.argv[2], sys.argv[3:])
if 200 <= status <... | data = json.loads(data)
lines = json.dumps(data, sort_keys=True, indent=2).splitlines()
for line in lines:
print(line.rstrip()) | conditional_block |
task_7_6.py | #Задача 7. Вариант 6
#компьютер загадывает название одного из семи городов России, имеющих действующий метрополитен, а игрок должен его угадать.
#Борщёва В.О
#28.03.2016
import random
subways=('Москва','Санкт-Петербург','Нижний Новгород','Новосибирск','Самара','Екатеринбург','Казань')
subway=random.randint(0,... | conditional_block | ||
task_7_6.py | #Задача 7. Вариант 6
#компьютер загадывает название одного из семи городов России, имеющих действующий метрополитен, а игрок должен его угадать.
#Борщёва В.О
#28.03.2016
import random
subways=('Москва','Санкт-Петербург','Нижний Новгород','Новосибирск','Самара','Екатеринбург','Казань')
subway=random.randint(0,... | elif (otvet)==(rand):
print("Ваш счет:"+ str(ball))
break
input(" Нажмите Enter для выхода") | ball/=2
| random_line_split |
config.rs | extern crate serde_json;
use log::LogLevelFilter;
use logger::MetricsLoggerFactory;
use logger::MetricsLogger;
use self::serde_json::Value;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::collections::BTreeMap;
// This is the config file that reads all the json from m... |
failing "get_u64 should fail for a missing key" {
cfg.get_u64("start22Time");
}
it "get_string should return a string for an existing key" {
let save_path: String = cfg.get_string("savePath").to_string();
assert_eq!(save_path, "testSavePath");
}
failing "get_string should ... | random_line_split | |
config.rs | extern crate serde_json;
use log::LogLevelFilter;
use logger::MetricsLoggerFactory;
use logger::MetricsLogger;
use self::serde_json::Value;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::collections::BTreeMap;
// This is the config file that reads all the json from m... |
fn parse_json(&mut self, json_string: String) {
// It's ok to unwrap here because if something is wrong here, we want to
// know and expose the bug.
let data: Value = serde_json::from_str(&json_string).unwrap();
self.parsed_json = Some(data.as_object().unwrap().clone());
}
... | {
// TODO: Need to make this look at env variable or take a path to the file.
logger().log(LogLevelFilter::Debug,
format!("config file: {}", file_name).as_str());
let path = Path::new(file_name);
let display = path.display();
// Open the path in read-only mo... | identifier_body |
config.rs | extern crate serde_json;
use log::LogLevelFilter;
use logger::MetricsLoggerFactory;
use logger::MetricsLogger;
use self::serde_json::Value;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::collections::BTreeMap;
// This is the config file that reads all the json from m... | (&mut self, key: &str) -> String {
if let Some(ref mut parsed_json) = self.parsed_json {
let val = parsed_json.get(key);
match val {
Some(v) => {
let nv = v.clone();
match nv {
Value::String(nv) => nv.clone()... | get_string | identifier_name |
config.rs | extern crate serde_json;
use log::LogLevelFilter;
use logger::MetricsLoggerFactory;
use logger::MetricsLogger;
use self::serde_json::Value;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::collections::BTreeMap;
// This is the config file that reads all the json from m... |
Err(e) => panic!("cannot open file: {}", e),
};
}
pub fn init(&mut self, file_name: &str) -> bool {
// TODO: Need to make this look at env variable or take a path to the file.
logger().log(LogLevelFilter::Debug,
format!("config file: {}", file_name).as... | {
let _ = t.write(json.as_bytes());
} | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
#
##############################################################################
#
# Authors: Adrien Peiffer
# Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Genera... | from . import account_companyweb_report_wizard
from . import partner_update_companyweb | random_line_split | |
unix.rs | // Copyright 2013 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 s2 = s1.clone();
let (done, rx) = channel();
spawn(proc() {
let mut s2 = s2;
let mut buf = [0, 0];
s2.read(buf).unwrap();
tx2.send(());
done.send(());
});
let mut buf = [0, 0];
s1.read(buf).unwrap();
... | let mut s1 = acceptor.accept().unwrap(); | random_line_split |
unix.rs | // Copyright 2013 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 ... |
}
impl Reader for UnixStream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.obj.read(buf) }
}
impl Writer for UnixStream {
fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.obj.write(buf) }
}
/// A value that can listen for incoming named pipe connection requests.
pub struct UnixListener... | {
UnixStream { obj: self.obj.clone() }
} | identifier_body |
unix.rs | // Copyright 2013 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 ... | <P: ToCStr>(path: &P) -> IoResult<UnixListener> {
LocalIo::maybe_raise(|io| {
io.unix_bind(&path.to_c_str()).map(|s| UnixListener { obj: s })
})
}
}
impl Listener<UnixStream, UnixAcceptor> for UnixListener {
fn listen(self) -> IoResult<UnixAcceptor> {
self.obj.listen().map(|... | bind | identifier_name |
video.ts | /*{# Copyright (c) 2012 Turbulenz Limited #}*/
/*
* @title: Video playback
* @description:
* This sample shows how to play a video into a texture.
*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/services/... |
gameSession = TurbulenzServices.createGameSession(requestHandler, sessionCreated);
//==========================================================================
// Main loop.
//==========================================================================
var fpsElement = document.getElementById("fps... | {
TurbulenzServices.createMappingTable(
requestHandler,
gameSession,
mappingTableReceived
);
} | identifier_body |
video.ts | /*{# Copyright (c) 2012 Turbulenz Limited #}*/
/*
* @title: Video playback
* @description:
* This sample shows how to play a video into a texture.
*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/services/... | var x, y;
if (aspectRatio < videoAspectRatio)
{
x = 1;
y = aspectRatio / videoAspectRatio;
}
else //if (aspectRatio >= videoAspectRatio)
{
x = videoAspectRatio / aspectRatio;
y = 1;
... | random_line_split | |
video.ts | /*{# Copyright (c) 2012 Turbulenz Limited #}*/
/*
* @title: Video playback
* @description:
* This sample shows how to play a video into a texture.
*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/services/... |
graphicsDevice.clear(clearColor);
graphicsDevice.setTechnique(technique);
technique.texture = texture;
technique.clipSpace = mathDevice.v4Build(x, -y, 0, 0, clipSpace);
technique.color = videoColor;
graphicsDevice.setStream(vertexBuffer, semant... | {
if (currentVideoPosition < videoPosition)
{
// looped, sync
source.seek(videoPosition);
}
videoPosition = currentVideoPosition;
texture.setData(video);
} | conditional_block |
video.ts | /*{# Copyright (c) 2012 Turbulenz Limited #}*/
/*
* @title: Video playback
* @description:
* This sample shows how to play a video into a texture.
*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/services/... | (mappingTable)
{
var videoURL;
if (graphicsDevice.isSupported("FILEFORMAT_WEBM"))
{
videoURL = mappingTable.getURL("videos/turbulenzanimation.webm");
}
else
{
videoURL = mappingTable.getURL("videos/turbulenzanimation.mp4");
}
g... | mappingTableReceived | identifier_name |
numeric.rs | use backend::Backend;
use expression::{Expression, SelectableExpression, NonAggregate};
use query_builder::*;
use types;
macro_rules! numeric_operation {
($name:ident, $op:expr) => {
pub struct $name<Lhs, Rhs> {
lhs: Lhs,
rhs: Rhs,
}
impl<Lhs, Rhs> $name<Lhs, Rhs> {... |
numeric_operation!(Add, " + ");
numeric_operation!(Sub, " - ");
numeric_operation!(Mul, " * ");
numeric_operation!(Div, " / "); | random_line_split | |
env.py | from __future__ import with_statement
import os
import sys
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# We need to go back a dir to get the config.
_this_dir = os.path.dirname((os.path.abspath(__file__)))
_parent_dir = os.path.join(_this_dir, '../'... |
else:
run_migrations_online()
| run_migrations_offline() | conditional_block |
env.py | from __future__ import with_statement
import os
import sys
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# We need to go back a dir to get the config.
_this_dir = os.path.dirname((os.path.abspath(__file__)))
_parent_dir = os.path.join(_this_dir, '../'... |
connectable = engine_from_config(
merged_ini_py_conf(),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata
)
with context.beg... |
""" | random_line_split |
env.py | from __future__ import with_statement
import os
import sys
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# We need to go back a dir to get the config.
_this_dir = os.path.dirname((os.path.abspath(__file__)))
_parent_dir = os.path.join(_this_dir, '../'... | ():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
merged_ini_py_conf(),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with connectable.connect() as c... | run_migrations_online | identifier_name |
env.py | from __future__ import with_statement
import os
import sys
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
# We need to go back a dir to get the config.
_this_dir = os.path.dirname((os.path.abspath(__file__)))
_parent_dir = os.path.join(_this_dir, '../'... |
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
| """Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
merged_ini_py_conf(),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with connectable.connect() as connectio... | identifier_body |
auth.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the Licen... | }
}
});
Ok(Auth {
receiver: i_receiver,
sender: i_sender,
})
}
pub fn authenticate<S: Into<String>>(&self, password: S) -> Result<(), SendError<Request>> {
self.sender.send(Request::Authenticate(password.into()))
}
}
impl Deref for Auth {
type Target = Receiver<Response>;
fn deref(&self) ... | if methods.is_empty() {
warn!("no authentication method");
sender.send(Response::Success).unwrap();
continue 'main;
}
for method in &mut methods {
if let Ok(true) = method.authenticate(user.to_str().unwrap(), &password) {
sender.send(Response::Success).unwrap();
... | conditional_block |
auth.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the Licen... | // screenruster 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
//... | // | random_line_split |
auth.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the Licen... | : Into<String>>(&self, password: S) -> Result<(), SendError<Request>> {
self.sender.send(Request::Authenticate(password.into()))
}
}
impl Deref for Auth {
type Target = Receiver<Response>;
fn deref(&self) -> &Receiver<Response> {
&self.receiver
}
}
| thenticate<S | identifier_name |
plot_weighted_samples.py | """
=====================
SVM: Weighted samples
=====================
Plot decision function of a weighted dataset, where the size of points
is proportional to its weight.
""" |
# we create 20 points
np.random.seed(0)
X = np.r_[np.random.randn(10, 2) + [1, 1], np.random.randn(10, 2)]
Y = [1] * 10 + [-1] * 10
sample_weight = 100 * np.abs(np.random.randn(20))
# and assign a bigger weight to the last 10 samples
sample_weight[:10] *= 10
# # fit the model
clf = svm.SVC()
clf.fit(X, Y, sample_weig... | print __doc__
import numpy as np
import pylab as pl
from sklearn import svm | random_line_split |
test_releasehook.py | """
sentry.plugins.base.structs
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
__all__ = ['ReleaseHook']
from sentry.models import Release
from sentry.plug... | assert release.date_released | project=project,
version=version,
) | random_line_split |
test_releasehook.py | """
sentry.plugins.base.structs
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
__all__ = ['ReleaseHook']
from sentry.models import Release
from sentry.plug... | (TestCase):
def test_minimal(self):
project = self.create_project()
version = 'bbee5b51f84611e4b14834363b8514c2'
hook = ReleaseHook(project)
hook.start_release(version)
release = Release.objects.get(
project=project,
version=version,
)
... | StartReleaseTest | identifier_name |
test_releasehook.py | """
sentry.plugins.base.structs
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
__all__ = ['ReleaseHook']
from sentry.models import Release
from sentry.plug... |
class FinishReleaseTest(TestCase):
def test_minimal(self):
project = self.create_project()
version = 'bbee5b51f84611e4b14834363b8514c2'
hook = ReleaseHook(project)
hook.finish_release(version)
release = Release.objects.get(
project=project,
versio... | def test_minimal(self):
project = self.create_project()
version = 'bbee5b51f84611e4b14834363b8514c2'
hook = ReleaseHook(project)
hook.start_release(version)
release = Release.objects.get(
project=project,
version=version,
)
assert release... | identifier_body |
util.rs | // Copyright 2012 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 ... |
}
| { ~";" }
pub fn logv(config: &config, s: ~str) {
debug!("{}", s);
if config.verbose { println!("{}", s); } | identifier_body |
util.rs | // Copyright 2012 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 ... | () -> ~str { ~"PATH" }
#[cfg(target_os = "win32")]
pub fn path_div() -> ~str { ~";" }
pub fn logv(config: &config, s: ~str) {
debug!("{}", s);
if config.verbose { println!("{}", s); }
}
| lib_path_env_var | identifier_name |
util.rs | // Copyright 2012 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 ... |
/// Conversion table from triple OS name to Rust SYSNAME
static OS_TABLE: &'static [(&'static str, &'static str)] = &[
("mingw32", "win32"),
("win32", "win32"),
("darwin", "macos"),
("android", "android"),
("linux", "linux"),
("freebsd", "freebsd"),
];
pub fn get_os(triple: &str) -> &'static s... | random_line_split | |
no-landing-pads.rs | // Copyright 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-MIT or ... | {
thread::spawn(move|| -> () {
let _a = A;
panic!();
}).join().err().unwrap();
assert!(unsafe { !HIT });
} | identifier_body | |
no-landing-pads.rs | // Copyright 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-MIT or ... | () {
thread::spawn(move|| -> () {
let _a = A;
panic!();
}).join().err().unwrap();
assert!(unsafe { !HIT });
}
| main | identifier_name |
no-landing-pads.rs | // Copyright 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-MIT or ... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z no-landing-pads
use std::thread;
static mut HIT: bool = false;
struct A;
impl Drop for A {
fn drop(&mut self) {
unsafe { HIT = true; }
}
}
fn main() {
thread::spawn(move|| ... | random_line_split | |
cookiesetter.rs | /*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0
*
* © Gregor Reitzenstein
*/
use iron::prelude::*;
use iron::AfterMiddleware;
use iron::headers::SetCookie;
use iron::typemap::Key;
use cookie::Cookie;
use api::API;
/// This Struct sets Cookies on outgoing Responses as ... |
impl AfterMiddleware for CookieSetter
{
fn after(&self, req: &mut Request, mut res: Response) -> IronResult<Response>
{
// If the Request contains a CookieReq struct, set the specified Cookie
if req.extensions.contains::<CookieReq>()
{
let cookievalvec: Vec<[String; 2]> = re... | CookieSetter
}
} | random_line_split |
cookiesetter.rs | /*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0
*
* © Gregor Reitzenstein
*/
use iron::prelude::*;
use iron::AfterMiddleware;
use iron::headers::SetCookie;
use iron::typemap::Key;
use cookie::Cookie;
use api::API;
/// This Struct sets Cookies on outgoing Responses as ... | Ok(res)
}
}
// This Struct notifies CookieSetter to set a cookie.
pub struct CookieReq;
// Key needs to be implented so this Struct can be inserted to req.extensions
impl Key for CookieReq { type Value = Vec<[String; 2]>; }
|
let cookievalvec: Vec<[String; 2]> = req.extensions.remove::<CookieReq>().unwrap();
// A Cookie is a slice of two Strings: The key and the associated value
let cookies: Vec<Cookie> = cookievalvec.into_iter().map(|x| Cookie::new(x[1].clone(),x[2].clone())).collect();
res... | conditional_block |
cookiesetter.rs | /*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0
*
* © Gregor Reitzenstein
*/
use iron::prelude::*;
use iron::AfterMiddleware;
use iron::headers::SetCookie;
use iron::typemap::Key;
use cookie::Cookie;
use api::API;
/// This Struct sets Cookies on outgoing Responses as ... | _: &API) -> CookieSetter
{
CookieSetter
}
}
impl AfterMiddleware for CookieSetter
{
fn after(&self, req: &mut Request, mut res: Response) -> IronResult<Response>
{
// If the Request contains a CookieReq struct, set the specified Cookie
if req.extensions.contains::<CookieReq>()
... | ew( | identifier_name |
components.tsx | /*
Copyright 2019 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... | article,
link,
} = props;
const supertext = [];
if (category) {
supertext.push(<span key="label" {...css(TITLE_CELL_STYLES.categoryLabel)}>{category.label}</span>);
}
if (article.sourceCreatedAt) {
supertext.push((
<span key="timestamp">
<MagicTimestamp timestamp={article.source... | random_line_split | |
components.tsx | /*
Copyright 2019 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... |
const moderators = s.toArray().map((uid: string) => users.get(uid));
if (moderators.length === 0) {
return (
<div onClick={props.openSetModerators} {...css(MODERATOR_WIDGET_STYLES.widget)}>
<PseudoAvatar size={IMAGE_BASE}>
<PersonAdd/>
</PseudoAvatar>
</div>
);
}
... | {
s = s.merge(superModeratorIds);
} | conditional_block |
check-kibana-settings.service.ts | /*
* Wazuh app - Check Kibana settings service
*
* Copyright (C) 2015-2021 Wazuh, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your op... | (kibanaSettingName, defaultAppValue, retries = 3) {
return await getUiSettings()
.set(kibanaSettingName, null)
.catch(async (error) => {
if (retries > 0) {
return await updateSetting(kibanaSettingName, defaultAppValue, --retries);
}
throw error;
});
}
function stringifySetting(s... | updateSetting | identifier_name |
check-kibana-settings.service.ts | /*
* Wazuh app - Check Kibana settings service
*
* Copyright (C) 2015-2021 Wazuh, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your op... |
throw error;
});
}
function stringifySetting(setting: any){
try{
return JSON.stringify(setting);
}catch(error){
return setting;
};
};
| {
return await updateSetting(kibanaSettingName, defaultAppValue, --retries);
} | conditional_block |
check-kibana-settings.service.ts | /*
* Wazuh app - Check Kibana settings service
*
* Copyright (C) 2015-2021 Wazuh, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your op... |
async function updateSetting(kibanaSettingName, defaultAppValue, retries = 3) {
return await getUiSettings()
.set(kibanaSettingName, null)
.catch(async (error) => {
if (retries > 0) {
return await updateSetting(kibanaSettingName, defaultAppValue, --retries);
}
throw error;
});
}... | }
} | random_line_split |
check-kibana-settings.service.ts | /*
* Wazuh app - Check Kibana settings service
*
* Copyright (C) 2015-2021 Wazuh, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your op... | ;
| {
try{
return JSON.stringify(setting);
}catch(error){
return setting;
};
} | identifier_body |
bitstream.rs | //! This module provides bit readers and writers
use std::io::{self, Write};
/// Containes either the consumed bytes and reconstructed bits or
/// only the consumed bytes if the supplied buffer was not bit enough
pub enum Bits {
/// Consumed bytes, reconstructed bits
Some(usize, u16),
/// Consumed bytes
... |
let mut consumed = 0;
while self.bits < n {
let byte = if buf.len() > 0 {
let byte = buf[0];
buf = &buf[1..];
byte
} else {
return Bits::None(consumed)
};
self.acc |= (byte as u32) << self.bi... | {
// This is a logic error the program should have prevented this
// Ideally we would used bounded a integer value instead of u8
panic!("Cannot read more than 16 bits")
} | conditional_block |
bitstream.rs | //! This module provides bit readers and writers
use std::io::{self, Write};
/// Containes either the consumed bytes and reconstructed bits or
/// only the consumed bytes if the supplied buffer was not bit enough
pub enum Bits {
/// Consumed bytes, reconstructed bits
Some(usize, u16),
/// Consumed bytes
... | () {
let data = [255, 20, 40, 120, 128];
let mut offset = 0;
let mut expanded_data = Vec::new();
let mut reader = super::LsbReader::new();
while let Bits::Some(consumed, b) = reader.read_bits(&data[offset..], 10) {
offset += consumed;
expanded_data.push(b)... | reader_writer | identifier_name |
bitstream.rs | //! This module provides bit readers and writers
use std::io::{self, Write};
/// Containes either the consumed bytes and reconstructed bits or
/// only the consumed bytes if the supplied buffer was not bit enough
pub enum Bits {
/// Consumed bytes, reconstructed bits
Some(usize, u16),
/// Consumed bytes
... | }
assert_eq!(&data[..], &compressed_data[..])
}
} | for &datum in expanded_data.iter() {
let _ = writer.write_bits(datum, 10);
} | random_line_split |
bitstream.rs | //! This module provides bit readers and writers
use std::io::{self, Write};
/// Containes either the consumed bytes and reconstructed bits or
/// only the consumed bytes if the supplied buffer was not bit enough
pub enum Bits {
/// Consumed bytes, reconstructed bits
Some(usize, u16),
/// Consumed bytes
... |
}
impl<W: Write> BitWriter for MsbWriter<W> {
fn write_bits(&mut self, v: u16, n: u8) -> io::Result<()> {
self.acc |= (v as u32) << (32 - n - self.bits);
self.bits += n;
while self.bits >= 8 {
try!(self.w.write_all(&[(self.acc >> 24) as u8]));
self.acc <<= 8;
... | {
self.acc |= (v as u32) << self.bits;
self.bits += n;
while self.bits >= 8 {
try!(self.w.write_all(&[self.acc as u8]));
self.acc >>= 8;
self.bits -= 8
}
Ok(())
} | identifier_body |
api.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate hyper;
extern crate time;
extern crate url;
use foxbox_taxonomy::api::{ Error, InternalError };
use ... | };
let mut options = fs::OpenOptions::new();
options.write(true);
options.create(true);
options.truncate(true);
let filename_base = time::strftime("%Y-%m-%d-%H%M%S", &time::now()).unwrap();
let mut full_filename;
let image_file;
let mut loop_coun... | random_line_split | |
api.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate hyper;
extern crate time;
extern crate url;
use foxbox_taxonomy::api::{ Error, InternalError };
use ... |
}
}
#[derive(Clone)]
pub struct IpCamera {
pub udn: String,
url: String,
snapshot_dir: String,
pub image_list_id: Id<Getter>,
pub image_newest_id: Id<Getter>,
pub snapshot_id: Id<Setter>,
}
impl IpCamera {
pub fn new(udn: &str, url: &str, root_snapshot_dir: &str) -> Result<Self, Erro... | {
warn!("read of image data from {} failed: {}", url, err);
Err(Error::InternalError(InternalError::InvalidInitialService))
} | conditional_block |
api.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate hyper;
extern crate time;
extern crate url;
use foxbox_taxonomy::api::{ Error, InternalError };
use ... | <IO>(prefix: &str, operation: &str, service_id: &str) -> Id<IO>
where IO: IOMechanism
{
Id::new(&format!("{}:{}.{}@link.mozilla.org", prefix, operation, service_id))
}
fn get_bytes(url: String) -> Result<Vec<u8>, Error> {
let client = hyper::Client::new();
let get_result = client.get(&url)
... | create_io_mechanism_id | identifier_name |
api.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate hyper;
extern crate time;
extern crate url;
use foxbox_taxonomy::api::{ Error, InternalError };
use ... |
pub fn create_setter_id(operation: &str, service_id: &str) -> Id<Setter> {
create_io_mechanism_id("setter", operation, service_id)
}
pub fn create_getter_id(operation: &str, service_id: &str) -> Id<Getter> {
create_io_mechanism_id("getter", operation, service_id)
}
pub fn create_io_mechanism_id<IO>(prefix: ... | {
Id::new(&format!("service:{}@link.mozilla.org", service_id))
} | identifier_body |
lib.rs | // Copyright 2015 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 ... | }
}
impl PartialOrd<LogLevel> for LogLevelFilter {
#[inline]
fn partial_cmp(&self, other: &LogLevel) -> Option<cmp::Ordering> {
other.partial_cmp(self).map(|x| x.reverse())
}
}
impl Ord for LogLevelFilter {
#[inline]
fn cmp(&self, other: &LogLevelFilter) -> cmp::Ordering {
(*se... | #[inline]
fn partial_cmp(&self, other: &LogLevelFilter) -> Option<cmp::Ordering> {
Some(self.cmp(other)) | random_line_split |
lib.rs | // Copyright 2015 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 ... |
/// The name of the target of the directive.
pub fn target(&self) -> &str {
self.metadata.target()
}
}
/// Metadata about a log message.
pub struct LogMetadata<'a> {
level: LogLevel,
target: &'a str,
}
impl<'a> LogMetadata<'a> {
/// The verbosity level of the message.
pub fn leve... | {
self.metadata.level()
} | identifier_body |
lib.rs | // Copyright 2015 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 ... | (&self, other: &LogLevelFilter) -> bool {
*self as usize == *other as usize
}
}
impl PartialEq<LogLevel> for LogLevelFilter {
#[inline]
fn eq(&self, other: &LogLevel) -> bool {
other.eq(self)
}
}
impl PartialOrd for LogLevelFilter {
#[inline]
fn partial_cmp(&self, other: &LogLe... | eq | identifier_name |
lib.rs | // Copyright 2015 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 ... |
}
// WARNING
// This is not considered part of the crate's public API. It is subject to
// change at any time.
#[doc(hidden)]
pub fn __log(level: LogLevel, target: &str, loc: &LogLocation,
args: fmt::Arguments) {
if let Some(logger) = logger() {
let record = LogRecord {
metadata: ... | {
false
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.