file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
simplewebserver.py
import BaseHTTPServer import cgi import ctypes import os import sys import threading from PySide import QtGui import MaxPlus PORT = 8000 class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.exiting = False address = ('localhost', PORT) self...
class _GCProtector(object): controls = [] if __name__ == '__main__': app = QtGui.QApplication.instance() if not app: app = QtGui.QApplication([]) window = MyWindow() _GCProtector.controls.append(window) window.show() capsule = window.effectiveWinId() ctypes.pythonapi.PyCObj...
print "Stopping webserver" self.btn_run.setText('Run') self.serverThread.stop() self.serverThread = None
conditional_block
simplewebserver.py
import BaseHTTPServer import cgi import ctypes import os import sys import threading from PySide import QtGui import MaxPlus PORT = 8000 class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.exiting = False address = ('localhost', PORT) self...
(self, parent=None): super(MyWindow, self).__init__(parent) self.setWindowTitle('Simple 3ds Max webserver') self.resize(200,50) self.btn_run = QtGui.QPushButton('Run') layout = QtGui.QVBoxLayout() layout.addWidget(self.btn_run) self.setLayout(layout) self....
__init__
identifier_name
simplewebserver.py
import BaseHTTPServer import cgi import ctypes
import os import sys import threading from PySide import QtGui import MaxPlus PORT = 8000 class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.exiting = False address = ('localhost', PORT) self.server = BaseHTTPServer.HTTPServer(address, My...
random_line_split
simplewebserver.py
import BaseHTTPServer import cgi import ctypes import os import sys import threading from PySide import QtGui import MaxPlus PORT = 8000 class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.exiting = False address = ('localhost', PORT) self...
def stop(self): self.server.server_close() self.server.shutdown() self._stop.set() class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): rootdir = os.path.join(os.path.dirname(__file__) + '/html') try: if self.path == '/': ...
self.server.serve_forever()
identifier_body
main.rs
/* * SPKI - Simple Public Key Infrastructure * * Copyright © 2014 Senso-Rezo * All rigths reserved. * * See LICENSE file for licensing information. * See http://github/olemaire/spki for more information. */ fn main() { Usage(); } fn Usage() {
Exemples: spki --issue server www.senso-rezo.org spki --issue user olivier.lemaire@senso-rezo.org spki --info www.senso-rezo.org spki --revoke ldap.senso-rezo.org spki --revoke www.senso-rezo.org keyCompromise spki --renew olivier.lemaire@senso-rezo.org spki --crl...
let message = "Copyright (C) Senso-Rezo - SPKI (http://github.com/olemaire/spki) Usage: spki <option> (<subject>) Available options are: --initialize Initialize a new Certificate Authority --issue <type> <subject> Issue a certificate of <type> for <subject> server <...
identifier_body
main.rs
/* * SPKI - Simple Public Key Infrastructure * * Copyright © 2014 Senso-Rezo * All rigths reserved. * * See LICENSE file for licensing information. * See http://github/olemaire/spki for more information. */ fn main() { Usage(); } fn U
) { let message = "Copyright (C) Senso-Rezo - SPKI (http://github.com/olemaire/spki) Usage: spki <option> (<subject>) Available options are: --initialize Initialize a new Certificate Authority --issue <type> <subject> Issue a certificate of <type> for <subject> serve...
sage(
identifier_name
main.rs
/* * SPKI - Simple Public Key Infrastructure * * Copyright © 2014 Senso-Rezo * All rigths reserved. * * See LICENSE file for licensing information. * See http://github/olemaire/spki for more information. */ fn main() { Usage(); } fn Usage() { let message = "Copyright (C) Senso-Rezo - SPKI (http://github...
--revoke <email,fqdn> (reason) Revoke a given certificate --crl Generate a Certificate Revocation List --print <email,fqdn,ca,crl> Will display a raw print of certificate/CRL --info (email,fqdn,ca,crl) Will give human readable information on SPKI certificate/CA/CR...
random_line_split
metrics.py
# Copyright 2020 The FedLearner Authors. 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 applica...
document = self._produce_document(name, value, tags, index_type) if not Config.METRICS_TO_STDOUT: # if filebeat not yet refurbished, directly emit to ES action = {'_index': INDEX_NAME[index_type], '_source': document} if self._version == 6: ...
def emit(self, name, value, tags=None, index_type='metrics'): assert index_type in INDEX_TYPE if tags is None: tags = {}
random_line_split
metrics.py
# Copyright 2020 The FedLearner Authors. 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 applica...
def emit(self, name, value, tags=None, index_type='metrics'): self.init_handlers() if not self.handlers or len(self.handlers) == 0: fl_logging.info('No handlers. Not emitting.') return for hdlr in self.handlers: try: hdlr.emit(name, valu...
""" Remove the specified handler from this logger. """ with self._lock: if hdlr in self.handlers: self.handlers.remove(hdlr)
identifier_body
metrics.py
# Copyright 2020 The FedLearner Authors. 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 applica...
def flush(self): emit_batch = [] with self._lock: if self._emit_batch: emit_batch = self._emit_batch self._emit_batch = [] if emit_batch: fl_logging.info('Emitting %d documents to ES', len(emit_batch)) self._helpers.bulk(s...
document['index_type__'] = index_type print(json.dumps(document))
conditional_block
metrics.py
# Copyright 2020 The FedLearner Authors. 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 applica...
(name, value, tags, index_type): application_id = os.environ.get('APPLICATION_ID', '') if application_id: tags['application_id'] = str(application_id) if index_type == 'metrics': tags['process_time'] = datetime.datetime.now(tz=pytz.utc) \ .isoformat(timesp...
_produce_document
identifier_name
Router.js
/** * Copyright (c) 2015-present, Pavel Aksonov * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * */ import React, { Component, PropTypes, } from 'react'; import NavigationExperimental from 'react-nativ...
(navigationState, onNavigate) { if (!navigationState) { return null; } Actions.get = key => findElement(navigationState, key, ActionConst.REFRESH); Actions.callback = props => { const constAction = (props.type && ActionMap[props.type] ? ActionMap[props.type] : null); if (this.props.dis...
renderNavigation
identifier_name
Router.js
/** * Copyright (c) 2015-present, Pavel Aksonov * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * */ import React, { Component, PropTypes, } from 'react'; import NavigationExperimental from 'react-nativ...
if (!navigationState) { return null; } Actions.get = key => findElement(navigationState, key, ActionConst.REFRESH); Actions.callback = props => { const constAction = (props.type && ActionMap[props.type] ? ActionMap[props.type] : null); if (this.props.dispatch) { if (constAction...
renderNavigation(navigationState, onNavigate) {
random_line_split
Router.js
/** * Copyright (c) 2015-present, Pavel Aksonov * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * */ import React, { Component, PropTypes, } from 'react'; import NavigationExperimental from 'react-nativ...
} // eslint-disable-next-line no-unused-vars const { children, styles, scenes, reducer, createReducer, ...parentProps } = props; scenesMap.rootProps = parentProps; const initialState = getInitialState(scenesMap); const reducerCreator = props.createReducer || Reducer; const routerReducer ...
{ let scenesMap; if (props.scenes) { scenesMap = props.scenes; } else { let scenes = props.children; if (Array.isArray(props.children) || props.children.props.component) { scenes = ( <Scene key="__root" hideNav {...this.props} ...
identifier_body
ObjectUtils.ts
import {Injectable} from "@angular/core"; @Injectable() export class ObjectUtils { public equals(obj1: any, obj2: any): boolean { if (obj1 == null && obj2 == null) { return true; } if (obj1 == null || obj2 == null) { return false; } if (obj1 == obj2) { return true; } ...
(data: any, field: string): any { if (data && field) { if (field.indexOf('.') == -1) { return data[field]; } else { let fields: string[] = field.split('.'); let value = data; for (var i = 0, len = fields.length; i < len; ++i) { if (value == null) { ...
resolveFieldData
identifier_name
ObjectUtils.ts
import {Injectable} from "@angular/core"; @Injectable() export class ObjectUtils { public equals(obj1: any, obj2: any): boolean { if (obj1 == null && obj2 == null) { return true; } if (obj1 == null || obj2 == null) { return false; } if (obj1 == obj2) { return true; } ...
return null; } value = value[fields[i]]; } return value; } } else { return null; } } }
else { let fields: string[] = field.split('.'); let value = data; for (var i = 0, len = fields.length; i < len; ++i) { if (value == null) {
random_line_split
subscriber.py
from collections import defaultdict import re import json import os import Pubnub as PB PUB_KEY = os.environ["PUB_KEY"] SUB_KEY = os.environ["SUB_KEY"] SEC_KEY = os.environ["SEC_KEY"] CHANNEL_NAME = os.environ["CHANNEL_NAME"] def frequency_count(text): "determine count of each letter" count = defaultdict(int)...
return count def callback(message, channel): "print message, channel, and frequency count to STDOUT" print("python recevied:" + str({ "channel": channel, "message": message, "frequency count":dict(frequency_count(message)), })) def error(message): print({ "erro...
count[char] += 1
conditional_block
subscriber.py
from collections import defaultdict import re import json import os import Pubnub as PB PUB_KEY = os.environ["PUB_KEY"] SUB_KEY = os.environ["SUB_KEY"] SEC_KEY = os.environ["SEC_KEY"] CHANNEL_NAME = os.environ["CHANNEL_NAME"] def frequency_count(text): "determine count of each letter" count = defaultdict(int)...
if __name__ == "__main__": PB.Pubnub( publish_key = PUB_KEY, subscribe_key = SUB_KEY, secret_key = SEC_KEY, cipher_key = '', ssl_on = False, ).subscribe( channels=CHANNEL_NAME, callback=callback, error=error )
print({ "error" : message })
identifier_body
subscriber.py
from collections import defaultdict import re import json import os import Pubnub as PB PUB_KEY = os.environ["PUB_KEY"]
SUB_KEY = os.environ["SUB_KEY"] SEC_KEY = os.environ["SEC_KEY"] CHANNEL_NAME = os.environ["CHANNEL_NAME"] def frequency_count(text): "determine count of each letter" count = defaultdict(int) for char in text: count[char] += 1 return count def callback(message, channel): "print message, cha...
random_line_split
subscriber.py
from collections import defaultdict import re import json import os import Pubnub as PB PUB_KEY = os.environ["PUB_KEY"] SUB_KEY = os.environ["SUB_KEY"] SEC_KEY = os.environ["SEC_KEY"] CHANNEL_NAME = os.environ["CHANNEL_NAME"] def frequency_count(text): "determine count of each letter" count = defaultdict(int)...
(message): print({ "error" : message }) if __name__ == "__main__": PB.Pubnub( publish_key = PUB_KEY, subscribe_key = SUB_KEY, secret_key = SEC_KEY, cipher_key = '', ssl_on = False, ).subscribe( channels=CHANNEL_NAME, callback=callback, ...
error
identifier_name
blog_post.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe, re from frappe.website.website_generator import WebsiteGenerator from frappe.website.render import clear_cache from frappe.utils import today, cint, global_dat...
# update posts frappe.db.sql("""update tabBlogger set posts=(select count(*) from `tabBlog Post` where ifnull(blogger,'')=tabBlogger.name) where name=%s""", (self.blogger,)) def on_update(self): WebsiteGenerator.on_update(self) clear_cache("writers") def get_context(self, context): # this is for dou...
condition_field = "published" template = "templates/generators/blog_post.html" save_versions = True order_by = "published_on desc" parent_website_route_field = "blog_category" page_title_field = "title" def validate(self): super(BlogPost, self).validate() if not self.blog_intro: self.blog_intro = self.co...
identifier_body
blog_post.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe, re from frappe.website.website_generator import WebsiteGenerator from frappe.website.render import clear_cache from frappe.utils import today, cint, global_dat...
(WebsiteGenerator): condition_field = "published" template = "templates/generators/blog_post.html" save_versions = True order_by = "published_on desc" parent_website_route_field = "blog_category" page_title_field = "title" def validate(self): super(BlogPost, self).validate() if not self.blog_intro: self...
BlogPost
identifier_name
blog_post.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe, re from frappe.website.website_generator import WebsiteGenerator from frappe.website.render import clear_cache from frappe.utils import today, cint, global_dat...
select t1.title, t1.name, concat(t1.parent_website_route, "/", t1.page_name) as page_name, t1.published_on as creation, day(t1.published_on) as day, monthname(t1.published_on) as month, year(t1.published_on) as year, ifnull(t1.blog_intro, t1.content) as content, t2.full_name, t2.avatar, t1....
query = """\
random_line_split
blog_post.py
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe, re from frappe.website.website_generator import WebsiteGenerator from frappe.website.render import clear_cache from frappe.utils import today, cint, global_dat...
if category: condition += " and t1.blog_category='%s'" % category.replace("'", "\'") query = """\ select t1.title, t1.name, concat(t1.parent_website_route, "/", t1.page_name) as page_name, t1.published_on as creation, day(t1.published_on) as day, monthname(t1.published_on) as month, year(t1.pu...
condition = " and t1.blogger='%s'" % by.replace("'", "\'")
conditional_block
merge_pgc_files.py
#!/usr/bin/env python # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Merge the PGC files generated during the profiling step to the PGD database. This is required to workaround a flakyness in pgomgr.e...
return pgomgr_path def merge_pgc_files(pgomgr_path, files, pgd_path): """Merge all the pgc_files in |files| to |pgd_path|.""" merge_command = [ pgomgr_path, '/merge' ] merge_command.extend(files) merge_command.append(pgd_path) proc = subprocess.Popen(merge_command, stdout=subprocess.PIPE) ...
"""Find pgomgr.exe.""" win_toolchain_json_file = os.path.join(chrome_checkout_dir, 'build', 'win_toolchain.json') if not os.path.exists(win_toolchain_json_file): raise Exception('The toolchain JSON file is missing.') with open(win_toolchain_json_file) as temp_f: toolchain_data = json.load(temp_f) ...
identifier_body
merge_pgc_files.py
#!/usr/bin/env python # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Merge the PGC files generated during the profiling step to the PGD database. This is required to workaround a flakyness in pgomgr.e...
pgc_files = glob.glob(os.path.join(options.build_dir, '%s*.pgc' % options.binary_name)) pgd_file = os.path.join(options.build_dir, '%s.pgd' % options.binary_name) def _split_in_chunks(items, chunk_size): """Split |items| in chunks of size |chunk_size|. Source: http:...
# Starts by finding pgomgr.exe. pgomgr_path = find_pgomgr(options.checkout_dir)
random_line_split
merge_pgc_files.py
#!/usr/bin/env python # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Merge the PGC files generated during the profiling step to the PGD database. This is required to workaround a flakyness in pgomgr.e...
(): parser = optparse.OptionParser(usage='%prog [options]') parser.add_option('--checkout-dir', help='The Chrome checkout directory.') parser.add_option('--target-cpu', help='[DEPRECATED] The target\'s bitness.') parser.add_option('--build-dir', help='Chrome build directory.') parser.add_option('--binary-name...
main
identifier_name
merge_pgc_files.py
#!/usr/bin/env python # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Merge the PGC files generated during the profiling step to the PGD database. This is required to workaround a flakyness in pgomgr.e...
if __name__ == '__main__': sys.exit(main())
print 'Error while trying to merge %s, continuing.' % pgc_file
conditional_block
settings.tsx
import Form from './reuse/form'; import Input from './reuse/input'; import { BreadCrumb } from './reuse/breadcrumb'; import { GET_SETTINGS, GfycatClientSettingsFromRender, SETTINGS_CHANGED, RETURN_SETTINGS } from '../settingsHandler'; import * as React from 'react'; import { ipcRenderer } from 'electron'; export defau...
() { this.getSavedSettings(); } handleSubmit(event: GfycatClientSettingsFromRender) { //history.pushState('/', 'Home'); ipcRenderer.send(SETTINGS_CHANGED, event); this.updateState({...event, password: this.state.password, apiSecret: this.state.apiSecret}); } getSavedSettings() { ipcRendere...
componentDidMount
identifier_name
settings.tsx
import Form from './reuse/form'; import Input from './reuse/input'; import { BreadCrumb } from './reuse/breadcrumb'; import { GET_SETTINGS, GfycatClientSettingsFromRender, SETTINGS_CHANGED, RETURN_SETTINGS } from '../settingsHandler';
_defaultSettings: GfycatClientSettingsFromRender = {userName: '', apiId: '', password: '', apiSecret: '', paths: []}; constructor(props: any) { super(props); this.state = this._defaultSettings; ipcRenderer.on(RETURN_SETTINGS, (event: any, args: GfycatClientSettingsFromRender) => { this.updateSt...
import * as React from 'react'; import { ipcRenderer } from 'electron'; export default class Settings extends React.Component<any, GfycatClientSettingsFromRender> {
random_line_split
base.py
# 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 agreed to in writing, software # d...
@six.add_metaclass(abc.ABCMeta) class TaskBase(object): def __init__(self, context, instance): self.context = context self.instance = instance @rollback_wrapper def execute(self): """Run task's logic, written in _execute() method """ return self._execute() @...
@functools.wraps(original) def wrap(self): try: return original(self) except Exception as ex: with excutils.save_and_reraise_exception(): self.rollback(ex) return wrap
identifier_body
base.py
# 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 agreed to in writing, software # d...
(self): """Descendants should place task's logic here, while resource initialization should be performed over __init__ """ pass def rollback(self, ex): """Rollback failed task Descendants should implement this method to allow task user to rollback status to s...
_execute
identifier_name
base.py
# 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 agreed to in writing, software # d...
Descendants should implement this method to allow task user to rollback status to state before execute method was call """ pass
random_line_split
find_requires_correct_type.rs
#[macro_use] extern crate diesel; use diesel::*; use diesel::pg::PgConnection; table! { int_primary_key { id -> Integer, } } table! { string_primary_key { id -> VarChar, }
let connection = PgConnection::establish("").unwrap(); int_primary_key::table.find("1").first(&connection).unwrap(); //~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<int_primary_key::table, diesel::expression::predicates::Eq<int_primary_key::columns::id, &...
} fn main() {
random_line_split
find_requires_correct_type.rs
#[macro_use] extern crate diesel; use diesel::*; use diesel::pg::PgConnection; table! { int_primary_key { id -> Integer, } } table! { string_primary_key { id -> VarChar, } } fn
() { let connection = PgConnection::establish("").unwrap(); int_primary_key::table.find("1").first(&connection).unwrap(); //~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<int_primary_key::table, diesel::expression::predicates::Eq<int_primary_key::columns::...
main
identifier_name
find_requires_correct_type.rs
#[macro_use] extern crate diesel; use diesel::*; use diesel::pg::PgConnection; table! { int_primary_key { id -> Integer, } } table! { string_primary_key { id -> VarChar, } } fn main()
{ let connection = PgConnection::establish("").unwrap(); int_primary_key::table.find("1").first(&connection).unwrap(); //~^ ERROR no method named `first` found for type `diesel::query_source::filter::FilteredQuerySource<int_primary_key::table, diesel::expression::predicates::Eq<int_primary_key::columns::id,...
identifier_body
swarmingserver_bot_fake.py
# Copyright 2014 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. import base64 import copy import json import os import sys import threading BOT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert...
if self.path == '/swarming/api/v1/bot/poll': self.server.parent.has_polled.set() return self.send_json({'cmd': 'sleep', 'duration': 60}) if self.path.startswith('/swarming/api/v1/bot/task_update/'): task_id = self.path[len('/swarming/api/v1/bot/task_update/'):] must_stop = self.server...
return self.send_json({'xsrf_token': 'fine'})
conditional_block
swarmingserver_bot_fake.py
# Copyright 2014 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. import base64 import copy import json import os import sys import threading BOT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert...
def _add_bot_event(self, data): # Used by the handler. with self._lock: self._bot_events.append(data) def _on_task_update(self, task_id, data): with self._lock: self._tasks.setdefault(task_id, []).append(data) must_stop = self.must_stop self.has_updated_task.set() return...
"""Returns the task errors reported by the bots.""" with self._lock: return self._task_errors.copy()
identifier_body
swarmingserver_bot_fake.py
# Copyright 2014 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. import base64 import copy import json import os import sys import threading BOT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert...
(httpserver.Server): """Fake a Swarming bot API server for local testing.""" _HANDLER_CLS = Handler def __init__(self): super(Server, self).__init__() self._lock = threading.Lock() # Accumulated bot events. self._bot_events = [] # Running tasks. self._tasks = {} # Bot reported task er...
Server
identifier_name
swarmingserver_bot_fake.py
# Copyright 2014 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. import base64 import copy import json import os import sys import threading BOT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert...
self.send_response(200) self.end_headers() return None if self.path == '/auth/api/v1/server/oauth_config': return self.send_json({ 'client_id': 'id', 'client_not_so_secret': 'hunter2', 'primary_url': self.server.url, }) raise NotImplementedError(self...
"""Minimal Swarming bot server fake implementation.""" def do_GET(self): if self.path == '/swarming/api/v1/bot/server_ping':
random_line_split
tests.py
# -*- coding:utf-8 -*- from __future__ import unicode_literals import unittest from io import BytesIO, StringIO from decimal import Decimal import threading from importlib import import_module from ijson import common from ijson.backends.python import basic_parse, Lexer from ijson.compat import IS_PY2 JSON = b''' { ...
in__': unittest.main()
.decode('utf-8'))) self.assertEqual(next(l)[1], '{') if __name__ == '__ma
identifier_body
tests.py
# -*- coding:utf-8 -*- from __future__ import unicode_literals import unittest from io import BytesIO, StringIO from decimal import Decimal import threading from importlib import import_module from ijson import common from ijson.backends.python import basic_parse, Lexer from ijson.compat import IS_PY2 JSON = b''' { ...
for json in INVALID_JSONS: # Yajl1 doesn't complain about additional data after the end # of a parsed object. Skipping this test. if self.__class__.__name__ == 'YajlParse' and json == YAJL1_PASSING_INVALID: continue with self.assertRaises(common.JS...
def test_invalid(self):
random_line_split
tests.py
# -*- coding:utf-8 -*- from __future__ import unicode_literals import unittest from io import BytesIO, StringIO from decimal import Decimal import threading from importlib import import_module from ijson import common from ijson.backends.python import basic_parse, Lexer from ijson.compat import IS_PY2 JSON = b''' { ...
self.assertTrue(list(self.backend.items(BytesIO(JSON), ''))) self.assertTrue(list(self.backend.parse(BytesIO(JSON)))) # Generating real TestCase classes for each importable backend for name in ['python', 'yajl', 'yajl2', 'yajl2_cffi']: try: classname = '%sParse' % ''.join(p.capitalize() for p in...
):
identifier_name
tests.py
# -*- coding:utf-8 -*- from __future__ import unicode_literals import unittest from io import BytesIO, StringIO from decimal import Decimal import threading from importlib import import_module from ijson import common from ijson.backends.python import basic_parse, Lexer from ijson.compat import IS_PY2 JSON = b''' { ...
conditional_block
outlinePanel.ts
= codeEditor.onDidChangeModelLanguage(_ => { this._callback(codeEditor, undefined); }); let disposeListener = codeEditor.onDidDispose(() => { this._callback(undefined, undefined); }); this._sessionDisposable = { dispose() { contentListener.dispose(); clearTimeout(handle); modeListener.disp...
} get sortBy(): OutlineItemCompareType { return this._sortBy; } persist(storageService: IStorageService): void { storageService.store('outline/state', JSON.stringify({ followCursor: this.followCursor, sortBy: this.sortBy }), StorageScope.WORKSPACE); } restore(storageService: IStorageService): void { let...
{ this._sortBy = value; this._onDidChange.fire({ sortBy: true }); }
conditional_block
outlinePanel.ts
= codeEditor.onDidChangeModelLanguage(_ => { this._callback(codeEditor, undefined); }); let disposeListener = codeEditor.onDidDispose(() => { this._callback(undefined, undefined); }); this._sessionDisposable = { dispose() { contentListener.dispose(); clearTimeout(handle); modeListener.disp...
get sortBy(): OutlineItemCompareType { return this._sortBy; } persist(storageService: IStorageService): void { storageService.store('outline/state', JSON.stringify({ followCursor: this.followCursor, sortBy: this.sortBy }), StorageScope.WORKSPACE); } restore(storageService: IStorageService): void { let ra...
{ if (value !== this._sortBy) { this._sortBy = value; this._onDidChange.fire({ sortBy: true }); } }
identifier_body
outlinePanel.ts
= codeEditor.onDidChangeModelLanguage(_ => { this._callback(codeEditor, undefined); }); let disposeListener = codeEditor.onDidDispose(() => { this._callback(undefined, undefined); }); this._sessionDisposable = { dispose() { contentListener.dispose(); clearTimeout(handle); modeListener.disp...
(): boolean { return this._followCursor; } get filterOnType() { return this._filterOnType; } set filterOnType(value) { if (value !== this._filterOnType) { this._filterOnType = value; this._onDidChange.fire({ filterOnType: true }); } } set sortBy(value: OutlineItemCompareType) { if (value !== th...
followCursor
identifier_name
outlinePanel.ts
= codeEditor.onDidChangeModelLanguage(_ => { this._callback(codeEditor, undefined); }); let disposeListener = codeEditor.onDidDispose(() => { this._callback(undefined, undefined); }); this._sessionDisposable = { dispose() { contentListener.dispose(); clearTimeout(handle); modeListener.disp...
this._treeRenderer.renderProblemColors = this._configurationService.getValue(OutlineConfigKeys.problemsColors); this._treeRenderer.renderProblemBadges = this._configurationService.getValue(OutlineConfigKeys.problemsBadges); this._disposables.push(this._tree, this._input); this._disposables.push(this._outlineVi...
this._tree = this._instantiationService.createInstance(WorkbenchTree, treeContainer, { controller, renderer: this._treeRenderer, dataSource: this._treeDataSource, sorter: this._treeComparator, filter: this._treeFilter }, {});
random_line_split
src.py
from itertools import permutations import re def create_formula(combination,numbers): formula = "" index = 0 for op in combination: formula += str(numbers[index]) + op index += 1 formula += numbers[index] return formula ''' Unnecessary Funtion ''' def evaluate(form):
def countdown(numbers): rightCombinations = [] finalScore = numbers.pop() combinations = returnAllCombinations(len(numbers) - 1) perms = list(permutations(numbers)) for combination in combinations: for permut in perms: formula = create_formula(combination,permut) #...
result = 0 for index in range(len(form)): if form[index] == "+": result += int(form[index+1]) index += 1 elif form[index] == "-": result -= int(form[index+1]) index += 1 elif form[index] == "*": result *= int(form[index+1]) ...
identifier_body
src.py
from itertools import permutations import re def create_formula(combination,numbers): formula = "" index = 0 for op in combination: formula += str(numbers[index]) + op index += 1 formula += numbers[index] return formula ''' Unnecessary Funtion ''' def evaluate(form): result ...
listFinal = list(newList) return listFinal out = open("output.txt",'w') for line in open("input.txt",'r'): for formula in countdown(line.split(" ")): out.write(formula) out.write("\n") out.write("\n\n")
newLine = list(l) if y == 0: newLine.append("+") elif y == 1: newLine.append("-") elif y == 2: newLine.append("*") else: newLine.append("/") ...
conditional_block
src.py
from itertools import permutations import re def
(combination,numbers): formula = "" index = 0 for op in combination: formula += str(numbers[index]) + op index += 1 formula += numbers[index] return formula ''' Unnecessary Funtion ''' def evaluate(form): result = 0 for index in range(len(form)): if form[index] ==...
create_formula
identifier_name
src.py
index = 0 for op in combination: formula += str(numbers[index]) + op index += 1 formula += numbers[index] return formula ''' Unnecessary Funtion ''' def evaluate(form): result = 0 for index in range(len(form)): if form[index] == "+": result += int(form[ind...
from itertools import permutations import re def create_formula(combination,numbers): formula = ""
random_line_split
index.js
/** * @version $Id: index.js 10702 2008-08-21 09:31:31Z eddieajau $ * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it i...
});
{ var menu = new JMenu(element) document.menu = menu }
conditional_block
index.js
/** * @version $Id: index.js 10702 2008-08-21 09:31:31Z eddieajau $ * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it i...
/** * Joomla! 1.5 Admininstrator index template behvaior * * @package Joomla * @since 1.5 * @version 1.0 */ //For IE6 - Background flicker fix try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} document.menu = null window.addEvent('load', function(){ element = $('menu') if(!...
* other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */
random_line_split
pip.js
/* * grunt-pip * https://github.com/davidshrader/grunt-pip * * Copyright (c) 2014 david.shrader * Licensed under the MIT license. */ module.exports = function(grunt) { 'use strict'; //var exec = require('exec'); var exec = require('child_process').exec; // Please see the Grunt documentation for more in...
args: args }, function(error, result, code) { grunt.log.writeln(result); done(error); }); // grunt.util.spawn({ // cmd: ['ls'], // args: ['-l'] // }, function(error, result, code) { // grunt.log.writeln('hey there'); // grunt.log.writeln(error); //...
random_line_split
pip.js
/* * grunt-pip * https://github.com/davidshrader/grunt-pip * * Copyright (c) 2014 david.shrader * Licensed under the MIT license. */ module.exports = function(grunt) { 'use strict'; //var exec = require('exec'); var exec = require('child_process').exec; // Please see the Grunt documentation for more in...
grunt.log.writeln(args); var done = this.async(); grunt.util.spawn({ cmd: 'virtualenv', args: args }, function(error, result, code) { grunt.log.writeln(result); done(error); }); // grunt.util.spawn({ // cmd: ['ls'], // args: ['-l'] // }, function(er...
{ args.push('-v'); }
conditional_block
component.ts
// Copyright 2017 The Kubernetes Authors. // // 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 a...
ngOnInit(): void { this.httpClient .get<EnabledAuthenticationModes>('api/v1/login/modes') .subscribe((enabledModes: EnabledAuthenticationModes) => { this.enabledAuthenticationModes_ = enabledModes.modes; }); this.httpClient .get<LoginSkippableResponse>('api/v1/login/skippabl...
{}
identifier_body
component.ts
// Copyright 2017 The Kubernetes Authors. // // 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 a...
(): AuthenticationMode[] { if ( this.enabledAuthenticationModes_.length > 0 && this.enabledAuthenticationModes_.indexOf(LoginModes.Kubeconfig) < 0 ) { // Push this option to the beginning of the list this.enabledAuthenticationModes_.splice(0, 0, LoginModes.Kubeconfig); } return ...
getEnabledAuthenticationModes
identifier_name
component.ts
// Copyright 2017 The Kubernetes Authors. // // 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 a...
return this.enabledAuthenticationModes_; } login(): void { this.authService_.login(this.getLoginSpec_(), (errors: K8SError[]) => { if (errors.length > 0) { this.errors = errors; return; } this.state_.go(overviewState.name, { [NAMESPACE_STATE_PARAM]: CONFIG.defau...
{ // Push this option to the beginning of the list this.enabledAuthenticationModes_.splice(0, 0, LoginModes.Kubeconfig); }
conditional_block
component.ts
// Copyright 2017 The Kubernetes Authors. // // 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 a...
errors: K8SError[]; private enabledAuthenticationModes_: AuthenticationMode[] = []; private isLoginSkippable_ = false; private kubeconfig_: string; private token_: string; private username_: string; private password_: string; constructor( private readonly authService_: AuthService, private rea...
export class LoginComponent implements OnInit { loginModes = LoginModes; selectedAuthenticationMode = LoginModes.Kubeconfig; // TODO handle errors
random_line_split
latex_generation.py
############################################################################## # Copyright 2016-2019 Rigetti Computing # # 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...
from pyquil.latex._main import to_latex warnings.warn( '"pyquil.latex.latex_generation.to_latex" has been moved -- please import it' 'as "from pyquil.latex import to_latex going forward"', FutureWarning, ) return to_latex(circuit, settings)
identifier_body
latex_generation.py
############################################################################## # Copyright 2016-2019 Rigetti Computing # # 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...
(circuit: Program, settings: Optional[DiagramSettings] = None) -> str: from pyquil.latex._main import to_latex warnings.warn( '"pyquil.latex.latex_generation.to_latex" has been moved -- please import it' 'as "from pyquil.latex import to_latex going forward"', FutureWarning, ) re...
to_latex
identifier_name
latex_generation.py
############################################################################## # Copyright 2016-2019 Rigetti Computing # # 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...
FutureWarning, ) return to_latex(circuit, settings)
random_line_split
localisationService_spec.js
/*global angular */ 'use strict'; var angular = require('angular'); var angularMocks = require('angular-mocks'); // var angular = require('angular'); var localisationService = require('../../../src/app/services/localisationService'); describe('Unit: LocalisationService', function() { var service; beforeEach(f...
it('Service is defined', function () { expect(service).toBeDefined(); }); it('init() method is type of function', function () { expect(typeof service.init).toBe('function'); }); it('localise() method is type of function', function () { expect(typeof service.localise).toBe('function'); }); it('test en-...
random_line_split
XYItemContainer.ts
import { VNode } from 'snabbdom/vnode'; import h from 'snabbdom/h'; import { Inject, PostConstruct } from '../di' import { Renderable, RenderableInjector, ConfiguredRenderable, AddChildArgs, RenderableConfigArgs } from '../dom'; import { ConfigurationRef, ContainerRef, UNALLOCATED, RenderableArg } fr...
} static configure(config: XYItemContainerConfig): ConfiguredRenderable<XYItemContainer> { return new ConfiguredRenderable(XYItemContainer, config); } }
{ this._container.setSizeOf(this, size); }
conditional_block
XYItemContainer.ts
import { VNode } from 'snabbdom/vnode'; import h from 'snabbdom/h'; import { Inject, PostConstruct } from '../di' import { Renderable, RenderableInjector, ConfiguredRenderable, AddChildArgs, RenderableConfigArgs } from '../dom'; import { ConfigurationRef, ContainerRef, UNALLOCATED, RenderableArg } fr...
} }, [ this._item.render() ]); } setSize(args: { width: number, height: number }): void { this._width = args.width; this._height = args.height; } isVisible(): boolean { return !this._isMinimized && this._container.isVisible(); } addChild(item: Renderable, options?: AddChil...
random_line_split
XYItemContainer.ts
import { VNode } from 'snabbdom/vnode'; import h from 'snabbdom/h'; import { Inject, PostConstruct } from '../di' import { Renderable, RenderableInjector, ConfiguredRenderable, AddChildArgs, RenderableConfigArgs } from '../dom'; import { ConfigurationRef, ContainerRef, UNALLOCATED, RenderableArg } fr...
@PostConstruct() initialize(): void { super.initialize(); if (this._config) { this.ratio = isNumber(this._config.ratio) ? this._config.ratio : UNALLOCATED; } this._contentItems = [ RenderableInjector.fromRenderable( this._config.use, [ { provide: XYItemConta...
{ return this._contentItems[0]; }
identifier_body
XYItemContainer.ts
import { VNode } from 'snabbdom/vnode'; import h from 'snabbdom/h'; import { Inject, PostConstruct } from '../di' import { Renderable, RenderableInjector, ConfiguredRenderable, AddChildArgs, RenderableConfigArgs } from '../dom'; import { ConfigurationRef, ContainerRef, UNALLOCATED, RenderableArg } fr...
(): number { return this._container.isRow ? this.minSizeX : this.minSizeY; } get maxSize(): number { return this._container.isRow ? this.maxSizeX : this.maxSizeY; } get width(): number { return this._width; } get height(): number { return this._height; } get minSizeX(): number { ...
minSize
identifier_name
stylist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use html5ever_atoms::LocalName; use selectors::parser::LocalName as LocalNameSelector; use selectors::parser::Sele...
"div:nth-last-child(2)", "div:nth-of-type(2)", "div:nth-last-of-type(2)", "div:first-of-type", "div:last-of-type", "div:only-of-type", // Note: it would be nice to test :moz-any and the various other non-TS // pseudo classes supported by gecko, but we don...
random_line_split
stylist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use html5ever_atoms::LocalName; use selectors::parser::LocalName as LocalNameSelector; use selectors::parser::Sele...
#[test] fn test_get_class_name() { let (rules_list, _) = get_mock_rules(&[".intro.foo", "#top"]); assert_eq!(SelectorMap::get_class_name(&rules_list[0][0]), Some(Atom::from("foo"))); assert_eq!(SelectorMap::get_class_name(&rules_list[1][0]), None); } #[test] fn test_get_local_name() { let (rules_list...
{ let (rules_list, _) = get_mock_rules(&[".intro", "#top"]); assert_eq!(SelectorMap::get_id_name(&rules_list[0][0]), None); assert_eq!(SelectorMap::get_id_name(&rules_list[1][0]), Some(Atom::from("top"))); }
identifier_body
stylist.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use html5ever_atoms::LocalName; use selectors::parser::LocalName as LocalNameSelector; use selectors::parser::Sele...
() { let (rules_list, _) = get_mock_rules(&["a.intro", "img.sidebar"]); let a = &rules_list[0][0]; let b = &rules_list[1][0]; assert!((a.specificity(), a.source_order) < ((b.specificity(), b.source_order)), "The rule that comes later should win."); } #[test] fn test_get_id_name() { let...
test_rule_ordering_same_specificity
identifier_name
File.js
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; var _excluded = ["children", "align", "controlSize", "mode", "stretched", "before", "className", "style", "getRef", "getRootRef", "onClick"]; import { createScopedElement } from ...
var File = function File(props) { var children = props.children, align = props.align, controlSize = props.controlSize, mode = props.mode, stretched = props.stretched, before = props.before, className = props.className, style = props.style, getRef = props.getRef, g...
random_line_split
EtsyProduct_20170624130727.js
import React from 'react' import '../../styles/gkm-item.scss'; import ProductItem from './ProductItem' import Input from '../Common/Input' import SearchBar from '../SearchBar'; import _ from 'lodash' class EtsyProduct extends React.Component { constructor(props, context) { super(props, context); this.edit...
} } /> </div> ) } } /* Item.propTypes = { }; */ export default EtsyProduct
<SearchBar products={listings} onSelect={ (listingId) => { addListingToProduct(product, this.getListingById(listingId))
random_line_split
EtsyProduct_20170624130727.js
import React from 'react' import '../../styles/gkm-item.scss'; import ProductItem from './ProductItem' import Input from '../Common/Input' import SearchBar from '../SearchBar'; import _ from 'lodash' class EtsyProduct extends React.Component { constructor(props, context) { super(props, context); this.edit...
(update) { console.log(update) let product = this.props.product _.each(update, (v, k) => { product[k] = v; }) this.props.updateItem(product); } getListingById(id) { return _.find(this.props.listings, (l) => l.id === id) } editableFieldsHtml() { const { product } = this.props...
onUpdateField
identifier_name
manage-admin.ts
import $ from "@/jlib2"; import api from "@/pg-api"; import flashMessage from "@/flash"; import "@/manage"; import { ModalPrompt, ModalConfirm } from "@/modals"; // Event handlers $("[name=blacklist-sel]").change(e => { const self = $(e.target); const cmodal = new ModalConfirm(); switch (self.value()) { ...
} const reloadPage = () => location.reload(); const errorAdding = () => flashMessage("Error blacklisting devices"); const errorRemoving = () => flashMessage("Error removing devices from blacklist");
{ api.reassignDevices(username, devices, reloadPage, () => flashMessage("Error reassigning devices") ); }
conditional_block
manage-admin.ts
import $ from "@/jlib2"; import api from "@/pg-api"; import flashMessage from "@/flash"; import "@/manage"; import { ModalPrompt, ModalConfirm } from "@/modals"; // Event handlers $("[name=blacklist-sel]").change(e => { const self = $(e.target);
case "username": if (self.data("blacklisted") === "true") { cmodal.show( "Remove username from blacklist?", removeUsernameBlacklist ); } else { cmodal.show("Add username to blacklist?", addUsernameBla...
const cmodal = new ModalConfirm(); switch (self.value()) {
random_line_split
manage-admin.ts
import $ from "@/jlib2"; import api from "@/pg-api"; import flashMessage from "@/flash"; import "@/manage"; import { ModalPrompt, ModalConfirm } from "@/modals"; // Event handlers $("[name=blacklist-sel]").change(e => { const self = $(e.target); const cmodal = new ModalConfirm(); switch (self.value()) { ...
() { const devicesToRemove = getCheckedDevices(); if (devicesToRemove.length > 0) { api.unblacklistDevices(devicesToRemove, reloadPage, errorRemoving); } } function reassignSelectedDevices(username: string) { const devices = getCheckedDevices(); if (devices.length > 0 && username) { ...
removeFromBlacklist
identifier_name
manage-admin.ts
import $ from "@/jlib2"; import api from "@/pg-api"; import flashMessage from "@/flash"; import "@/manage"; import { ModalPrompt, ModalConfirm } from "@/modals"; // Event handlers $("[name=blacklist-sel]").change(e => { const self = $(e.target); const cmodal = new ModalConfirm(); switch (self.value()) { ...
function removeFromBlacklist() { const devicesToRemove = getCheckedDevices(); if (devicesToRemove.length > 0) { api.unblacklistDevices(devicesToRemove, reloadPage, errorRemoving); } } function reassignSelectedDevices(username: string) { const devices = getCheckedDevices(); if (devices.len...
{ const devicesToRemove = getCheckedDevices(); if (devicesToRemove.length > 0) { api.blacklistDevices(devicesToRemove, reloadPage, errorAdding); } }
identifier_body
test_web_page.py
from __future__ import unicode_literals import unittest import frappe from frappe.website.router import resolve_route import frappe.website.render from frappe.utils import set_request test_records = frappe.get_test_records('Web Page') def get_page_content(route): set_request(method='GET', path = route) response = f...
(self): web_page = frappe.get_doc(dict( doctype = 'Web Page', title = 'Test Dynamic Route', published = 1, dynamic_route = 1, route = '/doctype-view/<doctype>', content_type = 'HTML', dymamic_template = 1, main_section_html = '<div>{{ frappe.form_dict.doctype }}</div>' )).insert() try: ...
test_dynamic_route
identifier_name
test_web_page.py
from __future__ import unicode_literals import unittest import frappe from frappe.website.router import resolve_route import frappe.website.render from frappe.utils import set_request test_records = frappe.get_test_records('Web Page') def get_page_content(route): set_request(method='GET', path = route) response = f...
web_page.content_type = 'Markdown' web_page.save() self.assertTrue('markdown content' in get_page_content('/test-content-type')) web_page.content_type = 'HTML' web_page.save() self.assertTrue('html content' in get_page_content('/test-content-type')) web_page.delete() def test_dynamic_route(self): w...
main_section_md = '# h1\nmarkdown content', main_section_html = '<div>html content</div>' )).insert() self.assertTrue('rich text' in get_page_content('/test-content-type'))
random_line_split
test_web_page.py
from __future__ import unicode_literals import unittest import frappe from frappe.website.router import resolve_route import frappe.website.render from frappe.utils import set_request test_records = frappe.get_test_records('Web Page') def get_page_content(route): set_request(method='GET', path = route) response = f...
def test_check_sitemap(self): resolve_route("test-web-page-1") resolve_route("test-web-page-1/test-web-page-2") resolve_route("test-web-page-1/test-web-page-3") def test_base_template(self): content = get_page_content('/_test/_test_custom_base.html') # assert the text in base template is rendered self...
frappe.get_doc(t).insert()
conditional_block
test_web_page.py
from __future__ import unicode_literals import unittest import frappe from frappe.website.router import resolve_route import frappe.website.render from frappe.utils import set_request test_records = frappe.get_test_records('Web Page') def get_page_content(route):
class TestWebPage(unittest.TestCase): def setUp(self): frappe.db.sql("delete from `tabWeb Page`") for t in test_records: frappe.get_doc(t).insert() def test_check_sitemap(self): resolve_route("test-web-page-1") resolve_route("test-web-page-1/test-web-page-2") resolve_route("test-web-page-1/test-web-pa...
set_request(method='GET', path = route) response = frappe.website.render.render() return frappe.as_unicode(response.data)
identifier_body
neopixel.py
# NeoPixel driver for MicroPython on ESP8266 # MIT license; Copyright (c) 2016 Damien P. George from esp import neopixel_write class NeoPixel: ORDER = (1, 0, 2, 3) def __init__(self, pin, n, bpp=3): self.pin = pin self.n = n self.bpp = bpp self.buf = bytearray(n * bpp) ...
(self, index): offset = index * self.bpp return tuple(self.buf[offset + self.ORDER[i]] for i in range(self.bpp)) def fill(self, color): for i in range(self.n): self[i] = color def write(self): neopixel_write(self.pin, self.buf, True)
__getitem__
identifier_name
neopixel.py
# NeoPixel driver for MicroPython on ESP8266 # MIT license; Copyright (c) 2016 Damien P. George from esp import neopixel_write class NeoPixel: ORDER = (1, 0, 2, 3) def __init__(self, pin, n, bpp=3):
def __setitem__(self, index, val): offset = index * self.bpp for i in range(self.bpp): self.buf[offset + self.ORDER[i]] = val[i] def __getitem__(self, index): offset = index * self.bpp return tuple(self.buf[offset + self.ORDER[i]] for i in rang...
self.pin = pin self.n = n self.bpp = bpp self.buf = bytearray(n * bpp) self.pin.init(pin.OUT)
identifier_body
neopixel.py
# NeoPixel driver for MicroPython on ESP8266 # MIT license; Copyright (c) 2016 Damien P. George from esp import neopixel_write class NeoPixel: ORDER = (1, 0, 2, 3) def __init__(self, pin, n, bpp=3): self.pin = pin self.n = n self.bpp = bpp self.buf = bytearray(n * bpp) ...
def write(self): neopixel_write(self.pin, self.buf, True)
self[i] = color
conditional_block
neopixel.py
# NeoPixel driver for MicroPython on ESP8266 # MIT license; Copyright (c) 2016 Damien P. George from esp import neopixel_write class NeoPixel: ORDER = (1, 0, 2, 3) def __init__(self, pin, n, bpp=3):
def __setitem__(self, index, val): offset = index * self.bpp for i in range(self.bpp): self.buf[offset + self.ORDER[i]] = val[i] def __getitem__(self, index): offset = index * self.bpp return tuple(self.buf[offset + self.ORDER[i]] for i in range...
self.pin = pin self.n = n self.bpp = bpp self.buf = bytearray(n * bpp) self.pin.init(pin.OUT)
random_line_split
deriving-primitive.rs
// Copyright 2013 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
use std::num::FromPrimitive; use std::isize; #[derive(FromPrimitive)] struct A { x: isize } //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ ERROR `FromPrimitive` cannot be derived for structs #[derive(FromPrimitive)] struct B(isize); //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ E...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
deriving-primitive.rs
// Copyright 2013 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 ...
{ x: isize } //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ ERROR `FromPrimitive` cannot be derived for structs #[derive(FromPrimitive)] struct B(isize); //~^^ ERROR `FromPrimitive` cannot be derived for structs //~^^^ ERROR `FromPrimitive` cannot be derived for structs #[derive(FromPrimitive)] enu...
A
identifier_name
svglength-additive-from-by-1.js
description("This tests from-by-animations adding to previous underlying values"); embedSVGTestCase("resources/svglength-additive-from-by-1.svg"); // Setup animation test function sample1() { shouldBeCloseEnough("rect.width.animVal.value", "10"); shouldBe("rect.width.baseVal.value", "10"); } function sample2(...
]; runAnimationTest(expectedValues); } window.animationStartsImmediately = true; var successfullyParsed = true;
["an1", 4.0, sample3], ["an1", 7.0, sample4], ["an1", 9.0, sample5], ["an1", 60.0, sample5]
random_line_split
svglength-additive-from-by-1.js
description("This tests from-by-animations adding to previous underlying values"); embedSVGTestCase("resources/svglength-additive-from-by-1.svg"); // Setup animation test function sample1() { shouldBeCloseEnough("rect.width.animVal.value", "10"); shouldBe("rect.width.baseVal.value", "10"); } function sample2(...
function sample4() { shouldBeCloseEnough("rect.width.animVal.value", "75"); shouldBe("rect.width.baseVal.value", "10"); } function sample5() { shouldBeCloseEnough("rect.width.animVal.value", "100"); shouldBe("rect.width.baseVal.value", "10"); } function executeTest() { rect = rootSVGElement.owne...
{ shouldBeCloseEnough("rect.width.animVal.value", "50"); shouldBe("rect.width.baseVal.value", "10"); }
identifier_body
svglength-additive-from-by-1.js
description("This tests from-by-animations adding to previous underlying values"); embedSVGTestCase("resources/svglength-additive-from-by-1.svg"); // Setup animation test function sample1() { shouldBeCloseEnough("rect.width.animVal.value", "10"); shouldBe("rect.width.baseVal.value", "10"); } function sample2(...
() { shouldBeCloseEnough("rect.width.animVal.value", "100"); shouldBe("rect.width.baseVal.value", "10"); } function executeTest() { rect = rootSVGElement.ownerDocument.getElementsByTagName("rect")[0]; const expectedValues = [ // [animationId, time, sampleCallback] ["an1", 0.0, sample1...
sample5
identifier_name
loading.js
/** * Created by 斌 on 2017/4/19. */ import {UPDATE_LOADING_STATUS, SHOW_TOAST, HIDE_TOAST, DESTINATION, TEMP_HIDING} from '../../lib/constant' import _ from 'lodash' export default { state: { isLoading: false, toast: { value: false, time: 1000, width: '80%', type: 'text', posi...
}, [HIDE_TOAST] (state) { state.toast.value = false }, [DESTINATION] (state, destination) { state.destination = destination }, [TEMP_HIDING] (state, payload) { state.tempHiding = payload } } }
state.toast = _.assign(state.toast, payload, {value: true}) }
conditional_block
loading.js
/** * Created by 斌 on 2017/4/19. */ import {UPDATE_LOADING_STATUS, SHOW_TOAST, HIDE_TOAST, DESTINATION, TEMP_HIDING} from '../../lib/constant' import _ from 'lodash' export default { state: { isLoading: false, toast: { value: false, time: 1000, width: '80%', type: 'text', posi...
state) { state.toast.value = false }, [DESTINATION] (state, destination) { state.destination = destination }, [TEMP_HIDING] (state, payload) { state.tempHiding = payload } } }
IDE_TOAST] (
identifier_name
loading.js
/** * Created by 斌 on 2017/4/19. */ import {UPDATE_LOADING_STATUS, SHOW_TOAST, HIDE_TOAST, DESTINATION, TEMP_HIDING} from '../../lib/constant' import _ from 'lodash'
time: 1000, width: '80%', type: 'text', position: 'default', text: '' }, destination: {}, tempHiding: false }, mutations: { [UPDATE_LOADING_STATUS] (state, payload) { state.isLoading = payload.isLoading }, [SHOW_TOAST] (state, payload) { if (_.isStri...
export default { state: { isLoading: false, toast: { value: false,
random_line_split
loading.js
/** * Created by 斌 on 2017/4/19. */ import {UPDATE_LOADING_STATUS, SHOW_TOAST, HIDE_TOAST, DESTINATION, TEMP_HIDING} from '../../lib/constant' import _ from 'lodash' export default { state: { isLoading: false, toast: { value: false, time: 1000, width: '80%', type: 'text', posi...
[HIDE_TOAST] (state) { state.toast.value = false }, [DESTINATION] (state, destination) { state.destination = destination }, [TEMP_HIDING] (state, payload) { state.tempHiding = payload } } }
if (_.isString(payload)) { state.toast = _.assign(state.toast, {value: true, text: payload}) } else { state.toast = _.assign(state.toast, payload, {value: true}) } },
identifier_body
main.component.ts
import { Component } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; @Component({ selector: 'app-root', styles: [` .main-background { background-image: linear-gradient(0deg,#f5f5f5 1.1px, transparent 0), linear-gradient(90deg,#f5f5f5 1.1px, transparent 0); background-size: 20...
else { this.detail = ''; } } }); } } // <header></header> // <sidebar></sidebar> // <section [ngClass]="detail" class="main-container center" [ngClass]="{sidebarPushRight: isActive}"> // <router-outlet></router-outlet> // </section> // <detail></detail> // <footer></footer>
{ this.detail = 'center-detail' }
conditional_block
main.component.ts
import { Component } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; @Component({ selector: 'app-root', styles: [` .main-background { background-image: linear-gradient(0deg,#f5f5f5 1.1px, transparent 0), linear-gradient(90deg,#f5f5f5 1.1px, transparent 0); background-size: 20...
<sidebar></sidebar> <section [ngClass]="detail" class="main-container main-background center" [ngClass]="{sidebarPushRight: isActive}"> <router-outlet></router-outlet> </section> <footer></footer> `, }) export class MainComponent { public detail:any = ''; constructor(public router: Router) { router.eve...
// <footer></footer> // `, template: ` <heading></heading>
random_line_split
main.component.ts
import { Component } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; @Component({ selector: 'app-root', styles: [` .main-background { background-image: linear-gradient(0deg,#f5f5f5 1.1px, transparent 0), linear-gradient(90deg,#f5f5f5 1.1px, transparent 0); background-size: 20...
} // <header></header> // <sidebar></sidebar> // <section [ngClass]="detail" class="main-container center" [ngClass]="{sidebarPushRight: isActive}"> // <router-outlet></router-outlet> // </section> // <detail></detail> // <footer></footer>
{ router.events.subscribe(value => { if (value instanceof NavigationEnd) { if (this.router.routerState.snapshot.url == '/agenciesNN') { this.detail = 'center-detail' } else { this.detail = ''; } } }); }
identifier_body
main.component.ts
import { Component } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; @Component({ selector: 'app-root', styles: [` .main-background { background-image: linear-gradient(0deg,#f5f5f5 1.1px, transparent 0), linear-gradient(90deg,#f5f5f5 1.1px, transparent 0); background-size: 20...
(public router: Router) { router.events.subscribe(value => { if (value instanceof NavigationEnd) { if (this.router.routerState.snapshot.url == '/agenciesNN') { this.detail = 'center-detail' } else { this.detail = ''; } } }); } } // <header></header> // <sidebar></sidebar> ...
constructor
identifier_name
forecastqueryservice.d.ts
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class
extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: ForecastQueryService.Types.ClientConfiguration) config: Config & ForecastQueryService.Types.ClientConfiguration; /** * Retrieves a forecast for a single item, filtered by th...
ForecastQueryService
identifier_name