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 |
|---|---|---|---|---|
poll.rs |
/// A macro.
#[macro_export]
macro_rules! try_poll {
($e:expr) => (match $e {
$crate::Poll::NotReady => return $crate::Poll::NotReady,
$crate::Poll::Ok(t) => Ok(t),
$crate::Poll::Err(e) => Err(e),
})
}
/// Possible return values from the `Future::poll` method.
#[derive(Copy, Clone, Deb... | <F, U>(self, f: F) -> Poll<U, E>
where F: FnOnce(T) -> U
{
match self {
Poll::NotReady => Poll::NotReady,
Poll::Ok(t) => Poll::Ok(f(t)),
Poll::Err(e) => Poll::Err(e),
}
}
/// Change the error type of this `Poll` value with the closure provided
... | map | identifier_name |
barcodescanner.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... | //# sourceMappingURL=barcodescanner.js.map | random_line_split | |
barcodescanner.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... |
/**
* Open the barcode scanner.
* @param options {Object} Optional options to pass to the scanner
* @returns {Promise<any>} Returns a Promise that resolves with scanner data, or rejects with an error.
*/
BarcodeScanner.scan = function (options) { return; };
/**
* Encodes data into ... | {
} | identifier_body |
barcodescanner.js | "use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl... | () {
}
/**
* Open the barcode scanner.
* @param options {Object} Optional options to pass to the scanner
* @returns {Promise<any>} Returns a Promise that resolves with scanner data, or rejects with an error.
*/
BarcodeScanner.scan = function (options) { return; };
/**
* Encodes ... | BarcodeScanner | identifier_name |
singular.ts | // Copyright 2018 Google LLC
//
// 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 ... | <T>(fn: Func<T>): Func<T> {
return fn;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
patchEmitterToPropagateContext(ee: EventEmitter): void {}
}
| bindWithCurrentContext | identifier_name |
singular.ts | // Copyright 2018 Google LLC
//
// 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 ... | * A trivial implementation of continuation-local storage where everything is
* in the same continuation. Therefore, only one unique value can be stored at
* a time.
*/
export class SingularCLS<Context> implements CLS<Context> {
private enabled = false;
private currentContext: Context;
constructor(private rea... |
import {CLS, Func} from './base';
/** | random_line_split |
singular.ts | // Copyright 2018 Google LLC
//
// 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 ... |
getContext(): Context {
return this.currentContext;
}
runWithContext<T>(fn: Func<T>, value: Context): T {
this.currentContext = value;
return fn();
}
bindWithCurrentContext<T>(fn: Func<T>): Func<T> {
return fn;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
patchEmi... | {
this.enabled = false;
this.currentContext = this.defaultContext;
} | identifier_body |
GeneralPunctuation.js | /* | *
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
... | * /MathJax/jax/output/SVG/fonts/TeX/AMS/Regular/GeneralPunctuation.js | random_line_split |
api.py | # -*- coding: utf-8 -*-
"""
API for submitting background tasks by an instructor for a course.
Also includes methods for getting information about tasks that have
already been submitted, filtered either by running state or input
arguments.
"""
from ga_instructor_task.tasks import (
generate_score_detail_report,
... | """
Submits a task to generate a CSV playback status report.
"""
task_type = 'generate_playback_status_report'
task_class = generate_playback_status_report
task_input = {}
task_key = ""
return submit_task(request, task_type, task_class, course_key, task_input, task_key) | identifier_body | |
api.py | # -*- coding: utf-8 -*- | """
API for submitting background tasks by an instructor for a course.
Also includes methods for getting information about tasks that have
already been submitted, filtered either by running state or input
arguments.
"""
from ga_instructor_task.tasks import (
generate_score_detail_report,
generate_playback_stat... | random_line_split | |
api.py | # -*- coding: utf-8 -*-
"""
API for submitting background tasks by an instructor for a course.
Also includes methods for getting information about tasks that have
already been submitted, filtered either by running state or input
arguments.
"""
from ga_instructor_task.tasks import (
generate_score_detail_report,
... | (request, course_key):
"""
Submits a task to generate a CSV playback status report.
"""
task_type = 'generate_playback_status_report'
task_class = generate_playback_status_report
task_input = {}
task_key = ""
return submit_task(request, task_type, task_class, course_key, task_input, task... | submit_generate_playback_status_report | identifier_name |
irrigation.ts | ''
trellis_plots = {}
channels:any [] = []
parameters
constructor() {
super()
this.parameters = {
trellis: 'trellis',
id: 'int',
action: 'string'
}
}
// vineyard:Vineyard null
// initialize_vineyard (vineyard) {
// this.vineyard = vineyard;
// ... | var length = Math.max(a.length, b.length);
var x = -1, y = -1, ax, by, ax_pure;
for (var i = 0; i < length; i++) {
if (++x >= a.length)
return false;
ax = a[x];
if (++y >= b.length) {
if (ax[ax.length - 1] == '?') {
--y;
continue;
... | random_line_split | |
irrigation.ts | ''
trellis_plots = {}
channels:any [] = []
parameters
constructor() {
super()
this.parameters = {
trellis: 'trellis',
id: 'int',
action: 'string'
}
}
// vineyard:Vineyard null
// initialize_vineyard (vineyard) {
// this.vineyard = vineyard;
// ... | if (++y >= b.length) {
if (ax[ax.length - 1] == '?') {
--y;
continue;
}
else
return false;
}
by = b[y];
ax_pure = ax.replace(/\?$/, '');
if (ax_pure == by
|| ax == '*'
|| (ax[0] == '%' && this.compare_par... | {
var a = Irrigation.convert_path_to_array(primary);
var b = Irrigation.convert_path_to_array(secondary);
var result = [];
// Optional parameters can only be in the primary path,
// so the secondary path can be possibly shorter but
// never longer than the primary path.
if (a.length... | identifier_body |
irrigation.ts | = ''
trellis_plots = {}
channels:any [] = []
parameters
constructor() {
super()
this.parameters = {
trellis: 'trellis',
id: 'int',
action: 'string'
}
}
// vineyard:Vineyard null
// initialize_vineyard (vineyard) {
// this.vineyard = vineyard;
// ... | (pattern, action) {
pattern = Irrigation.convert_path_to_array(pattern);
var priority = this.calculate_priority(pattern);
var i, channel, result = {
pattern: pattern,
action: action,
priority: priority
};
// Find the right slot based on priority.
// This is faster th... | add_channel | identifier_name |
bowtie2.py | import glob
import logging
import os
import subprocess
from plugins import BaseAligner
from yapsy.IPlugin import IPlugin
from assembly import get_qual_encoding
class Bowtie2Aligner(BaseAligner, IPlugin):
def run(self):
"""
Map READS to CONTIGS and return alignment.
Set MERGED_PAIR to True ... |
else:
raise Exception('Bowtie plugin error')
self.arast_popen(cmd_args, overrides=False)
if not os.path.exists(samfile):
raise Exception('Unable to complete alignment')
## Convert to BAM
bamfile = samfile.replace('.sam', '.bam... | cmd_args += ['-U', reads[0]] | conditional_block |
bowtie2.py | import glob
import logging
import os
import subprocess
from plugins import BaseAligner
from yapsy.IPlugin import IPlugin
from assembly import get_qual_encoding
class Bowtie2Aligner(BaseAligner, IPlugin):
def run(self):
| if len(reads) == 2:
cmd_args += ['-1', reads[0], '-2', reads[1]]
elif len(reads) == 1:
cmd_args += ['-U', reads[0]]
else:
raise Exception('Bowtie plugin error')
self.arast_popen(cmd_args, overrides=False)
if not ... | """
Map READS to CONTIGS and return alignment.
Set MERGED_PAIR to True if reads[1] is a merged
paired end file
"""
contig_file = self.data.contigfiles[0]
reads = self.data.readfiles
## Index contigs
prefix = os.path.join(self.outpath, 'bt2')
cmd... | identifier_body |
bowtie2.py | import glob
import logging
import os
import subprocess
from plugins import BaseAligner
from yapsy.IPlugin import IPlugin
from assembly import get_qual_encoding
class | (BaseAligner, IPlugin):
def run(self):
"""
Map READS to CONTIGS and return alignment.
Set MERGED_PAIR to True if reads[1] is a merged
paired end file
"""
contig_file = self.data.contigfiles[0]
reads = self.data.readfiles
## Index contigs
pre... | Bowtie2Aligner | identifier_name |
bowtie2.py | import glob
import logging
import os
import subprocess
from plugins import BaseAligner
from yapsy.IPlugin import IPlugin
from assembly import get_qual_encoding
class Bowtie2Aligner(BaseAligner, IPlugin):
def run(self):
"""
Map READS to CONTIGS and return alignment.
Set MERGED_PAIR to True ... |
## Convert to BAM
bamfile = samfile.replace('.sam', '.bam')
cmd_args = ['samtools', 'view',
'-bSho', bamfile, samfile]
self.arast_popen(cmd_args)
bamfiles.append(bamfile)
### Merge samfiles if multiple
if len(bamfiles)... | raise Exception('Unable to complete alignment') | random_line_split |
server.ts | import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
import * as path from 'path';
import * as express from 'express';
import * as expressSession from 'express-session';
import * as mongoose from 'mongoose';
import * as MongoStore from 'connect-mongo';
const _MongoStore: MongoStore.Mo... |
// go stream
streaming(server);
sticky.listen(server);
process.send({cmd: 'ready'});
| {
server = http.createServer(app);
} | conditional_block |
server.ts | import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
import * as path from 'path';
import * as express from 'express';
import * as expressSession from 'express-session';
import * as mongoose from 'mongoose';
import * as MongoStore from 'connect-mongo';
const _MongoStore: MongoStore.Mo... | res.sendStatus(200);
} else {
next();
}
});
// Session settings
app.use(expressSession(session));
// CSRF
app.use(csrf({
cookie: false
}));
app.use((req, res, next) => {
res.locals.csrftoken = req.csrfToken();
next();
});
app.use(require('subdomain')(subdomainOptions));
// HSTS
if (config.https.enable) {
... | random_line_split | |
auth.guard.ts | import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { UserService } from '../_services/user.service';
import 'rxjs/add/observable/of';
/**
* Protect User's routes
*
* @e... |
else {
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}
} | {
return this.userService.me()
.map(response => {
return true;
})
.catch(() => {
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return Observable.of(false);
});
} | conditional_block |
auth.guard.ts | import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { UserService } from '../_services/user.service';
import 'rxjs/add/observable/of';
/**
* Protect User's routes
*
* @e... |
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('token')) {
return this.userService.me()
.map(response => {
return true;
})
.catch(() => {
this.router.navigate(['/login'], { queryParams: { returnUrl: state.ur... | {} | identifier_body |
auth.guard.ts | import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { UserService } from '../_services/user.service';
import 'rxjs/add/observable/of';
/**
* Protect User's routes
*
* @e... | implements CanActivate {
constructor(private router: Router, private userService: UserService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('token')) {
return this.userService.me()
.map(response => {
return true;
})
... | AuthGuard | identifier_name |
auth.guard.ts | import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { UserService } from '../_services/user.service';
import 'rxjs/add/observable/of';
/**
* Protect User's routes
*
* @e... | this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return Observable.of(false);
});
}
else {
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
retur... | .catch(() => { | random_line_split |
word_dict.py | #!/usr/local/bin/python
# coding: UTF-8
# released under bsd licence
# see LICENCE file or http://www.opensource.org/licenses/bsd-license.php for details
# Institute of Applied Simulation (ZHAW)
# Author Thomas Niederberger
from mlscripts.text.utilities import *
from mlscripts.text.word_desc import WordDesc
... |
return mapping
def get_by_id(self, id):
for key, entry in self.__words.iteritems():
if entry.id == id:
return key
| mapping[word.id] = c
c += 1 | conditional_block |
word_dict.py | #!/usr/local/bin/python
# coding: UTF-8
# released under bsd licence
# see LICENCE file or http://www.opensource.org/licenses/bsd-license.php for details
# Institute of Applied Simulation (ZHAW)
# Author Thomas Niederberger
from mlscripts.text.utilities import *
from mlscripts.text.word_desc import WordDesc
... |
def vectorize(self, word_list):
"""Word_list must be in a sorted order"""
#cleaned_list.sort()
id_list = []
for stem in word_list:
if stem in self.__words:
item = self.__words[stem]
if item.document_count >= 2:
... | self.__current_id = 0
self.__words = {} | identifier_body |
word_dict.py | #!/usr/local/bin/python
# coding: UTF-8
# released under bsd licence
# see LICENCE file or http://www.opensource.org/licenses/bsd-license.php for details
# Institute of Applied Simulation (ZHAW)
# Author Thomas Niederberger
from mlscripts.text.utilities import *
from mlscripts.text.word_desc import WordDesc
... |
@property
def size(self):
return self.__current_id
def id_mapping_by_document_frequency(self, frequency=2):
c = 0
mapping = {}
for key, word in self.__words.items():
if word.document_count >= frequency:
mapping[word.id] = c
... | random_line_split | |
word_dict.py | #!/usr/local/bin/python
# coding: UTF-8
# released under bsd licence
# see LICENCE file or http://www.opensource.org/licenses/bsd-license.php for details
# Institute of Applied Simulation (ZHAW)
# Author Thomas Niederberger
from mlscripts.text.utilities import *
from mlscripts.text.word_desc import WordDesc
... | (self, frequency=2):
c = 0
mapping = {}
for key, word in self.__words.items():
if word.document_count >= frequency:
mapping[word.id] = c
c += 1
return mapping
def get_by_id(self, id):
for key, entry in self.__words.iterit... | id_mapping_by_document_frequency | identifier_name |
Checkbox.js | import React from 'react';
import style from 'PVWStyle/ReactProperties/CheckboxProperty.mcss';
export default React.createClass({
displayName: 'Checkbox',
propTypes: {
idx: React.PropTypes.number,
label: React.PropTypes.string,
onChange: React.PropTypes.func,
value: React.PropTypes.bool,
},
... |
}
},
render() {
return (
<div>
<label className={style.label}>{this.props.label}</label>
<input
className={style.input}
type="checkbox"
checked={this.props.value}
onChange={this.valueChange}
/>
</div>);
},
});
| {
this.props.onChange(null, e.target.checked);
} | conditional_block |
Checkbox.js | import React from 'react';
import style from 'PVWStyle/ReactProperties/CheckboxProperty.mcss';
export default React.createClass({
displayName: 'Checkbox',
propTypes: {
idx: React.PropTypes.number,
label: React.PropTypes.string,
onChange: React.PropTypes.func,
value: React.PropTypes.bool,
},
... | () {
return (
<div>
<label className={style.label}>{this.props.label}</label>
<input
className={style.input}
type="checkbox"
checked={this.props.value}
onChange={this.valueChange}
/>
</div>);
},
});
| render | identifier_name |
Checkbox.js | import React from 'react';
import style from 'PVWStyle/ReactProperties/CheckboxProperty.mcss';
export default React.createClass({
displayName: 'Checkbox',
propTypes: {
idx: React.PropTypes.number,
label: React.PropTypes.string,
onChange: React.PropTypes.func,
value: React.PropTypes.bool,
},
... | <div>
<label className={style.label}>{this.props.label}</label>
<input
className={style.input}
type="checkbox"
checked={this.props.value}
onChange={this.valueChange}
/>
</div>);
},
}); |
render() {
return ( | random_line_split |
Checkbox.js | import React from 'react';
import style from 'PVWStyle/ReactProperties/CheckboxProperty.mcss';
export default React.createClass({
displayName: 'Checkbox',
propTypes: {
idx: React.PropTypes.number,
label: React.PropTypes.string,
onChange: React.PropTypes.func,
value: React.PropTypes.bool,
},
... | ,
render() {
return (
<div>
<label className={style.label}>{this.props.label}</label>
<input
className={style.input}
type="checkbox"
checked={this.props.value}
onChange={this.valueChange}
/>
</div>);
},
});
| {
if (this.props.onChange) {
if (this.props.idx >= 0) {
this.props.onChange(this.props.idx, e.target.checked);
} else {
this.props.onChange(null, e.target.checked);
}
}
} | identifier_body |
posts.js | 'use strict';
angular.module('myApp.post', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/new-post', {
templateUrl: 'posts/new-post.html',
controller: 'PostCtrl'
});
}])
.controller('PostCtrl', ['$scope', '$firebaseArray', 'CommonProp', '$location', function($scope, $f... |
$scope.addPost = function() {
var firebaseObj = new Firebase("https://amber-heat-2147.firebaseio.com/articles");
var fb = $firebaseArray(firebaseObj);
var title = $scope.article.title;
var content = $scope.article.content;
fb.$add({
title: title,
content: content,
author: CommonProp.getUser()
}... | {
$location.path('/signin');
} | conditional_block |
posts.js | 'use strict';
angular.module('myApp.post', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/new-post', {
templateUrl: 'posts/new-post.html',
controller: 'PostCtrl'
});
}])
.controller('PostCtrl', ['$scope', '$firebaseArray', 'CommonProp', '$location', function($scope, $f... | }]); | } | random_line_split |
E3DBaseEnv.ts | class E3DBaseEnv extends EUIBaseEnv{
protected _time: number = 0;
protected _delay: number = 0;
protected _timeDate: Date = null;
protected _view3D: egret3d.View3D = null;
protected _viewPort: egret3d.Rectangle = null;
protected _camera3D: egret3d.Camera3D = null;
protected _cameraCtl: Camer... | blic start3D() {
//window.addEventListener("touchstart",(e) => this.touchStart(e));
this._cameraCtl = new CameraHoverController(this._view3D.camera3D,null,45,45,200,8,85);
this._cameraCtl.useEventDis(this.rect);
this._cameraCtl.lookAtPosition = new egret3d.Vector3D(0,10,0);
this... |
pu | identifier_body |
E3DBaseEnv.ts | class E3DBaseEnv extends EUIBaseEnv{
protected _time: number = 0;
protected _delay: number = 0;
protected _timeDate: Date = null;
protected _view3D: egret3d.View3D = null;
protected _viewPort: egret3d.Rectangle = null;
protected _camera3D: egret3d.Camera3D = null;
protected _cameraCtl: Camer... | alert("11111");
}
protected onView3DInitComplete(): void {
}
public start3D() {
//window.addEventListener("touchstart",(e) => this.touchStart(e));
this._cameraCtl = new CameraHoverController(this._view3D.camera3D,null,45,45,200,8,85);
this._cameraCtl.useEventDis(this.rect... | rt(e) {
| identifier_name |
E3DBaseEnv.ts | class E3DBaseEnv extends EUIBaseEnv{
protected _time: number = 0;
protected _delay: number = 0;
protected _timeDate: Date = null;
protected _view3D: egret3d.View3D = null;
protected _viewPort: egret3d.Rectangle = null;
protected _camera3D: egret3d.Camera3D = null;
protected _cameraCtl: Camer... | this._viewPort = new egret3d.Rectangle(0,0,width,height);
egret3d.Egret3DDrive.requstContext3D(DeviceUtil.getGPUMode,this._viewPort,() => this.onInit3D());
}
protected onResize(x: number,y: number,width: number,height: number) {
super.onResize(x,y,width,height);
this._view3D.resiz... |
public constructor(width: number = 800,height: number = 600) {
super(); | random_line_split |
parse_laws.py | (self, days_back):
self.url = PRIVATE_LAWS_URL
self.rtf_url = r"http://www.knesset.gov.il/privatelaw"
self.laws_data = []
self.parse_pages_days_back(days_back)
# parses the required pages data
def parse_pages_days_back(self, days_back):
today = datetime.date.today()
... | __init__ | identifier_name | |
parse_laws.py | self.url = PRIVATE_LAWS_URL
self.rtf_url = r"http://www.knesset.gov.il/privatelaw"
self.laws_data = []
self.parse_pages_days_back(days_back)
# parses the required pages data
def parse_pages_days_back(self, days_back):
today = datetime.date.today()
last_required_d... | law_data['comment'] = None
if comment1:
law_data['correction'] = clean_line(comment1)
else:
law_data['correction'] = None
law_data['correction'] = normalize_correction_title_dashes(law_data['correction'])
law... | name_tag = soup.findAll(lambda tag: tag.name == 'tr' and tag.has_key('valign') and tag['valign'] == 'Top')
for tag in name_tag:
tds = tag.findAll(lambda td: td.name == 'td')
law_data = {}
law_data['knesset_id'] = int(tds[0].string.strip())
law_data['law_id'] = int... | identifier_body |
parse_laws.py | comments = soup.findAll(text=lambda text: isinstance(text, Comment))
[comment.extract() for comment in comments]
return soup
else:
data = urllib.urlencode(params)
try:
url_data = urllib2.urlopen(self.url, data)
except urlli... | try:
html_page = urllib2.urlopen(self.url).read().decode('windows-1255').encode('utf-8')
except urllib2.URLError as e:
logger.error("can't open URL: %s" % self.url)
send_chat_notification(__name__, 'failed to open url', {'url': self.url, 'params': params})
... | conditional_block | |
parse_laws.py | ):
self.url = PRIVATE_LAWS_URL
self.rtf_url = r"http://www.knesset.gov.il/privatelaw"
self.laws_data = []
self.parse_pages_days_back(days_back)
# parses the required pages data
def parse_pages_days_back(self, days_back):
today = datetime.date.today()
last_requir... | def get_param(self, soup):
name_tags = soup.findAll(
lambda tag: tag.name == 'a' and tag.has_key('href') and re.match("javascript:SndSelf\((\d+)\);",
tag['href']))
if name_tags and name_tags[0].get('href'):
... | index = self.get_param(soup_current_page)
self.parse_private_laws_page(soup_current_page)
last_law_checked_date = self.update_last_date()
| random_line_split |
msvc.py | (target, source, env, parent_emitter):
"""Sets up the PCH dependencies for an object file."""
validate_vars(env)
parent_emitter(target, source, env)
# Add a dependency, but only if the target (e.g. 'Source1.obj')
# doesn't correspond to the pre-compiled header ('Source1.pch').
# If the basena... | env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES'
env['BUILDERS']['RES'] = res_builder
env['OBJPREFIX'] = ''
env['OBJSUFFIX'] = '.obj' | random_line_split | |
msvc.py | "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
import re
import sys
import SCons.Action
import SCons.Builder
import SCons.Errors
import SCons.Platform.win32
import SCons.Tool
import SCons.Tool.msvs
import SCons.Util
import SCons.Warnings
import SCons.Scanner.RC
from .MSCommon import msvc_exists, msvc... |
env['CCPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Z7") or ""}'])
env['CCPCHFLAGS'] = SCons.Util.CLVar(['${(PCH and "/Yu%s \\\"/Fp%s\\\""%(PCHSTOP or "",File(PCH))) or ""}'])
env['_MSVC_OUTPUT_FLAG'] = msvc_output_flag
env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $CCPCHFLAGS $CCPDBFLAGS'... | """Add Builders and construction variables for MSVC++ to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
# TODO(batch): shouldn't reach in to cmdgen this way; necessary
# for now to bypass the checks in Builder.DictCmdGenerator.__call__()
# and allow .cc and .cpp to be co... | identifier_body |
msvc.py | "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
import re
import sys
import SCons.Action
import SCons.Builder
import SCons.Errors
import SCons.Platform.win32
import SCons.Tool
import SCons.Tool.msvs
import SCons.Util
import SCons.Warnings
import SCons.Scanner.RC
from .MSCommon import msvc_exists, msvc... | (target, source, env):
"""Adds the object file target."""
validate_vars(env)
pch = None
obj = None
for t in target:
if SCons.Util.splitext(str(t))[1] == '.pch':
pch = t
if SCons.Util.splitext(str(t))[1] == '.obj':
obj = t
if not obj:
obj = SCon... | pch_emitter | identifier_name |
msvc.py | , source)
def static_object_emitter(target, source, env):
return object_emitter(target, source, env,
SCons.Defaults.StaticObjectEmitter)
def shared_object_emitter(target, source, env):
return object_emitter(target, source, env,
SCons.Defaults.SharedObjectEmi... | env['ENV']['SystemRoot'] = SCons.Platform.win32.get_system_root() | conditional_block | |
index.d.ts | // Type definitions for jasmine-ajax 3.1
// Project: https://github.com/jasmine/jasmine-ajax
// Definitions by: Louis Grignon <https://github.com/lgrignon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
interface JasmineAjaxResponse {
status?: number;
statusText?: strin... | {
constructor(globals: any);
install(): void;
uninstall(): void;
withMock(closure: () => void): void;
addCustomParamParser(parser: JasmineAjaxParamParser): void;
stubRequest(url: RegExp, data?: string, method?: string): JasmineAjaxRequestStub;
stubRequest(url: string, data?: string, method?: string): Jasmine... | MockAjax | identifier_name |
index.d.ts | // Type definitions for jasmine-ajax 3.1
// Project: https://github.com/jasmine/jasmine-ajax
// Definitions by: Louis Grignon <https://github.com/lgrignon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
interface JasmineAjaxResponse {
status?: number;
statusText?: strin... | }
interface JasmineAjaxParamParser {
test(xhr: XMLHttpRequest): boolean;
parse(paramString: string): any;
}
declare class MockAjax {
constructor(globals: any);
install(): void;
uninstall(): void;
withMock(closure: () => void): void;
addCustomParamParser(parser: JasmineAjaxParamParser): void;
stubRequest(ur... | interface JasmineAjaxStubTracker {
addStub(stub: JasmineAjaxRequestStub): void;
reset(): void;
findStub(url: string, data?: string, method?: string): JasmineAjaxRequestStub; | random_line_split |
migration.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... | """Get the path for the migrate repository."""
path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'migrate_repo')
assert os.path.exists(path)
return path | identifier_body | |
migration.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... | ():
"""Get the path for the migrate repository."""
path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'migrate_repo')
assert os.path.exists(path)
return path
| get_migrate_repo_path | identifier_name |
migration.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
import os
from migrate.versioning import api as versioning_api
# See LP bug #719834. sqlalchemy-migrate changed location of
... | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT | random_line_split |
control.js | var Util = require( 'findhit-util' );
// -----------------------------------------------------------------------------
// Data handles wizard data into session
function Data ( route ) | ;
// Export Data
module.exports = Data;
/* instance methods */
Data.prototype.currentStep = function ( step ) {
// If there is no `step` provided, it means that we wan't to get!
// Otherwise, lets set it!
};
/*
Data.prototype.save = function () {
};
Data.prototype.destroy = function () {
};
*/
Data.prot... | {
var session = route.req[ route.router.options.reqSessionKey ];
// If there isn't a `wiz` object on session, just add it
if( ! session.wiz ) {
session.wiz = {};
}
// Save route on this instance
this.route = route;
// Gather session from session, or just create a new one
this.... | identifier_body |
control.js | var Util = require( 'findhit-util' );
// -----------------------------------------------------------------------------
// Data handles wizard data into session
function Data ( route ) {
var session = route.req[ route.router.options.reqSessionKey ];
// If there isn't a `wiz` object on session, just add it
... |
// Save route on this instance
this.route = route;
// Gather session from session, or just create a new one
this.session = session.wiz[ route.id ] || ( session.wiz[ route.id ] = {} );
// Add a control variable for changed state
this.changed = false;
return this;
};
// Export Data
modul... | {
session.wiz = {};
} | conditional_block |
control.js | var Util = require( 'findhit-util' );
// -----------------------------------------------------------------------------
// Data handles wizard data into session
function Data ( route ) {
var session = route.req[ route.router.options.reqSessionKey ];
// If there isn't a `wiz` object on session, just add it
... | Data.prototype.currentStep = function ( step ) {
// If there is no `step` provided, it means that we wan't to get!
// Otherwise, lets set it!
};
/*
Data.prototype.save = function () {
};
Data.prototype.destroy = function () {
};
*/
Data.prototype.getFromStep = function ( step ) {
}; | random_line_split | |
control.js | var Util = require( 'findhit-util' );
// -----------------------------------------------------------------------------
// Data handles wizard data into session
function | ( route ) {
var session = route.req[ route.router.options.reqSessionKey ];
// If there isn't a `wiz` object on session, just add it
if( ! session.wiz ) {
session.wiz = {};
}
// Save route on this instance
this.route = route;
// Gather session from session, or just create a new on... | Data | identifier_name |
manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
# if os.path.exists('.env'):
# print('Importing environment from .env...')
# for... |
# if __name__ == '__main__':
# manager.run() | random_line_split | |
manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
|
# if os.path.exists('.env'):
# print('Importing environment from .env...')
# for line in open('.env'):
# var = line.strip().split('=')
# if len(var) == 2:
# os.environ[var[0]] = var[1]
# from finance import create_app
# from flask.ext.script import Manager
# from finance import db... | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) | conditional_block |
goggle-paper.js | /* google-paper.js */
'use strict';
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var RAD_2_DEG = 180/Math.PI;
function moving_average(period) |
var GP = GP || {};
GP.PaperTracker = function(options){
this.options = options || {};
this.video;
this.canvas;
this.context;
this.camDirection = 'front'; // back
this.imageData;
this.detector;
this.posit;
this.markers;
this.init(options);
};
GP.PaperTracker.prototype.init = function(options){
thi... | {
var nums = [];
return function(num) {
nums.push(num);
if (nums.length > period)
nums.splice(0,1);
var sum = 0;
for (var i in nums)
sum += nums[i];
var n = period;
if (nums.length < period)
n = nums.length;
return(sum/n);
}
} | identifier_body |
goggle-paper.js | /* google-paper.js */
'use strict';
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var RAD_2_DEG = 180/Math.PI;
function moving_average(period) {
var nums = [];
return function(num) {
nums.push(num);
if (nums.length > period)
nums.splic... | function (stream){
if (window.webkitURL) {
vid.src = window.webkitURL.createObjectURL(stream);
} else if (vid.mozSrcObject !== undefined) {
vid.mozSrcObject = stream;
} else {
vid.src = stream;
}
},
function(error){
console.log('stream not found');
}... | navigator.getUserMedia({video:true}, | random_line_split |
goggle-paper.js | /* google-paper.js */
'use strict';
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var RAD_2_DEG = 180/Math.PI;
function | (period) {
var nums = [];
return function(num) {
nums.push(num);
if (nums.length > period)
nums.splice(0,1);
var sum = 0;
for (var i in nums)
sum += nums[i];
var n = period;
if (nums.length < period)
n = nums.length;
return(sum/n);
}
}
var GP = GP || {};
GP.PaperTra... | moving_average | identifier_name |
goggle-paper.js | /* google-paper.js */
'use strict';
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var RAD_2_DEG = 180/Math.PI;
function moving_average(period) {
var nums = [];
return function(num) {
nums.push(num);
if (nums.length > period)
nums.splic... |
this.context.stroke();
this.context.closePath();
this.context.strokeStyle = "blue";
this.context.strokeRect(corners[0].x - 2, corners[0].y - 2, 4, 4);
}
};
GP.PaperTracker.prototype.updateTracking = function(){
var corners, corner, pose, i;
if (this.markers.length == 0) {
this.trac... | {
corner = corners[j];
this.context.moveTo(corner.x, corner.y);
corner = corners[(j + 1) % corners.length];
this.context.lineTo(corner.x, corner.y);
} | conditional_block |
test_utils.py | # Copyright (C) 2013 Yahoo! Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | (self):
self.assertTrue(utils.str2bool('true'))
def test_string_to_bool_false(self):
self.assertFalse(utils.str2bool('false'))
def test_string_to_bool_None(self):
self.assertIsNone(utils.str2bool(None))
def test_string_to_dictionary(self):
input_str = 'key1=value1,key2=val... | test_string_to_bool_true | identifier_name |
test_utils.py | # Copyright (C) 2013 Yahoo! Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... | mixed_fields = ('test user', 'ID')
item = Fake()
actual = utils.get_item_properties(item, fields, mixed_fields)
self.assertEqual(('test_name', 'test_id', 'test'), actual)
def test_get_object_item_desired_fields_differ_from_item(self):
class Fake(object):
def __in... | self.name = 'test_name'
self.test_user = 'test'
fields = ('name', 'id', 'test user') | random_line_split |
test_utils.py | # Copyright (C) 2013 Yahoo! Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... |
class ImportClassTestCase(testtools.TestCase):
def test_get_client_class_invalid_version(self):
self.assertRaises(
exceptions.UnsupportedVersion,
utils.get_client_class, 'image', '2', {'image': '2'})
| class Fake(object):
def __init__(self):
self.id = 'test_id'
self.name = 'test_name'
self.test_user = 'test'
class FakeCallable(object):
def __call__(self, *args, **kwargs):
return 'pass'
fields = ('name', 'id', 'te... | identifier_body |
Gruntfile.js | /**
* http://gruntjs.com/configuring-tasks
*/
module.exports = function (grunt) {
var path = require('path');
var DIST_PATH = 'demo/dist';
var SRC_PATH = 'demo/sample';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
options: {
host... | /*'less',*/
'clean:doc',
'copy:plugin',
'copy:pluginForNewNPM',
'jsdoc:doc'
]);
grunt.registerTask('egjs', 'Create documentations for egjs', [
/*'less',*/
'clean:doc',
'copy:plugin',
'copy:pluginForNewNPM',
'jsdoc:egjs'
]);
}; | // 'watch'
// ]);
grunt.registerTask('default', 'Create documentations for yours', [ | random_line_split |
webgl_lines_colors.ts | /// <reference path="../../three.d.ts" />
/// <reference path="../three-tests-setup.ts" />
// https://github.com/mrdoob/three.js/blob/master/examples/webgl_lines_colors.html
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var hilbert3D: any;
... |
}
//
function animate() {
requestAnimationFrame(animate);
render();
stats.update();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * .05;
camera.position.y += (- mouseY + 200 - camera.position.y) * .05;
... |
event.preventDefault();
mouseX = event.touches[0].pageX - windowHalfX;
mouseY = event.touches[0].pageY - windowHalfY;
}
| conditional_block |
webgl_lines_colors.ts | /// <reference path="../../three.d.ts" />
/// <reference path="../three-tests-setup.ts" />
// https://github.com/mrdoob/three.js/blob/master/examples/webgl_lines_colors.html
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var hilbert3D: any;
... | document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('touchstart', onDocumentTouchStart, false);
document.addEventListener('touchmove', onDocumentTouchMove, false);
//
var renderModel = new THREE.RenderPass(scene, camera);
... | //
| random_line_split |
webgl_lines_colors.ts | /// <reference path="../../three.d.ts" />
/// <reference path="../three-tests-setup.ts" />
// https://github.com/mrdoob/three.js/blob/master/examples/webgl_lines_colors.html
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var hilbert3D: any;
... | {
camera.position.x += (mouseX - camera.position.x) * .05;
camera.position.y += (- mouseY + 200 - camera.position.y) * .05;
camera.lookAt(scene.position);
var time = Date.now() * 0.0005;
for (var i = 0; i < scene.children.length; i++) {
var object = s... | nder() | identifier_name |
webgl_lines_colors.ts | /// <reference path="../../three.d.ts" />
/// <reference path="../three-tests-setup.ts" />
// https://github.com/mrdoob/three.js/blob/master/examples/webgl_lines_colors.html
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var hilbert3D: any;
... |
//
function animate() {
requestAnimationFrame(animate);
render();
stats.update();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * .05;
camera.position.y += (- mouseY + 200 - camera.position.y) * .05;
camer... |
if (event.touches.length == 1) {
event.preventDefault();
mouseX = event.touches[0].pageX - windowHalfX;
mouseY = event.touches[0].pageY - windowHalfY;
}
}
| identifier_body |
jwplatform.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
float_or_none,
int_or_none,
)
class JWPlatformBaseIE(InfoExtractor):
@staticmethod
def _find_jwplayer_data(webpage):
# TODO: Merge this with JWPlayer-r... |
def _real_extract(self, url):
video_id = self._match_id(url)
json_data = self._download_json('http://content.jwplatform.com/feeds/%s.json' % video_id, video_id)
return self._parse_jwplayer_data(json_data, video_id)
| return mobj.group('url') | conditional_block |
jwplatform.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
float_or_none,
int_or_none,
)
class JWPlatformBaseIE(InfoExtractor):
@staticmethod
def _find_jwplayer_data(webpage):
# TODO: Merge this with JWPlayer-r... | video_id = self._match_id(url)
json_data = self._download_json('http://content.jwplatform.com/feeds/%s.json' % video_id, video_id)
return self._parse_jwplayer_data(json_data, video_id) | return mobj.group('url')
def _real_extract(self, url): | random_line_split |
jwplatform.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
float_or_none,
int_or_none,
)
class JWPlatformBaseIE(InfoExtractor):
@staticmethod
def _find_jwplayer_data(webpage):
# TODO: Merge this with JWPlayer-r... | return mobj.group('url')
def _real_extract(self, url):
video_id = self._match_id(url)
json_data = self._download_json('http://content.jwplatform.com/feeds/%s.json' % video_id, video_id)
return self._parse_jwplayer_data(json_data, video_id)
| _VALID_URL = r'(?:https?://content\.jwplatform\.com/(?:feeds|players|jw6)/|jwplatform:)(?P<id>[a-zA-Z0-9]{8})'
_TEST = {
'url': 'http://content.jwplatform.com/players/nPripu9l-ALJ3XQCI.js',
'md5': 'fa8899fa601eb7c83a64e9d568bdf325',
'info_dict': {
'id': 'nPripu9l',
'e... | identifier_body |
jwplatform.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
float_or_none,
int_or_none,
)
class JWPlatformBaseIE(InfoExtractor):
@staticmethod
def | (webpage):
# TODO: Merge this with JWPlayer-related codes in generic.py
mobj = re.search(
'jwplayer\((?P<quote>[\'"])[^\'" ]+(?P=quote)\)\.setup\((?P<options>[^)]+)\)',
webpage)
if mobj:
return mobj.group('options')
def _extract_jwplayer_data(self, webpa... | _find_jwplayer_data | identifier_name |
lcm.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
... |
#[test]
fn lcm_fail() {
apply_fn_to_unsigneds!(lcm_fail_helper);
}
#[test]
fn test_checked_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: Option<T>) {
assert_eq!(x.checked_lcm(y), out);
}
test::<u8>(0, 0, Some(0));
test::<u16>(0, 6, Some(0));
test::<u32>(6, 0, Some(0));
tes... | } | random_line_split |
lcm.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn | <T: PrimitiveUnsigned>(x: T, y: T, out: T) {
assert_eq!(x.lcm(y), out);
let mut x = x;
x.lcm_assign(y);
assert_eq!(x, out);
}
test::<u8>(0, 0, 0);
test::<u16>(0, 6, 0);
test::<u32>(6, 0, 0);
test::<u64>(1, 6, 6);
test::<u128>(6, 1, 6);
test::<usize>(8, 12, 24... | test | identifier_name |
lcm.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
... |
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.checked_lcm(x), Some(x));
assert_eq!(x.checked_lcm(T::ONE), Some(x));
assert_eq!(x.checked_lcm(T::ZERO), Some(T::ZERO));
});
unsigned_triple_gen_var_19::<T>().test_properties(|(x, y, z)| {
if x != T::ZERO && y ... | {
assert_eq!(x.lcm(y), lcm);
} | conditional_block |
lcm.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
... |
#[test]
fn test_checked_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: Option<T>) {
assert_eq!(x.checked_lcm(y), out);
}
test::<u8>(0, 0, Some(0));
test::<u16>(0, 6, Some(0));
test::<u32>(6, 0, Some(0));
test::<u64>(1, 6, Some(6));
test::<u128>(6, 1, Some(6));
test::<us... | {
apply_fn_to_unsigneds!(lcm_fail_helper);
} | identifier_body |
index.ts | import { deepMix, get, isFunction } from '@antv/util';
import { FIELD_ORIGIN } from '../constant';
import { Coordinate, IGroup, IShape } from '../dependents';
import { AnimateCfg, Data, Datum, GAnimateCfg, Point } from '../interface';
import { AnimateExtraCfg } from './interface';
import { getAnimation } from './anima... | {
const data = get(shape.get('origin'), 'data', FIELD_ORIGIN);
const animation = animateCfg.animation; // 获取动画执行函数
const parsedAnimateCfg = parseAnimateConfig(animateCfg, data);
if (animation) {
// 用户声明了动画执行函数
const animateFunction = getAnimation(animation);
if (animateFunction) {
animateFunc... | animateCfg: AnimateCfg, cfg: AnimateExtraCfg) | conditional_block |
index.ts | import { deepMix, get, isFunction } from '@antv/util';
import { FIELD_ORIGIN } from '../constant';
import { Coordinate, IGroup, IShape } from '../dependents';
import { AnimateCfg, Data, Datum, GAnimateCfg, Point } from '../interface';
import { AnimateExtraCfg } from './interface';
import { getAnimation } from './anima... | line: () => {
return {
animation: 'wave-in',
};
},
area: () => {
return {
animation: 'wave-in',
};
},
path: () => {
return {
animation: 'fade-in',
};
},
interval(coordinate: Coordinate) {
let animation;
if (coordinate.isRect) {
animation = coordinat... | },
};
// 各个 Geometry 默认的群组出场动画
const GEOMETRY_GROUP_APPEAR_ANIMATION = { | random_line_split |
index.ts | import { deepMix, get, isFunction } from '@antv/util';
import { FIELD_ORIGIN } from '../constant';
import { Coordinate, IGroup, IShape } from '../dependents';
import { AnimateCfg, Data, Datum, GAnimateCfg, Point } from '../interface';
import { AnimateExtraCfg } from './interface';
import { getAnimation } from './anima... | pMix({}, DEFAULT_ANIMATE_CFG, animateCfg);
if (animateType) {
return animateCfg[animateType];
}
}
return animateCfg;
}
/**
* @ignore
* 工具函数
* 根据用户传入的配置为 shape 执行动画
* @param shape 执行动画的图形元素
* @param animateCfg 动画配置
* @param cfg 额外的信息
*/
export function doAnimate(shape: IGroup | IShape, animate... | animateCfg = dee | identifier_name |
index.ts | import { deepMix, get, isFunction } from '@antv/util';
import { FIELD_ORIGIN } from '../constant';
import { Coordinate, IGroup, IShape } from '../dependents';
import { AnimateCfg, Data, Datum, GAnimateCfg, Point } from '../interface';
import { AnimateExtraCfg } from './interface';
import { getAnimation } from './anima... | ,动画类型
*/
export function getDefaultAnimateCfg(elementName: string, coordinate: Coordinate, animateType?: string) {
let animateCfg = GEOMETRY_ANIMATE_CFG[elementName];
if (animateCfg) {
if (isFunction(animateCfg)) {
animateCfg = animateCfg(coordinate);
}
animateCfg = deepMix({}, DEFAULT_ANIMATE_C... | : animateCfg.easing,
duration: isFunction(animateCfg.duration) ? animateCfg.duration(data) : animateCfg.duration,
callback: animateCfg.callback,
repeat: animateCfg.repeat,
};
}
/**
* @ignore
* 获取 elementName 对应的动画配置,当声明了 `animateType`,则返回 `animateType` 对应的动画配置
* @param elementName 元素名称
* @param coord... | identifier_body |
args.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 ... | (&self) -> &[OsString] {
self.iter.as_slice()
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl ExactSizeIterator for Args {
f... | inner_debug | identifier_name |
args.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 ... | Args {
iter: v.into_iter(),
_dont_send_or_sync_me: PhantomData,
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn inner_debug(&self) -> &[OsString] {
self.iter.as_slice()
}
}
impl Iterator for Args {
... | pub unsafe fn cleanup() {
}
pub fn args() -> Args {
let v = ArgsSysCall::perform(); | random_line_split |
args.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 ... |
pub unsafe fn cleanup() {
}
pub fn args() -> Args {
let v = ArgsSysCall::perform();
Args {
iter: v.into_iter(),
_dont_send_or_sync_me: PhantomData,
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn inner_de... | {
// On wasm these should always be null, so there's nothing for us to do here
} | identifier_body |
score_responsible.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | # Copyright (C) 2015-2021 Université catholique de Louvain (http://www.uclouvain.be)
#
# 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 3 of the License, or
# (at yo... | # | random_line_split |
score_responsible.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | earning_class_year = factory.SubFactory(
LearningClassYearFactory,
learning_component_year__lecturing=True,
learning_component_year__learning_unit_year=factory.LazyAttribute(
lambda component: component.factory_parent.factory_parent.learning_unit_year
)
)
| identifier_body | |
score_responsible.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... |
model = 'assessments.ScoreResponsible'
tutor = factory.SubFactory(TutorFactory)
learning_unit_year = factory.SubFactory(LearningUnitYearFactory)
learning_class_year = None
class ScoreResponsibleOfClassFactory(ScoreResponsibleFactory):
learning_class_year = factory.SubFactory(
Learnin... | eta: | identifier_name |
delete_data_for_sample.py | #!/usr/bin/env python3
# noinspection PyUnresolvedReferences
import init_django
from django.db import transaction
from common.utils import utcnow
from main.archive import DataArchiver
from main.delete import DataDeleter
from main.models import Ranking
from main.purge import purge_player_data
from tasks.base import C... | (Command):
def __init__(self):
super().__init__("Delete ranking and all cache data and ranking data linked to it, used for broken "
"rankings.",
pid_file=True, stoppable=False)
self.add_argument('--delete', dest="delete", action='store_true', de... | Main | identifier_name |
delete_data_for_sample.py | #!/usr/bin/env python3
# noinspection PyUnresolvedReferences
import init_django
from django.db import transaction
from common.utils import utcnow
from main.archive import DataArchiver
from main.delete import DataDeleter
from main.models import Ranking
from main.purge import purge_player_data
from tasks.base import C... |
else:
logger.info("DRY RUN no archiving of rankings")
# Delete ladders that are no longer needed.
keep_season_ids = {r.season_id for r in Ranking.objects.all()}
data_deleter.delete_ladders(tuple(keep_season_ids))
# Delete cache data tha... | logger.info(f"archiving ranking {ranking.id}")
data_archiver.archive_ranking(ranking, self.check_stop) | conditional_block |
delete_data_for_sample.py | #!/usr/bin/env python3
# noinspection PyUnresolvedReferences
import init_django
from django.db import transaction
from common.utils import utcnow
from main.archive import DataArchiver
from main.delete import DataDeleter
from main.models import Ranking
from main.purge import purge_player_data
from tasks.base import C... | def __init__(self):
super().__init__("Delete ranking and all cache data and ranking data linked to it, used for broken "
"rankings.",
pid_file=True, stoppable=False)
self.add_argument('--delete', dest="delete", action='store_true', default=False,
... | random_line_split | |
delete_data_for_sample.py | #!/usr/bin/env python3
# noinspection PyUnresolvedReferences
import init_django
from django.db import transaction
from common.utils import utcnow
from main.archive import DataArchiver
from main.delete import DataDeleter
from main.models import Ranking
from main.purge import purge_player_data
from tasks.base import C... | logger.info("DRY RUN no archiving of rankings")
# Delete ladders that are no longer needed.
keep_season_ids = {r.season_id for r in Ranking.objects.all()}
data_deleter.delete_ladders(tuple(keep_season_ids))
# Delete cache data that is unused.
... | keep_ids = (int(id) for id in args.keep_rankings.split(","))
with transaction.atomic():
remove_ids = [r.id for r in Ranking.objects.exclude(id__in=keep_ids)]
data_deleter = DataDeleter(dry_run=not args.delete)
data_archiver = DataArchiver(utcnow(), remove=True)
... | identifier_body |
test_forms.py | # -*- coding: utf-8 -*-
"""
Unit tests for embargo app admin forms.
"""
from __future__ import absolute_import
import six
# Explicitly import the cache from ConfigurationModel so we can reset it after each test
from config_models.models import cache
from django.test import TestCase
from opaque_keys.edx.locator import... | " Please fix the error(s) and try again."
self.assertEquals(bmsg, form._errors['blacklist'][0]) # pylint: disable=protected-access
with self.assertRaisesRegexp(ValueError, "The IPFilter could not be created because the data didn't validate."):
form.save()
| form_data = {
'whitelist': u'.0.0.1, :dead:beef:::, 1.0.0.0/55',
'blacklist': u' 18.244.* , 999999:c0a8:101::42, 1.0.0.0/'
}
form = IPFilterForm(data=form_data)
self.assertFalse(form.is_valid())
if six.PY2:
wmsg = "Invalid IP Address(es): [u'.0.0.1... | identifier_body |
test_forms.py | # -*- coding: utf-8 -*-
"""
Unit tests for embargo app admin forms.
"""
from __future__ import absolute_import
import six
# Explicitly import the cache from ConfigurationModel so we can reset it after each test
from config_models.models import cache
from django.test import TestCase
from opaque_keys.edx.locator import... |
else:
wmsg = "Invalid IP Address(es): ['.0.0.1', ':dead:beef:::', '1.0.0.0/55']" \
" Please fix the error(s) and try again."
self.assertEquals(wmsg, form._errors['whitelist'][0]) # pylint: disable=protected-access
if six.PY2:
bmsg = "Invalid IP Addre... | wmsg = "Invalid IP Address(es): [u'.0.0.1', u':dead:beef:::', u'1.0.0.0/55']" \
" Please fix the error(s) and try again." | conditional_block |
test_forms.py | # -*- coding: utf-8 -*-
"""
Unit tests for embargo app admin forms.
"""
from __future__ import absolute_import
import six
# Explicitly import the cache from ConfigurationModel so we can reset it after each test
from config_models.models import cache
from django.test import TestCase
from opaque_keys.edx.locator import... | for addr in [u'2.0.0.0', u'1.1.0.0']:
self.assertNotIn(addr.strip(), blacklist)
# ips in blacklist network
for addr in [u'1.0.100.0', u'1.0.0.10']:
self.assertIn(addr.strip(), blacklist)
# Test clearing by adding an empty list is OK too
form_data = {
... | self.assertNotIn(addr.strip(), whitelist)
# ips in whitelist network
for addr in [u'1.1.0.1', u'1.0.0.100']:
self.assertIn(addr.strip(), whitelist)
# ips not in blacklist network | random_line_split |
test_forms.py | # -*- coding: utf-8 -*-
"""
Unit tests for embargo app admin forms.
"""
from __future__ import absolute_import
import six
# Explicitly import the cache from ConfigurationModel so we can reset it after each test
from config_models.models import cache
from django.test import TestCase
from opaque_keys.edx.locator import... | (self, form):
"""
Validation shouldn't work.
"""
self.assertFalse(form.is_valid())
msg = 'COURSE NOT FOUND'
self.assertIn(msg, form._errors['course_key'][0]) # pylint: disable=protected-access
with self.assertRaisesRegexp(
ValueError, "The Restricte... | _assert_course_field_error | identifier_name |
response.rs | use std::{fmt,str};
use std::collections::HashMap;
pub type Headers = HashMap<String, Vec<String>>;
pub struct Response {
code: uint,
hdrs: Headers,
body: Vec<u8>
}
impl Response {
pub fn new(code: uint, hdrs: Headers, body: Vec<u8>) -> Response {
Response {
code: code,
... |
}
impl fmt::Show for Response {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::FormatError> {
try!(write!(fmt, "Response {{{}, ", self.code));
for (name, val) in self.hdrs.iter() {
try!(write!(fmt, "{}: {}, ", name, val.connect(", ")));
}
match str::from_u... | {
self.body
} | identifier_body |
response.rs | use std::{fmt,str};
use std::collections::HashMap;
pub type Headers = HashMap<String, Vec<String>>;
pub struct Response {
code: uint,
hdrs: Headers,
body: Vec<u8>
}
impl Response {
pub fn new(code: uint, hdrs: Headers, body: Vec<u8>) -> Response {
Response {
code: code,
... | (&self) -> uint {
self.code
}
pub fn get_headers<'a>(&'a self) -> &'a Headers {
&self.hdrs
}
pub fn get_header<'a>(&'a self, name: &str) -> &'a [String] {
self.hdrs
.find_equiv(name)
.map(|v| v.as_slice())
.unwrap_or(&[])
}
pub fn ge... | get_code | identifier_name |
response.rs | use std::{fmt,str};
use std::collections::HashMap;
pub type Headers = HashMap<String, Vec<String>>;
pub struct Response {
code: uint,
hdrs: Headers,
body: Vec<u8>
}
impl Response {
pub fn new(code: uint, hdrs: Headers, body: Vec<u8>) -> Response {
Response {
code: code,
... | Some(b) => try!(write!(fmt, "{}", b)),
None => try!(write!(fmt, "bytes[{}]", self.body.len()))
}
try!(write!(fmt, "]"));
Ok(())
}
} | random_line_split | |
settings.py | """
Django settings for CL_Project project.
Generated by 'django-admin startproject' using Django 1.9.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os... | 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAut... | MIDDLEWARE_CLASSES = [ | random_line_split |
stored_values.py | #!/usr/bin/env python
'''
@author Luke C
@date Mon Mar 25 09:57:59 EDT 2013
@file ion/util/stored_values.py
'''
from pyon.core.exception import NotFound
import gevent
class StoredValueManager(object):
def __init__(self, container):
self.store = container.object_store
def | (self, doc_key, document_updates):
'''
Performs a check and set for a lookup_table in the object store for the given key
'''
try:
doc = self.store.read_doc(doc_key)
except NotFound:
doc_id, rev = self.store.create_doc(document_updates, object_id=doc_key)
... | stored_value_cas | identifier_name |
stored_values.py | #!/usr/bin/env python
'''
@author Luke C
@date Mon Mar 25 09:57:59 EDT 2013
@file ion/util/stored_values.py
'''
from pyon.core.exception import NotFound
import gevent
class StoredValueManager(object):
def __init__(self, container):
self.store = container.object_store
def stored_value_cas(self, doc_... | doc = self.store.read_doc(doc_key)
except NotFound:
doc_id, rev = self.store.create_doc(document_updates, object_id=doc_key)
return doc_id, rev
except KeyError as e:
if 'http' in e.message:
doc_id, rev = self.store.create_doc(document_updat... | try: | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.