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 |
|---|---|---|---|---|
interpolation.ts | import { IPoint, Point } from '../primitives/point';
import { EasingMethod, linear } from './easing';
/**
* This enum is just a common way to define interpolation types
*/
export enum InterpolationMethod {
BEZIER2,
BEZIER3,
CIRCULAR,
}
/**
* This calculates a quadratic bezier curve.
*
* We use specific bez... | (t: number, p1: IPoint, p2: IPoint, c1: IPoint, c2: IPoint): IPoint {
const t2 = t * t;
const t3 = t2 * t;
const mt = 1 - t;
const mt2 = mt * mt;
const mt3 = mt2 * mt;
return {
x: p1.x * mt3 + 3 * c1.x * mt2 * t + 3 * c2.x * mt * t2 + p2.x * t3,
y: p1.y * mt3 + 3 * c1.y * mt2 * t + 3 * c2.y * mt * ... | bezier3 | identifier_name |
icon_system_fontawesome.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is dis... |
if (map) {
staticMap = map;
return $.when(this);
}
if (fetchMap === null) {
fetchMap = Ajax.call([{
methodname: 'core_output_load_fontawesome_icon_system_map',
args: {
themename: M.cfg.theme,
... | {
map = JSON.parse(map);
} | conditional_block |
icon_system_fontawesome.js | // This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is dis... | attributes: [
{name: 'src', value: url},
{name: 'alt', value: title},
{name: 'title', value: title}
]
};
}
var context = {
key: mappedIcon,
title: title,
alt: titl... | var unmappedIcon = false;
if (typeof mappedIcon === "undefined") {
var url = Url.imageUrl(key, component);
unmappedIcon = { | random_line_split |
__init__.py | # coding: utf-8
# Copyright 2014 Globo.com Player authors. All rights reserved.
# Use of this source code is governed by a MIT License
# license that can be found in the LICENSE file.
import sys
PYTHON_MAJOR_VERSION = sys.version_info
import os
import posixpath
try:
import urlparse as url_parser
import urlli... | (resource):
return resource.read().decode(resource.headers.get_content_charset(failobj="utf-8"))
def _load_from_file(uri):
with open(uri) as fileobj:
raw_content = fileobj.read().strip()
base_uri = os.path.dirname(uri)
return M3U8(raw_content, base_uri=base_uri)
| _read_python3x | identifier_name |
__init__.py | # coding: utf-8
# Copyright 2014 Globo.com Player authors. All rights reserved.
# Use of this source code is governed by a MIT License
# license that can be found in the LICENSE file.
import sys
PYTHON_MAJOR_VERSION = sys.version_info
import os
import posixpath
try:
import urlparse as url_parser
import urlli... |
else:
content = _read_python3x(resource)
return M3U8(content, base_uri=base_uri)
def _url_for(uri):
return urlopen(uri).geturl()
def _parsed_url(url):
parsed_url = url_parser.urlparse(url)
prefix = parsed_url.scheme + '://' + parsed_url.netloc
base_path = posixpath.normpath(parsed_url... | content = _read_python2x(resource) | conditional_block |
__init__.py | # coding: utf-8
# Copyright 2014 Globo.com Player authors. All rights reserved.
# Use of this source code is governed by a MIT License
# license that can be found in the LICENSE file.
import sys
PYTHON_MAJOR_VERSION = sys.version_info
import os
import posixpath
try:
import urlparse as url_parser
import urlli... | Given a string with a m3u8 content, returns a M3U8 object.
Raises ValueError if invalid content
'''
return M3U8(content)
def load(uri):
'''
Retrieves the content from a given URI and returns a M3U8 object.
Raises ValueError if invalid content or IOError if request fails.
'''
if is_u... | __all__ = ('M3U8', 'Playlist', 'IFramePlaylist', 'Media',
'Segment', 'loads', 'load', 'parse', 'ParseError')
def loads(content):
''' | random_line_split |
__init__.py | # coding: utf-8
# Copyright 2014 Globo.com Player authors. All rights reserved.
# Use of this source code is governed by a MIT License
# license that can be found in the LICENSE file.
import sys
PYTHON_MAJOR_VERSION = sys.version_info
import os
import posixpath
try:
import urlparse as url_parser
import urlli... |
def _load_from_file(uri):
with open(uri) as fileobj:
raw_content = fileobj.read().strip()
base_uri = os.path.dirname(uri)
return M3U8(raw_content, base_uri=base_uri)
| return resource.read().decode(resource.headers.get_content_charset(failobj="utf-8")) | identifier_body |
SyncSet.py |
import logging
log = logging.getLogger("SyncSet")
import conduit
import conduit.Conduit as Conduit
import conduit.Settings as Settings
import conduit.XMLSerialization as XMLSerialization
SETTINGS_VERSION = XMLSerialization.Settings.XML_VERSION
class SyncSet(gobject.GObject):
"""
Represents a group of condui... |
cond.add_dataprovider(wrapper, trySourceFirst)
def on_dataprovider_available_unavailable(self, loader, dpw):
"""
Removes all PendingWrappers corresponding to dpw and replaces with new dpw instances
"""
key = dpw.get_key()
for c in self.get_all_conduits():
... | wrapper.set_configuration_xml(xmltext=i.toxml()) | conditional_block |
SyncSet.py |
import logging
log = logging.getLogger("SyncSet")
import conduit
import conduit.Conduit as Conduit
import conduit.Settings as Settings
import conduit.XMLSerialization as XMLSerialization
SETTINGS_VERSION = XMLSerialization.Settings.XML_VERSION
class SyncSet(gobject.GObject):
"""
Represents a group of condui... | (self, cond):
self.conduits.append(cond)
self.emit("conduit-added", cond)
def remove_conduit(self, cond):
self.emit("conduit-removed", cond)
cond.quit()
self.conduits.remove(cond)
def get_all_conduits(self):
return self.conduits
def get_conduit(self, index)... | add_conduit | identifier_name |
SyncSet.py | object
import logging
log = logging.getLogger("SyncSet")
import conduit
import conduit.Conduit as Conduit
import conduit.Settings as Settings
import conduit.XMLSerialization as XMLSerialization
SETTINGS_VERSION = XMLSerialization.Settings.XML_VERSION
class SyncSet(gobject.GObject):
"""
Represents a group of ... | rootxml.setAttribute("application-version", conduit.VERSION)
rootxml.setAttribute("settings-version", SETTINGS_VERSION)
doc.appendChild(rootxml)
#Store the conduits
for cond in self.conduits:
conduitxml = doc.createElement("conduit")
conduitxml.se... | #Build the application settings xml document
doc = xml.dom.minidom.Document()
rootxml = doc.createElement("conduit-application") | random_line_split |
SyncSet.py | object
import logging
log = logging.getLogger("SyncSet")
import conduit
import conduit.Conduit as Conduit
import conduit.Settings as Settings
import conduit.XMLSerialization as XMLSerialization
SETTINGS_VERSION = XMLSerialization.Settings.XML_VERSION
class SyncSet(gobject.GObject):
| self.moduleManager.connect("dataprovider-available", self.on_dataprovider_available_unavailable)
self.moduleManager.connect("dataprovider-unavailable", self.on_dataprovider_available_unavailable)
# FIXME: temporary hack - need to let factories know about this factory :-\!
self.moduleMa... | """
Represents a group of conduits
"""
__gsignals__ = {
#Fired when a new instantiatable DP becomes available. It is described via
#a wrapper because we do not actually instantiate it till later - to save memory
"conduit-added" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [
... | identifier_body |
SamplePlugin.js | not a real plugin.</strong>
*
* Plugins are registered based on file extension, or supported preload types, which are defined as constants on
* the {{#crossLink "LoadQueue"}}{{/crossLink}} class. Available load types are:
* <ul>
* <li>binary ({{#crossLink "LoadQueue/BINARY:property"}}{{/crossLink}})</li>... |
// Tell PreloadJS to continue normally
if (options.doNothing) { return true; }
// Modify the LoadItem
loadItem.id = "newId";
loadItem.completeHandler = createjs.proxy(s.fileCompleteHandler, s);
// Return a new loader. This is an advanced usage, similar to what SoundJS does.
var loader = new createjs.I... | { return false; } | conditional_block |
SamplePlugin.js | is not a real plugin.</strong>
*
* Plugins are registered based on file extension, or supported preload types, which are defined as constants on
* the {{#crossLink "LoadQueue"}}{{/crossLink}} class. Available load types are:
* <ul>
* <li>binary ({{#crossLink "LoadQueue/BINARY:property"}}{{/crossLink}})</... | * fire when it matches the type.
*
* @method getPreloadHandlers
* @return {Object} An object defining a callback, type handlers, and extension handlers (see description)
*/
s.getPreloadHandlers = function () {
return {
callback: s.preloadHandler, // Proxy the method to maintain scope
types: ["image"]... | * }
* }
*
* If a plugin provides both "type" and "extension" handlers, the type handler will take priority, and will only
* fire once per file. For example if you have a handler for type=sound, and for extension=mp3, the callback will | random_line_split |
LanguageMenu.js | (function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["Handlebars"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work wit... |
}(this, function (Handlebars) {
return { "renderState":Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
return "<ul class=\"dropdown-content blue-grey white-text\">\n <li class=\"divider\"></li>\n <li><a lang=\"en\" href=\"javascript:false;\" c... | {
root['Languagemenu'] = factory(root["Handlebars"]);
} | conditional_block |
LanguageMenu.js | (function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["Handlebars"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work wit... | return { "renderState":Handlebars.template({"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
return "<ul class=\"dropdown-content blue-grey white-text\">\n <li class=\"divider\"></li>\n <li><a lang=\"en\" href=\"javascript:false;\" class=\"white-text\">English / Engl... | }(this, function (Handlebars) {
| random_line_split |
about_method_bindings.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
def function():
return "pineapple"
def function2():
return "tractor"
class Class(object):
def method(self):
return "parrot"
class AboutMethodBindings(Koan):
def test_methods_are_bound_to_an_object(self):
obj... | # owner_type = cls
self.assertEqual('BoundClass', bound_obj.__class__.__name__)
self.assertEqual('AboutMethodBindings', binding_owner.__class__.__name__)
self.assertEqual(AboutMethodBindings, owner_type)
# ------------------------------------------------------------------
cl... | # Look at BoundClass.__get__():
# bound_obj = self
# binding_owner = obj | random_line_split |
about_method_bindings.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
def function():
return "pineapple"
def function2():
return "tractor"
class Class(object):
def method(self):
return "parrot"
class AboutMethodBindings(Koan):
def test_methods_are_bound_to_an_object(self):
obj... | (self):
obj = Class()
self.assertEqual('parrot', obj.method())
self.assertEqual('parrot', obj.method.im_func(obj))
def test_functions_have_attributes(self):
self.assertEqual(31, len(dir(function)))
self.assertEqual(True, dir(function) == dir(Class.method.im_func))
def t... | test_methods_are_also_bound_to_a_function | identifier_name |
about_method_bindings.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
def function():
return "pineapple"
def function2():
return "tractor"
class Class(object):
def method(self):
return "parrot"
class AboutMethodBindings(Koan):
def test_methods_are_bound_to_an_object(self):
obj... |
def test_inner_functions_are_unbound(self):
function2.get_fruit = function
try:
cls = function2.get_fruit.im_self
except AttributeError as ex:
self.assertMatch('object has no attribute', ex[0])
# -----------------------------------------------------------------... | function2.get_fruit = function
self.assertEqual('pineapple', function2.get_fruit()) | identifier_body |
Block.js | /**
* Copyright © 2009-2012 A. Matías Quezada
*/
use('sassmine').on(function(sas) {
var Block = Class.extend({
constructor: function(message, code) {
this.base();
this.message = message;
this.code = code;
this.before = [];
this.after = [];
},
execute: function() {
this.code.call(null, sa... | }
});
sas.Spec = sas.Suite = Block.extend();
}); | this.after[i].call(null, sas); | random_line_split |
courses.client.routes.js | 'use strict';
//Setting up route
angular.module('courses').config(['$stateProvider',
function($stateProvider) {
// Courses state routing
$stateProvider.
state('listCourses', {
url: '/courses',
templateUrl: 'modules/courses/views/list-courses.client.view.html'
}).
state('createCourse', {
url: '/cour... | templateUrl: 'modules/courses/views/quicesPorCurso-course.client.view.html'
});
}
]); | url: '/courses/:courseId/edit',
templateUrl: 'modules/courses/views/edit-course.client.view.html'
}).
state('quicesPorCurso', {
url: '/quicesPorCurso', | random_line_split |
debugging.py | #!/usr/bin/env python3
# coding=utf-8
"""
This module, debugging.py, will contain code related to debugging (such as printing error messages).
"""
#import sys
#sys.path.insert(0, '/home/dev_usr/urbtek')
#from universal_code import system_operations as so
class MyException(Exception):
"""
Just something useful to ... | (self, message):
super(ParameterException, self).__init__(message)
class AbstractMethodNotImplementedException(Exception):
"""
A custom exception for when a function gets called that hasn't been set in a child class.
"""
def __init(self, message):
super(AbstractMethodNotImplementedException, self).__init__(me... | __init__ | identifier_name |
debugging.py | #!/usr/bin/env python3
# coding=utf-8
"""
This module, debugging.py, will contain code related to debugging (such as printing error messages).
"""
#import sys
#sys.path.insert(0, '/home/dev_usr/urbtek')
#from universal_code import system_operations as so
class MyException(Exception):
"""
Just something useful to ... | class AbstractMethodNotImplementedException(Exception):
"""
A custom exception for when a function gets called that hasn't been set in a child class.
"""
def __init(self, message):
super(AbstractMethodNotImplementedException, self).__init__(message)
def raise_exception(exception, message):
raise exception(mess... | random_line_split | |
debugging.py | #!/usr/bin/env python3
# coding=utf-8
"""
This module, debugging.py, will contain code related to debugging (such as printing error messages).
"""
#import sys
#sys.path.insert(0, '/home/dev_usr/urbtek')
#from universal_code import system_operations as so
class MyException(Exception):
"""
Just something useful to ... |
else:
print_text_with_color(termination_message, TextColors.WARNING, '')
if not termination_message.endswith('.'):
print_text_with_color('. The program will now terminate.', TextColors.FAIL)
else:
print_text_with_color(' The program will now terminate.', TextColors.FAIL)
exit()
| print_text_with_color('Program termination has been initiated, good bye!', TextColors.FAIL) | conditional_block |
debugging.py | #!/usr/bin/env python3
# coding=utf-8
"""
This module, debugging.py, will contain code related to debugging (such as printing error messages).
"""
#import sys
#sys.path.insert(0, '/home/dev_usr/urbtek')
#from universal_code import system_operations as so
class MyException(Exception):
"""
Just something useful to ... |
def print_text_with_color(text, color, end=None):
if end is None:
print(color + text + TextColors.ENDC + '\n')
else:
print(color + text + TextColors.ENDC, end='')
def terminate(termination_message=''):
if termination_message is '':
print_text_with_color('Program termination has been initiated, good bye!', T... | HEADER = '\033[95m'
OK_BLUE = '\033[94m'
OK_GREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m' | identifier_body |
drop.ts | import { Mutable } from '../shared/Mutable';
import { TapFn } from '../shared/Function';
import { Result, Ok, Err } from './Result';
import { asMutResult } from './asMut';
type MutOk<T> = Mutable<Ok<T>>;
type MutErr<E> = Mutable<Err<E>>;
type MutResult<T, E> = MutOk<T> | MutErr<E>;
function noop<T, E>(_input: MutResu... |
}
/**
* The _okMutator_ is called if _v_ is `Ok<T>`.
*
* This function allows you to cut the reference to the contain value from the inputted _v_.
* However, it would be unsafe operation if you do some more operation after this.
* For example, you can write the following code.
*
* ```javascript
* co... | {
errMutator(mutable);
} | conditional_block |
drop.ts | import { Mutable } from '../shared/Mutable';
import { TapFn } from '../shared/Function';
import { Result, Ok, Err } from './Result';
import { asMutResult } from './asMut';
type MutOk<T> = Mutable<Ok<T>>;
type MutErr<E> = Mutable<Err<E>>;
type MutResult<T, E> = MutOk<T> | MutErr<E>;
function noop<T, E>(_input: MutResu... | *
* Compared to Rust, JavaScript does not have ownership semantics in language
* and this API is designed to use as a destructor or similar fashions.
* So if you call this for same object more than once, your code might contain "double free" problem.
*/
export function unsafeDropOkForResult<T, E>(v: Result<T, E... | * ``` | random_line_split |
drop.ts | import { Mutable } from '../shared/Mutable';
import { TapFn } from '../shared/Function';
import { Result, Ok, Err } from './Result';
import { asMutResult } from './asMut';
type MutOk<T> = Mutable<Ok<T>>;
type MutErr<E> = Mutable<Err<E>>;
type MutResult<T, E> = MutOk<T> | MutErr<E>;
function noop<T, E>(_input: MutResu... |
/**
* The _errMutator_ is called if _v_ is `Err<E>`.
*
* This function allows you to cut the reference to the contain value from the inputted _v_.
* However, it would be unsafe operation if you do some more operation after this.
* For example, you can write the following code.
*
* ```javascript
* co... | {
return unsafeDropBothForResult(v, okMutator, noop);
} | identifier_body |
drop.ts | import { Mutable } from '../shared/Mutable';
import { TapFn } from '../shared/Function';
import { Result, Ok, Err } from './Result';
import { asMutResult } from './asMut';
type MutOk<T> = Mutable<Ok<T>>;
type MutErr<E> = Mutable<Err<E>>;
type MutResult<T, E> = MutOk<T> | MutErr<E>;
function noop<T, E>(_input: MutResu... | <T, E>(
v: Result<T, E>,
okMutator: TapFn<MutOk<T>>,
errMutator: TapFn<MutErr<E>>
): void {
const mutable = asMutResult(v);
if (mutable.ok) {
okMutator(mutable);
} else {
errMutator(mutable);
}
}
/**
* The _okMutator_ is called if _v_ is `Ok<T>`.
*
* This function allow... | unsafeDropBothForResult | identifier_name |
test_reader.py | from pixie.vm.reader import read, StringReader
from pixie.vm.object import Object
from pixie.vm.cons import Cons
from pixie.vm.numbers import Integer
from pixie.vm.symbol import symbol, Symbol
from pixie.vm.persistent_vector import PersistentVector
import pixie.vm.rt as rt
import unittest
data = {u"(1 2)": (1, 2,),
... |
elif isinstance(to, int):
assert isinstance(frm, Integer)
assert frm._int_val == to
elif isinstance(to, Symbol):
assert isinstance(frm, Symbol)
assert frm._str == to._str
elif isinstance(to, list):
assert isinstance(frm, PersistentVe... | self._compare(frm.first(), x)
frm = frm.next() | conditional_block |
test_reader.py | from pixie.vm.reader import read, StringReader
from pixie.vm.object import Object
from pixie.vm.cons import Cons
from pixie.vm.numbers import Integer
from pixie.vm.symbol import symbol, Symbol
from pixie.vm.persistent_vector import PersistentVector
import pixie.vm.rt as rt
import unittest
data = {u"(1 2)": (1, 2,),
... | (unittest.TestCase):
def _compare(self, frm, to):
if isinstance(to, tuple):
assert isinstance(frm, Cons)
for x in to:
self._compare(frm.first(), x)
frm = frm.next()
elif isinstance(to, int):
assert isinstance(frm, Integer)
... | TestReader | identifier_name |
test_reader.py | from pixie.vm.reader import read, StringReader
from pixie.vm.object import Object
from pixie.vm.cons import Cons
from pixie.vm.numbers import Integer
from pixie.vm.symbol import symbol, Symbol
from pixie.vm.persistent_vector import PersistentVector
import pixie.vm.rt as rt
import unittest
data = {u"(1 2)": (1, 2,),
... | assert isinstance(frm, Integer)
assert frm._int_val == to
elif isinstance(to, Symbol):
assert isinstance(frm, Symbol)
assert frm._str == to._str
elif isinstance(to, list):
assert isinstance(frm, PersistentVector)
for x in range(l... | frm = frm.next()
elif isinstance(to, int): | random_line_split |
test_reader.py | from pixie.vm.reader import read, StringReader
from pixie.vm.object import Object
from pixie.vm.cons import Cons
from pixie.vm.numbers import Integer
from pixie.vm.symbol import symbol, Symbol
from pixie.vm.persistent_vector import PersistentVector
import pixie.vm.rt as rt
import unittest
data = {u"(1 2)": (1, 2,),
... | else:
raise Exception("Don't know how to handle " + str(type(to)))
def test_forms(self):
for s in data:
tst = data[s]
result = read(StringReader(s), True)
assert isinstance(result, Object)
self._compare(result, tst)
| if isinstance(to, tuple):
assert isinstance(frm, Cons)
for x in to:
self._compare(frm.first(), x)
frm = frm.next()
elif isinstance(to, int):
assert isinstance(frm, Integer)
assert frm._int_val == to
elif isinstance(to, Sym... | identifier_body |
TimePicker.js | {
name: 'data',
postSet: function(old, nu) {
if (!nu) return;
var h = nu.getHours();
if (h < 12) {
this.amPM = 'AM';
this.hours = h === 0 ? 12 : h;
} else {
this.amPM = 'PM';
this.hours = h === 12 ? 12 : h - 12;
}
var m... | random_line_split | ||
TimePicker.js | set to the
current time.</p>
*/},
properties: [
{
name: 'data',
postSet: function(old, nu) {
if (!nu) return;
var h = nu.getHours();
if (h < 12) {
this.amPM = 'AM';
this.hours = h === 0 ? 12 : h;
} else {
this.amPM = 'PM';
... |
}
},
{
name: 'dragMove',
code: function(x, y) {
var tx = x - this.faceE.el().offsetLeft;
var ty = y - this.faceE.el().offsetTop;
// Draw two concentric circles with radii of 135 and 90 respectively.
// Only drag locations inside the gap between them actually c... | {
this.showHours = false;
} | conditional_block |
weak_lang_items.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | /// Checks the crate for usage of weak lang items, returning a vector of all the
/// language items required by this crate, but not defined yet.
pub fn check_crate(krate: &ast::Crate,
sess: &Session,
items: &mut lang_items::LanguageItems) {
// These are never called by user cod... | random_line_split | |
stage.ts | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | extends ValidatableMixin {
type: Stream<ApprovalType> = stream();
state: (value?: boolean) => boolean;
//authorization must be present for server side validations
//even though it's not editable from the create pipeline page
authorization: Stream<any> = stream({});
constructor() {
super();
Valida... | Approval | identifier_name |
stage.ts | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
import JsonUtils from "helpers/json_utils";
import {Stream} from "mithril/stream";
import * as stream from "mithril/stream";
import {ValidatableMixin} from "models/mixins/new_validatable_mixin";
import {Job} from "./job";
import {NameableSet} from "./nameable_set";
enum ApprovalType { success = "success", manual = "m... | * See the License for the specific language governing permissions and
* limitations under the License.
*/ | random_line_split |
stage.ts | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
return ApprovalType.success === this.type();
};
}
}
export class Stage extends ValidatableMixin {
name: Stream<string>;
approval: Stream<Approval> = stream(new Approval());
jobs: Stream<NameableSet<Job>>;
constructor(name: string, jobs: Job[]) {
super();
ValidatableMixin.call(this);
... | {
this.type(value ? ApprovalType.success : ApprovalType.manual);
} | conditional_block |
lib.rs | extern crate log;
extern crate flexi_logger;
extern crate ansi_term;
extern crate wrust_types;
extern crate wrust_conf;
pub mod conf;
use log::{LogLevel, LogRecord};
use wrust_types::{Error, Result};
use wrust_conf::{Conf, FromConf};
use conf::{LogConf, LogDevice};
/// Initialize logging system using configuration ... | {
match record.level() {
LogLevel::Error => format!("[!] {} in {} ({}:{})", record.args(), record.location().module_path(), record.location().file(), record.location().line()),
LogLevel::Warn => format!("[W] {} in {} ({}:{})", record.args(), record.location().module_path(), record.location().file(), record.locatio... | identifier_body | |
lib.rs | extern crate log;
extern crate flexi_logger;
extern crate ansi_term;
extern crate wrust_types;
extern crate wrust_conf;
pub mod conf;
use log::{LogLevel, LogRecord};
use wrust_types::{Error, Result};
use wrust_conf::{Conf, FromConf};
use conf::{LogConf, LogDevice};
/// Initialize logging system using configuration ... | let mut flexi_config = LogConfig::new();
flexi_config.print_message = false;
flexi_config.duplicate_error = false;
flexi_config.duplicate_info = false;
// Setup flexi logger based on log device
match config.device {
LogDevice::Stderr(colorize) => {
flexi_config.format = if colorize {
colorized_format
... | random_line_split | |
lib.rs | extern crate log;
extern crate flexi_logger;
extern crate ansi_term;
extern crate wrust_types;
extern crate wrust_conf;
pub mod conf;
use log::{LogLevel, LogRecord};
use wrust_types::{Error, Result};
use wrust_conf::{Conf, FromConf};
use conf::{LogConf, LogDevice};
/// Initialize logging system using configuration ... | (config: &Conf, xpath: &str) -> Result<()> {
// Initialize logger
match LogConf::from_conf(&config, xpath) {
Ok(settings) => init(settings),
Err(err) => Error::new("Logger configuration failed").because(err).result()
}
}
fn colorized_format(record: &LogRecord) -> String {
use ansi_term::Colour::{Red, Green, Y... | init_from_conf | identifier_name |
parse_args.py | """
atomorder/parse_args.py
Parses command line arguments and overwrites setting defaults
"""
from . import settings
import argparse
import sys
| description = ""
epilog = ""
parser = argparse.ArgumentParser(
description = description,
formatter_class = argparse.RawDescriptionHelpFormatter,
epilog = epilog)
parser = argparse.ArgumentParser(description='Fit probability density functions to data-files')
parser.add_argument('-r', '--reacta... | random_line_split | |
index.js | var express = require('express')
, app = express()
, server = require('http').Server(app)
//, bodyParser = require('body-parser')
, config = require('./lib/config')
;
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: true }));
// Web interface
//app.get('/user/:id', users.userPage);
... | // Last wall of defense against a bad crash
process.on('uncaughtException', function (err) {
console.log('Caught an uncaught exception, I should probably send an email or something');
console.log(err);
if (err.stack) { console.log(err.stack); }
});
// Launch server
server.listen(config.serverPort); | });
| random_line_split |
index.js | var express = require('express')
, app = express()
, server = require('http').Server(app)
//, bodyParser = require('body-parser')
, config = require('./lib/config')
;
//app.use(bodyParser.json());
//app.use(bodyParser.urlencoded({ extended: true }));
// Web interface
//app.get('/user/:id', users.userPage);
... |
});
// Launch server
server.listen(config.serverPort);
| { console.log(err.stack); } | conditional_block |
nested-enum-same-names.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 ... |
}
pub fn main() {}
| {
enum Panic { Common };
} | identifier_body |
nested-enum-same-names.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 ... | name, rustc gives the same LLVM symbol for the two of them and fails,
as it does not include the method name in the symbol name.
*/
pub struct Foo;
impl Foo {
pub fn foo() {
enum Panic { Common };
}
pub fn bar() {
enum Panic { Common };
}
}
pub fn main() {} |
If you have two methods in an impl block, each containing an enum
(with the same name), each containing at least one value with the same | random_line_split |
nested-enum-same-names.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 ... | () {
enum Panic { Common };
}
}
pub fn main() {}
| bar | identifier_name |
chart.js | 'use strict';
/* Controllers */
app
// Flot Chart controller
.controller('FlotChartDemoCtrl', ['$scope', function($scope) {
$scope.d = [ [1,6.5],[2,6.5],[3,7],[4,8],[5,7.5],[6,7],[7,6.8],[8,7],[9,7.2],[10,7],[11,6.8],[12,7] ];
$scope.d0_1 = [ [0,7],[1,6.5],[2,12.5],[3,7],[4,9],[5,6],[6,11],[7,6.5],[8,8]... | $scope.d2 = [];
for (var i = 0; i < 20; ++i) {
$scope.d2.push([i, Math.round( Math.sin(i)*100)/100] );
}
$scope.d3 = [
{ label: "iPhone5S", data: 40 },
{ label: "iPad Mini", data: 10 },
{ label: "iPad Mini Retina", data: 20 },
{ label: "iPhone4S", data: 12 },
{... | random_line_split | |
grid.ts | import {
Component, Input, Output, EventEmitter, ViewChild, QueryList,
OnInit, AfterContentInit, Inject, Optional, ContentChild, ContentChildren
} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { format } from 'date-fns';
import { MatSort, MatPaginator, PageEvent } from '@ang... | }
private _changePageSizeData() {
if (this.settingsProvider != null) {
this.settingsProvider.put('gridPageSize', this.pageSize.getValue());
}
}
private _getPageSettingValue() {
if (this.settingsProvider != null) {
return this.settingsProvider.get('gridPag... | this.settingsProvider.put('gridPage', this.page.getValue());
}
| conditional_block |
grid.ts | import {
Component, Input, Output, EventEmitter, ViewChild, QueryList,
OnInit, AfterContentInit, Inject, Optional, ContentChild, ContentChildren
} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { format } from 'date-fns';
import { MatSort, MatPaginator, PageEvent } from '@ang... | private _handleRequestDataError(error) {
if (this.onRequestDataError) {
this.onRequestDataError.emit(error);
}
}
private _transformToObj(columns: ColumnModel[], data: any) {
const obj = {};
columns.forEach((column, key) => {
obj[column.Name] = data[ke... | // transform direction values to strings
const result = this.http.request<GridResponse>(
this.requestMethod || 'POST',
this.dataUrl,
{
body: tbRequest,
withCredentials: false,
responseType: 'json'
}
)... | identifier_body |
grid.ts | import {
Component, Input, Output, EventEmitter, ViewChild, QueryList,
OnInit, AfterContentInit, Inject, Optional, ContentChild, ContentChildren
} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { format } from 'date-fns';
import { MatSort, MatPaginator, PageEvent } from '@ang... | throw Error('Invalid column name');
}
this.columns.next(ColumnModel.sortColumnArray(columnName, value, true));
this.refresh();
}
filterByColumnName(columnName: string) {
const value = this.columns.getValue();
const columnModel = value.find(c => c.Name === c... | random_line_split | |
grid.ts | import {
Component, Input, Output, EventEmitter, ViewChild, QueryList,
OnInit, AfterContentInit, Inject, Optional, ContentChild, ContentChildren
} from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { format } from 'date-fns';
import { MatSort, MatPaginator, PageEvent } from '@ang... | mplements OnInit, AfterContentInit {
// data is just observable and children can't push
private _dataStream = new BehaviorSubject([]);
private _totalRecords = new BehaviorSubject(0);
// TODO: Check we really need to push internally, only
private _pageInfo = new BehaviorSubject(new GridPageInfo());
... | idComponent i | identifier_name |
webgluniformlocation.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUn... |
pub fn new(global: GlobalRef, id: u32) -> Temporary<WebGLUniformLocation> {
reflect_dom_object(box WebGLUniformLocation::new_inherited(id), global, WebGLUniformLocationBinding::Wrap)
}
}
pub trait WebGLUniformLocationHelpers {
fn get_id(&self) -> u32;
}
impl<'a> WebGLUniformLocationHelpers for J... | {
WebGLUniformLocation {
reflector_: Reflector::new(),
id: id,
}
} | identifier_body |
webgluniformlocation.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUn... | {
reflector_: Reflector,
id: u32,
}
impl WebGLUniformLocation {
fn new_inherited(id: u32) -> WebGLUniformLocation {
WebGLUniformLocation {
reflector_: Reflector::new(),
id: id,
}
}
pub fn new(global: GlobalRef, id: u32) -> Temporary<WebGLUniformLocation> {
... | WebGLUniformLocation | identifier_name |
webgluniformlocation.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/. */
// https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl
use dom::bindings::codegen::Bindings::WebGLUn... | }
} | impl<'a> WebGLUniformLocationHelpers for JSRef<'a, WebGLUniformLocation> {
fn get_id(&self) -> u32 {
self.id | random_line_split |
deriving-non-type.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
const c: usize = 0us;
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
mod m { }
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
extern "C" { }
#[derive(PartialEq)] //... | #[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
static s: usize = 0us; | random_line_split |
deriving-non-type.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ;
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
trait T { }
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
impl S { }
#[derive(PartialEq)] //~ ERROR: `derive` may only be applied to structs and enums
impl T for S { }
#[derive(PartialEq)] //~ ERR... | S | identifier_name |
lib.rs | //
// Copyright (c) ShuYu Wang <andelf@gmail.com>, Feather Workshop and Pirmin Kalberer. All rights reserved.
//
//! An extension to rust-postgres, adds support for PostGIS.
//!
//! - PostGIS type helper
//! - GCJ02 support (used offically in Mainland China)
//! - Tiny WKB (TWKB) support
//!
//! ```rust,no_run
//! use... | //! let route = row.try_get::<_, Option<ewkb::LineString>>("route");
//! match route {
//! Ok(Some(geom)) => { println!("{:?}", geom) }
//! Ok(None) => { /* Handle NULL value */ }
//! Err(err) => { println!("Error: {}", err) }
//! }
//! ```
pub mod error;
mod types;
pub use types::{LineString, MultiLineStr... | //! # let row = rows.first().unwrap(); | random_line_split |
BrunchDiningOutlined.js | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M2 21.5c0 .28.22.5.49.5h13.02c.27 0 .49-.22.49-.5V20H2v1.5zM15.5 16H11v-2H7v2H2.5c-.28 0-.5.22-.5.5V18h14v-1.5c0-.28-.22-.5-.5-.5zm4.97-.55c.99-1.07 1.53-2.48 1.53-3.94V2h-6v9.47c0 1.48.58 2.92 1... | , 'BrunchDiningOutlined'); | random_line_split | |
pam.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the Licen... | // Probably the password, since it doesn't want us to echo it.
PamMessageStyle::PROMPT_ECHO_OFF => {
response.resp = strdup(info.password);
}
PamMessageStyle::ERROR_MSG => {
result = PamReturnCode::CONV_ERR;
error!("{}", String::from_utf8_lossy(CStr::from_ptr(message.msg).to_bytes()));
... | response.resp = strdup(info.user);
}
| conditional_block |
pam.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the Licen... |
PamMessageStyle::ERROR_MSG => {
result = PamReturnCode::CONV_ERR;
error!("{}", String::from_utf8_lossy(CStr::from_ptr(message.msg).to_bytes()));
}
PamMessageStyle::TEXT_INFO => {
info!("{}", String::from_utf8_lossy(CStr::from_ptr(message.msg).to_bytes()));
}
}
}
if result != Pam... | unsafe {
let info = &*(data as *mut Info as *const Info);
let mut result = PamReturnCode::SUCCESS;
*responses = calloc(count as size_t, mem::size_of::<PamResponse>() as size_t).as_mut().unwrap() as *mut _ as *mut _;
for i in 0 .. count as isize {
let message = &**messages.offset(i);
let response... | identifier_body |
pam.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the Licen... |
accounts: bool,
}
pub fn new(_config: toml::value::Table) -> error::Result<Auth> {
Ok(Auth {
accounts: cfg!(feature = "auth-pam-accounts"),
})
}
struct Info {
user: *const c_char,
password: *const c_char,
}
impl Authenticate for Auth {
fn authenticate(&mut self, user: &str, password: &str) -> error::Res... | th { | identifier_name |
pam.rs | // Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co
//
// This file is part of screenruster.
//
// screenruster is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the Licen... |
(set_item $ty:ident => $value:expr) => (
pam!(checked pam_set_item(&mut *handle.assume_init(), PamItemType::$ty as i32, strdup($value.as_ptr() as *const _) as *mut _))
);
(authenticate) => (
pam!(checked pam_authenticate(&mut *handle.assume_init(), PamFlag::NONE as i32))
);
(end) => (
... |
(start) => (
pam!(check pam_start(b"screenruster\x00".as_ptr() as *const _, ptr::null(), &conv, handle.as_mut_ptr() as *mut *const _))
); | random_line_split |
factor.rs | 2020 nicoo <nicoo@debian.org>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt;
use crate::numeric::{Arithmetic, Montgomery};
use crate::{miller_rabin, rho, table};
type... | me: u64) {
self.add(prime, 1);
}
#[cfg(test)]
fn product(&self) -> u64 {
self.0.borrow().product()
}
}
impl fmt::Display for Factors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let v = &mut (self.0).borrow_mut().0;
v.sort_unstable();
for (p... | pri | identifier_name |
factor.rs | 020 nicoo <nicoo@debian.org>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt;
use crate::numeric::{Arithmetic, Montgomery};
use crate::{miller_rabin, rho, table};
type ... | // We are overflowing u64, retry
continue 'attempt;
}
}
}
return f;
}
}
}
#[cfg(test)]
impl quickcheck::Arbitrary for Factors {
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
factor(u64::arbitrary... | f.push(n);
g = h;
} else {
| conditional_block |
factor.rs | 2020 nicoo <nicoo@debian.org>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt;
use crate::numeric::{Arithmetic, Montgomery};
use crate::{miller_rabin, rho, table};
type... | // Repeat the test 20 times, as it only fails some fraction
// of the time.
assert!(factor(pseudoprime).product() == pseudoprime);
}
}
quickcheck! {
fn factor_recombines(i: u64) -> bool {
i == 0 || factor(i).product() == i
}
fn re... | // miller_rabbin::Result::Composite
let pseudoprime = 17179869183;
for _ in 0..20 { | random_line_split |
factor.rs | 2020 nicoo <nicoo@debian.org>
// *
// * For the full copyright and license information, please view the LICENSE file
// * that was distributed with this source code.
use smallvec::SmallVec;
use std::cell::RefCell;
use std::fmt;
use crate::numeric::{Arithmetic, Montgomery};
use crate::{miller_rabin, rho, table};
type... | sh(&mut self, prime: u64) {
self.add(prime, 1);
}
#[cfg(test)]
fn product(&self) -> u64 {
self.0.borrow().product()
}
}
impl fmt::Display for Factors {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let v = &mut (self.0).borrow_mut().0;
v.sort_unstable()... | _assert!(miller_rabin::is_prime(prime));
self.0.borrow_mut().add(prime, exp);
}
pub fn pu | identifier_body |
scopetools.js | // scopetools.js
// MIT licensed, see LICENSE file
// Copyright (c) 2013-2015 Olov Lassus <olov.lassus@gmail.com>
"use strict";
const assert = require("assert");
const traverse = require("ordered-ast-traverse");
const Scope = require("./scope");
const is = require("simple-is");
module.exports = {
set... | (node) {
return isForInOf(node) && node.left.type === "VariableDeclaration" && isConstLet(node.left.kind);
}
function isForInOf(node) {
return node.type === "ForInStatement" || node.type === "ForOfStatement";
}
function isFunction(node) {
return node.type === "FunctionDeclaration" || node.type ==... | isForInOfWithConstLet | identifier_name |
scopetools.js | // scopetools.js
// MIT licensed, see LICENSE file
// Copyright (c) 2013-2015 Olov Lassus <olov.lassus@gmail.com>
"use strict";
const assert = require("assert");
const traverse = require("ordered-ast-traverse");
const Scope = require("./scope");
const is = require("simple-is");
module.exports = {
set... | node.declarations.forEach(function(declarator) {
const name = declarator.id.name;
node.$scope.add(name, node.kind, declarator.id, declarator.range[1]);
});
} else if (isFunction(node)) {
// Function is a scope, with params in it
// There's no block-sco... |
} else if (node.type === "VariableDeclaration") {
// Variable declarations names goes in current scope
| random_line_split |
scopetools.js | // scopetools.js
// MIT licensed, see LICENSE file
// Copyright (c) 2013-2015 Olov Lassus <olov.lassus@gmail.com>
"use strict";
const assert = require("assert");
const traverse = require("ordered-ast-traverse");
const Scope = require("./scope");
const is = require("simple-is");
module.exports = {
set... |
}
node.params.forEach(function(param) {
node.$scope.add(param.name, "param", param, null);
});
} else if (isForWithConstLet(node) || isForInOfWithConstLet(node)) {
// For(In/Of) loop with const|let declaration is a scope, with declaration in it
// Ther... | {
assert(false);
} | conditional_block |
scopetools.js | // scopetools.js
// MIT licensed, see LICENSE file
// Copyright (c) 2013-2015 Olov Lassus <olov.lassus@gmail.com>
"use strict";
const assert = require("assert");
const traverse = require("ordered-ast-traverse");
const Scope = require("./scope");
const is = require("simple-is");
module.exports = {
set... |
function isForInOf(node) {
return node.type === "ForInStatement" || node.type === "ForOfStatement";
}
function isFunction(node) {
return node.type === "FunctionDeclaration" || node.type === "FunctionExpression";
}
function isReference(node) {
const parent = node.$parent;
return node.$ref... | {
return isForInOf(node) && node.left.type === "VariableDeclaration" && isConstLet(node.left.kind);
} | identifier_body |
html.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateEleme... | (&mut self) {
self.inner.set_plaintext_state();
}
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for HtmlTokenizer<TreeBuilder<JS<Node>, Sink>> {
unsafe fn trace(&self, trc: *mut JSTracer) {
struct Tracer(*mut JSTracer);
let tracer = Tracer(trc);
impl HtmlTracer for Tracer {
... | set_plaintext_state | identifier_name |
html.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateEleme... |
pub fn set_plaintext_state(&mut self) {
self.inner.set_plaintext_state();
}
}
#[allow(unsafe_code)]
unsafe impl JSTraceable for HtmlTokenizer<TreeBuilder<JS<Node>, Sink>> {
unsafe fn trace(&self, trc: *mut JSTracer) {
struct Tracer(*mut JSTracer);
let tracer = Tracer(trc);
... | {
&self.inner.sink.sink.base_url
} | identifier_body |
html.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateEleme... | ;
for handle in children {
(&*handle).serialize(serializer, IncludeNode)?;
}
if traversal_scope == IncludeNode {
serializer.end_elem(name.clone())?;
}
Ok(())
},
(ChildrenOnl... | {
node.children()
} | conditional_block |
html.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/. */
#![allow(unrooted_must_root)]
use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateEleme... | tree_builder.trace_handles(&tracer);
tree_builder.sink.trace(trc);
}
}
impl<'a> Serialize for &'a Node {
fn serialize<S: Serializer>(&self, serializer: &mut S,
traversal_scope: TraversalScope) -> io::Result<()> {
let node = *self;
match (traversal... | unsafe { node.trace(self.0); }
}
}
let tree_builder = &self.sink; | random_line_split |
index.js | /**!
* koa-body-parser - index.js
* Copyright(c) 2014
* MIT Licensed
*
* Authors:
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
* fengmk2 <m@fengmk2.com> (http://fengmk2.com)
*/
'use strict';
/**
* Module dependencies.
*/
var parse = require('co-body');
var copy = require('copy-to');
/**
* @... |
return {};
}
};
function formatOptions(opts, type) {
var res = {};
copy(opts).to(res);
res.limit = opts[type + 'Limit'];
return res;
}
function extendType(original, extend) {
if (extend) {
if (!Array.isArray(extend)) {
extend = [extend];
}
extend.forEach(function (extend) {
or... | {
return yield parse.text(ctx, textOpts) || '';
} | conditional_block |
index.js | /**!
* koa-body-parser - index.js
* Copyright(c) 2014
* MIT Licensed
*
* Authors:
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
* fengmk2 <m@fengmk2.com> (http://fengmk2.com)
*/
'use strict';
/**
* Module dependencies.
*/
var parse = require('co-body');
var copy = require('copy-to');
/**
* @... |
function checkEnable(types, type) {
return types.indexOf(type) >= 0;
}
| {
if (extend) {
if (!Array.isArray(extend)) {
extend = [extend];
}
extend.forEach(function (extend) {
original.push(extend);
});
}
} | identifier_body |
index.js | /**!
* koa-body-parser - index.js
* Copyright(c) 2014
* MIT Licensed
*
* Authors:
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
* fengmk2 <m@fengmk2.com> (http://fengmk2.com)
*/
'use strict';
/**
* Module dependencies.
*/
var parse = require('co-body');
var copy = require('copy-to');
/**
* @... | }
return {};
}
};
function formatOptions(opts, type) {
var res = {};
copy(opts).to(res);
res.limit = opts[type + 'Limit'];
return res;
}
function extendType(original, extend) {
if (extend) {
if (!Array.isArray(extend)) {
extend = [extend];
}
extend.forEach(function (extend) {
... | if (enableText && ctx.request.is(textTypes)) {
return yield parse.text(ctx, textOpts) || ''; | random_line_split |
index.js | /**!
* koa-body-parser - index.js
* Copyright(c) 2014
* MIT Licensed
*
* Authors:
* dead_horse <dead_horse@qq.com> (http://deadhorse.me)
* fengmk2 <m@fengmk2.com> (http://fengmk2.com)
*/
'use strict';
/**
* Module dependencies.
*/
var parse = require('co-body');
var copy = require('copy-to');
/**
* @... | (opts, type) {
var res = {};
copy(opts).to(res);
res.limit = opts[type + 'Limit'];
return res;
}
function extendType(original, extend) {
if (extend) {
if (!Array.isArray(extend)) {
extend = [extend];
}
extend.forEach(function (extend) {
original.push(extend);
});
}
}
function c... | formatOptions | identifier_name |
hi.py | .quantities.spectrum import Spectrum
from marvin.utils.general.general import get_drpall_table
from marvin.utils.plot.scatter import plot as scatplot
from marvin import log
from .base import VACMixIn, VACTarget
def choose_best_spectrum(par1, par2, conf_thresh=0.1):
| programs = [par1['program'],par2['program']]
sel_high_snr = np.argmax([par1['snr'],par2['snr']])
sel_low_rms = np.argmin([par1['rms'],par2['rms']])
sel_low_conf = np.argmin([par1['conf_prob'],par2['conf_prob']])
#both detected
if (par1['snr'] > 0) & (par2['snr'] > 0):
if (par1['co... | '''choose optimal HI spectrum based on the following criteria:
(1) If both detected and unconfused, choose highest SNR
(2) If both detected and both confused, choose lower confusion prob.
(3) If both detected and one confused, choose non-confused
(4) If one non-confused detection and one non-detection, ... | identifier_body |
hi.py | .quantities.spectrum import Spectrum
from marvin.utils.general.general import get_drpall_table
from marvin.utils.plot.scatter import plot as scatplot
from marvin import log
from .base import VACMixIn, VACTarget
def choose_best_spectrum(par1, par2, conf_thresh=0.1):
'''choose optimal HI spectrum based on the follo... | (self,plateifu):
# download the vac from the SAS if it does not already exist locally
if not self.file_exists(self.summary_file):
self.summary_file = self.download_vac('mangahisum', path_params=self.path_params)
# Find all entries in summary file with this plate-ifu.
# Need... | set_program | identifier_name |
hi.py | .quantities.spectrum import Spectrum
from marvin.utils.general.general import get_drpall_table
from marvin.utils.plot.scatter import plot as scatplot
from marvin import log
from .base import VACMixIn, VACTarget
def choose_best_spectrum(par1, par2, conf_thresh=0.1):
'''choose optimal HI spectrum based on the follo... |
elif (par1['conf_prob'] > conf_thresh) & (par2['conf_prob'] > conf_thresh):
pick = sel_low_conf
#both nondetected
elif (par1['snr'] <= 0) & (par2['snr'] <= 0):
pick = sel_low_rms
#one detected
elif (par1['snr'] > 0) & (par2['snr'] <= 0):
if par1['conf_prob'] < conf... | pick = 1 | conditional_block |
hi.py | #
# Licensed under a 3-clause BSD license.
#
# @Author: Brian Cherinka
# @Date: 2018-10-11 17:51:43
# @Last modified by: Brian Cherinka
# @Last Modified time: 2018-11-29 17:23:15
from __future__ import print_function, division, absolute_import
import numpy as np
import astropy
import astropy.units as u
import mar... | # !usr/bin/env python
# -*- coding: utf-8 -*- | random_line_split | |
zip.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... | dir, name = path.split(completename)
self.filedata.append((dir, name)) | conditional_block | |
zip.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... |
def unit_iter(self):
"""Iterator over all the units in all the files in this zip file."""
for dirname, filename in self.file_iter():
strfile = wStringIO.StringIO(self.archive.read(path.join(dirname, filename)))
strfile.filename = filename
store = factory.getobje... | self.filename = filename
self.filedata = [] | identifier_body |
zip.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... | """Populate the internal file data."""
self.filedata = []
self.archive = ZipFile(self.filename)
for completename in self.archive.namelist():
dir, name = path.split(completename)
self.filedata.append((dir, name)) | #TODO: don't regenerate all the storage objects
for unit in store.unit_iter():
yield unit
def scanfiles(self): | random_line_split |
zip.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of t... | (self):
"""Iterator over all the units in all the files in this zip file."""
for dirname, filename in self.file_iter():
strfile = wStringIO.StringIO(self.archive.read(path.join(dirname, filename)))
strfile.filename = filename
store = factory.getobject(strfile)
... | unit_iter | identifier_name |
simpleWorker.nls.zh-cn.js | /*!-----------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Version: 0.5.3(793ede49d53dba79d39e52205f16321278f5183c)
* Released under the MIT license
* https://github.com/Microsoft/vscode/blob/master/LICENSE.txt
*-------------------------------------... | "Windows",
"控件",
"Shift",
"Alt",
"命令",
"Windows",
"Ctrl",
"Shift",
"Alt",
"命令",
"Windows",
],
"vs/base/common/severity": [
"错误",
"警告",
"信息",
]
}); | ],
"vs/base/common/keyCodes": [ | random_line_split |
events-mock.ts | // import { VREvent } from './event-type';
export var EVENTS =
[
{ "id": 1, "name" : "UBS Teambuilding event", "events":
[
{ "id": 11, "name": "Felcsut little train", "votes": [ 0, 0, 0 ] },
{ "id": 12, "name": "Lasertag", "votes": [ 0, 6, 0 ] },
{ "id": 13, "name": "Paintball", "votes": [ 0, 0,... | 'Filemon'
]
}
]; | random_line_split | |
device.py | from lxml import etree
from nxpy.interface import Interface
from nxpy.vlan import Vlan
from nxpy.flow import Flow
from util import tag_pattern
class Device(object):
# Singleton
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(
... | (self, netconf_config=False):
config = etree.Element("configuration")
device = etree.Element('system')
if self.name:
etree.SubElement(device, "host-name").text = self.name
if self.domain_name:
etree.SubElement(device, "domain-name").text = self.domain_name
... | export | identifier_name |
device.py | from lxml import etree
from nxpy.interface import Interface
from nxpy.vlan import Vlan
from nxpy.flow import Flow
from util import tag_pattern
class Device(object):
# Singleton
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(
... |
if nodeName_ == 'routing-options':
for node in child_:
childName_ = tag_pattern.match(node.tag).groups()[-1]
# *************** FLOW ****************
if childName_ == 'flow':
obj_ = Flow()
obj_.build(node)
... | obj_ = Vlan()
obj_.build(node)
self.vlans.append(obj_) | conditional_block |
device.py | from lxml import etree
from nxpy.interface import Interface
from nxpy.vlan import Vlan
from nxpy.flow import Flow
from util import tag_pattern
class Device(object):
# Singleton
_instance = None | if not cls._instance:
cls._instance = super(
Device, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self):
self.name = ''
self.domain_name = ''
self.interfaces = []
self.vlans = []
self.routing_options = []
... |
def __new__(cls, *args, **kwargs): | random_line_split |
device.py | from lxml import etree
from nxpy.interface import Interface
from nxpy.vlan import Vlan
from nxpy.flow import Flow
from util import tag_pattern
class Device(object):
# Singleton
| if self.domain_name:
etree.SubElement(device, "domain-name").text = self.domain_name
if len(device.getchildren()):
config.append(device)
interfaces = etree.Element('interfaces')
if len(self.interfaces):
for interface in self.interfaces:
... | _instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(
Device, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self):
self.name = ''
self.domain_name = ''
self.interfaces = []
... | identifier_body |
metering_rpc_agent_api.py | # Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Sylvain Afchain <sylvain.afchain@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... |
else:
cctxt = self.client.prepare(fanout=True)
cctxt.cast(context, method, routers=routers)
def router_deleted(self, context, router_id):
self._notification_fanout(context, 'router_deleted', router_id)
def routers_updated(self, context, routers):
if routers:
... | self._agent_notification(context, method, routers) | conditional_block |
metering_rpc_agent_api.py | # Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Sylvain Afchain <sylvain.afchain@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... |
def add_metering_label(self, context, routers):
self._notification(context, 'add_metering_label', routers)
def remove_metering_label(self, context, routers):
self._notification(context, 'remove_metering_label', routers)
| self._notification(context, 'update_metering_label_rules', routers) | identifier_body |
metering_rpc_agent_api.py | # Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Sylvain Afchain <sylvain.afchain@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... | (self, context, method, router_id):
LOG.debug(_('Fanout notify metering agent at %(topic)s the message '
'%(method)s on router %(router_id)s'),
{'topic': self.client.target.topic,
'method': method,
'router_id': router_id})
cctxt... | _notification_fanout | identifier_name |
metering_rpc_agent_api.py | # Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Sylvain Afchain <sylvain.afchain@enovance.com>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apach... |
def update_metering_label_rules(self, context, routers):
self._notification(context, 'update_metering_label_rules', routers)
def add_metering_label(self, context, routers):
self._notification(context, 'add_metering_label', routers)
def remove_metering_label(self, context, routers):
... | self._notification(context, 'routers_updated', routers) | random_line_split |
emit-appender.ts | import { LoggingEvent } from "log4js";
import { EventEmitter } from "events";
import { EMIT_APPENDER_EVENT_NAME } from "../../../constants";
function emitAppender(layout: Function, emitter: EventEmitter) {
const appender = (loggingEvent: LoggingEvent) => {
emitter.emit(EMIT_APPENDER_EVENT_NAME, {
loggingEvent,
... |
// create a new appender instance
return emitAppender(layout, config.emitter);
}
| {
layout = layouts.layout(config.layout.type, config.layout);
} | conditional_block |
emit-appender.ts | import { LoggingEvent } from "log4js";
import { EventEmitter } from "events";
import { EMIT_APPENDER_EVENT_NAME } from "../../../constants";
function emitAppender(layout: Function, emitter: EventEmitter) {
const appender = (loggingEvent: LoggingEvent) => {
emitter.emit(EMIT_APPENDER_EVENT_NAME, {
loggingEvent,
... | (
config: Log4JSEmitAppenderConfiguration,
layouts: any
) {
if (!config.emitter) {
throw new Error("Emitter must be passed to emit-appender");
}
if (!config.emitter.emit || typeof config.emitter.emit !== "function") {
throw new Error("The passed emitter must be instance of EventEmitter");
}
// the default ... | configure | identifier_name |
emit-appender.ts | import { LoggingEvent } from "log4js";
import { EventEmitter } from "events";
import { EMIT_APPENDER_EVENT_NAME } from "../../../constants"; | const appender = (loggingEvent: LoggingEvent) => {
emitter.emit(EMIT_APPENDER_EVENT_NAME, {
loggingEvent,
formattedMessage: layout(loggingEvent),
});
};
appender.shutdown = () => {
emitter.removeAllListeners(EMIT_APPENDER_EVENT_NAME);
};
return appender;
}
export function configure(
config: Log4JSE... |
function emitAppender(layout: Function, emitter: EventEmitter) { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.