query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Queries given the query criteria, retrieves single instance of JMXMBean | def getJMXMBean1(domain='WebSphere', **attributes):
queryString = '%s:*' % domain
for (k, v) in attributes.items():
queryString += ',%s=%s' % (k, v)
result = AdminControl.queryNames(queryString).splitlines()
if len(result) == 1:
return JMXMBean(result[0])
elif len(result) == 0:
... | [
"def getJMXMBean(domain='WebSphere', **attributes):\n queryString = '%s:*' % domain\n for (k, v) in attributes.items():\n queryString += ',%s=%s' % (k, v)\n result = AdminControl.queryNames(queryString).splitlines()\n if len(result) == 1:\n return JMXMBean(result[0])\n elif len(result) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return Quad info as dict | def getMyQuadInfo(self):
d = self.getMyInfoAsDict()
d['components'] = self.getMyDictInfo('components')
d['weapons'] = self.getMyDictInfo('weapons')
return d | [
"def getMyShipInfo(self):\n d = self.getMyInfoAsDict()\n d['quads'] = self.getMyDictInfo('quads', 'getMyQuadInfo')\n d['targets'] = self.targets\n d['availSystems'] = self.availSystems\n d['oldAvailSystems'] = self.oldAvailSystems\n return d",
"def convertToQuad(self,qtyp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reload Ammo in any weapons in quad | def reloadAmmo(self):
for componentID, myComponent in self.components.iteritems():
if myComponent.myComponentData.maxAmmo > 0:
myComponent.currentAmount = myComponent.myComponentData.maxAmmo | [
"def updateWeapons(self):\n self.readyWeapons = []\n self.setWeaponStatus()\n\n for myWeapon in self.activeWeapons:\n if myWeapon.preFireCheck() == 1:\n self.readyWeapons.append(myWeapon)\n self.alternateTargets = []\n\n if self.amsTargets != []:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take the current max AP and SP and reset the current AP SP | def resetDefences(self):
self.currentAP = self.maxAP
self.currentSP = self.maxSP | [
"async def set_max_current(self, currentP1: int, currentP2: int = None, currentP3: int = None):\n json = {\n \"maxCircuitCurrentP1\": currentP1,\n \"maxCircuitCurrentP2\": currentP2 if currentP2 is not None else currentP1,\n \"maxCircuitCurrentP3\": currentP3 if currentP3 is ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute allunorderedpairs distances on the given list of hashes (ftr). If prfx is given, save the full dst matrix as mat_[prfx].npy (not recommended, as this can be a very large file). | def calc_distances(ftr, prfx=None):
print(time.asctime(), ' Computing distances')
start = time.time()
dst = util.compute_pair_distances(ftr)
end = time.time()
print(time.asctime(), ' Done Computing distances in ', end-start, ' seconds', flush=True)
# Only save if requested (this can be a very l... | [
"def return_matches(self, hashes, batch_size: int=1000):\n # Create a dictionary of hash => offset pairs for later lookups\n mapper = {}\n for hsh, offset in hashes:\n if hsh in mapper.keys():\n mapper[hsh].append(offset)\n else:\n mapper[hsh]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For the given distance matrix, return a tuple of two lists of indices such that dst[midx[0][i], midx[1][i]] are the minimumdistance values in dst, for i<n_matches. | def get_min_distances(dst, n_matches):
print(time.asctime(), ' Sorting distances')
start = time.time()
midx = util.mindist(dst, n=n_matches)
end = time.time()
print(time.asctime(), ' Done Sorting distances in ', end-start, ' seconds', flush=True)
return midx | [
"def get_min_distances_per_query(dst, n_matches_per_query):\n print(time.asctime(), ' Sorting distances')\n start = time.time()\n query_matches = []\n for i in range(dst.shape[0]):\n midx = util.mindist(dst[i,:], n=n_matches_per_query)\n query_matches.append(midx)\n end = time.time()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all pairs in dst with dst[i][j] < threshold | def get_matches(dst, threshold):
print(time.asctime(), ' Filtering and sorting distances')
start = time.time()
dup_dict = util.find_duplicates(dst, threshold)
n_matches = len(dup_dict)
end = time.time()
print(time.asctime(), ' Done Filtering distances for ', n_matches, ' matches in ', end-start,... | [
"def list_dst():\n d = {}\n for tag in _dst_tags:\n dst = [map(int, v.split('.')[0][3:].split('_')) for v in os.listdir(os.path.join(_dst_path, tag)) if v.endswith('mat') and not ('_light' in v)]\n for run, index in dst:\n\t try:\n\t if d[run][1] < index:\n\t\t d[run][1] = index\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For every row of dst, find the n_matches_per_query smallest distances. | def get_min_distances_per_query(dst, n_matches_per_query):
print(time.asctime(), ' Sorting distances')
start = time.time()
query_matches = []
for i in range(dst.shape[0]):
midx = util.mindist(dst[i,:], n=n_matches_per_query)
query_matches.append(midx)
end = time.time()
print(time... | [
"def get_min_distances(dst, n_matches):\n print(time.asctime(), ' Sorting distances')\n start = time.time()\n midx = util.mindist(dst, n=n_matches)\n end = time.time()\n print(time.asctime(), ' Done Sorting distances in ', end-start, ' seconds', flush=True)\n return midx",
"def get_matches(dst, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows to connect force_averaging input to the operator | def force_averaging(self):
return self._force_averaging | [
"def _set_averaging_mode(self, value: int) -> None:\n self._averaging_mode = value",
"def set_average(self, *args, **kwargs):\n return _qtgui_swig.number_sink_sptr_set_average(self, *args, **kwargs)",
"def set_average(self, *args, **kwargs):\n return _qtgui_swig.number_sink_set_average(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The set of arguments for constructing a ConfigurationSetEventDestination resource. | def __init__(__self__, *,
configuration_set_name: pulumi.Input[str],
event_destination: pulumi.Input['ConfigurationSetEventDestinationEventDestinationArgs'],
event_destination_name: pulumi.Input[str]):
pulumi.set(__self__, "configuration_set_name", configuratio... | [
"def create_configuration_set_event_destination(ConfigurationSetName=None, EventDestination=None):\n pass",
"def __init__(__self__, *,\n configuration_set_name: Optional[pulumi.Input[str]] = None,\n event_destination: Optional[pulumi.Input['ConfigurationSetEventDestinationEventD... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The name of the configuration set. | def configuration_set_name(self) -> pulumi.Input[str]:
return pulumi.get(self, "configuration_set_name") | [
"def configuration_set_name(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"configuration_set_name\")",
"def config_name(self) -> str:\n return self._name",
"def name_server_set(self) -> str:\n return pulumi.get(self, \"name_server_set\")",
"def getConfigurationName(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Input properties used for looking up and filtering ConfigurationSetEventDestination resources. | def __init__(__self__, *,
configuration_set_name: Optional[pulumi.Input[str]] = None,
event_destination: Optional[pulumi.Input['ConfigurationSetEventDestinationEventDestinationArgs']] = None,
event_destination_name: Optional[pulumi.Input[str]] = None):
if confi... | [
"def __init__(__self__, *,\n configuration_set_name: pulumi.Input[str],\n event_destination: pulumi.Input['ConfigurationSetEventDestinationEventDestinationArgs'],\n event_destination_name: pulumi.Input[str]):\n pulumi.set(__self__, \"configuration_set_name\", c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an existing ConfigurationSetEventDestination resource's state with the given name, id, and optional extra properties used to qualify the lookup. | def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
configuration_set_name: Optional[pulumi.Input[str]] = None,
event_destination: Optional[pulumi.Input[pulumi.InputType['ConfigurationSetEventDestinationEventDestinationArgs']]... | [
"def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None) -> 'EventSourceMapping':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = EventSourceMappingArgs.__new__(EventSourceMappingArgs)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The name of the configuration set. | def configuration_set_name(self) -> pulumi.Output[str]:
return pulumi.get(self, "configuration_set_name") | [
"def configuration_set_name(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"configuration_set_name\")",
"def config_name(self) -> str:\n return self._name",
"def name_server_set(self) -> str:\n return pulumi.get(self, \"name_server_set\")",
"def getConfigurationName(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Computed) The policy data | def policy_data(self) -> str:
return pulumi.get(self, "policy_data") | [
"def extractPolicy(self):\n\n self.policy = np.zeros([len(self.s),len(self.a)])\n\n for i in range(len(self.s)-1):\n\n state_policy = np.zeros(len(self.a))\n\n state_policy = self.r[i] + self.discount* \\\n np.dot(self.t[i][:][:], self.values)\n\n # Softmax the policy \n state_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the current IAM policy data for a folder. example ```python import pulumi import pulumi_gcp as gcp test = gcp.folder.get_iam_policy(folder=google_folder["permissiontest"]["name"]) ``` | def get_iam_policy(folder: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetIamPolicyResult:
__args__ = dict()
__args__['folder'] = folder
opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke('g... | [
"def get_iam_policy_output(folder: Optional[pulumi.Input[str]] = None,\n opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetIamPolicyResult]:\n ...",
"def get_bucket_iam_policy_output(bucket: Optional[pulumi.Input[str]] = None,\n opts: Opti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the current IAM policy data for a folder. example ```python import pulumi import pulumi_gcp as gcp test = gcp.folder.get_iam_policy(folder=google_folder["permissiontest"]["name"]) ``` | def get_iam_policy_output(folder: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetIamPolicyResult]:
... | [
"def get_iam_policy(folder: Optional[str] = None,\n opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetIamPolicyResult:\n __args__ = dict()\n __args__['folder'] = folder\n opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)\n __ret__ = pulumi.runtime... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process the provided mango and setup all the structures. | def process_mango(self):
to_ret = False
curr_parser = MangoParser()
all_mango_types = curr_parser.Parse(self.target_mango_file, self.target_engine, self.target_blender_factory)
if len(all_mango_types) > 0:
to_ret = True
return to_ret | [
"def run_project_parser(self):\n\n # get Ansible project structure\n self.__get_ansible_project_content()\n self.__generate_graph('project', self.__project_content)\n\n # get Ansible roles\n self.__get_ansible_roles_content()\n self.__generate_graph('roles', self.__role_con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Jucify using the provided mango config. | def jucify(self):
to_ret = False
# TODO: finish this
return to_ret | [
"async def libjuju(context, rule):\n await context.juju_model.deploy(str(context.config.path))",
"def _parse_juniper(config):",
"def main(verb, language):\n conjugator = Conjugator(language)\n result = conjugator.conjugate(verb)\n pprint(result.conjug_info)\n return",
"def set_json(config):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function save joints positions into json file | def savePositions():
home = expanduser("~")
jointPositionsList = []
jointPositions = {}
jsonPath = raw_input("Enter JSON file path in the following format: path_to_file/file_name\n")
while not rospy.is_shutdown():
prof = raw_input("Press the S-key and Enter to save position, or any key to e... | [
"def save_joints():\n joint_data_fn = os.path.join(MPII_OUT_DIR, 'data.json')\n mat = loadmat(os.path.join(MPII_DATA_DIR, 'mpii_human_pose_v1_u12_1.mat'))\n\n fp = open(joint_data_fn, 'w')\n\n for i, (anno, train_flag) in enumerate(\n izip(mat['RELEASE']['annolist'][0, 0][0],\n mat['RE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that we can create an approval object to access clients. | def testValidClientApprovalAllowsAccessToEverythingInsideClient(self):
self.InitDefaultRouter()
client_id = self.SetupClient(0)
gui_test_lib.CreateFileVersion(client_id, "fs/os/foo")
with self.assertRaises(grr_api_errors.AccessForbiddenError):
self.api.Client(client_id).File("fs/os/foo").Get()
... | [
"def test_account_approvers_created_successfully(self):\n self.assertEqual(self.AccountApprovers.name, \"Account Approvers\")",
"def test_create_o_auth_client_authorization(self):\n pass",
"def test_is_approved_with_approval(time_record_approval_factory):\n approval = time_record_approval_facto... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that we can create an approval object to run hunts. | def testValidHuntApprovalAllowsStartingHunt(self):
self.InitDefaultRouter()
hunt_id = self.CreateHunt()
self.assertRaises(grr_api_errors.AccessForbiddenError,
self.api.Hunt(hunt_id).Start)
self.CreateHuntApproval(hunt_id, self.test_username, admin=False)
self.assertRaisesReg... | [
"def test_create_warranty(self):\n pass",
"def test_create_goal(self):\n pass",
"def test_create_submission_award(self):\n allowance = self.create_allowance()\n data = {\n 'judge_allowance': allowance,\n 'amount': 10000,\n 'submission': self.submissio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in quiz length and determines proportion of q's allocated to each strand Returns a list of tuples representing strand id and num questions for each | def pick_strands(quiz_len):
strand_info = []
# checks how many strands there are and sees if the quiz can be evenly divided between them
# if the num_strands evenly goes into the quiz, you can divide q's evenly
num_strands = len(strands.keys())
if not quiz_len % num_strands:
for key in str... | [
"def lindivQ(sample, quantity, criteria=len):\n sizes = [criteria(dna) for dna in sample]\n return [size*quantity/sum(sizes) for size in sizes]",
"def test_assessment_structure():\n expected_number = N * (N - 1)\n assessment = get_assessment(TEST_DIMENSIONS)\n actual_number = len(assessment)\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in strand info from pick_strands function, returns new list of tuples with standard ids and number of questions for each | def pick_standards(strand_info):
standard_info = []
# goes through each item (aka strand) and looks at the standards available to it and how many questions
# that strand is supposed to get. if it can divide q's evenly, it does.
# otherwise, it goes through the "remainder" it can't evenly divide and pi... | [
"def pick_strands(quiz_len):\n\n strand_info = []\n\n # checks how many strands there are and sees if the quiz can be evenly divided between them\n # if the num_strands evenly goes into the quiz, you can divide q's evenly\n num_strands = len(strands.keys())\n if not quiz_len % num_strands:\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
inserts or updates depending on id's value | def save(self):
if self.id is None:
self._insert()
else:
self._update() | [
"def upsert(self):\n ...",
"def _insert_data(data, id_insert, dataInsert):\n if _isempty(id_insert):\n return data\n # TODO: actually implement rest of function\n raise NotImplementedError",
"def insert_or_update(self, table, record):\n try:\n request = s.query(table=tab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the Position object for this account's holdings in a given stock, return a new 0 share position if it does not exist. Why? To make buy simple, you always just get the current position and add to it. | def get_position_for(self, ticker):
return position.Position.from_account_id_and_ticker(self.id, ticker) | [
"def _get_positions_from_broker(self):\n cur_pos_in_tracker = self.metrics_tracker.positions\n for symbol in self._tws.positions:\n ib_position = self._tws.positions[symbol]\n try:\n z_position = zp.Position(zp.InnerPosition(symbol_lookup(symbol)))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return all Trade objects for this account and a given ticker | def get_trades_for(self, ticker):
return trade.Trade.all_from_account_id_and_ticker(self.id, ticker) | [
"def get_trades(self):\n return trade.Trade.all_from_account_id(self.id)",
"async def get_all_trades(self) -> List[TradeRecord]:\n\n cursor = await self.db_connection.execute(\"SELECT * from trade_records\")\n rows = await cursor.fetchall()\n await cursor.close()\n records = []\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return all Trades this account has made | def get_trades(self):
return trade.Trade.all_from_account_id(self.id) | [
"def all_trades(self) -> List[Dict]:\n lst = []\n if self._trades:\n for k, v in self._trades.items():\n lst.extend(v)\n return lst",
"def trades(self) -> list[TradeOffer]:\n return self._connection.trades",
"def get_trades(self):\n for exchange, keys... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search using the given ingredients and return the HTML | def search_recipe(ingredients):
params = '+'.join(ingredients.split())
url_search = SEARCH_URL.format(params)
response = req.get(url_search)
return response.content | [
"def search():\n\n search = request.args.get('name') #must use request.args.get for GET requests\n app_key = os.environ['app_key']\n app_id = os.environ['app_id']\n payload = {'ingr': search, 'app_id': app_id, 'app_key': app_key}\n url = 'https://api.edamam.com/api/food-database/v2/parser'\n res =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initialize the battery's attributes | def __init__(self, battery_size=70):
self.battery_size = battery_size | [
"def __init__( self, battery_size = 60 ):\r\n self.battery_size = battery_size",
"def __init__(self, battery_size = 70):\r\n\t\tself.battery_size = battery_size",
"def __init__(self, battery_size):\n self.battery_size = battery_size",
"def __init__(self, battery_size=40):\n self.battery_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
print a statement describing the battery size. | def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.") | [
"def describe_battery(self):\r\n\t\tprint(\"This car has a \" + str(self.battery_size)+ \"-kWh battery.\")",
"def describe_battery(self):\n print(\"This car has a \"+str(self.battery_size)+\"-kwh battery.\")",
"def describe_battery(self):\r\n\t\tprint(\"This car has a \" + str(self.battery_size) + \"-kWh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
print a statement about the range this battery provides | def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approx. " + str(range)
message += " miles on a full charge."
print(message) | [
"def get_range( self ):\r\n if self.battery_size == 60:\r\n range = 140\r\n elif self.battery_size == 85:\r\n range = 185\r\n message = 'This car can go approximately ' + str( range )\r\n message += ' miles on a full charge.'\r\n print( message )",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
electric cars don't have gas tanks we are pretending that this method is in the parent class | def fill_gas_tank(self):
print("This car doesn't need a gas tank.") | [
"def fill_gas_tank(self):\r\n\t\tprint(\"This car doesn't need a gas tank!\")",
"def __init__(self, car, second_at_charge_name):\n super(self.__class__, self).__init__(car)\n self.second_at_charge_name = second_at_charge_name\n self.cars_at_intersection = car.get_cars_at_intersection()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make_move() > int Makes a move for the reflex agent based on a set of rules. Returns 1 if blue wins; returns 1 if red wins; returns 0 if noone wins. | def make_move(self):
# If the agent is starting a game, make an
# initial move
if self.get_play_status() == False:
self.initial_move()
return
# for speeds sake, allow the reflex agent to respond to manual
# input. comment out for automatic running.
... | [
"def make_move(self, move):\n if int(move) < 0 or int(move) > 48 or self.board[int(move) // 7][int(move) % 7] != \"\" or int(move) % 2 == 0:\n raise ValueError(\"{} is not a valid move for {}\".format(move, self.board))\n DotsAndBoxesState.score1 += self.check_score(move)\n self.boar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initial_move() Makes the first move for the agent. Returns nothing. | def initial_move(self):
# Make the first move based on the game we
# are currently playing, otherwise return
if isinstance(self.get_game_space(), Gomoku):
# play one stone in the bottom left-hand corner
self.get_game_space().set_tile(0,6,self.get_affinity())
... | [
"def make_move(self):\n\n # If the agent is starting a game, make an \n # initial move\n if self.get_play_status() == False: \n self.initial_move()\n return\n\n # for speeds sake, allow the reflex agent to respond to manual\n # input. comment out for automati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
victory_check() > (int,int) Check if the agent can win by placing one more tile. If so, return the (x,y) position of where to place the tile. | def victory_check(self):
# get essential values
board = self.get_game_space()
affinity = self.get_affinity()
# pick the right check for the game we are playing
if isinstance(board, Gomoku):
# get the possible ways to win
possible_win... | [
"def check_victory(self):\n winner = self.board.victory()\n if winner != 'n':\n if winner == 't':\n print(\"It's a tie!\")\n else:\n print(self.board)\n print('\"{0}\" won!'.format(winner))\n sys.exit(0)",
"def checkWin(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
counter_opponent_win() > None Check if the opponent is about to win, and if so, counter that move which they will make. | def counter_opponent_win(self):
# get essential values
board = self.get_game_space()
affinity = self.get_opponent().get_affinity()
# pick the right check for the game we are playing
if isinstance(board, Gomoku):
# get the possible ways for the o... | [
"def counter_opponent_adv(self):\n\n # get essential values\n board = self.get_game_space()\n affinity = self.get_affinity()\n opaffinity = self.get_opponent().get_affinity()\n\n # pick the right check for the game we are playing\n if isinstance(board, Gomoku):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
counter_opponent_adv() > None Check if the opponent has a very adventageous move, i.e., a row of three tiles with no blockage on either end. Counter this. | def counter_opponent_adv(self):
# get essential values
board = self.get_game_space()
affinity = self.get_affinity()
opaffinity = self.get_opponent().get_affinity()
# pick the right check for the game we are playing
if isinstance(board, Gomoku):
# get advant... | [
"def counter_opponent_win(self):\n\n # get essential values\n board = self.get_game_space()\n affinity = self.get_opponent().get_affinity()\n \n # pick the right check for the game we are playing\n if isinstance(board, Gomoku):\n \n # get the possible ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
best_last_option() > None Pick a move for the agent to make which is the best based on a set of understood conditions. The best move is the mostleft, mostlow move in the block containing the most tiles of the same affinity. | def best_last_option(self):
# get essential values
board = self.get_game_space()
affinity = self.get_affinity()
# pick the right check for the game we are playing
if isinstance(board, Gomoku):
# get all possible blocks to make a move in
... | [
"def _choose_best_option(self) -> None:\r\n pawn = choice(list(self._state.game.engine.get_movable_pawns()))\r\n move = choice(self._state.game.engine.get_moves_for_pawn(pawn))\r\n self._selected_pawn = pawn\r\n self._selected_move = move",
"def pickBestMove(self):\n aggressiven... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make_move() > None Makes a move for the minimax agent. Runs a search to the proper depth and prints the number of nodes expanded. Also picks the best move to make based on the search. | def make_move(self):
# get relavent information
affinity = self.get_affinity()
sample_space = self.get_game_space()
depth_limit = self.__search_depth
# run a minimax search and get the best value
bestval = MinimaxTree.minimax(self, sample_space, affinity, depth_limit, T... | [
"def make_move(self):\n\n # get relavent information\n affinity = self.get_affinity()\n sample_space = self.get_game_space()\n depth_limit = self.__search_depth\n\n # run a minimax search and get the best value\n bestval = MinimaxTree.alphabeta(self, sample_space, affinity,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make_move() > None Makes a move for the alphabeta agent. Runs a search to the proper depth and prints the number of nodes expanded. Also picks the best move to make based on the search. | def make_move(self):
# get relavent information
affinity = self.get_affinity()
sample_space = self.get_game_space()
depth_limit = self.__search_depth
# run a minimax search and get the best value
bestval = MinimaxTree.alphabeta(self, sample_space, affinity, depth_limit,... | [
"def make_move(self):\n\n # get relavent information\n affinity = self.get_affinity()\n sample_space = self.get_game_space()\n depth_limit = self.__search_depth\n\n # run a minimax search and get the best value\n bestval = MinimaxTree.minimax(self, sample_space, affinity, d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return number of occupied seats immediately adjacent to seat (r,c). | def occupied(r, c, layout):
occupy = 0
NW = (-1, -1)
NE = (-1, 1)
N = (-1, 0)
W = (0, -1)
E = (0, 1)
SW = (1, -1)
SE = (1, 1)
S = (1, 0)
for dirs in [NW, NE, N, W, E, SW, SE, S]:
dr, dc = r+dirs[0], c + dirs[1]
if (dr >= 0) and (dc >= 0) and (dr < ... | [
"def occupied_seats(data: List[str]) -> int:\r\n matrix = [list(x) for x in data]\r\n final_matrix = switch_loop(switches(matrix), matrix)\r\n\r\n return sum(x.count(\"#\") for x in final_matrix)",
"def count_neighbours(self, x, y, stop_at=8):\n possible_locations = [\n (x - 1, y - 1),\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds list of ages at which self is operable, given an action code and period index. | def operable_ages(self, acode, period):
if acode not in self.oper_expr: # action not defined for this development type
return None
if acode not in self.operability: # action not compiled yet...
if self.compile_action(acode) == -1: return None # never operable
#print ' '.j... | [
"def operable_area(self, acode, period, age=None, cleanup=True):\n if acode not in self.oper_expr: # action not defined for this development type\n return 0.\n if acode not in self.operability: # action not xf yet...\n if self.compile_action(acode) == -1: return 0. # never operab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns 0 if inoperable or no current inventory, operable area given action code and period (and optionally age) index otherwise. If cleanup switch activated (default True) and age specified, deletes the ageclass from the inventory dict if operable area is less than self.parent.area_epsilon. | def operable_area(self, acode, period, age=None, cleanup=True):
if acode not in self.oper_expr: # action not defined for this development type
return 0.
if acode not in self.operability: # action not xf yet...
if self.compile_action(acode) == -1: return 0. # never operable
... | [
"def apply_action(self,\n dtype_key,\n acode,\n period,\n age,\n area,\n override_operability=False,\n fuzzy_age=True,\n recourse_enabled=True,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If area not specified, returns area inventory for period (optionally age), else sets area for period and age. If delta switch active (default True), area value is interpreted as an increment on current inventory. | def area(self, period, age=None, area=None, delta=True):
#if area is not None:
# print area
# assert area > 0
if area is None: # return area for period and age
if age is not None:
try:
return self._areas[period][age]
e... | [
"def operable_area(self, acode, period, age=None, cleanup=True):\n if acode not in self.oper_expr: # action not defined for this development type\n return 0.\n if acode not in self.operability: # action not xf yet...\n if self.compile_action(acode) == -1: return 0. # never operab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find lower and upper ages that correspond to lo and hi values of yname (interpreted as first occurence of yield value, reading curve from left and right, respectively). | def resolve_condition(self, yname, lo, hi):
return [x for x, y in enumerate(self.ycomp(yname)) if y >= lo and y <= hi] | [
"def get_y_coordinate(height, name, name_data, year):\n \"\"\"\n Approach\n The y coordinate for plot is linear with the rank, that is:\n y = int(GRAPH_MARGIN_SIZE + (rank/MAX_RANK) * (CANVAS_HEIGHT - 2 * GRAPH_MARGIN_SIZE)\n a_height is the available height between top and bottom line\n str_year ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compile action, given action code. This mostly involves resolving operability expression strings into lower and upper operability limits, defined as (alo, ahi) age pair for each period. Deletes action from self if not operable in any period. | def compile_action(self, acode, verbose=False):
self.operability[acode] = {}
for expr in self.oper_expr[acode]:
self._compile_oper_expr(acode, expr, verbose)
is_operable = False
for p in self.operability[acode]:
if self.operability[acode][p] is not None:
... | [
"def apply_action(self,\n dtype_key,\n acode,\n period,\n age,\n area,\n override_operability=False,\n fuzzy_age=True,\n recourse_enabled=True,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compiles a ``ws3``compatible schedule data object from a solved ``ws3.opt.Problem`` instance. This is just a dispatcher functionthe actual compilation is done by a formulationspecific function (assumes Model I formulation if not specified). | def _compile_schedule_from_problem(self, problem, formulation=1, skip_null='null'):
cmp_sch_dsp = {1:self._cmp_sch_m1, 2:self._cmp_sch_m2}
return cmp_sch_dsp[formulation](problem, skip_null) | [
"def ParseSchedule(self, schedule_data):\n\n if self.verbose:\n\n print \"Parsing schedule data\"\n \n\n # Finds internal identifier for the schedule.\n if self._schedule_data.has_key('name'):\n\n self.name = schedule_data['name']\n\n if self.verbose:\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if acode corresponds to a harvesting action. | def is_harvest(self, acode):
return self.actions[acode].is_harvest | [
"def ActionEnabled(self, a, args):\r\n step = self.test_suite[self.irun][self.pc]\r\n action, arguments = step[0:2] # works whether or not step has result\r\n return (a == action and args == arguments)",
"def is_action(self) -> bool:\n return self.is_action_str(self.content)",
"def match_action(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns piece size, given development type key and age. | def piece_size(self, dtype_key, age):
return self.dtypes[dtype_key].ycomp(self.piece_size_yname)[age] * self.piece_size_factor | [
"def __get_size(self):\n\t\treturn 4*self.version + 17",
"def get_entry_size(dt_version):\n if dt_version == 1:\n return 20\n elif dt_version == 2:\n return 24\n else:\n return 40",
"def Size(self) -> int:",
"def kLen(key: Tuple[int, int]) -> int:\n return key[1].bit_length() ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns age class distribution (dict of areas, keys on age). | def age_class_distribution(self, period, mask=None, omit_null=False):
result = {age:0. for age in self.ages}
dtype_keys = self.unmask(mask) if mask else list(self.dtypes.keys())
for dtk in dtype_keys:
dt = self.dtypes[dtk]
for age in dt._areas[period]:
res... | [
"def get_age_distribution(school_type, N_classes):\n\tage_bracket = get_age_bracket(school_type)\n\tclasses = list(range(1, N_classes + 1))\n\tN_age_bracket = len(age_bracket)\n\tclasses_per_age_bracket = int(N_classes / N_age_bracket)\n\t\n\tassert N_age_bracket <= N_classes, \\\n\t'not enough classes to accommoda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns dict (keyed on development type key, values are lists of operable ages). | def operable_dtypes(self, acode, period, mask=None):
result = {}
dtype_keys = self.unmask(mask) if mask else list(self.dtypes.keys())
for dtk in dtype_keys:
dt = self.dtypes[dtk]
operable_ages = dt.operable_ages(acode, period)
if operable_ages:
... | [
"def get_age_fields():\n under_18_fields = CensusFields.get_under_18_fields()\n\n age_18_to_29_fields = [ \n 'B01001_007E', # Male:!!18 and 19 years\n 'B01001_008E', # Male:!!20 years\n 'B01001_009E', # Male:!!21 years\n 'B010... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Flexible method that compiles inventory at given period. Unit of return data defaults to area if yname not given, but takes on unit of yield component otherwise. Can be constrained by age and development type mask. | def inventory(self, period, yname=None, age=None, mask=None, dtype_keys=None, verbose=0):
result = 0.
assert not (mask and dtype_keys) # too confusing to allow both to be specified...
if mask:
_dtype_keys = self.unmask(mask, verbose=verbose)
elif dtype_keys:
_dtyp... | [
"def budget(df, df_hist, harmonize_year=\"2015\"):\n\n harmonize_year = int(harmonize_year)\n\n df = df.set_axis(df.columns.astype(int), axis=\"columns\")\n df_hist = df_hist.set_axis(df_hist.columns.astype(int), axis=\"columns\")\n\n data_years = df.columns\n hist_years = df_hist.columns\n\n year... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset areas for all development types. | def reset_areas(self, period=None):
for dtk in self.dtypes: self.dtypes[dtk].reset_areas(period) | [
"def reset_all_geo():\n all_meta = (\n extension_tables,\n geocollections,\n intersections,\n loadings,\n topocollections,\n )\n shutil.rmtree(projects.request_directory(\"regional\"))\n projects.request_directory(\"regional\")\n for meta in all_meta:\n meta.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add curve to global curve hash map (uses result of Curve.points() to construct hash key). | def register_curve(self, curve):
key = tuple(curve.points())
if key not in self.curves:
# new curve (lock and register)
curve.is_locked = True # points list must not change, else not valid key
self.curves[key] = curve
return self.curves[key] | [
"def add(self, curve_name, x, y, z):\n if curve_name not in self.data.keys():\n self.data[curve_name] = dict()\n if z not in self.data[curve_name].keys():\n self.data[curve_name][z] = dict()\n if y not in self.data[curve_name][z]:\n self.data[curve_name][z][y] =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resets actions. By default resets, all actions in all periods (except for sticky actions, unless overridden), unless period or acode specified. | def reset_actions(self, period=None, acode=None, override_sticky=False):
periods = [period] if period else self.periods
acodes = [acode] if acode else list(self.actions.keys())
for p in periods:
if p not in self.applied_actions: self.applied_actions[p] = {}
for a in acode... | [
"def reset(self):\n for action in self._action_map.values():\n action.reset()",
"def reset(self):\n self.state = InitialAction.State.inactive",
"def reset(self):\n self.state = NormalAction.State.released",
"def reset(self):\n temp = {\n \"req\": \"reset\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compiles products from applied actions in given period. Parses string expression, which resolves to a single coefficient. Operated area can be filtered on action code, development type key list, and age. Result is product of sum of filtered area and coefficient. | def compile_product(self,
period,
expr,
acode=None,
dtype_keys=None,
age=None,
coeff=False,
verbose=False):
aa = self.applied_actions
if... | [
"def evaluate(compiled_expression):",
"def _compile_expression(self):\n self._xmltranslator.open_section(\"expression\")\n self._compile_term()\n while is_op(self.tokens[self._cur_ind]):\n oper = self.tokens[self._cur_ind][\"value\"]\n self._process_token()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempts to repair the action schedule for given period, using an AreaSelector object (defaults to classdefault areaselector, which is a simple greedy oldestfirst selector). | def repair_actions(self, period, areaselector=None, verbose=False):
if areaselector is None: # use default (greedy) selector
areaselector = self.areaselector
aa = copy.copy(self.applied_actions[period])
self.reset_actions(period)
for acode in aa:
if not aa[acode]:... | [
"def apply_action(self,\n dtype_key,\n acode,\n period,\n age,\n area,\n override_operability=False,\n fuzzy_age=True,\n recourse_enabled=True,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Commits applied actions (i.e., apply transitions and grow, default starting at period 1). By default, will attempt to repair broken (infeasible) future actions, attempting to replace infeasiblea operated area using default AreaSelector. | def commit_actions(self, period=1, repair_future_actions=False, verbose=False):
while period < self.horizon:
if verbose: print('growing period', period)
self.grow(period, cascade=False)
period += 1
if repair_future_actions:
if verbose: print('repai... | [
"def handle_apply(self):\n self._validate_transition(self.actions.APPLY,\n {self.states.UNCOMMITTED,\n self.states.ABANDONED})\n self.state = self.states.APPLIED",
"def repair_actions(self, period, areaselector=None, verbose=False):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies action, given action code, development type, period, age, area. Can optionally override operability limits, optionally use fuzzy age (i.e., attempt to apply action to proximal age class if specified age is not operable), optionally use default AreaSelector to patch missing area (if recourse enabled). Applying a... | def apply_action(self,
dtype_key,
acode,
period,
age,
area,
override_operability=False,
fuzzy_age=True,
recourse_enabled=True,
area... | [
"def operable_area(self, acode, period, age=None, cleanup=True):\n if acode not in self.oper_expr: # action not defined for this development type\n return 0.\n if acode not in self.operability: # action not xf yet...\n if self.compile_action(acode) == -1: return 0. # never operab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new development type, given a key (checks for existing, autoassigns yield compompontents, autoassign actions and transitions, checks for operability (filed under inoperable if applicable). | def create_dtype_fromkey(self, key):
assert key not in self.dtypes # should not be creating new dtypes from existing key
dt = DevelopmentType(key, self)
self.dtypes[key] = dt
# assign yields
for mask, t, ycomps in self.yields:
if self.match_mask(mask, key):
... | [
"def make_test_case(self, key: StorageTestData) -> test_case.TestCase:\n verb = 'save' if self.forward else 'read'\n tc = test_case.TestCase()\n tc.set_description(verb + ' ' + key.description)\n dependencies = automatic_dependencies(\n key.lifetime.string, key.type.string,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports OUTPUTS section from a Forest model. | def import_outputs_section(self, filename_suffix='out'):
with open('%s/%s.%s' % (self.model_path, self.model_name, filename_suffix)) as f:
s = f.read()
self._resolve_outputs_buffer(s) | [
"def read_outputs_from_model(self):\n # Validate there is a model available:\n if self._model is None:\n raise mlrun.errors.MLRunRuntimeError(\n \"The model in this handler was not loaded or given in initialization so the outputs cannot be read.\"\n )\n\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return list of base codes, given theme index. | def theme_basecodes(self, theme_index):
return self._theme_basecodes[theme_index]
#return self._themes[theme_index] | [
"def base_codes(self):\n bases = []\n\n if self.is_gas_giant:\n bases.append(\"G\")\n if self.is_naval_base:\n bases.append(\"N\")\n if self.is_scout_base:\n bases.append(\"S\")\n if self.is_research_base:\n bases.append(\"R\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports AREAS section from a Forest model. | def import_areas_section(self, model_path=None, model_name=None, filename_suffix='are', import_empty=False):
n = self.nthemes
model_path = self.model_path if not model_path else model_path
model_name = self.model_name if not model_name else model_name
with open('%s/%s.%s' % (model_path, ... | [
"def importAovs(self):\n\t\tLayersInfo = pickle.load( open( self.aovsPath.path, \"rb\") )\n\t\tmc.refresh( su = 1 )\n\t\tfor ao in LayersInfo.keys():\n\t\t\taov.create( ao, LayersInfo[ao]['name'], LayersInfo[ao]['type'], LayersInfo[ao]['enabled'] )\n\t\tmc.refresh( su = 0 )",
"def import_model(file):\n fil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if key matches mask. | def match_mask(self, mask, key):
#dt = self.dtypes[key]
for ti, tac in enumerate(mask):
if tac == '?': continue # wildcard matches all keys
tacs = self._expand_theme(self._themes[ti], tac)
if key[ti] not in tacs: return False # reject key
return True # key mat... | [
"def HasMask(self) -> bool:\n ...",
"def has_mask(self):\r\n return hasattr(self, '_has_mask')",
"def test_sensitive_mask(self):\n for val in self.vals:\n sensitive = utils.Sensitive(val)\n self.assertTrue(re.match(r'\\*+', sensitive.mask()))",
"def IsMaskEnabled(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iteratively filter list of development type keys using mask values. Accepts Woodstockstyle string masks to facilitate cutandpaste testing. | def unmask(self, mask, verbose=0):
if isinstance(mask, str): # Woodstock-style string mask format
mask = tuple(re.sub('\s+', ' ', mask).lower().split(' '))
assert len(mask) == self.nthemes # must be bad mask if wrong theme count
else:
try:
assert isins... | [
"def filter_dict(fdict, mask):\n\n if fdict is None:\n fdict = dict()\n\n if mask is None:\n mask = []\n\n return {k: v for (k, v) in fdict.items() if k in mask}",
"def filters_from_dict(fdict):\n return [lambda w: not any(fw in w for fw in fdict['infix']),\n lambda w: not any... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports CONSTANTS section from a Forest model. | def import_constants_section(self, filename_suffix='con'):
with open('%s/%s.%s' % (self.model_path, self.model_name, filename_suffix)) as f:
for lnum, l in enumerate(f):
if re.match('^\s*(;|$)', l): continue # skip comments and blank lines
l = l.strip().partition(';')... | [
"def load_from_constants(self):\n constant_settings = import_module('mindinsight.conf.constants')\n for setting in dir(constant_settings):\n if setting.isupper():\n setattr(self, setting, getattr(constant_settings, setting))",
"def _imported_constants_from_scope(self, expr,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports YIELDS section from a Forest model. | def import_yields_section(self, filename_suffix='yld', mask_func=None, verbose=False):
###################################################
# local utility functions #########################
def flush_ycomps(t, m, n, c):
#if verbose: print t, m, n, c
#self.ycomps.update(n... | [
"def enaml_importer():\n print(imports, dir(imports))\n old = imports.get_importers()\n\n yield imports\n\n imports._imports__importers = old",
"def setupFromYml(self, yml):",
"def load():\n from . import (BlockGrassBlock, BlockDirt, BlockCraftingTable)",
"def _load_tail(self, m, tail):\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports ACTIONS section from a Forest model. | def import_actions_section(self, filename_suffix='act', mask_func=None, nthemes=None):
nthemes = nthemes if nthemes else self.nthemes
actions = {}
#oper = {}
aggregates = {}
partials = {}
keyword = ''
with open('%s/%s.%s' % (self.model_path, self.model_name, filen... | [
"def import_actions(self):\n self.get_id_maps(['templates', 'hostgroups'])\n # self.original_ids = json.load(open(self.original_ids_file))\n try:\n self.zbx_client.action.delete(\"3\")\n except ZabbixAPIException as err:\n # todo: add checking for failures when obje... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluate or condition. Returns list of ages. | def resolve_condition(self, condition, dtype_key=None):
if not condition:
return self.ages
elif condition.startswith('@AGE'):
lo, hi = [int(a) for a in condition[5:-1].split('..')]
return list(range(lo, hi+1))
elif condition.startswith('@YLD'):
arg... | [
"def animal_ages(self):\n herb_ages = []\n carn_ages = []\n for cell in self.land_cells.values():\n for herb in cell.herbivores:\n herb_ages.append(herb.age)\n for carn in cell.carnivores:\n carn_ages.append(carn.age)\n if not herb_ages... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports TRANSITIONS section from a Forest model. | def import_transitions_section(self, filename_suffix='trn', mask_func=None, nthemes=None):
nthemes = nthemes if nthemes else self.nthemes
# local utility function ####################################
def flush_transitions(acode, sources):
if not acode: return # nothing to flush on fi... | [
"def load_transform_graph(self):\n saved_transform_io.partially_apply_saved_transform_internal(\n self.transform_savedmodel_dir, {})",
"def _load_transform_saved_model(transform_savedmodel_dir):\n saved_model = saved_model_loader.parse_saved_model(\n transform_savedmodel_dir)\n meta_graph_def = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports OPTIMIZE section from a Forest model. | def import_optimize_section(self, filename_suffix='opt'):
pass | [
"def create_optimiser(self):",
"def get_optimizer():\n ##################\n # YOUR CODE HERE #\n ##################",
"def importOptimizer():\n module_path = os.path.join(path, \"optimization\")\n module_path = os.path.join(module_path, \"optimizer.py\")\n optimizer_class = importClass(\"Optim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports SCHEDULE section from a Forest model. | def import_schedule_section(self, filename_suffix='seq', replace_commas=True, filename_prefix=None):
filename_prefix = self.model_name if filename_prefix is None else filename_prefix
schedule = []
n = self.nthemes
with open('%s/%s.%s' % (self.model_path, filename_prefix, filename_suffix)... | [
"def loadSchedule(self, fname):\n\n\t\t# Open the file, iterate over rows, extract first columen (count)\n\t\t# and all opened valves\n\t\twith open(fname, \"rb\") as csvfile:\n\t\t\treader = csv.reader(csvfile, delimiter = \",\", quotechar = \"\\\"\")\n\t\t\tmaxcolumns = 0\n\n\t\t\tfor row in reader:\n\t\t\t\tt = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports CONTROL section from a Forest model. | def import_control_section(self, filename_suffix='run'):
pass | [
"def loadAdjustedModel(self):\r\n # Load model in GUI\r\n addModel(self.trcFilePath.replace('.trc','.osim'))",
"def import_model(self):\n gen_path = os.path.join(smtk.testing.DATA_DIR,\n 'model/3d/genesis/filling1.gen')\n import_op = smtk.session.vtk.Impo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
performs an asynchronous (nonblocking) request | def async_request(self, callback, *args):
seq = self.send_request(*args)
self.async_replies[seq] = callback | [
"def _asyncRequest(self, type, doc, callback=None):\n\n # build a quick closure to call the request\n # silently, in case the server isn't running\n # or whatever\n def safe_caller():\n try:\n data = self._makeRequest(type, doc, \\\n raiseEr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
serves a single request or reply (may block) | def serve(self):
self.channel.wait()
handler, seq, obj = self._recv()
if handler == "result":
self.dispatch_result(seq, obj)
elif handler == "exception":
self.dispatch_exception(seq, obj)
else:
self.dispatch_request(handler, seq, obj) | [
"def __call__(self):\n hub.sleep(random.randint(1, self.interval))\n while True:\n self.send_req()\n self.reply_pending = True\n hub.sleep(self.interval)\n if self.reply_pending:\n self.no_response()",
"def _onresponse(self, msg):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Eventually call a command to get the value, if the value starts and ends with quotes "`". | def eventually_call_command(value):
if value.startswith(u'`') and value.endswith(u'`'):
cmd = value[1:-1]
try:
processed_value = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError as e:
raise ValueError(u'The call to the external tool failed... | [
"def get_value(command):\n if is_get(command) or is_delete(command):\n return None\n elif is_insert(command) or is_update(command):\n return command.split(\" \")[2]",
"def _get_value_from_command_line(self):\r\n \r\n # check precondition\r\n if self._cli_arg == None:\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get_originating_ray returns the ray (if any) which originated from this location | def get_originating_ray(self):
return self._originating_ray | [
"def ray(self):\n return self._ray",
"def get_mouse_ray(self, context, event):\n region, rv3d = context.region, context.region_data\n coord = event.mouse_region_x, event.mouse_region_y\n ray_direction = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord)\n ray_origin = view3d_u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set_originating_ray sets the set_originating_ray property | def set_originating_ray(self, ray):
self._originating_ray = ray | [
"def get_originating_ray(self):\n return self._originating_ray",
"def set_terminating_ray(self, location):\n self._terminating_ray = location",
"def propagate_ray(self, ray):\n \t\traise NotImplementedError()",
"def ray(self):\n return self._ray",
"def set_origin_displace( self , origin , ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get_terminating_ray returns the origin of any ray terminating at the square | def get_terminating_ray(self):
return self._terminating_ray | [
"def get_originating_ray(self):\n return self._originating_ray",
"def ray(self):\n return self._ray",
"def shoot_ray(self, origin_row, origin_column):\n\n # get the the square object at row x column\n origin = self._board.get_board_square((origin_row, origin_column))\n\n # check t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set_terminating_ray Records that a ray terminates at the square | def set_terminating_ray(self, location):
self._terminating_ray = location | [
"def get_terminating_ray(self):\n return self._terminating_ray",
"def set_originating_ray(self, ray):\n\n self._originating_ray = ray",
"def shoot_ray(self, origin_row, origin_column):\n\n # get the the square object at row x column\n origin = self._board.get_board_square((origin_row... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
is_edge returns whether or not the square is an "edge" of the board from which a ray can be shot | def is_edge(self):
if self._row == 0 or self._row == 9 or self._column == 0 or self._column == 9:
# check that the edge is not actually a corner square
if not self.is_corner():
# If not a corner and in a border row return True
return True
return F... | [
"def _is_on_edge(tile):\n tile_left, tile_bottom, tile_right, tile_top = tile.bounds\n touches_left = tile_left <= tile.tile_pyramid.left\n touches_bottom = tile_bottom <= tile.tile_pyramid.bottom\n touches_right = tile_right >= tile.tile_pyramid.right\n touches_top = tile_top >= tile.tile_pyramid.to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set_atom sets the status of a square regarding containing an atom | def set_atom(self, status):
self._atom = status | [
"def set_atom(self, locant, atom):\n atom.set_id(locant)\n if locant >= self._next_locant:\n self._next_locant = locant + 1\n self._atom_index[locant] = atom\n self._graph.add_vertex(atom)",
"def test_set_molecule(self):\n mol = Molecule.from_smiles(\"CCO\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
is_atom returns a Bool indicating whether or not a square contains an atom | def is_atom(self):
return self._atom | [
"def is_atom(atomline: str) -> bool:\n # no empty line, not in cards and not space at start:\n if atomline[:4].upper() not in SHX_CARDS: # exclude all non-atom cards\n spline: List[str] = atomline.split()\n # Too few parameter for an atom:\n if len(spline) < 5:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
toggle_selected toggles the current value of a square's _selected property | def toggle_selected(self):
self._selected = not self._selected | [
"def is_selected(self):\n self.state = 1\n self.colour = selected_color",
"def toggle_selection(self):\n if self.selection_visible:\n self.canvas.itemconfig(self.selection, state='hidden')\n self.selection_visible = False\n else:\n self.canvas.itemconfi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate an assembled solid shaft using the BRepBuilderAPI_MakeSolid algorithm. This method requires PythonOCC to be installed. | def generate_solid(self):
ext = os.path.splitext(self.filename)[1][1:]
if ext == 'stl':
shaft_compound = read_stl_file(self.filename)
elif ext == 'iges':
iges_reader = IGESControl_Reader()
iges_reader.ReadFile(self.filename)
iges_reader.TransferRoo... | [
"def fcc(filename = '/mnt/hgfs/10_19_simple_shear/VPSC/sx/hijhiihb.sx',\r\n hii = 1.0, hij = 1.4, hb = -0.4,\r\n tau0 = 1.0, tau1 = 0.2, thet0 = 1.0, thet1 = 0.05,\r\n #tau0 = 1.045e2, tau1= 70., thet0 = 2.6e2, thet1 = 0.95e2,\r\n hpfac = 0., gndfac = 0., header = '** material info',\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Representation of this atom | def __repr__(self):
x, y, z = self.coord
return f'Atom({self.label}, {x:.4f}, {y:.4f}, {z:.4f})' | [
"def __repr__(self):\n return (\n f\"<Element: {self.name}, symbol: {self.symbol}, \"\n f\"atomic number: {self.atomic_number}, mass: {self.mass.to('amu')}>\"\n )",
"def get_atom(self):\n\n return self._atom",
"def __repr__(self) -> str:\n return str(self.atomke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Atomic numbers are the position in the elements (indexed from zero), | def atomic_number(self) -> int:
return elements.index(self.label) + 1 | [
"def element_atomic_number(self, element): # pragma: no cover\n raise NotImplementedError",
"def get_atomic_numbers(self):\n if self._atomic_numbers is None:\n self._atomic_numbers = [[data[1].upper() for data in atom_data].index(element.upper())\n for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Row of transition metals that this element is in. Returns None if | def tm_row(self) -> Optional[int]:
for row in [1, 2, 3]:
if self.label in PeriodicTable.transition_metals(row):
return row
return None | [
"def get_full_transitions(self, row, column):\n return self.grid[row][column]",
"def next(self):\n if self.index < len(self.layout.sequence) - 1:\n return self.layout.rows[self.layout.sequence[self.index + 1]]\n else:\n return None",
"def transition_entry(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The maximum/maximal valance that this atom supports in any charge state (most commonly). i.e. for H the maximal_valance=1. Useful for generating molecular graphs | def maximal_valance(self) -> int:
max_valances = {'H': 1, 'B': 4, 'C': 4, 'N': 4, 'O': 3, 'F': 1,
'Si': 4, 'P': 6, 'S': 6, 'Cl': 4, 'Br': 4, 'I': 6}
if self.label in max_valances:
return max_valances[self.label]
else:
logger.warning(f'Could not f... | [
"def calculate_max_Evac(self):\n self.Evac_max = np.sqrt(sc.constants.hbar*2*math.pi*(sc.constants.c/self.lambda_i)/(2*sc.constants.epsilon_0*self.mode_volume))/self.n_z0",
"def charge_max_ampere(self):\n return self.attrs.get('vehicleEmanager').get('rbc').get('settings').get('chargerMaxCurrent')",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rotate this atom theta radians around an axis given an origin. By default the rotation is applied around the origin with the angle in radians (unless an autode.values.Angle). Rotation is applied in | def rotate(self,
axis: Union[np.ndarray, Sequence],
theta: Union[Angle, float],
origin: Union[np.ndarray, Sequence, None] = None) -> None:
# If specified, shift so that the origin is at (0, 0, 0)
if origin is not None:
self.translate(vec=-np.as... | [
"def _rotate_about_origin(self, angle, axis):\n matrix = rotation_matrix(angle, axis)\n self._normal = matrix.dot(self._normal)\n self._position = matrix.dot(self._position)",
"def _rotate_about_origin(self, angle, axis):\n matrix = rotation_matrix(angle, axis)\n self._center = matrix.dot(self._cen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The atomic number is defined as 0 for a dummy atom | def atomic_number(self):
return 0 | [
"def atomic_number(a):\n\n return a.GetAtomicNum()",
"def zero(self):\n self.counter.set_value(0)",
"def GetAtomicNum(self) -> int:\n return self.atomic_num",
"def element_atomic_number(self, element): # pragma: no cover\n raise NotImplementedError",
"def atomic_number(self) -> int:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add another set of Atoms to this one. Can add None | def __add__(self, other):
if other is None:
return self
return super().__add__(other) | [
"def _add(self, other):\n return None",
"def __add__(self, other: 'Monoid[A]') -> 'Monoid[A]':\n return self.mappend(other)",
"def __add__(self, other: NFA) -> Self:\n if isinstance(other, NFA):\n return self.concatenate(other)\n else:\n return NotImplemented",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy these atoms, deeply | def copy(self) -> 'Atoms':
return deepcopy(self) | [
"def copy(self):\n\n copy = self.__class__(*[a.copy() for a in self.atoms()])\n copy._id, copy._name = self._id, self._name\n return copy",
"def __deepcopy__(self, memo) -> \"IC_Chain\":\n existing = memo.get(id(self), False)\n if existing:\n return existing\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all the dummy atoms from this list of atoms | def remove_dummy(self) -> None:
for i, atom in enumerate(self):
if isinstance(atom, DummyAtom):
del self[i]
return | [
"def clear_dummy_obj(self):\n for d in self.dummies:\n self.map.remove_node(d)\n\n self.dummies = []",
"def removeDoubleUnbondedAtoms (self):\r\n atomsToRemove = [] # Stores index of atoms we will need to remove\r\n \r\n # Go through each mol\r\n for i in range... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Vector from atom i to atom j | def vector(self,
i: int,
j: int) -> np.ndarray:
return self[j].coord - self[i].coord | [
"def vec_swap_entries(x, i, j):\n xi = x[i]\n xj = x[j]\n x = x.at[i].set(xj)\n x = x.at[j].set(xi)\n return x",
"def nvector(self,\n i: int,\n j: int) -> np.ndarray:\n vec = self.vector(i, j)\n return vec / np.linalg.norm(vec)",
"def vector_result(j):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalised vector from atom i to atom j | def nvector(self,
i: int,
j: int) -> np.ndarray:
vec = self.vector(i, j)
return vec / np.linalg.norm(vec) | [
"def vector(self,\n i: int,\n j: int) -> np.ndarray:\n return self[j].coord - self[i].coord",
"def unit_vectors(x):\n xnew = x.copy()\n for v in range(x.shape[-1]):\n xnew[:, v] = x[:, v] / np.linalg.norm(x[:, v])\n return xnew",
"def normal_vector(v):\n\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the coordinates from a numpy array | def coordinates(self,
value: np.ndarray):
if self.atoms is None:
raise ValueError('Must have atoms set to be able to set the '
'coordinates of them')
if value.ndim == 1:
assert value.shape == (3 * self.n_atoms,)
value ... | [
"def setCoords(self, coords):\n self.coords = coords",
"def set_coords(self, coords):\n try:\n coords = np.reshape(coords, (-1,3))\n except ValueError:\n raise Exception('Coordinates cannot be reshaped into matrix of size Nx3')\n assert len(coords) == len(self.ato... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Are a set of indexes present in the collection of atoms? | def _idxs_are_present(self, *args):
return set(args).issubset(set(range(self.n_atoms))) | [
"def is_indset(adj_lists, a):\n return all(w not in adj_lists[v] for v in a for w in a)",
"def get_indexes(self):\n return set(k.index for k in self if k.has_index)",
"def _check_index_contains_sets(self):\n index_types = [ type(x) for x in self.index.values() ]\n if not all([ x== type(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Dihedral angle between four atoms (x, y, z, w), where the atoms are | def dihedral(self,
w: int,
x: int,
y: int,
z: int) -> Angle:
if not self._idxs_are_present(w, x, y, z):
raise ValueError(f'Cannot calculate the dihedral angle involving '
f'atoms {z}-{w}-{x}-{y}. At leas... | [
"def dihedral_angle(a, b, c, d):\n \n v = b - c\n m = numpy.cross((a - b), v)\n m /= norm(m)\n n = numpy.cross((d - c), v)\n n /= norm(n)\n\n c = numpy.dot(m, n)\n s = numpy.dot(numpy.cross(n, m), v) / norm(v)\n \n angle = math.degrees(math.atan2(s, c)) \n\n if angle > 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |