file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
main.rs
// Copyright (C) 2015, Alberto Corona <ac@albertocorona.com> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. #![crate_type = "bin"] #![crate_name = "mkdir"] static UTIL: Prog = Prog { name: "mkdir", vers: "0.1.0", yr: "2015"...
fn main() { let args: Vec<String> = env::args().collect(); let mut opts = Options::new(); opts.optflag("v", "verbose", "Print the name of each created directory"); opts.optflag("p", "parents", "No error if existing, make parent directories as needed"); opts.optflag("h", "help", "Print help infor...
{ print!("{}: {} {}... {}...\n\ Create DIRECTORY(ies) if they do not already exist.", "Usage".bold(), UTIL.name.bold(), "[OPTION]".underline(), "DIRECTORY".underline()); println!("{}", opts.options()); }
identifier_body
GSheet2Python.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Takes Google's json encoded spreadsheet and prints a python dictionary keyed by the values in the first column of the SS. ©2017 J. J. Crump, GNU general public license """ import urllib2 from pprint import pprint import re import json # This is the url of a sample googl...
def parsestring(rowstring, fields): """yields tuples of (fieldname, fieldvalue)""" i = iter(fields[1:]) field = i.next() start = end = 0 try: while True: lastfield = field field = i.next() if rowstring.find(field) == -1: field = lastfield ...
random_line_split
GSheet2Python.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Takes Google's json encoded spreadsheet and prints a python dictionary keyed by the values in the first column of the SS. ©2017 J. J. Crump, GNU general public license """ import urllib2 from pprint import pprint import re import json # This is the url of a sample googl...
rowstring, fields): """yields tuples of (fieldname, fieldvalue)""" i = iter(fields[1:]) field = i.next() start = end = 0 try: while True: lastfield = field field = i.next() if rowstring.find(field) == -1: field = lastfield c...
arsestring(
identifier_name
GSheet2Python.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Takes Google's json encoded spreadsheet and prints a python dictionary keyed by the values in the first column of the SS. ©2017 J. J. Crump, GNU general public license """ import urllib2 from pprint import pprint import re import json # This is the url of a sample googl...
end = rowstring.find(field) yield lastfield, re.sub('^.*?:', '', rowstring[start:end].strip().strip(',')).strip() start = end except StopIteration: start = rowstring.find(field) yield lastfield, re.sub('^.*?:', '', rowstring[start:].strip...
ield = lastfield continue
conditional_block
GSheet2Python.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ Takes Google's json encoded spreadsheet and prints a python dictionary keyed by the values in the first column of the SS. ©2017 J. J. Crump, GNU general public license """ import urllib2 from pprint import pprint import re import json # This is the url of a sample googl...
for e in entryList: entrydict = dict([x for x in parsestring(e['content']['$t'], fields)]) entrykey = e['title']['$t'] SSdict[entrykey] = entrydict #print stringIn pprint(SSdict)
""yields tuples of (fieldname, fieldvalue)""" i = iter(fields[1:]) field = i.next() start = end = 0 try: while True: lastfield = field field = i.next() if rowstring.find(field) == -1: field = lastfield continue end =...
identifier_body
ui.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
.version(&version!()[..]) .author("Matthias Beyer <mail@beyermatthias.de>") .about("Initialize a ~/.imag repository. Optionally with git") .arg(Arg::with_name("devel") .long("dev") .takes_value(false) .required(false) .multiple(false) ...
App::new("imag-init")
random_line_split
ui.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
{ App::new("imag-init") .version(&version!()[..]) .author("Matthias Beyer <mail@beyermatthias.de>") .about("Initialize a ~/.imag repository. Optionally with git") .arg(Arg::with_name("devel") .long("dev") .takes_value(false) .required(false) ...
identifier_body
ui.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
<'a>() -> App<'a, 'a> { App::new("imag-init") .version(&version!()[..]) .author("Matthias Beyer <mail@beyermatthias.de>") .about("Initialize a ~/.imag repository. Optionally with git") .arg(Arg::with_name("devel") .long("dev") .takes_value(false) ...
build_ui
identifier_name
index.ts
import styled from 'styled-components' import type { TTestable } from '@/spec' import Img from '@/Img' import { theme } from '@/utils/themes' import css from '@/utils/css' import { getNormalColor, getActiveColor, getNormalTextSize, getActiveIconSize, getNormalIconSize, } from './metric' type TIcon = { ac...
export const Wrapper = styled.div.attrs(({ testid }: TTestable) => ({ 'data-test-id': testid, }))<TTestable & TText>` ${css.flex('align-center')}; /* margin-left: 12px; */ cursor: pointer; background: ${({ hideTextOnInit, active }) => !hideTextOnInit || active ? '#0f3f4e' : 'transparent'}; padding: ${({...
random_line_split
__init__.py
import numpy as np import logging from logging.handlers import RotatingFileHandler from time import strftime, gmtime import json import sys import os import traceback __version__ = '2.7.5' # Setup Logger logging.basicConfig(level=logging.DEBUG) logging.getLogger('PyQt5').setLevel(logging.WARNING) root_logger = loggi...
PATH_TO_RESOURCES = os.path.join(package_dir, 'resources') PATH_TO_CFG_FILE = os.path.join(package_dir, 'inlinino_cfg.json') # Logging in file path_to_log = os.path.join(package_dir, 'logs') if not os.path.isdir(path_to_log): root_logger.debug('Create log directory: %s' % path_to_log) os.mkdir(path_to_log) lo...
root_logger.debug('Running from source') package_dir = os.path.dirname(__file__)
conditional_block
__init__.py
import numpy as np import logging from logging.handlers import RotatingFileHandler from time import strftime, gmtime import json import sys import os import traceback __version__ = '2.7.5' # Setup Logger logging.basicConfig(level=logging.DEBUG) logging.getLogger('PyQt5').setLevel(logging.WARNING) root_logger = loggi...
def write(self): self.__logger.info('Writing configuration.') cfg = {'instruments': self.instruments} with open(PATH_TO_CFG_FILE, 'w') as file: json.dump(cfg, file, cls=BytesEncoder) CFG = Cfg() class RingBuffer: # Ring buffer based on numpy.roll for np.array # Same ...
sys.exit(-1) self.instruments = cfg['instruments']
random_line_split
__init__.py
import numpy as np import logging from logging.handlers import RotatingFileHandler from time import strftime, gmtime import json import sys import os import traceback __version__ = '2.7.5' # Setup Logger logging.basicConfig(level=logging.DEBUG) logging.getLogger('PyQt5').setLevel(logging.WARNING) root_logger = loggi...
def __str__(self): return str(self.data)
return self.data[0:_n]
identifier_body
__init__.py
import numpy as np import logging from logging.handlers import RotatingFileHandler from time import strftime, gmtime import json import sys import os import traceback __version__ = '2.7.5' # Setup Logger logging.basicConfig(level=logging.DEBUG) logging.getLogger('PyQt5').setLevel(logging.WARNING) root_logger = loggi...
(self, _length, _dtype=None): # initialize buffer with NaN values # length correspond to the size of the buffer if _dtype is None: self.data = np.empty(_length) # np.dtype = float64 self.data[:] = np.NAN else: # type needs to be compatible with np.NaN...
__init__
identifier_name
EarlyDotRefreshes.tsx
import { formatDuration } from 'common/format'; import Spell from 'common/SPELLS/Spell'; import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events, { ApplyDebuffEvent, RefreshDebuffEvent, GlobalCooldownEvent, CastEvent, } from 'parser/core/Events'; import AbilityTracker from 'pars...
if (text && text !== '') { this.addBadCast(this.lastCast, text); } } // Get the suggestion for last bad cast. If empty, cast will be considered good. getLastBadCastText(event: CastEvent, dot: Dot) { return `${dot.name} was refreshed ${formatDuration( this.lastCastMinWaste, )} seconds ...
return; // Should not be marked as bad. } const dot = this.getDotByCast(this.lastCast.ability.guid); const text = dot && this.getLastBadCastText(event, dot);
random_line_split
EarlyDotRefreshes.tsx
import { formatDuration } from 'common/format'; import Spell from 'common/SPELLS/Spell'; import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events, { ApplyDebuffEvent, RefreshDebuffEvent, GlobalCooldownEvent, CastEvent, } from 'parser/core/Events'; import AbilityTracker from 'pars...
// We wait roughly a GCD to check, to account for minor travel times. const timeSinceCast = event.timestamp - this.lastGCD.timestamp; if (!this.lastCastBuffer || timeSinceCast < this.lastCastBuffer) { return; } this.casts[this.lastCast.ability.guid].addedDuration += this.lastCastMaxEffect; ...
{ return; }
conditional_block
EarlyDotRefreshes.tsx
import { formatDuration } from 'common/format'; import Spell from 'common/SPELLS/Spell'; import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events, { ApplyDebuffEvent, RefreshDebuffEvent, GlobalCooldownEvent, CastEvent, } from 'parser/core/Events'; import AbilityTracker from 'pars...
//Returns the dot object getDot(spellId: number) { const ctor = this.constructor as typeof EarlyDotRefreshes; const dot = ctor.dots.find((element) => element.debuffId === spellId); return dot; } //Returns the dot object getDotByCast(spellId: number) { const ctor = this.constructor as typeof...
{ return `${dot.name} was refreshed ${formatDuration( this.lastCastMinWaste, )} seconds before the pandemic window. It should be refreshed with at most ${formatDuration( PANDEMIC_WINDOW * dot.duration, )} left or part of the dot will be wasted.`; }
identifier_body
EarlyDotRefreshes.tsx
import { formatDuration } from 'common/format'; import Spell from 'common/SPELLS/Spell'; import Analyzer, { Options, SELECTED_PLAYER } from 'parser/core/Analyzer'; import Events, { ApplyDebuffEvent, RefreshDebuffEvent, GlobalCooldownEvent, CastEvent, } from 'parser/core/Events'; import AbilityTracker from 'pars...
(spellId: number) { const ctor = this.constructor as typeof EarlyDotRefreshes; const dot = ctor.dots.find((element) => element.castId === spellId); return dot; } // Extends the dot and returns true if it was a good extension (no duration wasted) or false if it was a bad extension. extendDot(spellId: ...
getDotByCast
identifier_name
location.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::LocationBinding; use dom::bindings::codegen::Bindings::LocationBinding::Loca...
}
{ &self.reflector_ }
identifier_body
location.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::LocationBinding; use dom::bindings::codegen::Bindings::LocationBinding::Loca...
(self) -> DOMString { UrlHelper::Href(&self.page.get_url()) } fn Search(self) -> DOMString { UrlHelper::Search(&self.page.get_url()) } fn Hash(self) -> DOMString { UrlHelper::Hash(&self.page.get_url()) } } impl Reflectable for Location { fn reflector<'a>(&'a self) -> &...
Href
identifier_name
location.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::LocationBinding; use dom::bindings::codegen::Bindings::LocationBinding::Loca...
fn reflector<'a>(&'a self) -> &'a Reflector { &self.reflector_ } }
random_line_split
app.js
'use strict'; /** * @ngdoc overview * @name gabineteApp * @description * # gabineteApp * * Main module of the application. */ angular .module('gabineteApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'slugifier' ]) .config(function ($routeProv...
indexData.map(function(row,ix) { that.data[row.grupo] = {elements: responses[ix]}; }) that.loading = false; resolve({ data: that.data, keys: that.keys }); }) return indexData; }); ...
}) Promise.all(fileList).then(function(responses) {
random_line_split
app.js
'use strict'; /** * @ngdoc overview * @name gabineteApp * @description * # gabineteApp * * Main module of the application. */ angular .module('gabineteApp', [ 'ngAnimate', 'ngCookies', 'ngResource', 'ngRoute', 'ngSanitize', 'ngTouch', 'slugifier' ]) .config(function ($routeProv...
else { resolve({data:that.data,keys:that.keys}); } }); }; });
{ // if(!that.loading){ that.loading = true; d3.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vSZG-bnXn217ELlkVTAuNZDdmtdPTdsbJ6CGYxAXyFEz24Uk503mOeMtr2dEVUNlg2OowwWpCOKGgIr/pub?gid=1766965020&single=true&output=csv") .then(function(indexData) { var f...
conditional_block
CustomComponentMentionEditor.tsx
import React, { ReactElement, useRef, useState } from 'react'; import { EditorState } from 'draft-js'; import Editor from '@draft-js-plugins/editor'; import createMentionPlugin, { defaultSuggestionsFilter, } from '@draft-js-plugins/mention'; import editorStyles from './editorStyles.css'; import mentions from './menti...
const [editorState, setEditorState] = useState(EditorState.createEmpty()); const editor = useRef<Editor>(); const [open, setOpen] = useState(false); const [suggestions, setSuggestions] = useState(mentions); const onChange = (value): void => { setEditorState(value); }; const focus = (): void => { ...
const CustomMentionEditor = (): ReactElement => {
random_line_split
CustomComponentMentionEditor.tsx
import React, { ReactElement, useRef, useState } from 'react'; import { EditorState } from 'draft-js'; import Editor from '@draft-js-plugins/editor'; import createMentionPlugin, { defaultSuggestionsFilter, } from '@draft-js-plugins/mention'; import editorStyles from './editorStyles.css'; import mentions from './menti...
, }); const { MentionSuggestions } = mentionPlugin; const plugins = [mentionPlugin]; const CustomMentionEditor = (): ReactElement => { const [editorState, setEditorState] = useState(EditorState.createEmpty()); const editor = useRef<Editor>(); const [open, setOpen] = useState(false); const [suggestions, setSug...
{ return ( <span className={props.className} // eslint-disable-next-line no-alert onClick={() => alert('Clicked on the Mention!')} > {props.children} </span> ); }
identifier_body
CustomComponentMentionEditor.tsx
import React, { ReactElement, useRef, useState } from 'react'; import { EditorState } from 'draft-js'; import Editor from '@draft-js-plugins/editor'; import createMentionPlugin, { defaultSuggestionsFilter, } from '@draft-js-plugins/mention'; import editorStyles from './editorStyles.css'; import mentions from './menti...
(props): ReactElement { return ( <span className={props.className} // eslint-disable-next-line no-alert onClick={() => alert('Clicked on the Mention!')} > {props.children} </span> ); }, }); const { MentionSuggestions } = mentionPlugin; const plugins = [mention...
mentionComponent
identifier_name
index.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import * as _ from 'lodash'; import styled from 'react-emotion'; import { HUD...
} public shouldComponentUpdate(nextProps: AbilityBarProps, nextState: AbilityBarState) { return true; // return !_.isEqual(nextState.clientAbilities, this.state.clientAbilities) || // !_.isEqual(nextProps.apiAbilities, this.props.apiAbilities); } private updateAbilities = () => { const sorte...
if (game.abilityBarState.isReady) { this.updateAbilities(); }
random_line_split
index.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import * as _ from 'lodash'; import styled from 'react-emotion'; import { HUD...
} private sortByAbilityID = (a: AbilityBarItem, b: AbilityBarItem) => { const aID = !_.isNumber(a.id) ? parseInt(a.id, 16) : a.id; const bID = !_.isNumber(b.id) ? parseInt(b.id, 16) : b.id; return aID - bID; } } class AbilityBarWithInjectedContext extends React.Component<{}> { public render() { ...
{ window.setTimeout(() => this.props.apiAbilities.refetch(), 50); }
conditional_block
index.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import * as _ from 'lodash'; import styled from 'react-emotion'; import { HUD...
} export default AbilityBarWithInjectedContext;
{ return ( <HUDContext.Consumer> {({ skills }) => { return ( <AbilityBar apiAbilities={skills} /> ); }} </HUDContext.Consumer> ); }
identifier_body
index.tsx
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import * as _ from 'lodash'; import styled from 'react-emotion'; import { HUD...
() { return ( <HUDContext.Consumer> {({ skills }) => { return ( <AbilityBar apiAbilities={skills} /> ); }} </HUDContext.Consumer> ); } } export default AbilityBarWithInjectedContext;
render
identifier_name
exposure.rs
use leelib::math; use leelib::matrix::Matrix; pub struct ExposureInfo { pub floor: usize, pub ceil: usize, pub bias: f64 } /** * 'Static' class * Finds the 'meaningful' range of values in a matrix, along with a 'bias' value. * Experiment. */ pub struct ExposureUtil; impl ExposureUtil { /** * max_val -...
} let mut i_c = 0 as usize; let thresh = sum as f64 * (0.5 + 0.34); let mut s = 0; for i in lower..(upper + 1) { s += histogram[i] as u64; if s as f64 > thresh { // is like 84th percentile i_c = i; break; } } // make hand-wavey value using the above to represent 'bias' let a = ...
i_b = i; break; }
random_line_split
exposure.rs
use leelib::math; use leelib::matrix::Matrix; pub struct ExposureInfo { pub floor: usize, pub ceil: usize, pub bias: f64 } /** * 'Static' class * Finds the 'meaningful' range of values in a matrix, along with a 'bias' value. * Experiment. */ pub struct ExposureUtil; impl ExposureUtil { /** * max_val -...
(matrix: &Matrix<u16>, max_val: u16, lower_thresh_ratio: f64, upper_thresh_ratio: f64) -> ExposureInfo { // count the values in `matrix` let mut histogram = vec!(0u16; (max_val + 1) as usize); for val in matrix { histogram[val as usize] += 1; } let range = ExposureUtil::get_range(&histogram, &matrix, low...
calc
identifier_name
exposure.rs
use leelib::math; use leelib::matrix::Matrix; pub struct ExposureInfo { pub floor: usize, pub ceil: usize, pub bias: f64 } /** * 'Static' class * Finds the 'meaningful' range of values in a matrix, along with a 'bias' value. * Experiment. */ pub struct ExposureUtil; impl ExposureUtil { /** * max_val -...
/** * Returns a value in range (-1, +1) */ fn calc_bias(histogram: &Vec<u16>, lower: usize, upper: usize) -> f64 { if lower == upper { return 0.0; } if upper == lower + 1 { return if histogram[lower] < histogram[upper] { return -1.0; } else { return 1.0; } } // get sum of all v...
{ let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * lower_thresh_ratio; let mut lower_index = 0; let mut sum = 0; for i in 0..histogram.len() { sum += histogram[i]; if sum as f64 > sum_thresh { lower_index = if i <= 1 { 0 as usize } else { i - 1 // rewind by 1 ...
identifier_body
exposure.rs
use leelib::math; use leelib::matrix::Matrix; pub struct ExposureInfo { pub floor: usize, pub ceil: usize, pub bias: f64 } /** * 'Static' class * Finds the 'meaningful' range of values in a matrix, along with a 'bias' value. * Experiment. */ pub struct ExposureUtil; impl ExposureUtil { /** * max_val -...
} let sum_thresh = (matrix.width() as f64 * matrix.height() as f64) * upper_thresh_ratio; let mut upper_index = 0; let mut sum = 0; for i in (0..histogram.len()).rev() { sum += histogram[i]; if sum as f64 > sum_thresh { upper_index = if i == histogram.len() - 1 { histogram.len() - 1 ...
{ lower_index = if i <= 1 { 0 as usize } else { i - 1 // rewind by 1 }; break; }
conditional_block
settings.py
# AWX settings file import os def get_secret():
ADMINS = () STATIC_ROOT = '/var/lib/awx/public/static' PROJECTS_ROOT = '/var/lib/awx/projects' AWX_ANSIBLE_COLLECTIONS_PATHS = '/var/lib/awx/vendor/awx_ansible_collections' JOBOUTPUT_ROOT = '/var/lib/awx/job_status' SECRET_KEY = get_secret() ALLOWED_HOSTS = ['*'] # Container environments don't like chroots AW...
if os.path.exists("/etc/tower/SECRET_KEY"): return open('/etc/tower/SECRET_KEY', 'rb').read().strip()
identifier_body
settings.py
# AWX settings file import os def
(): if os.path.exists("/etc/tower/SECRET_KEY"): return open('/etc/tower/SECRET_KEY', 'rb').read().strip() ADMINS = () STATIC_ROOT = '/var/lib/awx/public/static' PROJECTS_ROOT = '/var/lib/awx/projects' AWX_ANSIBLE_COLLECTIONS_PATHS = '/var/lib/awx/vendor/awx_ansible_collections' JOBOUTPUT_ROOT = '/var/...
get_secret
identifier_name
settings.py
# AWX settings file import os def get_secret(): if os.path.exists("/etc/tower/SECRET_KEY"): return open('/etc/tower/SECRET_KEY', 'rb').read().strip() ADMINS = () STATIC_ROOT = '/var/lib/awx/public/static' PROJECTS_ROOT = '/var/lib/awx/projects' AWX_ANSIBLE_COLLECTIONS_PATHS = '/var/lib/awx/vendor/aw...
USE_X_FORWARDED_HOST = True USE_X_FORWARDED_PORT = True
DATABASES['default']['OPTIONS'] = {'sslmode': os.getenv("DATABASE_SSLMODE")}
conditional_block
settings.py
# AWX settings file import os def get_secret(): if os.path.exists("/etc/tower/SECRET_KEY"): return open('/etc/tower/SECRET_KEY', 'rb').read().strip() ADMINS = () STATIC_ROOT = '/var/lib/awx/public/static' PROJECTS_ROOT = '/var/lib/awx/projects' AWX_ANSIBLE_COLLECTIONS_PATHS = '/var/lib/awx/vendor/aw...
AWX_PROOT_ENABLED = False CLUSTER_HOST_ID = "awx" SYSTEM_UUID = '00000000-0000-0000-0000-000000000000' CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False ############################################################################### # EMAIL SETTINGS ###########################################################...
# Container environments don't like chroots
random_line_split
dashboard.js
var oscar = (function(o, $) { o.getCsrfToken = function() { // Extract CSRF token from cookies var cookies = document.cookie.split(';'); var csrf_token = null; $.each(cookies, function(index, cookie) { cookieParts = $.trim(cookie).split('='); if (cookieParts[...
} return false; }); // Adds error icon if there are errors in the product update form $('[data-behaviour="affix-nav-errors"] .tab-pane').each(function(){ var productErrorListener = $(this).find('[class*="error"]:not(:empty)').closest('.t...
$this.removeClass('ico_expand').addClass('ico_contract'); } else { $this.removeClass('ico_contract').addClass('ico_expand');
random_line_split
dashboard.js
var oscar = (function(o, $) { o.getCsrfToken = function() { // Extract CSRF token from cookies var cookies = document.cookie.split(';'); var csrf_token = null; $.each(cookies, function(index, cookie) { cookieParts = $.trim(cookie).split('='); if (cookieParts[...
$(e).select2(opts); }); }, initDatePickers: function(el) { // Use datepicker for all inputs that have 'date' or 'datetime' in the name $inputs = $(el).find('input').not('.no-widget-init input').not('.no-widget-init'); if ($.datepicker) { ...
{ opts = { 'ajax': { 'url': $(e).data('ajax-url'), 'dataType': 'json', 'results': function(data, page) { if((page==1) && !($(e).data('required')=='required')) {...
conditional_block
metricshandler.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
# pylint: disable=too-many-locals, no-self-use, unused-argument @tornado.gen.coroutine def getComponentMetrics(self, tmaster, componentName, metricNames, instances, interval, ...
""" get method """ try: cluster = self.get_argument_cluster() role = self.get_argument_role() environ = self.get_argument_environ() topology_name = self.get_argument_topology() component = self.get_argument_component() metric_names = self.get_required_arguments_metricnames() ...
identifier_body
metricshandler.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
# pylint: disable=too-many-locals, no-self-use, unused-argument @tornado.gen.coroutine def getComponentMetrics(self, tmaster, componentName, metricNames, instances, interval, ...
random_line_split
metricshandler.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
# Form the response. ret = {} ret["interval"] = metricResponse.interval ret["component"] = componentName ret["metrics"] = {} for metric in metricResponse.metric: instance = metric.instance_id for im in metric.metric: metricname = im.name value = im.value if ...
if metricResponse.status.HasField("message"): Log.warn("Received response from Tmaster: %s", metricResponse.status.message)
conditional_block
metricshandler.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache...
(self): """ get method """ try: cluster = self.get_argument_cluster() role = self.get_argument_role() environ = self.get_argument_environ() topology_name = self.get_argument_topology() component = self.get_argument_component() metric_names = self.get_required_arguments_metric...
get
identifier_name
mandelbrot_set.py
import numpy as np import moderngl from ported._example import Example class Fractal(Example): title = "Mandelbrot" gl_version = (3, 3) def __init__(self, **kwargs):
def render(self, time, frame_time): self.ctx.clear(1.0, 1.0, 1.0) self.center.value = (0.5, 0.0) self.iter.value = 100 self.scale.value = 1.5 self.ratio.value = self.aspect_ratio self.texture.use() self.vao.render(moderngl.TRIANGLE_STRIP) if __name__ == ...
super().__init__(**kwargs) self.prog = self.ctx.program( vertex_shader=''' #version 330 in vec2 in_vert; out vec2 v_text; void main() { gl_Position = vec4(in_vert, 0.0, 1.0); v_text = in_vert; ...
identifier_body
mandelbrot_set.py
import numpy as np import moderngl from ported._example import Example class
(Example): title = "Mandelbrot" gl_version = (3, 3) def __init__(self, **kwargs): super().__init__(**kwargs) self.prog = self.ctx.program( vertex_shader=''' #version 330 in vec2 in_vert; out vec2 v_text; void mai...
Fractal
identifier_name
mandelbrot_set.py
import numpy as np import moderngl from ported._example import Example class Fractal(Example): title = "Mandelbrot" gl_version = (3, 3) def __init__(self, **kwargs): super().__init__(**kwargs) self.prog = self.ctx.program( vertex_shader=''' #version 330 ...
Fractal.run()
conditional_block
mandelbrot_set.py
import numpy as np
class Fractal(Example): title = "Mandelbrot" gl_version = (3, 3) def __init__(self, **kwargs): super().__init__(**kwargs) self.prog = self.ctx.program( vertex_shader=''' #version 330 in vec2 in_vert; out vec2 v_text; ...
import moderngl from ported._example import Example
random_line_split
etudaffectationmodel.ts
//etudaffectationmodel.ts import {InfoUserInfo} from './infouserinfo'; import {AffectationViewModel} from './affectationmodel'; import {EtudAffectation} from '../domain/etudaffectation'; import {Etudiant} from '../domain/etudiant'; import {IGroupe} from 'infodata'; import {GROUPE_GENRE_TP} from '../utils/infoconstants'...
(): EtudAffectation { let p = new EtudAffectation({ departementid: this.departementid, anneeid: this.anneeid, semestreid: this.semestreid, groupeid: this.groupeid, startDate: this._start, endDate: this._end, departementSigle: (t...
create_item
identifier_name
etudaffectationmodel.ts
//etudaffectationmodel.ts import {InfoUserInfo} from './infouserinfo'; import {AffectationViewModel} from './affectationmodel'; import {EtudAffectation} from '../domain/etudaffectation'; import {Etudiant} from '../domain/etudiant'; import {IGroupe} from 'infodata'; import {GROUPE_GENRE_TP} from '../utils/infoconstants'...
return p; } protected filter_groupe(g:IGroupe): boolean { return (g.genre == GROUPE_GENRE_TP) ? true : false; } protected create_item(): EtudAffectation { let p = new EtudAffectation({ departementid: this.departementid, anneeid: this.anneeid, semestreid: t...
this.title = 'Affectations etudiants'; } // protected create_person(): Etudiant { let p = new Etudiant({ departementid: this.departementid });
random_line_split
etudaffectationmodel.ts
//etudaffectationmodel.ts import {InfoUserInfo} from './infouserinfo'; import {AffectationViewModel} from './affectationmodel'; import {EtudAffectation} from '../domain/etudaffectation'; import {Etudiant} from '../domain/etudiant'; import {IGroupe} from 'infodata'; import {GROUPE_GENRE_TP} from '../utils/infoconstants'...
protected compose_item(p: Etudiant): EtudAffectation { let a = super.compose_item(p); a.etudiantid = p.id; a.check_id(); return a; } }// class EtudAffViewModel
{ let p = new EtudAffectation({ departementid: this.departementid, anneeid: this.anneeid, semestreid: this.semestreid, groupeid: this.groupeid, startDate: this._start, endDate: this._end, departementSigle: (this.departement !== ...
identifier_body
parse.js
module.exports = { parse: function(inputString, inputBlocks, inputOperators) { //set default delimiter set var defaultBlocks = { warm: { "{": "}", "(": ")", "[": "]" }, cold: { "'": "'", ...
//output the tree root excluding the EOF and BOF markers var result = lineage[0].slice(1, -1) result.toString = tokenArrayToString return result } }
{ var processed = 0; var awaiting = currentNode.slice(-1)[0] //block end if (!escapeMode && (input.slice(cursor, cursor + awaiting.length) == awaiting)) { if (buffer.length) { insertChildNode(currentNode, buffer, 0, 0) ...
conditional_block
parse.js
module.exports = { parse: function(inputString, inputBlocks, inputOperators) { //set default delimiter set
warm: { "{": "}", "(": ")", "[": "]" }, cold: { "'": "'", '"': '"', "`": "`", "/*": "*/", "//": "\n", "/": "/", "<": ">" ...
var defaultBlocks = {
random_line_split
buttonStrings.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2016 */ /* eslint-disable max-len */ import LocalizedStrings from 'react-native-localization'; export const buttonStrings = new LocalizedStrings({ gb: { add_batch: 'Add Batch', add_master_list_items: 'Add Master List Items', all_items_selected: ...
current: '​ປັດ​ຈຸ​ບັນ', done: 'ສໍາເລັດແລ້ວ', hide_stockouts: 'ເຊື່ອງ ການ​ຂາດ​ສິ​ນ​ຄ້າ​ໃສ​ສາງ', manage_stocktake: 'ເຮັດ​ການ​ຈັດ​ການ ກວດ​ກາ​ສິນ​ຄ້າ​ໃນ​ສາງ', new_invoice: 'ເຮັດໃບ​ເກັບ​ເງິນ​ໃໝ່', new_item: '​ເຮັດລາຍ​ການສິນຄ້າ​ມາໃໝ່', new_line: 'ເພີ່ມລາຍການໃໝ່', new_requisition: 'ເຮັດ​ການ​ສະ​...
random_line_split
device_recovery.py
#!/usr/bin/env vpython # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A script to recover devices in a known bad state.""" import argparse import glob import logging import os import signal import sys ...
(devices, denylist, enable_usb_reset=False): """Attempts to recover any inoperable devices in the provided list. Args: devices: The list of devices to attempt to recover. denylist: The current device denylist, which will be used then reset. """ statuses = device_status.DeviceStatus(devices, deny...
RecoverDevices
identifier_name
device_recovery.py
#!/usr/bin/env vpython # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A script to recover devices in a known bad state.""" import argparse import glob import logging import os import signal import sys ...
adb_wrapper.AdbWrapper.StartServer() for serial in should_restart_usb: try: # TODO(crbug.com/642194): Resetting may be causing more harm # (specifically, kernel panics) than it does good. if enable_usb_reset: reset_usb.reset_android_usb(serial) else: logger.warning('US...
KillAllAdb()
random_line_split
device_recovery.py
#!/usr/bin/env vpython # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A script to recover devices in a known bad state.""" import argparse import glob import logging import os import signal import sys ...
except device_errors.CommandTimeoutError: logger.exception('Timed out while rebooting %s.', str(device)) if denylist: denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_timeout') try: device.WaitUntilFullyBooted( retries=0, timeout=device.REBOOT_DEFAULT_TIMEOUT)...
denylist.Extend([device.adb.GetDeviceSerial()], reason='reboot_failure')
conditional_block
device_recovery.py
#!/usr/bin/env vpython # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A script to recover devices in a known bad state.""" import argparse import glob import logging import os import signal import sys ...
for sig in [signal.SIGTERM, signal.SIGQUIT, signal.SIGKILL]: for p, pinfo in get_all_adb(): try: pinfo['signal'] = sig logger.info('kill %(signal)s %(pid)s (%(name)s [%(cmdline)s])', pinfo) p.send_signal(sig) except (psutil.NoSuchProcess, psutil.AccessDenied): pass ...
for p in psutil.process_iter(): try: # Retrieve all required process infos at once. pinfo = p.as_dict(attrs=['pid', 'name', 'cmdline']) if pinfo['name'] == 'adb': pinfo['cmdline'] = ' '.join(pinfo['cmdline']) yield p, pinfo except (psutil.NoSuchProcess, psutil.Acc...
identifier_body
user.ts
import { Action, action, Thunk, thunk } from 'easy-peasy'; import updateAccountEmail from '@/api/account/updateAccountEmail';
uuid: string; username: string; email: string; language: string; rootAdmin: boolean; useTotp: boolean; createdAt: Date; updatedAt: Date; } export interface UserStore { data?: UserData; setUserData: Action<UserStore, UserData>; updateUserData: Action<UserStore, Partial<UserDa...
export interface UserData {
random_line_split
addTrip.js
const pObj=pico.export('pico/obj'), fb=require('api/fbJSON'), rdTrip=require('redis/trip') return { setup(context,cb){ cb() }, addPickup(user,action,evt,name,next){ const text=pObj.dotchain(evt,['message','text']) if(!text) return next(null,`fb/ask${action[action.length-1]}`) const a=action.pop() switch(...
(user,action,evt,name,next){ const text=pObj.dotchain(evt,['message','text']) if(!text) return next(null,`fb/ask${action[action.length-1]}`) const a=action.pop() switch(a){ case 'TripFirstDropoff': switch(text.toLowerCase()){ case 'done': return next(null,`fb/ask${a}`) default: action.push('-',t...
addDropoff
identifier_name
addTrip.js
const pObj=pico.export('pico/obj'), fb=require('api/fbJSON'), rdTrip=require('redis/trip') return { setup(context,cb)
, addPickup(user,action,evt,name,next){ const text=pObj.dotchain(evt,['message','text']) if(!text) return next(null,`fb/ask${action[action.length-1]}`) const a=action.pop() switch(a){ case 'TripFirstPickup': switch(text.toLowerCase()){ case 'done': return next(null,`fb/ask${a}`) default: action...
{ cb() }
identifier_body
addTrip.js
const pObj=pico.export('pico/obj'), fb=require('api/fbJSON'), rdTrip=require('redis/trip') return { setup(context,cb){ cb() }, addPickup(user,action,evt,name,next){ const text=pObj.dotchain(evt,['message','text']) if(!text) return next(null,`fb/ask${action[action.length-1]}`) const a=action.pop() switch(...
switch(text.toLowerCase()){ case 'done': action.push('+:dropoff',null) this.set(name,'TripSeat') break default: action.push('-',text) this.set(name,'TripDropoff') break } break default: return next(null,`fb/ask${a}`) } next() }, done(user,cmd,msg,next){ console.log('addTrp...
break } break case 'TripDropoff':
random_line_split
lib.rs
#![feature(test, i128_type)] extern crate test; use test::Bencher; extern crate rand; extern crate speck; use rand::Rng; use rand::OsRng; use speck::Key; #[bench] fn generate_key(mut bencher: &mut Bencher) { let mut rng = OsRng::new().unwrap(); let key_input = rng.gen(); bencher.iter(|| test::black_b...
{ let mut rng = OsRng::new().unwrap(); (Key::new(rng.gen()), rng.gen()) }
identifier_body
lib.rs
#![feature(test, i128_type)] extern crate test; use test::Bencher; extern crate rand; extern crate speck; use rand::Rng; use rand::OsRng; use speck::Key; #[bench] fn generate_key(mut bencher: &mut Bencher) { let mut rng = OsRng::new().unwrap(); let key_input = rng.gen(); bencher.iter(|| test::black_b...
(mut bencher: &mut Bencher) { let (key, block) = gen_test(); bencher.iter(|| test::black_box(key.encrypt_block(block))); } #[bench] fn decrypt(mut bencher: &mut Bencher) { let (key, block) = gen_test(); bencher.iter(|| test::black_box(key.decrypt_block(block))); } fn gen_test() -> (Key, u128) { ...
encrypt
identifier_name
lib.rs
#![feature(test, i128_type)] extern crate test; use test::Bencher; extern crate rand; extern crate speck; use rand::Rng; use rand::OsRng;
#[bench] fn generate_key(mut bencher: &mut Bencher) { let mut rng = OsRng::new().unwrap(); let key_input = rng.gen(); bencher.iter(|| test::black_box(Key::new(key_input))); } #[bench] fn encrypt(mut bencher: &mut Bencher) { let (key, block) = gen_test(); bencher.iter(|| test::black_box(key.encry...
use speck::Key;
random_line_split
evlogger.py
#! /usr/bin/python # -*- coding: utf-8 -*- # # This file is part of hopr: https://github.com/hopr/hopr. # # Hopr 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 o...
(object): def __init__(self, filename): self.filename = filename @property def temp_filename(self): return self.filename + '.tmp' def __enter__(self): self.file = open(self.temp_filename, 'wb') return self def __exit__(self, exc, exc_type, exc_tb): os.f...
SaveFile
identifier_name
evlogger.py
#! /usr/bin/python # -*- coding: utf-8 -*- # # This file is part of hopr: https://github.com/hopr/hopr. # # Hopr 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 o...
def save_ngrams(filename, ngrams): n_ngrams = len(ngrams) n_event = sum([n for _,n in list(ngrams.items())]) logging.info('Saving: {filename} n-grams: {n_ngrams} event_count: {n_event}'.format(**locals())) key_header = None with SaveFile(filename) as f: w = csv.writer(f.file) ...
if isinstance(x, tuple): return x else: return (x,)
identifier_body
evlogger.py
#! /usr/bin/python # -*- coding: utf-8 -*- # # This file is part of hopr: https://github.com/hopr/hopr. # # Hopr 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 o...
# save_ngrams(filename + '.events', log['press2']) load_log = load_pickle def save_log(filename, log): save_pickle(filename, log) save_csv(filename, log) def start(filename, save_interval): " Log statistics for all keyboard events " if os.path.exists(filename): log = load_log(filename) ...
dump(log, f.file, protocol=2) # def save_csv(filename, log): # save_ngrams(filename + '.bigrams', log['event'])
random_line_split
evlogger.py
#! /usr/bin/python # -*- coding: utf-8 -*- # # This file is part of hopr: https://github.com/hopr/hopr. # # Hopr 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 o...
logging.debug('Running {} with args {}'.format(cmd, pformat(kwargs))) f = globals()[cmd] f(**kwargs) def run_parse_args(args): from argparse import ArgumentParser p = ArgumentParser() p.add_argument('-v', '--verbose', action='store_true') sp = p.add_subparsers(dest='cmd'...
logging.getLogger().setLevel(level=logging.DEBUG)
conditional_block
parser.js
var REGEX = require('REGEX'), MAX_SINGLE_TAG_LENGTH = 30, create = require('DIV/create'); var parseString = function(parentTagName, htmlStr) { var parent = create(parentTagName); parent.innerHTML = htmlStr; return parent; }; var parseSingleTag = function(htmlStr) { if (htmlStr.length > MAX_SIN...
parent = null; return arr.reverse(); };
{ child = parent.children[idx]; parent.removeChild(child); arr[idx] = child; }
conditional_block
parser.js
var REGEX = require('REGEX'), MAX_SINGLE_TAG_LENGTH = 30, create = require('DIV/create'); var parseString = function(parentTagName, htmlStr) { var parent = create(parentTagName); parent.innerHTML = htmlStr; return parent; }; var parseSingleTag = function(htmlStr) { if (htmlStr.length > MAX_SIN...
var parentTagName = REGEX.getParentTagName(htmlStr), parent = parseString(parentTagName, htmlStr); var child, idx = parent.children.length, arr = Array(idx); while (idx--) { child = parent.children[idx]; parent.removeChild(child); arr[idx] = child; ...
}; module.exports = function(htmlStr) { var singleTag = parseSingleTag(htmlStr); if (singleTag) { return singleTag; }
random_line_split
ometiff_write.py
import javabridge import bioformats as bf import numpy as np from matplotlib import pyplot as plt, cm javabridge.start_vm(class_path=bf.JARS, run_headless=True) NT = 10 NC = 2 NZ = 4 NX = 217 NY = 94 output_path = 'outome.tif' frames = [] for t in range(NT): for z in range(NZ):
""" xml_metadata = bf.get_omexml_metadata(path=output_path) metadata = bf.OMEXML(xml_metadata) NXp = metadata.image().Pixels.SizeX NYp = metadata.image().Pixels.SizeY NZp = metadata.image().Pixels.SizeZ NCp = metadata.image().Pixels.SizeC NTp = metadata.image().Pixels.SizeT print(NXp, NYp, NZp, NCp, NTp) assert(...
for c in range(NC): frame = np.random.randn(NY, NX, 1, 1, 1).astype(np.uint16) frames.append(np.squeeze(frame)) print(frame.shape) bf.write_image(output_path, pixels=frame, pixel_type=bf.PT_UINT16, c=c, t=t, z=z, size_c=NC, size_t=NT, size_z=NZ)
conditional_block
ometiff_write.py
import javabridge import bioformats as bf import numpy as np from matplotlib import pyplot as plt, cm javabridge.start_vm(class_path=bf.JARS, run_headless=True) NT = 10 NC = 2 NZ = 4 NX = 217 NY = 94 output_path = 'outome.tif' frames = [] for t in range(NT): for z in range(NZ): for c in range(NC): ...
plt.show()
random_line_split
text_actions.ts
/* Copyright 2020 The TensorFlow Authors. 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 a...
'[Text] Runs To Tag Loaded', props<{runToTags: Map<string, string[]>}>() ); export const textTagGroupVisibilityChanged = createAction( '[Text] Tag Group Visibility Changed', props<{ tagGroup: TagGroup; visibleTextCards: Array<{ run: string; tag: string; }>; }>() ); export const textD...
export const textPluginLoaded = createAction('[Text] Text Plugin Loaded'); export const textRunToTagsLoaded = createAction(
random_line_split
test_20x4.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import sys from RPLCD_i2c import CharLCD from RPLCD_i2c import Alignment, CursorMode, ShiftMode from RPLCD_i2c import cursor, cleared try: input = raw_input
try: unichr = unichr except NameError: unichr = chr lcd = CharLCD(address=0x38, port=1, cols=20, rows=4, dotsize=8) input('Display should be blank. ') lcd.cursor_mode = CursorMode.blink input('The cursor should now blink. ') lcd.cursor_mode = CursorMode.line input('The cursor should now be a line. ') lcd...
except NameError: pass
random_line_split
reducer_post.py
#!/usr/bin/env python import sys import os os.environ['MPLCONFIGDIR'] = "/tmp/" import pandas as pd import numpy as np import commands import csv from sklearn import svm from sklearn.cross_validation import StratifiedKFold from sklearn import preprocessing from sklearn.externals import joblib current_key = None key...
for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # parse the input we got from mapper.py key, values = line.split('\t', 1) values = values[1:-1] values = values.split(",") day = qt_rmvd(values[0]) values = values[1:] #print line, key, day ,values...
string = string.strip() if string.startswith("'") and string.endswith("'"): string = string[1:-1] return string
identifier_body
reducer_post.py
#!/usr/bin/env python import sys import os os.environ['MPLCONFIGDIR'] = "/tmp/" import pandas as pd import numpy as np import commands import csv from sklearn import svm from sklearn.cross_validation import StratifiedKFold from sklearn import preprocessing from sklearn.externals import joblib current_key = None key...
( string ): string = string.strip() if string.startswith("'") and string.endswith("'"): string = string[1:-1] return string for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # parse the input we got from mapper.py key, values = line.split('\t', 1) ...
qt_rmvd
identifier_name
reducer_post.py
#!/usr/bin/env python import sys import os os.environ['MPLCONFIGDIR'] = "/tmp/" import pandas as pd import numpy as np import commands import csv from sklearn import svm from sklearn.cross_validation import StratifiedKFold from sklearn import preprocessing from sklearn.externals import joblib current_key = None key...
if len(dayList) > 0: dayList.sort(key= lambda x: int(x[0].split("_")[-1])) fname = "Event_DailyRecord_"+current_key.strip()+".csv" f = open(fname,"wt") w = csv.writer(f) w.writerow(("Day","Event")) for elem in dayList: w.writerow((elem[0],elem[1])) f.close() #print comm...
dayList.sort(key= lambda x: int(x[0].split("_")[-1])) fname = "Event_DailyRecord_"+current_key.strip()+".csv" f = open(fname,"wt") w = csv.writer(f) w.writerow(("Day","Event")) for elem in dayList: w.writerow((elem[0],elem[1])) f.close() #print command...
conditional_block
reducer_post.py
#!/usr/bin/env python import sys import os os.environ['MPLCONFIGDIR'] = "/tmp/" import pandas as pd import numpy as np import commands import csv from sklearn import svm from sklearn.cross_validation import StratifiedKFold from sklearn import preprocessing from sklearn.externals import joblib current_key = None key...
for elem in dayList: w.writerow((elem[0],elem[1])) f.close() #print commands.getoutput("ls") #print commands.getoutput("hadoop fs -rm /user/dropuser/schlumberger-result/"+fname) print commands.getoutput("hadoop fs -put "+fname+" /user/dropuser/schlumberger-result/") ...
w.writerow(("Day","Event"))
random_line_split
base.rs
// Copyright 2012-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-MI...
/// A syntax extension that is attached to an item and modifies it /// in-place. ItemModifier(ItemModifier), /// A normal, function-like syntax extension. /// /// `bytes!` is a `NormalTT`. NormalTT(~MacroExpander:'static, Option<Span>), /// A function-like syntax extension that has an...
/// A syntax extension that is attached to an item and creates new items /// based upon it. /// /// `#[deriving(...)]` is an `ItemDecorator`. ItemDecorator(ItemDecorator),
random_line_split
base.rs
// Copyright 2012-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-MI...
pub fn bt_push(&mut self, ei: codemap::ExpnInfo) { match ei { ExpnInfo {call_site: cs, callee: ref callee} => { self.backtrace = Some(@ExpnInfo { call_site: Span {lo: cs.lo, hi: cs.hi, expn_info...
{ let mut v = Vec::new(); v.push(token::str_to_ident(self.ecfg.crate_id.name)); v.extend(self.mod_path.iter().map(|a| *a)); return v; }
identifier_body
base.rs
// Copyright 2012-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-MI...
(&self) { } pub fn backtrace(&self) -> Option<@ExpnInfo> { self.backtrace } pub fn mod_push(&mut self, i: ast::Ident) { self.mod_path.push(i); } pub fn mod_pop(&mut self) { self.mod_path.pop().unwrap(); } pub fn mod_path(&self) -> Vec<ast::Ident> { let mut v = Vec::new(); v.push(token::s...
print_backtrace
identifier_name
ng_if.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { TemplateRef, ViewContainerRef } from '@angular/core'; /** * Conditionally includes a template based on the ...
$implicit: any; ngIf: any; }
*/ export declare class NgIfContext {
random_line_split
ng_if.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { TemplateRef, ViewContainerRef } from '@angular/core'; /** * Conditionally includes a template based on the ...
{ $implicit: any; ngIf: any; }
NgIfContext
identifier_name
SkinSelector.py
# -*- coding: utf-8 -*- from Screens.Screen import Screen from Screens.Standby import TryQuitMainloop from Screens.MessageBox import MessageBox from Components.ActionMap import NumberActionMap from Components.Pixmap import Pixmap from Components.Sources.StaticText import StaticText from Components.MenuList import MenuL...
if self.previewPath != pngpath: self.previewPath = pngpath self.picload.startDecode(self.previewPath) def restartGUI(self, answer): if answer is True: self.session.open(TryQuitMainloop, 3) class SkinSelector(Screen, SkinSelectorBase): SKINXML = "skin.xml" DEFAULTSKIN = "< Default >" PICONSKINXML = ...
pngpath = resolveFilename(SCOPE_ACTIVE_SKIN, "noprev.png")
conditional_block
SkinSelector.py
# -*- coding: utf-8 -*- from Screens.Screen import Screen from Screens.Standby import TryQuitMainloop from Screens.MessageBox import MessageBox from Components.ActionMap import NumberActionMap from Components.Pixmap import Pixmap from Components.Sources.StaticText import StaticText from Components.MenuList import MenuL...
class SkinSelector(Screen, SkinSelectorBase): SKINXML = "skin.xml" DEFAULTSKIN = "< Default >" PICONSKINXML = None PICONDEFAULTSKIN = None skinlist = [] root = os.path.join(eEnv.resolve("${datadir}"),"enigma2") def __init__(self, session, args = None): Screen.__init__(self, session) SkinSelectorBase.__in...
def __init__(self, session, args = None): self.skinlist = [] self.previewPath = "" if self.SKINXML and os.path.exists(os.path.join(self.root, self.SKINXML)): self.skinlist.append(self.DEFAULTSKIN) if self.PICONSKINXML and os.path.exists(os.path.join(self.root, self.PICONSKINXML)): self.skinlist.append(sel...
identifier_body
SkinSelector.py
# -*- coding: utf-8 -*- from Screens.Screen import Screen from Screens.Standby import TryQuitMainloop from Screens.MessageBox import MessageBox from Components.ActionMap import NumberActionMap from Components.Pixmap import Pixmap from Components.Sources.StaticText import StaticText from Components.MenuList import MenuL...
(self): self["SkinList"].pageUp() self.loadPreview() def right(self): self["SkinList"].pageDown() self.loadPreview() def info(self): aboutbox = self.session.open(MessageBox,_("Enigma2 skin selector"), MessageBox.TYPE_INFO) aboutbox.setTitle(_("About...")) def loadPreview(self): if self["SkinList"].g...
left
identifier_name
SkinSelector.py
# -*- coding: utf-8 -*- from Screens.Screen import Screen from Screens.Standby import TryQuitMainloop from Screens.MessageBox import MessageBox from Components.ActionMap import NumberActionMap from Components.Pixmap import Pixmap from Components.Sources.StaticText import StaticText from Components.MenuList import MenuL...
DEFAULTSKIN = "< Default >" PICONSKINXML = None PICONDEFAULTSKIN = None skinlist = [] root = os.path.join(eEnv.resolve("${datadir}"),"enigma2") def __init__(self, session, args = None): Screen.__init__(self, session) SkinSelectorBase.__init__(self, args) Screen.setTitle(self, _("Skin setup")) self.skinN...
self.session.open(TryQuitMainloop, 3) class SkinSelector(Screen, SkinSelectorBase): SKINXML = "skin.xml"
random_line_split
time.py
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # 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 appli...
(self, text): if self._line_started and "\n" not in text: return text timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3] if not self._line_started: self._line_started = True text = "%s > %s" % (timestamp, text) if text.endswith("\n"): ...
rx
identifier_name
time.py
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # 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 appli...
timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3] if not self._line_started: self._line_started = True text = "%s > %s" % (timestamp, text) if text.endswith("\n"): self._line_started = False return text[:-1].replace("\n", "\n%s > " % timesta...
return text
conditional_block
time.py
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # 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 appli...
def rx(self, text): if self._line_started and "\n" not in text: return text timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3] if not self._line_started: self._line_started = True text = "%s > %s" % (timestamp, text) if text.endswith("\n"): ...
super(Timestamp, self).__init__(*args, **kwargs) self._line_started = False
identifier_body
time.py
# Copyright (c) 2014-present PlatformIO <contact@platformio.org> # # 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 appli...
def rx(self, text): if self._line_started and "\n" not in text: return text timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3] if not self._line_started: self._line_started = True text = "%s > %s" % (timestamp, text) if text.endswith("\n"): ...
def __init__(self, *args, **kwargs): super(Timestamp, self).__init__(*args, **kwargs) self._line_started = False
random_line_split
opaque_node.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] use gfx::display_list::OpaqueNode; use libc::{c_void, uintptr_t}; use script::layout_inter...
/// of node that script expects to receive in a hit test. fn to_untrusted_node_address(&self) -> UntrustedNodeAddress; } impl OpaqueNodeMethods for OpaqueNode { fn from_script_node(node: TrustedNodeAddress) -> OpaqueNode { unsafe { OpaqueNodeMethods::from_jsmanaged(&LayoutJS::from_trust...
/// Converts this node to an `UntrustedNodeAddress`. An `UntrustedNodeAddress` is just the type
random_line_split
opaque_node.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] use gfx::display_list::OpaqueNode; use libc::{c_void, uintptr_t}; use script::layout_inter...
(node: TrustedNodeAddress) -> OpaqueNode { unsafe { OpaqueNodeMethods::from_jsmanaged(&LayoutJS::from_trusted_node_address(node)) } } fn from_jsmanaged(node: &LayoutJS<Node>) -> OpaqueNode { unsafe { let ptr: uintptr_t = node.get_jsobject() as uintptr_t; ...
from_script_node
identifier_name
opaque_node.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] use gfx::display_list::OpaqueNode; use libc::{c_void, uintptr_t}; use script::layout_inter...
}
{ UntrustedNodeAddress(self.0 as *const c_void) }
identifier_body
geniza-net.rs
// Free Software under GPL-3.0, see LICENSE // Copyright 2017 Bryan Newbold extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate geniza; extern crate sodiumoxide; // TODO: more careful import use geniza::*; use std::path::Path; use clap::{App, SubCommand, Arg}; use sodiumoxi...
quick_main!(run);
{ env_logger::init().unwrap(); let matches = App::new("geniza-net") .version(env!("CARGO_PKG_VERSION")) .subcommand( SubCommand::with_name("connect") .about("Connects to a peer and exchanges handshake") .arg_from_usage("<host_port> 'peer host:port to ...
identifier_body
geniza-net.rs
// Free Software under GPL-3.0, see LICENSE // Copyright 2017 Bryan Newbold extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate geniza; extern crate sodiumoxide; // TODO: more careful import use geniza::*; use std::path::Path; use clap::{App, SubCommand, Arg}; use sodiumoxi...
() -> Result<()> { env_logger::init().unwrap(); let matches = App::new("geniza-net") .version(env!("CARGO_PKG_VERSION")) .subcommand( SubCommand::with_name("connect") .about("Connects to a peer and exchanges handshake") .arg_from_usage("<host_port> 'p...
run
identifier_name
geniza-net.rs
// Free Software under GPL-3.0, see LICENSE // Copyright 2017 Bryan Newbold extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate geniza; extern crate sodiumoxide; // TODO: more careful import use geniza::*; use std::path::Path; use clap::{App, SubCommand, Arg}; use sodiumoxi...
.arg_from_usage("<dat_key> 'dat key (public key) to lookup"), ) .subcommand( SubCommand::with_name("naive-clone") .about("Pulls a drive from a single (known) peer, using a naive algorithm") .arg(Arg::with_name("dat-dir") .sh...
.subcommand( SubCommand::with_name("discover-dns") .about("Does a centralized DNS lookup for peers with the given key")
random_line_split
geniza-net.rs
// Free Software under GPL-3.0, see LICENSE // Copyright 2017 Bryan Newbold extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate geniza; extern crate sodiumoxide; // TODO: more careful import use geniza::*; use std::path::Path; use clap::{App, SubCommand, Arg}; use sodiumoxi...
("discover-dns", Some(subm)) => { let dat_key = subm.value_of("dat_key").unwrap(); let key_bytes = parse_dat_address(&dat_key)?; let peers = discover_peers_dns(&key_bytes)?; if peers.len() == 0 { println!("No peers found!"); } else { ...
{ let dat_key = subm.value_of("dat_key").unwrap(); let key_bytes = parse_dat_address(&dat_key)?; let disc_key = make_discovery_key(&key_bytes); for b in 0..20 { print!("{:02x}", disc_key[b]); } println!(".dat.local"); }
conditional_block
midiflip.py
#Ret Samys, creator of this program, can be found at RetSamys.deviantArt.com #Please feel free to change anything or to correct me or to make requests... I'm a really bad coder. =) #Watch Andrew Huang's video here: https://www.youtube.com/watch?v=4IAZY7JdSHU changecounter=0 path="for_elise_by_beethoven.mid" prin...
writeme=writeme+"MTrk"+"".join(i) #join list of characters to final string counter=1 path=path.replace(".mid","") while True: try: newfile = open(path+"_midiflip_"+str(counter)+".mid") newfile.close() counter+=1 except IOError as e: newfile = open(path+"_midiflip_"...
print "WARNING: There were notes out of range: "+str(lowcount)+" too low and "+str(highcount)+" too high."
conditional_block
midiflip.py
#Ret Samys, creator of this program, can be found at RetSamys.deviantArt.com #Please feel free to change anything or to correct me or to make requests... I'm a really bad coder. =) #Watch Andrew Huang's video here: https://www.youtube.com/watch?v=4IAZY7JdSHU changecounter=0 path="for_elise_by_beethoven.mid"
if pth!="":path=pth try: f=open(path,"rb") except: try: f=open(path+".mid","rb") except: print "Sorry, but are you sure this is where the file is?" cset=raw_input("As a standard setting, this program will flip all notes around C', which will flip the 'hands'. To use this mode press e...
print """Welcome to my horribly inefficient program to tonal invert MIDI files according to Andrew Huang's #MIDIFLIP challenge as seen on https://www.youtube.com/watch?v=4IAZY7JdSHU """ pth=raw_input("Please enter your MIDI file's path here (save the file in the same directory as this program if you want to avoid typ...
random_line_split