code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Make sure the key we're trying conforms to the pattern of a # SHA1 hash; if it doesn't, no point trying to look it up in # the database. if SHA1_RE.search(activation_key): try: profile = RegistrationProfile.objects.get( activation_key=activation_key) ex...
def activate_user(activation_key)
Validate an activation key and activate the corresponding ``User`` if valid. If the key is valid and has not expired, return the ``User`` after activating. If the key is not valid or has expired, return ``False``. If the key is valid but the ``User`` is already active, return ``False``. To p...
3.177737
2.769872
1.14725
ctx_dict = {'activation_key': user.api_registration_profile.activation_key, 'expiration_days': get_settings('REGISTRATION_API_ACCOUNT_ACTIVATION_DAYS'), 'site': site} subject = render_to_string('registration_api/activation_email_subject.txt', c...
def send_activation_email(user, site)
Send an activation email to the ``user``. The activation email will make use of two templates: ``registration/activation_email_subject.txt`` This template will be used for the subject line of the email. Because it is used as the subject line of an email, this template's output **must** be only a si...
2.402374
2.635028
0.911707
return [self.read_byte(addr) for addr in range(start, end)]
def get(self, start, end)
used in unittests
5.427016
5.248432
1.034026
ea = self.pull_word(self.system_stack_pointer) # log.info("%x|\tRTS to $%x \t| %s" % ( # self.last_op_address, # ea, # self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_RTS(self, opcode)
Program control is returned from the subroutine to the calling program. The return address is pulled from the stack. source code forms: RTS CC bits "HNZVC": -----
8.193453
8.509157
0.962898
# log.info("%x|\tJSR/BSR to $%x \t| %s" % ( # self.last_op_address, # ea, self.cfg.mem_info.get_shortest(ea) # )) self.push_word(self.system_stack_pointer, self.program_counter.value) self.program_counter.set(ea)
def instruction_BSR_JSR(self, opcode, ea)
Program control is transferred to the effective address after storing the return address on the hardware stack. A return from subroutine (RTS) instruction is used to reverse this process and must be the last instruction executed in a subroutine. source code forms: BSR dd; LBSR DDDD; JS...
8.019136
9.06261
0.88486
if self.Z == 1: # log.info("$%x BEQ branch to $%x, because Z==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BEQ(self, opcode, ea)
Tests the state of the Z (zero) bit and causes a branch if it is set. When used after a subtract or compare operation, this instruction will branch if the compared values, signed or unsigned, were exactly the same. source code forms: BEQ dd; LBEQ DDDD CC bits "HNZVC": -----
8.691663
8.977641
0.968145
# Note these variantes are the same: # self.N == self.V # (self.N ^ self.V) == 0 # not operator.xor(self.N, self.V) if self.N == self.V: # log.info("$%x BGE branch to $%x, because N XOR V == 0 \t| %s" % ( # self.program_counter, ea, sel...
def instruction_BGE(self, opcode, ea)
Causes a branch if the N (negative) bit and the V (overflow) bit are either both set or both clear. That is, branch if the sign of a valid twos complement result is, or would be, positive. When used after a subtract or compare operation on twos complement values, this instruction will br...
7.237864
7.203111
1.004825
# Note these variantes are the same: # not ((self.N ^ self.V) == 1 or self.Z == 1) # not ((self.N ^ self.V) | self.Z) # self.N == self.V and self.Z == 0 # ;) if not self.Z and self.N == self.V: # log.info("$%x BGT branch to $%x, because (N==V ...
def instruction_BGT(self, opcode, ea)
Causes a branch if the N (negative) bit and V (overflow) bit are either both set or both clear and the Z (zero) bit is clear. In other words, branch if the sign of a valid twos complement result is, or would be, positive and not zero. When used after a subtract or compare operation on tw...
7.257862
7.148468
1.015303
if self.C == 0 and self.Z == 0: # log.info("$%x BHI branch to $%x, because C==0 and Z==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BHI(self, opcode, ea)
Causes a branch if the previous operation caused neither a carry nor a zero result. When used after a subtract or compare operation on unsigned binary values, this instruction will branch if the register was higher than the memory register. Generally not useful after INC/DEC, LD/TST, an...
7.334053
7.485126
0.979817
# if (self.C|self.Z) == 0: if self.C == 1 or self.Z == 1: # log.info("$%x BLS branch to $%x, because C|Z==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BLS(self, opcode, ea)
Causes a branch if the previous operation caused either a carry or a zero result. When used after a subtract or compare operation on unsigned binary values, this instruction will branch if the register was lower than or the same as the memory register. Generally not useful after INC/DEC...
7.399772
7.277866
1.01675
if (self.N ^ self.V) == 1: # N xor V # log.info("$%x BLT branch to $%x, because N XOR V == 1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BLT(self, opcode, ea)
Causes a branch if either, but not both, of the N (negative) or V (overflow) bits is set. That is, branch if the sign of a valid twos complement result is, or would be, negative. When used after a subtract or compare operation on twos complement binary values, this instruction will branc...
8.785958
8.247637
1.06527
if self.N == 1: # log.info("$%x BMI branch to $%x, because N==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BMI(self, opcode, ea)
Tests the state of the N (negative) bit and causes a branch if set. That is, branch if the sign of the twos complement result is negative. When used after an operation on signed binary values, this instruction will branch if the result is minus. It is generally preferred to use the LBLT...
8.860637
9.445685
0.938062
if self.Z == 0: # log.info("$%x BNE branch to $%x, because Z==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BNE(self, opcode, ea)
Tests the state of the Z (zero) bit and causes a branch if it is clear. When used after a subtract or compare operation on any binary values, this instruction will branch if the register is, or would be, not equal to the memory register. source code forms: BNE dd; LBNE DDDD CC ...
8.71214
9.147942
0.952361
if self.N == 0: # log.info("$%x BPL branch to $%x, because N==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BPL(self, opcode, ea)
Tests the state of the N (negative) bit and causes a branch if it is clear. That is, branch if the sign of the twos complement result is positive. When used after an operation on signed binary values, this instruction will branch if the result (possibly invalid) is positive. It is ...
8.932766
9.302319
0.960273
if self.V == 0: # log.info("$%x BVC branch to $%x, because V==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BVC(self, opcode, ea)
Tests the state of the V (overflow) bit and causes a branch if it is clear. That is, branch if the twos complement result was valid. When used after an operation on twos complement binary values, this instruction will branch if there was no overflow. source code forms: BVC dd; LBVC DDDD...
8.819934
9.502909
0.92813
if self.V == 1: # log.info("$%x BVS branch to $%x, because V==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BVS(self, opcode, ea)
Tests the state of the V (overflow) bit and causes a branch if it is set. That is, branch if the twos complement result was invalid. When used after an operation on twos complement binary values, this instruction will branch if there was an overflow. source code forms: BVS dd; LBVS DDDD...
9.108027
9.668664
0.942015
if self.C == 1: # log.info("$%x BLO/BCS/LBLO/LBCS branch to $%x, because C==1 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BLO(self, opcode, ea)
CC bits "HNZVC": ----- case 0x5: cond = REG_CC & CC_C; break; // BCS, BLO, LBCS, LBLO
10.370813
8.799301
1.178595
if self.C == 0: # log.info("$%x BHS/BCC/LBHS/LBCC branch to $%x, because C==0 \t| %s" % ( # self.program_counter, ea, self.cfg.mem_info.get_shortest(ea) # )) self.program_counter.set(ea)
def instruction_BHS(self, opcode, ea)
CC bits "HNZVC": ----- case 0x4: cond = !(REG_CC & CC_C); break; // BCC, BHS, LBCC, LBHS
10.189157
9.042499
1.126808
return "{0}d {1}s {2}us".format( obj.days, obj.seconds, obj.microseconds)
def to_json(cls, obj)
Serialize wrapped datetime.timedelta instance to a string the with the following format: [DAYS]d [SECONDS]s [MICROSECONDS]us
7.600077
3.120557
2.435488
if not isinstance(doc, basestring): raise TypeError("JSON document must be a string") match = cls.PATTERN.match(doc) if not match: raise ValueError("JSON document must match expected pattern") days, seconds, microseconds = map(int, match.groups()) ...
def from_json(cls, doc)
Deserialize JSON document (string) to datetime.timedelta instance
3.144593
2.447353
1.284895
# log.debug("$%x LD16 set %s to $%x \t| %s" % ( # self.program_counter, # register.name, m, # self.cfg.mem_info.get_shortest(m) # )) register.set(m) self.clear_NZV() self.update_NZ_16(m)
def instruction_LD16(self, opcode, m, register)
Load the contents of the memory location M:M+1 into the designated 16-bit register. source code forms: LDD P; LDX P; LDY P; LDS P; LDU P CC bits "HNZVC": -aa0-
6.601834
7.318995
0.902014
# log.debug("$%x LD8 %s = $%x" % ( # self.program_counter, # register.name, m, # )) register.set(m) self.clear_NZV() self.update_NZ_8(m)
def instruction_LD8(self, opcode, m, register)
Loads the contents of memory location M into the designated register. source code forms: LDA P; LDB P CC bits "HNZVC": -aa0-
5.778489
6.446897
0.896321
value = register.value # log.debug("$%x ST16 store value $%x from %s at $%x \t| %s" % ( # self.program_counter, # value, register.name, ea, # self.cfg.mem_info.get_shortest(ea) # )) self.clear_NZV() self.update_NZ_16(value) retu...
def instruction_ST16(self, opcode, ea, register)
Writes the contents of a 16-bit register into two consecutive memory locations. source code forms: STD P; STX P; STY P; STS P; STU P CC bits "HNZVC": -aa0-
7.759564
8.079533
0.960398
value = register.value # log.debug("$%x ST8 store value $%x from %s at $%x \t| %s" % ( # self.program_counter, # value, register.name, ea, # self.cfg.mem_info.get_shortest(ea) # )) self.clear_NZV() self.update_NZ_8(value) return...
def instruction_ST8(self, opcode, ea, register)
Writes the contents of an 8-bit register into a memory location. source code forms: STA P; STB P CC bits "HNZVC": -aa0-
8.08404
8.712886
0.927826
ret = super(UserSerializer, self).to_native(obj) del ret['password'] return ret
def to_native(self, obj)
Remove password field when serializing an object
4.357317
2.72789
1.597321
env = request.environ # Send HTTP response 101 Switch Protocol downstream uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', '')) # Map the websocket URL to the upstream localhost:4000x Notebook instance parts = urlparse(request.url) parts = parts._replace(sch...
def serve_websocket(request, port)
Start UWSGI websocket loop and proxy.
6.648756
6.504561
1.022168
headers = [ ('Host', self.host), ('Connection', 'Upgrade'), ('Upgrade', 'WebSocket'), ('Sec-WebSocket-Key', self.key.decode('utf-8')), # Origin is proxyed from the downstream server, don't set it twice # ('Origin', self.url), ...
def handshake_headers(self)
List of headers appropriate for the upgrade handshake.
3.122223
3.141712
0.993797
# TODO: No support for binary messages m = str(m) logger.debug("Incoming upstream WS: %s", m) uwsgi.websocket_send(m) logger.debug("Send ok")
def received_message(self, m)
Push upstream messages to downstream.
13.33089
11.517644
1.157432
self.sock.setblocking(False) try: while not self.terminated: logger.debug("Doing nothing") time.sleep(0.050) logger.debug("Asking for downstream msg") msg = uwsgi.websocket_recv_nb() if msg: ...
def run(self)
Combine async uwsgi message loop with ws4py message loop. TODO: This could do some serious optimizations and behave asynchronously correct instead of just sleep().
4.694724
4.345516
1.080361
cache_path = self._url_to_path(url) try: with open(cache_path, 'rb') as f: return f.read() except IOError: return None
def get_content(self, url)
Returns the content of a cached resource. Args: url: The url of the resource Returns: The content of the cached resource or None if not in the cache
2.864431
3.251652
0.880916
cache_path = self._url_to_path(url) if os.path.exists(cache_path): return cache_path return None
def get_path(self, url)
Returns the path of a cached resource. Args: url: The url of the resource Returns: The path to the cached resource or None if not in the cache
3.498778
4.050041
0.863887
cache_path = self._url_to_path(url) # Ensure that cache directories exist try: dir = os.path.dirname(cache_path) os.makedirs(dir) except OSError as e: if e.errno != errno.EEXIST: raise Error('Failed to create cache directories...
def put_content(self, url, content)
Stores the content of a resource into the disk cache. Args: url: The url of the resource content: The content of the resource Raises: CacheError: If the content cannot be put in cache
2.555339
2.794953
0.914269
cache_path = self._url_to_path(url) # Ensure that cache directories exist try: dir = os.path.dirname(cache_path) os.makedirs(dir) except OSError as e: if e.errno != errno.EEXIST: raise Error('Failed to create cache directories...
def put_path(self, url, path)
Puts a resource already on disk into the disk cache. Args: url: The original url of the resource path: The resource already available on disk Raises: CacheError: If the file cannot be put in cache
3.325947
3.45274
0.963278
total_size = 0 for dir_path, dir_names, filenames in os.walk(self.dir): for f in filenames: fp = os.path.join(dir_path, f) total_size += os.path.getsize(fp) return total_size
def size(self)
Returns the size of the cache in bytes.
2.094531
1.875801
1.116606
def decorator(func): setattr(func, "_is_opcode", True) setattr(func, "_opcodes", opcodes) return func return decorator
def opcode(*opcodes)
A decorator for opcodes
3.096541
2.882253
1.074347
if os.path.exists(fname): return from nbformat import v4 as nbf # Courtesy of http://nbviewer.ipython.org/gist/fperez/9716279 text = "Welcome to *pyramid_notebook!* Use *File* *>* *Shutdown* to close this." cells = [nbf.new_markdown_cell(text)] greeting = context.get("greeting")...
def create_named_notebook(fname, context)
Create a named notebook if one doesn't exist.
4.241356
4.139328
1.024648
if self.pidfile is None: raise DaemonError('Cannot stop daemon without PID file') pid = self._read_pidfile() if pid is None: # I don't think this should be a fatal error self._emit_warning('{prog} is not running'.format(prog=self.prog)) r...
def stop(self)
Stop the daemon. IPython Notebook tends to hang on exit 1) on certain Linux servers 2) sometimes. I am not sure why, but here is the traceback back when gdb was attached to the process:: #0 0x00007fa7632c912d in poll () at ../sysdeps/unix/syscall-template.S:81 #1 0x00007fa75e...
3.581849
3.546295
1.010026
self.cycles += 1 self.push_word(self.system_stack_pointer, self.program_counter.value) # PC self.push_word(self.system_stack_pointer, self.user_stack_pointer.value) # U self.push_word(self.system_stack_pointer, self.index_y.value) # Y self.push_word(self.system_stack_poi...
def push_irq_registers(self)
push PC, U, Y, X, DP, B, A, CC on System stack pointer
2.278883
1.855838
1.227954
self.cycles += 1 self.push_word(self.system_stack_pointer, self.program_counter.value) # PC self.push_byte(self.system_stack_pointer, self.get_cc_value())
def push_firq_registers(self)
FIRQ - Fast Interrupt Request push PC and CC on System stack pointer
6.500344
4.092025
1.58854
cc = self.pull_byte(self.system_stack_pointer) # CC self.set_cc(cc) if self.E: self.accu_a.set( self.pull_byte(self.system_stack_pointer) # A ) self.accu_b.set( self.pull_byte(self.system_stack_pointer) # B ...
def instruction_RTI(self, opcode)
The saved machine state is recovered from the hardware stack and control is returned to the interrupted program. If the recovered E (entire) bit is clear, it indicates that only a subset of the machine state was saved (return address and condition codes) and only that subset is recovered. ...
2.395658
2.346839
1.020802
''' Returns features of char at position `i` in given sentence When it possible, result features list also includes features for 2 characters ahead and behind current position (like bigrams, or something like it) Currently, used features is: 1. lower-cased value of character 2. result of cal...
def char2features(sentence, i)
Returns features of char at position `i` in given sentence When it possible, result features list also includes features for 2 characters ahead and behind current position (like bigrams, or something like it) Currently, used features is: 1. lower-cased value of character 2. result of calling `charac...
2.063097
1.287564
1.602326
''' Marks all characters in given `text`, that doesn't exists within any element of `sents` with `1` character, other characters (within sentences) will be marked with `0` Used in training process >>> text = 'привет. меня зовут аня.' >>> sents = ['привет.', 'меня зовут аня.'] >>> labels ...
def text2labels(text, sents)
Marks all characters in given `text`, that doesn't exists within any element of `sents` with `1` character, other characters (within sentences) will be marked with `0` Used in training process >>> text = 'привет. меня зовут аня.' >>> sents = ['привет.', 'меня зовут аня.'] >>> labels = text2label...
4.114065
1.380065
2.981066
''' Splits given text at predicted positions from `labels` ''' sentence = '' for i, label in enumerate(labels): if label == '1': if sentence: yield sentence sentence = '' else: sentence += text[i] if sentence: yield sent...
def text2sentences(text, labels)
Splits given text at predicted positions from `labels`
4.569222
2.795322
1.634596
''' >>> corpus = CorpusReader('annot.opcorpora.xml') >>> X_train, x_test, y_train, y_test = get_train_data(corpus, test_size=0.33, random_state=42) >>> crf = train(X_train, X_test, y_train, y_test) ''' crf = Trainer() crf.set_params({ 'c1': 1.0, 'c2': 0.001, 'max_iter...
def train(X_train, X_test, y_train, y_test, **kwargs)
>>> corpus = CorpusReader('annot.opcorpora.xml') >>> X_train, x_test, y_train, y_test = get_train_data(corpus, test_size=0.33, random_state=42) >>> crf = train(X_train, X_test, y_train, y_test)
3.221574
1.919919
1.677974
# From WSGI spec, PEP 333 url = environ.get('PATH_INFO', '') if not url.startswith(('http://', 'https://')): url = '%s://%s%s' % ( environ['wsgi.url_scheme'], environ['HTTP_HOST'], url ) # Fix ;arg=value in url if '%3B' in url: url, ar...
def reconstruct_url(environ, port)
Reconstruct the remote url from the given WSGI ``environ`` dictionary. :param environ: the WSGI environment :type environ: :class:`collections.MutableMapping` :returns: the remote url to proxy :rtype: :class:`basestring`
2.947424
3.058054
0.963823
logger = logging.getLogger(__name__ + '.WSGIProxyApplication.handler') url = urlparse(reconstruct_url(environ, self.port)) # Create connection object try: connection = self.connection_class(url.netloc) # Build path path = url.geturl().replace...
def handler(self, environ, start_response)
Proxy for requests to the actual http server
3.582294
3.56339
1.005305
''' >>> corpus = CorpusReader('annot.opcorpora.xml') >>> X_train, x_test, y_train, y_test = get_train_data(corpus, test_size=0.33, random_state=42) >>> crf = train(X_train, y_train) ''' crf = Trainer() crf.set_params({ 'c1': 1.0, 'c2': 0.001, 'max_iterations': 200, ...
def train(X_train, y_train, **kwargs)
>>> corpus = CorpusReader('annot.opcorpora.xml') >>> X_train, x_test, y_train, y_test = get_train_data(corpus, test_size=0.33, random_state=42) >>> crf = train(X_train, y_train)
3.451978
2.074049
1.664367
try: index = 0 while True: rb = _RightBarPage(client, index) summaries = rb.summaries() if filter is not None: summaries = filter.filter(summaries) for summary in summaries: yield summary index +=...
def get_summaries(client, filter=None)
Generate presentation summaries in a reverse chronological order. A filter class can be supplied to filter summaries or bound the fetching process.
4.524197
4.583397
0.987084
url = client.get_url("/presentations/" + self.id) content = self.client.fetch_no_cache(url).decode('utf-8') return bs4.BeautifulSoup(content, "html.parser")
def _fetch(self)
Download the page and create the soup
5.894072
4.882072
1.207289
try: return self._soup except AttributeError: url = client.get_url("/presentations/%s" % self.index) content = self.client.fetch_no_cache(url).decode('utf-8') self._soup = bs4.BeautifulSoup(content, "html.parser") return self._soup
def soup(self)
Download the page and create the soup
4.186889
4.320268
0.969127
def create_summary(div): def get_id(div): return get_url(div).rsplit('/')[-1] def get_url(div): return client.get_url(div.find('h2', class_='itemtitle').a['href']) def get_desc(div): return div.p.get_text(strip=True) ...
def summaries(self)
Return a list of all the presentation summaries contained in this page
2.550416
2.475072
1.030441
if format_string: context_list = format_string.split(' ') context = { 'app_label':context_list[0],'model':context_list[1], 'counts':context_list[2] } else: context = {} return render_to_string('tagging_ext/tagging_autocomplete_js.html', context)
def tag_autocomplete_js(format_string=None)
format_string should be ``app_label model counts`` renders 'tagging_ext/tag_autocomplete_js.html
3.665124
2.727772
1.343633
# Set up some default imports and variables nc = notebook_context add_greeting(nc, "\nAvailable variables and functions:") # http://docs.pylonsproject.org/projects/pyramid/en/1.1-branch/narr/commandline.html#writing-a-script if config_file is not None: assert type(config_file) == s...
def make_startup(notebook_context, config_file, bootstrap_py=PYRAMID_BOOSTRAP, bootstrap_greeting=PYRAMID_GREETING, cwd="")
Populate notebook context with startup.py initialization file skeleton and greeting. This will set up context ``startup`` and ``greeting`` for their default values. :param notebook_context: Dictionary of notebook context info to be to passed to NotebookManager :param config_file: The current .ini file us...
3.515919
3.473487
1.012216
from sqlalchemy.ext.declarative.clsregistry import _ModuleMarker # Include all SQLAlchemy models in the local namespace for name, klass in Base._decl_class_registry.items(): print(name, klass) if isinstance(klass, _ModuleMarker): continue add_script(nc, get_import...
def include_sqlalchemy_models(nc, Base)
Include all SQLAlchemy models in the script context. :param nc: notebook_context dictionary :param Base: SQLAlchemy model Base class from where the all models inherit.
5.078539
5.811899
0.873818
assert type(nc) == dict nc["startup"] = nc.get("startup") or "" if not nc["startup"].endswith("\n"): nc["startup"] += "\n" nc["startup"] += line + "\n"
def add_script(nc, line)
Add one-liner script or several lines (newline separated)
4.092196
3.925516
1.04246
assert type(nc) == dict nc["greeting"] = nc.get("greeting") or "" # Markdown hard line break is two new lines if not nc["greeting"].endswith("\n"): nc["greeting"] += "\n" nc["greeting"] += line + "\n"
def add_greeting(nc, line)
Add one-liner script or several lines (newline separated)
5.813221
5.78901
1.004182
try: new_value = float(value) / float(trigger) * target except ZeroDivisionError: return value * 2 if new_value > max_value: return max_value new_value = int((value + new_value) / 2) if new_value < min_value: return min_value return new_value
def calc_new_count(min_value, value, max_value, trigger, target)
change 'value' between 'min_value' and 'max_value' so that 'trigger' will be match 'target' >>> calc_new_count(min_value=0, value=100, max_value=200, trigger=30, target=30) 100 >>> calc_new_count(min_value=0, value=100, max_value=200, trigger=50, target=5) 55 >>> calc_new_count(min_value=6...
2.792997
3.234882
0.8634
a = register.value r = a | m register.set(r) self.clear_NZV() self.update_NZ_8(r)
def instruction_OR(self, opcode, m, register)
Performs an inclusive OR operation between the contents of accumulator A or B and the contents of memory location M and the result is stored in accumulator A or B. source code forms: ORA P; ORB P CC bits "HNZVC": -aa0-
7.033361
10.022098
0.701785
assert register == self.cc_register old_cc = self.get_cc_value() new_cc = old_cc & m self.set_cc(new_cc)
def instruction_ANDCC(self, opcode, m, register)
Performs a logical AND between the condition code register and the immediate byte specified in the instruction and places the result in the condition code register. source code forms: ANDCC #xx CC bits "HNZVC": ddddd
4.067734
4.75556
0.855364
r = a << 1 self.clear_NZVC() self.update_NZVC_8(a, a, r) return r
def LSL(self, a)
Shifts all bits of accumulator A or B or memory location M one place to the left. Bit zero is loaded with a zero. Bit seven of accumulator A or B or memory location M is shifted into the C (carry) bit. This is a duplicate assembly-language mnemonic for the single machine instruction ASL...
10.83371
8.729381
1.241063
r = self.LSL(m) # log.debug("$%x LSL memory value $%x << 1 = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff
def instruction_LSL_memory(self, opcode, ea, m)
Logical shift left memory location / Arithmetic shift of memory left
7.985722
7.806626
1.022941
a = register.value r = self.LSL(a) # log.debug("$%x LSL %s value $%x << 1 = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r)
def instruction_LSL_register(self, opcode, register)
Logical shift left accumulator / Arithmetic shift of accumulator
5.638804
5.742264
0.981983
r = a >> 1 self.clear_NZC() self.C = get_bit(a, bit=0) # same as: self.C |= (a & 1) self.set_Z8(r) return r
def LSR(self, a)
Performs a logical shift right on the register. Shifts a zero into bit seven and bit zero into the C (carry) bit. source code forms: LSR Q; LSRA; LSRB CC bits "HNZVC": -0a-s
7.825567
7.054303
1.109332
r = self.LSR(m) # log.debug("$%x LSR memory value $%x >> 1 = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff
def instruction_LSR_memory(self, opcode, ea, m)
Logical shift right memory location
7.661602
7.601168
1.007951
a = register.value r = self.LSR(a) # log.debug("$%x LSR %s value $%x >> 1 = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r)
def instruction_LSR_register(self, opcode, register)
Logical shift right accumulator
5.535385
5.594061
0.989511
r = (a >> 1) | (a & 0x80) self.clear_NZC() self.C = get_bit(a, bit=0) # same as: self.C |= (a & 1) self.update_NZ_8(r) return r
def ASR(self, a)
ASR (Arithmetic Shift Right) alias LSR (Logical Shift Right) Shifts all bits of the register one place to the right. Bit seven is held constant. Bit zero is shifted into the C (carry) bit. source code forms: ASR Q; ASRA; ASRB CC bits "HNZVC": uaa-s
7.016611
6.274315
1.118307
r = self.ASR(m) # log.debug("$%x ASR memory value $%x >> 1 | Carry = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff
def instruction_ASR_memory(self, opcode, ea, m)
Arithmetic shift memory right
8.713272
8.559875
1.01792
a = register.value r = self.ASR(a) # log.debug("$%x ASR %s value $%x >> 1 | Carry = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r)
def instruction_ASR_register(self, opcode, register)
Arithmetic shift accumulator right
6.256218
6.231259
1.004005
r = (a << 1) | self.C self.clear_NZVC() self.update_NZVC_8(a, a, r) return r
def ROL(self, a)
Rotates all bits of the register one place left through the C (carry) bit. This is a 9-bit rotation. source code forms: ROL Q; ROLA; ROLB CC bits "HNZVC": -aaas
7.817669
6.729335
1.16173
r = self.ROL(m) # log.debug("$%x ROL memory value $%x << 1 | Carry = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff
def instruction_ROL_memory(self, opcode, ea, m)
Rotate memory left
8.648934
8.424745
1.026611
a = register.value r = self.ROL(a) # log.debug("$%x ROL %s value $%x << 1 | Carry = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r)
def instruction_ROL_register(self, opcode, register)
Rotate accumulator left
5.955623
5.975509
0.996672
r = (a >> 1) | (self.C << 7) self.clear_NZ() self.update_NZ_8(r) self.C = get_bit(a, bit=0) # same as: self.C = (a & 1) return r
def ROR(self, a)
Rotates all bits of the register one place right through the C (carry) bit. This is a 9-bit rotation. moved the carry flag into bit 8 moved bit 7 into carry flag source code forms: ROR Q; RORA; RORB CC bits "HNZVC": -aa-s
5.951025
5.588789
1.064815
r = self.ROR(m) # log.debug("$%x ROR memory value $%x >> 1 | Carry = $%x and write it to $%x \t| %s" % ( # self.program_counter, # m, r, ea, # self.cfg.mem_info.get_shortest(ea) # )) return ea, r & 0xff
def instruction_ROR_memory(self, opcode, ea, m)
Rotate memory right
8.60177
8.507028
1.011137
a = register.value r = self.ROR(a) # log.debug("$%x ROR %s value $%x >> 1 | Carry = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r)
def instruction_ROR_register(self, opcode, register)
Rotate accumulator right
5.983482
5.940146
1.007295
src_value = src_reg.value if src_reg.WIDTH == 8 and dst_reg.WIDTH == 16: # e.g.: $cd -> $ffcd src_value += 0xff00 elif src_reg.WIDTH == 16 and dst_reg.WIDTH == 8: # This not not really needed, because all 8Bit register will # limit the value, too. # e.g.: $1234 -...
def convert_differend_width(src_reg, dst_reg)
e.g.: 8bit $cd TFR into 16bit, results in: $ffcd 16bit $1234 TFR into 8bit, results in: $34 >>> reg8 = ValueStorage8Bit(name="bar", initial_value=0xcd) >>> reg16 = ValueStorage16Bit(name="foo", initial_value=0x0000) >>> hex(convert_differend_width(src_reg=reg8, dst_reg=reg16)) '0xffcd' ...
5.114081
3.98516
1.283281
python = sys.executable #: XXX fix this hack, uwsgi sets itself as Python #: Make better used Python interpreter autodiscovery if python.endswith("/uwsgi"): python = python.replace("/uwsgi", "/python") return python
def discover_python(self)
Get the Python interpreter we need to use to run our Notebook daemon.
19.732616
18.261063
1.080584
pid_file = os.path.join(self.get_work_folder(name), "notebook.pid") return pid_file
def get_pid(self, name)
Get PID file name for a named notebook.
6.279625
3.732901
1.682237
cmd = os.path.abspath(os.path.join(os.path.dirname(__file__), "server", "notebook_daemon.py")) assert os.path.exists(cmd) return cmd
def get_manager_cmd(self)
Get our daemon script path.
4.46593
3.664341
1.218754
ports = set(range(self.min_port, self.min_port + self.port_range)) return port_for.select_random(ports)
def pick_port(self)
Pick open TCP/IP port.
6.038585
5.303017
1.138708
return [self.python, self.cmd, action, self.get_pid(name), self.get_work_folder(name), port, self.kill_timeout] + list(extra)
def get_notebook_daemon_command(self, name, action, port=0, *extra)
Assume we launch Notebook with the same Python which executed us.
7.495608
7.063342
1.061199
cmd = self.get_notebook_daemon_command(name, cmd, port) # Make all arguments explicit strings cmd = [str(arg) for arg in cmd] logger.info("Running notebook command: %s", " ".join(cmd)) # print("XXX - DEBUG - Running notebook command:", " ".join(cmd)) # Add sup...
def exec_notebook_daemon_command(self, name, cmd, port=0)
Run a daemon script command.
3.644469
3.677304
0.991071
context = comm.get_context(self.get_pid(name)) if not context: return None return context
def get_notebook_status(self, name)
Get the running named Notebook status. :return: None if no notebook is running, otherwise context dictionary
8.956309
9.556376
0.937208
assert context assert type(context) == dict assert "context_hash" in context assert type(context["context_hash"]) == int http_port = self.pick_port() assert http_port context = context.copy() context["http_port"] = http_port # We can't p...
def start_notebook(self, name, context: dict, fg=False)
Start new IPython Notebook daemon. :param name: The owner of the Notebook will be *name*. He/she gets a new Notebook content folder created where all files are placed. :param context: Extra context information passed to the started Notebook. This must contain {context_hash:int} parameter used to ident...
4.426748
3.985797
1.110631
if self.is_running(name): last_context = self.get_context(name) logger.info("Notebook context change detected for %s", name) if not self.is_same_context(context, last_context): self.stop_notebook(name) # Make sure we don't get race co...
def start_notebook_on_demand(self, name, context)
Start notebook if not yet running with these settings. Return the updated settings with a port info. :return: (context dict, created flag)
4.138654
4.115331
1.005667
@functools.wraps(func) def wrapper(*args, **kwargs): extra_files = [] try: return func(*args, **kwargs) except: exc_type, exc_val, exc_tb = sys.exc_info() traceback.print_exc() tb = exc_tb while tb: filename = tb.tb_...
def failsafe(func)
Wraps an app factory to provide a fallback in case of import errors. Takes a factory function to generate a Flask app. If there is an error creating the app, it will return a dummy app that just returns the Flask error page for the exception. This works with the Flask code reloader so that if the app ...
2.470391
2.276607
1.08512
if not isinstance(schema, Schema): raise ValueError( "schema value {0!r} is not a Schema" " object".format(schema)) self = cls() self.validate_toplevel(schema, obj) return True
def validate(cls, schema, obj)
Validate specified JSON object obj with specified schema. :param schema: Schema to validate against :type schema: :class:`json_schema_validator.schema.Schema` :param obj: JSON object to validate :rtype: bool :returns: T...
5.318997
5.525949
0.962549
object_expr = self._get_object_expression() schema_expr = self._get_schema_expression() if schema_suffix: schema_expr += schema_suffix raise ValidationError(legacy_message, new_message, object_expr, schema_expr)
def _report_error(self, legacy_message, new_message=None, schema_suffix=None)
Report an error during validation. There are two error messages. The legacy message is used for backwards compatibility and usually contains the object (possibly very large) that failed to validate. The new message is much better as it contains just a short message on what went wrong. U...
3.278134
2.485524
1.31889
schema = Schema(self._schema.properties[prop]) self._push_schema(schema, ".properties." + prop)
def _push_property_schema(self, prop)
Construct a sub-schema from a property of the current schema.
6.359866
5.430271
1.171188
root = os.path.dirname(pid_file) port_file = os.path.join(root, "context.json") return port_file
def get_context_file_name(pid_file)
When the daemon is started write out the information which port it was using.
3.727146
3.528206
1.056385
assert type(context_info) == dict port_file = get_context_file_name(pid_file) with open(port_file, "wt") as f: f.write(json.dumps(context_info))
def set_context(pid_file, context_info)
Set context of running notebook. :param context_info: dict of extra context parameters, see comm.py comments
2.903769
3.632795
0.799321
port_file = get_context_file_name(pid_file) if not os.path.exists(port_file): return None with open(port_file, "rt") as f: json_data = f.read() try: data = json.loads(json_data) except ValueError as e: logger.error("Damaged context json data %s...
def get_context(pid_file, daemon=False)
Get context of running notebook. A context file is created when notebook starts. :param daemon: Are we trying to fetch the context inside the daemon. Otherwise do the death check. :return: dict or None if the process is dead/not launcherd
4.234347
4.011875
1.055453
return raise RuntimeError("Should not happen") fname = get_context_file_name(pid_file) shutil.move(fname, fname.replace("context.json", "context.old.json")) data = {} data["terminated"] = str(datetime.datetime.now(datetime.timezone.utc)) set_context(pid_file, data)
def clear_context(pid_file)
Called at exit. Delete the context file to signal there is no active notebook. We don't delete the whole file, but leave it around for debugging purposes. Maybe later we want to pass some information back to the web site.
4.898587
4.491461
1.090644
# utils imported here to avoid circular import import utils expiration_date = datetime.timedelta( days=utils.get_settings('REGISTRATION_API_ACCOUNT_ACTIVATION_DAYS')) return self.activation_key == self.ACTIVATED or \ (self.user.date_joined + expiration_...
def activation_key_expired(self)
Determine whether this ``RegistrationProfile``'s activation key has expired, returning a boolean -- ``True`` if the key has expired. Key expiration is determined by a two-step process: 1. If the user has already activated, the key will have been reset to the string constant ``ACT...
7.069312
4.158579
1.699934
old_cycles = self.cycles start_time = time.time() self.burst_run() is_duration = time.time() - start_time new_cycles = self.cycles - old_cycles try: is_cycles_per_sec = new_cycles / is_duration except ZeroDivisionError: pass ...
def delayed_burst_run(self, target_cycles_per_sec)
Run CPU not faster than given speedlimit
2.815926
2.82569
0.996544
model_counts = [] for model in tagged_models: model['count'] = model['query'](tag).count() if model['count']: model_counts.append(model) return model_counts
def get_model_counts(tagged_models, tag)
This does a model count so the side bar looks nice.
4.082966
3.659806
1.115624
query = cursor = connection.cursor() cursor.execute(query, [min_size, limit]) results = [] for row in cursor.fetchall(): try: tag=Tag.objects.get(id=row[0]) except ObjectDoesNotExist: continue if ' ' in tag.name: ...
def index(request, template_name="tagging_ext/index.html", min_size=0,limit=10)
min_size: Smallest size count accepted for a tag order_by: asc or desc by count limit: maximum number of tags to display TODO: convert the hand-written query to an ORM call. Right now I know this works with Sqlite3 and PostGreSQL.
3.316149
3.495476
0.948697
# get the relevent model if applicable if app_label and model: try: model = ContentType.objects.get(app_label=app_label, model=model) except: raise Http404 else: model = None if not request.GET.has_key("q"): raise Http404 else: ...
def autocomplete(request, app_label=None, model=None)
returns ``\\n`` delimited strings in the form <tag>||(#) GET params are ``q``, ``limit``, ``counts``, ``q`` is what the user has typed, ``limit`` defaults to 10, and ``counts`` can be "model", "all" or, if absent, will default to all - ie a site-wide count.
2.387122
2.149186
1.11071
'''Wrap all termui functions with a custom decorator.''' NONE = object() import click saved = [] for name, info in sorted(_ui_functions.items()): f = getattr(click, name, NONE) if f is NONE: continue new_f = wrapper(_copy_fn(f), info) argspec = getargs...
def patch_ui_functions(wrapper)
Wrap all termui functions with a custom decorator.
3.68791
3.415328
1.079811
cells = defaultdict(Cell) start_row = row_number(start) end_row = row_number(end) if end % 0x10 == 0: end_row -= 1 ## topmost cells if start_row == end_row: for i in range(start, end): cells[i].top = True else: for i in range(start, row_end_index(st...
def compute_region_border(start, end)
given the buffer start and end indices of a range, compute the border edges that should be drawn to enclose the range. this function currently assumes 0x10 length rows. the result is a dictionary from buffer index to Cell instance. the Cell instance has boolean properties "top", "bottom", "left", and...
1.994206
1.894405
1.052682
# Currently rely on swftools # # Would be great to have a native python dependency to convert swf into png or jpg. # However it seems that pyswf isn't flawless. Some graphical elements (like the text!) are lost during # the export. try: cmd = [swfrender_path, swf_path, '-o', png_pa...
def swf2png(swf_path, png_path, swfrender_path="swfrender")
Convert SWF slides into a PNG image Raises: OSError is raised if swfrender is not available. ConversionError is raised if image cannot be created.
4.814903
4.863965
0.989913