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
fortran_parser_test.py
#!/usr/bin/env python # # ParameterWeaver: a code generator to handle command line parameters # and configuration files for C/C++/Fortran/R/Octave # Copyright (C) 2013 Geert Jan Bex <geertjan.bex@uhasselt.be> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gener...
def test_simple_tab_separated_valid(self): '''Parse a simple file that is well-formed and valid''' file_name = 'tests/good_fortran.txt' t = CharacterArray() try: self.assertEqual(self._parameters, self._parser.parse(file_name)) except ParameterDefinitionError as e...
random_line_split
products.service.ts
import { Injectable } from '@angular/core' import { SystemDomainApi } from '@colmena/admin-lb-sdk' import { UiDataGridService, FormService } from '@colmena/admin-ui' @Injectable() export class ProductsService extends UiDataGridService { public icon = 'icon-basket' public title = 'Products' public files: any[]...
else { this.domainApi.createContentProducts(this.domain.id, item).subscribe(successCb, errorCb) } } deleteItem(item, successCb, errorCb) { this.domainApi .destroyByIdContentProducts(this.domain.id, item.id) .subscribe( (success) => successCb(success), (error) => errorCb(e...
{ this.domainApi.updateByIdContentProducts(this.domain.id, item.id, item).subscribe(successCb, errorCb) }
conditional_block
products.service.ts
import { Injectable } from '@angular/core' import { SystemDomainApi } from '@colmena/admin-lb-sdk' import { UiDataGridService, FormService } from '@colmena/admin-ui' @Injectable() export class
extends UiDataGridService { public icon = 'icon-basket' public title = 'Products' public files: any[] = [] public tableColumns = [ { field: 'name', label: 'Name', action: 'view' }, { field: 'description', label: 'Description' }, { field: 'sku', label: 'SKU' }, ] public formFields = [ thi...
ProductsService
identifier_name
products.service.ts
import { Injectable } from '@angular/core' import { SystemDomainApi } from '@colmena/admin-lb-sdk'
export class ProductsService extends UiDataGridService { public icon = 'icon-basket' public title = 'Products' public files: any[] = [] public tableColumns = [ { field: 'name', label: 'Name', action: 'view' }, { field: 'description', label: 'Description' }, { field: 'sku', label: 'SKU' }, ] p...
import { UiDataGridService, FormService } from '@colmena/admin-ui' @Injectable()
random_line_split
products.service.ts
import { Injectable } from '@angular/core' import { SystemDomainApi } from '@colmena/admin-lb-sdk' import { UiDataGridService, FormService } from '@colmena/admin-ui' @Injectable() export class ProductsService extends UiDataGridService { public icon = 'icon-basket' public title = 'Products' public files: any[]...
deleteItem(item, successCb, errorCb) { this.domainApi .destroyByIdContentProducts(this.domain.id, item.id) .subscribe( (success) => successCb(success), (error) => errorCb(error), ) } }
{ if (item.id) { this.domainApi.updateByIdContentProducts(this.domain.id, item.id, item).subscribe(successCb, errorCb) } else { this.domainApi.createContentProducts(this.domain.id, item).subscribe(successCb, errorCb) } }
identifier_body
lib.rs
#[cfg(feature="replayer")] use core::clone::Clone; #[cfg(feature="replayer")] use core::cell::RefCell; #[cfg(not(feature="replayer"))] use core::intrinsics::{volatile_load, volatile_store}; #[cfg(feature="replayer")] use core::intrinsics::transmute; // TODO(farcaller): why this needs copy/clone? /// This structure is...
random_line_split
lib.rs
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A cell that with volatile setter and getter. #![feature(no_std, core_intrinsics)] #![no_std] #[cfg(feature="replayer")] #[macro_use(expect)] ...
matches
identifier_name
lib.rs
the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A cell that with volatile setter and getter. #![feature(no_std, core_intrinsics)] #!...
pub fn verify(&self, loc: expectest::core::SourceLocation) { expect(self.current_replay).location(loc).to( be_equal_to_with_context( self.replays.len(), format!("expected {} replays, performed {}", self.replays.len(), self.current_replay))); for ref replay in &*self....
{ self.replays.push(ReplayRecord { is_read: false, address: address, value: value, replayed: false, did_read: false, actual_address: 0, actual_value: 0, loc: loc, }); }
identifier_body
VParallax.ts
// Style import '../../stylus/components/_parallax.styl' // Mixins import Translatable from '../../mixins/translatable' // Types import Vue from 'vue' import { VNode, VNodeData } from 'vue/types/vnode' import mixins, { ExtractVue } from '../../util/mixins' interface options extends Vue { $refs: { img: HTMLImag...
() { this.init() }, methods: { init () { const img = this.$refs.img if (!img) return if (img.complete) { this.translate() this.listeners() } else { img.addEventListener('load', () => { this.translate() this.listeners() }, false)...
mounted
identifier_name
VParallax.ts
// Style import '../../stylus/components/_parallax.styl' // Mixins import Translatable from '../../mixins/translatable' // Types import Vue from 'vue' import { VNode, VNodeData } from 'vue/types/vnode' import mixins, { ExtractVue } from '../../util/mixins' interface options extends Vue { $refs: { img: HTMLImag...
parallax () { this.isBooted = true } }, mounted () { this.init() }, methods: { init () { const img = this.$refs.img if (!img) return if (img.complete) { this.translate() this.listeners() } else { img.addEventListener('load', () => { ...
} }, watch: {
random_line_split
VParallax.ts
// Style import '../../stylus/components/_parallax.styl' // Mixins import Translatable from '../../mixins/translatable' // Types import Vue from 'vue' import { VNode, VNodeData } from 'vue/types/vnode' import mixins, { ExtractVue } from '../../util/mixins' interface options extends Vue { $refs: { img: HTMLImag...
else { img.addEventListener('load', () => { this.translate() this.listeners() }, false) } }, objHeight () { return this.$refs.img.naturalHeight } }, render (h): VNode { const imgData: VNodeData = { staticClass: 'v-parallax__image', style:...
{ this.translate() this.listeners() }
conditional_block
VParallax.ts
// Style import '../../stylus/components/_parallax.styl' // Mixins import Translatable from '../../mixins/translatable' // Types import Vue from 'vue' import { VNode, VNodeData } from 'vue/types/vnode' import mixins, { ExtractVue } from '../../util/mixins' interface options extends Vue { $refs: { img: HTMLImag...
return h('div', { staticClass: 'v-parallax', style: { height: `${this.height}px` }, on: this.$listeners }, [container, content]) } })
{ const imgData: VNodeData = { staticClass: 'v-parallax__image', style: this.styles, attrs: { src: this.src, alt: this.alt }, ref: 'img' } const container = h('div', { staticClass: 'v-parallax__image-container' }, [ h('img', imgData) ]) ...
identifier_body
addon.py
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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MER...
return context_menu def format_episode_title(title): if fix_show_title and '-' in title and ('Folge' in title or 'Staffel' in title): title, show = title.rsplit('-', 1) title = title.replace('Staffel ', 'S').replace(' Folge ', 'E') title = title.replace('Folge '...
context_menu = [( _('del_from_my_favs'), 'XBMC.RunPlugin(%s)' % plugin.url_for( endpoint='del_from_my_favs', item_path=item_path ), )]
conditional_block
addon.py
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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # ...
_('add_to_my_favs'), 'XBMC.RunPlugin(%s)' % plugin.url_for( endpoint='add_to_my_favs', item_path=item_path ), )] else: context_menu = [( _('del_from_my_favs'), 'XBMC.Ru...
if not item_path in my_fav_items: context_menu = [(
random_line_split
addon.py
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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # ...
def __add_items(entries, next_page=None, prev_page=None): my_fav_items = plugin.get_storage('my_fav_items') def context_menu(item_path, video_id): if not item_path in my_fav_items: context_menu = [( _('add_to_my_favs'), 'XBMC.RunPlugin(%s)' % plugin.url_fo...
try: items, next_page, prev_page = scraper.get_path(path) except NotImplementedError: plugin.notify(msg=_('no_scraper_found'), title='Path: %s' % path) else: return __add_items(items, next_page, prev_page)
identifier_body
addon.py
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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # ...
(item_path, video_id): if not item_path in my_fav_items: context_menu = [( _('add_to_my_favs'), 'XBMC.RunPlugin(%s)' % plugin.url_for( endpoint='add_to_my_favs', item_path=item_path ), )] else...
context_menu
identifier_name
fsm.ts
interface IDataFSM { name: string, from: string, to: string, onEnter: Function, onExit: Function, onUpdate: Function, } export class FSM { stateMap: { [index: string]: IDataFSM } currentState: string currentLogic: Function stack: string[] target: any constructor(states: ...
} update(dt: number) { if (this.stateMap[this.currentState].onUpdate) { this.stateMap[this.currentState].onUpdate(this.target, dt) } } }
this.switchState(newState) } popState() { var restoreState = this.stack.pop() if (restoreState) this.switchState(restoreState)
random_line_split
fsm.ts
interface IDataFSM { name: string, from: string, to: string, onEnter: Function, onExit: Function, onUpdate: Function, } export class FSM { stateMap: { [index: string]: IDataFSM } currentState: string currentLogic: Function stack: string[] target: any constructor(states: ...
() { var restoreState = this.stack.pop() if (restoreState) this.switchState(restoreState) } update(dt: number) { if (this.stateMap[this.currentState].onUpdate) { this.stateMap[this.currentState].onUpdate(this.target, dt) } } }
popState
identifier_name
default.js
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICU...
lse { splitView.closedDisplayMode = WinJS.UI.SplitView.ClosedDisplayMode.none; splitView.openedDisplayMode = WinJS.UI.SplitView.OpenedDisplayMode.overlay; splitView.closePane(); } } nav.addEventListener("navigating", navigating); app.addEventListener("activated",...
splitView.closedDisplayMode = WinJS.UI.SplitView.ClosedDisplayMode.none; splitView.openedDisplayMode = WinJS.UI.SplitView.OpenedDisplayMode.inline; } e
conditional_block
default.js
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICU...
var initialState = {}; var navHistory = app.sessionState.navigationHistory; if (navHistory) { nav.history = navHistory; url = navHistory.current.location; initialState = navHistory.current.state || initialState; ...
var activationKind = eventObject.detail.kind; var activatedEventArgs = eventObject.detail.detail; SdkSample.paneHiddenInitially = window.innerWidth <= 768; var p = WinJS.UI.processAll(). then(function () { splitView = document.querySelector("#root").winContro...
identifier_body
default.js
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICU...
if (navHistory) { nav.history = navHistory; url = navHistory.current.location; initialState = navHistory.current.state || initialState; } initialState.activationKind = activationKind; initialState...
var initialState = {}; var navHistory = app.sessionState.navigationHistory;
random_line_split
default.js
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICU...
{ if (window.innerWidth > 768) { splitView.closedDisplayMode = WinJS.UI.SplitView.ClosedDisplayMode.none; splitView.openedDisplayMode = WinJS.UI.SplitView.OpenedDisplayMode.inline; } else { splitView.closedDisplayMode = WinJS.UI.SplitView.ClosedDisplayMode.none; ...
ndleResize()
identifier_name
__init__.py
from flask import Flask, render_template from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.mail import Mail from flask.ext.assets import Environment #from flask.ext.admin import Admin #from flask_debugtoolbar import DebugToolbarExtension app = Flask(__name__) app.config.from_object('config') # SelectiveHTMLCo...
from app import views, models
return render_template('404.html'), 404
identifier_body
__init__.py
from flask import Flask, render_template from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.mail import Mail from flask.ext.assets import Environment #from flask.ext.admin import Admin #from flask_debugtoolbar import DebugToolbarExtension app = Flask(__name__) app.config.from_object('config') # SelectiveHTMLCo...
#toolbar = DebugToolbarExtension(app) mail = Mail(app) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 from app import views, models
db = SQLAlchemy(app) #admin = Admin(app)
random_line_split
__init__.py
from flask import Flask, render_template from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.mail import Mail from flask.ext.assets import Environment #from flask.ext.admin import Admin #from flask_debugtoolbar import DebugToolbarExtension app = Flask(__name__) app.config.from_object('config') # SelectiveHTMLCo...
(error): return render_template('404.html'), 404 from app import views, models
not_found
identifier_name
settings.tsx
import React from 'react'; import type { BackgroundSettings } from '../types/settings'; import { IMAGE_MODE_FLAG, COLOR_MODE_FLAG, GRADIENT_MODE_FLAG, } from './../const/mode'; // import { defaultTranslations as defaultImageUploadTranslations } from '@react-page/editor/lib/ui/ImageUpload/defaultTranslations'; ex...
cellStyle: { padding: 0, }, };
random_line_split
xparser.py
# # This is a parser that generates the document tree for you. # # To use this parser, create an instance of XElementParser: # parser = saxexts.make_parser() # xp = XElementParser(parser) # # If you have defined classes in the current environment, you might want ot # pass this environment *to* the parser, so your...
import string import sys import types from xml.sax import saxexts from xml.sax import saxlib from xelement import XElement, XTreeHandler class XElementParser: def __init__(self, outer_env={}, parser=None): if parser == None: self.parser = saxexts.XMLValParserFactory.make_parser() else: ...
# # for doc in doc_list: # doc_tree = xp.process(doc) # print doc_tree.toXML()
random_line_split
xparser.py
# # This is a parser that generates the document tree for you. # # To use this parser, create an instance of XElementParser: # parser = saxexts.make_parser() # xp = XElementParser(parser) # # If you have defined classes in the current environment, you might want ot # pass this environment *to* the parser, so your...
: def __init__(self, outer_env={}, parser=None): if parser == None: self.parser = saxexts.XMLValParserFactory.make_parser() else: self.parser = parser self.parser_error_handler = ErrorPrinter() self.parser.setErrorHandler(self.parser_error_handler) self.xth = XTreeHan...
XElementParser
identifier_name
xparser.py
# # This is a parser that generates the document tree for you. # # To use this parser, create an instance of XElementParser: # parser = saxexts.make_parser() # xp = XElementParser(parser) # # If you have defined classes in the current environment, you might want ot # pass this environment *to* the parser, so your...
def has_errors(self): return self.error_count def warning(self, exception): print "Warning: %s %s" % (str(exception), exception.getMessage()) sys.exit(1) def error(self, exception): self.error_count = self.error_count + 1 print "Error: %s %s" % (str(exception), excepti...
self.error_count = 0
identifier_body
xparser.py
# # This is a parser that generates the document tree for you. # # To use this parser, create an instance of XElementParser: # parser = saxexts.make_parser() # xp = XElementParser(parser) # # If you have defined classes in the current environment, you might want ot # pass this environment *to* the parser, so your...
self.parser_error_handler = ErrorPrinter() self.parser.setErrorHandler(self.parser_error_handler) self.xth = XTreeHandler(IgnoreWhiteSpace='yes', RemoveWhiteSpace='yes', CreateElementMap='yes', RequireUserClasses='yes') for x in ...
self.parser = parser
conditional_block
MedicalRecordNav.js
/**
* Time: 1:45 PM * To change this template use File | Settings | File Templates. */ Ext.define('App.view.MedicalRecordNav', { extend: 'Ext.Container', xtype:'medicalrecordnav', requires:[ 'App.view.MedicalRecordMenu' ], cls:'medicalRecordNav', config: { layout:'vbox', i...
* Created with JetBrains PhpStorm. * User: ernesto * Date: 11/11/12
random_line_split
abstract_colormap.py
""" Defines the base class for color maps """ from traits.api import Enum, HasTraits, Instance from data_range_1d import DataRange1D class AbstractColormap(HasTraits): """ Abstract class for color maps, which map from scalar values to color values. """ # The data-space bounds of the mapper. range...
def map_uint8(self, val): """ map_uint8(val) -> rgb24 or rgba32 color Maps a single value to a single color. Color is represented as either length-3 or length-4 array of rgb(a) uint8 values, depending on the **color_depth** setting. """ # default implement...
""" map_index(ary) -> index into color_bands This method is like map_screen(), but it returns an array of indices into the color map's color bands instead of an array of colors. If the input array is NxM, then the output is NxM integer indices. This method might not apply to a...
identifier_body
abstract_colormap.py
""" Defines the base class for color maps """ from traits.api import Enum, HasTraits, Instance from data_range_1d import DataRange1D class AbstractColormap(HasTraits): """ Abstract class for color maps, which map from scalar values to color values. """ # The data-space bounds of the mapper. range...
(self, ary): """ map_data(ary) -> color_array Returns an array of values containing the colors mapping to the values in *ary*. If the input array is NxM, the returned array is NxMx3 or NxMx4, depending on the **color_depth** setting. """ # XXX this seems bogus: b...
map_data
identifier_name
abstract_colormap.py
""" Defines the base class for color maps """ from traits.api import Enum, HasTraits, Instance from data_range_1d import DataRange1D class AbstractColormap(HasTraits): """ Abstract class for color maps, which map from scalar values to color values. """ # The data-space bounds of the mapper. range...
def map_screen(self, val): """ map_screen(val) -> color Maps an array of values to an array of colors. If the input array is NxM, the returned array is NxMx3 or NxMx4, depending on the **color_depth** setting. """ raise NotImplementedError() def map_d...
# The color depth of the colors to use. color_depth = Enum('rgba', 'rgb')
random_line_split
weatherpublisher.py
#!/usr/bin/env python3 import time import json import requests from datetime import datetime import paho.mqtt.client as mqtt from sense_hat import SenseHat BROKER_URL = '192.168.24.25' CYCLE_TIME = 10 # initialisiere SenseHat-Erweiterung sense = SenseHat() sense.low_light = True def
(): """Ermittelt die Stadt zur eigenen IP-Adresse.""" IP_LOCKUP_URL = "https://ipinfo.io/" try: r = requests.get(IP_LOCKUP_URL) except: print("error while querying info...") data = json.loads(r.text) return data['city'] def get_weather(city): """Fragt das aktuelle Wetter be...
get_location
identifier_name
weatherpublisher.py
#!/usr/bin/env python3 import time import json import requests from datetime import datetime import paho.mqtt.client as mqtt from sense_hat import SenseHat BROKER_URL = '192.168.24.25' CYCLE_TIME = 10 # initialisiere SenseHat-Erweiterung sense = SenseHat() sense.low_light = True def get_location(): """Ermit...
if __name__ == '__main__': try: mqttc = mqtt.Client() mqttc.connect(BROKER_URL, 1883, 60) while True: weather, temp, humidity, wind_speed, sunrise, sunset = get_weather(get_location()) mqttc.publish('umgebung/wetter', str(weather)) mqttc.publish('umgebun...
"""Fragt das aktuelle Wetter bei openweathermap.org ab und gibt Temperatur, Luftfeuchtigkeit, Windgeschwindigkeit und die Zeiten von Sonnenaufgang und Sonnenuntergang zurück.""" URL = 'http://api.openweathermap.org/data/2.5/weather?q={}&APPID={}' API_KEY = '' # <- insert API key for openweathermap.org ...
identifier_body
weatherpublisher.py
#!/usr/bin/env python3 import time import json import requests from datetime import datetime import paho.mqtt.client as mqtt from sense_hat import SenseHat BROKER_URL = '192.168.24.25' CYCLE_TIME = 10 # initialisiere SenseHat-Erweiterung sense = SenseHat() sense.low_light = True def get_location(): """Ermit...
weather = data['weather'][0]['main'] temp = data['main']['temp'] - 273.15 humidity = data['main']['humidity'] wind_speed = data['wind']['speed'] sunrise = datetime.fromtimestamp(data['sys']['sunrise']) sunset = datetime.fromtimestamp(data['sys']['sunset']) return weather, temp, humidity, win...
eturn '', 0, 0, 0, '', ''
conditional_block
weatherpublisher.py
#!/usr/bin/env python3 import time import json import requests from datetime import datetime import paho.mqtt.client as mqtt from sense_hat import SenseHat BROKER_URL = '192.168.24.25' CYCLE_TIME = 10 # initialisiere SenseHat-Erweiterung sense = SenseHat() sense.low_light = True def get_location(): """Ermit...
exit() time.sleep(CYCLE_TIME) except KeyboardInterrupt: mqttc.disconnect() sense.clear() print('Tschüß!')
for event in sense.stick.get_events(): if 'down' in event.direction:
random_line_split
ace.py
''' Created on 2014. 9. 26. @author: jongyeob ''' from __future__ import absolute_import import sys import logging import re from . import utils from .utils import datetime as dt from .utils import download as dl DATA_DIR = 'data/' LOG = logging.getLogger(__name__); LOG.setLevel(0) PACKAGES = '' INST_NAME = ['m...
return mag def load_swepam(filepath): ''' Load a file is solar wind parameters of 1hr averaged ACE realtime data :param string filepath: local filepath :return: (dict) swepam data ''' lines = [] with open(filepath) as f: lines = f.re...
mag[key].append(data.group(i)) i = i + 1
conditional_block
ace.py
''' Created on 2014. 9. 26. @author: jongyeob ''' from __future__ import absolute_import import sys import logging import re from . import utils from .utils import datetime as dt from .utils import download as dl DATA_DIR = 'data/' LOG = logging.getLogger(__name__); LOG.setLevel(0) PACKAGES = '' INST_NAME = ['m...
### data = re.match('\A(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+\d+\s+\d+\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+',line) if(data is not None): datetime_string = "%4s-%02s-%02s"%data.groups()[0:3] + " %2s:%2s:00"%(data.group(4)[0:2],data.group(4...
''' Load a file is magnetic parameters of 1hr averaged ACE realtime data :param string filepath: local filepath :return: (dict) mag data ''' lines = [] with open(filepath) as f: lines = f.readlines() mag = empty_data('mag') for line in lines: ### ...
identifier_body
ace.py
''' Created on 2014. 9. 26. @author: jongyeob ''' from __future__ import absolute_import import sys import logging import re from . import utils from .utils import datetime as dt from .utils import download as dl DATA_DIR = 'data/' LOG = logging.getLogger(__name__); LOG.setLevel(0) PACKAGES = '' INST_NAME = ['m...
(date,inst,filepath='',overwrite=False): ''' Download ACE Realtime 1h average data. :param datetime date: Datetime :param string inst: Instrument name :return: Downloaded path ''' f = remote_path(dt.tuples(date, 'date'), inst) if filepath =...
download_file
identifier_name
ace.py
''' Created on 2014. 9. 26. @author: jongyeob ''' from __future__ import absolute_import import sys import logging import re from . import utils from .utils import datetime as dt from .utils import download as dl DATA_DIR = 'data/' LOG = logging.getLogger(__name__); LOG.setLevel(0) PACKAGES = ''
INST_KEYS = [MAG_KEYS,SWEPAM_KEYS,SIS_KEYS,LOC_KEYS] def initialize(config=Config()): global DATA_DIR,PACKAGES config.set_section(__name__) config.load_ns('DATA_DIR',globals()) config.load_ns('PACKAGES',globals()) LOG = utils.get_logger() for pkg in PACKAGES.split(): utils.im...
INST_NAME = ['mag','swepam','sis','loc'] MAG_KEYS = ['datetime','status','bx','by','bz','bt','latitude','longitude'] SWEPAM_KEYS = ['datetime','status','density','speed','temperature'] SIS_KEYS = [] LOC_KEYS = []
random_line_split
demo.rs
use euclid::default::Rect; use euclid::point2; use vitral::{ color, Align, AppConfig, ButtonAction, Canvas, PngBytes, RectUtil, Rgba, Scene, SceneSwitch, }; struct World { font: vitral::FontData, image: vitral::ImageData, fore_color: Rgba, back_color: Rgba, } impl World { pub fn new() -> World...
(&mut self, _ctx: &mut World) -> Option<SceneSwitch<World>> { None } fn render(&mut self, ctx: &mut World, canvas: &mut Canvas) -> Option<SceneSwitch<World>> { canvas.draw_image(&ctx.image, point2(20, 20), color::WHITE); let bounds = canvas.bounds(); let (_, title_area) = bounds.horizontal...
update
identifier_name
demo.rs
use euclid::default::Rect; use euclid::point2; use vitral::{ color, Align, AppConfig, ButtonAction, Canvas, PngBytes, RectUtil, Rgba, Scene, SceneSwitch, }; struct World { font: vitral::FontData, image: vitral::ImageData, fore_color: Rgba, back_color: Rgba, } impl World { pub fn new() -> World...
fn render(&mut self, ctx: &mut World, canvas: &mut Canvas) -> Option<SceneSwitch<World>> { canvas.draw_image(&ctx.image, point2(20, 20), color::WHITE); let bounds = canvas.bounds(); let (_, title_area) = bounds.horizontal_split(12); self.title_bar(ctx, canvas, &title_area, "Vitral...
{ None }
identifier_body
demo.rs
use euclid::default::Rect; use euclid::point2; use vitral::{ color, Align, AppConfig, ButtonAction, Canvas, PngBytes, RectUtil, Rgba, Scene, SceneSwitch, }; struct World { font: vitral::FontData, image: vitral::ImageData, fore_color: Rgba, back_color: Rgba, } impl World { pub fn new() -> World...
impl Scene<World> for DemoScene { fn update(&mut self, _ctx: &mut World) -> Option<SceneSwitch<World>> { None } fn render(&mut self, ctx: &mut World, canvas: &mut Canvas) -> Option<SceneSwitch<World>> { canvas.draw_image(&ctx.image, point2(20, 20), color::WHITE); let bounds = canvas.bounds(); ...
random_line_split
demo.rs
use euclid::default::Rect; use euclid::point2; use vitral::{ color, Align, AppConfig, ButtonAction, Canvas, PngBytes, RectUtil, Rgba, Scene, SceneSwitch, }; struct World { font: vitral::FontData, image: vitral::ImageData, fore_color: Rgba, back_color: Rgba, } impl World { pub fn new() -> World...
else { ctx.fore_color }; canvas.fill_rect(bounds, color); canvas.fill_rect(&bounds.inflate(-1, -1), ctx.back_color); let inner = bounds.inflate(-3, -3).inclusivize(); canvas.draw_line(1.0, color, inner.bottom_right(), inner.origin); canvas.draw_line(1.0, ...
{ self.bright_color() }
conditional_block
buddy.py
__author__ = "Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel" __license__ = "GPLv3" __maintainer__ = "Steffen Vogel" __email__ = "post@steffenvogel.de" """ This file is part of transWhat transWhat is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Li...
(dict): def __init__(self, owner, backend, user, session): self.owner = owner self.backend = backend self.session = session self.user = user self.logger = logging.getLogger(self.__class__.__name__) self.synced = False def _load(self, buddies): for buddy in buddies: number = buddy.buddyName nick ...
BuddyList
identifier_name
buddy.py
__author__ = "Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel" __license__ = "GPLv3" __maintainer__ = "Steffen Vogel" __email__ = "post@steffenvogel.de" """ This file is part of transWhat transWhat is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Li...
self.image_hash = image_hash if image_hash is not None else "" self.statusMsg = u"" self.lastseen = 0 self.presence = 0 def update(self, nick, groups, image_hash): self.nick = nick self.groups = groups if image_hash is not None: self.image_hash = image_hash def __str__(self): return "%s (nick=%s)...
def __init__(self, owner, number, nick, statusMsg, groups, image_hash): self.nick = nick self.owner = owner self.number = number self.groups = groups
random_line_split
buddy.py
__author__ = "Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel" __license__ = "GPLv3" __maintainer__ = "Steffen Vogel" __email__ = "post@steffenvogel.de" """ This file is part of transWhat transWhat is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Li...
def __str__(self): return "%s (nick=%s)" % (self.number, self.nick) class BuddyList(dict): def __init__(self, owner, backend, user, session): self.owner = owner self.backend = backend self.session = session self.user = user self.logger = logging.getLogger(self.__class__.__name__) self.synced = False...
self.nick = nick self.groups = groups if image_hash is not None: self.image_hash = image_hash
identifier_body
buddy.py
__author__ = "Steffen Vogel" __copyright__ = "Copyright 2015, Steffen Vogel" __license__ = "GPLv3" __maintainer__ = "Steffen Vogel" __email__ = "post@steffenvogel.de" """ This file is part of transWhat transWhat is free software: you can redistribute it and/or modify it under the terms of the GNU General Public Li...
def load(self, buddies): if self.session.loggedIn: self._load(buddies) else: self.session.loginQueue.append(lambda: self._load(buddies)) def update(self, number, nick, groups, image_hash): if number in self: buddy = self[number] buddy.update(nick, groups, image_hash) else: buddy = Buddy(sel...
buddy = self[number] if status is None: buddy.statusMsg = "" else: buddy.statusMsg = utils.softToUni(status) self.updateSpectrum(buddy)
conditional_block
frompsql.py
""" PostgreSQL Database data to Python Object/Array """ from gasp.pgsql import connection def sql_query(conParam, query, encoding=None): """ Retrive data from a SQL query """ conn = connection(conParam) if encoding: conn.set_client_encoding(encoding) cursor = conn.cursor() ...
return [ {cols[i] : row[i] for i in range(len(cols))} for row in data ] def sql_query_with_innerjoin( dic4con, main_table_lst, relation_table_lst, fld_of_interest, obj_of_interest, fields_to_select): """ Select data based on it relation with something Applies the SQL INN...
if cols[i][1:-1] in pgsql_special_words(): cols[i] = cols[i][1:-1]
conditional_block
frompsql.py
""" PostgreSQL Database data to Python Object/Array """ from gasp.pgsql import connection def sql_query(conParam, query, encoding=None): """ Retrive data from a SQL query """ conn = connection(conParam) if encoding: conn.set_client_encoding(encoding) cursor = conn.cursor() ...
) ) if not sanitizeColsName: from gasp.pgsql import pgsql_special_words for i in range(len(cols)): if cols[i][1:-1] in pgsql_special_words(): cols[i] = cols[i][1:-1] return [ {cols[i] : row[i] for i in range(len(cols))} for row in data ...
random_line_split
frompsql.py
""" PostgreSQL Database data to Python Object/Array """ from gasp.pgsql import connection def sql_query(conParam, query, encoding=None): """ Retrive data from a SQL query """ conn = connection(conParam) if encoding: conn.set_client_encoding(encoding) cursor = conn.cursor() ...
(conParam, query, geomCol='geom', epsg=None): """ Query database and convert data to Pandas GeoDataframe """ from geopandas import GeoDataFrame from gasp.pgsql import connection con = connection(conParam) df = GeoDataFrame.from_postgis( query, co...
psql_to_geodf
identifier_name
frompsql.py
""" PostgreSQL Database data to Python Object/Array """ from gasp.pgsql import connection def sql_query(conParam, query, encoding=None): """ Retrive data from a SQL query """ conn = connection(conParam) if encoding: conn.set_client_encoding(encoding) cursor = conn.cursor() ...
""" Query database and convert data to Pandas GeoDataframe """ from geopandas import GeoDataFrame from gasp.pgsql import connection con = connection(conParam) df = GeoDataFrame.from_postgis( query, con, geom_col=geomCol, crs="epsg:{}".format(str(epsg)) if epsg els...
identifier_body
index.js
'use strict'; var fs = require('fs') var path = require('path') var log = require('spm-log') var template = require('gulp-template') var inquirer = require('inquirer') var semver = require('semver') var vfs = require('vinyl-fs') module.exports = function(options) { if (!options.force && fs.readdirSync(process.cwd...
) inquirer.prompt([{ message: ' 项目名:', name: 'appname', 'default': path.basename(process.cwd()), validate: function(input) { var done = this.async() if (!/^[a-z][a-z0-9\-\.]*$/.test(input)) { log.warn('init spa', 'Must be only lowercase letters, numbers, dashes or dots, and start...
{ return log.error('init spa', '请在非空目录上执行初始化命令!') } log.info('init spa', '...'
conditional_block
index.js
'use strict'; var fs = require('fs') var path = require('path') var log = require('spm-log') var template = require('gulp-template') var inquirer = require('inquirer') var semver = require('semver') var vfs = require('vinyl-fs') module.exports = function(options) { if (!options.force && fs.readdirSync(process.cwd...
var done = this.async() if (!semver.valid(input)) { log.warn('init spa', 'Must be a valid semantic version (semver.org).') return } done(true) } }, { message: '项目描述:', name: 'description' }], function(answers) { answers.varname = answers.appname .replace...
name: 'version', 'default': '0.0.0', validate: function(input) {
random_line_split
index.d.ts
// Type definitions for form-serialize 0.7 // Project: https://github.com/defunctzombie/form-serialize#readme // Definitions by: Tyler Johnson <https://github.com/tyler-johnson> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3
} interface Options<Result> { /** Configure the output type. If true, the output will be a js object. */ hash?: boolean; /** * Optional serializer function to override the default one. The function takes 3 arguments (result, key, * value) and should return new result hash and url encoded str seri...
interface ResultHash { [key: string]: string | string[] | ResultHash;
random_line_split
numword_en_gb.py
# coding: utf-8 #This file is part of numword. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. ''' numword for EN_GB ''' from numword_en import NumWordEN class NumWordENGB(NumWordEN): ''' NumWord EN_GB ''' def currency(self, val, longva...
(value, longval=True): ''' Convert to currency ''' return _NW.currency(value, longval=longval) def year(value, longval=True): ''' Convert to year ''' return _NW.year(value, longval=longval) def main(): ''' Main ''' for val in [ 1, 11, 12, 21, 31, 33, 71, 80, 81, 91, 99,...
currency
identifier_name
numword_en_gb.py
# coding: utf-8 #This file is part of numword. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. ''' numword for EN_GB ''' from numword_en import NumWordEN class NumWordENGB(NumWordEN): ''' NumWord EN_GB ''' def currency(self, val, longva...
_NW.test(val) if __name__ == "__main__": main()
180, 300, 308, 832, 1000, 1001, 1061, 1100, 1120, 1500, 1701, 1800, 2000, 2010, 2099, 2171, 3000, 8280, 8291, 150000, 500000, 1000000, 2000000, 2000001, -21212121211221211111, -2.121212, -1.0000100, 132532543606787680176870010760100101221213214321047320754032705732095...
random_line_split
numword_en_gb.py
# coding: utf-8 #This file is part of numword. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. ''' numword for EN_GB ''' from numword_en import NumWordEN class NumWordENGB(NumWordEN): ''' NumWord EN_GB ''' def currency(self, val, longva...
_NW = NumWordENGB() def cardinal(value): ''' Convert to cardinal ''' return _NW.cardinal(value) def ordinal(value): ''' Convert to ordinal ''' return _NW.ordinal(value) def ordinal_number(value): ''' Convert to ordinal number ''' return _NW.ordinal_number(value) def...
''' Convert to currency ''' return self._split(val, hightxt=u"pound/s", lowtxt=u"pence", jointxt=u"and", longval=longval)
identifier_body
numword_en_gb.py
# coding: utf-8 #This file is part of numword. The COPYRIGHT file at the top level of #this repository contains the full copyright notices and license terms. ''' numword for EN_GB ''' from numword_en import NumWordEN class NumWordENGB(NumWordEN): ''' NumWord EN_GB ''' def currency(self, val, longva...
if __name__ == "__main__": main()
_NW.test(val)
conditional_block
class_tri_1_1_graphic_1_1_model.js
var class_tri_1_1_graphic_1_1_model = [ [ "Model", "class_tri_1_1_graphic_1_1_model.html#a57f8abc051d104b925e6a2cbb253b56c", null ], [ "GetNormal", "class_tri_1_1_graphic_1_1_model.html#a086a31e07b32371a5d7d6c4629853cb9", null ], [ "GetUV", "class_tri_1_1_graphic_1_1_model.html#a64da67596d9650b41ce0dd60f90e...
[ "GetVertex", "class_tri_1_1_graphic_1_1_model.html#af64f04fc0559ceb51061f8dfed0eb4e6", null ], [ "Render", "class_tri_1_1_graphic_1_1_model.html#aa190ca9e2258a28ea12a36d7fb25b0de", null ] ];
random_line_split
mod.rs
//! This module defines the trait necessary for a session storage struct. use self::session::Session; pub mod session; /// A default implementation of `SessionStore`: `Session`. pub mod hashsession; /// This `Trait` defines a session storage struct. It must be implemented on any store passed to `Sessions`. pub trai...
/// Set the value of the session belonging to `key`, replacing any previously set value. fn insert(&self, key: &K, value: V); /// Retrieve the value of this session. /// /// Returns `None` if the session belonging to `key` has not been set. fn find(&self, key: &K) -> Option<V>; /// Swap the...
{ Session::new(key, box self.clone()) }
identifier_body
mod.rs
//! This module defines the trait necessary for a session storage struct. use self::session::Session; pub mod session; /// A default implementation of `SessionStore`: `Session`. pub mod hashsession; /// This `Trait` defines a session storage struct. It must be implemented on any store passed to `Sessions`. pub trai...
/// Swap the given value with the current value of the session belonging to `key`. /// /// Returns the value being replaced, or `None` if this session was not yet set. fn swap(&self, key: &K, value: V) -> Option<V>; /// Insert value, if not yet set, or update the current value of the session belongi...
/// /// Returns `None` if the session belonging to `key` has not been set. fn find(&self, key: &K) -> Option<V>;
random_line_split
mod.rs
//! This module defines the trait necessary for a session storage struct. use self::session::Session; pub mod session; /// A default implementation of `SessionStore`: `Session`. pub mod hashsession; /// This `Trait` defines a session storage struct. It must be implemented on any store passed to `Sessions`. pub trai...
(&mut self, key: K) -> Session<K, V> { Session::new(key, box self.clone()) } /// Set the value of the session belonging to `key`, replacing any previously set value. fn insert(&self, key: &K, value: V); /// Retrieve the value of this session. /// /// Returns `None` if the session belongi...
select_session
identifier_name
options.js
require('./options-styles'); var CodeMirror = require('codemirror'); require('codemirror/addon/fold/foldcode'); require('codemirror/addon/fold/foldgutter'); require('codemirror/addon/fold/brace-fold'); require('codemirror/mode/javascript/javascript'); require('codemirror/addon/hint/show-hint'); require('codemirror/addo...
() { var version = process.env.VERSION; var versionLink = document.getElementsByClassName('version')[0]; versionLink.innerHTML = version; versionLink.href = "https://github.com/tulios/json-viewer/tree/" + version; } function onLoaded() { var currentOptions = Storage.load(); renderVersion(); renderThemeL...
renderVersion
identifier_name
options.js
require('./options-styles'); var CodeMirror = require('codemirror'); require('codemirror/addon/fold/foldcode'); require('codemirror/addon/fold/foldgutter'); require('codemirror/addon/fold/brace-fold'); require('codemirror/mode/javascript/javascript'); require('codemirror/addon/hint/show-hint'); require('codemirror/addo...
function renderVersion() { var version = process.env.VERSION; var versionLink = document.getElementsByClassName('version')[0]; versionLink.innerHTML = version; versionLink.href = "https://github.com/tulios/json-viewer/tree/" + version; } function onLoaded() { var currentOptions = Storage.load(); renderV...
{ try { JSON.parse(pseudoJSON); return true; } catch(e) { return false; } }
identifier_body
options.js
require('./options-styles'); var CodeMirror = require('codemirror'); require('codemirror/addon/fold/foldcode'); require('codemirror/addon/fold/foldgutter'); require('codemirror/addon/fold/brace-fold'); require('codemirror/mode/javascript/javascript'); require('codemirror/addon/hint/show-hint'); require('codemirror/addo...
else if (!isValidJSON(options.structure)) { sweetAlert("Ops!", "\"Structure\" isn't a valid JSON", "error"); } else { Storage.save(options); sweetAlert("Success", "Options saved!", "success"); } }); } document.addEventListener("DOMContentLoaded", onLoaded, false);
{ sweetAlert("Ops!", "\"Add-ons\" isn't a valid JSON", "error"); }
conditional_block
options.js
require('./options-styles'); var CodeMirror = require('codemirror'); require('codemirror/addon/fold/foldcode'); require('codemirror/addon/fold/foldgutter'); require('codemirror/addon/fold/brace-fold'); require('codemirror/mode/javascript/javascript'); require('codemirror/addon/hint/show-hint'); require('codemirror/addo...
document.addEventListener("DOMContentLoaded", onLoaded, false);
random_line_split
image_background.js
function loadText() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "Afbeelding Bron"; txtLang[1].innerHTML = "Herhalen"; txtLang[2].innerHTML = "Horizontale Uitlijning"; txtLang[3].innerHTML = "Verticale Uitlijning"; var optLang = document.getElementsB...
() { document.write("<title>Achtergrond Afbeelding</title>") }
writeTitle
identifier_name
image_background.js
function loadText() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "Afbeelding Bron"; txtLang[1].innerHTML = "Herhalen"; txtLang[2].innerHTML = "Horizontale Uitlijning"; txtLang[3].innerHTML = "Verticale Uitlijning"; var optLang = document.getElementsB...
{ document.write("<title>Achtergrond Afbeelding</title>") }
identifier_body
image_background.js
function loadText() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "Afbeelding Bron";
var optLang = document.getElementsByName("optLang"); optLang[0].text = "Herhalen" optLang[1].text = "Niet herhalen" optLang[2].text = "Herhalen x" optLang[3].text = "Herhalen y" optLang[4].text = "links" optLang[5].text = "midden" optLang[6].text = "rechts" optLang[7].text = ...
txtLang[1].innerHTML = "Herhalen"; txtLang[2].innerHTML = "Horizontale Uitlijning"; txtLang[3].innerHTML = "Verticale Uitlijning";
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-16 14:10 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
('created_at', models.DateTimeField()), ], ), migrations.AddField( model_name='answer', name='question', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='qa.Question'), ), ]
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Answer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.TextField()), ...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-16 14:10 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
('text', models.TextField()), ('created_at', models.DateTimeField()), ], ), migrations.CreateModel( name='Question', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID...
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-16 14:10 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Answer', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.T...
Migration
identifier_name
website-redirect.service.js
import { escapeFormat } from '../../core/badge-urls/path-helpers.js' import { redirector } from '../index.js' function
(t) { return ( escapeFormat(t) // Double slash .replace(/\/\//g, '/') ) } /* Old documentation, for reference: <p> <code>[OPTIONS]</code> can be: <ul> <li> Nothing:&nbsp; <code>…/website/…</code> </li> <li> Online and offline text:&nbsp; <code>…/website-up-d...
escapeFormatSlashes
identifier_name
website-redirect.service.js
import { escapeFormat } from '../../core/badge-urls/path-helpers.js' import { redirector } from '../index.js' function escapeFormatSlashes(t) { return ( escapeFormat(t) // Double slash .replace(/\/\//g, '/') ) } /* Old documentation, for reference: <p> <code>[OPTIONS]</code> can be: <ul> ...
export default [ redirector({ category: 'monitoring', route: { base: '', format: 'website-(([^-/]|--|//)+)-(([^-/]|--|//)+)(-(([^-/]|--|//)+)-(([^-/]|--|//)+))?/([^/]+)/(.+?)', capture: [ // Some of these could be made into non-capturing groups so these unused // para...
*/
random_line_split
website-redirect.service.js
import { escapeFormat } from '../../core/badge-urls/path-helpers.js' import { redirector } from '../index.js' function escapeFormatSlashes(t)
/* Old documentation, for reference: <p> <code>[OPTIONS]</code> can be: <ul> <li> Nothing:&nbsp; <code>…/website/…</code> </li> <li> Online and offline text:&nbsp; <code>…/website-up-down/…</code> </li> <li> Online and offline text, then online and offline colors...
{ return ( escapeFormat(t) // Double slash .replace(/\/\//g, '/') ) }
identifier_body
timer.rs
use std::sync::atomic::{Ordering,AtomicBool}; use std::sync::Arc; #[derive(Clone)] pub struct Timer{ seconds:u64, running:Arc<AtomicBool>, } impl Timer{ pub fn new(seconds:u64)->Timer{ let running = Arc::new(AtomicBool::new(false)); Timer{ seconds, running }
use std::thread; use std::time::Duration; if self.running.load(Ordering::Relaxed){ return Err("timer already running") } let running_clone = self.running.clone(); let sleep_time = self.seconds; let thread_builder = thread::Builder::new(); matc...
} pub fn start(&self)->Result<(),&str>{
random_line_split
timer.rs
use std::sync::atomic::{Ordering,AtomicBool}; use std::sync::Arc; #[derive(Clone)] pub struct Timer{ seconds:u64, running:Arc<AtomicBool>, } impl Timer{ pub fn new(seconds:u64)->Timer{ let running = Arc::new(AtomicBool::new(false)); Timer{ seconds, running }...
}
{ let timer = Timer::new(30); timer.start().unwrap(); std::thread::sleep(std::time::Duration::from_secs(5)); timer.start().unwrap(); }
identifier_body
timer.rs
use std::sync::atomic::{Ordering,AtomicBool}; use std::sync::Arc; #[derive(Clone)] pub struct Timer{ seconds:u64, running:Arc<AtomicBool>, } impl Timer{ pub fn new(seconds:u64)->Timer{ let running = Arc::new(AtomicBool::new(false)); Timer{ seconds, running }...
(){ let timer = Timer::new(30); assert_eq!(timer.is_running(),false); timer.start().unwrap(); } #[test] #[should_panic(expected = "timer already running")] fn multiple_timer_test(){ let timer = Timer::new(30); timer.start().unwrap(); std::thread::sleep(st...
timer_test
identifier_name
timer.rs
use std::sync::atomic::{Ordering,AtomicBool}; use std::sync::Arc; #[derive(Clone)] pub struct Timer{ seconds:u64, running:Arc<AtomicBool>, } impl Timer{ pub fn new(seconds:u64)->Timer{ let running = Arc::new(AtomicBool::new(false)); Timer{ seconds, running }...
let running_clone = self.running.clone(); let sleep_time = self.seconds; let thread_builder = thread::Builder::new(); match thread_builder.spawn(move ||{ running_clone.store(true,Ordering::Relaxed); thread::sleep(Duration::from_secs(sleep_time)); runn...
{ return Err("timer already running") }
conditional_block
__init__.py
""" The Django User class is used to handle users and authentication. https://docs.djangoproject.com/en/1.10/ref/contrib/auth/ User groups: superadmin - Can access django admin page admin - Can access regular admin pages hacker - Hacker pages mentor - Mentor pages judge - Judge pages user (imp...
# TODO OldParseUser # TODO OldParseHacker # TODO OldParseMentor
random_line_split
tmdb-api.ts
import { SearchApi } from './features/search-api'; import { Context } from './context'; import { MoviesApi } from './features/movies-api'; import { CollectionsApi } from './features/collections-api'; import { PeopleApi } from './features/people-api'; import { TvApi } from './features/tv-api'; export class TmdbApi { ...
get movies() { return this._movies || (this._movies = new MoviesApi(this.context)); } get collections() { return this._collections || (this._collections = new CollectionsApi(this.context)); } get people() { return this._people || (this._people = new PeopleApi(this.context)); } get tvshows() { return ...
} get search() { return this._search || (this._search = new SearchApi(this.context)); }
random_line_split
tmdb-api.ts
import { SearchApi } from './features/search-api'; import { Context } from './context'; import { MoviesApi } from './features/movies-api'; import { CollectionsApi } from './features/collections-api'; import { PeopleApi } from './features/people-api'; import { TvApi } from './features/tv-api'; export class TmdbApi { ...
(apiKey: string, language = 'en') { this.context = new Context(); this.context.apiKey = apiKey; this.context.language = language; } get search() { return this._search || (this._search = new SearchApi(this.context)); } get movies() { return this._movies || (this._movies = new MoviesApi(this.context)); }...
constructor
identifier_name
tmdb-api.ts
import { SearchApi } from './features/search-api'; import { Context } from './context'; import { MoviesApi } from './features/movies-api'; import { CollectionsApi } from './features/collections-api'; import { PeopleApi } from './features/people-api'; import { TvApi } from './features/tv-api'; export class TmdbApi { ...
}
{ return this._tvshows || (this._tvshows = new TvApi(this.context)); }
identifier_body
klog.rs
use core::fmt; #[derive(PartialEq, PartialOrd)] pub enum Level { Debug, Info, Warning, Error, Fatal, } fn write_nothing(_: &str) {} static mut WRITE: fn(&str) = write_nothing; static mut LEVEL: Level = Level::Info; pub fn init(write: fn(&str), level: Level) { unsafe { WRITE = write; ...
(level: Level, args: fmt::Arguments) { unsafe { if level < LEVEL { return; } let writer: &mut fmt::Write = &mut Writer; let prefix = match level { Level::Debug => "d ", Level::Info => "i ", Level::Warning => "W ", Level::Er...
log
identifier_name
klog.rs
use core::fmt; #[derive(PartialEq, PartialOrd)] pub enum Level { Debug, Info, Warning, Error, Fatal, } fn write_nothing(_: &str) {} static mut WRITE: fn(&str) = write_nothing; static mut LEVEL: Level = Level::Info; pub fn init(write: fn(&str), level: Level) { unsafe { WRITE = write; ...
fn write_str(&mut self, s: &str) -> fmt::Result { unsafe { WRITE(s); } Ok(()) } } pub fn log(level: Level, args: fmt::Arguments) { unsafe { if level < LEVEL { return; } let writer: &mut fmt::Write = &mut Writer; let prefix = match level { ...
struct Writer; impl fmt::Write for Writer {
random_line_split
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from glob import glob from io import open import os import re import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('python setup...
setup( name=meta_info('__title__'), version=meta_info('__version__'), description='shanbay.com team assistant', long_description=long_description(), url='https://github.com/mozillazg/python-shanbay-team-assistant', download_url='', author=meta_info('__author__'), author_email=meta_inf...
meta = re.escape(meta) m = re.search(r"""%s\s+=\s+(?P<quote>['"])(?P<meta>.+?)(?P=quote)""" % meta, read_f(filename)) return m.group('meta') if m else default
identifier_body
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from glob import glob from io import open import os import re import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('python setup...
'README.md', 'LICENSE', 'CHANGELOG.md', 'settings.ini.example', ] + glob('templates/*.example') + glob('templates/*/*.example'), 'include_msvcr': True, } } try: from cx_Freeze import setup, Executable kwargs = dict( options=options, ...
random_line_split
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from glob import glob from io import open import os import re import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish':
options = { 'build_exe': { 'packages': ['lxml', 'bs4', 'requests', 'html5lib', 'argparse', 'shanbay'], 'icon': 'shanbay.ico', 'include_files': [ 'README.md', 'LICENSE', 'CHANGELOG.md', 'settings.ini.example', ] + glob('templates/*.exa...
os.system('python setup.py sdist upload') os.system('python setup.py bdist_wheel upload') sys.exit()
conditional_block
setup.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from glob import glob from io import open import os import re import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('python setup...
(meta, filename='shanbay_assistant/__init__.py', default=''): meta = re.escape(meta) m = re.search(r"""%s\s+=\s+(?P<quote>['"])(?P<meta>.+?)(?P=quote)""" % meta, read_f(filename)) return m.group('meta') if m else default setup( name=meta_info('__title__'), version=meta_info('__ve...
meta_info
identifier_name
mod.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn decode_error_kind(errno: i32) -> ErrorKind { match errno { syscall::ECONNREFUSED => ErrorKind::ConnectionRefused, syscall::ECONNRESET => ErrorKind::ConnectionReset, syscall::EPERM | syscall::EACCES => ErrorKind::PermissionDenied, syscall::EPIPE => ErrorKind::BrokenPipe, ...
{}
identifier_body
mod.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub mod thread_local; pub mod time; #[cfg(not(test))] pub fn init() {} pub fn decode_error_kind(errno: i32) -> ErrorKind { match errno { syscall::ECONNREFUSED => ErrorKind::ConnectionRefused, syscall::ECONNRESET => ErrorKind::ConnectionReset, syscall::EPERM | syscall::EACCES => ErrorKind::...
pub mod stack_overflow; pub mod stdio; pub mod syscall; pub mod thread;
random_line_split
mod.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() {} pub fn decode_error_kind(errno: i32) -> ErrorKind { match errno { syscall::ECONNREFUSED => ErrorKind::ConnectionRefused, syscall::ECONNRESET => ErrorKind::ConnectionReset, syscall::EPERM | syscall::EACCES => ErrorKind::PermissionDenied, syscall::EPIPE => ErrorKind::BrokenPipe,...
init
identifier_name
jacapo.py
# do some tests here before we import # Right version of Scientific? from ase.test import NotAvailable import os try: import Scientific version = Scientific.__version__.split(".") print 'Found ScientificPython version: ',Scientific.__version__ if map(int,version) < [2,8]: print 'ScientificPython...
print "No Dacapo Fortran executable (dacapo.run) found. Check your path settings." raise NotAvailable('dacapo.run is not installed on this machine or not in the path') # Now Scientific 2.8 and dacapo.run should both be available from ase import Atoms, Atom from ase.calculators.jacapo import Jacapo atoms = At...
print "No Scientific python found. Check your PYTHONPATH" raise NotAvailable('ScientificPython version 2.8 or greater is required') if not (os.system('which dacapo.run') == 0):
random_line_split
jacapo.py
# do some tests here before we import # Right version of Scientific? from ase.test import NotAvailable import os try: import Scientific version = Scientific.__version__.split(".") print 'Found ScientificPython version: ',Scientific.__version__ if map(int,version) < [2,8]: print 'ScientificPython...
# Now Scientific 2.8 and dacapo.run should both be available from ase import Atoms, Atom from ase.calculators.jacapo import Jacapo atoms = Atoms([Atom('H',[0,0,0])], cell=(2,2,2)) calc = Jacapo('Jacapo-test.nc', pw=200, nbands=2, kpts=(1,1,1), spi...
print "No Dacapo Fortran executable (dacapo.run) found. Check your path settings." raise NotAvailable('dacapo.run is not installed on this machine or not in the path')
conditional_block
create-app.component.ts
import { UserService } from './../../shared/services/user.service'; import { Links, RuntimeImage } from './../../shared/models/constants'; import { Component, OnInit, OnDestroy, Input, Injector } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { CustomFormControl } from './../../co...
const required = new RequiredValidator(this._translateService); const siteNameValidator = new SiteNameValidator(injector, sub.subscriptionId); this.group = _fb.group({ name: [null, required.validate.bind(required), siteNameValidator.validate.bind(siteNameValidator)...
{ return; }
conditional_block
create-app.component.ts
import { UserService } from './../../shared/services/user.service'; import { Links, RuntimeImage } from './../../shared/models/constants'; import { Component, OnInit, OnDestroy, Input, Injector } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { CustomFormControl } from './../../co...
(viewInfo: TreeViewInfo<any>) { this.viewInfoStream.next(viewInfo); } ngOnInit() { this._broadcastService .getEvents<TreeViewInfo<any>>(BroadcastEvent.TreeNavigation) .filter(info => { return info.dashboardType === DashboardType.createApp; }) ...
viewInfoInput
identifier_name
create-app.component.ts
import { UserService } from './../../shared/services/user.service'; import { Links, RuntimeImage } from './../../shared/models/constants'; import { Component, OnInit, OnDestroy, Input, Injector } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { CustomFormControl } from './../../co...
}); this.runtimeImageOptions.push({ displayLabel: this._translateService.instant(PortalResources.runtimeImagev1), value: RuntimeImage.v1 }); this.runtimeImageOptions.push({ displayLabel: this._translateService.instant(PortalResources.runtimeImagev2), ...
subscription: defaultSubId, runtimeImage: RuntimeImage.v2 });
random_line_split