query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Retrieve the content of the subtitle download. | def getSubtitleContent(cls, version_sub_stage):
url = version_sub_stage.version_code
subtitle_page = cls._my_perform_request(url)
subtitle_url = Utils.getregexresults(
SUBSCENE_REGEX.SUBTITLE_URL_PARSER,
subtitle_page)
# If for some reason we failed.
... | [
"def download_subtitle(self, subtitles, filename):\n sub = subtitles[0]\n return self.download_subtitle_by_id(sub.get_id(), sub.get_download_url(), filename)",
"def download_subtitle_by_id(self, identifier, url, filename):\n working_dir = os.getcwd()\n is_tmp = False\n result_fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a ConvertImage task. | def __init__(self, *args, **kwargs):
super(ConvertImageTask, self).__init__(*args, **kwargs)
self.setMetadata('dispatch.split', True) | [
"def convert_image(*args, **kwargs): # real signature unknown; restored from __doc__\n pass",
"def export_task(self, img, cont):\r\n return self._tasks_manager.create(\"export\", img=img, cont=cont)",
"def import_task(self, img, cont, img_format=None, img_name=None):\r\n return self._tasks_mana... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This route gets the heartbeat for a token. The heartbeat is the object that contains data for proving existence of a file (for example, Swizzle, Merkle objects) Provided for nodes that need to recover their heartbeat. The heartbeat does not contain any private information, so having someone else's heartbeat does not he... | def api_downstream_heartbeat(token):
with HttpHandler(app.mongo_logger) as handler:
handler.context['token'] = token
handler.context['remote_addr'] = request.remote_addr
db_token = Token.query.filter(Token.token == token).first()
if (db_token is None):
raise NotFoundErro... | [
"def _new_heartbeat_frame():\n return frame.Heartbeat()",
"async def _start_heartbeat(self, ctx, arg=None):\n self.heartbeat.start()",
"def send_heartbeat(self):\n self._heartbeats += 1\n self._missed_heartbeats += 1\n self.send('~h~%d' % self._heartbeats)",
"def _send_heartbeat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calls next() on hash_iterable until at most bufsz hashes have been retrieved, at which point it queries the database and retrieves all the contracts associated with those hashes. then it yields each contract associated with the hashes in hash_iterable, or None if a contract was not found associated with the hash specif... | def get_contract_iter(hash_iterable, key=None, bufsz=100):
done = False
while (not done):
count = 0
map = dict()
try:
while (count < bufsz):
item = next(hash_iterable)
if (key is None):
# item is id
id = ... | [
"async def get_blocks_by_hash(self, header_hashes: List[bytes32]) -> List[FullBlock]:\n\n if len(header_hashes) == 0:\n return []\n\n formatted_str = (\n f'SELECT header_hash, block from full_blocks WHERE header_hash in ({\"?,\" * (len(header_hashes) - 1)}?)'\n )\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
special print function to not add spaces! Just writes IO directly to stdout. Required by all below functions so that we don't end up with spaces after every command. | def myPrint(str):
sys.stdout.write(str)
return str | [
"def standout_print(info):\n sys.stdout.write(str(info))\n sys.stdout.write(\"\\n\")",
"def _print(data):\n sys.stdout.buffer.write(data)",
"def printout(string):\r\n print(string)",
"def print(self, *args, **kwargs) -> str:\n self.console.print(*args, highlight=False, **kwargs)\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set the foreground color using DOSish 016. Colors are out of order but that's ok. live with it! | def fg(clr):
if clr < 8:
return myPrint ("%s[%im" % (C_ESC,clr+30))
else:
return myPrint ("%s[1,%im" % (C_ESC,clr-8+30)) | [
"def text_foreground_color(self, color): # Sub-section .6\n command = 'FFE7{0}'.format(self._to_16_bit_rgb(color))\n reply = self._send_command(command, 2)\n return self._from_16_bit_rgb(reply)",
"def setConsoleColor(hex_color=\"\",counter=0):\r\n if len(hex_color) != 7:\r\n hex_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set the background color using DOSish 07 (can not use high color backgrounds ) colors are not in dos order | def bg(clr):
return myPrint ("%s[%im" % (C_ESC,clr+40)) | [
"def set_background_colors(self) -> None:\n self._window_all.bkgd(\" \", curses.color_pair(m_color_pair.ColorPair.BLACK_N_WHITE.value))",
"def background(self, color):\r\n doc.bg_color = color",
"def setConsoleColor(hex_color=\"\",counter=0):\r\n if len(hex_color) != 7:\r\n hex_color = M... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates data for the first test case. There are 3 columns corresponding to data1, data2 and data3 all of which are of type string. | def exampleCase1(self):
data = [['data1', 'data2', 'data3']]
for _ in range(10000000):
data.append([self.randomText() for x in range(3)])
self.writeCSV(1, data) | [
"def test_dataset(source='dict'):\n \n def static(): \n row={'name':'Ivan Krsti\\xc4\\x87', 'id':1234,\n 'badge_line1':'laptop.org', 'badge_line2':'Sprint Leader: OLPC',\n 'key_note':True, 'speaker':True, 'vendor':True,\n 'session_chair':True, 'sponsor':True,\n '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates data for the second test case. There are 2 columns corresponding to date and data all of which are of type string. The date is of type python datetime.datetime. | def exampleCase2(self):
data = [['date', 'data']]
date_1 = datetime.datetime(2015, 8, 1)
date_2 = datetime.datetime(2017, 8, 1)
for _ in range(1800000):
data.append([date_1, self.randomText()])
for _ in range(1800000, 2000000):
data.append([date_2, self.randomText()])
self.writeCSV(2, data) | [
"def generate_testdata(field_type, driver):\n\n # Test data for 'date' data type\n if field_type == \"date\":\n return [\n (\"2018-03-25\", datetime.date(2018, 3, 25)),\n (datetime.date(2018, 3, 25), datetime.date(2018, 3, 25)),\n ]\n\n # Test data for 'datetime' data ty... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates data for the third test case. There are 2 columns corresponding to name and phone which are of type string and integer respectively. | def exampleCase3(self):
data = [['name', 'phone']]
for _ in range(10000):
data.append([self.randomText(), self.randomPhoneNumber()])
self.writeCSV(3, data) | [
"def add_test_data():\n add_furniture(\"invoice_file.csv\", \"Elisa Miles\", \"LR04\", \"Leather Sofa\", \"25.00\")\n add_furniture(\"invoice_file.csv\", \"Edward Data\", \"KT78\", \"Kitchen Table\", \"10.00\")\n add_furniture(\"invoice_file.csv\", \"Alex Gonzales\", \"BR02\", \"Queen Mattress\", \"17.00\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For "count" times we take new successors and choose to go there or not depending on their fitness value. | def exec(self, count):
hist_t = []
hist_fit = []
for t in range(count):
T = self.schedule(self.T0, self.alpha, t)
hist_t.append(T)
hist_fit.append(self.fitness(self.state))
if T == 0:
return self.state
succe... | [
"def next_generation(self, survivors=5, chance_of_mutation=0.01):\n\n self.sort_by_fitness()\n # add fitness of current generation to self.fitness_history:\n self.fitness_history.append(self.individuals['Fitness'])\n # assign fittest individuals to next generation\n new_individual... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fits given training data on random forest and logistic regression classifiers and returns scoring results with best model. Carries out hyperparameter optimization on both to find best model. | def prediction(X_train, y_train):
assert X_train.shape[0] == y_train.shape[0], "data sets not the same size"
results_dict = {}
# set scoring
scoring = ['f1', 'accuracy'] # use f1 scoring because of class imbalance
# baseline model
print("Running baseline")
dummy_model = DummyClassifier(str... | [
"def model_fit(df, features_to_use, random_state, **kwargs):\r\n\r\n # read in boosted tree paramters\r\n lr, n_est, max_depth = get_params(**kwargs['get_params'])\r\n\r\n\r\n ## fit model on historical player data\r\n try:\r\n X = df[features_to_use]\r\n y = df['HOF_A']\r\n except:\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Samples the given frame. | def sample(self, frame):
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.ensure_child(f.f_code, void)
stats = parent_stats.ensure_child(frame.f_code, RecordingStatistics)
... | [
"def from_frame_and_timestamp(active_frame, timestamp_ms):\n stack_trace = []\n frame = active_frame\n while frame is not None:\n code = frame.f_code\n stack_trace.append((code, frame.f_lineno))\n frame = frame.f_back\n\n return ProfileSample(stack_trace,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clears the requests record. | def clear_record():
requests_header_record[:] = []
return "request record cleared" | [
"def clear_request(self):\n self.request_data.clear()",
"def clear_requests(self) -> None:\n with self._lock:\n self._requests.clear()",
"def clear_data():\n try:\n db.all_requests.remove()\n return {\"msg\": \"complete\"}\n except:\n return {\"msg\": \"error\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clamp the value of each RGB component to the range of 0 to 255 | def rgb_clamp(vals):
return tuple(_adjusted_round(max(0, min(255, c))) for c in vals) | [
"def brighten(val, minval):\n return minval + (255 - minval) * val // 255",
"def scale_down_rgb(rgb: ndarray):\n return rgb/255.0",
"def rgb_bound(rgb_value):\n\n # upper bound\n if rgb_value > 255:\n rgb_value = 255\n # lower bound\n elif rgb_value < 0:\n rgb_value = 0\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate packet initializer values | def gen_params():
return {
u'be': SubPacketBE(int64=0x7eaddeaddeaddead, uint64=0xdeaddeaddeaddead),
u'le': SubPacketLE(int64=0x7eaddeaddeaddead, uint64=0xdeaddeaddeaddead)
} | [
"def make_packet(packet_num):",
"def generate_initialisation_vector():\n initialisation_vector = Random.new().read(AES.block_size)\n return (initialisation_vector, int(binascii.hexlify(initialisation_vector), 16))",
"def _create_state_init_parameters(self):\n self.init_ws, self.init_bs, self.init_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function that gets called for response change and response add It opens a new courselab and then uploads the grading files | def _open_and_upload(self, obj):
for problem in obj.problems.all().filter(autograde_problem=True):
# open (make) the courselab on tango server with the callback
# _upload_ps_files
tango.open(problem, obj)
# upload the grader librarires
for lib in mode... | [
"def upload_course(request):\n status = 0\n form = json.loads(request.POST.get(\"updateForm\"))\n img_info = form[\"imgInfo\"]\n profile_url = None\n for img in img_info:\n if img[\"start\"] == 0:\n profile_url = img[\"id\"]\n break\n try:\n profile = PictureTem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator close object on socket.error. | def socket_exception(func):
def read(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except socket.error:
logger.debug('ignoring socket exception', exc_info=True)
self.close()
return read | [
"def socket_close(self, socket_name):\n msg = \"socket_close(\\\"{}\\\")\".format(socket_name)\n self._add_line_to_program(msg)",
"def close(self):\n try:\n self.client_socket.close()\n except Exception as e:\n pass",
"def close(self):\n _osutil.unlink_si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does select on open connections. | def _select(self):
readable = [self.tsocket.handle.fileno(), self._read.fileno()]
writable = []
remaining = []
for i, connection in list(self.clients.items()):
if connection.is_readable():
readable.append(connection.fileno())
if connection.rema... | [
"def _select(self):\n readable = []\n for sock in self.serverTransport:\n readable.append(sock.handle.fileno())\n writable = []\n print(\"33339999\")\n try:\n res = select.select(readable, writable, readable)\n except Exception as e:\n res =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cancel a scheduled event or kill a process. This method takes one argument, which is the return value from sched() or process(). In either case, it's an opaque object to the user, which can be either an event or process. If it's an event, when cancelled, the previously scheduled function will no longer be invoked at th... | def cancel(self, o):
if o is None:
errmsg = "simulator.cancel(o=None) requires event or process."
log.error(errmsg)
raise ValueError(errmsg)
elif isinstance(o, _Event):
try:
self._eventlist.cancel(o)
except Exception:
... | [
"def cancel(self):\n assert self.running\n\n self._cancelled = True\n\n # in this section we callback on processes's deferreds, it's\n # callbacks need to know that conversion is cancelled\n self.stop_running_processes()\n self.reset_tasks_queue()\n\n self.stop_sched... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reschedule an event. One can change the time of a scheduled event using this method. When rescheduled, the previously scheduled function will be invoked at the new designated time. If the event already happens, this method would have no effect. This method takes at least one argument, which is the return value from sch... | def resched(self, e, offset=None, until=None):
if not isinstance(e, _Event):
errmsg = "simulator.resched(e=%r) not an event" % e
log.error(errmsg)
raise TypeError(errmsg)
# figure out the event time
if until == None and offset == None:
# if both ... | [
"def reschedule(self, schedtime: 'SbTime') -> \"void\":\n return _coin.SoTimerSensor_reschedule(self, schedtime)",
"def schedule_relative(self, duetime, action, state=None):\n\n scheduler = self\n seconds = GEventScheduler.normalize(duetime)\n if seconds == 0:\n return sched... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the current running process, or None if we are not in a process context. | def cur_process(self):
assert self._theproc is None or \
self._theproc.state == _Process.STATE_RUNNING
return self._theproc | [
"def _as_process(self):\n pid = self.pid\n if not pid:\n raise self.NotStarted()\n return psutil.Process(pid)",
"def get_instance(self):\n if not self.is_server_active():\n self._log('The TCPServer instance is not running!')\n return self._process",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether the given process has terminated. | def terminated(self, p):
if not isinstance(p, _Process):
errmsg = "simulator.terminated(p=%r) not a process" % p
log.error(errmsg)
raise TypeError(errmsg)
return p.state == _Process.STATE_TERMINATED | [
"def is_process_alive(pid):\n try:\n os.kill(pid, 0)\n except OSError:\n # no such process or process is already dead\n return False\n else:\n return True",
"def is_process_running(pid: int):\n try:\n os.kill(pid, 0)\n return True\n except OSError as ex:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the priority of a process. A process should be provided as the only argument. If it's ignored, it's assumed to be the current process. | def get_priority(self, p=None):
if p is not None:
# get priority of another process
if not isinstance(p, _Process):
errmsg = "simulator.get_priority(p=%r) not a process" % p
log.error(errmsg)
raise TypeError(errmsg)
else:
... | [
"def getPriorityCode(priority):\n\treturn getProcessPriorityCodes()[priority]",
"def getProcessPriorityCodes():\n\tpriorities = {}\n\tif onPosix():\n\t\t# -20 to 20, -20 being highest priority\n\t\tpriorities[-2] = 18\n\t\tpriorities[-1] = 9\n\t\tpriorities[0] = 0\n\t\tpriorities[1] = -9\n\t\tpriorities[2] = -... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and return a trap for interprocess communication. | def trap(self):
return Trap(self) | [
"def traps(self, argv):\n from pycopia import asyncio\n from pycopia.SNMP import traps\n traps.get_dispatcher(self._trap_handler)\n asyncio.start_sigio()",
"def mkTunnel(id):\n logging.debugv(\"functions/linux.py->mkTunnel(id)\", [id])\n logging.info(\"Creating tunnel with id %s\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a semaphore for interprocess communication. | def semaphore(self, initval=0, qdis=QDIS.FIFO):
if initval < 0:
errmsg = "simulator.semaphore(initval=%r) negative init value" % initval
log.error(errmsg)
raise ValueError(errmsg)
if qdis < QDIS.FIFO or qdis > QDIS.PRIORITY:
errmsg = "simulator.semaphore(... | [
"def __init__(self, *args):\n _ida_pro.__qsemaphore_t_swiginit(self, _ida_pro.new___qsemaphore_t(*args))",
"def acquire(self, obj_id=None, i=None):\r\n if not isinstance(obj_id,Process):\r\n raise Exception(\"semaphore requires items added to be of type 'Process'\")\r\n self.sem_di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run simulation up to the given time 'until' (by processing all events with timestamps less than 'until'), and if 'updating_until' is true, update the simulation clock to 'until' after processing all the events. | def _run(self, upper, updating_until):
# this is the main event loop of the simulator!
while len(self._eventlist) > 0:
t = self._eventlist.get_min()
if t >= upper: break
self._process_one_event()
# after all the events, make sure we don't wind back t... | [
"def _cron(self):\n while True:\n self.check_update()\n sleep(60)",
"def update_until(self, then):\n self._model.run(to=then)",
"def resched(self, e, offset=None, until=None):\n\n if not isinstance(e, _Event):\n errmsg = \"simulator.resched(e=%r) not an even... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process one event on the event list, assuming there is a least one event on the event list. | def _process_one_event(self):
e = self._eventlist.delete_min()
self.now = e.time
#log.debug("[r%d] simulator '%s' execute event at time %g" %
# (self._simulus.comm_rank, self.name[-4:], self.now))
self._runtime["executed_events"] += 1
# trigger the trap... | [
"async def process_events(self, events: List[EventData]):\n pass",
"def process_events(self):\n pass",
"def _ProcessEvent(self, event):\n if FLAGS.debug_events:\n self._logger.debug('Processing event: %s' % event)\n if isinstance(event, kbevent.QuitEvent):\n self._logger.info('got ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the pseudorandom number generator attached to this simulator. It's a random.Random instance (Mersenne twister). | def rng(self):
if self._rng is None:
u = uuid.uuid3(self._simulus.namespace, self.name)
self._rng = random.Random(int(u.int/2**32))
return self._rng | [
"def rng(self):\n if self._rng is None:\n # One-time initialization from backend-neutral seed int.\n self._rng = fastmath.random.get_prng(self._rng_seed_int)\n return self._rng",
"def get_rng(self, instance: Instance, seed: Optional[int] = None) -> Random:\n assert instance.id is not None\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the list of all future events currently on the event list. This is an expensive operation and should be used responsively, possibly just for debugging purposes. | def show_calendar(self):
print("list of all future events (num=%d) at time %g on simulator '%s':" %
(len(self._eventlist), self.now, self.name if self.name else ''))
for e in sorted(self._eventlist.pqueue.values()):
print(" %s" % e) | [
"def print_possible_events():\n print(\"Registered Events:\")\n print(_BasicEvent.get_possible_events())\n print(\"******************************\")",
"def print_event_handlers(self):\n self.__scheduler.print_event_handlers()",
"async def dump_events(self) -> str:\n\n try:\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print a report on the simulator's runtime performance. | def show_runtime_report(self, prefix=''):
t = time.time()-self._runtime["start_clock"]
print('%s*********** simulator performance metrics ***********' % prefix)
print('%ssimulator name: %s' % (prefix, self.name))
print('%ssimulation time: %g' % (prefix, self.now-self.init_time))
... | [
"def print_report(self):\n print self.__report_str()",
"def print_report():\n print_days_percent_errors()\n print \"\"\n print_popular_authors()\n print \"\"\n print_popular_articles()\n print \"\"",
"def report(self, log):\n max_own_cpu = self.get_max_own_cpu()\n #if max_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
suppress both stdout and stderr outputs | def suppress_output():
if sys.version_info >= (3, 5):
from contextlib import redirect_stderr, redirect_stdout
else:
class _RedirectStream(object):
_stream = None
def __init__(self, new_target):
self._new_target = new_target
self._old_tar... | [
"def suppress_stderr():\n with open(os.devnull, 'w') as fnull:\n with redirect_stderr(fnull):\n yield None",
"def silence_stderr():\n class Devnull(object):\n def write(self, _): pass\n\n def flush(self): pass\n\n orig_stderr = sys.stderr\n sys.stderr = Devnull()\n t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all tweets from profile and write them on a txt file. Leave filter=True to remove RTs, links and mentions. Twitter only allows access to a users most recent 3240 tweets with this method. keys = [consumer_key,consumer_secret,access_key,access_secret] | def get_all_tweets(screen_name,keys=keys,filter=True):
consumer_key,consumer_secret,access_key,access_secret = keys
#re
rt = r'^RT'
link = r'https?:\/\/([\w\.-]+)\/([\w\.-]+)'
mention = r'^\@'
#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_tok... | [
"def get_all_tweets(screen_name):\n #Twitter only allows access to a users most recent 3240 tweets with this method\n \n #authorize twitter, initialize tweepy\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_key, access_secret)\n api = tweepy.API(auth)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/changelog[/{revision}] Show information about multiple changesets. If the optional ``revision`` URL argument is absent, information about all changesets starting at ``tip`` will be rendered. If the ``revision`` argument is present, changesets will be shown starting from the specified revision. If ``revision`` is absen... | def changelog(web, shortlog=False):
query = b''
if b'node' in web.req.qsparams:
ctx = webutil.changectx(web.repo, web.req)
symrev = webutil.symrevorshortnode(web.req, ctx)
elif b'rev' in web.req.qsparams:
return _search(web)
else:
ctx = web.repo[b'tip']
symrev = ... | [
"def revision_list(self, args):\n\n messages = []\n def canceler(cancel_args):\n if cancel_args[0].lower() in ['revision','rev']:\n return RevisionCommand(parent=self.parent, ctx=self.ctx, args=cancel_args, guild=self.guild, user=self.user, channel=self.channel).run()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/shortlog Show basic information about a set of changesets. This accepts the same parameters as the ``changelog`` handler. The only difference is the ``shortlog`` template will be rendered instead of the ``changelog`` template. | def shortlog(web):
return changelog(web, shortlog=True) | [
"def changelog(web, shortlog=False):\n\n query = b''\n if b'node' in web.req.qsparams:\n ctx = webutil.changectx(web.repo, web.req)\n symrev = webutil.symrevorshortnode(web.req, ctx)\n elif b'rev' in web.req.qsparams:\n return _search(web)\n else:\n ctx = web.repo[b'tip']\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/changeset[/{revision}] Show information about a single changeset. A URL path argument is the changeset identifier to show. See ``hg help revisions`` for possible values. If not defined, the ``tip`` changeset will be shown. The ``changeset`` template is rendered. Contents of the ``changesettag``, ``changesetbookmark``,... | def changeset(web):
ctx = webutil.changectx(web.repo, web.req)
return web.sendtemplate(b'changeset', **webutil.changesetentry(web, ctx)) | [
"def grab_changesets(self, path, url, changesets):\n raise NotImplementedError",
"def changelog(web, shortlog=False):\n\n query = b''\n if b'node' in web.req.qsparams:\n ctx = webutil.changectx(web.repo, web.req)\n symrev = webutil.symrevorshortnode(web.req, ctx)\n elif b'rev' in web... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/branches Show information about branches. All known branches are contained in the output, even closed branches. No arguments are accepted. The ``branches`` template is rendered. | def branches(web):
entries = webutil.branchentries(web.repo, web.stripecount)
latestentry = webutil.branchentries(web.repo, web.stripecount, 1)
return web.sendtemplate(
b'branches',
node=hex(web.repo.changelog.tip()),
entries=entries,
latestentry=latestentry,
) | [
"def _gitlab_list_branches(self) -> typing.Set[str]:\n response = requests.Session().get(\n f\"{IGitt.GitLab.BASE_URL}/projects/{quote_plus(self.slug)}/repository/branches\",\n params={'private_token': self.token},\n )\n\n response.raise_for_status()\n # TODO: pagin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/diff/{revision}/{path} Show how a file changed in a particular commit. The ``filediff`` template is rendered. This handler is registered under both the ``/diff`` and ``/filediff`` paths. ``/diff`` is used in modern code. | def filediff(web):
fctx, ctx = None, None
try:
fctx = webutil.filectx(web.repo, web.req)
except LookupError:
ctx = webutil.changectx(web.repo, web.req)
path = webutil.cleanpath(web.repo, web.req.qsparams[b'file'])
if path not in ctx.files():
raise
if fctx is ... | [
"def git_diff(filepath, since):\n html_diff = None\n commits = git_commits(filepath, since)\n if commits:\n cmd = ('git', '--no-pager', 'diff', commits[-1]+'^', '--',\n filepath)\n stdout, stderr = execute(cmd)\n\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/comparison/{revision}/{path} Show a comparison between the old and new versions of a file from changes made on a particular revision. This is similar to the ``diff`` handler. However, this form features a split or sidebyside diff rather than a unified diff. The ``context`` query string argument can be used to control ... | def comparison(web):
ctx = webutil.changectx(web.repo, web.req)
if b'file' not in web.req.qsparams:
raise ErrorResponse(HTTP_NOT_FOUND, b'file not given')
path = webutil.cleanpath(web.repo, web.req.qsparams[b'file'])
parsecontext = lambda v: v == b'full' and -1 or int(v)
if b'context' in we... | [
"def filediff(web):\n fctx, ctx = None, None\n try:\n fctx = webutil.filectx(web.repo, web.req)\n except LookupError:\n ctx = webutil.changectx(web.repo, web.req)\n path = webutil.cleanpath(web.repo, web.req.qsparams[b'file'])\n if path not in ctx.files():\n raise\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/annotate/{revision}/{path} Show changeset information for each line in a file. The ``ignorews``, ``ignorewsamount``, ``ignorewseol``, and ``ignoreblanklines`` query string arguments have the same meaning as their ``[annotate]`` config equivalents. It uses the hgrc boolean parsing logic to interpret the value. e.g. ``0... | def annotate(web):
fctx = webutil.filectx(web.repo, web.req)
f = fctx.path()
parity = paritygen(web.stripecount)
ishead = fctx.filenode() in fctx.filelog().heads()
# parents() is called once per line and several lines likely belong to
# same revision. So it is worth caching.
# TODO there ar... | [
"def annotate(self):\n for line in self.line_map:\n if line.is_tier_line:\n line.annotations = self._extract_annots(line.tier, line.onset,\n line.offset, line.content,\n lin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/filelog/{revision}/{path} Show information about the history of a file in the repository. The ``revcount`` query string argument can be defined to control the maximum number of entries to show. The ``filelog`` template will be rendered. | def filelog(web):
try:
fctx = webutil.filectx(web.repo, web.req)
f = fctx.path()
fl = fctx.filelog()
except error.LookupError:
f = webutil.cleanpath(web.repo, web.req.qsparams[b'file'])
fl = web.repo.file(f)
numrevs = len(fl)
if not numrevs: # file doesn... | [
"def getRevisionLog(url, revision):\r\n svn_log = subprocess2.check_output(\r\n ['svn', 'log', url, '-r', str(revision)],\r\n universal_newlines=True).splitlines(True)\r\n # Don't include the header lines and the trailing \"---...\" line.\r\n return ''.join(svn_log[3:-1])",
"def get_repo_log(path=Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/archive/{revision}.{format}[/{path}] Obtain an archive of repository content. The content and type of the archive is defined by a URL path parameter. ``format`` is the file extension of the archive type to be generated. e.g. ``zip`` or ``tar.bz2``. Not all archive types may be allowed by your server configuration. The... | def archive(web):
type_ = web.req.qsparams.get(b'type')
allowed = web.configlist(b"web", b"allow-archive")
key = web.req.qsparams[b'node']
if type_ not in webutil.archivespecs:
msg = b'Unsupported archive type: %s' % stringutil.pprint(type_)
raise ErrorResponse(HTTP_NOT_FOUND, msg)
... | [
"def archive(\n repo,\n dest,\n node,\n kind,\n decode=True,\n match=None,\n prefix=b'',\n mtime=None,\n subrepos=False,\n):\n\n if kind == b'txz' and not pycompat.ispy3:\n raise error.Abort(_(b'xz compression is only available in Python 3'))\n\n if kind == b'files':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/graph[/{revision}] Show information about the graphical topology of the repository. Information rendered by this handler can be used to create visual representations of repository topology. The ``revision`` URL parameter controls the starting changeset. If it's absent, the default is ``tip``. The ``revcount`` query st... | def graph(web):
if b'node' in web.req.qsparams:
ctx = webutil.changectx(web.repo, web.req)
symrev = webutil.symrevorshortnode(web.req, ctx)
else:
ctx = web.repo[b'tip']
symrev = b'tip'
rev = ctx.rev()
bg_height = 39
revcount = web.maxshortchanges
if b'revcount' ... | [
"def graph():\n return render_template('main/graph.html')",
"def get_graph(request):\r\n data = {\"links\":[]}\r\n name = memcache.get(\"name\")\r\n id = memcache.get(\"id\")\r\n if 'graphid' not in request.session:\r\n nodes = memcache.get(\"nodes\")\r\n if not name or not nodes:\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/help[/{topic}] Render help documentation. | def help(web):
from .. import commands, help as helpmod # avoid cycle
topicname = web.req.qsparams.get(b'node')
if not topicname:
def topics(context):
for h in helpmod.helptable:
entries, summary, _doc = h[0:3]
yield {b'topic': entries[0], b'summary': s... | [
"def api_help():\n docs = [{'name': route.__name__, 'value': route.__doc__}\n for route in [aliases, connections, databases, fetch, now, reports]]\n return render_template('help.html', docs=docs, version=__version__, url_root=request.url_root)",
"def show_help_topic(self):\n \n pass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checking that getting rotation matrices from diffpy.structure works without issue. | def test_get_rotation_matrix_from_diffpy(self):
r = Rotation.from_matrix([i.R for i in sg225.symop_list])
assert not np.isnan(r.data).any() | [
"def test_rotation_matrix_conversions(self):\n from clifford.g3c import layout\n from clifford.tools.g3 import rotation_matrix_to_rotor, rotor_to_rotation_matrix\n e1 = layout.blades['e1']\n e2 = layout.blades['e2']\n\n rotor = e1*e2\n print(rotor)\n matrix = rotor_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the purpose of this function is to create a list of residues names A11 of proteins that are made of two helixes seperated by a gap pro_eitherside is how many side of the gap I should search | def double_helix_parser(input_file, output_file, helicies_length = 6, helix_gap = 3, pro_eitherside = 3):
res_no_l = [] # for residue names
res_name_l = [] # for amino acid names
sec_str_l = [] # for sec structure prediction
two_helix_l = [] # contains a list aminoacids (also a l... | [
"def get_exemplu_apartamente():\r\n apartamente = []\r\n p = 100\r\n for i in range(0,10):\r\n adauga_apartament(apartamente,i*p,i*p+1,i*p+2,i*p+3,i*p+4)\r\n return apartamente",
"def genenames_from10x(genelist):\n genesymbol=[]\n #ensemblid=[]\n for i in range(len(genelist)):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the post settings. This function sets custom values for post type, post status and maxposts if custom values are definied in the object initialization. If not, the function will set default values as provided from the Constants section. The Basic Post Configuration is configuratable, the postMetaFields only via Co... | def __init__(self, **kwargs):
self.postBasicInformation = {}
if 'post_type' in kwargs:
self.postBasicInformation['post_type'] = kwargs.get('post_type')
else:
self.postBasicInformation['post_type'] = DEFAULT_POST_TYPE
if 'post... | [
"def post_type(self, post_type):\n\n self._post_type = post_type",
"def _structure_blog_settings(_khoros_object, _blog_settings, _payload, _discussion_style):\n if any(_blog_settings.values()) and _discussion_style != 'blog':\n _warn_about_ignored_settings('blog', _discussion_style)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
J_ij = t , or if rdep is true, J_ij = t/r^3 t selfexplanatory rdep whether or not to have J depend on r^3 | def __init__(self, nnOnly, t, rdep):
super().__init__(nnOnly)
self.t = t
self.rdep = rdep
if (rdep):
self.desc = "j_ij = t/r**3, with t = %f" % (t)
else:
self.desc = "j_ij = t, with t = %f" % (t)
if (self.nnOnly):
self.desc = self.desc + ", j_ij on nearest neighbours only\n" | [
"def jacobian(\n self, t: float, state: np.ndarray, u: np.ndarray) -> np.ndarray:\n pass",
"def __constant_jerk__(x, dt, params, options=None):\n\n if options is None:\n options = {'backward': False}\n\n r, q = params\n A = np.matrix([[1, dt, 0, 0],\n [0, 1, dt, 0],... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries to use the configuration to get the principal. If this fails with an exception, the client was not configured corectly, so this is a good way to check for that. | def try_configuration(self) -> None:
with self.context():
kerberos.getServerPrincipalDetails(self.service, self.hostname) | [
"def _get_credentials():\n if not CONFIG:\n raise ConfigError(\"Configuration is not passed\")\n\n try:\n return CONFIG[\"credentials\"]\n except KeyError:\n raise ConfigError(\"Credentials configurations are missing from config\")",
"def authenticate_client(self):\n client_pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs the block inside the context manager with the keytab set to the provider's keytab. All functions that interact with kerberos must be run inside this context. For convenience, this context returns the kerberos module when invoked. | def context(self) -> 'Iterator[None]':
previous = os.environ.pop('KRB5_KTNAME', None)
os.environ['KRB5_KTNAME'] = self.keytab
yield
if previous is not None:
os.environ['KRB5_KTNAME'] = previous | [
"def kerberos_http_auth(self):\n\n try:\n r = None\n if self.version == 7:\n r = requests.get(\n \"{}://{}:{}/api/v40/cm/kerberosPrincipals\".format(\n self.http,\n self.cloudera_manager_host_ip,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates code to instantiate a stateful 'Delay' object, and provides reference to that object's output. The name of the stateful object is based upon the passed in parameters, so if there are multiple places where identical delay functions are referenced, the translated python file will only maintain one stateful object... | def add_delay(identifier, delay_input, delay_time, initial_value, order,
subs):
import_modules['functions'].add("Delay")
new_structure = []
py_name = '_delay_%s' % identifier
if len(subs) == 0:
stateful_py_expr = "Delay(lambda: %s, lambda: %s,"\
"lambda... | [
"def add_delay_f(identifier, delay_input, delay_time, initial_value):\n import_modules['functions'].add(\"DelayFixed\")\n\n py_name = '_delayfixed_%s' % identifier\n\n stateful_py_expr = \"DelayFixed(lambda: %s, lambda: %s,\"\\\n \"lambda: %s, time_step, '%s')\" % (\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates code to instantiate a stateful 'DelayFixed' object, and provides reference to that object's output. The name of the stateful object is based upon the passed in parameters, so if there are multiple places where identical delay functions are referenced, the translated python file will only maintain one stateful o... | def add_delay_f(identifier, delay_input, delay_time, initial_value):
import_modules['functions'].add("DelayFixed")
py_name = '_delayfixed_%s' % identifier
stateful_py_expr = "DelayFixed(lambda: %s, lambda: %s,"\
"lambda: %s, time_step, '%s')" % (
delay_inp... | [
"def add_delay(identifier, delay_input, delay_time, initial_value, order,\n subs):\n import_modules['functions'].add(\"Delay\")\n\n new_structure = []\n py_name = '_delay_%s' % identifier\n\n if len(subs) == 0:\n stateful_py_expr = \"Delay(lambda: %s, lambda: %s,\"\\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates code to instantiate a stateful 'DelayN' object, and provides reference to that object's output. The name of the stateful object is based upon the passed in parameters, so if there are multiple places where identical delay functions are referenced, the translated python file will only maintain one stateful objec... | def add_n_delay(identifier, delay_input, delay_time, initial_value, order,
subs):
import_modules['functions'].add("DelayN")
new_structure = []
py_name = '_delayn_%s' % identifier
if len(subs) == 0:
stateful_py_expr = "DelayN(lambda: %s, lambda: %s,"\
... | [
"def add_delay(identifier, delay_input, delay_time, initial_value, order,\n subs):\n import_modules['functions'].add(\"Delay\")\n\n new_structure = []\n py_name = '_delay_%s' % identifier\n\n if len(subs) == 0:\n stateful_py_expr = \"Delay(lambda: %s, lambda: %s,\"\\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates code to instantiate a stateful 'SampleIfTrue' object, and provides reference to that object's output. | def add_sample_if_true(identifier, condition, actual_value, initial_value):
import_modules['functions'].add("SampleIfTrue")
py_name = '_sample_if_true_%s' % identifier
# describe the stateful object
stateful = {
'py_name': py_name,
'real_name': 'Sample if true of %s' % identifier,
... | [
"def test_samples_bool_true(base_store: Store, helpers):\n\n # GIVEN sample that is received, prepared, sequenced and delivered\n new_case = add_case(helpers, base_store)\n sample = helpers.add_sample(\n base_store,\n received_at=datetime.now(),\n prepared_at=datetime.now(),\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs stock and flow chains that implement the calculation of a smoothing function. | def add_n_smooth(identifier, smooth_input, smooth_time, initial_value, order,
subs):
import_modules['functions'].add("Smooth")
new_structure = []
py_name = '_smooth_%s' % identifier
if len(subs) == 0:
stateful_py_expr = "Smooth(lambda: %s, lambda: %s,"\
... | [
"def smoothCurve(smoothness=float, replaceOriginal=bool, object=bool, nodeState=int, constructionHistory=bool, caching=bool, name=\"string\"):\n pass",
"def _smooth_price_data(self, sigma):\n self.High = features.gaussian_filter(self.High_raw, sigma)\n self.Low = features.gaussian_filter(self.Low... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Incomplete functions don't really need to be 'builders' as they add no new real structure, but it's helpful to have a function in which we can raise a warning about the incomplete equation at translate time. | def add_incomplete(var_name, dependencies):
import_modules['functions'].add("incomplete")
warnings.warn('%s has no equation specified' % var_name,
SyntaxWarning, stacklevel=2)
# first arg is `self` reference
return "incomplete(%s)" % ', '.join(dependencies), [] | [
"def Expression(self) -> _n_4_t_1:",
"def dummy_no_ephem():",
"def solve(equation):\r\n\r\n if not validator.is_valid(equation):\r\n raise Invalid(\"not valid\")\r\n #make haircut for the minuses\r\n equation = solver_helper.minuses_haircut(equation)\r\n #strip the expression from it's bracke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ZBar's implementation of bch15_5_encode | def zbar_bch15_5_encode(x):
return (
(-(x & 1) & 0x0537) ^
(-(x >> 1 & 1) & 0x0A6E) ^
(-(x >> 2 & 1) & 0x11EB) ^
(-(x >> 3 & 1) & 0x23D6) ^
(-(x >> 4 & 1) & 0x429B)
) | [
"def encode(postings_list):\n ### Begin your code\n if postings_list == []:\n return array.array('B', []).tobytes()\n result = []\n pre = postings_list[0]\n for item in CompressedPostings().getBin(pre):\n result.append(int(item, 2))\n for i in range(1,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a QR code grid | def decode_qr_grid(qrgrid):
qrsize = len(qrgrid)
assert all(len(col) == qrsize for col in qrgrid), "not a square grid"
# Extract format info, which is present in lines
format_int1 = 0
format_int2 = 0
for y in range(6):
format_int1 |= qrgrid[8][y] << y
format_int1 |= qrgrid[8][7] << ... | [
"def decode_hello():\n # Load the image\n im = Image.open(os.path.join(os.path.dirname(__file__), 'barcode-image21helloqrworld.png'))\n im = im.crop((24, 24, 108, 108))\n imdata = im.getdata()\n\n qrsize = 21\n qrgrid = [[None] * qrsize for _ in range(qrsize)]\n for x in range(qrsize):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw a QR code grid | def draw_grid(qrgrid):
qrsize = len(qrgrid)
assert all(len(col) == qrsize for col in qrgrid), "not a square grid"
im = Image.new("RGB", (qrsize * 8, qrsize * 8), "blue")
draw = ImageDraw.Draw(im)
for (x, column) in enumerate(qrgrid):
for (y, val) in enumerate(column):
if (x <= 8... | [
"def __draw_grid(self):\n MARGIN = self.MARGIN\n for i in range(4):\n x0 = (4-i) * MARGIN + MARGIN\n y0 = i * MARGIN\n x1 = 160-(4-i)*MARGIN + MARGIN\n y1 = i * MARGIN\n self.canvas.create_line(x0, y0, x1, y1)\n\n for j in range(3-i, 5+... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode a basic QR code | def decode_hello():
# Load the image
im = Image.open(os.path.join(os.path.dirname(__file__), 'barcode-image21helloqrworld.png'))
im = im.crop((24, 24, 108, 108))
imdata = im.getdata()
qrsize = 21
qrgrid = [[None] * qrsize for _ in range(qrsize)]
for x in range(qrsize):
for y in rang... | [
"def decode_qr(arg_image):\n qr_result = decode(arg_image)\n\n if (len( qr_result ) > 0):\n decoded_data = qr_result[0].data\n else:\n decoded_data = \"NA\"\n\n #Return the Decode data from QR \n return decoded_data",
"def decode(image_file):\n \n # Set message\n message = \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a new StatsD client. | def __init__(self, prefix="", host="127.0.0.1", port="8125"):
self.stat = statsd.StatsClient(host=host, port=port, prefix=prefix) | [
"def _init_client(self):\n pass",
"def __init__(self):\r\n super().__init__()\r\n self.params = SysParams().params\r\n self.database = self.params['influx_database']\r\n self.logger = Logger().logger\r\n\r\n # The client should be an instance of InfluxDBClient.\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that the embeddings can be loaded, have the right dimension, and that one line matches. | def test_load(self):
embedder = LookupEmbedder(init_fastext='examples/data/wiki.ja.vec.small', emb_dim=300, vocab=self.input_reader.vocab)
# self.assertEqual(embedder.embeddings.shape()[::-1], (self.input_reader.vocab_size(), 300))
with open('examples/data/wiki.ja.vec.small', encoding='utf-8') as vecfile:
... | [
"def _check_constraints(self):\n assert self.instance.entity_representations[0].enriched_embeddings is None",
"def _check_constraints(self):\n assert all_in_bounds(self.instance.entity_embeddings(indices=None).norm(p=2, dim=-1), high=1.0, a_tol=EPSILON)",
"def _check_constraints(self):\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compile GPSGstyle rules into CFG rules. | def expand_gpsg_rules(rules):
def free_variables_in(element):
parts = element.split("_")
for part in parts:
if part.startswith("{") and part.endswith("}"):
yield part.strip("{}")
def possible_feature_values_in(element):
parts = element.split("_")
for ... | [
"def build_goci_rules():\n rules_dict = {\n 'level 1a': processing_rules.build_rule('level 1a', ['level 0'],\n run_bottom_error, False),\n 'l1brsgen': processing_rules.build_rule('l1brsgen', ['l1'],\n run_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the attributes `data_type` and 'loader_class` based of the given `smrf_config` parameter. Currently supports two types of data | def __determine_data_type(self, smrf_config):
loader_args = dict(start_date=self.start_date, end_date=self.end_date)
if InputCSV.DATA_TYPE in smrf_config:
self.data_type = InputCSV.DATA_TYPE
self.load_class = InputCSV(
**loader_args,
stations=smrf... | [
"def data_loader_cls(self, new_loader_cls):\n\n assert inspect.isclass(new_loader_cls) and issubclass(new_loader_cls,\n SlimDataLoaderBase)\n self._data_loader_cls = new_loader_cls",
"def set_from_dict(config):\n if \"CACHE\" in config:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the pixel location in the topo for each station | def metadata_pixel_location(self):
self.metadata['xi'] = self.metadata.apply(
lambda row: self.find_pixel_location(
row,
self.topo.x,
'utm_x'), axis=1)
self.metadata['yi'] = self.metadata.apply(
lambda row: self.find_pixel_location... | [
"def _set_pixel_geometries(self):\n\n feats = self.features\n if feats is None:\n return\n\n proj_method = self._extract_geolocation_details()\n for feat in feats.features:\n if feat.geometry is None or feat.uid in self._pixel_geometries:\n continue\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert the new titratable groups in to self.pkagroups | def insert_new_titratable_group(self, ligand_titratable_groups):
group_type = ligand_titratable_groups['type']
if group_type in self.pKagroups:
#
# Now modify the group so that it will correspond to the group
# we have in the ligand
#
ligand_na... | [
"def insert_group(self, group):\n index = self.find_named_folder(\"Groups\")\n\n parent_node = self.get_node(index)\n\n # Check to see if an AOV Group of the same name already exists. If it\n # does then we want to just update the internal item for the node.\n for row, child in e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the radii for specific atoms in a residue | def setRadii(self, residue, atomlist):
for atom in residue.get("atoms"):
atomname = atom.get("name")
if atomname not in atomlist: continue
charge, radius = self.forcefield.getParams(residue, atomname)
if radius != None:
atom.set("radius", radius)
... | [
"def setAllRadii(self):\n for chain in self.protein.getChains():\n for residue in chain.get(\"residues\"):\n for atom in residue.get(\"atoms\"):\n atomname = atom.get(\"name\")\n if atomname.find('FLIP') != -1:\n continue\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the charges for specific atoms in a residue | def setCharges(self, residue, atomlist):
for atom in residue.get("atoms"):
atomname = atom.get("name")
if atomname not in atomlist:
continue
charge, radius = self.forcefield.getParams(residue, atomname)
if charge != None:
atom.set("... | [
"def update_charge(self):\n for atom in self.atoms:\n if (len(atom.charge) == 1) and (len(atom.lone_pairs) == 1) and (len(atom.radical_electrons) == 1):\n # if the charge of the group is not labeled, then no charge update will be\n # performed. If there multiple charg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set all radii for the entire protein | def setAllRadii(self):
for chain in self.protein.getChains():
for residue in chain.get("residues"):
for atom in residue.get("atoms"):
atomname = atom.get("name")
if atomname.find('FLIP') != -1:
continue
... | [
"def zeroAllRadiiCharges(self):\n for chain in self.protein.getChains():\n for residue in chain.get(\"residues\"):\n for atom in residue.get(\"atoms\"):\n atom.set(\"ffcharge\", 0.0)\n atom.set(\"radius\", 0.0)",
"def set_bond_radii(atoms, bon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set all charges and radii for the protein to zero | def zeroAllRadiiCharges(self):
for chain in self.protein.getChains():
for residue in chain.get("residues"):
for atom in residue.get("atoms"):
atom.set("ffcharge", 0.0)
atom.set("radius", 0.0) | [
"def zero(self):\n self.set(0.0)",
"def _zeronan(self):\n self.rate[np.isnan(self.rate)] = 0\n self.error[np.isnan(self.error)] = 0",
"def clear_zero(self):\n self._zero = None\n self._vel_sp = 0\n self._pos_sp = None\n self._on_sp = False\n self._log.info... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all titratable groups in the protein based on the definition Returns | def findTitratableGroups(self):
pKalist = []
print("Finding Titratable residues:")
for chain in self.protein.getChains():
for residue in chain.get("residues"):
resname = residue.get("name")
for group in self.pKagroups:
if resname =... | [
"def getGroupedHebergementTypes():",
"def get_taxonomy_groups(self):\n tgroups = TaxonomyGroup.objects.filter(taxonomyitem__taxonomymap__object_id=self.pk).distinct()\n return list(tgroups)",
"def test_get_groups_list(self):\n pass",
"def _findgroups(self):\n\t\t# find all attribute group... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the Titration Definition | def readTitrationDefinition(self):
mygroups = {}
filename = TITRATIONFILE
if not os.path.isfile(TITRATIONFILE):
raise ValueError("Could not find TITRATION.DAT!")
file = open(filename)
while 1:
line = file.readline()
if line.startswith("//"):
... | [
"def _read_structure_attributes(f):\n\n line = ''\n variogram_info = {}\n while \"end structure\" not in line:\n line = f.readline()\n if line == '':\n raise Exception(\"EOF while reading structure\")\n line = line.strip().lower().split()\n if line[0].startswith('#'):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the interface with pKaTool | def test_interface():
import pKaTool.pKa_calc
X = pKaTool.pKa_calc.Monte_Carlo_Mult_CPP()
X.intrinsic_pKa = {':0001:ASP': [0.0, 4.0, 5.0]}
X.charged_state = {':0001:ASP': [0, 1, 1]}
X.acid_base = {':0001:ASP': -1}
X.intene_mult = {':0001:ASP': {':0001:ASP': [[0, 0, 0], [0, 0, 0], [0, 0, 0]]}}
... | [
"def testSKPCA():\n pass",
"def test_example_azerty():\n azerty.main(test=True)",
"def test_ProjE():\n testing_function('proje_pointwise')",
"def test_pro_bowlers(self):\n pass",
"def test_vicars_get(self):\n pass",
"def test_run_feature_selection(self):",
"def tests(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates an angular defect of the given vertex | def angular_defect(self, vertex):
defect = 2 * math.pi
for face in self.faces:
if vertex in face:
tmp = list(face)
tmp.remove(vertex)
u, v = tmp
top = self.distance(vertex, u) ** 2 + self.distance(vertex, v) ** 2 - self.distance... | [
"def get_angularv(self):\n\t\treturn \"{} {} {}\".format(self.data.angular_velocity.x, self.data.angular_velocity.y, self.data.angular_velocity.z)",
"def angleDefect(self):\n if 'angleDefect' in self._cache: return self._cache['angleDefect']\n\n if(self.isBoundary()):\n defect = 0\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get slot of a specific index. | def slot(self, i):
if i < 0 or i > 2:
raise ValueError('Only three slots are available')
return self.get_slots()[i] | [
"def getSlot(self, index: int) -> InventoryItem:\r\n\t\treturn self._content[index]",
"def _find_slot(self, key):\n hashkey = hash(key) % self._size\n slot = self._slots[hashkey]\n return slot",
"def GetSlot(self, name):\n return next((x for x in self._slots if x.Name == name), None)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get alarm slots. Speakers have 3 alarm slots available. This method will return the ones that are set as well as empty ones to use for setting new alarms. | def get_slots(self):
alarms = self._api.get_alarm_info()
for alarm in alarms:
index = int(alarm['@index'])
self._slots[index] = AlarmSlot(self._api, index, alarm)
# fill with empty slots
for index in range(3):
if self._slots[index] is None:
... | [
"def get_slots(self):\n return set(self._slots.keys())",
"def get_schedule_slots_by_time(self, time):\n return # osid.calendaring.ScheduleSlotList",
"def get_alarms(zone=None):\n alarms = Alarms()\n alarms.update(zone)\n return set(alarms.alarms.values())",
"def get_timeslot_include_ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete this alarm and set alarm settings to defaults. | def delete(self):
self._api.del_alarm(self._index)
self._set_defaults() | [
"def delete_alarm(self, alarm):\r\n return self.manager.delete_alarm(self, alarm)",
"def reset(self):\n self.clear()\n dict.update(self, self.defaults)",
"def remove(self):\n result = self.zone.alarmClock.DestroyAlarm([(\"ID\", self.alarm_id)])\n alarms = Alarms()\n ala... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get station_data by providing playlist of compatible items. | def _get_station_data_from_playlist(self, playlist):
for radio in playlist:
if radio.object_type not in ['tunein_radio']:
continue
station_data = self._api.get_station_data(radio.object_id)
return {
'title': station_data['title'] or '',
... | [
"def get_similar(self):\n\n similar_url = 'http://songza.com/api/1/station/%s/similar'\n\n HEADER = {\"User-Agent\":\n \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)\"}\n\n\n REQUEST_KWARGS = {'headers':HEADER, 'timeout':10.0, 'allow_redirects':Fals... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to convert speaker's hex representation of weekdays into list of integers represending weekdays. | def hexweek_to_weekday_list(hexweek):
intweek = int(hexweek, 16)
# Mon, Tue, Wed, Thu, Fri, Sat, Sun
weekday_bits = [32, 16, 8, 4, 2, 1, 64]
return [weekday for weekday, weekday_bit in enumerate(weekday_bits) if intweek & weekday_bit] | [
"def weekday_list_to_hexweek(weekday_list):\n # Mon, Tue, Wed, Thu, Fri, Sat, Sun\n weekday_bits = [32, 16, 8, 4, 2, 1, 64]\n weekday_list = set(weekday_list)\n\n return hex(sum([weekday_bits[weekday] for weekday in weekday_list]))",
"def get_weekday_time() -> list:\n return [DAYS[date.today().week... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to convert list of integers represending weekdays into speaker's hex representation of weekdays. | def weekday_list_to_hexweek(weekday_list):
# Mon, Tue, Wed, Thu, Fri, Sat, Sun
weekday_bits = [32, 16, 8, 4, 2, 1, 64]
weekday_list = set(weekday_list)
return hex(sum([weekday_bits[weekday] for weekday in weekday_list])) | [
"def convert_to_hexadecimal_list(list): \n for i in range (0, len(list)):\n list[i] = hex(int(list[i]))\n return list",
"def hexweek_to_weekday_list(hexweek):\n intweek = int(hexweek, 16)\n\n # Mon, Tue, Wed, Thu, Fri, Sat, Sun\n weekday_bits = [32, 16, 8, 4, 2, 1, 64]\n\n return [weekd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts the grid by a specified metric | def sort_grid(self, metric= ''):
Point.sort_by = metric
self.grid = sorted(self.grid)
self.sorted_by = metric
return True | [
"def _sort(self, units, param):\n return np.array(sorted(units, key=lambda unit: unit.get(param),\n reverse=not self.winner))",
"def _sort_by(self, criteria):\n log.info('Sorting kernels by {}')\n assert self._select_drop_down('sort', criteria)",
"def sort(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a grid object from a specific ShakeMap | def create_grid(shakemap=None):
grid = ShakeMapGrid()
grid_location = os.path.join(shakemap.directory_name, 'grid.xml')
grid.load(grid_location)
return grid | [
"def _add_manual_grid_mapping(): \n data = {}\n data['crs'] = ncout.createVariable('crs', np.dtype('c').char)\n utils.addGridMappingVars(data['crs'], locationLat, locationLong, rotation)",
"def make_snakes(map,coords,surface=None):\r\n elements = {}\r\n snakes = []\r\n n = len(coo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the name / code snippet pair for each Lua function in the file under file_name. | def _split_lua_file_into_funcs(self, file_name):
with open(self._get_lua_path(file_name)) as f:
for func in f.read().strip().split("function "):
if func:
bits = func.split("\n", 1)
name = bits[0].split("(")[0].strip()
snippe... | [
"def _get_lua_funcs(self):\n with open(\"bitwise.lua\", \"r\") as f:\n for func in f.read().strip().split(\"local function \"):\n if func:\n bits = func.split(\"\\n\", 1)\n name = bits[0].split(\"(\")[0].strip()\n snippet = bi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers the code snippet as a Lua script, and binds the script to the client as a method that can be called with the same signature as regular client methods, eg with a single key arg. | def _bind_lua_method(self, name, code):
script = self._client.register_script(code)
method = lambda key, *a, **k: script(keys=[key], args=a, **k)
setattr(self, name, method) | [
"def _bind_private_lua_script(self, name, code):\n script = self._client.register_script(code)\n setattr(self, '_' + name, script)",
"def register_script(self, script):\n from aredis.scripting import Script\n return Script(self, script)",
"def add_script(self, script, raw=False):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers the code snippet as a Lua script, and binds the script to the client as a private method (eg. some_lua_func becomes a _some_lua_func method of HotClient) that can be latter wrapped in public methods with better argument and error handling. | def _bind_private_lua_script(self, name, code):
script = self._client.register_script(code)
setattr(self, '_' + name, script) | [
"def _bind_lua_method(self, name, code):\n script = self._client.register_script(code)\n method = lambda key, *a, **k: script(keys=[key], args=a, **k)\n setattr(self, name, method)",
"def register_script(self, script):\n from aredis.scripting import Script\n return Script(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the value of the other type instance to use in an operator method, namely when the method's instance is on the left side of the expression. | def value_left(self, other):
return other.value if isinstance(other, self.__class__) else other | [
"def op_left(op):\n\n def method(self, other):\n return op(self.value, value_left(self, other))\n\n return method",
"def __call__(self, other):\n return Type.engine.apply(self, other)",
"def _cast_other(binary_op):\r\n def cast_op(self, other):\r\n \"\"\"A wrapped binary operator t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a type instance method for the given operator, applied when the instance appears on the left side of the expression. | def op_left(op):
def method(self, other):
return op(self.value, value_left(self, other))
return method | [
"def binary_operator(op):\n def _binary_operator(self, other):\n return_type = binop_return_type(op)\n if isinstance(self, NumExprFactor):\n self_expr, other_expr, new_inputs = self.build_binary_op(\n op, other\n )\n return return_type(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a type instance method for the given operator, applied when the instance appears on the right side of the expression. | def op_right(op):
def method(self, other):
return op(value_left(self, other), value_right(self, other))
return method | [
"def binary_operator(op):\n def _binary_operator(self, other):\n return_type = binop_return_type(op)\n if isinstance(self, NumExprFactor):\n self_expr, other_expr, new_inputs = self.build_binary_op(\n op, other\n )\n return return_type(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an ics.Event object from the provided entry | def make_event( self, entry ):
e = ics.Event()
e.name = entry.name
e.begin = '%s %s' % (entry.date, entry.start)
e.end = '%s %s' % (entry.date, entry.end)
return e | [
"def add_event( self, entry: CalendarHelpers.DataStructures.Entry ):\n event = self.make_event( entry )\n self.calendar.events.append( event )",
"def _create_event_entry(event, originator, data):\n data = CaseLogger._format_data(data)\n event = Event(\n type=event.event_type... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an entry from the entry and adds it to the calendar | def add_event( self, entry: CalendarHelpers.DataStructures.Entry ):
event = self.make_event( entry )
self.calendar.events.append( event ) | [
"def _create_entry(self, start_time, end_time=None, user=None):\r\n data = {\r\n 'user': user or self.user,\r\n 'project': self.project,\r\n 'activity': self.activity,\r\n 'location': self.location,\r\n 'status': self.status,\r\n 'start_time':... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the content of a Parquet file into a Pandas DataFrame. | def read_parquet(filename, columns=None, index=None):
pf = ParquetFile(filename)
return pf.to_pandas(columns=columns, index=index) | [
"def read(\n cls, file_path: str, unflatten_kwargs: dict = None, **read_kwargs\n ) -> pd.DataFrame:\n return pd.read_parquet(path=file_path, **read_kwargs)",
"def read_dataframe_from_bucket(file_path: str) -> pd.DataFrame:\n return pd.read_parquet(file_path)",
"def read_file(self, file_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite current damage and return self. | def with_attack(self, damage: int) -> object:
self.damage = damage
return self | [
"def take_damage(self, damage):\n # self.current_health -= self.defend(damage)\n # return self.current_health",
"def setDamage(self, damage):\n getHandle().setDamage(float(damage))",
"def harm(self, damage):\n\n print \"%d damage was done to %s\" % (damage, self.id)\n self.hea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite current cooldown and return self. | def with_cooldown(self, cooldown: int) -> object:
self.cooldown = cooldown
return self | [
"def cooldown(self, value):\n\n pass",
"def other_cooldown(self, value):\n\n pass",
"def other_cooldown(self):\n\n if self._other == None:\n return None\n\n return self._other_cooldown",
"def start_cooldown(self):\r\n self.cooldown_timer = 0\r\n self.cast_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overwrite current dot and dot_ticks. Return self. | def with_dot(self, damage: int, ticks: int) -> object:
self.dot = damage
self.dot_ticks = ticks
return self | [
"def draw(self):\n super().draw()\n dot(self.prop['dotSize'], self.prop['dotColor'])",
"def plot_dot(self, frame_index):\n\n if self.dot is not None:\n self.dot.remove()\n self.dot = plt.scatter(self.x[frame_index], self.y[frame_index], s=20, color='red')\n self.fig.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attack target and apply dot if applicable. | def attack(self, target: Health) -> None:
if self.__cooldown_tick == 0:
target.apply_damage(self.damage)
if self.dot > 0: target.apply_dot(self.dot, self.dot_ticks) | [
"def attack(self, data, target):\n B, K = data.shape[:2]\n data = data.float().cuda().detach()\n data = data.transpose(1, 2).contiguous()\n ori_data = data.clone().detach()\n ori_data.requires_grad = False\n\n # points and normals\n if ori_data.shape[1] == 3:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if attack has completed cooldown upon update. | def on_update(self) -> None:
if self.__cooldown_tick == self.cooldown:
self.__cooldown_tick = 0
else:
self.__cooldown_tick += 1 | [
"def tick_cooldowns(self):\n\n if self.bullet_cooldown > 0:\n self.bullet_cooldown -= 1",
"def can_shoot(self):\n\n return (self._cooldown <= 0)",
"def check_cooldown(db: Database, channel_name: str) -> bool:\n if channel_name[0] == \"#\":\n channel_name = channel_name[1:]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Respond to iOS notification to empty vacuum. | def response_from_push_notification(
self, event_name: str, data: dict, kwargs: dict) -> None:
self.hass.log('Responding to iOS request that vacuum is empty')
self.hass.manager_app.bin_state = (
self.hass.manager_app.BinStates.empty)
target = self.hass.notification_mana... | [
"def vacuum_empty(self):\n return self._vacuum.is_empty()",
"def vacuum_full(self):\n return self._vacuum.is_full()",
"def listen_unallocated(self):\n\n pass",
"async def test_no_fan_vacuum(opp, mqtt_mock):\n config = deepcopy(DEFAULT_CONFIG)\n del config[mqttvacuum.CONF_FAN_SPEED_L... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define a property to get the bin state. | def bin_state(self) -> Enum:
return self.BinStates(self.get_state(self.entities['bin_state'])) | [
"def flag_property(flag):\n def getter(self):\n return (self._flags & flag) != 0\n def setter(self, value):\n if value:\n self._flags |= flag\n else:\n self._flags &= ~flag\n return property(getter, setter)",
"def readStateAttribute(self):\r\n return _osg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function for validating an ABI | def validate_abi(abi):
if not is_list_like(abi):
raise TypeError("'abi' is not a list")
for e in abi:
if not is_dict(e):
raise TypeError("The elements of 'abi' are not all dictionaries") | [
"def validate_abi(abi: ABI) -> None:\n if not is_list_like(abi):\n raise ValueError(\"'abi' is not a list\")\n\n if not all(is_dict(e) for e in abi):\n raise ValueError(\"'abi' is not a list of dictionaries\")\n\n functions = filter_by_type(\"function\", abi)\n selectors = groupby(compose(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function for validating an address EIP55 checksum | def validate_address_checksum(address):
if is_checksum_formatted_address(address):
if not is_checksum_address(address):
raise ValueError("'address' has an invalid EIP55 checksum") | [
"def isAddress(check):\n\timport re\n\tif re.search('^[13][a-zA-Z0-9]{26,33}$', check):\n\t\treturn True\n\telse:\n\t\treturn False",
"def is_valid_base58_address(value: str) -> bool:\n if 25 > len(value) > 35:\n return False\n\n try:\n abytes = base58check.b58decode(value)\n except (ValueE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |