query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Sets the payment_method of this ChannelOrderRequest. | def payment_method(self, payment_method):
if (self.local_vars_configuration.client_side_validation and
payment_method is not None and len(payment_method) > 50):
raise ValueError("Invalid value for `payment_method`, length must be less than or equal to `50`") # noqa: E501
if (self.local_vars_configuration.client_side_validation and
payment_method is not None and len(payment_method) < 0):
raise ValueError("Invalid value for `payment_method`, length must be greater than or equal to `0`") # noqa: E501
self._payment_method = payment_method | [
"def payment_method_type(self, payment_method_type):\n if payment_method_type is None:\n raise ValueError(\"Invalid value for `payment_method_type`, must not be `None`\")\n\n self._payment_method_type = payment_method_type",
"def setPayment(self, payment):\n self.payment = payment"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the payment_reference_no of this ChannelOrderRequest. | def payment_reference_no(self, payment_reference_no):
if (self.local_vars_configuration.client_side_validation and
payment_reference_no is not None and len(payment_reference_no) > 250):
raise ValueError("Invalid value for `payment_reference_no`, length must be less than or equal to `250`") # noqa: E501
if (self.local_vars_configuration.client_side_validation and
payment_reference_no is not None and len(payment_reference_no) < 0):
raise ValueError("Invalid value for `payment_reference_no`, length must be greater than or equal to `0`") # noqa: E501
self._payment_reference_no = payment_reference_no | [
"def contact_payment(self, contact_payment):\n\n self._contact_payment = contact_payment",
"def set_bill_payment_id(self, bill_payment_id):\n self.bill_payment_id = bill_payment_id",
"def card_authorization_reference_number(self, card_authorization_reference_number):\n\n self._card_authoriz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the shipping_costs_incl_vat of this ChannelOrderRequest. | def shipping_costs_incl_vat(self, shipping_costs_incl_vat):
if self.local_vars_configuration.client_side_validation and shipping_costs_incl_vat is None: # noqa: E501
raise ValueError("Invalid value for `shipping_costs_incl_vat`, must not be `None`") # noqa: E501
if (self.local_vars_configuration.client_side_validation and
shipping_costs_incl_vat is not None and shipping_costs_incl_vat < 0): # noqa: E501
raise ValueError("Invalid value for `shipping_costs_incl_vat`, must be a value greater than or equal to `0`") # noqa: E501
self._shipping_costs_incl_vat = shipping_costs_incl_vat | [
"def set_require_confirmed_shipping( self, required ):\n\n req = '1' if required else '0'\n self._nvp_request['REQCONFIRMSHIPPING'] = req",
"def adjusted_shipping(self, adjusted_shipping):\n\n self._adjusted_shipping = adjusted_shipping",
"def update_total(self):\n self.order_total =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the order_date of this ChannelOrderRequest. | def order_date(self, order_date):
if self.local_vars_configuration.client_side_validation and order_date is None: # noqa: E501
raise ValueError("Invalid value for `order_date`, must not be `None`") # noqa: E501
self._order_date = order_date | [
"def set_order(self, order_key: str) -> None:\n if order_key not in self.orders:\n raise exceptions.CommandError(\n \"Unknown flow order: %s\" % order_key\n )\n order_key = self.orders[order_key]\n self.order_key = order_key\n newview = sortedcontaine... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the channel_customer_no of this ChannelOrderRequest. | def channel_customer_no(self, channel_customer_no):
if (self.local_vars_configuration.client_side_validation and
channel_customer_no is not None and len(channel_customer_no) > 50):
raise ValueError("Invalid value for `channel_customer_no`, length must be less than or equal to `50`") # noqa: E501
if (self.local_vars_configuration.client_side_validation and
channel_customer_no is not None and len(channel_customer_no) < 0):
raise ValueError("Invalid value for `channel_customer_no`, length must be greater than or equal to `0`") # noqa: E501
self._channel_customer_no = channel_customer_no | [
"def customer_order_number(self, customer_order_number):\n\n self._customer_order_number = customer_order_number",
"def channel_order_no(self, channel_order_no):\n if self.local_vars_configuration.client_side_validation and channel_order_no is None: # noqa: E501\n raise ValueError(\"Inva... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the extra_data of this ChannelOrderRequest. | def extra_data(self, extra_data):
self._extra_data = extra_data | [
"def extra_info(self, extra_info: Dict):\n\n self._extra_info = extra_info",
"def extra_fields(self, extra_fields):\n\n self._extra_fields = extra_fields",
"def __set_request_data(self, request_data):\n if request_data is None:\n self.__request_data = None\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
when we change the branch, effects on help desk, talent acquisition, GR, HR, etc. | def onchange_branch_id(self):
self.helpdesk_ids = False
self.talent_acquisition_ids = False
self.gr_ids = False
self.hr_ids = False
self.finance_ids = False
self.admin_ids = False
self.payroll_ids = False
self.driver_ids = False
self.hop_ids = False | [
"def action_update(self):\n if self.related_type == 'github':\n local_branches = [br.name for br in self.branch_ids]\n remote_branches = []\n for b in self._get_repo()[0].get_branches():\n remote_branches.append(b.name)\n if b.name not in local_b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads a .edf file. | def read_edf(path: str, immutable=True) -> Tuple[ Dict[str, Any], Dict[str, Sequence[float]] ] :
# def read_edf(path: str):
data_file = open(path, 'rb')
header = read_header(data_file)
signals = read_signals(data_file, header, immutable=immutable)
data_file.close()
for label in header['labels']:
# compute sampling frequency for every channel
header['signal_infos'][label]['frequency'] = header['signal_infos'][label]['num_samples_in_record'] / header['record_duration']
# compute length for each channel
header['signal_infos'][label]['num_samples'] = len(signals[label])
return header, signals | [
"def test_read_from_edf(self):\n self._compare_reader_with_expected_attrs(self.reader_from_edf,\n self.expected_start_time, self.expected_sample_freqs,\n self.expected_units, self.expected_ECG_head,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scales the signal from digital (arbitrary) to physical (uV) units. | def scale(physical_max: float, digital_max: float, signal: Sequence[float]):
# note: this function will increase the computational complexity of Reader
signal *= physical_max / digital_max
return signal | [
"def scale(self, factor: 'float') -> \"void\":\n return _coin.SbViewVolume_scale(self, factor)",
"def scale(self, factor: 'double') -> \"void\":\n return _coin.SbDPViewVolume_scale(self, factor)",
"def scale(self, value):\n\t\tfor val in self.dilutions:\n\t\t\tself.dilutions[val] /= value",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates this packet's 'current_position' from its 'pod_speed' | def update_postion_pod(self):
self.current_position += self.pod_speed | [
"def update_pos(self) -> None:\n self.pos = (self.pos[0] + self.touch.dpos[0], self.pos[1] + self.touch.dpos[1])",
"def update_pos(self):\n\t\tself.pos += self.vel",
"def _update_velocity_position(self):\n # Define the hyperparameters from kwargs dictionary\n c1, c2, m = self.kwargs['c1'], ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a code string(int string) into a fixedwith binary string, padding with 0s. | def pad_bin_code(code_str, code_width):
return (code_width - len(bin(code_str)) + 2) * "0" + bin(code_str)[2 : ] | [
"def encode_string(S):\n if S != '':\n S = '{0:b}'.format(int(hexlify(S), 16))\n while (len(S) % 8) != 0:\n S = '0' + S\n if (len(S) >= 0) and (len(S) < 2040):\n U = left_encode(len(S)) + S\n return U\n else:\n print ('Invalid bit string (encode_string)')",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the hashcodes of all the sentences in the corpus from a given path. | def load_corpus_hashcode(codes_path):
src_f = open(codes_path, "r")
corpus_hashcodes = []
for ln in src_f:
corpus_hashcodes.append(int(ln.strip()))
return corpus_hashcodes | [
"def load_sentences(path, lower, zeros):\n sentences = []\n sentence = []\n num = 0\n for line in codecs.open(path, 'r', 'utf8'):\n num+=1\n line = zero_digits(line.rstrip()) if zeros else line.rstrip()\n # print(list(line))\n if not line:\n if len(sentence) > 0:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the amount of damage a move does. If the move doesn't exist or if the player ran out of those moves, this will return 0. If the move is valid, it will return the amount of damage it will do. move => String returns => Int | def attack(self, move):
try:
if self.moves[move] <= 0:
return 0
except KeyError:
return 0
else:
extra_damage = random.randint(1, 5)
with open('move_damage.json') as damage_file:
return json.loads(damage_file.read())["Mario"][move] + extra_damage | [
"def opp_open_move_score(game, player):\n if game.is_loser(player):\n return float(\"-inf\")\n\n if game.is_winner(player):\n return float(\"inf\")\n\n return 8-float(len(game.get_legal_moves(game.get_opponent(player))))",
"def number_of_moves(self, player):\n return len(self.history... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the damage an enemy will do after Mario's defence. enemy_damage => Int returns => Int | def defend(self, enemy_damage):
return enemy_damage - random.randint(0, 5) | [
"def _calc_damage(self, enemy_level):\n return ((((enemy_level + self.level - 1) // self.level) - 1) *\n enemy_level)",
"def take_damage(self, damage):\n # self.current_health -= self.defend(damage)\n # return self.current_health",
"def _calculate_damage(self, attack: int) ->... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse heading names from a file path | def extract_heading_name(file_path: str) -> Tuple[str, str]:
file_base = os.path.basename(file_path)
both_headings = os.path.splitext(file_base)[0]
heading1, heading2 = both_headings.split('-')
return heading1, heading2 | [
"def parse_header_path(header_path):\n\n (\n *_,\n radiative_transfer_code,\n model_photospheres,\n isotopes,\n folder,\n basename,\n ) = header_path.split(\"/\")\n\n parts = basename.split(\"_\")\n # p_apst{gd}{spectral_type}_{date}_lsf{lsf}_{aspcap}_012_075\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the dataframe containing papers' percentiles and pageranks | def load_percentile_data(heading1:str , heading2: str, base_dir='viz_dataframes') -> pd.DataFrame:
path = f'{base_dir}/percentiles/{heading1}-{heading2}.pkl'
if os.path.exists(path):
with open(path, 'rb') as in_file:
result_df = pkl.load(in_file)
else:
path = f'{base_dir}/percentiles/{heading2}-{heading1}.pkl'
with open(path, 'rb') as in_file:
result_df = pkl.load(in_file)
return result_df | [
"def load_precipout(url, year=None):\n df = table_to_frame(get_table(url))\n\n if year:\n df['year'] = year\n\n return df",
"def calculate_percentiles(self):\n self.percentile_low = np.percentile(self.data, 25)\n self.percentile_high = np.percentile(self.data, 75)",
"def create_df(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the dataframe containing information about journals across fields | def load_journal_data(heading1: str, heading2: str, base_dir='viz_dataframes') -> pd.DataFrame:
path = f'{base_dir}/journals/{heading1}-{heading2}.pkl'
if os.path.exists(path):
with open(path, 'rb') as in_file:
result_df = pkl.load(in_file)
else:
path = f'{base_dir}/journals/{heading2}-{heading1}.pkl'
with open(path, 'rb') as in_file:
result_df = pkl.load(in_file)
return result_df | [
"def handle_actors_df(self):\r\n credits_cp = self.credits.copy()\r\n credits_cp['cast'] = credits_cp['cast'].apply(lambda row: ast.literal_eval(row))\r\n\r\n actors_df = self.metadata_nested_transformer(\r\n df=credits_cp,\r\n main_column='cast',\r\n secondary_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all dishes (CSV version) | def get(self):
if not current_user.is_host():
abort(403, "Forbidden")
all_dishes = Dish.query.all()
rows = []
for dish in all_dishes:
invitation = Invitation.query.filter_by(id=dish.invitation_id).first();
if invitation is None:
continue
rows.append({
'id': dish.id,
'dish_type': dish.dish_type,
'name': dish.name,
'desc': dish.desc,
'invitation_id': dish.invitation_id,
'invitation_name': invitation.name,
'allergens': ", ".join([x.name for x in dish.allergens]),
'special_preparation': ", ".join([x.name for x in dish.special_preparations]),
})
si = io.StringIO()
keys = rows[0].keys() if len(rows) > 0 else []
cw = csv.DictWriter(si, fieldnames=keys)
cw.writeheader()
cw.writerows(rows)
output = make_response(si.getvalue())
output.headers["Content-Disposition"] = "attachment; filename=food.csv"
output.headers["Content-type"] = "text/csv"
return output | [
"def csv():\n\n print \"HOST,GUEST,PERSISTENT,ACTIVE,LUN,LV,MASK,SNAP,POOL,SIZE\"\n\n for host in config.HOSTS:\n doms = guests(host, alldoms=True)\n\n for dom in doms:\n printcsv(host, dom)",
"def get_dishes(restaurant_id):\n db_session = current_app.config[\"DB_SESSION\"]\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Number of main arguments of Fx (t,x,u,xdot), not counting parameters | def nArgs(self):
n=2 # x and t
if self.has_input:
n+=1 #u
if self.implicit:
n+=1 # xdot
return n | [
"def nArgsOutput(self):\n return self.nArgsImplicit-1",
"def _num_arguments(func: Callable) -> int:\n sig = signature(func)\n return len(sig.parameters)",
"def arguments():\n if len(sys.argv) == 3:\n cov = 50\n iden = 25\n\n elif len(sys.argv) == 5:\n if sys.argv[3].isnum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Number of main arguments of the output equation Fx (t,x,u), not counting parameters | def nArgsOutput(self):
return self.nArgsImplicit-1 | [
"def nArgs(self):\n n=2 # x and t\n if self.has_input:\n n+=1 #u\n if self.implicit:\n n+=1 # xdot\n return n",
"def n_independent_parameters(self):\n return",
"def num_sol( at, y0, params):\r\n nSteps = at.shape[0]# this is to define the start of our ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a user to the data base | def add_user(self, user: User) -> None:
pass | [
"def add_user(self):\n db.session.flush()\n db.session.add(self)\n db.session.commit()",
"def add_user(self, id, name):\n\t\tconnection = self.connect_to_db()\n\t\tcursor = connection.cursor()\n\n\t\tcursor.execute(\"insert into users values (%s, %s, %s, %s);\", (id,name, '{}', '{}'))\n\t\tco... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edits a user, setting a new attribute, given as a dictionary. The dictionary key must be an atribute of the User dataclass | def edit_user(self, user: User, attribute: dict[str, Any]) -> None:
pass | [
"def set_attr(self, user, key, value):\n query1 = \"\"\"SELECT attr_value FROM attributes WHERE attr_uid = ?\n AND attr_key = ?\"\"\"\n query2 = \"INSERT INTO attributes VALUES (?, ?, ?)\"\n query3 = \"\"\"UPDATE attributes SET attr_value = ? WHERE attr_uid = ?\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a dict of attributes to a user object | def convert_attributes_user(attributes: dict[str, Any]) -> User:
attributes.pop("id")
return User().set(attributes) | [
"def create_user(dct):\n return User.dict2user(dct)",
"def create_user_from_tunnistamo_data(payload):\n return User(\n id=get_user_id(payload),\n first_name=payload.get('given_name'),\n last_name=payload.get('family_name'),\n email=payload.get('email'),\n is_staff=False,\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return fileId from a url. | def fileId_from_url(url):
raw_fileId = re.findall("~[A-z.]+/[0-9]+", url)[0][1: ]
return raw_fileId.replace('/', ':') | [
"def fileid_from_url(url):\r\n raw_fileid = re.findall(\"~[A-z.]+/[0-9]+\", url)[0][1:]\r\n return raw_fileid.replace('/', ':')",
"def get_file_by_url(self, url):\r\n parts = urlsplit(url)\r\n query = parse_qs(parts.query)\r\n keys = query.keys()\r\n if \"sourcedoc\" in keys:\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configure Pig with the correct classpath. If Hadoop is available, use HADOOP_CONF_DIR, otherwise use PIG_HOME. | def update_config(self, mode):
with utils.environment_edit_in_place('/etc/environment') as env:
key = 'HADOOP_CONF_DIR' if mode == 'mapreduce' else 'PIG_HOME'
env['PIG_CLASSPATH'] = env[key] | [
"def setup_environment():\n\n add_pyspark_path()\n\n current_location = path.dirname(path.realpath(__file__))\n cwd = os.getcwd()\n\n local_prefixes = [\n path.abspath(path.join(current_location, 'jars')),\n path.abspath(path.join(cwd, 'jars')),\n path.abspath(path.join(cwd, '../geo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates realized vol using historical spot data | def calculate_realized_vol(spot_df, tenor='6m'):
weighting = (22-1)/(22+1)
short_vol, long_vol, robust_vol = {}, {}, {}
for ccy, row in spot_df.iteritems():
long_vol[ccy] = volatility(row, tenor, returns_type=Returns.LOGARITHMIC)
short_vol[ccy] = annualize(returns(row,1, Returns.LOGARITHMIC).ewm(alpha=1-weighting, adjust=True).std())*100
robust_vol[ccy] = robust_volatility(row, tenor)
return pd.DataFrame.from_dict(long_vol), pd.DataFrame.from_dict(short_vol), pd.DataFrame.from_dict(robust_vol) | [
"def vat_rate():",
"def inVolts(mv):\r\n return mv/1000.0",
"def phase_space_volume(self) -> float:",
"def getOBV(currency):\n temp = exeSqlSelect(\"SELECT close, volume FROM \" + str(currency) + \"_Candles ORDER BY PID desc limit 100\")\n\n prices = []\n for i in range(len(temp)):\n prices.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates volatility swap spread screen | def calculate_vol_swap_screen(bbids=['USDJPY', 'AUDUSD'], long_tenor='6m',
end=business_day_offset(date.today(), -1, roll='forward'),
start=RelativeDate('-5y').apply_rule()):
vol_df, spot_df = get_data(bbids, long_tenor, end, start)
long_rvol, short_rvol, robust_vol = calculate_realized_vol(spot_df, long_tenor)
results = pd.DataFrame(columns=['crosses', '6m Implied spread', 'Beta', f'Entry vs {long_tenor} Z-score',
'Avg Carry Z-score', 'Score', f'{long_tenor} Realized Vol', f'{long_tenor} Carry', f'{long_tenor} 5y Avg', f'{long_tenor} 10th',
f'{long_tenor} 90th', '1m Realized Vol', '1m Carry'])
pairs = itertools.combinations(crosses, 2)
for pair in pairs:
short, long = pair[0], pair[1]
beta = LinearRegression(vol_df[short], vol_df[long], fit_intercept=False).coefficient(1)
iv_spread = vol_df.iloc[-1][long] - beta*vol_df.iloc[-1][short]
rv_long_spread = long_rvol[long] - beta*long_rvol[short]
rv_short_spread = short_rvol[long] - beta*short_rvol[short]
robust_spread = robust_vol[long] - beta*robust_vol[short]
z_score = (robust_spread.mean() - iv_spread)/robust_spread.std()
carry_long = rv_long_spread[-1] - iv_spread
carry_short = rv_short_spread[-1] - iv_spread
carry_avg = (carry_long + carry_short)/2
carry_zscore = carry_avg / robust_spread.std()
results = results.append({'crosses': f'{long} vs. {short}', '6m Implied spread': iv_spread, 'Beta': beta, f'Entry vs {long_tenor} Z-score': z_score,
'Avg Carry Z-score': carry_zscore, 'Score': z_score + carry_zscore, f'{long_tenor} Realized Vol': rv_long_spread[-1],
f'{long_tenor} Carry': carry_long,f'{long_tenor} 5y Avg': robust_spread.mean(),
f'{long_tenor} 10th': rv_long_spread.quantile(0.1), f'{long_tenor} 90th': rv_long_spread.quantile(0.9),
'1m Realized Vol': rv_short_spread[-1], '1m Carry': carry_short}, ignore_index=True)
return results.set_index('crosses').sort_values('6m Implied spread') | [
"def set_driftless_volatility(self):\n day_range = self.day_ranges.get('volatility', [20, 40, 60, 80, 100])\n dict = {}\n\n o = np.log(self.opens / self.closes.shift(1))\n u = np.log(self.highs / self.opens)\n d = np.log(self.lows / self.opens)\n c = np.log(self.closes / se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
CJspeed2 Calculates CJ detonation velocity and CJ state FUNCTION SYNTAX [cj_speed,gas] = CJspeed(P1,T1,q,mech) INPUT P1 = initial pressure (Pa) T1 = initial temperature (K) q = string of reactant species mole fractions mech = cti file containing mechanism data (i.e. 'gri30.cti') OUTPUT cj_speed = CJ detonation speed (m/s) gas = gas object at CJ state | def CJspeed2(P1, T1, q, mech):
gas2 = Solution(mech)
gas1 = Solution(mech)
gas = Solution(mech)
#INTIAL CONDITIONS
gas.TPX = T1, P1, q;
gas1.TPX = T1, P1, q;
gas2.TPX = T1, P1, q;
#INITIALIZE ERROR VALUES & CHANGE VALUES
ERRFT = 1.0*10**-4; ERRFV = 1.0*10**-4;
r1 = gas1.density; V1 = 1/r1;
P1 = gas1.P; T1 = gas1.T;
i = 0;
#PRELIMINARY GUESS
Vg = V1/10; rg = 1/Vg;
gas.TD = T1,rg;
gas.equilibrate('UV')
Tg = gas.T;
gas2.TDX = Tg, rg, gas.X
#SAVE STATE
V = Vg; r = rg;
T = Tg;
deltaT = 1000; deltaV = 1000; cj_speed = 0;
#START LOOP
while(abs(deltaT) > ERRFT*T or abs(deltaV) > ERRFV*V):
i = i + 1
if i == 500:
print "CJ speed 2 calc did not converge"
return gas
#CALCULATE FH & FP FOR GUESS 1
[FH,FP,cj_speed] = FHFP_CJ2(gas,gas1,gas2)
#TEMPERATURE PERTURBATION
DT = T*0.01; Tper = T + DT;
Vper = V; Rper = 1/Vper;
gas.TD = Tper, Rper
gas.equilibrate('TV',2)
gas2.TDX = Tper, Rper, gas.X
#CALCULATE FHX & FPX FOR "IO" STATE
[FHX,FPX,cj_speed] = FHFP_CJ2(gas,gas1,gas2)
#ELEMENTS OF JACOBIAN
DFHDT = (FHX-FH)/DT; DFPDT = (FPX-FP)/DT;
#VOLUME PERTURBATION
DV = 0.01*V; Vper = V + DV;
Tper = T; Rper = 1/Vper;
gas.TD = Tper, Rper
gas.equilibrate('TV',2)
gas2.TDX = Tper, Rper, gas.X
#CALCULATE FHX & FPX FOR "IO" STATE
[FHX,FPX,cj_speed] = FHFP_CJ2(gas,gas1,gas2)
#ELEMENTS OF JACOBIAN
DFHDV = (FHX-FH)/DV; DFPDV = (FPX-FP)/DV;
#INVERT MATRIX
J = DFHDT*DFPDV - DFPDT*DFHDV
b = [DFPDV, -DFHDV, -DFPDT, DFHDT]
a = [-FH, -FP]
deltaT = (b[0]*a[0]+b[1]*a[1])/J; deltaV = (b[2]*a[0]+b[3]*a[1])/J;
#CHECK & LIMIT CHANGE VALUES
#TEMPERATURE
DTM = 0.2*T
if abs(deltaT) > DTM:
deltaT = DTM*deltaT/abs(deltaT)
#VOLUME
V2X = V + deltaV
if V2X > V1:
DVM = 0.5*(V1 - V)
else:
DVM = 0.2*V
if abs(deltaV) > DVM:
deltaV = DVM*deltaV/abs(deltaV)
#MAKE THE CHANGES
T = T + deltaT; V = V + deltaV; r = 1/V;
gas.TD = T, r
gas.equilibrate('TV',2)
gas2.TDX = T, r, gas.X
[FH,FP,cj_speed] = FHFP_CJ2(gas,gas1,gas2)
return [gas,cj_speed] | [
"def FHFP_CJ2(gas,gas1,gas2):\n \n P1 = gas1.P\n H1 = gas1.enthalpy_mass\n r1 = gas1.density\n P2 = gas.P\n H2 = gas.enthalpy_mass\n r2 = gas.density\n \n speeds = equilSoundSpeeds(gas2)\n w2s=(speeds[0])**2\n w1s = w2s*(r2/r1)**2\n FH = H2 + 0.5*w2s - (H1 + 0.5*w1s)\n FP = P... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FHFP_CJ2 Uses the momentum and energy conservation equations and the equilibrium sound speed to calculate error in current pressure and enthalpy guesses. In this case, state 2 is in equilibrium. FUNCTION SYNTAX [FH,FP,cj_speed] = FHFP_CJ2(gas,gas1,gas2) INPUT gas = working gas object gas1 = gas object at initial state gas2 = dummy gas object (for calculating numerical derivatives) OUTPUT FH,FP = error in enthalpy and pressure cj_speed = CJ detonation speed (m/s) | def FHFP_CJ2(gas,gas1,gas2):
P1 = gas1.P
H1 = gas1.enthalpy_mass
r1 = gas1.density
P2 = gas.P
H2 = gas.enthalpy_mass
r2 = gas.density
speeds = equilSoundSpeeds(gas2)
w2s=(speeds[0])**2
w1s = w2s*(r2/r1)**2
FH = H2 + 0.5*w2s - (H1 + 0.5*w1s)
FP = P2 + r2*w2s - (P1 + r1*w1s)
return [FH, FP, sqrt(w1s)] | [
"def CJspeed2(P1, T1, q, mech):\n \n gas2 = Solution(mech)\n gas1 = Solution(mech)\n gas = Solution(mech)\n\n #INTIAL CONDITIONS\n gas.TPX = T1, P1, q;\n gas1.TPX = T1, P1, q;\n gas2.TPX = T1, P1, q; \n \n #INITIALIZE ERROR VALUES & CHANGE VALUES\n ERRFT = 1.0*10**-4; ERRFV = 1.0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
equilSoundSpeeds Calculates equilibrium and frozen sound speeds. For the equilibrium sound speed, the gas is equilibrated holding entropy and specific volume constant. FUNCTION SYNTAX [aequil,afrozen] = equilSoundSpeeds(gas) INPUT gas = working gas object (modified inside function) OUTPUT aequil = equilibrium sound speed (m/s) afrozen = frozen sound speed (m/s) | def equilSoundSpeeds(gas):
# set the gas to equilibrium at its current T and P
gas.equilibrate('TP')
# save properties
s0 = gas.entropy_mass
p0 = gas.P
r0 = gas.density
# perturb the density
r1 = r0*1.0001
# set the gas to a state with the same entropy and composition but
# the perturbed density
gas.SV = s0, 1.0/r1
# save the pressure for this case for the frozen sound speed
pfrozen = gas.P
# now equilibrate the gas holding S and V constant
gas.equilibrate("SV")
p1 = gas.P
# equilibrium sound speed
aequil = math.sqrt((p1 - p0)/(r1 - r0));
# frozen sound speed
afrozen = math.sqrt((pfrozen - p0)/(r1 - r0));
return (aequil, afrozen) | [
"def getmixspeeds(self):\n assert not self.refillable # Mixing of refillable wells not supported (unknown volume)\n ptype=self.plate.plateType\n\n if self.isMixed():\n minspeed=0\n elif self.wellMixed:\n minspeed=1000 # Was already mixed, but may have settled or... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a speckle image of given shape, speckle diameter etc. and saves it to specified path as JPEG or TIFF, configured for printing. | def generate_and_save(height, width, dpi, speckle_diameter, path, size_randomness=0.5,
position_randomness=0.5, speckle_blur=1, grid_step=1.2):
ppmm = dpi / 25.4
w = int(np.round((width * ppmm)))
h = int(np.round((height * ppmm)))
D = np.ceil(speckle_diameter*ppmm)
im = speckle_image((h, w), D, size_randomness, position_randomness, speckle_blur, grid_step)
if path is None:
path = f'speckle_{width}x{height}mm_D{speckle_diameter}mm_{dpi}DPI.tiff'
# Add exif comment to image:
image_comment = f'height: {height} mm\nwidth: {width} mm\ndpi: {dpi}\nD: {speckle_diameter} mm\n'\
f'size_randomness: {size_randomness}\nposition_randomness: {position_randomness}\n'\
f'speckle_blur: {speckle_blur}\ngrid_step: {grid_step}'
save_image(path, im, dpi, comment=image_comment)
print(f'Image saved to {path}.')
return im | [
"def generate_image(self) -> None:",
"def make_image(sim, scenario_file, scenario_fn, output_path='./img.png'):\n scenario = sim.getScenario()\n img = scenario_fn(scenario)\n dpi = 100\n height, width, depth = img.shape\n figsize = width / dpi, height / dpi\n plt.figure(figsize=figsize, dpi=dpi)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a pattern of lines and saves it to specified path as JPEG or TIFF, configured for printing. | def generate_lines(height, width, dpi, line_width, path, orientation='vertical', N_lines=None):
ppmm = dpi / 25.4
w = int(np.round((width * ppmm)))
h = int(np.round((height * ppmm)))
if N_lines is not None:
if orientation == 'vertical':
line_width = width // (2*N_lines)
else:
line_width = height // (2*N_lines)
D = int(np.round(line_width * ppmm))
im = np.full((h, w), 255, dtype=np.uint8)
if orientation == 'vertical':
black_id = np.hstack( [np.arange(i*D, i*D+D) for i in range(0, w//D, 2)] )
if black_id[-1] + D < w:
black_id = np.hstack([black_id, np.arange(w//D*D, w)])
im[:, black_id] = 0
else:
black_id = np.hstack( [np.arange(i*D, i*D+D) for i in range(0, h//D, 2)] )
if black_id[-1] + D < h:
black_id = np.hstack([black_id, np.arange(h//D*D, h)])
im[black_id] = 0
image_comment = f'{orientation} lines\nline width: {line_width}\n DPI: {dpi}'
save_image(path, im, dpi, comment=image_comment)
print(f'Image saved to {path}.')
return im | [
"def write_line_segmentation(file,seg_):\n seg = iulib.intarray()\n seg.copy(seg_)\n ocropus.make_line_segmentation_white(seg)\n iulib.write_image_packed(file,seg)",
"def _save_line_image(image: np.ndarray, line_pts: np.ndarray, save_prefix: os.path):\n save_image = copy.deepcopy(image)\n for (x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a checkerboard pattern and saves it to specified path as JPEG or TIFF, configured for printing. | def generate_checkerboard(height, width, dpi, path, line_width=1, N_rows=None):
ppmm = dpi / 25.4
w = int(np.round((width * ppmm)))
h = int(np.round((height * ppmm)))
if N_rows is not None:
line_width = height // (2*N_rows)
D = int(np.round(line_width * ppmm))
im = np.ones((h, w), dtype=np.uint8)
black_id = np.hstack( [np.clip(np.arange(i*D, i*D+D), 0, h-1) for i in range(0, h//D+1, 2)] )
im[black_id] = 0
# invert values in every other column
invert_id = np.hstack( [np.clip(np.arange(i*D, i*D+D), 0, w-1) for i in range(0, w//D+1, 2)] )
im[:, invert_id] = 1 - im[:, invert_id]
im = im * 255
image_comment = f'checkerboard\nline width: {line_width}\n DPI: {dpi}'
save_image(path, im, dpi, comment=image_comment)
print(f'Image saved to {path}.')
return im | [
"def generate_png_mask(tiff_path):\n color = (255, 255, 0)\n\n def convert_to_color(data):\n print(\"converting...\")\n for i in range(0, len(data)):\n for j in range(0, len(data[i])):\n if data[i][j][3] != 0:\n data[i][j][0], data[i][j][1], data[i][j... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the first matching line in a list of lines. See match() | def matching_line(lines, keyword):
for line in lines:
matching=match(line,keyword)
if matching!=None:
return matching
return None | [
"def find_first_line_matching(lines, text, start=0):\r\n for i in range(start, len(lines)):\r\n line = lines[i].strip()\r\n if line == text:\r\n return i\r\n return -1",
"def get_line(self, line_name):\n for line in self.line_list:\n if line.name == line_name:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the first part of line (modulo blanks) matches keyword, returns the end of that line. Otherwise returns None | def match(line,keyword):
line=line.lstrip()
length=len(keyword)
if line[:length] == keyword:
return line[length:]
else:
return None | [
"def matching_line(lines, keyword):\r\n for line in lines:\r\n matching=match(line,keyword)\r\n if matching!=None:\r\n return matching\r\n return None",
"def find_line(content: str, keyword: str) -> str:\n for line in content.splitlines():\n if keyword.lower() in line.lowe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies the rules to the bunch of text describing a cell and returns the corresponding dictionary | def parse_cell(cell):
parsed_cell={}
for key in rules:
rule=rules[key]
parsed_cell.update({key:rule(cell)})
return parsed_cell | [
"def extract_dictionary(df):\n word_dict = {}\n \n # TODO: Implement this function\n index=0\n for text in df[\"text\"]:\n for p in string.punctuation:\n text=text.replace(p,\" \")\n text=text.lower()\n spl=text.split()\n for word in spl:\n if word no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
uses a mask to get cropping indices, so that images can be cropped to minimum rectangle covering mask | def get_crop_indices_from_mask(mask):
ys, xs = np.where(mask == 255)
return min(ys), max(ys), min(xs), max(xs) | [
"def crop_image_with_masks(image,\n masks,\n max_area=8000,\n min_area=500,\n width_height_ratio=0.9):\n cropped_images = []\n\n for mask_data in masks:\n # Extract mask and bounding box data\n bb... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get centre coords of polygon | def get_polygon_centre(polygon):
if type(polygon) != np.ndarray:
polygon = np.array(polygon)
polygon = np.squeeze(polygon, axis=1)
min_y = np.min(polygon[:,0])
min_x = np.min(polygon[:,1])
max_y = np.max(polygon[:,0])
max_x = np.max(polygon[:,1])
centre_x = max_x - (max_x - min_x) / 2
centre_y = max_y - (max_y - min_y) / 2
return np.array([centre_y, centre_x]) | [
"def compute_center(points: list) -> list:\n\n\tpolygon = numpy.array(points)\n\n\tlength = polygon.shape[0]\n\tsum_lon = numpy.sum(polygon[:, 0])\n\tsum_lat = numpy.sum(polygon[:, 1])\n\n\treturn [sum_lon / length, sum_lat / length]",
"def get_center(self):\n\t\treturn sum([self.xyz0, self.get_diagonal/2], axis=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes a polygon and expands it by increasing length of vectors from centre to all corners | def enlargen_polygon(polygon, ratio):
centre = get_polygon_centre(polygon)
polygon = polygon.astype(np.int)
enlargened_poly = []
for corner in polygon:
diff = corner - centre
enlargened_poly.append((diff * ratio) + centre)
return np.array(enlargened_poly).astype(np.int32) | [
"def regular_polygon(length, num_sides):\n interior_angle = 360 / num_sides\n for count in range(num_sides):\n forward(length)\n left(interior_angle)",
"def centroid_as_polygon(rectangle, relative_size=0.05):\n w, h = size_of_rotated_rectangle(rectangle)\n c = max(h, w) * relative_size\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
uses enlargened polygon to add a white border around masked portion of original image | def get_padded_polygon_image(enlargened_poly, img, mask, color=255):
# mask to extract area of interest
extracted_img = cv2.bitwise_and(img, img, mask=mask)
# invert mask
mask_inv = cv2.bitwise_not(mask)
padded_mask = np.zeros(mask.shape, dtype=np.uint8)
cv2.fillPoly(padded_mask, [np.int32(enlargened_poly)], (color))
padding = cv2.bitwise_and(padded_mask, padded_mask, mask=mask_inv)
padding = np.expand_dims(padding, 2)
padding = np.repeat(padding, 3, 2)
padded_img = cv2.add(padding, extracted_img)
return padded_img, padded_mask | [
"def poly_mask(self):\n result, mapped = self._roiItem.getArrayRegion(\n np.ones_like(self.imageItem.image), self.imageItem, returnMappedCoords=True\n )\n\n # TODO -- move this code to own function and test\n # Reverse the result array to make indexing calculations easier, the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
use mask to extract image portion and pad with white border (set ratio to 0 for no padding) uses cv2.findContours to locate separate polygons in a single mask, if more than one present. added padding may overlap, nothing is implemented to handle this. | def extract_and_pad_mask(fg_img, fg_mask, bg_mask, padding_ratio, transform=True):
# threshold to make binary
# if transform:
# tmp_fg_mask = np.zeros(fg_img.shape, dtype=np.uint8)
# fg_img, fg_mask = transforms(fg_img, fg_mask, bg_mask)
# fg_mask = fg_mask.draw_on_image(tmp_fg_mask)[0]
# print(fg_img.shape, fg_img.dtype, fg_mask.shape, fg_mask.dtype)
_, threshold = cv2.threshold(fg_mask, 110, 255,
cv2.THRESH_BINARY)
# find contours
contours, _ = cv2.findContours(fg_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
results = []
for cnt in contours:
# convert contour to polygon
poly = cv2.approxPolyDP(cnt, 0.009 * cv2.arcLength(cnt, True), True)
# create new mask with only current polygon
this_poly_mask = np.zeros(fg_img.shape[:2], dtype=np.uint8)
cv2.fillPoly(this_poly_mask, [poly], (255))
# enlargen polygon for padding
enlargened_poly = np.squeeze(enlargen_polygon(poly, padding_ratio), axis=1)
# get image of original polygon + added padding
padded_poly_img, padded_mask = \
get_padded_polygon_image(enlargened_poly, fg_img, this_poly_mask)
# get indices to crop from original fg_img into smallest region possible
min_y, max_y, min_x, max_x = get_crop_indices_from_mask(padded_mask)
padded_poly_img = padded_poly_img[min_y:max_y,min_x:max_x,:]
padded_mask = padded_mask[min_y:max_y,min_x:max_x]
this_poly_mask = this_poly_mask[min_y:max_y, min_x:max_x]
results.append({"padded_img":padded_poly_img,
"padded_mask": padded_mask, "annotations_mask": this_poly_mask})
return results | [
"def bg_mask(self, anns, width_height, *, crowd_margin):\n anns1, anns2 = anns\n\n mask = np.ones((\n (width_height[1] - 1) // self.stride + 1,\n (width_height[0] - 1) // self.stride + 1,\n ), dtype=np.bool)\n crowd_bbox = [np.inf, np.inf, 0, 0]\n for ann in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a mask indicating positions of previous overlays, find a new position to overlay current fg | def randomly_choose_overlay_location(fg, bg_mask, step=50):
# get height, width of img mask
rows, cols = bg_mask.shape
# get height, with of current foreground to overlay
h, w, _ = fg.shape
# adjust max row, col by subtracting foreground dimensions
rows = rows - h
cols = cols - w
# get list of possible starting coordinates
possible_starting_points = list(product([i for i in range(0, rows, step)], [i for i in range(0, cols, step)]))
starting_indices = [i for i in range(len(possible_starting_points))]
# until a good region is found, randomly sample from possible overlay regions
# and check to see if any previous overlays intersect with that position
while len(starting_indices):
start = np.random.choice(starting_indices, 1)[0]
start = starting_indices.pop(start)
row, col = possible_starting_points[start]
slice = bg_mask[row:row+h, col:col+w]
if slice.sum() == 0:
return row, col
return None | [
"def overlay(start_coords, padded_fg_img, padded_fg_mask, fg_anno_mask, bg_img, bg_mask):\n row, col = start_coords\n h, w = padded_fg_mask.shape\n\n # create new mask of same dims as bg and place padded_fg_mask there at proper location\n tmp_bg_mask = np.zeros(shape= bg_mask.shape, dtype=np.uint8)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
use padded foreground mask to overlay padded fg onto bg update the bg_mask with annotations mask of fg that is currently overlayed | def overlay(start_coords, padded_fg_img, padded_fg_mask, fg_anno_mask, bg_img, bg_mask):
row, col = start_coords
h, w = padded_fg_mask.shape
# create new mask of same dims as bg and place padded_fg_mask there at proper location
tmp_bg_mask = np.zeros(shape= bg_mask.shape, dtype=np.uint8)
tmp_bg_mask[row:row+h, col:col+w] = padded_fg_mask
tmp_bg_mask_inv = cv2.bitwise_not(tmp_bg_mask)
# create new img of same dims as bg, place padded_fg_img there
tmp_fg_img = np.zeros(bg_img.shape, dtype=np.uint8)
tmp_fg_img[row:row+h, col:col+w] = padded_fg_img
# use mask to combine bg_img, tmp_fg_img
bg_img = cv2.bitwise_and(bg_img, bg_img, mask=tmp_bg_mask_inv)
tmp_fg_img = cv2.bitwise_and(tmp_fg_img, tmp_fg_img, mask=tmp_bg_mask)
bg_img = cv2.add(bg_img, tmp_fg_img)
# update bg_mask with annos
bg_mask[row:row+h, col:col+w] += fg_anno_mask
return bg_img, bg_mask | [
"def extract_and_pad_mask(fg_img, fg_mask, bg_mask, padding_ratio, transform=True):\n # threshold to make binary\n # if transform:\n # tmp_fg_mask = np.zeros(fg_img.shape, dtype=np.uint8)\n # fg_img, fg_mask = transforms(fg_img, fg_mask, bg_mask)\n # fg_mask = fg_mask.draw_on_image(tmp_fg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function that logs the metadata from Optuna Study to Neptune. | def log_study_metadata(study: optuna.Study,
run: neptune.Run,
base_namespace='',
log_plots=True,
log_study=True,
log_all_trials=True,
log_distributions=True,
visualization_backend='plotly',
log_plot_contour=True,
log_plot_edf=True,
log_plot_parallel_coordinate=True,
log_plot_param_importances=True,
log_plot_pareto_front=True,
log_plot_slice=True,
log_plot_intermediate_values=True,
log_plot_optimization_history=True):
run = run[base_namespace]
_log_study_details(run, study)
run['best'] = _stringify_keys(_log_best_trials(study))
if log_all_trials:
_log_trials(run, study.trials)
if log_distributions:
run['study/distributions'].log(list(trial.distributions for trial in study.trials))
if log_plots:
_log_plots(run, study,
visualization_backend=visualization_backend,
log_plot_contour=log_plot_contour,
log_plot_edf=log_plot_edf,
log_plot_parallel_coordinate=log_plot_parallel_coordinate,
log_plot_param_importances=log_plot_param_importances,
log_plot_pareto_front=log_plot_pareto_front,
log_plot_slice=log_plot_slice,
log_plot_optimization_history=log_plot_optimization_history,
log_plot_intermediate_values=log_plot_intermediate_values,
)
if log_study:
_log_study(run, study) | [
"def printMetadata(self):\n print (\"************COMMONDATA************\")\n print (\"Setname:\", self.setname, \"PROC:\", self.proc)\n print (\"NDAT:\", self.ndata,\"NSYS:\",self.nsys)",
"def _log_in_neptune(self, logs: List[LogData]):\n # log scalar metrics\n try:\n for log in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function that loads Optuna Study from an existing Neptune Run. | def load_study_from_run(run: neptune.Run):
if run['study/storage_type'].fetch() == 'InMemoryStorage':
return _get_pickle(path='study/study', run=run)
else:
return optuna.load_study(study_name=run['study/study_name'].fetch(), storage=run['study/storage_url'].fetch()) | [
"def load_study(owner, title, info):\n study = load_study_from_cmd(owner, title, info)\n click.echo(\"Study successfully added to the database with id %s\"\n % study.id)",
"def load_run(cls, run_id, out_dir=None, phase_indices=None, verbose=True):\n out_dir = out_dir if out_dir is not N... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the front door. | async def open_front_door(self):
self.status = enums.OvenStatus.OPEN.value
self.set_pizza_status(enums.PizzaStatus.OVEN_OPEN.value)
await self.execute_task('open_front_door') | [
"def open_door(self):\n if not self.door_open:\n self.do(2, \"Opening door\")\n self.door_open = True",
"def open(self):\n self.servo.set(robotmap.positionList.openGearDoorPosition)",
"def __open_door(self):\n\n self.status = StatusEnum.STOP.value\n print(\"Elev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Closes the front door. | async def close_front_door(self):
await self.execute_task('close_front_door') | [
"def close_door(self):\n if self.door_open:\n self.do(2, \"Closing door\")\n self.door_open = False",
"def close(self):\n self.servo.set(robotmap.positionList.closeGearDoorPosition)",
"def close(self):\r\n pygame.quit()",
"def close_board(self):\n self.ctrl.cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the back door. | async def open_back_door(self):
await self.execute_task('open_back_door')
self.status = enums.OvenStatus.WAITING_FOR_ROBOT_AFTER.value | [
"def open_door(self):\n if not self.door_open:\n self.do(2, \"Opening door\")\n self.door_open = True",
"def open_back_gate(self):\r\n self.send_line('2')",
"def open(self):\n self.servo.set(robotmap.positionList.openGearDoorPosition)",
"def __open_door(self):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
3 APs, two roots, one mesh, 3 APs can mesh each other. R1)))M2 R3 Reboot from M2 and check hearbeat host/reboot info. | def test_map_reboot(self):
logging.info('Facilitate all AP to right status.')
self._setup_env()
logging.info('Wait for 90 seconds to trigger statistic report')
time.sleep(90)
xml = STR.get_xml_data(self.zdipaddr, self.zduser, self.zdpasswd)
self.xmlhnd.update_xml(xml)
aptwo_ul_num = self.xmlhnd.get_ap_mesh_uplink_acquired(self.testaptwo)
self.testaptwo.apins.reboot()
elipsetime = self._check_aps_on_zd()
logging.info('Wait for 90 seconds to trigger statistic report')
time.sleep(90 - elipsetime)
xml_next = STR.get_xml_data(self.zdipaddr, self.zduser, self.zdpasswd)
self.xmlhnd.update_xml(xml_next)
aptwo_ul_num_n = self.xmlhnd.get_ap_mesh_uplink_acquired(self.testaptwo)
res1 = self.TestCaseResulter("Reboot MAP")
res2 = self.TestCaseResulter("MAP heartbeat lost")
if aptwo_ul_num_n != aptwo_ul_num + 1:
msg = "AP%s Expected mesh-num-uplink-acquired=%s, actual mesh-num-uplink-acquired=%s" \
% (self.testaptwo.get_ap_mac(), aptwo_ul_num + 1, aptwo_ul_num_n)
res1.update_result("FAIL", msg)
res2.update_result("FAIL", msg)
else:
res1.update_result("PASS", "Correct Behavior")
res2.update_result("PASS", "Correct Behavior")
return [res1, res2] | [
"def multinic_bootstrap_booting(self):\n self.env.revert_snapshot(\"ready\")\n\n slave = self.env.nodes().slaves[0]\n mac_addresses = [interface.mac_address for interface in\n slave.interfaces.filter(network__name='internal')]\n try:\n for mac in mac_ad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
draws a line in an image 'Img' given 'rho' and 'theta' | def draw_line(Img, rho, theta):
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
x1 = int(x0 + 1000 * (-b))
y1 = int(y0 + 1000 * a)
x2 = int(x0 - 1000 * (-b))
y2 = int(y0 - 1000 * a)
cv2.line(Img, (x1, y1), (x2, y2), (0, 0, 255), 1) | [
"def draw_line(theta, rho, **args):\n def clamp(a, b, a_min, a_max, rho, A, B):\n if a < a_min or a > a_max:\n a = np.fmax(a_min, np.fmin(a_max, a))\n b = (rho-a*A)/B\n return a, b\n\n x_min,x_max = np.sort(plt.xlim())\n y_min,y_max = np.sort(plt.ylim())\n c = np.cos(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override the default register function to automagically register submodules at once. | def register(self, app, options, first_registration=False):
if first_registration:
self.submodules = list(app.find_submodules(self.import_name))
super(PgAdminModule, self).register(app, options, first_registration)
for module in self.submodules:
app.register_blueprint(module) | [
"def call_register(root_dir):\n for mod in imported_modules:\n if hasattr(mod, \"register\"):\n mod.register()",
"def register_by_module(module):\n\n # Get a list of all user specified modules attached to module\n module_names = module.__all__\n\n # Add in package preamble\n modul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A small addition to pprint that converts any Django model objects to dictionaries so they print prettier. h3. Example usage >>> from toolbox.dprint import dprint >>> from app.models import Dummy >>> dprint(Dummy.objects.all().latest()) | def dprint(object, stream=None, indent=1, width=80, depth=None):
# Catch any singleton Django model object that might get passed in
if getattr(object, '__metaclass__', None):
if object.__metaclass__.__name__ == 'ModelBase':
# Convert it to a dictionary
object = object.__dict__
# Catch any Django QuerySets that might get passed in
elif isinstance(object, QuerySet):
# Convert it to a list of dictionaries
object = [i.__dict__ for i in object]
# Pass everything through pprint in the typical way
printer = PrettyPrinter(stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object) | [
"def pprint(obj):\n print(json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')))",
"def pp(object):\n return pprint.PrettyPrinter(indent=2, width=200).pprint(object)",
"def pprint(self, fh=None):\n if fh is None:\n fh = sys.stdout\n for doc in self:\n print(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace missing info fields with mean values | def replace_mean(df):
df['Glucose'] = df['Glucose'].fillna(df['Glucose'].mean())
df['BloodPressure'] = df['BloodPressure'].fillna(df['BloodPressure'].mean())
df['SkinThickness'] = df['SkinThickness'].fillna(df['SkinThickness'].mean())
df['Insulin'] = df['Insulin'].fillna(df['Insulin'].mean())
df['BMI'] = df['BMI'].fillna(df['BMI'].mean())
return df | [
"def replace_nan(self):\n for column in self.X.columns:\n self.calc_and_fill_mean(column)",
"def fill_empty_values(dataset):\n for f in dataset.get_feature_names():\n if dataset.feature_is_continuous(f):\n f_analysis = dataset.analyse_continuous_feature(f)\n if f_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find local maximum if image. Starting point is (x,y) and algorithm looks all posible ways Values other than maximum will be set to 0 | def find_local_maximum(y, x, img, last_max, max_y, max_x):
if x == 147 and y == 156:
cv.imshow(img)
cv.waitKey(0)
last_max = img[y][x]
max_y = y
max_x = x
# * * *
# * x *
# * * *
for spaceing in range(1, 100, 1):
treshhold_area = True
max_has_changed = True
while max_has_changed:
max_has_changed = False
for tmp_y in range(max_y-spaceing, max_y + 2*spaceing + 1, 1):
# check vertical lines of pixels
# out of bounds
if tmp_y < 0 or tmp_y >= img.shape[0] or max_x-spaceing < 0 or max_x+spaceing >= img.shape[1]:
continue
if img[tmp_y][max_x-spaceing] != 0:
treshhold_area = False
if img[tmp_y][max_x-spaceing] > last_max:
last_max = img[tmp_y][max_x-spaceing]
max_y = tmp_y
max_x = max_x-spaceing
max_has_changed = True
break
else:
img[tmp_y][max_x-spaceing] = 0
if img[tmp_y][max_x+spaceing] != 0:
treshhold_area = False
if img[tmp_y][max_x+spaceing] > last_max:
last_max = img[tmp_y][max_x+spaceing]
max_y = tmp_y
max_x = max_x+spaceing
max_has_changed = True
break
else:
img[tmp_y][max_x+spaceing] = 0
for tmp_x in range(max_x-spaceing, max_x+2*spaceing + 1, 1):
# check horizontal lines of pixels
if tmp_x < 0 or tmp_x >= img.shape[1] or max_y-spaceing < 0 or max_y+spaceing >= img.shape[0]:
continue
if img[max_y-spaceing][tmp_x] != 0:
treshhold_area = False
if img[max_y-spaceing][tmp_x] > last_max:
last_max = img[max_y-spaceing][tmp_x]
max_y = max_y-spaceing
max_x = tmp_x
max_has_changed = True
break
else:
img[max_y-spaceing][tmp_x] = 0
if img[max_y+spaceing][tmp_x] != 0:
treshhold_area = False
if img[max_y+spaceing][tmp_x] > last_max:
last_max = img[max_y+spaceing][tmp_x]
max_y = max_y+spaceing
max_x = tmp_x
max_has_changed = True
break
else:
img[max_y+spaceing][tmp_x] = 0
if treshhold_area:
break
return max_y, max_x, last_max | [
"def __franjaMax (img, alto, ancho, x_ini, y_ini, y_fin):\n\t\t\n\tmax=0\n\ty_max_franja=y_ini\n\n\tfor i in range(y_ini, y_fin-alto):\n\t\tvalor_franja = cvSum(cvGetSubRect(img, cvRect(x_ini,i,ancho,alto)))\n\t\tif valor_franja[0]>=max:\n\t\t\tmax = valor_franja[0]\n\t\t\ty_max_franja = i\n\n\treturn x_ini,y_max_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produces a formatted printout of the given sentence number, comparing the correct POS tags with the predicted POS tags. | def get_sent(self, num):
assert num in self.res.sent_num.values, "Sentence index is out of range for this dataset"
this_sentence = self.res[self.res.sent_num == num]
star_if_true = lambda boolean: '*' if boolean else ''
check_if_true = lambda boolean: '✓' if boolean else ''
printout = pd.DataFrame({'true': self.tagset[this_sentence.y_true],
'predict': self.tagset[this_sentence.y_predict],
'correct?': (this_sentence.y_true == this_sentence.y_predict) \
.map(check_if_true).values,
'oov?': this_sentence.oov.map(star_if_true).values,
'ambiguous?': this_sentence.ambig.map(star_if_true).values},
index = this_sentence.token,)
print(printout) | [
"def show_numbers(text):\n for paragraph in text:\n for sentence in paragraph.split('. '):\n if re.findall(r'\\d+', sentence):\n print sentence",
"def print_intermediate_results(n, tagged, census):\n\n print('\\n')\n print('****** total sentences tested = {} ******'.forma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the top guesses for this page | def question_top_guesses(text, deep, guess_connection, id, page, num_guesses=4):
c = guess_connection.cursor()
command = ('select page from guesses where sentence = 2 and token = 0 and question = %i ' +
'order by score desc limit %i') % (id, num_guesses+1)
c.execute(command)
choices = set([page])
for ii, in c:
if len(choices) < num_guesses and not ii in choices:
choices.add(ii)
# If we don't have enough guesses, generate more
new_guesses = deep.text_guess(text)
# sort the guesses and add them
for guess, score in sorted(new_guesses.items(), key=operator.itemgetter(1), reverse=True):
if len(choices) < num_guesses and not guess in choices:
choices.add(guess)
return choices | [
"def get_top(self, entries):\n def calc_score(k, v):\n for tag in get_artist_genres(k):\n v += self.genres_scores[tag]\n return v\n\n def get_reason(artist):\n similar_to = []\n for similar_artist, sugg in self.similar.items():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the last activity date is min date, when an http error occurs during tasks retrieval. | def test_datetime_http_error_tasks(self, mock_url_read, mock_write_json, mock_read_json):
mock_url_read.side_effect = [
'{"access_token": "ey_xx", "refresh_token": "new_refresh_token"}',
urllib.error.HTTPError(None, None, None, None, None)]
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='/home', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
last_activity_date = planner.datetime('plan_id_xx')
mock_write_json.assert_called_once()
self.assertEqual(last_activity_date, datetime.datetime.min) | [
"def test_datetime_on_error(self):\n self.contents = 'raise'\n self.assertEqual(datetime.datetime.min, self.__report.datetime('url'))",
"def test_datetime_json_error_tasks(self, mock_url_read, mock_error, mock_write_json, mock_read_json):\n mock_url_read.side_effect = [\n '{\"acces... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the last activity date is min date, when invalid json retrieved during tasks retrieval. | def test_datetime_json_error_tasks(self, mock_url_read, mock_error, mock_write_json, mock_read_json):
mock_url_read.side_effect = [
'{"access_token": "ey_xx", "refresh_token": "new_refresh_token"}',
'non-json']
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='/home', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
last_activity_date = planner.datetime('plan_id_xx')
mock_write_json.assert_called_once()
self.assertEqual(last_activity_date, datetime.datetime.min)
self.assertEqual('Invalid json retrieved for tasks. Reason: %s.', mock_error.call_args_list[0][0][0])
self.assertIsInstance(mock_error.call_args_list[0][0][1], ValueError) | [
"def test_datetime_http_error_tasks(self, mock_url_read, mock_write_json, mock_read_json):\n mock_url_read.side_effect = [\n '{\"access_token\": \"ey_xx\", \"refresh_token\": \"new_refresh_token\"}',\n urllib.error.HTTPError(None, None, None, None, None)]\n mock_read_json.return_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the number of overdue tasks returns 1 when http error occurs. | def test_nr_of_over_due_actions_http_error(self, mock_url_read, mock_write_json, mock_read_json):
mock_url_read.side_effect = [
'{"access_token": "ey_xx", "refresh_token": "new_refresh_token"}',
urllib.error.HTTPError(None, None, None, None, None)]
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='/home', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
mock_write_json.assert_called_once_with({'refresh_token': 'new_refresh_token'}, 'file_location_of_token.json')
self.assertEqual(planner.nr_of_over_due_actions('plan_id_xx'), -1) | [
"def test_nr_of_over_due_actions_invalid_time(self, mock_url_read, mock_error, mock_write_json, mock_read_json):\n mock_url_read.side_effect = [\n '{\"access_token\": \"ey_xx\", \"refresh_token\": \"new_refresh_token\"}',\n '{\"non-value\": [{\"completedDateTime\": null, '\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the number of overdue tasks returns 1 when tasks json is invalid. | def test_nr_of_over_due_actions_invalid_json(self, mock_url_read, mock_error, mock_write_json, mock_read_json):
mock_url_read.side_effect = [
'{"access_token": "ey_xx", "refresh_token": "new_refresh_token"}',
'non-json']
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='/home', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
mock_write_json.assert_called_once_with({'refresh_token': 'new_refresh_token'}, 'file_location_of_token.json')
self.assertEqual(planner.nr_of_over_due_actions('plan_id_xx'), -1)
self.assertEqual('Invalid json retrieved for tasks. Reason: %s.', mock_error.call_args_list[0][0][0])
self.assertIsInstance(mock_error.call_args_list[0][0][1], ValueError) | [
"def test_nr_of_over_due_actions_invalid_time(self, mock_url_read, mock_error, mock_write_json, mock_read_json):\n mock_url_read.side_effect = [\n '{\"access_token\": \"ey_xx\", \"refresh_token\": \"new_refresh_token\"}',\n '{\"non-value\": [{\"completedDateTime\": null, '\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the number of overdue tasks returns 1 when refresh token file is empty. | def test_nr_of_over_due_actions_empty_refresh_json(self, mock_url_read, mock_info, mock_write_json, mock_read_json):
mock_read_json.return_value = ''
planner = SharepointPlanner(url='/home', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
mock_write_json.assert_not_called()
mock_info.assert_called_once_with(
'No refresh token could be loaded. Please, generate one using the script refresh_token_generator.py.')
self.assertEqual(planner.nr_of_over_due_actions('plan_id_xx'), -1)
mock_url_read.assert_not_called() | [
"def test_exhaustion_refresh():\n clock = MockedTime()\n tb = RateLimitTokenBucket('key', 5, 40, clock=clock)\n tb.decrease_tokens(2)\n tb.compute_current_tokens()\n assert tb.current_tokens == 3 \n clock.tick(8)\n tb.compute_current_tokens()\n assert tb.curr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the number of overdue tasks returns 1 when json is invalid. | def test_nr_of_over_due_actions_invalid_time(self, mock_url_read, mock_error, mock_write_json, mock_read_json):
mock_url_read.side_effect = [
'{"access_token": "ey_xx", "refresh_token": "new_refresh_token"}',
'{"non-value": [{"completedDateTime": null, '
'"createdDateTime":"2018-02-28T11:01:08.8386828Z","assignments": {}}]}']
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='/home', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
mock_write_json.assert_called_once_with({'refresh_token': 'new_refresh_token'}, 'file_location_of_token.json')
self.assertEqual(planner.nr_of_over_due_actions('plan_id_xx'), -1)
self.assertEqual('Invalid json retrieved for tasks. Reason: %s.', mock_error.call_args_list[0][0][0])
self.assertIsInstance(mock_error.call_args_list[0][0][1], KeyError) | [
"def test_nr_of_over_due_actions_invalid_json(self, mock_url_read, mock_error, mock_write_json, mock_read_json):\n mock_url_read.side_effect = [\n '{\"access_token\": \"ey_xx\", \"refresh_token\": \"new_refresh_token\"}',\n 'non-json']\n mock_read_json.return_value = {'refresh_to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the urls of overdue tasks match. | def test_nr_of_over_due_actions_url(self, mock_url_read, mock_write_json, mock_read_json):
mock_url_read.side_effect = [
'{"access_token": "ey_xx", "refresh_token": "new_refresh_token"}',
'{"value": [{"completedDateTime": null, "createdDateTime":"2018-02-28T13:01:08.828Z", "id": "id_VbPAGNM", '
'"title": "Title!", "dueDateTime": "' + (datetime.datetime.utcnow() - relativedelta(days=7)
).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + '",'
'"bucketId": "1a", "assignments": {"ecf0xx": {"assignedDateTime": "2018-02-28T13:01:08.8386828Z"}}}]}']
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='https://planner_home/', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
mock_write_json.assert_called_once_with({'refresh_token': 'new_refresh_token'}, 'file_location_of_token.json')
self.assertEqual(planner.over_due_actions_url('plan_id_xx'),
[('https://planner_home/Home/Task/id_VbPAGNM', 'Title!', '7 dagen')]) | [
"def test_check_url():\n airbnb = Airbnb()\n\n assert airbnb.check_url(\n 'https://www.airbnb.co.uk/rooms/111?guests=2&adults=1')\n\n assert airbnb.check_url('https://www.airbnb.com/rooms/12')\n assert airbnb.check_url('http://www.airbnb.com/rooms/12')\n assert airbnb.check_url('http://airbnb.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the number of inactive tasks returns 1 when http error occurs. | def test_nr_of_inactive_actions_http_error(self, mock_url_read, mock_write_json, mock_read_json):
mock_url_read.side_effect = [
'{"access_token": "ey_xx", "refresh_token": "new_refresh_token"}',
urllib.error.HTTPError(None, None, None, None, None)]
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='/home', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
mock_write_json.assert_called_once_with({'refresh_token': 'new_refresh_token'}, 'file_location_of_token.json')
self.assertEqual(planner.nr_of_inactive_actions('plan_id_xx'), -1) | [
"def test_get_task_status(self):\n pass",
"def test_status_forcelist_2(self):\n\n url = 'http://localhost:7654/status_code=500'\n \n # start counting the number of requests received\n self.http_server.reset_counter()\n\n res = obstinate.oget(url, o_status_forcelist=['501'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the number of inactive tasks returns 1 when json is invalid. | def test_nr_of_inactive_actions_invalid_json(self, mock_url_read, mock_error, mock_write_json, mock_read_json):
mock_url_read.side_effect = [
'{"access_token": "ey_xx", "refresh_token": "new_refresh_token"}',
'non-json']
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='/home', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
mock_write_json.assert_called_once_with({'refresh_token': 'new_refresh_token'}, 'file_location_of_token.json')
self.assertEqual(planner.nr_of_inactive_actions('plan_id_xx'), -1)
self.assertEqual('Invalid json retrieved for tasks. Reason: %s.', mock_error.call_args_list[0][0][0])
self.assertIsInstance(mock_error.call_args_list[0][0][1], json.decoder.JSONDecodeError) | [
"def test_read_incompleted_task_list():\n response = client.get('/task/?completed=false')\n assert response.status_code == 200\n assert response.json() == {}",
"def test_nr_of_inactive_actions_http_error(self, mock_url_read, mock_write_json, mock_read_json):\n mock_url_read.side_effect = [\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the task urls of inactive actions are retrieved correctly. | def test_inactive_actions_url(self, mock_url_read, mock_write_json, mock_read_json):
mock_url_read.side_effect = [
'{"access_token": "ey_xx", "refresh_token": "new_refresh_token"}',
'{"value": [{"completedDateTime": null, "createdDateTime":"2018-02-28T13:01:08.8386828Z", '
'"id": "id_VbPAGNM", "title": "Title!", "dueDateTime": null,'
'"bucketId": "1a", "assignments": {"ecf0xx": {"assignedDateTime": "' + (
datetime.datetime.utcnow() - relativedelta(days=19)).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + '"}}}]}']
mock_read_json.return_value = {'refresh_token': 'refresh_token_content_xx'}
planner = SharepointPlanner(url='https://planner_home/', client_id='client_id_xx',
client_secret='client_secret_k=',
refresh_token_location='file_location_of_token.json')
mock_write_json.assert_called_once_with({'refresh_token': 'new_refresh_token'}, 'file_location_of_token.json')
self.assertEqual(planner.inactive_actions_url('plan_id_xx'),
[('https://planner_home/Home/Task/id_VbPAGNM', 'Title!', '19 dagen')]) | [
"def test_get_task_status(self):\n pass",
"def test_web_task_anonymous_cant_edit(webapp, new_task):\n webapp.homepage()\n for task in webapp.taskboard.tasks():\n assert \"edit\" not in task.options",
"def test_read_incompleted_task_list():\n response = client.get('/task/?completed=false')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merges the first and second half of an array. | def merge(first_half, second_half, array):
i = 0
j = 0
k = 0
while i < len(first_half) and j < len(second_half):
if first_half[i] < second_half[j]:
array[k] = first_half[i]
i += 1
else:
array[k] = second_half[j]
j += 1
k += 1
while i < len(first_half):
array[k] = first_half[i]
i += 1
k += 1
while j < len(second_half):
array[k] = second_half[j]
j += 1
k += 1 | [
"def merge(array, lo, mid, hi):\n # merge array[lo..mid] and array[mid..hi]\n i = lo\n j = mid + 1\n\n aux = array[:] # copy the array to aux\n\n for k in range(lo, hi+1): # actually we need to change at least 2 times!\n # run out of the left side array\n if i > mid:\n array[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves loss plot to output directory | def save_loss_plot(out_dir, loss, log=False, tag=''):
if log:
filename = os.path.join(out_dir, 'loss_log_plot'+tag+'.pdf')
else:
filename = os.path.join(out_dir, 'loss_plot'+tag+'.pdf')
plt.figure()
if log:
plt.plot(range(len(loss)), np.log(loss), 'r')
else:
plt.plot(range(len(loss)), loss, 'r')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.tight_layout()
plt.savefig(filename)
plt.close() | [
"def plot_save_losses(train_loss, test_loss):\n\t#save the losses\n\tnp.savetxt(f'{output_loc}/Losses_v{version}_c{target_label}.txt', np.array([train_loss, test_loss]), header = 'train_loss test_loss')\n\n\t#plot\n\tplt.plot(np.arange(1, len(train_loss)+1), train_loss, label = 'Train loss')\n\tplt.plot(np.arange(1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a random subset from input data of shape (batch_size, num_cells_per_input, num_markers) | def generate_subset(inputs,
num_cells_per_input,
batch_size,
weights=None,
return_indices=False):
num_cells_total = inputs.shape[0]
if weights is not None:
indices = np.random.choice(
num_cells_total,
size=batch_size * num_cells_per_input,
replace=True,
p=weights)
else:
indices = np.random.choice(
num_cells_total,
size=batch_size * num_cells_per_input,
replace=True)
subset = inputs[indices, ]
subset = np.reshape(subset, newshape=(batch_size, num_cells_per_input, -1))
if return_indices:
return subset, indices
else:
return subset | [
"def get_data_subset(dataset, n_samples=1000):\n idcs = np.arange(len(dataset))\n n_samples = min(n_samples, len(dataset))\n np.random.shuffle(idcs) # shuffles inplace\n new_idcs = idcs[:n_samples]\n return torch.utils.data.Subset(dataset, new_idcs)",
"def random_subset(self, perc=0.5):",
"def s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
extract face array from VGGFace model | def extract_face_feature(self, input_face, save = False):
model = self.config['model']
layer = self.config['layer']
# build model to specify the layer of feature extraction
vggface = VGGFace(model = model, input_shape=(224, 224, 3))
vggface = Model(vggface.input, vggface.get_layer(layer).output)
# extract face feature
face_array = {}
# for single image
if os.path.isfile(input_face):
img = image.load_img(input_face, target_size=(224, 224))
res = vggface.predict(process_image(img, model))[0,:].reshape(-1)
face_array[input_face.split('/')[-1]] = res
# for image directory
if os.path.isdir(input_face):
for i in tqdm(os.listdir(input_face)):
img = image.load_img('%s/%s'%(input_face,i), target_size=(224, 224))
res = vggface.predict(process_image(img, model))[0,:].reshape(-1)
face_array[i] = res
if save:
save_object(face_array, self.config['face_array_path'])
return face_array | [
"def faces(self):\n return self.face.values()",
"def faces(self):\n return [self.face(i) for i in range(self.dimension() + 1)]",
"def vgg19_feature_extraction(dataset_path):\n base_model = VGG19(weights='imagenet')\n model = Model(inputs=base_model.input, outputs=base_model.get_layer('block5... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for Airflow Database Retention feature. | def _ConstructAirflowDatabaseRetentionDaysPatch(airflow_database_retention_days,
release_track):
messages = api_util.GetMessagesModule(release_track=release_track)
config = messages.EnvironmentConfig()
config.dataRetentionConfig = messages.DataRetentionConfig(
airflowDatabaseRetentionDays=airflow_database_retention_days)
return ('config.data_retention_configuration.airflow_database_retention_days',
messages.Environment(config=config)) | [
"def create():\n return _DynamicEnvironment()",
"def _ConstructEnvVariablesPatch(env_ref,\n clear_env_variables,\n remove_env_variables,\n update_env_variables,\n release_track=base.Relea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Patches an Environment, optionally waiting for the operation to complete. This function is intended to perform the common work of an Environment patching command's Run method. That is, calling the patch API method and waiting for the result or immediately returning the Operation. | def Patch(env_resource,
field_mask,
patch,
is_async,
release_track=base.ReleaseTrack.GA):
operation = environments_api_util.Patch(
env_resource, patch, field_mask, release_track=release_track)
details = 'with operation [{0}]'.format(operation.name)
if is_async:
log.UpdatedResource(
env_resource.RelativeName(),
kind='environment',
is_async=True,
details=details)
return operation
try:
operations_api_util.WaitForOperation(
operation,
'Waiting for [{}] to be updated with [{}]'.format(
env_resource.RelativeName(), operation.name),
release_track=release_track)
except command_util.Error as e:
raise command_util.Error('Error updating [{}]: {}'.format(
env_resource.RelativeName(), six.text_type(e))) | [
"def __try_set_patch_mode(self):\n try:\n self.status_handler.set_current_operation(Constants.CONFIGURE_PATCHING)\n self.current_auto_os_patch_state = self.package_manager.get_current_auto_os_patch_state()\n\n # disable auto OS updates if VM is configured for platform updates... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for private environment. | def _ConstructPrivateEnvironmentPatch(
enable_private_environment,
release_track=base.ReleaseTrack.GA,
):
messages = api_util.GetMessagesModule(release_track=release_track)
private_environment_config = messages.PrivateEnvironmentConfig()
config = messages.EnvironmentConfig(
privateEnvironmentConfig=private_environment_config
)
update_mask = 'config.private_environment_config.enable_private_environment'
private_environment_config.enablePrivateEnvironment = bool(
enable_private_environment
)
return (
update_mask,
messages.Environment(config=config),
) | [
"def patch_jinja2_env():\n from pyinfra.api import util\n\n util.Environment = Jinja2Environment",
"def patch_env(self, **kwargs):\n new_shell = self._shell.clone()\n for key, value in kwargs.items():\n new_shell.setenv(key, value)\n return attr.evolve(self, shell=new_shell)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for vpc connectivity. Used only in Composer 3. | def _ConstructVpcConnectivityPatch(
disable_vpc_connectivity,
network,
subnetwork,
network_attachment,
release_track=base.ReleaseTrack.GA,
):
messages = api_util.GetMessagesModule(release_track=release_track)
node_config = messages.NodeConfig()
config = messages.EnvironmentConfig(nodeConfig=node_config)
update_mask = None
if disable_vpc_connectivity:
update_mask = 'config.node_config.network,config.node_config.subnetwork'
elif network_attachment:
update_mask = 'config.node_config.network_attachment'
node_config.composerNetworkAttachment = network_attachment
elif network and subnetwork:
update_mask = 'config.node_config.network,config.node_config.subnetwork'
node_config.network = network
node_config.subnetwork = subnetwork
return (
update_mask,
messages.Environment(config=config),
) | [
"def _ConstructPrivateEnvironmentPatch(\n enable_private_environment,\n release_track=base.ReleaseTrack.GA,\n):\n messages = api_util.GetMessagesModule(release_track=release_track)\n private_environment_config = messages.PrivateEnvironmentConfig()\n config = messages.EnvironmentConfig(\n privateEnviro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for node count. | def _ConstructNodeCountPatch(node_count, release_track=base.ReleaseTrack.GA):
messages = api_util.GetMessagesModule(release_track=release_track)
config = messages.EnvironmentConfig(nodeCount=node_count)
return 'config.node_count', messages.Environment(config=config) | [
"def create_num_bases(self):\r\n if self.dimension==1:\r\n KV_xi=self.knot_vector(self.number_elements,self.order,self.mp)\r\n self.num_bases=len(KV_xi)-(self.order+1)\r\n return\r\n \"\"\"\r\n Generates knot vectors for each patch\r\n \"\"\"\r\n# ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for environment size. | def _ConstructEnvironmentSizePatch(environment_size,
release_track=base.ReleaseTrack.GA):
messages = api_util.GetMessagesModule(release_track=release_track)
config = messages.EnvironmentConfig(environmentSize=environment_size)
return 'config.environment_size', messages.Environment(config=config) | [
"def getPatchSize(self) -> retval:\n ...",
"def _ConstructEnvVariablesPatch(env_ref,\n clear_env_variables,\n remove_env_variables,\n update_env_variables,\n release_track=base.Releas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for partially updating PyPI packages. | def _ConstructPyPiPackagesPatch(clear_pypi_packages,
remove_pypi_packages,
update_pypi_packages,
release_track=base.ReleaseTrack.GA):
messages = api_util.GetMessagesModule(release_track=release_track)
env_cls = messages.Environment
pypi_packages_cls = (messages.SoftwareConfig.PypiPackagesValue)
entry_cls = pypi_packages_cls.AdditionalProperty
def _BuildEnv(entries):
software_config = messages.SoftwareConfig(
pypiPackages=pypi_packages_cls(additionalProperties=entries))
config = messages.EnvironmentConfig(softwareConfig=software_config)
return env_cls(config=config)
return command_util.BuildPartialUpdate(
clear_pypi_packages, remove_pypi_packages, update_pypi_packages,
'config.software_config.pypi_packages', entry_cls, _BuildEnv) | [
"def update_pipenv_env():\n subprocess.call([\"pipenv\", \"sync\", \"--dev\"])",
"def CmdPkgPatch(package, options):\n package.Patch()",
"def _ConstructEnvVariablesPatch(env_ref,\n clear_env_variables,\n remove_env_variables,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for updating labels. | def _ConstructLabelsPatch(clear_labels,
remove_labels,
update_labels,
release_track=base.ReleaseTrack.GA):
messages = api_util.GetMessagesModule(release_track=release_track)
env_cls = messages.Environment
entry_cls = env_cls.LabelsValue.AdditionalProperty
def _BuildEnv(entries):
return env_cls(labels=env_cls.LabelsValue(additionalProperties=entries))
return command_util.BuildPartialUpdate(clear_labels, remove_labels,
update_labels, 'labels', entry_cls,
_BuildEnv) | [
"def UpdateLabels(unused_ref, args, patch_request):\n labels_diff = labels_util.Diff.FromUpdateArgs(args)\n if labels_diff.MayHaveUpdates():\n patch_request = command_util.AddFieldToUpdateMask('labels', patch_request)\n messages = api_util.GetMessagesModule(args.calliope_command.ReleaseTrack())\n app_con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for updating Airflow configs. | def _ConstructAirflowConfigsPatch(clear_airflow_configs,
remove_airflow_configs,
update_airflow_configs,
release_track=base.ReleaseTrack.GA):
messages = api_util.GetMessagesModule(release_track=release_track)
env_cls = messages.Environment
airflow_config_overrides_cls = (
messages.SoftwareConfig.AirflowConfigOverridesValue)
entry_cls = airflow_config_overrides_cls.AdditionalProperty
def _BuildEnv(entries):
software_config = messages.SoftwareConfig(
airflowConfigOverrides=airflow_config_overrides_cls(
additionalProperties=entries))
config = messages.EnvironmentConfig(softwareConfig=software_config)
return env_cls(config=config)
return command_util.BuildPartialUpdate(
clear_airflow_configs, remove_airflow_configs, update_airflow_configs,
'config.software_config.airflow_config_overrides', entry_cls, _BuildEnv) | [
"def _ConstructEnvVariablesPatch(env_ref,\n clear_env_variables,\n remove_env_variables,\n update_env_variables,\n release_track=base.ReleaseTrack.GA):\n env_obj = environments_api_util.Get(e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for updating environment variables. Note that environment variable updates do not support partial update masks unlike other map updates due to comments in (b/78298321). For this reason, we need to retrieve the Environment, apply an update on EnvVariable dictionary, and patch the entire dictionary. The potential race condition here (environment variables being updated between when we retrieve them and when we send patch request)is not a concern since environment variable updates take 5 mins to complete, and environments cannot be updated while already in the updating state. | def _ConstructEnvVariablesPatch(env_ref,
clear_env_variables,
remove_env_variables,
update_env_variables,
release_track=base.ReleaseTrack.GA):
env_obj = environments_api_util.Get(env_ref, release_track=release_track)
initial_env_var_value = env_obj.config.softwareConfig.envVariables
initial_env_var_list = (
initial_env_var_value.additionalProperties
if initial_env_var_value else [])
messages = api_util.GetMessagesModule(release_track=release_track)
env_cls = messages.Environment
env_variables_cls = messages.SoftwareConfig.EnvVariablesValue
entry_cls = env_variables_cls.AdditionalProperty
def _BuildEnv(entries):
software_config = messages.SoftwareConfig(
envVariables=env_variables_cls(additionalProperties=entries))
config = messages.EnvironmentConfig(softwareConfig=software_config)
return env_cls(config=config)
return ('config.software_config.env_variables',
command_util.BuildFullMapUpdate(clear_env_variables,
remove_env_variables,
update_env_variables,
initial_env_var_list, entry_cls,
_BuildEnv)) | [
"def get_updated_env(env, update):\n # If an update env var references itself, merge the original env value\n # into the update value.\n # (This is to somewhat generalize the \"PATH=/foo:$PATH\" special case.)\n for k in update:\n if k not in env or not isinstance(update[k], str) or \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for web server plugins mode patch. | def _ConstructWebServerPluginsModePatch(
support_web_server_plugins, release_track=base.ReleaseTrack.GA
):
messages = api_util.GetMessagesModule(release_track=release_track)
software_config = messages.SoftwareConfig()
if support_web_server_plugins:
software_config.webServerPluginsMode = (
messages.SoftwareConfig.WebServerPluginsModeValueValuesEnum.PLUGINS_ENABLED
)
else:
software_config.webServerPluginsMode = (
messages.SoftwareConfig.WebServerPluginsModeValueValuesEnum.PLUGINS_DISABLED
)
config = messages.EnvironmentConfig(softwareConfig=software_config)
return 'config.software_config.web_server_plugins_mode', messages.Environment(
config=config) | [
"def patch_jinja2_env():\n from pyinfra.api import util\n\n util.Environment = Jinja2Environment",
"def _ConstructPrivateEnvironmentPatch(\n enable_private_environment,\n release_track=base.ReleaseTrack.GA,\n):\n messages = api_util.GetMessagesModule(release_track=release_track)\n private_environmen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for environment image version. | def _ConstructImageVersionPatch(update_image_version,
release_track=base.ReleaseTrack.GA):
messages = api_util.GetMessagesModule(release_track=release_track)
software_config = messages.SoftwareConfig(imageVersion=update_image_version)
config = messages.EnvironmentConfig(softwareConfig=software_config)
return 'config.software_config.image_version', messages.Environment(
config=config) | [
"def _ConstructEnvVariablesPatch(env_ref,\n clear_env_variables,\n remove_env_variables,\n update_env_variables,\n release_track=base.ReleaseTrack.GA):\n env_obj = environments_api_util.Get(e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for web server network access control. | def _ConstructWebServerAccessControlPatch(web_server_access_control,
release_track):
messages = api_util.GetMessagesModule(release_track=release_track)
config = messages.EnvironmentConfig(
webServerNetworkAccessControl=environments_api_util
.BuildWebServerNetworkAccessControl(web_server_access_control,
release_track))
return 'config.web_server_network_access_control', messages.Environment(
config=config) | [
"def _ConstructPrivateEnvironmentPatch(\n enable_private_environment,\n release_track=base.ReleaseTrack.GA,\n):\n messages = api_util.GetMessagesModule(release_track=release_track)\n private_environment_config = messages.PrivateEnvironmentConfig()\n config = messages.EnvironmentConfig(\n privateEnviro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for Cloud SQL machine type. | def _ConstructCloudSqlMachineTypePatch(cloud_sql_machine_type, release_track):
messages = api_util.GetMessagesModule(release_track=release_track)
config = messages.EnvironmentConfig(
databaseConfig=messages.DatabaseConfig(
machineType=cloud_sql_machine_type))
return 'config.database_config.machine_type', messages.Environment(
config=config) | [
"def _ConstructWebServerMachineTypePatch(web_server_machine_type, release_track):\n messages = api_util.GetMessagesModule(release_track=release_track)\n config = messages.EnvironmentConfig(\n webServerConfig=messages.WebServerConfig(\n machineType=web_server_machine_type))\n return 'config.web_serv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for Airflow web server machine type. | def _ConstructWebServerMachineTypePatch(web_server_machine_type, release_track):
messages = api_util.GetMessagesModule(release_track=release_track)
config = messages.EnvironmentConfig(
webServerConfig=messages.WebServerConfig(
machineType=web_server_machine_type))
return 'config.web_server_config.machine_type', messages.Environment(
config=config) | [
"def _ConstructCloudSqlMachineTypePatch(cloud_sql_machine_type, release_track):\n messages = api_util.GetMessagesModule(release_track=release_track)\n config = messages.EnvironmentConfig(\n databaseConfig=messages.DatabaseConfig(\n machineType=cloud_sql_machine_type))\n return 'config.database_conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for Master authorized networks feature. | def _ConstructMasterAuthorizedNetworksTypePatch(enabled, networks,
release_track):
messages = api_util.GetMessagesModule(release_track=release_track)
config = messages.EnvironmentConfig()
networks = [] if networks is None else networks
config.masterAuthorizedNetworksConfig = messages.MasterAuthorizedNetworksConfig(
enabled=enabled,
cidrBlocks=[
messages.CidrBlock(cidrBlock=network) for network in networks
])
return 'config.master_authorized_networks_config', messages.Environment(
config=config) | [
"def env_creator(config: dict):\n \n from gridworld import MultiAgentEnv\n\n return MultiAgentEnv(**config)",
"def make_env(args):\r\n scenario = scenarios.load(args.env_name + \".py\").Scenario()\r\n world = scenario.make_world()\r\n done_callback = None\r\n\r\n env = MultiAgentEnv(\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs an environment patch for updating maintenance window. | def _ConstructMaintenanceWindowPatch(maintenance_window_start,
maintenance_window_end,
maintenance_window_recurrence,
release_track=base.ReleaseTrack.GA):
messages = api_util.GetMessagesModule(release_track=release_track)
window_value = messages.MaintenanceWindow(
startTime=maintenance_window_start.isoformat(),
endTime=maintenance_window_end.isoformat(),
recurrence=maintenance_window_recurrence)
config = messages.EnvironmentConfig(maintenanceWindow=window_value)
return 'config.maintenance_window', messages.Environment(config=config) | [
"def _ConstructEnvVariablesPatch(env_ref,\n clear_env_variables,\n remove_env_variables,\n update_env_variables,\n release_track=base.ReleaseTrack.GA):\n env_obj = environments_api_util.Get(e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a patch for updating scheduler count for Composer 1... | def _ConstructSoftwareConfigurationSchedulerCountPatch(
scheduler_count, release_track=base.ReleaseTrack.GA):
messages = api_util.GetMessagesModule(release_track=release_track)
return 'config.software_config.scheduler_count', messages.Environment(
config=messages.EnvironmentConfig(
softwareConfig=messages.SoftwareConfig(
schedulerCount=scheduler_count))) | [
"def scheduled(self, scheduler):",
"def test_patch_with_reschedule(self):\n Run.objects.update(enqueue_dts=timezone.now())\n response = self.patch(\n '/api/v1/run/1/',\n {\n 'return_dts': timezone.now().isoformat(' '),\n 'return_success': True,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a patch for updating Cloud Data Lineage integration config. | def _ConstructSoftwareConfigurationCloudDataLineageIntegrationPatch(
enabled, release_track):
messages = api_util.GetMessagesModule(release_track=release_track)
return 'config.software_config.cloud_data_lineage_integration', messages.Environment(
config=messages.EnvironmentConfig(
softwareConfig=messages.SoftwareConfig(
cloudDataLineageIntegration=messages.CloudDataLineageIntegration(
enabled=enabled)))) | [
"def apply_patch_to_config(\n config: dict,\n patch: dict\n ):\n from meerschaum.utils.packages import cascadict\n base = cascadict.CascaDict(config)\n new = base.cascade(patch)\n return new.copy_flat()",
"def patch_gcloud(monkeypatch, gcloud_run, gcloud_config):\n monkeypatch.seta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a patch for updating high resilience. | def _ConstructHighResiliencePatch(
enabled, release_track):
messages = api_util.GetMessagesModule(release_track=release_track)
if not enabled:
return 'config.resilience_mode', messages.Environment(
config=messages.EnvironmentConfig()
)
return 'config.resilience_mode', messages.Environment(
config=messages.EnvironmentConfig(
resilienceMode=(
messages.EnvironmentConfig.ResilienceModeValueValuesEnum.HIGH_RESILIENCE
)
)
) | [
"def _patch_update():\n def patched_update(self, *args, **kwargs):\n \"\"\"\n Patched version of Resource.update which send update requests\n containing only the properties specified as arguments to the\n method. If no properties are specified all of them are sent ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download reference genome from the S3 bucket to an EC2 instance, run alignment jobs with kallisto, then generate loom files based on the alignment results, and upload the loom files to S3 bucket. logger Logger object that exposes the interface the code directly uses | def main(logger):
parser = get_parser()
args = parser.parse_args()
root_dir = pathlib.Path(args.root_dir)
if os.environ.get("AWS_BATCH_JOB_ID"):
root_dir = root_dir / os.environ["AWS_BATCH_JOB_ID"]
# local directories on the EC2 instance
if args.s3_input_path.endswith("/"):
args.s3_input_path = args.s3_input_path[:-1]
run_dir = root_dir / "data"
run_dir.mkdir(parents=True)
# extract sample name(s) and technology from the metadata tsv file
metadata_name = os.path.basename(args.metadata)
metadata_dir = run_dir / "metadata"
metadata_dir.mkdir(parents=True)
metadata_dir = metadata_dir / metadata_name
s3_metadata_bucket, s3_metadata_prefix = s3u.s3_bucket_and_key(args.metadata)
s3c.download_file(
Bucket=s3_metadata_bucket, # just always download this from us-west-2...
Key=s3_metadata_prefix,
Filename=str(metadata_dir),
)
technology, sample_name = "", ""
with open(metadata_dir) as fd:
rd = csv.reader(fd, delimiter="\t", quotechar='"')
file_content = list()
for row in rd:
file_content.append(row)
file_content = file_content[1:]
sample_name = file_content[0][0]
technology = file_content[0][
1
] # need to fix this later to fit tsv file with multiple samples
# check if the input genome is valid
if args.taxon in reference_genomes_indexes:
genome_name = reference_genomes_indexes[args.taxon]
else:
raise ValueError(f"unknown taxon {args.taxon}")
if "10x" in technology:
genome_dir = root_dir / "genome" / "10X" / genome_name
elif (
"smartseq2" in technology
): # may need to update these after confirming what technology name looks like for smartseq2 data
genome_dir = (
root_dir / "genome" / "smartseq2" / genome_name
) # necessary to separate the reference genome location path for 10x and smartseq2?
genome_dir.mkdir(parents=True)
s3_input_bucket, s3_input_prefix = s3u.s3_bucket_and_key(args.s3_input_path)
logger.info(
f"""Run Info: partition {args.partition_id} out of {args.num_partitions}
genome_dir:\t{genome_dir}
taxon:\t{args.taxon}
s3_input_path:\t{args.s3_input_path}"""
)
s3 = boto3.resource("s3")
# download the reference genome index data from s3 bucket to an EC2 instance
logger.info("Downloading reference genome index files of {}".format(genome_name))
if "10x" in technology:
s3_genome_index = f"s3://{S3_REFERENCE['west']}/loompy/10X/{genome_name}"
elif "smartseq2" in technology:
s3_genome_index = f"s3://{S3_REFERENCE['west']}/loompy/smartseq2/{genome_name}"
s3_genome_index_bucket, s3_genome_index_prefix = s3u.s3_bucket_and_key(
s3_genome_index
)
s3_genome_files_prefix = list(
s3u.get_files(s3_genome_index_bucket, s3_genome_index_prefix)
)
s3_genome_files_prefix = s3_genome_files_prefix[1:]
file_names = list(
os.path.basename(file_path) for file_path in s3_genome_files_prefix
)
genome_name_to_prefix = dict(zip(file_names, s3_genome_files_prefix))
for file in genome_name_to_prefix.keys():
s3c.download_file(
Bucket=s3_genome_index_bucket,
Key=genome_name_to_prefix[file],
Filename=str(genome_dir / file),
)
# extract valid fastq files
sample_re_smartseq2 = re.compile("([^/]+)_R\d(?:_\d+)?.fastq.gz$")
sample_re_10x = re.compile("([^/]+)_L\d+_R\d(?:_\d+)?.fastq.gz$")
s3_output_bucket, s3_output_prefix = s3u.s3_bucket_and_key(args.s3_output_path)
logger.info(
"Running partition {} of {}".format(args.partition_id, args.num_partitions)
)
# fastq files are either stored directly under the s3 input folder, or in sample sub-folders under the s3 input folder
if list(s3u.get_files(s3_input_bucket, s3_input_prefix)):
fastq_key_and_size = [
(fn, s)
for fn, s in s3u.get_size(s3_input_bucket, s3_input_prefix)
if fn.endswith("fastq.gz")
]
else:
sample_folder_paths = s3u.get_folders(s3_input_bucket, s3_input_prefix + "/")
fastq_key_and_size = []
for sample in sample_folder_paths:
files = [
(fn, s)
for fn, s in s3u.get_size(s3_input_bucket, s3_input_prefix)
if fn.endswith("fastq.gz")
]
fastq_key_and_size += files
sample_name_to_fastq_keys = defaultdict(list)
fastq_sizes = defaultdict(list)
fastqs_key_to_name = dict()
for fn, s in fastq_key_and_size:
matched = False
if "10x" in technology:
matched = sample_re_10x.search(os.path.basename(fn))
elif "smartseq2" in technology:
matched = sample_re_smartseq2.search(os.path.basename(fn))
if matched:
sample_name_to_fastq_keys[matched.group(1)].append(fn)
fastq_sizes[matched.group(1)].append(s)
fastqs_key_to_name[fn] = os.path.basename(fn)
logger.info(f"number of samples: {len(sample_name_to_fastq_keys)}")
# download input fastqs from S3 to an EC2 instance
fastq_dir = run_dir / "fastqs"
fastq_dir.mkdir(parents=True)
for key in fastqs_key_to_name.keys():
s3c.download_file(
Bucket=s3_input_bucket,
Key=key,
Filename=str(fastq_dir / fastqs_key_to_name[key]),
)
# run kallisto alignment and RNA velocity analysis on the valid fastq files
for sample in sorted(sample_name_to_fastq_keys)[
args.partition_id :: args.num_partitions
]:
result_path = run_dir / "results"
result_path.mkdir(parents=True)
command = [
"loompy",
"fromfq",
str(result_path / f"{sample_name}.loom"),
sample_name,
str(genome_dir),
str(metadata_dir),
]
fastq_names = [
fastqs_key_to_name[key] for key in sample_name_to_fastq_keys[sample]
]
fastq_dirs = [str(fastq_dir / fastq) for fastq in fastq_names]
command += fastq_dirs
print(command) # for testing purpose
failed = ut_log.log_command(
logger,
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
)
t_config = TransferConfig(use_threads=False)
if failed:
raise RuntimeError("loompy failed")
else:
logger.info(f"Uploading {sample_name}.loom")
s3c.upload_file(
Filename=str(result_path / f"{sample_name}.loom"),
Bucket=s3_output_bucket,
Key=os.path.join(s3_output_prefix, f"{sample_name}.loom"),
Config=t_config,
)
command = ["rm", "-rf", str(result_path)]
ut_log.log_command(logger, command, shell=True)
time.sleep(30)
logger.info("Job completed") | [
"def download_files(\n self, mcg_obj, awscli_pod, bucket_to_read, download_dir, s3_creds=None\n ):\n ns_bucket_path = f\"s3://{bucket_to_read}\"\n\n if s3_creds:\n # Read data directly from target bucket (uls) to result dir\n sync_object_directory(\n awsc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deduplicate Whitehall statistics announcement | def dedupe_stats_announcement(duplicate_slug, authoritative_slug):
command = 'govuk_setenv whitehall ./script/dedupe_stats_announcement {} {}'
with cd('/var/apps/whitehall'):
sudo(command.format(duplicate_slug, authoritative_slug),
user='deploy') | [
"def clear_summaries(self):\n\n\t\tself.count = 0\n\t\tmemset(self.counts, 0, self.n*sizeof(double))",
"async def reset_weekly_stats(self):\n await self.insert_data(\"UPDATE staff SET weekly_tickets = 0\")\n await self.insert_data(\"UPDATE staff SET weekly_Started = 0\")",
"def truncate_dist_repor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allocates item_count into groups of bin_count If we cannot divide evenly we find mininum which should be allocated to each bin and rest we distribute evenly starting from first bin till all items are accounted for | def allocate(bin_count: int, item_count: int) -> list[int]:
assert bin_count > 0, item_count >= 0
per_bin, left_over = divmod(item_count, bin_count)
allocations = []
for _ in range(bin_count):
this_allocation = per_bin
if left_over > 0:
this_allocation += 1
left_over -= 1
allocations.append(this_allocation)
return allocations | [
"def first_fit(items, bin_size):\n #check input: if an item is greater than bin_size, terminate program, let user know\n for item in items:\n if item > bin_size:\n return print (\"unidentified object in bagging area: your item is too big for our bins.\")\n #sort items into reverse order t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a list of days between start and end excluding current and prev | def get_missing_days(start: datetime, end: datetime) -> list[datetime]:
assert start > end
one_day = timedelta(days=-1)
missing_days, current = [], start + one_day
while current > end:
print(current)
missing_days.append(current)
current += one_day
return missing_days | [
"def get_dates(self):\n\t\tdates = []\n\t\tif self.end_date==self.start_date:\n\t\t\tdates.append(self.start_date)\n\t\telse:\n\t\t\tdelta = self.end_date - self.start_date\n\t\t\tfor day in range(0, delta.days+1):\n\t\t\t\tdates.append(self.start_date + timedelta(days=day))\n\t\treturn dates",
"def get_date_rang... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recieves the current ProductSales and last ProductSales we have in our database and posts new cup sales objects to our api. | def interpolate_and_post(current: ProductSales, prev: ProductSales) -> None:
assert current.date > prev.date
results = get_interpolated_list(current, prev)
json_payload = [obj.to_json() for obj in results]
return requests.post(api_url, json=json_payload) | [
"def update_deliveries():\n with db.session.connection(execution_options={\"schema_translate_map\":{\"tenant\":session['schema']}}):\n \n shift_id = request.form.get(\"shift\")\n shift = Shift.query.get(shift_id)\n document= request.form.get(\"docum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the info we're getting from the page is being scraped with the right format | def test_page_info_format(self):
url = self.refs_list[random.randint(0, len(self.refs_list)-1)]
test_page = self.scraper.get_url_page(url) # exchange this for a copy of an html file
url_info = self.scraper.get_info_itemprop('a', 'url', test_page)
self.assertTrue(re.search(r'^http://www.', url_info) or url_info == "Not found")
email_info = self.scraper.get_info_itemprop('a', 'email', test_page)
self.assertTrue(re.search(r'^\S+@\S+', email_info) or email_info == "Not found") | [
"def _good_response(self, resp):\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200\n and content_type is not None\n and content_type.find('html') > -1)",
"def check_url_format(self):\n m = re.match('^https://www.att.com/.*\\.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get spec_sdr and spec_sensor info | def get_spec_data(self):
print "Start get spec threshold data..."
# get spec threshold data
spec_threshold_sensor, spec_threshold_sdr = self.get_spec_threshold_discrete_data("Threshold Sensors",
conf.Start_SpecFile,
conf.End_SpecFile)
# get spec discrete data
spec_discrete_sensor, spec_discrete_sdr = self.get_spec_threshold_discrete_data("Discrete Sensors",
conf.Start_Discrete_SpecFile,
conf.End_Discrete_SpecFile)
return spec_threshold_sensor, spec_threshold_sdr, spec_discrete_sdr | [
"def sdrandsensor_compare(spec_sdr, ipmi_sdr, spec_sensor, ipmi_sensor):\n if spec_sensor and ipmi_sensor:\n if len(ipmi_sdr) != len(ipmi_sensor):\n print \"get ipmi sdr/sensor data info error\"\n logger.error(\"get ipmi data error\")\n return 0\n print \"Start compare ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks, if this container is set to the compact view mode. | def is_compact (self):
if self.container:
return self.container.is_compact ( )
else:
return False | [
"def is_compact (self):\n return self.grid.is_compact ( )",
"def isCompact(self) -> \"SbBool\":\n return _coin.SoOutput_isCompact(self)",
"def __nonzero__(self): # pragma: no cover\n return self._panels is not None",
"def is_display_active(self):\n return self.op is not None",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks, if this container is set to the full span view mode. | def is_full_span (self):
return self.container.is_full_span ( ) | [
"def is_full_span (self):\n return self.grid.is_full_span ( )",
"def _get_isFullScreen(self) -> \"bool\" :\n return _core.Viewport__get_isFullScreen(self)",
"def _is_full(self):\n\t\t # the number of round can't be superior to the number of case of the grid\n\t\treturn self._round > self.width * self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Event listener for a single cell selection. | def __cell_selected (self, event):
if event.Selecting ( ):
self.SelectBlock (event.GetRow ( ), event.GetCol ( ), event.GetRow ( ), event.GetCol ( ))
dates = self.container.get_dates ([event.GetCol ( )])
people = self.container.get_people ([event.GetRow ( )])
wx.PostEvent (self.GetEventHandler ( ), custom_events.ComplexSelectEvent (self.GetId ( ), dates=dates, people=people))
event.Skip ( ) | [
"def cell_selected(self):\n\n self.file_selection(self.ui.tableWidget.currentRow())",
"def get_selected_row(event):",
"def on_select_menuitem(self, event, grid, row, col, selection):\n if self.grid.changes: # if user selects a menuitem, that is an edit\n self.grid.changes.add(row)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |