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
shard.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::Error; use context::{CoreContext, PerfCounterType}; use futures_stats::TimedTryFutureExt; use std::collections::hash_map::Defau...
stats.completion_time.as_millis_unchecked() as i64, ); Ok(permit) } } pub struct Shards { semaphores: Vec<Semaphore>, perf_counter_type: PerfCounterType, } impl Shards { pub fn new(shard_count: NonZeroUsize, perf_counter_type: PerfCounterType) -> Self { let semapho...
random_line_split
updater.js
var _ = require('underscore'); var runLog = require('../run-log.js'); var catalog = require('../catalog/catalog.js'); var archinfo = require('../archinfo.js'); var isopack = require('../isobuild/isopack.js'); var buildmessage = require('../buildmessage.js'); var Console = require('../console.js').Console; var auth = r...
// symlink to go to the default track.) var latestReleaseVersion = catalog.official.getDefaultReleaseVersion(); // Maybe you're on some random track with nothing recommended. That's OK. if (!latestReleaseVersion) return; var latestRelease = catalog.official.getReleaseVersion( latestReleaseVersion.tra...
random_line_split
client.js
// // AutoLinker is a named function that will replace links on messages // @param {Object} message - The message object // import Autolinker from 'autolinker'; function
(message) { if (RocketChat.settings.get('AutoLinker') !== true) { return message; } if (_.trim(message.html)) { const regUrls = new RegExp(RocketChat.settings.get('AutoLinker_UrlsRegExp')); const autolinker = new Autolinker({ stripPrefix: RocketChat.settings.get('AutoLinker_StripPrefix'), urls: { s...
AutoLinker
identifier_name
client.js
// // AutoLinker is a named function that will replace links on messages // @param {Object} message - The message object // import Autolinker from 'autolinker'; function AutoLinker(message) { if (RocketChat.settings.get('AutoLinker') !== true) { return message; } if (_.trim(message.html)) { const regUrls = ne...
tldMatches: RocketChat.settings.get('AutoLinker_Urls_TLD') }, email: RocketChat.settings.get('AutoLinker_Email'), phone: RocketChat.settings.get('AutoLinker_Phone'), twitter: false, replaceFn(match) { if (match.getType() === 'url') { if (regUrls.test(match.matchedText)) { if (match.mat...
urls: { schemeMatches: RocketChat.settings.get('AutoLinker_Urls_Scheme'), wwwMatches: RocketChat.settings.get('AutoLinker_Urls_www'),
random_line_split
client.js
// // AutoLinker is a named function that will replace links on messages // @param {Object} message - The message object // import Autolinker from 'autolinker'; function AutoLinker(message) { if (RocketChat.settings.get('AutoLinker') !== true) { return message; } if (_.trim(message.html)) { const regUrls = ne...
}); let regNonAutoLink = /(```\w*[\n ]?[\s\S]*?```+?)|(`(?:[^`]+)`)/; if (RocketChat.settings.get('Katex_Enabled')) { regNonAutoLink = /(```\w*[\n ]?[\s\S]*?```+?)|(`(?:[^`]+)`)|(\\\(\w*[\n ]?[\s\S]*?\\\)+?)/; } // Separate text in code blocks and non code blocks const msgParts = message.html.split(re...
{ if (match.getType() === 'url') { if (regUrls.test(match.matchedText)) { if (match.matchedText.indexOf(Meteor.absoluteUrl()) === 0) { // returns an `Autolinker.HtmlTag` instance for an <a> tag const tag = match.buildTag(); // sets target to empty, instead of _blank tag.setAtt...
identifier_body
client.js
// // AutoLinker is a named function that will replace links on messages // @param {Object} message - The message object // import Autolinker from 'autolinker'; function AutoLinker(message) { if (RocketChat.settings.get('AutoLinker') !== true) { return message; } if (_.trim(message.html)) { const regUrls = ne...
// Separate text in code blocks and non code blocks const msgParts = message.html.split(regNonAutoLink); msgParts.forEach((part, index) => { if (part && part.length > 0) { // Verify if this part is code const codeMatch = part.match(regNonAutoLink); if (!codeMatch) { msgParts[index] = autoli...
{ regNonAutoLink = /(```\w*[\n ]?[\s\S]*?```+?)|(`(?:[^`]+)`)|(\\\(\w*[\n ]?[\s\S]*?\\\)+?)/; }
conditional_block
ListTypeIcon.tsx
import React from 'react'; import {TypeIcon, SelectBox} from './index'; import classNames from 'classnames'; interface IProps { selectingDisabled?: boolean; onMultiSelect: () => void; item: any; } interface IState { hover: boolean; } export class ListTypeIcon extends React.Component<IProps, IState> {...
type: this.props.item.type, highlight: this.props.item.highlight, }, ), ); } }
{ const {selectingDisabled} = this.props; const showSelect = selectingDisabled !== true && (this.state.hover || this.props.item.selected); return React.createElement( 'div', { className: classNames('list-field type-icon sd-monitoring-item-multi-select-che...
identifier_body
ListTypeIcon.tsx
import React from 'react'; import {TypeIcon, SelectBox} from './index'; import classNames from 'classnames'; interface IProps { selectingDisabled?: boolean; onMultiSelect: () => void; item: any; } interface IState { hover: boolean; } export class ListTypeIcon extends React.Component<IProps, IState> {...
} render() { const {selectingDisabled} = this.props; const showSelect = selectingDisabled !== true && (this.state.hover || this.props.item.selected); return React.createElement( 'div', { className: classNames('list-field type-icon sd-monitoring-...
{ this.setState({hover: false}); }
conditional_block
ListTypeIcon.tsx
import React from 'react'; import {TypeIcon, SelectBox} from './index'; import classNames from 'classnames'; interface IProps { selectingDisabled?: boolean; onMultiSelect: () => void; item: any; } interface IState { hover: boolean; } export class ListTypeIcon extends React.Component<IProps, IState> {...
() { if (this.state.hover) { this.setState({hover: false}); } } render() { const {selectingDisabled} = this.props; const showSelect = selectingDisabled !== true && (this.state.hover || this.props.item.selected); return React.createElement( 'div',...
unsetHover
identifier_name
ListTypeIcon.tsx
import React from 'react'; import {TypeIcon, SelectBox} from './index'; import classNames from 'classnames'; interface IProps { selectingDisabled?: boolean; onMultiSelect: () => void; item: any; } interface IState { hover: boolean; } export class ListTypeIcon extends React.Component<IProps, IState> {...
const showSelect = selectingDisabled !== true && (this.state.hover || this.props.item.selected); return React.createElement( 'div', { className: classNames('list-field type-icon sd-monitoring-item-multi-select-checkbox'), onMouseEnter: selectingDi...
const {selectingDisabled} = this.props;
random_line_split
canvas_texture.ts
import {Texture} from "./texture" import * as p from "core/properties" import {Context2d} from 'core/util/canvas' import {use_strict} from 'core/util/string' export namespace CanvasTexture { export type Attrs = p.AttrsOf<Props> export type Props = Texture.Props & { code: p.Property<string> } } ...
get_pattern(color: any, scale: number, weight: number): (ctx: Context2d) => CanvasPattern | null { return (ctx: Context2d): CanvasPattern | null => { const canvas = document.createElement('canvas') canvas.width = scale canvas.height = scale const pattern_ctx = canvas.getContext('2d') ...
return new Function("ctx", "color", "scale", "weight", code) }
random_line_split
canvas_texture.ts
import {Texture} from "./texture" import * as p from "core/properties" import {Context2d} from 'core/util/canvas' import {use_strict} from 'core/util/string' export namespace CanvasTexture { export type Attrs = p.AttrsOf<Props> export type Props = Texture.Props & { code: p.Property<string> } } ...
(): void { this.define<CanvasTexture.Props>({ code: [ p.String ], }) } get func(): Function { const code = use_strict(this.code) return new Function("ctx", "color", "scale", "weight", code) } get_pattern(color: any, scale: number, weight: number): (ctx: Context2d) => CanvasPattern | null...
init_CanvasTexture
identifier_name
canvas_texture.ts
import {Texture} from "./texture" import * as p from "core/properties" import {Context2d} from 'core/util/canvas' import {use_strict} from 'core/util/string' export namespace CanvasTexture { export type Attrs = p.AttrsOf<Props> export type Props = Texture.Props & { code: p.Property<string> } } ...
}
{ return (ctx: Context2d): CanvasPattern | null => { const canvas = document.createElement('canvas') canvas.width = scale canvas.height = scale const pattern_ctx = canvas.getContext('2d') this.func.call(this, pattern_ctx, color, scale, weight) return ctx.createPattern(canvas, thi...
identifier_body
0033_apiaccess.py
# Generated by Django 2.2.13 on 2020-10-23 00:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
('level', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='api_access', to='community.AccessLevel')), ], options={ 'unique_together': {('community', 'level')}, }, ), ]
dependencies = [ ('community', '0032_accesslevel'), ] operations = [ migrations.CreateModel( name='ApiAccess', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('status_limit', mod...
identifier_body
0033_apiaccess.py
# Generated by Django 2.2.13 on 2020-10-23 00:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('community', '0032_accesslevel'), ] operations = [ migrations.CreateModel( name='ApiAccess', ...
'unique_together': {('community', 'level')}, }, ), ]
random_line_split
0033_apiaccess.py
# Generated by Django 2.2.13 on 2020-10-23 00:43 from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('community', '0032_accesslevel'), ] operations = [ migrations.CreateModel( name='ApiAccess', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
Migration
identifier_name
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os from indico.core import signals from indico.core.db import db from .logger import logger from ...
@signals.users.merged.connect def _delete_merged_user_tokens(target, source, **kwargs): target_app_links = {link.application: link for link in target.oauth_app_links} for source_link in source.oauth_app_links.all(): try: target_link = target_app_links[source_link.application] excep...
@signals.core.app_created.connect def _no_ssl_required_on_debug(app, **kwargs): if app.debug or app.testing: os.environ['AUTHLIB_INSECURE_TRANSPORT'] = '1'
random_line_split
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os from indico.core import signals from indico.core.db import db from .logger import logger from ...
logger.info('merge: merging %r into %r', source_link, target_link) target_link.update_scopes(set(source_link.scopes)) target_link.tokens.extend(source_link.tokens) db.session.delete(source_link)
conditional_block
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os from indico.core import signals from indico.core.db import db from .logger import logger from ...
target_app_links = {link.application: link for link in target.oauth_app_links} for source_link in source.oauth_app_links.all(): try: target_link = target_app_links[source_link.application] except KeyError: logger.info('merge: reassigning %r to %r', source_link, target) ...
identifier_body
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. import os from indico.core import signals from indico.core.db import db from .logger import logger from ...
(target, source, **kwargs): target_app_links = {link.application: link for link in target.oauth_app_links} for source_link in source.oauth_app_links.all(): try: target_link = target_app_links[source_link.application] except KeyError: logger.info('merge: reassigning %r to ...
_delete_merged_user_tokens
identifier_name
login.js
function loginKey(event) {if(event.keyCode == 13) login();} function login() { var username = document.getElementById('username').value; var password = document.getElementById('password').value; var success = Handler.Login(username,password); var out = document.getElementById('t'); if(success) { ...
() { return "Gooey Booey Chika laka chucha"; } function newAlert(message) { document.getElementById("message").innerHTML = message; document.getElementById("dialog").style.display = "block"; }
run
identifier_name
login.js
function loginKey(event) {if(event.keyCode == 13) login();} function login() { var username = document.getElementById('username').value; var password = document.getElementById('password').value; var success = Handler.Login(username,password); var out = document.getElementById('t'); if(success) { ...
{ document.getElementById("message").innerHTML = message; document.getElementById("dialog").style.display = "block"; }
identifier_body
login.js
function loginKey(event) {if(event.keyCode == 13) login();} function login() { var username = document.getElementById('username').value; var password = document.getElementById('password').value; var success = Handler.Login(username,password); var out = document.getElementById('t'); if(success) { ...
document.getElementById("dialog").style.display = "block"; }
document.getElementById("message").innerHTML = message;
random_line_split
004-280565a54124-add_custom_head_tags.py
# This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2015 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) any later version. # See LICENSE.txt in the main project ...
settings.insert().\ values({ 'key': inline_literal(key), 'value': inline_literal(value), }) ) def delete_setting(key): execute( settings.delete().\ where(settings.c.key==inline_literal(key)) ) # ----------------------------...
# -- helpers ------------------------------------------------------------------ def insert_setting(key, value): execute(
random_line_split
004-280565a54124-add_custom_head_tags.py
# This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2015 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) any later version. # See LICENSE.txt in the main project ...
# ----------------------------------------------------------------------------- SETTINGS = [ (u'appearance_custom_head_tags', u''), ] def upgrade(): for key, value in SETTINGS: insert_setting(key, value) def downgrade(): for key, value in SETTINGS: delete_setting(key)
execute( settings.delete().\ where(settings.c.key==inline_literal(key)) )
identifier_body
004-280565a54124-add_custom_head_tags.py
# This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2015 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) any later version. # See LICENSE.txt in the main project ...
(): for key, value in SETTINGS: insert_setting(key, value) def downgrade(): for key, value in SETTINGS: delete_setting(key)
upgrade
identifier_name
004-280565a54124-add_custom_head_tags.py
# This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2015 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) any later version. # See LICENSE.txt in the main project ...
delete_setting(key)
conditional_block
keymap.rs
how many characters at the front of KEY /// it takes to reach a non-prefix key. /// /// Normally, `lookup-key' ignores bindings for t, which act as default /// bindings, used when nothing else in the keymap applies; this makes it /// usable as a general function for probing keymaps. However, if the /// third optional...
key_binding
identifier_name
keymap.rs
/// Return t if OBJECT is a keymap. /// /// A keymap is a list (keymap . ALIST), /// or a symbol whose function definition is itself a keymap. /// ALIST elements look like (CHAR . DEFN) or (SYMBOL . DEFN); /// a vector of densely packed bindings for small character codes /// is also allowed as an element. #[lisp_fn] ...
{ let tail: LispObject = if string.is_not_nil() { list!(string) } else { Qnil }; let char_table = unsafe { Fmake_char_table(Qkeymap, Qnil) }; (Qkeymap, (char_table, tail)) }
identifier_body
keymap.rs
make_char_table(Qkeymap, Qnil) }; (Qkeymap, (char_table, tail)) } /// Return t if OBJECT is a keymap. /// /// A keymap is a list (keymap . ALIST), /// or a symbol whose function definition is itself a keymap. /// ALIST elements look like (CHAR . DEFN) or (SYMBOL . DEFN); /// a vector of densely packed bindings for...
} if !map.is_cons() { map = get_keymap(map, false, autoload); } } } /// Call FUNCTION once for each event binding in KEYMAP. /// FUNCTION is called with two arguments: the event that is bound, and /// the definition it is bound to. The event may be a character range. /// /// ...
{ map = map_keymap_internal(map, fun, args, data); }
conditional_block
keymap.rs
has a parent, this function returns it without processing it. #[lisp_fn(name = "map-keymap-internal", c_name = "map_keymap_internal")] pub fn map_keymap_internal_lisp(function: LispObject, mut keymap: LispObject) -> LispObject { keymap = get_keymap(keymap, true, true); unsafe { map_keymap_internal(keymap, Some...
/// (set-keymap-parent map <theirmap>)
random_line_split
_Pose3DOF.py
"""autogenerated by genpy from hrl_lib/Pose3DOF.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import std_msgs.msg class Pose3DOF(genpy.Message): _md5sum = "646ead44a0e6fecf4e14ca116f12b08b" _type = "hrl_lib/Pose3DOF" _has_header = True #flag ...
(self, buff, numpy): """ serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module """ try: _x = self buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id...
serialize_numpy
identifier_name
_Pose3DOF.py
"""autogenerated by genpy from hrl_lib/Pose3DOF.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import std_msgs.msg class Pose3DOF(genpy.Message): _md5sum = "646ead44a0e6fecf4e14ca116f12b08b" _type = "hrl_lib/Pose3DOF" _has_header = True #flag ...
float64 dt ================================================================================ MSG: std_msgs/Header # Standard metadata for higher-level stamped data types. # This is generally used to communicate timestamped data # in a particular coordinate frame. # # sequence ID: consecutively increasing ID uint32 ...
random_line_split
_Pose3DOF.py
"""autogenerated by genpy from hrl_lib/Pose3DOF.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import std_msgs.msg class Pose3DOF(genpy.Message): _md5sum = "646ead44a0e6fecf4e14ca116f12b08b" _type = "hrl_lib/Pose3DOF" _has_header = True #flag ...
_x = self start = end end += 32 (_x.x, _x.y, _x.theta, _x.dt,) = _struct_4d.unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I _struct_3I = struct.Struct("<3I") _struct_4d = s...
self.header.frame_id = str[start:end]
conditional_block
_Pose3DOF.py
"""autogenerated by genpy from hrl_lib/Pose3DOF.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import std_msgs.msg class Pose3DOF(genpy.Message): _md5sum = "646ead44a0e6fecf4e14ca116f12b08b" _type = "hrl_lib/Pose3DOF" _has_header = True #flag ...
def serialize(self, buff): """ serialize message into buffer :param buff: buffer, ``StringIO`` """ try: _x = self buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x...
""" internal API method """ return self._slot_types
identifier_body
urls.py
from __future__ import absolute_import from django.conf.urls import url from oauth2_provider import views from .views import CoffeestatsApplicationRegistration, \ CoffeestatsApplicationDetail, \ CoffeestatsApplicationApproval, \ CoffeestatsApplicationRejection, \ CoffeestatsApplicationFullList urlpat...
views.AuthorizedTokenDeleteView.as_view(), name="authorized-token-delete"), )
urlpatterns += ( url(r'^authorized_tokens/$', views.AuthorizedTokensListView.as_view(), name="authorized-token-list"), url(r'^authorized_tokens/(?P<pk>\d+)/delete/$',
random_line_split
auth.ts
import assign = require('../lib/base/assign'); import { bufferFromString, hexlify } from '../lib/base/collectionutil'; import crypto = require('../lib/base/crypto'); import env = require('../lib/base/env'); import { defer } from '../lib/base/promise_util'; import { parseHash } from '../lib/base/url_util'; export inter...
}, 200); credentials.promise.catch(() => {}).then(() => { if (authWindow) { authWindow.close(); } clearTimeout(pollTimeout); }); return credentials.promise; } }
{ credentials.reject(new Error('Login canceled')); }
conditional_block
auth.ts
import assign = require('../lib/base/assign'); import { bufferFromString, hexlify } from '../lib/base/collectionutil'; import crypto = require('../lib/base/crypto'); import env = require('../lib/base/env'); import { defer } from '../lib/base/promise_util'; import { parseHash } from '../lib/base/url_util'; export inter...
{ private options: OAuthFlowOptions; constructor(options: OAuthFlowOptions) { let defaultRedirectURL: string = document.location.href.replace( /\/[a-z]+\.html|\/$|$/, '/auth.html' ); if (env.isChromeExtension()) { // for Firefox the auth redirect URL...
OAuthFlow
identifier_name
auth.ts
import assign = require('../lib/base/assign'); import { bufferFromString, hexlify } from '../lib/base/collectionutil'; import crypto = require('../lib/base/crypto'); import env = require('../lib/base/env'); import { defer } from '../lib/base/promise_util'; import { parseHash } from '../lib/base/url_util'; export inter...
interface TabChangeInfo { url?: string; } const DUMMY_OAUTH_REDIRECT_URL = 'http://localhost:8000/webui/index.html'; /** * Wait for OAuth authentication to complete and redirect to a dummy URL from * which we extract the hash. */ function interceptOAuthRedirect() { const listener = (tabId: number, change...
{ return Object.keys(settings) .map(key => `${key}=${settings[key]}`) .join(','); }
identifier_body
auth.ts
import assign = require('../lib/base/assign'); import { bufferFromString, hexlify } from '../lib/base/collectionutil'; import crypto = require('../lib/base/crypto'); import env = require('../lib/base/env'); import { defer } from '../lib/base/promise_util'; import { parseHash } from '../lib/base/url_util'; export inter...
let requiredFields = ['state', 'accessToken']; for (let field of requiredFields) { if (!tokenData[field]) { throw new Error( `Missing field "${field}" in token data` )...
win.localStorage.removeItem(OAUTH_TOKEN_KEY); let tokenData = <TokenData>JSON.parse(tokenDataStr);
random_line_split
noise_stats.py
from paths import rpath,mpath,opath from make_apex_cubes import all_apexfiles,get_source_tel_line,_is_sci, hdr_to_freq from pyspeckit.spectrum.readers import read_class from astropy.table import Table from astropy import log from astropy.utils.console import ProgressBar import numpy as np import os import pylab as pl ...
(plot=False): if plot: fig1 = pl.figure(1) fig2 = pl.figure(2) fig1.clf() fig2.clf() ax1 = fig1.gca() ax2 = fig2.gca() datadict = {} tbldict = {} for apex_filename in all_apexfiles: log.info(apex_filename) cl = read_class.ClassObject(ape...
tsys_data
identifier_name
noise_stats.py
from paths import rpath,mpath,opath from make_apex_cubes import all_apexfiles,get_source_tel_line,_is_sci, hdr_to_freq from pyspeckit.spectrum.readers import read_class from astropy.table import Table from astropy import log from astropy.utils.console import ProgressBar import numpy as np import os import pylab as pl ...
datadict = {} tbldict = {} for apex_filename in all_apexfiles: log.info(apex_filename) cl = read_class.ClassObject(apex_filename) sourcereg,line,telescopes = get_source_tel_line(apex_filename) sci_sources = [source for source in cl.sources if _is_sc...
fig1 = pl.figure(1) fig2 = pl.figure(2) fig1.clf() fig2.clf() ax1 = fig1.gca() ax2 = fig2.gca()
conditional_block
noise_stats.py
from paths import rpath,mpath,opath from make_apex_cubes import all_apexfiles,get_source_tel_line,_is_sci, hdr_to_freq from pyspeckit.spectrum.readers import read_class from astropy.table import Table from astropy import log from astropy.utils.console import ProgressBar import numpy as np import os import pylab as pl ...
for telescope in telescopes: log.info('{0}: {1}'.format(apex_filename, telescope)) selection = [x for source in sci_sources for x in cl.select_spectra(telescope=telescope, line=line, ...
if plot: fig1 = pl.figure(1) fig2 = pl.figure(2) fig1.clf() fig2.clf() ax1 = fig1.gca() ax2 = fig2.gca() datadict = {} tbldict = {} for apex_filename in all_apexfiles: log.info(apex_filename) cl = read_class.ClassObject(apex_filename) ...
identifier_body
noise_stats.py
from paths import rpath,mpath,opath from make_apex_cubes import all_apexfiles,get_source_tel_line,_is_sci, hdr_to_freq from pyspeckit.spectrum.readers import read_class from astropy.table import Table from astropy import log from astropy.utils.console import ProgressBar import numpy as np import os import pylab as pl ...
for ii in (0,1)], names=[t+"_"+s for t in telescopes for s in ('STDDEV','TSYS',)], dtype=['float' for t in telescopes for s in ('STDDEV','TSYS',) ...
for t in telescopes
random_line_split
define.py
import urllib import ast import xchat __module_name__ = "Define" __module_author__ = "TingPing" __module_version__ = "2" __module_description__ = "Show word definitions" # based on google dictionary script by Sridarshan Shetty - http://sridarshan.co.cc def define(word, word_eol, userdata): if len(word) >= 2: _wor...
index+=1 return xchat.EAT_ALL else: xchat.prnt('Description unavailable for ' + _word) return xchat.EAT_ALL xchat.hook_command("define", define) xchat.prnt(__module_name__ + ' version ' + __module_version__ + ' loaded.')
if i["type"]=="meaning": ans=i["terms"] op=ans[0]['text'] split=op.split(';') xchat.prnt(_word + ': ' + split[0].strip())
conditional_block
define.py
import urllib import ast import xchat __module_name__ = "Define" __module_author__ = "TingPing" __module_version__ = "2" __module_description__ = "Show word definitions" # based on google dictionary script by Sridarshan Shetty - http://sridarshan.co.cc def define(word, word_eol, userdata): if len(word) >= 2: _wor...
xchat.hook_command("define", define) xchat.prnt(__module_name__ + ' version ' + __module_version__ + ' loaded.')
random_line_split
define.py
import urllib import ast import xchat __module_name__ = "Define" __module_author__ = "TingPing" __module_version__ = "2" __module_description__ = "Show word definitions" # based on google dictionary script by Sridarshan Shetty - http://sridarshan.co.cc def define(word, word_eol, userdata):
index=1 for i in webdef: if index == _number: if i["type"]=="meaning": ans=i["terms"] op=ans[0]['text'] split=op.split(';') xchat.prnt(_word + ': ' + split[0].strip()) index+=1 return xchat.EAT_ALL else: xchat.prnt('Description unavailable for ' + _word) return xchat.EAT_ALL ...
if len(word) >= 2: _word = xchat.strip(word[1]) _number = 1 if len(word) >= 3: _number = int(xchat.strip(word[2])) else: xchat.prnt('Define Usage: /define word [number]') xchat.prnt(' number being alternate definition') return xchat.EAT_ALL url="http://www.google.com/dictionary/json?callback=s&q=" + _...
identifier_body
define.py
import urllib import ast import xchat __module_name__ = "Define" __module_author__ = "TingPing" __module_version__ = "2" __module_description__ = "Show word definitions" # based on google dictionary script by Sridarshan Shetty - http://sridarshan.co.cc def
(word, word_eol, userdata): if len(word) >= 2: _word = xchat.strip(word[1]) _number = 1 if len(word) >= 3: _number = int(xchat.strip(word[2])) else: xchat.prnt('Define Usage: /define word [number]') xchat.prnt(' number being alternate definition') return xchat.EAT_ALL url="http://www.google.com/dict...
define
identifier_name
slice.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 ...
let b = [1, 2, 4, 6, 8, 9]; assert!(b.binary_search_by(|v| v.cmp(&6)) == Ok(3)); let b = [1, 2, 4, 6, 8, 9]; assert!(b.binary_search_by(|v| v.cmp(&5)) == Err(3)); let b = [1, 2, 4, 6, 7, 8, 9]; assert!(b.binary_search_by(|v| v.cmp(&6)) == Ok(3)); let b = [1, 2, 4, 6, 7, 8, 9]; assert!(b....
random_line_split
slice.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 ...
{ let mut iter = data.iter_mut(); assert_eq!(&iter[], &other_data[]); // mutability: assert!(&mut iter[] == other_data); iter.next(); assert_eq!(&iter[], &other_data[1..]); assert!(&mut iter[] ==...
{ macro_rules! test { ($data: expr) => {{ let data: &mut [_] = &mut $data; let other_data: &mut [_] = &mut $data; { let mut iter = data.iter(); assert_eq!(&iter[], &other_data[]); iter.next(); assert_eq!(&i...
identifier_body
slice.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 ...
() { macro_rules! test { ($data: expr) => {{ let data: &mut [_] = &mut $data; let other_data: &mut [_] = &mut $data; { let mut iter = data.iter(); assert_eq!(&iter[], &other_data[]); iter.next(); assert_eq!...
iterator_to_slice
identifier_name
mass-text.service.ts
import { Injectable } from "@angular/core"; import { Http } from "@angular/http"; import * as moment from "moment"; import { Observable } from "rxjs"; import { MassTextSendResponse } from "./mass-text-send-response"; import { BaseService } from "../utils/base.service"; import { ApiKeyService } from "../utils/api-key.s...
( startDate: moment.Moment, endDate: moment.Moment, template: string, expectedRendered: string ): Observable<MassTextSendResponse> { const body = { startDate: startDate, endDate: endDate, template: template, expectedRendered: expectedRendered }; return this.post(th...
send
identifier_name
mass-text.service.ts
import { Injectable } from "@angular/core"; import { Http } from "@angular/http"; import * as moment from "moment"; import { Observable } from "rxjs"; import { MassTextSendResponse } from "./mass-text-send-response"; import { BaseService } from "../utils/base.service"; import { ApiKeyService } from "../utils/api-key.s...
}
random_line_split
form-field.d.ts
export declare const _MAT_HINT: InjectionToken<MatHint>; export declare type FloatLabelType = 'always' | 'never' | 'auto'; export declare function getMatFormFieldDuplicatedHintError(align: string): Error; export declare function getMatFormFieldMissingControlError(): Error; export declare function getMatFormFieldPla...
d'; id: string; static ɵdir: i0.ɵɵDirectiveDefWithMeta<MatHint, "mat-hint", never, { "align": "align"; "id": "id"; }, {}, never>; static ɵfac: i0.ɵɵFactoryDef<MatHint, never>; } export declare class MatLabel { static ɵdir: i0.ɵɵDirectiveDefWithMeta<MatLabel, "mat-label", never, {}, {}, never>; stat...
' | 'en
identifier_name
form-field.d.ts
export declare const _MAT_HINT: InjectionToken<MatHint>; export declare type FloatLabelType = 'always' | 'never' | 'auto'; export declare function getMatFormFieldDuplicatedHintError(align: string): Error; export declare function getMatFormFieldMissingControlError(): Error; export declare function getMatFormFieldPla...
} export declare const matFormFieldAnimations: { readonly transitionMessages: AnimationTriggerMetadata; }; export declare type MatFormFieldAppearance = 'legacy' | 'standard' | 'fill' | 'outline'; export declare abstract class MatFormFieldControl<T> { readonly autofilled?: boolean; readonly controlType?: ...
ngOnDestroy(): void; updateOutlineGap(): void; static ngAcceptInputType_hideRequiredMarker: BooleanInput; static ɵcmp: i0.ɵɵComponentDefWithMeta<MatFormField, "mat-form-field", ["matFormField"], { "color": "color"; "appearance": "appearance"; "hideRequiredMarker": "hideRequiredMarker"; "hintLabel": "hin...
random_line_split
Animation.js
/** * 애니메이션 부모 클래스 * * @class * @extends collie.Component * @param {Function} fCallback 타이머 콜백 함수 * @param {Number} nDuration 타이머 실행 시간, 지연 시간 (ms) * @param {Object} htOption 설정 * @param {Boolean} htOption.useAutoStart TimerList에 추가될 때 자동으로 시작 된다 * @param {Function} [htOption.on이벤트명] onComplete와 같이 이...
* @param {Number|String} nDuration 실행 시간, 지연 시간 설정 (ms) */ setDuration : function (nDuration) { this._nDuration = parseInt(nDuration, 10); }, /** * Duration을 반환 * * @return {Number} (ms) */ getDuration : function () { return this._nDuration...
}, /** * Duration을 설정 *
random_line_split
Animation.js
/** * 애니메이션 부모 클래스 * * @class * @extends collie.Component * @param {Function} fCallback 타이머 콜백 함수 * @param {Number} nDuration 타이머 실행 시간, 지연 시간 (ms) * @param {Object} htOption 설정 * @param {Boolean} htOption.useAutoStart TimerList에 추가될 때 자동으로 시작 된다 * @param {Function} [htOption.on이벤트명] onComplete와 같이 이...
행 중 */ isPlaying : function () { return this._bIsPlaying; }, /** * 애니메이션이 완료 됐을 때 실행 */ complete : function () { if (this.isPlaying()) { if (this._fCallbackComplete) { this._fCallbackComplete(); } ...
oTimerList !== null) { this._oTimerList.add(this); } /** * 타이머를 실행할 때 발생. Timer를 이용해서 생성할 때는 생성하는 순간 시작 상태이다. * @name collie.Animation#start * @event * @param {Object} oEvent 기본 컴포넌트 이벤트 객체 */ ...
conditional_block
useFirestore.js
import { useContext } from 'react' import ReduxFirestoreContext from './ReduxFirestoreContext' /** * @name useFirestore * @description React hook that return firestore object. * @returns {object} - Extended Firestore instance * @see https://react-redux-firebase.com/docs/api/useFirestore.html * @example <caption>B...
() { return useContext(ReduxFirestoreContext) }
useFirestore
identifier_name
useFirestore.js
import { useContext } from 'react' import ReduxFirestoreContext from './ReduxFirestoreContext' /** * @name useFirestore * @description React hook that return firestore object. * @returns {object} - Extended Firestore instance * @see https://react-redux-firebase.com/docs/api/useFirestore.html * @example <caption>B...
return useContext(ReduxFirestoreContext) }
* } */ export default function useFirestore() {
random_line_split
useFirestore.js
import { useContext } from 'react' import ReduxFirestoreContext from './ReduxFirestoreContext' /** * @name useFirestore * @description React hook that return firestore object. * @returns {object} - Extended Firestore instance * @see https://react-redux-firebase.com/docs/api/useFirestore.html * @example <caption>B...
{ return useContext(ReduxFirestoreContext) }
identifier_body
main.js
// ES2015 사용을 위한 babel 모듈 호출 import 'babel-polyfill'; // 전역 변수 객체 호출 import globalConfig from './helpers/global-config';
// npm 모듈 호출 import mobileDetect from 'mobile-detect'; //import scroll from 'scroll'; //import ease from 'ease-component'; import detectScrollPageObj from 'scroll-doc'; // devTools 호출 import devTools from './devtools/dev-tools'; import mirror from './devtools/mirror'; import preview from './devtools/preview'; // 헬퍼 ...
random_line_split
image_utils.py
[height, width] if n_channels == 1: curr_image = np.reshape(curr_image, [height, width]) s = io.BytesIO() matplotlib_pyplot().imsave(s, curr_image, format="png") img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=height, width=width, ...
(self): return ["ID_%d" % i for i in range(self.num_classes)] def feature_encoders(self, data_dir): del data_dir return { "inputs": text_encoder.ImageEncoder(channels=self.num_channels), "targets": text_encoder.ClassLabelEncoder(self.class_labels) } def generator(self, data_dir, tm...
class_labels
identifier_name
image_utils.py
[height, width] if n_channels == 1: curr_image = np.reshape(curr_image, [height, width]) s = io.BytesIO() matplotlib_pyplot().imsave(s, curr_image, format="png") img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=height, width=width, ...
return all_summaries def resize_by_area(img, size): """image resize function used by quite a few image problems.""" return tf.to_int64( tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) def make_multiscale(image, resolutions, resize_method=tf.image.ResizeMethod....
output_summary = image_to_tf_summary_value( prediction["outputs"], tag="%d_output" % ind) input_summary = image_to_tf_summary_value( prediction["inputs"], tag="%d_input" % ind) all_summaries.append(input_summary) all_summaries.append(output_summary)
conditional_block
image_utils.py
to [height, width] if n_channels == 1: curr_image = np.reshape(curr_image, [height, width]) s = io.BytesIO() matplotlib_pyplot().imsave(s, curr_image, format="png") img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=height, width=width, ...
dilation_rate = image_height // height # assuming height = width scaled_image = image[::dilation_rate, ::dilation_rate] scaled_image = tf.to_int64(scaled_image) scaled_image.set_shape([None, None, num_channels]) scaled_images.append(scaled_image) return scaled_images class ImageProblem(problem...
"""Returns list of scaled images, one for each resolution. Resizes by skipping every nth pixel. Args: image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. The function assumes VALID padding, so the original image's height must be divi...
identifier_body
image_utils.py
to [height, width] if n_channels == 1: curr_image = np.reshape(curr_image, [height, width]) s = io.BytesIO() matplotlib_pyplot().imsave(s, curr_image, format="png") img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=height, width=width, ...
"""Optionally converts images from hooks_args to image summaries. Args: hook_args: DecodeHookArgs namedtuple Returns: summaries: list of tf.Summary values if hook_args.decode_hpara """ decode_hparams = hook_args.decode_hparams if not decode_hparams.display_decoded_images: return [] prediction...
return tf.Summary.Value(tag=tag, image=img_sum) def convert_predictions_to_image_summaries(hook_args):
random_line_split
datepicker.ts
ulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MdDatepickerContent<D> implements AfterContentInit { datepicker: MdDatepicker<D>; @ViewChild(MdCalendar) _calendar: MdCalendar<D>; ngAfterContentInit() { this._calendar._focusActiveCell(); } /** * Han...
random_line_split
datepicker.ts
.com/Microsoft/TypeScript/issues/14953) // tslint:disable-next-line:no-unused-variable ScrollStrategy, } from '@angular/cdk/overlay'; import {ComponentPortal} from '@angular/cdk/portal'; import {Directionality} from '@angular/cdk/bidi'; import {ESCAPE} from '@angular/cdk/keycodes'; import {MdDialog} from '../dialog...
if (!this._datepickerInput) { throw Error('Attempted to open an MdDatepicker with no associated input.'); } if (this._document) { this._focusedElementBeforeOpen = this._document.activeElement; } this.touchUi ? this._openAsDialog() : this._openAsPopup(); this.opened = true; } /...
{ return; }
conditional_block
datepicker.ts
.com/Microsoft/TypeScript/issues/14953) // tslint:disable-next-line:no-unused-variable ScrollStrategy, } from '@angular/cdk/overlay'; import {ComponentPortal} from '@angular/cdk/portal'; import {Directionality} from '@angular/cdk/bidi'; import {ESCAPE} from '@angular/cdk/keycodes'; import {MdDialog} from '../dialog...
private _validSelected: D | null = null; /** The minimum selectable date. */ get _minDate(): D | null { return this._datepickerInput && this._datepickerInput.min; } /** The maximum selectable date. */ get _maxDate(): D | null { return this._datepickerInput && this._datepickerInput.max; } get...
{ this._validSelected = value; }
identifier_body
datepicker.ts
github.com/Microsoft/TypeScript/issues/14953) // tslint:disable-next-line:no-unused-variable ScrollStrategy, } from '@angular/cdk/overlay'; import {ComponentPortal} from '@angular/cdk/portal'; import {Directionality} from '@angular/cdk/bidi'; import {ESCAPE} from '@angular/cdk/keycodes'; import {MdDialog} from '../...
(): (date: D | null) => boolean { return this._datepickerInput && this._datepickerInput._dateFilter; } /** A reference to the overlay when the calendar is opened as a popup. */ private _popupRef: OverlayRef; /** A reference to the dialog when the calendar is opened as a dialog. */ private _dialogRef: Md...
_dateFilter
identifier_name
metadata.py
# (c) 2014 Michael DeHaan, <michael@ansible.com> # # This file is part of Ansible # # Ansible 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 ve...
__all__ = ['RoleMetadata'] class RoleMetadata(Base): ''' This class wraps the parsing and validation of the optional metadata within each Role (meta/main.yml). ''' _allow_duplicates = FieldAttribute(isa='bool', default=False) _dependencies = FieldAttribute(isa='list', default=list) _gala...
from ansible.playbook.role.requirement import RoleRequirement
random_line_split
metadata.py
# (c) 2014 Michael DeHaan, <michael@ansible.com> # # This file is part of Ansible # # Ansible 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 ve...
except AnsibleError as exc: raise AnsibleParserError(to_native(exc), obj=role_def, orig_exc=exc) current_role_path = None if self._owner: current_role_path = os.path.dirname(self._owner._role_path) try: return load_list_of_roles(roles...
''' This is a helper loading function for the dependencies list, which returns a list of RoleInclude objects ''' roles = [] if ds: if not isinstance(ds, list): raise AnsibleParserError("Expected role dependencies to be a list.", obj=self._ds) ...
identifier_body
metadata.py
# (c) 2014 Michael DeHaan, <michael@ansible.com> # # This file is part of Ansible # # Ansible 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 ve...
(self): return dict( allow_duplicates=self._allow_duplicates, dependencies=self._dependencies, ) def deserialize(self, data): setattr(self, 'allow_duplicates', data.get('allow_duplicates', False)) setattr(self, 'dependencies', data.get('dependencies', []))
serialize
identifier_name
metadata.py
# (c) 2014 Michael DeHaan, <michael@ansible.com> # # This file is part of Ansible # # Ansible 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 ve...
current_role_path = None if self._owner: current_role_path = os.path.dirname(self._owner._role_path) try: return load_list_of_roles(roles, play=self._owner._play, current_role_path=current_role_path, variable_manager=self._variable_manager, ...
if isinstance(role_def, string_types) or 'role' in role_def or 'name' in role_def: roles.append(role_def) continue try: # role_def is new style: { src: 'galaxy.role,version,name', other_vars: "here" } def_parsed = RoleRequir...
conditional_block
radio3.py
#!/usr/bin/python # selects stream from tuning dial position # monitors battery condition from __future__ import division import spidev import time import os import gc import sys import math global tune1, tune2, tunerout, volts2, volume1, volume2, volumeout, IStream tune1 = False tune2 = False tunerout = False volts2...
(channel): # read channel from mcd3008; channel must be integer 0 - 7 adc = spi.xfer2([1,(8+channel)<<4,0]) data = ((adc[1]&3) << 8) + adc[2] return data # returns value between 0 and 1023 # check volume control here. If < 1, # set voice control os.popen("mpc repeat on") # playlist will loop os.popen("mpc play -...
ReadChannel
identifier_name
radio3.py
#!/usr/bin/python # selects stream from tuning dial position # monitors battery condition from __future__ import division import spidev import time import os import gc import sys import math
tune1 = False tune2 = False tunerout = False volts2 = False volume1 = False volume2 = False volumeout = False IStream = False # start system on mp3s # open spi port: spi = spidev.SpiDev() spi.open(0,0) def ReadChannel(channel): # read channel from mcd3008; channel must be integer 0 - 7 adc = spi.xfer2([1,(8+channe...
global tune1, tune2, tunerout, volts2, volume1, volume2, volumeout, IStream
random_line_split
radio3.py
#!/usr/bin/python # selects stream from tuning dial position # monitors battery condition from __future__ import division import spidev import time import os import gc import sys import math global tune1, tune2, tunerout, volts2, volume1, volume2, volumeout, IStream tune1 = False tune2 = False tunerout = False volts2...
# check volume control here. If < 1, # set voice control os.popen("mpc repeat on") # playlist will loop os.popen("mpc play -q ") # start playing whatever the last playlist was while True: # main loop # Check battery: volts2 = ReadChannel(2) if ((volts2 < 210) and (volts2 > 10)): # battery is present, but wea...
adc = spi.xfer2([1,(8+channel)<<4,0]) data = ((adc[1]&3) << 8) + adc[2] return data # returns value between 0 and 1023
identifier_body
radio3.py
#!/usr/bin/python # selects stream from tuning dial position # monitors battery condition from __future__ import division import spidev import time import os import gc import sys import math global tune1, tune2, tunerout, volts2, volume1, volume2, volumeout, IStream tune1 = False tune2 = False tunerout = False volts2...
ditherfactor = int(tune2 / 50) + 3 # anti-dither if ((tune2 < tune1 - ditherfactor) or (tune2 > tune1 + ditherfactor)): # tuning change? tunerout = int(tune2 / 25) # returns a value of 0 to 40 tunerout = tunerout + (100 * IStream) # adds 100 to base if playing streams tuneroutstring = "mpc load -q " + str(tu...
IStream = True
conditional_block
pymsp.py
hhhhh", "AccX,AccY,AccZ,GyrX,GyrY,GyrZ,MagX,MagY,MagZ"), MSP_SERVO: MSPItem('SERVO', "8h", "servo"), MSP_MOTOR: MSPItem('MOTOR', "8h", "motor"), MSP_RC: MSPItem('RC', "8h", "rc"), MSP_COMP_GPS: MSPItem('COMP_GPS', "HhB", "distanceToHome,directionToHome,update"), ...
print('"invalid checksum for command "+((int)(cmd&0xFF))+": "+(checksum&0xFF)+" expected, got "+(int)(c&0xFF))')
conditional_block
pymsp.py
= 57 MSP_NAME =10 MSP_OSD_CONFIG =84 MSP_IDENT =100 MSP_STATUS =101 MSP_RAW_IMU =102 MSP_SERVO =103 MSP_MOTOR =104 MSP_RC =105 MSP_RAW_GPS ...
'''unsigned 8 bit number''' value, = struct.unpack("<B", self.inBuf[self.p:self.p+1]) self.p += 1 return value
identifier_body
pymsp.py
", "task_delta,i2c_err_count,sensor_status,mode_flags,nop_1,system_load,gyro_time,nop_2,nop_3,armed,extra"), } def __init__(self): self.msp_name = { 'name':None } self.msp_osd_config = {} self.inBuf = bytearray([0] * 255) self.p = 0 ...
disarm
identifier_name
pymsp.py
44 OSD_FLIP_ARROW = 45 OSD_LINK_QUALITY = 46 OSD_FLIGHT_DIST = 47 OSD_STICK_OVERLAY_LEFT = 48 OSD_STICK_OVERLAY_RIGHT = 49 OSD_DISPLAY_NAME = 50 OSD_ESC_RPM_FREQ = 51
OSD_RATE_PROFILE_NAME = 52 OSD_PID_PROFILE_NAME = 53 OSD_PROFILE_NAME = 54 OSD_RSSI_DBM_VALUE = 55 OSD_RC_CHANNELS = 56 OSD_CAMERA_FRAME = 57 MSP_NAME =10 MSP_OSD_CONFIG =84 MSP_IDENT ...
random_line_split
selection_sort.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 09/09/2015 Updated: 07/03/2018 # Description Selection sorting is conceptually probably the simplest sorting algorithm. This algorithm first finds the smallest element in the list and exchanges it with the element in ...
(ls: list) -> None: """Selection-sort in-place sorting algorithm. Time complexity +-------+----------+----------+ | Best | Average | Worst | +-------+----------+----------+ | O(n²) | O(n²) | O(n²) | +-------+----------+----------+ Space complexity: O(n).""" for i in ran...
selection_sort
identifier_name
selection_sort.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 09/09/2015 Updated: 07/03/2018 # Description Selection sorting is conceptually probably the simplest sorting algorithm. This algorithm first finds the smallest element in the list and exchanges it with the element in ...
def selection_sort(ls: list) -> None: """Selection-sort in-place sorting algorithm. Time complexity +-------+----------+----------+ | Best | Average | Worst | +-------+----------+----------+ | O(n²) | O(n²) | O(n²) | +-------+----------+----------+ Space complexity: O(n).""...
""" __all__ = ["selection_sort"]
random_line_split
selection_sort.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 09/09/2015 Updated: 07/03/2018 # Description Selection sorting is conceptually probably the simplest sorting algorithm. This algorithm first finds the smallest element in the list and exchanges it with the element in ...
ls[j] < ls[k]: ls[k], ls[j] = ls[j], ls[k]
conditional_block
selection_sort.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 09/09/2015 Updated: 07/03/2018 # Description Selection sorting is conceptually probably the simplest sorting algorithm. This algorithm first finds the smallest element in the list and exchanges it with the element in ...
"""Selection-sort in-place sorting algorithm. Time complexity +-------+----------+----------+ | Best | Average | Worst | +-------+----------+----------+ | O(n²) | O(n²) | O(n²) | +-------+----------+----------+ Space complexity: O(n).""" for i in range(len(ls) - 1): ...
identifier_body
searchCtrl.js
'use strict'; app.controller('searchCtrl', function ( $scope, $rootScope, $http, $stateParams, SCapiService, utilsService ) { $scope.title = 'Results for: ' + $stateParams.q; $scope.data = ''; var limit = 20; SCapiService.search('tracks', limit, $stateParams.q) .then(f...
$scope.busy = true; SCapiService.getNextPage() .then(function(data) { for ( var i = 0; i < data.collection.length; i++ ) { $scope.data.push( data.collection[i] ) } utilsService.updateTracksReposts(data.collection, true); ...
{ return; }
conditional_block
searchCtrl.js
'use strict'; app.controller('searchCtrl', function ( $scope, $rootScope, $http, $stateParams, SCapiService, utilsService ) { $scope.title = 'Results for: ' + $stateParams.q; $scope.data = ''; var limit = 20; SCapiService.search('tracks', limit, $stateParams.q) .then(f...
console.log('error', error); }).finally(function(){ $scope.busy = false; $rootScope.isLoading = false; }); }; });
}, function(error) {
random_line_split
main.rs
use std::fs::File; use std::io::prelude::*; fn get_input() -> Vec<u8> { let mut file = File::open("input.txt").unwrap(); let mut content = Vec::new(); file.read_to_end(&mut content).unwrap(); for i in 0 .. content.len() { content[i] = content[i] - ('0' as u8); } content } fn offset_s...
} sum } fn main() { let input = get_input(); println!("Part 1 total: {}", offset_sum(&input, 1)); println!("Part 2 total: {}", offset_sum(&input, input.len()/2)); }
}
random_line_split
main.rs
use std::fs::File; use std::io::prelude::*; fn get_input() -> Vec<u8>
fn offset_sum(input: &[u8], offset: usize) -> i32 { let len = input.len(); let mut sum = 0; for i in 0 .. len { let j = (i + offset) % len; if input[i] == input[j] { sum += input[i] as i32; } } sum } fn main() { let input = get_input(); println!("Par...
{ let mut file = File::open("input.txt").unwrap(); let mut content = Vec::new(); file.read_to_end(&mut content).unwrap(); for i in 0 .. content.len() { content[i] = content[i] - ('0' as u8); } content }
identifier_body
main.rs
use std::fs::File; use std::io::prelude::*; fn get_input() -> Vec<u8> { let mut file = File::open("input.txt").unwrap(); let mut content = Vec::new(); file.read_to_end(&mut content).unwrap(); for i in 0 .. content.len() { content[i] = content[i] - ('0' as u8); } content } fn offset_s...
} sum } fn main() { let input = get_input(); println!("Part 1 total: {}", offset_sum(&input, 1)); println!("Part 2 total: {}", offset_sum(&input, input.len()/2)); }
{ sum += input[i] as i32; }
conditional_block
main.rs
use std::fs::File; use std::io::prelude::*; fn get_input() -> Vec<u8> { let mut file = File::open("input.txt").unwrap(); let mut content = Vec::new(); file.read_to_end(&mut content).unwrap(); for i in 0 .. content.len() { content[i] = content[i] - ('0' as u8); } content } fn offset_s...
() { let input = get_input(); println!("Part 1 total: {}", offset_sum(&input, 1)); println!("Part 2 total: {}", offset_sum(&input, input.len()/2)); }
main
identifier_name
utils.py
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
for option, value in extra_options[section].items(): conf_object.set(section, option, value) return conf_object
conf_object.add_section(section)
conditional_block
utils.py
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
(extra_options, conf_object): conf_object.optionxform = str for section in extra_options: if section not in (conf_object.sections() + ["DEFAULT"]): conf_object.add_section(section) for option, value in extra_options[section].items(): conf_object.set(section, option, value...
add_extra_options
identifier_name
utils.py
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
debug_output = kwargs.pop("debug_output", True) kwargs["stderr"] = subprocess.STDOUT try: output = subprocess.check_output(*args, **kwargs) except subprocess.CalledProcessError as exc: if msg_on_err: LOG.error(msg_on_err) LOG.error("Failed cmd: '%s'" % exc.cmd) ...
""" msg_on_err = kwargs.pop("msg_on_err", None)
random_line_split
utils.py
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
conf_object.optionxform = str for section in extra_options: if section not in (conf_object.sections() + ["DEFAULT"]): conf_object.add_section(section) for option, value in extra_options[section].items(): conf_object.set(section, option, value) return conf_object
identifier_body
khr_vgimage.py
#!/usr/bin/env python3 '''Khronos OpenVG parent image binding for EGL. http://www.khronos.org/registry/egl/extensions/KHR/EGL_KHR_vg_parent_image.txt ''' # Copyright © 2012-13 Tim Pederick. # # This file is part of Pegl.
# 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. # # Pegl is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or ...
# # Pegl is free software: you can redistribute it and/or modify it
random_line_split
rt_20000515.py
#"Ron Ten-Hove" <rtenhove@forte.com>, by wondering why he doesn't get the expected result from passing params to unnamed templates, exposes a subtle gotcha. 15 May 2000 from Xml.Xslt import test_harness sheet_1 = """<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" ...
source_1 = """<?xml version="1.0"?> <doc> <chapter name="The beginning"> Alpha. </chapter> </doc> """ expected_1="""<?xml version='1.0' encoding='UTF-8'?> <root> <chap title='The beginning' cat='Unset'/> </root>""" def Test(tester): source = test_harness.FileInfo(string=source_1) sheet = test_har...
<xsl:template match="text()" /> </xsl:stylesheet>"""
random_line_split
rt_20000515.py
#"Ron Ten-Hove" <rtenhove@forte.com>, by wondering why he doesn't get the expected result from passing params to unnamed templates, exposes a subtle gotcha. 15 May 2000 from Xml.Xslt import test_harness sheet_1 = """<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" ...
(tester): source = test_harness.FileInfo(string=source_1) sheet = test_harness.FileInfo(string=sheet_1) test_harness.XsltTest(tester, source, [sheet], expected_1) return
Test
identifier_name
rt_20000515.py
#"Ron Ten-Hove" <rtenhove@forte.com>, by wondering why he doesn't get the expected result from passing params to unnamed templates, exposes a subtle gotcha. 15 May 2000 from Xml.Xslt import test_harness sheet_1 = """<?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" ...
source = test_harness.FileInfo(string=source_1) sheet = test_harness.FileInfo(string=sheet_1) test_harness.XsltTest(tester, source, [sheet], expected_1) return
identifier_body
osc_writer.rs
use std::convert::TryInto; use std::io::Write; use byteorder::{BigEndian, WriteBytesExt}; use error::ResultE; /// auto-implemented trait to write OSC data to a Write object. pub trait OscWriter: Write { fn osc_write_i32(&mut self, value: i32) -> ResultE<()> { Ok(self.write_i32::<BigEndian>(value)?) } ...
let zeros = b"\0\0\0\0"; Ok(self.write_all(&zeros[..pad_bytes])?) } fn write_blob_tag(&mut self) -> ResultE<()> { Ok(self.write_u8(b'b')?) } /// Write the OSC timetag, characterized by a (u32, u32) pair. /// The first u32 is the seconds, second is fraction of seconds. fn ...
random_line_split