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 |
|---|---|---|---|---|
Bootstrap.js | /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) |
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/*****... | {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: fals... | identifier_body |
MailAddressToGroup.ts | import {create} from "../../common/utils/EntityUtils.js"
import {TypeRef, downcast} from "@tutao/tutanota-utils"
import type {TypeModel} from "../../common/EntityTypes.js"
export const MailAddressToGroupTypeRef: TypeRef<MailAddressToGroup> = new TypeRef("sys", "MailAddressToGroup")
export const _TypeModel: TypeModel ... | "encrypted": false
},
"_permissions": {
"id": 207,
"type": "GeneratedId",
"cardinality": "One",
"final": true,
"encrypted": false
}
},
"associations": {
"internalGroup": {
"id": 209,
"type": "ELEMENT_ASSOCIATION",
"cardinality": "ZeroOrOne",
"final": false,
"refType": "Group"
... | random_line_split | |
MailAddressToGroup.ts | import {create} from "../../common/utils/EntityUtils.js"
import {TypeRef, downcast} from "@tutao/tutanota-utils"
import type {TypeModel} from "../../common/EntityTypes.js"
export const MailAddressToGroupTypeRef: TypeRef<MailAddressToGroup> = new TypeRef("sys", "MailAddressToGroup")
export const _TypeModel: TypeModel ... |
export type MailAddressToGroup = {
_type: TypeRef<MailAddressToGroup>;
_format: NumberString;
_id: Id;
_ownerGroup: null | Id;
_permissions: Id;
internalGroup: null | Id;
} | {
return Object.assign(create(_TypeModel, MailAddressToGroupTypeRef), downcast<MailAddressToGroup>(values))
} | identifier_body |
MailAddressToGroup.ts | import {create} from "../../common/utils/EntityUtils.js"
import {TypeRef, downcast} from "@tutao/tutanota-utils"
import type {TypeModel} from "../../common/EntityTypes.js"
export const MailAddressToGroupTypeRef: TypeRef<MailAddressToGroup> = new TypeRef("sys", "MailAddressToGroup")
export const _TypeModel: TypeModel ... | (values?: Partial<MailAddressToGroup>): MailAddressToGroup {
return Object.assign(create(_TypeModel, MailAddressToGroupTypeRef), downcast<MailAddressToGroup>(values))
}
export type MailAddressToGroup = {
_type: TypeRef<MailAddressToGroup>;
_format: NumberString;
_id: Id;
_ownerGroup: null | Id;
_permissions: Id... | createMailAddressToGroup | identifier_name |
objects.py | import _metagam3d
from _metagam3d import AxisAlignment, AlignmentType
from metagam3d.channels import blocking
from metagam3d.scripts import m3d_expr
from concurrence import Tasklet
class LoadError(Exception):
pass
class Object(_metagam3d.Object):
def __init__(self, objid):
_metagam3d.Object.__init__(s... |
val = _metagam3d.DynamicValue(val)
self.param(paramid).setValue(val)
def setParam3(self, paramid, x, y, z):
self.setParam(paramid, _metagam3d.Vec3d(x, y, z))
def setParamExpr(self, paramid, expr, till=None):
self.param(paramid).setValue(m3d_expr(expr, till))
def assig... | val = _metagam3d.Variant(val) | conditional_block |
objects.py | import _metagam3d
from _metagam3d import AxisAlignment, AlignmentType
from metagam3d.channels import blocking
from metagam3d.scripts import m3d_expr
from concurrence import Tasklet
class LoadError(Exception):
pass
class Object(_metagam3d.Object):
def __init__(self, objid):
_metagam3d.Object.__init__(s... | (axisAlignment=AxisAlignment.XY_PLANE, alignment=AlignmentType.CENTER_CENTER):
"Create text object"
return Object(_metagam3d._createText(0, axisAlignment, alignment))
def createConsole(cols=80, rows=25, fontSize=1.0):
return Console(_metagam3d._createConsole(0, cols, rows, fontSize))
def createLine():
... | createText | identifier_name |
objects.py | import _metagam3d
from _metagam3d import AxisAlignment, AlignmentType
from metagam3d.channels import blocking
from metagam3d.scripts import m3d_expr
from concurrence import Tasklet
class LoadError(Exception):
pass
class Object(_metagam3d.Object):
def __init__(self, objid):
_metagam3d.Object.__init__(s... | if type(val) is not _metagam3d.Variant:
val = _metagam3d.Variant(val)
val = _metagam3d.DynamicValue(val)
self.param(paramid).setValue(val)
def setParam3(self, paramid, x, y, z):
self.setParam(paramid, _metagam3d.Vec3d(x, y, z))
def setParamExpr(self, par... | def getParam(self, paramid, t):
return self.param(paramid).getValue(t)
def setParam(self, paramid, val):
if type(val) is not _metagam3d.DynamicValue: | random_line_split |
objects.py | import _metagam3d
from _metagam3d import AxisAlignment, AlignmentType
from metagam3d.channels import blocking
from metagam3d.scripts import m3d_expr
from concurrence import Tasklet
class LoadError(Exception):
pass
class Object(_metagam3d.Object):
def __init__(self, objid):
_metagam3d.Object.__init__(s... |
def assignMaterial(self, geodeName, ambient=0, diffuse=0, specular=0, emission=0, shininess=0):
_metagam3d._assignMaterial(self.id, geodeName, ambient, diffuse, specular, emission, shininess)
def createConsole(self, cols=80, rows=25, fontSize=1.0):
return Console(_metagam3d._createConsole(sel... | self.param(paramid).setValue(m3d_expr(expr, till)) | identifier_body |
AoFecharAspas.js | /* Copyright 2017 Assembleia Legislativa de Minas Gerais
*
* This file is part of Editor-Articulacao.
*
* Editor-Articulacao is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3.
*
* Edito... | *
* You should have received a copy of the GNU Lesser General Public License
* along with Editor-Articulacao. If not, see <http://www.gnu.org/licenses/>.
*/
import { TransformacaoDoProximo } from './Transformacao';
/**
* Quando usuário encerra as aspas na continuação do caput de um artigo,
* então cria-se um n... | * GNU Lesser General Public License for more details. | random_line_split |
AoFecharAspas.js | /* Copyright 2017 Assembleia Legislativa de Minas Gerais
*
* This file is part of Editor-Articulacao.
*
* Editor-Articulacao is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3.
*
* Edito... | ends TransformacaoDoProximo {
constructor() {
super('"\n', '".\n');
}
get tipoTransformacao() {
return 'AoFecharAspas';
}
proximoTipo(editor, ctrl, contexto) {
return contexto.cursor.artigo && contexto.cursor.continuacao ? 'artigo' : null;
}
}
export default AoFecharAs... | charAspas ext | identifier_name |
cli.py | #!/usr/bin/env python
# Copyright 2017, Major Hayden <major@mhtx.net>
#
# 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... |
VALID_OUTPUT_FORMATS = [
'json',
'line',
'telegraf',
'rax-maas'
]
@click.command(cls=MonitorStackCLI, context_settings=context_settings)
@click.option(
'-f', '--format', 'output_format',
type=click.Choice(VALID_OUTPUT_FORMATS),
default='json',
help="Output format (valid options: {}"... | """Load a command and run it."""
for _, pkg_name, _ in pkgutil.iter_modules([self.cmd_folder]):
if pkg_name == name:
mod = importlib.import_module(
'monitorstack.plugins.{}'.format(name)
)
return getattr(mod, 'cli')
else:
... | identifier_body |
cli.py | #!/usr/bin/env python
# Copyright 2017, Major Hayden <major@mhtx.net>
#
# 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... |
else:
raise SystemExit('Module "{}" Not Found.'.format(name))
VALID_OUTPUT_FORMATS = [
'json',
'line',
'telegraf',
'rax-maas'
]
@click.command(cls=MonitorStackCLI, context_settings=context_settings)
@click.option(
'-f', '--format', 'output_format',
type=click.Choice(VAL... | if pkg_name == name:
mod = importlib.import_module(
'monitorstack.plugins.{}'.format(name)
)
return getattr(mod, 'cli') | conditional_block |
cli.py | #!/usr/bin/env python
# Copyright 2017, Major Hayden <major@mhtx.net>
#
# 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... |
import click
context_settings = dict(auto_envvar_prefix='MonitorStack')
class Context(object):
"""Set up a context object that we can pass."""
def __init__(self):
"""Initialize class."""
self.verbose = False
self.home = os.getcwd()
def log(self, msg, *args):
"""Log a m... | import os
import pkgutil
import sys | random_line_split |
cli.py | #!/usr/bin/env python
# Copyright 2017, Major Hayden <major@mhtx.net>
#
# 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... | (self, ctx):
"""Get a list of all available commands."""
rv = list()
for _, pkg_name, _ in pkgutil.iter_modules([self.cmd_folder]):
rv.append(pkg_name)
else:
return sorted(rv)
def get_command(self, ctx, name):
"""Load a command and run it."""
... | list_commands | identifier_name |
ezRPConfig.py | # Copyright (C) 2013-2015 Computer Sciences Corporation
#
# 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 a... | confdDirectory = os.path.join(configDirectory,'conf.d')
manualDirectory = os.path.join(containerDir,'manual')
ezconfig_dir = os.path.join(containerDir, 'config')
htmlRootDir = os.path.join(containerDir, 'static_content')
favicon_file = os.path.join(htmlRootDir, 'ezbstatic', 'images', 'favicon.ico')
# external facing ... | random_line_split | |
ezRPConfig.py | # Copyright (C) 2013-2015 Computer Sciences Corporation
#
# 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 a... | (thriftService, kzMonitor, cfgChange, shutdown):
global clientService
global zkMonitor
global cfgGreenlet
global wGreenlet
clientService = thriftService
zkMonitor = kzMonitor
cfgGreenlet = cfgChange
wGreenlet = shutdown
def kill():
if clientService:
clientService.kill()
... | addGreenlets | identifier_name |
ezRPConfig.py | # Copyright (C) 2013-2015 Computer Sciences Corporation
#
# 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 a... |
def kill():
if clientService:
clientService.kill()
if zkMonitor:
zkMonitor.kill()
if cfgGreenlet:
cfgGreenlet.kill()
| global clientService
global zkMonitor
global cfgGreenlet
global wGreenlet
clientService = thriftService
zkMonitor = kzMonitor
cfgGreenlet = cfgChange
wGreenlet = shutdown | identifier_body |
ezRPConfig.py | # Copyright (C) 2013-2015 Computer Sciences Corporation
#
# 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 a... | cfgGreenlet.kill() | conditional_block | |
hint.rs | use std::collections::HashMap;
pub type FieldIndex = usize;
/// Hints given when reading parcels.
#[derive(Clone, Debug, PartialEq)]
pub struct Hints {
pub current_field_index: Option<FieldIndex>,
/// The fields for which a length prefix
/// was already present earlier in the layout.
pub known_field_l... |
// Updates the hints to indicate a field was just read.
#[doc(hidden)]
pub fn next_field(&mut self) {
*self.current_field_index.as_mut()
.expect("cannot increment next field when not in a struct")+= 1;
}
// Sets the length of a variable-sized field ... | {
self.current_field_index = Some(0);
} | identifier_body |
hint.rs | use std::collections::HashMap;
pub type FieldIndex = usize;
/// Hints given when reading parcels.
#[derive(Clone, Debug, PartialEq)]
pub struct Hints {
pub current_field_index: Option<FieldIndex>,
/// The fields for which a length prefix
/// was already present earlier in the layout.
pub known_field_l... |
impl Default for Hints {
fn default() -> Self {
Hints {
current_field_index: None,
known_field_lengths: HashMap::new(),
}
}
}
impl Hints {
/// Gets the length of the field currently being
/// read, if known.
pub fn current_field_length(&self) -> Option<Field... | Bytes,
/// The length prefix stores the total number of elements inside another field.
Elements,
}
| random_line_split |
hint.rs | use std::collections::HashMap;
pub type FieldIndex = usize;
/// Hints given when reading parcels.
#[derive(Clone, Debug, PartialEq)]
pub struct Hints {
pub current_field_index: Option<FieldIndex>,
/// The fields for which a length prefix
/// was already present earlier in the layout.
pub known_field_l... | {
/// The length prefix stores the total number of bytes making up another field.
Bytes,
/// The length prefix stores the total number of elements inside another field.
Elements,
}
impl Default for Hints {
fn default() -> Self {
Hints {
current_field_index: None,
k... | LengthPrefixKind | identifier_name |
nonuniform_random_number_generation.py | import sys
import random
import collections
import itertools
import bisect
# @include
def | (values, probabilities):
prefix_sum_of_probabilities = (
[0.0] + list(itertools.accumulate(probabilities)))
interval_idx = bisect.bisect(prefix_sum_of_probabilities,
random.random()) - 1
return values[interval_idx]
# @exclude
def main():
n = int(sys.argv[1]) if... | nonuniform_random_number_generation | identifier_name |
nonuniform_random_number_generation.py | import sys
import random
import collections
import itertools
import bisect
# @include
def nonuniform_random_number_generation(values, probabilities):
prefix_sum_of_probabilities = (
[0.0] + list(itertools.accumulate(probabilities)))
interval_idx = bisect.bisect(prefix_sum_of_probabilities,
... |
if __name__ == '__main__':
main()
| n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 50)
T = [float(i) for i in range(n)]
P = []
full_prob = 1.0
for i in range(n - 1):
pi = random.uniform(0.0, full_prob)
P.append(pi)
full_prob -= pi
P.append(full_prob)
print(*T)
print(*P)
print(nonu... | identifier_body |
nonuniform_random_number_generation.py | import sys
import random
import collections
import itertools
import bisect
# @include
def nonuniform_random_number_generation(values, probabilities):
prefix_sum_of_probabilities = (
[0.0] + list(itertools.accumulate(probabilities)))
interval_idx = bisect.bisect(prefix_sum_of_probabilities,
... |
P.append(full_prob)
print(*T)
print(*P)
print(nonuniform_random_number_generation(T, P))
# Test. Perform the nonuniform random number generation for n * k_times
# times and calculate the distribution of each bucket.
k_times = 100000
counts = collections.Counter(
int(nonuniform_r... | pi = random.uniform(0.0, full_prob)
P.append(pi)
full_prob -= pi | conditional_block |
nonuniform_random_number_generation.py | import sys
import random
import collections
import itertools
import bisect
# @include
def nonuniform_random_number_generation(values, probabilities):
prefix_sum_of_probabilities = (
[0.0] + list(itertools.accumulate(probabilities)))
interval_idx = bisect.bisect(prefix_sum_of_probabilities,
... | k_times = 100000
counts = collections.Counter(
int(nonuniform_random_number_generation(T, P))
for _ in range(n * k_times))
for i in range(n):
print(counts[i] / (n * k_times), P[i])
assert abs(counts[i] / (n * k_times) - P[i]) < 0.01
if __name__ == '__main__':
main() | # times and calculate the distribution of each bucket. | random_line_split |
requireFiles_test.js | var assert = require('assert');
var fs = require('fs');
var requireFiles = require(__dirname + '/../lib/requireFiles');
var files = [
__dirname + '/moch/custom_test.txt',
__dirname + '/moch/json_test.json',
__dirname + '/moch/test.js'
];
describe('requireFiles testing', function(){
describe('Structure... | });
describe('Custom engine', function(){
it('Custom engines should work', function(){
var result = requireFiles(files, {
'.js' : require,
'.json' : require,
'.txt' : function(path){
return fs.readFileSync(path).toString();... | '.js' : require,
'.json' : require
});
});
}); | random_line_split |
red.js | /**
* Copyright 2013 IBM Corp.
*
* 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 wr... | return p.version;
}
}
};
RED.__defineGetter__("app", function() { console.log("Deprecated use of RED.app - use RED.httpAdmin instead"); return server.app });
RED.__defineGetter__("httpAdmin", function() { return server.app });
RED.__defineGetter__("httpNode", function() { return server.nodeApp ... | version: function () {
var p = require(path.join(process.env.NODE_RED_HOME,"package.json"));
if (fs.existsSync(path.join(process.env.NODE_RED_HOME,".git"))) {
return p.version+".git";
} else { | random_line_split |
red.js | /**
* Copyright 2013 IBM Corp.
*
* 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 wr... |
}
};
RED.__defineGetter__("app", function() { console.log("Deprecated use of RED.app - use RED.httpAdmin instead"); return server.app });
RED.__defineGetter__("httpAdmin", function() { return server.app });
RED.__defineGetter__("httpNode", function() { return server.nodeApp });
RED.__defineGetter__("server", func... | {
return p.version;
} | conditional_block |
template.js | import defaults from './defaults.js';
import _ from './underscore.js';
import './templateSettings.js';
// When customizing `_.templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters ne... |
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
index = offset + match.length;
if (esc... | random_line_split | |
template.js | import defaults from './defaults.js';
import _ from './underscore.js';
import './templateSettings.js';
// When customizing `_.templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters ne... | (match) {
return '\\' + escapes[match];
}
// In order to prevent third-party code injection through
// `_.templateSettings.variable`, we test it against the following regular
// expression. It is intentionally a bit more liberal than just matching valid
// identifiers, but still prevents possible loopholes through d... | escapeChar | identifier_name |
template.js | import defaults from './defaults.js';
import _ from './underscore.js';
import './templateSettings.js';
// When customizing `_.templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters ne... |
// In order to prevent third-party code injection through
// `_.templateSettings.variable`, we test it against the following regular
// expression. It is intentionally a bit more liberal than just matching valid
// identifiers, but still prevents possible loopholes through defaults or
// destructuring assignment.
var... | {
return '\\' + escapes[match];
} | identifier_body |
managers.py | import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models import Sum
from django.contrib.contenttypes.models import ContentType
class TrendingManager(models.Manager):
def trending(self, model, days=30, kind=""):
views = self.filter(
... |
return views
| try:
d["object"] = ContentType.objects.get_for_id(
d["viewed_content_type"]
).get_object_for_this_type(
pk=d["viewed_object_id"]
)
except ObjectDoesNotExist:
d["object"] = None | conditional_block |
managers.py | import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models import Sum
from django.contrib.contenttypes.models import ContentType
class TrendingManager(models.Manager):
| def trending(self, model, days=30, kind=""):
views = self.filter(
viewed_content_type=ContentType.objects.get_for_model(model),
views_on__gte=datetime.date.today() - datetime.timedelta(days=days),
kind=kind
).values(
"viewed_content_type",
"vie... | identifier_body | |
managers.py | import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models import Sum
from django.contrib.contenttypes.models import ContentType
class TrendingManager(models.Manager):
def trending(self, model, days=30, kind=""):
views = self.filter(
... | num_views=Sum("count")
).order_by("-num_views")
for d in views:
try:
d["object"] = ContentType.objects.get_for_id(
d["viewed_content_type"]
).get_object_for_this_type(
pk=d["viewed_object_id"]
... | "viewed_object_id",
"kind"
).annotate( | random_line_split |
managers.py | import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models import Sum
from django.contrib.contenttypes.models import ContentType
class TrendingManager(models.Manager):
def | (self, model, days=30, kind=""):
views = self.filter(
viewed_content_type=ContentType.objects.get_for_model(model),
views_on__gte=datetime.date.today() - datetime.timedelta(days=days),
kind=kind
).values(
"viewed_content_type",
"viewed_object_i... | trending | identifier_name |
work-dashboard.component.ts | import { Component, OnInit } from '@angular/core';
import { CurrentWorkService } from '../current-work/current-work.service';
import { Work } from 'src/app/services/work/work';
import { Chapter } from 'src/app/services/chapter/chapter';
import { WorkReview } from 'src/app/services/review/work-review';
import { ReviewMo... |
ngOnInit() {
this.currentWork.work
.subscribe(work => this.work = work);
this.currentWork.chapters
.subscribe(chapters => this.workChapters = chapters);
this.currentWork.reviews
.subscribe(reviews => this.workReviews = reviews);
}
}
| { } | identifier_body |
work-dashboard.component.ts | import { Component, OnInit } from '@angular/core';
import { CurrentWorkService } from '../current-work/current-work.service';
import { Work } from 'src/app/services/work/work';
import { Chapter } from 'src/app/services/chapter/chapter';
import { WorkReview } from 'src/app/services/review/work-review';
import { ReviewMo... | activeModal.componentInstance.review = review;
}
constructor(
private currentWork: CurrentWorkService,
private modalService: NgbModal,
) { }
ngOnInit() {
this.currentWork.work
.subscribe(work => this.work = work);
this.currentWork.chapters
.subscribe(chapters => this.wo... | workChapters: Chapter[];
workReviews: WorkReview[];
openReview(review: WorkReview) {
const activeModal = this.modalService.open(ReviewModalComponent, { size: 'lg', scrollable: true, centered: true }); | random_line_split |
work-dashboard.component.ts | import { Component, OnInit } from '@angular/core';
import { CurrentWorkService } from '../current-work/current-work.service';
import { Work } from 'src/app/services/work/work';
import { Chapter } from 'src/app/services/chapter/chapter';
import { WorkReview } from 'src/app/services/review/work-review';
import { ReviewMo... | () {
this.currentWork.work
.subscribe(work => this.work = work);
this.currentWork.chapters
.subscribe(chapters => this.workChapters = chapters);
this.currentWork.reviews
.subscribe(reviews => this.workReviews = reviews);
}
}
| ngOnInit | identifier_name |
photo-page.ts | /**
* Created by tiwen.wang on 8/4/2015.
*/
import {Component,
View,
ElementRef,
EventEmitter,
Inject,
NgFor, NgIf} from 'angular2/angular2';
import { PhotoApi } from 'services/Apis';
@Component({
selector: 'photo-page',
properties: ['photoId', 'open'],
events: ['openChanged: open'],
... |
}
get open() {
return this._open;
}
onPhotoDialogClosed() {
this._open = false;
this.openChanged.next(false);
}
getPhoto(id) {
this.photoLoading = true;
this.photoApi.getPhoto(id).subscribe((photo) => {
this.photoLoading = false;
... | {
delete this.photo;
var el = this.elementRef.nativeElement;
var pd = el.querySelector("#photoDialog");
pd.open();
this.getPhoto(this.id);
} | conditional_block |
photo-page.ts | /**
* Created by tiwen.wang on 8/4/2015.
*/
import {Component,
View,
ElementRef,
EventEmitter,
Inject,
NgFor, NgIf} from 'angular2/angular2';
import { PhotoApi } from 'services/Apis';
@Component({
selector: 'photo-page',
properties: ['photoId', 'open'],
events: ['openChanged: open'],
... | _open: boolean;
openChanged = new EventEmitter();
photoLoading: boolean;
photoApi: PhotoApi;
constructor(elementRef: ElementRef, @Inject(PhotoApi) photoApi) {
this.elementRef = elementRef;
this.photoApi = photoApi;
}
set photoId(id) {
this.id = id;
}
get phot... | random_line_split | |
photo-page.ts | /**
* Created by tiwen.wang on 8/4/2015.
*/
import {Component,
View,
ElementRef,
EventEmitter,
Inject,
NgFor, NgIf} from 'angular2/angular2';
import { PhotoApi } from 'services/Apis';
@Component({
selector: 'photo-page',
properties: ['photoId', 'open'],
events: ['openChanged: open'],
... | (id) {
this.id = id;
}
get photoId() {
return this.id;
}
set open(open) {
this._open = open;
if(this._open && this.id) {
delete this.photo;
var el = this.elementRef.nativeElement;
var pd = el.querySelector("#photoDialog");
... | photoId | identifier_name |
photo-page.ts | /**
* Created by tiwen.wang on 8/4/2015.
*/
import {Component,
View,
ElementRef,
EventEmitter,
Inject,
NgFor, NgIf} from 'angular2/angular2';
import { PhotoApi } from 'services/Apis';
@Component({
selector: 'photo-page',
properties: ['photoId', 'open'],
events: ['openChanged: open'],
... |
set photoId(id) {
this.id = id;
}
get photoId() {
return this.id;
}
set open(open) {
this._open = open;
if(this._open && this.id) {
delete this.photo;
var el = this.elementRef.nativeElement;
var pd = el.querySelector("#photoDialo... | {
this.elementRef = elementRef;
this.photoApi = photoApi;
} | identifier_body |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... |
/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
pub unsafe extern fn trace_refcounted_objects(tracer: *mut JSTracer, _data: *mut libc::c_void) {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let table = live_references.tabl... | let TrustedReference(raw_reflectable) = raw_reflectable;
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
... | identifier_body |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... | }
pub use self::dummy::LIVE_REFERENCES;
/// A pointer to a Rust DOM object that needs to be destroyed.
pub struct TrustedReference(*const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operatio... | use std::rc::Rc;
use std::cell::RefCell;
use super::LiveDOMReferences;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None))); | random_line_split |
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task ... | const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance.
#[allow_un... | ustedReference(* | identifier_name |
TestFileDoc.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) | return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x... | { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } | identifier_body |
TestFileDoc.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('v... | () {
_classCallCheck(this, TestFileDoc);
_get(Object.getPrototypeOf(TestFileDoc.prototype), 'constructor', this).apply(this, arguments);
}
_inherits(TestFileDoc, _FileDoc);
_createClass(TestFileDoc, [{
key: '@kind',
/** set ``testFile`` to kind. */
value: function kind() {
this._valu... | TestFileDoc | identifier_name |
TestFileDoc.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('v... |
var _FileDocJs2 = _interopRequireDefault(_FileDocJs);
/**
* Doc class for test code file.
*/
var TestFileDoc = (function (_FileDoc) {
function TestFileDoc() {
_classCallCheck(this, TestFileDoc);
_get(Object.getPrototypeOf(TestFileDoc.prototype), 'constructor', this).apply(this, arguments);
}
_inher... |
var _FileDocJs = require('./FileDoc.js'); | random_line_split |
TestFileDoc.js | 'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('v... | else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esMo... | { return undefined; } | conditional_block |
plugins.rs | use crate::{
config::{self},
prelude::*,
};
use neon::{prelude::*, result::Throw};
use std::str::FromStr;
use stencila::{
config::Config,
tokio::sync::MutexGuard,
};
use plugins::{self, Plugin, PluginInstallation, Plugins, PLUGINS};
/// Lock the global plugins store
pub fn lock(cx: &mut FunctionContext... |
/// Install a plugin
pub fn install(mut cx: FunctionContext) -> JsResult<JsString> {
let spec = &cx.argument::<JsString>(0)?.value(&mut cx);
let config = &config::lock(&mut cx)?;
let installs = &installations(&mut cx, 1, config)?;
let aliases = &config.plugins.aliases;
let plugins = &mut *lock(&m... | {
let aliases = &config::lock(&mut cx)?.plugins.aliases;
let plugins = &*lock(&mut cx)?;
to_json(cx, plugins.list_plugins(aliases))
} | identifier_body |
plugins.rs | use crate::{
config::{self},
prelude::*,
};
use neon::{prelude::*, result::Throw};
use std::str::FromStr;
use stencila::{
config::Config,
tokio::sync::MutexGuard,
};
use plugins::{self, Plugin, PluginInstallation, Plugins, PLUGINS};
/// Lock the global plugins store
pub fn lock(cx: &mut FunctionContext... | (
cx: &mut FunctionContext,
position: i32,
config: &Config,
) -> Result<Vec<PluginInstallation>, Throw> {
let arg = cx.argument::<JsArray>(position)?.to_vec(cx)?;
if arg.is_empty() {
Ok(config.plugins.installations.clone())
} else {
let mut installations = Vec::new();
for... | installations | identifier_name |
plugins.rs | use crate::{
config::{self},
prelude::*,
};
use neon::{prelude::*, result::Throw};
use std::str::FromStr;
use stencila::{
config::Config,
tokio::sync::MutexGuard,
};
use plugins::{self, Plugin, PluginInstallation, Plugins, PLUGINS};
/// Lock the global plugins store
pub fn lock(cx: &mut FunctionContext... | {
Ok(_) => to_json(cx, plugins.list_plugins(aliases)),
Err(error) => cx.throw_error(error.to_string()),
}
}
/// Uninstall a plugin
pub fn uninstall(mut cx: FunctionContext) -> JsResult<JsString> {
let alias = &cx.argument::<JsString>(0)?.value(&mut cx);
let aliases = &config::lock(&mut ... | random_line_split | |
test-gun-modifier-base.ts | import { expect } from 'chai';
import 'mocha';
import {Vector2D} from '../../gun-tree-ts/vector';
import {Bullet} from '../../gun-tree-ts/bullet';
import {Effect} from '../../gun-tree-ts/effect';
import {Gun, AimingDirectionType, UnusableDirectionTypeError, MustContainSubGunsError}
from '../../gun-tree-ts/gun-base... | const property = new FiringProperty(player);
const angleOffset = 2;
const speedOffset = 3;
const gun = new CombinedModifier(
new AddAngle(angleOffset),
new AddSpeed(speedOffset)
);
gun.modifyProperty(property);
expect(property.getAngle()).... | describe('CombinedModifier_gun_unit_test', () => {
it('modify_property', () => {
const player = new DebuggerGunTreePlayer(); | random_line_split |
contactus.js | $(document).on('click', '.contact-click', function () {
var name = $("input#name-contact").val();
var surname = $("input#surname-contact").val();
var email = $("input#email-contact").val();
var message = $("textarea#message-contact").val();
var phone = $("input#phone-contact").val();
var htmlB... | };
if(name && surname && email && message && phone && htmlBody){
$.ajax({
type: "POST",
url: "controllers/contactus.php",
data: {
Contact: jsonFile
},
dataType: "json"
}).done(function (data) {
if (data.response == 'ok') {
$('#conta... | 'surname': surname,
'mail': email,
'message': htmlBody,
'phone': phone | random_line_split |
contactus.js | $(document).on('click', '.contact-click', function () {
var name = $("input#name-contact").val();
var surname = $("input#surname-contact").val();
var email = $("input#email-contact").val();
var message = $("textarea#message-contact").val();
var phone = $("input#phone-contact").val();
var htmlB... | else{
alert("Uppss! Ha habido un error durante el envío: Por favor intentelo de nuevo más tarde");
document.location = "contactus";
}
});
}
else{
alert('Todos los campos del formulario son obligatorios, rellenelos para continuar');
}
}); | $('#contactModal').modal('show');
$('#contactModal').on('hidden.bs.modal', function () {
document.location = "home";
});
}
| conditional_block |
forms.py | # -*- coding: utf-8 -*-
import django
import sys
from itertools import chain
from django import forms
from django.conf import settings
from django.db.models.query import QuerySet
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.html import conditional_es... |
else:
unselected.append(item)
# re-order `selected` array according str_values which is a set of `option_value`s in the order they should be shown on screen
ordered = []
for value in str_values:
for select in selected:
if value == select[... | selected.append(item) | conditional_block |
forms.py | # -*- coding: utf-8 -*-
import django
import sys
from itertools import chain
from django import forms
from django.conf import settings
from django.db.models.query import QuerySet
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.html import conditional_es... | return data_set != initial_set | initial_set = [force_text(value) for value in self.prepare_value(initial)]
data_set = [force_text(value) for value in data] | random_line_split |
forms.py | # -*- coding: utf-8 -*-
import django
import sys
from itertools import chain
from django import forms
from django.conf import settings
from django.db.models.query import QuerySet
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.html import conditional_es... |
class SortedMultipleChoiceField(forms.ModelMultipleChoiceField):
widget = SortedCheckboxSelectMultiple
def clean(self, value):
queryset = super(SortedMultipleChoiceField, self).clean(value)
if value is None or not isinstance(queryset, QuerySet):
return queryset
object_lis... | class Media:
js = (
STATIC_URL + 'sortedm2m/widget.js',
STATIC_URL + 'sortedm2m/jquery-ui.js',
)
css = {'screen': (
STATIC_URL + 'sortedm2m/widget.css',
)}
def build_attrs(self, attrs=None, **kwargs):
attrs = super(SortedCheckboxSelectMult... | identifier_body |
forms.py | # -*- coding: utf-8 -*-
import django
import sys
from itertools import chain
from django import forms
from django.conf import settings
from django.db.models.query import QuerySet
from django.template.loader import render_to_string
from django.utils.encoding import force_text
from django.utils.html import conditional_es... | (self, value):
queryset = super(SortedMultipleChoiceField, self).clean(value)
if value is None or not isinstance(queryset, QuerySet):
return queryset
object_list = dict((
(str_(key), value)
for key, value in iteritems(queryset.in_bulk(value))))
return ... | clean | identifier_name |
mod.rs | // Copyright 2012-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-MI... | #[cfg(windows)] pub use sys::ext as windows;
#[cfg(target_os = "android")] pub mod android;
#[cfg(target_os = "bitrig")] pub mod bitrig;
#[cfg(target_os = "dragonfly")] pub mod dragonfly;
#[cfg(target_os = "freebsd")] pub mod freebsd;
#[cfg(target_os = "ios")] pub mod ios;
#[cfg(target_os = "linux")] ... | #![allow(missing_docs, bad_style)]
#[cfg(unix)] pub use sys::ext as unix; | random_line_split |
utils.js | exports.pathResolver = function pathResolver(base, path) {
base = base.slice();
path = path.slice();
while (base.length && path[0] === '..') {
path.shift();
base.pop();
}
return base.concat(path);
};
exports.pathSpliter = function pathSpliter(path) {
var splitPath;
if (pa... | }
}
return '';
}
exports.findPath = findPath; | var argI = findPath(arg.arguments[i]);
if (argI.type === 'insert') {
return argI.argument;
}
} | random_line_split |
utils.js | exports.pathResolver = function pathResolver(base, path) {
base = base.slice();
path = path.slice();
while (base.length && path[0] === '..') {
path.shift();
base.pop();
}
return base.concat(path);
};
exports.pathSpliter = function pathSpliter(path) {
var splitPath;
if (pa... | (arg) {
if (arg) {
if (arg.type === 'insert') {
return arg.path;
} else if (
arg.type === 'operator' ||
arg.type === 'transform'
) {
for (var i = 0; i < arg.arguments.length; i++) {
var argI = findPath(arg.arguments[i]);
... | findPath | identifier_name |
utils.js | exports.pathResolver = function pathResolver(base, path) {
base = base.slice();
path = path.slice();
while (base.length && path[0] === '..') {
path.shift();
base.pop();
}
return base.concat(path);
};
exports.pathSpliter = function pathSpliter(path) {
var splitPath;
if (pa... |
exports.findPath = findPath;
| {
if (arg) {
if (arg.type === 'insert') {
return arg.path;
} else if (
arg.type === 'operator' ||
arg.type === 'transform'
) {
for (var i = 0; i < arg.arguments.length; i++) {
var argI = findPath(arg.arguments[i]);
... | identifier_body |
utils.js | exports.pathResolver = function pathResolver(base, path) {
base = base.slice();
path = path.slice();
while (base.length && path[0] === '..') {
path.shift();
base.pop();
}
return base.concat(path);
};
exports.pathSpliter = function pathSpliter(path) {
var splitPath;
if (pa... | else {
splitPath = path.split('.');
}
if (!splitPath[0] && !splitPath[1]) {
splitPath = ['.'];
}
var barsProp = splitPath.pop()
.split('@');
if (barsProp[0]) {
splitPath.push(barsProp[0]);
}
if (barsProp[1]) {
... | {
splitPath = path.split('/');
} | conditional_block |
utils.ts | import {EventEmitter} from 'events';
import * as _isPlainObject from 'lodash.isplainobject';
export function drop(item: any, arr: Array<any>): void {
const index = arr.indexOf(item);
if (index > -1) {
arr.splice(index, 1);
}
}
export function readyErrorHandling(emitter: EventEmitter): void {
if (!(emitter... | result = value;
}
return result;
}
export function isObject(value: any): value is Object {
return _isPlainObject(value);
} | result = [value];
} else { | random_line_split |
utils.ts |
import {EventEmitter} from 'events';
import * as _isPlainObject from 'lodash.isplainobject';
export function drop(item: any, arr: Array<any>): void |
export function readyErrorHandling(emitter: EventEmitter): void {
if (!(emitter instanceof EventEmitter)) throw new TypeError(`invalid parameter. [emitter: EventEmitter]: ${typeof emitter}`);
const eventName = 'error';
if (emitter.listenerCount(eventName) == 0) {
emitter.once(eventName, () => {});
}
}
ex... | {
const index = arr.indexOf(item);
if (index > -1) {
arr.splice(index, 1);
}
} | identifier_body |
utils.ts |
import {EventEmitter} from 'events';
import * as _isPlainObject from 'lodash.isplainobject';
export function drop(item: any, arr: Array<any>): void {
const index = arr.indexOf(item);
if (index > -1) {
arr.splice(index, 1);
}
}
export function readyErrorHandling(emitter: EventEmitter): void {
if (!(emitte... | (value: any): value is Object {
return _isPlainObject(value);
}
| isObject | identifier_name |
utils.ts |
import {EventEmitter} from 'events';
import * as _isPlainObject from 'lodash.isplainobject';
export function drop(item: any, arr: Array<any>): void {
const index = arr.indexOf(item);
if (index > -1) {
arr.splice(index, 1);
}
}
export function readyErrorHandling(emitter: EventEmitter): void {
if (!(emitte... |
}
export function normalizeArray<T>(value: T|Array<T>): Array<T> {
let result: Array<T>;
if (value == undefined) {
result = [];
} else if (!(value instanceof Array)) {
result = [value];
} else {
result = value;
}
return result;
}
export function isObject(value: any): value is Object {
retur... | {
emitter.once(eventName, () => {});
} | conditional_block |
power-cycle-droplet.mock.ts | export const request = {
"headers": {
"Content-Type": "application/json",
},
"body": {
"type": "power_cycle",
},
};
export const response = {
"body": {
"action": {
"id": 72531856,
"status": "completed",
"type": "power_cycle",
"started_at": "2015-11-12T17:51:03Z"... | "s-16vcpu-64gb",
"s-20vcpu-96gb",
"s-24vcpu-128gb",
"s-32vcpu-192gb"
],
"features": [
"private_networking",
"backups",
"ipv6",
"metadata"
],
"available": true
},
"regio... | "s-2vcpu-4gb",
"s-4vcpu-8gb",
"s-6vcpu-16gb",
"s-8vcpu-32gb",
"s-12vcpu-48gb", | random_line_split |
__init__.py | """Hierarchical Networks Package.
This package makes it possible to construct graph-like Node structures,
especially hierarchical networks.
The most important building block is the new Layer node, which works as an
horizontal version of flow. It encapsulates a list of Nodes, which are trained
and executed in parallel... | 'switchboard_factory',
'utils',
'fixup_namespace'
)) | 'layer',
'switchboard',
'hinet_Visitor', | random_line_split |
tests.py | from django.contrib.gis.db.models.functions import (
Area, Distance, Length, Perimeter, Transform,
)
from django.contrib.gis.geos import GEOSGeometry, LineString, Point
from django.contrib.gis.measure import D # alias for Distance
from django.db import connection
from django.db.models import F, Q
from django.test ... | # Reference queries:
# SELECT ST_Area(poly) FROM distapp_southtexaszipcode;
area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461]
# Tolerance has to be lower for Oracle
tol = 2
for i, z in enumerate(SouthTexasZipcode.objects.annotate(area=Ar... | fixtures = ['initial']
@skipUnlessDBFeature("has_Area_function")
def test_area(self): | random_line_split |
tests.py | from django.contrib.gis.db.models.functions import (
Area, Distance, Length, Perimeter, Transform,
)
from django.contrib.gis.geos import GEOSGeometry, LineString, Point
from django.contrib.gis.measure import D # alias for Distance
from django.db import connection
from django.db.models import F, Q
from django.test ... |
for qs in querysets:
cities = self.get_names(qs)
self.assertEqual(cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])
@skipUnlessDBFeature("supports_distances_lookups")
def test_distance_lookups_with_expression_rhs(self):
qs = SouthTexasCity.objects.filter(
... | gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid'))
gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid'))
qs2 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq3 | gq4)
querysets.append(qs2) | conditional_block |
tests.py | from django.contrib.gis.db.models.functions import (
Area, Distance, Length, Perimeter, Transform,
)
from django.contrib.gis.geos import GEOSGeometry, LineString, Point
from django.contrib.gis.measure import D # alias for Distance
from django.db import connection
from django.db.models import F, Q
from django.test ... | (self):
qs = SouthTexasCity.objects.filter(
point__distance_lte=(self.stx_pnt, F('radius')),
).order_by('name')
self.assertEqual(
self.get_names(qs),
['Bellaire', 'Downtown Houston', 'Southside Place', 'West University Place']
)
# With a combi... | test_distance_lookups_with_expression_rhs | identifier_name |
tests.py | from django.contrib.gis.db.models.functions import (
Area, Distance, Length, Perimeter, Transform,
)
from django.contrib.gis.geos import GEOSGeometry, LineString, Point
from django.contrib.gis.measure import D # alias for Distance
from django.db import connection
from django.db.models import F, Q
from django.test ... |
@skipUnlessDBFeature("has_Perimeter_function")
def test_perimeter(self):
"""
Test the `Perimeter` function.
"""
# Reference query:
# SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
perim_m = [18404.3550889361, 15627.2108551001... | """
Test the `Length` function.
"""
# Reference query (should use `length_spheroid`).
# SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]]');
len_m1 = 473504.769553813
len_m2 = 4617.668
... | identifier_body |
postcss.js | 'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
var _processor = require('./processor');
var _processor2 = _interopRequi... |
return new _processor2['default'](plugins);
};
postcss.plugin = function (name, initializer) {
var creator = function creator() {
var transformer = initializer.apply(undefined, arguments);
transformer.postcssPlugin = name;
transformer.postcssVersion = new _processor2['default']().versi... | {
plugins = plugins[0];
} | conditional_block |
postcss.js | 'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
| var _stringify = require('./stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _comment = require('./comment');
var _comment2 = _interopRequireDefault(_comment);
var _atRule = require('./at-rule');
var _atRule2 = _interopRequireDefault(_atRule);
var _vendor = require('./vendor');
var _vendor2... | var _processor = require('./processor');
var _processor2 = _interopRequireDefault(_processor);
| random_line_split |
postcss.js | 'use strict';
exports.__esModule = true;
function | (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
var _processor = require('./processor');
var _processor2 = _interopRequireDefault(_processor);
var _stringify = require('./stringify');
var _str... | _interopRequireDefault | identifier_name |
postcss.js | 'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) |
var _declaration = require('./declaration');
var _declaration2 = _interopRequireDefault(_declaration);
var _processor = require('./processor');
var _processor2 = _interopRequireDefault(_processor);
var _stringify = require('./stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _comment = requ... | { return obj && obj.__esModule ? obj : { 'default': obj }; } | identifier_body |
persistent_list.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/. */
//! A persistent, thread-safe singly-linked list.
use std::mem;
use std::sync::Arc;
pub struct PersistentList<T>... | (&self) -> PersistentList<T> {
// This establishes the persistent nature of this list: we can clone a list by just cloning
// its head.
PersistentList {
head: self.head.clone(),
length: self.length,
}
}
}
pub struct PersistentListIterator<'a,T> where T: 'a + ... | clone | identifier_name |
persistent_list.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/. */
//! A persistent, thread-safe singly-linked list. |
use std::mem;
use std::sync::Arc;
pub struct PersistentList<T> {
head: PersistentListLink<T>,
length: usize,
}
struct PersistentListEntry<T> {
value: T,
next: PersistentListLink<T>,
}
type PersistentListLink<T> = Option<Arc<PersistentListEntry<T>>>;
impl<T> PersistentList<T> where T: Send + Sync {
... | random_line_split | |
map.rs | #![allow(dead_code)]
#[derive(Debug)] enum | { Apple, Carrot, Potato }
#[derive(Debug)] struct Peeled(Food);
#[derive(Debug)] struct Chopped(Food);
#[derive(Debug)] struct Cooked(Food);
// 削水果皮。如果没有水果,就返回 `None`。
// 否则返回削好皮的水果。
fn peel(food: Option<Food>) -> Option<Peeled> {
match food {
Some(food) => Some(Peeled(food)),
None => None,... | Food | identifier_name |
map.rs | #![allow(dead_code)]
#[derive(Debug)] enum Food { Apple, Carrot, Potato }
#[derive(Debug)] struct Peeled(Food);
#[derive(Debug)] struct Chopped(Food);
#[derive(Debug)] struct Cooked(Food);
// 削水果皮。如果没有水果,就返回 `None`。
// 否则返回削好皮的水果。
fn peel(food: Option<Food>) -> Option<Peeled> {
match food {
Some(food) =>... | Some(Peeled(food)) => Some(Chopped(food)),
None => None,
}
}
// 和前面的检查类似,但是使用 `map()` 来替代 `match`。
fn cook(chopped: Option<Chopped>) -> Option<Cooked> {
chopped.map(|Chopped(food)| Cooked(food))
}
// 另外一种实现,我们可以链式调用 `map()` 来简化上述的流程。
fn process(food: Option<Food>) -> Option<Cooke... | // 和上面一样,我们要在切水果之前确认水果是否已经削皮。
fn chop(peeled: Option<Peeled>) -> Option<Chopped> {
match peeled { | random_line_split |
exceptions.py | """Custom Exception Classes for Phylotyper Module
"""
class PhylotyperError(Exception):
"""Basic exception for errors raised by Phylotyper modules"""
def __init__(self, subtype, msg=None):
if msg is None:
|
super(PhylotyperError, self).__init__(msg)
self.subtype = subtype
class ValuesError(PhylotyperError):
"""Unknown subtype"""
def __init__(self, subtype, msg=None):
super(PhylotyperError, self).__init__(
subtype, msg="Unrecognized subtype {}".format(subtype))
class Datab... | msg = "An error occured for subtype {}".format(subtype) | conditional_block |
exceptions.py | """Custom Exception Classes for Phylotyper Module
"""
class PhylotyperError(Exception):
"""Basic exception for errors raised by Phylotyper modules"""
def __init__(self, subtype, msg=None):
if msg is None: | msg = "An error occured for subtype {}".format(subtype)
super(PhylotyperError, self).__init__(msg)
self.subtype = subtype
class ValuesError(PhylotyperError):
"""Unknown subtype"""
def __init__(self, subtype, msg=None):
super(PhylotyperError, self).__init__(
subt... | random_line_split | |
exceptions.py | """Custom Exception Classes for Phylotyper Module
"""
class PhylotyperError(Exception):
"""Basic exception for errors raised by Phylotyper modules"""
def __init__(self, subtype, msg=None):
if msg is None:
msg = "An error occured for subtype {}".format(subtype)
super(PhylotyperError... | (PhylotyperError):
"""Unknown subtype"""
def __init__(self, subtype, msg=None):
super(PhylotyperError, self).__init__(
subtype, msg="Unrecognized subtype {}".format(subtype))
class DatabaseError(PhylotyperError):
"""Missing data in Database"""
def __init__(self, subtype, data, ms... | ValuesError | identifier_name |
exceptions.py | """Custom Exception Classes for Phylotyper Module
"""
class PhylotyperError(Exception):
"""Basic exception for errors raised by Phylotyper modules"""
def __init__(self, subtype, msg=None):
if msg is None:
msg = "An error occured for subtype {}".format(subtype)
super(PhylotyperError... |
class DatabaseError(PhylotyperError):
"""Missing data in Database"""
def __init__(self, subtype, data, msg=None):
m = "Database is missing data {} for {}".format(data, subtype)
super(PhylotyperError, self).__init__(subtype, m)
self.data = data | super(PhylotyperError, self).__init__(
subtype, msg="Unrecognized subtype {}".format(subtype)) | identifier_body |
py_group.py | # coding=UTF-8
import mysql.connector
import xlrd
import xlsxwriter
import os
from mysql.connector import errorcode
from datetime import datetime
# 符号化后的 Excel 文件名
EXCEL_NAME = '20170223_4.0.1_feedback_result_py'
DB_NAME = 'zl_crash'
config = {
'user': 'root',
'password': '123456',
'host': '127.0.0.1',
... | exception_symbols, os_version)
# insert report data
cursor.execute(insert_report, data_report)
conn.commit()
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
... | ice_id, | conditional_block |
py_group.py | # coding=UTF-8
import mysql.connector
import xlrd
import xlsxwriter
import os
from mysql.connector import errorcode
from datetime import datetime
# 符号化后的 Excel 文件名
EXCEL_NAME = '20170223_4.0.1_feedback_result_py'
DB_NAME = 'zl_crash'
config = {
'user': 'root',
'password': '123456',
'host': '127.0.0.1',
... | else:
print(err.msg)
finally:
cursor.close()
conn.close()
def insert_symbolication_result_into_db(table_name):
'''
Insert the symbolicated result into database
:param table_name: table_name in database
'''
try:
conn = mysql.connector.connect(**confi... | elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist") | random_line_split |
py_group.py | # coding=UTF-8
import mysql.connector
import xlrd
import xlsxwriter
import os
from mysql.connector import errorcode
from datetime import datetime
# 符号化后的 Excel 文件名
EXCEL_NAME = '20170223_4.0.1_feedback_result_py'
DB_NAME = 'zl_crash'
config = {
'user': 'root',
'password': '123456',
'host': '127.0.0.1',
... | begin_time = datetime.now()
# 表名
table_name = 'report_' + begin_time.strftime("%Y_%m_%d_%H_%M_%S")
# 建表
create_table_in_db(table_name)
# 插入数据
insert_symbolication_result_into_db(table_name)
# 对数据进行分组并导出
generate_grouped_exception(table_name)
end_time = datetime.now()
pri... | lass used to encapsulate the row data in EXCEL
'''
def __init__(self, report_id, exception_type, device_id, exception_symbols, os_version):
self.report_id = report_id;
self.exception_type = exception_type;
self.device_id = device_id;
self.exception_symbols = exception_symbols;
... | identifier_body |
py_group.py | # coding=UTF-8
import mysql.connector
import xlrd
import xlsxwriter
import os
from mysql.connector import errorcode
from datetime import datetime
# 符号化后的 Excel 文件名
EXCEL_NAME = '20170223_4.0.1_feedback_result_py'
DB_NAME = 'zl_crash'
config = {
'user': 'root',
'password': '123456',
'host': '127.0.0.1',
... | d named as `table_name`
:param table_name: table_name
'''
SQLS = {}
SQLS['drop_report'] = (
"DROP TABLE IF EXISTS `" + table_name + "`")
SQLS['report'] = (
"CREATE TABLE `" + table_name + "` ( "
"`report_id` int(11) NOT NULL AUTO_INCREMENT, "
"`exception_type` varch... | le in database, an | identifier_name |
drawing.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | x: gen.gen_range(20.0, 500.0),
y: gen.gen_range(20.0, 500.0),
color: RGBA::new(
gen.gen_range(0.0, 1.0),
gen.gen_range(0.0, 1.0),
gen.gen_range(0.0, 1.0),
1.0,
),
vx: gen.gen_range(1.0, 5.0),
... | let mut gen = rand::thread_rng();
Circle { | random_line_split |
drawing.rs | /*
* Copyright (c) 2018 Boucher, Antoni <bouanto@zoho.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy,... | () {
Win::run(()).unwrap();
}
| main | identifier_name |
finally.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 mut i = 0;
(|| {
i = 10;
fail!();
}).finally(|| {
assert!(failing());
assert_eq!(i, 10);
})
}
#[test]
fn test_retval() {
let closure: || -> int = || 10;
let i = closure.finally(|| { });
assert_eq!(i, 10);
}
#[test]
fn test_compact() {
fn do_some... | test_fail | identifier_name |
finally.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 ... |
}
#[test]
fn test_success() {
let mut i = 0;
(|| {
i = 10;
}).finally(|| {
assert!(!failing());
assert_eq!(i, 10);
i = 20;
});
assert_eq!(i, 20);
}
#[test]
#[should_fail]
fn test_fail() {
let mut i = 0;
(|| {
i = 10;
fail!();
}).finally(... | {
(self.dtor)();
} | identifier_body |
finally.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<'a,T> Finally<T> for 'a || -> T {
fn finally(&self, dtor: ||) -> T {
let _d = Finallyalizer {
dtor: dtor
};
(*self)()
}
}
finally_fn!(extern "Rust" fn() -> T)
struct Finallyalizer<'a> {
dtor: 'a ||
}
#[unsafe_destructor]
impl<'a> Drop for Finallyalizer<'a> {
... | }
}
} | random_line_split |
service.py | # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | returned_value = func(project, text)
cache.set(key, returned_value, timeout=None)
return returned_value
return _decorator
def _get_markdown(project):
extensions = _make_extensions_list(project=project)
md = Markdown(extensions=extensions)
md.extracted_data = {"mentions": [], "... | turn cached
| conditional_block |
service.py | # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | bleach._serialize = _serialize
# END PATCH
from django.core.cache import cache
from django.utils.encoding import force_bytes
from markdown import Markdown
from .extensions.autolink import AutolinkExtension
from .extensions.automail import AutomailExtension
from .extensions.semi_sane_lists import SemiSaneListExtensio... | lker = html5lib.treewalkers.getTreeWalker('etree')
stream = walker(domtree)
serializer = HTMLSerializer(quote_attr_values=True,
omit_optional_tags=False,
alphabetical_attributes=True)
return serializer.render(stream)
| identifier_body |
service.py | # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | roject, text):
sha1_hash = hashlib.sha1(force_bytes(text)).hexdigest()
key = "{}-{}".format(sha1_hash, project.id)
# Try to get it from the cache
cached = cache.get(key)
if cached is not None:
return cached
returned_value = func(project, text)
cache.... | ecorator(p | identifier_name |
service.py | # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the F... | from .extensions.spaced_link import SpacedLinkExtension
from .extensions.strikethrough import StrikethroughExtension
from .extensions.wikilinks import WikiLinkExtension
from .extensions.emojify import EmojifyExtension
from .extensions.mentions import MentionsExtension
from .extensions.references import TaigaReferencesE... | from .extensions.semi_sane_lists import SemiSaneListExtension | random_line_split |
view_environment.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals
"""
Script to visualize the model coordination environments
"""
__author__ = "David Waroquiers"
__copyright__ = "Copyright 2012, The Materials Project"
__vers... | if algo.minimum_number_of_points == 2:
pts.append(cg_central_site)
centre = cg_central_site
else:
centre = np.sum(pts, axis=0) / len(pts)
factor = 1.5
target_dist = max([np.dot(pp-centre, pp-centre) for pp in cg_points])
... | pts = [cg_points[ii] for ii in algo.plane_points] | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.