_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6100 | interpolated_strings.types | train | def types(self):
"""
Tuple containing types transformed by this transformer.
"""
out = []
if self._transform_bytes:
out.append(bytes)
if self._transform_str:
out.append(str)
return tuple(out) | python | {
"resource": ""
} |
q6101 | interpolated_strings._transform_constant_sequence | train | def _transform_constant_sequence(self, seq):
"""
Transform a frozenset or tuple.
"""
should_transform = is_a(self.types)
if not any(filter(should_transform, flatten(seq))):
# Tuple doesn't contain any transformable strings. Ignore.
yield LOAD_CONST(seq)
... | python | {
"resource": ""
} |
q6102 | interpolated_strings.transform_stringlike | train | def transform_stringlike(self, const):
"""
Yield instructions to process a str or bytes constant.
"""
yield LOAD_CONST(const)
if isinstance(const, bytes):
yield from self.bytes_instrs
elif isinstance(const, str):
yield from self.str_instrs | python | {
"resource": ""
} |
q6103 | Instruction.steal | train | def steal(self, instr):
"""Steal the jump index off of `instr`.
This makes anything that would have jumped to `instr` jump to
this Instruction instead.
Parameters
----------
instr : Instruction
The instruction to steal the jump sources from.
Returns... | python | {
"resource": ""
} |
q6104 | Instruction.from_opcode | train | def from_opcode(cls, opcode, arg=_no_arg):
"""
Create an instruction from an opcode and raw argument.
Parameters
----------
opcode : int
Opcode for the instruction to create.
arg : int, optional
The argument for the instruction.
Returns
... | python | {
"resource": ""
} |
q6105 | Instruction.stack_effect | train | def stack_effect(self):
"""
The net effect of executing this instruction on the interpreter stack.
Instructions that pop values off the stack have negative stack effect
equal to the number of popped values.
Instructions that push values onto the stack have positive stack effect... | python | {
"resource": ""
} |
q6106 | Instruction.equiv | train | def equiv(self, instr):
"""Check equivalence of instructions. This checks against the types
and the arguments of the instructions
Parameters
----------
instr : Instruction
The instruction to check against.
Returns
-------
is_equiv : bool
... | python | {
"resource": ""
} |
q6107 | EnvSubprocess._get_python_cmd | train | def _get_python_cmd(self):
"""
return the python executable in the virtualenv.
Try first sys.executable but use fallbacks.
"""
file_names = ["pypy.exe", "python.exe", "python"]
executable = sys.executable
if executable is not None:
executable = os.path... | python | {
"resource": ""
} |
q6108 | convert | train | def convert(source_file, destination_file, cfg):
"""
convert in every way.
"""
source_ext = os.path.splitext(source_file)[1]
source_ext = source_ext.lower()
dest_ext = os.path.splitext(destination_file)[1]
dest_ext = dest_ext.lower()
if source_ext not in (".wav", ".cas", ".bas"):
... | python | {
"resource": ""
} |
q6109 | ScrolledText.save_position | train | def save_position(self):
"""
save cursor and scroll position
"""
# save text cursor position:
self.old_text_pos = self.index(tkinter.INSERT)
# save scroll position:
self.old_first, self.old_last = self.yview() | python | {
"resource": ""
} |
q6110 | ScrolledText.restore_position | train | def restore_position(self):
"""
restore cursor and scroll position
"""
# restore text cursor position:
self.mark_set(tkinter.INSERT, self.old_text_pos)
# restore scroll position:
self.yview_moveto(self.old_first) | python | {
"resource": ""
} |
q6111 | ROMFile.download | train | def download(self):
"""
Request url and return his content
The Requested content will be cached into the default temp directory.
"""
if os.path.isfile(self.archive_path):
print("Use %r" % self.archive_path)
with open(self.archive_path, "rb") as f:
... | python | {
"resource": ""
} |
q6112 | BaseTkinterGUI.paste_clipboard | train | def paste_clipboard(self, event):
"""
Send the clipboard content as user input to the CPU.
"""
log.critical("paste clipboard")
clipboard = self.root.clipboard_get()
for line in clipboard.splitlines():
log.critical("paste line: %s", repr(line))
self... | python | {
"resource": ""
} |
q6113 | DragonTkinterGUI.display_callback | train | def display_callback(self, cpu_cycles, op_address, address, value):
""" called via memory write_byte_middleware """
self.display.write_byte(cpu_cycles, op_address, address, value)
return value | python | {
"resource": ""
} |
q6114 | PIA.read_PIA0_A_data | train | def read_PIA0_A_data(self, cpu_cycles, op_address, address):
"""
read from 0xff00 -> PIA 0 A side Data reg.
bit 7 | PA7 | joystick comparison input
bit 6 | PA6 | keyboard matrix row 7
bit 5 | PA5 | keyboard matrix row 6
bit 4 | PA4 | keyboard matrix row 5
bit 3 |... | python | {
"resource": ""
} |
q6115 | PIA.write_PIA0_A_data | train | def write_PIA0_A_data(self, cpu_cycles, op_address, address, value):
""" write to 0xff00 -> PIA 0 A side Data reg. """
log.error("%04x| write $%02x (%s) to $%04x -> PIA 0 A side Data reg.\t|%s",
op_address, value, byte2bit_string(value), address,
self.cfg.mem_info.get_shortest(op... | python | {
"resource": ""
} |
q6116 | PIA.read_PIA0_A_control | train | def read_PIA0_A_control(self, cpu_cycles, op_address, address):
"""
read from 0xff01 -> PIA 0 A side control register
"""
value = 0xb3
log.error(
"%04x| read $%04x (PIA 0 A side Control reg.) send $%02x (%s) back.\t|%s",
op_address, address, value, byte2bi... | python | {
"resource": ""
} |
q6117 | PIA.write_PIA0_A_control | train | def write_PIA0_A_control(self, cpu_cycles, op_address, address, value):
"""
write to 0xff01 -> PIA 0 A side control register
TODO: Handle IRQ
bit 7 | IRQ 1 (HSYNC) flag
bit 6 | IRQ 2 flag(not used)
bit 5 | Control line 2 (CA2) is an output = 1
bit 4 | Control li... | python | {
"resource": ""
} |
q6118 | PIA.read_PIA0_B_data | train | def read_PIA0_B_data(self, cpu_cycles, op_address, address):
"""
read from 0xff02 -> PIA 0 B side Data reg.
bit 7 | PB7 | keyboard matrix column 8
bit 6 | PB6 | keyboard matrix column 7 / ram size output
bit 5 | PB5 | keyboard matrix column 6
bit 4 | PB4 | keyboard matri... | python | {
"resource": ""
} |
q6119 | PIA.read_PIA0_B_control | train | def read_PIA0_B_control(self, cpu_cycles, op_address, address):
"""
read from 0xff03 -> PIA 0 B side Control reg.
"""
value = self.pia_0_B_control.value
log.error(
"%04x| read $%04x (PIA 0 B side Control reg.) send $%02x (%s) back.\t|%s",
op_address, addre... | python | {
"resource": ""
} |
q6120 | PIA.write_PIA0_B_control | train | def write_PIA0_B_control(self, cpu_cycles, op_address, address, value):
"""
write to 0xff03 -> PIA 0 B side Control reg.
TODO: Handle IRQ
bit 7 | IRQ 1 (VSYNC) flag
bit 6 | IRQ 2 flag(not used)
bit 5 | Control line 2 (CB2) is an output = 1
bit 4 | Control line 2... | python | {
"resource": ""
} |
q6121 | Machine.inject_basic_program | train | def inject_basic_program(self, ascii_listing):
"""
save the given ASCII BASIC program listing into the emulator RAM.
"""
program_start = self.cpu.memory.read_word(
self.machine_api.PROGRAM_START_ADDR
)
tokens = self.machine_api.ascii_listing2program_dump(ascii... | python | {
"resource": ""
} |
q6122 | Wave2Bitstream.sync | train | def sync(self, length):
"""
synchronized weave sync trigger
"""
# go in wave stream to the first bit
try:
self.next()
except StopIteration:
print "Error: no bits identified!"
sys.exit(-1)
log.info("First bit is at: %s" % self.... | python | {
"resource": ""
} |
q6123 | Wave2Bitstream.iter_duration | train | def iter_duration(self, iter_trigger):
"""
yield the duration of two frames in a row.
"""
print
process_info = ProcessInfo(self.frame_count, use_last_rates=4)
start_time = time.time()
next_status = start_time + 0.25
old_pos = next(iter_trigger)
fo... | python | {
"resource": ""
} |
q6124 | Wave2Bitstream.iter_trigger | train | def iter_trigger(self, iter_wave_values):
"""
trigger middle crossing of the wave sinus curve
"""
window_size = (2 * self.cfg.END_COUNT) + self.cfg.MID_COUNT
# sinus curve goes from negative into positive:
pos_null_transit = [(0, self.cfg.END_COUNT), (self.cfg.END_COUNT,... | python | {
"resource": ""
} |
q6125 | Wave2Bitstream.iter_wave_values | train | def iter_wave_values(self):
"""
yield frame numer + volume value from the WAVE file
"""
typecode = self.get_typecode(self.samplewidth)
if log.level >= 5:
if self.cfg.AVG_COUNT > 1:
# merge samples -> log output in iter_avg_wave_values
... | python | {
"resource": ""
} |
q6126 | iter_steps | train | def iter_steps(g, steps):
"""
iterate over 'g' in blocks with a length of the given 'step' count.
>>> for v in iter_steps([1,2,3,4,5], steps=2): v
[1, 2]
[3, 4]
[5]
>>> for v in iter_steps([1,2,3,4,5,6,7,8,9], steps=3): v
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
... | python | {
"resource": ""
} |
q6127 | TkPeripheryBase._new_output_char | train | def _new_output_char(self, char):
""" insert in text field """
self.text.config(state=tkinter.NORMAL)
self.text.insert("end", char)
self.text.see("end")
self.text.config(state=tkinter.DISABLED) | python | {
"resource": ""
} |
q6128 | InputPollThread.check_cpu_interval | train | def check_cpu_interval(self, cpu_process):
"""
work-a-round for blocking input
"""
try:
# log.critical("check_cpu_interval()")
if not cpu_process.is_alive():
log.critical("raise SystemExit, because CPU is not alive.")
_thread.interru... | python | {
"resource": ""
} |
q6129 | BaseTkinterGUIConfig.command_max_delay | train | def command_max_delay(self, event=None):
""" CPU burst max running time - self.runtime_cfg.max_delay """
try:
max_delay = self.max_delay_var.get()
except ValueError:
max_delay = self.runtime_cfg.max_delay
if max_delay < 0:
max_delay = self.runtime_cfg... | python | {
"resource": ""
} |
q6130 | BaseTkinterGUIConfig.command_inner_burst_op_count | train | def command_inner_burst_op_count(self, event=None):
""" CPU burst max running time - self.runtime_cfg.inner_burst_op_count """
try:
inner_burst_op_count = self.inner_burst_op_count_var.get()
except ValueError:
inner_burst_op_count = self.runtime_cfg.inner_burst_op_count
... | python | {
"resource": ""
} |
q6131 | BaseTkinterGUIConfig.command_max_burst_count | train | def command_max_burst_count(self, event=None):
""" max CPU burst op count - self.runtime_cfg.max_burst_count """
try:
max_burst_count = self.max_burst_count_var.get()
except ValueError:
max_burst_count = self.runtime_cfg.max_burst_count
if max_burst_count < 1:
... | python | {
"resource": ""
} |
q6132 | BaseTkinterGUIConfig.command_max_run_time | train | def command_max_run_time(self, event=None):
""" CPU burst max running time - self.runtime_cfg.max_run_time """
try:
max_run_time = self.max_run_time_var.get()
except ValueError:
max_run_time = self.runtime_cfg.max_run_time
self.runtime_cfg.max_run_time = max_run_... | python | {
"resource": ""
} |
q6133 | prompt | train | def prompt(pagenum):
"""
Show default prompt to continue and process keypress.
It assumes terminal/console understands carriage return \r character.
"""
prompt = "Page -%s-. Press any key to continue . . . " % pagenum
echo(prompt)
if getch() in [ESC_, CTRL_C_, 'q', 'Q']:
return Fals... | python | {
"resource": ""
} |
q6134 | page | train | def page(content, pagecallback=prompt):
"""
Output `content`, call `pagecallback` after every page with page
number as a parameter. `pagecallback` may return False to terminate
pagination.
Default callback shows prompt, waits for keypress and aborts on
'q', ESC or Ctrl-C.
"""
width = ge... | python | {
"resource": ""
} |
q6135 | reformat_v09_trace | train | def reformat_v09_trace(raw_trace, max_lines=None):
"""
reformat v09 trace simmilar to XRoar one
and add CC and Memory-Information.
Note:
v09 traces contains the register info line one trace line later!
We reoder it as XRoar done: addr+Opcode with resulted registers
"""
print()
... | python | {
"resource": ""
} |
q6136 | human_duration | train | def human_duration(t):
"""
Converts a time duration into a friendly text representation.
>>> human_duration("type error")
Traceback (most recent call last):
...
TypeError: human_duration() argument must be integer or float
>>> human_duration(0.01)
u'10.0 ms'
>>> human_duration(0.9)... | python | {
"resource": ""
} |
q6137 | average | train | def average(old_avg, current_value, count):
"""
Calculate the average. Count must start with 0
>>> average(None, 3.23, 0)
3.23
>>> average(0, 1, 0)
1.0
>>> average(2.5, 5, 4)
3.0
"""
if old_avg is None:
return current_value
return (float(old_avg) * count + current_va... | python | {
"resource": ""
} |
q6138 | iter_window | train | def iter_window(g, window_size):
"""
interate over 'g' bit-by-bit and yield a window with the given 'window_size' width.
>>> for v in iter_window([1,2,3,4], window_size=2): v
[1, 2]
[2, 3]
[3, 4]
>>> for v in iter_window([1,2,3,4,5], window_size=3): v
[1, 2, 3]
[2, 3, 4]
[3, 4, ... | python | {
"resource": ""
} |
q6139 | get_word | train | def get_word(byte_iterator):
"""
return a uint16 value
>>> g=iter([0x1e, 0x12])
>>> v=get_word(g)
>>> v
7698
>>> hex(v)
'0x1e12'
"""
byte_values = list(itertools.islice(byte_iterator, 2))
try:
word = (byte_values[0] << 8) | byte_values[1]
except TypeError, err:
... | python | {
"resource": ""
} |
q6140 | _run | train | def _run(*args, **kwargs):
"""
Run current executable via subprocess and given args
"""
verbose = kwargs.pop("verbose", False)
if verbose:
click.secho(" ".join([repr(i) for i in args]), bg='blue', fg='white')
executable = args[0]
if not os.path.isfile(executable):
raise Runt... | python | {
"resource": ""
} |
q6141 | FileContent.add_block_data | train | def add_block_data(self, block_length, data):
"""
add a block of tokenized BASIC source code lines.
>>> cfg = Dragon32Config
>>> fc = FileContent(cfg)
>>> block = [
... 0x1e,0x12,0x0,0xa,0x80,0x20,0x49,0x20,0xcb,0x20,0x31,0x20,0xbc,0x20,0x31,0x30,0x0,
... 0x0,0x... | python | {
"resource": ""
} |
q6142 | FileContent.add_ascii_block | train | def add_ascii_block(self, block_length, data):
"""
add a block of ASCII BASIC source code lines.
>>> data = [
... 0xd,
... 0x31,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0x54,0x45,0x53,0x54,0x22,
... 0xd,
... 0x32,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0... | python | {
"resource": ""
} |
q6143 | validate | train | def validate(validation, dictionary):
"""
Validate that a dictionary passes a set of
key-based validators. If all of the keys
in the dictionary are within the parameters
specified by the validation mapping, then
the validation passes.
:param validation: a mapping of keys to validators
:... | python | {
"resource": ""
} |
q6144 | ArgSpec | train | def ArgSpec(*args, **kwargs):
"""
Validate a function based on the given argspec.
# Example:
validations = {
"foo": [ArgSpec("a", "b", c", bar="baz")]
}
def pass_func(a, b, c, bar="baz"):
pass
def fail_func(b, c, a, baz="bar"):
pass
... | python | {
"resource": ""
} |
q6145 | GitRepository.get_snapshots | train | def get_snapshots(self,**kwargs):
"""
Returns a list of snapshots in a given repository.
"""
commits = self.repository.get_commits(**kwargs)
snapshots = []
for commit in commits:
for key in ('committer_date','author_date'):
commit[key] = dateti... | python | {
"resource": ""
} |
q6146 | diff_objects | train | def diff_objects(objects_a,objects_b,key,comparator = None,with_unchanged = False):
"""
Returns a "diff" between two lists of objects.
:param key: The key that identifies objects with identical location in each set,
such as files with the same path or code objects with the same URL.
:pa... | python | {
"resource": ""
} |
q6147 | CodeEnvironment.save_file_revisions | train | def save_file_revisions(self,snapshot,file_revisions):
"""
We convert various items in the file revision to documents,
so that we can easily search and retrieve them...
"""
annotations = defaultdict(list)
for file_revision in file_revisions:
issues_results =... | python | {
"resource": ""
} |
q6148 | update | train | def update(d,ud):
"""
Recursively merge the values of ud into d.
"""
if ud is None:
return
for key,value in ud.items():
if not key in d:
d[key] = value
elif isinstance(value,dict):
update(d[key],value)
else:
d[key] = value | python | {
"resource": ""
} |
q6149 | Command.find_git_repository | train | def find_git_repository(self, path):
"""
Tries to find a directory with a .git repository
"""
while path is not None:
git_path = os.path.join(path,'.git')
if os.path.exists(git_path) and os.path.isdir(git_path):
return path
path = os.pa... | python | {
"resource": ""
} |
q6150 | get_hash | train | def get_hash(node,fields = None,exclude = ['pk','_id'],target = 'pk'):
"""
Here we generate a unique hash for a given node in the syntax tree.
"""
hasher = Hasher()
def add_to_hash(value):
if isinstance(value,dict):
if target in value:
add_to_hash(value[target]... | python | {
"resource": ""
} |
q6151 | Reporter.add_message | train | def add_message(self, msg_id, location, msg):
"""Client API to send a message"""
self._messages.append((msg_id,location,msg)) | python | {
"resource": ""
} |
q6152 | BaseAnalyzer.get_fingerprint_from_code | train | def get_fingerprint_from_code(self,file_revision,location, extra_data=None):
"""
This function generates a fingerprint from a series of code snippets.
Can be used by derived analyzers to generate fingerprints based on code
if nothing better is available.
"""
code = file_... | python | {
"resource": ""
} |
q6153 | Project.get_issue_classes | train | def get_issue_classes(self,backend = None,enabled = True,sort = None,**kwargs):
"""
Retrieves the issue classes for a given backend
:param backend: A backend to use. If None, the default backend will be used
:param enabled: Whether to retrieve enabled or disabled issue classes.
... | python | {
"resource": ""
} |
q6154 | replace_symbol | train | def replace_symbol(text, replacement_text="", is_replace_consecutive_chars=False, is_strip=False):
"""
Replace all of the symbols in the ``text``.
:param str text: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
:Examples:
:ref... | python | {
"resource": ""
} |
q6155 | validate_filename | train | def validate_filename(filename, platform=None, min_len=1, max_len=_DEFAULT_MAX_FILENAME_LEN):
"""Verifying whether the ``filename`` is a valid file name or not.
Args:
filename (str):
Filename to validate.
platform (str, optional):
.. include:: platform.txt
min_le... | python | {
"resource": ""
} |
q6156 | validate_filepath | train | def validate_filepath(file_path, platform=None, min_len=1, max_len=None):
"""Verifying whether the ``file_path`` is a valid file path or not.
Args:
file_path (str):
File path to validate.
platform (str, optional):
.. include:: platform.txt
min_len (int, optional)... | python | {
"resource": ""
} |
q6157 | sanitize_filename | train | def sanitize_filename(
filename, replacement_text="", platform=None, max_len=_DEFAULT_MAX_FILENAME_LEN
):
"""Make a valid filename from a string.
To make a valid filename the function does:
- Replace invalid characters as file names included in the ``filename``
with the ``replacement_tex... | python | {
"resource": ""
} |
q6158 | sanitize_filepath | train | def sanitize_filepath(file_path, replacement_text="", platform=None, max_len=None):
"""Make a valid file path from a string.
Replace invalid characters for a file path within the ``file_path``
with the ``replacement_text``.
Invalid characters are as followings:
|invalid_file_path_chars|, |invalid_w... | python | {
"resource": ""
} |
q6159 | sanitize_ltsv_label | train | def sanitize_ltsv_label(label, replacement_text=""):
"""
Replace all of the symbols in text.
:param str label: Input text.
:param str replacement_text: Replacement text.
:return: A replacement string.
:rtype: str
"""
validate_null_string(label, error_msg="label is empty")
return _... | python | {
"resource": ""
} |
q6160 | Url.domain | train | def domain(self):
"""
Return domain from the url
"""
remove_pac = self.cleanup.replace(
"https://", "").replace("http://", "").replace("www.", "")
try:
return remove_pac.split('/')[0]
except:
return None | python | {
"resource": ""
} |
q6161 | KitsuUser.search | train | def search(self, term):
"""
Search for a user by name.
:param str term: What to search for.
:return: The results as a SearchWrapper iterator or None if no results.
:rtype: SearchWrapper or None
"""
r = requests.get(self.apiurl + "/users", params={"filter[name]": ... | python | {
"resource": ""
} |
q6162 | KitsuUser.create | train | def create(self, data):
"""
Create a user. Please review the attributes required. You need only provide the attributes.
:param data: A dictionary of the required attributes
:return: Dictionary returned by server or a ServerError exception
:rtype: Dictionary or Exception
... | python | {
"resource": ""
} |
q6163 | KitsuUser.get | train | def get(self, uid):
"""
Get a user's information by their id.
:param uid str: User ID
:return: The user's information or None
:rtype: Dictionary or None
"""
r = requests.get(self.apiurl + "/users/{}".format(uid), headers=self.header)
if r.status_code != ... | python | {
"resource": ""
} |
q6164 | KitsuUser.update | train | def update(self, uid, data, token):
"""
Update a user's data. Requires an auth token.
:param uid str: User ID to update
:param data dict: The dictionary of data attributes to change. Just the attributes.
:param token str: The authorization token for this user
:return: Tr... | python | {
"resource": ""
} |
q6165 | VNDB.get | train | def get(self, stype, flags, filters, options=None):
"""
Send a request to the API to return results related to Visual Novels.
:param str stype: What are we searching for? One of: vn, release, producer, character, votelist, vnlist, wishlist
:param flags: See the D11 docs. A comma separat... | python | {
"resource": ""
} |
q6166 | VNDB.set | train | def set(self, stype, sid, fields):
"""
Send a request to the API to modify something in the database if logged in.
:param str stype: What are we modifying? One of: votelist, vnlist, wishlist
:param int sid: The ID that we're modifying.
:param dict fields: A dictionary of the fie... | python | {
"resource": ""
} |
q6167 | AGet.anime | train | def anime(self, item_id):
"""
The function to retrieve an anime's details.
:param int item_id: the anime's ID
:return: dict or None
:rtype: dict or NoneType
"""
query_string = """\
query ($id: Int) {
Media(id: $id, type: ANIME) {
... | python | {
"resource": ""
} |
q6168 | AGet.review | train | def review(self, item_id, html = True):
"""
With the change to v2 of the api, reviews have their own IDs. This accepts the ID of the review.
You can set html to False if you want the review body returned without html formatting.
The API Default is true.
:param item_id: the Id of... | python | {
"resource": ""
} |
q6169 | KitsuMappings.get | train | def get(self, external_site: str, external_id: int):
"""
Get a kitsu mapping by external site ID
:param str external_site: string representing the external site
:param int external_id: ID of the entry in the external site.
:return: Dictionary or None (for not found)
:rty... | python | {
"resource": ""
} |
q6170 | KitsuAuth.authenticate | train | def authenticate(self, username, password):
"""
Obtain an oauth token. Pass username and password. Get a token back. If KitsuAuth is set to remember your tokens
for this session, it will store the token under the username given.
:param username: username
:param password: passwor... | python | {
"resource": ""
} |
q6171 | KitsuAuth.refresh | train | def refresh(self, refresh_token):
"""
Renew an oauth token given an appropriate refresh token.
:param refresh_token: The Refresh Token
:return: A tuple of (token, expiration time in unix time stamp)
"""
r = requests.post(self.apiurl + "/token", params={"grant_type": "ref... | python | {
"resource": ""
} |
q6172 | KitsuAuth.get | train | def get(self, username):
"""
If using the remember option and KitsuAuth is storing your tokens, this function will retrieve one.
:param username: The username whose token we are retrieving
:return: A token, NotFound or NotSaving error
"""
if not self.remember:
... | python | {
"resource": ""
} |
q6173 | save | train | def save(url, destination):
"""
This is just the thread target.
It's actually responsible for downloading and saving.
:param str url: which dump to download
:param str destination: a file path to save to
"""
r = requests.get(url, stream=True)
with open(destination, 'wb') as fd:
... | python | {
"resource": ""
} |
q6174 | Dump.download | train | def download(which, destination=None):
"""
I realize that the download for the dumps is going to take awhile.
Given that, I've decided to approach this using threads.
When you call this method, it will launch a thread to download the data.
By default, the dump is dropped into the... | python | {
"resource": ""
} |
q6175 | KitsuManga.get | train | def get(self, aid):
"""
Get manga information by id.
:param int aid: ID of the manga.
:return: Dictionary or None (for not found)
:rtype: Dictionary or None
:raises: :class:`Pymoe.errors.ServerError`
"""
r = requests.get(self.apiurl + "/manga/{}".format(a... | python | {
"resource": ""
} |
q6176 | Bakatsuki.active | train | def active(self):
"""
Get a list of active projects.
:return list: A list of tuples containing a title and pageid in that order.
"""
projects = []
r = requests.get(self.api,
params={'action': 'query', 'list': 'categorymembers', 'cmpageid': self.a... | python | {
"resource": ""
} |
q6177 | Bakatsuki.light_novels | train | def light_novels(self, language="English"):
"""
Get a list of light novels under a certain language.
:param str language: Defaults to English. Replace with whatever language you want to query.
:return list: A list of tuples containing a title and pageid element in that order.
""... | python | {
"resource": ""
} |
q6178 | Bakatsuki.chapters | train | def chapters(self, title):
"""
Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage.
:param str title: The title of the novel you want chapters from
:return OrderedDic... | python | {
"resource": ""
} |
q6179 | Bakatsuki.cover | train | def cover(self, pageid):
"""
Get a cover image given a page id.
:param str pageid: The pageid for the light novel you want a cover image for
:return str: the image url
"""
r = requests.get(self.api,
params={'action': 'query', 'prop': 'pageimages'... | python | {
"resource": ""
} |
q6180 | Bakatsuki.get_text | train | def get_text(self, title):
"""
This will grab the html content of the chapter given by url. Technically you can use this to get the content of other pages too.
:param title: Title for the page you want the content of
:return: a string containing the html content
"""
r = ... | python | {
"resource": ""
} |
q6181 | Mal._verify_credentials | train | def _verify_credentials(self):
"""
An internal method that verifies the credentials given at instantiation.
:raises: :class:`Pymoe.errors.UserLoginFailed`
"""
r = requests.get(self.apiurl + "account/verify_credentials.xml",
auth=HTTPBasicAuth(self._usern... | python | {
"resource": ""
} |
q6182 | Mal._anime_add | train | def _anime_add(self, data):
"""
Adds an anime to a user's list.
:param data: A :class:`Pymoe.Mal.Objects.Anime` object with the anime data
:raises: SyntaxError on invalid data type
:raises: ServerError on failure to add
:rtype: Bool
:return: True on success
... | python | {
"resource": ""
} |
q6183 | Mal.user | train | def user(self, name):
"""
Get a user's anime list and details. This returns an encapsulated data type.
:param str name: The username to query
:rtype: :class:`Pymoe.Mal.Objects.User`
:return: A :class:`Pymoe.Mal.Objects.User` Object
"""
anime_data = requests.get(s... | python | {
"resource": ""
} |
q6184 | VNDBConnection.send_command | train | def send_command(self, command, args=None):
"""
Send a command to VNDB and then get the result.
:param command: What command are we sending
:param args: What are the json args for this command
:return: Servers Response
:rtype: Dictionary (See D11 docs on VNDB)
""... | python | {
"resource": ""
} |
q6185 | VNDBConnection._recv_data | train | def _recv_data(self):
"""
Receieves data until we reach the \x04 and then returns it.
:return: The data received
"""
temp = ""
while True:
self.data_buffer = self.sslwrap.recv(1024)
if '\x04' in self.data_buffer.decode('utf-8', 'ignore'):
... | python | {
"resource": ""
} |
q6186 | KitsuLib.get | train | def get(self, uid, filters=None):
"""
Get a user's list of library entries. While individual entries on this
list don't show what type of entry it is, you can use the filters provided
by the Kitsu API to only select which ones you want
:param uid: str: User ID to get library ent... | python | {
"resource": ""
} |
q6187 | KitsuLib.create | train | def create(self, user_id, media_id, item_type, token, data):
"""
Create a library entry for a user. data should be just the attributes.
Data at least needs a status and progress.
:param user_id str: User ID that this Library Entry is for
:param media_id str: ID for the media thi... | python | {
"resource": ""
} |
q6188 | KitsuLib.update | train | def update(self, eid, data, token):
"""
Update a given Library Entry.
:param eid str: Entry ID
:param data dict: Attributes
:param token str: OAuth token
:return: True or ServerError
:rtype: Bool or Exception
"""
final_dict = {"data": {"id": eid, ... | python | {
"resource": ""
} |
q6189 | KitsuLib.delete | train | def delete(self, eid, token):
"""
Delete a library entry.
:param eid str: Entry ID
:param token str: OAuth Token
:return: True or ServerError
:rtype: Bool or Exception
"""
final_headers = self.header
final_headers['Authorization'] = "Bearer {}".fo... | python | {
"resource": ""
} |
q6190 | convert_to_record | train | def convert_to_record(func):
"""Wrap mongodb record to a dict record with default value None
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if result is not None:
if isinstance(result, dict):
return _record(... | python | {
"resource": ""
} |
q6191 | MixinModel.to_one_str | train | def to_one_str(cls, value, *args, **kwargs):
"""Convert single record's values to str
"""
if kwargs.get('wrapper'):
return cls._wrapper_to_one_str(value)
return _es.to_dict_str(value) | python | {
"resource": ""
} |
q6192 | MixinModel.to_str | train | def to_str(cls, values, callback=None):
"""Convert many records's values to str
"""
if callback and callable(callback):
if isinstance(values, dict):
return callback(_es.to_str(values))
return [callback(_es.to_str(i)) for i in values]
return _es.to... | python | {
"resource": ""
} |
q6193 | MixinModel.import_model | train | def import_model(cls, ins_name):
"""Import model class in models package
"""
try:
package_space = getattr(cls, 'package_space')
except AttributeError:
raise ValueError('package_space not exist')
else:
return import_object(ins_name, package_spac... | python | {
"resource": ""
} |
q6194 | register_app | train | def register_app(app_name, app_setting, web_application_setting, mainfile, package_space):
"""insert current project root path into sys path
"""
from turbo import log
app_config.app_name = app_name
app_config.app_setting = app_setting
app_config.project_name = os.path.basename(get_base_dir(mainf... | python | {
"resource": ""
} |
q6195 | register_url | train | def register_url(url, handler, name=None, kwargs=None):
"""insert url into tornado application handlers group
:arg str url: url
:handler object handler: url mapping handler
:name reverse url name
:kwargs dict tornado handler initlize args
"""
if name is None and kwargs is None:
app_... | python | {
"resource": ""
} |
q6196 | BaseBaseHandler.parameter | train | def parameter(self):
'''
according to request method config to filter all request paremter
if value is invalid then set None
'''
method = self.request.method.lower()
arguments = self.request.arguments
files = self.request.files
rpd = {} # request paramet... | python | {
"resource": ""
} |
q6197 | BaseBaseHandler.wo_resp | train | def wo_resp(self, resp):
"""
can override for other style
"""
if self._data is not None:
resp['res'] = self.to_str(self._data)
return self.wo_json(resp) | python | {
"resource": ""
} |
q6198 | BaseBaseModel.find | train | def find(self, *args, **kwargs):
"""collection find method
"""
wrapper = kwargs.pop('wrapper', False)
if wrapper is True:
return self._wrapper_find(*args, **kwargs)
return self.__collect.find(*args, **kwargs) | python | {
"resource": ""
} |
q6199 | BaseBaseModel._wrapper_find_one | train | def _wrapper_find_one(self, filter_=None, *args, **kwargs):
"""Convert record to a dict that has no key error
"""
return self.__collect.find_one(filter_, *args, **kwargs) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.