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
browser.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. 'use strict'; import { IContentsModel } from 'jupyter-js-services'; import { Message } from 'phosphor-messaging'; import { PanelLayout } from 'phosphor-panel'; import { Widget } from 'phosphor-widget'; im...
*/ delete(): Promise<void> { return this._listing.delete(); } /** * Duplicate the currently selected item(s). */ duplicate(): Promise<void> { return this._listing.duplicate(); } /** * Download the currently selected item(s). */ download(): Promise<void> { return this._listing....
random_line_split
browser.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. 'use strict'; import { IContentsModel } from 'jupyter-js-services'; import { Message } from 'phosphor-messaging'; import { PanelLayout } from 'phosphor-panel'; import { Widget } from 'phosphor-widget'; im...
else { this.model.open(item.name); } } } /** * Create a new untitled file or directory in the current directory. */ newUntitled(type: string, ext?: string): Promise<IContentsModel> { return this.model.newUntitled(type, ext); } /** * Rename the first currently selected item. ...
{ foundDir = true; this._model.open(item.name).catch(error => showErrorMessage(this, 'Open directory', error) ); }
conditional_block
browser.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. 'use strict'; import { IContentsModel } from 'jupyter-js-services'; import { Message } from 'phosphor-messaging'; import { PanelLayout } from 'phosphor-panel'; import { Widget } from 'phosphor-widget'; im...
/** * Duplicate the currently selected item(s). */ duplicate(): Promise<void> { return this._listing.duplicate(); } /** * Download the currently selected item(s). */ download(): Promise<void> { return this._listing.download(); } /** * Shut down kernels on the applicable currentl...
{ return this._listing.delete(); }
identifier_body
browser.ts
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. 'use strict'; import { IContentsModel } from 'jupyter-js-services'; import { Message } from 'phosphor-messaging'; import { PanelLayout } from 'phosphor-panel'; import { Widget } from 'phosphor-widget'; im...
(): Promise<void> { return this._listing.download(); } /** * Shut down kernels on the applicable currently selected items. */ shutdownKernels(): Promise<void> { return this._listing.shutdownKernels(); } /** * Refresh the current directory. */ refresh(): Promise<void> { return this....
download
identifier_name
vcq12.py
#! /usr/bin/env python ''' vcq12.py: 12TET quantizer for V/oct control voltages Copyright (c) 2020 Bill Gribble <grib@billgribble.com> ''' from ..processor import Processor from ..mfp_app import MFPApp from ..bang import Uninit from mfp import log class VCQ12(Processor): doc_tooltip_obj = "Quantize to 12TET se...
else: self.mapname = "semitone" self.map = self.maps.get(self.mapname) self.hot_inlets = [0, 1] self.dsp_inlets = [0] self.dsp_outlets = [0] mapvals = [val for pair in self.map for val in pair] self.dsp_init("vcq12~", map=mapvals) def trigger(se...
self.mapname = initargs[0]
conditional_block
vcq12.py
#! /usr/bin/env python ''' vcq12.py: 12TET quantizer for V/oct control voltages Copyright (c) 2020 Bill Gribble <grib@billgribble.com> ''' from ..processor import Processor from ..mfp_app import MFPApp from ..bang import Uninit from mfp import log class VCQ12(Processor): doc_tooltip_obj = "Quantize to 12TET se...
self.dsp_setparam("map", [val for pair in self.map for val in pair]) def register(): MFPApp().register("vcq12~", VCQ12)
self.mapname = self.inlets[1] self.map = self.maps.get(self.mapname, self.maps['semitone'])
random_line_split
vcq12.py
#! /usr/bin/env python ''' vcq12.py: 12TET quantizer for V/oct control voltages Copyright (c) 2020 Bill Gribble <grib@billgribble.com> ''' from ..processor import Processor from ..mfp_app import MFPApp from ..bang import Uninit from mfp import log class VCQ12(Processor): doc_tooltip_obj = "Quantize to 12TET se...
def trigger(self): if self.inlets[1] is not Uninit: self.mapname = self.inlets[1] self.map = self.maps.get(self.mapname, self.maps['semitone']) self.dsp_setparam("map", [val for pair in self.map for val in pair]) def register(): MFPApp().register("vcq12~", VCQ12)
Processor.__init__(self, 2, 1, init_type, init_args, patch, scope, name) initargs, kwargs = self.parse_args(init_args) if len(initargs): self.mapname = initargs[0] else: self.mapname = "semitone" self.map = self.maps.get(self.mapname) self.hot_inlets = [...
identifier_body
vcq12.py
#! /usr/bin/env python ''' vcq12.py: 12TET quantizer for V/oct control voltages Copyright (c) 2020 Bill Gribble <grib@billgribble.com> ''' from ..processor import Processor from ..mfp_app import MFPApp from ..bang import Uninit from mfp import log class
(Processor): doc_tooltip_obj = "Quantize to 12TET semitones" doc_tooltip_inlet = [ "Signal input", "Map of quantized tones" ] maps = { 'major': [ (0, 0), (1, 0), (2, 2), (3, 2), (4, 4), (5, 5), (6, 5), (7, 7), (8, 7), (9, 9), (10, 9), (11, 11), ...
VCQ12
identifier_name
__init__.py
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
import clv_medicament_template_wkf
random_line_split
health_test.py
import mox import time import unittest from zoom.agent.predicate.health import PredicateHealth from zoom.common.types import PlatformType class PredicateHealthTest(unittest.TestCase): def setUp(self): self.mox = mox.Mox() self.interval = 0.1 def
(self): self.mox.UnsetStubs() def test_start(self): pred = PredicateHealth("test", "echo", self.interval, PlatformType.LINUX) self.mox.StubOutWithMock(pred, "_run") pred._run().MultipleTimes() self.mox.ReplayAll() print "This test should complete quickly" ...
tearDown
identifier_name
health_test.py
import mox import time
from zoom.agent.predicate.health import PredicateHealth from zoom.common.types import PlatformType class PredicateHealthTest(unittest.TestCase): def setUp(self): self.mox = mox.Mox() self.interval = 0.1 def tearDown(self): self.mox.UnsetStubs() def test_start(self): pre...
import unittest
random_line_split
health_test.py
import mox import time import unittest from zoom.agent.predicate.health import PredicateHealth from zoom.common.types import PlatformType class PredicateHealthTest(unittest.TestCase): def setUp(self): self.mox = mox.Mox() self.interval = 0.1 def tearDown(self): self.mox.UnsetStubs() ...
pred = PredicateHealth("test", "echo", self.interval, PlatformType.LINUX) self.mox.StubOutWithMock(pred, "_run") pred._run().MultipleTimes() self.mox.ReplayAll() pred.start() time.sleep(0.25) # give other thread time to check pred.stop() pred.stop() pr...
identifier_body
mhc_names.py
05:01 02:01 13.16 02:01 02:02 11.08 03:02 02:02 0.08 03:01 04:02 0.03 03:02 04:02 0.11 04:01 04:02 2.26 01:01 05:01 10.85 01:02 05:01 0.03 01:03 05:01 0.03 01:04 05:01 0.71 01:02 05:02 1.20 01:03 05:02 0.05 01:04 05:03 2.03 01:02 05:04 0.08 01:03 06:01 0.66 01...
from collections import defaultdict # source: wikipedia article on HLA-DQ dq_allele_freq_table = """
random_line_split
mhc_names.py
from collections import defaultdict # source: wikipedia article on HLA-DQ dq_allele_freq_table = """ 05:01 02:01 13.16 02:01 02:02 11.08 03:02 02:02 0.08 03:01 04:02 0.03 03:02 04:02 0.11 04:01 04:02 2.26 01:01 05:01 10.85 01:02 05:01 0.03 01:03 05:01 0.03 01:04 05:01 0.71 01:02...
a, b, freq = line.split() a = a.replace(":", "") b = b.replace(":", "") freq = float(freq) dq_beta_to_alphas[b].append((a, freq)) dq_alpha_to_betas[a].append((b, freq)) dq_beta_to_alpha = { b: max(pairs, key=lambda x: x[1])[0] for (b, pairs) in dq_beta_to_alphas.items() } dq_alpha_to_...
continue
conditional_block
mhc_names.py
from collections import defaultdict # source: wikipedia article on HLA-DQ dq_allele_freq_table = """ 05:01 02:01 13.16 02:01 02:02 11.08 03:02 02:02 0.08 03:01 04:02 0.03 03:02 04:02 0.11 04:01 04:02 2.26 01:01 05:01 10.85 01:02 05:01 0.03 01:03 05:01 0.03 01:04 05:01 0.71 01:02...
# if DQ beta is given without its paired alpha assert len(name) == 12, (len(name), name) beta = name[8:12] if beta in dq_beta_to_alpha: name = "HLA-DQA1%s-DQB1%s" % ( dq_beta_to_alpha[beta], beta) elif name.startswith("HLA-DQA0"): # if DQA1 has bee...
if len(name) == 7 and name.startswith("DRB"): name = "DRB1" + name[3:] if not name.startswith("HLA"): name = "HLA-" + name name = name.replace("_", "") name = name.replace(":", "") name = name.replace("/", "-") name = name.replace("*", "") if name.startswith("HLA-DRB"): #...
identifier_body
mhc_names.py
from collections import defaultdict # source: wikipedia article on HLA-DQ dq_allele_freq_table = """ 05:01 02:01 13.16 02:01 02:02 11.08 03:02 02:02 0.08 03:01 04:02 0.03 03:02 04:02 0.11 04:01 04:02 2.26 01:01 05:01 10.85 01:02 05:01 0.03 01:03 05:01 0.03 01:04 05:01 0.71 01:02...
(name): if len(name) == 7 and name.startswith("DRB"): name = "DRB1" + name[3:] if not name.startswith("HLA"): name = "HLA-" + name name = name.replace("_", "") name = name.replace(":", "") name = name.replace("/", "-") name = name.replace("*", "") if name.startswith("HLA-DRB"...
normalize_mhc_name
identifier_name
test_nova.py
# Copyright 2013 IBM Corp. # # 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 #
# distributed under 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. from cinder.compute import nova from cinder import context fr...
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software
random_line_split
test_nova.py
# Copyright 2013 IBM Corp. # # 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 agree...
(object): def __getattr__(self, item): return None def __init__(self): self.volumes = self.Volumes() def create_volume_snapshot(self, *args, **kwargs): pass def delete_volume_snapshot(self, *args, **kwargs): pass class NovaApiTestCase(test.TestCase): def ...
Volumes
identifier_name
test_nova.py
# Copyright 2013 IBM Corp. # # 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 agree...
def delete_volume_snapshot(self, *args, **kwargs): pass class NovaApiTestCase(test.TestCase): def setUp(self): super(NovaApiTestCase, self).setUp() self.api = nova.API() self.novaclient = FakeNovaClient() self.ctx = context.get_admin_context() self.mox.StubOu...
pass
identifier_body
emr.py
import logging import time import boto3 import dns.resolver from retrying import retry logger = logging.getLogger(__name__) def get_cluster_id(): """Determine EMR cluster ID via DNS""" resolver = dns.resolver.Resolver() cluster_id = resolver.query('dataproc.rasterfoundry.com', 'TXT')[0] return clust...
(step_id, cluster_id): """Wait for batch success/failure given an initial EMR response Args: step_id (str): EMR step ID cluster_id (str): EMR cluster ID to check status of step in Returns: boolean """ emr = boto3.client('emr') get_description = lambda: emr.describe_step...
wait_for_emr_success
identifier_name
emr.py
import logging import time import boto3 import dns.resolver from retrying import retry logger = logging.getLogger(__name__) def get_cluster_id():
@retry(wait_exponential_multiplier=2000, wait_exponential_max=30000, stop_max_attempt_number=5) def wait_for_emr_success(step_id, cluster_id): """Wait for batch success/failure given an initial EMR response Args: step_id (str): EMR step ID cluster_id (str): EMR cluster ID to check status of ...
"""Determine EMR cluster ID via DNS""" resolver = dns.resolver.Resolver() cluster_id = resolver.query('dataproc.rasterfoundry.com', 'TXT')[0] return cluster_id.to_text().strip('"')
identifier_body
emr.py
import logging import time import boto3 import dns.resolver from retrying import retry logger = logging.getLogger(__name__) def get_cluster_id(): """Determine EMR cluster ID via DNS""" resolver = dns.resolver.Resolver() cluster_id = resolver.query('dataproc.rasterfoundry.com', 'TXT')[0] return clust...
get_description = lambda: emr.describe_step(ClusterId=cluster_id, StepId=step_id) logger.info('Starting to check for status updates for step %s', step_id) step_description = get_description() current_status = step_description['Step']['Status']['State'] logger.info('Initial status: %s', current_statu...
""" emr = boto3.client('emr')
random_line_split
emr.py
import logging import time import boto3 import dns.resolver from retrying import retry logger = logging.getLogger(__name__) def get_cluster_id(): """Determine EMR cluster ID via DNS""" resolver = dns.resolver.Resolver() cluster_id = resolver.query('dataproc.rasterfoundry.com', 'TXT')[0] return clust...
else: logger.error('Something went wrong with %s. Current Status: %s', step_id, current_status) raise Exception('Step {} failed'.format(step_id))
logger.info('Successfully completed step id: %s', step_id) return True
conditional_block
oneshot.rs
disconnect /// on behalf of the channel side of things (it can be mentally thought of as /// consuming the port). This upgrade is then also stored in the shared packet. /// The one caveat to consider is that when a port sees a disconnected channel /// it must check for data because there is no "data plus upgrade" stat...
// Not possible, these are one-use channels DATA => unreachable!(), // There is a thread waiting on the other end. We leave the 'DATA' // state inside so it'll pick it up on the other end. ptr => unsafe { SignalToken::cast_from_usize(ptr).sign...
{ // Sanity check match self.upgrade { NothingSent => {} _ => panic!("sending on a oneshot that's already sent on "), } assert!(self.data.is_none()); self.data = Some(t); self.upgrade = SendUsed; match self.state.swap(DATA, Ordering::SeqCs...
identifier_body
oneshot.rs
disconnect /// on behalf of the channel side of things (it can be mentally thought of as /// consuming the port). This upgrade is then also stored in the shared packet. /// The one caveat to consider is that when a port sees a disconnected channel /// it must check for data because there is no "data plus upgrade" stat...
SelCanceled, SelUpgraded(SignalToken, Receiver<T>), SelSuccess, } enum MyUpgrade<T> { NothingSent, SendUsed, GoUp(Receiver<T>), } impl<T> Packet<T> { pub fn new() -> Packet<T> { Packet { data: None, upgrade: NothingSent, state: AtomicUsize::new(E...
pub enum SelectionResult<T> {
random_line_split
oneshot.rs
contains the slot for the upgrade upgrade: MyUpgrade<T>, } pub enum Failure<T> { Empty, Disconnected, Upgraded(Receiver<T>), } pub enum UpgradeResult { UpSuccess, UpDisconnected, UpWoke(SignalToken), } pub enum SelectionResult<T> { SelCanceled, SelUpgraded(SignalToken, Receiver<T...
abort_selection
identifier_name
foundation.dropdown.js
/*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, document, undefined) { 'use strict'; Foundation.libs.dropdown = { name : 'dropdown', version : '4.3.2', settings : { activeClass: 'open', is_hover: false, opened: function(){}, closed: function(){} ...
}, resize : function () { var dropdown = $('[data-dropdown-content].open'), target = $("[data-dropdown='" + dropdown.attr('id') + "']"); if (dropdown.length && target.length) { this.css(dropdown, target); } }, css : function (dropdown, target) { var offset_p...
{ this.close.call(this, $('[data-dropdown-content]')) this.open.call(this, dropdown, target); }
conditional_block
foundation.dropdown.js
/*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, document, undefined) { 'use strict'; Foundation.libs.dropdown = { name : 'dropdown', version : '4.3.2', settings : { activeClass: 'open', is_hover: false, opened: function(){}, closed: function(){} ...
}; }(Foundation.zj, this, this.document));
$('[data-dropdown-content]').off('.fndtn.dropdown'); this.settings.init = false; }, reflow : function () {}
random_line_split
core.d.ts
/**
* * 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 */ /** * @module * @description * Entry point from which you should import all public core APIs. */ export * from './metadata'; export * from './version'; export * from './util';...
* @license * Copyright Google Inc. All Rights Reserved.
random_line_split
WindowType.py
# encoding: utf-8 # module gtk.gdk # from /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so # by generator 1.135 # no doc # imports from exceptions import Warning import gio as __gio import gobject as __gobject import gobject._gobject as __gobject__gobject import pango as __pango import pangocairo as __pangocairo ...
(self, *args, **kwargs): # real signature unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" __dict__ = None # (!) real value is '' __enum_values__ = { 0: 0, 1:...
__init__
identifier_name
WindowType.py
# encoding: utf-8 # module gtk.gdk # from /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so # by generator 1.135 # no doc # imports from exceptions import Warning import gio as __gio import gobject as __gobject import gobject._gobject as __gobject__gobject import pango as __pango import pangocairo as __pangocairo ...
def __init__(self, *args, **kwargs): # real signature unknown pass __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" __dict__ = None # (!) real value is '' __enum_values__ = { 0: 0...
identifier_body
WindowType.py
# encoding: utf-8 # module gtk.gdk # from /usr/lib/python2.7/dist-packages/gtk-2.0/gtk/_gtk.so # by generator 1.135 # no doc # imports from exceptions import Warning import gio as __gio import gobject as __gobject import gobject._gobject as __gobject__gobject import pango as __pango import pangocairo as __pangocairo ...
__weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """list of weak references to the object (if defined)""" __dict__ = None # (!) real value is '' __enum_values__ = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, ...
random_line_split
dialogs.py
): def __init__(self, parent=None, **kwargs): super(GtkBuilderDialog, self).__init__() ui_filename = os.path.join(datapath.get(), 'ui', self.glade_file) if not os.path.exists(ui_filename): raise ValueError("ui file does not exists: %s" % ui_fil...
def on_sources_selection_changed(self, widget, data=None): """Set sentivity of remove source button.""" (model, treeiter) = self.sources_selection.get_selected() self.remove_source_button.set_sensitive(treeiter is not None) class ClientLoginDialog(GtkBuilderDialog): glade_file = 'dia...
model.remove(treeiter)
conditional_block
dialogs.py
): def __init__(self, parent=None, **kwargs): super(GtkBuilderDialog, self).__init__() ui_filename = os.path.join(datapath.get(), 'ui', self.glade_file) if not os.path.exists(ui_filename): raise ValueError("ui file does not exists: %s" % ui_fil...
(Gtk.Dialog): """Dialog showing a download in progress.""" def __init__(self, url=None, dest=None, title=None, label=None, downloader=None): Gtk.Dialog.__init__(self, title or "Downloading file") self.set_size_request(485, 104) self.set_border_width(12) params = ...
DownloadDialog
identifier_name
dialogs.py
(self, widget, response): if response == Gtk.ResponseType.DELETE_EVENT: try: self.dialog.hide() except AttributeError: pass class AboutDialog(GtkBuilderDialog): glade_file = 'about-dialog.ui' dialog_object = "about_dialog" def initialize(sel...
MANUAL_CONF = 1 NEW_INSTALLER = 2 EXIT = 4 def __init__(self, parent=None): Gtk.MessageDialog.__init__(self, parent, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.NONE, "Unable to install the game") self.format_secondary_text...
identifier_body
dialogs.py
): def __init__(self, parent=None, **kwargs): super(GtkBuilderDialog, self).__init__()
raise ValueError("ui file does not exists: %s" % ui_filename) self.builder = Gtk.Builder() self.builder.add_from_file(ui_filename) self.dialog = self.builder.get_object(self.dialog_object) self.builder.connect_signals(self) if parent: self.dialog.set_tran...
ui_filename = os.path.join(datapath.get(), 'ui', self.glade_file) if not os.path.exists(ui_filename):
random_line_split
nvp_qos_queue.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Nicira Inc. # 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/lice...
(quantumv20.ListCommand): """List queues that belong to a given tenant.""" resource = 'qos_queue' log = logging.getLogger(__name__ + '.ListQoSQueue') _formatters = {} list_columns = ['id', 'name', 'min', 'max', 'qos_marking', 'dscp', 'default'] class ShowQoSQueue(quantumv20.Sh...
ListQoSQueue
identifier_name
nvp_qos_queue.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Nicira Inc. # 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/lice...
' if queue is not specified')), parser.add_argument( '--dscp', help='Differentiated Services Code Point'), def args2body(self, parsed_args): params = {'name': parsed_args.name, 'default': parsed_args.default} if parsed_args.min: ...
help=('If true all ports created with be the size of this queue'
random_line_split
nvp_qos_queue.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Nicira Inc. # 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/lice...
if parsed_args.dscp: params['dscp'] = parsed_args.dscp if parsed_args.tenant_id: params['tenant_id'] = parsed_args.tenant_id return {'qos_queue': params} class DeleteQoSQueue(quantumv20.DeleteCommand): """Delete a given queue.""" log = logging.getLogger(__name...
params['qos_marking'] = parsed_args.qos_marking
conditional_block
nvp_qos_queue.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Nicira Inc. # 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/lice...
def args2body(self, parsed_args): params = {'name': parsed_args.name, 'default': parsed_args.default} if parsed_args.min: params['min'] = parsed_args.min if parsed_args.max: params['max'] = parsed_args.max if parsed_args.qos_marking: ...
parser.add_argument( 'name', metavar='NAME', help='Name of queue') parser.add_argument( '--min', help='min-rate'), parser.add_argument( '--max', help='max-rate'), parser.add_argument( '--qos-marking', ...
identifier_body
google.py
"""~google <search term> will return three results from the google search for <search term>""" import re import requests from random import shuffle from googleapiclient.discovery import build import logging from secret_example import GOOGLE_CUSTOM_SEARCH_ENGINE, GOOGLE_SEARCH_API """fuction to fetch data from Googl...
def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"~google (.*)", text) if not match: return searchterm = match[0] return google_search(searchterm) on_bot_message = on_message
results = google(searchterm, GOOGLE_SEARCH_API, GOOGLE_CUSTOM_SEARCH_ENGINE, num=10) length = len(results) retval = "" if length < 3: for index in range(length): retval += results[index]['link'] + "\n" else: for index in range(3): retval += results[index]['link'] ...
identifier_body
google.py
"""~google <search term> will return three results from the google search for <search term>""" import re import requests from random import shuffle from googleapiclient.discovery import build import logging from secret_example import GOOGLE_CUSTOM_SEARCH_ENGINE, GOOGLE_SEARCH_API """fuction to fetch data from Googl...
def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"~google (.*)", text) if not match: return searchterm = match[0] return google_search(searchterm) on_bot_message = on_message
random_line_split
google.py
"""~google <search term> will return three results from the google search for <search term>""" import re import requests from random import shuffle from googleapiclient.discovery import build import logging from secret_example import GOOGLE_CUSTOM_SEARCH_ENGINE, GOOGLE_SEARCH_API """fuction to fetch data from Googl...
return retval def on_message(msg, server): text = msg.get("text", "") match = re.findall(r"~google (.*)", text) if not match: return searchterm = match[0] return google_search(searchterm) on_bot_message = on_message
retval += results[index]['link'] + "\n"
conditional_block
google.py
"""~google <search term> will return three results from the google search for <search term>""" import re import requests from random import shuffle from googleapiclient.discovery import build import logging from secret_example import GOOGLE_CUSTOM_SEARCH_ENGINE, GOOGLE_SEARCH_API """fuction to fetch data from Googl...
(msg, server): text = msg.get("text", "") match = re.findall(r"~google (.*)", text) if not match: return searchterm = match[0] return google_search(searchterm) on_bot_message = on_message
on_message
identifier_name
page.rs
use iron::prelude::*; use iron::middleware::Handler; use iron::status; use iron::headers::{ContentType}; use utils::Utils; use rustview::view::View; pub struct Index { utils: Utils, template: View, } impl Index { pub fn new(utils: Utils, admin_template: View) -> Index { Index { utils:...
"newTitle": "New Cool Title here :)", "helloUser": "Hi Andrei !", "testText": "It's working!!!!!", "user": "Andrei", "child_user": "Pages" }); let mut response = Response::with((status::Ok, self.template.render("home.html", model))); r...
let model = json!({ "title": "Testing",
random_line_split
page.rs
use iron::prelude::*; use iron::middleware::Handler; use iron::status; use iron::headers::{ContentType}; use utils::Utils; use rustview::view::View; pub struct Index { utils: Utils, template: View, } impl Index { pub fn new(utils: Utils, admin_template: View) -> Index
} impl Handler for Index { fn handle(&self, req: &mut Request) -> IronResult<Response> { let model = json!({ "title": "Testing", "newTitle": "New Cool Title here :)", "helloUser": "Hi Andrei !", "testText": "It's working!!!!!", "user": "Andrei", ...
{ Index { utils: utils, template: admin_template, } }
identifier_body
page.rs
use iron::prelude::*; use iron::middleware::Handler; use iron::status; use iron::headers::{ContentType}; use utils::Utils; use rustview::view::View; pub struct
{ utils: Utils, template: View, } impl Index { pub fn new(utils: Utils, admin_template: View) -> Index { Index { utils: utils, template: admin_template, } } } impl Handler for Index { fn handle(&self, req: &mut Request) -> IronResult<Response> { let...
Index
identifier_name
grafo-3.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Mar 27 01:20:46 2016 @author: caioau """ import matplotlib.pyplot as plt import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout def
(): G = nx.DiGraph() # G eh um grafo direcionado # gera o grafo apartir de suas arestas G.add_weighted_edges_from([(1,2,2.0),(1,3,1.0),(2,3,3.0),(2,4,3.0),(3,5,1.0),(4,6,2.0),(5,4,2.0),(5,6,5.0)]) for i in G.edges(): # print i[0], i[1] G[i[0]][i[1]]["color"] = "black" # G[1][2]["col...
main
identifier_name
grafo-3.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Mar 27 01:20:46 2016 @author: caioau """ import matplotlib.pyplot as plt import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout def main(): G = nx.DiGraph() # G eh um grafo direcionado # gera o grafo apartir de suas are...
if __name__ == "__main__": main()
edge_labels=dict([((u,v,),d['weight']) # gera os labels das arestas for u,v,d in G.edges(data=True)]) colors = [G[u][v]['color'] for u,v in G.edges()] pos = graphviz_layout(G,prog='neato') # obtem a posicao dos nos (para desenhalo) # TODO: desativar isso? nx.draw_networkx_edges(G,pos, ed...
identifier_body
grafo-3.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Mar 27 01:20:46 2016 @author: caioau """ import matplotlib.pyplot as plt import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout def main(): G = nx.DiGraph() # G eh um grafo direcionado # gera o grafo apartir de suas are...
nx.draw_networkx_edges(G,pos, edge_color=colors) # desenha as arestas nx.draw_networkx_labels(G,pos) # desenha os labels das arestas nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels) # desenha os labels dos nos nx.draw_networkx_nodes(G,pos,node_color='w') # desenha os nos plt.axis('off') #...
for u,v,d in G.edges(data=True)]) colors = [G[u][v]['color'] for u,v in G.edges()] pos = graphviz_layout(G,prog='neato') # obtem a posicao dos nos (para desenhalo) # TODO: desativar isso?
random_line_split
grafo-3.py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Mar 27 01:20:46 2016 @author: caioau """ import matplotlib.pyplot as plt import networkx as nx from networkx.drawing.nx_agraph import graphviz_layout def main(): G = nx.DiGraph() # G eh um grafo direcionado # gera o grafo apartir de suas are...
desenhaGrafo(G, "grafo-3.png") def desenhaGrafo(G,pngfilename): # desenha o grafo e salva numa imagem png edge_labels=dict([((u,v,),d['weight']) # gera os labels das arestas for u,v,d in G.edges(data=True)]) colors = [G[u][v]['color'] for u,v in G.edges()] pos = graphviz_layout(G,p...
G[maiorCaminho[i-1]][maiorCaminho[i]]["color"] = "red"
conditional_block
lib.rs
can be iterated over. //! for row in &rows { //! println!("{:?}", row); //! } //! } //! //! # } //! ``` extern crate postgres; extern crate rand; #[macro_use] #[cfg(test)] extern crate lazy_static; use std::{fmt, mem}; use std::iter::IntoIterator; use postgres::Connection; use postgres::types::ToSql...
/// Set the tag for cursor name. /// /// Adding a tag to the cursor name can be helpful for identifying where /// cursors originate when viewing `pg_stat_activity`. /// /// Default is `default`. /// /// # Examples /// /// Any type that implements `fmt::Display` may be provided ...
{ self.batch_size = batch_size; self }
identifier_body
lib.rs
can be iterated over. //! for row in &rows { //! println!("{:?}", row); //! } //! } //! //! # } //! ``` extern crate postgres; extern crate rand; #[macro_use] #[cfg(test)] extern crate lazy_static; use std::{fmt, mem}; use std::iter::IntoIterator; use postgres::Connection; use postgres::types::ToSql...
<'c, 'a, D>(builder: Builder<'c, 'a, D>) -> postgres::Result<Cursor<'c>> where D: fmt::Display + ?Sized { let mut bytes: [u8; 8] = unsafe { mem::uninitialized() }; thread_rng().fill_bytes(&mut bytes[..]); let cursor_name = format!("cursor:{}:{}", builder.tag, Hex(&bytes)); l...
new
identifier_name
lib.rs
can be iterated over. //! for row in &rows { //! println!("{:?}", row); //! } //! } //! //! # } //! ``` extern crate postgres; extern crate rand; #[macro_use] #[cfg(test)] extern crate lazy_static; use std::{fmt, mem}; use std::iter::IntoIterator; use postgres::Connection; use postgres::types::ToSql...
Ok(()) } } impl<'a> Drop for Cursor<'a> { fn drop(&mut self) { let _ = self.close(); } } /// Builds a Cursor /// /// This type is constructed by calling `Cursor::build`. pub struct Builder<'conn, 'builder, D: ?Sized + 'builder> { batch_size: u32, query: &'builder str, conn: &...
{ let close_query = format!("CLOSE \"{}\"", self.cursor_name); self.conn.execute(&close_query[..], &[])?; self.conn.execute("COMMIT", &[])?; self.closed = true; }
conditional_block
lib.rs
// can be iterated over. //! for row in &rows { //! println!("{:?}", row); //! } //! } //! //! # } //! ``` extern crate postgres; extern crate rand; #[macro_use] #[cfg(test)] extern crate lazy_static; use std::{fmt, mem}; use std::iter::IntoIterator; use postgres::Connection; use postgres::types::To...
/// Builds a Cursor /// /// This type is constructed by calling `Cursor::build`. pub struct Builder<'conn, 'builder, D: ?Sized + 'builder> { batch_size: u32, query: &'builder str, conn: &'conn Connection, tag: &'builder D, params: &'builder [&'builder ToSql], } impl<'conn, 'builder, D: fmt::Display...
}
random_line_split
CombatEvent.ts
/* * 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/. */ export {}; declare global {
fromName: string; fromFaction: any; toName: string; toFaction: any; damages?: { sent: number; received: number; part: BodyPart; type: DamageType; }[]; // damage against an abilities disruption health, high enough disruption damage causes and interrupt disruptio...
interface CombatEvent {
random_line_split
read.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use std::io; use std::pin::Pin; /// Future for the [`read`](super::AsyncReadExt::read) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Read<'a, R: ?Sized> { r...
impl<R: ?Sized + Unpin> Unpin for Read<'_, R> {} impl<'a, R: AsyncRead + ?Sized + Unpin> Read<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Read { reader, buf } } } impl<R: AsyncRead + ?Sized + Unpin> Future for Read<'_, R> { type Output = io::Result<usize>; fn po...
buf: &'a mut [u8], }
random_line_split
read.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use std::io; use std::pin::Pin; /// Future for the [`read`](super::AsyncReadExt::read) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct
<'a, R: ?Sized> { reader: &'a mut R, buf: &'a mut [u8], } impl<R: ?Sized + Unpin> Unpin for Read<'_, R> {} impl<'a, R: AsyncRead + ?Sized + Unpin> Read<'a, R> { pub(super) fn new(reader: &'a mut R, buf: &'a mut [u8]) -> Self { Read { reader, buf } } } impl<R: AsyncRead + ?Sized + Unpin> Futur...
Read
identifier_name
read.rs
use crate::io::AsyncRead; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use std::io; use std::pin::Pin; /// Future for the [`read`](super::AsyncReadExt::read) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Read<'a, R: ?Sized> { r...
} impl<R: AsyncRead + ?Sized + Unpin> Future for Read<'_, R> { type Output = io::Result<usize>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = &mut *self; Pin::new(&mut this.reader).poll_read(cx, this.buf) } }
{ Read { reader, buf } }
identifier_body
test_phenology.py
#!/usr/bin/env python2 import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from os.path import expanduser import scipy def treegrass_frac(ndvi, day_rs): """ Process based on Donohue et al. (2009) to separate out tree and grass cov...
(): climo_raw = import_one_year(clim_met_file).resample('D', how='mean') phen = treegrass_frac(climo_raw["Lai_1km_new_smooth"], 30) plt.plot(phen.tree*0.7, c='blue') plt.plot(phen.grass*1.3, c='red') plt.show() return None if __name__ == "__main__": clim_met_file = expanduser("~/Dropbo...
main
identifier_name
test_phenology.py
#!/usr/bin/env python2 import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from os.path import expanduser import scipy def treegrass_frac(ndvi, day_rs): """ Process based on Donohue et al. (2009) to separate out tree and grass cov...
tseries[0:im+half]])) elif im > tlen-half: # fold back into the beginning of the time-series twin[im] = _fun(np.hstack([tseries[im-half:tlen],\ tseries[0:half-(tlen-im)]])) else: twin[im] ...
""" Applies a function to a moving window of the time-series: ft_ = function([ f(t-N), f(t). f(t+N)]) """ # if the time-series is at a day-time step, update the window to a step-size of 16 days if is_days: p0 = period*day_rs else: p0 = period # find upper and lower bounds of...
identifier_body
test_phenology.py
#!/usr/bin/env python2 import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from os.path import expanduser import scipy def treegrass_frac(ndvi, day_rs): """ Process based on Donohue et al. (2009) to separate out tree and grass cov...
clim_raw.columns = time_label + list(clim_raw.columns[4:]) # datetime column clim_raw['DT'] = pd.date_range("2004-01-01", periods=len(clim_raw), freq="30min") # index on time clim_data = clim_raw.set_index('DT') # return to user return clim_data.ix[:, 4:] def main(): climo_raw = import...
clim_raw = pd.read_csv(clim_met_file) # fix column names
random_line_split
test_phenology.py
#!/usr/bin/env python2 import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from os.path import expanduser import scipy def treegrass_frac(ndvi, day_rs): """ Process based on Donohue et al. (2009) to separate out tree and grass cov...
else: p0 = period # find upper and lower bounds of the moving window half = p0//2 tlen = len(tseries) twin = [0]*tlen for im in range(tlen): # find the something for the window that satisfy the edge conditions if im < half: # fold back onto the end of the t...
p0 = period*day_rs
conditional_block
luksmeta-monitor-hack.py
#! /usr/bin/python3 # This simulates the org.freedesktop.UDisks.Encrypted.Slots property # et al for versions of UDisks that don't have them yet. import sys import json import subprocess import re import base64 import signal import atexit import os def b64_decode(data): # The data we get doesn't seem to have any...
in_luks2_token_section = True if in_luks2_slot_section: match = re.match(b" ([0-9]+): luks2$", line) else: match = re.match(b"Key Slot ([0-9]+): ENABLED$", line) if match: slot = int(match.group(1)) entry = { "Index": { "v": slot } } ...
slots = { } version = 1 max_slots = 8 try: result = subprocess.check_output([ "cryptsetup", "luksDump", dev ], stderr=subprocess.PIPE) except subprocess.CalledProcessError: return { "version": version, "slots": [ ], "max_slots": max_slots } in_luks2_slot_section = False in_luks...
identifier_body
luksmeta-monitor-hack.py
#! /usr/bin/python3 # This simulates the org.freedesktop.UDisks.Encrypted.Slots property # et al for versions of UDisks that don't have them yet. import sys import json import subprocess import re import base64 import signal import atexit import os def b64_decode(data): # The data we get doesn't seem to have any...
"-u", "cb6e8904-81ff-40da-a84a-07ab9ab5715e" ], stderr=subprocess.PIPE) entry["ClevisConfig"] = { "v": json.dumps(get_clevis_config_from_jwe(luksmeta.decode("utf-8"))) ...
try: luksmeta = subprocess.check_output([ "luksmeta", "load", "-d", dev, "-s", str(slot),
random_line_split
luksmeta-monitor-hack.py
#! /usr/bin/python3 # This simulates the org.freedesktop.UDisks.Encrypted.Slots property # et al for versions of UDisks that don't have them yet. import sys import json import subprocess import re import base64 import signal import atexit import os def b64_decode(data): # The data we get doesn't seem to have any...
(): if mon: mon.terminate() def sigexit(signo, stack): killmon() os._exit(0) atexit.register(killmon) signal.signal(signal.SIGTERM, sigexit) signal.signal(signal.SIGINT, sigexit) signal.signal(signal.SIGHUP, sigexit) path = subprocess.check_output([ "udevad...
killmon
identifier_name
luksmeta-monitor-hack.py
#! /usr/bin/python3 # This simulates the org.freedesktop.UDisks.Encrypted.Slots property # et al for versions of UDisks that don't have them yet. import sys import json import subprocess import re import base64 import signal import atexit import os def b64_decode(data): # The data we get doesn't seem to have any...
def get_clevis_config_from_jwe(jwe): return get_clevis_config_from_protected_header(jwe.split(".")[0]) def info(dev): slots = { } version = 1 max_slots = 8 try: result = subprocess.check_output([ "cryptsetup", "luksDump", dev ], stderr=subprocess.PIPE) except subprocess.CalledProcess...
return { "pin": pin, pin: { } }
conditional_block
RenderContext3D.ts
import { RenderElement } from "./RenderElement"; import { Scene3D } from "../scene/Scene3D" import { Matrix4x4 } from "../../math/Matrix4x4" import { Viewport } from "../../math/Viewport" import { ShaderInstance } from "../../shader/ShaderInstance" import { ShaderData } from "../../shader/ShaderData"; import { Camera }...
/** @internal */ viewport: Viewport; /** @internal */ scene: Scene3D; /** @internal */ camera: Camera; /** @internal */ cameraShaderValue: ShaderData; /** @internal */ renderElement: RenderElement; /** @internal */ shader: ShaderInstance; /** @internal */ invertY: boolean = false; /** @internal */ pipe...
projectionMatrix: Matrix4x4; /** @internal */ projectionViewMatrix: Matrix4x4;
random_line_split
RenderContext3D.ts
import { RenderElement } from "./RenderElement"; import { Scene3D } from "../scene/Scene3D" import { Matrix4x4 } from "../../math/Matrix4x4" import { Viewport } from "../../math/Viewport" import { ShaderInstance } from "../../shader/ShaderInstance" import { ShaderData } from "../../shader/ShaderData"; import { Camera }...
identifier_body
RenderContext3D.ts
import { RenderElement } from "./RenderElement"; import { Scene3D } from "../scene/Scene3D" import { Matrix4x4 } from "../../math/Matrix4x4" import { Viewport } from "../../math/Viewport" import { ShaderInstance } from "../../shader/ShaderInstance" import { ShaderData } from "../../shader/ShaderData"; import { Camera }...
identifier_name
__init__.py
_cache_key) current = None if data is None or self.sensor_type not in data else data[self.sensor_type] if current is None: self._sensor_cache.clear_data(self.__sensor_cache_key) else: self._device['last_update'] = int(starttime) self._device['value'] = current return current de...
if device.rssi > terrariumBluetoothSensor.__MIN_DB and device.getValueText(9) is not None and device.getValueText(9).lower() in ids: for sensor_type in sensorclass.TYPES: logger.debug(sensor_type, sensorclass, device.addr) yield terrariumSensor(None, ...
conditional_block
__init__.py
return sorted(list(set(sensor_types))) # Return polymorph sensor.... def
(cls, sensor_id, hardware_type, sensor_type, address, name = '', unit_value_callback = None, trigger_callback = None): known_sensors = terrariumSensor.available_hardware if hardware_type not in known_sensors: raise terrariumSensorUnknownHardwareException(f'Trying to load an unknown hardware device {hardw...
__new__
identifier_name
__init__.py
: raise terrariumSensorUnknownHardwareException(f'Trying to load an unknown hardware device {hardware_type} at address {address} with name {name}') if sensor_type not in known_sensors[hardware_type].TYPES: raise terrariumSensorInvalidSensorTypeException(f'Hardware does not have a {sensor_type} sensor a...
def _get_data(self): # This will return the measured voltage of the analog device. values = [] for counter in range(self.__AMOUNT_OF_MEASUREMENTS):
random_line_split
__init__.py
# Return polymorph sensor.... def __new__(cls, sensor_id, hardware_type, sensor_type, address, name = '', unit_value_callback = None, trigger_callback = None): known_sensors = terrariumSensor.available_hardware if hardware_type not in known_sensors: raise terrariumSensorUnknownHardwareException(f'T...
sensor_types = [] for sensor in __cls__.available_sensors: sensor_types += sensor['types'] return sorted(list(set(sensor_types)))
identifier_body
eventon_gen_maps.js
/* EventON Generate Google maps function */ (function($){ $.fn.evoGenmaps = function(opt){ var defaults = { delay: 0, fnt: 1, cal: '', mapSpotId: '', _action:'' }; var options = $.extend({}, defaults, opt); var geocoder; // popup lightbox generation i...
} // functions if(options.fnt==1){ this.each(function(){ var eventcard = $(this).attr('eventcard'); if(eventcard=='1'){ $(this).find('a.desc_trig').each(function(elm){ //$(this).siblings('.event_description').slideDown(); var obj = $(this); if...
{ var cal = this.closest('div.ajde_evcal_calendar '); loadl_gmaps_in(this, cal, idd+'_evop'); }
conditional_block
eventon_gen_maps.js
/* EventON Generate Google maps function */ (function($){ $.fn.evoGenmaps = function(opt){ var defaults = { delay: 0, fnt: 1, cal: '', mapSpotId: '', _action:'' }; var options = $.extend({}, defaults, opt); var geocoder; // popup lightbox generation i...
(obj, cal, mapId){ var evodata = cal.find('.evo-data'); var mapformat = evodata.data('mapformat'); var ev_location = obj.find('.evcal_desc'); var location_type = ev_location.attr('data-location_type'); if(location_type=='address'){ var address = ev_location.attr('data-location_address...
loadl_gmaps_in
identifier_name
eventon_gen_maps.js
/* EventON Generate Google maps function */ (function($){ $.fn.evoGenmaps = function(opt){ var defaults = { delay: 0, fnt: 1, cal: '', mapSpotId: '', _action:'' }; var options = $.extend({}, defaults, opt); var geocoder; // popup lightbox generation i...
// google maps styles // @since 2.2.22 var styles = ''; if(gmapstyles != 'default'){ styles = $.parseJSON(gmapstyles); } var zoom = evodata.data('mapzoom'); var zoomlevel = (typeof zoom !== 'undefined' && zoom !== false)? parseInt(zoom):12; var scroll = evodata.data('mapscro...
{ var evodata = cal.find('.evo-data'); var mapformat = evodata.data('mapformat'); var ev_location = obj.find('.evcal_desc'); var location_type = ev_location.attr('data-location_type'); if(location_type=='address'){ var address = ev_location.attr('data-location_address'); var loca...
identifier_body
eventon_gen_maps.js
/* EventON Generate Google maps function */ (function($){ $.fn.evoGenmaps = function(opt){ var defaults = {
}; var options = $.extend({}, defaults, opt); var geocoder; // popup lightbox generation if(options._action=='lightbox'){ var cur_window_top = parseInt($(window).scrollTop()) + 50; $('.evo_popin').css({'margin-top':cur_window_top}); $('.evo_pop_body').html(''); va...
delay: 0, fnt: 1, cal: '', mapSpotId: '', _action:''
random_line_split
test_largefile.py
2' class LargeFileTest: def setUp(self): if os.path.exists(TESTFN): mode = 'r+b' else: mode = 'w+b' with self.open(TESTFN, mode) as f: current_size = os.fstat(f.fileno())[stat.ST_SIZE] if current_size == size+1: return ...
(self): super().setUp() self.thread = None def tearDown(self): super().tearDown() if self.thread is not None: self.thread.join(self.timeout) self.thread = None def tcp_server(self, sock): def run(sock): with sock: conn...
setUp
identifier_name
test_largefile.py
2' class LargeFileTest: def setUp(self): if os.path.exists(TESTFN): mode = 'r+b' else:
with self.open(TESTFN, mode) as f: current_size = os.fstat(f.fileno())[stat.ST_SIZE] if current_size == size+1: return if current_size == 0: f.write(b'z') f.seek(0) f.seek(size) f.write(b'a') ...
mode = 'w+b'
conditional_block
test_largefile.py
2' class LargeFileTest: def setUp(self): if os.path.exists(TESTFN): mode = 'r+b' else: mode = 'w+b' with self.open(TESTFN, mode) as f: current_size = os.fstat(f.fileno())[stat.ST_SIZE] if current_size == size+1: return ...
def tcp_server(self, sock): def run(sock): with sock: conn, _ = sock.accept() conn.settimeout(self.timeout) with conn, open(TESTFN2, 'wb') as f: event.wait(self.timeout) while True: ...
super().tearDown() if self.thread is not None: self.thread.join(self.timeout) self.thread = None
identifier_body
test_largefile.py
def setUp(self): if os.path.exists(TESTFN): mode = 'r+b' else: mode = 'w+b' with self.open(TESTFN, mode) as f: current_size = os.fstat(f.fileno())[stat.ST_SIZE] if current_size == size+1: return if current_size == ...
TESTFN2 = TESTFN + '2' class LargeFileTest:
random_line_split
mod.rs
// This Source Code Form is subject to the terms of the GNU General Public // License, version 3. If a copy of the GPL was not distributed with this file, // You can obtain one at https://www.gnu.org/licenses/gpl.txt. pub(super) mod tostr; use crate::{path::ConcretePath, tree::Tree, value::Value}; use failure::Fallibl...
} impl fmt::Debug for Box<dyn NativeFunc + Send + Sync> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Unknown NativeFunc>") } }
{ self.box_clone() }
identifier_body
mod.rs
// This Source Code Form is subject to the terms of the GNU General Public // License, version 3. If a copy of the GPL was not distributed with this file, // You can obtain one at https://www.gnu.org/licenses/gpl.txt. pub(super) mod tostr; use crate::{path::ConcretePath, tree::Tree, value::Value}; use failure::Fallibl...
(&self) -> Box<dyn NativeFunc + Send + Sync> { self.box_clone() } } impl fmt::Debug for Box<dyn NativeFunc + Send + Sync> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Unknown NativeFunc>") } }
clone
identifier_name
mod.rs
// This Source Code Form is subject to the terms of the GNU General Public // License, version 3. If a copy of the GPL was not distributed with this file, // You can obtain one at https://www.gnu.org/licenses/gpl.txt. pub(super) mod tostr; use crate::{path::ConcretePath, tree::Tree, value::Value}; use failure::Fallibl...
} }
impl fmt::Debug for Box<dyn NativeFunc + Send + Sync> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<Unknown NativeFunc>")
random_line_split
app.js
/* Copyright 2012 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
blob) { if (!fs) { return; } fs.root.getDirectory(FOLDERNAME, {create: true}, function(dirEntry) { dirEntry.getFile(blob.name, {create: true, exclusive: false}, function(fileEntry) { // Créer un objet FileWriter pour notre FileEntry, et écrire le blob fileEntry.createWriter(function(fileWrite...
riteFile(
identifier_name
app.js
/* Copyright 2012 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
// 'http://gstatic.google.com/doc_icon_128.png' -> 'doc_icon_128.png' doc.iconFilename = doc.icon.substring(doc.icon.lastIndexOf('/') + 1); // Si le fichier existe, il retourne un FileEntry pour l'URL du système de fichier // Sinon, nous allons avoir un callback d'erreur qui nous permettra de ...
$scope.contacts = []; $scope.fetchContacts = function(resp) { var docs = []; var totalEntries = resp.items.length; resp.items.forEach(function(entry, i) { var doc = { title: entry.title, firstname: entry.firstname, lastname: entry.lastname, email: entry.email, ...
identifier_body
app.js
/* Copyright 2012 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
}); }); }); }; $scope.clearContacts = function() { $scope.contacts = []; // Vider les anciens résultats }; } ContactsController.$inject = ['$scope', '$http', 'gcontacts']; // Pour la minification du code source. //Initialisation et attachement des Listeners document.addEventListener('DOMCont...
$scope.contacts.sort(Util.sortByDate); }
conditional_block
app.js
/* Copyright 2012 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
if (totalEntries - 1 == i) { $scope.contacts.sort(Util.sortByDate); } }); }); }); }; $scope.clearContacts = function() { $scope.contacts = []; // Vider les anciens résultats }; } ContactsController.$inject = ['$scope', '$http', 'gcontacts']; // Pour la ...
doc.icon = window.URL.createObjectURL(blob); $scope.contacts.push(doc);
random_line_split
comm_adapters.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} #[cfg(test)] mod test { use prelude::v1::*; use sync::mpsc::channel; use super::*; use old_io; use thread::Thread; #[test] fn test_rx_reader() { let (tx, rx) = channel(); Thread::spawn(move|| { tx.send(vec![1u8, 2u8]).unwrap(); tx.send(vec![]).unwra...
{ self.tx.send(buf.to_vec()).map_err(|_| { old_io::IoError { kind: old_io::BrokenPipe, desc: "Pipe closed", detail: None } }) }
identifier_body
comm_adapters.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
if num_read == buf.len() || self.closed { break; } } if self.closed && num_read == 0 { Err(old_io::standard_error(old_io::EndOfFile)) } else { Ok(num_read) } } } /// Allows writing to a tx. /// /// # Example /// /// ```...
self.consume(count); num_read += count;
random_line_split
comm_adapters.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } if self.closed { Err(old_io::standard_error(old_io::EndOfFile)) } else { Ok(&self.buf[self.pos..]) } } fn consume(&mut self, amt: uint) { self.pos += amt; assert!(self.pos <= self.buf.len()); } } impl Reader for ChanR...
{ self.closed = true; self.buf = Vec::new(); }
conditional_block
comm_adapters.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self, buf: &mut [u8]) -> IoResult<uint> { let mut num_read = 0; loop { let count = match self.fill_buf().ok() { Some(src) => { let dst = &mut buf[num_read..]; let count = cmp::min(src.len(), dst.len()); bytes::...
read
identifier_name
annotate.py
# Portions Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # Copyright Mercurial Contributors # # This software may be used and distributed according to the terms of the # GNU General Public License v...
(parents, childfctx, child, skipchild, diffopts): r""" Given parent and child fctxes and annotate data for parents, for all lines in either parent that match the child, annotate the child with the parent's data. Additionally, if `skipchild` is True, replace all other lines with parent annotate ...
_annotatepair
identifier_name
annotate.py
# Portions Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # Copyright Mercurial Contributors # # This software may be used and distributed according to the terms of the # GNU General Public License v...
else: remaining[idx][1].append((a1, a2, b1, b2)) # Then, look at anything left, which might involve repeating the last # line. for parent, blocks in remaining: for a1, a2, b1, b2 in blocks: for bk in range(b1, b2): ...
if child[0][bk].fctx == childfctx: ak = min(a1 + (bk - b1), a2 - 1) child[0][bk] = attr.evolve(parent[0][ak], skip=True)
conditional_block
annotate.py
# Portions Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # Copyright Mercurial Contributors # # This software may be used and distributed according to the terms of the # GNU General Public License v...
for parent in parents ] if skipchild: # Need to iterate over the blocks twice -- make it a list pblocks = [(p, list(blocks)) for (p, blocks) in pblocks] # Mercurial currently prefers p2 over p1 for annotate. # TODO: change this? for parent, blocks in pblocks: for (a1...
See test-annotate.py for unit tests. """ pblocks = [ (parent, mdiff.allblocks(parent[1], child[1], opts=diffopts))
random_line_split
annotate.py
# Portions Copyright (c) Meta Platforms, Inc. and affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # Copyright Mercurial Contributors # # This software may be used and distributed according to the terms of the # GNU General Public License v...
for parent, blocks in pblocks: for (a1, a2, b1, b2), t in blocks: # Changed blocks ('!') or blocks made only of blank lines ('~') # belong to the child. if t == "=": child[0][b1:b2] = parent[0][a1:a2] if skipchild: # Now try and match up anyth...
r""" Given parent and child fctxes and annotate data for parents, for all lines in either parent that match the child, annotate the child with the parent's data. Additionally, if `skipchild` is True, replace all other lines with parent annotate data as well such that child is never blamed for any l...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class
(SchemaMigration): def forwards(self, orm): # Adding model 'Post' db.create_table(u'blog_post', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=60)), ('body', self.gf('dj...
Migration
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Post'
def backwards(self, orm): # Deleting model 'Post' db.delete_table(u'blog_post') models = { u'blog.post': { 'Meta': {'object_name': 'Post'}, 'body': ('django.db.models.fields.TextField', [], {}), 'created': ('django.db.models.fields.DateTimeField',...
db.create_table(u'blog_post', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=60)), ('body', self.gf('django.db.models.fields.TextField')()), ('tags', self.gf('django.db.models.fi...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Post' db.create_table(u'blog_post', ( (u'id', self.gf('django.db.models.fields.A...
} complete_apps = ['blog']
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'tags': ('django.db.models.fields.TextField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '60'}) }
random_line_split