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 |
|---|---|---|---|---|
surface3d.ts | // This file contains the JavaScript (TypeScript) implementation
// for a Bokeh custom extension. The "surface3d.py" contains the
// python counterpart.
//
// This custom model wraps one part of the third-party vis.js library:
//
// http://visjs.org/index.html
//
// Making it easy to hook up python data analytics t... |
return data
}
}
// We must also create a corresponding JavaScript model subclass to
// correspond to the python Bokeh model subclass. In this case, since we want
// an element that can position itself in the DOM according to a Bokeh layout,
// we subclass from ``HTMLBox``
export namespace Surface3d {
export ... | {
data.add({
x: source.data[this.model.x][i],
y: source.data[this.model.y][i],
z: source.data[this.model.z][i],
})
} | conditional_block |
surface3d.ts | // This file contains the JavaScript (TypeScript) implementation
// for a Bokeh custom extension. The "surface3d.py" contains the
// python counterpart.
//
// This custom model wraps one part of the third-party vis.js library:
//
// http://visjs.org/index.html
//
// Making it easy to hook up python data analytics t... | }
// We must also create a corresponding JavaScript model subclass to
// correspond to the python Bokeh model subclass. In this case, since we want
// an element that can position itself in the DOM according to a Bokeh layout,
// we subclass from ``HTMLBox``
export namespace Surface3d {
export type Attrs = p.AttrsO... | random_line_split | |
surface3d.ts | // This file contains the JavaScript (TypeScript) implementation
// for a Bokeh custom extension. The "surface3d.py" contains the
// python counterpart.
//
// This custom model wraps one part of the third-party vis.js library:
//
// http://visjs.org/index.html
//
// Making it easy to hook up python data analytics t... | (): vis.DataSet {
const data = new vis.DataSet()
const source = this.model.data_source
for (let i = 0; i < source.get_length()!; i++) {
data.add({
x: source.data[this.model.x][i],
y: source.data[this.model.y][i],
z: source.data[this.model.z][i],
})
}
return data
... | get_data | identifier_name |
surface3d.ts | // This file contains the JavaScript (TypeScript) implementation
// for a Bokeh custom extension. The "surface3d.py" contains the
// python counterpart.
//
// This custom model wraps one part of the third-party vis.js library:
//
// http://visjs.org/index.html
//
// Making it easy to hook up python data analytics t... |
connect_signals(): void {
super.connect_signals()
// Set listener so that when the Bokeh data source has a change
// event, we can process the new data
this.connect(this.model.data_source.change, () => this._graph.setData(this.get_data()))
}
// This is the callback executed when the Bokeh data ... | {
super.render()
// Create a new Graph3s using the vis.js API. This assumes the vis.js has
// already been loaded (e.g. in a custom app template). In the future Bokeh
// models will be able to specify and load external scripts automatically.
//
// Views create <div> elements by default, accessib... | identifier_body |
form_group_name.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core... | * `FormGroup` instance you passed into `FormGroupDirective`.
*
* Nested form groups can come in handy when you want to validate a sub-group of a
* form separately from the rest or when you'd like to group the values of certain
* controls into their own nested object.
*
* **Access the group**: You can access the ... | *
* It accepts the string name of the nested `FormGroup` you want to link, and
* will look for a `FormGroup` registered with that name in the parent | random_line_split |
form_group_name.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core... |
get path(): string[] { return controlPath(this.name, this._parent); }
get validator(): ValidatorFn|null { return composeValidators(this._validators); }
get asyncValidator(): AsyncValidatorFn|null {
return composeAsyncValidators(this._asyncValidators);
}
private _checkParentType(): void {
if (_has... | {
return this._parent ? <FormGroupDirective>this._parent.formDirective : null;
} | identifier_body |
form_group_name.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core... | extends AbstractFormGroupDirective implements OnInit, OnDestroy {
@Input('formGroupName') name: string;
constructor(
@Optional() @Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValid... | FormGroupName | identifier_name |
form_group_name.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, Host, Inject, Input, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core... |
}
}
function _hasInvalidParent(parent: ControlContainer): boolean {
return !(parent instanceof FormGroupName) && !(parent instanceof FormGroupDirective) &&
!(parent instanceof FormArrayName);
}
| {
ReactiveErrors.arrayParentException();
} | conditional_block |
thread_dummy.rs | // Copyright 2014 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 ... | #[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "recently introduced")]
pub fn park_timeout(_: Duration) {
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn unpark(&self) {
}
#[stable(feature = "rust1", since = ... |
}
/// Deprecated: use module-level free function. | random_line_split |
thread_dummy.rs | // Copyright 2014 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 ... |
#[stable(feature = "rust1", since = "1.0.0")]
pub fn yield_now() {
}
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn panicking() -> bool {
unwind::panicking()
}
#[stable(feature = "rust1", since = "1.0.0")]
pub fn park() {
}
#[unstable(feature = "std_misc", reason = "recently introduced, depen... | {
Thread
} | identifier_body |
thread_dummy.rs | // Copyright 2014 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 ... | () -> Thread {
Thread
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[unstable(feature = "std_misc", reason = "name may change")]
pub fn yield_now() {
}
#[deprecated(since = "1.0.0", reason = "use module-level free function")]
#[inline]
#[stable(f... | current | identifier_name |
logger.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use core::fmt::Write;
use log::{LogLevelFilter, LogMetadata, SetLoggerError, ShutdownLoggerError};
pub struct | ;
impl SimpleLogger {
pub fn new() -> Self {
SimpleLogger
}
pub fn init(&self) -> Result<(), SetLoggerError> {
unsafe {
log::set_logger_raw(move |max_log_level| {
max_log_level.set(LogLevelFilter::Info);
self.ptr()
})
}
}
... | SimpleLogger | identifier_name |
logger.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use core::fmt::Write;
use log::{LogLevelFilter, LogMetadata, SetLoggerError, ShutdownLoggerError};
pub struct SimpleLogger;
i... | log::shutdown_logger_raw().map(|logger| {
let logger = unsafe { &*(logger as *const SimpleLogger) };
logger.flush();
})
} | }
pub fn shutdown() -> Result<(), ShutdownLoggerError> { | random_line_split |
server.py | import tornado.ioloop
import tornado.web
import socket
import os
import sys
import time
import signal
# import datetime
import h5py
from datetime import datetime, date
import tornado.httpserver
from browserhandler import BrowseHandler
from annotationhandler import AnnotationHandler
from projecthandler import Proje... | "static_path": 'resources',
}
tornado.web.Application.__init__(self, handlers, **settings)
import numpy as np
class Server():
def __init__(self, name, port):
self.name = name
self.port = port
application = Application()
self.http_server = tornado.httpserver.HTTPServer( appl... |
settings = {
"template_path": 'resources', | random_line_split |
server.py | import tornado.ioloop
import tornado.web
import socket
import os
import sys
import time
import signal
# import datetime
import h5py
from datetime import datetime, date
import tornado.httpserver
from browserhandler import BrowseHandler
from annotationhandler import AnnotationHandler
from projecthandler import Proje... |
stop_loop()
def sig_handler(sig, frame):
msg = 'caught interrupt signal: %s'%sig
Utility.print_msg ('\033[93m'+ msg + '\033[0m', True)
tornado.ioloop.IOLoop.instance().add_callback(shutdown)
def shutdown():
server.stop()
def main():
global server
signal.signal(signal.SIGTERM, sig_han... | io_loop.stop()
Utility.print_msg ('\033[93m'+ 'shutdown' + '\033[0m', True, 'done') | conditional_block |
server.py | import tornado.ioloop
import tornado.web
import socket
import os
import sys
import time
import signal
# import datetime
import h5py
from datetime import datetime, date
import tornado.httpserver
from browserhandler import BrowseHandler
from annotationhandler import AnnotationHandler
from projecthandler import Proje... | ():
server.stop()
def main():
global server
signal.signal(signal.SIGTERM, sig_handler)
signal.signal(signal.SIGINT, sig_handler)
port = 8888
name = 'icon webserver'
server = Server(name, port)
server.start()
if __name__ == "__main__":
main()
| shutdown | identifier_name |
server.py | import tornado.ioloop
import tornado.web
import socket
import os
import sys
import time
import signal
# import datetime
import h5py
from datetime import datetime, date
import tornado.httpserver
from browserhandler import BrowseHandler
from annotationhandler import AnnotationHandler
from projecthandler import Proje... |
def print_status(self):
Utility.print_msg ('.')
Utility.print_msg ('\033[93m'+ self.name + ' running/' + '\033[0m', True)
Utility.print_msg ('.')
Utility.print_msg ('open ' + '\033[92m'+'http://' + self.ip + ':' + str(self.port) + '/' + '\033[0m', True)
Utility.print_msg ('... | self.name = name
self.port = port
application = Application()
self.http_server = tornado.httpserver.HTTPServer( application )
hostname = socket.gethostname()
print 'hostname:', hostname
self.ip = hostname #socket.gethostbyname( hostname ) | identifier_body |
objimport.py | #
# Copyright 2011-2019 Universidad Complutense de Madrid
#
# This file is part of Numina
#
# SPDX-License-Identifier: GPL-3.0+
# License-Filename: LICENSE.txt
#
"""Import objects by name"""
import importlib
import inspect
import warnings
def import_object(path):
"""Import an object given its fully qualified na... |
# avoid last part for the moment
cls = spl[-1]
mods = '.'.join(spl[:-1])
mm = importlib.import_module(mods)
# try to get the last part as an attribute
try:
obj = getattr(mm, cls)
return obj
except AttributeError:
pass
# Try to import the last part
rr = impo... | return importlib.import_module(path) | conditional_block |
objimport.py | #
# Copyright 2011-2019 Universidad Complutense de Madrid
#
# This file is part of Numina
#
# SPDX-License-Identifier: GPL-3.0+
# License-Filename: LICENSE.txt
#
"""Import objects by name"""
import importlib
import inspect
import warnings
def import_object(path):
"""Import an object given its fully qualified na... | warnings.warn(
"use numina.util.fqn.fully_qualified_name instead",
DeprecationWarning, stacklevel=2
)
import numina.util.fqn as fqn
return fqn.fully_qualified_name(obj, sep) | identifier_body | |
objimport.py | #
# Copyright 2011-2019 Universidad Complutense de Madrid
#
# This file is part of Numina
#
# SPDX-License-Identifier: GPL-3.0+
# License-Filename: LICENSE.txt
#
"""Import objects by name"""
import importlib
import inspect
import warnings
def | (path):
"""Import an object given its fully qualified name."""
spl = path.split('.')
if len(spl) == 1:
return importlib.import_module(path)
# avoid last part for the moment
cls = spl[-1]
mods = '.'.join(spl[:-1])
mm = importlib.import_module(mods)
# try to get the last part as a... | import_object | identifier_name |
objimport.py | #
# Copyright 2011-2019 Universidad Complutense de Madrid
#
# This file is part of Numina
#
# SPDX-License-Identifier: GPL-3.0+
# License-Filename: LICENSE.txt
#
"""Import objects by name"""
import importlib
import inspect
import warnings
def import_object(path):
"""Import an object given its fully qualified na... | mm = importlib.import_module(mods)
# try to get the last part as an attribute
try:
obj = getattr(mm, cls)
return obj
except AttributeError:
pass
# Try to import the last part
rr = importlib.import_module(path)
return rr
def fully_qualified_name(obj, sep='.'):
... | random_line_split | |
types.py | from typing import Any, Dict, List, Union
from flask import abort, flash, g, render_template, url_for
from flask_babel import format_number, lazy_gettext as _
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from openatlas import app
from openatlas.database.connect import Transaction
from op... |
nodes[type_][node] = render_template(
'forms/tree_select_item.html',
name=sanitize(node.name),
data=walk_tree(Node.get_nodes(node.name)))
return render_template(
'types/index.html',
nodes=nodes,
title=_('types'),
crumbs=[_('types')])
@ap... | type_ = 'value' | conditional_block |
types.py | from typing import Any, Dict, List, Union
from flask import abort, flash, g, render_template, url_for
from flask_babel import format_number, lazy_gettext as _
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from openatlas import app
from openatlas.database.connect import Transaction
from op... | (nodes: List[int]) -> List[Dict[str, Any]]:
items = []
for id_ in nodes:
item = g.nodes[id_]
count_subs = f' ({format_number(item.count_subs)})' \
if item.count_subs else ''
items.append({
'id': item.id,
'href': url_for('entity_view', id_=item.id),
... | walk_tree | identifier_name |
types.py | from typing import Any, Dict, List, Union
from flask import abort, flash, g, render_template, url_for
from flask_babel import format_number, lazy_gettext as _
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from openatlas import app
from openatlas.database.connect import Transaction
from op... |
@app.route('/types')
@required_group('readonly')
def node_index() -> str:
nodes: Dict[str, Dict[Entity, str]] = \
{'standard': {}, 'custom': {}, 'places': {}, 'value': {}}
for node in g.nodes.values():
if node.root:
continue
type_ = 'custom'
if node.class_.name == ... | items = []
for id_ in nodes:
item = g.nodes[id_]
count_subs = f' ({format_number(item.count_subs)})' \
if item.count_subs else ''
items.append({
'id': item.id,
'href': url_for('entity_view', id_=item.id),
'a_attr': {'href': url_for('entity_view... | identifier_body |
types.py | from typing import Any, Dict, List, Union
from flask import abort, flash, g, render_template, url_for
from flask_babel import format_number, lazy_gettext as _
from werkzeug.utils import redirect
from werkzeug.wrappers import Response
from openatlas import app
from openatlas.database.connect import Transaction
from op... | tab = 'value'
else:
tab = 'custom'
return redirect(
f"{url_for('node_index')}#menu-tab-{tab}_collapse-{root.id}")
getattr(form, str(root.id)).data = node.id
return render_template(
'types/move.html',
table=Table(
header=['#', _('sel... | tab = 'standard'
elif node.value_type: # pragma: no cover | random_line_split |
UI.py | # -*- coding: utf-8 -*-
# -- cmd -- pip install PyUserInput
import time
import win32gui
import win32con
import PIL.ImageGrab
from pymouse import PyMouse
PIECE_X = 44
PIECE_Y = 40
NUM_X = 14
NUM_Y = 10
def getOrigin():
cwllk = '宠物连连看'.decode('utf8')
hwnd = win32gui.FindWindow("#32770", cwllk)
print hwnd
... | ic()
pic.save("screenshot" + ".png")
click((0,0))
click((0,9))
click((13,9))
click((13,0))
pause()
| conditional_block | |
UI.py | # -*- coding: utf-8 -*-
# -- cmd -- pip install PyUserInput
import time
import win32gui
import win32con
import PIL.ImageGrab
from pymouse import PyMouse
PIECE_X = 44
PIECE_Y = 40
NUM_X = 14
NUM_Y = 10
def getOrigin():
cwllk = '宠物连连看'.decode('utf8')
hwnd = win32gui.FindWindow("#32770", cwllk)
print hwnd
... | '''
pos: (x, y) # (0, 0) for top left piece
'''
m = PyMouse()
m.click(pos[0],pos[1])
# only for test
if __name__ == '__main__':
pic = getPic()
pic.save("screenshot" + ".png")
click((0,0))
click((0,9))
click((13,9))
click((13,0))
pause()
| :
| identifier_name |
UI.py | # -*- coding: utf-8 -*-
# -- cmd -- pip install PyUserInput
import time
import win32gui
import win32con
import PIL.ImageGrab
from pymouse import PyMouse
PIECE_X = 44
PIECE_Y = 40
NUM_X = 14
NUM_Y = 10
def getOrigin():
cwllk = '宠物连连看'.decode('utf8')
hwnd = win32gui.FindWindow("#32770", cwllk)
print hwnd
... | time.sleep(0.5)
#print rect
#newRect = (rect[0] + 58, rect[1] + 104, rect[0] + 674, rect[1] + 504)
return rect
def getPic(RECT):
"""
RECT = (x1,y1,x2,y2)
"""
pic = PIL.ImageGrab.grab(getOrigin())
return pic
def pause():
m = PyMouse()
m.click(RECT[0] -58 + 307, REC... | win32gui.SetForegroundWindow(hwnd)
rect = win32gui.GetWindowRect(hwnd) | random_line_split |
UI.py | # -*- coding: utf-8 -*-
# -- cmd -- pip install PyUserInput
import time
import win32gui
import win32con
import PIL.ImageGrab
from pymouse import PyMouse
PIECE_X = 44
PIECE_Y = 40
NUM_X = 14
NUM_Y = 10
def getOrigin():
cwllk = '宠物连连看'.decode('utf8')
hwnd = win32gui.FindWindow("#32770", cwllk)
print hwnd
... | e():
m = PyMouse()
m.click(RECT[0] -58 + 307, RECT[1] - 104 + 62)
time.sleep(0.5)
def click(pos):
'''
pos: (x, y) # (0, 0) for top left piece
'''
m = PyMouse()
m.click(pos[0],pos[1])
# only for test
if __name__ == '__main__':
pic = getPic()
pic.save("screenshot" + ".png"... | CT = (x1,y1,x2,y2)
"""
pic = PIL.ImageGrab.grab(getOrigin())
return pic
def paus | identifier_body |
edc_dashboard_extras.py | from django import template
from django.urls.base import reverse
from urllib.parse import urljoin, parse_qsl, urlencode, unquote
register = template.Library()
class Number:
def __init__(self, number=None, url=None, current=None):
self.number = number
self.url = url
self.active = 'active'... |
for page in page_numbers(page_obj.number, paginator.num_pages):
current = page_obj.number == page
url = '#'
if not current:
url = url_maker.url(page)
numbers.append(
Number(number=page, url=url, current=current))
sub_text ... | next_url = url_maker.url(page_obj.next_page_number())
last_url = url_maker.url(paginator.num_pages) | conditional_block |
edc_dashboard_extras.py | from django import template
from django.urls.base import reverse
from urllib.parse import urljoin, parse_qsl, urlencode, unquote
register = template.Library()
class Number:
def __init__(self, number=None, url=None, current=None):
self.number = number
self.url = url
self.active = 'active'... | (self):
return f'{self.__class__.__name__}<number={self.number} {self.active}>'
class UrlMaker:
def __init__(self, base=None, querystring=None):
self.base = base
self.querystring = querystring
def url(self, page):
url = urljoin(self.base, str(page)) + '/'
if self.query... | __repr__ | identifier_name |
edc_dashboard_extras.py | from django import template
from django.urls.base import reverse
from urllib.parse import urljoin, parse_qsl, urlencode, unquote
register = template.Library()
class Number:
def __init__(self, number=None, url=None, current=None):
self.number = number
self.url = url
self.active = 'active'... |
def page_numbers(page, numpages, display=None):
"""Returns a list of x integers (display) relative to the value of n
where n > 0 and the length of the list cannot exceed count.
"""
page_numbers = None
if page and numpages:
min_n = page - 5
min_n = 1 if min_n <= 0 else min_n
... | def __init__(self, base=None, querystring=None):
self.base = base
self.querystring = querystring
def url(self, page):
url = urljoin(self.base, str(page)) + '/'
if self.querystring:
return '?'.join([url, self.querystring])
return url | identifier_body |
edc_dashboard_extras.py | from django import template
from django.urls.base import reverse
from urllib.parse import urljoin, parse_qsl, urlencode, unquote
register = template.Library()
class Number:
def __init__(self, number=None, url=None, current=None):
self.number = number
self.url = url
self.active = 'active'... | if show:
url_maker = UrlMaker(base=paginator_url, querystring=querystring)
if page_obj.has_previous():
first_url = url_maker.url(1)
previous_url = url_maker.url(page_obj.previous_page_number())
if page_obj.has_next():
next_url = url_maker.url(page_obj.next... | querystring = querystring.split('?')[1]
query_dict = parse_qsl(querystring)
querystring = unquote(urlencode(query_dict)) | random_line_split |
calc_length.py | # -*- coding: utf-8 -*-
"""
Created on 27/04/2015
@author: C&C - HardSoft
"""
from util.HOFs import *
from util.CobolPatterns import *
from util.homogenize import Homogenize
def calc_length(copy):
if isinstance(copy, list):
book = copy
else:
if isinstance(copy, str):
book = ... |
if match['occurs']:
occurs += 1
attrib = {}
attrib['occ'] = int(match['occurs'])
attrib['level'] = level
attrib['length'] = 0
dicoccurs[occurs] = attrib
if match['pic']:
if occurs:
dicoccurs[occurs]['l... | break | conditional_block |
calc_length.py | # -*- coding: utf-8 -*-
"""
Created on 27/04/2015
@author: C&C - HardSoft
"""
from util.HOFs import *
from util.CobolPatterns import *
from util.homogenize import Homogenize
def calc_length(copy):
| level_redefines = 0
for line in lines:
match = CobolPatterns.row_pattern.match(line.strip())
if not match:
continue
match = match.groupdict()
if not match['level']:
continue
if 'REDEFINES' in line and not match['redefines']:
match['re... | if isinstance(copy, list):
book = copy
else:
if isinstance(copy, str):
book = copy.splitlines()
else:
book = []
lines = Homogenize(book)
havecopy = filter(isCopy, lines)
if havecopy:
bkm = ''.join(havecopy[0].split('COPY')[1].replace('.', '').spl... | identifier_body |
calc_length.py | # -*- coding: utf-8 -*-
"""
Created on 27/04/2015
@author: C&C - HardSoft
"""
from util.HOFs import *
from util.CobolPatterns import *
from util.homogenize import Homogenize
def | (copy):
if isinstance(copy, list):
book = copy
else:
if isinstance(copy, str):
book = copy.splitlines()
else:
book = []
lines = Homogenize(book)
havecopy = filter(isCopy, lines)
if havecopy:
bkm = ''.join(havecopy[0].split('COPY')[1].replace(... | calc_length | identifier_name |
calc_length.py | # -*- coding: utf-8 -*-
"""
Created on 27/04/2015
@author: C&C - HardSoft
"""
from util.HOFs import *
from util.CobolPatterns import *
from util.homogenize import Homogenize
def calc_length(copy):
if isinstance(copy, list):
book = copy
else:
if isinstance(copy, str):
book = ... | attrib['occ'] = int(match['occurs'])
attrib['level'] = level
attrib['length'] = 0
dicoccurs[occurs] = attrib
if match['pic']:
dicoccurs[occurs]['length'] += FieldLength(match['pic'], match['usage'])
... | random_line_split | |
replaceShorthandObjectMethod.js | import * as t from "babel-types";
import * as util from "./util";
// this function converts a shorthand object generator method into a normal
// (non-shorthand) object property which is a generator function expression. for
// example, this:
//
// var foo = {
// *bar(baz) { return 5; }
// }
//
// should be replace... |
const parameters = path.node.params.map(function (param) {
return t.cloneDeep(param);
})
const functionExpression = t.functionExpression(
null, // id
parameters, // params
t.cloneDeep(path.node.body), // body
path.node.generator,
path.node.async
);
util.replaceWithOrRemove(path,
... | {
return path;
} | conditional_block |
replaceShorthandObjectMethod.js | import * as t from "babel-types";
import * as util from "./util";
// this function converts a shorthand object generator method into a normal
// (non-shorthand) object property which is a generator function expression. for
// example, this:
//
// var foo = {
// *bar(baz) { return 5; }
// }
//
// should be replace... | const functionExpression = t.functionExpression(
null, // id
parameters, // params
t.cloneDeep(path.node.body), // body
path.node.generator,
path.node.async
);
util.replaceWithOrRemove(path,
t.objectProperty(
t.cloneDeep(path.node.key), // key
functionExpression, //value
... | {
if (!path.node || !t.isFunction(path.node)) {
throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths.");
}
// this function only replaces shorthand object methods (called ObjectMethod
// in Babel-speak).
if (!t.isObjectMethod(path.node)) {
return path;
}
//... | identifier_body |
replaceShorthandObjectMethod.js | import * as t from "babel-types";
import * as util from "./util";
// this function converts a shorthand object generator method into a normal
// (non-shorthand) object property which is a generator function expression. for
// example, this:
//
// var foo = {
// *bar(baz) { return 5; }
// }
//
// should be replace... | (path) {
if (!path.node || !t.isFunction(path.node)) {
throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths.");
}
// this function only replaces shorthand object methods (called ObjectMethod
// in Babel-speak).
if (!t.isObjectMethod(path.node)) {
return path;
... | replaceShorthandObjectMethod | identifier_name |
replaceShorthandObjectMethod.js | import * as t from "babel-types";
import * as util from "./util";
// this function converts a shorthand object generator method into a normal | // example, this:
//
// var foo = {
// *bar(baz) { return 5; }
// }
//
// should be replaced with:
//
// var foo = {
// bar: function*(baz) { return 5; }
// }
//
// to do this, it clones the parameter array and the body of the object generator
// method into a new FunctionExpression.
//
// this method can be ... | // (non-shorthand) object property which is a generator function expression. for | random_line_split |
same-origin-test.js | // Copyright 2018 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.
function waitUntilIdle() {
return new Promise(resolve=>{
window.requestIdleCallback(()=>resolve());
});
}
(async function() {
TestRunner.addRes... |
// There are two scripts:
// [A] http://127.0.0.1:8000/devtools/resources/v8-cache-script.cgi
// [B] http://localhost:8000/devtools/resources/v8-cache-script.cgi
// An iframe that loads [A].
// The script is executed as a parser-inserted script,
// to keep the ScriptResource on the MemoryCache.
// Scrip... |
// Clear browser cache to avoid any existing entries for the fetched
// scripts in the cache.
SDK.multitargetNetworkManager.clearBrowserCache(); | random_line_split |
same-origin-test.js | // Copyright 2018 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.
function waitUntilIdle() {
return new Promise(resolve=>{
window.requestIdleCallback(()=>resolve());
});
}
(async function() {
TestRunner.addRes... |
async function expectationComment(msg) {
await stopAndPrintTimeline();
TestRunner.addResult(msg);
await PerformanceTestRunner.startTimeline();
}
// Load [A] thrice. With the current V8 heuristics (defined in
// third_party/blink/renderer/bindings/core/v8/v8_code_cache.cc) we produce
// cache on... | {
await PerformanceTestRunner.stopTimeline();
await PerformanceTestRunner.printTimelineRecordsWithDetails(
TimelineModel.TimelineModel.RecordType.CompileScript,
TimelineModel.TimelineModel.RecordType.CacheScript);
} | identifier_body |
same-origin-test.js | // Copyright 2018 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.
function | () {
return new Promise(resolve=>{
window.requestIdleCallback(()=>resolve());
});
}
(async function() {
TestRunner.addResult(`Tests V8 code cache for javascript resources\n`);
await TestRunner.loadLegacyModule('timeline'); await TestRunner.loadTestModule('performance_test_runner');
await TestRunner.showP... | waitUntilIdle | identifier_name |
analysis.py | # python3
# pylint: disable=g-bad-file-header
# Copyright 2019 DeepMind Technologies Limited. 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... | )
p += gg.geom_hline(gg.aes(yintercept=BASE_REGRET),
linetype='dashed', alpha=0.4, size=1.75)
return p
def plot_seeds(df_in: pd.DataFrame,
sweep_vars: Optional[Sequence[str]] = None) -> gg.ggplot:
"""Plot the returns through time individually by run."""
df = dc_preprocess... | df_in=df,
group_col='optimal_horizon',
episode=sweep.NUM_EPISODES,
sweep_vars=sweep_vars | random_line_split |
analysis.py | # python3
# pylint: disable=g-bad-file-header
# Copyright 2019 DeepMind Technologies Limited. 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... | (df: pd.DataFrame,
sweep_vars: Optional[Sequence[str]] = None) -> gg.ggplot:
"""Plots the average regret through time by optimal_horizon."""
df = dc_preprocess(df_in=df)
p = plotting.plot_regret_learning(
df_in=df,
group_col='optimal_horizon',
sweep_vars=sweep_vars,
max_e... | plot_learning | identifier_name |
analysis.py | # python3
# pylint: disable=g-bad-file-header
# Copyright 2019 DeepMind Technologies Limited. 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... |
else:
if 'seed' in df.columns:
print('WARNING: seed renamed to "mapping_seed" for compatibility.')
df['mapping_seed'] = df.seed
else:
print('ERROR: outdated bsuite run, please relaunch.')
return df
def dc_preprocess(df_in: pd.DataFrame) -> pd.DataFrame:
"""Preprocess discounting chain... | df.loc[nan_seeds, 'mapping_seed'] = df.loc[nan_seeds, 'seed']
print('WARNING: seed renamed to "mapping_seed" for compatibility.') | conditional_block |
analysis.py | # python3
# pylint: disable=g-bad-file-header
# Copyright 2019 DeepMind Technologies Limited. 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... |
def dc_preprocess(df_in: pd.DataFrame) -> pd.DataFrame:
"""Preprocess discounting chain data for use with regret metrics."""
df = df_in.copy()
df = _mapping_seed_compatibility(df)
df['optimal_horizon'] = _HORIZONS[
(df.mapping_seed % len(_HORIZONS)).astype(int)]
df['total_regret'] = 1.1 * df.episode ... | """Utility function to maintain compatibility with old bsuite runs."""
# Discounting chain kwarg "seed" was renamed to "mapping_seed"
if 'mapping_seed' in df.columns:
nan_seeds = df.mapping_seed.isna()
if np.any(nan_seeds):
df.loc[nan_seeds, 'mapping_seed'] = df.loc[nan_seeds, 'seed']
print('WAR... | identifier_body |
base.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
from collections import OrderedDict
from django.core.management.base import BaseCommand, CommandParser
from django.core.management.color import no_style
def add_builtin_arguments(parser):
parser.add_argume... |
if options.get('stdout'):
command.stdout._out = options.get('stdout')
if options.get('stderr'):
command.stderr._out = options.get('stderr')
command.handle(*args, **options)
else:
self.print_help('manage.py', 'cms')
| command.style = no_style()
command.stderr.style_func = None | conditional_block |
base.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
from collections import OrderedDict
from django.core.management.base import BaseCommand, CommandParser
from django.core.management.color import no_style
def add_builtin_arguments(parser):
| parser.add_argument('--pythonpath',
help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".')
parser.add_argument('--traceback', action='store_true',
help='Raise on CommandError exceptions')
parser.add_argument('--no-color', action='store_true', dest='no_color', d... | parser.add_argument(
'--noinput',
action='store_false',
dest='interactive',
default=True,
help='Tells Django CMS to NOT prompt the user for input of any kind.'
)
# These are taking "as-is" from Django's management base
# management command.
parser.add_argument('-... | identifier_body |
base.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
from collections import OrderedDict
from django.core.management.base import BaseCommand, CommandParser
from django.core.management.color import no_style
def add_builtin_arguments(parser):
parser.add_argume... | command.stderr.style_func = None
if options.get('stdout'):
command.stdout._out = options.get('stdout')
if options.get('stderr'):
command.stderr._out = options.get('stderr')
command.handle(*args, **options)
else:
self... | def handle(self, *args, **options):
if options[self.subcommand_dest] in self.instances:
command = self.instances[options[self.subcommand_dest]]
if options.get('no_color'):
command.style = no_style() | random_line_split |
base.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import os
from collections import OrderedDict
from django.core.management.base import BaseCommand, CommandParser
from django.core.management.color import no_style
def add_builtin_arguments(parser):
parser.add_argume... | (self, parser):
self.instances = {}
if self.subcommands:
subparsers = parser.add_subparsers(dest=self.subcommand_dest)
for command, cls in self.subcommands.items():
instance = cls(self.stdout._out, self.stderr._out)
instance.style = self.style
... | add_arguments | identifier_name |
parser.rs | use std::str;
use combine::*;
use combine::byte::*;
use combine::primitives::RangeStream;
use combine::range::*;
use types::Source;
/// Whether or not a character is valid for a nickname when it is not the first character.
fn is_nick_trailing_char(c: u8) -> bool {
match c {
b'A'...b'Z'
| b'a'...b... | ),
host().map(|host| {
let host = unsafe { str::from_utf8_unchecked(host) };
Source::Server { host: host.into() }
})
)
}
| {
let nick = || recognize((letter(), skip_many(satisfy(is_nick_trailing_char))));
let ident = || take_while1(is_ident_char);
let host = || take_while1(is_host_char);
let user = || (nick().skip(byte(b'!')), ident().skip(byte(b'@')), host());
choice!(
try(
user().and_then(|(nick,... | identifier_body |
parser.rs | use std::str;
use combine::*;
use combine::byte::*;
use combine::primitives::RangeStream;
use combine::range::*;
use types::Source;
/// Whether or not a character is valid for a nickname when it is not the first character.
fn | (c: u8) -> bool {
match c {
b'A'...b'Z'
| b'a'...b'z'
| b'0'...b'9'
| b'['
| b']'
| b'`'
| b'^'
| b'\\'
| b'-'
| b'{'
| b'}' => true,
_ => false,
}
}
/// Whether or not a character is valid for an ident.
///
/// RFC... | is_nick_trailing_char | identifier_name |
parser.rs | use std::str;
use combine::*;
use combine::byte::*;
use combine::primitives::RangeStream;
use combine::range::*;
use types::Source;
/// Whether or not a character is valid for a nickname when it is not the first character.
fn is_nick_trailing_char(c: u8) -> bool {
match c {
b'A'...b'Z'
| b'a'...b... | }
}
/// Parse the source of a message.
pub fn source<'a, I>() -> impl Parser<Input = I, Output = Source>
where
I: RangeStream<Item = u8, Range = &'a [u8]>,
I::Error: ParseError<u8, &'a [u8], I::Position>,
<I::Error as ParseError<I::Item, I::Range, I::Position>>::StreamError: From<str::Utf8Error>,
{
... | _ => true, | random_line_split |
HomeIcon.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | ({ className, fill, filled = false, ...iconProps }: Props) {
return (
<Icon
className={classNames(className, 'icon-outline', { 'is-filled': filled })}
style={{ color: fill || colors.orange }}
{...iconProps}>
<g transform="matrix(0.870918,0,0,0.870918,0.978227,0.978227)">
<path d="M... | HomeIcon | identifier_name |
HomeIcon.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | import Icon, { IconProps } from './Icon';
interface Props extends IconProps {
filled?: boolean;
}
export default function HomeIcon({ className, fill, filled = false, ...iconProps }: Props) {
return (
<Icon
className={classNames(className, 'icon-outline', { 'is-filled': filled })}
style={{ color: f... | import * as React from 'react';
import { colors } from '../../app/theme'; | random_line_split |
HomeIcon.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... | {
return (
<Icon
className={classNames(className, 'icon-outline', { 'is-filled': filled })}
style={{ color: fill || colors.orange }}
{...iconProps}>
<g transform="matrix(0.870918,0,0,0.870918,0.978227,0.978227)">
<path d="M15.9,7.8L8.2,0.1C8.1,0 7.9,0 7.8,0.1L0.1,7.8C0,7.9 0,8.1 0.... | identifier_body | |
login.js | (function(){
function isValid($, eventName){
var valid = true;
$.each(function(i, el){
valid = valid && el.dispatchEvent(new Event(eventName));
});
return valid;
}
function setHandler(els){
els.each(function(i, el){
if(!(el instanceof HT... |
if(el instanceof HTMLFormElement){
$Form = $(el).on("submit keyup",formHnd);
$Input = $(el).find("input, textarea").on("input invalid",inputHnd);
} else if(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement){
$Input =... | e.target.removeAttribute("w-is-equal");
}
e.target.dispatchEvent(new Event(e.target.checkValidity() && isEqual ? "validdata" : "invaliddata"));
}; | random_line_split |
login.js | (function(){
function isValid($, eventName){
var valid = true;
$.each(function(i, el){
valid = valid && el.dispatchEvent(new Event(eventName));
});
return valid;
}
function setHandler(els){
els.each(function(i, el){
if(!(el instanceof HT... | }
;
if(el instanceof HTMLFormElement){
$Form = $(el).on("submit keyup",formHnd);
$Input = $(el).find("input, textarea").on("input invalid",inputHnd);
} else if(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement){
... | {
if(e.type == "invalid") return e.target.dispatchEvent(new Event("invaliddata"));
try {
var curretPos = e.target.selectionStart;
e.target.value = e.target.value;
curretPos = curretPos > e.target.value.length ? e.target.value.length : ... | identifier_body |
login.js | (function(){
function | ($, eventName){
var valid = true;
$.each(function(i, el){
valid = valid && el.dispatchEvent(new Event(eventName));
});
return valid;
}
function setHandler(els){
els.each(function(i, el){
if(!(el instanceof HTMLInputElement || el instanceof HT... | isValid | identifier_name |
sha256.js | , 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4... | i*4)) & 0xf; s += v.toString(16); }
return | conditional_block | |
sha256.js | only deals with byte-streams
msg = msg.utf8Encode();
| 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
... | // constants [§4.2.2]
var K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
| random_line_split |
stan.js | /* ========================================================================
* STAN Utils: Stan
* Author: Andrew Womersley
* ======================================================================== */
(function($STAN, CustomConfig) {
'use strict';
var Tag = !!CustomConfig.tag ? CustomConfig.tag : 'body';
va... | data: {
mobile: true,
desktop: false
}
},
sm: {
min_width: 768,
classes: 'device-sm mobile',
data: {
mobile: true,
desktop: false
}
},
md: {
min_width: 992,
classes: 'device-md desktop',
data: {
mobile: false,
... | xs: {
min_width: 0,
classes: 'device-xs mobile', | random_line_split |
ada_radio.py | # Only display reload the library if in PLAYER mode
def cycle_options(radio,direction):
log.message("cycle_options " + str(direction) , log.DEBUG)
option = radio.getOption()
if direction == UP:
option += 1
else:
option -= 1
# Don;t display reload if not player mode
source = radio.getSource()
if option == ... | index = leng - 1 | conditional_block | |
ada_radio.py | displayWakeUpMessage(lcd)
radio.setDisplayMode(radio.MODE_TIME)
if radio.volumeChanged():
lcd.line2("Volume " + str(radio.getVolume()))
time.sleep(0.5)
time.sleep(0.1)
def status(self):
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf... |
# Alarm wakeup function
if display_mode == radio.MODE_SLEEP and radio.alarmFired():
log.message("Alarm fired", log.INFO)
unmuteRadio(lcd,radio) | random_line_split | |
ada_radio.py | log.DEBUG)
if radio.alarmActive() and not radio.getTimer() and option == radio.ALARMSET:
radio.setDisplayMode(radio.MODE_SLEEP)
radio.mute()
else:
radio.setDisplayMode(radio.M... | mount_share | identifier_name | |
ada_radio.py | )
time.sleep(0.2)
interrupt = True
elif lcd.buttonPressed(lcd.UP):
log.message("UP switch", log.DEBUG)
if display_mode != radio.MODE_SLEEP:
radio.unmute()
if display_mode == radio.MODE_SOURCE:
radio.toggleSource()
radio.setReload(True)
elif display_mode == radio.MODE_SEARCH:
scroll_s... | rss_line = rss.getFeed()
lcd.setScrollSpeed(0.2) # Display rss feeds a bit quicker
lcd.scroll2(rss_line,interrupt)
return | identifier_body | |
features.rs | //! Feature tests for OS functionality
pub use self::os::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod os {
use crate::sys::utsname::uname;
// Features:
// * atomic cloexec on socket: 2.6.27
// * pipe2: 2.6.27
// * accept4: 2.6.28
static VERS_UNKNOWN: usize = 1;
static VE... | () -> bool {
kernel_version() >= VERS_2_6_27
}
#[test]
pub fn test_parsing_kernel_version() {
assert!(kernel_version() > 0);
}
}
#[cfg(any(target_os = "illumos"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
... | socket_atomic_cloexec | identifier_name |
features.rs | //! Feature tests for OS functionality
pub use self::os::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod os {
use crate::sys::utsname::uname;
// Features:
// * atomic cloexec on socket: 2.6.27
// * pipe2: 2.6.27
// * accept4: 2.6.28
static VERS_UNKNOWN: usize = 1;
static VE... | else if major >= 2 {
if minor >= 7 {
VERS_UNKNOWN
} else if minor >= 6 {
if patch >= 28 {
VERS_2_6_28
} else if patch >= 27 {
VERS_2_6_27
} else {
VERS_2_6_18
... | {
VERS_3
} | conditional_block |
features.rs | //! Feature tests for OS functionality
pub use self::os::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod os {
use crate::sys::utsname::uname;
// Features:
// * atomic cloexec on socket: 2.6.27
// * pipe2: 2.6.27
// * accept4: 2.6.28
static VERS_UNKNOWN: usize = 1;
static VE... | target_os = "openbsd", target_os = "netbsd",
target_os = "redox", target_os = "fuchsia",
target_os = "solaris"))]
mod os {
/// Check if the OS supports atomic close-on-exec for sockets
pub fn socket_atomic_cloexec() -> bool {
false
}
} | #[cfg(any(target_os = "macos", target_os = "freebsd",
target_os = "dragonfly", target_os = "ios", | random_line_split |
features.rs | //! Feature tests for OS functionality
pub use self::os::*;
#[cfg(any(target_os = "linux", target_os = "android"))]
mod os {
use crate::sys::utsname::uname;
// Features:
// * atomic cloexec on socket: 2.6.27
// * pipe2: 2.6.27
// * accept4: 2.6.28
static VERS_UNKNOWN: usize = 1;
static VE... |
fn parse_kernel_version() -> usize {
let u = uname();
let mut curr: usize = 0;
let mut major: usize = 0;
let mut minor: usize = 0;
let mut patch: usize = 0;
for b in u.release().bytes() {
if curr >= 3 {
break;
}
... | {
*dst *= 10;
*dst += (b - b'0') as usize;
} | identifier_body |
ajax.js | // ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
var pendingRequests = {},
ajax;
// Use a prefilter if available (1.5+)
if ($.ajaxPrefilter) {
$.ajaxPrefilter... | ajax = $.ajax;
$.ajax = function (settings) {
var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
port = ( "port" in settings ? settings : $.ajaxSettings ).port;
if (mode === "abort") {
if (pendingRequests[port]) {
pendingRequests[port].abo... | }
});
} else {
// Proxy ajax | random_line_split |
ajax.js | // ajax mode: abort
// usage: $.ajax({ mode: "abort"[, port: "uniqueport"]});
// if mode:"abort" is used, the previous request on that port (port can be undefined) is aborted via XMLHttpRequest.abort()
var pendingRequests = {},
ajax;
// Use a prefilter if available (1.5+)
if ($.ajaxPrefilter) {
$.ajaxPrefilter... |
pendingRequests[port] = xhr;
}
});
} else {
// Proxy ajax
ajax = $.ajax;
$.ajax = function (settings) {
var mode = ( "mode" in settings ? settings : $.ajaxSettings ).mode,
port = ( "port" in settings ? settings : $.ajaxSettings ).port;
if (mode === "abort... | {
pendingRequests[port].abort();
} | conditional_block |
FlattenIntoArray.d.ts | type NestedReadonlyNumberRecordOrArray<T> = Readonly<Record<number, T | readonly unknown[]>>;
declare function FlattenIntoArray<T>(
target: Record<number, T>,
source: Readonly<Record<number, T | readonly unknown[]>>,
sourceLen: number,
start: number,
depth: number,
): number;
declare function Flatt... | export = FlattenIntoArray; | depth: number,
mapperFunction: (this: THIS_ARG, element: S | U, sourceIndex: number, source: AS) => T | U,
thisArg: THIS_ARG,
): number; | random_line_split |
tabsDirective.js | (function() {
'use strict';
angular.module('material.components.tabs')
.directive('mdTabs', TabsDirective);
/**
* @ngdoc directive
* @name mdTabs
* @module material.components.tabs
*
* @restrict E
*
* @description
* The `<md-tabs>` directive serves as the container for 1..n `<md-tab>` child directives to pr... | * </md-tabs>
* </hljs>
*
*/
function TabsDirective($mdTheming) {
return {
restrict: 'E',
controller: '$mdTabs',
require: 'mdTabs',
transclude: true,
scope: {
selectedIndex: '=?mdSelected'
},
template:
'<section class="md-header" ' +
'ng-class="{\'md-paginating\': pa... | * </md-tab>
* | random_line_split |
tabsDirective.js | (function() {
'use strict';
angular.module('material.components.tabs')
.directive('mdTabs', TabsDirective);
/**
* @ngdoc directive
* @name mdTabs
* @module material.components.tabs
*
* @restrict E
*
* @description
* The `<md-tabs>` directive serves as the container for 1..n `<md-tab>` child directives to pr... | // overflow: hidden container when paginating
'<div class="md-header-items-container" md-tabs-pagination>' +
// flex container for <md-tab> elements
'<div class="md-header-items">' +
'<md-tabs-ink-bar></md-tabs-ink-bar>' +
'</div>' +
'</div>' +
... | {
return {
restrict: 'E',
controller: '$mdTabs',
require: 'mdTabs',
transclude: true,
scope: {
selectedIndex: '=?mdSelected'
},
template:
'<section class="md-header" ' +
'ng-class="{\'md-paginating\': pagination.active}">' +
'<button class="md-paginator md-prev... | identifier_body |
tabsDirective.js | (function() {
'use strict';
angular.module('material.components.tabs')
.directive('mdTabs', TabsDirective);
/**
* @ngdoc directive
* @name mdTabs
* @module material.components.tabs
*
* @restrict E
*
* @description
* The `<md-tabs>` directive serves as the container for 1..n `<md-tab>` child directives to pr... |
checkHeight();
});
}
}
}
})();
| {
var newTab = tabsCtrl.itemAt(newIndex);
while (newTab && newTab.isDisabled()) {
newTab = newIndex > oldIndex
? tabsCtrl.next(newTab)
: tabsCtrl.previous(newTab);
}
tabsCtrl.select(newTab, rightToLeft);
} | conditional_block |
tabsDirective.js | (function() {
'use strict';
angular.module('material.components.tabs')
.directive('mdTabs', TabsDirective);
/**
* @ngdoc directive
* @name mdTabs
* @module material.components.tabs
*
* @restrict E
*
* @description
* The `<md-tabs>` directive serves as the container for 1..n `<md-tab>` child directives to pr... | (scope, element, attr, tabsCtrl, transclude) {
scope.stretchTabs = attr.hasOwnProperty('mdStretchTabs') ? attr.mdStretchTabs || 'always' : 'auto';
$mdTheming(element);
configureAria();
watchSelected();
transclude(scope.$parent, function(clone) {
angular.element(element[0].querySelector('.md... | postLink | identifier_name |
reducerRegistry.spec.ts | /**
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
import getStore, { resetStore } from "@library/redux/getStore";
import { registerReducer, resetReducers } from "@library/redux/reducerRegistry";
describe("reducerRegistry", () => {
afterEach(() => {
resetStore();
resetRed... | }
};
registerReducer("reducer2", reducer2);
const state = store.getState();
expect(state["reducer1"]).toEqual("updated1");
expect(state["reducer2"]).toEqual("updated2");
});
}); | if (action.type === "update") {
return "updated2";
} else {
return state; | random_line_split |
reducerRegistry.spec.ts | /**
* @copyright 2009-2019 Vanilla Forums Inc.
* @license GPL-2.0-only
*/
import getStore, { resetStore } from "@library/redux/getStore";
import { registerReducer, resetReducers } from "@library/redux/reducerRegistry";
describe("reducerRegistry", () => {
afterEach(() => {
resetStore();
resetRed... |
};
registerReducer("reducer1", reducer1);
const store = getStore<any>();
const reducer2 = (state = "2before", action) => {
if (action.type === "update") {
return "updated2";
} else {
return state;
}
};
... | {
return state;
} | conditional_block |
schema.ts | export type Schema = {
type: 'boolean' | 'number' | 'string' | 'array' | 'object' | 'any';
nullable: boolean;
optional: boolean;
items?: Schema;
properties?: Obj;
description?: string;
example?: any;
format?: string;
ref?: string;
enum?: string[];
};
type NonUndefinedPropertyNames<T extends Obj> = {
[K in k... | : (T | null)
: p['optional'] extends true
? (T | undefined)
: T;
export type SchemaType<p extends Schema> =
p['type'] extends 'number' ? NullOrUndefined<p, number> :
p['type'] extends 'string' ? NullOrUndefined<p, string> :
p['type'] extends 'boolean' ? NullOrUndefined<p, boolean> :
p['type'] extends 'a... | ? (T | null | undefined) | random_line_split |
plot_knn_regression.py | import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import euclidean_distances
from .datasets import make_wave
from .plot_helpers import cm3
def plot_knn_regression(n_neighbors=1):
X, y = make_wave(n_samples=40)
X_test = np.array([[-1.5],... |
train, = plt.plot(X, y, 'o', c=cm3(0))
test, = plt.plot(X_test, -3 * np.ones(len(X_test)), '*', c=cm3(2),
markersize=20)
pred, = plt.plot(X_test, y_pred, '*', c=cm3(0), markersize=20)
plt.vlines(X_test, -3.1, 3.1, linestyle="--")
plt.legend([train, test, pred],
... | plt.arrow(x[0], y_, X[neighbor, 0] - x[0], y[neighbor] - y_,
head_width=0, fc='k', ec='k') | conditional_block |
plot_knn_regression.py | import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import euclidean_distances
from .datasets import make_wave
from .plot_helpers import cm3
def | (n_neighbors=1):
X, y = make_wave(n_samples=40)
X_test = np.array([[-1.5], [0.9], [1.5]])
dist = euclidean_distances(X, X_test)
closest = np.argsort(dist, axis=0)
plt.figure(figsize=(10, 6))
reg = KNeighborsRegressor(n_neighbors=n_neighbors).fit(X, y)
y_pred = reg.predict(X_test)
for... | plot_knn_regression | identifier_name |
plot_knn_regression.py | import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import euclidean_distances
from .datasets import make_wave
from .plot_helpers import cm3
def plot_knn_regression(n_neighbors=1):
| plt.vlines(X_test, -3.1, 3.1, linestyle="--")
plt.legend([train, test, pred],
["training data/target", "test data", "test prediction"],
ncol=3, loc=(.1, 1.025))
plt.ylim(-3.1, 3.1)
plt.xlabel("Feature")
plt.ylabel("Target")
| X, y = make_wave(n_samples=40)
X_test = np.array([[-1.5], [0.9], [1.5]])
dist = euclidean_distances(X, X_test)
closest = np.argsort(dist, axis=0)
plt.figure(figsize=(10, 6))
reg = KNeighborsRegressor(n_neighbors=n_neighbors).fit(X, y)
y_pred = reg.predict(X_test)
for x, y_, neighbors in ... | identifier_body |
plot_knn_regression.py | import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import euclidean_distances
from .datasets import make_wave
from .plot_helpers import cm3
def plot_knn_regression(n_neighbors=1):
X, y = make_wave(n_samples=40)
X_test = np.array([[-1.5],... | pred, = plt.plot(X_test, y_pred, '*', c=cm3(0), markersize=20)
plt.vlines(X_test, -3.1, 3.1, linestyle="--")
plt.legend([train, test, pred],
["training data/target", "test data", "test prediction"],
ncol=3, loc=(.1, 1.025))
plt.ylim(-3.1, 3.1)
plt.xlabel("Feature")
... |
train, = plt.plot(X, y, 'o', c=cm3(0))
test, = plt.plot(X_test, -3 * np.ones(len(X_test)), '*', c=cm3(2),
markersize=20) | random_line_split |
confirm-export.ts | import require from 'require';
function getDescriptor(obj: Record<string, unknown>, path: string) {
let parts = path.split('.');
let value: unknown = obj;
for (let i = 0; i < parts.length - 1; i++) {
let part = parts[i]!;
// NOTE: This isn't entirely safe since we could have a null!
value = (value as... | } | });
} | random_line_split |
confirm-export.ts | import require from 'require';
function getDescriptor(obj: Record<string, unknown>, path: string) {
let parts = path.split('.');
let value: unknown = obj;
for (let i = 0; i < parts.length - 1; i++) {
let part = parts[i]!;
// NOTE: This isn't entirely safe since we could have a null!
value = (value as... | (
Ember: Record<string, unknown>,
assert: QUnit['assert'],
path: string,
moduleId: string,
exportName: string | { value: unknown; get: string; set: string }
) {
try {
let desc: PropertyDescriptor | null | undefined;
if (path !== null) {
desc = getDescriptor(Ember, path);
assert.ok(desc,... | confirmExport | identifier_name |
confirm-export.ts | import require from 'require';
function getDescriptor(obj: Record<string, unknown>, path: string) {
let parts = path.split('.');
let value: unknown = obj;
for (let i = 0; i < parts.length - 1; i++) {
let part = parts[i]!;
// NOTE: This isn't entirely safe since we could have a null!
value = (value as... | let value = 'value' in desc ? desc.value : desc.get!.call(Ember);
assert.equal(value, mod[exportName], `Ember.${path} is exported correctly`);
assert.notEqual(mod[exportName], undefined, `Ember.${path} is not \`undefined\``);
} else if ('value' in desc) {
assert.equal(desc.value, exportName.... | {
try {
let desc: PropertyDescriptor | null | undefined;
if (path !== null) {
desc = getDescriptor(Ember, path);
assert.ok(desc, `the ${path} property exists on the Ember global`);
} else {
desc = null;
}
if (desc == null) {
let mod = require(moduleId);
assert.notEq... | identifier_body |
commit_stats.py | # 统计一下提交代码量
import os
import subprocess
import pandas as pd
os.chdir('../')
# %%
start_dt = '2019-05-01'
end_dt = '2019-06-20'
commits = subprocess.check_output(
"git log --after={start_dt} --before={end_dt} --format='%s%cr'".
format(start_dt=start_dt, end_dt=end_dt),
shell=True)
commits = commits.d... | detail_str=eval(str(detail).replace('\\\\','\\')).decode('utf-8')
detail_formated=[line.split('\t') for line in detail_str.split('\n') if len(line)>0]
detail_pd=pd.DataFrame(detail_formated)
print(detail_pd) | random_line_split | |
JournalEntryForm.js | import React from 'react'
import { compose } from 'redux'
import { connect } from 'react-redux'
import { Field, FieldArray, reduxForm } from 'redux-form'
import { amount, autocomplete, debitCredit } from './Fields'
import { Button, FontIcon } from 'react-toolbox'
import { getAutocomplete } from 'modules/autocomplete'
i... | fetchLedgers
}
const mapStateToProps = (state) => {
return {
ledgers: getAutocomplete(state, 'ledgers')
}
}
export default compose(
connect(mapStateToProps, mapDispatchToProps),
reduxForm({
form: 'JournalEntryForm',
validate
}))(JournalEntryForm) | })
}
const mapDispatchToProps = {
onSubmit, | random_line_split |
main.rs | mod system;
mod math;
mod renderer;
mod canvas;
use renderer::context::*;
use renderer::mesh;
use renderer::shader::{Program, Shader, ShaderType};
use renderer::texture;
use math::mat4::*;
use math::transform;
use math::vec3::*;
use canvas::Canvas;
extern crate rand;
extern crate time;
extern crate gl;
extern crate ... | (mesh::Mesh);
impl specs::Component for CompMesh{
type Storage = specs::VecStorage<CompMesh>;
}
fn main() {
let mut VERTEX_COL_DATA: [GLfloat; 12] = [
1.0, 1.0, 1.0, 1.0,
1.0, 0.0, 1.0, 1.0,
0.0, 1.0, 1.0, 1.0
];
let mut ctx = Context::new("data/config.json");
let t =... | CompMesh | identifier_name |
main.rs | mod system;
mod math;
mod renderer;
mod canvas; | use renderer::shader::{Program, Shader, ShaderType};
use renderer::texture;
use math::mat4::*;
use math::transform;
use math::vec3::*;
use canvas::Canvas;
extern crate rand;
extern crate time;
extern crate gl;
extern crate specs;
use specs::Join;
use gl::types::*;
use std::mem;
use std::ptr;
use std::ffi::CString;
u... |
use renderer::context::*;
use renderer::mesh; | random_line_split |
main.rs | mod system;
mod math;
mod renderer;
mod canvas;
use renderer::context::*;
use renderer::mesh;
use renderer::shader::{Program, Shader, ShaderType};
use renderer::texture;
use math::mat4::*;
use math::transform;
use math::vec3::*;
use canvas::Canvas;
extern crate rand;
extern crate time;
extern crate gl;
extern crate ... |
//now we update the systems
program.bind();
t.bind();
m0.render();
canvas_program.bind();
canvas1.update(elapsed);
canvas1.render();
ctx.end_frame();
}
}
| {
accum -= 1.0;
// try modifying tri color
for i in 0..12 {
if i % 4 != 0 {
VERTEX_COL_DATA[i] = rng.gen::<f32>();
}
}
m0.update_buffer(mesh::MeshAttrib::Color, &VERTEX_COL_DATA);
} | conditional_block |
__init__.py | import unittest
import testRObject
import testVector
import testArray
import testDataFrame
import testFormula
import testFunction
import testEnvironment
import testRobjects
import testMethods
import testPackages
import testHelp
import testLanguage
# wrap this nicely so a warning is issued if no numpy present
import t... | suite_Robjects,
suite_Methods,
suite_NumpyConversions,
suite_Packages,
suite_Help,
suite_Language
... | suite_RObject = testRObject.suite()
suite_Vector = testVector.suite()
suite_Array = testArray.suite()
suite_DataFrame = testDataFrame.suite()
suite_Function = testFunction.suite()
suite_Environment = testEnvironment.suite()
suite_Formula = testFormula.suite()
suite_Robjects = testRobjects.su... | identifier_body |
__init__.py | import unittest
import testRObject
import testVector
import testArray
import testDataFrame
import testFormula
import testFunction
import testEnvironment
import testRobjects
import testMethods
import testPackages
import testHelp
import testLanguage
# wrap this nicely so a warning is issued if no numpy present
import t... | tr = unittest.TextTestRunner(verbosity = 2)
suite = suite()
tr.run(suite) | conditional_block | |
__init__.py | import unittest
import testRObject
import testVector
import testArray
import testDataFrame
import testFormula
import testFunction
import testEnvironment
import testRobjects
import testMethods
import testPackages
import testHelp
import testLanguage
# wrap this nicely so a warning is issued if no numpy present
import t... | ():
r = unittest.TestResult()
suite().run(r)
return r
if __name__ == '__main__':
tr = unittest.TextTestRunner(verbosity = 2)
suite = suite()
tr.run(suite)
| main | identifier_name |
__init__.py | import unittest
import testRObject
import testVector
import testArray
import testDataFrame
import testFormula
import testFunction
import testEnvironment
import testRobjects
import testMethods
import testPackages
import testHelp
import testLanguage
# wrap this nicely so a warning is issued if no numpy present
import t... | suite_Methods = testMethods.suite()
suite_Packages = testPackages.suite()
suite_Help = testHelp.suite()
suite_Language = testLanguage.suite()
alltests = unittest.TestSuite([suite_RObject,
suite_Vector,
suite_Arr... | suite_NumpyConversions = testNumpyConversions.suite() | random_line_split |
Test_Watchdog.py | """ unit test for Watchdog.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# imports
import os
from mock import MagicMock
# sut
from DIRAC.WorkloadManagementSystem.JobWrapper.Watchdog import Watchdog
mock_exeThread = MagicMock()
mock_spObject = Mag... |
def test__performChecks():
pid = os.getpid()
wd = Watchdog(pid, mock_exeThread, mock_spObject, 5000)
res = wd.calibrate()
assert res['OK'] is True
res = wd._performChecks()
assert res['OK'] is True
def test__performChecksFull():
pid = os.getpid()
wd = Watchdog(pid, mock_exeThread, mock_spObject, 5... | pid = os.getpid()
wd = Watchdog(pid, mock_exeThread, mock_spObject, 5000)
res = wd.calibrate()
assert res['OK'] is True | identifier_body |
Test_Watchdog.py | """ unit test for Watchdog.py
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# imports
import os
from mock import MagicMock
# sut
from DIRAC.WorkloadManagementSystem.JobWrapper.Watchdog import Watchdog
mock_exeThread = MagicMock()
mock_spObject = Mag... | ():
pid = os.getpid()
wd = Watchdog(pid, mock_exeThread, mock_spObject, 5000)
wd.testCPULimit = 1
wd.testMemoryLimit = 1
res = wd.calibrate()
assert res['OK'] is True
res = wd._performChecks()
assert res['OK'] is True
| test__performChecksFull | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.