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
argv.js
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.definePro...
argv = arrayify(argv); } else { argv = process.argv.slice(0); argv.splice(0, 2); } this.list = argv; } _createClass(Argv, [{ key: 'clear', value: function clear() { this.list.length = 0; } }, { key: 'expandOptionEqualsNotation', value: func...
function Argv(argv) { _classCallCheck(this, Argv); if (argv) {
random_line_split
cron_trigger.py
# coding=utf-8 ''' cron trigger @author: Huiyugeng ''' import datetime import trigger class CronTrigger(trigger.Trigger): def __init__(self, cron): trigger.Trigger.__init__(self, 0, 1); self.cron = cron def _is_match(self): parser = CronParser(self.cron) ...
def _add_to_set(self, start, end): result = [i for i in range(start, end + 1)] return result def _parse_month(self, value): months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"] for i in range(0, 12): value = value.rep...
random_line_split
cron_trigger.py
# coding=utf-8 ''' cron trigger @author: Huiyugeng ''' import datetime import trigger class CronTrigger(trigger.Trigger): def __init__(self, cron): trigger.Trigger.__init__(self, 0, 1); self.cron = cron def _is_match(self): parser = CronParser(self.cron) ...
return self._parse_integer(value, 1, 12); def _parse_day_of_week(self, value): day_of_weeks = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"] for i in range(0, 7): value = value.replace(day_of_weeks[i], str(i + 1)); return self._parse_integer(value, 1, 7); ...
value = value.replace(months[i], str(i + 1))
conditional_block
cron_trigger.py
# coding=utf-8 ''' cron trigger @author: Huiyugeng ''' import datetime import trigger class CronTrigger(trigger.Trigger): def __init__(self, cron): trigger.Trigger.__init__(self, 0, 1); self.cron = cron def _is_match(self): parser = CronParser(self.cron) ...
def _parse_day_of_week(self, value): day_of_weeks = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"] for i in range(0, 7): value = value.replace(day_of_weeks[i], str(i + 1)); return self._parse_integer(value, 1, 7); def _is_match(self, _date, _time): ...
months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"] for i in range(0, 12): value = value.replace(months[i], str(i + 1)) return self._parse_integer(value, 1, 12);
identifier_body
cron_trigger.py
# coding=utf-8 ''' cron trigger @author: Huiyugeng ''' import datetime import trigger class CronTrigger(trigger.Trigger): def __init__(self, cron): trigger.Trigger.__init__(self, 0, 1); self.cron = cron def _is_match(self): parser = CronParser(self.cron) ...
(self, cron): cron_item = cron.split(' ') if len(cron_item) == 6 or len(cron_item) == 7: self.second_set = self._parse_integer(cron_item[0], 0, 59) self.minute_set = self._parse_integer(cron_item[1], 0, 59) self.hour_set = self._parse_integer(cron_i...
__init__
identifier_name
errors.py
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2016 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to us...
class BadArgument(UserInputError): """Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command. """ pass class NoPrivateMessage(CommandError): """Exception raised when an operation does not work in private message contexts. """ pass c...
"""Exception raised when the command was passed too many arguments and its :attr:`Command.ignore_extra` attribute was not set to ``True``. """ pass
identifier_body
errors.py
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2016 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to us...
(CommandError): """The base exception type for errors that involve errors regarding user input. This inherits from :exc:`CommandError`. """ pass class CommandNotFound(CommandError): """Exception raised when a command is attempted to be invoked but no command under that name is found. ...
UserInputError
identifier_name
errors.py
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2016 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to us...
original The original exception that was raised. You can also get this via the ``__cause__`` attribute. """ def __init__(self, e): self.original = e super().__init__('Command raised an exception: {0.__class__.__name__}: {0}'.format(e)) class CommandOnCooldown(CommandError): ...
class CommandInvokeError(CommandError): """Exception raised when the command being invoked raised an exception. Attributes -----------
random_line_split
errors.py
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2016 Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to us...
else: super().__init__(*args) class UserInputError(CommandError): """The base exception type for errors that involve errors regarding user input. This inherits from :exc:`CommandError`. """ pass class CommandNotFound(CommandError): """Exception raised when a command is at...
m = message.replace('@everyone', '@\u200beveryone').replace('@here', '@\u200bhere') super().__init__(m, *args)
conditional_block
nilan_connectiontest.py
#!/usr/bin/env python import minimalmodbus import serial __author__ = "Nick Ma" class Nilan( minimalmodbus.Instrument ): """Instrument class for nilan heat pump. communication via RS485 """ HOLDINGREG_OFFSET = 10000 def __init__(self, portname, slaveaddress=30): minimalmodbus.Ins...
(self): """This is a holding register -> functioncode=3""" return self.read_register(1003, numberOfDecimals=0, signed=False, functioncode=3) def set_userVent(self, speed=2): if (speed<0) or (speed>4): return return self.write_register(1003, speed) #######################...
get_userVent
identifier_name
nilan_connectiontest.py
#!/usr/bin/env python import minimalmodbus import serial __author__ = "Nick Ma" class Nilan( minimalmodbus.Instrument ): """Instrument class for nilan heat pump. communication via RS485 """ HOLDINGREG_OFFSET = 10000 def __init__(self, portname, slaveaddress=30): minimalmodbus.Ins...
pass
NILAN_SERIAL_PORT = '/dev/ttyUSB0' print( 'TESTING Nilan Connection') n = Nilan(NILAN_SERIAL_PORT) n.debug = True print(n) ## starting demo old_userVent_value = n.get_userVent() print( 'old userVentSet: {0}'.format( old_userVent_value )) n.debug = False new_designated...
conditional_block
nilan_connectiontest.py
#!/usr/bin/env python import minimalmodbus import serial __author__ = "Nick Ma" class Nilan( minimalmodbus.Instrument ): """Instrument class for nilan heat pump. communication via RS485 """ HOLDINGREG_OFFSET = 10000 def __init__(self, portname, slaveaddress=30): minimalmodbus.Ins...
return return self.write_register(1003, speed) ######################## ## Testing the module ## ######################## if __name__ == '__main__': NILAN_SERIAL_PORT = '/dev/ttyUSB0' print( 'TESTING Nilan Connection') n = Nilan(NILAN_SERIAL_PORT) n.debug = True print(n)...
def set_userVent(self, speed=2): if (speed<0) or (speed>4):
random_line_split
nilan_connectiontest.py
#!/usr/bin/env python import minimalmodbus import serial __author__ = "Nick Ma" class Nilan( minimalmodbus.Instrument ): """Instrument class for nilan heat pump. communication via RS485 """ HOLDINGREG_OFFSET = 10000 def __init__(self, portname, slaveaddress=30): minimalmodbus.Ins...
def get_userVent(self): """This is a holding register -> functioncode=3""" return self.read_register(1003, numberOfDecimals=0, signed=False, functioncode=3) def set_userVent(self, speed=2): if (speed<0) or (speed>4): return return self.write_register(1003, speed) ...
"""Return the setpoint (SP) target for loop1.""" return self.read_register(211, numberOfDecimals=2, signed=True, functioncode=4)
identifier_body
Row.tsx
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; /** * @ngdoc react * @name Row * @description Row Component to be used in an item preview to show an item's detail */
) => ( enabled ? <div className={classNames( { form__row: !rowItem, 'form__row-item': rowItem, 'no-padding': noPadding, 'form__row--flex': flex, } )} > ...
export const Row:React.StatelessComponent<any> = ( {label, value, className, children, noPadding, enabled, flex, rowItem}
random_line_split
rasterize_over.py
# -*- coding: utf-8 -*- """ *************************************************************************** rasterize_over.py --------------------- Date : September 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com ********...
def commandName(self): return 'gdal_rasterize' def getConsoleCommands(self, parameters, context, feedback, executing=True): ogrLayer, layerName = self.getOgrCompatibleSource(self.INPUT, parameters, context, feedback, executing) inLayer = self.parameterAsRasterLayer(parameters, self.INPU...
def icon(self): return QIcon(os.path.join(pluginPath, 'images', 'gdaltools', 'rasterize.png'))
random_line_split
rasterize_over.py
# -*- coding: utf-8 -*- """ *************************************************************************** rasterize_over.py --------------------- Date : September 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com ********...
(self): super().__init__() def initAlgorithm(self, config=None): self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT, self.tr('Input vector layer'))) self.addParameter(QgsProcessingParameterRasterLayer(self.INPUT_RAS...
__init__
identifier_name
rasterize_over.py
# -*- coding: utf-8 -*- """ *************************************************************************** rasterize_over.py --------------------- Date : September 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com ********...
self.addOutput(QgsProcessingOutputRasterLayer(self.OUTPUT, self.tr('Rasterized'))) def name(self): return 'rasterize_over' def displayName(self): return self.tr('Rasterize (overwrite with attribute)') def group(self): ...
p.setFlags(p.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.addParameter(p)
conditional_block
rasterize_over.py
# -*- coding: utf-8 -*- """ *************************************************************************** rasterize_over.py --------------------- Date : September 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com ********...
] for p in params: p.setFlags(p.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.addParameter(p) self.addOutput(QgsProcessingOutputRasterLayer(self.OUTPUT, self.tr('Rasterized'))) def name(self): ...
self.addParameter(QgsProcessingParameterFeatureSource(self.INPUT, self.tr('Input vector layer'))) self.addParameter(QgsProcessingParameterRasterLayer(self.INPUT_RASTER, self.tr('Input raster...
identifier_body
lib.rs
//! # How to use serde with rust-protobuf //! //! rust-protobuf 3 no longer directly supports serde. //! //! Practically, serde is needed mostly to be able to serialize and deserialize JSON, //! and **rust-protobuf supports JSON directly**, and more correctly according to //! official protobuf to JSON mapping. For that...
where R: serde::de::Error, { Ok(Some(EnumOrUnknown::from_i32(v))) } fn visit_unit<R>(self) -> Result<Self::Value, R> where R: serde::de::Error, { Ok(None) } } d.deserialize_any(DeserializeEnumVisitor(Phanto...
} } fn visit_i32<R>(self, v: i32) -> Result<Self::Value, R>
random_line_split
lib.rs
//! # How to use serde with rust-protobuf //! //! rust-protobuf 3 no longer directly supports serde. //! //! Practically, serde is needed mostly to be able to serialize and deserialize JSON, //! and **rust-protobuf supports JSON directly**, and more correctly according to //! official protobuf to JSON mapping. For that...
fn visit_i32<R>(self, v: i32) -> Result<Self::Value, R> where R: serde::de::Error, { Ok(Some(EnumOrUnknown::from_i32(v))) } fn visit_unit<R>(self) -> Result<Self::Value, R> where R: serde::de::Error, { Ok(None) ...
{ match E::enum_descriptor_static().value_by_name(v) { Some(v) => Ok(Some(EnumOrUnknown::from_i32(v.value()))), None => Err(serde::de::Error::custom(format!( "unknown enum value: {}", v ))), } }
identifier_body
lib.rs
//! # How to use serde with rust-protobuf //! //! rust-protobuf 3 no longer directly supports serde. //! //! Practically, serde is needed mostly to be able to serialize and deserialize JSON, //! and **rust-protobuf supports JSON directly**, and more correctly according to //! official protobuf to JSON mapping. For that...
<E: EnumFull>(PhantomData<E>); impl<'de, E: EnumFull> serde::de::Visitor<'de> for DeserializeEnumVisitor<E> { type Value = Option<EnumOrUnknown<E>>; fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result { write!(formatter, "a string, an integer or none") } ...
DeserializeEnumVisitor
identifier_name
lib.rs
//! # How to use serde with rust-protobuf //! //! rust-protobuf 3 no longer directly supports serde. //! //! Practically, serde is needed mostly to be able to serialize and deserialize JSON, //! and **rust-protobuf supports JSON directly**, and more correctly according to //! official protobuf to JSON mapping. For that...
} fn deserialize_enum_or_unknown<'de, E: EnumFull, D: serde::Deserializer<'de>>( d: D, ) -> Result<Option<EnumOrUnknown<E>>, D::Error> { struct DeserializeEnumVisitor<E: EnumFull>(PhantomData<E>); impl<'de, E: EnumFull> serde::de::Visitor<'de> for DeserializeEnumVisitor<E> { type Value = Option<E...
{ s.serialize_unit() }
conditional_block
locks.py
Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.python import log from twisted.internet import reactor, defer from buildbot import util if False: # for debugging debuglog = log.msg else: debuglog = lambda m: None clas...
# Wants counting access return num_excl == 0 and num_counting < self.maxCount else: # Wants exclusive access return num_excl == 0 and num_counting == 0 def claim(self, owner, access): """ Claim the lock (lock must be available) """ debuglog("%...
""" Return a boolean whether the lock is available for claiming """ debuglog("%s isAvailable(%s): self.owners=%r" % (self, access, self.owners)) num_excl, num_counting = self._getOwnersCount() if access.mode == 'counting':
random_line_split
locks.py
Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.python import log from twisted.internet import reactor, defer from buildbot import util if False: # for debugging debuglog = log.msg else: debuglog = lambda m: None clas...
class RealSlaveLock: def __init__(self, lockid): self.name = lockid.name self.maxCount = lockid.maxCount self.maxCountForSlave = lockid.maxCountForSlave self.description = "<SlaveLock(%s, %s, %s)>" % (self.name, self.maxCount,...
return self
identifier_body
locks.py
Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.python import log from twisted.internet import reactor, defer from buildbot import util if False: # for debugging debuglog = log.msg else: debuglog = lambda m: None clas...
def waitUntilMaybeAvailable(self, owner, access): """Fire when the lock *might* be available. The caller will need to check with isAvailable() when the deferred fires. This loose form is used to avoid deadlocks. If we were interested in a stronger form, this would be named 'waitUnt...
access, d = self.waiting[0] if access.mode == 'counting': if num_excl > 0 or num_counting == self.maxCount: break else: num_counting = num_counting + 1 else: # access.mode == 'exclusive' if nu...
conditional_block
locks.py
Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from twisted.python import log from twisted.internet import reactor, defer from buildbot import util if False: # for debugging debuglog = log.msg else: debuglog = lambda m: None clas...
(self, lockid, mode): self.lockid = lockid self.mode = mode assert isinstance(lockid, (MasterLock, SlaveLock)) assert mode in ['counting', 'exclusive'] class BaseLockId(util.ComparableMixin): """ Abstract base class for LockId classes. Sets up the 'access()' function for the ...
__init__
identifier_name
query.py
import datetime import numbers from django.db.models.fields import FieldDoesNotExist from django.utils import tree from django.core.exceptions import FieldError try: from django.db.models.sql.constants import LOOKUP_SEP except: from django.db.models.constants import LOOKUP_SEP class HStoreConstraint(): v...
(self, alias, field, value, lookup_type, key=None): self.lvalue = '%s' self.alias = alias self.field = field self.values = [value] if lookup_type == 'contains': if isinstance(value, basestring): self.operator = '?' elif isinstance(value, ...
__init__
identifier_name
query.py
import datetime import numbers from django.db.models.fields import FieldDoesNotExist from django.utils import tree from django.core.exceptions import FieldError try: from django.db.models.sql.constants import LOOKUP_SEP except: from django.db.models.constants import LOOKUP_SEP class HStoreConstraint(): v...
parts = parts[:-1] opts = query.get_meta() alias = query.get_initial_alias() field, target, opts, join_list, last, extra = query.setup_joins(parts, opts, alias, True) col, alias, join_list = query.trim_joins(target, join_list, last, Fal...
else: key = parts[-1]
random_line_split
query.py
import datetime import numbers from django.db.models.fields import FieldDoesNotExist from django.utils import tree from django.core.exceptions import FieldError try: from django.db.models.sql.constants import LOOKUP_SEP except: from django.db.models.constants import LOOKUP_SEP class HStoreConstraint(): v...
# Not a field. Bail out. lookup_type = parts.pop() break # Unless we're at the end of the list of lookups, let's attempt # to continue traversing relations. if (cou...
for child in self.children: if isinstance(child, HQ): node = query.where_class() child.add_to_node(node, query, used_aliases) where_node.add(node, self.connector) else: field, value = child parts = field.split(LOOKU...
identifier_body
query.py
import datetime import numbers from django.db.models.fields import FieldDoesNotExist from django.utils import tree from django.core.exceptions import FieldError try: from django.db.models.sql.constants import LOOKUP_SEP except: from django.db.models.constants import LOOKUP_SEP class HStoreConstraint(): v...
else: test_value = value if isinstance(test_value, datetime.datetime): cast_type = 'timestamp' elif isinstance(test_value, datetime.date): cast_type = 'date' elif isinstance(test_value, datetime.time): cast_...
test_value = value[0] if len(value) > 0 else '' self.values = [tuple(value)]
conditional_block
visualize_noe.py
import glob import sys import string import Bio.PDB def
(filename): f = open(filename, 'r') noe_pairs = [] for line in f.readlines(): res_a = int(string.split(line)[2]) res_b = int(string.split(line)[7]) noe_pair = [res_a, res_b] if noe_pair not in noe_pairs: noe_pairs.append(noe_pair) f.clos...
parse_noe
identifier_name
visualize_noe.py
import glob import sys import string import Bio.PDB def parse_noe(filename): f = open(filename, 'r') noe_pairs = [] for line in f.readlines(): res_a = int(string.split(line)[2]) res_b = int(string.split(line)[7]) noe_pair = [res_a, res_b] if noe_pair n...
count_restraints(noe_file) cmd.load(native_pdb, "native") cmd.hide("all") cmd.show("cartoon", "native") if noe: for pair in parse_noe(noe_file): cmd.distance("noe", "native and resi %i and name ca" % (pair[0]), "native and resi %i and name ca" % (pair[1])) cmd.hide("labels", ...
noe = True noe_file = sys.argv[2]
conditional_block
visualize_noe.py
import glob import sys import string import Bio.PDB def parse_noe(filename): f = open(filename, 'r') noe_pairs = [] for line in f.readlines(): res_a = int(string.split(line)[2]) res_b = int(string.split(line)[7]) noe_pair = [res_a, res_b] if noe_pair n...
f = open(filename, 'r') noe_pairs = [] for line in f.readlines(): # print line res_a = int(string.split(line)[2]) res_b = int(string.split(line)[7]) name_a = string.split(line)[5].rstrip(")")[:-1] name_b = string.split(line)[10].rstrip(")")[:-1]...
def count_restraints(filename):
random_line_split
visualize_noe.py
import glob import sys import string import Bio.PDB def parse_noe(filename):
def count_restraints(filename): f = open(filename, 'r') noe_pairs = [] for line in f.readlines(): # print line res_a = int(string.split(line)[2]) res_b = int(string.split(line)[7]) name_a = string.split(line)[5].rstrip(")")[:-1] name_b = stri...
f = open(filename, 'r') noe_pairs = [] for line in f.readlines(): res_a = int(string.split(line)[2]) res_b = int(string.split(line)[7]) noe_pair = [res_a, res_b] if noe_pair not in noe_pairs: noe_pairs.append(noe_pair) f.close() print le...
identifier_body
gulpfile.js
/* Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com> Copyright (C) 2019-2020 Apple Inc. 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 th...
] }, 'env': { 'node': true } }; gulp.task('test', gulp.series(function () { return gulp.src(TEST) .pipe(mocha({ reporter: 'spec', timeout: 100000 // 100s })); })); gulp.task('lint', gulp.series(function () { return gulp.src(LINT) .pip...
'capIsNew': false }
random_line_split
gmailApiService.ts
import * as angular from 'angular'; declare var gapi: any; export class GmailApiService { public static $inject = ['$q']; private static CLIENT_ID: string = '272636970927-ul1mrflj9a7sc697k9ldkt5r28pfahal.apps.googleusercontent.com'; private static SCOPES: string[] = ['https://www.googleapis.com/auth/...
gapi.auth.authorize( { 'client_id': GmailApiService.CLIENT_ID, 'scope': GmailApiService.SCOPES, 'immediate': false }, function handleAuth(authResult) { if (authResult && !authResult.error) { resolve(authResult); ...
authorize(): angular.IPromise<any> { return this.$q(function (resolve, reject) {
random_line_split
gmailApiService.ts
import * as angular from 'angular'; declare var gapi: any; export class GmailApiService { public static $inject = ['$q']; private static CLIENT_ID: string = '272636970927-ul1mrflj9a7sc697k9ldkt5r28pfahal.apps.googleusercontent.com'; private static SCOPES: string[] = ['https://www.googleapis.com/auth/...
private callApi(clientCall: Function): angular.IPromise<any> { return this.$q((resolve, reject) => { gapi.client.load('gmail', 'v1') .then(() => clientCall()) .then((response) => resolve(response.result)); }); } };
{ return this .callApi(() => { return gapi.client.gmail.users.messages.list({ 'userId': 'me' }); }) .then(result => result.messages); }
identifier_body
gmailApiService.ts
import * as angular from 'angular'; declare var gapi: any; export class GmailApiService { public static $inject = ['$q']; private static CLIENT_ID: string = '272636970927-ul1mrflj9a7sc697k9ldkt5r28pfahal.apps.googleusercontent.com'; private static SCOPES: string[] = ['https://www.googleapis.com/auth/...
else { reject(authResult); } }); }); } getMessageById(messageId: string): angular.IPromise<any> { return this.callApi(() => { return gapi.client.gmail.users.messages.get({ 'userId': 'me', 'id': messageId, 'format': 'raw' }...
{ resolve(authResult); }
conditional_block
gmailApiService.ts
import * as angular from 'angular'; declare var gapi: any; export class GmailApiService { public static $inject = ['$q']; private static CLIENT_ID: string = '272636970927-ul1mrflj9a7sc697k9ldkt5r28pfahal.apps.googleusercontent.com'; private static SCOPES: string[] = ['https://www.googleapis.com/auth/...
(): angular.IPromise<any[]> { return this .callApi(() => { return gapi.client.gmail.users.messages.list({ 'userId': 'me' }); }) .then(result => result.messages); } private callApi(clientCall: Function): angular.IPromise<any> { return this...
getMessageList
identifier_name
jsCompiler.js
const fs = require('fs'); /** * Thanks to @williammustaffa for this compiler. * Original src: https://github.com/williammustaffa/jGame.js/blob/master/compile.js * */ // Project src const srcDir = './app/assets/javascript' const entryPoint = `${srcDir}/main.js`; // regex to serach @include('file'); declaration...
return content; } /** * Retrive the include declaration file path * * @param {String} include declaration like @include('test.js') * @returns {String} path */ function getPath(include) { return `${srcDir}/${include.replace(/include\((\'|\")|(\'|\")\)/g, '')}`; } function insertFileInfo(src, content) { let...
{ content = content.replace(';', ''); let includeDeclaration = searchResult[0]; // get included file path let includePath = getPath(includeDeclaration); // parse include declaration content let includeContent = parseInclude(includePath); // replace include with file content content = con...
conditional_block
jsCompiler.js
const fs = require('fs'); /** * Thanks to @williammustaffa for this compiler. * Original src: https://github.com/williammustaffa/jGame.js/blob/master/compile.js * */ // Project src const srcDir = './app/assets/javascript' const entryPoint = `${srcDir}/main.js`; // regex to serach @include('file'); declaration...
function insertFileInfo(src, content) { let prefix = `/* >> ${src} START */`, sufix = `/* << ${src} END */`; return prefix + '\n' + content + '\n' + sufix; } module.exports = jsCompiler;
{ return `${srcDir}/${include.replace(/include\((\'|\")|(\'|\")\)/g, '')}`; }
identifier_body
jsCompiler.js
const fs = require('fs'); /** * Thanks to @williammustaffa for this compiler. * Original src: https://github.com/williammustaffa/jGame.js/blob/master/compile.js * */ // Project src const srcDir = './app/assets/javascript' const entryPoint = `${srcDir}/main.js`; // regex to serach @include('file'); declaration...
(include) { return `${srcDir}/${include.replace(/include\((\'|\")|(\'|\")\)/g, '')}`; } function insertFileInfo(src, content) { let prefix = `/* >> ${src} START */`, sufix = `/* << ${src} END */`; return prefix + '\n' + content + '\n' + sufix; } module.exports = jsCompiler;
getPath
identifier_name
jsCompiler.js
const fs = require('fs'); /** * Thanks to @williammustaffa for this compiler. * Original src: https://github.com/williammustaffa/jGame.js/blob/master/compile.js * */ // Project src const srcDir = './app/assets/javascript' const entryPoint = `${srcDir}/main.js`; // regex to serach @include('file'); declaration...
*/ function parseInclude(src) { let content = fs.readFileSync(src, 'utf8'); // verify all include declarations and replace with file content while((searchResult = searchRegex.exec(content))) { content = content.replace(';', ''); let includeDeclaration = searchResult[0]; // get included file path ...
/** * Replaces all @include('file') declarations with file content * * @param {String} file src * @returns {String} File content with 'includes' content
random_line_split
lfrectify.py
#!/usr/bin/env python2.7 # __BEGIN_LICENSE__ # # Copyright (C) 2010-2012 Stanford University. # All rights reserved. # # __END_LICENSE__ # rectify.py # # Usage: rectify.py <lightfield_image.{tif,png,etc}> [--pixels-per-lenslet <ppl>] # # This script simply applies a rectification from a # campixel_to_camlens.warp fil...
else: calibration_file = options.calibration_file # Default output filename has a -RECTIFIED suffix if not options.output_filename: fileName, fileExtension = os.path.splitext(filename) output_filename = fileName + '-RECTIFIED' + fileExtension else: ...
fileName, fileExtension = os.path.splitext(filename) calibration_file = fileName + '.lfc'
conditional_block
lfrectify.py
#!/usr/bin/env python2.7 # __BEGIN_LICENSE__ # # Copyright (C) 2010-2012 Stanford University. # All rights reserved. # # __END_LICENSE__ # rectify.py # # Usage: rectify.py <lightfield_image.{tif,png,etc}> [--pixels-per-lenslet <ppl>] # # This script simply applies a rectification from a # campixel_to_camlens.warp fil...
else: output_filename = options.output_filename # Load the calibration data from lflib.calibration import LightFieldCalibration lfcal = LightFieldCalibration.load(calibration_file) # Rectify the image im = load_image(filename, normalize = False) ...
random_line_split
main.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
all_errors.insert(err_code, info); } } Ok(all_errors) } /// Output an HTML page for the errors in `err_map` to `output_path`. fn render_error_page(err_map: &ErrorMetadataMap, output_path: &Path) -> Result<(), Box<Error>> { let mut output_file = try!(File::create(output_path)); try...
let some_errors: ErrorMetadataMap = try!(json::decode(&metadata_str)); for (err_code, info) in some_errors {
random_line_split
main.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
{ panic!("{}", e.description()); }
conditional_block
main.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { if let Err(e) = main_with_result() { panic!("{}", e.description()); } }
main
identifier_name
main.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { if let Err(e) = main_with_result() { panic!("{}", e.description()); } }
{ let metadata_dir = get_metadata_dir(); let err_map = try!(load_all_errors(&metadata_dir)); try!(render_error_page(&err_map, Path::new("doc/error-index.html"))); Ok(()) }
identifier_body
arm.py
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
elif target.core in ["Cortex-M0", "Cortex-M0+"]: self.sys_libs.extend([join(ARM_CPPLIB, lib+".l") for lib in ["cpp_ps", "cpprt_p"]]) else: self.ld.append("--libpath=%s" % ARM_LIB)
ARM.__init__(self, target, options, notify, macros, silent, extra_verbose=extra_verbose) # Compiler self.asm += ["-D__MICROLIB"] self.cc += ["--library_type=microlib", "-D__MICROLIB", "-D__ASSERT_MSG"] self.cppc += ["--library_type=microlib", "-D__MICROLIB", "-D__ASSERT_MSG"] ...
identifier_body
arm.py
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
def __init__(self, target, options=None, notify=None, macros=None, silent=False, extra_verbose=False): ARM.__init__(self, target, options, notify, macros, silent, extra_verbose=extra_verbose) self.cc += ["-D__ASSERT_MSG"] self.cppc += ["-D__ASSERT_MSG"] self.ld.append("--libpath=%s...
args = self.target.binary_cmdline_hook(self.__class__.__name__, args) self.default_cmd(args) class ARM_STD(ARM):
random_line_split
arm.py
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
(self, output): for line in output.splitlines(): match = ARM.DIAGNOSTIC_PATTERN.match(line) if match is not None: self.cc_info( match.group('severity').lower(), match.group('file'), match.group('line'), ...
parse_output
identifier_name
arm.py
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wr...
if mem_map: args.extend(["--scatter", mem_map]) if hasattr(self.target, "link_cmdline_hook"): args = self.target.link_cmdline_hook(self.__class__.__name__, args) self.default_cmd(self.ld + args + objects + libraries + self.sys_libs) @hook_tool def binary(self...
args = ["-o", output, "--info=totals", "--list=.link_totals.txt"]
conditional_block
bounding-box.js
define([ "utils/range" ],function(Range) { "use strict"; function BoundingBox(position, width, height) { this.position = position; this.width = width; this.height = height; this.rangeX = new Range(position.x, position.x + width); this.rangeY = new Range(position.y, position.y + width); } BoundingB...
return isCollidingX && isCollidingY; }; BoundingBox.prototype.toString = function() { return "BoundingBox(rangeX = " + this.rangeX + ", rangeY = " + this.rangeY + ")"; }; function updateRanges(boundingBox) { var pos = boundingBox.position; boundingBox.rangeX.update(pos.x, pos.x + boundingBox.width); ...
*/ BoundingBox.prototype.isColliding = function(other) { var isCollidingX = this.rangeX.intersects(other.rangeX), isCollidingY = this.rangeY.intersects(other.rangeY);
random_line_split
bounding-box.js
define([ "utils/range" ],function(Range) { "use strict"; function
(position, width, height) { this.position = position; this.width = width; this.height = height; this.rangeX = new Range(position.x, position.x + width); this.rangeY = new Range(position.y, position.y + width); } BoundingBox.prototype.setPosition = function(position) { this.position = position; r...
BoundingBox
identifier_name
bounding-box.js
define([ "utils/range" ],function(Range) { "use strict"; function BoundingBox(position, width, height) { this.position = position; this.width = width; this.height = height; this.rangeX = new Range(position.x, position.x + width); this.rangeY = new Range(position.y, position.y + width); } BoundingB...
return BoundingBox; });
{ var pos = boundingBox.position; boundingBox.rangeX.update(pos.x, pos.x + boundingBox.width); boundingBox.rangeY.update(pos.y, pos.y + boundingBox.height); return boundingBox; }
identifier_body
0002_auto_20161111_1113.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-11 03:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration):
migrations.AddField( model_name='bill', name='type_id', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='bill.Type'), preserve_default=False, ), ]
dependencies = [ ('bill', '0001_initial'), ] operations = [ migrations.CreateModel( name='Type', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_leng...
identifier_body
0002_auto_20161111_1113.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-11 03:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class
(migrations.Migration): dependencies = [ ('bill', '0001_initial'), ] operations = [ migrations.CreateModel( name='Type', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nam...
Migration
identifier_name
0002_auto_20161111_1113.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-11 03:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('bill', '0001_initial'), ] ...
]
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='bill.Type'), preserve_default=False, ),
random_line_split
test.ts
/// <reference path="../typings/tsd.d.ts" /> import fs = require('fs'); import path = require('path'); import yeoman = require('yeoman-generator'); declare var describe: any; declare var beforeEach: any; declare var it: any; import helpers = yeoman.test; function
(context, dir, name, appPath, done) { helpers.testDirectory(dir, function (err) { if (err) { return done(err); } this[name] = helpers.createGenerator('typescript-tmp:app', [appPath, [helpers.createDummyGenerator(), 'mocha:app']]); this[name].options['skip-install'] = true; done(); ...
createGenerator
identifier_name
test.ts
/// <reference path="../typings/tsd.d.ts" /> import fs = require('fs'); import path = require('path'); import yeoman = require('yeoman-generator'); declare var describe: any; declare var beforeEach: any; declare var it: any; import helpers = yeoman.test; function createGenerator(context, dir, name, appPath, done) {...
this[name] = helpers.createGenerator('typescript-tmp:app', [appPath, [helpers.createDummyGenerator(), 'mocha:app']]); this[name].options['skip-install'] = true; done(); }.bind(context)); } describe('generator-typescript tests: Web Project', function() { this.timeout(2000); var roo...
{ return done(err); }
conditional_block
test.ts
/// <reference path="../typings/tsd.d.ts" /> import fs = require('fs'); import path = require('path'); import yeoman = require('yeoman-generator'); declare var describe: any; declare var beforeEach: any; declare var it: any; import helpers = yeoman.test; function createGenerator(context, dir, name, appPath, done)
describe('generator-typescript tests: Web Project', function() { this.timeout(2000); var root = path.join(__dirname, 'temp'); beforeEach(function (done) { createGenerator(this, root, 'generator', '../../app', done); }); it('the generator can be required without throwing', function () { ...
{ helpers.testDirectory(dir, function (err) { if (err) { return done(err); } this[name] = helpers.createGenerator('typescript-tmp:app', [appPath, [helpers.createDummyGenerator(), 'mocha:app']]); this[name].options['skip-install'] = true; done(); }.bind(context)); }
identifier_body
test.ts
/// <reference path="../typings/tsd.d.ts" /> import fs = require('fs'); import path = require('path'); import yeoman = require('yeoman-generator'); declare var describe: any; declare var beforeEach: any; declare var it: any; import helpers = yeoman.test; function createGenerator(context, dir, name, appPath, done) {...
}); }); });
helpers.assertFiles(expected); done();
random_line_split
router_5_5_4.py
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
(self, dialog, title): pass if __name__ == '__main__': unittest.main()
on_dialog
identifier_name
router_5_5_4.py
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. #
# Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form mu...
random_line_split
router_5_5_4.py
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
if __name__ == '__main__': unittest.main()
pass
identifier_body
router_5_5_4.py
#!/usr/bin/env python # # Copyright (c) 2016, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notic...
unittest.main()
conditional_block
specialization-cross-crate-no-gate.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// except according to those terms. // run-pass // Test that specialization works even if only the upstream crate enables it // aux-build:specialization_cross_crate.rs extern crate specialization_cross_crate; use specialization_cross_crate::*; fn main() { assert!(0u8.foo() == "generic Clone"); assert!(ve...
// // 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
specialization-cross-crate-no-gate.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { assert!(0u8.foo() == "generic Clone"); assert!(vec![0u8].foo() == "generic Vec"); assert!(vec![0i32].foo() == "Vec<i32>"); assert!(0i32.foo() == "i32"); assert!(String::new().foo() == "String"); assert!(((), 0).foo() == "generic pair"); assert!(((), ()).foo() == "generic uniform pair");...
main
identifier_name
specialization-cross-crate-no-gate.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ assert!(0u8.foo() == "generic Clone"); assert!(vec![0u8].foo() == "generic Vec"); assert!(vec![0i32].foo() == "Vec<i32>"); assert!(0i32.foo() == "i32"); assert!(String::new().foo() == "String"); assert!(((), 0).foo() == "generic pair"); assert!(((), ()).foo() == "generic uniform pair"); ...
identifier_body
ej.culture.az-Latn-AZ.js
ej.addCulture( "az-Latn-AZ", { name: "az-Latn-AZ", englishName: "Azerbaijani (Latin, Azerbaijan)", nativeName: "Azərbaycan dili (Azərbaycan)", language: "az-Latn", numberFormat: { ",": " ", ".": ",", percent: { pattern: ["-n%","n%"], ",": " ", ".": "," }, currency: { pattern: ["-n $","n $"], ...
} } // determine month by looking at how many days into the hyear we are // monthDays contains the number of days up to each month. hmonth = 0; var daysIntoYear = daysSince...
absDays += daysInYear; hyear++;
random_line_split
ej.culture.az-Latn-AZ.js
ej.addCulture( "az-Latn-AZ", { name: "az-Latn-AZ", englishName: "Azerbaijani (Latin, Azerbaijan)", nativeName: "Azərbaycan dili (Azərbaycan)", language: "az-Latn", numberFormat: { ",": " ", ".": ",", percent: { pattern: ["-n%","n%"], ",": " ", ".": "," }, currency: { pattern: ["-n $","n $"], ...
absDays += daysInYear; hyear++; } } // determine month by looking at how many days into the hyear we are // monthDays contains the number of days up to each month. ...
} else { if (daysSinceJan0101 > (absDays + daysInYear)) {
conditional_block
users.py
from ..helpers import ResourceBase, FilteredIterableResource from ..errors import ok_or_error, response_or_error from ..compat import update_doc class Users(ResourceBase, FilteredIterableResource): @response_or_error def add(self, name, password, displayName, emailAddress, addToDefaultGroup=True): """ ...
""" return self._client.post(self.url("/remove-group"), dict(context=user, itemName=group)) def more_members(self, user, filter=None): """ Retrieves a list of groups the specified user is a member of. filter: if specified only groups with names containing the supplied strin...
@ok_or_error def remove_group(self, user, group): """ Remove the given user from the given group.
random_line_split
users.py
from ..helpers import ResourceBase, FilteredIterableResource from ..errors import ok_or_error, response_or_error from ..compat import update_doc class Users(ResourceBase, FilteredIterableResource): @response_or_error def
(self, name, password, displayName, emailAddress, addToDefaultGroup=True): """ Add a user, returns a dictionary containing information about the newly created user """ data = dict(name=name, password=password, displayName=displayName, ...
add
identifier_name
users.py
from ..helpers import ResourceBase, FilteredIterableResource from ..errors import ok_or_error, response_or_error from ..compat import update_doc class Users(ResourceBase, FilteredIterableResource): @response_or_error def add(self, name, password, displayName, emailAddress, addToDefaultGroup=True): """ ...
return self.paginate("/more-members", params) def more_non_members(self, user, filter=None): """ Retrieves a list of groups that the specified user is not a member of filter: if specified only groups with names containing the supplied string will be returned """ pa...
params['filter'] = filter
conditional_block
users.py
from ..helpers import ResourceBase, FilteredIterableResource from ..errors import ok_or_error, response_or_error from ..compat import update_doc class Users(ResourceBase, FilteredIterableResource): @response_or_error def add(self, name, password, displayName, emailAddress, addToDefaultGroup=True):
@ok_or_error def delete(self, user): """ Delete a user. """ return self._client.delete(self.url(), params=dict(name=user)) @response_or_error def update(self, name, displayName=None, emailAddress=None): """ Update the user information, and return the up...
""" Add a user, returns a dictionary containing information about the newly created user """ data = dict(name=name, password=password, displayName=displayName, emailAddress=emailAddress, addToDefaultGroup=addToDefaul...
identifier_body
search.js
'use strict'; var _ = require('lodash'), async = require('async'), moment = require('moment'), cheerio = require('cheerio'), request = require('request'), url = require('url'), util = require('util'), searchQueue, onComplete, requests = require('./requests'); searchQueue = async.queue(doRequest, 3); ...
parseBody(_.assign({}, options, { body: body }), callback); }); } function parseBody(options, callback) { var body = options.body, uri = options.searchURI, $ = cheerio.load(body), next = $('.pagination .next_page').attr('href'), requestLinks = $('.request_listing .head a'); if (ne...
{ return callback(err); }
conditional_block
search.js
'use strict'; var _ = require('lodash'), async = require('async'), moment = require('moment'), cheerio = require('cheerio'), request = require('request'), url = require('url'), util = require('util'), searchQueue, onComplete, requests = require('./requests'); searchQueue = async.queue(doRequest, 3); ...
(options, callback) { var uri = options.searchURI; request({ strictSSL: false, uri: uri }, function(err, response, body) { if (err) { return callback(err); } parseBody(_.assign({}, options, { body: body }), callback); }); } function parseBody(options, callback) { var body...
doRequest
identifier_name
search.js
'use strict'; var _ = require('lodash'), async = require('async'), moment = require('moment'), cheerio = require('cheerio'), request = require('request'), url = require('url'), util = require('util'), searchQueue, onComplete, requests = require('./requests');
/** * Accept the options for a search & initialise search queue * For each */ module.exports = function(options, callback) { onComplete = callback; startRequests(options); }; function doRequest(options, callback) { var uri = options.searchURI; request({ strictSSL: false, uri: uri }, function(err...
searchQueue = async.queue(doRequest, 3); searchQueue.drain = function() { requests.onComplete(onComplete); };
random_line_split
search.js
'use strict'; var _ = require('lodash'), async = require('async'), moment = require('moment'), cheerio = require('cheerio'), request = require('request'), url = require('url'), util = require('util'), searchQueue, onComplete, requests = require('./requests'); searchQueue = async.queue(doRequest, 3); ...
requestURI: url.format(uri) + '.json' })); }); callback(); } function startRequests(options) { var from = options.from || moment().subtract(10, 'years'), to = options.to || moment(), uri, start, end; from = moment(from).startOf('month'); options.from = from.clone(); to = mo...
{ var body = options.body, uri = options.searchURI, $ = cheerio.load(body), next = $('.pagination .next_page').attr('href'), requestLinks = $('.request_listing .head a'); if (next) { searchQueue.push(_.assign({}, options, { searchURI: options.site + next })); } console.log('%s li...
identifier_body
extract_xml.py
import os import types from sllib.LLSD import LLSD try: os.makedirs('./httpcap') except: pass data = open('httpcap.txt','r').read() c = 0 btag = '<llsd>' etag = '</llsd>' ##mbtag = '<key>message</key><string>' ##metag = '</string>' b = data.find(btag) mnames = {} while b >= 0: e = da...
## mnames[m] = None ## else: ## m = 'Unknown' ll = LLSD.fromstring(xml) m = 'DATA' if type(ll) == types.DictType and ll.has_key('events'): ## print ll for msg in ll['events']: m = msg['message'] ## print m mnames[m] = None ...
## m = xml[bm:em]
random_line_split
extract_xml.py
import os import types from sllib.LLSD import LLSD try: os.makedirs('./httpcap') except: pass data = open('httpcap.txt','r').read() c = 0 btag = '<llsd>' etag = '</llsd>' ##mbtag = '<key>message</key><string>' ##metag = '</string>' b = data.find(btag) mnames = {} while b >= 0: e = da...
name = './httpcap/%s_%d.xml' % (m,c) try: open(name, 'w+').write(xml) except: print xml raise c += 1 b = data.find(btag, e) print mnames.keys()
for msg in ll['events']: m = msg['message'] ## print m mnames[m] = None
conditional_block
0019_algorithmtagproposal_difficultyproposal.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-06-24 23:35 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('problems', '0018_origintag_helptexts'), ] operations = [ migrations.CreateModel( name='AlgorithmTagProposal', fields=[ ('id', models.AutoFie...
Migration
identifier_name
0019_algorithmtagproposal_difficultyproposal.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-06-24 23:35 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_depende...
]
random_line_split
0019_algorithmtagproposal_difficultyproposal.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-06-24 23:35 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
name='DifficultyProposal', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('difficulty', models.CharField(max_length=10)), ('problem', models.ForeignKey(on_delete=django.db.models.deletio...
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('problems', '0018_origintag_helptexts'), ] operations = [ migrations.CreateModel( name='AlgorithmTagProposal', fields=[ ('id', models.AutoField(auto_created=True, primary...
identifier_body
FormList.tsx
import * as React from 'react'; import { List } from 'rc-field-form'; import { ValidatorRule, StoreValue } from 'rc-field-form/lib/interface'; import devWarning from '../_util/devWarning'; import { ConfigContext } from '../config-provider'; import { FormItemPrefixContext } from './context'; export interface FormListFi...
) => React.ReactNode; } const FormList: React.FC<FormListProps> = ({ prefixCls: customizePrefixCls, children, ...props }) => { devWarning(!!props.name, 'Form.List', 'Miss `name` prop.'); const { getPrefixCls } = React.useContext(ConfigContext); const prefixCls = getPrefixCls('form', customizePrefixCls);...
operation: FormListOperation, meta: { errors: React.ReactNode[] },
random_line_split
microbatched_model.py
import tensorflow as tf import numpy as np from baselines.ppo2.model import Model class MicrobatchedModel(Model):
max_grad_norm=max_grad_norm, mpi_rank_weight=mpi_rank_weight, comm=comm) self.grads_ph = [tf.placeholder(dtype=g.dtype, shape=g.shape) for g in self.grads] grads_ph_and_vars = list(zip(self.grads_ph, self.var)) self._apply_gradients_op = self.trai...
""" Model that does training one microbatch at a time - when gradient computation on the entire minibatch causes some overflow """ def __init__(self, *, policy, ob_space, ac_space, nbatch_act, nbatch_train, nsteps, ent_coef, vf_coef, max_grad_norm, mpi_rank_weight, comm, microbatch_size)...
identifier_body
microbatched_model.py
import tensorflow as tf import numpy as np from baselines.ppo2.model import Model class
(Model): """ Model that does training one microbatch at a time - when gradient computation on the entire minibatch causes some overflow """ def __init__(self, *, policy, ob_space, ac_space, nbatch_act, nbatch_train, nsteps, ent_coef, vf_coef, max_grad_norm, mpi_rank_weight, comm, mic...
MicrobatchedModel
identifier_name
microbatched_model.py
import tensorflow as tf import numpy as np from baselines.ppo2.model import Model class MicrobatchedModel(Model): """ Model that does training one microbatch at a time - when gradient computation on the entire minibatch causes some overflow """ def __init__(self, *, policy, ob_space, ac_space, nbat...
feed_dict = {ph: sum_g / self.nmicrobatches for ph, sum_g in zip(self.grads_ph, sum_grad_v)} feed_dict[self.LR] = lr # Update variables using average of the gradients self.sess.run(self._apply_gradients_op, feed_dict) # Return average of the stats return np.mean(np.arra...
_sli = range(microbatch_idx * self.microbatch_size, (microbatch_idx+1) * self.microbatch_size) td_map = { self.train_model.X: obs[_sli], self.A:actions[_sli], self.ADV:advs[_sli], self.R:returns[_sli], self.CLIPRANGE:cliprange, ...
conditional_block
microbatched_model.py
import tensorflow as tf import numpy as np from baselines.ppo2.model import Model class MicrobatchedModel(Model): """ Model that does training one microbatch at a time - when gradient computation on the entire minibatch causes some overflow """ def __init__(self, *, policy, ob_space, ac_space, nbat...
self.CLIPRANGE:cliprange, self.OLDNEGLOGPAC:neglogpacs[_sli], self.OLDVPRED:values[_sli] } # Compute gradient on a microbatch (note that variables do not change here) ... grad_v, stats_v = self.sess.run([self.grads, self.stats_list], ...
td_map = { self.train_model.X: obs[_sli], self.A:actions[_sli], self.ADV:advs[_sli], self.R:returns[_sli],
random_line_split
ObstacleBox.js
(function() { var isBrowser = (typeof window !== 'undefined'); //TODO: performance optimization -- merge geometries. http://learningthreejs.com/blog/2011/10/05/performance-merging-geometry/ function _ObstacleBoxFactory(THREE) { var textureLoader = new THREE.TextureLoader(); var obstacleBoxTexture1 = (isBrowser)...
const size = 10; var boxGeometry = new THREE.BoxGeometry(size, size, size); function ObstacleBox(type, originX, originY) { var boxMaterial = new THREE.MeshLambertMaterial({ map: getTexture(type), }); THREE.Mesh.call(this, boxGeometry, boxMaterial); this.position.set(originX + 5, originY + 5, 5);...
{ if (type == 1) return obstacleBoxTexture1; else if (type == 2) return obstacleBoxTexture2; else if (type == 3) return obstacleBoxTexture3; else if (type == 4) return obstacleBoxTexture4; else return obstacleBoxTexture5; }
identifier_body
ObstacleBox.js
(function() { var isBrowser = (typeof window !== 'undefined'); //TODO: performance optimization -- merge geometries. http://learningthreejs.com/blog/2011/10/05/performance-merging-geometry/ function
(THREE) { var textureLoader = new THREE.TextureLoader(); var obstacleBoxTexture1 = (isBrowser) ? textureLoader.load("textures/crate1.png") : null; var obstacleBoxTexture2 = (isBrowser) ? textureLoader.load("textures/crate2.png") : null; var obstacleBoxTexture3 = (isBrowser) ? textureLoader.load("textures/crate...
_ObstacleBoxFactory
identifier_name
ObstacleBox.js
(function() { var isBrowser = (typeof window !== 'undefined'); //TODO: performance optimization -- merge geometries. http://learningthreejs.com/blog/2011/10/05/performance-merging-geometry/ function _ObstacleBoxFactory(THREE) { var textureLoader = new THREE.TextureLoader(); var obstacleBoxTexture1 = (isBrowser)...
else if (type == 2) return obstacleBoxTexture2; else if (type == 3) return obstacleBoxTexture3; else if (type == 4) return obstacleBoxTexture4; else return obstacleBoxTexture5; } const size = 10; var boxGeometry = new THREE.BoxGeometry(size, size, size); function ObstacleBox(type, originX, originY)...
function getTexture(type) { if (type == 1) return obstacleBoxTexture1;
random_line_split
sample_ian.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from collections import OrderedDict import imp import time import logging import itertools import os import numpy as np from path import Path import theano import theano.tensor as T import lasagne from fuel.datasets import CelebA from gan.util import ( ...
l_IAF_ls = model['l_IAF_ls'] # Sample function sample = theano.function([Z],lasagne.layers.get_output(l_out,{l_Z_IAF:Z},deterministic=True),on_unused_input='warn') sampleZ = theano.function([Z],lasagne.layers.get_output(l_out,{l_Z:Z},deterministic=True),on_unused_input='warn') # Inference Func...
is_iaf = 'l_Z_IAF' in model.keys() # Image Input X = T.TensorType('float32', [False]*4)('X') # Latent Input, for providing latent values from the main function Z = T.TensorType('float32', [False]*2)('Z') # Latents # Model layers l_in = model['l_in'] l_out = model['l_out'] l_Z = model[...
identifier_body
sample_ian.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from collections import OrderedDict import imp import time import logging import itertools import os import numpy as np from path import Path import theano import theano.tensor as T import lasagne from fuel.datasets import CelebA from gan.util import ( ...
os.makedirs(res_dir) # Get configuration parameters cfg = config_module.CFG # Define name of npz file to which the model parameters will be saved if args.weights_file is None: weights_fname = os.path.join(res_dir, "weights.npz") else: weights_fname = args.weights_file ...
res_dir = os.path.join(DEFAULT_RES_DIR, model_name) if not os.path.isdir(res_dir):
random_line_split
sample_ian.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from collections import OrderedDict import imp import time import logging import itertools import os import numpy as np from path import Path import theano import theano.tensor as T import lasagne from fuel.datasets import CelebA from gan.util import ( ...
(cfg,model): # Define input tensors # Tensor axes are batch-channel-dim1-dim2 is_iaf = 'l_Z_IAF' in model.keys() # Image Input X = T.TensorType('float32', [False]*4)('X') # Latent Input, for providing latent values from the main function Z = T.TensorType('float32', [False]*2)('Z') # Latent...
make_training_functions
identifier_name
sample_ian.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse from collections import OrderedDict import imp import time import logging import itertools import os import numpy as np from path import Path import theano import theano.tensor as T import lasagne from fuel.datasets import CelebA from gan.util import ( ...
# Dictionary of Theano Variables tvars = {'X' : X, 'Z' : Z} return tfuncs, tvars, model # Main Function def main(args): # Load Config Module from source file model_name = os.path.basename(args.config_path)[:-3] config_module = imp.load_source(model_name, args.config_path) ...
Z_IAF_fn = theano.function([Z],lasagne.layers.get_output(l_Z,{l_Z_IAF:Z},deterministic=True),on_unused_input='warn') tfuncs['Z_IAF_fn'] = Z_IAF_fn
conditional_block
2082002.js
engine.eval("load('nashorn:mozilla_compat.js');"); /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modi...
{ if(mode == -1) { cm.dispose(); return; } else { status++; if(mode == 0) { cm.sendOk("You'll get to your destination in moment. Go ahead and talk to other people, and before you know it, you'll be there already."); cm.dispose(); return; } if(status == 0) { cm.sendYesNo("Do you want to leave t...
identifier_body
2082002.js
engine.eval("load('nashorn:mozilla_compat.js');"); /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modi...
} }
{ cm.warp(240000110); cm.dispose(); }
conditional_block
2082002.js
engine.eval("load('nashorn:mozilla_compat.js');");
Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software...
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
random_line_split