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 |
|---|---|---|---|---|
List.py | # -*- coding: utf-8 -*-
#
# CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2010-2014 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the... | entry += widget
Container.__iadd__ (self, entry)
def __iadd__ (self, widget):
self.Add (widget)
return self
def Render (self):
render = Container.Render (self)
props = {'id': self.id,
'tag': self.tag,
'props':... | random_line_split | |
List.py | # -*- coding: utf-8 -*-
#
# CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2010-2014 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the... |
else:
entry += widget
Container.__iadd__ (self, entry)
def __iadd__ (self, widget):
self.Add (widget)
return self
def Render (self):
render = Container.Render (self)
props = {'id': self.id,
'tag': self.tag,
... | entry += w | conditional_block |
List.py | # -*- coding: utf-8 -*-
#
# CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2010-2014 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the... | (Container):
def __init__ (self, _props={}, tag='li'):
Container.__init__ (self)
self.tag = tag
self.props = _props.copy()
def Render (self):
render = Container.Render (self)
if 'id' in self.props:
self.id = self.props['id']
props = {'id': s... | ListEntry | identifier_name |
List.py | # -*- coding: utf-8 -*-
#
# CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2010-2014 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the... | self.tag = tag
self.props = _props.copy()
def Add (self, widget, props={}):
assert isinstance(widget, Widget) or widget is None or type(widget) is list
entry = ListEntry (props.copy())
if widget:
if type(widget) == list:
for w in widget:
... | """
Widget for lists of elements. The list can grow dynamically, and
accept any kind of CTK widget as listed element. Arguments are
optional.
Arguments:
_props: dictionary with properties for the HTML element,
such as {'name': 'foo', 'id': 'bar', 'class': 'baz'}
... | identifier_body |
todos.ts | export interface TodoItem {
id: number;
completed: boolean;
text: string;
}
export const ADD_TODO = 'ADD_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER';
export const COMPLETE_ALL_TODOS = 'COMPLETE_ALL_TODOS';
let _id = 0;
export const Visibilit... | );
default:
return state;
}
} | todo => (todo.id === payload.id ? { ...todo, completed: true } : todo) | random_line_split |
todos.ts | export interface TodoItem {
id: number;
completed: boolean;
text: string;
}
export const ADD_TODO = 'ADD_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER';
export const COMPLETE_ALL_TODOS = 'COMPLETE_ALL_TODOS';
let _id = 0;
export const Visibilit... | (
state: TodoItem[] = [],
{ type, payload }: any
): TodoItem[] {
switch (type) {
case ADD_TODO:
return [
...state,
{
id: ++_id,
text: payload.text,
completed: false,
},
];
case COMPLETE_ALL_TODOS:
return state.map(todo => ({ ...todo, ... | todos | identifier_name |
todos.ts | export interface TodoItem {
id: number;
completed: boolean;
text: string;
}
export const ADD_TODO = 'ADD_TODO';
export const COMPLETE_TODO = 'COMPLETE_TODO';
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER';
export const COMPLETE_ALL_TODOS = 'COMPLETE_ALL_TODOS';
let _id = 0;
export const Visibilit... | }
| {
switch (type) {
case ADD_TODO:
return [
...state,
{
id: ++_id,
text: payload.text,
completed: false,
},
];
case COMPLETE_ALL_TODOS:
return state.map(todo => ({ ...todo, completed: true }));
case COMPLETE_TODO:
return state.map... | identifier_body |
djvutext.py | #!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
... | ) -> None:
"""
Initializer.
:param djvu: djvu from where to fetch the text layer
:type djvu: DjVuFile object
:param index: index page in the Index: namespace
:type index: Page object
:param pages: page interval to upload (start, end)
"""
super... | """
A bot that uploads text-layer from djvu files to Page:namespace.
Works only on sites with Proofread Page extension installed.
.. versionchanged:: 7.0
CheckerBot is a ConfigParserBot
"""
update_options = {
'force': False,
'summary': '',
}
def __init__(
s... | identifier_body |
djvutext.py | #!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
... |
# Check the djvu file exists and, if so, create the DjVuFile wrapper.
djvu = DjVuFile(djvu_path)
if not djvu.has_text():
pywikibot.error('No text layer in djvu file {}'.format(djvu.file))
return
# Parse pages param.
pages = pages.split(',')
for i, page_interval in enumerate(p... | djvu_path = os.path.join(djvu_path, index) | conditional_block |
djvutext.py | #!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
... | 'Use -force option to overwrite the output page.'
.format(page))
else:
self.userPut(page, old_text, new_text, summary=self.opt.summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv i... | random_line_split | |
djvutext.py | #!/usr/bin/python3
"""
This bot uploads text from djvu files onto pages in the "Page" namespace.
It is intended to be used for Wikisource.
The following parameters are supported:
-index:... name of the index page (without the Index: prefix)
-djvu:... path to the djvu file, it shall be:
... | (self, page) -> None:
"""Process one page."""
old_text = page.text
# Overwrite body of the page with content from djvu
page.body = self._djvu.get_page(page.page_number)
new_text = page.text
if page.exists() and not self.opt.force:
pywikibot.output(
... | treat | identifier_name |
list_funds.js | dojo.require("dijit.Dialog");
dojo.require("dijit.form.FilteringSelect");
dojo.require('dijit.form.Button');
dojo.require('dijit.TooltipDialog');
dojo.require('dijit.form.DropDownButton');
dojo.require('dijit.form.CheckBox');
dojo.require('dojox.grid.DataGrid');
dojo.require('dojo.data.ItemFileWriteStore');
dojo.requir... | () {
contextOrg = openils.User.user.ws_ou();
/* Reveal controls for rollover without money if org units say ok.
* Actual ability to do the operation is controlled in the database, of
* course. */
var ouSettings = fieldmapper.aou.fetchOrgSettingBatch(
openils.User.user.ws_ou(), ["acq.fund.... | initPage | identifier_name |
list_funds.js | dojo.require("dijit.Dialog");
dojo.require("dijit.form.FilteringSelect");
dojo.require('dijit.form.Button');
dojo.require('dijit.TooltipDialog');
dojo.require('dijit.form.DropDownButton');
dojo.require('dijit.form.CheckBox');
dojo.require('dojox.grid.DataGrid');
dojo.require('dojo.data.ItemFileWriteStore');
dojo.requir... | else {
method += '.propagate';
}
var dryRun = args.dry_run[0] == 'on';
if(dryRun) method += '.dry_run';
var encumbOnly = args.encumb_only[0] == 'on';
var count = 0;
var amount_rolled = 0;
var year = fundFilterYearSelect.attr('value'); // TODO alternate selector?
... | {
method += '.combined';
} | conditional_block |
list_funds.js | dojo.require("dijit.Dialog");
dojo.require("dijit.form.FilteringSelect");
dojo.require('dijit.form.Button');
dojo.require('dijit.TooltipDialog');
dojo.require('dijit.form.DropDownButton');
dojo.require('dijit.form.CheckBox');
dojo.require('dojox.grid.DataGrid');
dojo.require('dojo.data.ItemFileWriteStore');
dojo.requir... | function() {
contextOrg = this.attr('value');
dojo.byId('oils-acq-rollover-ctxt-org').innerHTML =
fieldmapper.aou.findOrgUnit(contextOrg).shortname();
rolloverMode = false;
gridDataLoader();
}
);
};
... | {
contextOrg = openils.User.user.ws_ou();
/* Reveal controls for rollover without money if org units say ok.
* Actual ability to do the operation is controlled in the database, of
* course. */
var ouSettings = fieldmapper.aou.fetchOrgSettingBatch(
openils.User.user.ws_ou(), ["acq.fund.all... | identifier_body |
list_funds.js | dojo.require("dijit.Dialog");
dojo.require("dijit.form.FilteringSelect");
dojo.require('dijit.form.Button');
dojo.require('dijit.TooltipDialog');
dojo.require('dijit.form.DropDownButton');
dojo.require('dijit.form.CheckBox');
dojo.require('dojox.grid.DataGrid');
dojo.require('dojo.data.ItemFileWriteStore');
dojo.requir... | dojo.query(".encumb_only").forEach(
function(o) { openils.Util.show(o, "table-row"); }
);
}
var connect = function() {
dojo.connect(contextOrgSelector, 'onChange',
function() {
contextOrg = this.attr('value');
dojo.byId('oils-acq-r... | ouSettings["acq.fund.allow_rollover_without_money"].value
) { | random_line_split |
robots_txt.rs | use crate::model::Path;
use crate::model::RequestRate;
use crate::model::RobotsTxt;
use crate::service::RobotsTxtService;
use std::time::Duration;
use url::Url;
impl RobotsTxtService for RobotsTxt {
fn can_fetch(&self, user_agent: &str, url: &Url) -> bool {
if url.origin() != *self.get_origin() {
... |
fn normalize_url_ignore_origin(&self, url: &mut Url) {
if url.query().is_none() {
return;
}
let mut query_params_to_filter = Vec::new();
let path = Path::from_url(url);
for clean_params in self.get_clean_params().iter() {
if clean_params.get_path_pat... | {
if url.origin() != *self.get_origin() {
return false;
}
self.normalize_url_ignore_origin(url);
true
} | identifier_body |
robots_txt.rs | use crate::model::Path;
use crate::model::RequestRate;
use crate::model::RobotsTxt;
use crate::service::RobotsTxtService;
use std::time::Duration;
use url::Url;
impl RobotsTxtService for RobotsTxt {
fn can_fetch(&self, user_agent: &str, url: &Url) -> bool {
if url.origin() != *self.get_origin() {
... | (&self, url: &mut Url) {
if url.query().is_none() {
return;
}
let mut query_params_to_filter = Vec::new();
let path = Path::from_url(url);
for clean_params in self.get_clean_params().iter() {
if clean_params.get_path_pattern().applies_to(&path) {
... | normalize_url_ignore_origin | identifier_name |
robots_txt.rs | use crate::model::Path;
use crate::model::RequestRate;
use crate::model::RobotsTxt;
use crate::service::RobotsTxtService;
use std::time::Duration;
use url::Url;
impl RobotsTxtService for RobotsTxt {
fn can_fetch(&self, user_agent: &str, url: &Url) -> bool {
if url.origin() != *self.get_origin() {
... |
}
let mut pairs: Vec<(String, String)> = url
.query_pairs()
.map(|(key, value)| (key.into(), value.into()))
.collect();
{
let mut query_pairs_mut = url.query_pairs_mut();
query_pairs_mut.clear();
for (key, value) in pairs.d... | {
query_params_to_filter.extend_from_slice(clean_params.get_params())
} | conditional_block |
robots_txt.rs | use crate::model::Path;
use crate::model::RequestRate;
use crate::model::RobotsTxt;
use crate::service::RobotsTxtService;
use std::time::Duration;
use url::Url;
impl RobotsTxtService for RobotsTxt {
fn can_fetch(&self, user_agent: &str, url: &Url) -> bool {
if url.origin() != *self.get_origin() {
... | }
None
});
if let Some(rule_decision) = rule_decision {
return rule_decision;
}
// Empty robots.txt allows crawling. Everything that was not denied must be allowed.
true
}
fn get_crawl_delay(&self, user_agent: &str) -> Option<Duration>... | return Some(rule.get_allowance());
} | random_line_split |
hygiene_example_codegen.rs | // force-host
// no-prefer-dynamic
#![feature(proc_macro_quote)]
#![crate_type = "proc-macro"]
extern crate proc_macro as proc_macro_renamed; // This does not break `quote!`
use proc_macro_renamed::{TokenStream, quote};
#[proc_macro]
pub fn | (input: TokenStream) -> TokenStream {
quote!(hello_helper!($input))
//^ `hello_helper!` always resolves to the following proc macro,
//| no matter where `hello!` is used.
}
#[proc_macro]
pub fn hello_helper(input: TokenStream) -> TokenStream {
quote! {
extern crate hygiene_example; // This is n... | hello | identifier_name |
hygiene_example_codegen.rs | // force-host |
#![feature(proc_macro_quote)]
#![crate_type = "proc-macro"]
extern crate proc_macro as proc_macro_renamed; // This does not break `quote!`
use proc_macro_renamed::{TokenStream, quote};
#[proc_macro]
pub fn hello(input: TokenStream) -> TokenStream {
quote!(hello_helper!($input))
//^ `hello_helper!` always re... | // no-prefer-dynamic | random_line_split |
hygiene_example_codegen.rs | // force-host
// no-prefer-dynamic
#![feature(proc_macro_quote)]
#![crate_type = "proc-macro"]
extern crate proc_macro as proc_macro_renamed; // This does not break `quote!`
use proc_macro_renamed::{TokenStream, quote};
#[proc_macro]
pub fn hello(input: TokenStream) -> TokenStream {
quote!(hello_helper!($input)... | {
quote! {
extern crate hygiene_example; // This is never a conflict error
let string = format!("hello {}", $input);
//^ `format!` always resolves to the prelude macro,
//| even if a different `format!` is in scope where `hello!` is used.
hygiene_example::print(&string)
}... | identifier_body | |
test_something.py | # Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this... | post_install = True
at_install = False
def test_ui_web(self):
"""Test backend tests."""
self.phantom_js(
"/web/tests?debug=assets&module=module_name",
"",
login="admin",
)
def test_ui_website(self):
"""Test frontend tour."""
s... | pass
class UICase(HttpCase):
| random_line_split |
test_something.py | # Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this... | (self):
"""Test backend tests."""
self.phantom_js(
"/web/tests?debug=assets&module=module_name",
"",
login="admin",
)
def test_ui_website(self):
"""Test frontend tour."""
self.phantom_js(
url_path="/?debug=assets",
... | test_ui_web | identifier_name |
test_something.py | # Copyright <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo.tests.common import HttpCase, TransactionCase
class SomethingCase(TransactionCase):
def setUp(self, *args, **kwargs):
super(SomethingCase, self).setUp(*args, **kwargs)
# TODO Replace this... |
def test_ui_website(self):
"""Test frontend tour."""
self.phantom_js(
url_path="/?debug=assets",
code="odoo.__DEBUG__.services['web.Tour']"
".run('test_module_name', 'test')",
ready="odoo.__DEBUG__.services['web.Tour'].tours.test_module_name",
... | """Test backend tests."""
self.phantom_js(
"/web/tests?debug=assets&module=module_name",
"",
login="admin",
) | identifier_body |
sync_rando.py | from django.conf import settings
from django.utils import translation
from geotrek.tourism import models as tourism_models
from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet
from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand
# Register mapentity models |
class Command(BaseCommand):
def sync_content(self, lang, content):
self.sync_pdf(lang, content)
for picture, resized in content.resized_pictures:
self.sync_media_file(lang, resized)
def sync_event(self, lang, event):
self.sync_pdf(lang, event)
for picture, resized... | from geotrek.tourism import urls # NOQA
| random_line_split |
sync_rando.py | from django.conf import settings
from django.utils import translation
from geotrek.tourism import models as tourism_models
from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet
from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand
# Register mapentity models
fro... |
def sync(self):
super(Command, self).sync()
self.sync_static_file('**', 'tourism/touristicevent.svg')
self.sync_pictograms('**', tourism_models.InformationDeskType)
self.sync_pictograms('**', tourism_models.TouristicContentCategory)
self.sync_pictograms('**', tourism_model... | self.sync_geojson(lang, TouristicContentViewSet, 'touristiccontents')
self.sync_geojson(lang, TouristicEventViewSet, 'touristicevents')
contents = tourism_models.TouristicContent.objects.existing().order_by('pk')
contents = contents.filter(**{'published_{lang}'.format(lang=lang): True})
... | identifier_body |
sync_rando.py | from django.conf import settings
from django.utils import translation
from geotrek.tourism import models as tourism_models
from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet
from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand
# Register mapentity models
fro... | (self, lang, event):
self.sync_pdf(lang, event)
for picture, resized in event.resized_pictures:
self.sync_media_file(lang, resized)
def sync_tourism(self, lang):
self.sync_geojson(lang, TouristicContentViewSet, 'touristiccontents')
self.sync_geojson(lang, TouristicEvent... | sync_event | identifier_name |
sync_rando.py | from django.conf import settings
from django.utils import translation
from geotrek.tourism import models as tourism_models
from geotrek.tourism.views import TouristicContentViewSet, TouristicEventViewSet
from geotrek.trekking.management.commands.sync_rando import Command as BaseCommand
# Register mapentity models
fro... |
events = tourism_models.TouristicEvent.objects.existing().order_by('pk')
events = events.filter(**{'published_{lang}'.format(lang=lang): True})
for event in events:
self.sync_event(lang, event)
def sync(self):
super(Command, self).sync()
self.sync_static_file(... | self.sync_content(lang, content) | conditional_block |
_logs.service.ts | <%# | Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the Licen... | Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
| random_line_split |
_logs.service.ts | <%#
Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ma... | {
constructor(private http: Http) { }
changeLevel(log: Log): Observable<Response> {
return this.http.put(SERVER_API_URL + 'management/logs', log);
}
findAll(): Observable<Log[]> {
return this.http.get(SERVER_API_URL + 'management/logs').map((res: Response) => res.json());
}
}
| LogsService | identifier_name |
_logs.service.ts | <%#
Copyright 2013-2018 the original author or authors from the JHipster project.
This file is part of the JHipster project, see http://www.jhipster.tech/
for more information.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You ma... |
findAll(): Observable<Log[]> {
return this.http.get(SERVER_API_URL + 'management/logs').map((res: Response) => res.json());
}
}
| {
return this.http.put(SERVER_API_URL + 'management/logs', log);
} | identifier_body |
wineryDuplicateValidator.directive.ts | /**
* Copyright (c) 2017 University of Stuttgart.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and the Apache License 2.0 which both accompany this distribution,
* and are available at http://www.eclipse.org/legal/epl-v... | else {
no = compareObject.list.find(item => item[compareObject.property] === name);
}
return no ? {'wineryDuplicateValidator': {name}} : null;
};
}
}
@Directive({
selector: '[wineryDuplicateValidator]',
providers: [{provide: NG_VALIDATORS, useExisting: Winer... | {
no = compareObject.list.find(item => item === name);
} | conditional_block |
wineryDuplicateValidator.directive.ts | /**
* Copyright (c) 2017 University of Stuttgart.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and the Apache License 2.0 which both accompany this distribution,
* and are available at http://www.eclipse.org/legal/epl-v... |
@Input() wineryDuplicateValidator: WineryValidatorObject;
private valFn = Validators.nullValidator;
ngOnChanges(changes: SimpleChanges): void {
const change = changes['wineryDuplicateValidator'];
if (change && !isNullOrUndefined(this.wineryDuplicateValidator)) {
const val: Win... | providers: [{provide: NG_VALIDATORS, useExisting: WineryDuplicateValidatorDirective, multi: true}]
})
export class WineryDuplicateValidatorDirective implements Validator, OnChanges { | random_line_split |
wineryDuplicateValidator.directive.ts | /**
* Copyright (c) 2017 University of Stuttgart.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and the Apache License 2.0 which both accompany this distribution,
* and are available at http://www.eclipse.org/legal/epl-v... |
}
| {
return this.valFn(control);
} | identifier_body |
wineryDuplicateValidator.directive.ts | /**
* Copyright (c) 2017 University of Stuttgart.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and the Apache License 2.0 which both accompany this distribution,
* and are available at http://www.eclipse.org/legal/epl-v... | (changes: SimpleChanges): void {
const change = changes['wineryDuplicateValidator'];
if (change && !isNullOrUndefined(this.wineryDuplicateValidator)) {
const val: WineryValidatorObject = change.currentValue;
this.valFn = this.wineryDuplicateValidator.validate(val);
} else... | ngOnChanges | identifier_name |
lightbot.js | var keypress = require("keypress");
// var Spark = require("spark-io");
var Spark = require("../");
var five = require("johnny-five");
var Sumobot = require("sumobot")(five);
keypress(process.stdin);
var board = new five.Board({
io: new Spark({
token: process.env.SPARK_TOKEN,
deviceId: process.env.SPARK_DEV... | else {
bot.rev();
}
});
// Ensure the bot is stopped
bot.stop();
});
| {
bot.fwd();
} | conditional_block |
lightbot.js | var keypress = require("keypress");
// var Spark = require("spark-io");
var Spark = require("../");
var five = require("johnny-five");
var Sumobot = require("sumobot")(five);
keypress(process.stdin);
var board = new five.Board({
io: new Spark({
token: process.env.SPARK_TOKEN,
deviceId: process.env.SPARK_DEV... | });
var light = new five.Sensor("A0");
var isQuitting = false;
light.on("change", function() {
if (isQuitting || this.value === null) {
return;
}
if (this.value < 512) {
bot.fwd();
} else {
bot.rev();
}
});
// Ensure the bot is stopped
bot.stop();
}); | var bot = new Sumobot({
left: "D0",
right: "D1",
speed: 0.50 | random_line_split |
req_handler_unary.rs | use crate::error;
use crate::result;
use crate::server::req_handler::ServerRequestStreamHandler;
use crate::server::req_handler::ServerRequestUnaryHandler;
use httpbis::IncreaseInWindow;
use std::marker;
pub(crate) struct RequestHandlerUnaryToStream<M, H>
where
H: ServerRequestUnaryHandler<M>,
M: Send + 'stati... |
}
| {
// TODO: overflow check
self.increase_in_window
.increase_window_auto_above(buffered as u32)?;
Ok(())
} | identifier_body |
req_handler_unary.rs | use crate::error;
use crate::result;
use crate::server::req_handler::ServerRequestStreamHandler;
use crate::server::req_handler::ServerRequestUnaryHandler;
use httpbis::IncreaseInWindow;
use std::marker;
pub(crate) struct RequestHandlerUnaryToStream<M, H>
where
H: ServerRequestUnaryHandler<M>,
M: Send + 'stati... |
self.message = Some(message);
Ok(())
}
fn end_stream(&mut self) -> result::Result<()> {
match self.message.take() {
Some(message) => self.handler.grpc_message(message),
None => Err(error::Error::Other("no message, end of stream")),
}
}
fn buffer... | {
return Err(error::Error::Other("more than one message in a stream"));
} | conditional_block |
req_handler_unary.rs | use crate::error;
use crate::result;
use crate::server::req_handler::ServerRequestStreamHandler;
use crate::server::req_handler::ServerRequestUnaryHandler;
use httpbis::IncreaseInWindow;
use std::marker;
pub(crate) struct | <M, H>
where
H: ServerRequestUnaryHandler<M>,
M: Send + 'static,
{
pub(crate) increase_in_window: IncreaseInWindow,
pub(crate) handler: H,
pub(crate) message: Option<M>,
pub(crate) _marker: marker::PhantomData<M>,
}
impl<M, H> ServerRequestStreamHandler<M> for RequestHandlerUnaryToStream<M, H>
... | RequestHandlerUnaryToStream | identifier_name |
req_handler_unary.rs | use crate::error;
use crate::result;
use crate::server::req_handler::ServerRequestStreamHandler;
use crate::server::req_handler::ServerRequestUnaryHandler;
use httpbis::IncreaseInWindow;
use std::marker;
pub(crate) struct RequestHandlerUnaryToStream<M, H>
where
H: ServerRequestUnaryHandler<M>,
M: Send + 'stati... | fn buffer_processed(&mut self, buffered: usize) -> result::Result<()> {
// TODO: overflow check
self.increase_in_window
.increase_window_auto_above(buffered as u32)?;
Ok(())
}
} | Some(message) => self.handler.grpc_message(message),
None => Err(error::Error::Other("no message, end of stream")),
}
}
| random_line_split |
class-add.tsx | import { connect } from 'react-redux'
import { State} from '../../control/reducers'
import { User, Roles } from '../../control/user'
import * as React from "react";
import {Course, Class} from "../../control/class"
import {DropdownStringInput} from '../utilities/dropdown-string-input'
import {Input} from '../utilities/... |
render() {
if (this.props.user.role === Roles.student || this.props.user.role === Roles.teacher) {
return <div/>
}
return <tr className={"class-add" + (this.state.syllabus?" link":"")} >
<td>
<IntInput value={this.state.section} label=... | {
super(props);
this.state = {
section: undefined,
semester: undefined,
term: "", year: undefined,
teacher: props.user,
CRN: undefined,
days: {sun: false, mon: false, tue: false, thu: false, wed: false, fri: false, sat: false, id... | identifier_body |
class-add.tsx | import { connect } from 'react-redux'
import { State} from '../../control/reducers'
import { User, Roles } from '../../control/user'
import * as React from "react";
import {Course, Class} from "../../control/class"
import {DropdownStringInput} from '../utilities/dropdown-string-input'
import {Input} from '../utilities/... | user: User,
course: Course
}
export const ClassAdd = connect( (state: State) => ({user: state.user}))
(class extends React.Component<ClassAdd, {}> {
state: Class;
constructor(props: ClassAdd) {
super(props);
this.state = {
section: undefined,
semester: undefined... |
import {DepartmentDropdown} from '../department-dropdown'
import {WeekView} from "../utilities/week-view"
export interface ClassAdd { | random_line_split |
class-add.tsx | import { connect } from 'react-redux'
import { State} from '../../control/reducers'
import { User, Roles } from '../../control/user'
import * as React from "react";
import {Course, Class} from "../../control/class"
import {DropdownStringInput} from '../utilities/dropdown-string-input'
import {Input} from '../utilities/... | (props: ClassAdd) {
super(props);
this.state = {
section: undefined,
semester: undefined,
term: "", year: undefined,
teacher: props.user,
CRN: undefined,
days: {sun: false, mon: false, tue: false, thu: false, wed: false, fri: fal... | constructor | identifier_name |
class-add.tsx | import { connect } from 'react-redux'
import { State} from '../../control/reducers'
import { User, Roles } from '../../control/user'
import * as React from "react";
import {Course, Class} from "../../control/class"
import {DropdownStringInput} from '../utilities/dropdown-string-input'
import {Input} from '../utilities/... |
return <tr className={"class-add" + (this.state.syllabus?" link":"")} >
<td>
<IntInput value={this.state.section} label="section" onChange={v => this.setState({section: v})} />
</td>
<td>
{this.state.ter... | {
return <div/>
} | conditional_block |
mkfs.py | fs
def mkfs(options, compression_methods=None, hash_functions=None):
| _fuse.setOption("gc_vacuum_enabled", False)
_fuse.setOption("gc_enabled", False)
_fuse.operations.init()
_fuse.operations.destroy()
except Exception:
import traceback
print(traceback.format_exc())
ret = -1
if ops:
ops.getManager().... | from dedupsqlfs.fuse.dedupfs import DedupFS
from dedupsqlfs.fuse.operations import DedupOperations
ops = None
ret = 0
try:
ops = DedupOperations()
_fuse = DedupFS(
ops, None,
options,
fsname="dedupsqlfs", allow_root=True)
if not _fuse.checkI... | identifier_body |
mkfs.py | fs
def | (options, compression_methods=None, hash_functions=None):
from dedupsqlfs.fuse.dedupfs import DedupFS
from dedupsqlfs.fuse.operations import DedupOperations
ops = None
ret = 0
try:
ops = DedupOperations()
_fuse = DedupFS(
ops, None,
options,
fsna... | mkfs | identifier_name |
mkfs.py | :
import traceback
print(traceback.format_exc())
ret = -1
if ops:
ops.getManager().close()
return ret
def main(): # {{{1
"""
This function enables using mkfs.dedupsqlfs.py as a shell script that creates FUSE
mount points. Execute "mkfs.dedupsqlfs -h" for a list of v... | profile = '.dedupsqlfs.cprofile-%i' % time()
profiler = cProfile.Profile() | random_line_split | |
mkfs.py | logger.addHandler(logging.StreamHandler(sys.stderr))
parser = argparse.ArgumentParser(
prog="%s/%s mkfs/%s python/%s" % (dedupsqlfs.__name__, dedupsqlfs.__version__, dedupsqlfs.__fsversion__, sys.version.split()[0]),
conflict_handler="resolve")
# Register some custom command line options with... | result = mkfs(args, compression_methods, hash_functions) | conditional_block | |
gonzo.py | # GONZO: A PYTHON SCRIPT TO RECORD PHP ERRORS INTO MONGO
# Michael Vendivel - vendivel@gmail.com
import subprocess
import datetime
from pymongo import MongoClient
# where's the log file
filename = '/path/to/php/logs.log'
# set up mongo client
client = MongoClient('mongo.server.address', 27017)
# which DB
db = clien... | line = f.stdout.readline()
# compose the document to be inserted
post = {"line": line,
"created": datetime.datetime.utcnow()
}
# insert the document into the Collection
post_id = php_logs.insert(post)
# output the line for visual debugging (optional)
print line | conditional_block | |
gonzo.py | # GONZO: A PYTHON SCRIPT TO RECORD PHP ERRORS INTO MONGO
# Michael Vendivel - vendivel@gmail.com
import subprocess
import datetime
from pymongo import MongoClient
# where's the log file
filename = '/path/to/php/logs.log'
# set up mongo client
client = MongoClient('mongo.server.address', 27017)
# which DB
db = clien... | # read line by line
line = f.stdout.readline()
# compose the document to be inserted
post = {"line": line,
"created": datetime.datetime.utcnow()
}
# insert the document into the Collection
post_id = php_logs.insert(post)
# output the line for visual debugging (optional)
print line | random_line_split | |
storage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::StorageBinding;
use dom::bindings::codegen::Bindings::StorageBinding::Storag... | new_value: Option<DOMString>) -> StorageEventRunnable {
StorageEventRunnable { element: storage, key: key, old_value: old_value, new_value: new_value }
}
}
impl MainThreadRunnable for StorageEventRunnable {
fn handler(self: Box<StorageEventRunnable>, script_task: &ScriptTask) {
let t... |
impl StorageEventRunnable {
fn new(storage: Trusted<Storage>, key: Option<DOMString>, old_value: Option<DOMString>, | random_line_split |
storage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::StorageBinding;
use dom::bindings::codegen::Bindings::StorageBinding::Storag... |
fn Key(self, index: u32) -> Option<DOMString> {
let (sender, receiver) = channel();
self.get_storage_task().send(StorageTaskMsg::Key(sender, self.get_url(), self.storage_type, index)).unwrap();
receiver.recv().unwrap()
}
fn GetItem(self, name: DOMString) -> Option<DOMString> {
... | {
let (sender, receiver) = channel();
self.get_storage_task().send(StorageTaskMsg::Length(sender, self.get_url(), self.storage_type)).unwrap();
receiver.recv().unwrap() as u32
} | identifier_body |
storage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::StorageBinding;
use dom::bindings::codegen::Bindings::StorageBinding::Storag... | (global: &GlobalRef, storage_type: StorageType) -> Temporary<Storage> {
reflect_dom_object(box Storage::new_inherited(global, storage_type), *global, StorageBinding::Wrap)
}
fn get_url(&self) -> Url {
let global_root = self.global.root();
let global_ref = global_root.r();
global... | new | identifier_name |
storage.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::StorageBinding;
use dom::bindings::codegen::Bindings::StorageBinding::Storag... |
}
}
}
| {
let target: JSRef<EventTarget> = EventTargetCast::from_ref(it_window);
event.fire(target);
} | conditional_block |
color.rs | // Copyright (c) 2015-2019 William (B.J.) Snow Orvis
//
// 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 applicab... | (pub [u8; 4]);
/// Black for use with `graphics`' functions
pub const BLACK_F32: ColorF32 = ColorF32([0.0, 0.0, 0.0, 1.0]);
/// Grey for use with `graphics`' functions
pub const GREY_F32: ColorF32 = ColorF32([0.5, 0.5, 0.5, 1.0]);
/// White for use with `graphics`' functions
pub const WHITE_F32: ColorF32 = ColorF32([1... | ColorU8 | identifier_name |
color.rs | // Copyright (c) 2015-2019 William (B.J.) Snow Orvis
//
// 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 applicab... | ///
/// ```
/// use fractal_lib::color::{ColorU8, color_range_linear};
/// use std::cmp::min;
///
/// let black = ColorU8([0,0,0,255]);
/// let white = ColorU8([255,255,255,255]);
/// let gradient_count = 128;
/// let range = color_range_linear(black, white, gradient_count);
///
/// assert_eq!(range[min(gradient_count-... | /// error: | random_line_split |
color.rs | // Copyright (c) 2015-2019 William (B.J.) Snow Orvis
//
// 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 applicab... |
let deltas = [
(f32::from(last.0[0]) - f32::from(first.0[0])) / f32::from((count as u16) - 1),
(f32::from(last.0[1]) - f32::from(first.0[1])) / f32::from((count as u16) - 1),
(f32::from(last.0[2]) - f32::from(first.0[2])) / f32::from((count as u16) - 1),
(f32::from(last.0[3]) - f32:... | {
panic!("Count must be 2 or more: {}", count);
} | conditional_block |
dumpAST-baselining.ts | rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, ... | function deleteExistingBaselineFiles() {
var outputPath = getOutputPath();
// Might need to create this
IO.createDirectory(outputPath);
// Delete any old reports from the local path
var localFiles = IO.dir(outputPath);
for (var i = 0; i < localFiles.length; ... | var inputPath = getInputPath();
return IO.dir(inputPath, null, { recursive: true });
}
| identifier_body |
dumpAST-baselining.ts | rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, ... | var script = typescriptLS.parseSourceText(fileName, sourceText);
// Dump source text (as JS comments)
var indentStr = " ";
var text = "{\r\n";
text += indentStr;
text += addKey("sourceText");
text += ": [\r\n";
for (var i = 1; i < script.location... | function createDumpContentForFile(typescriptLS: Harness.TypeScriptLS, fileName: string): string {
var sourceText = new TypeScript.StringSourceText(IO.readFile(fileName))
| random_line_split |
dumpAST-baselining.ts | reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, softwar... | eName: string): string {
fileName = switchToForwardSlashes(fileName);
var nameIndex = fileName.lastIndexOf("/") + 1;
return getOutputPath() + "/" + fileName.substring(nameIndex) + ".json";
}
var addKey = function (key: string): string {
return JSON2.stringify(key);
}... | aselineFileName(fil | identifier_name |
dumpAST-baselining.ts | rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, ... | var start = script.locationInfo.lineMap[i];
var end = (i < script.locationInfo.lineMap.length - 1 ? script.locationInfo.lineMap[i + 1] : sourceText.getLength());
text += indentStr + indentStr + JSON2.stringify(sourceText.getText(start, end));
}
text += "],";
... | text += ",\r\n";
}
| conditional_block |
txtPipe.ts | import * as fs from "fs-extra";
import { IPipe, IPipeItems } from "../interfaces";
export interface ITxtPipeOpts {
name: string;
path: string;
items: IPipeItems;
}
class TxtPipe {
public name: string;
public items: IPipeItems;
private stream: fs.WriteStream;
private isFirst: boolean;
constructor(opts:... | this.stream.end();
}
}
export default function txtPipe(opts: ITxtPipeOpts): IPipe {
return new TxtPipe(opts);
}
| "";
if (this.isFirst) {
this.isFirst = false;
const headers = (Array.isArray(this.items)) ? this.items : Object.keys(this.items);
chunk += headers.reduce((str, c) => `${str}\t${c}`) + "\n";
}
chunk += data.reduce((str, c) => `${str}\t${c}`) + "\n";
this.stream.write(chunk);
}
publi... | identifier_body |
txtPipe.ts | import * as fs from "fs-extra";
import { IPipe, IPipeItems } from "../interfaces";
export interface ITxtPipeOpts {
name: string;
path: string;
items: IPipeItems;
}
class TxtPipe {
public name: string;
public items: IPipeItems;
private stream: fs.WriteStream;
private isFirst: boolean;
constructor(opts:... | .reduce((str, c) => `${str}\t${c}`) + "\n";
this.stream.write(chunk);
}
public end() {
this.stream.end();
}
}
export default function txtPipe(opts: ITxtPipeOpts): IPipe {
return new TxtPipe(opts);
}
| st = false;
const headers = (Array.isArray(this.items)) ? this.items : Object.keys(this.items);
chunk += headers.reduce((str, c) => `${str}\t${c}`) + "\n";
}
chunk += data | conditional_block |
txtPipe.ts | import * as fs from "fs-extra";
import { IPipe, IPipeItems } from "../interfaces";
export interface ITxtPipeOpts {
name: string;
path: string;
items: IPipeItems;
}
class | {
public name: string;
public items: IPipeItems;
private stream: fs.WriteStream;
private isFirst: boolean;
constructor(opts: ITxtPipeOpts) {
this.name = opts.name;
this.items = opts.items;
this.stream = fs.createWriteStream(opts.path);
this.isFirst = true;
}
/**
* 根据表头写入新数据
* @param... | TxtPipe | identifier_name |
txtPipe.ts | import * as fs from "fs-extra";
import { IPipe, IPipeItems } from "../interfaces"; | name: string;
path: string;
items: IPipeItems;
}
class TxtPipe {
public name: string;
public items: IPipeItems;
private stream: fs.WriteStream;
private isFirst: boolean;
constructor(opts: ITxtPipeOpts) {
this.name = opts.name;
this.items = opts.items;
this.stream = fs.createWriteStream(opts... |
export interface ITxtPipeOpts { | random_line_split |
data.ioos.us-pycsw.py | # coding: utf-8
# # Query `apiso:ServiceType`
# In[43]:
from owslib.csw import CatalogueServiceWeb
from owslib import fes
import numpy as np
# The GetCaps request for these services looks like this:
# http://catalog.data.gov/csw-all/csw?SERVICE=CSW&VERSION=2.0.2&REQUEST=GetCapabilities
# In[56]:
endpoint = ... | escapeChar='\\',wildCard='*',singleChar='?')
filter_list = [fes.And([filter1, filter2, filter3])]
csw.getrecords2(constraints=filter_list, maxrecords=1000)
# In[51]:
print(len(csw.records.keys()))
for rec in list(csw.records.keys()):
print('title:'+csw.records[rec].title)
print('iden... |
# In[50]:
val = 'OPeNDAP'
filter3 = fes.PropertyIsLike(propertyname='apiso:ServiceType',literal=('*%s*' % val), | random_line_split |
data.ioos.us-pycsw.py |
# coding: utf-8
# # Query `apiso:ServiceType`
# In[43]:
from owslib.csw import CatalogueServiceWeb
from owslib import fes
import numpy as np
# The GetCaps request for these services looks like this:
# http://catalog.data.gov/csw-all/csw?SERVICE=CSW&VERSION=2.0.2&REQUEST=GetCapabilities
# In[56]:
endpoint =... |
# Now let's print out the references (service endpoints) to see what types of services are available
# In[48]:
choice=np.random.choice(list(csw.records.keys()))
print(csw.records[choice].title)
csw.records[choice].references
# In[49]:
csw.records[choice].xml
# We see that the `OPeNDAP` service is available, ... | print csw.records[rec].title | conditional_block |
test_auto_ApplyTOPUP.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..epi import ApplyTOPUP
def test_ApplyTOPUP_inputs():
input_map = dict(args=dict(argstr='%s',
),
datatype=dict(argstr='-d=%s',
),
encoding_file=dict(argstr='--datain=%s',
mandatory=True,
),
... | def test_ApplyTOPUP_outputs():
output_map = dict(out_corrected=dict(),
)
outputs = ApplyTOPUP.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value | random_line_split | |
test_auto_ApplyTOPUP.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..epi import ApplyTOPUP
def test_ApplyTOPUP_inputs():
input_map = dict(args=dict(argstr='%s',
),
datatype=dict(argstr='-d=%s',
),
encoding_file=dict(argstr='--datain=%s',
mandatory=True,
),
... |
def test_ApplyTOPUP_outputs():
output_map = dict(out_corrected=dict(),
)
outputs = ApplyTOPUP.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(outputs.traits()[key], metakey) == value
| for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value | conditional_block |
test_auto_ApplyTOPUP.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..epi import ApplyTOPUP
def test_ApplyTOPUP_inputs():
| in_topup_fieldcoef=dict(argstr='--topup=%s',
copyfile=False,
requires=['in_topup_movpar'],
),
in_topup_movpar=dict(copyfile=False,
requires=['in_topup_fieldcoef'],
),
interp=dict(argstr='--interp=%s',
),
method=dict(argstr='--method=%s',
),
out_corrected=dict(argstr='--ou... | input_map = dict(args=dict(argstr='%s',
),
datatype=dict(argstr='-d=%s',
),
encoding_file=dict(argstr='--datain=%s',
mandatory=True,
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
in_files=dict(argstr='--imain=%... | identifier_body |
test_auto_ApplyTOPUP.py | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..epi import ApplyTOPUP
def | ():
input_map = dict(args=dict(argstr='%s',
),
datatype=dict(argstr='-d=%s',
),
encoding_file=dict(argstr='--datain=%s',
mandatory=True,
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
in_files=dict(argstr='-... | test_ApplyTOPUP_inputs | identifier_name |
preprocess_trace.py | #! /usr/bin/env python
# Copyright (c) 2014 Quanta Research Cambridge, Inc
# Original author John Ankcorn
#
# 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 with... | lastch = ch
line = line[:ind] + 'printfInd.' + freplace + '(' + ','.join(pactual) + ');\n'
pformal = ''
pactual = ''
pbsv = ''
pcount = 1
for item in plist:
if pcount > 1:
... | freplace = freplace + '__'
elif (ch >= 'A' and ch <= 'Z') or (ch >= 'a' and ch <= 'z') or (ch >= '0' and ch <= '9'):
freplace = freplace + ch
else:
freplace = freplace + '_' + '{:02x}'.format(ord(ch)) | random_line_split |
preprocess_trace.py | #! /usr/bin/env python
# Copyright (c) 2014 Quanta Research Cambridge, Inc
# Original author John Ankcorn
#
# 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 with... |
else:
formatstr = formatstr + ch
elif ch == ',':
if pitem != '':
pactual.append(pitem.strip())
pitem = ''
else:
pitem = pitem +... | informat = False | conditional_block |
inline-nested.tsx | /** @jsx jsx */
import { Editor } from 'slate'
import { jsx } from '../../../..'
export const input = (
<editor>
<block>
one
<inline>
two<inline>three</inline>four
</inline>
five
</block>
</editor>
)
export const test = editor => { | }
export const output = [
[input, []],
[
<block>
one
<inline>
two<inline>three</inline>four
</inline>
five
</block>,
[0],
],
[<text>one</text>, [0, 0]],
[
<inline>
two<inline>three</inline>four
</inline>,
[0, 1],
],
[<text>two</text>, [0, 1, 0]... | return Array.from(Editor.nodes(editor, { at: [] })) | random_line_split |
or-patterns-syntactic-fail.rs | // Test some cases where or-patterns may ostensibly be allowed but are in fact not.
// This is not a semantic test. We only test parsing.
fn | () {}
enum E { A, B }
use E::*;
fn no_top_level_or_patterns() {
// We do *not* allow or-patterns at the top level of lambdas...
let _ = |A | B: E| (); //~ ERROR no implementation for `E | ()`
// -------- This looks like an or-pattern but is in fact `|A| (B: E | ())`.
// ...and for now neith... | main | identifier_name |
or-patterns-syntactic-fail.rs | // Test some cases where or-patterns may ostensibly be allowed but are in fact not.
// This is not a semantic test. We only test parsing.
fn main() {}
enum E { A, B }
use E::*;
fn no_top_level_or_patterns() {
// We do *not* allow or-patterns at the top level of lambdas...
let _ = |A | B: E| (); //~ ERROR no ... |
//~^ ERROR top-level or-patterns are not allowed
fn fun2(| A | B: E) {}
//~^ ERROR top-level or-patterns are not allowed
// We don't allow top-level or-patterns before type annotation in let-statements because we
// want to reserve this syntactic space for possible future type ascription.
let... | {} | identifier_body |
or-patterns-syntactic-fail.rs | // Test some cases where or-patterns may ostensibly be allowed but are in fact not.
// This is not a semantic test. We only test parsing.
fn main() {}
enum E { A, B } | // We do *not* allow or-patterns at the top level of lambdas...
let _ = |A | B: E| (); //~ ERROR no implementation for `E | ()`
// -------- This looks like an or-pattern but is in fact `|A| (B: E | ())`.
// ...and for now neither do we allow or-patterns at the top level of functions.
fn f... | use E::*;
fn no_top_level_or_patterns() { | random_line_split |
array_slice.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 may... | )
.collect();
Arc::new(array)
}
fn array_slice_benchmark(c: &mut Criterion) {
let array = create_array_with_nulls(4096);
c.bench_function("array_slice 128", |b| {
b.iter(|| create_array_slice(&array, 128))
});
c.bench_function("array_slice 512", |b| {
b.iter(|| create_array_... | { None } | conditional_block |
array_slice.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 may... | });
c.bench_function("array_slice 2048", |b| {
b.iter(|| create_array_slice(&array, 2048))
});
}
criterion_group!(benches, array_slice_benchmark);
criterion_main!(benches); | b.iter(|| create_array_slice(&array, 512)) | random_line_split |
array_slice.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 may... |
fn create_array_with_nulls(size: usize) -> ArrayRef {
let array: Float64Array = (0..size)
.map(|i| if i % 2 == 0 { Some(1.0) } else { None })
.collect();
Arc::new(array)
}
fn array_slice_benchmark(c: &mut Criterion) {
let array = create_array_with_nulls(4096);
c.bench_function("array_... | {
array.slice(0, length)
} | identifier_body |
array_slice.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 may... | (c: &mut Criterion) {
let array = create_array_with_nulls(4096);
c.bench_function("array_slice 128", |b| {
b.iter(|| create_array_slice(&array, 128))
});
c.bench_function("array_slice 512", |b| {
b.iter(|| create_array_slice(&array, 512))
});
c.bench_function("array_slice 2048", ... | array_slice_benchmark | identifier_name |
vscode-vim.d.ts | interface IEditor {
// Status
CloseCommandStatus();
ShowCommandStatus(text: string);
ShowModeStatus(mode: Mode);
SetModeStatusVisibility(visible: boolean);
// Edit
InsertTextAtCurrentPosition(text: string);
Insert(position: IPosition, text: string);
DeleteRange(range: IRang... |
interface IVimStyle {
Register: IRegister;
PushKey(key: Key): void;
PushEscKey(): void;
ApplyInsertMode(): void;
}
declare const enum Key {
a,
b,
c,
d,
e,
f,
g,
h,
i,
j,
k,
l,
m,
n,
o,
p,
q,
r,
s,
t,
u,
v,
w,
... | SetCount(count: number);
CalculateEnd(editor: IEditor, start: IPosition): IPosition;
} | random_line_split |
urls.py | from cl.api import views
from cl.audio import api_views as audio_views
from cl.people_db import api_views as judge_views
from cl.search import api_views as search_views
from django.conf.urls import url, include | router.register(r'dockets', search_views.DocketViewSet)
router.register(r'courts', search_views.CourtViewSet)
router.register(r'audio', audio_views.AudioViewSet)
router.register(r'clusters', search_views.OpinionClusterViewSet)
router.register(r'opinions', search_views.OpinionViewSet)
router.register(r'opinions-cited', ... | from rest_framework.routers import DefaultRouter
router = DefaultRouter()
# Search & Audio | random_line_split |
sha256_bench.rs | #![cfg_attr(all(feature = "nightly", test), feature(test))]
#![cfg(all(feature = "nightly", test))]
extern crate test;
extern crate cxema;
#[cfg(test)]
use cxema::sha2::{Sha256};
use cxema::digest::Digest;
use test::Bencher;
#[bench]
pub fn sha256_10(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes... | (bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 1024];
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_64k(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 65536];
bh.iter(|| {
sh.input(&byt... | sha256_1k | identifier_name |
sha256_bench.rs | #![cfg_attr(all(feature = "nightly", test), feature(test))]
#![cfg(all(feature = "nightly", test))]
extern crate test;
extern crate cxema;
#[cfg(test)]
use cxema::sha2::{Sha256};
use cxema::digest::Digest;
use test::Bencher;
#[bench]
pub fn sha256_10(bh: &mut Bencher) {
let mut sh = Sha256::new(); |
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_1k(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 1024];
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_64k(bh: &m... | let bytes = [1u8; 10]; | random_line_split |
sha256_bench.rs | #![cfg_attr(all(feature = "nightly", test), feature(test))]
#![cfg(all(feature = "nightly", test))]
extern crate test;
extern crate cxema;
#[cfg(test)]
use cxema::sha2::{Sha256};
use cxema::digest::Digest;
use test::Bencher;
#[bench]
pub fn sha256_10(bh: &mut Bencher) {
let mut sh = Sha256::new();
let bytes... | {
let mut sh = Sha256::new();
let bytes = [1u8; 65536];
bh.iter(|| {
sh.input(&bytes);
});
bh.bytes = bytes.len() as u64;
} | identifier_body | |
ngx-admin-lte.module.ts | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { ToastrModule, ToastrService } from 'ngx-toastr';
// import ngx-translate and the http loader
import {TranslateLoader, TranslateModule} from '@ngx-translate/core... |
// Pipes
import { SafeHtmlPipe } from './pipes/safe-html.pipes';
// Widgets
import { AppHeaderComponent } from './widgets/app-header/app-header.component';
import { LogoComponent } from './widgets/logo/logo.component';
import { AppFooterComponent } from './widgets/app-footer/app-footer.component';
import { MenuAside... | {
return new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json');
} | identifier_body |
ngx-admin-lte.module.ts | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { ToastrModule, ToastrService } from 'ngx-toastr';
// import ngx-translate and the http loader
import {TranslateLoader, TranslateModule} from '@ngx-translate/core... | CanActivateGuard,
NotificationsService,
TranslateService,
LoggerService,
ControlSidebarService,
ToastrService
]
})
export class NgxAdminLteModule { } | FooterService,
BreadcrumbService,
MessagesService, | random_line_split |
ngx-admin-lte.module.ts | import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { ToastrModule, ToastrService } from 'ngx-toastr';
// import ngx-translate and the http loader
import {TranslateLoader, TranslateModule} from '@ngx-translate/core... | (httpClient) {
return new TranslateHttpLoader(httpClient, 'assets/i18n/', '.json');
}
// Pipes
import { SafeHtmlPipe } from './pipes/safe-html.pipes';
// Widgets
import { AppHeaderComponent } from './widgets/app-header/app-header.component';
import { LogoComponent } from './widgets/logo/logo.component';
import { A... | HttpLoaderFactory | identifier_name |
webpack.config.js | const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
styles: './content/styles/app.scss',
image: './content/images/awesome.jpg',
... | jQuery: "jquery",
tether: 'tether',
Tether: 'tether',
'window.Tether': 'tether',
'Popper': 'popper.js'
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks: Infinity,
// (with more entries,... | $: "jquery",
jquery: "jquery",
"window.jQuery": "jquery", | random_line_split |
Tracker.ts | import { Queue } from "../Queue/Queue";
import { EventHandler } from "../Event/Handler/EventHandler";
import { ObjectMerger } from "../Common/ObjectMerger";
export class Tracker {
public static get SEND_COMMAND(): string { return "send"; }
constructor(private global: any, private eventHandler: EventHandler, p... |
public run() {
if (this.global !== undefined) {
let dataLayerCallback = this.global;
let queue = dataLayerCallback.q;
let push = dataLayerCallback.q.push;
this.process(new Queue(queue));
queue.push = (...dataLayerElements) => {
... | {} | identifier_body |
Tracker.ts | import { Queue } from "../Queue/Queue";
import { EventHandler } from "../Event/Handler/EventHandler";
import { ObjectMerger } from "../Common/ObjectMerger";
export class Tracker {
public static get SEND_COMMAND(): string { return "send"; }
constructor(private global: any, private eventHandler: EventHandler, p... |
}
private process(queue: Queue) {
let dataLayerElementPayload: any = {};
queue.consume((index, dataLayerElement) => {
if (dataLayerElement.length >= 2) {
dataLayerElementPayload = this.objectMerger.merge(dataLayerElementPayload, dataLayerElement[1]);
... | {
let dataLayerCallback = this.global;
let queue = dataLayerCallback.q;
let push = dataLayerCallback.q.push;
this.process(new Queue(queue));
queue.push = (...dataLayerElements) => {
push.apply(queue, Array.prototype.slice.call(dataLayerElemen... | conditional_block |
Tracker.ts | import { Queue } from "../Queue/Queue";
import { EventHandler } from "../Event/Handler/EventHandler";
import { ObjectMerger } from "../Common/ObjectMerger";
export class Tracker {
public static get SEND_COMMAND(): string { return "send"; }
constructor(private global: any, private eventHandler: EventHandler, p... | () {
if (this.global !== undefined) {
let dataLayerCallback = this.global;
let queue = dataLayerCallback.q;
let push = dataLayerCallback.q.push;
this.process(new Queue(queue));
queue.push = (...dataLayerElements) => {
push.apply(queu... | run | identifier_name |
Tracker.ts | import { Queue } from "../Queue/Queue";
import { EventHandler } from "../Event/Handler/EventHandler";
import { ObjectMerger } from "../Common/ObjectMerger";
export class Tracker { | public static get SEND_COMMAND(): string { return "send"; }
constructor(private global: any, private eventHandler: EventHandler, private objectMerger: ObjectMerger) {}
public run() {
if (this.global !== undefined) {
let dataLayerCallback = this.global;
let queue = dataLaye... | random_line_split | |
require-sri-for.js | "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var config_1 = __importDefault(require("../../config"));
var is_function_1 = __importDefault(require("../../is-function"));
module.exports = function requireSriForChec... | });
}; | throw new Error("\"" + expression + "\" is not a valid " + key + " value. Remove it.");
} | random_line_split |
require-sri-for.js | "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var config_1 = __importDefault(require("../../config"));
var is_function_1 = __importDefault(require("../../is-function"));
module.exports = function requireSriForChec... |
if (value.length === 0) {
throw new Error(key + " must have at least one value. To require nothing, omit the directive.");
}
value.forEach(function (expression) {
if (is_function_1.default(expression)) {
return;
}
if (config_1.default.requireSriForValues.indexOf(... | {
throw new Error("\"" + value + "\" is not a valid value for " + key + ". Use an array of strings.");
} | conditional_block |
RadioButton-test.js | import React from 'react';
import RadioButton from '../RadioButton';
import { mount } from 'enzyme';
const render = (props) => mount(
<RadioButton
{...props}
className="extra-class"
name="test-name"
value="test-value"
/>
);
describe('RadioButton', () => {
describe('renders as expected', () => {
... | const inputElement = input.get(0);
inputElement.checked = true;
wrapper.find('input').simulate('change');
const call = onChange.mock.calls[0];
expect(call[0]).toEqual('test-value');
expect(call[1]).toEqual('test-name');
expect(call[2].target).toBe(inputElement);
});
})... | random_line_split | |
append.ts | 'use strict';
var append: {
(parentNode: HTMLElement, node: any, position?: string): HTMLElement;
create: (node: string) => HTMLElement;
remove: (node: HTMLElement) => void;
toIndex: (parentNode: HTMLElement, node: HTMLElement, index: number) => HTMLElement;
};
append = (() => {
var append: any = function(parentN... |
parentNode.insertAdjacentElement(position || 'beforeEnd', node);
return node;
};
if (!window.document.body || !window.document.body.insertAdjacentElement) {
append = function(parentNode: HTMLElement, node: any, position: string) {
if (typeof(node) === 'string') {
node = parentNode.ownerDocument.createEl... | {
node = parentNode.ownerDocument.createElement(node);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.