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 |
|---|---|---|---|---|
lsp_state.rs | , LSPExtraDataProvider};
use common::{Diagnostic as CompilerDiagnostic, PerfLogger, SourceLocationKey, Span};
use crossbeam::Sender;
use dashmap::{mapref::entry::Entry, DashMap};
use fnv::FnvBuildHasher;
use graphql_ir::{
build_ir_with_extra_features, BuilderOptions, FragmentVariablesSemantic, Program,
};
use graph... |
pub(crate) fn extract_executable_document_from_text(
&mut self,
position: &TextDocumentPositionParams,
index_offset: usize,
) -> LSPRuntimeResult<(ExecutableDocument, Span, StringKey)> {
extract_executable_document_from_text(
&position,
&self.synced_grap... | {
self.synced_graphql_documents.remove(url);
self.diagnostic_reporter
.clear_quick_diagnostics_for_url(url);
} | identifier_body |
lsp_state.rs | , DashMap};
use fnv::FnvBuildHasher;
use graphql_ir::{
build_ir_with_extra_features, BuilderOptions, FragmentVariablesSemantic, Program,
};
use graphql_syntax::{
parse_executable_with_error_recovery, ExecutableDefinition, ExecutableDocument, GraphQLSource,
};
use interner::StringKey;
use log::debug;
use lsp_ser... | {
tokio::spawn(async move { compiler.watch().await });
} | conditional_block | |
lsp_state.rs | , LSPExtraDataProvider};
use common::{Diagnostic as CompilerDiagnostic, PerfLogger, SourceLocationKey, Span};
use crossbeam::Sender;
use dashmap::{mapref::entry::Entry, DashMap};
use fnv::FnvBuildHasher;
use graphql_ir::{
build_ir_with_extra_features, BuilderOptions, FragmentVariablesSemantic, Program,
};
use graph... | file_categorizer: FileCategorizer,
schemas: Schemas,
source_programs: SourcePrograms,
synced_graphql_documents: HashMap<Url, Vec<GraphQLSource>>,
perf_logger: Arc<TPerfLogger>,
diagnostic_reporter: Arc<DiagnosticReporter>,
notify_sender: Arc<Notify>,
project_status: ProjectStatusMap,
... | pub extra_data_provider: Box<dyn LSPExtraDataProvider>, | random_line_split |
lsp_state.rs | , LSPExtraDataProvider};
use common::{Diagnostic as CompilerDiagnostic, PerfLogger, SourceLocationKey, Span};
use crossbeam::Sender;
use dashmap::{mapref::entry::Entry, DashMap};
use fnv::FnvBuildHasher;
use graphql_ir::{
build_ir_with_extra_features, BuilderOptions, FragmentVariablesSemantic, Program,
};
use graph... | (&self) -> &SourcePrograms {
&self.source_programs
}
pub(crate) fn resolve_node(
&self,
params: TextDocumentPositionParams,
) -> LSPRuntimeResult<NodeResolutionInfo> {
get_node_resolution_info(
params,
&self.synced_graphql_documents,
&self... | get_source_programs_ref | identifier_name |
0005_adjust_issue_report_fields.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-29 13:23
from django.db import migrations, models
class Migration(migrations.Migration):
| model_name="issuetracker",
name="issue_report_params",
field=models.CharField(
blank=True,
default="",
help_text="Parameters used to format URL for reporting issue. Each line is a <code>key:value</code> pair of parameters. Nitrate provi... | dependencies = [
("issuetracker", "0004_data_migration_set_bugzilla_to_allow_add_case_to_issue"),
]
operations = [
migrations.RemoveField(
model_name="issuetracker",
name="issue_report_fmt",
),
migrations.AddField(
model_name="issuetracker",
... | identifier_body |
0005_adjust_issue_report_fields.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-29 13:23
from django.db import migrations, models
class | (migrations.Migration):
dependencies = [
("issuetracker", "0004_data_migration_set_bugzilla_to_allow_add_case_to_issue"),
]
operations = [
migrations.RemoveField(
model_name="issuetracker",
name="issue_report_fmt",
),
migrations.AddField(
... | Migration | identifier_name |
0005_adjust_issue_report_fields.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-29 13:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("issuetracker", "0004_data_migration_set_bugzilla_to_allow_add_case_to_issue"),
]
operations = [
migrations.RemoveFi... | name="issue_report_templ",
field=models.CharField(
blank=True,
default="",
help_text="The issue content template, which could be arbitrary text with format arguments. Nitrate provides these format arguments: <code>TestBuild.name</code>, <code>setup... | random_line_split | |
process.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
persistent_safety_storage::PersistentSafetyStorage,
remote_service::{self, RemoteService},
safety_rules_manager,
};
use diem_config::config::{SafetyRulesConfig, SafetyRulesService};
use std::net::SocketAddr;
p... |
}
impl RemoteService for ProcessService {
fn server_address(&self) -> SocketAddr {
self.server_addr
}
fn network_timeout_ms(&self) -> u64 {
self.network_timeout_ms
}
}
| {
Self {
server_addr,
network_timeout_ms: network_timeout,
}
} | identifier_body |
process.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
persistent_safety_storage::PersistentSafetyStorage,
remote_service::{self, RemoteService},
safety_rules_manager,
};
use diem_config::config::{SafetyRulesConfig, SafetyRulesService};
use std::net::SocketAddr;
p... | (&self) -> SocketAddr {
self.server_addr
}
fn network_timeout_ms(&self) -> u64 {
self.network_timeout_ms
}
}
| server_address | identifier_name |
process.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
persistent_safety_storage::PersistentSafetyStorage,
remote_service::{self, RemoteService},
safety_rules_manager, | pub struct Process {
data: Option<ProcessData>,
}
impl Process {
pub fn new(config: SafetyRulesConfig) -> Self {
let storage = safety_rules_manager::storage(&config);
let verify_vote_proposal_signature = config.verify_vote_proposal_signature;
let export_consensus_key = config.export_co... | };
use diem_config::config::{SafetyRulesConfig, SafetyRulesService};
use std::net::SocketAddr;
| random_line_split |
PermitSearchResultsAddresses.js | import React from 'react';
import PermitSearchResultsByAddress from './PermitSearchResultsByAddress'
function | (props) {
if (props.data === null) {
return <p>No results found</p>;
}
if (!props.data.length) {
return <p>No results found</p>;
}
const addressList = props.data.map((result, index) => {
const addressButtonStyle = (parseInt(result.civic_address_id) === parseInt(props.showPermitsForID)) ? 'acti... | PermitSearchResultsAddress | identifier_name |
PermitSearchResultsAddresses.js | import React from 'react';
import PermitSearchResultsByAddress from './PermitSearchResultsByAddress'
function PermitSearchResultsAddress(props) {
if (props.data === null) {
return <p>No results found</p>;
}
if (!props.data.length) |
const addressList = props.data.map((result, index) => {
const addressButtonStyle = (parseInt(result.civic_address_id) === parseInt(props.showPermitsForID)) ? 'active' : '';
return (
<li key={index}>
<button
type="button"
title={`View permits for ${result.address}`}
... | {
return <p>No results found</p>;
} | conditional_block |
PermitSearchResultsAddresses.js | import React from 'react';
import PermitSearchResultsByAddress from './PermitSearchResultsByAddress'
function PermitSearchResultsAddress(props) | className={`list-group-item list-group-item-action ${addressButtonStyle}`}
onClick={props.handleAddressSelection}
>
{result.address}, {result.zipcode} (ID: {result.civic_address_id})
</button>
{parseInt(result.civic_address_id) === parseInt(props.showPermitsForID) ... | {
if (props.data === null) {
return <p>No results found</p>;
}
if (!props.data.length) {
return <p>No results found</p>;
}
const addressList = props.data.map((result, index) => {
const addressButtonStyle = (parseInt(result.civic_address_id) === parseInt(props.showPermitsForID)) ? 'active' : ''... | identifier_body |
PermitSearchResultsAddresses.js | import React from 'react';
import PermitSearchResultsByAddress from './PermitSearchResultsByAddress'
|
if (!props.data.length) {
return <p>No results found</p>;
}
const addressList = props.data.map((result, index) => {
const addressButtonStyle = (parseInt(result.civic_address_id) === parseInt(props.showPermitsForID)) ? 'active' : '';
return (
<li key={index}>
<button
ty... | function PermitSearchResultsAddress(props) {
if (props.data === null) {
return <p>No results found</p>;
} | random_line_split |
installer.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2008-2012 Alistek Ltd (http://www.alistek.com) All Rights Reserved.
# General contacts <info@alistek.com>
#
# WARNING: This program as such is intended to be used by professional... |
try:
fp = tools.file_open('report_aeroo_ooo/test_temp.odt', mode='rb')
file_data = fp.read()
DC = netsvc.Service._services.setdefault('openoffice', \
OpenOffice_service(cr, data['host'], data['port']))
with aeroo_lock:
DC.putD... | config_id = config_obj.create(cr, 1, data, context=context) | conditional_block |
installer.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2008-2012 Alistek Ltd (http://www.alistek.com) All Rights Reserved.
# General contacts <info@alistek.com>
#
# WARNING: This program as such is intended to be used by professional... | (self, cr, uid, fields, context=None):
config_obj = self.pool.get('oo.config')
data = super(aeroo_config_installer, self).default_get(cr, uid, fields, context=context)
ids = config_obj.search(cr, 1, [], context=context)
if ids:
res = config_obj.read(cr, 1, ids[0], context=con... | default_get | identifier_name |
installer.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2008-2012 Alistek Ltd (http://www.alistek.com) All Rights Reserved.
# General contacts <info@alistek.com>
#
# WARNING: This program as such is intended to be used by professional... |
def _get_image_fn(self, cr, uid, ids, name, args, context=None):
image = self._get_image(cr, uid, context)
return dict.fromkeys(ids, image) # ok to use .fromkeys() as the image is same for all
_columns = {
'host':fields.char('Host', size=64, required=True),
'port':fields.inte... | if self._logo_image:
return self._logo_image
try:
im = urllib2.urlopen(_url.encode("UTF-8"))
if im.headers.maintype!='image':
raise TypeError(im.headers.maintype)
except Exception, e:
path = os.path.join('report_aeroo','config_pixmaps','mod... | identifier_body |
installer.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2008-2012 Alistek Ltd (http://www.alistek.com) All Rights Reserved.
# General contacts <info@alistek.com>
#
# WARNING: This program as such is intended to be used by professional... | return data
def check(self, cr, uid, ids, context=None):
config_obj = self.pool.get('oo.config')
data = self.read(cr, uid, ids, ['host','port','ooo_restart_cmd'])[0]
del data['id']
config_id = config_obj.search(cr, 1, [], context=context)
if config_id:
co... | random_line_split | |
app.js | (function() {
'use strict';
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('v... | });
module.exports = app;
}()); | random_line_split | |
events.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are ... | __version__ = '$Id: events.py 1966 2008-03-23 07:01:26Z Alex.Holkner $'
import pyglet
from pyglet.window import key
from pyglet.window import mouse
window = pyglet.window.Window()
@window.event
def on_key_press(symbol, modifiers):
if symbol == key.A:
print 'The "A" key was pressed.'
elif symbol == ke... | random_line_split | |
events.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are ... |
elif symbol == key.ENTER:
print 'The enter key was pressed.'
@window.event
def on_mouse_press(x, y, button, modifiers):
if button == mouse.LEFT:
print 'The left mouse button was pressed.'
@window.event
def on_draw():
window.clear()
pyglet.app.run()
| print 'The left arrow key was pressed.' | conditional_block |
events.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are ... | (symbol, modifiers):
if symbol == key.A:
print 'The "A" key was pressed.'
elif symbol == key.LEFT:
print 'The left arrow key was pressed.'
elif symbol == key.ENTER:
print 'The enter key was pressed.'
@window.event
def on_mouse_press(x, y, button, modifiers):
if button == mouse.L... | on_key_press | identifier_name |
events.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are ... |
@window.event
def on_mouse_press(x, y, button, modifiers):
if button == mouse.LEFT:
print 'The left mouse button was pressed.'
@window.event
def on_draw():
window.clear()
pyglet.app.run()
| if symbol == key.A:
print 'The "A" key was pressed.'
elif symbol == key.LEFT:
print 'The left arrow key was pressed.'
elif symbol == key.ENTER:
print 'The enter key was pressed.' | identifier_body |
linkmap.py | # Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
# Copyright (C) 2009-2013 Kai Willadsen <kai.willadsen@gmail.com>
#
# 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 2 ... |
def associate(self, filediff, left_view, right_view):
self.filediff = filediff
self.views = [left_view, right_view]
if self.get_direction() == Gtk.TextDirection.RTL:
self.views.reverse()
self.view_indices = [filediff.textview.index(t) for t in self.views]
self.... | self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | identifier_body |
linkmap.py | # Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
# Copyright (C) 2009-2013 Kai Willadsen <kai.willadsen@gmail.com>
#
# 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 2 ... |
from meld.misc import get_common_theme
from meld.settings import meldsettings
# Rounded rectangle corner radius for culled changes display
RADIUS = 3
class LinkMap(Gtk.DrawingArea):
__gtype_name__ = "LinkMap"
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on... | random_line_split | |
linkmap.py | # Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
# Copyright (C) 2009-2013 Kai Willadsen <kai.willadsen@gmail.com>
#
# 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 2 ... | (self, melddoc):
self.melddoc = melddoc
def do_scroll_event(self, event):
if not self.melddoc:
return
self.melddoc.next_diff(event.direction)
| associate | identifier_name |
linkmap.py | # Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
# Copyright (C) 2009-2013 Kai Willadsen <kai.willadsen@gmail.com>
#
# 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 2 ... |
else:
context.move_to(x_steps[0], f0 - 0.5)
context.curve_to(x_steps[1], f0 - 0.5,
x_steps[2], t0 - 0.5,
x_steps[3], t0 - 0.5)
context.line_to(x_steps[3], t1 - 0.5)
context.curv... | if t0 == t1:
continue
context.arc_negative(x_steps[3], t0 - 0.5 + RADIUS, RADIUS,
-q_rad, q_rad * 2)
context.arc_negative(x_steps[3], t1 - 0.5 - RADIUS, RADIUS,
q_rad * 2, q_rad)
... | conditional_block |
header.py | import markdown
from markdown.blockprocessors import BlockProcessor
from markdown import util
import re
import logging
logger = logging.getLogger('MARKDOWN')
# copied from class markdown.blockprocessors.HashHeaderProcessor
class C2CHeaderProcessor(BlockProcessor):
""" Process Hash Headers. """
# Detect a he... | return C2CHeaderExtension(configs=configs) | identifier_body | |
header.py | import markdown
from markdown.blockprocessors import BlockProcessor
from markdown import util
import re
import logging
logger = logging.getLogger('MARKDOWN')
# copied from class markdown.blockprocessors.HashHeaderProcessor
class C2CHeaderProcessor(BlockProcessor):
""" Process Hash Headers. """
# Detect a he... |
if after:
# Insert remaining lines as first block for future parsing.
blocks.insert(0, after)
else: # pragma: no cover
# This should never happen, but just in case...
logger.warn("We've got a problem header: %r" % block)
class C2CHeaderExt... | emphasis = util.etree.SubElement(h, 'span')
emphasis.set('class', 'header-emphasis')
emphasis.text = ' ' + emphasis_text | conditional_block |
header.py | import markdown
from markdown.blockprocessors import BlockProcessor
from markdown import util
import re
import logging
logger = logging.getLogger('MARKDOWN')
# copied from class markdown.blockprocessors.HashHeaderProcessor
class C2CHeaderProcessor(BlockProcessor):
""" Process Hash Headers. """
# Detect a he... | after = block[m.end():] # All lines after header
if before:
# As the header was not the first line of the block and the
# lines before the header must be parsed first,
# recursively parse this lines as a block.
self.parser.parseBlo... | before = block[:m.start()] # All lines before header | random_line_split |
header.py | import markdown
from markdown.blockprocessors import BlockProcessor
from markdown import util
import re
import logging
logger = logging.getLogger('MARKDOWN')
# copied from class markdown.blockprocessors.HashHeaderProcessor
class C2CHeaderProcessor(BlockProcessor):
""" Process Hash Headers. """
# Detect a he... | (markdown.Extension):
def extendMarkdown(self, md, md_globals): # noqa
md.parser.blockprocessors.add(
'header_emphasis',
C2CHeaderProcessor(md.parser),
"<hashheader")
def makeExtension(configs=[]): # noqa
return C2CHeaderExtension(configs=configs)
| C2CHeaderExtension | identifier_name |
helper_dbus.py | # Copyright (c) 2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# 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.
... |
#######################
# PRIVATE #
#######################
def __on_get_proxy(self, source, result, call, dbus_args, callback, *args):
"""
Launch call and connect it to callback
@param source as GObject.Object
@param result as Gio.AsyncResult
@p... | (bus, subscribe_id) = self.__signals[page_id]
bus.signal_unsubscribe(subscribe_id)
del self.__signals[page_id] | conditional_block |
helper_dbus.py | # Copyright (c) 2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# 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.
... |
def call(self, call, page_id, dbus_args=None, callback=None, *args):
"""
Call function
@param call as str
@param page_id as int
@param dbus_args as GLib.Variant()/None
@param callback as function
"""
try:
bus = El().ge... | self.__signals = {} | identifier_body |
helper_dbus.py | # Copyright (c) 2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# 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.
... | from eolie.define import PROXY_BUS, PROXY_PATH, PROXY_INTERFACE, El
class DBusHelper:
"""
Simpler helper for DBus
"""
def __init__(self):
self.__signals = {}
def call(self, call, page_id, dbus_args=None, callback=None, *args):
"""
Call function
@param ... | from gi.repository import Gio
| random_line_split |
helper_dbus.py | # Copyright (c) 2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# 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.
... | (self, call, page_id, dbus_args=None, callback=None, *args):
"""
Call function
@param call as str
@param page_id as int
@param dbus_args as GLib.Variant()/None
@param callback as function
"""
try:
bus = El().get_dbus_connect... | call | identifier_name |
importstates.py | # -*- coding: utf-8 -*-
import simplejson
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import MultiPolygon, Polygon
from ...models import State
class Command(BaseCommand):
args = 'filename'
help = 'Import states from a GeoJSON file'
def handle(self, *args, **options... | code=feature['properties'].get('code'),
)
if feature['geometry'].get('type') == 'MultiPolygon':
state.geom = MultiPolygon(
[Polygon(poly) for poly in feature['geometry'].get('coordinates')[0]]
)
... |
for feature in data['features']:
state = State(
name=feature['properties'].get('name'), | random_line_split |
importstates.py | # -*- coding: utf-8 -*-
import simplejson
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import MultiPolygon, Polygon
from ...models import State
class Command(BaseCommand):
| args = 'filename'
help = 'Import states from a GeoJSON file'
def handle(self, *args, **options):
for filename in args:
data_json = open(filename, 'r').read()
data = simplejson.loads(data_json)
for feature in data['features']:
state = State(
... | identifier_body | |
importstates.py | # -*- coding: utf-8 -*-
import simplejson
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import MultiPolygon, Polygon
from ...models import State
class Command(BaseCommand):
args = 'filename'
help = 'Import states from a GeoJSON file'
def | (self, *args, **options):
for filename in args:
data_json = open(filename, 'r').read()
data = simplejson.loads(data_json)
for feature in data['features']:
state = State(
name=feature['properties'].get('name'),
code=feat... | handle | identifier_name |
importstates.py | # -*- coding: utf-8 -*-
import simplejson
from django.core.management.base import BaseCommand
from django.contrib.gis.geos import MultiPolygon, Polygon
from ...models import State
class Command(BaseCommand):
args = 'filename'
help = 'Import states from a GeoJSON file'
def handle(self, *args, **options... | data_json = open(filename, 'r').read()
data = simplejson.loads(data_json)
for feature in data['features']:
state = State(
name=feature['properties'].get('name'),
code=feature['properties'].get('code'),
)
... | conditional_block | |
bomb.py | import src
import random
class Bomb(src.items.Item):
"""
ingame item to kill things and destroy stuff
"""
type = "Bomb"
name = "bomb"
description = "designed to explode"
usageInfo = """
The explosion will damage/destroy everything on the current tile or the container.
Activate it to trig... | (self):
"""
initialise state
"""
super().__init__(display=src.canvas.displayChars.bomb)
def apply(self, character):
"""
handle a character trying to use this item
by exploding
Parameters:
character: the character trying to use this item
... | __init__ | identifier_name |
bomb.py | import src
import random
class Bomb(src.items.Item):
"""
ingame item to kill things and destroy stuff
"""
type = "Bomb"
name = "bomb"
description = "designed to explode"
usageInfo = """
The explosion will damage/destroy everything on the current tile or the container.
Activate it to trig... |
super().destroy(generateScrap=False)
src.items.addType(Bomb)
| new = src.items.itemMap["Explosion"]()
self.container.addItem(new,(self.xPosition-offset[0],self.yPosition-offset[1],self.zPosition))
event = src.events.RunCallbackEvent(
src.gamestate.gamestate.tick + delay
)
event.setCallback({"container": new, "method":... | conditional_block |
bomb.py | import src
import random
class Bomb(src.items.Item):
"""
ingame item to kill things and destroy stuff
"""
type = "Bomb"
name = "bomb"
description = "designed to explode"
usageInfo = """
The explosion will damage/destroy everything on the current tile or the container.
Activate it to trig... |
def destroy(self, generateScrap=True):
"""
destroy the item
Parameters:
generateScrap: flag to toggle leaving residue
"""
if not self.xPosition or not self.yPosition:
return
offsets = [(0,0),(1,0),(-1,0),(0,1),(0,-1)]
rando... | """
handle a character trying to use this item
by exploding
Parameters:
character: the character trying to use this item
"""
character.addMessage("the bomb starts to fizzle")
event = src.events.RunCallbackEvent(
#src.gamestate.gamestate.tick+rand... | identifier_body |
bomb.py | import src
import random
class Bomb(src.items.Item):
"""
ingame item to kill things and destroy stuff
"""
type = "Bomb"
name = "bomb"
description = "designed to explode"
usageInfo = """
The explosion will damage/destroy everything on the current tile or the container.
Activate it to trig... | self.container.addEvent(event)
def destroy(self, generateScrap=True):
"""
destroy the item
Parameters:
generateScrap: flag to toggle leaving residue
"""
if not self.xPosition or not self.yPosition:
return
offsets = [(0,0),(1... | src.gamestate.gamestate.tick+1
)
event.setCallback({"container": self, "method": "destroy"}) | random_line_split |
static-query-utils.ts | import fs from "fs-extra"
import * as path from "path"
// we want to force posix-style joins, so Windows doesn't produce backslashes for urls
const { join } = path.posix
import type { IScriptsAndStyles } from "./client-assets-for-template"
import { IPageDataWithQueryResult } from "./page-data"
const outputDir = path.j... | getStaticQueryPromise.then(() => {
inFlightStaticQueryPromise.delete(staticQueryHash)
})
}
staticQueryResultPromises.push(
getStaticQueryPromise.then(results => {
staticQueryContext[staticQueryHash] = results
})
)
}
await Promise.all(staticQueryResultPromises)
... | random_line_split | |
static-query-utils.ts | import fs from "fs-extra"
import * as path from "path"
// we want to force posix-style joins, so Windows doesn't produce backslashes for urls
const { join } = path.posix
import type { IScriptsAndStyles } from "./client-assets-for-template"
import { IPageDataWithQueryResult } from "./page-data"
const outputDir = path.j... | (): void {
staticQueryResultCache.clear()
inFlightStaticQueryPromise.clear()
}
export const getStaticQueryContext = async (
staticQueryHashes: IPageDataWithQueryResult["staticQueryHashes"]
): Promise<{
staticQueryContext: IResourcesForTemplate["staticQueryContext"]
}> => {
const staticQueryResultPromises: Ar... | clearStaticQueryCaches | identifier_name |
static-query-utils.ts | import fs from "fs-extra"
import * as path from "path"
// we want to force posix-style joins, so Windows doesn't produce backslashes for urls
const { join } = path.posix
import type { IScriptsAndStyles } from "./client-assets-for-template"
import { IPageDataWithQueryResult } from "./page-data"
const outputDir = path.j... |
staticQueryResultPromises.push(
getStaticQueryPromise.then(results => {
staticQueryContext[staticQueryHash] = results
})
)
}
await Promise.all(staticQueryResultPromises)
return { staticQueryContext }
}
export const writeStaticQueryContext = async (
staticQueryHashes: IPageDataWi... | {
getStaticQueryPromise = getStaticQueryResult(staticQueryHash)
inFlightStaticQueryPromise.set(staticQueryHash, getStaticQueryPromise)
getStaticQueryPromise.then(() => {
inFlightStaticQueryPromise.delete(staticQueryHash)
})
} | conditional_block |
static-query-utils.ts | import fs from "fs-extra"
import * as path from "path"
// we want to force posix-style joins, so Windows doesn't produce backslashes for urls
const { join } = path.posix
import type { IScriptsAndStyles } from "./client-assets-for-template"
import { IPageDataWithQueryResult } from "./page-data"
const outputDir = path.j... |
export const getStaticQueryContext = async (
staticQueryHashes: IPageDataWithQueryResult["staticQueryHashes"]
): Promise<{
staticQueryContext: IResourcesForTemplate["staticQueryContext"]
}> => {
const staticQueryResultPromises: Array<Promise<void>> = []
const staticQueryContext: IResourcesForTemplate["staticQ... | {
staticQueryResultCache.clear()
inFlightStaticQueryPromise.clear()
} | identifier_body |
test_uuid.py | # Copyright 2015, 2018 IBM Corp.
#
# 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... | self.assertEqual((False, 123), uuid_utils.id_or_uuid(conv('123')))
uuid = conv('12345678-abcd-ABCD-0000-0a1B2c3D4e5F')
self.assertEqual((True, uuid), uuid_utils.id_or_uuid(uuid))
uuid = conv('12345678abcdABCD00000a1B2c3D4e5F')
self.assertEqual((True, uuid), uuid_utils.id_... | conditional_block | |
test_uuid.py | # Copyright 2015, 2018 IBM Corp.
#
# 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... | self.assertRaises(ValueError, uuid_utils.id_or_uuid,
conv('12345678-abcd-ABCD-0000-0a1B2c3D4e5F0')) | random_line_split | |
test_uuid.py | # Copyright 2015, 2018 IBM Corp.
#
# 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... | (self):
self.assertEqual((False, 123), uuid_utils.id_or_uuid(123))
# Test all stringish permutations
converters = [lambda x: x, six.text_type]
for conv in converters:
self.assertEqual((False, 123), uuid_utils.id_or_uuid(conv('123')))
uuid = conv('12345678-abcd-ABC... | test_id_or_uuid | identifier_name |
test_uuid.py | # Copyright 2015, 2018 IBM Corp.
#
# 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... | self.assertEqual((False, 123), uuid_utils.id_or_uuid(conv('123')))
uuid = conv('12345678-abcd-ABCD-0000-0a1B2c3D4e5F')
self.assertEqual((True, uuid), uuid_utils.id_or_uuid(uuid))
uuid = conv('12345678abcdABCD00000a1B2c3D4e5F')
self.assertEqual((True, uuid), uu... | """Unit tests for the uuid."""
def test_uuid_conversion(self):
uuid = '089ffb20-5d19-4a8c-bb80-13650627d985'
pvm_uuid = uuid_utils.convert_uuid_to_pvm(uuid)
self.assertEqual(uuid, pvm_uuid)
uuid = '989ffb20-5d19-4a8c-bb80-13650627d985'
pvm_uuid = uuid_utils.convert_uuid_to_... | identifier_body |
test_aras.py | 2],43 :[5,13],44 :[5,14],45 :[5,15],46 :[5,16],47 :[5,17],48 :[5,18]\
,55 :[6,1] ,56: [6,2]#Row6\
,81 :[6,3] ,82: [6,4] ,83 :[6,5] ,84 :[6,6] ,85 :[6,7] ,86 :[6,8]
,72: [6,10],73 :[6,11],74 :[6,12],75 :[6,13],76 :[6,14],77 :[6,15],78 :[6,16],79 :[6,17],80 :[6,18]\
,57 :[6,19],58:... | for j, charge in enumerate(mols[b].nuclear_charges):
q2[b,j] = int(charge) | conditional_block | |
test_aras.py | 4 :[6,12],75 :[6,13],76 :[6,14],77 :[6,15],78 :[6,16],79 :[6,17],80 :[6,18]\
,57 :[6,19],58: [6,20],59 :[6,21],60 :[6,22],61 :[6,23],62 :[6,24],63 :[6,25],64 :[6,26],65 :[6,27],66 :[6,28],67 :[6,29],68 :[6,30],69 :[6,31],70 :[6,32],71 :[6,33]\
,87 :[7,1] ,88: [7,2]#Row7\
,113:[7,3] ,114:[7,4] ,... | for filename in sorted(filenames): | random_line_split | |
test_aras.py | ] ,16 :[3,6] ,17 :[3,7] ,18 :[3,8]\
,19 :[4,1] ,20: [4,2]#Row4\
,31 :[4,3] ,32: [4,4] ,33 :[4,5] ,34 :[4,6] ,35 :[4,7] ,36 :[4,8]\
,21 :[4,9] ,22: [4,10],23 :[4,11],24 :[4,12],25 :[4,13],26 :[4,14],27 :[4,15],28 :[4,16],29 :[4,17],30 :[4,18]\
,37 :[5,1] ,38: [5,2]#Row5\
... | (mols1, mols2, sigma, max_size=30):
K = np.zeros((len(mols1), len(mols2)))
for i, mol1 in enumerate(mols1):
for j, mol2 in enumerate(mols2):
print i, j
d = aras_distance(mol1, mol2)
d *= -0.5 / (sigma**2)
np.exp(d, d)
K[i,j] = np.sum(d)
... | get_kernel | identifier_name |
test_aras.py | ] ,16 :[3,6] ,17 :[3,7] ,18 :[3,8]\
,19 :[4,1] ,20: [4,2]#Row4\
,31 :[4,3] ,32: [4,4] ,33 :[4,5] ,34 :[4,6] ,35 :[4,7] ,36 :[4,8]\
,21 :[4,9] ,22: [4,10],23 :[4,11],24 :[4,12],25 :[4,13],26 :[4,14],27 :[4,15],28 :[4,16],29 :[4,17],30 :[4,18]\
,37 :[5,1] ,38: [5,2]#Row5\
... |
def ksi(x):
return 1.0 - np.sin(np.pi * x/(2.0 * cut_distance))
def aras_scalar(atom1, atom2, q1, q2, n1, n2, qall1, qall2):
ksi1 = ksi(atom1[0,:n1])
ksi2 = ksi(atom2[0,:n2])
a = 1.0 / (np.sum(ksi1) * np.sum(ksi2)) \
* np.sqrt(np.pi) * d_width * r_width**4 * c_width**4 \
/ p... | ra = PTP[int(a)][0]
rb = PTP[int(b)][0]
ca = PTP[int(a)][1]
cb = PTP[int(b)][1]
return (r_width**2 + (ra - rb)**2) * (c_width**2 + (ca - cb)**2) | identifier_body |
Polygon.ts | import Node, {Bounds, Point} from './Node';
import NodeFixedBounds from './NodeFixedBounds';
const zeroPoint: Point = {x: 0, y: 0};
export interface PolygonStyle {
strokeStyle?: string;
lineWidth?: number;
fillStyle?: string;
lineDash?: Array<number>;
}
export interface PolygonParameters extends Poly... |
for (let j = 1; j < this.points[i].length; j++) {
const {x, y} = this.points[i][j];
context.lineTo(x, y);
}
context.closePath();
}
context.fill();
if (this.lineWidth > 0) {
context.setLineDash(this.lineDash);
... | {
const {x, y} = this.points[i][0];
context.moveTo(x, y);
} | conditional_block |
Polygon.ts | import Node, {Bounds, Point} from './Node';
import NodeFixedBounds from './NodeFixedBounds';
const zeroPoint: Point = {x: 0, y: 0};
export interface PolygonStyle {
strokeStyle?: string;
lineWidth?: number;
fillStyle?: string;
lineDash?: Array<number>;
}
export interface PolygonParameters extends Poly... | context.lineTo(x, y);
}
context.closePath();
}
context.fill();
if (this.lineWidth > 0) {
context.setLineDash(this.lineDash);
context.stroke();
}
context.strokeStyle = oldStrokeStyle;
context.lineWidth = oldL... | {
const oldStrokeStyle = context.strokeStyle;
const oldLineWidth = context.lineWidth;
const oldFillStyle = context.fillStyle;
const oldLineDash = context.getLineDash();
context.strokeStyle = this.strokeStyle;
context.lineWidth = this.lineWidth;
context.fillStyle =... | identifier_body |
Polygon.ts | import Node, {Bounds, Point} from './Node';
import NodeFixedBounds from './NodeFixedBounds';
const zeroPoint: Point = {x: 0, y: 0};
export interface PolygonStyle {
strokeStyle?: string;
lineWidth?: number;
fillStyle?: string;
lineDash?: Array<number>;
}
export interface PolygonParameters extends Poly... | ({points, strokeStyle = 'rgba(0, 0, 0, 1)', lineWidth = 1, fillStyle = 'rgba(255, 255, 255, 1)', lineDash = []}: PolygonParameters) {
// TODO: lineWidth to increase bounds
let minX = Number.POSITIVE_INFINITY;
let minY = Number.POSITIVE_INFINITY;
let maxX = Number.NEGATIVE_INFINITY;
... | constructor | identifier_name |
Polygon.ts | import Node, {Bounds, Point} from './Node';
import NodeFixedBounds from './NodeFixedBounds';
const zeroPoint: Point = {x: 0, y: 0};
export interface PolygonStyle {
strokeStyle?: string;
lineWidth?: number;
fillStyle?: string;
lineDash?: Array<number>;
} | class Polygon<T> extends NodeFixedBounds<T> {
private points: Array<Array<Point>>;
private strokeStyle: string;
private lineWidth: number;
private fillStyle: string;
private lineDash: Array<number>;
constructor({points, strokeStyle = 'rgba(0, 0, 0, 1)', lineWidth = 1, fillStyle = 'rgba(255, 255... |
export interface PolygonParameters extends PolygonStyle {
points: Array<Array<Point>>;
}
| random_line_split |
macros.rs | pub fn macros() {
println!("***Macros***");
basics();
advanced();
common_macros();
println!("");
}
macro_rules! mvec {
( $( $x:expr),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
... | () {
unimplemented!();
}
if false {
unreachable!();
}
let x: Option<i32> = None;
match x {
Some(_) => unreachable!(),
None => println!("I know x is None!"),
}
// will panic because unimp_test is not yet implemented
// unimp_test();
}
| unimp_test | identifier_name |
macros.rs | pub fn macros() |
macro_rules! mvec {
( $( $x:expr),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
macro_rules! foo {
(x => $e:expr) => (println!("mode X: {}", $e));
(y => $e:expr) => (println!("mode Y: ... | {
println!("***Macros***");
basics();
advanced();
common_macros();
println!("");
} | identifier_body |
macros.rs | pub fn macros() {
println!("***Macros***");
basics();
advanced();
common_macros();
println!("");
}
macro_rules! mvec {
( $( $x:expr),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
... | #[allow(unused_variables, dead_code)]
fn common_macros() {
// panic!("oh no!"); // causes the thread to panic
let v1 = vec![1, 2, 3];
let v2 = vec![0; 10];
assert!(true);
assert_eq!(5, 3+2);
// not really
// assert!(5 < 3);
// assert_eq!(5, 3);
use std;
use std::fs::File;
... | ($x:expr) => ( $crate::increment($x) )
}
| random_line_split |
reader.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | /// # Panics
///
/// It will panic if it there is insufficient data to fulfill a request.
///
/// # Example
///
/// ```rust
/// use std::rand::{reader, Rng};
/// use std::io::MemReader;
///
/// let mut rng = reader::ReaderRng::new(MemReader::new(vec!(1,2,3,4,5,6,7,8)));
/// println!("{:x}", rng.gen::<uint>());
/// ```
... |
/// An RNG that reads random bytes straight from a `Reader`. This will
/// work best with an infinite reader, but this is not required.
/// | random_line_split |
reader.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn next_u64(&mut self) -> u64 {
// see above for explanation.
if cfg!(target_endian="little") {
self.reader.read_le_u64().unwrap()
} else {
self.reader.read_be_u64().unwrap()
}
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { retur... | {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="little") {
self.reader.read_le_u32().unwrap()
} else {
... | identifier_body |
reader.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
match self.reader.read_at_least(v.len(), v) {
Ok(_) => {}
Err(e) => panic!("ReaderRng.fill_bytes error: {}", e)
}
}
}
#[cfg(test)]
mod test {
use prelude::*;
use super::ReaderRng;... | {
self.reader.read_be_u64().unwrap()
} | conditional_block |
reader.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&mut self) -> u64 {
// see above for explanation.
if cfg!(target_endian="little") {
self.reader.read_le_u64().unwrap()
} else {
self.reader.read_be_u64().unwrap()
}
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
matc... | next_u64 | identifier_name |
xhr.js | http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* 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 governi... | pagespeed.XhrHijack.prototype['send'] = function(opt_x) {
pagespeed.XhrHijack.listener_['xhrSendHook']();
this.xhr.send(opt_x);
};
/**
* Hijacked.
* @param {string} x
* @this {pagespeed.XhrHijack}
*
* Note: this usage of at-this is deployed in lieu of at-export because of
* much smaller output file sizes fo... | * Note: this usage of at-this is deployed in lieu of at-export because of
* much smaller output file sizes for this module, which is loaded blocking
* in head.
*/ | random_line_split |
xhr.js | http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* 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 pe... |
if (this.readyState == 4) {
pagespeed.XhrHijack.listener_['xhrResponseHook'](this.status);
}
};
/**
* Wrapped abort callback.
* @this {pagespeed.XhrHijack}
*
* Note: this usage of at-this is deployed in lieu of at-export because of
* much smaller output file sizes for this module, which is loaded blocki... | {
this.onreadystatechange();
} | conditional_block |
dates.ts | import { ParsedMatchSchema } from 'serina.schema';
import { DateTime } from 'luxon';
import { DATES } from './dates.constants';
import parseMatches from 'utils/parseMatches';
import convertDateStringToObj from 'utils/convertDateStringToObj';
import remove from 'utils/remove';
import matchPattern from 'utils/matchPatter... |
static convertMatchToDateObj(matchingText: string): Date {
const removedFillerWords = remove(matchingText, DATES.FILLER_WORDS);
const dateObj = convertDateStringToObj(removedFillerWords);
if (!dateObj) return null;
const { day, month, year } = dateObj;
const newDateTime =... | {
const pattern = `(${DATES.FILLER_WORDS})?(${DATES.ANY})`;
const matches = matchPattern(text, pattern, false);
if (!matches) return null;
return matches.map(match => {
const dateTimeObj = this.convertMatchToDateObj(match);
return parseMatches(text, match, dateT... | identifier_body |
dates.ts | import { DateTime } from 'luxon';
import { DATES } from './dates.constants';
import parseMatches from 'utils/parseMatches';
import convertDateStringToObj from 'utils/convertDateStringToObj';
import remove from 'utils/remove';
import matchPattern from 'utils/matchPattern';
export default class Dates {
static parseT... | import { ParsedMatchSchema } from 'serina.schema'; | random_line_split | |
dates.ts | import { ParsedMatchSchema } from 'serina.schema';
import { DateTime } from 'luxon';
import { DATES } from './dates.constants';
import parseMatches from 'utils/parseMatches';
import convertDateStringToObj from 'utils/convertDateStringToObj';
import remove from 'utils/remove';
import matchPattern from 'utils/matchPatter... | (text: string): ParsedMatchSchema[] {
const pattern = `(${DATES.FILLER_WORDS})?(${DATES.ANY})`;
const matches = matchPattern(text, pattern, false);
if (!matches) return null;
return matches.map(match => {
const dateTimeObj = this.convertMatchToDateObj(match);
re... | parseText | identifier_name |
SaveQuery.js | compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF AN... | {
alert(textStatus.responseText);
} | conditional_block | |
SaveQuery.js | * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* ... | var $target = $( event.currentTarget );
this.unselect_current_selected_folder( );
$target.children('.folder_row').addClass( 'selected' );
var f_name = $target.find( 'a' ).attr('href').replace('#', '');
this.set_name(f_name, null);
var $queries = $target.children( '.fold... |
toggle_folder: function( event ) { | random_line_split |
findsong.py | Parser 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.
The Jazz Parser is distributed in the hope that it will be useful,
but WITHOUT... | ():
usage = "%prog [options] <song-set> <results-file0> [<results-file1> ...]"
parser = OptionParser(usage=usage)
parser.add_option("--popt", "--parser-options", dest="popts", action="append", help="specify options for the parser that interprets the gold standard annotations. Type '--popt help' to get a lis... | main | identifier_name |
findsong.py | Parser 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.
The Jazz Parser is distributed in the hope that it will be useful,
but WITHOUT... | print options_help_text(DirectedCkyParser.PARSER_OPTIONS, intro="Available options for gold standard interpreter")
sys.exit(0)
poptstr = ":".join(poptstr)
else:
poptstr = ""
popts = ModuleOption.process_option_string(poptstr)
# Check that the options are valid
try... | usage = "%prog [options] <song-set> <results-file0> [<results-file1> ...]"
parser = OptionParser(usage=usage)
parser.add_option("--popt", "--parser-options", dest="popts", action="append", help="specify options for the parser that interprets the gold standard annotations. Type '--popt help' to get a list of opt... | identifier_body |
findsong.py | Parser 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.
The Jazz Parser is distributed in the hope that it will be useful,
but WITHOUT... | # The song name was not found in the corpus at all
correct_rank = None
if correct_rank is None:
print "Song was not found in corpus"
else:
print "Correct answer got rank %d" % correct_rank
# Record the r... | break
else: | random_line_split |
findsong.py | parser.data.parsing import ParseResults
from jazzparser.parsers.cky.parser import DirectedCkyParser
from jazzparser.utils.options import options_help_text, ModuleOption
from jazzparser.data.tonalspace import TonalSpaceAnalysisSet
from jazzparser.formalisms.music_halfspan import Formalism
from jazzparser.utils.tableprin... | print "\nGot ranks for %d sequences" % num_ranked
# Compute the mean reciprocal rank, the reciprocal of the harmonic mean
# of the ranks of the correct answers
mrr = sum([0.0 if rank is None else 1.0/rank for rank in ranks], 0.0) \
... | conditional_block | |
setup.py |
from distutils.command.build_py \
import build_py_2to3 as build_py
# need to convert sources to Py3 on installation
fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
if fix.split('fix_')[-1] not in ('next',)
]
build_py.fixer_names... | defines.append(('CYTHON_REFNANNY', '1'))
extensions = []
if sys.version_info[0] >= 3:
from Cython.Distutils import build_ext as build_ext_orig
for module in compiled_modules:
source_file = os.path.join(source_root, *module.split('.'))
if os.path.exists(source_fil... | source_root = os.path.abspath(os.path.dirname(__file__))
compiled_modules = ["Cython.Plex.Scanners",
"Cython.Plex.Actions",
"Cython.Compiler.Lexicon",
"Cython.Compiler.Scanning",
"Cython.Compiler.Parsing",
... | identifier_body |
setup.py |
from distutils.command.build_py \
import build_py_2to3 as build_py
# need to convert sources to Py3 on installation
fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
if fix.split('fix_')[-1] not in ('next',)
]
build_py.fixer_names... | (profile=False, compile_more=False, cython_with_refnanny=False):
source_root = os.path.abspath(os.path.dirname(__file__))
compiled_modules = ["Cython.Plex.Scanners",
"Cython.Plex.Actions",
"Cython.Compiler.Lexicon",
"Cython.Compiler.Scannin... | compile_cython_modules | identifier_name |
setup.py |
from distutils.command.build_py \
import build_py_2to3 as build_py
# need to convert sources to Py3 on installation
fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
if fix.split('fix_')[-1] not in ('next',)
]
build_py.fixer_names... | keep_alive(sys.modules[module])
del sys.modules[module]
sys.path.insert(0, os.path.join(source_root, self.build_lib))
if profile:
from Cython.Compiler.Options import directive_defaults
directive_defaults['pr... | for module in already_imported: | random_line_split |
setup.py |
from distutils.command.build_py \
import build_py_2to3 as build_py
# need to convert sources to Py3 on installation
fixers = [ fix for fix in lib2to3.refactor.get_fixers_from_package("lib2to3.fixes")
if fix.split('fix_')[-1] not in ('next',)
]
build_py.fixer_names... |
def compile_cython_modules(profile=False, compile_more=False, cython_with_refnanny=False):
source_root = os.path.abspath(os.path.dirname(__file__))
compiled_modules = ["Cython.Plex.Scanners",
"Cython.Plex.Actions",
"Cython.Compiler.Lexicon",
... | scripts = ["cython.py"]
if include_debugger:
scripts.append('cygdb.py') | conditional_block |
lib.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | // Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#![deny(
dead_code,
non_camel_cas... | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | random_line_split |
lhp.controller.ts | /**
* Created by akabeera on 2/18/2016.
*/
/// <reference path="../../typings/browser.d.ts" />
/// <reference path="../data/gifs-data-model.ts" />
/// <reference path="../services/gif-data.ts" />
module app.Controllers {
export interface ILhpController {
gifSections:Array<string>;
gifData:Array<... |
public SelectSection(s:string):void {
this.gifData.forEach( section => {
if (section.id.toLowerCase() === s.toLowerCase()) {
this.currentSection = s;
this.$state.go('home.main.section', {
section:s
... | {
this.Init();
} | identifier_body |
lhp.controller.ts | /**
* Created by akabeera on 2/18/2016.
*/
/// <reference path="../../typings/browser.d.ts" />
/// <reference path="../data/gifs-data-model.ts" />
/// <reference path="../services/gif-data.ts" />
module app.Controllers {
export interface ILhpController {
gifSections:Array<string>;
gifData:Array<... | (s:string):void {
this.gifData.forEach( section => {
if (section.id.toLowerCase() === s.toLowerCase()) {
this.currentSection = s;
this.$state.go('home.main.section', {
section:s
});
retur... | SelectSection | identifier_name |
lhp.controller.ts | /**
* Created by akabeera on 2/18/2016.
*/
/// <reference path="../../typings/browser.d.ts" />
/// <reference path="../data/gifs-data-model.ts" />
/// <reference path="../services/gif-data.ts" />
module app.Controllers {
export interface ILhpController {
gifSections:Array<string>;
gifData:Array<... |
return false;
}
private Init() {
this.$log.info('LHP Controller');
this.gifSections = new Array<string>();
this.gifDataService.GetData().then( (data) => {
this.gifData = data.data;
this.gifData.forEach( g => {
... | {
return true;
} | conditional_block |
lhp.controller.ts | /**
* Created by akabeera on 2/18/2016.
*/
/// <reference path="../../typings/browser.d.ts" />
/// <reference path="../data/gifs-data-model.ts" />
/// <reference path="../services/gif-data.ts" />
module app.Controllers {
export interface ILhpController {
gifSections:Array<string>;
gifData:Array<... | if (section.id.toLowerCase() === s.toLowerCase()) {
this.currentSection = s;
this.$state.go('home.main.section', {
section:s
});
return;
}
});
}
public se... | random_line_split | |
build.rs | /*
* 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 ... | () {
let out_dir = env::var("OUT_DIR").unwrap();
let output = Command::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/build_test_lib.py"
))
.arg(&out_dir)
.output()
.expect("Failed to execute command");
assert!(
Path::new(&format!("{}/test.so", out_dir)).exists(),
... | main | identifier_name |
build.rs | /*
* 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 ... | */
use std::{env, path::Path, process::Command};
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let output = Command::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/build_test_lib.py"
))
.arg(&out_dir)
.output()
.expect("Failed to execute command");
assert!(
... | * software 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. | random_line_split |
build.rs | /*
* 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 ... | }
| {
let out_dir = env::var("OUT_DIR").unwrap();
let output = Command::new(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/build_test_lib.py"
))
.arg(&out_dir)
.output()
.expect("Failed to execute command");
assert!(
Path::new(&format!("{}/test.so", out_dir)).exists(),
... | identifier_body |
literal.js | /**
* @license
* Copyright 2014 Software Freedom Conservancy
*
* 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 ... |
/**
* @override
*/
wgxpath.Literal.prototype.toString = function() {
return 'Literal: ' + this.text_;
}; | random_line_split | |
commswave.py | """
commswave
=========
Takes device communications up and down according to a timefunction.
Comms will be working whenever the timefunction returns non-zero.
Configurable parameters::
{
"timefunction" : A timefunction definition
"threshold" : (optional) Comms will only work when the timefunction ... | self.messages_sent += 1
return is_ok
def transmit(self, the_id, ts, properties, force_comms):
if self.comms_gate_properties is not None: # We're gating properties
if not self.timefunction_says_communicate():
for p in self.comms_gate_properties:
... | self.messages_attempted += 1
is_ok = super(Commswave, self).comms_ok()
is_ok = is_ok and self.timefunction_says_communicate()
if is_ok: | random_line_split |
commswave.py | """
commswave
=========
Takes device communications up and down according to a timefunction.
Comms will be working whenever the timefunction returns non-zero.
Configurable parameters::
{
"timefunction" : A timefunction definition
"threshold" : (optional) Comms will only work when the timefunction ... |
else:
self.messages_attempted += 1
is_ok = super(Commswave, self).comms_ok()
is_ok = is_ok and self.timefunction_says_communicate()
if is_ok:
self.messages_sent += 1
return is_ok
def transmit(self, the_id, ts, properties, force_co... | return super(Commswave, self).comms_ok() | conditional_block |
commswave.py | """
commswave
=========
Takes device communications up and down according to a timefunction.
Comms will be working whenever the timefunction returns non-zero.
Configurable parameters::
{
"timefunction" : A timefunction definition
"threshold" : (optional) Comms will only work when the timefunction ... | (self):
super(Commswave,self).close()
logging.info("Comms report for " + str(self.properties["$id"]) + " " +
str(self.messages_sent) + " sent ("+str(100 * self.messages_sent/self.messages_attempted) + "%) from " +
str(self.messages_attempted) + " total")
# Private methods
... | close | identifier_name |
commswave.py | """
commswave
=========
Takes device communications up and down according to a timefunction.
Comms will be working whenever the timefunction returns non-zero.
Configurable parameters::
{
"timefunction" : A timefunction definition
"threshold" : (optional) Comms will only work when the timefunction ... |
def timefunction_says_communicate(self):
thresh = 0.0
if self.comms_tf_threshold is not None:
thresh = self.comms_tf_threshold
return self.comms_timefunction.state() > thresh
def comms_ok(self):
if self.comms_gate_properties is not None: # If we're gating individu... | """Take Comms up and down according to some time function"""
tf = params["commswave"]["timefunction"]
self.comms_timefunction = importer.get_class("timefunction", list(tf.keys())[0])(engine, self, tf[list(tf.keys())[0]])
self.comms_tf_threshold = params["commswave"].get("threshold", None)
... | identifier_body |
linalg.py | 7, 22
], dtype=float)
# A = np.array([
# [3,-0.1,-0.2],
# [0.1,7,-0.3],
# [0.3,-0.2,10]
# ], dtype = float)
# b = np.array([
# 7.85, -19.3, 71.4
# ], dtype=float)
# Simplest version
def gauss1(A, b):
assert A.shape[0] == len(b), "A and b must have the same length"
dim = A.shape[0]
x = np.zeros(dim)
... | (A, b, tol, err):
assert A.shape[0] == len(b), "A and b must have the same length"
dim = A.shape[0]
x = np.zeros(dim)
pv = np.arange(0, dim, 1)
err = 0
# Eliminate everything but the last row (dim-1)
for i in range(dim - 1):
# Store the current pivot from the pivot list
pvt =... | gauss | identifier_name |
linalg.py | , 7, 22
], dtype=float)
# A = np.array([
# [3,-0.1,-0.2],
# [0.1,7,-0.3],
# [0.3,-0.2,10]
# ], dtype = float)
# b = np.array([
# 7.85, -19.3, 71.4
# ], dtype=float)
# Simplest version
def gauss1(A, b):
assert A.shape[0] == len(b), "A and b must have the same length"
dim = A.shape[0]
x = np.zeros(dim)
... | # print(pv)
# Check if the current pivot is close to 0
# if it is, break and set the error flag
if np.abs(A[pv[i], i]) < tol:
err = -1
break
# Here we actually perform the actual elimination
for j in range(i + 1, dim):
# print("c = {0}/... | pv[pvt] = tmp | random_line_split |
linalg.py | 7, 22
], dtype=float)
# A = np.array([
# [3,-0.1,-0.2],
# [0.1,7,-0.3],
# [0.3,-0.2,10]
# ], dtype = float)
# b = np.array([
# 7.85, -19.3, 71.4
# ], dtype=float)
# Simplest version
def gauss1(A, b):
assert A.shape[0] == len(b), "A and b must have the same length"
dim = A.shape[0]
x = np.zeros(dim)
... |
x[i] = sum / A[pv[i], i]
return x
def inv(A, tol, err):
"""We always assume square matrices"""
dim = A.shape[0]
A1 = np.zeros(A.shape)
A, pvt = lu_factor(A, tol, err)
if err == -1:
return None
for i in range(dim):
b = np.zeros(dim)
b[i] = 1
x = l... | sum -= x[j] * A[pv[i], j] | conditional_block |
linalg.py | 7, 22
], dtype=float)
# A = np.array([
# [3,-0.1,-0.2],
# [0.1,7,-0.3],
# [0.3,-0.2,10]
# ], dtype = float)
# b = np.array([
# 7.85, -19.3, 71.4
# ], dtype=float)
# Simplest version
def gauss1(A, b):
|
def gauss(A, b, tol, err):
assert A.shape[0] == len(b), "A and b must have the same length"
dim = A.shape[0]
x = np.zeros(dim)
pv = np.arange(0, dim, 1)
err = 0
# Eliminate everything but the last row (dim-1)
for i in range(dim - 1):
# Store the current pivot from the pivot list
... | assert A.shape[0] == len(b), "A and b must have the same length"
dim = A.shape[0]
x = np.zeros(dim)
# Elimination
for i in range(dim - 1):
for j in range(i + 1, dim):
c = A[j, i] / A[i, i]
A[j, :] -= (c * A[i, :])
b[j] -= (c * b[i])
# Substitution
x[-1... | identifier_body |
mod.rs | // The MIT License (MIT)
// Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com>
| // the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY K... | // Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell co... | random_line_split |
StahnuTo.py | # -*- coding: utf-8 -*-
import re
from pyload.plugin.Account import Account
class StahnuTo(Account):
__name = "StahnuTo"
__type = "account"
__version = "0.05"
__description = """StahnuTo account plugin"""
__license = "GPLv3"
__authors = [("zoidberg", "zoidberg@mujmail.cz")]
... | self.wrongPassword() | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.