file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
markdown-to-jsx-tests.tsx | import Markdown, { compiler } from 'markdown-to-jsx';
import * as React from 'react';
import { render } from 'react-dom';
render(<Markdown># Hello world!</Markdown>, document.body);
<Markdown options={{ forceBlock: true }}>Hello there old chap!</Markdown>;
compiler('Hello there old chap!', { forceBlock: true });
<Ma... |
return <img alt={props.alt} src={props.src} width={width} height={height} />;
};
interface MyStatelessRoundImageProps {
src: string;
alt?: string;
size?: number;
}
class MyStatelessRoundImage extends React.Component<MyStatelessRoundImageProps> {
render() {
let width: string | undefined;
... | {
width = `${props.size}px`;
height = `${props.size}px`;
} | conditional_block |
orm.py | # -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import django
import patchy
from django.db.models.deletion import get_candidate_relations_to_delete
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
from django.db.models.sql.... |
patch_ORM_to_be_deterministic.have_patched = False
def patch_QuerySet():
patchy.patch(QuerySet.annotate, """\
@@ -17,7 +17,7 @@
except (AttributeError, TypeError):
raise TypeError("Complex annotations require an alias")
annotations[arg.default_alia... | patch_delete() | conditional_block |
orm.py | # -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import django
import patchy
from django.db.models.deletion import get_candidate_relations_to_delete
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
from django.db.models.sql.... | raise TypeError("Complex annotations require an alias")
annotations[arg.default_alias] = arg
- annotations.update(kwargs)
+ annotations.update(sorted(kwargs.items()))
clone = self._clone()
names = self._fields
""")
def patch_Qu... | patchy.patch(QuerySet.annotate, """\
@@ -17,7 +17,7 @@
except (AttributeError, TypeError): | random_line_split |
orm.py | # -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import django
import patchy
from django.db.models.deletion import get_candidate_relations_to_delete
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
from django.db.models.sql.... |
patch_ORM_to_be_deterministic.have_patched = False
def patch_QuerySet():
patchy.patch(QuerySet.annotate, """\
@@ -17,7 +17,7 @@
except (AttributeError, TypeError):
raise TypeError("Complex annotations require an alias")
annotations[arg.default_alia... | """
Django's ORM is non-deterministic with regards to the queries it outputs
for e.g. OR clauses. We need it to be deterministic so that we can compare
queries between runs, so we make a couple patches to its internals to do
this. Mostly this is done by adding sorted() in some places so we're not
af... | identifier_body |
orm.py | # -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import django
import patchy
from django.db.models.deletion import get_candidate_relations_to_delete
from django.db.models.query import QuerySet
from django.db.models.query_utils import Q
from django.db.models.sql.... | ():
patchy.patch(QuerySet.annotate, """\
@@ -17,7 +17,7 @@
except (AttributeError, TypeError):
raise TypeError("Complex annotations require an alias")
annotations[arg.default_alias] = arg
- annotations.update(kwargs)
+ annotations.... | patch_QuerySet | identifier_name |
backend.py | #!/usr/bin/python
"""
Resources:
http://code.google.com/p/pybluez/
http://lightblue.sourceforge.net/
http://code.google.com/p/python-bluetooth-scanner
"""
from __future__ import with_statement
import select
import logging
import bluetooth
import gobject
import util.misc as misc_utils
_moduleLogger = logging.getL... |
def get_contacts(self):
try:
self._disco.find_devices(
duration=self._timeout,
flush_cache = True,
lookup_names = True,
)
self._disco.process_inquiry()
except bluetooth.BluetoothError, e:
# lightblue does this, so I guess I will too
_moduleLogger.error("Error while getting contacts, at... | listener.stop() | conditional_block |
backend.py | #!/usr/bin/python
"""
Resources:
http://code.google.com/p/pybluez/
http://lightblue.sourceforge.net/
http://code.google.com/p/python-bluetooth-scanner
"""
from __future__ import with_statement
import select
import logging
import bluetooth
import gobject
import util.misc as misc_utils
_moduleLogger = logging.getL... | (self):
return self.description
MAJOR_CLASS = BluetoothClass("Major Class")
MAJOR_CLASS.MISCELLANEOUS = BluetoothClass("Miscellaneous")
MAJOR_CLASS.COMPUTER = BluetoothClass("Computer")
MAJOR_CLASS.PHONE = BluetoothClass("Phone")
MAJOR_CLASS.LAN = BluetoothClass("LAN/Network Access Point")
MAJOR_CLASS.AV = Bluetoot... | __str__ | identifier_name |
backend.py | #!/usr/bin/python
"""
Resources:
http://code.google.com/p/pybluez/
http://lightblue.sourceforge.net/
http://code.google.com/p/python-bluetooth-scanner
"""
from __future__ import with_statement
import select
import logging
import bluetooth
import gobject
import util.misc as misc_utils
_moduleLogger = logging.getL... | sock.settimeout(self._timeout)
try:
sock.connect((addr, port))
except bluetooth.error, e:
sock.close()
raise
return _BluetoothConnection(sock, addr, "")
gobject.type_register(BluetoothBackend)
class BluetoothClass(object):
def __init__(self, description):
self.description = description
def _... | random_line_split | |
backend.py | #!/usr/bin/python
"""
Resources:
http://code.google.com/p/pybluez/
http://lightblue.sourceforge.net/
http://code.google.com/p/python-bluetooth-scanner
"""
from __future__ import with_statement
import select
import logging
import bluetooth
import gobject
import util.misc as misc_utils
_moduleLogger = logging.getL... |
@property
def isListening(self):
return self._socket is not None and self._incomingId is not None
@property
def socket(self):
assert self._socket is not None
return self._socket
@misc_utils.log_exception(_moduleLogger)
def _on_incoming(self, source, condition):
newSocket, (address, port) = self._socke... | if self._socket is None or self._incomingId is None:
return
gobject.source_remove(self._incomingId)
self._incomingId = None
bluetooth.stop_advertising(self._socket)
self._socket.close()
self._socket = None
self.emit("stop_listening") | identifier_body |
tensor_array.py | #
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
if __name__ == "__main__":
main()
| tf.set_random_seed(10)
with tf.Session() as sess:
inputs = tf.Variable(tf.random_uniform((20, 30, 32)), name = 'input')
inputs = tf.identity(inputs, "input_node")
input1, input2, input3, input4 = tf.split(inputs, 4, 0)
# scatter and gather
tensor_array = tf.TensorArray(tf.fl... | identifier_body |
tensor_array.py | #
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | ():
tf.set_random_seed(10)
with tf.Session() as sess:
inputs = tf.Variable(tf.random_uniform((20, 30, 32)), name = 'input')
inputs = tf.identity(inputs, "input_node")
input1, input2, input3, input4 = tf.split(inputs, 4, 0)
# scatter and gather
tensor_array = tf.TensorArr... | main | identifier_name |
tensor_array.py | #
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | main() | conditional_block | |
tensor_array.py | #
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | inputs = tf.Variable(tf.random_uniform((20, 30, 32)), name = 'input')
inputs = tf.identity(inputs, "input_node")
input1, input2, input3, input4 = tf.split(inputs, 4, 0)
# scatter and gather
tensor_array = tf.TensorArray(tf.float32, 128)
tensor_array = tensor_array.scatte... | with tf.Session() as sess: | random_line_split |
DashboardView.js | /*
* Copyright (C) 2013-2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditi... | (representedObject, identifier)
{
console.assert(identifier);
super();
this._representedObject = representedObject;
this._element = document.createElement("div");
this._element.classList.add("dashboard");
this._element.classList.add(identifier);
}
// Stati... | constructor | identifier_name |
DashboardView.js | /*
* Copyright (C) 2013-2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditi... | // Implemented by subclasses.
}
closed()
{
// Implemented by subclasses.
}
}; | }
hidden()
{ | random_line_split |
DashboardView.js | /*
* Copyright (C) 2013-2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditi... |
get representedObject()
{
return this._representedObject;
}
shown()
{
// Implemented by subclasses.
}
hidden()
{
// Implemented by subclasses.
}
closed()
{
// Implemented by subclasses.
}
};
| {
return this._element;
} | identifier_body |
edit_subset_mode_toolbar.py | from __future__ import absolute_import, division, print_function
from ...external.qt import QtGui
from ...core.edit_subset_mode import (EditSubsetMode, OrMode, AndNotMode,
AndMode, XorMode, ReplaceMode)
from ..actions import act
from ..qtutil import nonpartial
def set_mode(mode... | self._modes[mode].trigger() | mode = self._backup_mode
self._backup_mode = None
if mode: | random_line_split |
edit_subset_mode_toolbar.py | from __future__ import absolute_import, division, print_function
from ...external.qt import QtGui
from ...core.edit_subset_mode import (EditSubsetMode, OrMode, AndNotMode,
AndMode, XorMode, ReplaceMode)
from ..actions import act
from ..qtutil import nonpartial
def set_mode(mode... | (self, mode):
"""Temporarily set the edit mode to mode
:param mode: Name of the mode (Or, Not, And, Xor, Replace)
:type mode: str
"""
try:
mode = self._modes[mode] # label to mode class
except KeyError:
raise KeyError("Unrecognized mode: %s" % mod... | set_mode | identifier_name |
edit_subset_mode_toolbar.py | from __future__ import absolute_import, division, print_function
from ...external.qt import QtGui
from ...core.edit_subset_mode import (EditSubsetMode, OrMode, AndNotMode,
AndMode, XorMode, ReplaceMode)
from ..actions import act
from ..qtutil import nonpartial
def set_mode(mode... | self._modes[mode].trigger() | conditional_block | |
edit_subset_mode_toolbar.py | from __future__ import absolute_import, division, print_function
from ...external.qt import QtGui
from ...core.edit_subset_mode import (EditSubsetMode, OrMode, AndNotMode,
AndMode, XorMode, ReplaceMode)
from ..actions import act
from ..qtutil import nonpartial
def set_mode(mode... |
class EditSubsetModeToolBar(QtGui.QToolBar):
def __init__(self, title="Subset Update Mode", parent=None):
super(EditSubsetModeToolBar, self).__init__(title, parent)
self._group = QtGui.QActionGroup(self)
self._modes = {}
self._add_actions()
self._modes[EditSubsetMode().mo... | edit_mode = EditSubsetMode()
edit_mode.mode = mode | identifier_body |
my_music.py | from feeluown.utils.dispatch import Signal
from feeluown.gui.widgets.my_music import MyMusicModel
class MyMusicItem(object):
def __init__(self, text):
self.text = text
self.clicked = Signal()
class MyMusicUiManager:
"""
.. note::
目前,我们用数组的数据结构来保存 items,只提供 add_item 和 clear 方法。 |
而 Provider 是比较上层的对象,我们会提供 get_item 这种比较精细的控制方法。
"""
def __init__(self, app):
self._app = app
self._items = []
self.model = MyMusicModel(app)
@classmethod
def create_item(cls, text):
return MyMusicItem(text)
def add_item(self, item):
self.model.add(i... | 我们希望,MyMusic 中的 items 应该和 provider 保持关联。provider 是 MyMusic
的上下文。 | random_line_split |
my_music.py | from feeluown.utils.dispatch import Signal
from feeluown.gui.widgets.my_music import MyMusicModel
class | (object):
def __init__(self, text):
self.text = text
self.clicked = Signal()
class MyMusicUiManager:
"""
.. note::
目前,我们用数组的数据结构来保存 items,只提供 add_item 和 clear 方法。
我们希望,MyMusic 中的 items 应该和 provider 保持关联。provider 是 MyMusic
的上下文。
而 Provider 是比较上层的对象,我们会提供 g... | MyMusicItem | identifier_name |
my_music.py | from feeluown.utils.dispatch import Signal
from feeluown.gui.widgets.my_music import MyMusicModel
class MyMusicItem(object):
def __init__(self, text):
|
class MyMusicUiManager:
"""
.. note::
目前,我们用数组的数据结构来保存 items,只提供 add_item 和 clear 方法。
我们希望,MyMusic 中的 items 应该和 provider 保持关联。provider 是 MyMusic
的上下文。
而 Provider 是比较上层的对象,我们会提供 get_item 这种比较精细的控制方法。
"""
def __init__(self, app):
self._app = app
self._... | self.text = text
self.clicked = Signal() | identifier_body |
simpledb.py | #!/usr/bin/python
'''
Created on May 14, 2012
@author: Charlie
'''
import ConfigParser
import boto
import cgitb
cgitb.enable()
class MyClass(object):
def __init__(self, domain):
config = ConfigParser.RawConfigParser()
config.read('.boto')
key = config.get('Credentials', 'aws_access_key_i... | (self):
domains = self.conn.get_all_domains()
print domains
def createDomain(self):
self.conn.create_domain(self.domain)
def addData(self, itemName, itemAttrs):
dom = self.conn.get_domain(self.domain)
item_name = itemName
dom.put_attributes(item_name, itemAttrs)... | showDomains | identifier_name |
simpledb.py | #!/usr/bin/python
'''
Created on May 14, 2012
@author: Charlie
'''
import ConfigParser
import boto
import cgitb
cgitb.enable()
class MyClass(object):
def __init__(self, domain):
|
def showDomains(self):
domains = self.conn.get_all_domains()
print domains
def createDomain(self):
self.conn.create_domain(self.domain)
def addData(self, itemName, itemAttrs):
dom = self.conn.get_domain(self.domain)
item_name = itemName
dom.put_attributes(... | config = ConfigParser.RawConfigParser()
config.read('.boto')
key = config.get('Credentials', 'aws_access_key_id')
secretKey = config.get('Credentials', 'aws_secret_access_key')
self.conn = boto.connect_sdb(key, secretKey)
self.domain = domain | identifier_body |
simpledb.py | #!/usr/bin/python
'''
Created on May 14, 2012
@author: Charlie
'''
import ConfigParser
import boto
import cgitb
cgitb.enable()
class MyClass(object):
def __init__(self, domain):
config = ConfigParser.RawConfigParser()
config.read('.boto')
key = config.get('Credentials', 'aws_access_key_i... |
xml += "\t</line>\n"
xml += '</test01>'
return xml
my_class = MyClass("Test01")
# my_class.addData('Line01', {'Field01': 'one', 'Field02': 'two'})
# my_class.showDomains()
print my_class.showQuery('select * from Test01')
| xml += '\t\t<' + x + '>' + item[x] + '</' + x + '>\n' | conditional_block |
simpledb.py | #!/usr/bin/python
'''
Created on May 14, 2012
@author: Charlie
'''
import ConfigParser
import boto
import cgitb
cgitb.enable()
class MyClass(object):
def __init__(self, domain):
config = ConfigParser.RawConfigParser()
config.read('.boto')
key = config.get('Credentials', 'aws_access_key_i... | xml += '</test01>'
return xml
my_class = MyClass("Test01")
# my_class.addData('Line01', {'Field01': 'one', 'Field02': 'two'})
# my_class.showDomains()
print my_class.showQuery('select * from Test01') | random_line_split | |
karma.conf.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... | '--disable-extensions',
// Allows simulating user actions (e.g unmute) which otherwise will be denied.
'--autoplay-policy=no-user-gesture-required',
];
if (argv.debug) {
COMMON_CHROME_FLAGS.push('--auto-open-devtools-for-tabs');
}
// Used by persistent browserify caching to further salt hashes with our
// env... | // Dramatically speeds up iframe creation time. | random_line_split |
karma.conf.js | /**
* Copyright 2015 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless require... |
// Used by persistent browserify caching to further salt hashes with our
// environment state. Eg, when updating a babel-plugin, the environment hash
// must change somehow so that the cache busts and the file is retransformed.
const createHash = (input) =>
crypto.createHash('sha1').update(input).digest('hex');
co... | {
COMMON_CHROME_FLAGS.push('--auto-open-devtools-for-tabs');
} | conditional_block |
Guides through All Selected Nodes.py | #MenuTitle: Guides through All Selected Nodes
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Creates guides through all selected nodes.
"""
from Foundation import NSPoint
import math
thisFont = Glyphs.font # frontmost font
selectedLayers = thisFont.selectedLayers... |
def newGuide( position, angle=0 ):
try:
# GLYPHS 3
newGuide = GSGuide()
except:
# GLYPHS 2
newGuide = GSGuideLine()
newGuide.position = position
newGuide.angle = angle
return newGuide
def isThereAlreadyAGuideWithTheseProperties(thisLayer,guideposition,guideangle):
if guideangle < 0:
guideangle += 180... | """
Returns the angle (in degrees) of the straight line between firstPoint and secondPoint,
0 degrees being the second point to the right of first point.
firstPoint, secondPoint: must be NSPoint or GSNode
"""
xDiff = secondPoint.x - firstPoint.x
yDiff = secondPoint.y - firstPoint.y
return math.degrees(math.atan2... | identifier_body |
Guides through All Selected Nodes.py | #MenuTitle: Guides through All Selected Nodes
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Creates guides through all selected nodes.
"""
from Foundation import NSPoint
import math
thisFont = Glyphs.font # frontmost font
selectedLayers = thisFont.selectedLayers... | (thisLayer,guideposition,guideangle):
if guideangle < 0:
guideangle += 180
if guideangle > 180:
guideangle -= 180
for thisGuide in thisLayer.guides:
thisAngle = thisGuide.angle
if thisAngle < 0:
thisAngle += 180
if thisAngle > 180:
thisAngle -= 180
if abs(thisAngle - guideangle) < 0.01 and abs(this... | isThereAlreadyAGuideWithTheseProperties | identifier_name |
Guides through All Selected Nodes.py | #MenuTitle: Guides through All Selected Nodes
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Creates guides through all selected nodes.
"""
from Foundation import NSPoint
import math
thisFont = Glyphs.font # frontmost font
selectedLayers = thisFont.selectedLayers... |
return False
if len(selectedLayers) == 1:
thisLayer = selectedLayers[0]
thisGlyph = thisLayer.parent
currentPointSelection = [point.position for point in thisLayer.selection if type(point) in (GSNode,GSAnchor)]
# thisGlyph.beginUndo() # undo grouping causes crashes
try:
if len(currentPointSelection) > 1:
... | thisAngle = thisGuide.angle
if thisAngle < 0:
thisAngle += 180
if thisAngle > 180:
thisAngle -= 180
if abs(thisAngle - guideangle) < 0.01 and abs(thisGuide.position.x - guideposition.x) < 0.01 and abs(thisGuide.position.y - guideposition.y) < 0.01:
return True | conditional_block |
Guides through All Selected Nodes.py | #MenuTitle: Guides through All Selected Nodes
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Creates guides through all selected nodes.
"""
from Foundation import NSPoint
import math
thisFont = Glyphs.font # frontmost font
selectedLayers = thisFont.selectedLayers... | if guideangle > 180:
guideangle -= 180
for thisGuide in thisLayer.guides:
thisAngle = thisGuide.angle
if thisAngle < 0:
thisAngle += 180
if thisAngle > 180:
thisAngle -= 180
if abs(thisAngle - guideangle) < 0.01 and abs(thisGuide.position.x - guideposition.x) < 0.01 and abs(thisGuide.position.y - guid... | random_line_split | |
shell.py | import os
from flask import current_app
from flask.cli import FlaskGroup, run_command
from opsy.db import db
from opsy.app import create_app, create_scheduler
from opsy.utils import load_plugins
DEFAULT_CONFIG = '%s/opsy.ini' % os.path.abspath(os.path.curdir)
def create_opsy_app(info):
return create_app(config=o... |
def main():
with create_opsy_app(None).app_context():
for plugin in load_plugins(current_app):
plugin.register_cli_commands(cli)
cli()
| """Drop everything in cache database and rebuild the schema."""
current_app.logger.info('Creating cache database')
db.drop_all(bind='cache')
db.create_all(bind='cache')
db.session.commit() | identifier_body |
shell.py | import os
from flask import current_app
from flask.cli import FlaskGroup, run_command
from opsy.db import db
from opsy.app import create_app, create_scheduler
from opsy.utils import load_plugins
DEFAULT_CONFIG = '%s/opsy.ini' % os.path.abspath(os.path.curdir)
def create_opsy_app(info):
return create_app(config=o... |
shell_ctx.update(app.make_shell_context())
try:
from IPython import embed
embed(user_ns=shell_ctx, banner1=banner)
return
except ImportError:
import code
code.interact(banner, local=shell_ctx)
@cli.command('init-cache')
def init_cache():
"""Drop everything in c... | plugin.register_shell_context(shell_ctx) | conditional_block |
shell.py | import os
from flask import current_app
from flask.cli import FlaskGroup, run_command
from opsy.db import db
from opsy.app import create_app, create_scheduler
from opsy.utils import load_plugins
DEFAULT_CONFIG = '%s/opsy.ini' % os.path.abspath(os.path.curdir)
def create_opsy_app(info):
return create_app(config=o... | ():
"""Drop everything in cache database and rebuild the schema."""
current_app.logger.info('Creating cache database')
db.drop_all(bind='cache')
db.create_all(bind='cache')
db.session.commit()
def main():
with create_opsy_app(None).app_context():
for plugin in load_plugins(current_app)... | init_cache | identifier_name |
shell.py | import os
from flask import current_app
from flask.cli import FlaskGroup, run_command
from opsy.db import db
from opsy.app import create_app, create_scheduler
from opsy.utils import load_plugins | def create_opsy_app(info):
return create_app(config=os.environ.get('OPSY_CONFIG', DEFAULT_CONFIG))
cli = FlaskGroup(create_app=create_opsy_app, # pylint: disable=invalid-name
add_default_commands=False,
help='The Opsy management cli.')
cli.add_command(run_command)
@cli.command... |
DEFAULT_CONFIG = '%s/opsy.ini' % os.path.abspath(os.path.curdir)
| random_line_split |
server_decoration.rs | //! Support for the KDE Server Decoration Protocol
use crate::wayland_sys::server::wl_display as wl_server_display;
pub use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode;
use wlroots_sys::{
wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_cr... | else {
None
}
}
/// Given a mode, set the server decoration mode
pub fn set_default_mode(&mut self, mode: Mode) {
wlr_log!(WLR_INFO, "New server decoration mode: {:?}", mode);
unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) }
}
}... | {
Some(Manager { manager: manager_raw })
} | conditional_block |
server_decoration.rs | //! Support for the KDE Server Decoration Protocol
use crate::wayland_sys::server::wl_display as wl_server_display;
pub use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode;
use wlroots_sys::{
wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_cr... |
}
impl Drop for Manager {
fn drop(&mut self) {
unsafe { wlr_server_decoration_manager_destroy(self.manager) }
}
}
| {
wlr_log!(WLR_INFO, "New server decoration mode: {:?}", mode);
unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) }
} | identifier_body |
server_decoration.rs | //! Support for the KDE Server Decoration Protocol
use crate::wayland_sys::server::wl_display as wl_server_display;
pub use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode;
use wlroots_sys::{
wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_cr... | (&mut self, mode: Mode) {
wlr_log!(WLR_INFO, "New server decoration mode: {:?}", mode);
unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) }
}
}
impl Drop for Manager {
fn drop(&mut self) {
unsafe { wlr_server_decoration_manager_destroy(self.manager) }
... | set_default_mode | identifier_name |
server_decoration.rs | pub use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode;
use wlroots_sys::{
wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_create,
wlr_server_decoration_manager_destroy, wlr_server_decoration_manager_set_default_mode
};
#[derive(Debug)]
... | //! Support for the KDE Server Decoration Protocol
use crate::wayland_sys::server::wl_display as wl_server_display; | random_line_split | |
views.py | from django.views.generic import TemplateView
#from apiclient.discovery import build
from googleapiclient.discovery import build
from .utils import SearchResults
from . import *
class SearchView(TemplateView):
template_name = "googlesearch/search_results.html"
def get_context_data(self, **kwargs):
c... | results = SearchResults(results)
""" Set some defaults """
context.update({
'items': [],
'total_results': 0,
'current_page': 0,
'prev_page': 0,
'next_page': 0,
'search_terms': self.request.GET.get('q', ''),
... | pages = [0, 1, 2]
| random_line_split |
views.py | from django.views.generic import TemplateView
#from apiclient.discovery import build
from googleapiclient.discovery import build
from .utils import SearchResults
from . import *
class SearchView(TemplateView):
| template_name = "googlesearch/search_results.html"
def get_context_data(self, **kwargs):
context = super(SearchView, self).get_context_data(**kwargs)
service = build("customsearch", GOOGLE_SEARCH_API_VERSION,
developerKey=GOOGLE_SEARCH_API_KEY)
#add a "try" block ... | identifier_body | |
views.py | from django.views.generic import TemplateView
#from apiclient.discovery import build
from googleapiclient.discovery import build
from .utils import SearchResults
from . import *
class | (TemplateView):
template_name = "googlesearch/search_results.html"
def get_context_data(self, **kwargs):
context = super(SearchView, self).get_context_data(**kwargs)
service = build("customsearch", GOOGLE_SEARCH_API_VERSION,
developerKey=GOOGLE_SEARCH_API_KEY)
... | SearchView | identifier_name |
views.py | from django.views.generic import TemplateView
#from apiclient.discovery import build
from googleapiclient.discovery import build
from .utils import SearchResults
from . import *
class SearchView(TemplateView):
template_name = "googlesearch/search_results.html"
def get_context_data(self, **kwargs):
c... |
return int(page) * int(GOOGLE_SEARCH_RESULTS_PER_PAGE) + 1 - int(GOOGLE_SEARCH_RESULTS_PER_PAGE)
| page = self.request.GET.get('p', 1) | conditional_block |
elc_dsi_t1_test.py | #!/usr/bin/env python3
"""
Created on 27 May 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import sys
import time
from scs_dfe.gas.isi.elc_dsi_t1 import ElcDSIt1
from scs_dfe.interface.interface_conf import InterfaceConf
from scs_host.bus.i2c import I2C
from scs_host.sys.host import Host
# ... |
print("-")
while True:
controller.start_conversion()
time.sleep(0.1)
v_wrk, v_aux = controller.read_conversion_voltage()
print('{"wrk": %0.5f, "aux": %0.5f}' % (v_wrk, v_aux))
sys.stdout.flush()
time.sleep(2.0)
except KeyboardInterrupt:
print("-")
fin... | controller.start_conversion()
time.sleep(0.1)
c_wrk, c_aux = controller.read_conversion_voltage()
print('{"wrk": %f, "aux": %f}' % (c_wrk, c_aux))
sys.stdout.flush()
time.sleep(2.0) | conditional_block |
elc_dsi_t1_test.py | #!/usr/bin/env python3
"""
Created on 27 May 2019
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
import sys
import time
from scs_dfe.gas.isi.elc_dsi_t1 import ElcDSIt1
from scs_dfe.interface.interface_conf import InterfaceConf
from scs_host.bus.i2c import I2C
from scs_host.sys.host import Host
# ... |
sys.stdout.flush()
time.sleep(2.0)
print("-")
while True:
controller.start_conversion()
time.sleep(0.1)
v_wrk, v_aux = controller.read_conversion_voltage()
print('{"wrk": %0.5f, "aux": %0.5f}' % (v_wrk, v_aux))
sys.stdout.flush()
time.sleep... | print('{"wrk": %f, "aux": %f}' % (c_wrk, c_aux)) | random_line_split |
test_same_as.py | # Copyright (c) 2015-2019, Activision Publishing, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of ... |
def test_is_not_same_as_failure():
for obj in [object(), 1, 'foo', True, None, 123.456]:
try:
assert_that(obj).is_not_same_as(obj)
fail('should have raised error')
except AssertionError as ex:
assert_that(str(ex)).matches('Expected <.+> to be not identical to <... | assert_that((1,2,3)).is_not_same_as((1,2,3)) | conditional_block |
test_same_as.py | # Copyright (c) 2015-2019, Activision Publishing, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of ... | for obj in [object(), 1, 'foo', True, None, 123.456]:
try:
assert_that(obj).is_not_same_as(obj)
fail('should have raised error')
except AssertionError as ex:
assert_that(str(ex)).matches('Expected <.+> to be not identical to <.+>, but was.') | identifier_body | |
test_same_as.py | # Copyright (c) 2015-2019, Activision Publishing, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of ... | ():
obj = object()
other = object()
assert_that(obj).is_not_same_as(other)
assert_that(obj).is_not_same_as(1)
assert_that(obj).is_not_same_as(True)
assert_that(1).is_not_same_as(2)
assert_that({'a':1}).is_not_same_as({'a':1})
assert_that([1,2,3]).is_not_same_as([1,2,3])
if sys.vers... | test_is_not_same_as | identifier_name |
test_same_as.py | # Copyright (c) 2015-2019, Activision Publishing, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of ... | assert_that([1,2,3]).is_not_same_as([1,2,3])
if sys.version_info[0] == 3 and sys.version_info[1] >= 7:
assert_that((1,2,3)).is_same_as((1,2,3)) # tuples are identical in py 3.7
else:
assert_that((1,2,3)).is_not_same_as((1,2,3))
def test_is_not_same_as_failure():
for obj in [object(), ... | assert_that({'a':1}).is_not_same_as({'a':1}) | random_line_split |
ZxErrorCode.ts | /*
* Copyright (C) 2017 ZeXtras S.r.l.
*
* This program 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, version 2 of
* the License.
*
* This program is distributed in the hope that it will be useful,
... |
export class ZxErrorCode {
public static GENERIC_ERROR: string = "GENERIC_ERROR";
public static CHAT_DB_EXCEPTION: string = "CHAT_DB_EXCEPTION";
public static CHAT_SQL_EXCEPTION: string = "CHAT_SQL_EXCEPTION";
public static CHAT_CONCURRENT_PING: string = "CHAT_CONCURRENT_PING";
public static DELEGATED_OR_RE... | *
* You should have received a copy of the GNU General Public License.
* If not, see <http://www.gnu.org/licenses/>.
*/ | random_line_split |
ZxErrorCode.ts | /*
* Copyright (C) 2017 ZeXtras S.r.l.
*
* This program 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, version 2 of
* the License.
*
* This program is distributed in the hope that it will be useful,
... | (code: string): string { return ZxErrorCode.sMsgs[code]; }
private static sMsgs: {[key: string]: string} = {
AJX_EXCEPTION: "AJX_EXCEPTION",
CHAT_CONCURRENT_PING: "Multiple concurrent pings, older ping has been killed",
CHAT_DB_EXCEPTION: "Chat database error: {message}",
// tslint:disable-next-line:... | getMessage | identifier_name |
ZxErrorCode.ts | /*
* Copyright (C) 2017 ZeXtras S.r.l.
*
* This program 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, version 2 of
* the License.
*
* This program is distributed in the hope that it will be useful,
... |
interface IZxErrorCodeWindow extends Window {
ZxErrorCode: typeof ZxErrorCode;
}
| {
// tslint:disable-next-line:no-string-literal
(window as IZxErrorCodeWindow)["ZxErrorCode"] = ZxErrorCode;
} | conditional_block |
signUpOrLoginFromThirdParty.js | import _ from 'lodash';
import request from 'superagent';
import Promise from 'bluebird';
import { Feedable } from 'models/feedable';
import { User } from 'models/user';
import { Verification } from 'models/verification';
/**
* Signs up or logs in the user from either facebook or google
*
* Each user can have mult... |
}
function createUser() {
return User
.forge( {
name: this.userDetails.name,
image_url: this.userDetails.imageUrl,
last_logged_in: new Date()
} )
.save();
}
function setUser( user ) {
this.user = user;
}
function updateLastLogin() {
return this... | {
//user doesn't exist :-
// 1. create a user
// 2. create a verification and link to user
// 3. return new user
return createUser.call( this )
.then( setUser.bind( this ) )
.then( createVerificationForUser.bind( this ) )
.then( createFeedab... | conditional_block |
signUpOrLoginFromThirdParty.js | import _ from 'lodash';
import request from 'superagent';
import Promise from 'bluebird';
import { Feedable } from 'models/feedable';
import { User } from 'models/user';
import { Verification } from 'models/verification';
/**
* Signs up or logs in the user from either facebook or google
*
* Each user can have mult... | ( user ) {
this.user = user;
}
function updateLastLogin() {
return this.user.save( { last_logged_in: new Date() }, { patch: true } );
}
function createVerificationForUser() {
return Verification
.forge( {
user_id: this.user.id,
provider_name: this.provider,
prov... | setUser | identifier_name |
signUpOrLoginFromThirdParty.js | import _ from 'lodash';
import request from 'superagent';
import Promise from 'bluebird';
import { Feedable } from 'models/feedable';
import { User } from 'models/user';
import { Verification } from 'models/verification';
/**
* Signs up or logs in the user from either facebook or google
*
* Each user can have mult... |
function returnUser() {
return this.user;
}
function getUser( userId ) {
return User
.forge( { id: userId } )
.fetch();
} | {
return Feedable
.forge( {
feedable_id: this.user.get( 'id' ),
feedable_type: 'users',
feedable_meta: {
user: {
id: this.user.get( 'id' ),
name: this.user.get( 'name' ),
image_url: this.user.get(... | identifier_body |
signUpOrLoginFromThirdParty.js | import _ from 'lodash';
import request from 'superagent';
import Promise from 'bluebird';
import { Feedable } from 'models/feedable';
import { User } from 'models/user';
import { Verification } from 'models/verification';
/**
* Signs up or logs in the user from either facebook or google
*
* Each user can have mult... | .then( setUser.bind( this ) )
.then( updateLastLogin.bind( this ) )
.then( setUser.bind( this ) )
.then( returnUser.bind( this ) );
} else {
//user doesn't exist :-
// 1. create a user
// 2. create a verification and link to user
// ... | //user exists - update load_logged in
return getUser.call( this, verification.get( 'user_id' ) ) | random_line_split |
pointing.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Pointing", inherited=True, gecko_... | use style_traits::cursor::Cursor;
#[derive(Clone, PartialEq, Eq, Copy, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum T {
AutoCursor,
SpecifiedCursor(Cursor),
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W)... | use cssparser::ToCss;
use std::fmt; | random_line_split |
pointing.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Pointing", inherited=True, gecko_... |
</%helpers:longhand>
// NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact)
// is nonstandard, slated for CSS4-UI.
// TODO(pcwalton): SVG-only values.
${helpers.single_keyword("pointer-events", "auto none")}
${helpers.single_keyword("-moz-user-input", "none enabled disabled",... | {
use std::ascii::AsciiExt;
use style_traits::cursor::Cursor;
let ident = try!(input.expect_ident());
if ident.eq_ignore_ascii_case("auto") {
Ok(SpecifiedValue::AutoCursor)
} else {
Cursor::from_css_keyword(&ident)
.map(SpecifiedValue::Specifie... | identifier_body |
pointing.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Pointing", inherited=True, gecko_... | (_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
use std::ascii::AsciiExt;
use style_traits::cursor::Cursor;
let ident = try!(input.expect_ident());
if ident.eq_ignore_ascii_case("auto") {
Ok(SpecifiedValue::AutoCursor)
} else {
... | parse | identifier_name |
pointing.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Pointing", inherited=True, gecko_... | else {
Cursor::from_css_keyword(&ident)
.map(SpecifiedValue::SpecifiedCursor)
}
}
</%helpers:longhand>
// NB: `pointer-events: auto` (and use of `pointer-events` in anything that isn't SVG, in fact)
// is nonstandard, slated for CSS4-UI.
// TODO(pcwalton): SVG-only values.
${helper... | {
Ok(SpecifiedValue::AutoCursor)
} | conditional_block |
unformattedFile.ts | module XYZ {
interface I {
x: number,
y,
z
}
var zZz={
a: 123,
b: 456
};
enum En {
AB,
CD
}
var y = 3;
switch(y {
case X:
console.log("x");
break;
default:
console.log("y");
}
if (x === ... |
function xyz() {
function mem() {
console.log("yes");
}
}
} | } | random_line_split |
unformattedFile.ts | module XYZ {
interface I {
x: number,
y,
z
}
var zZz={
a: 123,
b: 456
};
enum En {
AB,
CD
}
var y = 3;
switch(y {
case X:
console.log("x");
break;
default:
console.log("y");
}
if (x === ... | {
private x : number;
constructor() {
console.log("hi");
}
public mem() {
console.log("yes");
}
}
function xyz() {
function mem() {
console.log("yes");
}
}
}
| X | identifier_name |
unformattedFile.ts | module XYZ {
interface I {
x: number,
y,
z
}
var zZz={
a: 123,
b: 456
};
enum En {
AB,
CD
}
var y = 3;
switch(y {
case X:
console.log("x");
break;
default:
console.log("y");
}
if (x === ... |
}
function xyz() {
function mem() {
console.log("yes");
}
}
}
| {
console.log("yes");
} | identifier_body |
__init__.py | #!/usr/bin/env python
"""
This module contains the :class:`.DataType` class and its subclasses. These
types define how data should be converted during the creation of a
:class:`.Table`.
A :class:`TypeTester` class is also included which be used to infer data
types from column data.
"""
from copy import copy
from ag... | """
Infer data types for the columns in a given set of data.
:param force:
A dictionary where each key is a column name and each value is a
:class:`.DataType` instance that overrides inference.
:param limit:
An optional limit on how many rows to evaluate before selecting the
... | identifier_body | |
__init__.py | #!/usr/bin/env python
"""
This module contains the :class:`.DataType` class and its subclasses. These
types define how data should be converted during the creation of a
:class:`.Table`.
A :class:`TypeTester` class is also included which be used to infer data
types from column data.
"""
from copy import copy
from ag... |
return tuple(column_types)
| if t in h:
column_types.append(t)
break | conditional_block |
__init__.py | #!/usr/bin/env python
"""
This module contains the :class:`.DataType` class and its subclasses. These
types define how data should be converted during the creation of a
:class:`.Table`.
A :class:`TypeTester` class is also included which be used to infer data
types from column data.
"""
from copy import copy
from ag... | :param limit:
An optional limit on how many rows to evaluate before selecting the
most likely type. Note that applying a limit may mean errors arise when
the data is cast--if the guess is proved incorrect in further rows of
data.
:param types:
A sequence of possible types... | Infer data types for the columns in a given set of data.
:param force:
A dictionary where each key is a column name and each value is a
:class:`.DataType` instance that overrides inference. | random_line_split |
__init__.py | #!/usr/bin/env python
"""
This module contains the :class:`.DataType` class and its subclasses. These
types define how data should be converted during the creation of a
:class:`.Table`.
A :class:`TypeTester` class is also included which be used to infer data
types from column data.
"""
from copy import copy
from ag... | (object):
"""
Infer data types for the columns in a given set of data.
:param force:
A dictionary where each key is a column name and each value is a
:class:`.DataType` instance that overrides inference.
:param limit:
An optional limit on how many rows to evaluate before selecti... | TypeTester | identifier_name |
font_context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate app_units;
extern crate gfx;
extern crate servo_arc;
extern crate servo_atoms;
extern crate style;
ex... | #[test]
fn test_font_group_find_by_codepoint() {
let source = TestFontSource::new();
let count = source.find_font_count.clone();
let mut context = FontContext::new(source);
let mut style = style();
style.set_font_family(font_family(vec!["CSSTest ASCII", "CSSTest Basic"]));
let group = context.... | "different font groups should be returned for two styles with different hashes"
)
}
| random_line_split |
font_context.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate app_units;
extern crate gfx;
extern crate servo_arc;
extern crate servo_atoms;
extern crate style;
ex... | ) {
let source = TestFontSource::new();
let mut context = FontContext::new(source);
let mut style = style();
style.set_font_family(font_family(vec!["CSSTest ASCII"]));
let group = context.font_group(Arc::new(style));
let font = group
.borrow_mut()
.find_by_codepoint(&mut conte... | est_font_fallback( | identifier_name |
ATNSimulator.js | "use strict";
/*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3... | const DFAState_1 = require("../dfa/DFAState");
const Decorators_1 = require("../Decorators");
const PredictionContext_1 = require("./PredictionContext");
let ATNSimulator = class ATNSimulator {
constructor(atn) {
this.atn = atn;
}
static get ERROR() {
if (!ATNSimulator._ERROR) {
... | exports.ATNSimulator = void 0;
const ATNConfigSet_1 = require("./ATNConfigSet");
| random_line_split |
ATNSimulator.js | "use strict";
/*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3... |
return ATNSimulator._ERROR;
}
/**
* Clear the DFA cache used by the current instance. Since the DFA cache may
* be shared by multiple ATN simulators, this method may affect the
* performance (but not accuracy) of other parsers which are being used
* concurrently.
*
... | {
ATNSimulator._ERROR = new DFAState_1.DFAState(new ATNConfigSet_1.ATNConfigSet());
ATNSimulator._ERROR.stateNumber = PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY;
} | conditional_block |
ATNSimulator.js | "use strict";
/*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3... | (atn) {
this.atn = atn;
}
static get ERROR() {
if (!ATNSimulator._ERROR) {
ATNSimulator._ERROR = new DFAState_1.DFAState(new ATNConfigSet_1.ATNConfigSet());
ATNSimulator._ERROR.stateNumber = PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY;
}
... | constructor | identifier_name |
ATNSimulator.js | "use strict";
/*!
* Copyright 2016 The ANTLR Project. All rights reserved.
* Licensed under the BSD-3-Clause license. See LICENSE file in the project root for license information.
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3... |
/**
* Clear the DFA cache used by the current instance. Since the DFA cache may
* be shared by multiple ATN simulators, this method may affect the
* performance (but not accuracy) of other parsers which are being used
* concurrently.
*
* @ if the current instance does not
... | {
if (!ATNSimulator._ERROR) {
ATNSimulator._ERROR = new DFAState_1.DFAState(new ATNConfigSet_1.ATNConfigSet());
ATNSimulator._ERROR.stateNumber = PredictionContext_1.PredictionContext.EMPTY_FULL_STATE_KEY;
}
return ATNSimulator._ERROR;
} | identifier_body |
vidspot.py | '''
Allmyvideos urlresolver plugin
Copyright (C) 2013 Vinnydude
This program 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.
This program i... |
def get_url(self, host, media_id):
return 'http://vidspot.net/embed-%s.html' % (media_id)
| raise ResolverError('could not find sources') | conditional_block |
vidspot.py | '''
Allmyvideos urlresolver plugin
Copyright (C) 2013 Vinnydude
This program 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.
This program i... | from urlresolver.resolver import UrlResolver, ResolverError
class VidSpotResolver(UrlResolver):
name = "vidspot"
domains = ["vidspot.net"]
pattern = '(?://|\.)(vidspot\.net)/(?:embed-)?([0-9a-zA-Z]+)'
def __init__(self):
self.net = common.Net()
def get_media_url(self, host, media_id):
... | import urllib
import urlparse
from lib import helpers
from urlresolver import common | random_line_split |
vidspot.py | '''
Allmyvideos urlresolver plugin
Copyright (C) 2013 Vinnydude
This program 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.
This program i... | (self):
self.net = common.Net()
def get_media_url(self, host, media_id):
url = self.get_url(host, media_id)
html = self.net.http_GET(url).content
data = helpers.get_hidden(html)
html = self.net.http_POST(url, data).content
r = re.search('"sources"\s*:\s*\[(.*?)\]', ... | __init__ | identifier_name |
vidspot.py | '''
Allmyvideos urlresolver plugin
Copyright (C) 2013 Vinnydude
This program 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.
This program i... | name = "vidspot"
domains = ["vidspot.net"]
pattern = '(?://|\.)(vidspot\.net)/(?:embed-)?([0-9a-zA-Z]+)'
def __init__(self):
self.net = common.Net()
def get_media_url(self, host, media_id):
url = self.get_url(host, media_id)
html = self.net.http_GET(url).content
data =... | identifier_body | |
tally.js |
/**
* Actually tallies up the votes.
*/
var wilson = require('wilson-score')
var assert = require('assert')
var mdb = require('../databases/mongodb')
var syndicate = require('../syndicate')
var values = require('./values.json')
module.exports = function* (options) {
var thing = options.thing
var type = option... | (up, down, factor) {
return (up + down)
/ (Math.abs(up - down) + (factor || 1))
}
| controversial | identifier_name |
tally.js |
/**
* Actually tallies up the votes.
*/
var wilson = require('wilson-score')
var assert = require('assert')
var mdb = require('../databases/mongodb')
var syndicate = require('../syndicate')
var values = require('./values.json')
module.exports = function* (options) {
var thing = options.thing
var type = option... | {
return (up + down)
/ (Math.abs(up - down) + (factor || 1))
} | identifier_body | |
tally.js | /**
* Actually tallies up the votes.
*/
var wilson = require('wilson-score')
var assert = require('assert')
var mdb = require('../databases/mongodb')
var syndicate = require('../syndicate')
var values = require('./values.json')
module.exports = function* (options) {
var thing = options.thing
var type = options... |
syndicate.emit('tally', options, votes)
return votes
}
function controversial(up, down, factor) {
return (up + down)
/ (Math.abs(up - down) + (factor || 1))
} | down: wilson(votes.score.down, votes.score.total)
} | random_line_split |
ws.ts | /**
* @module customer/ws транспортный модуль для принимания информации с сервера
*/
/// <reference path="../globals.d.ts"/>
// import * as mod1 from "mod1";
// import mod2 = require("mod2");
// import {z} from "mod3";
import * as Base from 'common/ws'
import * as DrawController from 'draw/controller' |
let WS = Base.WebsocketTransport;
class WebSocketClient extends WS {
private observer:Observer;
constructor() {
super();
this.socket.onopen = () => {
let boardId = Utils.getCurrentBoardId();
console.log('socket init!');
this.socket.send(JSON.stringify({
... |
import Utils = require('core/utils'); | random_line_split |
ws.ts | /**
* @module customer/ws транспортный модуль для принимания информации с сервера
*/
/// <reference path="../globals.d.ts"/>
// import * as mod1 from "mod1";
// import mod2 = require("mod2");
// import {z} from "mod3";
import * as Base from 'common/ws'
import * as DrawController from 'draw/controller'
import Utils... | this.observer.on('draw-update', callb);
}
}
export = new WebSocketClient();
| () => {
let boardId = Utils.getCurrentBoardId();
console.log('socket init!');
this.socket.send(JSON.stringify({
type: WS.types.CONNECT,
data: boardId
}));
};
this.socket.onmessage = (e) => {
let msg = JSON.par... | identifier_body |
ws.ts | /**
* @module customer/ws транспортный модуль для принимания информации с сервера
*/
/// <reference path="../globals.d.ts"/>
// import * as mod1 from "mod1";
// import mod2 = require("mod2");
// import {z} from "mod3";
import * as Base from 'common/ws'
import * as DrawController from 'draw/controller'
import Utils... | raw-update', callb);
}
}
export = new WebSocketClient();
| server.on('d | identifier_name |
stack-push.js | 'use strict';
/**
* StackPush
*
* [TOP][MAX][0][][][][MAX - 1]
*/
const Command = require('../../command');
class StackPush extends Command {
run(base, value, length = 1) {
this.writeLog(`base: ${base}, value: ${value}, length: ${length}`); //TODO
return true;
}
output(base, value, length = 1) {
... | H';
}
}
module.exports = StackPush;
| ack-PUS | identifier_name |
stack-push.js | 'use strict';
/**
* StackPush
*
* [TOP][MAX][0][][][][MAX - 1]
*/
const Command = require('../../command');
class StackPush extends Command {
run(base, value, length = 1) {
this.writeLog(`base: ${base}, value: ${value}, length: ${length}`); //TODO
return true;
}
output(base, value, length = 1) | 'SET:stack-PUSH';
}
}
module.exports = StackPush;
| {
const ret = [];
base = this.parseVar(base);
// isFull
if (length == 1) {
ret.push(`If(01, ${base}, 1, ${base + 1}, 1, 1)`); // equalでもいいけど……
} else {
const tmpVar = this.getTmpVarNumber(0);
ret.push(`Variable(0, ${tmpVar}, ${tmpVar}, 0, 1, ${base}, 0)`);
ret.push(`Variable... | identifier_body |
stack-push.js | 'use strict';
/**
* StackPush
*
* [TOP][MAX][0][][][][MAX - 1]
*/
const Command = require('../../command');
class StackPush extends Command {
run(base, value, length = 1) {
this.writeLog(`base: ${base}, value: ${value}, length: ${length}`); //TODO
return true;
}
output(base, value, length = 1) {
... | }
get JP_NAME() {
return 'SET:stack-PUSH';
}
}
module.exports = StackPush; |
return ret; | random_line_split |
stack-push.js | 'use strict';
/**
* StackPush
*
* [TOP][MAX][0][][][][MAX - 1]
*/
const Command = require('../../command');
class StackPush extends Command {
run(base, value, length = 1) {
this.writeLog(`base: ${base}, value: ${value}, length: ${length}`); //TODO
return true;
}
output(base, value, length = 1) {
... | nst tmpVar = this.getTmpVarNumber(0);
ret.push(`Variable(0, ${tmpVar}, ${tmpVar}, 0, 1, ${base}, 0)`);
ret.push(`Variable(0, ${tmpVar}, ${tmpVar}, 1, 0, ${length - 1}, 0)`);
ret.push(`If(01, ${tmpVar}, 1, ${base + 1}, 1, 1)`);
}
// debug Message // TODO エラー処理
// ret.push(`Text("isFull")... | {
ret.push(`If(01, ${base}, 1, ${base + 1}, 1, 1)`); // equalでもいいけど……
} else {
co | conditional_block |
problem11.py | #!/usr/bin/env python
"""
Largest product in a grid
Problem 11
Published on 22 February 2002 at 06:00 pm [Server Time]
In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
The product of these numbers is 26 * 63 * 78 * 14 = 1788696.
What is the greatest product of four adjac... | ():
g = THE_GRID
maxp = 0
rows, cols, path_size = len(g), len(g[0]), 5
for i in range(rows):
for j in range(cols - path_size + 1):
phv = max(product([g[i][j+s] for s in range(path_size)]),
product([g[j+s][i] for s in range(path_size)]))
... | solve | identifier_name |
problem11.py | #!/usr/bin/env python
"""
Largest product in a grid
Problem 11
Published on 22 February 2002 at 06:00 pm [Server Time]
In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
The product of these numbers is 26 * 63 * 78 * 14 = 1788696.
What is the greatest product of four adjac... | run =[THE_GRID[row+(y_dir*i)][column+x_dir*i] for i in range(run_length)]
result = product(run)
print run, result
#if result > highest:
# highest = result
#return(highest)
#----------------------------------------------------... | highest = 0
for row in range(height-run_length+1):
for column in range(width-run_length+1):
for x_dir, y_dir in [(1, 0), (0, 1), (1, 1)]:
| random_line_split |
problem11.py | #!/usr/bin/env python
"""
Largest product in a grid
Problem 11
Published on 22 February 2002 at 06:00 pm [Server Time]
In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
The product of these numbers is 26 * 63 * 78 * 14 = 1788696.
What is the greatest product of four adjac... |
def solve(run_length):
height = len(THE_GRID)
width = len(THE_GRID[0])
for row in range(height-run_length+1):
for column in range(width-run_length+1):
for y_dir in (0, 1):
for x_dir in (0,1):
for i in range(run_length):
... | return reduce(operator.mul, iterable, 1) | identifier_body |
problem11.py | #!/usr/bin/env python
"""
Largest product in a grid
Problem 11
Published on 22 February 2002 at 06:00 pm [Server Time]
In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
The product of these numbers is 26 * 63 * 78 * 14 = 1788696.
What is the greatest product of four adjac... |
def solve(run_length):
height = len(THE_GRID)
width = len(THE_GRID[0])
for row in range(height-run_length+1):
for column in range(width-run_length+1):
for i in range(run_length):
for y_dir in (0, 1):
for x_dir i... | for x_dir in (0,1):
for i in range(run_length):
print THE_GRID[row+(y_dir*i)][column+x_dir*i] | conditional_block |
script07_use_gene_list.py | #!/usr/bin/env python
import os
import sys
import glob
import argparse
from datetime import datetime
import platform
if platform.system().lower() == 'darwin':
os.environ['PYTHONPATH'] = '%s/osx_libs:$PYTHONPATH' % os.getcwd()
import wormtable as wt
###########################################################... |
if os.path.exists(file_name):
sys.stderr.write("\nFile named '" + file_name + "' already exists.\n")
sys.exit()
return file_name
def store_genes(genes_to_query):
"""
Store all input gene names in a set. If the path of genes_to_query does not
exist, it will treat genes_to_query as a string.
"""
... | """ | random_line_split |
script07_use_gene_list.py | #!/usr/bin/env python
import os
import sys
import glob
import argparse
from datetime import datetime
import platform
if platform.system().lower() == 'darwin':
os.environ['PYTHONPATH'] = '%s/osx_libs:$PYTHONPATH' % os.getcwd()
import wormtable as wt
###########################################################... | (inp_folder, genes,
field_name, negative_query, previous_results):
"""
Open the field_name wormtable (assumed to be named 'inp_folder/field_name.wt')
within inp_folder and return a set of all row IDs where at least one gene from
genes is found. Use ids from previous_results as starting point to further
filt... | get_variants_assoc_to_gene_set_from_previous_results | identifier_name |
script07_use_gene_list.py | #!/usr/bin/env python
import os
import sys
import glob
import argparse
from datetime import datetime
import platform
if platform.system().lower() == 'darwin':
os.environ['PYTHONPATH'] = '%s/osx_libs:$PYTHONPATH' % os.getcwd()
import wormtable as wt
###########################################################... |
def get_variants_assoc_to_gene_set_from_previous_results(inp_folder, genes,
field_name, negative_query, previous_results):
"""
Open the field_name wormtable (assumed to be named 'inp_folder/field_name.wt')
within inp_folder and return a set of all row IDs where at least one gene from
genes is found. Use ids... | """
Store all input gene names in a set. If the path of genes_to_query does not
exist, it will treat genes_to_query as a string.
"""
genes = set()
# genes_to_query is a text file
if os.path.exists(genes_to_query):
f = open(genes_to_query)
for line in f:
genes.add(line.strip('\n'))
f.close... | identifier_body |
script07_use_gene_list.py | #!/usr/bin/env python
import os
import sys
import glob
import argparse
from datetime import datetime
import platform
if platform.system().lower() == 'darwin':
os.environ['PYTHONPATH'] = '%s/osx_libs:$PYTHONPATH' % os.getcwd()
import wormtable as wt
###########################################################... |
f.close()
# open wormtable for the field of interest
table = wt.open_table(inp_folder + '/' + field_name + '.wt',
db_cache_size='4G')
index = table.open_index('row_id')
all_ids = set()
pos_ids = set()
# NOTE: it assumes the wormtable has only two columns: 'row_id' and field_name
row_id_idx = ... | if header:
header = False
else:
ids_to_check.add(int(line.split('\t')[0])) | conditional_block |
badguys.js | module.exports = {
data: {
badguys: []
},
methods: {
generate_badguys: function () {
var amount = 1000
// generate code here
this.badguys = null // replace null with an array of objects
// this will be the structure of the generated code
// this is temporary data (more li... | },
behavior_badguys: function () {
// if player is within x radius move postition of badguy 1 block closer to player
// if touching player, attack player
// upon death of baguy remove badguy from badguys array
}
}
} | // health: 1000,
// stamina: 40
// }
// ], | random_line_split |
framebuffer_info.rs | //! Handles the framebuffer information tag.
use super::get_tag;
#[cfg(target_arch = "x86_64")]
use arch::vga_buffer;
use memory::{Address, VirtualAddress};
/// Represents the framebuffer information tag.
#[repr(C)]
pub struct FramebufferInfo {
// type = 8
tag_type: u32,
size: u32,
pub framebuffer_add... | () -> vga_buffer::Info {
let framebuffer_tag = get_tag(8);
match framebuffer_tag {
Some(framebuffer_tag_address) => {
let framebuffer_tag = unsafe { &*(framebuffer_tag_address as *const FramebufferInfo) };
vga_buffer::Info {
height: framebuffer_tag.framebuffer_hei... | get_vga_info | identifier_name |
framebuffer_info.rs | //! Handles the framebuffer information tag.
use super::get_tag;
#[cfg(target_arch = "x86_64")]
use arch::vga_buffer;
use memory::{Address, VirtualAddress};
/// Represents the framebuffer information tag.
#[repr(C)]
pub struct FramebufferInfo {
// type = 8
tag_type: u32,
size: u32,
pub framebuffer_add... | vga_buffer::Info {
height: framebuffer_tag.framebuffer_height as usize,
width: framebuffer_tag.framebuffer_width as usize,
address: VirtualAddress::from_usize(to_virtual!(framebuffer_tag.framebuffer_addr))
}
},
None => vga_buffer::I... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.