file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
views.py
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer # Create your views here. class AccountCreateView(generics.Create...
(generics.RetrieveAPIView): queryset = Account.objects.all() serializer_class = AccountRetrieveSerializer class UpdateAccountView(generics.UpdateAPIView): queryset = Account.objects.all() serializer_class = UpdateAccountSerializer # permission_classes = [permissions.IsAuthenticated] class Accoun...
AccountRetrieveView
identifier_name
views.py
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer # Create your views here. class AccountCreateView(generics.Create...
queryset = Account.objects.all() serializer_class = AuthenticateSerializer def post(self, request): data = request.data serializer = AuthenticateSerializer(data=data) if serializer.is_valid(raise_exception=True): new_date = serializer.data return response.Respons...
identifier_body
views.py
from rest_framework import generics, permissions, views, response,status from .models import Account from .serializers import AccountCreateSerializer, AccountSerializer, AuthenticateSerializer, \ UpdateAccountSerializer, AccountRetrieveSerializer # Create your views here. class AccountCreateView(generics.Create...
return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
new_date = serializer.data return response.Response(new_date,status=status.HTTP_200_OK)
conditional_block
test_tfidf.py
import unittest from datetime import datetime import tempfile import os
from due.episode import Episode from due.event import Event from due.persistence import serialize, deserialize from due.models.tfidf import TfIdfAgent from due.models.dummy import DummyAgent class TestTfIdfAgent(unittest.TestCase): def test_save_load(self): agent = TfIdfAgent() agent.learn_episodes(_get_train_e...
from due.agent import Agent
random_line_split
test_tfidf.py
import unittest from datetime import datetime import tempfile import os from due.agent import Agent from due.episode import Episode from due.event import Event from due.persistence import serialize, deserialize from due.models.tfidf import TfIdfAgent from due.models.dummy import DummyAgent class TestTfIdfAgent(unitte...
(self): cb = TfIdfAgent() # Learn sample episode sample_episode, alice, bob = _sample_episode() cb.learn_episodes([sample_episode]) # Predict answer e2 = alice.start_episode(bob) alice.say("Hi!", e2) answer_events = cb.utterance_callback(e2) self.assertEqual(len(answer_events), 1) self.assertEqual...
test_tfidf_agent
identifier_name
test_tfidf.py
import unittest from datetime import datetime import tempfile import os from due.agent import Agent from due.episode import Episode from due.event import Event from due.persistence import serialize, deserialize from due.models.tfidf import TfIdfAgent from due.models.dummy import DummyAgent class TestTfIdfAgent(unitte...
def test_utterance_callback(self): agent = TfIdfAgent() agent.learn_episodes(_get_train_episodes()) result = agent.utterance_callback(_get_test_episode()) self.assertEqual(result[0].payload, 'bbb') def test_tfidf_agent(self): cb = TfIdfAgent() # Learn sample episode sample_episode, alice, bob = _sa...
agent = TfIdfAgent() agent.learn_episodes(_get_train_episodes()) saved_agent = agent.save() with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, 'serialized_tfidf_agent.due') serialize(saved_agent, path) loaded_agent = Agent.load(deserialize(path)) assert agent.parameters == ...
identifier_body
index.js
/** * Core dependencies. */ var path = require('path'); var dirname = path.dirname; /** * Create path. * * @param {String} pattern * @returns {Object} * @api private */ function createPattern(pattern) { return { pattern: pattern, included: true, served: true, watched: false }; } /** * I...
before.reverse().forEach(function(file) { config.files.unshift(createPattern(path.resolve(file))); }); } /** * Inject. */ init.$inject = [ 'config' ]; /** * Primary export. */ module.exports = { 'framework:hydro': [ 'factory', init ] };
var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js'; var before = hydroConfig.before || []; config.files.unshift(createPattern(__dirname + '/adapter.js')); config.files.unshift(createPattern(hydroJs));
random_line_split
index.js
/** * Core dependencies. */ var path = require('path'); var dirname = path.dirname; /** * Create path. * * @param {String} pattern * @returns {Object} * @api private */ function createPattern(pattern) { return { pattern: pattern, included: true, served: true, watched: false }; } /** * I...
/** * Inject. */ init.$inject = [ 'config' ]; /** * Primary export. */ module.exports = { 'framework:hydro': [ 'factory', init ] };
{ var hydroConfig = config.hydro || {}; var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js'; var before = hydroConfig.before || []; config.files.unshift(createPattern(__dirname + '/adapter.js')); config.files.unshift(createPattern(hydroJs)); before.reverse().for...
identifier_body
index.js
/** * Core dependencies. */ var path = require('path'); var dirname = path.dirname; /** * Create path. * * @param {String} pattern * @returns {Object} * @api private */ function createPattern(pattern) { return { pattern: pattern, included: true, served: true, watched: false }; } /** * I...
(config) { var hydroConfig = config.hydro || {}; var hydroJs = hydroConfig.path || dirname(dirname(require.resolve('hydro'))) + '/dist/hydro.js'; var before = hydroConfig.before || []; config.files.unshift(createPattern(__dirname + '/adapter.js')); config.files.unshift(createPattern(hydroJs)); before.reve...
init
identifier_name
scatter-demo-basic.component.ts
import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef } from '@angular/core'; import { getThemes } from '@covalent/echarts/base'; import { ChartThemeSelectorService } from '../../../../../../utilities/chart-theme'; @Component({ selector: 'scatter-demo-basic', styleUrls: ['./scatter-demo-basic.comp...
(): Promise<void> { this.selectedTheme = this.themeSelector.selected; this._cdr.markForCheck(); } selectChartTheme(theme: string): void { this.themeSelector.select(theme); } symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; } }
ngOnInit
identifier_name
scatter-demo-basic.component.ts
import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef } from '@angular/core'; import { getThemes } from '@covalent/echarts/base'; import { ChartThemeSelectorService } from '../../../../../../utilities/chart-theme'; @Component({ selector: 'scatter-demo-basic', styleUrls: ['./scatter-demo-basic.comp...
async ngOnInit(): Promise<void> { this.selectedTheme = this.themeSelector.selected; this._cdr.markForCheck(); } selectChartTheme(theme: string): void { this.themeSelector.select(theme); } symbolSize(data: number[]): number { return Math.sqrt(data[2]) / 5e2; } }
{}
identifier_body
scatter-demo-basic.component.ts
import { Component, ChangeDetectionStrategy, OnInit, ChangeDetectorRef } from '@angular/core'; import { getThemes } from '@covalent/echarts/base'; import { ChartThemeSelectorService } from '../../../../../../utilities/chart-theme'; @Component({ selector: 'scatter-demo-basic', styleUrls: ['./scatter-demo-basic.comp...
[23038, 73.13, 143456918, 'Russia', 2015], [19360, 76.5, 78665830, 'Turkey', 2015], [38225, 81.4, 64715810, 'United Kingdom', 2015], [53354, 79.1, 321773631, 'United States', 2015], ], type: 'scatter', itemStyle: { opacity: 0.75, color:...
[24787, 77.3, 38611794, 'Poland', 2015],
random_line_split
remote_try_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import mox import os import sys import shutil import time import constants sys.path.insert(0, constants.SOURCE_ROOT) f...
# Get ourselves a working dir. tmp_repo = os.path.join(self.tempdir, 'tmp-repo') git.RunGit(self.tempdir, ['clone', path, tmp_repo]) vpath = os.path.join(tmp_repo, remote_try.RemoteTryJob.TRYJOB_FORMAT_FILE) with open(vpath, 'w') as f: f.write(str(version)) git.RunGit(tmp_re...
continue
conditional_block
remote_try_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import mox import os import sys import shutil import time import constants sys.path.insert(0, constants.SOURCE_ROOT) f...
def _RunCommandSingleOutput(self, cmd, cwd): result = cros_build_lib.RunCommandCaptureOutput(cmd, cwd=cwd) out_lines = result.output.split() self.assertEqual(len(out_lines), 1) return out_lines[0] def _GetNewestFile(self, dirname, basehash): newhash = git.GetGitRepoRevision(dirname) self....
self.parser = cbuildbot._CreateParser() args = ['-r', '/tmp/test_build1', '-g', '5555', '-g', '6666', '--remote'] args.extend(self.BOTS) self.options, args = cbuildbot._ParseCommandLine(self.parser, args) self.checkout_dir = os.path.join(self.tempdir, 'test_checkout') self.int_mirror, se...
identifier_body
remote_try_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import mox import os import sys import shutil import time import constants sys.path.insert(0, constants.SOURCE_ROOT) f...
job = job_class(self.options, self.BOTS, []) return job def testJobTimestamp(self): """Verify jobs have unique names.""" def submit_helper(dirname): work_dir = os.path.join(self.tempdir, dirname) return os.path.basename(self._SubmitJob(work_dir, job)) self.mox.StubOutWithMock(reposit...
if mirror: job_class = RemoteTryJobMock self._SetupMirrors()
random_line_split
remote_try_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import mox import os import sys import shutil import time import constants sys.path.insert(0, constants.SOURCE_ROOT) f...
(self): self.assertRaises( remote_try.ChromiteUpgradeNeeded, self.testSimpleTryJob, version=remote_try.RemoteTryJob.TRYJOB_FORMAT_VERSION + 1) def testInternalTryJob(self): """Verify internal tryjobs are pushed properly.""" self.mox.StubOutWithMock(repository, 'IsARepoRoot') r...
testClientVersionAwareness
identifier_name
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPl...
impl RustBotPlugin for WhoAmIPlugin { fn configure(&mut self, conf: &mut IrcBotConfigurator) { conf.map_format(CMD_WHOAMI, Format::from_str("whoami").unwrap()); conf.map_format(CMD_WHEREAMI, Format::from_str("whereami").unwrap()); } fn dispatch_cmd(&mut self, m: &CommandMapperDispatch, m...
{ match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAmI), _ => None } }
identifier_body
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPl...
() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> { match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), CMD_WHEREAMI => Some(WhoAmICommandType::WhereAm...
get_plugin_name
identifier_name
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1);
WhoAmIPlugin } pub fn get_plugin_name() -> &'static str { "whoami" } } enum WhoAmICommandType { WhoAmI, WhereAmI } fn parse_command<'a>(m: &CommandMapperDispatch) -> Option<WhoAmICommandType> { match m.command().token { CMD_WHOAMI => Some(WhoAmICommandType::WhoAmI), ...
pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin {
random_line_split
whoami.rs
use irc::{IrcMsg, server}; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WHOAMI: Token = Token(0); const CMD_WHEREAMI: Token = Token(1); pub struct WhoAmIPlugin; impl WhoAmIPlugin { pub fn new() -> WhoAmIPlugin { WhoAmIPl...
, None => () } } }
{ m.reply(&format!("{}: you are in {:?}", privmsg.source_nick(), m.target)); }
conditional_block
generatorBase.ts
import { TemplateEngine } from './templateEngine'; export abstract class OpGeneratorBase { /** * Name of the object used to inject dependencies. * In the generated functions, the dependencies are accessed via * `__dep__.Dependency`. */ public readonly DEP_OBJ_NAME = '__dep__'; protect...
(fs: {[key: string]: Function}): string { let result = ''; for (let key in fs) { if (fs.hasOwnProperty(key)) { let fStr = fs[key].toString(); if (fStr.indexOf('[native code]') > 0) { throw new Error('Cannot inline native functions.'); ...
_flattenInlineFunctions
identifier_name
generatorBase.ts
import { TemplateEngine } from './templateEngine'; export abstract class OpGeneratorBase { /** * Name of the object used to inject dependencies. * In the generated functions, the dependencies are accessed via * `__dep__.Dependency`. */ public readonly DEP_OBJ_NAME = '__dep__'; protect...
// replace function name let idxFirstP = fStr.indexOf('('); if (idxFirstP < 0) { throw new Error('Cannot find the first pair of parenthesis.'); } // note that the specified function name is NOT checked f...
{ throw new Error('Cannot inline native functions.'); }
conditional_block
generatorBase.ts
import { TemplateEngine } from './templateEngine'; export abstract class OpGeneratorBase { /** * Name of the object used to inject dependencies. * In the generated functions, the dependencies are accessed via * `__dep__.Dependency`. */ public readonly DEP_OBJ_NAME = '__dep__'; protect...
/** * Checks the symbols used in the given code. Throws when encounters any * symbol that is not allowed. Returns a list of used symbols. * @param code Block of code to be checked. * @param allowed A list of allowed symbols. Case sensitive. */ protected _checkUsedSymbols(code: string,...
{ this._engine = new TemplateEngine(); }
identifier_body
generatorBase.ts
import { TemplateEngine } from './templateEngine'; export abstract class OpGeneratorBase { /** * Name of the object used to inject dependencies. * In the generated functions, the dependencies are accessed via * `__dep__.Dependency`. */ public readonly DEP_OBJ_NAME = '__dep__'; protect...
} } return result; } /** * Converts inline functions to string. * @param fs Functions to be converted. */ protected _flattenInlineFunctions(fs: {[key: string]: Function}): string { let result = ''; for (let key in fs) { if (fs.hasOwnPro...
result.push(prop);
random_line_split
manipulation.js
define([ "./core", "./var/strundefined", "./var/concat", "./var/push", "./var/deletedIds", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, strundefined, concat, push, deletedIds, a...
( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild,...
fixDefaultChecked
identifier_name
manipulation.js
define([ "./core", "./var/strundefined", "./var/concat", "./var/push", "./var/deletedIds", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, strundefined, concat, push, deletedIds, a...
else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]...
{ nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes }
conditional_block
manipulation.js
define([ "./core", "./var/strundefined", "./var/concat", "./var/push", "./var/deletedIds", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, strundefined, concat, push, deletedIds, a...
function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = e...
{ elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; }
identifier_body
manipulation.js
define([ "./core", "./var/strundefined", "./var/concat", "./var/push", "./var/deletedIds", "./core/access", "./manipulation/var/rcheckableType", "./manipulation/support", "./core/init", "./data/accepts", "./traversing", "./selector", "./event" ], function( jQuery, strundefined, concat, push, deletedIds, a...
} else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src....
// IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132.
random_line_split
typography.py
# -*- encoding: utf-8 -*- # # License: New BSD Style # # [typography.py][1] is a set of filters enhancing written text output. As the # name says, it adds specific typography things documented in the definitions # itself and [smartypants][2]. # # The typography.py filter comes with two options: ``mode`` and ``default``...
# [2]: http://web.chad.org/projects/smartypants.py/ import re import smartypants from acrylamid.filters import Filter class Typography(Filter): match = [re.compile('^(T|t)ypo(graphy)?$'), 'smartypants'] version = 2 priority = 25.0 def init(self, conf, env): self.mode = conf.get("typograp...
# [1]: https://github.com/mintchaos/typogrify
random_line_split
typography.py
# -*- encoding: utf-8 -*- # # License: New BSD Style # # [typography.py][1] is a set of filters enhancing written text output. As the # name says, it adds specific typography things documented in the definitions # itself and [smartypants][2]. # # The typography.py filter comes with two options: ``mode`` and ``default``...
return """%s<span class="%s">%s</span>""" % (matchobj.group(1), classname, quote) output = quote_finder.sub(_quote_wrapper, text) return output def widont(text): """Replaces the space between the last two words in a string with ``&nbsp;`` Works in these block tags ``(h1-h6, p, li, dd, dt)`` a...
classname = "quo" quote = matchobj.group(8)
conditional_block
typography.py
# -*- encoding: utf-8 -*- # # License: New BSD Style # # [typography.py][1] is a set of filters enhancing written text output. As the # name says, it adds specific typography things documented in the definitions # itself and [smartypants][2]. # # The typography.py filter comes with two options: ``mode`` and ``default``...
def caps(text): """Wraps multiple capital letters in ``<span class="caps">`` so they can be styled with CSS. >>> caps("A message from KU") u'A message from <span class="caps">KU</span>' Uses the smartypants tokenizer to not screw with HTML or with tags it shouldn't. >>> caps("<PRE>CAPS</pr...
"""Wraps apersands in HTML with ``<span class="amp">`` so they can be styled with CSS. Apersands are also normalized to ``&amp;``. Requires ampersands to have whitespace or an ``&nbsp;`` on both sides. >>> amp('One & two') u'One <span class="amp">&amp;</span> two' >>> amp('One &amp; two') u'One...
identifier_body
typography.py
# -*- encoding: utf-8 -*- # # License: New BSD Style # # [typography.py][1] is a set of filters enhancing written text output. As the # name says, it adds specific typography things documented in the definitions # itself and [smartypants][2]. # # The typography.py filter comes with two options: ``mode`` and ``default``...
(content): """The super typography filter Applies the following filters: widont, smartypants, caps, amp, initial_quotes""" return number_suffix( initial_quotes( caps( smartypants.smartyPants( widont( amp(content)), "2"))))
typogrify
identifier_name
indent_list_item.py
import re import sublime import sublime_plugin class IndentListItemCommand(sublime_plugin.TextCommand): bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))' bullet_pattern_re = re.compile(bullet_pattern) line_pattern_re = re.compile(r'^\s*' + bullet_pattern) spaces_re = re.co...
endings = ['.', ')'] # Transform the bullet to the next/previous bullet type if self.view.settings().get('list_indent_auto_switch_bullet', True): bullets = self.view.settings().get('list_indent_bullets', ['*', '-', '+']) def change_bullet(m): ...
if not new_line.startswith(tab_str): continue # Do the unindentation new_line = re.sub(tab_str + sep_str + self.bullet_pattern, r'\1', new_line) # Insert the new item if prev_line_content: new_line = '\n' + new_line...
conditional_block
indent_list_item.py
import re import sublime import sublime_plugin class IndentListItemCommand(sublime_plugin.TextCommand): bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))' bullet_pattern_re = re.compile(bullet_pattern) line_pattern_re = re.compile(r'^\s*' + bullet_pattern) spaces_re = re.co...
else: if not new_line.startswith(tab_str): continue # Do the unindentation new_line = re.sub(tab_str + sep_str + self.bullet_pattern, r'\1', new_line) # Insert the new item if prev_line_content: ...
# Insert the new item if prev_line_content: new_line = '\n' + new_line
random_line_split
indent_list_item.py
import re import sublime import sublime_plugin class IndentListItemCommand(sublime_plugin.TextCommand):
bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))' bullet_pattern_re = re.compile(bullet_pattern) line_pattern_re = re.compile(r'^\s*' + bullet_pattern) spaces_re = re.compile(r'^\s*') def run(self, edit, reverse=False): for region in self.view.sel(): if r...
identifier_body
indent_list_item.py
import re import sublime import sublime_plugin class IndentListItemCommand(sublime_plugin.TextCommand): bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))' bullet_pattern_re = re.compile(bullet_pattern) line_pattern_re = re.compile(r'^\s*' + bullet_pattern) spaces_re = re.co...
(self): return bool(self.view.score_selector(self.view.sel()[0].a, 'text.restructuredtext'))
is_enabled
identifier_name
bpmn2xpdl20-min.js
if(!ORYX.Plugins)
ORYX.Plugins.BPMN2XPDL20=ORYX.Plugins.AbstractPlugin.extend({construct:function(){arguments.callee.$.construct.apply(this,arguments); this.facade.offer({name:ORYX.I18N.BPMN2XPDL.xpdlExport,functionality:this.transform.bind(this),group:ORYX.I18N.BPMN2XPDL.group,dropDownGroupIcon:ORYX.BASE_FILE_PATH+"images/export2.png",...
{ORYX.Plugins=new Object() }
conditional_block
bpmn2xpdl20-min.js
if(!ORYX.Plugins){ORYX.Plugins=new Object() }ORYX.Plugins.BPMN2XPDL20=ORYX.Plugins.AbstractPlugin.extend({construct:function(){arguments.callee.$.construct.apply(this,arguments); this.facade.offer({name:ORYX.I18N.BPMN2XPDL.xpdlExport,functionality:this.transform.bind(this),group:ORYX.I18N.BPMN2XPDL.group,dropDownGroupI...
}});
d.items.items[2].setValue(f) },true)
random_line_split
App.js
import React, { useState } from 'react'; import ReactNodeGraph from '../index'; const exampleGraph = { "nodes":[ {"nid":1,"type":"WebGLRenderer","x":1479,"y":351,"fields":{"in":[{"name":"width"},{"name":"height"},{"name":"scene"},{"name":"camera"},{"name":"bg_color"},{"name":"postfx"},{"name":"shadowCameraNear"...
}); } const onNodeMove = (nid, pos) => { console.log(`end move:`, nid, pos); } const onNodeStartMove = nid => { console.log(`start move:`, nid); } const handleNodeSelect = nid => { console.log(`node selected:`, nid); } const handleNodeDeselect = nid => { console.log(`node desele...
"connections": connections }
random_line_split
create_org_data_czar_policy.py
""" create_org_data_czar_policy.py Creates an IAM group for an edX org and applies an S3 policy to that group that allows for read-only access to the group. """ import argparse import boto3 from botocore.exceptions import ClientError from string import Template import sys template = Template("""{ "Version":"2012-1...
parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-o', '--org', help='Name of the org for which to create an IAM ' 'role and policy, this should have the same ' 'name as the S3 bucket') gr...
print(bse) print(template.substitute(org=org))
conditional_block
create_org_data_czar_policy.py
""" create_org_data_czar_policy.py Creates an IAM group for an edX org and applies an S3 policy to that group that allows for read-only access to the group. """ import argparse import boto3 from botocore.exceptions import ClientError from string import Template import sys template = Template("""{ "Version":"2012-1...
(org, iam_connection): group_name = "edx-course-data-{org}".format(org=org) try: iam_connection.create_group(GroupName=group_name) except ClientError as bse: if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: ...
add_org_group
identifier_name
create_org_data_czar_policy.py
""" create_org_data_czar_policy.py Creates an IAM group for an edX org and applies an S3 policy to that group that allows for read-only access to the group. """ import argparse import boto3 from botocore.exceptions import ClientError from string import Template import sys template = Template("""{ "Version":"2012-1...
parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-o', '--org', help='Name of the org for which to create an IAM ' 'role and policy, this should have the same ' 'name as the S3 bucket') gr...
group_name = "edx-course-data-{org}".format(org=org) try: iam_connection.create_group(GroupName=group_name) except ClientError as bse: if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: print(bse) try: ...
identifier_body
create_org_data_czar_policy.py
""" create_org_data_czar_policy.py Creates an IAM group for an edX org and applies an S3 policy to that group that allows for read-only access to the group. """ import argparse import boto3 from botocore.exceptions import ClientError from string import Template import sys template = Template("""{ "Version":"2012-1...
if bse.response['ResponseMetadata']['HTTPStatusCode'] == 409: pass else: print(bse) try: iam_connection.put_group_policy( GroupName=group_name, PolicyName=group_name, PolicyDocument=template.subs...
iam_connection.create_group(GroupName=group_name) except ClientError as bse:
random_line_split
advent9.rs
// advent9.rs // // Traveling Santa Problem extern crate permutohedron; #[macro_use] extern crate scan_fmt; use std::io; fn main() { let mut city_table = CityDistances::new(); loop { let mut input = String::new(); let result = io::stdin().read_line(&mut input); match result { ...
(&mut self, city: &str) -> usize { match self.cities.iter().position(|x| x == city) { Some(idx) => idx, None => { self.cities.push(String::from(city)); self.cities.len() - 1 } } } fn add_distance(&mut self, city1: &str, city2: ...
find_city_idx
identifier_name
advent9.rs
// advent9.rs // // Traveling Santa Problem extern crate permutohedron; #[macro_use] extern crate scan_fmt; use std::io; fn main() { let mut city_table = CityDistances::new(); loop { let mut input = String::new(); let result = io::stdin().read_line(&mut input); match result { ...
#[test] fn test_distance_struct() { let mut cities = CityDistances::new(); cities.add_distance("Hoth", "Tatooine", 1000); cities.add_distance("Hoth", "Coruscant", 300); cities.add_distance("Coruscant", "Tatooine", 900); assert_eq!(1000, cities.find_distance(0, 1)); assert_eq!(1000, cities.find...
{ let mut indices: Vec<_> = (0..city_table.cities.len()).collect(); permutohedron::Heap::new(&mut indices[..]) .map(|x| x.windows(2).fold(0, |acc, x| acc + city_table.find_distance(x[0], x[1]))) .min().unwrap() }
identifier_body
advent9.rs
// advent9.rs // // Traveling Santa Problem extern crate permutohedron; #[macro_use] extern crate scan_fmt; use std::io; fn main() { let mut city_table = CityDistances::new(); loop {
match result { Ok(byte_count) => if byte_count == 0 { break; }, Err(_) => { println!("error reading from stdin"); break; } } // Parse input let (city1, city2, distance) = scan_fmt!(&input, "{} to {} = {}", String, String...
let mut input = String::new(); let result = io::stdin().read_line(&mut input);
random_line_split
test-fsreqwrap-readFile.js
'use strict'; const common = require('../common'); const assert = require('assert'); const tick = require('./tick'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const fs = require('fs'); const hooks = initHooks(); hooks.enable(); fs.readFile(__filename, common.mu...
checkInvocations(as[1], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[1]: while in onread callback'); checkInvocations(as[2], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[2]: while in onread callback'); // this callback is called from within the last fs re...
random_line_split
test-fsreqwrap-readFile.js
'use strict'; const common = require('../common'); const assert = require('assert'); const tick = require('./tick'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const fs = require('fs'); const hooks = initHooks(); hooks.enable(); fs.readFile(__filename, common.mu...
() { const as = hooks.activitiesOfTypes('FSREQWRAP'); let lastParent = 1; for (let i = 0; i < as.length; i++) { const a = as[i]; assert.strictEqual(a.type, 'FSREQWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, lastParent); lastParent = a.uid; } chec...
onread
identifier_name
test-fsreqwrap-readFile.js
'use strict'; const common = require('../common'); const assert = require('assert'); const tick = require('./tick'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const fs = require('fs'); const hooks = initHooks(); hooks.enable(); fs.readFile(__filename, common.mu...
process.on('exit', onexit); function onexit() { hooks.disable(); hooks.sanityCheck('FSREQWRAP'); const as = hooks.activitiesOfTypes('FSREQWRAP'); const a = as.pop(); checkInvocations(a, { init: 1, before: 1, after: 1, destroy: 1 }, 'when process exits'); }
{ const as = hooks.activitiesOfTypes('FSREQWRAP'); let lastParent = 1; for (let i = 0; i < as.length; i++) { const a = as[i]; assert.strictEqual(a.type, 'FSREQWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, lastParent); lastParent = a.uid; } checkIn...
identifier_body
test-fsreqwrap-readFile.js
'use strict'; const common = require('../common'); const assert = require('assert'); const tick = require('./tick'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const fs = require('fs'); const hooks = initHooks(); hooks.enable(); fs.readFile(__filename, common.mu...
checkInvocations(as[0], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[0]: while in onread callback'); checkInvocations(as[1], { init: 1, before: 1, after: 1, destroy: 1 }, 'reqwrap[1]: while in onread callback'); checkInvocations(as[2], { init: 1, before: 1, after: ...
{ const a = as[i]; assert.strictEqual(a.type, 'FSREQWRAP'); assert.strictEqual(typeof a.uid, 'number'); assert.strictEqual(a.triggerAsyncId, lastParent); lastParent = a.uid; }
conditional_block
jsonconfig.py
""" Read a dictionary from a JSON file, and add its contents to a Python dictionary. """ import json import types from instmakelib import rtimport INSTMAKE_SITE_DIR = "instmakesite" # These are the supported field names # =================================== # The name of the plugin (without ".py") for logging # usa...
(name): """Import a plugin from the instmakesite directory. The import can throw exceptions that the caller has to catch.""" plugin_name = INSTMAKE_SITE_DIR + "." + name return rtimport.rtimport(plugin_name)
load_site_plugin
identifier_name
jsonconfig.py
and add its contents to a Python dictionary. """ import json import types from instmakelib import rtimport INSTMAKE_SITE_DIR = "instmakesite" # These are the supported field names # =================================== # The name of the plugin (without ".py") for logging # usage of instmake CONFIG_USAGE_LOGGER = "us...
""" Read a dictionary from a JSON file,
random_line_split
jsonconfig.py
""" Read a dictionary from a JSON file, and add its contents to a Python dictionary. """ import json import types from instmakelib import rtimport INSTMAKE_SITE_DIR = "instmakesite" # These are the supported field names # =================================== # The name of the plugin (without ".py") for logging # usa...
"""Import a plugin from the instmakesite directory. The import can throw exceptions that the caller has to catch.""" plugin_name = INSTMAKE_SITE_DIR + "." + name return rtimport.rtimport(plugin_name)
identifier_body
Teacher-Quiz.py
# Teacher Quiz - Python Code - Elizabeth Tweedale import csv, random def askName(): # askName function returns the name of the student print("Welcome to the Super Python Quiz!") yourName = input("What is your name? ") print ("Hello",str(yourName...
(question,score): # askQuestion prints the question and choices to the screen then checks the answer print(question[0]) # print the question - this is in the [0] position of the row for eachChoice in question[1:-1]: ...
askQuestion
identifier_name
Teacher-Quiz.py
# Teacher Quiz - Python Code - Elizabeth Tweedale import csv, random def askName(): # askName function returns the name of the student print("Welcome to the Super Python Quiz!") yourName = input("What is your name? ") print ("Hello",str(yourName...
def askQuestion(question,score): # askQuestion prints the question and choices to the screen then checks the answer print(question[0]) # print the question - this is in the [0] position of the row for eachChoice in...
questions = [] # this creates an empty list for adding the questions to with open("SuperPythonQuiz.csv", mode="r", encoding="utf-8") as myFile: myQuiz = csv.reader(myFile) for row in myQuiz: questions.append(row) return questio...
identifier_body
Teacher-Quiz.py
# Teacher Quiz - Python Code - Elizabeth Tweedale import csv, random def askName(): # askName function returns the name of the student print("Welcome to the Super Python Quiz!") yourName = input("What is your name? ") print ("Hello",str(yourName...
return score # return the score def recordScore(studentName, score): with open("QuizResults.txt", mode="a+",encoding="utf-8") as myFile: # note the '+' sign after the a means if the file does not exist, then create it myFile.write(str(stud...
print("Incorrect, the correct answer was {0}.".format(question[-1]))
conditional_block
Teacher-Quiz.py
# Teacher Quiz - Python Code - Elizabeth Tweedale import csv, random def askName(): # askName function returns the name of the student print("Welcome to the Super Python Quiz!") yourName = input("What is your name? ") print ("Hello",str(yourName...
number = len(questions) # use the number to keep track of the total number of questions - which is the length of the 'questions' list for eachQuestion in range(number): # reppeat for each question question = random.choice(questions) # choose a random question...
random_line_split
RepositoryList.js
import React from 'react' import { filter, get } from 'lodash' import utils from '~/utils' import Filter from '~/components/filter/Filter' import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll' import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard' /** * The Reposit...
/> ) } /> </div> ) } /** * Handle filter value changes. * @param {String} value The new filter value. */ filterChanged(value) { const { repos } = this.state // Filter repos. const query = utils.unicodeNormalize(value) const matcher = new RegExp(ut...
render={ (repo) => ( <RepositoryCard key={ repo.id } repo={ repo }
random_line_split
RepositoryList.js
import React from 'react' import { filter, get } from 'lodash' import utils from '~/utils' import Filter from '~/components/filter/Filter' import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll' import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard' /** * The Reposit...
() { const { filteredRepos } = this.state return ( <div> <Filter placeholder="Filter repositories by name or author..." onChange={ (value) => this.filterChanged(value) } /> <InfiniteScroll items={ filteredRepos } render={ (repo) => ( ...
render
identifier_name
RepositoryList.js
import React from 'react' import { filter, get } from 'lodash' import utils from '~/utils' import Filter from '~/components/filter/Filter' import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll' import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard' /** * The Reposit...
} /** * Render this component. */ render() { const { filteredRepos } = this.state return ( <div> <Filter placeholder="Filter repositories by name or author..." onChange={ (value) => this.filterChanged(value) } /> <InfiniteScroll items={ ...
{ this.setState({ repos: nextRepos, filteredRepos: nextRepos, }) }
conditional_block
RepositoryList.js
import React from 'react' import { filter, get } from 'lodash' import utils from '~/utils' import Filter from '~/components/filter/Filter' import InfiniteScroll from '~/components/infinite-scroll/InfiniteScroll' import RepositoryCard from '~/components/repository-list/repository-card/RepositoryCard' /** * The Reposit...
/** * Render this component. */ render() { const { filteredRepos } = this.state return ( <div> <Filter placeholder="Filter repositories by name or author..." onChange={ (value) => this.filterChanged(value) } /> <InfiniteScroll items={ filt...
{ const currRepos = get(this.props, 'repos', []) const nextRepos = get(nextProps, 'repos', []) if (currRepos.length !== nextRepos.length) { this.setState({ repos: nextRepos, filteredRepos: nextRepos, }) } }
identifier_body
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub unsafe fn destroy(&self) { let lock = self.lock.get(); let recursion = self.recursion.get(); assert_eq!( (*lock).load(Ordering::Relaxed), abi::LOCK_UNLOCKED.0, "Attempted to destroy locked mutex" ); assert_eq!(*recursion, 0, "Re...
{ // Lock is managed by kernelspace. Call into the kernel // to unblock waiting threads. let ret = abi::lock_unlock(lock as *mut abi::lock, abi::scope::PRIVATE); assert_eq!(ret, abi::errno::SUCCESS, "Failed to unlock a mutex"); }
conditional_block
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub unsafe fn uninitialized() -> ReentrantMutex { mem::uninitialized() } pub unsafe fn init(&mut self) { self.lock = UnsafeCell::new(AtomicU32::new(abi::LOCK_UNLOCKED.0)); self.recursion = UnsafeCell::new(0); } pub unsafe fn try_lock(&self) -> bool { // Attempt to a...
impl ReentrantMutex {
random_line_split
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) { self.0.write() } pub unsafe fn unlock(&self) { self.0.write_unlock() } pub unsafe fn destroy(&self) { self.0.destroy() } } pub struct ReentrantMutex { lock: UnsafeCell<AtomicU32>, recursion: UnsafeCell<u32>, } impl ReentrantMutex { pub unsafe fn unin...
lock
identifier_name
mutex.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub unsafe fn init(&mut self) { // This function should normally reinitialize the mutex after // moving it to a different memory address. This implementation // does not require adjustments after moving. } pub unsafe fn try_lock(&self) -> bool { self.0.try_write() } ...
{ Mutex(RWLock::new()) }
identifier_body
topics.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
# Mappings. Each row is a (topic_id, url_suffix), where topic_id is a string # containing the unique identifier of the help topic, and url_suffix is a string # giving the suffix of the help URL. Neither may be missing or empty. url_suffix # is relative to the version component of the URL. If you have a URL of the fo...
"""A legacy URL, where the value is taken verbatim instead of calculated.""" def __init__(self, value): self.value = value
identifier_body
topics.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
(self, value): self.value = value # Mappings. Each row is a (topic_id, url_suffix), where topic_id is a string # containing the unique identifier of the help topic, and url_suffix is a string # giving the suffix of the help URL. Neither may be missing or empty. url_suffix # is relative to the version componen...
__init__
identifier_name
topics.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
# giving the suffix of the help URL. Neither may be missing or empty. url_suffix # is relative to the version component of the URL. If you have a URL of the form # # https://www.google.com/edu/openonline/course-builder/docs/1.10/something, # # the value to put here is '/something'. _ALL = [ ('certificate:certific...
self.value = value # Mappings. Each row is a (topic_id, url_suffix), where topic_id is a string # containing the unique identifier of the help topic, and url_suffix is a string
random_line_split
vera.py
""" Support for Vera sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.vera/ """ import logging from homeassistant.const import ( TEMP_CELSIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import Entity from homeassistant.componen...
(self): """Return the name of the sensor.""" return self.current_value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" if self.vera_device.category == "Temperature Sensor": return self._temperature_units e...
state
identifier_name
vera.py
""" Support for Vera sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.vera/ """ import logging from homeassistant.const import ( TEMP_CELSIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import Entity from homeassistant.componen...
@property def state(self): """Return the name of the sensor.""" return self.current_value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" if self.vera_device.category == "Temperature Sensor": return self...
"""Initialize the sensor.""" self.current_value = None self._temperature_units = None VeraDevice.__init__(self, vera_device, controller) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id)
identifier_body
vera.py
""" Support for Vera sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.vera/ """ import logging from homeassistant.const import ( TEMP_CELSIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import Entity from homeassistant.componen...
elif self.vera_device.category == "Sensor": tripped = self.vera_device.is_tripped self.current_value = 'Tripped' if tripped else 'Not Tripped' else: self.current_value = 'Unknown'
self.current_value = self.vera_device.humidity
conditional_block
vera.py
""" Support for Vera sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.vera/ """ import logging from homeassistant.const import ( TEMP_CELSIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import Entity from homeassistant.componen...
elif self.vera_device.category == "Light Sensor": self.current_value = self.vera_device.light elif self.vera_device.category == "Humidity Sensor": self.current_value = self.vera_device.humidity elif self.vera_device.category == "Sensor": tripped = self.vera_de...
if vera_temp_units == 'F': self._temperature_units = TEMP_FAHRENHEIT else: self._temperature_units = TEMP_CELSIUS
random_line_split
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only ...
}
{ let current_size = (self.top_address - self.bottom_address) as isize; let difference = new_size as isize - current_size; if difference > 0 { self.grow(difference as usize, address_space); } else { self.shrink(-difference as usize, address_space); } ...
identifier_body
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only ...
let area = MemoryArea::new(start_address, max_size); assert!( address_space.add_segment(Segment::new(area, flags, SegmentType::MemoryOnly)), "Could not add stack segment." ); } stack.resize(initial_size, address_space); sta...
{ flags |= USER_ACCESSIBLE; }
conditional_block
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only ...
"Bottom: {:?}, Top: {:?}, Max size: {:x}", self.bottom_address, self.top_address, self.max_size ) } } impl Drop for Stack { fn drop(&mut self) { // NOTE: This assumes that the stack is dropped in its own address space. self.resize(0, None); } } impl Stack { ...
random_line_split
stack.rs
//! Provides functionality to manage multiple stacks. use arch::{self, Architecture}; use core::cmp::{max, min}; use core::fmt; use core::mem::size_of; use memory::address_space::{AddressSpace, Segment, SegmentType}; use memory::{MemoryArea, VirtualAddress, READABLE, USER_ACCESSIBLE, WRITABLE}; // NOTE: For now only ...
{ /// Represents the top address of the stack. top_address: VirtualAddress, /// Represents the bottom address of the stack. bottom_address: VirtualAddress, /// Represents the maximum stack size. max_size: usize, /// Represents the first address of the stack. pub base_stack_pointer: Virt...
Stack
identifier_name
MetronomeAnimation.ts
/** * MetronomeAnimation
Default coordinate framefor canvas: (0,0)-----> x | | y Where the origin is to the top left of the canvas. The animation uses a translated coordinate frame where the origin is moved down to the right. The y-axis wraps around such that the last 7/8 of a bar are animated as a right-...
*/ /*
random_line_split
MetronomeAnimation.ts
/** * MetronomeAnimation */ /* Default coordinate framefor canvas: (0,0)-----> x | | y Where the origin is to the top left of the canvas. The animation uses a translated coordinate frame where the origin is moved down to the right. The y-axis wraps around such that the last 7/8...
stop() { this.running = false; window.cancelAnimationFrame(this.animationFrameId); } toggle() { if (this.running) { this.stop(); } else { this.start(); } } private setSize(width: number, height: number) { this.gridCanvas.wid...
{ this.updateNoteInfo(); this.running = true; this.animationFrameId = window.requestAnimationFrame(() => { this.drawBall(); }); }
identifier_body
MetronomeAnimation.ts
/** * MetronomeAnimation */ /* Default coordinate framefor canvas: (0,0)-----> x | | y Where the origin is to the top left of the canvas. The animation uses a translated coordinate frame where the origin is moved down to the right. The y-axis wraps around such that the last 7/8...
else { this.start(); } } private setSize(width: number, height: number) { this.gridCanvas.width = width; this.gridCanvas.height = height; this.ballCanvas.width = width; this.ballCanvas.height = height; } private updateNoteInfo() { let data =...
{ this.stop(); }
conditional_block
MetronomeAnimation.ts
/** * MetronomeAnimation */ /* Default coordinate framefor canvas: (0,0)-----> x | | y Where the origin is to the top left of the canvas. The animation uses a translated coordinate frame where the origin is moved down to the right. The y-axis wraps around such that the last 7/8...
{ private width: number; private height: number; private container: HTMLDivElement; private gridCanvas: HTMLCanvasElement; private ballCanvas: HTMLCanvasElement; private gridContext: CanvasRenderingContext2D; private ballContext: CanvasRenderingContext2D; private animationFrameId: n...
MetronomeAnimation
identifier_name
basic.test.ts
import { isEqual } from 'lodash' import { nanoid } from 'nanoid' import { Client, createWaitForResponseMiddleware } from '@resolve-js/client' import { getClient } from '../../utils/utils' let client: Client beforeEach(() => { client = getClient() }) const registerUser = async (userId: string) => client.command({...
}, attempts: 5, period: 3000, }), }, } ) } catch (e) { // eslint-disable-next-line no-console console.error(lastResult) throw e } } test('execute register command and check the result', async () => { const userId = nanoid() const resu...
{ confirm(result) }
conditional_block
basic.test.ts
import { isEqual } from 'lodash' import { nanoid } from 'nanoid' import { Client, createWaitForResponseMiddleware } from '@resolve-js/client' import { getClient } from '../../utils/utils' let client: Client beforeEach(() => { client = getClient() }) const registerUser = async (userId: string) => client.command({...
response: createWaitForResponseMiddleware({ validator: async (response, confirm) => { const result = await response.json() if (isEqual(result.data, data)) { confirm(result) } }, attempts: 5, period: 3000,...
}, }, { middleware: {
random_line_split
ClassRegister.js
Ext.define('Desktop.controller.ClassRegister', { extend: 'Deft.mvc.ViewController', inject: ['sharedStorage'], requires: [], config: { sharedStorage: null, descrizione: null, istituto: null, anno_Scolastico:null, classe: null, docente: null, materia: null }, control: { view: { show: 'onShow...
else{ if (Ext.isEmpty(this.getMateria())){ Desktop.ux.window.Notification.info(i18n.important, i18n.workspace_required_subject); view.destroy(); } else{ // ho tutto il necessario preparo la finistra view.setTitle(i18n.teacher_register_title + " - " + this.getDescrizione()); ...
{ Desktop.ux.window.Notification.info(i18n.important, i18n.workspace_required_teacher); view.destroy(); }
conditional_block
ClassRegister.js
Ext.define('Desktop.controller.ClassRegister', { extend: 'Deft.mvc.ViewController', inject: ['sharedStorage'], requires: [], config: { sharedStorage: null, descrizione: null, istituto: null, anno_Scolastico:null, classe: null, docente: null, materia: null }, control: { view: { show: 'onShow...
window.open(url, i18n.class_register_title); }, onChangeScheduleGridWeek: function ( combo, newValue, oldValue, eOpts ){ }, onChangeTeachersScheduleGridWeek: function ( combo, newValue, oldValue, eOpts ){ } });
var istituto = this.getIstituto(); var anno_scolastico = this.getAnno_Scolastico(); var classe = this.getClasse(); var url = app_context_path + "/print/registroDiClasse/" + istituto + "/" + anno_scolastico + "/" + classe;
random_line_split
exposer.js
import { FieldErrorProcessor } from "./processors/field-error-processor"; import { RuleResolver } from "./rulesets/rule-resolver"; import { ValidationGroupBuilder } from "./builders/validation-group-builder"; import { ruleRegistry } from "./rule-registry-setup"; import { RulesetBuilder } from "./builders/ruleset-builde...
return rulesetBuilder.create(basedUpon); } export function mergeRulesets(rulesetA, rulesetB) { const newRuleset = new Ruleset(); newRuleset.rules = Object.assign({}, rulesetA.rules, rulesetB.rules); newRuleset.compositeRules = Object.assign({}, rulesetA.compositeRules, rulesetB.compositeRules); newR...
const fieldErrorProcessor = new FieldErrorProcessor(ruleRegistry, defaultLocaleHandler); const ruleResolver = new RuleResolver(); export function createRuleset(basedUpon, withRuleVerification = false) { const rulesetBuilder = withRuleVerification ? new RulesetBuilder(ruleRegistry) : new RulesetBuilder();
random_line_split
exposer.js
import { FieldErrorProcessor } from "./processors/field-error-processor"; import { RuleResolver } from "./rulesets/rule-resolver"; import { ValidationGroupBuilder } from "./builders/validation-group-builder"; import { ruleRegistry } from "./rule-registry-setup"; import { RulesetBuilder } from "./builders/ruleset-builde...
(rulesetA, rulesetB) { const newRuleset = new Ruleset(); newRuleset.rules = Object.assign({}, rulesetA.rules, rulesetB.rules); newRuleset.compositeRules = Object.assign({}, rulesetA.compositeRules, rulesetB.compositeRules); newRuleset.propertyDisplayNames = Object.assign({}, rulesetA.propertyDisplayName...
mergeRulesets
identifier_name
exposer.js
import { FieldErrorProcessor } from "./processors/field-error-processor"; import { RuleResolver } from "./rulesets/rule-resolver"; import { ValidationGroupBuilder } from "./builders/validation-group-builder"; import { ruleRegistry } from "./rule-registry-setup"; import { RulesetBuilder } from "./builders/ruleset-builde...
{ defaultLocaleHandler.supplementLocaleFrom(localeCode, localeResource); }
identifier_body
show_reply_thumbnails.js
//================================================ // show_reply_thumbnails.js // Author: @iihoshi //================================================
var my_filename = 'show_reply_thumbnails.js'; // プラグイン情報 ここから // プラグイン情報の初期化 if (!jn.pluginInfo) jn.pluginInfo = {}; // プラグイン情報本体 jn.pluginInfo[my_filename.split('.')[0]] = { 'name' : { 'ja' : 'リプライサムネイル表示', 'en' : 'Show thumbnails in reply chain' }, 'author' : { 'en' : '@iihoshi' }, 'versi...
(function ($, jn) {
random_line_split
show_reply_thumbnails.js
//================================================ // show_reply_thumbnails.js // Author: @iihoshi //================================================ (function ($, jn) { var my_filename = 'show_reply_thumbnails.js'; // プラグイン情報 ここから // プラグイン情報の初期化 if (!jn.pluginInfo) jn.pluginInfo = {}; // プラグイン情報本体 jn.plugin...
d = /_content\.find\('div\.tweet-body /gm; if (!re_siblings.test(orig_janetterThumbnail) || !re_find.test(orig_janetterThumbnail)) { return false; } var replaced = orig_janetterThumbnail .replace(re_siblings, "_content.children('div.tweet-thumb');") .replace(re_find, "_content.find('div.tweet-reply-...
/m; var re_fin
identifier_name
show_reply_thumbnails.js
//================================================ // show_reply_thumbnails.js // Author: @iihoshi //================================================ (function ($, jn) { var my_filename = 'show_reply_thumbnails.js'; // プラグイン情報 ここから // プラグイン情報の初期化 if (!jn.pluginInfo) jn.pluginInfo = {}; // プラグイン情報本体 jn.plugin...
itle: my_filename, icon: '', message: 'Sorry, ' + my_filename+ ' cannot be installed.', buttons: [ janet.msg.ok ], }); return; } var orig_generateReply = jn.generateReply; jn.generateReply = function (item, is_default) { var reply = orig_generateReply(item, is_default); reply.append('<div...
mbnail(\W)/gm; if (!re_tweet_content.test(orig_jn_expandUrl) || !re_janetterThumbnail.test(orig_jn_expandUrl)) { return false; } var replaced = orig_jn_expandUrl .replace(re_tweet_content, 'div.tweet-reply:first') .replace(re_janetterThumbnail, '.janetterThumbnailForReply$1'); // console.log(repla...
identifier_body
backup_unittest.py
#!/usr/bin/python # # Copyright (C) 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of...
testutils.GanetiTestProgram()
conditional_block
backup_unittest.py
#!/usr/bin/python # # Copyright (C) 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of...
class TestLUBackupExportLocalExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportLocalExport, self).setUp() self.inst = self.cfg.AddNewInstance() self.target_node = self.cfg.AddNewNode() self.op = opcodes.OpBackupExport(mode=constants.EXPORT_MODE_LOCAL, ...
inst = self.cfg.AddNewInstance(disk_template=constants.DT_FILE) op = opcodes.OpBackupExport(instance_name=inst.name, target_node=self.master.name) self.ExecOpCodeExpectOpPrereqError( op, "Export not supported for instances with file-based disks")
identifier_body
backup_unittest.py
#!/usr/bin/python # # Copyright (C) 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of...
(self): op = self.CopyOpCode(self.op, compress="invalid") self.cfg.SetCompressionTools(["gzip", "lzop"]) self.ExecOpCodeExpectOpPrereqError(op, "Compression tool not allowed") class TestLUBackupExportRemoteExport(TestLUBackupExportBase): def setUp(self): super(TestLUBackupExportRemoteExport, self).s...
testInvalidCompressionTool
identifier_name
backup_unittest.py
#!/usr/bin/python # # Copyright (C) 2013 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of...
self.rpc.call_export_start.return_value = \ self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(self.master, "export_daemon") def ImpExpStatus(node_uuid, name): return self.RpcResultsBuilder() \ .CreateSuccessfulNodeResult(node_uuid, ...
.CreateSuccessfulNodeResult(self.master, None)
random_line_split
index.js
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './n...
(identity) { // bot already exists, get bot token for this users team var SlackUserId = identity.user_id; var TeamId = identity.team_id; models.Team.find({ where: { TeamId } }) .then((team) => { const { token } = team; if (token) { var bot = controller.spawn({ token }); controller.trigger('logi...
connectOnLogin
identifier_name
index.js
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './n...
controller.on('rtm_open',function(bot) { console.log(`\n\n\n\n** The RTM api just connected! for bot token: ${bot.config.token}\n\n\n`); }); // upon install controller.on('create_bot', (bot,team) => { const { id, url, name, bot: { token, user_id, createdBy, accessToken, scopes } } = team; // this is what is us...
{ // bot already exists, get bot token for this users team var SlackUserId = identity.user_id; var TeamId = identity.team_id; models.Team.find({ where: { TeamId } }) .then((team) => { const { token } = team; if (token) { var bot = controller.spawn({ token }); controller.trigger('login_bot', [bo...
identifier_body
index.js
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './n...
console.log(`\n\n\n\n CONNECTING ON INSTALL \n\n\n\n`); let bot = controller.spawn(team_config); controller.trigger('create_bot', [bot, team_config]); } export function connectOnLogin(identity) { // bot already exists, get bot token for this users team var SlackUserId = identity.user_id; var TeamId = iden...
export function connectOnInstall(team_config) {
random_line_split
index.js
import Botkit from 'botkit'; import os from 'os'; import Wit from 'botkit-middleware-witai'; import moment from 'moment-timezone'; import models from '../../app/models'; import storageCreator from '../lib/storage'; import setupReceiveMiddleware from '../middleware/receiveMiddleware'; import notWitController from './n...
else { console.log("RTM failed") console.log(err); } }); } });
{ console.log("RTM on and listening"); trackBot(bot); loginInitiateConversation(bot, identity); }
conditional_block
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
raise Forbidden(_('You are not authorized to take this action.'))
conditional_block
__init__.py
# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (a...
# along with Indico; if not, see <http://www.gnu.org/licenses/>. from flask import session from werkzeug.exceptions import Forbidden from indico.modules.rb.controllers import RHRoomBookingBase from indico.modules.rb.util import rb_is_admin from indico.util.i18n import _ class RHRoomBookingAdminBase(RHRoomBookingBas...
# WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License
random_line_split