file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
modal_matchers.d.ts
/* * Copyright 2019 ThoughtWorks, Inc. *
* you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WA...
* Licensed under the Apache License, Version 2.0 (the "License");
random_line_split
test_stringutils.py
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2013 Async Open Source ## ## This program is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public License ## as published by the Free Software Foundation; either version 2 ## of the License, or...
(unittest.TestCase): def test_next_value_for(self): # Trivial cases self.assertEqual(next_value_for(u''), u'1') self.assertEqual(next_value_for(u'1'), u'2') self.assertEqual(next_value_for(u'999'), u'1000') # Ending with digit cases self.assertEqual(next_value_for(u'...
TestStringUtils
identifier_name
test_stringutils.py
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2013 Async Open Source ## ## This program is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public License ## as published by the Free Software Foundation; either version 2 ## of the License, or...
self.assertEqual(next_value_for(u'A999-Z'), u'A999-00') # Not handled cases self.assertEqual(next_value_for(u'A999-'), u'A999-0') def test_max_value_for(self): self.assertEqual(max_value_for([u'']), u'') self.assertEqual(max_value_for([u'1']), u'1') self.assertEqua...
self.assertEqual(next_value_for(u''), u'1') self.assertEqual(next_value_for(u'1'), u'2') self.assertEqual(next_value_for(u'999'), u'1000') # Ending with digit cases self.assertEqual(next_value_for(u'A999'), u'A1000') self.assertEqual(next_value_for(u'A8'), u'A9') self.as...
identifier_body
test_stringutils.py
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2013 Async Open Source ## ## This program is free software; you can redistribute it and/or ## modify it under the terms of the GNU Lesser General Public License ## as published by the Free Software Foundation; either version 2 ## of the License, or...
self.assertEqual(next_value_for(u'999'), u'1000') # Ending with digit cases self.assertEqual(next_value_for(u'A999'), u'A1000') self.assertEqual(next_value_for(u'A8'), u'A9') self.assertEqual(next_value_for(u'A9'), u'A10') self.assertEqual(next_value_for(u'A99'), u'A100'...
# Trivial cases self.assertEqual(next_value_for(u''), u'1') self.assertEqual(next_value_for(u'1'), u'2')
random_line_split
main.rs
extern crate nt; extern crate time; extern crate getopts; use std::io::Read; use getopts::{Options,Matches}; use nt::core::Note; use nt::core::persistence::Store; use nt::core::editor; use nt::core::persistence::Search; use nt::core::persistence::sqlite::SQLiteStore; // Whether new notes should be read from stdin. I...
{ let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief)); }
identifier_body
main.rs
extern crate nt; extern crate time; extern crate getopts; use std::io::Read; use getopts::{Options,Matches}; use nt::core::Note; use nt::core::persistence::Store; use nt::core::editor; use nt::core::persistence::Search; use nt::core::persistence::sqlite::SQLiteStore; // Whether new notes should be read from stdin. I...
(program: &str, opts: Options) { let brief = format!("Usage: {} [options]", program); print!("{}", opts.usage(&brief)); }
print_usage
identifier_name
main.rs
extern crate nt; extern crate time; extern crate getopts;
use std::io::Read; use getopts::{Options,Matches}; use nt::core::Note; use nt::core::persistence::Store; use nt::core::editor; use nt::core::persistence::Search; use nt::core::persistence::sqlite::SQLiteStore; // Whether new notes should be read from stdin. If unset, the system editor // is used. const READ_FROM_STD...
random_line_split
macros.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
) // Some basic logging. Enabled by passing `--cfg rtdebug` to the libstd build. macro_rules! rtdebug ( ($($arg:tt)*) => ( { if cfg!(rtdebug) { rterrln!($($arg)*) } }) ) macro_rules! rtassert ( ( $arg:expr ) => ( { if ::macros::ENFORCE_SANITY { if !$arg { ...
random_line_split
macros.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
> ! { use std::intrinsics; unsafe { intrinsics::abort() } } }
t() -
identifier_name
macros.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use std::intrinsics; unsafe { intrinsics::abort() } } }
identifier_body
FlatgridKeyingTest.ts
import { FocusTools, Keyboard, Keys, Step } from '@ephox/agar'; import { UnitTest } from '@ephox/bedrock'; import { Objects } from '@ephox/boulder'; import { Arr } from '@ephox/katamari'; import * as Behaviour from 'ephox/alloy/api/behaviour/Behaviour'; import { Focusing } from 'ephox/alloy/api/behaviour/Focusing'; im...
Focusing.config({ }) ]) }); }; return GuiFactory.build( Container.sketch({ dom: { tag: 'div', classes: [ 'flat-grid-keying-test'], styles: { background: 'white', width: '150px', height: '200px' } ...
containerBehaviours: Behaviour.derive([
random_line_split
code2seq_dataset.py
.tar.gz', 'sha1sum': '219e558ddf46678ef322ff75bf1982faa1b6204d', } } _URLS_LARGE = { 'java-large-preprocessed.tar.gz': { 'url': 'https://s3.amazonaws.com/code2seq/datasets/java-large-preprocessed.tar.gz', 'sha1sum': 'ebc229ba1838a3c8f3a69ab507eb26fa5460152a', } } ...
subtoken_node_ids = [] prev_subtoken_id = -1 # Create a node each subtoken. for subtoken in subtokens: graph_to_output_example.add_node(cur_node_id, 'SUBTOKEN', subtoken) subtoken_node_ids.append(cur_node_id) # Connects to the previous subtoken node if prev_subtoken_id != -1: ...
"""Construct the token subtree in a AST path. We create a node for each subtoken in the token, all subtokens are connected to the next subtoken via the 'NEXT_SUBTOKEN' edge. All subtokens are connected to the token root node via the 'SUBTOKEN' edge. See the draw.io figure mentioned in the class doc for...
identifier_body
code2seq_dataset.py
= token.split('|') subtoken_node_ids = [] prev_subtoken_id = -1 # Create a node each subtoken. for subtoken in subtokens: graph_to_output_example.add_node(cur_node_id, 'SUBTOKEN', subtoken) subtoken_node_ids.append(cur_node_id) # Connects to the previous subtoken node if prev_su...
return constants.TEST_SPLIT_NAME
conditional_block
code2seq_dataset.py
graph_to_output_example, cur_node_id, token_node_id. graph_to_output_example is updated with the token subtree, cur_node_id is the next available node id after all the token subtree nodes are added, and token_node_id is the node id of the root token node. """ subtokens = token.split('|') ...
_get_split
identifier_name
code2seq_dataset.py
.tar.gz', 'sha1sum': '219e558ddf46678ef322ff75bf1982faa1b6204d', } } _URLS_LARGE = { 'java-large-preprocessed.tar.gz': { 'url': 'https://s3.amazonaws.com/code2seq/datasets/java-large-preprocessed.tar.gz', 'sha1sum': 'ebc229ba1838a3c8f3a69ab507eb26fa5460152a', } } ...
"""Construct the AST nodes subtree in a AST path. We create a node for each AST node in the AST path. Each AST node are connected to the next AST node via the 'NEXT_AST_NODE' edge. See the draw.io figure mentioned in the class doc for the visualization. Args: graph_to_output_example: A Graph...
return graph_to_output_example, cur_node_id, token_node_id def _construct_ast_nodes_subtree(self, graph_to_output_example, ast_nodes, cur_node_id):
random_line_split
_feature_agglomeration.py
""" Feature agglomeration. Base classes and functions for performing feature agglomeration. """ # Author: V. Michel, A. Gramfort # License: BSD 3 clause import numpy as np from ..base import TransformerMixin from ..utils import array2d ############################################################################### ...
(TransformerMixin): """ A class for feature agglomeration via the transform interface """ def transform(self, X, pooling_func=np.mean): """ Transform a new matrix using the built clustering Parameters --------- X : array-like, shape = [n_samples, n_features] ...
AgglomerationTransform
identifier_name
_feature_agglomeration.py
""" Feature agglomeration. Base classes and functions for performing feature agglomeration. """ # Author: V. Michel, A. Gramfort # License: BSD 3 clause import numpy as np from ..base import TransformerMixin from ..utils import array2d ############################################################################### ...
A M by N array of M observations in N dimensions or a length M array of M one-dimensional observations. pooling_func : a function that takes an array of shape = [M, N] and return an array of value of size M. Defaut is np.mean """ ...
Transform a new matrix using the built clustering Parameters --------- X : array-like, shape = [n_samples, n_features]
random_line_split
_feature_agglomeration.py
""" Feature agglomeration. Base classes and functions for performing feature agglomeration. """ # Author: V. Michel, A. Gramfort # License: BSD 3 clause import numpy as np from ..base import TransformerMixin from ..utils import array2d ############################################################################### ...
return X
if np.size((Xred.shape)) == 1: X[self.labels_ == unil[i]] = Xred[i] else: X[:, self.labels_ == unil[i]] = array2d(Xred[:, i]).T
conditional_block
_feature_agglomeration.py
""" Feature agglomeration. Base classes and functions for performing feature agglomeration. """ # Author: V. Michel, A. Gramfort # License: BSD 3 clause import numpy as np from ..base import TransformerMixin from ..utils import array2d ############################################################################### ...
nX.append(pooling_func(X[:, self.labels_ == l], axis=1)) return np.array(nX).T def inverse_transform(self, Xred): """ Inverse the transformation. Return a vector of size nb_features with the values of Xred assigned to each group of features Parameters ...
""" Transform a new matrix using the built clustering Parameters --------- X : array-like, shape = [n_samples, n_features] A M by N array of M observations in N dimensions or a length M array of M one-dimensional observations. pooling_func : a function t...
identifier_body
App.tsx
import React from 'react'; import { Form, Formik, FormikHelpers } from 'formik'; import JSZip from 'jszip'; import FileSaver from 'file-saver'; import Environment from './Environment'; import Page from './Page'; import Header from './Header'; import Layout from './Layout'; import Styles from './Styles'; import Cover fr...
{ return ( <DndProvider backend={HTML5Backend}> <Formik initialValues={getInitValues()} onSubmit={onSubmit}> <Form> <Environment /> <Page /> <Header /> <Layout /> <Styles /> <Cover /> <Other /> <Metadata /> <Do...
identifier_body
App.tsx
import React from 'react'; import { Form, Formik, FormikHelpers } from 'formik'; import JSZip from 'jszip'; import FileSaver from 'file-saver'; import Environment from './Environment'; import Page from './Page'; import Header from './Header'; import Layout from './Layout'; import Styles from './Styles'; import Cover fr...
() { return ( <DndProvider backend={HTML5Backend}> <Formik initialValues={getInitValues()} onSubmit={onSubmit}> <Form> <Environment /> <Page /> <Header /> <Layout /> <Styles /> <Cover /> <Other /> <Metadata /> ...
App
identifier_name
App.tsx
import React from 'react'; import { Form, Formik, FormikHelpers } from 'formik'; import JSZip from 'jszip'; import FileSaver from 'file-saver'; import Environment from './Environment'; import Page from './Page';
import Metadata from './Metadata'; import Download from './Download'; import { getInitValues, toPluginModel, Values } from './common'; import Generator from '../../generator'; import { DndProvider } from 'react-dnd'; import { HTML5Backend } from 'react-dnd-html5-backend'; import { SaxonJS } from '../../types/saxon-js';...
import Header from './Header'; import Layout from './Layout'; import Styles from './Styles'; import Cover from './Cover'; import Other from './Other';
random_line_split
server.py
# Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
bject has no attribute 'wait_for_termination' # You can use the following code instead: # import time # while 1: # time.sleep(10) if __name__ == '__main__': main()
r' o
identifier_name
server.py
# Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
e # 服务端流模式(在一次调用中, 客户端只能一次向服务器传输数据, 但是服务器可以多次返回响应) # unary-stream (In a single call, the client can only transmit data to the server at one time, # but the server can return the response many times.) def ServerStreamingMethod(self, request, context): print("ServerStreamingMethod called by clien...
id=SERVER_ID, response_data="Python server ClientStreamingMethod ok") return respons
conditional_block
server.py
# Copyright 2019 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
# 服务端流模式(在一次调用中, 客户端只能一次向服务器传输数据, 但是服务器可以多次返回响应) # unary-stream (In a single call, the client can only transmit data to the server at one time, # but the server can return the response many times.) def ServerStreamingMethod(self, request, context): print("ServerStreamingMethod called by client(%...
y client(%d) the message: %s" % (request.client_id, request.request_data)) response = demo_pb2.Response( server_id=SERVER_ID, response_data="Python server SimpleMethod Ok!!!!") return response # 客户端流模式(在一次调用中, 客户端可以多次向服务器传输数据, 但是服务器只能返回一次响应) # stream-unary ...
identifier_body
server.py
# Copyright 2019 gRPC authors. #
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing ...
# 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
random_line_split
recipe_manager.py
import os from iotile.core.dev import ComponentRegistry from iotile.ship.recipe import RecipeObject from iotile.ship.exceptions import RecipeNotFoundError class RecipeManager: """A class that maintains a list of installed recipes and recipe actions. It allows fetching recipes by name and auotmatically buildi...
recipe_folder (str): The path to the folder of recipes to add. whitelist (list): Only include files whose os.basename() matches something on the whitelist """ if whitelist is not None: whitelist = set(whitelist) if recipe_folder == '': ...
Args:
random_line_split
recipe_manager.py
import os from iotile.core.dev import ComponentRegistry from iotile.ship.recipe import RecipeObject from iotile.ship.exceptions import RecipeNotFoundError class RecipeManager: """A class that maintains a list of installed recipes and recipe actions. It allows fetching recipes by name and auotmatically buildi...
def get_recipe(self, recipe_name): """Get a recipe by name. Args: recipe_name (str): The name of the recipe to fetch. Can be either the yaml file name or the name of the recipe. """ if recipe_name.endswith('.yaml'): recipe = self._recipes.ge...
"""Add additional valid recipe actions to RecipeManager args: recipe_actions (list): List of tuples. First value of tuple is the classname, second value of tuple is RecipeAction Object """ for action_name, action in recipe_actions: self._recipe_actions[a...
identifier_body
recipe_manager.py
import os from iotile.core.dev import ComponentRegistry from iotile.ship.recipe import RecipeObject from iotile.ship.exceptions import RecipeNotFoundError class RecipeManager: """A class that maintains a list of installed recipes and recipe actions. It allows fetching recipes by name and auotmatically buildi...
(self): self._recipe_actions = {} self._recipe_resources = {} self._recipes = {} reg = ComponentRegistry() for name, action in reg.load_extensions('iotile.recipe_action', product_name='build_step'): self._recipe_actions[name] = action for name, resource in ...
__init__
identifier_name
recipe_manager.py
import os from iotile.core.dev import ComponentRegistry from iotile.ship.recipe import RecipeObject from iotile.ship.exceptions import RecipeNotFoundError class RecipeManager: """A class that maintains a list of installed recipes and recipe actions. It allows fetching recipes by name and auotmatically buildi...
return recipe
raise RecipeNotFoundError("Could not find recipe", recipe_name=recipe_name, known_recipes=[x for x in self._recipes.keys()])
conditional_block
notify.rs
quick_error! { /// Error when waking up a connection /// /// In most cases it's okay to panic on this error #[derive(Debug)] pub enum WakeupError { /// I/O error when sending data to internal pipe /// /// We discard the io error as there no practical reason for this ...
use mio::Token; use mio::deprecated::Sender; use handler::{Notify};
random_line_split
notify.rs
use mio::Token; use mio::deprecated::Sender; use handler::{Notify}; quick_error! { /// Error when waking up a connection /// /// In most cases it's okay to panic on this error #[derive(Debug)] pub enum WakeupError { /// I/O error when sending data to internal pipe /// /// W...
(token: Token, channel: &Sender<Notify>) -> Notifier { Notifier { token: token, channel: channel.clone() } } impl Notifier { /// Wakeup a state machine /// /// pub fn wakeup(&self) -> Result<(), WakeupError> { use mio::deprecated::NotifyError::*; match self.chann...
create_notifier
identifier_name
poplog.py
import sys, datetime, os, time from mcstatus import MinecraftServer # GLOBALS # List containing all the mcstatus server objects serverList = [] # appendLog() polls the server for population data and appends it to the log # In: The hostname and population of a server, as well as the timestamp for its retrieval time # ...
# getPopulations() Gets all the populations of the servers and calls appendLog() for each # In: the list of servers # Out: Nada def getPopulations(): global serverList print("Oy") # Loop through all the servers for serverObject in serverList: status = serverObject.status() pop = status.players.online time...
fileName = host.replace(".", "")+ ".csv" with open(fileName, "a") as logFile: # If the file is empty add the column names if not os.stat(fileName).st_size > 0: logFile.write('"time","pop"') # Write the data to the file logFile.write("\n"+ '"'+ time+ '",'+ str(pop))
identifier_body
poplog.py
import sys, datetime, os, time from mcstatus import MinecraftServer # GLOBALS # List containing all the mcstatus server objects serverList = [] # appendLog() polls the server for population data and appends it to the log # In: The hostname and population of a server, as well as the timestamp for its retrieval time # ...
else: print("[mpl]", url, "not found! It will not be tracked.") while 1: getPopulations() time.sleep(300) # Run the main. main()
print("[mpl]", url, "was found!") serverList.append(serverObject)
conditional_block
poplog.py
import sys, datetime, os, time from mcstatus import MinecraftServer # GLOBALS # List containing all the mcstatus server objects serverList = [] # appendLog() polls the server for population data and appends it to the log # In: The hostname and population of a server, as well as the timestamp for its retrieval time # ...
for serverObject in serverList: status = serverObject.status() pop = status.players.online time = datetime.datetime.now().isoformat() appendLog(serverObject.host, time, pop) # Entry point. def main(): global serverList print("[mpl] Minecraft Population Logger") print("[mpl] Version 0.1.0") # No server U...
print("Oy") # Loop through all the servers
random_line_split
poplog.py
import sys, datetime, os, time from mcstatus import MinecraftServer # GLOBALS # List containing all the mcstatus server objects serverList = [] # appendLog() polls the server for population data and appends it to the log # In: The hostname and population of a server, as well as the timestamp for its retrieval time # ...
(): global serverList print("Oy") # Loop through all the servers for serverObject in serverList: status = serverObject.status() pop = status.players.online time = datetime.datetime.now().isoformat() appendLog(serverObject.host, time, pop) # Entry point. def main(): global serverList print("[mpl] Minec...
getPopulations
identifier_name
Session.ts
import * as Moment from "moment" import * as Lodash from "lodash" // import { ParameterBag } from "./ParameterBag" export interface sessionOptions { name?: string expires?: string | number | null | Moment.Moment path?: string domain?: string | Array<string> secure?: boolean httponly?: boolean }...
setup(options: sessionOptions): Session { // this.name = options.name || null this.setExpires(options.expires) this.setPath(options.path || null) this.setDomain(options.domain || null) this.setSecure(options.secure || null) this.setHttponly(options.httponly || null) ...
private secure: boolean | null private httponly: boolean | null
random_line_split
Session.ts
import * as Moment from "moment" import * as Lodash from "lodash" // import { ParameterBag } from "./ParameterBag" export interface sessionOptions { name?: string expires?: string | number | null | Moment.Moment path?: string domain?: string | Array<string> secure?: boolean httponly?: boolean }...
isSecure(): boolean | null { return this.secure } isHttponly(): boolean | null { return this.httponly } }
{ return this.domain }
identifier_body
Session.ts
import * as Moment from "moment" import * as Lodash from "lodash" // import { ParameterBag } from "./ParameterBag" export interface sessionOptions { name?: string expires?: string | number | null | Moment.Moment path?: string domain?: string | Array<string> secure?: boolean httponly?: boolean }...
(secure: boolean | null): Session { this.secure = secure return this } setHttponly(httponly: boolean | null): Session { this.httponly = httponly return this } getExpiresUnix(): number | void { if(this.getExpires() !== null) return Moment().add(<number>this.getEx...
setSecure
identifier_name
conf_fixture.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
self.conf.set_default('fatal_exception_format_errors', True) self.conf.set_default('enabled', True, 'osapi_v3') self.conf.set_default('force_dhcp_release', False) self.conf.set_default('periodic_enable', False) self.addCleanup(utils.cleanup_dns_managers) self.addCleanup(i...
super(ConfFixture, self).setUp() self.conf.set_default('api_paste_config', paths.state_path_def('etc/nova/api-paste.ini')) self.conf.set_default('host', 'fake-mini') self.conf.set_default('compute_driver', 'nova.virt.fake.SmallFakeDrive...
identifier_body
conf_fixture.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
(self): super(ConfFixture, self).setUp() self.conf.set_default('api_paste_config', paths.state_path_def('etc/nova/api-paste.ini')) self.conf.set_default('host', 'fake-mini') self.conf.set_default('compute_driver', 'nova.virt.fak...
setUp
identifier_name
conf_fixture.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
"""Fixture to manage global conf settings.""" def setUp(self): super(ConfFixture, self).setUp() self.conf.set_default('api_paste_config', paths.state_path_def('etc/nova/api-paste.ini')) self.conf.set_default('host', 'fake-mini') self.conf.set_default...
class ConfFixture(config_fixture.Config):
random_line_split
MetaEmail_test.js
import React from 'react'; import {shallow} from 'enzyme'; import { MetaEmail , Avatar , UserDetails} from '../MetaEmail'; describe('MetaEmail',() => { let metaEmail = null; beforeEach(() => { const sampleProps = { selected : false, unread : false, name : 'Test...
sample.unread = false; const Email3 = shallow(<MetaEmail {...sample} />); expect(Email1.props().className).toContain('email-item-selected'); expect(Email2.props().className).toContain('email-item-unread'); expect(Email2.props().className).not.toContain('email-item-selec...
const Email2 = shallow(<MetaEmail {...sample} />); sample.selected = false;
random_line_split
models.py
set with all partners who had at least one movement in this voucher. The function is expected to add more partners to this set. Then call `check_clearings` for all these partners. """ existing_mvts = self.movement_set.all() partners = set() # accounts = set() ...
random_line_split
models.py
get_template_groups`. if not voucher_type: return [] #~ print 20131006, voucher_type template_groups = [voucher_type.model.get_template_group()] return cls.get_template_choices(build_method, template_groups) # # # @dd.python_2_unicode_compatible class AccountingPeriod(Da...
def get_due_date(self): return self.entry_date def get_trade_type(self): return self.journal.trade_type def get_printed_name(self): return dd.babelattr(self.j
"""If user changes the :attr:`accounting_period`, then the `number` might need to change. """ self.number = self.journal.get_next_number(self)
identifier_body
models.py
('ref', width=6) class PaymentTerm(mixins.BabelNamed, mixins.Referrable): class Meta: app_label = 'ledger' verbose_name = _("Payment term") verbose_name_plural = _("Payment terms") days = models.IntegerField(_("Days"), default=0) months = models.IntegerField(_("Mo...
doit
identifier_name
models.py
else: self.dc = DEBIT # cannot be NULL if not self.name: self.name = self.id #~ if not self.pos: #~ self.pos = self.__class__.objects.all().count() + 1 super(Journal, self).full_clean(*args, **kw) def disable_voucher_delete(self, doc): ...
self.dc = self.account.type.dc
conditional_block
layout.py
# -*- coding: utf-8 -*- """ This scripts sets an initial layout for the ProEMOnline software. It uses the PyQtGraph dockarea system and was designed from the dockarea.py example. Contains: Left column: Observing Log Center column: Plots Right column: Images and Process Log Menu bar """ import pyqtgraph as pg from p...
ptr += 1 timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(50) d3.addWidget(w3) ## Smoothed Light Curve w4 = pg.PlotWidget(title="Dock 4 plot") w4.plot(np.random.normal(size=100)) d4.addWidget(w4) ## Image w5 = pg.ImageView() w5.ui.roiBtn.hide() w5.ui.normBtn.hide() displayframe(displayimg,autosc...
w3.enableAutoRange('xy', False) ## stop auto-scaling after the first data set is plotted
conditional_block
layout.py
# -*- coding: utf-8 -*- """ This scripts sets an initial layout for the ProEMOnline software. It uses the PyQtGraph dockarea system and was designed from the dockarea.py example. Contains: Left column: Observing Log Center column: Plots Right column: Images and Process Log Menu bar """ import pyqtgraph as pg from p...
"""Display an RBG image Autoscale optional. Return nothing. """ if autoscale: w5.setImage(displayimg,autoRange=True,levels=[np.min(displayimg),np.max(displayimg)-1]) else: w5.setImage(displayimg,autoRange=False,autoLevels=False) #Set up a list to keep track of star positions sta...
img,displayimg = newframe(fitsfile) #Use a function to display a new image #Autoscaling levels optional def displayframe(displayimg,autoscale=False):
random_line_split
layout.py
# -*- coding: utf-8 -*- """ This scripts sets an initial layout for the ProEMOnline software. It uses the PyQtGraph dockarea system and was designed from the dockarea.py example. Contains: Left column: Observing Log Center column: Plots Right column: Images and Process Log Menu bar """ import pyqtgraph as pg from p...
(self): fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home') #print str(fname) img = fits.getdata(str(fname))[0] w5.setImage(img) def closeEvent(self, event): reply = QtGui.QMessageBox.question(self, 'Message', ...
showDialog
identifier_name
layout.py
# -*- coding: utf-8 -*- """ This scripts sets an initial layout for the ProEMOnline software. It uses the PyQtGraph dockarea system and was designed from the dockarea.py example. Contains: Left column: Observing Log Center column: Plots Right column: Images and Process Log Menu bar """ import pyqtgraph as pg from p...
def initUI(self): #Note: Exit is protected on Mac. This may work on Windows. exitAction = QtGui.QAction('Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.showDialog) ...
super(WithMenu, self).__init__() self.initUI()
identifier_body
test_complex.py
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. import unittest from iptest.type_util import * from iptest import run_test class ComplexTest(unittest.TestCase...
(self): # complex from string: negative # - space related l = ['1.2', '.3', '4e3', '.3e-4', "0.031"] for x in l: for y in l: self.assertRaises(ValueError, complex, "%s +%sj" % (x, y)) self.assertRaises(ValueError, complex, "%s+ %sj" % (x, y)) ...
test_from_string
identifier_name
test_complex.py
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. import unittest from iptest.type_util import * from iptest import run_test class ComplexTest(unittest.TestCase...
self.assertEqual(complex(" %s+%sj" % (x, y)), complex(" %s+%sj " % (x, y))) def test_misc(self): self.assertEqual(mycomplex(), complex()) a = mycomplex(1) b = mycomplex(1,0) c = complex(1) d = complex(1,0) for x in [a,b,c,d]: for y in ...
random_line_split
test_complex.py
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. import unittest from iptest.type_util import * from iptest import run_test class ComplexTest(unittest.TestCase...
def test_inherit(self): class mycomplex(complex): pass a = mycomplex(2+1j) self.assertEqual(a.real, 2) self.assertEqual(a.imag, 1) def test_repr(self): self.assertEqual(repr(1-6j), '(1-6j)') def test_infinite(self): self.assertEqual(repr(1.0e340j), 'in...
self.assertEqual(mycomplex(), complex()) a = mycomplex(1) b = mycomplex(1,0) c = complex(1) d = complex(1,0) for x in [a,b,c,d]: for y in [a,b,c,d]: self.assertEqual(x,y) self.assertEqual(a ** 2, a) self.assertEqual(a-complex(), a) ...
identifier_body
test_complex.py
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. import unittest from iptest.type_util import * from iptest import run_test class ComplexTest(unittest.TestCase...
self.assertEqual(a ** 2, a) self.assertEqual(a-complex(), a) self.assertEqual(a+complex(), a) self.assertEqual(complex()/a, complex()) self.assertEqual(complex()*a, complex()) self.assertEqual(complex()%a, complex()) self.assertEqual(complex() // a, complex()) ...
for y in [a,b,c,d]: self.assertEqual(x,y)
conditional_block
ko.ts
export default { badge: '배지', close: '닫기', dataIterator: { noResultsText: '일치하는 항목이 없습니다.', loadingText: '불러오는 중...', }, dataTable: { itemsPerPageText: '페이지 당 행 수:', ariaLabel: { sortDescending: '내림차순 정렬.', sortAscending: '오름차순 정렬.', sortNone: '정렬하지 않음.', activateNone: ...
next: '다음 화면', ariaLabel: { delimiter: 'Carousel slide {0} of {1}', }, }, calendar: { moreEvents: '{0} 더보기', }, fileInput: { counter: '{0} files', counterSize: '{0} files ({1} in total)', }, timePicker: { am: '오전', pm: '오후', }, pagination: { ariaLabel: { w...
prevYearAriaLabel: '전년도', }, noDataText: '데이터가 없습니다.', carousel: { prev: '이전 화면',
random_line_split
physical-layer-full-transmit.js
// Copyright (c) 2015-2018 Robert Rypuła - https://audio-network.rypula.pl function transmitSymbol(channelIndex, ofdmIndex, symbol) { var pskSize = getIntById('tx-psk-size-' + channelIndex), symbolDuration = getFloatById('symbol-duration') / 1000 ; transmitAdapter.symbol(channelIndex, ofd...
channelIndex) { transmitAdapter.synchronization(channelIndex); }
ransmitSynchronization(
identifier_name
physical-layer-full-transmit.js
// Copyright (c) 2015-2018 Robert Rypuła - https://audio-network.rypula.pl function transmitSymbol(channelIndex, ofdmIndex, symbol) { var pskSize = getIntById('tx-psk-size-' + channelIndex), symbolDuration = getFloatById('symbol-duration') / 1000 ; transmitAdapter.symbol(channelIndex, ofd...
transmitAdapter.packet(channelIndex, data, syncPreamble, pskSize, symbolDuration, guardInterval, interpacketGap, amplitude); } function transmitSynchronization(channelIndex) { transmitAdapter.synchronization(channelIndex); }
symbolList = dataList[i].split('.'); symbolListParsed = []; for (j = 0; j < symbolList.length; j++) { mute = symbolList[j] === '-'; symbol = mute ? null : parseInt(symbolList[j]); if (i === 0) { amplitude.push(getFloatById('tx-amplitude-input...
conditional_block
physical-layer-full-transmit.js
// Copyright (c) 2015-2018 Robert Rypuła - https://audio-network.rypula.pl function transmitSymbol(channelIndex, ofdmIndex, symbol) { var pskSize = getIntById('tx-psk-size-' + channelIndex), symbolDuration = getFloatById('symbol-duration') / 1000 ; transmitAdapter.symbol(channelIndex, ofd...
symbolList = dataList[i].split('.'); symbolListParsed = []; for (j = 0; j < symbolList.length; j++) { mute = symbolList[j] === '-'; symbol = mute ? null : parseInt(symbolList[j]); if (i === 0) { amplitude.push(getFloatById('tx-amplitude-input-...
for (i = 0; i < dataList.length; i++) {
random_line_split
physical-layer-full-transmit.js
// Copyright (c) 2015-2018 Robert Rypuła - https://audio-network.rypula.pl function transmitSymbol(channelIndex, ofdmIndex, symbol) { var pskSize = getIntById('tx-psk-size-' + channelIndex), symbolDuration = getFloatById('symbol-duration') / 1000 ; transmitAdapter.symbol(channelIndex, ofd...
transmitAdapter.synchronization(channelIndex); }
identifier_body
mBlock.js
/** * mBlock // 实现与web通讯 * |----menu.js //菜单:构造、刷新 * |----project.js //项目文件:创建、保存、加载 * |----translator.js //多国语言 * |----boards.js //控制板 * |----serial.js //USB串口通讯 * |----hid.js //无线2.4G串口通讯 * |----autoupdater.js //自动更新 */ const {ipcMain,dialog,BrowserWindow,MenuItem,Menu,app} = require(...
ipcMain.on('itemDeleted', function(event, arg) { _menu.enableUnDelete(); }); // 保存收藏表情面板文件 ipcMain.on('saveDrawFile', function (event, arg) { _emotions.save(arg.fileName, arg.data); }); // 删除表情面板文件 ipcMain.on('deleteDrawFile', function (event, arg) { _emotions.del(arg.fileName); }); // 读取表...
ipcMain.on('changeArduinoStageMode', function(event, bool) { _stage.onlyChangeArduinoStageMode(bool); });
random_line_split
mBlock.js
/** * mBlock // 实现与web通讯 * |----menu.js //菜单:构造、刷新 * |----project.js //项目文件:创建、保存、加载 * |----translator.js //多国语言 * |----boards.js //控制板 * |----serial.js //USB串口通讯 * |----hid.js //无线2.4G串口通讯 * |----autoupdater.js //自动更新 */ const {ipcMain,dialog,BrowserWindow,MenuItem,Menu,app} = require(...
}); ipcMain.on('fullscreen',function(event,arg){ var win = BrowserWindow.getFocusedWindow(); win.setFullScreen(arg); }) ipcMain.on('package',function(event,arg){ if(_serial.isConnected()){ _serial.send(arg.data); } if(_hid.isConnected()){ _hid.send(arg.data); } if(_bluetooth.isConnected()){ _...
client = event.sender; _localStorage = new LocalStorage(); _translator = new Translator(self); _fontSize = new FontSize(self); _serial = new Serial(self); _boards = new Boards(self); _stage = new Stage(self); _hid = new HID(self); _bluetooth = new Bluetooth(self); _project = new Project(self); ...
identifier_body
mBlock.js
/** * mBlock // 实现与web通讯 * |----menu.js //菜单:构造、刷新 * |----project.js //项目文件:创建、保存、加载 * |----translator.js //多国语言 * |----boards.js //控制板 * |----serial.js //USB串口通讯 * |----hid.js //无线2.4G串口通讯 * |----autoupdater.js //自动更新 */ const {ipcMain,dialog,BrowserWindow,MenuItem,Menu,app} = require(...
_client = event.sender; _localStorage = new LocalStorage(); _translator = new Translator(self); _fontSize = new FontSize(self); _serial = new Serial(self); _boards = new Boards(self); _stage = new Stage(self); _hid = new HID(self); _bluetooth = new Bluetooth(self); _project = new Project(self);...
dy")
identifier_name
sandboxSignalMapper.py
from PyQt4 import QtGui, QtCore class Window(QtGui.QMainWindow): def __init__(self):
def handleButton(self, identifier): if identifier == 'One': text = 'Do This' elif identifier == 'Two': text = 'Do That' elif identifier == 'Three': text = 'Do Other' self.edit.setText(text) if __name__ == '__main__': import sys app = Qt...
QtGui.QMainWindow.__init__(self) self.mapper = QtCore.QSignalMapper(self) self.toolbar = self.addToolBar('Foo') self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) for text in 'One Two Three'.split(): action = QtGui.QAction(text, self) self.mapper.setMap...
identifier_body
sandboxSignalMapper.py
from PyQt4 import QtGui, QtCore class Window(QtGui.QMainWindow): def
(self): QtGui.QMainWindow.__init__(self) self.mapper = QtCore.QSignalMapper(self) self.toolbar = self.addToolBar('Foo') self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) for text in 'One Two Three'.split(): action = QtGui.QAction(text, self) se...
__init__
identifier_name
sandboxSignalMapper.py
from PyQt4 import QtGui, QtCore class Window(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.mapper = QtCore.QSignalMapper(self) self.toolbar = self.addToolBar('Foo') self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) for text in 'One...
import sys app = QtGui.QApplication(sys.argv) window = Window() window.resize(300, 60) window.show() sys.exit(app.exec_())
conditional_block
sandboxSignalMapper.py
from PyQt4 import QtGui, QtCore class Window(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) self.mapper = QtCore.QSignalMapper(self) self.toolbar = self.addToolBar('Foo') self.toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextOnly) for text in 'One...
text = 'Do That' elif identifier == 'Three': text = 'Do Other' self.edit.setText(text) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = Window() window.resize(300, 60) window.show() sys.exit(app.exec_())
def handleButton(self, identifier): if identifier == 'One': text = 'Do This' elif identifier == 'Two':
random_line_split
regress_determinants_ticpe.py
# -*- coding: utf-8 -*- """ Created on Tue Sep 22 09:47:41 2015 @author: thomas.douenne """ from __future__ import division import statsmodels.formula.api as smf from openfisca_france_indirect_taxation.examples.utils_example import simulate_df_calee_by_grosposte if __name__ == '__main__': import logging lo...
data = data_for_reg).fit() print regression_essence.summary() # It is tempting to add a variable 'vehicule'. However, I think it is a case of bad control. It captures part # of the effect we actually want to estimate.
regression_essence = smf.ols(formula = 'part_essence ~ \ decile_1 + decile_2 + decile_3 + decile_4 + decile_5 + decile_6 + decile_7 + decile_8 + decile_9 + \ rural + petite_villes + grandes_villes + agglo_paris + \ nenfants + nadultes + travaille',
random_line_split
regress_determinants_ticpe.py
# -*- coding: utf-8 -*- """ Created on Tue Sep 22 09:47:41 2015 @author: thomas.douenne """ from __future__ import division import statsmodels.formula.api as smf from openfisca_france_indirect_taxation.examples.utils_example import simulate_df_calee_by_grosposte if __name__ == '__main__':
for year in [2005]: data_for_reg = simulate_df_calee_by_grosposte(simulated_variables = simulated_variables, year = year) # In 2005 3 people consume fuel while their rev_disp_loyerimput is 0. Creates inf number in part_carburants data_for_reg = data_for_reg[data_for_reg['rev_disp_loyerimput'] > 0] ...
import logging log = logging.getLogger(__name__) import sys logging.basicConfig(level = logging.INFO, stream = sys.stdout) simulated_variables = [ 'pondmen', 'revtot', 'rev_disp_loyerimput', 'depenses_carburants', 'depenses_essence', 'depenses_diesel', ...
conditional_block
ln.rs
ARGO_PKG_VERSION"); pub struct Settings { overwrite: OverwriteMode, backup: BackupMode, suffix: String, symbolic: bool, target_dir: Option<String>, no_target_dir: bool, verbose: bool, } #[derive(Clone, Debug, Eq, PartialEq)] pub enum OverwriteMode { NoClobber, Interactive, Forc...
{ NoBackup, SimpleBackup, NumberedBackup, ExistingBackup, } pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("b", "", "make a backup of each file that would otherwise be overwritten or removed"); opts.optflagopt("", "backup", "make a backup of...
BackupMode
identifier_name
ln.rs
"); opts.optopt("t", "target-directory", "specify the DIRECTORY in which to create the links", "DIRECTORY"); opts.optflag("T", "no-target-directory", "treat LINK_NAME as a normal file always"); opts.optflag("v", "verbose", "print name of each linked file"); opts.optflag("h", "help", "display this help a...
{ match fs::symlink_metadata(path) { Ok(m) => m.file_type().is_symlink(), Err(_) => false } }
identifier_body
ln.rs
"remove existing destination files"); opts.optflag("i", "interactive", "prompt whether to remove existing destination files"); // TODO: opts.optflag("L", "logical", "dereference TARGETs that are symbolic links"); // TODO: opts.optflag("n", "no-dereference", "treat LINK_NAME as a normal file if it is a symb...
random_line_split
canpyY.py
#!/usr/bin/python """ Create Y matrix for Canopy. This is the connection between the SNAs and CNVs """ import sys Wm = open(sys.argv[1]) Wm.readline() cnvs = list() header = list() header.append("non-cna_region") for i in Wm:
Wm.close() X = open(sys.argv[2]) X.readline() print "\t".join(header) for i in X: sna = i.split()[0] chrx, pos, alt = sna.split("_") pos = int(pos) out = list() out.append(sna) out.append("0") # non-cna_region ok = False for j in cnvs: if chrx == j[0] and j[1] < pos and j[2] > pos: out.append("1") ok ...
region = i.split()[0] (chrx, start, end) = region.split("_") cnvs.append((chrx, int(start), int(end))) header.append(region)
conditional_block
canpyY.py
#!/usr/bin/python """ Create Y matrix for Canopy. This is the connection between the SNAs and CNVs """ import sys Wm = open(sys.argv[1]) Wm.readline() cnvs = list() header = list() header.append("non-cna_region") for i in Wm: region = i.split()[0] (chrx, start, end) = region.split("_") cnvs.append((chrx, int(s...
print "\t".join(header) for i in X: sna = i.split()[0] chrx, pos, alt = sna.split("_") pos = int(pos) out = list() out.append(sna) out.append("0") # non-cna_region ok = False for j in cnvs: if chrx == j[0] and j[1] < pos and j[2] > pos: out.append("1") ok = True else: out.append("0") if not ok: ...
X.readline()
random_line_split
hooks.py
from rsqueakvm.util.cells import QuasiConstant from rsqueakvm.plugins.vmdebugging.model import wrap_oplist, wrap_greenkey, wrap_debug_info from rpython.rlib.jit import JitHookInterface, Counters jit_iface_recursion = QuasiConstant(False) def make_hook(args, func): import inspect, re src = "\n".join([ ...
def before_compile(self, debug_info): pass def before_compile_bridge(self, debug_info): pass jitiface = JitIface()
self._compile_hook(debug_info, is_bridge=True)
identifier_body
hooks.py
from rsqueakvm.util.cells import QuasiConstant from rsqueakvm.plugins.vmdebugging.model import wrap_oplist, wrap_greenkey, wrap_debug_info from rpython.rlib.jit import JitHookInterface, Counters jit_iface_recursion = QuasiConstant(False) def make_hook(args, func): import inspect, re src = "\n".join([ ...
(self, jitdriver, debug_info, is_bridge): space = self.space return [ space.wrap_string('compile_loop' if not is_bridge else 'compile_bridge'), wrap_debug_info(space, debug_info, is_bridge=is_bridge)] wrapped_compiled_hook = make_hook( "self, jitdriver, debug_info, i...
prepare_compile_hook
identifier_name
hooks.py
from rsqueakvm.util.cells import QuasiConstant from rsqueakvm.plugins.vmdebugging.model import wrap_oplist, wrap_greenkey, wrap_debug_info from rpython.rlib.jit import JitHookInterface, Counters jit_iface_recursion = QuasiConstant(False) def make_hook(args, func): import inspect, re src = "\n".join([ ...
def after_compile(self, debug_info): self._compile_hook(debug_info, is_bridge=False) def after_compile_bridge(self, debug_info): self._compile_hook(debug_info, is_bridge=True) def before_compile(self, debug_info): pass def before_compile_bridge(self, debug_info): pass jitiface = JitIface()
random_line_split
bootstrap-formhelpers-countries.en_US.js
the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or impl...
'EG': 'Egypt', 'SV': 'El Salvador', 'GQ': 'Equatorial Guinea', 'ER': 'Eritrea', 'EE': 'Estonia', 'ET': 'Ethiopia', 'FO': 'Faeroe Islands', 'FK': 'Falkland Islands', 'FJ': 'Fiji', 'FI': 'Finland', 'MK': 'Former Yugoslav Republic of Macedonia', 'FR': 'France', 'FX': 'France, Metropolitan', 'GF...
'DJ': 'Djibouti', 'DM': 'Dominica', 'DO': 'Dominican Republic', 'TP': 'East Timor', 'EC': 'Ecuador',
random_line_split
derivable.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */
use std::fmt::Debug; use anyhow::Result; use async_trait::async_trait; use context::CoreContext; use futures::future::try_join; use futures::stream::{self, StreamExt, TryStreamExt}; use mononoke_types::{BonsaiChangeset, ChangesetId}; use crate::context::DerivationContext; use derived_data_service_if::types::DerivedD...
use std::any::TypeId; use std::collections::{HashMap, HashSet};
random_line_split
derivable.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::any::TypeId; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use anyhow::Result; use async_trait::async_trait; use...
else { Rest::check_dependencies(ctx, derivation_ctx, csid, visited).await } } } #[macro_export] macro_rules! dependencies { () => { () }; ($dep:ty) => { ( $dep , () ) }; ($dep:ty, $( $rest:tt )*) => { ( $dep , dependencies!($( $rest )*) ) }; }
{ try_join( derivation_ctx.fetch_dependency::<Derivable>(ctx, csid), Rest::check_dependencies(ctx, derivation_ctx, csid, visited), ) .await?; Ok(()) }
conditional_block
derivable.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::any::TypeId; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use anyhow::Result; use async_trait::async_trait; use...
( ctx: &CoreContext, derivation_ctx: &DerivationContext, changeset_ids: &[ChangesetId], ) -> Result<HashMap<ChangesetId, Self>> { stream::iter(changeset_ids.iter().copied().map(|csid| async move { let maybe_derived = Self::fetch(ctx, derivation_ctx, csid).await?; ...
fetch_batch
identifier_name
derivable.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::any::TypeId; use std::collections::{HashMap, HashSet}; use std::fmt::Debug; use anyhow::Result; use async_trait::async_trait; use...
} #[macro_export] macro_rules! dependencies { () => { () }; ($dep:ty) => { ( $dep , () ) }; ($dep:ty, $( $rest:tt )*) => { ( $dep , dependencies!($( $rest )*) ) }; }
{ let type_id = TypeId::of::<Derivable>(); if visited.insert(type_id) { try_join( derivation_ctx.fetch_dependency::<Derivable>(ctx, csid), Rest::check_dependencies(ctx, derivation_ctx, csid, visited), ) .await?; Ok(()) ...
identifier_body
xkl_wrapper.py
of keyboard layouts settings. """ import threading import gettext from gi.repository import GdkX11, Xkl from collections import namedtuple from pyanaconda import flags from pyanaconda import iutil from pyanaconda.constants import DEFAULT_KEYBOARD from pyanaconda.keyboard import join_layout_variant, parse_layout_var...
(self, c_reg, item, subitem, country): if subitem: name = item.get_name() + " (" + subitem.get_name() + ")" description = subitem.get_description() else: name = item.get_name() description = item.get_description() # if the layout was not added wit...
_get_country_variant
identifier_name
xkl_wrapper.py
keyboard layouts settings. """ import threading import gettext from gi.repository import GdkX11, Xkl from collections import namedtuple from pyanaconda import flags from pyanaconda import iutil from pyanaconda.constants import DEFAULT_KEYBOARD from pyanaconda.keyboard import join_layout_variant, parse_layout_varian...
else: lang = iutil.upcase_first_letter(layout_info.lang) description = layout_info.desc if with_lang and lang and not description.startswith(lang): return "%s (%s)" % (lang, description) else: return description def get_switch_opt_descriptio...
lang = iutil.upcase_first_letter(iso_(layout_info.lang).decode("utf-8")) description = Xkb_(layout_info.desc).decode("utf-8")
conditional_block
xkl_wrapper.py
of keyboard layouts settings. """ import threading import gettext from gi.repository import GdkX11, Xkl from collections import namedtuple from pyanaconda import flags from pyanaconda import iutil from pyanaconda.constants import DEFAULT_KEYBOARD from pyanaconda.keyboard import join_layout_variant, parse_layout_var...
variant = self._rec.variants[cur_group] except IndexError: # X server may have forgotten to add the "" variant for its default layout variant = "" self._engine.stop_listen(Xkl.EngineListenModes.TRACK_KEYBOARD_STATE) return join_layout_variant(layout, variant...
""" Get current activated X layout and variant :return: current activated X layout and variant (e.g. "cz (qwerty)") """ # ported from the widgets/src/LayoutIndicator.c code self._engine.start_listen(Xkl.EngineListenModes.TRACK_KEYBOARD_STATE) state = self._engine.get_c...
identifier_body
xkl_wrapper.py
of keyboard layouts settings. """ import threading import gettext from gi.repository import GdkX11, Xkl from collections import namedtuple from pyanaconda import flags from pyanaconda import iutil from pyanaconda.constants import DEFAULT_KEYBOARD from pyanaconda.keyboard import join_layout_variant, parse_layout_var...
""" # translate the description of the switching option return Xkb_(self._switch_opt_infos[switch_opt]) @gtk_action_wait def activate_default_layout(self): """ Activates default layout (the first one in the list of configured layouts). """ self...
:param switch_opt: switching option name/ID (e.g. 'grp:alt_shift_toggle') :type switch_opt: str :return: description of the layout switching option (e.g. 'Alt + Shift') :rtype: str
random_line_split
webglprogram.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
let (sender, receiver) = ipc::channel().unwrap(); self.renderer .send(CanvasMsg::WebGL(CanvasWebGLMsg::GetAttribLocation(self.id, String::from(name), sender))) .unwrap(); Ok(receiver.recv().unwrap()) } /// glGetUniformLocation pub fn get_uniform_location(&s...
{ return Ok(None); }
conditional_block
webglprogram.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
/// glLinkProgram pub fn link(&self) { self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::LinkProgram(self.id))).unwrap(); } /// glUseProgram pub fn use_program(&self) { self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::UseProgram(self.id))).unwrap(); } /// glAttachSha...
{ if !self.is_deleted.get() { self.is_deleted.set(true); let _ = self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteProgram(self.id))); } }
identifier_body
webglprogram.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
{ webgl_object: WebGLObject, id: u32, is_deleted: Cell<bool>, fragment_shader: MutNullableHeap<JS<WebGLShader>>, vertex_shader: MutNullableHeap<JS<WebGLShader>>, #[ignore_heap_size_of = "Defined in ipc-channel"] renderer: IpcSender<CanvasMsg>, } impl WebGLProgram { fn new_inherited(ren...
WebGLProgram
identifier_name
webglprogram.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
// shader. if shader_slot.get().is_some() { return Err(WebGLError::InvalidOperation); } shader_slot.set(Some(shader)); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::AttachShader(self.id, shader.id()))).unwrap(); Ok(()) } /// glBindAttribLocat...
}; // TODO(ecoal95): Differentiate between same shader already assigned and other previous
random_line_split
views.py
import datetime import six try: from django.contrib.sites.requests import RequestSite except ImportError: # Django < 1.9 from django.contrib.sites.models import RequestSite from django.core.exceptions import ObjectDoesNotExist from django.core.serializers.json import DjangoJSONEncoder from django.forms.model...
def detail(request, event_id): if request.META.get('HTTP_ACCEPT') == 'application/json': return jsonDetail(request, event_id) e = get_object_or_404(Event, pk=event_id) context = {'event': e} return render(request, 'event.html', context) def post_event(request): if request.method == 'PO...
try: e = Event.objects.get(id=event_id) e.tags = e.tags.split() return model_to_dict(e) except ObjectDoesNotExist: raise HttpError('Event matching query does not exist', status=404)
identifier_body
views.py
import datetime import six try: from django.contrib.sites.requests import RequestSite except ImportError: # Django < 1.9 from django.contrib.sites.models import RequestSite from django.core.exceptions import ObjectDoesNotExist from django.core.serializers.json import DjangoJSONEncoder from django.forms.model...
else: result.append(x.as_dict()) return result
result.append(x.as_dict())
conditional_block
views.py
import datetime import six try: from django.contrib.sites.requests import RequestSite except ImportError: # Django < 1.9 from django.contrib.sites.models import RequestSite from django.core.exceptions import ObjectDoesNotExist from django.core.serializers.json import DjangoJSONEncoder from django.forms.model...
if tags is not None: tags = request.GET.get('tags').split(' ') result = [] for x in Event.find_events(time_from, time_until, tags=tags, set_operation=set_operation): # django-tagging's with_intersection() returns matches with unknown tags # this is a workaround to ensure we only re...
tags = request.GET.get('tags')
random_line_split
views.py
import datetime import six try: from django.contrib.sites.requests import RequestSite except ImportError: # Django < 1.9 from django.contrib.sites.models import RequestSite from django.core.exceptions import ObjectDoesNotExist from django.core.serializers.json import DjangoJSONEncoder from django.forms.model...
(request): if request.GET.get('from') is not None: time_from = parseATTime(request.GET['from']) else: time_from = epoch_to_dt(0) if request.GET.get('until') is not None: time_until = parseATTime(request.GET['until']) else: time_until = now() set_operation = request....
fetch
identifier_name
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} Named(ref fields) => { let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span)) }).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_...
{ let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); cx.expr_call_ident(trait_span, substr.type_ident, exprs) }
conditional_block
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
}) }; trait_def.expand(cx, mitem, item, push) } fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let default_ident = vec!( cx.ident_of("std"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ...
{ let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: Path::new(vec!("std", "default", "Default")), additional_bounds: Vec::new(), generics: ...
identifier_body
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
use ast::{MetaItem, Item, Expr}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; use ext::deriving::generic::ty::*; use parse::token::InternedString; use ptr::P; pub fn expand_deriving_default<F>(cx: &mut ExtCtxt, span: Span, ...
random_line_split
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
<F>(cx: &mut ExtCtxt, span: Span, mitem: &MetaItem, item: &Item, push: F) where F: FnOnce(P<Item>), { let inline = cx.meta_word(span, InternedString::new("inline")); let at...
expand_deriving_default
identifier_name
holidays.js
angular.module('bhima.controllers') .controller('HolidayManagementController', HolidayManagementController); HolidayManagementController.$inject = [ 'HolidayService', 'ModalService', 'NotifyService', 'uiGridConstants', '$state', ]; /** * Holiday Management Controller * * This controller is about the Holiday mana...
function loadHolidays() { vm.loading = true; Holidays.read(null, { detailed : 1 }) .then(function (data) { vm.gridOptions.data = data; }) .catch(Notify.handleError) .finally(function () { vm.loading = false; }); } // switch to delete warning mode function deleteHoliday(...
vm.filterEnabled = !vm.filterEnabled; vm.gridOptions.enableFiltering = vm.filterEnabled; vm.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN); }
random_line_split
holidays.js
angular.module('bhima.controllers') .controller('HolidayManagementController', HolidayManagementController); HolidayManagementController.$inject = [ 'HolidayService', 'ModalService', 'NotifyService', 'uiGridConstants', '$state', ]; /** * Holiday Management Controller * * This controller is about the Holiday mana...
Holidays.delete(title.id) .then(function () { Notify.success('FORM.LABELS.DELETED'); loadHolidays(); }) .catch(Notify.handleError); }); } // update an existing Holiday function editHoliday(title) { $state.go('holidays.edit', { id : title.id }); } loadHoliday...
{ return; }
conditional_block