code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def hex_to_K( s ): <NEW_LINE> <INDENT> poly_bits = ZZ('0x'+s).bits() <NEW_LINE> poly_str = "" <NEW_LINE> for i in range(len(poly_bits)): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> if poly_bits[i] == 1: <NEW_LINE> <INDENT> poly_str = " + 1" <NEW_LINE> <DEDENT> <DEDENT> elif poly_bits[i] == 1: <NEW_LINE> <INDENT>... | test docstring | 625941e53539df3088e2e76f |
def getShowLegend(self): <NEW_LINE> <INDENT> return self._show_legend | Check if the legend is being shown.
Returns : bool
-------
True if the legend is displayed on the graph; False if not. | 625941e5c4546d3d9de72e5b |
def clean(self): <NEW_LINE> <INDENT> if self.__user: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> keystone_utils.delete_user(self._keystone, self.__user) <NEW_LINE> <DEDENT> except NotFound: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.__user = None <NEW_LINE> <DEDENT> super(self.__class__, self).clean() | Cleanse environment of user
:return: void | 625941e5d7e4931a7ee9e342 |
def check_keys(self): <NEW_LINE> <INDENT> default_dict = [] <NEW_LINE> for ikey in JSON_VALVE_KEYS: <NEW_LINE> <INDENT> if ikey not in self.current_dict: <NEW_LINE> <INDENT> if not default_dict: <NEW_LINE> <INDENT> default_dict = self.load_default() <NEW_LINE> <DEDENT> self.current_dict[ikey] = default_dict[ikey] <NEW_... | check that the essential keys of the object exists, otherwise put a
default one | 625941e597e22403b379d3bf |
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <IND... | serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module | 625941e5bf627c535bc135f3 |
def pr(left, right): <NEW_LINE> <INDENT> if left is None: <NEW_LINE> <INDENT> return right <NEW_LINE> <DEDENT> elif right is None: <NEW_LINE> <INDENT> return left <NEW_LINE> <DEDENT> k = klass <NEW_LINE> if isinstance(left, ConditionBinOp): <NEW_LINE> <INDENT> if (isinstance(left, ConditionBinOp) and isinstance(right, ... | create and return a new specialized BinOp from myself | 625941e5656771135c3ebc97 |
def test_avoid_collision(): <NEW_LINE> <INDENT> a1 = App1() <NEW_LINE> a2 = App2() <NEW_LINE> assert len(c) == 0 <NEW_LINE> a1.test1(1, 2) <NEW_LINE> assert len(c) == 1 <NEW_LINE> a2.test1(1, 2) <NEW_LINE> assert len(c) == 2 <NEW_LINE> print(c.dump()) | Make sure cache keys don't collide | 625941e507d97122c4178cb8 |
def Instance2Str(obj, conv_dict): <NEW_LINE> <INDENT> if obj.__class__ in (object, type): <NEW_LINE> <INDENT> return conv_dict[str](obj, conv_dict) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return conv_dict[obj.__class__](obj, conv_dict) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> for converter in conv_... | Convert an Instance to a string representation. If the __str__() method
produces acceptable output, then you don't need to add the class to
conversions; it will be handled by the default converter. If the exact class
is not found in conv_dict, it will use the first class it can find for which
obj is an instance. | 625941e5cad5886f8bd273fc |
def test_repeated_assign_1darr_slice_string(): <NEW_LINE> <INDENT> dag = dag_from_strings(["a(:) = 2.0 * a(:)"]) <NEW_LINE> node_names = [node.name for node in itervalues(dag._nodes)] <NEW_LINE> assert "a'(:)" in node_names <NEW_LINE> assert "a(:)" in node_names | Test that we get correctly-named nodes when it is an array slice
that is repeatedly assigned to and we generate the dag from strings. | 625941e55510c4643540f7fd |
def __init__(self): <NEW_LINE> <INDENT> TemperatureSensor.__init__(self) <NEW_LINE> HumiditySensor.__init__(self) <NEW_LINE> self.__dht11Temp = DHT11Temperature() <NEW_LINE> self.__dht11Hum = DHT11Humidity() | Constructor | 625941e5167d2b6e31218fb9 |
def get_paged_request(url, headers=None, **params): <NEW_LINE> <INDENT> results = [] <NEW_LINE> params.setdefault("per_page", 100) <NEW_LINE> for i in count(): <NEW_LINE> <INDENT> print("Fetching page %i" % i) <NEW_LINE> response = requests.get(url, headers=headers, params=params) <NEW_LINE> response.raise_for_status()... | get a full list, handling APIv3's paging | 625941e5e8904600ed9f2357 |
def _add_container_hosts(assignment, config, container_name, container_type, inventory, properties): <NEW_LINE> <INDENT> physical_host_type = '%s_hosts' % container_type.split('_')[0] <NEW_LINE> if physical_host_type not in config: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for host_type in inventory[physical_host_... | Add a given container name and type to the hosts.
:param assignment: ``str`` Name of container component target
:param config: ``dict`` User defined information
:param container_name: ``str`` Name fo container
:param container_type: ``str`` Type of container
:param inventory: ``dict`` Living dictionary of inventor... | 625941e5ad47b63b2c50a3a2 |
def display(self): <NEW_LINE> <INDENT> temp = self.top <NEW_LINE> if temp.data is None: <NEW_LINE> <INDENT> print("Stack is empty. No elements to display.") <NEW_LINE> return <NEW_LINE> <DEDENT> while temp.data is not None: <NEW_LINE> <INDENT> print(temp.data) <NEW_LINE> temp = temp.link | print stack elements. | 625941e5f8510a7c17cf9b23 |
def _parseConfigfileCache(cache_dict, dirpath): <NEW_LINE> <INDENT> if cache_dict.has_key('name'): <NEW_LINE> <INDENT> _class = Caches.getCacheByName(cache_dict['name']) <NEW_LINE> kwargs = {} <NEW_LINE> if _class is Caches.Test: <NEW_LINE> <INDENT> if cache_dict.get('verbose', False): <NEW_LINE> <INDENT> kwargs['logfu... | Used by parseConfigfile() to parse just the cache parts of a config.
| 625941e507f4c71912b118a8 |
def test_get_user_enrollment_id(self): <NEW_LINE> <INDENT> events = [mommy.make(CampusEvent) for _ in range(10)] <NEW_LINE> expected_result = {} <NEW_LINE> for idx, event in enumerate(events): <NEW_LINE> <INDENT> if idx >= 3: <NEW_LINE> <INDENT> obj = mommy.make(Enrollment, user=self.user, campus_event=event) <NEW_LINE... | Should get user enrollment id. | 625941e52ae34c7f2600d554 |
def left_neighbor(self): <NEW_LINE> <INDENT> prev = None <NEW_LINE> for c in self.parent.cols: <NEW_LINE> <INDENT> if self is c: <NEW_LINE> <INDENT> return prev <NEW_LINE> <DEDENT> prev = c | Returns the column on the left of this one | 625941e5d7e4931a7ee9e343 |
def main(): <NEW_LINE> <INDENT> ConsumerKeyModule() | Main execution | 625941e5cc40096d61595d73 |
def get_all_envvars(self): <NEW_LINE> <INDENT> all_envvars = dict(self.environ) <NEW_LINE> if "GOPATH" in all_envvars: <NEW_LINE> <INDENT> all_envvars["GOPATH"] = os.path.expanduser(all_envvars["GOPATH"]) <NEW_LINE> <DEDENT> return all_envvars | Return a dictionary of all environment variables. | 625941e5a934411ee3751ab8 |
def block_matrix(self, top_left, top_right, bottom_left, bottom_right): <NEW_LINE> <INDENT> return self.matrix_factory( ls_entries=self.create_block_ls_entries(top_left, top_right, bottom_left, bottom_right)) | Forms and returns a block matrix
Args:
top_left: <Matrix> to go on the top left corner
top_right: <Matrix> to go on the top right corner
bottom_left: <Matrix> to go on the bottom left corner
bottom_right: <Matrix> to go on the bottom right corner
Returns:
<Matrix> block matrix | 625941e56fb2d068a760f4c7 |
def setHandler(self, handler): <NEW_LINE> <INDENT> self.handler = handler | Set handler object which will be requested to action when it's entity's turn | 625941e56e29344779a62a34 |
def ward_segment(G, feature, stop=-1, qmax=1, verbose=False): <NEW_LINE> <INDENT> if feature.ndim == 1: <NEW_LINE> <INDENT> feature = np.reshape(feature, (-1, 1)) <NEW_LINE> <DEDENT> if feature.shape[0] != G.V: <NEW_LINE> <INDENT> raise ValueError( "Incompatible dimension for the feature matrix and the graph") <NEW_LIN... | Agglomerative function based on a topology-defining graph
and a feature matrix.
Parameters
----------
G : graph object
the input graph (a topological graph essentially)
feature : array of shape (G.V,dim_feature)
some vectorial information related to the graph vertices
stop : int or float, optional
the stop... | 625941e58a43f66fc4b54485 |
def get_elem_abspath(self, name): <NEW_LINE> <INDENT> return self.position + self.get_whitespace_name(name) | Get absolute path for dataset or group | 625941e5adb09d7d5db6cbb1 |
def on_draw(self): <NEW_LINE> <INDENT> arcade.start_render() | Called when it is time to draw the world | 625941e5ac7a0e7691ed44e8 |
def set_partition(self): <NEW_LINE> <INDENT> return SetPartitions()(self) | Return the underlying implementation of the diagram as a set of sets.
EXAMPLES::
sage: import sage.combinat.diagram_algebras as da
sage: pd = da.AbstractPartitionDiagrams(2)
sage: X = pd([[1,2],[-1,-2]]).set_partition(); X
{{-2, -1}, {1, 2}}
sage: X.parent()
Set partitions | 625941e56fb2d068a760f4c8 |
def testCase501(self): <NEW_LINE> <INDENT> global jval <NEW_LINE> global sval <NEW_LINE> global configdata <NEW_LINE> global appname <NEW_LINE> global schemafile <NEW_LINE> schema = { "$schema": "http://json-schema.org/draft-03/schema", 'phoneNumber':configdata.schema['properties']['phoneNumber'] } <NEW_LINE> datafile ... | Import another branch into memory and copy into the initial master data.
Use insertion point:
target = configdata.data['phoneNumber']
for file:
'branch1.json'
#---
{
"type":"home2",
"number":"222 222-333"
}
#---
Apply '$schema' key for branch/subtree of master schema. | 625941e57047854f462a1829 |
def fbprophet_known_r2(y: Y_TYPE, s: dict, k: int, a: A_TYPE = None, t: T_TYPE = None, e: E_TYPE = None, r:R_TYPE=None): <NEW_LINE> <INDENT> assert r is not None <NEW_LINE> y0 = [wrap(y)[0]] <NEW_LINE> param_names = ['changepoint_prior_scale', 'seasonality_prior_scale'] <NEW_LINE> return fbprophet_hyperparam_skater_fac... | Uses known-in-advance but not y[1:] | 625941e57b180e01f3dc4c19 |
def pomodoro(self): <NEW_LINE> <INDENT> if not self._initialized: <NEW_LINE> <INDENT> self._init() <NEW_LINE> <DEDENT> cached_until = self.py3.time_in(0) <NEW_LINE> if self._running: <NEW_LINE> <INDENT> self._time_left = ceil(self._end_time - time.monotonic()) <NEW_LINE> time_left = ceil(self._time_left) <NEW_LINE> <DE... | Pomodoro response handling and countdown | 625941e524f1403a92600f87 |
def get_content_from_url(self, url): <NEW_LINE> <INDENT> response = urllib2.urlopen(url) <NEW_LINE> return response.read() | Get text content from URL | 625941e5bf627c535bc135f4 |
@task <NEW_LINE> def install_chef(latest=False): <NEW_LINE> <INDENT> sudo('apt-get update', pty=True) <NEW_LINE> sudo('apt-get install -y emacs23-nox ruby1.9.1 ruby1.9.1-dev build-essential', pty=True) <NEW_LINE> if latest: <NEW_LINE> <INDENT> sudo('gem1.9.1 install --no-ri --no-rdoc chef', pty=True) <NEW_LINE> <DEDENT... | Install chef-solo on the server | 625941e51b99ca400220aed7 |
def __init__(self, stations=None, distances=None, iterations=1000, neighborhood=None, neighborhood_decay=0.99, learning_rate=0.8, learning_rate_decay=0.99): <NEW_LINE> <INDENT> super().__init__(stations, distances) <NEW_LINE> self.name = "Self-organizing map" <NEW_LINE> self.iterations = iterations <NEW_LINE> if neighb... | Create problem for stations to visit | 625941e530c21e258bdfa8c5 |
def vectorize(self, text_documents): <NEW_LINE> <INDENT> tf_vectors = np.zeros((len(text_documents), self.dim)) <NEW_LINE> for i, text in enumerate(text_documents): <NEW_LINE> <INDENT> self._sample_document(text, tf_vectors[i]) <NEW_LINE> <DEDENT> if self.tf_vectors is None: <NEW_LINE> <INDENT> self.tf_vectors = tf_vec... | Vectorize a batch of documents in python utf-8 strings or unicode | 625941e53617ad0b5ed6831b |
def update(): <NEW_LINE> <INDENT> self.update_plot() | Trigger a plot update and refresh of the 'data' variable that represents
the plottable data. | 625941e5d6c5a10208144473 |
def use_proxy(self, http: str, https: str): <NEW_LINE> <INDENT> return self.__nav._use_proxy(http, https) | Setups a proxy without refreshing capabilities.
:param http: the http proxy address
:type http: str
:param https: the https proxy address
:type https: str | 625941e51f037a2d8b946621 |
def p_declaration_int(self, p): <NEW_LINE> <INDENT> p[0] = nd.Node("declaration", [p[1],p[2],p[4],p[6]], [p[3],p[5]]) | declaration : CONST NAME COLON INT EQ expression
| VAR NAME COLON INT EQ expression | 625941e57b25080760e3987b |
def create_model(bert_config, is_training, input_ids, input_mask, segment_ids, labels, num_labels, use_one_hot_embeddings): <NEW_LINE> <INDENT> model = modeling.BertModel( config=bert_config, is_training=is_training, input_ids=input_ids, input_mask=input_mask, token_type_ids=segment_ids, use_one_hot_embeddings=use_one_... | Creates a classification model. | 625941e530c21e258bdfa8c6 |
def datetime_to_str(dt, format_str='%Y-%m-%d %H:%M:%S'): <NEW_LINE> <INDENT> return dt.strftime(format_str) if dt else '' | 将datetime转换成字符串
:param format_str:
:param dt:
:return: | 625941e5283ffb24f3c55d21 |
def __init__(self, *args): <NEW_LINE> <INDENT> _cmf_core.vector_int_swiginit(self, _cmf_core.new_vector_int(*args)) | __init__(std::vector<(int)> self) -> vector_int
__init__(std::vector<(int)> self, vector_int arg2) -> vector_int
__init__(std::vector<(int)> self, std::vector< int >::size_type size) -> vector_int
__init__(std::vector<(int)> self, std::vector< int >::size_type size, std::vector< int >::value_type const & value) -> vect... | 625941e5ab23a570cc2505aa |
def p_NON_FUNCTION(p): <NEW_LINE> <INDENT> pass | NON_FUNCTION : FOR_LOOP NON_FUNCTION
| DO_WHILE_LOOP NON_FUNCTION
| WHILE_LOOP NON_FUNCTION
| ELSE_CONDITIONAL NON_FUNCTION
| IF_CONDITIONAL NON_FUNCTION
| OUTPUT NON_FUNCTION
| INPUT NON_FUNCTION
| VAR NO... | 625941e5fb3f5b602dac3abc |
def manage_addNotificationSubscriptionManager(context, REQUEST=None): <NEW_LINE> <INDENT> nsm = NotificationSubscriptionManager(NotificationSubscriptionManager.root) <NEW_LINE> context._setObject(NotificationSubscriptionManager.root, nsm) <NEW_LINE> if REQUEST is not None: <NEW_LINE> <INDENT> REQUEST['RESPONSE'].redire... | Create the notification subscription manager. | 625941e55f7d997b87174ec0 |
def markup_transform(line): <NEW_LINE> <INDENT> leiden_line = re.sub(r'\{(.+?)\}',r'< =\1>', line) <NEW_LINE> leiden_line = re.sub(r'\.\s\.\s\.','...',leiden_line) <NEW_LINE> leiden_line = re.sub(r'&(\d+?)&', r'((\1))',leiden_line) <NEW_LINE> leiden_line = re.sub(r'\$(.+?)\$', r'/*\1*/',leiden_line) <NEW_LINE> leiden_l... | This substitution is happening on a line by line basis:
A. The markup should not span multiple lines
B. I need to split the text into individual lines to filter out blank and note lines. | 625941e544b2445a339324b7 |
def publish(self, changeLog: typing.Optional[str] = None) -> None: <NEW_LINE> <INDENT> from uds.core.managers import publicationManager <NEW_LINE> publicationManager().publish(self, changeLog) | Launches the publication of this deployed service.
No check is done, it simply redirects the request to PublicationManager, where checks are done. | 625941e5be7bc26dc91cda1d |
@app.callback( Output('heatmap', 'className'), [Input('sidebar', 'className')]) <NEW_LINE> def update_scatterplot_class(sidebar_class): <NEW_LINE> <INDENT> if sidebar_class == '': <NEW_LINE> <INDENT> return 'plot_sidebar_open' <NEW_LINE> <DEDENT> return 'plot_sidebar_collapsed' | Return class name for div element containing a plot based
on the collapsed state of the side bar.
Keyword arguments:
sidebar_class -- Current class name of the sidebar | 625941e56aa9bd52df0371cb |
def start(self): <NEW_LINE> <INDENT> cache = collections.defaultdict(lambda:{}) <NEW_LINE> def add_file(pyc_file, module): <NEW_LINE> <INDENT> fname = pyc_file.rpartition('.')[0] + '.py' <NEW_LINE> if fname not in cache and os.access(fname, os.W_OK): <NEW_LINE> <INDENT> log.warning("watching file %r" % (fname)) <NEW_LI... | things got quite messy here, don't try to understand the flow, sorry
the main point is that when, during new import, we know the file to import,
we still don't know the module and module name. | 625941e566656f66f7cbc5d1 |
def save_file(file, path=''): <NEW_LINE> <INDENT> filename = file._get_name() <NEW_LINE> new_filename = u'{name}.{ext}'.format( name=uuid.uuid4().hex, ext=os.path.splitext(filename)[1].strip('.')) <NEW_LINE> dir_path = '%s/%s' % (settings.MEDIA_ROOT, str(path)) <NEW_LINE> if not os.path.exists(dir_path): <NEW_LINE> ... | Little helper to save a file
| 625941e5a05bb46b383ecc42 |
def end(self): <NEW_LINE> <INDENT> return _pyBasePython.setSS_end(self) | end(self) -> iterator | 625941e567a9b606de4a82dc |
def get_asdesc_ripe(asn, req_session, reg): <NEW_LINE> <INDENT> r = req_session.get('https://stat.ripe.net/data/as-overview/data.json?resource=AS' + str(asn)) <NEW_LINE> if r: <NEW_LINE> <INDENT> description = r.json()['data']['holder'] <NEW_LINE> if description: <NEW_LINE> <INDENT> parsed = reg.search(description) <NE... | returns the ASN description from RIPE NCC | 625941e54a966d76dd551438 |
def _unfuse(self): <NEW_LINE> <INDENT> assert not self._projection_size, "_unfuse does not support projection layer yet!" <NEW_LINE> assert not self._lstm_state_clip_min and not self._lstm_state_clip_max, "_unfuse does not support state clipping yet!" <NEW_LINE> get_cell = {'rnn_relu': lambda **kwargs: r... | Unfuses the fused RNN in to a stack of rnn cells. | 625941e538b623060ff0b212 |
def do_get_dependencies(self): <NEW_LINE> <INDENT> ModelTest.do_get_dependencies(self) <NEW_LINE> functions.add_mapgroup(u'Root') <NEW_LINE> new_map = functions.add_map(u'Carte 1') <NEW_LINE> host1 = functions.add_host(u'host1.example.com') <NEW_LINE> host2 = functions.add_host(u'host2.example.com') <NEW_LINE> referenc... | Generate some data for the test | 625941e556b00c62f0f14a80 |
def resize(self, targetSize, order=1): <NEW_LINE> <INDENT> if not isinstance(targetSize, tuple): <NEW_LINE> <INDENT> if self.format_ == 'latlong': <NEW_LINE> <INDENT> targetSize = (targetSize, 2*targetSize) <NEW_LINE> <DEDENT> elif self.format_ == 'skylatlong': <NEW_LINE> <INDENT> targetSize = (targetSize, 4*targetSize... | Resize the current environnement map to targetSize.
targetSize can be a tuple or a single number, in which case the same factor is assumed
for both u and v.
If 0 < targetSize < 1, treat it as a ratio
If targetSize > 1, treat it as new dimensions to use | 625941e5dc8b845886cb595b |
def __init__(self, features, indices, spatial_shape, batch_size, grid=None): <NEW_LINE> <INDENT> self.features = features <NEW_LINE> self.indices = indices <NEW_LINE> if self.indices.dtype != torch.int32: <NEW_LINE> <INDENT> self.indices.int() <NEW_LINE> <DEDENT> self.spatial_shape = spatial_shape <NEW_LINE> self.batch... | Args:
grid: pre-allocated grid tensor. should be used when the volume of spatial shape
is very large. | 625941e5ff9c53063f47c616 |
def run(self, cmd_args): <NEW_LINE> <INDENT> args = self.process_args(cmd_args) <NEW_LINE> args = [sys_decode(arg) for arg in args] <NEW_LINE> if len(args) == 0: <NEW_LINE> <INDENT> cmd_args = ['help'] <NEW_LINE> args = ['help'] <NEW_LINE> <DEDENT> if '--help' in args or '-h' in args: <NEW_LINE> <INDENT> new_cmd_args =... | Run Nikola. | 625941e5dc8b845886cb595c |
def getId(self): <NEW_LINE> <INDENT> return self.id | Returns this probe's id | 625941e550485f2cf553d1c0 |
def handle_client(self, origin_address: (str, int), client_sock: socket): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lengthbuf = client_sock.recv(4) <NEW_LINE> length, = struct.unpack('!I', lengthbuf) <NEW_LINE> data = client_sock.recv(length) <NEW_LINE> <DEDENT> except: <NEW_LINE> <IN... | Handles all commands sent from the client. | 625941e54527f215b584c877 |
@pytest.mark.get_tests <NEW_LINE> def test_bst_get(non_empty_bst): <NEW_LINE> <INDENT> assert non_empty_bst.get(3) == None <NEW_LINE> assert non_empty_bst.get(73) == 'F' <NEW_LINE> assert non_empty_bst.get(14) == 'C' | Test get method of the BST class for a
non-empty bst | 625941e5851cf427c661a930 |
def read_cc_point(self, file_path, line_flag): <NEW_LINE> <INDENT> cc_point = [] <NEW_LINE> with open(os.path.expandvars(file_path)) as file_ref: <NEW_LINE> <INDENT> for line in file_ref: <NEW_LINE> <INDENT> if line.startswith(line_flag): <NEW_LINE> <INDENT> line = line.replace(line_flag, "").strip() <NEW_LINE> cc_poin... | Read vector values from ponscc.cut.log file generated by FreeSurfer | 625941e563b5f9789fde750b |
def add_cubic_bezier_curve_to(self, handle1, handle2, anchor): <NEW_LINE> <INDENT> self.throw_error_if_no_points() <NEW_LINE> quadratic_approx = get_quadratic_approximation_of_cubic( self.get_last_point(), handle1, handle2, anchor ) <NEW_LINE> if self.has_new_path_started(): <NEW_LINE> <INDENT> self.append_points(quadr... | Add cubic bezier curve to the path. | 625941e55fcc89381b1e1ae6 |
def test_softmax_sigmoid_mse(): <NEW_LINE> <INDENT> _check_ae(1.0, hidden_units=(2,), cat_inds=[2, 3], bin_inds=[0]) | Test softmax + sigmoid indices + MSE loss. | 625941e51f037a2d8b946622 |
def upload_work(work_item, content): <NEW_LINE> <INDENT> URL = ARGS.server + "/hosts/{0}/work-items/{1}/success".format(HOSTNAME, work_item['id']) <NEW_LINE> res = requests.post(url=URL, data=content, headers={'Content-Type': 'application/octet-stream'}, verify=~ARGS.insecure) <NEW_LINE> res.raise_for_status() | Upload content against work item | 625941e51d351010ab855f40 |
def FactoryCoefficients_R(self): <NEW_LINE> <INDENT> dataCount = 0 <NEW_LINE> replyCount = 1 <NEW_LINE> result = False <NEW_LINE> s_buffer = bytearray(MSG_HEADER_SIZE+MSG_CHECKSUM_SIZE+dataCount) <NEW_LINE> r_buffer = bytearray(MSG_HEADER_SIZE+MSG_CHECKSUM_SIZE+replyCount) <NEW_LINE> s_buffer[MSG_INDEX_COMMAND] ... | This command reads the factory calibration coefficients. Each
coefficient is a float. The firmware applies the coefficients
when calculating the voltage and temperature values for each
channel. The coefficients are applied immediately and stored in
the EEPROM. | 625941e5b7558d58953c5330 |
def auto_unfollow_nonfollowers(self): <NEW_LINE> <INDENT> following = self.get_follows_list() <NEW_LINE> followers = self.get_followers_list() <NEW_LINE> not_following_back = following - followers <NEW_LINE> already_followed = set(not_following_back) <NEW_LINE> already_followed_list = [] <NEW_LINE> with open(self.BOT_C... | Unfollows everyone who hasn't followed you back. | 625941e54f88993c3716c488 |
def CreateFromSweep1(rail, shapes, closed, tolerance, multiple=False): <NEW_LINE> <INDENT> url = "rhino/geometry/brep/createfromsweep-curve_curvearray_bool_double" <NEW_LINE> if multiple: url += "?multiple=true" <NEW_LINE> args = [rail, shapes, closed, tolerance] <NEW_LINE> if multiple: args = list(zip(rail, shapes, cl... | Sweep1 function that fits a surface through profile curves that define the surface cross-sections
and one curve that defines a surface edge.
Args:
rail (Curve): Rail to sweep shapes along
shapes (IEnumerable<Curve>): Shape curves
closed (bool): Only matters if shapes are closed
tolerance (double): Tole... | 625941e53317a56b8693a073 |
def create(self, params = None): <NEW_LINE> <INDENT> params = params or {} <NEW_LINE> if self._id is not None: <NEW_LINE> <INDENT> self._log.info("Create {0} failed, already has ID".format(self._object_type)) <NEW_LINE> raise kaiten.error.ThingiverseException <NEW_LINE> <DEDENT> if not self._attribute_check(params): <N... | Creates a new thingiverse object | 625941e585dfad0860c3b281 |
def resize_table(self, capacity): <NEW_LINE> <INDENT> new_bucket = [] <NEW_LINE> for c in range(capacity): <NEW_LINE> <INDENT> new_bucket.append(LinkedList()) <NEW_LINE> <DEDENT> self.capacity = capacity <NEW_LINE> for b in self._buckets: <NEW_LINE> <INDENT> while b.head is not None: <NEW_LINE> <INDENT> index = self._h... | Resizes the hash table to have a number of buckets equal to the given
capacity. All links need to be rehashed in this function after resizing
Args:
capacity: the new number of buckets. | 625941e57cff6e4e81117daa |
def exec_editor(editor_cmd, _file): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> check_call([editor_cmd, _file]) <NEW_LINE> <DEDENT> except (OSError, ValueError) as err: <NEW_LINE> <INDENT> raise CommandError(editor_cmd + " " + _file, "", "\nError message:\n" + str(err)) | Opens a shell text editor.
- _file -- File to be opened. | 625941e58e7ae83300e4b3f3 |
def setup(self): <NEW_LINE> <INDENT> args = self.job.args <NEW_LINE> self._job_log("PROVIDER : %s", self.job.args.libcloud_provider) <NEW_LINE> try: <NEW_LINE> <INDENT> self.node = self._create_node() <NEW_LINE> <DEDENT> except LibcloudError as exception: <NEW_LINE> <INDENT> raise exceptions.JobError(exception.messag... | Initialize VM, establish connection and install avocado | 625941e5b545ff76a891423a |
def require(request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request = request.split(".") <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> request = map(int, request) <NEW_LINE> provide = list(__version) <NEW_LINE> if request > provide: <NEW_LINE> <INDENT> raise AssertionErr... | Raise :exc:`AssertionError` if gtkmvc version is not compatible.
*request* a dotted string or iterable of string or integers representing the
minimum version you need. ::
require("1.0")
require(("1", "2", "2"))
require([1,99,0])
.. note::
For historical reasons this does not take all API changes into account.... | 625941e57b180e01f3dc4c1a |
def get(self): <NEW_LINE> <INDENT> users_db = g.con.get_users() <NEW_LINE> envelope = forum_obj.ForumObject() <NEW_LINE> envelope.add_namespace("forum", hyper_const.LINK_RELATIONS_URL) <NEW_LINE> envelope.add_control_add_user() <NEW_LINE> envelope.add_control_messages_all() <NEW_LINE> envelope.add_control_diagnoses_all... | Gets a list of all the users in the database.
It returns always status code 200.
RESPONSE ENTITY BODY:
OUTPUT:
* Media type: application/vnd.mason+json
https://github.com/JornWildt/Mason
* Profile: Forum_User
/profiles/user-profile
Link relations used in items: messages
Semantic descriptio... | 625941e57cff6e4e81117dab |
def timer(enabled=True): <NEW_LINE> <INDENT> def decor(func): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> if enabled is True: <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> result = func(*args, **kwargs) <NEW_LINE> stop = time.time() <NEW_LINE> elapsed = stop - start <NEW_LINE> print("{}: ... | Таймер исполнения функций с возможностью вкл/выкл | 625941e5e8904600ed9f2358 |
def test_job_archive(): <NEW_LINE> <INDENT> class DummyLink(Link): <NEW_LINE> <INDENT> appname = 'test_app' <NEW_LINE> linkname_default = 'test' <NEW_LINE> usage = '%s [options]' % (appname) <NEW_LINE> description = "Link to run %s" % (appname) <NEW_LINE> default_options = dict(optstr=('CALDB', 'options', str), infile1... | Test that we can build a JobArchive | 625941e510dbd63aa1bd2fc7 |
def aggregate(self): <NEW_LINE> <INDENT> df = self.model.df <NEW_LINE> from .dialogs import AggregateDialog <NEW_LINE> dlg = AggregateDialog(self, df=self.model.df) <NEW_LINE> g = dlg.result <NEW_LINE> if g is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> replace = False <NEW_LINE> if replace == True: <NEW_LINE>... | Show aggregate dialog | 625941e5851cf427c661a931 |
def checkconfig(): <NEW_LINE> <INDENT> cmd = ['lxc-checkconfig'] <NEW_LINE> return subprocess.check_output(cmd).replace('[1;32m', '').replace('[1;33m', '').replace('[0;39m', '').replace('[1;32m', '').replace(' ', '').split('\n') | returns the output of lxc-checkconfig | 625941e5f548e778e58cd9a4 |
def get_image_path(l): <NEW_LINE> <INDENT> rx = re.compile('\!\[\]\((?P<filename>.+)\)').search(l) <NEW_LINE> if rx: <NEW_LINE> <INDENT> path_new = '<a data-lightbox="note" href="' + PATH_TO_IMG + '/' + rx.group('filename') +'"><img src="' + PATH_TO_IMG + '/' + rx.group('filename') +'"></a> \n' <NEW_LINE> return path_n... | Get image path for l(ine).
:rtype: string, line | 625941e5f548e778e58cd9a5 |
def JYM(value): <NEW_LINE> <INDENT> modValue = value % 11 <NEW_LINE> if modValue == 0: <NEW_LINE> <INDENT> return '1' <NEW_LINE> <DEDENT> elif modValue == 1: <NEW_LINE> <INDENT> return '0' <NEW_LINE> <DEDENT> elif modValue == 2: <NEW_LINE> <INDENT> return 'X' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str(12 ... | 校验码 | 625941e5b5575c28eb68e429 |
def setUp(self): <NEW_LINE> <INDENT> add_objects() | Set up the test db | 625941e54428ac0f6e5bac1b |
def register_pick(self, match_number, user, userpick): <NEW_LINE> <INDENT> connection = sqlite3.connect(self.db) <NEW_LINE> cur = connection.cursor() <NEW_LINE> current_match = 0 <NEW_LINE> for m in self.get_matches(): <NEW_LINE> <INDENT> if m.number == match_number: <NEW_LINE> <INDENT> current_match = m <NEW_LINE> bre... | Registers the pick in the database
:param match_number: index of the match in the Match table
:param user: Discord ID to who the pick belongs
:param userpick: The team that the user picked
:return: False if the match is done or has started, True if the operation succeeds | 625941e53eb6a72ae02ec90d |
def parse(src): <NEW_LINE> <INDENT> tree = ast.parse(sanitize_source(src)) <NEW_LINE> _tree_normalizer.visit(tree) <NEW_LINE> return tree | Replaces ast.parse; ensures additional properties on the parsed tree.
This enforces the assumption that each node in the ast is unique. | 625941e5462c4b4f79d1daf4 |
def test_process_content_sections_table_disp_quote(self): <NEW_LINE> <INDENT> content_sections = [ OrderedDict( [ ("tag_name", "p"), ("content", "<italic>Paragraph.</italic>"), ] ), OrderedDict( [ ("tag_name", "p"), ("content", "<bold>Author response Table 1.</bold>"), ] ), OrderedDict( [ ("tag_name", "p"), ( "content"... | test for previous block is a disp-quote type | 625941e5099cdd3c635f107e |
def test_option_id_len(self): <NEW_LINE> <INDENT> repo = self.init_test_repo('gbp-test-native') <NEW_LINE> eq_(mock_ch(['--id-len=10']), 0) <NEW_LINE> commit_id = repo.rev_parse('HEAD', 10) <NEW_LINE> content = self.read_file('packaging/gbp-test-native.changes') <NEW_LINE> ok_(content[1].startswith('- [%s] ' % commit_i... | Test the --id-len cmdline option | 625941e56fece00bbac2db69 |
def create_loggers(file_localisation_all: str, file_localisation_error: str): <NEW_LINE> <INDENT> logger = logging.getLogger() <NEW_LINE> logger.setLevel(logging.DEBUG) <NEW_LINE> formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') <NEW_LINE> file_handler = RotatingFileHandler(file_localisation... | Create the logger for all information | 625941e5236d856c2ad44c05 |
def build_deposit_proof( aergo_from: herapy.Aergo, aergo_to: herapy.Aergo, receiver: str, bridge_from: str, bridge_to: str, deposit_height: int, token_origin: str, key_word: str ) -> herapy.obj.sc_state.SCState: <NEW_LINE> <INDENT> if not is_aergo_address(receiver): <NEW_LINE> <INDENT> raise InvalidArgumentsError( "Rec... | Check the last anchored root includes the lock and build
a lock proof for that root | 625941e5d58c6744b4258083 |
def is_prime(n:int) -> bool: <NEW_LINE> <INDENT> prime = True <NEW_LINE> for i in range(2, n): <NEW_LINE> <INDENT> if n % i == 0: <NEW_LINE> <INDENT> prime = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return prime | Tests to see if a number is prime.
>>> is_prime(2)
True
>>> is_prime(11)
True
>>> is_prime(8)
False | 625941e5566aa707497f4988 |
@cache.memoize(timeout=300) <NEW_LINE> def create_boxes_content(uid, collection='home'): <NEW_LINE> <INDENT> boxes_content = [] <NEW_LINE> all_settings = get_boxes_settings(uid, collection) <NEW_LINE> for box_settings in all_settings: <NEW_LINE> <INDENT> box = boxes[box_settings['type']](**box_settings) <NEW_LINE> boxe... | Create the content of all the boxes.
:param uid: User ID to retrieve the box settings.
:param collection: Collection name, by default `home`
:returns: Ordered list with the content of each box | 625941e5eab8aa0e5d26df7f |
def update(self, itr, **args): <NEW_LINE> <INDENT> Z, G = args['Z'], args['G'] <NEW_LINE> YTY = _nmp.sum(self.Y**2, 0) <NEW_LINE> GTY = G.T.dot(self.Y) <NEW_LINE> super().update(itr, YTY=YTY, GTY=GTY, **args) <NEW_LINE> self.Y = _sample_Y(Z, G, self.mu, self.phi, self.Y, self.beta, self.tau) <NEW_LINE> self.mu = _sampl... | TODO. | 625941e5c4546d3d9de72e5d |
def parametric_project_data_output_path(self): <NEW_LINE> <INDENT> path = os.path.join(self.landbosse_output_dir(), 'calculated_parametric_inputs', 'parametric_project_data') <NEW_LINE> if os.path.exists(path) and not os.path.isdir(path): <NEW_LINE> <INDENT> raise XlsxOperationException(f'Attempt to write project data ... | Returns th path to the project output data folder.
This folder is to put the parameterized project data sheets generated
during model runs.
If the directory does not exist, it is created.
Returns
-------
str
Path to project data output folder. | 625941e59c8ee82313fbbb9c |
def add(self, task_instance): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> task_query = "INSERT into Task (id,taskName,taskExePath) values ('" + task_instance.task_id + "','" + task_instance.task_name + "','" + re.escape(task_instance.task_exe_path) + "')" <NEW_LINE> if self.log: <NEW_LINE... | Adding a new task into the system | 625941e53539df3088e2e771 |
def delete_books(self, paths, end_session=True): <NEW_LINE> <INDENT> raise NotImplementedError() | Delete books at paths on device. | 625941e515baa723493c439e |
@step(r'Server (\S+) (NOT )?respond with (\w+) message.') <NEW_LINE> def send_wait_for_message(server_type, message, expect_response=True): <NEW_LINE> <INDENT> return dhcpmsg.send_wait_for_message(server_type, expect_response, message) | This step causes to send message to server and capture respond. | 625941e58c0ade5d55d3ede4 |
def adv_mlp(self, vec_sen, adv_ind, train, vec_drop): <NEW_LINE> <INDENT> if train: <NEW_LINE> <INDENT> drop = self._dropout <NEW_LINE> out = dy.dropout(vec_sen, vec_drop) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> drop = 0 <NEW_LINE> out = vec_sen <NEW_LINE> <DEDENT> for i in range(self._adv_depth): <NEW_LINE> <IND... | calculating the adversarial mlp over the sentence representation vector.
more than a single adversarial mlp is supported | 625941e5adb09d7d5db6cbb2 |
def xdg_open(application, wait=True): <NEW_LINE> <INDENT> proc = Popen(['xdg-open', application], stdout=PIPE) <NEW_LINE> if wait: <NEW_LINE> <INDENT> proc.communicate() | Open application using xdg-open.
Keyword arguments:
application -- string for application to run.
wait -- boolean on whether the proc.communicate() should be used.
(default True) | 625941e5de87d2750b8601bc |
def typedproperty(name: str, expected_type: Any) -> Any: <NEW_LINE> <INDENT> private_name = '_' + name <NEW_LINE> @property <NEW_LINE> def prop(self) -> Any: <NEW_LINE> <INDENT> return getattr(self, private_name) <NEW_LINE> <DEDENT> @prop.setter <NEW_LINE> def prop(self, value: Any) -> None: <NEW_LINE> <INDENT> if not ... | Creates property setter and getter allowing for data type control.
Args:
name: String - name of the property.
expected_type: Any - expected type of the property.
Raises:
TypeError: When value supplied to setter doesn't match expected type.
Usage:
import typedproperty as tp
class Stock:
name = tp.St... | 625941e501c39578d7e75261 |
def reset(self): <NEW_LINE> <INDENT> super().reset() <NEW_LINE> self.core.dir_remove(self.CODEDIR) <NEW_LINE> self._init() | helper method to clean what this module generates. | 625941e529b78933be1e5acc |
def has_section(self, section): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> next(tup for tup in self._config if tup.section==section) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True | Returns TF whether a SectionKV with the named ``section`` exists in this configuration instance. | 625941e5046cf37aa974d169 |
def __getitem__(self, key): <NEW_LINE> <INDENT> self.connect() <NEW_LINE> idx = self._child_dc_mapping[key] <NEW_LINE> connector = self._child_data_connectors[idx] <NEW_LINE> return connector | @param key: (str) engine_url
@return: (subclass of :class:`DataConnector`) | 625941e5cad5886f8bd273fe |
def test_return_list_length(self): <NEW_LINE> <INDENT> my_users = { 'j':{'username':'j','ans':[],'wrong':[],'score':2}, 'e':{'username':'e','ans':[],'wrong':[],'score':5}, 'a':{'username':'a','ans':[],'wrong':[],'score':9}, 'b ':{'username':'b','ans':[],'wrong':[],'score':6}, 'c':{'username':'c','ans':[],'wrong':[],'sc... | Should return a list of length 5 as 5 users score greater than 0 | 625941e5e8904600ed9f2359 |
def teardown_module(module): <NEW_LINE> <INDENT> if CLEAN_TMP_DIR: <NEW_LINE> <INDENT> shutil.rmtree(TMP_DIR) | teardown any state that was previously setup with a setup_module method. | 625941e5c432627299f0506f |
def set_gyro_low_pass(self, enabled=True, mode=5): <NEW_LINE> <INDENT> self.bank(2) <NEW_LINE> value = self.read(ICM20948_GYRO_CONFIG_1) & 0b10001110 <NEW_LINE> if enabled: <NEW_LINE> <INDENT> value |= 0b1 <NEW_LINE> <DEDENT> value |= (mode & 0x07) << 4 <NEW_LINE> self.write(ICM20948_GYRO_CONFIG_1, value) | Configure the gyro low pass filter. | 625941e53c8af77a43ae3bcb |
def animation_stop(self, name): <NEW_LINE> <INDENT> anim, speed, reset = self.animations[name] <NEW_LINE> anim.setEnabled(False) | Stop the animation with the given name. | 625941e5d164cc6175783175 |
def _flush(self): <NEW_LINE> <INDENT> while ogg.ogg_stream_flush( ctypes.pointer(self._stream_state), ctypes.pointer(self._ogg_page)) != 0: <NEW_LINE> <INDENT> self._write_page() | Flush all pages to the file. | 625941e591af0d3eaac9be42 |
def test_registration_validates_email(self): <NEW_LINE> <INDENT> user = self.get_authenticated_user() <NEW_LINE> response = self.client.post( self.api_link, data={ 'username': 'totallyNew', 'email': user.email, 'password': 'LoremP4ssword', }, ) <NEW_LINE> self.assertEqual(response.status_code, 400) <NEW_LINE> self.asse... | api validates usernames | 625941e557b8e32f524838c3 |
def split_file(mfile, max_bars=32, max_notes=256): <NEW_LINE> <INDENT> if len(mfile.tracks) != 1: <NEW_LINE> <INDENT> raise ValueError('can only handle one midi track, got {}'.format( len(mfile.tracks))) <NEW_LINE> <DEDENT> if len(mfile.tracks[0]) >= 8000: <NEW_LINE> <INDENT> split_files = map( functools.partial(_midif... | Splits a file into non-overlapping chunks with less than `max_notes`
'note on' events. Each chunk may in the future be a power of two bars, at
most `max_bars`. Proceeds "recursively" until we have chunks with both
conditions met and then attempts to remove duplicates.
Args:
mfile: the midi file to split, a mido.Mi... | 625941e5cb5e8a47e48b7eca |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.