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 |
|---|---|---|---|---|
last-use-in-cap-clause.rs | // Copyright 2012 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 ... | () {
assert_eq!(foo()(), 22);
}
| main | identifier_name |
last-use-in-cap-clause.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
assert_eq!(foo()(), 22);
}
| {
let k = ~22;
let _u = A {a: k.clone()};
let result: @fn() -> int = || 22;
result
} | identifier_body |
htmlfile.py | import subprocess
import os.path
import traceback
from radiopadre.file import FileBase
from radiopadre.render import render_title, render_url, render_preamble, render_error
from radiopadre import settings
from radiopadre import imagefile
class HTMLFile(FileBase):
def __init__(self, *args, **kw):
FileBase.... | return html
def _render_thumb_impl(self, npix=None, **kw):
thumbnail, thumbnail_url, update = self._get_cache_file("html-render", "png")
npix = npix or 800
if update:
script = os.path.join(os.path.dirname(__file__), "../html/html-thumbnail.js")
path = os.pat... | width = width or settings.display.cell_width
height = height or settings.display.window_height
url = render_url(self.fullpath)
html = render_preamble() + render_title(self.title)
html += """<IFRAME width={width} height={height} src={url}></IFRAME>""".format(**locals()) | random_line_split |
htmlfile.py | import subprocess
import os.path
import traceback
from radiopadre.file import FileBase
from radiopadre.render import render_title, render_url, render_preamble, render_error
from radiopadre import settings
from radiopadre import imagefile
class HTMLFile(FileBase):
def __init__(self, *args, **kw):
FileBase.... |
return imagefile.ImageFile._render_thumbnail(thumbnail, url=render_url(self.fullpath), npix=npix) + "\n" | script = os.path.join(os.path.dirname(__file__), "../html/html-thumbnail.js")
path = os.path.abspath(self.fullpath)
cmd = "phantomjs --debug=true {script} file://{path} {thumbnail} {npix} {npix} 200".format(**locals())
# print "Command is",cmd
try:
output ... | conditional_block |
htmlfile.py | import subprocess
import os.path
import traceback
from radiopadre.file import FileBase
from radiopadre.render import render_title, render_url, render_preamble, render_error
from radiopadre import settings
from radiopadre import imagefile
class | (FileBase):
def __init__(self, *args, **kw):
FileBase.__init__(self, *args, **kw)
def render_html(self, width="99%", context=None, height=None):
width = width or settings.display.cell_width
height = height or settings.display.window_height
url = render_url(self.fullpath)
... | HTMLFile | identifier_name |
htmlfile.py | import subprocess
import os.path
import traceback
from radiopadre.file import FileBase
from radiopadre.render import render_title, render_url, render_preamble, render_error
from radiopadre import settings
from radiopadre import imagefile
class HTMLFile(FileBase):
def __init__(self, *args, **kw):
FileBase.... |
def _render_thumb_impl(self, npix=None, **kw):
thumbnail, thumbnail_url, update = self._get_cache_file("html-render", "png")
npix = npix or 800
if update:
script = os.path.join(os.path.dirname(__file__), "../html/html-thumbnail.js")
path = os.path.abspath(self.full... | width = width or settings.display.cell_width
height = height or settings.display.window_height
url = render_url(self.fullpath)
html = render_preamble() + render_title(self.title)
html += """<IFRAME width={width} height={height} src={url}></IFRAME>""".format(**locals())
return htm... | identifier_body |
reminders.py | # -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['... | delay = delay.replace('d', ' days')
message = 'Your reminder has been set for *' + delay + '* from now:\n\n' + text
send_message(msg['chat']['id'], message, parse_mode="Markdown")
def cron():
reminders = load_json('data/reminders.json', True)
for id, reminder in reminders.items():
... | delay = delay.replace('h', ' hours')
if unit == 'd':
| random_line_split |
reminders.py | # -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['... | send_message(msg['chat']['id'], 'Please include a reminder.')
if 'username' in msg['from']:
text += '\n@' + msg['from']['username']
reminder = OrderedDict()
reminder['alarm'] = alarm
reminder['chat_id'] = msg['chat']['id']
reminder['text'] = text
remi... | input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = delay[-1:]
... | identifier_body |
reminders.py | # -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['... | (msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
return send_message(msg['chat']['id'], doc,
parse_mode="Markdown")
delay = first_word(input)
if delay:
time = delay[:-1]
unit = dela... | run | identifier_name |
reminders.py | # -*- coding: utf-8 -*-
from utils import *
commands = [
'^remindme',
'^reminder',
'^remind$',
'^r '
]
parameters = (
('delay', True),
('message', True),
)
description = 'Set a reminder for yourself. First argument is delay until you wish to be reminded.\nExample: `' + config['... |
elif unit == 'm':
return float(time) * 60
elif unit == 'h':
return float(time) * 60 * 60
elif unit == 'd':
return float(time) * 60 * 60 * 24
def run(msg):
input = get_input(msg['text'])
if not input:
doc = get_doc(commands, parameters, description)
... | return float(time) | conditional_block |
_conf.py | """Conf format
The conf format is registered by default. It reads and writes settings
using :mod:`ConfigParser` at locations that are similar to typical Unix
configuration files---that is, in :file:`.conf` files specific to each
component scope under :file:`/etc/{organization}` for system-wide
settings and under :fil... |
_core.Settings.register_format('conf', extension='.conf',
read_func=_read_settings,
write_func=_write_settings)
_homedir = _os.path.expanduser('~')
_paths = {('system', 'organization'):
_os.path.join(_os.path.sep, 'etc', '{organization}',
... | if settings:
# FIXME
raise NotImplementedError('writing \'conf\' settings is not yet'
' implemented') | identifier_body |
_conf.py | """Conf format
The conf format is registered by default. It reads and writes settings
using :mod:`ConfigParser` at locations that are similar to typical Unix
configuration files---that is, in :file:`.conf` files specific to each
component scope under :file:`/etc/{organization}` for system-wide
settings and under :fil... | (file_, keys):
settings = {}
parser = _configparser.RawConfigParser(allow_no_value=True)
parser.read(file_)
if keys == ['']:
for section in parser.sections():
for subkey, value in parser.items(section):
settings[section + '/' + subkey] = value
else:
for... | _read_settings | identifier_name |
_conf.py | """Conf format
The conf format is registered by default. It reads and writes settings
using :mod:`ConfigParser` at locations that are similar to typical Unix
configuration files---that is, in :file:`.conf` files specific to each
component scope under :file:`/etc/{organization}` for system-wide
settings and under :fil... |
else:
for key in keys:
section, _, subkey = key.rpartition('/')
if not section:
section = _configparser.DEFAULTSECT
if parser.has_section(section) \
and parser.has_option(section, subkey):
try:
setti... | settings[section + '/' + subkey] = value | conditional_block |
_conf.py | """Conf format
The conf format is registered by default. It reads and writes settings
using :mod:`ConfigParser` at locations that are similar to typical Unix
configuration files---that is, in :file:`.conf` files specific to each
component scope under :file:`/etc/{organization}` for system-wide
settings and under :fil... | section, _, subkey = key.rpartition('/')
if not section:
section = _configparser.DEFAULTSECT
if parser.has_section(section) \
and parser.has_option(section, subkey):
try:
settings[key] = parser.get(section, subke... | settings[section + '/' + subkey] = value
else:
for key in keys: | random_line_split |
elasticache_subnet_group.py | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | ():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
state = dict(required=True, choices=['present', 'absent']),
name = dict(required=True),
description = dict(required=False),
subnets = dict(required=False, type='list'),
... | main | identifier_name |
elasticache_subnet_group.py | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... |
state = module.params.get('state')
group_name = module.params.get('name').lower()
group_description = module.params.get('description')
group_subnets = module.params.get('subnets') or {}
if state == 'present':
for required in ['name', 'descrip... | module.fail_json(msg='boto required for this module') | conditional_block |
elasticache_subnet_group.py | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | if not module.params.get(required):
module.fail_json(msg = str("Parameter %s required for state='present'" % required))
else:
for not_allowed in ['description', 'subnets']:
if module.params.get(not_allowed):
module.fail_json(msg = str("Parameter %s not... | argument_spec = ec2_argument_spec()
argument_spec.update(dict(
state = dict(required=True, choices=['present', 'absent']),
name = dict(required=True),
description = dict(required=False),
subnets = dict(required=False, type='list'),
)
... | identifier_body |
elasticache_subnet_group.py | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | changed = False
module.exit_json(changed=changed)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
if __name__ == '__main__':
main() | else: | random_line_split |
MobileStepper.js | import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { integerPropType, deepmerge } from '@material-ui/utils';
im... | }), variant === 'dots' && /*#__PURE__*/_jsx(MobileStepperDots, {
styleProps: styleProps,
className: classes.dots,
children: [...new Array(steps)].map((_, index) => /*#__PURE__*/_jsx(MobileStepperDot, {
className: clsx(classes.dot, index === activeStep && classes.dotActive),
stylePr... | styleProps: styleProps
}, other, {
children: [backButton, variant === 'text' && /*#__PURE__*/_jsxs(React.Fragment, {
children: [activeStep + 1, " / ", steps] | random_line_split |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Hello Flask
Latest version can be found at https://github.com/dakside/pydemo
References:
Python documentation:
https://docs.python.org/
Flask documentation:
http://flask.pocoo.org/
PEP 0008 - Style Guide for Python Code
https://ww... | ():
title = "My First Flask App that uses template"
content = "<h1>Flask is beautiful</h1>Lorem ipsum dolor sit amet"
return render_template('layout.html', title=title, content=content)
if __name__ == '__main__':
app.debug = True # To show error message
app.run()
# app.run(host='0.0.0.0') to ... | rootpage | identifier_name |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Hello Flask
Latest version can be found at https://github.com/dakside/pydemo
References:
Python documentation:
https://docs.python.org/
Flask documentation:
http://flask.pocoo.org/
PEP 0008 - Style Guide for Python Code
https://ww... |
if __name__ == '__main__':
app.debug = True # To show error message
app.run()
# app.run(host='0.0.0.0') to listen on all public IPs
| title = "My First Flask App that uses template"
content = "<h1>Flask is beautiful</h1>Lorem ipsum dolor sit amet"
return render_template('layout.html', title=title, content=content) | identifier_body |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Hello Flask
Latest version can be found at https://github.com/dakside/pydemo
References:
Python documentation:
https://docs.python.org/
Flask documentation:
http://flask.pocoo.org/
PEP 0008 - Style Guide for Python Code
https://ww... | app.debug = True # To show error message
app.run()
# app.run(host='0.0.0.0') to listen on all public IPs | conditional_block | |
app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Hello Flask
Latest version can be found at https://github.com/dakside/pydemo
References:
Python documentation:
https://docs.python.org/
Flask documentation:
http://flask.pocoo.org/
PEP 0008 - Style Guide for Python Code
https://ww... |
app = Flask(__name__)
@app.route('/')
def rootpage():
title = "My First Flask App that uses template"
content = "<h1>Flask is beautiful</h1>Lorem ipsum dolor sit amet"
return render_template('layout.html', title=title, content=content)
if __name__ == '__main__':
app.debug = True # To show error m... | random_line_split | |
unboxed-closures-blanket-fn.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 ... | }
fn c<F:Fn() -> i32>(f: &F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&|| 22);
assert_eq!(x, 22);
let x = c(&|| 22);
assert_eq!(x, 22);
} | random_line_split | |
unboxed-closures-blanket-fn.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 ... |
fn b(f: &Fn() -> i32) -> i32 {
a(f)
}
fn c<F:Fn() -> i32>(f: &F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&|| 22);
assert_eq!(x, 22);
let x = c(&|| 22);
assert_eq!(x, 22);
}
| {
f()
} | identifier_body |
unboxed-closures-blanket-fn.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 ... | (f: &Fn() -> i32) -> i32 {
a(f)
}
fn c<F:Fn() -> i32>(f: &F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&|| 22);
assert_eq!(x, 22);
let x = c(&|| 22);
assert_eq!(x, 22);
}
| b | identifier_name |
user.py | import logging
from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import HrefField, StringField
from sevenbridges.meta.transformer import Transform
logger = logging.getLogger(__name__)
class User(Resource):
"""
Central resource for managing users.
"""
_URL = {
'me'... | (cls, api=None):
"""
Retrieves current user information.
:param api: Api instance.
:return: User object.
"""
api = api if api else cls._API
extra = {
'resource': cls.__name__,
'query': {}
}
logger.info('Fetching user informa... | me | identifier_name |
user.py | import logging
from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import HrefField, StringField
from sevenbridges.meta.transformer import Transform
logger = logging.getLogger(__name__)
class User(Resource):
"""
Central resource for managing users.
"""
_URL = {
'me'... | """
api = api if api else cls._API
extra = {
'resource': cls.__name__,
'query': {}
}
logger.info('Fetching user information', extra=extra)
user_data = api.get(cls._URL['me']).json()
return User(api=api, **user_data)
@classmethod
de... | random_line_split | |
user.py | import logging
from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import HrefField, StringField
from sevenbridges.meta.transformer import Transform
logger = logging.getLogger(__name__)
class User(Resource):
"""
Central resource for managing users.
"""
_URL = {
'me'... |
return super()._query(
url=cls._URL['query'],
api=api,
offset=offset,
limit=limit,
**params
)
def disable(self, api=None):
"""
Disable user
:param api: Api instance.
:return:
"""
api = api ... | params['role'] = role | conditional_block |
user.py | import logging
from sevenbridges.meta.resource import Resource
from sevenbridges.meta.fields import HrefField, StringField
from sevenbridges.meta.transformer import Transform
logger = logging.getLogger(__name__)
class User(Resource):
| zip_code = StringField(read_only=True)
city = StringField(read_only=True)
role = StringField(read_only=True)
def __eq__(self, other):
if type(other) is not type(self):
return False
return self is other or self.username == other.username
def __str__(self):
return... | """
Central resource for managing users.
"""
_URL = {
'me': '/user',
'get': '/users/{id}',
'query': '/users',
'delete': '/users/{username}'
}
href = HrefField(read_only=True)
username = StringField(read_only=True)
email = StringField(read_only=True)
first... | identifier_body |
registry_access.py | .match('^[a-z]+[a-z0-9+-]*$', name)
if not name_match:
raise access_common.AccessException(
'Target name "%s" is not valid (must contain only lowercase letters, hyphen, plus, and numbers)' % name
)
else:
name_match = re.match('^[a-z]+[a... | pubkey = serialization.load_pem_public_key(pubkey_pem, default_backend()) | conditional_block | |
registry_access.py | _raiseUnavailableFor401(message):
''' Returns a decorator to swallow a requests exception for modules that
are not accessible without logging in, and turn it into an Unavailable
exception.
'''
def __raiseUnavailableFor401(fn):
def wrapped(*args, **kwargs):
try:
... | unpackInto | identifier_name | |
registry_access.py | (this does not guarantee that the component actually exists in
the registry: use availableVersions() for that).
'''
# we deliberately allow only lowercase, hyphen, and (unfortunately)
# numbers in package names, to reduce the possibility of confusingly
# similar names: if th... | random_line_split | ||
registry_access.py | # any provider is sufficient for registry auth
auth.authorizeUser(provider=None, interactive=interactive)
if interactive:
logger.debug('retrying after authentication...')
return fn(*args, **kwargs)
raise
return wrapped
def _friend... |
return __raiseUnavailableFor401
def _swallowRequestExceptions(fail_return=None):
def __swallowRequestExceptions(fn):
''' Decorator to swallow known exceptions: use with _friendlyAuthError,
returns non-None if an exception occurred
'''
@functools.wraps(fn)
def wrappe... | def wrapped(*args, **kwargs):
try:
return fn(*args, **kwargs)
except requests.exceptions.HTTPError as e:
if e.response.status_code == requests.codes.unauthorized:
raise access_common.Unavailable(message)
else:
... | identifier_body |
truncate_fasta_qual_files.py | #!/usr/bin/env python
# File created Sept 29, 2010
from __future__ import division
__author__ = "William Walters"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["William Walters", "Greg Caporaso"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "William Walters"
__email__ = "William.... | (fasta_seqs,
qual_scores,
base_pos):
""" Truncates sequences to base position specified with base_pos
fasta_seqs: dict of seq label: seq string
qual_scores: dict of seq label: numpy array of int scores
base_pos: index in sequence to truncate at
"""
trunc_fas... | truncate_seqs | identifier_name |
truncate_fasta_qual_files.py | #!/usr/bin/env python
# File created Sept 29, 2010
from __future__ import division
__author__ = "William Walters"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["William Walters", "Greg Caporaso"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "William Walters"
__email__ = "William.... | if len(fasta_seqs[label]) != len(qual_scores[label]):
raise ValueError('Sequence %s does not have equivalent ' %
label + 'base positions between fasta and quality score file.')
def truncate_seqs(fasta_seqs,
qual_scores,
base_pos):
... | """ Tests for equivalent labels, base positions between fasta and qual file
fasta_seqs: dict of label:seq from fasta file
qual_scores: dict of label: qual scores
"""
if len(fasta_seqs) != len(qual_scores):
raise ValueError('Number of sequences not equal in input fasta ' +
... | identifier_body |
truncate_fasta_qual_files.py | #!/usr/bin/env python
# File created Sept 29, 2010
from __future__ import division
__author__ = "William Walters"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["William Walters", "Greg Caporaso"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "William Walters"
__email__ = "William.... |
fasta_seqs: dict of label:seq from fasta file
qual_scores: dict of label: qual scores
"""
if len(fasta_seqs) != len(qual_scores):
raise ValueError('Number of sequences not equal in input fasta ' +
'and qual file.')
qual_scores_labels = set(qual_scores.keys())
... | """ Tests for equivalent labels, base positions between fasta and qual file | random_line_split |
truncate_fasta_qual_files.py | #!/usr/bin/env python
# File created Sept 29, 2010
from __future__ import division
__author__ = "William Walters"
__copyright__ = "Copyright 2011, The QIIME Project"
__credits__ = ["William Walters", "Greg Caporaso"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "William Walters"
__email__ = "William.... |
def write_trunc_qual(trunc_qual_scores,
qual_out_fp,
seq_order):
""" Writes truncated quality score files out in proper format
trunc_qual_scores: dict of seq label: numpy array of scores as ints
qual_out_fp: output filepath to write truncated quality scores to
... | trunc_label = label.split()[0].strip()
fasta_out.write(">%s\n%s\n" % (label, trunc_fasta_seqs[trunc_label])) | conditional_block |
TestAcosh.rs | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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
* | * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma version(1)
#pragma rs java_package_name(android.renderscr... | * Unless required by applicable law or agreed to in writing, software | random_line_split |
index.js | import React from 'react';
import Telephone, {
CONTACTS,
PATTERNS,
} from '@department-of-veterans-affairs/component-library/Telephone';
export const LOADING_STATUS = {
failed: 'failed',
pending: 'pending',
success: 'success',
};
export const ServerErrorFragment = () => (
<>
<h2 className="vads-u-font... | e if (
formData.reasonForRemoval === WIZARD_OPTIONS_KEYS.CHILD_LEFT_SCHOOL
) {
const { fullName, date: dateChildLeftSchool } = universalData;
payload.childStoppedAttendingSchool = {
fullName,
dateChildLeftSchool,
birthDate,
ssn,
};
} else if (formData.reas... | const { fullName, date: dateMarried } = universalData;
payload.childMarriage = {
fullName,
dateMarried,
birthDate,
ssn,
};
} els | conditional_block |
index.js | import React from 'react';
import Telephone, {
CONTACTS,
PATTERNS,
} from '@department-of-veterans-affairs/component-library/Telephone';
export const LOADING_STATUS = {
failed: 'failed',
pending: 'pending',
success: 'success',
};
export const ServerErrorFragment = () => (
<>
<h2 className="vads-u-font... | const supportingStepchild = livingExpensesPaid !== 'None';
payload.stepChildren = [
{
...universalData,
ssn,
birthDate,
supportingStepchild,
livingExpensesPaid,
address,
whoDoesTheStepchildLiveWith,
},
];
}
}
... | const {
livingExpensesPaid,
whoDoesTheStepchildLiveWith,
address,
} = formData; | random_line_split |
lib.rs | pub struct RailFence {
rails: usize,
}
impl RailFence {
pub fn new(rails: u32) -> RailFence |
pub fn encode(&self, text: &str) -> String {
let mut rails = vec![String::new(); self.rails];
let indexes = (0..self.rails).chain((1..self.rails - 1).rev()).cycle();
text.chars()
.zip(indexes)
.for_each(|(c, i)| rails[i as usize].push(c));
rails.concat()
... | {
RailFence {
rails: rails as usize,
}
} | identifier_body |
lib.rs | pub struct RailFence {
rails: usize,
}
impl RailFence {
pub fn new(rails: u32) -> RailFence {
RailFence {
rails: rails as usize,
}
}
pub fn | (&self, text: &str) -> String {
let mut rails = vec![String::new(); self.rails];
let indexes = (0..self.rails).chain((1..self.rails - 1).rev()).cycle();
text.chars()
.zip(indexes)
.for_each(|(c, i)| rails[i as usize].push(c));
rails.concat()
}
pub fn de... | encode | identifier_name |
lib.rs | pub struct RailFence {
rails: usize,
}
impl RailFence {
pub fn new(rails: u32) -> RailFence {
RailFence {
rails: rails as usize,
}
}
pub fn encode(&self, text: &str) -> String {
let mut rails = vec![String::new(); self.rails];
let indexes = (0..self.rails).c... | }
} | text.iter().collect::<String>() | random_line_split |
main.rs | use std::str::FromStr;
use std::io::Read;
use std::fs::File;
// Input types and decoding
//
#[derive(Debug, Clone, Copy)]
enum Rotation {
Left = 1,
Forward = 0,
Right = -1,
}
#[derive(Debug)]
struct Step {
rotation: Rotation,
distance: i32,
}
impl FromStr for Rotation {
type Err = String;
... |
}
impl FromStr for Step {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (dir, dist) = s.split_at(1);
Ok(Step {
rotation: Rotation::from_str(dir).unwrap(),
distance: i32::from_str(dist.trim()).unwrap(),
})
}
}
// Common helpers
//
... | {
match s.chars().next() {
Some('L') => Ok(Rotation::Left),
Some('R') => Ok(Rotation::Right),
c => Err(format!("Unknown entry: {:?}", c)),
}
} | identifier_body |
main.rs | use std::str::FromStr;
use std::io::Read;
use std::fs::File;
// Input types and decoding
//
#[derive(Debug, Clone, Copy)]
enum Rotation {
Left = 1,
Forward = 0,
Right = -1,
}
#[derive(Debug)]
struct Step {
rotation: Rotation,
distance: i32,
}
impl FromStr for Rotation {
type Err = String;
... | let (x, y) = match int_dir {
0 => (pos.x, pos.y + step.distance),
1 => (pos.x - step.distance, pos.y),
2 => (pos.x, pos.y - step.distance),
3 => (pos.x + step.distance, pos.y),
_ => panic!("Unknown direction {}", int_dir),
};
Position {direction: int_dir, x: x, y: y}... | }
fn walk(pos: Position, step: Step) -> Position {
let int_dir = (pos.direction + step.rotation as i8 + 4) % 4; | random_line_split |
main.rs | use std::str::FromStr;
use std::io::Read;
use std::fs::File;
// Input types and decoding
//
#[derive(Debug, Clone, Copy)]
enum Rotation {
Left = 1,
Forward = 0,
Right = -1,
}
#[derive(Debug)]
struct Step {
rotation: Rotation,
distance: i32,
}
impl FromStr for Rotation {
type Err = String;
... | (&self) -> i32 {
self.x.abs() + self.y.abs()
}
}
fn walk(pos: Position, step: Step) -> Position {
let int_dir = (pos.direction + step.rotation as i8 + 4) % 4;
let (x, y) = match int_dir {
0 => (pos.x, pos.y + step.distance),
1 => (pos.x - step.distance, pos.y),
2 => (pos.x, ... | distance | identifier_name |
mw.LanguageUpWiz.js | /* jshint nomen: false */
( function( mw, $ ) {
// TODO come now, there has to be a better way
mediaWiki.messages.set( {
'mwe-upwiz-code-unknown': 'Unknown language'
} );
/**
* Utility class which knows about languages, and how to construct HTML to select them
* TODO: make this a more common library, used by this a... | * 1) mostly ready-to-go language HTML menu. When/if we upgrade, make it a jQuery combobox
* 2) dict of language code to name -- useful for testing for existence, maybe other things.
*/
initialize: function() {
var langs, langcode,
thisUri = new mw.Uri( window.location.href, { overrideKeys: true } ),
$sel... | },
/**
* cache some useful objects | random_line_split |
mw.LanguageUpWiz.js | /* jshint nomen: false */
( function( mw, $ ) {
// TODO come now, there has to be a better way
mediaWiki.messages.set( {
'mwe-upwiz-code-unknown': 'Unknown language'
} );
/**
* Utility class which knows about languages, and how to construct HTML to select them
* TODO: make this a more common library, used by this a... |
return mw.LanguageUpWiz.getClosest( code.substring( 0, code.indexOf( '-' )) );
}
};
}( mediaWiki, jQuery ) );
| {
return code;
} | conditional_block |
mongoRsSnippets.ts | ///<reference path='typings/node/node.d.ts'/>
let configSample=`{
_id : "my_replica_set",
members : [
{_id : 0, host : "rs1.example.net:27017"},
{_id : 1, host : "rs2.example.net:27017"},
{_id : 2, host : "rs3.example.net", arbiterOnly: true},
]
}`;
var mongoInitializeTemplate... | caption: "initiateWithSampleConfig",
snippet:
`${configSample}
initiate();`,
comment: 'Initiates a replica set. Optionally takes a configuration argument in the form of a document that holds the configuration of a replica set.',
example:
`${configSample}
rs.initiate()`,... | example:
`rs.initiate()`,
score:100
},
{ | random_line_split |
bugsnag.js | import { Meteor } from 'meteor/meteor';
import bugsnag from 'bugsnag';
import { settings } from '../../../settings';
import { Info } from '../../../utils';
settings.get('Bugsnag_api_key', (key, value) => {
if (value) |
});
const notify = function(message, stack) {
if (typeof stack === 'string') {
message += ` ${ stack }`;
}
let options = {};
if (Info) {
options = { app: { version: Info.version, info: Info } };
}
const error = new Error(message);
error.stack = stack;
bugsnag.notify(error, options);
};
process.on('uncaug... | {
bugsnag.register(value);
} | conditional_block |
bugsnag.js | import { Meteor } from 'meteor/meteor';
import bugsnag from 'bugsnag';
import { settings } from '../../../settings';
import { Info } from '../../../utils';
settings.get('Bugsnag_api_key', (key, value) => {
if (value) {
bugsnag.register(value);
}
});
const notify = function(message, stack) {
if (typeof stack ===... | process.on('uncaughtException', Meteor.bindEnvironment((error) => {
notify(error.message, error.stack);
throw error;
}));
const originalMeteorDebug = Meteor._debug;
Meteor._debug = function(...args) {
notify(...args);
return originalMeteorDebug(...args);
}; | random_line_split | |
bayes.py | # __author__ = MelissaChan
# -*- coding: utf-8 -*-
# 16-2-14 下午4:37
# 词表转换向量
# 创建词汇表
def createVocabList(dataSet):
vocabSet = set([])
for document in dataSet:
vocabSet = vocabSet | set(document)
return list(vocabSet)
# 转换为向量
def setOfWords2Vec(vocablist,inputset):
returnVec = [0] * len(vocablis... | testEntry2 = ['stupid','my','my']
thisDoc = array(setOfWords2Vec(myVocabList,testEntry))
thisDoc2 = array(setOfWords2Vec(myVocabList,testEntry2))
# print testEntry2,'classified as: ',classify(thisDoc2,p0v,p1v,pAb)
# print testEntry,'classified as: ',classify(thisDoc,p0v,p1v,pAb)
# print p0v
# print p1v
# 垃圾邮件过滤器
# 文本解... | testEntry = ['love','my','dalmatian'] | random_line_split |
bayes.py | # __author__ = MelissaChan
# -*- coding: utf-8 -*-
# 16-2-14 下午4:37
# 词表转换向量
# 创建词汇表
def createVocabList(dataSet):
vocabSet = set([])
for document in dataSet:
vocabSet = vocabSet | set(document)
return list(vocabSet)
# 转换为向量
def setOfWords2Vec(vocablist,inputset):
returnVec = [0] * len(vocablis... | conditional_block | ||
bayes.py | # __author__ = MelissaChan
# -*- coding: utf-8 -*-
# 16-2-14 下午4:37
# 词表转换向量
# 创建词汇表
def createVocabList(dataSet):
vocabSet = set([])
for document in dataSet:
vocabSet = vocabSet | set(document)
return list(vocabSet)
# 转换为向量
def setOfWords2Vec(vocablist,inputset):
returnVec = [0] * len(vocablis... | t' % i).read())
docList.append(wordList)
fullText.extend(wordList)
classList.append(1)
wordList = textParse(open('/home/melissa/桌面/email/ham/%d.txt' % i).read())
docList.append(wordList)
fullText.extend(wordList)
classList.append(0)
# 随机构建训练集
vocabList = c... | ssList = []; fullText =[]
for i in range(1,26):
wordList = textParse(open('/home/melissa/桌面/email/spam/%d.tx | identifier_body |
bayes.py | # __author__ = MelissaChan
# -*- coding: utf-8 -*-
# 16-2-14 下午4:37
# 词表转换向量
# 创建词汇表
def createVocabList(dataSet):
vocabSet = set([])
for document in dataSet:
vocabSet = vocabSet | set(document)
return list(vocabSet)
# 转换为向量
def setOfWords2Vec(vocablist,inputset):
returnVec = [0] * len(vocablis... | docList=[]; classList = []; fullText =[]
for i in range(1,26):
wordList = textParse(open('/home/melissa/桌面/email/spam/%d.txt' % i).read())
docList.append(wordList)
fullText.extend(wordList)
classList.append(1)
wordList = textParse(open('/home/melissa/桌面/email/ham/%d.txt' % ... | 入并解析文本
| identifier_name |
for_continue.py | import question_template
game_type = 'input_output'
source_language = 'C'
parameter_list = [
['$x1','int'],['$x2','int'],['$x3','int'],['$y0','int'],
]
tuple_list = [
['for_continue_',
[0,1,2,None],
[0,2,2,None],
[0,4,2,None], | [None,None,2,1],
[None,None,2,2],
[None,None,2,4],
[None,None,2,6],
[None,None,2,7],
[0,1,3,None],
[0,2,3,None],
[0,4,3,None],
[0,6,4,None],
[0,7,5,None],
[None,None,3,1],
[None,None,3,2],
[None,None,3,4],
[None,None,4,6],
[None,None,5,7],
]
]
global_code_template = '''\
d #include <s... | [0,6,2,None],
[0,7,2,None], | random_line_split |
L7PolicyListItem.js | import { useEffect, useState, useMemo } from "react"
import useCommons from "../../../lib/hooks/useCommons"
import { Link } from "react-router-dom"
import StaticTags from "../StaticTags"
import useL7Policy from "../../../lib/hooks/useL7Policy"
import CopyPastePopover from "../shared/CopyPastePopover"
import useListener... | actionRedirect,
deleteL7Policy,
persistL7Policy,
onSelectL7Policy,
reset,
} = useL7Policy()
const [loadbalancerID, setLoadbalancerID] = useState(null)
const { persistListener } = useListener()
const { entityStatus } = useStatus(
l7Policy.operating_status,
l7Policy.provisioning_status... | random_line_split | |
L7PolicyListItem.js | import { useEffect, useState, useMemo } from "react"
import useCommons from "../../../lib/hooks/useCommons"
import { Link } from "react-router-dom"
import StaticTags from "../StaticTags"
import useL7Policy from "../../../lib/hooks/useL7Policy"
import CopyPastePopover from "../shared/CopyPastePopover"
import useListener... |
onSelectL7Policy(props, l7Policy.id)
}
const canEdit = useMemo(
() =>
policy.isAllowed("lbaas2:l7policy_update", {
target: { scoped_domain_name: scope.domain },
}),
[scope.domain]
)
const canDelete = useMemo(
() =>
policy.isAllowed("lbaas2:l7policy_delete", {
... | {
e.stopPropagation()
e.preventDefault()
} | conditional_block |
test_groups.py | 13-2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed in the hope that it will be
# useful, but... | self):
""" Set up the environnment, ran before every tests. """
super(PkgdbGrouptests, self).setUp()
pkgdb2.APP.config['TESTING'] = True
pkgdb2.SESSION = self.session
pkgdb2.api.extras.SESSION = self.session
pkgdb2.ui.SESSION = self.session
pkgdb2.ui.acls.SESSION... | etUp( | identifier_name |
test_groups.py | 013-2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed in the hope that it will be
# useful, bu... | 'Fedora': {
"fedocal": {
"owner": "pingou",
"cclist": {
"groups": ["@infra-sig"],
"people": ["pingou"]
},
"qacontact": None,
... | "" Test the api_bugzilla function. """
create_package_acl2(self.session)
self.set_group_acls()
output = self.app.get('/api/bugzilla/')
self.assertEqual(output.status_code, 200)
expected = """# Package Database VCS Acls
# Text Format
# Collection|Package|Description|Owner|Initial... | identifier_body |
test_groups.py | 013-2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed in the hope that it will be
# useful, bu... | self.assertEqual(data, expected)
@patch('pkgdb2.lib.utils')
@patch('pkgdb2.packager_login_required')
def test_package_give_group(self, login_func, mock_func):
""" Test the package_give function to a group. """
login_func.return_value = None
create_package_acl(self.session)
... | },
'title': 'Fedora Package Database -- Bugzilla ACLs'
}
data = json.loads(output.data) | random_line_split |
test_groups.py | redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties of MERCHANTABILITY or FITNESS FOR A ... | UITE = unittest.TestLoader().loadTestsFromTestCase(PkgdbGrouptests)
unittest.TextTestRunner(verbosity=2).run(SUITE)
| conditional_block | |
mainThreadCommands.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (id: string) {
activations.push(id);
return Promise.resolve();
}
}
);
// case 1: arguments and retry
try {
activations.length = 0;
await commands.$executeCommand('bazz', [1, 2, { n: 3 }], true);
assert.ok(false);
} catch (e) {
assert.deepStrictEqual(activations, ['onCommand:bazz'])... | activateByEvent | identifier_name |
mainThreadCommands.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
},
new class extends mock<IExtensionService>() {
override activateByEvent(id: string) {
activations.push(id);
return Promise.resolve();
}
}
);
// case 1: arguments and retry
try {
activations.length = 0;
await commands.$executeCommand('bazz', [1, 2, { n: 3 }], true);
assert.o... | {
runs.push(id);
return Promise.resolve(undefined);
} | identifier_body |
mainThreadCommands.test.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | } catch (e) {
assert.deepStrictEqual(activations, ['onCommand:bazz']);
assert.strictEqual((<Error>e).message, '$executeCommand:retry');
}
// case 2: no arguments and retry
runs.length = 0;
await commands.$executeCommand('bazz', [], true);
assert.deepStrictEqual(runs, ['bazz']);
// case 3: argument... | await commands.$executeCommand('bazz', [1, 2, { n: 3 }], true);
assert.ok(false); | random_line_split |
seg_queue.rs | Segment<T> {
/// The used entries in the segment.
used: Range<AtomicUsize>,
/// The data.
data: [UnsafeCell<T>; SEG_SIZE],
/// What entries contain valid data?
valid: [AtomicBool; SEG_SIZE],
/// The next node.
next: Atomic<Segment<T>>,
}
impl<T> Default for Segment<T> {
fn default(... | {
enum LR {
Left(i64),
Right(i64),
}
let q: Arc< | eue_dequeue_many_mpmc() | identifier_name |
seg_queue.rs | {
write!(f, "Segment {{ ... }}")
}
}
unsafe impl<T: Send> Sync for Segment<T> {}
/// An faster, unrolled Michael-Scott queue.
///
/// This queue, usable with any number of producers and consumers, stores so called segments
/// (arrays of nodes) in order to be more lightweight.
#[derive(Debug)]
pub struct... | for _i in 0..CONC_COUNT {
match qc.dequeue() {
Some(LR::Left(x)) => vl.push(x),
Some(LR::Right(x)) => vr.push(x),
_ => {} | random_line_split | |
seg_queue.rs | struct Segment<T> {
/// The used entries in the segment.
used: Range<AtomicUsize>,
/// The data.
data: [UnsafeCell<T>; SEG_SIZE],
/// What entries contain valid data?
valid: [AtomicBool; SEG_SIZE],
/// The next node.
next: Atomic<Segment<T>>,
}
impl<T> Default for Segment<T> {
fn de... | // Write that data.
unsafe {
// Obtain the cell.
let cell = (*tail).data[i].get();
// Write the data into the cell.
ptr::write(&mut *cell, elem);
// Now that the cell is initialized, we can set the valid flag.
... | continue;
}
| conditional_block |
Helpers.ts | /**
* Helpers.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
import { Fun } from '@ephox/katamari';
import Tools from 'tinymce/core/api/util/Tools';
import Util from... | editor,
function (value) {
evt.control.value(value).fire('change');
},
evt.control.value()
);
};
}
};
return {
title: 'Advanced',
type: 'form',
defaults: {
onchange: Fun.curry(updateStyleField, editor)
},
items: [
... | if (colorPickerCallback) {
return function (evt) {
return colorPickerCallback.call( | random_line_split |
Helpers.ts | /**
* Helpers.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
import { Fun } from '@ephox/katamari';
import Tools from 'tinymce/core/api/util/Tools';
import Util from... |
rootControl.find('#style').value(dom.serializeStyle(dom.parseStyle(dom.serializeStyle(css))));
};
const extractAdvancedStyles = function (dom, elm) {
const css = dom.parseStyle(dom.getAttrib(elm, 'style'));
const data: any = {};
if (css['border-style']) {
data.borderStyle = css['border-style'];
}
i... | {
css['border-style'] = data.borderStyle;
css['border-color'] = data.borderColor;
css['background-color'] = data.backgroundColor;
css.width = data.width ? Util.addSizeSuffix(data.width) : '';
css.height = data.height ? Util.addSizeSuffix(data.height) : '';
} | conditional_block |
conftest.py | import pytest
import sys
import logging
from sqlalchemy import create_engine
import zk.model.meta as zkmeta
import zkpylons.model.meta as pymeta
from zkpylons.config.routing import make_map
from paste.deploy import loadapp
from webtest import TestApp
from paste.fixture import Dummy_smtplib
from .fixtures import Co... | def execute(self, *args, **kwargs):
return self.s1.execute(*args, **kwargs)
base_general_config = {
'sponsors' : {"top":[],"slideshow":[]},
'account_creation' : True,
'cfp_status' : "open",
'conference_status' : "open",
}
base_rego_config = {
... | random_line_split | |
conftest.py | import pytest
import sys
import logging
from sqlalchemy import create_engine
import zk.model.meta as zkmeta
import zkpylons.model.meta as pymeta
from zkpylons.config.routing import make_map
from paste.deploy import loadapp
from webtest import TestApp
from paste.fixture import Dummy_smtplib
from .fixtures import Co... |
base_general_config = {
'sponsors' : {"top":[],"slideshow":[]},
'account_creation' : True,
'cfp_status' : "open",
'conference_status' : "open",
}
base_rego_config = {
'personal_info' : {"phone":"yes","home_address":"yes"}
}
@pytest.yield_fixtu... | return self.s1.execute(*args, **kwargs) | identifier_body |
conftest.py | import pytest
import sys
import logging
from sqlalchemy import create_engine
import zk.model.meta as zkmeta
import zkpylons.model.meta as pymeta
from zkpylons.config.routing import make_map
from paste.deploy import loadapp
from webtest import TestApp
from paste.fixture import Dummy_smtplib
from .fixtures import Co... |
dsess.commit()
# Run the actual test
yield dsess
# No rollback, for functional tests we have to actually commit to DB
@pytest.yield_fixture
def smtplib():
Dummy_smtplib.install()
yield Dummy_smtplib
if Dummy_smtplib.existing:
Dummy_smtplib.existing.reset()
| ConfigFactory(category='rego', key=key, value=val) | conditional_block |
conftest.py | import pytest
import sys
import logging
from sqlalchemy import create_engine
import zk.model.meta as zkmeta
import zkpylons.model.meta as pymeta
from zkpylons.config.routing import make_map
from paste.deploy import loadapp
from webtest import TestApp
from paste.fixture import Dummy_smtplib
from .fixtures import Co... | (self, engine):
self.s1.configure(bind=engine)
self.s2.configure(bind=engine)
self.s1.configure(autoflush=False)
self.s2.configure(autoflush=False)
def commit(self):
self.s1.commit()
self.s2.commit()
# TODO: Maybe expire_all or refresh would be better
def e... | configure | identifier_name |
antiFloodBot.py | import os
import time
import json
import pprint
from util import hook
def readConfig():
### Read config json and parse it
|
inputs = {} #store time (unixtimestamp in sec) of every entry sent by user in map where key is user nickname
kicked = [] #store nicknames of kicked users
conf = readConfig()
timeIntervalScope = conf['timeIntervalScope'] # interval when entries are collected [sec]
entryThreshold = conf['entryThreshold'] #how many e... | confJson = None
with open(os.getcwd() + '/antiFloodBotConfig.json', 'r') as confFile:
confJson = confFile.read()
return json.loads(confJson) | identifier_body |
antiFloodBot.py | import os
import time
import json
import pprint
from util import hook
def readConfig():
### Read config json and parse it
confJson = None
with open(os.getcwd() + '/antiFloodBotConfig.json', 'r') as confFile:
confJson = confFile.read()
return json.loads(confJson)
inputs = {} #store time (uni... |
#todo
#if the same user joins again within 24 hour and keeps spamming temp ban in XX time.
#step 3) if the same user joins after the removal of the ban and spams, permanent ban.
@hook.event('PRIVMSG')
def paramDump(inp, nick=None, msg=None, conn=None, chan=None):
def saveToFile(file, label, obj):
file.... | explanationMessage = conf['kickMessage']
file = open(logFile, 'a')
file.write('Trying to kick %s on channel %s \n' % (nick, chan))
if nick in kicked:
explanationMessage = conf['banMessage']
out = "MODE %s +b %s" % (chan, nick)
conn.send(out)
file.... | conditional_block |
antiFloodBot.py | import os
import time
import json |
def readConfig():
### Read config json and parse it
confJson = None
with open(os.getcwd() + '/antiFloodBotConfig.json', 'r') as confFile:
confJson = confFile.read()
return json.loads(confJson)
inputs = {} #store time (unixtimestamp in sec) of every entry sent by user in map where key is use... | import pprint
from util import hook | random_line_split |
antiFloodBot.py | import os
import time
import json
import pprint
from util import hook
def | ():
### Read config json and parse it
confJson = None
with open(os.getcwd() + '/antiFloodBotConfig.json', 'r') as confFile:
confJson = confFile.read()
return json.loads(confJson)
inputs = {} #store time (unixtimestamp in sec) of every entry sent by user in map where key is user nickname
kick... | readConfig | identifier_name |
service.py | # Version 1.14: Added forced_down
# Version 1.15: ComputeNode version 1.12
# Version 1.16: Added version
# Version 1.17: ComputeNode version 1.13
# Version 1.18: ComputeNode version 1.14
# Version 1.19: Added get_minimum_version()
# Version 1.20: Added get_minimum_version_multi()
# Version ... | updates['uuid'] = uuidutils.generate_uuid()
self.uuid = updates['uuid'] | conditional_block | |
service.py | , binary):
try:
db_service = db.service_get_by_host_and_binary(context,
host, binary)
except exception.HostBinaryNotFound:
return
return cls._from_db_object(context, cls(), db_service)
@staticmethod
@db.s... | db_services = db.service_get_all_computes_by_hv_type(
context, hv_type, include_disabled=False)
return base.obj_make_list(context, cls(context), objects.Service,
db_services) | identifier_body | |
service.py | RPC version 4.13
{'compute_rpc': '4.13'},
# Version 14: The compute manager supports setting device tags.
{'compute_rpc': '4.13'},
# Version 15: Indicate that nova-conductor will stop a boot if BuildRequest
# is deleted before RPC to nova-compute.
{'compute_rpc': '4.13'},
# Version 16: Indi... | del primitive['uuid']
if _target_version < (1, 16) and 'version' in primitive:
del primitive['version']
if _target_version < (1, 14) and 'forced_down' in primitive:
del primitive['forced_down']
if _target_version < (1, 13) and 'last_seen_up' in primitive:
... | primitive, target_version, version_manifest)
_target_version = versionutils.convert_version_to_tuple(target_version)
if _target_version < (1, 21) and 'uuid' in primitive: | random_line_split |
service.py | RPC version 4.13
{'compute_rpc': '4.13'},
# Version 14: The compute manager supports setting device tags.
{'compute_rpc': '4.13'},
# Version 15: Indicate that nova-conductor will stop a boot if BuildRequest
# is deleted before RPC to nova-compute.
{'compute_rpc': '4.13'},
# Version 16: Indi... | (cls, context, service_uuid):
db_service = db.service_get_by_uuid(context, service_uuid)
return cls._from_db_object(context, cls(), db_service)
@ | get_by_uuid | identifier_name |
term.rs | pub static GREEN: Color = 2u16;
pub static YELLOW: Color = 3u16;
pub static BLUE: Color = 4u16;
pub static MAGENTA: Color = 5u16;
pub static CYAN: Color = 6u16;
pub static WHITE: Color = 7u16;
pub static BRIGHT_BLACK: Color = 8u16;
pub static BRIGHT_RED: Color = 9u16;
... | pub mod color {
pub type Color = u16;
pub static BLACK: Color = 0u16;
pub static RED: Color = 1u16; | random_line_split | |
error.rs | pub use crate::api::naming::error as naming;
pub use crate::rosxmlrpc::error as rosxmlrpc;
pub use crate::rosxmlrpc::ResponseError;
pub use crate::tcpros::error as tcpros;
error_chain::error_chain! {
foreign_links {
Io(::std::io::Error);
FromUTF8(::std::string::FromUtf8Error);
Response(Resp... | error_chain::error_chain! {
errors {
SystemFail(message: String) {
description("Failure to handle API call")
display("Failure to handle API call: {}", message)
}
BadData(message: String) {
description("Bad parameters provide... | pub mod api { | random_line_split |
rest_api.rs | use db;
use hyper::header::Authorization;
use iron;
use iron::prelude::*;
use iron::status;
use iron::status::Status;
use router::Router;
use serde_json;
use std::error::Error;
use std::fmt;
use std::io::Read;
use utils::json_response;
pub fn rest_router() -> Router {
let mut router = Router::new();
router.ge... |
fn _tile_post(req: &mut Request) -> Result<(Status, String), Box<Error>> {
let (dashboard_name, tile_id) = {
let router = req.extensions.get::<Router>().unwrap();
(
router.find("dashboard_name").unwrap(),
router.find("tile_id").unwrap(),
)
};
let request_tok... | {
let (dashboard_name, tile_id) = {
let router = req.extensions.get::<Router>().unwrap();
(
router.find("dashboard_name").unwrap(),
router.find("tile_id").unwrap(),
)
};
let db = match db::Db::new() {
Err(e) => return json_response(Status::InternalSer... | identifier_body |
rest_api.rs | use db;
use hyper::header::Authorization;
use iron;
use iron::prelude::*;
use iron::status;
use iron::status::Status;
use router::Router;
use serde_json;
use std::error::Error;
use std::fmt;
use std::io::Read;
use utils::json_response;
pub fn rest_router() -> Router {
let mut router = Router::new();
router.ge... | (req: &mut Request) -> IronResult<Response> {
let (dashboard_name, tile_id) = {
let router = req.extensions.get::<Router>().unwrap();
(
router.find("dashboard_name").unwrap(),
router.find("tile_id").unwrap(),
)
};
let db = match db::Db::new() {
Err(e)... | tile_get | identifier_name |
rest_api.rs | use db;
use hyper::header::Authorization;
use iron;
use iron::prelude::*;
use iron::status;
use iron::status::Status;
use router::Router;
use serde_json;
use std::error::Error;
use std::fmt;
use std::io::Read;
use utils::json_response;
pub fn rest_router() -> Router {
let mut router = Router::new();
router.ge... | }
}
}
pub fn tile_get(req: &mut Request) -> IronResult<Response> {
let (dashboard_name, tile_id) = {
let router = req.extensions.get::<Router>().unwrap();
(
router.find("dashboard_name").unwrap(),
router.find("tile_id").unwrap(),
)
};
let db = ma... | status::Forbidden,
))
}
Some(_) => Ok(()), | random_line_split |
pageCache.jest.ts | import { pageCacheMiddleware } from "../pageCache"
const { cache } = require("lib/cache")
jest.mock("lib/cache", () => ({
cache: {
get: jest.fn().mockResolvedValue(true),
set: jest.fn(),
},
}))
jest.mock("config", () => ({
PAGE_CACHE_ENABLED: true,
PAGE_CACHE_TYPES: "artist",
PAGE_CACHE_NAMESPACE: ... | expect(next).toBeCalled()
})
}) | url: "https://artsy.net/artist-series/test-artist",
}
await pageCacheMiddleware(req, res, next)
expect(cache.set).not.toBeCalled()
expect(cache.get).not.toBeCalled() | random_line_split |
util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ==============================================================================
# MIT License
#
# Copyright (c) 2017-2019 4k1
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "S... |
try:
f = open(self.__fn + str(tid) + ".log", "a")
f.write(value + '\r\n')
f.close()
except:
None
def warn(self, value):
with self.__lock:
try:
f = open(self.__fn + "!.log", "a")
f.write(value + '\r\... | return | conditional_block |
util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ==============================================================================
# MIT License
#
# Copyright (c) 2017-2019 4k1
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "S... | try:
f = open(self.__fn + str(tid) + ".log", "a")
f.write(value + '\r\n')
f.close()
except:
None
def warn(self, value):
with self.__lock:
try:
f = open(self.__fn + "!.log", "a")
f.write(value + '\r\n... | logmode = False
def __init__(self):
self.__lock = threading.Lock()
# create dir
projdir = "proj_" + datetime.datetime.today().strftime("%Y%m%d_%H%M%S")
os.mkdir(projdir)
self.__fn = projdir + "/" + datetime.datetime.today().strftime("%Y%m%d_%H%M%S... | identifier_body |
util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ==============================================================================
# MIT License
#
# Copyright (c) 2017-2019 4k1
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "S... | def set_logging_mode(self, logmode):
self.logmode = logmode
def log(self, tid, value):
if self.logmode:
return
try:
f = open(self.__fn + str(tid) + ".log", "a")
f.write(value + '\r\n')
f.close()
except:
None
de... | return self.__fn
| random_line_split |
util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ==============================================================================
# MIT License
#
# Copyright (c) 2017-2019 4k1
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "S... | ():
logmode = False
def __init__(self):
self.__lock = threading.Lock()
# create dir
projdir = "proj_" + datetime.datetime.today().strftime("%Y%m%d_%H%M%S")
os.mkdir(projdir)
self.__fn = projdir + "/" + datetime.datetime.today().strftime("... | Logging | identifier_name |
add.rs | use anyhow::Result;
use clap::{App, ArgMatches};
use rhq::Workspace;
use std::{env, path::PathBuf};
#[derive(Debug)]
pub struct AddCommand {
paths: Option<Vec<PathBuf>>,
verbose: bool,
}
impl AddCommand {
pub fn | <'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> {
app.about("Add existed repositories into management")
.arg_from_usage("[paths]... 'Location of local repositories'")
.arg_from_usage("-v, --verbose 'Use verbose output'")
}
pub fn from_matches(m: &ArgMatches) -> AddCommand {... | app | identifier_name |
add.rs | use anyhow::Result;
use clap::{App, ArgMatches};
use rhq::Workspace;
use std::{env, path::PathBuf};
#[derive(Debug)]
pub struct AddCommand {
paths: Option<Vec<PathBuf>>,
verbose: bool,
}
impl AddCommand {
pub fn app<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> {
app.about("Add existed repositories... |
let mut workspace = Workspace::new()?.verbose_output(self.verbose);
for path in paths {
workspace.add_repository_if_exists(&path)?;
}
workspace.save_cache()?;
Ok(())
}
} |
pub fn run(self) -> Result<()> {
let paths = self
.paths
.unwrap_or_else(|| vec![env::current_dir().expect("env::current_dir()")]); | random_line_split |
add.rs | use anyhow::Result;
use clap::{App, ArgMatches};
use rhq::Workspace;
use std::{env, path::PathBuf};
#[derive(Debug)]
pub struct AddCommand {
paths: Option<Vec<PathBuf>>,
verbose: bool,
}
impl AddCommand {
pub fn app<'a, 'b: 'a>(app: App<'a, 'b>) -> App<'a, 'b> {
app.about("Add existed repositories... |
pub fn run(self) -> Result<()> {
let paths = self
.paths
.unwrap_or_else(|| vec![env::current_dir().expect("env::current_dir()")]);
let mut workspace = Workspace::new()?.verbose_output(self.verbose);
for path in paths {
workspace.add_repository_if_exist... | {
AddCommand {
paths: m.values_of("paths").map(|s| s.map(PathBuf::from).collect()),
verbose: m.is_present("verbose"),
}
} | identifier_body |
raytracer_pinhole.rs | #![feature(box_syntax)]
use std::io::prelude::*;
use std::fs::File;
use std::ops::{Add, Sub, Mul};
use std::num::Float;
use std::default::Default;
#[derive(Debug, Copy, Clone, Default)]
struct Vector {
x: f64,
y: f64,
z: f64
}
#[derive(Debug, Copy, Clone, Default)]
struct Ray {
o: Vector,
d: Vect... |
if (b - det) > eps {
return b-det;
}
if (b + det) > eps {
return b+det;
}
return 0.0;
}
}
static LIGHT: Ray = Ray { o: Vector{x: 0.0, y: 0.0, z: 0.0 }, d: Vector{x: 0.0, y: 0.0, z: 1.0 } };
impl<'a> ShapeRef for &'a Sphere {
fn color(self, r... | {
det = det.sqrt();
} | conditional_block |
raytracer_pinhole.rs | #![feature(box_syntax)]
use std::io::prelude::*;
use std::fs::File;
use std::ops::{Add, Sub, Mul};
use std::num::Float;
use std::default::Default;
#[derive(Debug, Copy, Clone, Default)]
struct Vector {
x: f64,
y: f64,
z: f64
}
#[derive(Debug, Copy, Clone, Default)]
struct Ray {
o: Vector,
d: Vect... | (self, b: Vector) -> Vector {
Vector{x: self.y * b.z - self.z * b.y, y: self.z * b.x - self.x * b.z, z: self.x * b.y - self.y * b.x}
}
fn dot(&self, other: &Vector) -> f64 {
(*self).x * (*other).x + (*self).y * (*other).y + (*self).z * (*other).z
}
}
fn clamp(x: f64) -> f64
{
if x < 0.... | cross | identifier_name |
raytracer_pinhole.rs | #![feature(box_syntax)]
use std::io::prelude::*;
use std::fs::File;
use std::ops::{Add, Sub, Mul};
use std::num::Float;
use std::default::Default;
#[derive(Debug, Copy, Clone, Default)]
struct Vector {
x: f64,
y: f64,
z: f64
}
#[derive(Debug, Copy, Clone, Default)]
struct Ray {
o: Vector,
d: Vect... | let mut cam: Camera = Default::default();
cam.eye.o = Vector {x: 0.0, y: 0.0, z: 1.0};
cam.eye.d = Vector {x: 0.0, y: 0.0, z: -1.0};
cam.up = Vector{x: 0.0, y: 1.0, z: 0.0};
let mut output = box [[Vector{x: 0.0, y: 0.0, z: 0.0}; WIDTH]; HEIGHT];
for i in 0..HEIGHT {
for j in 0..WIDTH {
... | const HEIGHT: usize = 500;
fn main() {
println!("Raytracing...");
| random_line_split |
gpu-donut-chart.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | else if (this.get("gpu-render-type") === "gpu-utilization") {
var utilization = parseFloat(this.get("gpuInfo").gpuUtilizations.overallGpuUtilization);
data.push({
label: "Utilized",
value: utilization,
});
data.push({
label: "Available",
value: 100 - utilization
... | {
data.push({
label: "Used",
value: parseFloat(this.get("gpuInfo").gpuMemoryUsage.usedMemoryMiB),
});
data.push({
label: "Available",
value: parseFloat(this.get("gpuInfo").gpuMemoryUsage.availMemoryMiB)
});
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.