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 |
|---|---|---|---|---|
p051.rs | //! [Problem 51](https://projecteuler.net/problem=51) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
extern crate prime;
use integer::Integer;
use prime::PrimeSet;
... | }
}
}
unreachable!()
}
fn solve() -> String {
compute(8).to_string()
}
problem!("121313", solve);
#[cfg(test)]
mod tests {
#[test] fn seven() { assert_eq!(56003, super::compute(7)) }
} | }
if num_prime >= num_value {
return p | random_line_split |
p051.rs | //! [Problem 51](https://projecteuler.net/problem=51) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
extern crate integer;
extern crate prime;
use integer::Integer;
use prime::PrimeSet;
... |
}
if num_prime >= num_value {
return p
}
}
}
unreachable!()
}
fn solve() -> String {
compute(8).to_string()
}
problem!("121313", solve);
#[cfg(test)]
mod tests {
#[test] fn seven() { assert_eq!(56003, super::compute(7)) }
}
| {
num_prime += 1;
} | conditional_block |
font.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/. */
/// Implementation of Quartz (CoreGraphics) fonts.
extern crate core_foundation;
extern crate core_graphics;
exte... | (&self, glyph: GlyphId) -> Option<FractionalPixel> {
let glyphs = [glyph as CGGlyph];
let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation,
&glyphs[0],
ptr::null_mut... | glyph_h_advance | identifier_name |
font.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/. */
/// Implementation of Quartz (CoreGraphics) fonts.
extern crate core_foundation;
extern crate core_graphics;
exte... |
fn stretchiness(&self) -> font_stretch::T {
let normalized = self.ctfont.all_traits().normalized_width(); // [-1.0, 1.0]
let normalized = (normalized + 1.0) / 2.0 * 9.0; // [0.0, 9.0]
match normalized {
v if v < 1.0 => font_stretch::T::ultra_condensed,
v if v < 2.0... | v if v < 8.0 => font_weight::T::Weight800,
_ => font_weight::T::Weight900,
}
} | random_line_split |
font.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/. */
/// Implementation of Quartz (CoreGraphics) fonts.
extern crate core_foundation;
extern crate core_graphics;
exte... |
}
#[derive(Debug)]
pub struct FontHandle {
pub font_data: Arc<FontTemplateData>,
pub ctfont: CTFont,
}
impl FontHandleMethods for FontHandle {
fn new_from_template(_fctx: &FontContextHandle,
template: Arc<FontTemplateData>,
pt_size: Option<Au>)
... | {
blk(self.data.bytes().as_ptr(), self.data.len() as usize);
} | identifier_body |
module.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Julien Veyssier
#
# This file is part of weboob.
#
# weboob 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 Free Software Foundation, either version 3 of the License, or
# (at your op... | recipe.comments = rec.comments
recipe.author = rec.author
recipe.nb_person = rec.nb_person
recipe.cooking_time = rec.cooking_time
recipe.preparation_time = rec.preparation_time
return recipe
OBJECTS = {
Recipe: fill_recipe,
} | recipe.ingredients = rec.ingredients | random_line_split |
module.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Julien Veyssier
#
# This file is part of weboob.
#
# weboob 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 Free Software Foundation, either version 3 of the License, or
# (at your op... | (self, recipe, fields):
if 'nb_person' in fields or 'instructions' in fields:
rec = self.get_recipe(recipe.id)
recipe.picture_url = rec.picture_url
recipe.instructions = rec.instructions
recipe.ingredients = rec.ingredients
recipe.comments = rec.commen... | fill_recipe | identifier_name |
module.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Julien Veyssier
#
# This file is part of weboob.
#
# weboob 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 Free Software Foundation, either version 3 of the License, or
# (at your op... |
return recipe
OBJECTS = {
Recipe: fill_recipe,
}
| rec = self.get_recipe(recipe.id)
recipe.picture_url = rec.picture_url
recipe.instructions = rec.instructions
recipe.ingredients = rec.ingredients
recipe.comments = rec.comments
recipe.author = rec.author
recipe.nb_person = rec.nb_person
... | conditional_block |
module.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Julien Veyssier
#
# This file is part of weboob.
#
# weboob 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 Free Software Foundation, either version 3 of the License, or
# (at your op... |
OBJECTS = {
Recipe: fill_recipe,
}
| if 'nb_person' in fields or 'instructions' in fields:
rec = self.get_recipe(recipe.id)
recipe.picture_url = rec.picture_url
recipe.instructions = rec.instructions
recipe.ingredients = rec.ingredients
recipe.comments = rec.comments
recipe.author = r... | identifier_body |
Alert.stories.tsx | import React from 'react';
import { Meta } from '@storybook/react';
import { createTemplate, createStory } from '../../stories/utils';
import { Alert, AlertProps } from '.';
import { Link } from '../../';
export default {
title: 'Core/Alert',
component: Alert,
} as Meta;
const Template = createTemplate<AlertProps>(... | }); | random_line_split | |
response.js | this.removeHeader('Content-Length');
this.removeHeader('Transfer-Encoding');
body = '';
}
// respond
this.end((head ? null : body), encoding);
return this;
};
/**
* Send JSON response.
*
* Examples:
*
* res.json(null);
* res.json({ user: 'tj' });
* res.json(500, 'oh noes!');
*... | }
// transfer
var file = send(req, path);
if (options.root) file.root(options.root);
file.maxage(options.maxAge || 0);
file.on('error', error);
file.on('directory', next);
file.on('stream', stream);
file.pipe(this);
this.on('finish', cleanup);
};
/**
* Transfer the file at the given `path` as an ... |
// cleanup
function cleanup() {
req.socket.removeListener('error', error); | random_line_split |
response.js |
// freshness
if (req.fresh) this.statusCode = 304;
// strip irrelevant headers
if (204 == this.statusCode || 304 == this.statusCode) {
this.removeHeader('Content-Type');
this.removeHeader('Content-Length');
this.removeHeader('Transfer-Encoding');
body = '';
}
// respond
this.end((head ... | {
encoding = 'utf8';
type = this.get('Content-Type');
// reflect this in content-type
if ('string' === typeof type) {
this.set('Content-Type', setCharset(type, 'utf-8'));
}
} | conditional_block | |
response.js | this.removeHeader('Content-Length');
this.removeHeader('Transfer-Encoding');
body = '';
}
// respond
this.end((head ? null : body), encoding);
return this;
};
/**
* Send JSON response.
*
* Examples:
*
* res.json(null);
* res.json({ user: 'tj' });
* res.json(500, 'oh noes!');
*... |
// transfer
var file = send(req, path);
if (options.root) file.root(options.root);
file.maxage(options.maxAge || 0);
file.on('error', error);
file.on('directory', next);
file.on('stream', stream);
file.pipe(this);
this.on('finish', cleanup);
};
/**
* Transfer the file at the given `path` as an att... | {
req.socket.removeListener('error', error);
} | identifier_body |
response.js | this.removeHeader('Content-Length');
this.removeHeader('Transfer-Encoding');
body = '';
}
// respond
this.end((head ? null : body), encoding);
return this;
};
/**
* Send JSON response.
*
* Examples:
*
* res.json(null);
* res.json({ user: 'tj' });
* res.json(500, 'oh noes!');
*... | (err) {
if (done) return;
done = true;
// clean up
cleanup();
if (!self.headersSent) self.removeHeader('Content-Disposition');
// callback available
if (fn) return fn(err);
// list in limbo if there's no callback
if (self.headersSent) return;
// delegate
next(err);
}
... | error | identifier_name |
write_installer_json.py | #!/usr/bin/env python
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Writes a .json file with the per-apk details for an incremental install."""
import argparse
import json
import os
import sys
sys.... | (args):
args = build_utils.ExpandFileArgs(args)
parser = argparse.ArgumentParser()
parser.add_argument('--output-path',
help='Output path for .json file.',
required=True)
parser.add_argument('--apk-path',
help='Path to .apk relative to output dir... | _ParseArgs | identifier_name |
write_installer_json.py | #!/usr/bin/env python
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Writes a .json file with the per-apk details for an incremental install."""
import argparse
import json
import os
import sys
sys.... |
if __name__ == '__main__':
main(sys.argv[1:])
| options = _ParseArgs(args)
data = {
'apk_path': options.apk_path,
'native_libs': options.native_libs,
'dex_files': options.dex_files,
'show_proguard_warning': options.show_proguard_warning,
'split_globs': options.split_globs,
}
with build_utils.AtomicOutput(options.output_path, mod... | identifier_body |
write_installer_json.py | #!/usr/bin/env python
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Writes a .json file with the per-apk details for an incremental install."""
import argparse
import json
import os
import sys
sys.... | data = {
'apk_path': options.apk_path,
'native_libs': options.native_libs,
'dex_files': options.dex_files,
'show_proguard_warning': options.show_proguard_warning,
'split_globs': options.split_globs,
}
with build_utils.AtomicOutput(options.output_path, mode='w+') as f:
json.dump(... | options = _ParseArgs(args)
| random_line_split |
write_installer_json.py | #!/usr/bin/env python
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Writes a .json file with the per-apk details for an incremental install."""
import argparse
import json
import os
import sys
sys.... | main(sys.argv[1:]) | conditional_block | |
test_settings.py | import os
import django
TEST_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'tests')
COMPRESS_CACHE_BACKEND = 'locmem://'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'compressor',
'coffin',
'jingo',... |
SECRET_KEY = "iufoj=mibkpdz*%bob952x(%49rqgv8gg45k36kjcg76&-y5=!"
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',
)
| TEST_RUNNER = 'discover_runner.DiscoverRunner' | conditional_block |
test_settings.py | import os
import django | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'compressor',
'coffin',
'jingo',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(TEST_DIR, 'static')
TEMPLATE_DIRS = (
# Specifically choose a name that will no... |
TEST_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'tests')
COMPRESS_CACHE_BACKEND = 'locmem://'
| random_line_split |
htmlbrelement.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/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::root::DomRoot;
use dom::document::D... | impl HTMLBRElement {
fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLBRElement {
HTMLBRElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalNam... | }
| random_line_split |
htmlbrelement.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/. */
use dom::bindings::codegen::Bindings::HTMLBRElementBinding;
use dom::bindings::root::DomRoot;
use dom::document::D... | (local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> DomRoot<HTMLBRElement> {
Node::reflect_node(Box::new(HTMLBRElement::new_inherited(local_name, prefix, document)),
document,
HTMLBRElementBinding::Wrap)
... | new | identifier_name |
playlists.js | /**
* Copyright 2013 Ionică Bizău
*
* A Node.JS module, which provides an object oriented wrapper for the Youtube v3 API.
* Author: Ionică Bizău <bizauionica@gmail.com>
*
**/
var Util = require("../../util");
function list (options, callback) {
var self = this;
var url = Util.createUrl.apply(self, [... | tions, callback) {
callback(null, {"error": "Not yet implemented"});
}
function update (options, callback) {
callback(null, {"error": "Not yet implemented"});
}
function deleteItem (options, callback) {
callback(null, {"error": "Not yet implemented"});
}
module.exports = {
list: list,
insert: ins... | rt (op | identifier_name |
playlists.js | /**
* Copyright 2013 Ionică Bizău
*
* A Node.JS module, which provides an object oriented wrapper for the Youtube v3 API.
* Author: Ionică Bizău <bizauionica@gmail.com>
*
**/
var Util = require("../../util");
function list (options, callback) {
var self = this;
var url = Util.createUrl.apply(self, [... | nction deleteItem (options, callback) {
callback(null, {"error": "Not yet implemented"});
}
module.exports = {
list: list,
insert: insert,
update: update,
delete: deleteItem
};
| callback(null, {"error": "Not yet implemented"});
}
fu | identifier_body |
playlists.js | /**
* Copyright 2013 Ionică Bizău
*
* A Node.JS module, which provides an object oriented wrapper for the Youtube v3 API.
* Author: Ionică Bizău <bizauionica@gmail.com>
*
**/
var Util = require("../../util");
function list (options, callback) {
var self = this;
var url = Util.createUrl.apply(self, [... | }; | random_line_split | |
soundscape.py | :param image_to_sound_conversion_time:
:type image_to_sound_conversion_time: float
:param is_exponential:
:type is_exponential: bool
:param hifi:
:type hifi: bool
:param stereo:
:type stereo: bool
:param delay:
:type delay: bool
:param rel... |
def rnd():
global IR, IA, IC, IM
IR = (IR * IA + IC) % IM
return IR / (1.0 * IM)
def main():
current_frame = 0
b = 0
num_frames = 2 * int(0.5 * sample_frequency * image_to_sound_conversion_time)
frames_per_column = int(num_frames / num_columns)
sso = 0 if hifi else 128
ssm = 327... | i0 = l % 65536
i1 = (l - i0) / 65536
wi(fp, i0)
wi(fp, i1) | identifier_body |
soundscape.py | :param image_to_sound_conversion_time:
:type image_to_sound_conversion_time: float
:param is_exponential:
:type is_exponential: bool
:param hifi:
:type hifi: bool
:param stereo:
:type stereo: bool
:param delay:
:type delay: bool
:param rel... | ():
current_frame = 0
b = 0
num_frames = 2 * int(0.5 * sample_frequency * image_to_sound_conversion_time)
frames_per_column = int(num_frames / num_columns)
sso = 0 if hifi else 128
ssm = 32768 if hifi else 128
scale = 0.5 / math.sqrt(num_rows)
dt = 1.0 / sample_frequency
v = 340.0 #... | main | identifier_name |
soundscape.py | :param image_to_sound_conversion_time:
:type image_to_sound_conversion_time: float
:param is_exponential:
:type is_exponential: bool
:param hifi:
:type hifi: bool
:param stereo:
:type stereo: bool
:param delay:
:type delay: bool
:param rel... |
tmp = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
if frame.shape[1] != num_rows or frame.shape[0] != num_columns:
# cv.resize(tmp, gray, Size(num_columns,num_rows))
gray = cv.resize(tmp, (num_columns, num_rows), interpolation=cv.INTER_AREA)
else:
gray = tmp
... | continue | random_line_split |
soundscape.py | :param image_to_sound_conversion_time:
:type image_to_sound_conversion_time: float
:param is_exponential:
:type is_exponential: bool
:param hifi:
:type hifi: bool
:param stereo:
:type stereo: bool
:param delay:
:type delay: bool
:param rel... |
# def playSound(file):
# if sys.platform == "win32":
# winsound.PlaySound(file, winsound.SND_FILENAME) # Windows only
# # os.system('start %s' %file) # Windows only
# elif sys.platform.startswith('linux'):
# print("No audio player called for Linux")
# else:
# ... | def playsound(frequency, duration):
winsound.Beep(frequency, duration) | conditional_block |
models.py | #!/usr/bin/env python
# Copyright (C) 2017 DearBytes B.V. - All Rights Reserved
import os
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import create_engine
from ... | (cls):
"""
Get all keys in the current row as a list
:return: List containing all keys that the current model does
:rtype: list
"""
return cls.__mapper__.columns.keys()
def delete(self):
"""
Delete the current row
:return:
"""
... | keys | identifier_name |
models.py | #!/usr/bin/env python
# Copyright (C) 2017 DearBytes B.V. - All Rights Reserved
import os
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import create_engine
from ... | Get a related checksum by certain criteria
:param checksum: Checksum of the file
:param path: Path to the file
:type checksum: str
:type path: str
:return: Returns a checksum if one is found, otherwise None
"""
for row in self.checksums:
if row... | return server
def get_related_checksum(self, path, checksum):
""" | random_line_split |
models.py | #!/usr/bin/env python
# Copyright (C) 2017 DearBytes B.V. - All Rights Reserved
import os
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import create_engine
from ... |
def create_database():
""""
Create a new database or overwrite the existing one
:return: None
"""
Base.metadata.create_all(engine)
def database_exists():
"""
Check if the database exists
:return: True if the database exists
:rtype: bool
"""
return os.path.exists(DATABASE... | """
Create a new event and store it in the database
:param event: What type of event was it (constant)
:param description: Description of the event
:param checksum: What checksum was it related to
:type event: int
:type description: str
:type checksum: models.Chec... | identifier_body |
models.py | #!/usr/bin/env python
# Copyright (C) 2017 DearBytes B.V. - All Rights Reserved
import os
from datetime import datetime
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import create_engine
from ... |
@classmethod
def as_list(cls):
"""
Get all results as a list
:return: List
"""
return list(cls)
@classmethod
def query(cls):
"""
Get a new reference to query
:return:
"""
return session.query(cls)
class Server(Model, Ba... | if attr in values:
yield [attr, values[attr]] | conditional_block |
train_model.py | ):
return max(enumerate(array), key=operator.itemgetter(1))[0]
class ConvolutionalNeuralNetwork:
def __init__(self, layers, dataset):
self.layers = layers
self.dataset = dataset
layers.append(ReadoutLayer())
def build_graph(self):
input_shape = self.dataset.get_input_shape()
output_size = self.dataset.... | def build_prediction_node(self, input_tensor, session):
return self._build_node(input_tensor,
tf.constant(session.run(self._weights)),
tf.constant(session.run(self._biases)))
def _flattened_size(self, input_tensor):
return reduce(lambda a, b: a*b, input_tensor.shape[1:]).value
def _build_node(s... | self._biases = self.bias_variables([self.neurons])
return self._build_node(input_tensor, self._weights, self._biases)
| random_line_split |
train_model.py | _training_node(tensor)
self.y = tensor
self.cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=self.y_truth, logits=self.y)
self.loss = tf.reduce_mean(self.cross_entropy)
# TODO adapt learning rate each step to improve learning speed
self.learning_rate = tf.placeholder(tf.float32, name='learnin... | def __init__(self):
self.categories = []
self.categories_display = {}
with open(relative_path('data/katakana/categories.csv')) as file:
reader = csv.reader(file)
reader.next()
for category, display in reader:
self.categories_display[int(category)] = display
self.categories.append(int(category))
... | identifier_body | |
train_model.py | 1]
readout.output_size = output_size
self.x = tf.placeholder(tf.float32, [None] + input_shape, 'x')
self.y_truth = tf.placeholder(tf.float32, [None, output_size], 'y_truth')
tensor = self.x
for layer in self.layers:
tensor = layer.build_training_node(tensor)
self.y = tensor
self.cross_entropy = tf... | self.categories_display[int(category)] = display
self.categories.append(int(category)) | conditional_block | |
train_model.py | _default():
input_shape = self.dataset.get_input_shape()
output_size = self.dataset.get_output_size()
readout = self.layers[-1]
readout.output_size = output_size
input_placeholder = tf.placeholder(tf.float32, [None] + input_shape, 'input')
tensor = input_placeholder
for layer in self.layers:
... | classify | identifier_name | |
multi_polygons.ts | ScreenArray[][][]
}
export interface MultiPolygonsView extends MultiPolygonsData {}
export class MultiPolygonsView extends GlyphView {
override model: MultiPolygons
override visuals: MultiPolygons.Visuals
protected _hole_index: SpatialIndex
protected override _project_data(): void {
// TODO
}
prot... | else {
// We have discontinuous objects, so we need to find which
// one we're in, we can use point_in_poly again
const sxs = this.sxs[i]
const sys = this.sys[i]
for (let j = 0, end = sxs.length; j < end; j++) {
if (hittest.point_in_poly(sx, sy, sxs[j][0], sys[j][0])) {
... | {
// We don't have discontinuous objects so we're ok
const scx = this._get_snap_coord(this.sxs[i][0][0])
const scy = this._get_snap_coord(this.sys[i][0][0])
return [scx, scy]
} | conditional_block |
multi_polygons.ts | ScreenArray[][][]
}
export interface MultiPolygonsView extends MultiPolygonsData {}
export class MultiPolygonsView extends GlyphView {
override model: MultiPolygons
override visuals: MultiPolygons.Visuals
protected _hole_index: SpatialIndex
protected override _project_data(): void {
// TODO
}
prot... | }
this.visuals.fill.apply(ctx, i, "evenodd")
this.visuals.hatch.apply(ctx, i, "evenodd")
this.visuals.line.apply(ctx, i)
}
}
}
protected override _hit_rect(geometry: RectGeometry): Selection {
const {sx0, sx1, sy0, sy1} = geometry
const xs = [sx0, sx1, sx1, sx0]
... |
ctx.closePath()
} | random_line_split |
multi_polygons.ts | : ScreenArray[][][]
}
export interface MultiPolygonsView extends MultiPolygonsData {}
export class MultiPolygonsView extends GlyphView {
override model: MultiPolygons
override visuals: MultiPolygons.Visuals
protected _hole_index: SpatialIndex
protected override | (): void {
// TODO
}
protected _index_data(index: SpatialIndex): void {
const {min, max} = Math
const {data_size} = this
for (let i = 0; i < data_size; i++) {
const xsi = this._xs[i]
const ysi = this._ys[i]
if (xsi.length == 0 || ysi.length == 0) {
index.add_empty()
... | _project_data | identifier_name |
multi_polygons.ts | ScreenArray[][][]
}
export interface MultiPolygonsView extends MultiPolygonsData {}
export class MultiPolygonsView extends GlyphView {
override model: MultiPolygons
override visuals: MultiPolygons.Visuals
protected _hole_index: SpatialIndex
protected override _project_data(): void {
// TODO
}
prot... | const nl = Math.min(sx_ijk.length, sy_ijk.length)
for (let l = 0; l < nl; l++) {
const sx_ijkl = sx_ijk[l]
const sy_ijkl = sy_ijk[l]
if (l == 0)
ctx.moveTo(sx_ijkl, sy_ijkl)
else
ctx.lineTo(sx_ijkl, sy_ijkl)... | {
if (this.visuals.fill.doit || this.visuals.line.doit) {
const {sxs, sys} = data ?? this
for (const i of indices) {
ctx.beginPath()
const sx_i = sxs[i]
const sy_i = sys[i]
const nj = Math.min(sx_i.length, sy_i.length)
for (let j = 0; j < nj; j++) {
c... | identifier_body |
escprober.py | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... | (self):
return self._mDetectedCharset
def get_confidence(self):
if self._mDetectedCharset:
return 0.99
else:
return 0.00
def feed(self, aBuf):
for c in aBuf:
# PY3K: aBuf is a byte array, so c is an int, not a byte
for codingSM in... | get_charset_name | identifier_name |
escprober.py | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... | return self._mDetectedCharset
def get_confidence(self):
if self._mDetectedCharset:
return 0.99
else:
return 0.00
def feed(self, aBuf):
for c in aBuf:
# PY3K: aBuf is a byte array, so c is an int, not a byte
for codingSM in self._m... | def __init__(self):
CharSetProber.__init__(self)
self._mCodingSM = [ \
CodingStateMachine(HZSMModel),
CodingStateMachine(ISO2022CNSMModel),
CodingStateMachine(ISO2022JPSMModel),
CodingStateMachine(ISO2022KRSMModel)
]
self.reset()
d... | identifier_body |
escprober.py | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... |
return self.get_state()
| if not codingSM: continue
if not codingSM.active: continue
codingState = codingSM.next_state(c)
if codingState == constants.eError:
codingSM.active = False
self._mActiveSM -= 1
if self._mActiveSM <= 0:
... | conditional_block |
escprober.py | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... | elif codingState == constants.eItsMe:
self._mState = constants.eFoundIt
self._mDetectedCharset = codingSM.get_coding_state_machine()
return self.get_state()
return self.get_state() | random_line_split | |
dataexport.py | from main import *
from django.utils import simplejson
class CsvView(CachedPage):
cacheName = "CsvView"
mimeType = "text/csv"
selfurl = "database.csv"
def generatePage(self):
output = []
output.append( """title, homepage, person, category, posts_url, comments_url, priority, fav... |
output.append("""</Annotations>""")
return "".join(output)
class PostsJSONExport(CachedPage):
cacheName = "PostsJSONExport"
mimeType = "application/json"
def generatePage(self):
posts = []
for post in Post.gql("WHERE category IN :1 ORDER BY timestamp_created DESC L... | output.append( """
<Annotation about="%(homepage)s*">
<Label name="_cse_et7bffbfveg"/>
</Annotation>
""" % {'homepage': add_slash(strip_http(feed.homepage)) } ) | conditional_block |
dataexport.py | from main import *
from django.utils import simplejson
class CsvView(CachedPage):
cacheName = "CsvView"
mimeType = "text/csv"
selfurl = "database.csv"
def generatePage(self):
output = []
output.append( """title, homepage, person, category, posts_url, comments_url, priority, fav... | (self):
posts = []
for post in Post.gql("WHERE category IN :1 ORDER BY timestamp_created DESC LIMIT 150", ['history','fun','general','commercial','art','visual','pure','applied','teacher','journalism']):
posts.append({
"title": post.title,
"date":... | generatePage | identifier_name |
dataexport.py | from main import *
from django.utils import simplejson
class CsvView(CachedPage):
cacheName = "CsvView"
mimeType = "text/csv"
selfurl = "database.csv"
def generatePage(self):
output = []
output.append( """title, homepage, person, category, posts_url, comments_url, priority, fav... |
class WeeklyPicksJSONPHandler(JSONPHandler):
cacheName = "WeeklyPicksJSONPHandler"
def generatePage(self):
picks = [ {
"url": "http://rjlipton.wordpress.com/2011/12/03/the-meaning-of-omega/",
"caption": "If you haven't followed the debate on TCS breakthrough in matrix m... | mimeType = "application/javascript"
def post_process_content(self, content):
callback = self.request.get("callback")
logging.info("Add JSONP padding: " + callback)
return "%s(%s);" % (callback, content) | identifier_body |
dataexport.py | from main import *
from django.utils import simplejson
class CsvView(CachedPage):
cacheName = "CsvView"
mimeType = "text/csv"
selfurl = "database.csv"
def generatePage(self):
output = []
output.append( """title, homepage, person, category, posts_url, comments_url, priority, fav... | "title": post.title,
"date": post.timestamp_created.strftime('%B %d,%Y %I:%M:%S %p'),
"length": post.length,
"blog": post.service,
"tags": [tag for tag in post.tags],
"category": post.category,
... | def generatePage(self):
posts = []
for post in Post.gql("WHERE category IN :1 ORDER BY timestamp_created DESC LIMIT 150", ['history','fun','general','commercial','art','visual','pure','applied','teacher','journalism']):
posts.append({
| random_line_split |
__init__.py | ###
# Copyright (c) 2012, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditi... |
Class = plugin.Class
configure = config.configure
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
| from . import test | conditional_block |
__init__.py | ###
# Copyright (c) 2012, Valentin Lorentz
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditi... | # in here if you're keeping the plugin in CVS or some similar system.
__version__ = ""
# XXX Replace this with an appropriate author or supybot.Author instance.
__author__ = supybot.authors.unknown
# This is a dictionary mapping supybot.Author instances to lists of
# contributions.
__contributors__ = {}
# This is a ... | # Use this for the version of this plugin. You may wish to put a CVS keyword | random_line_split |
issue-3743.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 ... |
// Vec2's implementation of Mul "from the other side" using the above trait
impl<Res, Rhs: RhsOfVec2Mul<Res>> Mul<Rhs,Res> for Vec2 {
fn mul(&self, rhs: &Rhs) -> Res { rhs.mul_vec2_by(self) }
}
// Implementation of 'f64 as right-hand-side of Vec2::Mul'
impl RhsOfVec2Mul<Vec2> for f64 {
fn mul_vec2_by(&self, l... | // Right-hand-side operator visitor pattern
trait RhsOfVec2Mul<Result> { fn mul_vec2_by(&self, lhs: &Vec2) -> Result; } | random_line_split |
issue-3743.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 a = Vec2 { x: 3.0f64, y: 4.0f64 };
// the following compiles and works properly
let v1: Vec2 = a * 3.0f64;
println!("{} {}", v1.x, v1.y);
// the following compiles but v2 will not be Vec2 yet and
// using it later will cause an error that the type of v2
// must be known
let v2... | main | identifier_name |
Plugin.js | import BungieNet from "./BungieNet.js";
import request from "request";
/**
* Plugin base class for plugins. Each plugin MUST define an update method.
*
* void update( String: eventName, args[] )
*/
export default class Plugin {
/**
* Dummy function for inheriting classes
* @param {String} eventName - name... | }
}
}; | random_line_split | |
Plugin.js | import BungieNet from "./BungieNet.js";
import request from "request";
/**
* Plugin base class for plugins. Each plugin MUST define an update method.
*
* void update( String: eventName, args[] )
*/
export default class | {
/**
* Dummy function for inheriting classes
* @param {String} eventName - name of the event being raised
* @param {*} e - event object
* @return {undefined}
*/
static update(eventName, e) {
throw new Error("update method is undefined in subclass");
}
}
Plugin.CookieJarMemoryPlugin = class... | Plugin | identifier_name |
Plugin.js | import BungieNet from "./BungieNet.js";
import request from "request";
/**
* Plugin base class for plugins. Each plugin MUST define an update method.
*
* void update( String: eventName, args[] )
*/
export default class Plugin {
/**
* Dummy function for inheriting classes
* @param {String} eventName - name... |
}
};
Plugin.OAuthPlugin = class extends Plugin {
/**
* @param {String} accessToken - oauth access token
*/
constructor(accessToken) {
super();
this.accessToken = accessToken;
}
/**
* @param {String} eventName -
* @param {Object} e -
* @return {undefined}
*/
update(eventName, e... | {
e.target.options.jar = this.jar;
} | conditional_block |
Plugin.js | import BungieNet from "./BungieNet.js";
import request from "request";
/**
* Plugin base class for plugins. Each plugin MUST define an update method.
*
* void update( String: eventName, args[] )
*/
export default class Plugin {
/**
* Dummy function for inheriting classes
* @param {String} eventName - name... |
};
Plugin.OAuthPlugin = class extends Plugin {
/**
* @param {String} accessToken - oauth access token
*/
constructor(accessToken) {
super();
this.accessToken = accessToken;
}
/**
* @param {String} eventName -
* @param {Object} e -
* @return {undefined}
*/
update(eventName, e) {
... | {
if(eventName === BungieNet.Platform.events.frameBeforeSend) {
e.target.options.jar = this.jar;
}
} | identifier_body |
seriesList.ts | import { Component, ViewChild } from '@angular/core';
import { FourDInterface } from 'js44d';
import { DataGrid } from 'js44d';
import { Modal, ModalDialogInstance } from 'js44d';
import { SeriesInfoDialog } from './seriesInfoDialog';
import { AnalyzeSeriesComponent } from './analyzeSeries';
import { SeriesEx } from... | () {
if (this.theGrid && this.theGrid.currentRecord) {
let theRec: SeriesEx = <any>this.theGrid.currentRecord;
this.modal.openDialog(AnalyzeSeriesComponent, { seriesID: theRec.SeriesId, seriesName: theRec.IMDBTitle }); // open user recomendations dialog
}
}
}
| checkSeries | identifier_name |
seriesList.ts | import { Component, ViewChild } from '@angular/core';
import { FourDInterface } from 'js44d';
import { DataGrid } from 'js44d';
import { Modal, ModalDialogInstance } from 'js44d';
import { SeriesInfoDialog } from './seriesInfoDialog';
import { AnalyzeSeriesComponent } from './analyzeSeries';
import { SeriesEx } from... | //
constructor(private modal: Modal) {
}
public checkSeries() {
if (this.theGrid && this.theGrid.currentRecord) {
let theRec: SeriesEx = <any>this.theGrid.currentRecord;
this.modal.openDialog(AnalyzeSeriesComponent, { seriesID: theRec.SeriesId, seriesName: theRec.IMDBTit... | { title: 'Prod. Company', field: 'ProdCompany' }
];
//
// We need access to a Modal dialog component, to open an associated Record Edit Form | random_line_split |
seriesList.ts | import { Component, ViewChild } from '@angular/core';
import { FourDInterface } from 'js44d';
import { DataGrid } from 'js44d';
import { Modal, ModalDialogInstance } from 'js44d';
import { SeriesInfoDialog } from './seriesInfoDialog';
import { AnalyzeSeriesComponent } from './analyzeSeries';
import { SeriesEx } from... |
}
}
| {
let theRec: SeriesEx = <any>this.theGrid.currentRecord;
this.modal.openDialog(AnalyzeSeriesComponent, { seriesID: theRec.SeriesId, seriesName: theRec.IMDBTitle }); // open user recomendations dialog
} | conditional_block |
borrowck-preserve-box-in-uniq.rs | // xfail-pretty
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
//... | {
let mut x = ~@F{f: ~3};
borrow(x.f, |b_x| {
assert_eq!(*b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x)));
*x = @F{f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(*b_x)) as uint);
assert_eq!(*b_x, 3);
... | identifier_body | |
borrowck-preserve-box-in-uniq.rs | // xfail-pretty
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
//... | ptr::to_unsafe_ptr(&(*b_x)) as uint);
assert_eq!(*b_x, 3);
assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(*b_x)));
})
} | info!("ptr::to_unsafe_ptr(*b_x) = {:x}", | random_line_split |
borrowck-preserve-box-in-uniq.rs | // xfail-pretty
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
//... | { f: ~int }
pub fn main() {
let mut x = ~@F{f: ~3};
borrow(x.f, |b_x| {
assert_eq!(*b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x)));
*x = @F{f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(*b_x)) as uint);
... | F | identifier_name |
mails.py | # -*- coding: utf-8 -*-
"""OSF mailing utilities.
Email templates go in website/templates/emails
Templates must end in ``.txt.mako`` for plaintext emails or``.html.mako`` for html emails.
You can then create a `Mail` object given the basename of the template and
the email subject. ::
CONFIRM_EMAIL = Mail(tpl_pre... | (object):
"""An email object.
:param str tpl_prefix: The template name prefix.
:param str subject: The subject of the email.
"""
def __init__(self, tpl_prefix, subject):
self.tpl_prefix = tpl_prefix
self._subject = subject
def html(self, **context):
"""Render the HTML ... | Mail | identifier_name |
mails.py | # -*- coding: utf-8 -*-
"""OSF mailing utilities.
Email templates go in website/templates/emails
Templates must end in ``.txt.mako`` for plaintext emails or``.html.mako`` for html emails.
You can then create a `Mail` object given the basename of the template and
the email subject. ::
CONFIRM_EMAIL = Mail(tpl_pre... |
def html(self, **context):
"""Render the HTML email message."""
tpl_name = self.tpl_prefix + HTML_EXT
return render_message(tpl_name, **context)
def text(self, **context):
"""Render the plaintext email message"""
tpl_name = self.tpl_prefix + TXT_EXT
return rend... | self.tpl_prefix = tpl_prefix
self._subject = subject | identifier_body |
mails.py | # -*- coding: utf-8 -*-
"""OSF mailing utilities.
Email templates go in website/templates/emails
Templates must end in ``.txt.mako`` for plaintext emails or``.html.mako`` for html emails.
You can then create a `Mail` object given the basename of the template and
the email subject. ::
CONFIRM_EMAIL = Mail(tpl_pre... |
else:
ret = mailer(**kwargs)
if callback:
callback()
return ret
# Predefined Emails
TEST = Mail('test', subject='A test email to ${name}')
CONFIRM_EMAIL = Mail('confirm', subject='Confirm your email address')
CONFIRM_MERGE = Mail('confirm_merge', subject='Confirm account mer... | return mailer.apply_async(kwargs=kwargs, link=callback) | conditional_block |
mails.py | # -*- coding: utf-8 -*-
"""OSF mailing utilities.
Email templates go in website/templates/emails
Templates must end in ``.txt.mako`` for plaintext emails or``.html.mako`` for html emails.
You can then create a `Mail` object given the basename of the template and
the email subject. ::
CONFIRM_EMAIL = Mail(tpl_pre... | tpl_name = self.tpl_prefix + TXT_EXT
return render_message(tpl_name, **context)
def subject(self, **context):
return Template(self._subject).render(**context)
def render_message(tpl_name, **context):
"""Render an email message."""
tpl = _tpl_lookup.get_template(tpl_name)
retur... | return render_message(tpl_name, **context)
def text(self, **context):
"""Render the plaintext email message""" | random_line_split |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::FileKey;
use fixture_tests::Fixture;
use fnv::FnvHashMap;
use graphql_ir::{build, Program};
use graphql_syntax::parse;
... |
}
} else {
panic!("Expected exactly one %extensions% section marker.")
}
}
| {
let mut errs = errors
.into_iter()
.map(|err| err.print(&sources))
.collect::<Vec<_>>();
errs.sort();
Err(errs.join("\n\n"))
} | conditional_block |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::FileKey;
use fixture_tests::Fixture;
use fnv::FnvHashMap;
use graphql_ir::{build, Program};
use graphql_syntax::parse;
... | .collect::<Vec<_>>();
errs.sort();
Err(errs.join("\n\n"))
}
}
} else {
panic!("Expected exactly one %extensions% section marker.")
}
}
| {
let parts: Vec<_> = fixture.content.split("%extensions%").collect();
if let [base, extensions] = parts.as_slice() {
let file_key = FileKey::new(fixture.file_name);
let ast = parse(base, file_key).unwrap();
let schema = test_schema_with_extensions(extensions);
let mut sources =... | identifier_body |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::FileKey;
use fixture_tests::Fixture;
use fnv::FnvHashMap;
use graphql_ir::{build, Program};
use graphql_syntax::parse; |
if let [base, extensions] = parts.as_slice() {
let file_key = FileKey::new(fixture.file_name);
let ast = parse(base, file_key).unwrap();
let schema = test_schema_with_extensions(extensions);
let mut sources = FnvHashMap::default();
sources.insert(FileKey::new(fixture.file_na... | use graphql_transforms::validate_server_only_directives;
use test_schema::test_schema_with_extensions;
pub fn transform_fixture(fixture: &Fixture) -> Result<String, String> {
let parts: Vec<_> = fixture.content.split("%extensions%").collect(); | random_line_split |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::FileKey;
use fixture_tests::Fixture;
use fnv::FnvHashMap;
use graphql_ir::{build, Program};
use graphql_syntax::parse;
... | (fixture: &Fixture) -> Result<String, String> {
let parts: Vec<_> = fixture.content.split("%extensions%").collect();
if let [base, extensions] = parts.as_slice() {
let file_key = FileKey::new(fixture.file_name);
let ast = parse(base, file_key).unwrap();
let schema = test_schema_with_ext... | transform_fixture | identifier_name |
cache.rs | // This module defines a common API for caching internal runtime state.
// The `thread_local` crate provides an extremely optimized version of this.
// However, if the perf-cache feature is disabled, then we drop the
// thread_local dependency and instead use a pretty naive caching mechanism
// with a mutex.
//
// Stri... |
pub use self::imp::{Cached, CachedGuard};
#[cfg(feature = "perf-cache")]
mod imp {
use thread_local::CachedThreadLocal;
#[derive(Debug)]
pub struct Cached<T: Send>(CachedThreadLocal<T>);
#[derive(Debug)]
pub struct CachedGuard<'a, T: 'a>(&'a T);
impl<T: Send> Cached<T> {
pub fn new(... | // flexible thread_local API, but implementing thread_local's API doesn't
// seem possible in purely safe code. | random_line_split |
cache.rs | // This module defines a common API for caching internal runtime state.
// The `thread_local` crate provides an extremely optimized version of this.
// However, if the perf-cache feature is disabled, then we drop the
// thread_local dependency and instead use a pretty naive caching mechanism
// with a mutex.
//
// Stri... | (&self, create: impl FnOnce() -> T) -> CachedGuard<T> {
CachedGuard(self.0.get_or(|| create()))
}
}
impl<'a, T: Send> CachedGuard<'a, T> {
pub fn value(&self) -> &T {
self.0
}
}
}
#[cfg(not(feature = "perf-cache"))]
mod imp {
use std::marker::PhantomData... | get_or | identifier_name |
cache.rs | // This module defines a common API for caching internal runtime state.
// The `thread_local` crate provides an extremely optimized version of this.
// However, if the perf-cache feature is disabled, then we drop the
// thread_local dependency and instead use a pretty naive caching mechanism
// with a mutex.
//
// Stri... |
pub fn get_or(&self, create: impl FnOnce() -> T) -> CachedGuard<T> {
CachedGuard(self.0.get_or(|| create()))
}
}
impl<'a, T: Send> CachedGuard<'a, T> {
pub fn value(&self) -> &T {
self.0
}
}
}
#[cfg(not(feature = "perf-cache"))]
mod imp {
use s... | {
Cached(CachedThreadLocal::new())
} | identifier_body |
cache.rs | // This module defines a common API for caching internal runtime state.
// The `thread_local` crate provides an extremely optimized version of this.
// However, if the perf-cache feature is disabled, then we drop the
// thread_local dependency and instead use a pretty naive caching mechanism
// with a mutex.
//
// Stri... |
}
}
}
| {
self.cache.put(value);
} | conditional_block |
selector-set.next.d.ts | element: (el: Element) => Array<string> | void;
}
class SelectorSet<T> {
size: number;
matchesSelector: (el: Element, selector: string) => boolean;
querySelectorAll: (selectors: string, context: Element) => Array<Element>;
indexes: Array<ISelectorSetIndex>;
add(selector: string, data: T)... | declare module 'selector-set/selector-set.next' {
interface ISelectorSetIndex {
name: string;
selector: (selector: string) => string | void; | random_line_split | |
selector-set.next.d.ts | declare module 'selector-set/selector-set.next' {
interface ISelectorSetIndex {
name: string;
selector: (selector: string) => string | void;
element: (el: Element) => Array<string> | void;
}
class | <T> {
size: number;
matchesSelector: (el: Element, selector: string) => boolean;
querySelectorAll: (selectors: string, context: Element) => Array<Element>;
indexes: Array<ISelectorSetIndex>;
add(selector: string, data: T): void;
remove(selector: string, data?: T): void;
matches(el: Eleme... | SelectorSet | identifier_name |
memoize.js | 'use strict'; | // Create memoized function
fn // function, sync or async
// Returns: function, memoized
) => {
const cache = new Map();
const memoized = function(...args) {
const callback = args.pop();
const key = args[0];
const record = cache.get(key);
if (record) {
callback(record.err, record.data);... |
function Memoized() {}
const memoize = ( | random_line_split |
memoize.js | 'use strict';
function | () {}
const memoize = (
// Create memoized function
fn // function, sync or async
// Returns: function, memoized
) => {
const cache = new Map();
const memoized = function(...args) {
const callback = args.pop();
const key = args[0];
const record = cache.get(key);
if (record) {
callback(... | Memoized | identifier_name |
memoize.js | 'use strict';
function Memoized() |
const memoize = (
// Create memoized function
fn // function, sync or async
// Returns: function, memoized
) => {
const cache = new Map();
const memoized = function(...args) {
const callback = args.pop();
const key = args[0];
const record = cache.get(key);
if (record) {
callback(recor... | {} | identifier_body |
lnparse.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
bestandsnaam="De_Telegraaf2014-03-22_22-08.TXT" |
artikel=0
tekst={}
datum={}
section={}
length={}
loaddate={}
language={}
pubtype={}
journal={}
with open(bestandsnaam,"r") as f:
for line in f:
line=line.replace("\r","")
if line=="\n":
continue
matchObj=re.match(r"\s+(\d+) of (\d+) DOCUMENTS",line)
if matchObj:
# print matchObj.group(1), "of", matchOb... | random_line_split | |
lnparse.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
bestandsnaam="De_Telegraaf2014-03-22_22-08.TXT"
artikel=0
tekst={}
datum={}
section={}
length={}
loaddate={}
language={}
pubtype={}
journal={}
with open(bestandsnaam,"r") as f:
for line in f:
line=line.replace("\r","")
if line=="\n":
continue
matchObj... |
elif line.startswith("LANGUAGE"):
language[artikel]=line.replace("LANGUAGE: ","").rstrip("\n")
elif line.startswith("PUBLICATION-TYPE"):
pubtype[artikel]=line.replace("PUBLICATION-TYPE: ","").rstrip("\n")
elif line.startswith("JOURNAL-CODE"):
journal[artikel]=line.replace("JOURNAL-CODE: ","").rstrip("\n... | loaddate[artikel]=line.replace("LOAD-DATE: ","").rstrip("\n") | conditional_block |
stock_directive.js | <div ade-stock ade-id='1234' adeProvider="yahoo" ade-class="myClass" ng-model="data"></div>
Config:
ade-id:
If this id is set, it will be used in messages broadcast to the app on state changes.
ade-class:
A custom class to give to the input
ade-readonly:
If you don't want the stock ticker to be editable
a... |
Usage: | random_line_split | |
stock_directive.js | ade-class:
A custom class to give to the input
ade-readonly:
If you don't want the stock ticker to be editable
ade-provider:
By default, stock prices provided by google API. This could be set to yahoo.
Messages:
name: ADE-start
data: id from config
name: ADE-finish
data: {id from config, old value, ... |
if (change.indexOf("+") !== -1) {
// stock up
element.addClass("ade-stock-up").removeClass("ade-stock-down");
} else if (change.indexOf("-") !== -1) {
element.addClass("ade-stock-down").removeClass("ade-stock-up");
}
};
//called once the edit is done, so we can save the new data and ... | {
var $movementEl = $stockEl.find(".ade-price-movement");
$movementEl.addClass("ade-popup").addClass("dropdown-menu");
$stockEl.on("mouseenter", function() {
$movementEl.addClass("open");
}).on("mouseleave", function() {
$movementEl.removeClass("open");
});
} | conditional_block |
report.py | "# Sieving (algebraic|rational|side-0|side-1) q=(\d+);")
PATTERN_SQ = re.compile(r"# Average (.*) for (\d+) special-q's, max bucket fill (.*)")
PATTERN_CPUTIME = re.compile(r"# Total cpu time {cap_fp}s .norm {cap_fp}\+{cap_fp}, sieving {cap_fp} .{cap_fp} \+ {cap_fp} \+ {cap_fp}., factor {cap_fp}.".format(**REGEXES))
PA... | last_sq = int(match.group(2))
if first_sq is None:
first_sq = last_sq
else:
assert first_sq <= last_sq
match = PATTERN_SQ.match(line)
if match:
nr_sq = int(match.group(2))
match = ... | def __init__(self):
self.dupes = 0
self.nr_sq = 0
self.cputimes = ListArith([0.] * 8)
self.reports = 0
self.relations_int = NumInt()
self.dupes_int = NumInt()
self.elapsed_int = NumInt()
def parse_one_input(self, lines, verbose=False):
nr_sq = None
... | identifier_body |
report.py | "# Sieving (algebraic|rational|side-0|side-1) q=(\d+);")
PATTERN_SQ = re.compile(r"# Average (.*) for (\d+) special-q's, max bucket fill (.*)")
PATTERN_CPUTIME = re.compile(r"# Total cpu time {cap_fp}s .norm {cap_fp}\+{cap_fp}, sieving {cap_fp} .{cap_fp} \+ {cap_fp} \+ {cap_fp}., factor {cap_fp}.".format(**REGEXES))
PA... | class ListArith(list):
"""
>>> a = ListArith([1,2,3])
>>> b = ListArith([3,4,5])
>>> a + 1
[2, 3, 4]
>>> a - 1
[0, 1, 2]
>>> a * 2
[2, 4, 6]
>>> a + b
[4, 6, 8]
>>> b - a
[2, 2, 2]
>>> a * b
[3, 8, 15]
"""
def __add__(self, other):
if isinstanc... | x = coord - self.lastcoord[1]
prev_sum = self.sum - self.trapez_area()
return prev_sum + x * self.lastvalue[1]
| random_line_split |
report.py | "# Sieving (algebraic|rational|side-0|side-1) q=(\d+);")
PATTERN_SQ = re.compile(r"# Average (.*) for (\d+) special-q's, max bucket fill (.*)")
PATTERN_CPUTIME = re.compile(r"# Total cpu time {cap_fp}s .norm {cap_fp}\+{cap_fp}, sieving {cap_fp} .{cap_fp} \+ {cap_fp} \+ {cap_fp}., factor {cap_fp}.".format(**REGEXES))
PA... |
if reports is None:
sys.stderr.write("Did not receive value for reports\n")
return False
# check number of relations before number of special-q's
if reports == 0:
sys.stderr.write("No relation found in sample run, please increase q_range in las_run.py\n")
... | sys.stderr.write("Did not receive value for cputimes\n")
return False | conditional_block |
report.py | Sieving (algebraic|rational|side-0|side-1) q=(\d+);")
PATTERN_SQ = re.compile(r"# Average (.*) for (\d+) special-q's, max bucket fill (.*)")
PATTERN_CPUTIME = re.compile(r"# Total cpu time {cap_fp}s .norm {cap_fp}\+{cap_fp}, sieving {cap_fp} .{cap_fp} \+ {cap_fp} \+ {cap_fp}., factor {cap_fp}.".format(**REGEXES))
PATT... | (self, other):
if isinstance(other, Iterable):
return ListArith([a + b for a,b in zip(self, other)])
else:
return ListArith([a + other for a in self])
def __sub__(self, other):
if isinstance(other, Iterable):
return ListArith([a - b for a,b in zip(self, o... | __add__ | identifier_name |
discriminantPropertyCheck.ts | // @strict: true
type Item = Item1 | Item2;
interface Base {
bar: boolean;
}
interface Item1 extends Base {
kind: "A";
foo: string | undefined;
baz: boolean;
qux: true;
}
interface Item2 extends Base {
kind: "B";
foo: string | undefined;
baz: boolean;
qux: fals... | }
}
// Repro from #29106
const f = (_a: string, _b: string): void => {};
interface A {
a?: string;
b?: string;
}
interface B {
a: string;
b: string;
}
type U = A | B;
const u: U = {} as any;
u.a && u.b && f(u.a, u.b);
u.b && u.a && f(u.a, u.b);
// Repro from #29012
type ... | random_line_split | |
discriminantPropertyCheck.ts | // @strict: true
type Item = Item1 | Item2;
interface Base {
bar: boolean;
}
interface Item1 extends Base {
kind: "A";
foo: string | undefined;
baz: boolean;
qux: true;
}
interface Item2 extends Base {
kind: "B";
foo: string | undefined;
baz: boolean;
qux: fals... |
function foo5(x: Item) {
if (x.qux && x.foo !== undefined) {
x.foo.length;
}
}
function foo6(x: Item) {
if (x.foo !== undefined && x.qux) {
x.foo.length; // Error, intervening discriminant guard
}
}
// Repro from #27493
enum Types { Str = 1, Num = 2 }
type Instan... | {
if (x.foo !== undefined && x.baz) {
x.foo.length;
}
} | identifier_body |
discriminantPropertyCheck.ts | // @strict: true
type Item = Item1 | Item2;
interface Base {
bar: boolean;
}
interface Item1 extends Base {
kind: "A";
foo: string | undefined;
baz: boolean;
qux: true;
}
interface Item2 extends Base {
kind: "B";
foo: string | undefined;
baz: boolean;
qux: fals... |
}
function foo2(x: Item) {
if (x.foo !== undefined && x.bar) {
x.foo.length;
}
}
function foo3(x: Item) {
if (x.baz && x.foo !== undefined) {
x.foo.length;
}
}
function foo4(x: Item) {
if (x.foo !== undefined && x.baz) {
x.foo.length;
}
}
functio... | {
x.foo.length;
} | conditional_block |
discriminantPropertyCheck.ts | // @strict: true
type Item = Item1 | Item2;
interface Base {
bar: boolean;
}
interface Item1 extends Base {
kind: "A";
foo: string | undefined;
baz: boolean;
qux: true;
}
interface Item2 extends Base {
kind: "B";
foo: string | undefined;
baz: boolean;
qux: fals... | (x: Item) {
if (x.foo !== undefined && x.qux) {
x.foo.length; // Error, intervening discriminant guard
}
}
// Repro from #27493
enum Types { Str = 1, Num = 2 }
type Instance = StrType | NumType;
interface StrType {
type: Types.Str;
value: string;
length: number;
}
int... | foo6 | identifier_name |
load_dorado2009.py | #!/usr/bin/env python
'''
Loader for all 2009 Dorado missions written for Monique's notice of bad
depths in Dorado389_2009_084_02_084_02_decim.nc.
Mike McCann
MBARI 15 January 2013
@var __date__: Date of last svn commit
@undocumented: __doc__ parser
@status: production
@license: GPL
'''
import os
import sys
import d... |
else:
cl.loadDorado(stride=cl.args.stride)
##cl.loadM1ts(stride=cl.args.stride)
##cl.loadM1met(stride=cl.args.stride)
# Add any X3D Terrain information specified in the constructor to the database - must be done after a load is executed
cl.addTerrainResources()
print("All Done.")
| cl.loadDorado(stride=2)
cl.loadM1ts(stride=1)
cl.loadM1met(stride=1) | conditional_block |
load_dorado2009.py | #!/usr/bin/env python
'''
Loader for all 2009 Dorado missions written for Monique's notice of bad
depths in Dorado389_2009_084_02_084_02_decim.nc.
Mike McCann
MBARI 15 January 2013
@var __date__: Date of last svn commit
@undocumented: __doc__ parser
@status: production
@license: GPL
'''
import os
import sys
import d... | # Dorado surveys in 2009
cl.dorado_base = 'http://dods.mbari.org/opendap/data/auvctd/surveys/2009/netcdf/'
cl.dorado_files = [
'Dorado389_2009_055_05_055_05_decim.nc',
'Dorado389_2009_084_00_084_00_decim.nc',
'Dorado389_2009_084_02_084_02_decim.nc',
... | }
},
grdTerrain = os.path.join(parentDir, 'Monterey25.grd')
)
| random_line_split |
font.rs | _GlyphSlot, FT_Library, FT_Long, FT_ULong};
use freetype::freetype::{FT_STYLE_FLAG_ITALIC, FT_STYLE_FLAG_BOLD};
use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics};
use freetype::freetype::{ft_sfnt_os2};
use freetype::tt_os2::TT_OS2;
use std::cast;
use std::ptr;
use std::str;
fn float_to_fixed_ft(f: float)... |
}
enum FontSource {
FontSourceMem(~[u8]),
FontSourceFile(~str)
}
pub struct FontHandle {
// The font binary. This must stay valid for the lifetime of the font,
// if the font is created using FT_Memory_Face.
source: FontSource,
face: FT_Face,
handle: FontContextHandle
}
#[unsafe_destruct... | {
fail!()
} | identifier_body |
font.rs | _GlyphSlot, FT_Library, FT_Long, FT_ULong};
use freetype::freetype::{FT_STYLE_FLAG_ITALIC, FT_STYLE_FLAG_BOLD};
use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics};
use freetype::freetype::{ft_sfnt_os2};
use freetype::tt_os2::TT_OS2;
use std::cast;
use std::ptr;
use std::str;
fn float_to_fixed_ft(f: float)... | (&self,
fctx: &FontContextHandle,
style: &UsedFontStyle) -> Result<FontHandle, ()> {
match self.source {
FontSourceMem(ref buf) => {
FontHandleMethods::new_from_buffer(fctx, buf.clone(), style)
}
FontSourceFile(r... | clone_with_style | identifier_name |
font.rs | FT_GlyphSlot, FT_Library, FT_Long, FT_ULong};
use freetype::freetype::{FT_STYLE_FLAG_ITALIC, FT_STYLE_FLAG_BOLD};
use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics};
use freetype::freetype::{ft_sfnt_os2};
use freetype::tt_os2::TT_OS2;
use std::cast;
use std::ptr;
use std::str;
fn float_to_fixed_ft(f: floa... | }
}
return FontMetrics {
underline_size: underline_size,
underline_offset: underline_offset,
strikeout_size: strikeout_size,
strikeout_offset: strikeout_offset,
leading: geometry::from_pt(0.0), //FIXME
x_he... | strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as float);
strikeout_offset = self.font_units_to_au((*os2).yStrikeoutPosition as float);
x_height = self.font_units_to_au((*os2).sxHeight as float); | random_line_split |
font.rs | _GlyphSlot, FT_Library, FT_Long, FT_ULong};
use freetype::freetype::{FT_STYLE_FLAG_ITALIC, FT_STYLE_FLAG_BOLD};
use freetype::freetype::{FT_SizeRec, FT_UInt, FT_Size_Metrics};
use freetype::freetype::{ft_sfnt_os2};
use freetype::tt_os2::TT_OS2;
use std::cast;
use std::ptr;
use std::str;
fn float_to_fixed_ft(f: float)... |
}
}
}
fn clone_with_style(&self,
fctx: &FontContextHandle,
style: &UsedFontStyle) -> Result<FontHandle, ()> {
match self.source {
FontSourceMem(ref buf) => {
FontHandleMethods::new_from_buffer(fctx, buf.clo... | {
default_weight
} | conditional_block |
profile.py | import copy
from collections import OrderedDict
from collections import defaultdict
from conans.model.env_info import EnvValues
from conans.model.options import OptionsValues
from conans.model.values import Values
class Profile(object):
"""A profile contains a set of setting (with values), environment variables
... | (self):
return Values.from_list(list(self.settings.items()))
@property
def package_settings_values(self):
result = {}
for pkg, settings in self.package_settings.items():
result[pkg] = list(settings.items())
return result
def dumps(self):
result = ["[sett... | settings_values | identifier_name |
profile.py | import copy
from collections import OrderedDict
from collections import defaultdict
from conans.model.env_info import EnvValues
from conans.model.options import OptionsValues
from conans.model.values import Values
class Profile(object):
"""A profile contains a set of setting (with values), environment variables
... |
@property
def settings_values(self):
return Values.from_list(list(self.settings.items()))
@property
def package_settings_values(self):
result = {}
for pkg, settings in self.package_settings.items():
result[pkg] = list(settings.items())
return result
de... | self.settings = OrderedDict()
self.package_settings = defaultdict(OrderedDict)
self.env_values = EnvValues()
self.options = OptionsValues()
self.build_requires = OrderedDict() # conan_ref Pattern: list of conan_ref | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.