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
mallinson.py
"""Calculate exact solutions for the zero dimensional LLG as given by [Mallinson2000] """ from __future__ import division from __future__ import absolute_import from math import sin, cos, tan, log, atan2, acos, pi, sqrt import scipy as sp import matplotlib.pyplot as plt import functools as ft import simpleode.core.u...
return a alpha = magnetic_parameters.alpha no_range_azi = (-1/alpha) * log(tan(p_now/2) / tan(p_start/2)) return azi_into_range(no_range_azi) def generate_dynamics(magnetic_parameters, start_angle=pi/18, end_angle=17*pi/18, steps...
a += 2*pi
conditional_block
ragGen.py
# Methods for generating Region Adjacency Graphs import networkx as nx import numpy as np # Generates the Region Adjacency Graph def generate_rag(im, linear): G=nx.Graph() if linear == True: (max_diff, min_diff) = get_diff_range(im) scale_factor = 1/(max_diff - min_diff) x = 0 for col...
diffs = [] x = 0 for col in image: y = 0 for pix in col: point = (x,y) neighs = get_neighbors(point, image) for neigh in neighs: if neigh != None: diffs.append(abs(image[point] - image[neigh])) y+=1 x+...
identifier_body
ragGen.py
# Methods for generating Region Adjacency Graphs import networkx as nx import numpy as np # Generates the Region Adjacency Graph def generate_rag(im, linear): G=nx.Graph() if linear == True: (max_diff, min_diff) = get_diff_range(im) scale_factor = 1/(max_diff - min_diff) x = 0 for col...
to_add = [] which = 0 for neigh in neighs: if neigh != None: to_add.append((point, neigh, weights[which])) which+=1 # print to_add G.add_weighted_edges_from(to_add) y+=1 x+=1 re...
weights = get_weights_nonlinear(im, point, neighs)
conditional_block
ragGen.py
# Methods for generating Region Adjacency Graphs import networkx as nx import numpy as np # Generates the Region Adjacency Graph def generate_rag(im, linear): G=nx.Graph() if linear == True: (max_diff, min_diff) = get_diff_range(im) scale_factor = 1/(max_diff - min_diff) x = 0 for col...
which+=1 # print to_add G.add_weighted_edges_from(to_add) y+=1 x+=1 return G # point = tuple containing index of point (position) # returns list of neighbors in [north, east, south, west] def get_neighbors(point, image): shape = np.shape(image) ...
to_add.append((point, neigh, weights[which]))
random_line_split
ragGen.py
# Methods for generating Region Adjacency Graphs import networkx as nx import numpy as np # Generates the Region Adjacency Graph def generate_rag(im, linear): G=nx.Graph() if linear == True: (max_diff, min_diff) = get_diff_range(im) scale_factor = 1/(max_diff - min_diff) x = 0 for col...
(G, im): nodes_to_add = [] for x in range(np.shape(im)[0]): for y in range(np.shape(im)[1]): nodes_to_add.append((x,y)) G.add_nodes_from(nodes_to_add) # returns the max and min difference in node weight # to be used for scaling edges in graph def get_diff_range(image): diffs = [] ...
populate_graph
identifier_name
memory.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 https://mozilla.org/MPL/2.0/. */ use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::StreamId; use serde_json::{Map, Value}; ...
}
{ //TODO: TimelineMemoryReply { jsObjectSize: 1, jsStringSize: 1, jsOtherSize: 1, domSize: 1, styleSize: 1, otherSize: 1, totalSize: 1, jsMilliseconds: 1.1, nonJSMilliseconds: 1.1, } }
identifier_body
memory.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 https://mozilla.org/MPL/2.0/. */ use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::StreamId; use serde_json::{Map, Value}; ...
} pub fn measure(&self) -> TimelineMemoryReply { //TODO: TimelineMemoryReply { jsObjectSize: 1, jsStringSize: 1, jsOtherSize: 1, domSize: 1, styleSize: 1, otherSize: 1, totalSize: 1, jsMilliseconds: ...
registry.register_later(Box::new(actor)); actor_name
random_line_split
memory.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 https://mozilla.org/MPL/2.0/. */ use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; use crate::StreamId; use serde_json::{Map, Value}; ...
(registry: &ActorRegistry) -> String { let actor_name = registry.new_name("memory"); let actor = MemoryActor { name: actor_name.clone(), }; registry.register_later(Box::new(actor)); actor_name } pub fn measure(&self) -> TimelineMemoryReply { //TODO: ...
create
identifier_name
getPreviousElement.js
/*jslint browser: true, devel: true, node: true, ass: true, nomen: true, unparam: true, indent: 4 */ /** * @license * Copyright (c) 2015 The ExpandJS authors. All rights reserved. * This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt * The complete set of authors ...
* </script> * ``` * * @function getPreviousElement * @param {Element} element The reference element * @returns {Element | undefined} Returns the previous element or undefined */ module.exports = function getPreviousElement(element) { assertArgument(isElement(element),...
* * XP.getPreviousElement(elem); * // => <li class="one"></li>
random_line_split
vaccaleibundgut.py
import sys import os import glob import inspect import pylab as pl from numpy import * from scipy import optimize import pickle import time import copy cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]) + "/templates") if cmd_folder not in sys.path: sys.path.in...
else: pl.plot(x[10:], mycavvaccaleib(x[10:], p0, secondg=False), 'k') pf = scipy.optimize.minimize(minfunc, p0, args=(y[10:], x[10:], e[10:], 0), method='Powell') # ,options={'maxiter':5}) #pl.figure(4) pl.figure(0) ax.errorbar(mjd+0.5-53000, y, yerr=e, fmt=None, ms=7, ...
p0[0] += 1.5 p0[1] *= 2 pl.plot(x[10:], mycavvaccaleib(x[10:], p0, secondg=True), 'm') pf = scipy.optimize.minimize(minfunc, p0, args=(y[10:], x[10:], e[10:], 1), method='Powell') # ,options={'maxiter':5})
conditional_block
vaccaleibundgut.py
import sys import os import glob import inspect import pylab as pl from numpy import * from scipy import optimize import pickle import time import copy cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]) + "/templates") if cmd_folder not in sys.path: sys.path.in...
(p, y, x, e, secondg, plot=False): ''' p is the parameter list if secondg=1: secondgaussian added if secondg=0: secondgaussian not parameters are: p[0]=first gaussian normalization (negative if fitting mag) p[1]=first gaussian mean p[2]=first gaussian sigma p[3]=linear decay off...
minfunc
identifier_name
vaccaleibundgut.py
import sys import os import glob import inspect import pylab as pl from numpy import * from scipy import optimize import pickle import time import copy cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]) + "/templates") if cmd_folder not in sys.path: sys.path.in...
ax2 = ax.twiny() Vmax = 2449095.23-2453000 ax2.tick_params('both', length=10, width=1, which='major') ax2.tick_params('both', length=5, width=1, which='minor') ax2.set_xlabel("phase (days)") ax2.set_xlim((ax.get_xlim()[0] - Vmax, ax.get_xlim()[1] - Vmax)) # pl.ylim(10,21) pl.draw() ...
ax.set_ylim(max(y + 0.1), min(y - 0.1))
random_line_split
vaccaleibundgut.py
import sys import os import glob import inspect import pylab as pl from numpy import * from scipy import optimize import pickle import time import copy cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]) + "/templates") if cmd_folder not in sys.path: sys.path.in...
import scipy.optimize if __name__ == '__main__': lcv = np.loadtxt(sys.argv[1], unpack=True) secondg = False try: if int(sys.argv[2]) > 0: secondg = True except: pass x = lcv[1] y = lcv[2] e = lcv[3] mjd = lcv[0] ax = pl.figure(0, figsize=(10,5)).add_sub...
''' p is the parameter list if secondg=1: secondgaussian added if secondg=0: secondgaussian not parameters are: p[0]=first gaussian normalization (negative if fitting mag) p[1]=first gaussian mean p[2]=first gaussian sigma p[3]=linear decay offset p[4]=linear decay slope p[5...
identifier_body
mod.rs
/* Copyright 2018 Mozilla Foundation * * 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...
pub use self::name_section::FunctionName; pub use self::name_section::LocalName; pub use self::name_section::ModuleName; pub use self::name_section::Name; pub use self::name_section::NameSectionReader; pub use self::name_section::NamingReader; pub use self::producers_section::ProducersField; pub use self::producers_s...
random_line_split
test_with_fixture.py
"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): ...
"""`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context...
def test_external():
random_line_split
test_with_fixture.py
"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): ...
(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case...
teardown
identifier_name
test_with_fixture.py
"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): ...
return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0
if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1
conditional_block
test_with_fixture.py
"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists():
def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @wi...
"""`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType)
identifier_body
link.js
import React, { Component, PropTypes } from 'react'; import he from 'he'; import { format } from 'd3-format'; const formatNumber = format('.2s'); export default class Link extends Component {
() { const { onClick } = this.props; const { title, score, link, is_answered, answer_count, view_count } = this.props.link; const answered = is_answered ? 'is-success' : ''; const views = `${formatNumber(view_count)} views`; return ( <div className='box pointer' tabIndex='0' onClick={onClick}...
render
identifier_name
link.js
import React, { Component, PropTypes } from 'react'; import he from 'he'; import { format } from 'd3-format'; const formatNumber = format('.2s'); export default class Link extends Component { render() { const { onClick } = this.props; const { title, score, link, is_answered, answer_count, view_count } = this...
onClick: PropTypes.func.isRequired, };
link: PropTypes.object.isRequired,
random_line_split
link.js
import React, { Component, PropTypes } from 'react'; import he from 'he'; import { format } from 'd3-format'; const formatNumber = format('.2s'); export default class Link extends Component { render() { const { onClick } = this.props; const { title, score, link, is_answered, answer_count, view_count } = this...
Link.propTypes = { link: PropTypes.object.isRequired, onClick: PropTypes.func.isRequired, };
{ return he.decode(title).replace(' - Stack Overflow', ''); }
identifier_body
domimplementationregistry13.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANT...
} function runTest() { domimplementationregistry13(); }
domImpl = domImplList.item(indexN10067); hasFeature = domImpl.hasFeature("Core",nullVersion); assertTrue("hasCore",hasFeature); }
conditional_block
domimplementationregistry13.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANT...
** * DOMImplementationRegistry.getDOMImplementationList("cOrE") should return a list of at least one DOMImplementation where hasFeature("Core", null) returns true. * @author Curt Arnold * @see http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/java-binding * @see http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-2...
if (++docsLoaded == 0) { setUpPageStatus = 'complete'; } } /
identifier_body
domimplementationregistry13.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANT...
var success; if(checkInitialization(builder, "domimplementationregistry13") != null) return; var domImplRegistry; var hasFeature; var domImpl; var domImplList; var length; var nullVersion = null; domImplRegistry = DOMImplementationRegistry; assertNotNull("domImp...
mplementationregistry13() {
identifier_name
domimplementationregistry13.js
/* Copyright © 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, European Research Consortium for Informatics and Mathematics, Keio University). All Rights Reserved. This work is distributed under the W3C® Software License [1] in the hope that it will be useful, but WITHOUT ANY WARRANTY...
DOMImplementationRegistry.getDOMImplementationList("cOrE") should return a list of at least one DOMImplementation where hasFeature("Core", null) returns true. * @author Curt Arnold * @see http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/java-binding * @see http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-2004040...
random_line_split
entity.js
/* Copyright 2015 Dietrich Epp. This file is part of Dash and the Jetpack Space Pirates. The Dash and the Jetpack Space Pirates source code is distributed under the terms of the MIT license. See LICENSE.txt for details. */ 'use strict'; var glm = require('gl-matrix'); var vec2 = glm.vec2; var color = requ...
(type) { return Types[type]; } module.exports = { destroy: destroy, registerTypes: registerTypes, getType: getType, };
getType
identifier_name
entity.js
/* Copyright 2015 Dietrich Epp. This file is part of Dash and the Jetpack Space Pirates. The Dash and the Jetpack Space Pirates source code is distributed under the terms of the MIT license. See LICENSE.txt for details. */ 'use strict'; var glm = require('gl-matrix'); var vec2 = glm.vec2; var color = requ...
_.forOwn(types, function(value, key) { var inh = value.inherit, i; if (inh) { for (i = 0; i < inh.length; i++) { _.defaults(value, inh[i]); } delete value.inherit; } var tname = prefix + key; if (Types.hasOwnProperty(tname)) { console.error('Duplicate type registered: ' + tname); return; ...
*/ function registerTypes(types, category) { var prefix = category ? category + '.' : '';
random_line_split
entity.js
/* Copyright 2015 Dietrich Epp. This file is part of Dash and the Jetpack Space Pirates. The Dash and the Jetpack Space Pirates source code is distributed under the terms of the MIT license. See LICENSE.txt for details. */ 'use strict'; var glm = require('gl-matrix'); var vec2 = glm.vec2; var color = requ...
} var Types = {}; /* * Register entity types. * * category: The category name, or null. * types: Mapping from type names to types */ function registerTypes(types, category) { var prefix = category ? category + '.' : ''; _.forOwn(types, function(value, key) { var inh = value.inherit, i; if (inh) { for (...
{ body.world.removeBody(body); }
conditional_block
entity.js
/* Copyright 2015 Dietrich Epp. This file is part of Dash and the Jetpack Space Pirates. The Dash and the Jetpack Space Pirates source code is distributed under the terms of the MIT license. See LICENSE.txt for details. */ 'use strict'; var glm = require('gl-matrix'); var vec2 = glm.vec2; var color = requ...
module.exports = { destroy: destroy, registerTypes: registerTypes, getType: getType, };
{ return Types[type]; }
identifier_body
LDBDClient.py
""" The LDBDClient module provides an API for connecting to and making requests of a LDBDServer. This module requires U{pyGlobus<http://www-itg.lbl.gov/gtg/projects/pyGlobus/>}. This file is part of the Grid LSC User Environment (GLUE) GLUE is free software: you can redistribute it and/or modify it under the terms ...
return reply def insertmap(self,xmltext,lfnpfn_dict): """ Insert the LIGO_LW metadata in the xmltext string into the database. @return: message received (may be empty) from LDBD Server as a string """ pmsg = cPickle.dumps(lfnpfn_dict) msg = "INSERTMAP\0" + xmltext + "\0" + pmsg + "\0...
msg = "Error executing insert on server %d:%s" % (ret, reply) raise LDBDClientException, msg
conditional_block
LDBDClient.py
""" The LDBDClient module provides an API for connecting to and making requests of a LDBDServer. This module requires U{pyGlobus<http://www-itg.lbl.gov/gtg/projects/pyGlobus/>}. This file is part of the Grid LSC User Environment (GLUE) GLUE is free software: you can redistribute it and/or modify it under the terms ...
def __disconnect__(self): """ Disconnect from the LDBD Server. @return: None """ try: self.socket.shutdown(2) except: pass def __response__(self): """ Read the response sent back by the LDBD Server. Parse out the return code with 0 for success and non-zero for err...
sys.stderr = sys.__stderr__ f.close()
random_line_split
LDBDClient.py
""" The LDBDClient module provides an API for connecting to and making requests of a LDBDServer. This module requires U{pyGlobus<http://www-itg.lbl.gov/gtg/projects/pyGlobus/>}. This file is part of the Grid LSC User Environment (GLUE) GLUE is free software: you can redistribute it and/or modify it under the terms ...
def start_element(self, name, attrs): """ Callback for start of an XML element. Checks to see if we are about to start a table that matches the ignore pattern. @param name: the name of the tag being opened @type name: string @param attrs: a dictionary of the attributes for the tag being op...
""" Destroys an instance by shutting down and deleting the parser. """ self.__p("",1) del self.__p
identifier_body
LDBDClient.py
""" The LDBDClient module provides an API for connecting to and making requests of a LDBDServer. This module requires U{pyGlobus<http://www-itg.lbl.gov/gtg/projects/pyGlobus/>}. This file is part of the Grid LSC User Environment (GLUE) GLUE is free software: you can redistribute it and/or modify it under the terms ...
(self): """ Destroys an instance by shutting down and deleting the parser. """ self.__p("",1) del self.__p def start_element(self, name, attrs): """ Callback for start of an XML element. Checks to see if we are about to start a table that matches the ignore pattern. @param name: ...
__del__
identifier_name
from_raw_arc.rs
//! A "Manual Arc" which allows manually frobbing the reference count //! //! This module contains a copy of the `Arc` found in the standard library, //! stripped down to the bare bones of what we actually need. The reason this is //! done is for the ability to concretely know the memory layout of the `Inner` //! struc...
<T> { data: T, cnt: AtomicUsize, } impl<T> FromRawArc<T> { pub fn new(data: T) -> FromRawArc<T> { let x = Box::new(Inner { data: data, cnt: AtomicUsize::new(1), }); FromRawArc { _inner: unsafe { mem::transmute(x) }, } } pub unsafe...
Inner
identifier_name
from_raw_arc.rs
//! A "Manual Arc" which allows manually frobbing the reference count //! //! This module contains a copy of the `Arc` found in the standard library, //! stripped down to the bare bones of what we actually need. The reason this is //! done is for the ability to concretely know the memory layout of the `Inner` //! struc...
FromRawArc { _inner: unsafe { mem::transmute(x) }, } } pub unsafe fn from_raw(ptr: *mut T) -> FromRawArc<T> { // Note that if we could use `mem::transmute` here to get a libstd Arc // (guaranteed) then we could just use std::sync::Arc, but this is the // cruc...
let x = Box::new(Inner { data: data, cnt: AtomicUsize::new(1), });
random_line_split
from_raw_arc.rs
//! A "Manual Arc" which allows manually frobbing the reference count //! //! This module contains a copy of the `Arc` found in the standard library, //! stripped down to the bare bones of what we actually need. The reason this is //! done is for the ability to concretely know the memory layout of the `Inner` //! struc...
atomic::fence(Ordering::Acquire); drop(mem::transmute::<_, Box<T>>(self._inner)); } } } #[cfg(test)] mod tests { use super::FromRawArc; #[test] fn smoke() { let a = FromRawArc::new(1); assert_eq!(*a, 1); assert_eq!(*a.clone(), 1); } #[t...
{ return; }
conditional_block
InstancedInterleavedBuffer.ts
/// Copyright (C) 2016 [MonkeyBrush.js] /// /// Permission is hereby granted, free of charge, to any person obtaining a copy of this /// software and associated documentation files (the "Software"), to deal in the Software /// without restriction, including without limitation the rights to use, copy, modify, /// merge,...
; }; };
{ return this._meshPerAttr; }
identifier_body
InstancedInterleavedBuffer.ts
/// Copyright (C) 2016 [MonkeyBrush.js] /// /// Permission is hereby granted, free of charge, to any person obtaining a copy of this /// software and associated documentation files (the "Software"), to deal in the Software /// without restriction, including without limitation the rights to use, copy, modify, /// merge,...
extends BufferAttribute { protected _meshPerAttr: number; constructor(arr: ArrayLike<number>, stride: number, meshPerAttr: number = 1) { super(arr, stride); this._meshPerAttr = meshPerAttr; } get meshPerAttr(): number { return this._meshPerAttr; }; }; };
InstancedInterleavedBuffer
identifier_name
InstancedInterleavedBuffer.ts
/// Copyright (C) 2016 [MonkeyBrush.js] /// /// Permission is hereby granted, free of charge, to any person obtaining a copy of this /// software and associated documentation files (the "Software"), to deal in the Software /// without restriction, including without limitation the rights to use, copy, modify, /// merge,...
}; };
random_line_split
_posixserialport.py
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ Serial Port Protocol """ # system imports import os, errno # dependent on pyserial ( http://pyserial.sf.net/ ) # only tested w/ 1.18 (5 Dec 2002) import serial from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD from serial im...
abstract.FileDescriptor.connectionLost(self, reason) self._serial.close()
identifier_body
_posixserialport.py
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ Serial Port Protocol """
# system imports import os, errno # dependent on pyserial ( http://pyserial.sf.net/ ) # only tested w/ 1.18 (5 Dec 2002) import serial from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD from serial import STOPBITS_ONE, STOPBITS_TWO from serial import FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS from serialport impor...
random_line_split
_posixserialport.py
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ Serial Port Protocol """ # system imports import os, errno # dependent on pyserial ( http://pyserial.sf.net/ ) # only tested w/ 1.18 (5 Dec 2002) import serial from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD from serial im...
raise def doRead(self): """Some data's readable from serial device. """ return fdesc.readFromFD(self.fileno(), self.protocol.dataReceived) def connectionLost(self, reason): abstract.FileDescriptor.connectionLost(self, reason) self._serial.close()
return 0
conditional_block
_posixserialport.py
# Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ Serial Port Protocol """ # system imports import os, errno # dependent on pyserial ( http://pyserial.sf.net/ ) # only tested w/ 1.18 (5 Dec 2002) import serial from serial import PARITY_NONE, PARITY_EVEN, PARITY_ODD from serial im...
(BaseSerialPort, abstract.FileDescriptor): """A select()able serial device, acting as a transport.""" connected = 1 def __init__(self, protocol, deviceNameOrPortNumber, reactor, baudrate = 9600, bytesize = EIGHTBITS, parity = PARITY_NONE, stopbits = STOPBITS_ONE, timeout = 0, xonxoff = 0, ...
SerialPort
identifier_name
test-011-child-table.py
#!/usr/bin/env python # # Copyright (c) 2018, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
all_nodes = [router] + children # ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() # -------------------------------------------------------------------------------------------------------------------...
children.append(wpan.Node())
conditional_block
test-011-child-table.py
#!/usr/bin/env python # # Copyright (c) 2018, The OpenThread Authors. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # ...
all_nodes = [router] + children # ----------------------------------------------------------------------------------------------------------------------- # Init all nodes wpan.Node.init_all_nodes() # --------------------------------------------------------------------------------------------------------------------...
children = [] for i in range(NUM_CHILDREN): children.append(wpan.Node())
random_line_split
Searcher.js
import { EventEmitter } from 'events'; import Constants from './Constants'; // searchers import YoutubeSearcher from 'kaku-core/modules/searcher/YoutubeSearcher'; import VimeoSearcher from 'kaku-core/modules/searcher/VimeoSearcher'; import SoundCloudSearcher from 'kaku-core/modules/searcher/SoundCloudSearcher'; import...
return results; }); } } changeSearcher(searcherName) { let searcher = this._searchers[searcherName]; if (searcher) { this._selectedSearcherName = searcherName; this.emit('searcher-changed', searcherName); } } } module.exports = new Searcher();
{ this._searchResults = results; this.emit('search-results-updated', results); }
conditional_block
Searcher.js
import { EventEmitter } from 'events'; import Constants from './Constants'; // searchers import YoutubeSearcher from 'kaku-core/modules/searcher/YoutubeSearcher'; import VimeoSearcher from 'kaku-core/modules/searcher/VimeoSearcher'; import SoundCloudSearcher from 'kaku-core/modules/searcher/SoundCloudSearcher'; import...
get selectedSearcher() { return this._searchers[this._selectedSearcherName]; } get searchResults() { return this._searchResults; } getSupportedSearchers() { let promise = new Promise((resolve) => { resolve(Object.keys(this._searchers)); }); return promise; } search(keyword, l...
}; this._searchResults = []; }
random_line_split
Searcher.js
import { EventEmitter } from 'events'; import Constants from './Constants'; // searchers import YoutubeSearcher from 'kaku-core/modules/searcher/YoutubeSearcher'; import VimeoSearcher from 'kaku-core/modules/searcher/VimeoSearcher'; import SoundCloudSearcher from 'kaku-core/modules/searcher/SoundCloudSearcher'; import...
get searchResults() { return this._searchResults; } getSupportedSearchers() { let promise = new Promise((resolve) => { resolve(Object.keys(this._searchers)); }); return promise; } search(keyword, limit, toSave = false) { if (!keyword) { return Promise.resolve([]); } ...
{ return this._searchers[this._selectedSearcherName]; }
identifier_body
Searcher.js
import { EventEmitter } from 'events'; import Constants from './Constants'; // searchers import YoutubeSearcher from 'kaku-core/modules/searcher/YoutubeSearcher'; import VimeoSearcher from 'kaku-core/modules/searcher/VimeoSearcher'; import SoundCloudSearcher from 'kaku-core/modules/searcher/SoundCloudSearcher'; import...
() { return this._searchers[this._selectedSearcherName]; } get searchResults() { return this._searchResults; } getSupportedSearchers() { let promise = new Promise((resolve) => { resolve(Object.keys(this._searchers)); }); return promise; } search(keyword, limit, toSave = false) {...
selectedSearcher
identifier_name
api_str.rs
// These tests don't really make sense with the bytes API, so we only test them // on the Unicode API. #[test] fn empty_match_unicode_find_iter() { // Tests that we still yield byte ranges at valid UTF-8 sequence boundaries // even when we're susceptible to empty width matches. let re = regex!(r".*?"); ...
let re = regex!(r"fo+"); let caps = re.captures("barfoobar").unwrap(); assert_eq!(caps.get(0).map(|m| m.as_str()), Some("foo")); assert_eq!(caps.get(0).map(From::from), Some("foo")); assert_eq!(caps.get(0).map(Into::into), Some("foo")); }
assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], ms); } #[test] fn match_as_str() {
random_line_split
api_str.rs
// These tests don't really make sense with the bytes API, so we only test them // on the Unicode API. #[test] fn empty_match_unicode_find_iter() { // Tests that we still yield byte ranges at valid UTF-8 sequence boundaries // even when we're susceptible to empty width matches. let re = regex!(r".*?"); ...
// Same as empty_match_unicode_find_iter, but tests capture iteration. let re = regex!(r".*?"); let ms: Vec<_> = re .captures_iter(text!("Ⅰ1Ⅱ2")) .map(|c| c.get(0).unwrap()) .map(|m| (m.start(), m.end())) .collect(); assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)...
y_match_unicode_captures_iter() {
identifier_name
api_str.rs
// These tests don't really make sense with the bytes API, so we only test them // on the Unicode API. #[test] fn empty_match_unicode_find_iter() { // Tests that we still yield byte ranges at valid UTF-8 sequence boundaries // even when we're susceptible to empty width matches. let re = regex!(r".*?"); ...
t re = regex!(r"fo+"); let caps = re.captures("barfoobar").unwrap(); assert_eq!(caps.get(0).map(|m| m.as_str()), Some("foo")); assert_eq!(caps.get(0).map(From::from), Some("foo")); assert_eq!(caps.get(0).map(Into::into), Some("foo")); }
identifier_body
app.js
var roshamboApp = angular.module('roshamboApp', []), roshambo= [ { name:'Rock', src:'img/rock.png' }, { name:'Paper', src:'img/paper.png' }, { name:'Scissors', src:'img/scissors.png' } ], roshamboMap=roshambo.reduce(function...
}); }; });
},function(errorResponse){ alert('Error!'); console.log('Caught error posting throw:\n%s',JSON.stringify(errorResponse,null,2));
random_line_split
app.js
var roshamboApp = angular.module('roshamboApp', []), roshambo= [ { name:'Rock', src:'img/rock.png' }, { name:'Paper', src:'img/paper.png' }, { name:'Scissors', src:'img/scissors.png' } ], roshamboMap=roshambo.reduce(function...
else{ return $scope.outcome.outcome.charAt(0).toUpperCase()+$scope.outcome.outcome.slice(1)+' Wins!'; } } },function(errorResponse){ alert('Error!'); console.log('Caught error posting throw:\n%s',JSON.stringify(errorResponse,null,2)); }); }; });
{ return 'It\'s a Draw!'; }
conditional_block
font_template.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 font::FontHandleMethods; use platform::font_context::FontContextHandle; use platform::font::FontHandle; use pl...
/// Get the data for creating a font. pub fn get(&mut self) -> Option<Arc<FontTemplateData>> { if self.is_valid { Some(self.get_data()) } else { None } } /// Get the font template data. If any strong references still /// exist, it will return a clon...
{ // The font template data can be unloaded when nothing is referencing // it (via the Weak reference to the Arc above). However, if we have // already loaded a font, store the style information about it separately, // so that we can do font matching against it again in the future ...
identifier_body
font_template.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 font::FontHandleMethods; use platform::font_context::FontContextHandle; use platform::font::FontHandle; use pl...
, None if self.is_valid => { let data = self.get_data(); let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(fctx, data.clone(), None); match handle { Ok(handle) => { let act...
{ if *requested_desc == actual_desc { Some(self.get_data()) } else { None } }
conditional_block
font_template.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 font::FontHandleMethods; use platform::font_context::FontContextHandle; use platform::font::FontHandle; use pl...
(&mut self, fctx: &FontContextHandle, requested_desc: &FontTemplateDescriptor) -> Option<Arc<FontTemplateData>> { // The font template data can be unloaded when nothing is referencing // it (via the Weak reference to the Arc a...
get_if_matches
identifier_name
font_template.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 font::FontHandleMethods; use platform::font_context::FontContextHandle; use platform::font::FontHandle; use pl...
return data } assert!(self.strong_ref.is_none()); let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None)); self.weak_ref = Some(template_data.downgrade()); template_data } }
None => None, }; if let Some(data) = maybe_data {
random_line_split
analytics(1).js
// lagou dataHost = "a.lagou.com"; (function(i, s, o, g, r, a, m) { i['LgAnalytics'] = r; i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; ...
String(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null) return unescape(r[2]); return null; }
= time.getTime(); param.userid = window.global.idmd5; //logtype-0表成功 logtype-1表失败 var uri = 'v=1&logtype='+param.logtype+'&position='+param.position+'&orderid='+param.orderid+'&userid='+param.userid+'&positionid='+param.positionid+'&url='+param.url+'&fromsite='+param.fromsite+'&optime='+param.time; ...
identifier_body
analytics(1).js
// lagou dataHost = "a.lagou.com"; (function(i, s, o, g, r, a, m) { i['LgAnalytics'] = r; i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; ...
//baidu var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://"); document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F4233e74dff0ae5bd0a3d81c6ccf756e6' type='text/javascript'%3E%3C/script%3E")); //google analytics (function(i,s,o,g,r,a,m){i['GoogleAnal...
random_line_split
analytics(1).js
// lagou dataHost = "a.lagou.com"; (function(i, s, o, g, r, a, m) { i['LgAnalytics'] = r; i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; ...
liverId, positionId, position){ //平台统计代码 调用函数见analytics.js add by vee 2015-07-28 var param = {}; param.logtype = logtype; //suc=0表成功 1表失败 param.position = position || GetQueryString('i'); param.orderid = deliverId; param.positionid = positionId; param.url...
g(logtype, de
identifier_name
helpers.py
from __future__ import absolute_import from __future__ import unicode_literals import os from compose.config.config import ConfigDetails from compose.config.config import ConfigFile from compose.config.config import load def
(contents, **kwargs): return load(build_config_details(contents, **kwargs)) def build_config_details(contents, working_dir='working_dir', filename='filename.yml'): return ConfigDetails( working_dir, [ConfigFile(filename, contents)], ) def create_host_file(client, filename): dirname =...
build_config
identifier_name
helpers.py
from __future__ import absolute_import from __future__ import unicode_literals import os from compose.config.config import ConfigDetails from compose.config.config import ConfigFile from compose.config.config import load def build_config(contents, **kwargs): return load(build_config_details(contents, **kwargs))...
finally: client.remove_container(container, force=True)
output = client.logs(container) raise Exception( "Container exited with code {}:\n{}".format(exitcode, output))
conditional_block
helpers.py
from __future__ import absolute_import from __future__ import unicode_literals import os from compose.config.config import ConfigDetails from compose.config.config import ConfigFile from compose.config.config import load def build_config(contents, **kwargs): return load(build_config_details(contents, **kwargs))...
[ConfigFile(filename, contents)], ) def create_host_file(client, filename): dirname = os.path.dirname(filename) with open(filename, 'r') as fh: content = fh.read() container = client.create_container( 'busybox:latest', ['sh', '-c', 'echo -n "{}" > {}'.format(content, ...
random_line_split
helpers.py
from __future__ import absolute_import from __future__ import unicode_literals import os from compose.config.config import ConfigDetails from compose.config.config import ConfigFile from compose.config.config import load def build_config(contents, **kwargs): return load(build_config_details(contents, **kwargs))...
def create_host_file(client, filename): dirname = os.path.dirname(filename) with open(filename, 'r') as fh: content = fh.read() container = client.create_container( 'busybox:latest', ['sh', '-c', 'echo -n "{}" > {}'.format(content, filename)], volumes={dirname: {}}, ...
return ConfigDetails( working_dir, [ConfigFile(filename, contents)], )
identifier_body
serialize.ts
// @require core/cash.ts // @require core/each.ts // @require core/type_checking.ts // @require ./helpers/get_value.ts // @require ./helpers/query_encode.ts interface Cash { serialize (): string; } const skippableRe = /file|reset|submit|button|image/i, checkableRe = /radio|checkbox/i; fn.serialize = functio...
}); }); return query.slice ( 1 ); };
{ const values = isArray ( value ) ? value : [value]; each ( values, ( i, value ) => { query += queryEncode ( ele.name, value ); }); }
conditional_block
serialize.ts
// @require core/cash.ts // @require core/each.ts // @require core/type_checking.ts // @require ./helpers/get_value.ts // @require ./helpers/query_encode.ts interface Cash { serialize (): string; } const skippableRe = /file|reset|submit|button|image/i, checkableRe = /radio|checkbox/i; fn.serialize = function...
query += queryEncode ( ele.name, value ); }); } }); }); return query.slice ( 1 ); };
const values = isArray ( value ) ? value : [value]; each ( values, ( i, value ) => {
random_line_split
interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.js
var interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder = [
[ "getPacketsReceived", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#a190993a33fa895f9d07145f3a04f5d22", null ], [ "getPacketsSent", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#ae9a71f2c48c5430a348eba326eb6d112", null ], [ "getPort", "interfac...
random_line_split
test_machine.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # This program 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, eithe...
) ), 2 ) def assertTranslate(self, machine, lang='cs', word='world', empty=False): translation = machine.translate(lang, word, None, None) self.assertIsInstance(translation, list) if not empty: self.assertTrue(len(translation) > 0)...
self.assertEqual( len( machine_translation.translate( 'cs', 'Hello, world!', None, None
random_line_split
test_machine.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # This program 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, eithe...
.register_uri( httpretty.GET, 'https://www.googleapis.com/language/translate/v2/languages', body='{"data": {"languages": [ { "language": "cs" }]}}' ) httpretty.register_uri( httpretty.GET, 'https://www.googleapis.com/language/translate/v2/', ...
httpretty
identifier_name
test_machine.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # This program 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, eithe...
e def test_glosbe(self): httpretty.register_uri( httpretty.GET, 'http://glosbe.com/gapi/translate', body=GLOSBE_JSON ) machine = GlosbeTranslation() self.assertTranslate(machine) @httpretty.activate def test_mymemory(self): httpret...
slation) > 0) @httpretty.activat
conditional_block
test_machine.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2015 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # This program 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, eithe...
(self): machine_translation = DummyTranslation() self.assertEqual( machine_translation.translate('cs', 'Hello', None, None), [] ) self.assertEqual( len( machine_translation.translate( 'cs', 'Hello, world!', None, Non...
mmyTranslation() self.assertTrue(machine_translation.is_supported('cs')) self.assertFalse(machine_translation.is_supported('de')) def test_translate
identifier_body
stream.py
# mhkutil - A utility for dealing with Mohawk archives # # mhkutil is the legal property of its developers, whose names # can be found in the AUTHORS file distributed with this source # distribution. # # mhkutil is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licen...
elif whence == os.SEEK_END: self._pos = len(self._data) + offset else: self._pos = offset def read(self, size): if size == 0: return bytearray() start = self._pos end = start + size self._pos = end return self._data[start:end]
self._pos += offset
conditional_block
stream.py
# mhkutil - A utility for dealing with Mohawk archives # # mhkutil is the legal property of its developers, whose names # can be found in the AUTHORS file distributed with this source # distribution. # # mhkutil is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licen...
return struct.unpack('>L', self.read(4))[0] def readSint32BE(self): return struct.unpack('>l', self.read(4))[0] def readCString(self): text = '' while True: char = self.readByte() if char == 0: break text += chr(char) return text class WriteStream: def writeByte(self, x): self.write(st...
def readUint32BE(self):
random_line_split
stream.py
# mhkutil - A utility for dealing with Mohawk archives # # mhkutil is the legal property of its developers, whose names # can be found in the AUTHORS file distributed with this source # distribution. # # mhkutil is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licen...
def write(self, x): self._handle.write(x) class ByteStream(Stream): def __init__(self, data): self._data = data self._pos = 0 def tell(self): return self._pos def size(self): return len(self._data) def seek(self, offset, whence=os.SEEK_SET): if whence == os.SEEK_CUR: self._pos += offset elif...
self._handle = handle
identifier_body
stream.py
# mhkutil - A utility for dealing with Mohawk archives # # mhkutil is the legal property of its developers, whose names # can be found in the AUTHORS file distributed with this source # distribution. # # mhkutil is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Licen...
(self, x): self.write(struct.pack('B', x)) def writeSByte(self, x): self.write(struct.pack('b', x)) def writeUint16LE(self, x): self.write(struct.pack('<H', x)) def writeSint16LE(self, x): self.write(struct.pack('<h', x)) def writeUint16BE(self, x): self.write(struct.pack('>H', x)) def writeSint16BE...
writeByte
identifier_name
__init__.py
# 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 License, Version 2.0 (the # "License"); you may not u...
"datasource_type": dataset.datasource_type, "datasource_name": dataset.table_name, } # import charts with the correct parent ref chart_ids: Dict[str, int] = {} for file_name, config in configs.items(): if ( file...
dataset_info[str(dataset.uuid)] = { "datasource_id": dataset.id,
random_line_split
__init__.py
# 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 License, Version 2.0 (the # "License"); you may not u...
"""Import dashboards""" dao = DashboardDAO model_name = "dashboard" prefix = "dashboards/" schemas: Dict[str, Schema] = { "charts/": ImportV1ChartSchema(), "dashboards/": ImportV1DashboardSchema(), "datasets/": ImportV1DatasetSchema(), "databases/": ImportV1DatabaseSchem...
identifier_body
__init__.py
# 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 License, Version 2.0 (the # "License"); you may not u...
(ImportModelsCommand): """Import dashboards""" dao = DashboardDAO model_name = "dashboard" prefix = "dashboards/" schemas: Dict[str, Schema] = { "charts/": ImportV1ChartSchema(), "dashboards/": ImportV1DashboardSchema(), "datasets/": ImportV1DatasetSchema(), "databa...
ImportDashboardsCommand
identifier_name
__init__.py
# 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 License, Version 2.0 (the # "License"); you may not u...
# discover datasets associated with charts for file_name, config in configs.items(): if file_name.startswith("charts/") and config["uuid"] in chart_uuids: dataset_uuids.add(config["dataset_uuid"]) # discover databases associated with datasets database_uuids...
chart_uuids.update(find_chart_uuids(config["position"])) dataset_uuids.update( find_native_filter_datasets(config.get("metadata", {})) )
conditional_block
walker.rs
use std::cell::RefCell; use std::io; use std::path::{Path, PathBuf}; use walkdir::{DirEntry, WalkDir, WalkDirIterator}; use pulldown_cmark::{Event, Parser, Tag}; use file_utils; /// Wrapper of a list of Markdown files. With end goal to be able to convey the
/// hierarchy. pub struct MarkdownFileList { // Considering maintaining directory structure by Map<Vec<>> files: Vec<MarkdownFile>, } impl MarkdownFileList { pub fn new(files: Vec<MarkdownFile>) -> MarkdownFileList { let mut sorted_files = files; sorted_files.sort_by(|a, b| a.get_file_name(...
random_line_split
walker.rs
use std::cell::RefCell; use std::io; use std::path::{Path, PathBuf}; use walkdir::{DirEntry, WalkDir, WalkDirIterator}; use pulldown_cmark::{Event, Parser, Tag}; use file_utils; /// Wrapper of a list of Markdown files. With end goal to be able to convey the /// hierarchy. pub struct MarkdownFileList { // Consider...
} Ok(files) } #[cfg(test)] mod tests { use std::path::PathBuf; use std::cell::RefCell; #[test] fn test_get_file_name() { let file = super::MarkdownFile { path: PathBuf::from("resources/tester.md"), heading: RefCell::new(String::new()), }; asser...
{ debug!("Adding file {:?}", path); files.push(MarkdownFile::from(path)); }
conditional_block
walker.rs
use std::cell::RefCell; use std::io; use std::path::{Path, PathBuf}; use walkdir::{DirEntry, WalkDir, WalkDirIterator}; use pulldown_cmark::{Event, Parser, Tag}; use file_utils; /// Wrapper of a list of Markdown files. With end goal to be able to convey the /// hierarchy. pub struct MarkdownFileList { // Consider...
/// Determines if the provided entry should be excluded from the files to check. /// The check just determines if the file or directory begins with an /// underscore. fn is_excluded(entry: &DirEntry) -> bool { entry .file_name() .to_str() .map(|s| s.starts_with('_')) .unwrap_or(fal...
{ const FILE_EXT: &str = "md"; if let Some(extension) = path.extension().and_then(|x| x.to_str()) { if extension.to_lowercase().eq(FILE_EXT) { return true; } } false }
identifier_body
walker.rs
use std::cell::RefCell; use std::io; use std::path::{Path, PathBuf}; use walkdir::{DirEntry, WalkDir, WalkDirIterator}; use pulldown_cmark::{Event, Parser, Tag}; use file_utils; /// Wrapper of a list of Markdown files. With end goal to be able to convey the /// hierarchy. pub struct MarkdownFileList { // Consider...
(path: &Path) -> MarkdownFile { MarkdownFile { path: path.to_path_buf(), heading: RefCell::new(String::new()), } } /// Return the path of the Markdown file pub fn get_path(&self) -> &PathBuf { &self.path } /// Return the name of the Markdown file ...
from
identifier_name
i18n_select_pipe.d.ts
import { PipeTransform } from 'angular2/core'; /** * * Generic selector that displays the string that matches the current value. * * ## Usage * * expression | i18nSelect:mapping * * where `mapping` is an object that indicates the text that should be displayed * for different values of the provid...
implements PipeTransform { transform(value: string, mapping: { [key: string]: string; }): string; }
I18nSelectPipe
identifier_name
transitionevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::Transition...
// https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.upcast::<Event>().IsTrusted() } }
{ self.pseudo_element.clone() }
identifier_body
transitionevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::Transition...
(&self) -> DOMString { DOMString::from(&*self.property_name) } // https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-elapsedTime fn ElapsedTime(&self) -> Finite<f32> { self.elapsed_time.clone() } // https://drafts.csswg.org/css-transitions/#Events-TransitionEvent-pseu...
PropertyName
identifier_name
transitionevent.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::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::Transition...
} ev } pub fn Constructor(window: &Window, type_: DOMString, init: &TransitionEventInit) -> Fallible<Root<TransitionEvent>> { let global = window.upcast::<GlobalScope>(); Ok(TransitionEvent::new(global, Atom::from(type_), init)) ...
random_line_split
foundation.interchange.js
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.definePrope...
(element, options) { _classCallCheck(this, Interchange); this.$element = element; this.options = $.extend({}, Interchange.defaults, options); this.rules = []; this.currentPath = ''; this._init(); this._events(); Foundation.registerPlugin(this, 'Interchange'); } ...
Interchange
identifier_name
foundation.interchange.js
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.definePrope...
} }]); return Interchange; }(); /** * Default settings for plugin */ Interchange.defaults = { /** * Rules to be applied to Interchange elements. Set with the `data-interchange` array notation. * @option */ rules: null }; Interchange.SPECIAL_QUERIES = { 'land...
}, { key: 'destroy', value: function destroy() { //TODO this.
random_line_split
foundation.interchange.js
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.definePrope...
// Replacing background images else if (path.match(/\.(gif|jpg|jpeg|png|svg|tiff)([?#].*)?/i)) { this.$element.css({ 'background-image': 'url(' + path + ')' }).trigger(trigger); } // Replacing HTML else { $.get(path, function (response) { ...
{ this.$element.attr('src', path).load(function () { _this.currentPath = path; }).trigger(trigger); }
conditional_block
foundation.interchange.js
'use strict'; var _createClass = function () { function defineProperties(target, props)
return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new T...
{ for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
identifier_body
base.py
# -*- coding: utf-8 -*- # # # Copyright 2013 Netflix, 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 ...
(self, cloud): """ By default, BlockDevicePlugins are called using with blockdeviceplugin(cloud) as device: pass Override if need be """ self.cloud = cloud return self
__call__
identifier_name
base.py
# -*- coding: utf-8 -*- # # # Copyright 2013 Netflix, 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 ...
return False def __call__(self, cloud): """ By default, BlockDevicePlugins are called using with blockdeviceplugin(cloud) as device: pass Override if need be """ self.cloud = cloud return self
log.exception("Exception: {0}: {1}".format(typ.__name__,val))
conditional_block
base.py
# -*- coding: utf-8 -*- # # # Copyright 2013 Netflix, 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 ...
@abc.abstractmethod def __enter__(self): return self @abc.abstractmethod def __exit__(self, typ, val, trc): if typ: log.exception("Exception: {0}: {1}".format(typ.__name__,val)) return False def __call__(self, cloud): """ By default, BlockDevicePlugins are ...
__metaclass__ = abc.ABCMeta _entry_point = 'aminator.plugins.blockdevice'
random_line_split
base.py
# -*- coding: utf-8 -*- # # # Copyright 2013 Netflix, 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 ...
def __call__(self, cloud): """ By default, BlockDevicePlugins are called using with blockdeviceplugin(cloud) as device: pass Override if need be """ self.cloud = cloud return self
if typ: log.exception("Exception: {0}: {1}".format(typ.__name__,val)) return False
identifier_body
video.rs
use sdl2; pub fn main()
{ sdl2::init(sdl2::InitVideo); let window = match sdl2::video::Window::new("rust-sdl2 demo: Video", sdl2::video::PosCentered, sdl2::video::PosCentered, 800, 600, sdl2::video::OpenGL) { Ok(window) => window, Err(err) => fail!(format!("failed to create window: {}", err)) }; let renderer ...
identifier_body
video.rs
use sdl2; pub fn main() { sdl2::init(sdl2::InitVideo); let window = match sdl2::video::Window::new("rust-sdl2 demo: Video", sdl2::video::PosCentered, sdl2::video::PosCentered, 800, 600, sdl2::video::OpenGL) { Ok(window) => window, Err(err) => fail!(format!("failed to create window: {}", err)) ...
}, sdl2::event::NoEvent => break 'event, _ => {} } } } sdl2::quit(); }
{ break 'main }
conditional_block
video.rs
use sdl2; pub fn
() { sdl2::init(sdl2::InitVideo); let window = match sdl2::video::Window::new("rust-sdl2 demo: Video", sdl2::video::PosCentered, sdl2::video::PosCentered, 800, 600, sdl2::video::OpenGL) { Ok(window) => window, Err(err) => fail!(format!("failed to create window: {}", err)) }; let render...
main
identifier_name
video.rs
use sdl2; pub fn main() { sdl2::init(sdl2::InitVideo); let window = match sdl2::video::Window::new("rust-sdl2 demo: Video", sdl2::video::PosCentered, sdl2::video::PosCentered, 800, 600, sdl2::video::OpenGL) { Ok(window) => window, Err(err) => fail!(format!("failed to create window: {}", err)) ...
Err(err) => fail!(format!("failed to create renderer: {}", err)) }; let _ = renderer.set_draw_color(sdl2::pixels::RGB(255, 0, 0)); let _ = renderer.clear(); renderer.present(); 'main : loop { 'event : loop { match sdl2::event::poll_event() { sdl2::event:...
Ok(renderer) => renderer,
random_line_split