query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
count no of half nodes via level order traversal | def count_half_nodes(self):
queue = [self]
half_nodes = 0
half = False
while queue:
curr_node = queue.pop(0)
if curr_node.left:
queue.append(curr_node.left)
half = not half
if curr_node.right:
q... | [
"def countFullNodes(self, root):\n if not root:\n return 0\n h = 0\n while root.left:\n h += 1\n root = root.left\n return 2 ** h - 1",
"def count_nodes(self):\n if self.is_empty():\n return 0\n elif self.is_leaf():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A metaphorical superclass for various card factory functions. | def card_factory(rank,suit):
pass | [
"def create_card():\n card = Card(*ask_for_card_info())\n return card",
"def __init__(self, generic=True):\n if generic:\n self.create_std_deck()",
"def __init__(self,interface):\n self.interface = interface\n\n # Make the standard card deck\n self.deck = Deck(False)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method import all data files and collect them in one big dictionary, every key is a cell, and contains the data for this cell for all time_points | def createDictBase(self):
#allFiles = glob.glob(self.path + "/*"+ self.filetype)
#data = pd.read_excel(allFiles[0])
#==================================================================================================================
# self.list_files = self.Files_to_import()
# data=pd.r... | [
"def read_data(filepaths):\n df_all = []\n for filename in filepaths:\n gpx_file = open(filename, 'r')\n gpx = gpxpy.parse(gpx_file)\n # check that data is all in .points attribute of first segment and first track\n print(filename)\n #print(len(gpx.tracks))\n if (len(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method gives a possibility to us to export the data directly to the dataBase Sqlite3 | def FrameBase_to_Sqlite(self):
sql3 = Sql3(self.dataFRAME) # we import the created from us class Sql3 to add the data
sql3.sql_write() # very simple and easy | [
"def loadToSqlite(self, data):\n conn = sqlite3.connect('myDb.db')\n c = conn.cursor()\n #Delete table if already exists\n c.execute('''DROP TABLE IF EXISTS orders''')\n #Create table\n c.execute('''CREATE TABLE orders (MATERIAL text, COORDER text, DOC_NUMBER text, S_ORD_IT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method checks how many experiments are given and create a key for this experiment with the data for it in a Experimets dictionary | def exper(self):
self.dbase.pop('time') # since we do not want the time data to be included in our calculation we drop it out.
ind=list(zip(self.start, self.stop)) # here I recomend to Google; 'zip , list python' to understand what is going on :)
Experiments={} #... | [
"def _get_experiments_dictionary(self):\n\n system_dictionary = self._get_system_dictionary()\n system_key = next(iter(system_dictionary))\n\n protocol_dictionary = self._get_protocol_dictionary()\n protocol_key = next(iter(protocol_dictionary))\n\n return {\"system\": system_key,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method combines the previuos two methods exper and ReplicaStats end returns a list with means and std for each and every replicate | def Means_Stds(self):
self.means=[] # list taking care for the means of ll experiments
self.stds=[] # list taking care fro the Stds of all experiments
for replica in self.exper(): # remember self.exper, from above returns ListExperiments
mean, Std = self._ReplicaStats(replica.T)... | [
"def get_summarized_results(self):\n stats = [v.stats() for (k, v) in self.examples.items() if v.is_ready()]\n res = self.ExampleClass.average_stats(stats)\n\n res['loss'] = self.loss/self.loss_cnt\n res['recent_loss'] = sum(self.recent_loss_array) / sum(self.recent_loss_bs_array)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
On fit, a distribution is created for each column along the covariance and means | def test_fit_default_distribution(self):
copula = GaussianMultivariate(GaussianUnivariate)
copula.fit(self.data)
for i, key in enumerate(self.data.columns):
assert copula.columns[i] == key
assert copula.univariates[i].__class__ == GaussianUnivariate
assert c... | [
"def test_fit_distribution_arg(self):\n # Setup\n distribution = 'copulas.univariate.gaussian_kde.GaussianKDE'\n copula = GaussianMultivariate(distribution=distribution)\n\n # Run\n copula.fit(self.data)\n\n # Check\n assert copula.distribution == 'copulas.univariate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
On fit, the distributions for each column use instances of copula.distribution. | def test_fit_distribution_arg(self):
# Setup
distribution = 'copulas.univariate.gaussian_kde.GaussianKDE'
copula = GaussianMultivariate(distribution=distribution)
# Run
copula.fit(self.data)
# Check
assert copula.distribution == 'copulas.univariate.gaussian_kde.... | [
"def test_fit_default_distribution(self):\n\n copula = GaussianMultivariate(GaussianUnivariate)\n copula.fit(self.data)\n\n for i, key in enumerate(self.data.columns):\n assert copula.columns[i] == key\n assert copula.univariates[i].__class__ == GaussianUnivariate\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Probability_density computes probability for the given values. | def test_probability_density(self):
# Setup
copula = GaussianMultivariate(GaussianUnivariate)
copula.fit(self.data)
X = np.array([2000., 200., 0.])
expected_result = 0.032245296420409846
# Run
result = copula.probability_density(X)
# Check
assert... | [
"def probability_density(self, X):\n raise NotImplementedError",
"def f_density(values):\n return map(lambda value: value/values.sum(), values)",
"def prob_density_func(xs,norm=True,data_range='data'):\n if data_range=='data':\n dist_keys = set(xs)\n elif data_range=='ext_data':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gaussian copula can sample after being fit with a constant column. This process will raise warnings when computing the covariance matrix | def test_sample_constant_column(self):
# Setup
instance = GaussianMultivariate()
X = np.array([
[1.0, 2.0],
[1.0, 3.0],
[1.0, 4.0],
[1.0, 5.0]
])
instance.fit(X)
# Run
result = instance.sample(5)
# Check
... | [
"def test_check_reg_covar(self):\n x = ds.array([[0, 0], [0, 1], [1, 0]], block_size=(3, 2))\n with self.assertRaises(ValueError):\n gm = GaussianMixture(reg_covar=-0.1)\n gm.fit(x)",
"def extract_covariance(self, block):\n raise RuntimeError(\"You need to implement the ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The User cannot create a month that already exist. | def clean(self, *args, **kwargs):
name = self.cleaned_data.get('name')
if name in Month.objects.values_list('name', flat=True):
raise forms.ValidationError(f"The month of {name} already exist")
return super(MonthForm, self).clean(*args, **kwargs) | [
"def create_month(month):\n month = str(month)\n try:\n m = Month.objects.get(month_number=month)\n except ObjectDoesNotExist:\n # if object doesn't exist, create a new one\n m = Month(month_number=month)\n m.save()\n \n return m",
"def add_defined_month_expense(message)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the help file | def test_help(self):
help_file = os.path.join(cwd, indir, "r5json_help")
help_text = StringIO()
with redirect_stdout(help_text):
with self.assertRaises(HelpPrinted):
main(["--help"])
if os.path.exists(help_file):
with open(help_file) as f:
... | [
"def test_help(self):\n help_file = os.path.join(cwd, indir, \"rdfc_help\")\n help_text = StringIO()\n with redirect_stdout(help_text):\n with self.assertRaises(HelpPrinted):\n main([\"--help\"])\n if os.path.exists(help_file):\n with open(help_file) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download fname from the FHIR server and save it in target_directory if necessary. If it already exists, just use it | def from_web(self, fname: str, typ: str, target_directory: str) -> str:
target = os.path.join(target_directory, fname)
if not os.path.exists(target):
# f_url = FHIR_SERVER + typ + '/' + fname
f_url = FHIR_SERVER + fname
resp = requests.get(f_url)
if resp.o... | [
"def _do_retrieve(url, fname):\n import requests\n folder = os.path.dirname(fname)\n if not os.path.exists(folder):\n os.makedirs(folder)\n print(\"{}/ created.\".format(folder))\n if not os.path.exists(fname):\n with open(fname, 'wb') as fout:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the index of the vertex under point if within epsilon tolerance | def get_index_under_point(self, event):
xy = np.asarray(list(zip(self.xs, self.ys)))
xyt = self.line.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.sqrt((xt - event.x) ** 2 + (yt - event.y) ** 2)
pt_idx = np.argmin(d)
if d[pt_idx] >= self.max_pix... | [
"def get_ind_under_point(self, event):\n # Check target point\n xyt = self.ax.transData.transform(\n (self.target_point.get_xdata(), self.target_point.get_ydata()))\n xt, yt = xyt[:, 0], xyt[:, 1]\n d = np.sqrt((xt-event.x)**2 + (yt-event.y)**2)\n if d <= self.epsilon:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the two players passed as arguments have played each other already. Queries the matches database looking for the lowest player id as player_1_id because we wrote reportMatch() to always sort the player ids before creating a new row. This eliminates us having to look for the pair in either order in this ... | def havePlayedPreviously(player1, player2):
# Assign player ids in a way that'll allow us to search for the lowest
# first
player1ID = min(player1, player2)
player2ID = max(player1, player2)
# Query the database for this pairing
dbconnection = connect()
dbcursor = dbconnection.cursor()
... | [
"def havePlayed(player1, player2):\n global _activeTournament\n con = connect()\n cursor = con.cursor()\n cursor.execute(\"\"\"\n SELECT id FROM matches WHERE ((player1 = %s AND player2 = %s) OR\n (player1 = %s AND player2 = %s)) LIMIT 1\n \"\"\", (player1, player2, player2, player1))\n for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The test checks whether the virtual operation "hardfork_hive_operation" (generated on hardfork 23) contains correct data related to "air drop" HIVE. | def test_reset_data_provided_by_hardfork_hive_operation_generated_between_hf_22_and_hf_23(node: tt.InitNode):
wallet = tt.Wallet(attach_to=node)
wallet.create_account("goku1", hives=tt.Asset.Test(50) , hbds=tt.Asset.Tbd(50), vests=tt.Asset.Test(50))
wallet.create_account("steem", hives=tt.Asset.Test(100) ,... | [
"def test_ha_vms(self):\n vm_host = ll_vms.get_vm_host(vm_name=conf.VM_NAME[0])\n host_resource = rhevm_helpers.get_host_resource_by_name(\n host_name=vm_host\n )\n for vm_name in conf.VM_NAME[:2]:\n testflow.step(\n \"Kill QEMU process of VM %s on ho... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a filter name, import and return the filter class. By default, filter modules are searched within the ``ufo2ft.filters`` package. | def getFilterClass(filterName, pkg="ufo2ft.filters"):
# TODO add support for third-party plugin discovery?
# if filter name is 'Foo Bar', the module should be called 'fooBar'
filterName = filterName.replace(" ", "")
moduleName = filterName[0].lower() + filterName[1:]
module = importlib.import_module... | [
"def load_filter(name: str) -> Filter:\n filters = [i for i in entry_points()[\"larry.filters\"] if i.name == name]\n\n if not filters:\n raise FilterNotFound(name)\n\n try:\n return filters[0].load()\n except ModuleNotFoundError as error:\n raise FilterNotFound(name) from error",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse custom filters from the ufo's lib.plist. Return two lists, one for the filters that are applied before decomposition of composite glyphs, another for the filters that are applied after decomposition. | def loadFilters(ufo):
preFilters, postFilters = [], []
for filterDict in ufo.lib.get(FILTERS_KEY, []):
namespace = filterDict.get("namespace", "ufo2ft.filters")
try:
filterClass = getFilterClass(filterDict["name"], namespace)
except (ImportError, AttributeError):
... | [
"def parse_filters(filters_str):\n fltrs = []\n for part in str(filters_str).lower().split(\",\"):\n if part==\"blur\":\n fltrs.append(filters.blur(1))\n elif part==\"distort\":\n fltrs.append(filters.distort(18))\n\n return fltrs",
"def par... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if 'klass' is a valid filter class. A valid filter class is a class (of type 'type'), that has a '__call__' (bound method), with the signature matching the same method | def isValidFilter(klass):
if not isclass(klass):
logger.error(f"{klass!r} is not a class")
return False
if not callable(klass):
logger.error(f"{klass!r} is not callable")
return False
if getfullargspec(klass.__call__).args != getfullargspec(BaseFilter.__call__).args:
... | [
"def _is_filter_class(cls):\n return type(cls) is types.TypeType and issubclass(cls, BaseHostFilter)",
"def match(self, cls):\n return isinstance(self, cls)",
"def class_is(cls: Class) -> bool:\n pass",
"def IsClass(self) -> bool:",
"def match(cls, kind: 'dsl.Any') -> bool:\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take a string specifying a filter class to load (either a builtin filter or one defined in an external, userdefined module), initialize it with given options and return the filter object. | def loadFilterFromString(spec):
return _loadPluginFromString(spec, "ufo2ft.filters", isValidFilter) | [
"def __init__(self, classname=None, jobject=None, options=None):\n if jobject is None:\n jobject = Filter.new_instance(classname)\n self.enforce_type(jobject, \"weka.filters.Filter\")\n super(Filter, self).__init__(jobject=jobject, options=options)",
"def build_filter(class_name, *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate over lines and yield line itself with info whether the given line represents a checkbox. | def _iterate_lines(cls, text) -> typing.Generator[str, None, None]:
for line in text.split('\n'):
yield line, line.lstrip().startswith(cls._CHECKBOX) | [
"def logical_line(self, line):\n return concat([l.accept(self) for l in line.children])",
"def process_line(self, line):\n ltype = self.line_type(line)\n if ltype == 'gene':\n self.process_gene_line(line)\n return True\n elif ltype == 'mRNA':\n self.pro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get title of a checkbox item. | def _get_checkbox_title(cls, line: str) -> str:
return line.strip()[len('- [ ] '):] | [
"def item_title(self, item):\n return item.title",
"def item_title(self) -> str:\n return self._item_title",
"def get_label(self):\n\t\treturn self._item.get_property('Label')",
"def selected_title(self):\r\n return self.title",
"def getMITItemTitle(self,xc,item,id):\n \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set a checkbox tick in text based on checkbox title. >>> Checkbox.set(' Foo\\n [ ] bar', 'bar') returns ' Foo\\n [x] bar' | def set(cls, text: str, title: str, graceful: bool = True) -> str:
result, found, modified = cls._do_checkbox_setting(text, title, ('[ ]', '[x]', 1))
if not found:
raise UserInputError("Checkbox with title {!r} was not found in the provided text".format(title))
if not graceful and ... | [
"def uiCheckboxSetText(checkbox, text):\n\n clibui.uiCheckboxSetText(checkbox, bytes(text, 'utf-8'))",
"def _get_checkbox_title(cls, line: str) -> str:\n return line.strip()[len('- [ ] '):]",
"def checkmark(text: str) -> str:\n return \"\\N{WHITE HEAVY CHECK MARK} {}\".format(text)",
"def title_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unset a checkbox tick in text based on checkbox title. >>> Checkbox.unset(' Foo\\n [x] bar', 'bar') returns ' Foo\\n [ ] bar' | def unset(cls, text: str, title: str, graceful: bool = True) -> str:
result, found, modified = cls._do_checkbox_setting(text, title, ('[x]', '[ ]', 1))
if not found:
raise UserInputError("Checkbox with title {!r} was not found in the provided text".format(title))
if not modified:
... | [
"def _get_checkbox_title(cls, line: str) -> str:\n return line.strip()[len('- [ ] '):]",
"def uncheck_checkbox(self, selector: str):\n with self.playwright.grpc_channel() as stub:\n response = stub.UncheckCheckbox(\n Request().ElementSelector(selector=selector)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize preprocessor and model. | def serialize_pipeline(preprocessor, clf):
print("Serializing preprocessor and model.")
with open(DATA_DIR + "/preprocessor.dill", "wb") as prep_f:
dill.dump(preprocessor, prep_f)
with open(DATA_DIR + "/model.dill", "wb") as model_f:
dill.dump(clf, model_f) | [
"def dump_model(self):",
"def _serialise(self):\n # TODO (M Foley)\n pass",
"def save_model(self):\n joblib.dump(self.pipeline, 'model.joblib')",
"def save_model(self):\n joblib.dump(self.pipeline, \"model.joblib\")",
"def save_model(self):\n joblib.dump(self.pipeline, 'tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
() > () Attempt to train a neural network to predict the satisfaction probability of a continuously defined environment. | def run():
cons_in, soln_in, disc = make_discriminator()
target, loss, accuracy, optimiser = make_training_nodes(disc)
training_set_sampler = make_sampler(cons_in, soln_in, target)
test_set_sampler = make_sampler(cons_in, soln_in, target)
disc.get_session().run(tf.global_variables_initializer())
... | [
"def trainNet():",
"def __train_perceptron(x_train, y_train):\n pass",
"def EvalNetwork(inputValues, Network):\n\n # YOUR CODE HERE\n\n print \"\\n .................Starting Evaluation Network: ................\\n\"\n\n input_node = inputValues\n\n threshold_list = list()\n\n # 1. computin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws a wheel of radius 1, centered at the origin, in the xy plane | def draw_wheel():
outer_radius = 1
thickness = .4
if wireframe:
glutWireTorus(thickness,outer_radius - thickness,8,8)
else:
glutSolidTorus(thickness,outer_radius - thickness,8,8)
glPushAttrib(GL_CURRENT_BIT)
glPushAttrib(GL_LIGHTING_BIT)
glDisable(GL_LIGHTING)
glColor3f(0,0,0)
glutWireTorus... | [
"def wheel():\n wheel_pos = read_npy_file('wheel.position.npy')\n wheel_timestamps = read_npy_file('wheel.timestamps.npy')\n wheel_rate = get_rate(wheel_timestamps)\n\n wheel_ts = TimeSeries(\n name='wheel_position',\n starting_time=wheel_timestamps[0, 1],\n rate=wheel_rate,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws the car body. It is a 1x1x2 cube with its base at the origin. | def draw_car_body():
# draw the car body
glPushMatrix()
glTranslatef(0,.5,0)
glScalef(1,1,2)
if wireframe:
glutWireCube(1)
else:
glutSolidCube(1)
# draw the wireframe outer shell
glPushAttrib(GL_CURRENT_BIT)
glPushAttrib(GL_LIGHTING_BIT)
glDisable(GL_LIGHTING)
glColor3f(0,0,0)
glutW... | [
"def draw_car():\r\n\twheel_radius = .5\r\n\twheel_thickness = .4\r\n\r\n\tglPushMatrix()\r\n\r\n\t# shift the car up so the base lies at the origin\r\n\tglTranslatef(0,wheel_radius,0)\r\n\t\r\n\tdraw_car_body()\r\n\r\n\t# draw the car wheels\r\n\t# assume the car is facing down the -z axis\r\n\t# front left, front... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draws a car. The 'car' is a 1x1x2 cube with its base at the origin, with wheels at the four corners. | def draw_car():
wheel_radius = .5
wheel_thickness = .4
glPushMatrix()
# shift the car up so the base lies at the origin
glTranslatef(0,wheel_radius,0)
draw_car_body()
# draw the car wheels
# assume the car is facing down the -z axis
# front left, front right, back left, back right
ww = whee... | [
"def draw_car(self):\n a = self.h / 50\n ellipse(screen, BLACK, (self.x - 15 * a, self.y + 35 * a, 30 * a, 10 * a))\n rect(screen, LIGHT_BLUE, (self.x, self.y, self.dir * 260 * a, self.h))\n rect(screen, LIGHT_BLUE, (self.x + self.dir * 40 * a, self.y - 40 * a, self.dir * 130 * a, 40 * a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds an element at the end of the list. | def addLast(self, element):
if element is None:
raise TypeError('The input element is NoneType')
newNode = Node(element)
if self.__nelems == 0:
self.__head = self.__tail = newNode
else:
self.__tail.setNext(newNode)
self.__tail = newNode
... | [
"def addLast(self, element):\n return self.add(element)",
"def add_as_last(self, element):\n raise NotImplementedError(\"add_as_last: You should have implemented this method!\")",
"def add_last(self, new_item):\n has_space_left = not self.is_full()\n if has_space_left:\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the next node | def setNext(self, nextNode):
self.__next = nextNode | [
"def set_next(self, node):\r\n self.__next = node",
"def set_next(node, value):\n node['next'] = value",
"def next_node(self, next_node):\n self._next_node = next_node",
"def set_next(self, new_next):\n self.next = new_next",
"def set_next(self, new_next):\n self.next_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new CommandManager with the specified commands. Each argument is a pair containing the name, attrib pairs, as the __setitem__ method is called on each element. | def __init__(self, *commands):
self.cmds = dict()
for nm, attr in commands:
self[nm] = attr | [
"def __init__(self, command_list: list = None) -> None:\n if command_list is None:\n command_list = implemented_commands\n for command in command_list:\n setattr(self, command.get(\"name\").replace(\" \", \"_\"), self._SingleCommand(command))",
"def _build_cmds(self, item_stora... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and register a command with the name item. This is a shortcut for constructing a Command and registering it with the register method. attribs is a list containing arguments to be sent to Command's constructor. Raises TypeError if attribs is not a list. | def __setitem__(self, name, attribs):
assert(type(attribs) is list)
self.register(Command(*([name] + attribs))) | [
"def add(self, name, command):",
"def __init__(self, *commands):\n \n self.cmds = dict()\n \n for nm, attr in commands:\n self[nm] = attr",
"def _construct_command(self, chips, *cmd_args):\n return self.base_cmd + [self.MASK, self._mask(chips)] + list(cmd_args)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new command description. name is the name of the command that the user must type at the prompt. switches is a dictionary that maps from the allowed command line switch keys to the type of their values. | def __init__(self, name, switches = dict()):
self.name = name
self.data = CmdData()
self.data.switches = switches | [
"def command(self, name, inputs={}, outputs={}, description=None):\n if len(inputs.values()) == 0 or len(outputs.values()) == 0:\n raise Exception('You need to provide at least one input and output for the command')\n\n inputs_as_list = []\n for input_name, inp in inputs.items():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return point subtraction PQ | def sub(self, P, Q):
if not (isinstance(P, list) and isinstance(Q, list)):
raise ValueError("point P (resp. Q) must be [px, py] (resp. [qx, qy])")
#if not (self.whetherOn(P) and self.whetherOn(Q)):
# raise ValueError("either points must not be point on curve.")
if (P != s... | [
"def distPlusProche(p,pts):\r\n\tpoints=pts[::]\r\n\r\n\t#on enleve p de la liste des points en cas de répétition\r\n\tif p in points:\r\n\t\tpoints.remove(p)\r\n\t#on initialise mini avec la distance au premier point de la liste des points\r\n\tmini=sqrt((p[0]-points[0][0])**2+(p[1]-points[0][1])**2)\r\n\t#on comp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create ECoverGF object. coefficient must be length 5 or 2 list(represent as Weierstrass form), any coefficient is in basefield. basefield must be FiniteField subclass object (i.e. FinitePrimeField or FiniteExtendedField object.) | def __init__(self, coefficient, basefield=None):
# parameter parse
try:
character = basefield.getCharacteristic()
field = basefield
except AttributeError:
# backward compatibility
if isinstance(basefield, int):
field = finitefield.... | [
"def GF(modulus):\n poly = gf2x.Polynomial(modulus)\n\n if poly in _field_cache:\n return _field_cache[poly]\n\n if not gf2x.is_irreducible(poly):\n raise ValueError(f'{poly} is not irreducible')\n\n GFElement = type(f'GF(2^{poly.degree()})', (BinaryFieldElement,), {'__slots__': ()})\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return (E(F_q) mod 2, 2). char(F_q) > 3 is required. For odd characteristic > 3, t = E(F_q) mod 2 is determined by gcd(self.cubic, X^q X) == 1 t = 1 mod 2. | def _Schoof_mod2(self):
if not self.b:
result = 0
_log.debug("(%d, 2) #" % result)
else:
linearfactors = UniVarPolynomial({card(self.basefield):self.basefield.one, 1:-self.basefield.one}, self.basefield)
if GCD(self.cubic, linearfactors).degree() == 0:
... | [
"def chi_c_real(params):\n Qi = Q_i(params)\n Qc = params['Q_e_real'].value\n return ((4 * Qc * Qi) /\n (Qc + Qi) ** 2)",
"def Q2C(self, q):\n\n #q = q.squeeze();\n C = np.empty((3,3));\n\tC[0,0] = (q[0]**2.0) + (q[1]**2.0) - (q[2]**2.0) - (q[3]**2.0);\n\tC[0,1] = 2.0 * ((q[1]*q[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return q + 1 E(F_q) mod l. | def _Schoof_mod_l(self, l):
if l == 2:
return self._Schoof_mod2()
E = self.cubic
D = self.division_polynomials
lth_div = self.division_polynomials[l]
field = self.basefield
bfsize = card(field)
x = UniVarPolynomial({1:field.one}, field)
k = bfs... | [
"def _evaluate_f_s_l_q(self, q):",
"def get_Lfrac_lam(Lfrac, Lstar_10, qlf):\n D = np.tile(qlf.c_B*Lstar_10**qlf.k_B, [len(Lfrac),1])\n Lfrac_2D = np.tile(Lfrac, [len(qlf.c_B),1]).T\n return np.sum(D,axis=1)/np.sum(D*Lfrac_2D**(qlf.k_B-1),axis=1)",
"def Q(self, *l):\r\n if self.generic:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Frobenius trace t = q + 1 E(F_q), where q is basefield cardinality. If index is an integer greater than 1, then return the trace t = q^r + 1 E(F_q^r) for a subfield curve defined over F_q. | def trace(self, index=None):
bfsize = card(self.basefield)
if not self.ord:
if bfsize == self.ch: # prime field
# special cases
if bfsize == 2 or bfsize == 3:
trace = self._order_to_trace(self.order())
# trace main block
... | [
"def f0(self, ion, q):\n tab = WaasmaierTable\n row = self.query(tab)\n if isinstance(ion, int):\n row = row.filter(tab.atomic_number==ion).all()\n else:\n row = row.filter(tab.ion==ion.title()).all()\n if len(row) > 0:\n row = row[0]\n if i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return E(F_q) or E(F_{q^r}). E is defined over F_q. If the method is called as E.order(), the result is E(F_q). If the method is called as E.order(r), the result is E(F_{q^r}). | def order(self, index=None):
bfsize = card(self.basefield)
if not self.ord:
if self.ch in (2, 3):
if bfsize == self.ch == 2:
self.ord = self._order_2()
elif bfsize == self.ch == 3:
self.ord = self._order_3()
... | [
"def hecke_operator(self, f, m):\n\n # This should just be an instance of hecke_operator_on_qexp but that\n # won't accept arbitrary power series as input, although it's clearly\n # supposed to, which seems rather to defy the point but never mind...\n\n if f.parent() is self:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find point order of P and return order. | def pointorder(self, P, ord=None, f=None):
# parameter ord and f are extension for structre.
if ord:
N = ord
else:
N = self.order()
if f:
l = f
else:
l = factor_methods.factor(N)
o = 1
for p, e in l:
B = ... | [
"def order(self, point):\n\n # check point is on curve first\n # and pari curve exists\n if not self.onCurve(point) or self.E is None:\n return 0\n\n P = \"[\" + str(point.x) + \",\" + str(point.y) + \"]\" # string representation of point\n\n # finds order... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
computing the TateLichetenbaum pairing with Miller's algorithm. parameters satisfies that mul(m,P)==[0]. | def TatePairing(self, m, P, Q):
O = self.infpoint
if self.mul(m, P) != O:
raise ValueError("sorry, not mP=[0].")
if P == O or Q == O:
return self.basefield.one
forbidden = [O, P, self.mul(-1, Q), self.sub(P, Q)]
R = self.add(P, Q)
T = False
... | [
"def milnor_multiplication_odd(m1,m2,p):\n from sage.rings.all import GF\n F = GF(p)\n (f,s) = m2\n # First compute Q_e0 Q_e1 ... P(r1, r2, ...) Q_f0 Q_f1 ...\n # Store results (as dictionary of pairs of tuples) in 'answer'.\n answer = {m1: F(1)}\n for k in f:\n old_answer = answer\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
computing the Weil pairing with Miller's algorithm. we assume point P and Q that be in different mtortion group . | def WeilPairing(self, m, P, Q):
O = self.infpoint
if self.mul(m, P) != O or self.mul(m, Q) != O:
raise ValueError("sorry, not mP=[0] or mQ=[0].")
if P == O or Q == O or P == Q:
return self.basefield.one
T = U = False
forbidden = [O, P, Q, self.sub(Q, P)]... | [
"def TatePairing(self, m, P, Q):\n O = self.infpoint\n if self.mul(m, P) != O:\n raise ValueError(\"sorry, not mP=[0].\")\n\n if P == O or Q == O:\n return self.basefield.one\n\n forbidden = [O, P, self.mul(-1, Q), self.sub(P, Q)]\n R = self.add(P, Q)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate gamma passing rate as percentage of voxels with gamma index >= 1.0 Optionally, a mask may be provided which excludes all voxels with mask==0 | def gamma_passing_rate(gamma_map, mask=None):
if mask is None:
passing = np.count_nonzero(gamma_map<=1.0)
total = gamma_map.size
else:
mask = mask.astype(bool)
masked_gamma_map = gamma_map[mask]
try:
passing = np.count_nonzero(masked_gamma_map<=1.0)
... | [
"def gamma(x):\n return 0.0",
"def get_gamma(self, conv_op):",
"def Gamma_per_grain(ZZall, Gamma_a_Z, ZZ_fz, fdist, GG):\n\n # index in the ZZall array for the charges in ZZ_fz\n zi_down = np.where(ZZall == ZZ_fz[0])[0][0]# find the index of the ZZ_fz[0] in ZZall \n zi_up = np.where(ZZall == Z... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the KML note label, use tag if exists or content otherwise | def getLabel(self):
return self.content[:12] | [
"def getLabel(self):\n result = self.content[:12]\n if result == \"\":\n if self.tags:\n result = str(self.tags.first)\n return result",
"def getLabel(self, branch):\n try:\n return branch.attrib['label']\n except KeyError:\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the KML note label, use tag if exists or content otherwise | def getLabel(self):
result = self.content[:12]
if result == "":
if self.tags:
result = str(self.tags.first)
return result | [
"def getLabel(self, branch):\n try:\n return branch.attrib['label']\n except KeyError:\n return None",
"def get_label_text(self, label) -> str:\n return self.labelText(LABELS.inv[label])",
"def get_label(self, label):\n return self.labels[label]",
"def getLabel(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overrides default queryset to only display parent items | def get_queryset(self, request):
query = super(GipsyMenu, self).get_queryset(request)
return query.filter(parent__isnull=True) | [
"def get_children_queryset(self):\n pass",
"def get_base_queryset(self):\n return JST.objects.filter(active=True).select_related(\n \"category\", \"parent\", \"parent__parent\"\n )",
"def parent(self, parent_object):\n lookup = get_parent_lookup_kwargs(parent_object)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Context manager that ignores all of the specified exceptions. This will be in the standard library starting with Python 3.4. | def ignored(*exceptions):
try:
yield
except exceptions:
pass | [
"def ignored(*exceptions):\r\n try:\r\n yield\r\n except exceptions:\r\n pass",
"def ignored(*exceptions):\n try:\n yield\n except exceptions:\n pass",
"def suppress(*exceptions):\n try:\n yield\n except exceptions:\n pass",
"def supp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a Grid2DIterate (see Grid2DIterate.__new__) from a mask, where only unmasked pixels are included in the grid (if the grid is represented in 2D masked values are (0.0, 0.0)). The mask's pixel_scales and origin properties are used to compute the grid (y,x) coordinates. | def from_mask(
cls,
mask: Mask2D,
fractional_accuracy: float = 0.9999,
relative_accuracy: Optional[float] = None,
sub_steps: Optional[List[int]] = None,
) -> "Grid2DIterate":
grid_slim = grid_2d_util.grid_2d_slim_via_mask_from(
mask_2d=mask, pixe... | [
"def from_pixels_and_mask(cls, pixels, mask):\r\n coorindates = [\r\n mask.scaled_coordinates_2d_from(pixel_coordinates_2d=pixel_coordinates_2d)\r\n for pixel_coordinates_2d in pixels\r\n ]\r\n return cls(grid=coorindates)",
"def _mask_grid(self):\n xg, yg = self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup a blurringgrid from a mask, where a blurring grid consists of all pixels that are masked (and therefore have their values set to (0.0, 0.0)), but are close enough to the unmasked pixels that their values will be convolved into the unmasked those pixels. This when computing images from light profile objects. See G... | def blurring_grid_from(
cls,
mask: Mask2D,
kernel_shape_native: Tuple[int, int],
fractional_accuracy: float = 0.9999,
relative_accuracy: Optional[float] = None,
sub_steps: Optional[List[int]] = None,
) -> "Grid2DIterate":
blurring_mask = mask.derive_... | [
"def _mask_grid(self):\n xg, yg = self._build_grid()\n mask = self._build_mask(xg, yg)\n mask = mask.reshape(xg.shape)\n\n return xg, yg, mask",
"def blurred_image_2d_from_grid_and_psf(self, grid, psf, blurring_grid):\r\n\r\n if not self.has_light_profile:\r\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a ``Grid2D`` where the data is stored its ``slim`` representation, which is an ndarray of shape [total_unmasked_pixels sub_size2, 2]. If it is already stored in its ``slim`` representation it is returned as it is. If not, it is mapped from ``native`` to ``slim`` and returned as a new ``Grid2D``. | def slim(self) -> "Grid2DIterate":
return Grid2DIterate(
values=self,
mask=self.mask,
fractional_accuracy=self.fractional_accuracy,
sub_steps=self.sub_steps,
) | [
"def array_2d_slim_from(\r\n array_2d_native: np.ndarray, mask_2d: np.ndarray, sub_size: int\r\n) -> np.ndarray:\r\n\r\n total_sub_pixels = mask_2d_util.total_sub_pixels_2d_from(\r\n mask_2d=mask_2d, sub_size=sub_size\r\n )\r\n\r\n array_2d_slim = np.zeros(shape=total_sub_pixels)\r\n index = 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new Grid2DIterate from this grid, where the (y,x) coordinates of this grid have a grid of (y,x) values, termed the deflection grid, subtracted from them to determine the new grid of (y,x) values. This is used by PyAutoLens to perform grid raytracing. | def grid_2d_via_deflection_grid_from(
self, deflection_grid: np.ndarray
) -> "Grid2DIterate":
return Grid2DIterate(
values=self - deflection_grid,
mask=self.mask,
fractional_accuracy=self.fractional_accuracy,
sub_steps=self.sub_steps,
) | [
"def grid_from_deflection_grid(self, deflection_grid):\r\n return Grid2DIrregular(grid=self - deflection_grid)",
"def grid_from_deflection_grid(self, deflection_grid):\r\n return Grid2DIrregularUniform(\r\n grid=self - deflection_grid,\r\n pixel_scales=self.pixel_scales,\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the blurring grid from a grid and create it as a Grid2DIterate, via an input 2D kernel shape. For a full description of blurring grids, checkout blurring_grid_from. | def blurring_grid_via_kernel_shape_from(
self, kernel_shape_native: Tuple[int, int]
) -> "Grid2DIterate":
return Grid2DIterate.blurring_grid_from(
mask=self.mask,
kernel_shape_native=kernel_shape_native,
fractional_accuracy=self.fractional_accuracy,
... | [
"def blurred_image_2d_from_grid_and_psf(self, grid, psf, blurring_grid):\r\n\r\n if not self.has_light_profile:\r\n return np.zeros(shape=grid.shape_slim)\r\n\r\n image = self.image_2d_from_grid(grid=grid)\r\n\r\n blurring_image = self.image_2d_from_grid(grid=blurring_grid)\r\n\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the resulting iterated array, by mapping it to 1D and then passing it back as an ``Array2D`` structure. | def return_iterated_array_result(self, iterated_array: Array2D) -> Array2D:
iterated_array_1d = array_2d_util.array_2d_slim_from(
mask_2d=self.mask, array_2d_native=iterated_array, sub_size=1
)
return Array2D(values=iterated_array_1d, mask=self.mask.derive_mask.sub_1) | [
"def to_2d_array(self):\n return reshape_fns.to_2d(self._obj, raw=True)",
"def convert_array_to_2d(grid):\n grid_2d = []\n for row in range(MAP_SIZE):\n grid_2d.append([])\n for col in range(MAP_SIZE):\n grid_2d[row].append(grid[row*MAP_SIZE+col])\n return grid_2d",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate over a function that returns a grid of values until the it meets a specified fractional accuracy. The function returns a result on a pixelgrid where evaluating it on more points on a higher resolution subgrid followed by binning lead to a more precise evaluation of the function. For the fractional accuracy of t... | def iterated_grid_from(
self, func: Callable, cls: object, grid_lower_sub_2d: Grid2D
) -> Grid2D:
if not np.any(grid_lower_sub_2d):
return grid_lower_sub_2d.slim
iterated_grid = np.zeros(shape=(self.shape_native[0], self.shape_native[1], 2))
threshold_mask_low... | [
"def test_evaluation_grid(self):\n\n f = FDataGrid(self.data_matrix_1_n, sample_points=np.arange(10),\n interpolator=SplineInterpolator(2))\n\n t = [1.5,2.5,3.5]\n res = np.array([[[ 2.25 , 0.08721158],\n [ 6.25 , 0.24020233],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Event实现与Condition类似的功能,不过比Condition简单一点。 它通过维护内部的标识符来实现线程间的同步问题。(threading.Event和.NET中的System.Threading.ManualResetEvent类实现同样的功能。) 事件机制是线程间通信机制的一种, Event对象实现了简单的线程通信机制,它提供了设置信号,清除信号,等待等用于实现线程间的通信。 通俗点理解就如,跑步比赛的时候裁判是一个线程,各个运动员是是不同的线程,各个运动员(线程)都在等待裁判的枪声(event)才开始跑一样 | def use_event():
event = threading.Event()
def chiHuoGuo(name):
# 等待事件,进入等待阻塞状态
print('%s 已经启动' % threading.currentThread().getName())
print('小伙伴 %s 已经进入就餐状态!' % name)
time.sleep(1)
event.wait()
# 收到事件后进入运行状态
print('%s 收到通知了.' % threading.currentThread().... | [
"def waitEvent(self, event): # real signature unknown; restored from __doc__\n pass",
"def event(self, event):\r\n ret = event\r\n self.mutex.acquire()\r\n\r\n try:\r\n Handled = False\r\n if event.eventType == EV_SYN:\r\n if self.synHandler:\r\n self.synHandler(event.str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
可以把Condiftion理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。 threadiong.Condition在内部维护一个琐对象(默认是RLock),可以在创建Condigtion对象的时候把琐对象作为参数传入。 使用Condition对象可以在某些事件触发或者达到特定的条件后才处理数据, Condition除了具有Lock对象的acquire方法和release方法外,还有wait方法、notify方法、notifyAll方法等用于条件处理。 | def use_condition():
L = []
class boy(threading.Thread):
def __init__(self, cond, name='A boy'):
threading.Thread.__init__(self)
self.cond = cond
self.name = name
def run(self):
time.sleep(1)
'''boy start conversation, make sure
... | [
"def create_condition(lock: Lock = None) -> Condition:\n return _get_asynclib().Condition(lock=lock)",
"def create_condition(lock: Optional[Lock] = None) -> Condition:\n return Condition(lock=lock)",
"def condition(self,condition):\n self._check_condition(condition)\n # change data in each f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load a image as a grayscale image. | def read_gray_scale_image(data_path):
return cv2.imread(data_path, cv2.IMREAD_GRAYSCALE) | [
"def load_img_as_gray(img_path):\n img = io.imread(img_path)\n return (color.rgb2gray(img) * 255).astype(np.uint8)",
"def grayscale(filename):\r\n image = SimpleImage(filename)\r\n for pixel in image:\r\n luminosity = compute_luminosity(pixel.red, pixel.green, pixel.blue)\r\n pixel.red =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the test context by specifying expectation and function. | def __init__(self, expected, test_func):
self._f = test_func
self._exp = expected | [
"def context():\n\n class FakeContext:\n function_name = \"FUNCTION_NAME\"\n memory_limit_in_mb = 1024\n invoked_function_arn = \"INVOKED_FUNCTION_ARN\"\n aws_request_id = \"AWS_REQUEST_ID\"\n log_group_name = \"LOG_GROUP_NAME\"\n log_stream_name = \"LOG_STREAM_NAME\"\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes as input two dictionaries containing node>infection time and filter only the items that correspond to observer nodes, up to the max number of observers | def filter_diffusion_data(infected, obs, max_obs=np.inf):
### Filter only observer nodes
obs_time = dict((k,v) for k,v in infected.items() if k in obs)
### If maximum number does not include every observer, we pick the max_obs closest ones
if max_obs < len(obs_time):
### Sorting according to ... | [
"def filter_diffusion_data(infected, obs, max_obs=np.inf):\n obs_time = dict((k,v) for k,v in infected.iteritems() if k in obs)\n if max_obs < len(obs_time):\n max_time = sorted(obs_time.values())[max_obs]\n #obs_time = dict((k,v) for k,v in obs_time.iteritems() if (v < max_time))\n node_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Contructor. Sets up the eyepoint, lookat and up arrays. | def __init__(self):
self.eyepoint = np.array([*self.eyepoint], dtype=np.float32)
self.lookat = np.array([*self.lookat], dtype=np.float32)
self.up = np.array([*self.up], dtype=np.float32) | [
"def __init__(self):\n self.X = None\n self.Y = None\n self.features = None\n self.max = self.min = None\n self._look_up = None\n self.attr_weight = None",
"def _setup_ndarrays(self) -> None:\n empty = self.ele_orig * 0\n # 2D arrays\n self.ele = np.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the view matrix and passes it to a given shader program. | def setup_view(self, shader_program):
n = self.normalize(self.eyepoint - self.lookat)
u = self.normalize(np.cross(self.normalize(self.up), n))
v = self.normalize(np.cross(n, u))
view_mat = np.array([u[0], v[0], n[0], 0.0,
u[1], v[1], n[1], 0.0,
... | [
"def _update_view(self) -> None:\n self.view_matrix = lookAt.create_look_at(self._eye, self._target, self._up) \n self.current_shader.set_view(self.view_matrix) #Uploading to Shader ",
"def init_shader(self):\r\n self.attrib_locs = {\r\n \"mc_vertex\": -1,\r\n \"vert_te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the projection matrix and passes it to a given shader program. | def setup_projection(self, shader_program):
projection_mat = np.array([(2.0*self.near)/(self.right-self.left), 0.0, 0.0, 0.0,
0.0, ((2.0*self.near)/(self.top-self.bottom)), 0.0, 0.0,
((self.right+self.left)/(self.right-self.left)),
... | [
"def _update_projection(self) -> None:\n a = self._width / self._height\n self.projection_matrix = Perspective_projection.create_perspective_projection(self._fov, a, self._near, self._far)\n self.current_shader.set_projection(self.projection_matrix) #Uploading to Shader",
"def _projection_mat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a given vector in normalized form. | def normalize(vector):
return vector / np.linalg.norm(vector) | [
"def get_normalized_vector(vector):\n # WARN: Zero length may cause problems!\n vector_lenght = get_vector_length(vector)\n if vector_lenght != 0:\n return np.divide(vector, get_vector_length(vector))\n else:\n return [0, 0]",
"def normalize(v):\n return v / np.linalg.norm(v)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the Planck function for given frequency range and temperature in units of W sr^1 m^2 Hz^1 | def planck_f(nu, T):
return ((2*h*nu**3)/(c**2))*(1./(np.exp((h*nu)/(k*T))-1)) | [
"def plancks_law_function(temperature, wavelength):\n return ((2.0 * PlancksLaw.h * PlancksLaw.c ** 2.0) / (wavelength ** 5.0)\n * (1.0 / (np.exp((PlancksLaw.h * PlancksLaw.c) / (wavelength * PlancksLaw.kb * temperature)) - 1.0)))",
"def planck( wav_m, temp ):\n term1 = 2 * HPLANCK_SI * (... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update position of car according to the path | def update_pos(self):
self.imgx=self.pathX[min(self.x,len(self.pathX)-1)]\
[min(self.y,len(self.pathX[self.x])-1)]
self.imgy=self.pathY[min(self.x,len(self.pathY)-1)]\
[min(self.y,len(self.pathY[self.x])-1)] | [
"def move(self, path):\n self.current_location = (path[1][1], path[1][0])",
"def cl_update_position(self):\n self.mol.vel += 0.5 * self.dt * self.rforce / np.column_stack([self.mol.mass] * self.mol.ndim)\n self.mol.pos += self.dt * self.mol.vel",
"def updatePos(self):\n self.timeDriv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a PlatformParameterModel instance. | def create(
cls,
param_name: str,
rule_dicts: List[platform_parameter_domain.PlatformParameterRuleDict],
rule_schema_version: int,
default_value: platform_parameter_domain.PlatformDataTypes
) -> PlatformParameterModel:
return cls(
id=param_name,
... | [
"def create_model_parameter(self, name, value=None):\n\n if len(name) > 12:\n print('Warning: PEST has a max char length of parameter names of 12')\n print(' Parameter {0} has length {1}'.format(name, len(name)))\n # end if\n self.param[name] = {}\n self.par... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Map of each word count in a string | def get_word_count(my_str):
my_list = my_str.split(" ")
my_map = {}
for word in my_list:
# Strip the word from any character
word = word.strip(".")
word = word.strip(",")
# Convert word to all lowercase
word = word.lower()
if word not in my_map:
my... | [
"def word_count(input_str):\n counts = dict()\n words = input_str.split()\n for word in words:\n if word in counts:\n counts[word] += 1\n else:\n counts[word] = 1\n\n return counts",
"def wordsInStringToDictWordCount(s):\r\n myDict = {}\r\n tmpList = s.split(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Holds the neccessary content for the dockerfile for nginx | def get_dockerfile_content(self):
dockerfile_content: List[str] = [
'FROM nginx:latest',
'# Update and install required packages',
'RUN apt-get update',
'RUN apt-get install vim -y',
'',
'COPY ./.docker/config/nginx.conf /etc/nginx/conf.d/... | [
"def configure_nginx_ondisk(input_nginxconf='./nginx/'):\n if not os.path.exists(f'{WORK_DIR}/nginx_server'):\n os.mkdir(f'{WORK_DIR}/nginx_server')\n if not os.path.exists(f'{WORK_DIR}/nginx_server/conf'):\n os.mkdir(f'{WORK_DIR}/nginx_server/conf')\n os.system(f'rm -rf {WORK_DIR}/nginx_serv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Holds the neccessary content for the config file for nginx with phpfpm support commented out | def get_config_file_content(self):
config_content: List[str] = [
'server {',
' listen {};'.format(self.port),
'',
' ##',
' # PHP-FPM',
' ##',
' #location ~ \.php$ {',
' #include /etc/nginx/fastcgi_params;',
... | [
"def generate_config_nginx():\n nginx_conf = '''server {\n listen {PORT};\n\n access_log /var/log/nginx/{PROJECT_NAME}.access.log;\n error_log /var/log/nginx/{PROJECT_NAME}.error.log;\n\n location / {\n include uwsgi_params;\n uwsgi_pass unix:{SOCKET};\n }... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A somewhat more scalable way to get the max episode lengths. | def get_max_episode_len(path):
path = path.replace('data/', '')
path = path.replace('goals/', '')
task = tasks.names[path]()
max_steps = task.max_steps - 1 # Remember, subtract one!
return max_steps | [
"def calc_max_length(self) -> None:\n self.max_q_len = max(\n len(episode.question.question_tokens) for episode in self.episodes\n )\n self.max_action_len = max(\n len(episode.shortest_paths[0]) for episode in self.episodes\n )",
"def max_episode_steps(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an episode to the dataset. | def add(self, episode, last_stuff=None):
color, depth, action, info = [], [], [], []
for obs, act, i in episode:
color.append(obs['color'])
depth.append(obs['depth'])
action.append(act)
info.append(i)
color = np.uint8(color)
depth = np.flo... | [
"def add_episode(self, episode):\n pass",
"def add_episode(self, episode):\n if isinstance(episode, Episode):\n self._episodes[episode.epno] = Episode\n else:\n raise TypeError(\"Episode expected\")",
"def add_episode(self, ep):\n #make da season\n ses = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Depending on the env, make changes to image suffix `suff`. | def _change_name(self, suff, info_extra):
if 'cable-ring' in self.path:
i1 = info_extra['convex_hull_area']
i2 = info_extra['best_possible_area']
f = i1 / i2
suff = suff.replace('.png',
f'-area-{i1:0.3f}-best-{i2:0.3f}-FRAC-{f:0.3f}.png')
... | [
"def set_base_image_labels(driver, user_disk, img_name, branch, target):\n\n dashes = [i for i, c in enumerate(img_name) if c=='-']\n cf_version = img_name[dashes[0]+1:dashes[3]]\n build_id = img_name[dashes[-1]+1:]\n\n driver.ex_set_volume_labels(user_disk,\n {'cf_version': cf_version, 'branch':... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To get more finegrained analysis of environment performance. Many of these require the last_info, which is not saved in info_l, which has all the time steps BEFORE that. For cablering and bagaloneopen, we terminate based on a fraction. Use `info_l[0]['extras']` to get the dict at the start. The `last_info` is already t... | def _track_data_statistics(self, info_l, last_info, episode_len,
all_stats, maxlen_stats):
maxlen = get_max_episode_len(self.path)
start = info_l[0]['extras']
last_ex = last_info['extras']
if 'cable-shape' in self.path or 'cable-line-notarget' in self.path:
nb_si... | [
"def find_last_k(self):\n dtype = self.args.dtypes[0]\n df = pd.read_csv(self.lookup_file, names=(\"day\", \"mode\", \"prec\", \"path\"))\n df = df[df[\"mode\"] == \"performance\"]\n df = df[df[\"prec\"] == dtype]\n log_infos = []\n for day, path in zip(df[\"day\"], df[\"pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For each item (timestep) in this episode, save relevant images. | def _save_images(self, episode_len, color_l, depth_l, info_l, outdir, i_ep):
for t in range(episode_len):
assert color_l[t].shape == (3, 480, 640, 3), color_l[t].shape
assert depth_l[t].shape == (3, 480, 640), depth_l[t].shape
# Recall that I added 'extras' to the info dict... | [
"def save_images(self):\n for q in range(self.N_itr):\n plt.clf()\n self.plot_EM_estimate(q)\n plt.savefig('img%d.png' % (100 + q))",
"def save_img(self):\r\n self.extract_info_from_file()\r\n path_0 = os.path.join(self.output_path, self.field_id, self.patient... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Routine for determining the index mu such that t_mu <= x < t_mu+1. If x is larger than t[1], then the last index is returned, for convenience sake. If x is smaller than t[0], then the first index is returned, for convenience sake. | def index(x, t):
if x < t[0]:
return 0
for i in range(len(t) - 1):
if t[i] <= x < t[i + 1]:
return i
return len(t) - 2 | [
"def index(x, t):\n if abs(x - t[-1]) <= 1.0e-14:\n # at endpoint, return last non trivial index\n # TODO: Make this less hackish\n for i in range(len(t) - 1, 0, -1):\n if t[i] < x:\n return i\n for i in range(len(t) - 1):\n if t[i] <= x < t[i + 1]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Routine for computing the polynomial curve q of degree p that interpolates the points c. | def algorithm_1_1(p, c, t, x):
q = np.array(c, dtype=np.float64)
for k in range(1, p + 1):
for j in range(0, p - k + 1):
q[j] = (t[j + k] - x) / (t[j + k] - t[j]) * q[j] + (x - t[j]) / (
t[j + k] - t[j]) * q[j + 1]
return q[0] | [
"def algorithm_1_2(p, c, x):\n\n q = np.array(c, dtype=np.float64)\n\n for k in range(1, p + 1):\n for j in range(0, p - k + 1):\n q[j] = (1 - x) * q[j] + x * q[j + 1]\n return q[0]",
"def cubic_interpol(X_P, Y_P):\r\n y_derivs = derivatives( X_P, Y_P ).flatten() # flatten as FB_sub ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Routine for computing the Bezier curve q of degree p defined by the points c. | def algorithm_1_2(p, c, x):
q = np.array(c, dtype=np.float64)
for k in range(1, p + 1):
for j in range(0, p - k + 1):
q[j] = (1 - x) * q[j] + x * q[j + 1]
return q[0] | [
"def algorithm_1_1(p, c, t, x):\n\n q = np.array(c, dtype=np.float64)\n\n for k in range(1, p + 1):\n for j in range(0, p - k + 1):\n q[j] = (t[j + k] - x) / (t[j + k] - t[j]) * q[j] + (x - t[j]) / (\n t[j + k] - t[j]) * q[j + 1]\n return q[0]",
"def cubic_curve(p0, p1, p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
取得粉絲頁資訊 fans_type 粉絲頁名稱 talk_about_is 粉絲頁名稱 total_like_count 粉絲頁名稱 total_fans 粉絲頁名稱 | def get_fans(request):
fans_type = request.GET.get('fans_type')
talk_about_is = request.GET.get('talk_about_is')
total_like_count = request.GET.get('total_like_count')
total_fans = request.GET.get('total_fans')
try:
fans = FansPage.objects.get(date=datetime.date.today(), fans_type=fans_type)
fans.total_fans =... | [
"def week_report_handle(fans_type):\n\t#import pdb;pdb.set_trace()\n\tlast_day = datetime.date.today()-timedelta(days=datetime.datetime.today().weekday() + 1)\n\ttoday = datetime.date.today()\n\n\tfans_pages = FansPage.objects.filter(fans_type=fans_type, date__gte=last_day, date__lte=today).order_by(\"date\")\n\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
last_week=datetime.date.today()timedelta(days=7) import pdb;pdb.set_trace() fans_list = ["wwwttshow", "ttshowpet", "draw.fans", "TTShowMusic", "GoodNews.FANS"] fans_pages = FansPage.objects.filter(fans_type=fans_type, date__gte=last_week, date__lte=datetime.date.today()).order_by("date") start = fans_pages[0] last = fa... | def week_report_handle(fans_type):
#import pdb;pdb.set_trace()
last_day = datetime.date.today()-timedelta(days=datetime.datetime.today().weekday() + 1)
today = datetime.date.today()
fans_pages = FansPage.objects.filter(fans_type=fans_type, date__gte=last_day, date__lte=today).order_by("date")
start = fans_pages[... | [
"def month_report_handle(fans_type):\n\tstart = datetime.date.today() - timedelta(days=datetime.date.today().day - 1)\n\ttoday = datetime.date.today()\n\t#import pdb;pdb.set_trace()\n\t#fans_list = [\"wwwttshow\", \"ttshowpet\", \"draw.fans\", \"TTShowMusic\", \"GoodNews.FANS\"]\n\tfans_pages = FansPage.objects.fil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
last_week=datetime.date.today()timedelta(days=30) import pdb;pdb.set_trace() fans_list = ["wwwttshow", "ttshowpet", "draw.fans", "TTShowMusic", "GoodNews.FANS"] fans_pages = FansPage.objects.filter(fans_type=fans_type, date__gte=last_week, date__lte=datetime.date.today()).order_by("date") start = fans_pages[0] last = f... | def month_report_handle(fans_type):
start = datetime.date.today() - timedelta(days=datetime.date.today().day - 1)
today = datetime.date.today()
#import pdb;pdb.set_trace()
#fans_list = ["wwwttshow", "ttshowpet", "draw.fans", "TTShowMusic", "GoodNews.FANS"]
fans_pages = FansPage.objects.filter(fans_type=fans_type, ... | [
"def week_report_handle(fans_type):\n\t#import pdb;pdb.set_trace()\n\tlast_day = datetime.date.today()-timedelta(days=datetime.datetime.today().weekday() + 1)\n\ttoday = datetime.date.today()\n\n\tfans_pages = FansPage.objects.filter(fans_type=fans_type, date__gte=last_day, date__lte=today).order_by(\"date\")\n\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a range of pages from the Solr index. | def getPageRange(base_url, node, page_range, page_size, from_date=None, to_date=None, delay=None):
docs = None
for p in page_range:
print "Getting page %d" % (p)
page_result = getPage(base_url, node, p, from_date=from_date, to_date=to_date)
if docs is None:
docs = page_result
else:
docs = docs.append... | [
"def _get_page_range(self):\r\n return list(range(1, self.num_pages + 1))",
"def test_page_range(self):\n paginator = solr.SolrPaginator(self.result)\n self.assertEqual(paginator.page_range, range(1, 3))",
"def __pages_range(self):\n return range(1, self.total_pages + 1)",
"def ind... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the directory the script is being run from | def getScriptDirectory():
return os.path.dirname(os.path.realpath(__file__)) | [
"def scriptdir():\n return os.path.dirname(os.path.realpath(__file__))",
"def getScriptPath():\n\treturn os.path.dirname(os.path.realpath(sys.argv[0]))",
"def get_current_script_dir():\n module_location = os.path.abspath(inspect.stack()[0][1])\n return os.path.dirname(module_location)",
"def get_scri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Regresa una lista con los archivos .pyx del path dado Si abspath es true, la lista de archivos es el path absoluto de lo contrario es solo el nombre de los mismos | def get_pyx_files(path, abspath=True):
path = os.path.normpath(os.path.abspath(path))
to_compile = []
for name in os.listdir(path):
if name.endswith(".pyx"):
pyx = os.path.join(path,name)
if os.path.isfile(pyx):
to_compile.append(pyx if abspath else nam... | [
"def list_of_files(path):\r\n files_list=[]\r\n path = os.path.abspath(path)\r\n\r\n #if the path is a file name, returns a list of a single file name\r\n if os.path.isfile(path):\r\n files_list.append(path)\r\n #if the path is a directory name, returns a list of all the file names anded with ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Funcion para cythonize todos los .pyx del path dado inplace | def compile_dir(path):
to_compile = get_pyx_files(path)
print("De:",path)
if to_compile:
print("Se compilaran:", list(map(os.path.basename,to_compile)))
Cythonize.main( ['-a', '-i'] + to_compile )
else:
print("Nada para compilar") | [
"def prepare_Cython_extensions_as_C_extensions(extensions):\n for extension in extensions:\n c_sources = list()\n for source_path in extension.sources:\n path, source = os.path.split(source_path)\n filename, ext = os.path.splitext(source)\n\n if ext == '.pyx':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Funcion para cythonize todos los .pyx del path dado inplace incluyendo numpy | def compile_dir_with_numpy(path, cleanup=True):
from distutils.core import setup
import numpy
path = os.path.normpath(os.path.abspath(path))
temp = os.path.join(path,".temp_build")
with redirect_sys_argv(os.path.join(path,"make_virtual_script.py"), "build_ext", "--inplace", "-t", temp):
... | [
"def compile_cutils():\r\n\r\n types = ['npy_' + t for t in ['int8', 'int16', 'int32', 'int64', 'int128',\r\n 'int256', 'uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'uint256',\r\n 'float16', 'float32', 'float64', 'float80', 'float96', 'float128',\r\n 'float256']]\r\n\r\n complex_type... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display a digit. number the number (09) to display offset the leftmost column of the displayed digit color the RGB color to use to display the digit force_zero whether to leave a 0 blank (False) or display it | def display_digit(number, offset, color, force_zero):
bits = number_patterns[number]
for row in range(4):
for col in range(3):
if bits[row][col] == " " or (number == 0 and not force_zero):
trellis.pixels[col + offset, row] = (0, 0, 0)
else:
trellis... | [
"def draw_digit(self, digit, pos, color):\n\t\tbox = (digit*4+1, 1, digit*4+4, 8)\n\t\tnumber = self.number_font.crop(box)\n\t\tfor x in range(number.size[0]):\n\t\t\tfor y in range(number.size[1]):\n\t\t\t\tpixel = number.getpixel((x,y))\n\t\t\t\tif pixel == (255, 255, 255):\n\t\t\t\t\tself.screen.pixel[pos.x + x]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform an animation (displaying random numbers) before displaying the requested number. number the number to eventually display color the color to use (indicates the type of dice used) | def animate_to(number, color):
for _ in range(10):
trellis.pixels.fill((0, 0, 0))
display_number(random.randint(10, 99), color)
time.sleep(0.1)
trellis.pixels.fill((0, 0, 0))
display_number(number, color) | [
"def draw_red():\n return -random.randint(1, 10)",
"def diceSimulator():\n try:\n dice_number = random.randint(1,6)\n if dice_number == 1:\n one = (\" \\n o \\n \")\n print(colored(f'{one}', 'yellow', attrs=['bold']))\n elif dice_number == 2:\n tw... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a random dice roll. Returns the total of the roll. number the number of dice to roll sides the number of side on dice to roll (4, 6, 8, 10, 12, 20) | def roll(number, sides):
total = 0
for _ in range(number):
total += random.randint(1, sides + 1)
return total | [
"def roll_multiple_n_sided_dice(number_of_dice, n):\n total = 0\n for dice in range (number_of_dice):\n dice_roll = random.randint(1,n)\n total = dice_roll + total\n return total",
"def roll_die(number_of_rolls, number_of_sides):\n import random\n res = 0\n\n if number_of_rolls == ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detect when the Trellis is shaken. | def shaken():
global previous_reading
result = False
x, y, z = accelerometer.acceleration
if previous_reading[0] is not None:
result = (math.fabs(previous_reading[0] - x) > bound and
math.fabs(previous_reading[1] - y) > bound and
math.fabs(previous_reading[2] ... | [
"def _determine_sheep_sprite(self, action, t):\r\n return t % 2",
"def _cooldown_shot(self):\n\n now = pg.time.get_ticks()\n\n if (now - self.last_shot)/1000 >= self.weapon.rate:\n\n self.last_shot = now\n\n self.shot_ready = True\n\n else:\n\n self.sho... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a user with a random email. Perfect for tests where you just need to set a user on some data model, but the user is not used for anything. | def create_random_user():
try:
user = get_user_model().objects.create(
email='{}@example.com'.format(uuid.uuid4()))
except IntegrityError:
return create_random_user()
else:
user.set_password('test')
user.save()
return user | [
"def sample_user(email=user_v['email'], password=user_v['password']):\n return get_user_model().objects.create_user(email, password)",
"def generate_random_user():\n name = names.get_first_name()\n return User(name=name, email=f\"{name}@example.com\", password=\"testing_password\")",
"def sample_user(e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Roll the die once and insure the value is in possibleValues | def test_roll_once(self):
self.assertIn(self.new_die.roll(), self.possible_values, "Rolled value was not in possible die values") | [
"def set_value(self):\n for x in self.die_object_list:\n if not x.HOLD:\n x.set_random_value()",
"def roll(self):\n self.currentValue = choice(self.possibleValues)\n self.value = AngryDie.ANGRY_VALUES[self.currentValue]\n return self.currentValue",
"def safe_dice(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure the Die's currentValue is updated to match what is rolled | def test_currentValue_is_updated_to_roll_value(self):
rolled_value = self.new_die.roll()
if rolled_value == self.new_die.currentValue:
self.assertTrue(True, "currentValue {} matches the rolled value".format(self.new_die.currentValue))
return | [
"def roll(self):\n self.currentValue = choice(self.possibleValues)\n self.value = AngryDie.ANGRY_VALUES[self.currentValue]\n return self.currentValue",
"def test_roll_once(self):\n\n self.assertIn(self.new_die.roll(), self.possible_values, \"Rolled value was not in possible die values\")",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the pair (symbols, positions) where symbols is a row major array of images and positions is the corresponding centers of those images relative to the input image. | def get_symbol_images_and_positions(im):
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
_, threshold = cv2.threshold(gray, 100, 255, 0)
threshold = 255 - threshold
# show(threshold)
contours, hierarchy = cv2.findContours(threshold, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
contours = [cv2.approxPolyD... | [
"def sym_coordinates(self):\n return tuple([self.coordinates.indexed[p, i]\n for i in range(self.ndim)])",
"def get_coords_by_label_2D(image, label):\n coords = np.argwhere(image == label)\n y = [y for y, x in coords]\n x = [x for y, x in coords]\n return y, x",
"def get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
commandline frontend to portcheck | def portcheck_main(args=sys.argv[1:]):
ports = portcheck(*args)
for i in ports:
print '%s: %s' % (i, ports[i])
return 0 | [
"def main():\n import getopt\n\n try:\n options, remainder = getopt.getopt(\n sys.argv[1:], '',\n ['help', # Print usage msg, exit\n 'short', # Output is shortened\n 'pid', # Output only pid of listenig process\n 'proc', # Output... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
commandline frontend to portkill | def portkill_main(args=sys.argv[1:]):
# Probably should use optparse or some such.
kw = {}
if '-v' in args:
kw['verbose'] = True
args = [a for a in args if a != '-v']
if '-s' in args:
index = args.index('-s')
kw['sleeptime'] = args[index + 1]
args = args[:index] +... | [
"def commandPort(*args, **kwargs):\n\n pass",
"def main():\n import getopt\n\n try:\n options, remainder = getopt.getopt(\n sys.argv[1:], '',\n ['help', # Print usage msg, exit\n 'short', # Output is shortened\n 'pid', # Output only pid of ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hotfix for exporting mixed precision model as float32. | def export_model_as_float32(temporary_model, checkpoint_path, export_path):
checkpoint = tf.train.Checkpoint(model=temporary_model)
manager = tf.train.CheckpointManager(
checkpoint=checkpoint, directory=checkpoint_path, max_to_keep=3
)
checkpoint.restore(manager.latest_checkpoint).expec... | [
"def ggml_fp16_to_fp32(x: np.float16) -> float:\n ...",
"def writeFloat32(self, *args):\n self.out.write(pack(\"%df\" % len(args), *args))",
"def ggml_fp32_to_fp16(x: float) -> np.float16:\n ...",
"def Float32l():\n return FormatField(\"<\", \"f\")",
"def write_float32(self, f: float) -> Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a denormalized Catalog of matches This is intended for writing matches in a convenient way. | def denormalizeMatches(matches, matchMeta=None):
if len(matches) == 0:
raise RuntimeError("No matches provided.")
refSchema = matches[0].first.getSchema()
srcSchema = matches[0].second.getSchema()
refMapper, srcMapper = lsst.afw.table.SchemaMapper.join([refSchema, srcSchema], ["ref_", "src_"])... | [
"def matchesToCatalog(matches, matchMeta):\n if len(matches) == 0:\n raise RuntimeError(\"No matches provided.\")\n\n refSchema = matches[0].first.getSchema()\n srcSchema = matches[0].second.getSchema()\n\n mergedSchema = makeMergedSchema(refSchema, Schema(), targetPrefix=\"ref_\")\n mergedSch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns photon energy in keV if specified in eV or keV | def keV(E):
if np.min(E) >= 100:
return E / 1000
else:
return E | [
"def EnergyUnitInMeV(energy_unit):\n if energy_unit == 'eV':\n inMeV = 1e-6\n elif energy_unit == 'keV':\n inMeV = 1e-3\n elif energy_unit == 'MeV':\n inMeV = 1\n elif energy_unit == 'GeV':\n inMeV = 1e3\n else:\n print ('Unknown energy unit, please use either eV, k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the attenuation length (m) at given energies E in keV (vectorized) density in g/cm3, None=default density | def attenuationLength(matID, keV, density=None):
return 1.0 / mu(matID, keV, density) | [
"def debye_length_m(electron_density, electron_temperature):\n return 0.069 * np.sqrt(electron_temperature / electron_density)",
"def eam_density(self):\n return self._parse_params_section(\"EAM-Density\", self._parse_density_line)",
"def GammaPathLength(self,E):\n xz = self.TotalCrossSection(E)*self.D... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |