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 |
|---|---|---|---|---|
kendo.culture.ru-UA.js | /**
* Copyright <%= year %> Telerik AD
*
* 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 agr... | calendars: {
standard: {
days: {
names: ["воскресенье","понедельник","вторник","среда","четверг","пятница","суббота"],
namesAbbr: ["Вс","Пн","Вт","Ср","Чт","Пт","Сб"],
namesShort: ["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]
... | }, | random_line_split |
modal-scroll-example.ts | import { Component, ViewChild } from '@angular/core';
import { McButton } from '@ptsecurity/mosaic/button';
import { McModalService, ModalSize } from '@ptsecurity/mosaic/modal';
@Component({
selector: 'mc-long-component',
template: `
<p *ngFor="let item of longText">{{ item }}</p>
`
})
export clas... |
}
/**
* @title Component Modal Scroll
*/
@Component({
selector: 'modal-scroll-example',
template: `<button #modalButton mc-button (click)="createLongModal()">Open Modal</button>`,
styleUrls: ['modal-scroll-example.css']
})
export class ModalScrollExample {
@ViewChild('modalButton') modalButton: McB... | {
// tslint:disable-next-line:no-magic-numbers
for (let i = 0; i < 50; i++) {
this.longText.push(`text lint - ${i}`);
}
} | identifier_body |
modal-scroll-example.ts | import { Component, ViewChild } from '@angular/core';
import { McButton } from '@ptsecurity/mosaic/button';
import { McModalService, ModalSize } from '@ptsecurity/mosaic/modal';
@Component({
selector: 'mc-long-component',
template: `
<p *ngFor="let item of longText">{{ item }}</p>
`
})
export clas... |
}
}
/**
* @title Component Modal Scroll
*/
@Component({
selector: 'modal-scroll-example',
template: `<button #modalButton mc-button (click)="createLongModal()">Open Modal</button>`,
styleUrls: ['modal-scroll-example.css']
})
export class ModalScrollExample {
@ViewChild('modalButton') modalButto... | {
this.longText.push(`text lint - ${i}`);
} | conditional_block |
modal-scroll-example.ts | import { Component, ViewChild } from '@angular/core';
import { McButton } from '@ptsecurity/mosaic/button';
import { McModalService, ModalSize } from '@ptsecurity/mosaic/modal';
@Component({
selector: 'mc-long-component',
template: `
<p *ngFor="let item of longText">{{ item }}</p>
`
})
export clas... | })
export class ModalScrollExample {
@ViewChild('modalButton') modalButton: McButton;
constructor(private modalService: McModalService) {}
createLongModal() {
const modalRef = this.modalService.create({
mcSize : ModalSize.Small,
mcTitle : 'Modal Title',
... | selector: 'modal-scroll-example',
template: `<button #modalButton mc-button (click)="createLongModal()">Open Modal</button>`,
styleUrls: ['modal-scroll-example.css'] | random_line_split |
modal-scroll-example.ts | import { Component, ViewChild } from '@angular/core';
import { McButton } from '@ptsecurity/mosaic/button';
import { McModalService, ModalSize } from '@ptsecurity/mosaic/modal';
@Component({
selector: 'mc-long-component',
template: `
<p *ngFor="let item of longText">{{ item }}</p>
`
})
export clas... | () {
const modalRef = this.modalService.create({
mcSize : ModalSize.Small,
mcTitle : 'Modal Title',
mcContent : McLongComponent,
mcOkText : 'Yes',
mcCancelText: 'No'
});
modalRef.afterClose.subscribe(() => this.modalButto... | createLongModal | identifier_name |
index.js | 'use strict';
exports.light = (http) => {
var jfLib = require('johnny-five');
var board = new jfLib.Board();
var sock = require('socket.io')(http);
var mongo = require('./mongoWrapper');
var mongoWrapper = new mongo();
board.on('ready', function() {
var start, end;
var doo... | end = new Date();
if ((end - start) > longLimit) {
doYellow(/*c*/);
setTimeout(() => {
leds.yellow.off();
doGreen(/*c*/);
}, coolDown);
} else {
... | doRed(/*c*/);
} else {
doorOpen = true; | random_line_split |
index.js | 'use strict';
exports.light = (http) => {
var jfLib = require('johnny-five');
var board = new jfLib.Board();
var sock = require('socket.io')(http);
var mongo = require('./mongoWrapper');
var mongoWrapper = new mongo();
board.on('ready', function() {
var start, end;
var doo... | else {
doorOpen = true;
end = new Date();
if ((end - start) > longLimit) {
doYellow(/*c*/);
setTimeout(() => {
leds.yellow.off();
doGreen(/*c*/);
}, coolDown);
... | {
doorOpen = false;
start = new Date();
doRed(/*c*/);
} | conditional_block |
ringsim.py | 56
myhash = md5
# md5: 1520 "uploads" per second
# sha1: 1350 ups
# sha256: 930 ups
from itertools import count
from twisted.python import usage
def abbreviate_space(s, SI=True):
if s is None:
return "unknown"
if SI:
U = 1000.0
isuffix = "B"
else:
U = 1024.0
isuffix ... | s = servers[index]
accepted = s.upload(sharesize)
if not accepted:
server_was_full = True
remaining_servers.discard(s)
if not remaining_servers:
print "-- GRID IS FULL"
ring.dump_usage(filenum, av... | random_line_split | |
ringsim.py | 6
myhash = md5
# md5: 1520 "uploads" per second
# sha1: 1350 ups
# sha256: 930 ups
from itertools import count
from twisted.python import usage
def abbreviate_space(s, SI=True):
if s is None:
return "unknown"
if SI:
U = 1000.0
isuffix = "B"
else:
U = 1024.0
isuffix =... |
if s < 1024: # 1000-1023 get emitted as bytes, even in SI mode
return "%d B" % s
if s < U*U:
return r(s/U, "k")
if s < U*U*U:
return r(s/(U*U), "M")
if s < U*U*U*U:
return r(s/(U*U*U), "G")
if s < U*U*U*U*U:
return r(s/(U*U*U*U), "T")
return r(s/(U*U*U*U... | return "%.2f %s%s" % (count, suffix, isuffix) | identifier_body |
ringsim.py | 6
myhash = md5
# md5: 1520 "uploads" per second
# sha1: 1350 ups
# sha256: 930 ups
from itertools import count
from twisted.python import usage
def abbreviate_space(s, SI=True):
if s is None:
return "unknown"
if SI:
U = 1000.0
isuffix = "B"
else:
U = 1024.0
isuffix =... |
else:
return "<%s %s>" % (self.__class__.__name__, self.nodeid)
class Ring:
SHOW_MINMAX = False
def __init__(self, numservers, seed, permute):
self.servers = []
for i in range(numservers):
nodeid = myhash(str(seed)+str(i)).hexdigest()
capacity = SERV... | return "<%s %s full at %d>" % (self.__class__.__name__, self.nodeid, self.full_at_tick) | conditional_block |
ringsim.py | 6
myhash = md5
# md5: 1520 "uploads" per second
# sha1: 1350 ups
# sha256: 930 ups
from itertools import count
from twisted.python import usage
def abbreviate_space(s, SI=True):
if s is None:
return "unknown"
if SI:
U = 1000.0
isuffix = "B"
else:
U = 1024.0
isuffix =... | (s):
return myhash(s.nodeid+si).digest()
return sorted(self.servers, key=sortkey)
for i in range(len(self.servers)):
if self.servers[i].nodeid >= si:
return self.servers[i:] + self.servers[:i]
return list(self.servers)
def show_servers(self, p... | sortkey | identifier_name |
extendableevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::Extendable... | (global: GlobalRef,
type_: Atom,
bubbles: bool,
cancelable: bool)
-> Root<ExtendableEvent> {
let ev = reflect_dom_object(box ExtendableEvent::new_inherited(), global, ExtendableEventBinding::Wrap);
{
let event = ev.upcast::<Event>()... | new | identifier_name |
extendableevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::Extendable... | }
// https://dom.spec.whatwg.org/#dom-event-istrusted
pub fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
} | return Err(Error::InvalidState);
}
// Step 2
// TODO add a extended_promises array to enqueue the `val`
Ok(()) | random_line_split |
extendableevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::Extendable... |
// Step 2
// TODO add a extended_promises array to enqueue the `val`
Ok(())
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
pub fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| {
return Err(Error::InvalidState);
} | conditional_block |
extendableevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::Extendable... |
pub fn new(global: GlobalRef,
type_: Atom,
bubbles: bool,
cancelable: bool)
-> Root<ExtendableEvent> {
let ev = reflect_dom_object(box ExtendableEvent::new_inherited(), global, ExtendableEventBinding::Wrap);
{
let event = ev.up... | {
ExtendableEvent {
event: Event::new_inherited(),
extensions_allowed: true
}
} | identifier_body |
gu.js | /*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'docprops', 'gu', {
bgColor: 'બૅકગ્રાઉન્ડ રંગ',
bgFixed: 'સ્ક્રોલ ન થાય તેવું બૅકગ્રાઉન્ડ',
bgImage: 'બૅકગ્રાઉન્ડ ચિત્ર URL',
c... | docTypeOther: 'અન્ય ડૉક્યુમન્ટ પ્રકાર શીર્ષક',
label: 'ડૉક્યુમન્ટ ગુણ/પ્રૉપર્ટિઝ',
margin: 'પેજ માર્જિન',
marginBottom: 'નીચે',
marginLeft: 'ડાબી',
marginRight: 'જમણી',
marginTop: 'ઉપર',
meta: 'મેટાડૅટા',
metaAuthor: 'લેખક',
metaCopyright: 'કૉપિરાઇટ',
metaDescription: 'ડૉક્યુમન્ટ વર્ણન',
metaKeywords: 'ડૉક્... | charsetWE: 'પશ્ચિમ યુરોપિઅન (Western European)',
chooseColor: 'વિકલ્પ',
design: 'ડીસા',
docTitle: 'પેજ મથાળું/ટાઇટલ',
docType: 'ડૉક્યુમન્ટ પ્રકાર શીર્ષક', | random_line_split |
in_process_lease.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext;
use futures::{
channel::oneshot::{channel, Receiver, Sender... |
}
#[async_trait]
impl LeaseOps for InProcessLease {
async fn try_add_put_lease(&self, key: &str) -> Result<bool> {
let key = key.to_string();
let mut in_flight_leases = self.leases.lock().await;
let entry = in_flight_leases.entry(key);
if let Entry::Occupied(_) = entry {
... | {
Self {
leases: Arc::new(Mutex::new(HashMap::new())),
}
} | identifier_body |
in_process_lease.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext;
use futures::{
channel::oneshot::{channel, Receiver, Sender... | async fn try_add_put_lease(&self, key: &str) -> Result<bool> {
let key = key.to_string();
let mut in_flight_leases = self.leases.lock().await;
let entry = in_flight_leases.entry(key);
if let Entry::Occupied(_) = entry {
Ok(false)
} else {
let (send, r... | random_line_split | |
in_process_lease.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext;
use futures::{
channel::oneshot::{channel, Receiver, Sender... |
}
fn renew_lease_until(&self, _ctx: CoreContext, key: &str, done: BoxFuture<'static, ()>) {
let this = self.clone();
let key = key.to_string();
tokio::spawn(async move {
done.await;
this.release_lease(&key).await;
});
}
async fn wait_for_other_l... | {
let (send, recv) = channel();
entry.or_insert((send, recv.shared()));
Ok(true)
} | conditional_block |
in_process_lease.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use anyhow::Result;
use async_trait::async_trait;
use context::CoreContext;
use futures::{
channel::oneshot::{channel, Receiver, Sender... | () -> Self {
Self {
leases: Arc::new(Mutex::new(HashMap::new())),
}
}
}
#[async_trait]
impl LeaseOps for InProcessLease {
async fn try_add_put_lease(&self, key: &str) -> Result<bool> {
let key = key.to_string();
let mut in_flight_leases = self.leases.lock().await;
... | new | identifier_name |
elastic_profiles_widget.tsx | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* 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 agr... |
const actions = [
<IconGroup>
<Icons.Edit data-test-id="edit-elastic-profile"
onclick={vnode.attrs.onEdit}
title={disabledReason}
disabled={isDisabled}/>
<Icons.Clone data-test-id="clone-elastic-profile"
onclick... | {
isDisabled = true;
disabledReason = `You dont have permissions to administer '${vnode.attrs.elasticProfile.id()}' elastic agent profile.`;
} | conditional_block |
elastic_profiles_widget.tsx | * Copyright 2019 ThoughtWorks, Inc.
*
* 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... | /* | random_line_split | |
elastic_profiles_widget.tsx | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* 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 agr... |
view(vnode: m.Vnode<ProfileAttrs, {}>) {
const elasticProfile = vnode.attrs.elasticProfile;
let isDisabled = false, disabledReason;
if (!vnode.attrs.pluginInfo) {
isDisabled = true;
disabledReason = `Could not find plugin with id ${vnode.attrs.elasticProfile.pluginId()}`;
}
if... | {
const title = <div data-test-id="elastic-profile-id"><span>{profileId}</span></div>;
return <KeyValueTitle image={null} title={title}/>;
} | identifier_body |
elastic_profiles_widget.tsx | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* 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 agr... | (profileId: string) {
const title = <div data-test-id="elastic-profile-id"><span>{profileId}</span></div>;
return <KeyValueTitle image={null} title={title}/>;
}
view(vnode: m.Vnode<ProfileAttrs, {}>) {
const elasticProfile = vnode.attrs.elasticProfile;
let isDisabled = false, disabledReason;
... | profileHeader | identifier_name |
test_mimehandler.py | from thug.ThugAPI.ThugAPI import ThugAPI
class TestMIMEHandler(object):
| assert matches >= len(expected)
def test_zip_handler(self, caplog):
expected = ['[Window] Alert Text: Foobar']
self.do_perform_test(caplog, "https://github.com/buffer/thug/raw/master/tests/test_files/test.js.zip", expected)
| def do_perform_test(self, caplog, url, expected, type_ = "remote"):
thug = ThugAPI()
thug.set_useragent('win7ie90')
thug.set_features_logging()
thug.set_ssl_verify()
thug.log_init(url)
m = getattr(thug, "run_{}".format(type_))
m(url)
records = [r.messag... | identifier_body |
test_mimehandler.py | from thug.ThugAPI.ThugAPI import ThugAPI
class | (object):
def do_perform_test(self, caplog, url, expected, type_ = "remote"):
thug = ThugAPI()
thug.set_useragent('win7ie90')
thug.set_features_logging()
thug.set_ssl_verify()
thug.log_init(url)
m = getattr(thug, "run_{}".format(type_))
m(url)
recor... | TestMIMEHandler | identifier_name |
test_mimehandler.py | from thug.ThugAPI.ThugAPI import ThugAPI
class TestMIMEHandler(object):
def do_perform_test(self, caplog, url, expected, type_ = "remote"):
thug = ThugAPI()
thug.set_useragent('win7ie90')
thug.set_features_logging()
thug.set_ssl_verify()
thug.log_init(url)
m = get... |
assert matches >= len(expected)
def test_zip_handler(self, caplog):
expected = ['[Window] Alert Text: Foobar']
self.do_perform_test(caplog, "https://github.com/buffer/thug/raw/master/tests/test_files/test.js.zip", expected)
| matches += 1 | conditional_block |
test_mimehandler.py | from thug.ThugAPI.ThugAPI import ThugAPI
class TestMIMEHandler(object):
def do_perform_test(self, caplog, url, expected, type_ = "remote"):
thug = ThugAPI()
thug.set_useragent('win7ie90')
thug.set_features_logging()
thug.set_ssl_verify() |
m = getattr(thug, "run_{}".format(type_))
m(url)
records = [r.message for r in caplog.records]
matches = 0
for e in expected:
for record in records:
if e in record:
matches += 1
assert matches >= len(expected)
def ... | thug.log_init(url) | random_line_split |
item_26_multiple_inheritance_for_mixin_only.py | import json
from collections import abc
# item 26: use muptiple inheritance for mixin only
# a mixin that transforms a python object to a dictionary that's ready for seralization
class ToDictMixin(object):
def to_dict(self):
"""Return a dictionary representation of this object"""
return self._traver... | (BinaryTreeNode, ToJsonMixin):
pass
class EqualityMixin(object):
def __eq__(self, other):
return self.__dict__ == other.__dict__
class Switch(EqualityMixin):
def __init__(self, ports, speed):
self.ports = ports
self.speed = speed
class Machine(EqualityMixin):
def __init__(se... | BinaryTreeWithJson | identifier_name |
item_26_multiple_inheritance_for_mixin_only.py | import json
from collections import abc
# item 26: use muptiple inheritance for mixin only
# a mixin that transforms a python object to a dictionary that's ready for seralization
class ToDictMixin(object):
def to_dict(self):
"""Return a dictionary representation of this object"""
return self._traver... |
# Mixins can also play together
class ToJsonMixin(object):
@classmethod
def from_json(cls, kwargs):
"""given kwargs in json format, get it into dictionary format"""
kwargs = json.loads(kwargs)
return cls(**kwargs)
def to_json(self):
d = self.to_dict()
return json.... | self.name = name
self.tree = tree | identifier_body |
item_26_multiple_inheritance_for_mixin_only.py | import json
from collections import abc
# item 26: use muptiple inheritance for mixin only
# a mixin that transforms a python object to a dictionary that's ready for seralization
class ToDictMixin(object):
def to_dict(self):
"""Return a dictionary representation of this object"""
return self._traver... |
class BinaryTreeNode(ToDictMixin):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class BinaryTreeWithParent(BinaryTreeNode):
def __init__(self, value, left=None, right=None, parent=None):
super().__init__(value, left, ... | random_line_split | |
item_26_multiple_inheritance_for_mixin_only.py | import json
from collections import abc
# item 26: use muptiple inheritance for mixin only
# a mixin that transforms a python object to a dictionary that's ready for seralization
class ToDictMixin(object):
def to_dict(self):
"""Return a dictionary representation of this object"""
return self._traver... |
return obj
class BinaryTreeNode(ToDictMixin):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class BinaryTreeWithParent(BinaryTreeNode):
def __init__(self, value, left=None, right=None, parent=None):
super().... | return self._traverse(key, obj.__dict__) | conditional_block |
comment.ts | import Crowi from 'server/crowi'
import { Types, Document, Model, Schema, model } from 'mongoose'
import Debug from 'debug'
export interface CommentDocument extends Document {
_id: Types.ObjectId
page: Types.ObjectId | any
creator: Types.ObjectId
revision: Types.ObjectId
comment: string
commentPosition: nu... | await Activity.removeByPageCommentDelete(comment)
} catch (err) {
debug(err)
}
})
const Comment = model<CommentDocument, CommentModel>('Comment', commentSchema)
return Comment
} | random_line_split | |
spinner.js | /*
* Copyright (c) 2014 Jesse van den Kieboom. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list... | this.e.style.backgroundPositionX = (-100 * fx) + '%';
this.e.style.backgroundPositionY = (-100 * fy) + '%';
this.start();
};
module.exports = Spinner;
/* vi:ts=4:et */ | random_line_split | |
spinner.js | /*
* Copyright (c) 2014 Jesse van den Kieboom. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list... |
if (this._animateStart === null) {
this._animateStart = stamp;
}
// In seconds
var elapsed = (stamp - this._animateStart) / 1000.0;
var frame = Math.floor(elapsed / this._framePeriod % this._settings.nframes);
// Skip first frame, which is empty
frame += 1;
var fx = Math.flo... | {
this.cancel();
return;
} | conditional_block |
spinner.js | /*
* Copyright (c) 2014 Jesse van den Kieboom. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list... |
Spinner.prototype = Object.create(Widget.prototype);
Spinner.prototype.constructor = Spinner;
Spinner.prototype.start = function() {
this._animateId = requestAnimationFrame(this._animate.bind(this));
};
Spinner.prototype.cancel = function() {
if (this._animateId !== 0) {
cancelAnimationFrame(this._a... | {
settings = utils.merge({
nframes: 31
}, settings);
Widget.call(this, 'spinner', this.create('div'), settings);
this._animateId = 0;
this._animateStart = null;
this._framePeriod = 1 / (this._settings.nframes + 1);
} | identifier_body |
spinner.js | /*
* Copyright (c) 2014 Jesse van den Kieboom. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list... | (settings) {
settings = utils.merge({
nframes: 31
}, settings);
Widget.call(this, 'spinner', this.create('div'), settings);
this._animateId = 0;
this._animateStart = null;
this._framePeriod = 1 / (this._settings.nframes + 1);
}
Spinner.prototype = Object.create(Widget.prototype);
Spin... | Spinner | identifier_name |
context.rs | use ::handle::Handle;
/// A libudev context. Contexts may not be sent or shared between threads. The `libudev(3)` manpage
/// says:
///
/// > All functions require a libudev context to operate. This context can be create via
/// > udev_new(3). It is used to track library state and link objects together. No global stat... | }
} | /// Creates a new context.
pub fn new() -> ::Result<Self> {
Ok(Context {
udev: try_alloc!(unsafe { ::ffi::udev_new() }),
}) | random_line_split |
context.rs | use ::handle::Handle;
/// A libudev context. Contexts may not be sent or shared between threads. The `libudev(3)` manpage
/// says:
///
/// > All functions require a libudev context to operate. This context can be create via
/// > udev_new(3). It is used to track library state and link objects together. No global stat... | (&self) -> Self {
Context {
udev: unsafe { ::ffi::udev_ref(self.udev) },
}
}
}
impl Drop for Context {
/// Decrements reference count of `libudev` context.
fn drop(&mut self) {
unsafe {
::ffi::udev_unref(self.udev);
}
}
}
#[doc(hidden)]
impl Hand... | clone | identifier_name |
lib.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/. */
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead o... | {
Element,
HTMLCanvasElement,
HTMLIFrameElement,
HTMLImageElement,
HTMLInputElement,
HTMLObjectElement,
HTMLTableCellElement,
HTMLTableColElement,
HTMLTableElement,
HTMLTableRowElement,
HTMLTableSectionElement,
HTMLTextAreaElement,
SVGSVGElement,
}
pub struct HTMLCa... | LayoutElementType | identifier_name |
lib.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 |
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead of in script so that these modules won't have
//! to depend on script.
#![deny(unsafe_code)]
#![feature(box_syntax)]
#![feature(nonzero)]
extern crate app_units;
extern crate atomic_refcell;
extern crate ... | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split |
request_for_quotation.py | _request import set_missing_values
from erpnext.controllers.buying_controller import BuyingController
STANDARD_USERS = ("Guest", "Administrator")
class RequestforQuotation(BuyingController):
def validate(self):
self.validate_duplicate_supplier()
self.validate_common()
self.update_email_id()
def validate_dupl... | if not rfq_supplier.email_id:
rfq_supplier.email_id = frappe.db.get_value("Contact", rfq_supplier.contact, "email_id")
def validate_email_id(self, args):
if not args.email_id:
frappe.throw(_("Row {0}: For supplier {0} Email Address is required to send email").format(args.idx, args.supplier))
def on_subm... | pc = frappe.get_doc('Purchase Common')
pc.validate_for_items(self)
def update_email_id(self):
for rfq_supplier in self.suppliers: | random_line_split |
request_for_quotation.py | import set_missing_values
from erpnext.controllers.buying_controller import BuyingController
STANDARD_USERS = ("Guest", "Administrator")
class RequestforQuotation(BuyingController):
def validate(self):
|
def validate_duplicate_supplier(self):
supplier_list = [d.supplier for d in self.suppliers]
if len(supplier_list) != len(set(supplier_list)):
frappe.throw(_("Same supplier has been entered multiple times"))
def validate_common(self):
pc = frappe.get_doc('Purchase Common')
pc.validate_for_items(self)
d... | self.validate_duplicate_supplier()
self.validate_common()
self.update_email_id() | identifier_body |
request_for_quotation.py | import set_missing_values
from erpnext.controllers.buying_controller import BuyingController
STANDARD_USERS = ("Guest", "Administrator")
class RequestforQuotation(BuyingController):
def validate(self):
self.validate_duplicate_supplier()
self.validate_common()
self.update_email_id()
def validate_duplicate_su... |
try:
sq_doc = frappe.get_doc({
"doctype": "Supplier Quotation",
"supplier": doc.get('supplier'),
"terms": doc.get("terms"),
"company": doc.get("company"),
"currency": doc.get('currency') or get_party_account_currency('Supplier', doc.get('supplier'), doc.get('company')),
"buying_price_list": doc.g... | doc = json.loads(doc) | conditional_block |
request_for_quotation.py | import set_missing_values
from erpnext.controllers.buying_controller import BuyingController
STANDARD_USERS = ("Guest", "Administrator")
class RequestforQuotation(BuyingController):
def validate(self):
self.validate_duplicate_supplier()
self.validate_common()
self.update_email_id()
def validate_duplicate_su... | (self, data, update_password_link, rfq_link):
full_name = get_user_fullname(frappe.session['user'])
if full_name == "Guest":
full_name = "Administrator"
args = {
'update_password_link': update_password_link,
'message': frappe.render_template(self.message_for_supplier, data.as_dict()),
'rfq_link': rfq... | supplier_rfq_mail | identifier_name |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
import warning from 'warning';
export ... |
renderSelect = (locale: SelectLocale) => {
const {
prefixCls,
className = '',
size,
mode,
...restProps
} = this.props;
const cls = classNames({
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
}, className);
let { optionLabe... | {
const { mode } = this.props;
return mode === 'combobox' || mode === Select.SECRET_COMBOBOX_MODE_DO_NOT_USE;
} | identifier_body |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
import warning from 'warning';
export ... | (locale: SelectLocale) {
const { notFoundContent } = this.props;
if (this.isCombobox()) {
// AutoComplete don't have notFoundContent defaultly
return notFoundContent === undefined ? null : notFoundContent;
}
return notFoundContent === undefined ? locale.notFoundContent : notFoundContent;
}... | getNotFoundContent | identifier_name |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
import warning from 'warning';
export ... | label: React.ReactNode;
}
export type SelectValue = string | string[] | number | number[] | LabeledValue | LabeledValue[];
export interface SelectProps extends AbstractSelectProps {
value?: SelectValue;
defaultValue?: SelectValue;
mode?: 'default' | 'multiple' | 'tags' | 'combobox' | string;
optionLabelProp... | }
export interface LabeledValue {
key: string; | random_line_split |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
import warning from 'warning';
export ... | {
multiple: mode === 'multiple',
tags: mode === 'tags',
combobox: this.isCombobox(),
};
return (
<RcSelect
{...restProps}
{...modeConfig}
prefixCls={prefixCls}
className={cls}
optionLabelProp={optionLabelProp || 'children'}
notFoundConten... | {
// children 带 dom 结构时,无法填入输入框
optionLabelProp = optionLabelProp || 'value';
}
const modeConfig = | conditional_block |
setup.py | import os
from setuptools import setup, find_packages
version = '0.3.2'
install_requires = [
'Markdown < 3',
'beautifulsoup4 < 5',
'inlinestyler==0.2.1',
'pystache < 0.6',
'parse < 2'
]
tests_require = [
'nose',
'flake8==2.5.4',
'coverage',
]
devtools_require = [
'twine',
'bu... | (f):
return open(os.path.join(os.path.dirname(__file__), f)).read().strip()
setup(
name='ks-email-parser',
version=version,
description=('A command line tool to render HTML and text emails of markdown content.'),
classifiers=[
'License :: OSI Approved :: BSD License', 'Intended Audience :: ... | read | identifier_name |
setup.py | import os
from setuptools import setup, find_packages
version = '0.3.2'
install_requires = [
'Markdown < 3',
'beautifulsoup4 < 5',
'inlinestyler==0.2.1',
'pystache < 0.6',
'parse < 2'
]
tests_require = [
'nose',
'flake8==2.5.4',
'coverage',
]
devtools_require = [
'twine',
'bu... |
setup(
name='ks-email-parser',
version=version,
description=('A command line tool to render HTML and text emails of markdown content.'),
classifiers=[
'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Programming Language :: Python'
],
author='Keepsafe',
... | return open(os.path.join(os.path.dirname(__file__), f)).read().strip() | identifier_body |
setup.py | import os
from setuptools import setup, find_packages
version = '0.3.2'
install_requires = [
'Markdown < 3',
'beautifulsoup4 < 5',
'inlinestyler==0.2.1',
'pystache < 0.6',
'parse < 2'
]
tests_require = [
'nose',
'flake8==2.5.4',
'coverage',
]
devtools_require = [
'twine',
'bu... | ],
author='Keepsafe',
author_email='support@getkeepsafe.com',
url='https://github.com/KeepSafe/ks-email-parser',
license='Apache',
packages=find_packages(),
install_requires=install_requires,
tests_require=tests_require,
extras_require={
'tests': tests_require,
'devto... | classifiers=[
'License :: OSI Approved :: BSD License', 'Intended Audience :: Developers', 'Programming Language :: Python' | random_line_split |
trip-detail.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { TripManagerProvider, TravelCompanionProvider } from '../../providers';
import { TravelcompanionPage } from '../../pages';
/**
* Generated class for the TripDetailPage page.
*
* See http://ionic... | (public navCtrl: NavController, public navParams: NavParams, public tripManager: TripManagerProvider, public tc: TravelCompanionProvider) {
this.trip = this.navParams.get('trip') || this.exampleTrip;
// Add this trip to recently viewed.
this.tripManager.addToRecentlyViewedTrips(this.trip);
// Check if... | constructor | identifier_name |
trip-detail.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { TripManagerProvider, TravelCompanionProvider } from '../../providers';
import { TravelcompanionPage } from '../../pages';
/**
* Generated class for the TripDetailPage page.
*
* See http://ionic... |
});
this.tc.getNearbyPlaces(
this.trip.destination.lat + ',' + this.trip.destination.lon, // location = Lat,Lon
10000, // Radius
'', // Types
'') // Name
.map(res => res.json())
.subscribe(data => {
console.info('Received nearby places', data);
this.trip.ne... | {
this.trip.isAddedToMyTrips = true;
} | conditional_block |
trip-detail.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { TripManagerProvider, TravelCompanionProvider } from '../../providers';
import { TravelcompanionPage } from '../../pages';
/**
* Generated class for the TripDetailPage page.
*
* See http://ionic... | console.info('Received nearby places', data);
this.trip.nearbyPlaces = data.results;
});
console.info('Added trip to recently viewed trips', this.tripManager.recentlyViewedTrips);
}
ionViewDidLoad() {
console.log('ionViewDidLoad TripDetailPage');
}
moveToTravelCompanion() {
... | {
this.trip = this.navParams.get('trip') || this.exampleTrip;
// Add this trip to recently viewed.
this.tripManager.addToRecentlyViewedTrips(this.trip);
// Check if trip is added. For now, only match title.
this.tripManager.myTrips.forEach((trip) => {
if (this.trip.title === trip.title) {
... | identifier_body |
trip-detail.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { TripManagerProvider, TravelCompanionProvider } from '../../providers';
import { TravelcompanionPage } from '../../pages';
/**
* Generated class for the TripDetailPage page.
*
* See http://ionic... | }
};
constructor(public navCtrl: NavController, public navParams: NavParams, public tripManager: TripManagerProvider, public tc: TravelCompanionProvider) {
this.trip = this.navParams.get('trip') || this.exampleTrip;
// Add this trip to recently viewed.
this.tripManager.addToRecentlyViewedTrips(th... | location: 'Indiranagar',
city: 'Bangalore' | random_line_split |
removal.js | // This file contains methods responsible for removing a node.
import { hooks } from "./lib/removal-hooks";
export function remove() {
this._assertUnremoved();
this.resync();
if (this._callRemovalHooks()) {
this._markRemoved();
return;
}
this.shareCommentsWithSiblings();
this._remove();
this.... | else {
this._replaceWith(null);
}
}
export function _markRemoved() {
this.shouldSkip = true;
this.removed = true;
this.node = null;
}
export function _assertUnremoved() {
if (this.removed) {
throw this.buildCodeFrameError("NodePath has been removed so is read-only.");
}
}
| {
this.container.splice(this.key, 1);
this.updateSiblingKeys(this.key, -1);
} | conditional_block |
removal.js | // This file contains methods responsible for removing a node.
import { hooks } from "./lib/removal-hooks";
export function remove() {
this._assertUnremoved();
this.resync();
if (this._callRemovalHooks()) {
this._markRemoved();
return;
}
this.shareCommentsWithSiblings();
this._remove();
this.... | {
if (this.removed) {
throw this.buildCodeFrameError("NodePath has been removed so is read-only.");
}
} | identifier_body | |
removal.js | // This file contains methods responsible for removing a node.
import { hooks } from "./lib/removal-hooks";
export function remove() {
this._assertUnremoved();
this.resync();
| this.shareCommentsWithSiblings();
this._remove();
this._markRemoved();
}
export function _callRemovalHooks() {
for (let fn of (hooks: Array<Function>)) {
if (fn(this, this.parentPath)) return true;
}
}
export function _remove() {
if (Array.isArray(this.container)) {
this.container.splice(this.key,... | if (this._callRemovalHooks()) {
this._markRemoved();
return;
}
| random_line_split |
removal.js | // This file contains methods responsible for removing a node.
import { hooks } from "./lib/removal-hooks";
export function | () {
this._assertUnremoved();
this.resync();
if (this._callRemovalHooks()) {
this._markRemoved();
return;
}
this.shareCommentsWithSiblings();
this._remove();
this._markRemoved();
}
export function _callRemovalHooks() {
for (let fn of (hooks: Array<Function>)) {
if (fn(this, this.parentPa... | remove | identifier_name |
support.py | #!/usr/bin/python
#
# Frontend for running support related commands on hyperic installations.
#
# Opens as an interactive shell if no parameters are passed, otherwise runs
# the command and parameters that have been passed on the command line.
#
# Enter help to see available commands.
#
#
# Adding a new command is do... |
return
run_java_jar(sigar_jar,line)
else:
print "sigar command parameters are missing. Use 'sigar help' for details"
def help_sigar(self):
print "Run a sigar command\n"
sigar_jar = gd.getGlobalData(gd.SIGAR_JAR)
run_java_jar(sigar_jar,'help')... | print "Could not find sigar JAR file in. Expected location is %s" % sigar_jar | conditional_block |
support.py | #!/usr/bin/python
#
# Frontend for running support related commands on hyperic installations.
#
# Opens as an interactive shell if no parameters are passed, otherwise runs
# the command and parameters that have been passed on the command line.
#
# Enter help to see available commands.
#
#
# Adding a new command is do... |
def do_sigar(self,line):
"""Run a sigar command. See help for details"""
if line.strip() != '':
sigar_jar = gd.getGlobalData(gd.SIGAR_JAR)
if not os.path.isfile(sigar_jar):
if gd.getGlobalData(gd.INSTALLATION_TYPE) == hq_utils.DEV:
... | for k in sorted(gd.globalData.keys()):
print "%s: %s" % (k,gd.globalData[k]) | random_line_split |
support.py | #!/usr/bin/python
#
# Frontend for running support related commands on hyperic installations.
#
# Opens as an interactive shell if no parameters are passed, otherwise runs
# the command and parameters that have been passed on the command line.
#
# Enter help to see available commands.
#
#
# Adding a new command is do... | def do_get_variables(self,line):
"""get_variables - Retrieves the values of all support-related variables"""
for k in sorted(gd.globalData.keys()):
print "%s: %s" % (k,gd.globalData[k])
def do_sigar(self,line):
"""Run a sigar command. See help for details"""
... | DELEGATED_HELP_COMMANDS = ['package']
def __init__(self,base_folder):
self.base_folder = base_folder
cmd.Cmd.__init__(self)
def get_cmd_script_name(self,cmd_name):
return os.path.join(self.base_folder,'support-%s.py' % cmd_name)
def do_package(self,line):
run_with_jython(s... | identifier_body |
support.py | #!/usr/bin/python
#
# Frontend for running support related commands on hyperic installations.
#
# Opens as an interactive shell if no parameters are passed, otherwise runs
# the command and parameters that have been passed on the command line.
#
# Enter help to see available commands.
#
#
# Adding a new command is do... | (self):
pass
detectArchitecture()
# Find the path of the script
scripts_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
# NOTE: Assumption is that script is in $HQ_HOME/support/scripts/
hq_utils.detectHQInformation(os.path.abspath(os.path.join(scripts_path,'..','..')))
s = SupportCmd(scripts_path)
s.pr... | emptyline | identifier_name |
che-format-output.directive.ts | /*
* Copyright (c) 2015-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red H... | this.outputColors.forEach((outputColor) => {
regExp = new RegExp('\\[\\s*' + outputColor.type + '\\s*\\]', 'g');
result = result.replace(regExp, '[<span style=\"color: ' + outputColor.color + '\">' + outputColor.type + '</span>]')
});
result = '<span>' + result + '</span>';
elem... | var regExp = new RegExp('\n', 'g');
var result = value.replace(regExp, '<br/>')
| random_line_split |
che-format-output.directive.ts | /*
* Copyright (c) 2015-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red H... |
/**
* Keep reference to the model controller
*/
link($scope, element, attr) {
$scope.$watch(attr.ngModel, (value) => {
if (!value || value.length === 0) {
return;
}
var regExp = new RegExp('\n', 'g');
var result = value.replace(regExp, '<br/>')
this.outputColors.f... | {
this.restrict = 'A';
this.outputColors = angular.fromJson(jsonOutputColors);
this.$compile = $compile;
} | identifier_body |
che-format-output.directive.ts | /*
* Copyright (c) 2015-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red H... | {
/**
* Default constructor that is using resource
* @ngInject for Dependency injection
*/
constructor(jsonOutputColors, $compile) {
this.restrict = 'A';
this.outputColors = angular.fromJson(jsonOutputColors);
this.$compile = $compile;
}
/**
* Keep reference to the model controller
... | CheFormatOutput | identifier_name |
che-format-output.directive.ts | /*
* Copyright (c) 2015-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red H... |
var regExp = new RegExp('\n', 'g');
var result = value.replace(regExp, '<br/>')
this.outputColors.forEach((outputColor) => {
regExp = new RegExp('\\[\\s*' + outputColor.type + '\\s*\\]', 'g');
result = result.replace(regExp, '[<span style=\"color: ' + outputColor.color + '\">' + out... | {
return;
} | conditional_block |
mac_utils.py | ate": True,
"timeout": None,
"bg": False,
}
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **kwargs)
except OSError as exc:
raise CommandExecutionError(
"Unable to run command '{}' with the context '{}', reason: {}".format(
cmd, kwargs, e... |
def validate_enabled(enabled):
"""
Helper function to validate the enabled parameter. Boolean values are
converted to "on" and "off". String values are checked to make sure they are
either "on" or "off"/"yes" or "no". Integer ``0`` will return "off". All
other integers will return "on"
:para... | """
Returns the data portion of a string that is colon separated.
:param str data: The string that contains the data to be parsed. Usually the
standard out from a command
For example:
``Time Zone: America/Denver``
will return:
``America/Denver``
"""
if ": " in data:
return... | identifier_body |
mac_utils.py | ate": True,
"timeout": None,
"bg": False,
}
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **kwargs)
except OSError as exc:
raise CommandExecutionError(
"Unable to run command '{}' with the context '{}', reason: {}".format(
cmd, kwargs, e... |
return False
def execute_return_success(cmd):
"""
Executes the passed command. Returns True if successful
:param str cmd: The command to run
:return: True if successful, otherwise False
:rtype: bool
:raises: Error if command fails or is not supported
"""
ret = _run_all(cmd)
... | return True | conditional_block |
mac_utils.py | ate": True,
"timeout": None,
"bg": False,
}
try:
proc = salt.utils.timed_subprocess.TimedProc(cmd, **kwargs)
except OSError as exc:
raise CommandExecutionError(
"Unable to run command '{}' with the context '{}', reason: {}".format(
cmd, kwargs, e... | return {}
# ignore broken symlinks
if not os.path.exists(os.path.realpath(file_path)):
log.warning("read_plist: Ignoring broken symlink: %s", file_path)
return {}
try:
with salt.utils.files.fopen(file_path, "rb") as handle:
plist = plistlib.load(handle)
exc... | # Must be a plist file
if not file_path.lower().endswith(".plist"):
log.debug("read_plist: Not a plist file: %s", file_path) | random_line_split |
mac_utils.py | (cmd):
"""
Args:
cmd:
Returns:
"""
if not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd, posix=False)
for idx, item in enumerate(cmd):
if not isinstance(cmd[idx], str):
cmd[idx] = str(cmd[idx])
cmd = " ".join(cmd)
run_env = os.envi... | _run_all | identifier_name | |
complete.rs | use std::path::PathBuf;
pub trait Completer {
fn completions(&self, start: &str) -> Vec<String>;
}
pub struct BasicCompleter {
prefixes: Vec<String>,
}
impl BasicCompleter {
pub fn new<T: Into<String>>(prefixes: Vec<T>) -> BasicCompleter {
BasicCompleter { prefixes: prefixes.into_iter().map(|s| s... | fn completions(&self, mut start: &str) -> Vec<String> {
// XXX: this function is really bad, TODO rewrite
let start_owned;
if start.starts_with("\"") || start.starts_with("'") {
start = &start[1..];
if start.len() >= 1 {
start = &start[..start.len() -... | }
}
impl Completer for FilenameCompleter { | random_line_split |
complete.rs | use std::path::PathBuf;
pub trait Completer {
fn completions(&self, start: &str) -> Vec<String>;
}
pub struct BasicCompleter {
prefixes: Vec<String>,
}
impl BasicCompleter {
pub fn new<T: Into<String>>(prefixes: Vec<T>) -> BasicCompleter {
BasicCompleter { prefixes: prefixes.into_iter().map(|s| s... | (&self, mut start: &str) -> Vec<String> {
// XXX: this function is really bad, TODO rewrite
let start_owned;
if start.starts_with("\"") || start.starts_with("'") {
start = &start[1..];
if start.len() >= 1 {
start = &start[..start.len() - 1];
}... | completions | identifier_name |
complete.rs | use std::path::PathBuf;
pub trait Completer {
fn completions(&self, start: &str) -> Vec<String>;
}
pub struct BasicCompleter {
prefixes: Vec<String>,
}
impl BasicCompleter {
pub fn new<T: Into<String>>(prefixes: Vec<T>) -> BasicCompleter {
BasicCompleter { prefixes: prefixes.into_iter().map(|s| s... |
}
pub struct FilenameCompleter {
working_dir: Option<PathBuf>,
}
impl FilenameCompleter {
pub fn new<T: Into<PathBuf>>(working_dir: Option<T>) -> Self {
FilenameCompleter { working_dir: working_dir.map(|p| p.into()) }
}
}
impl Completer for FilenameCompleter {
fn completions(&self, mut start... | {
self.prefixes
.iter()
.filter(|s| s.starts_with(start))
.cloned()
.collect()
} | identifier_body |
irc_responder.rs | use command_with_sender_iter::CommandWithSenderIterable;
use star_handler::StarHandler;
use irc::client::prelude::*;
use std::sync::Arc;
pub struct IrcResponder {
starboard: StarHandler,
server : Arc<IrcServer>,
}
impl IrcResponder {
pub fn from_config(config: Config) -> IrcResponder |
pub fn handle(&mut self) {
for message in self.server.iter_cmd_sender() {
match message {
Ok((Command::JOIN(_, _, _), Some(sender))) =>
if sender == "StarBot" {
println!("I'm in")
},
Ok((Command::PRIVMSG(target, msg), sender)) => {
match (&target[..], &msg[..], sender.as_ref().map(|... | {
let server = Arc::new(IrcServer::from_config(config).unwrap());
server.identify().unwrap();
IrcResponder{
starboard: StarHandler::new(&server),
server : server,
}
} | identifier_body |
irc_responder.rs | use command_with_sender_iter::CommandWithSenderIterable;
use star_handler::StarHandler;
use irc::client::prelude::*;
use std::sync::Arc;
pub struct IrcResponder {
starboard: StarHandler,
server : Arc<IrcServer>,
}
impl IrcResponder {
pub fn from_config(config: Config) -> IrcResponder {
let server = Arc::new(I... | }
}
}
fn quit(&self) {
self.server.send_quit("Mára mesta").unwrap();
}
fn help(&self, whom: &str, level: i32) {
self.server.send_notice(whom, r#"Cummands, level 0:"#).unwrap();
self.server.send_notice(whom, r#" "add <" username ">" message content -- add your star to a message"#).unwrap();
self.serv... | random_line_split | |
irc_responder.rs | use command_with_sender_iter::CommandWithSenderIterable;
use star_handler::StarHandler;
use irc::client::prelude::*;
use std::sync::Arc;
pub struct IrcResponder {
starboard: StarHandler,
server : Arc<IrcServer>,
}
impl IrcResponder {
pub fn | (config: Config) -> IrcResponder {
let server = Arc::new(IrcServer::from_config(config).unwrap());
server.identify().unwrap();
IrcResponder{
starboard: StarHandler::new(&server),
server : server,
}
}
pub fn handle(&mut self) {
for message in self.server.iter_cmd_sender() {
match message {
O... | from_config | identifier_name |
size_of.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 script::test::size_of;
// Macro so that we can stringify type names
// I'd really prefer the tests themselves... | );
// Update the sizes here
sizeof_checker!(size_event_target, EventTarget, 40);
sizeof_checker!(size_node, Node, 184);
sizeof_checker!(size_element, Element, 352);
sizeof_checker!(size_htmlelement, HTMLElement, 368);
sizeof_checker!(size_div, HTMLDivElement, 368);
sizeof_checker!(size_span, HTMLSpanElement, 368);
siz... | avoids this increase. If you feel that the increase is necessary, \
update to the new size in tests/unit/script/size_of.rs.",
stringify!($t), old, new)
}
}); | random_line_split |
message_builder.rs | use session::{Session, ReceiptRequest, OutstandingReceipt};
use frame::Frame;
use option_setter::OptionSetter;
pub struct MessageBuilder<'a> {
pub session: &'a mut Session,
pub frame: Frame,
pub receipt_request: Option<ReceiptRequest>
}
impl<'a> MessageBuilder<'a> {
pub fn new(session: &'a mut Session... | <T>(self, option_setter: T) -> MessageBuilder<'a>
where T: OptionSetter<MessageBuilder<'a>>
{
option_setter.set_option(self)
}
}
| with | identifier_name |
message_builder.rs | use session::{Session, ReceiptRequest, OutstandingReceipt};
use frame::Frame;
use option_setter::OptionSetter;
pub struct MessageBuilder<'a> {
pub session: &'a mut Session,
pub frame: Frame,
pub receipt_request: Option<ReceiptRequest>
}
impl<'a> MessageBuilder<'a> {
pub fn new(session: &'a mut Session... |
self.session.send_frame(self.frame)
}
#[allow(dead_code)]
pub fn with<T>(self, option_setter: T) -> MessageBuilder<'a>
where T: OptionSetter<MessageBuilder<'a>>
{
option_setter.set_option(self)
}
}
| {
let request = self.receipt_request.unwrap();
self.session.state.outstanding_receipts.insert(
request.id,
OutstandingReceipt::new(
self.frame.clone()
)
);
} | conditional_block |
message_builder.rs | use session::{Session, ReceiptRequest, OutstandingReceipt};
use frame::Frame;
use option_setter::OptionSetter;
pub struct MessageBuilder<'a> {
pub session: &'a mut Session,
pub frame: Frame,
pub receipt_request: Option<ReceiptRequest>
}
impl<'a> MessageBuilder<'a> {
pub fn new(session: &'a mut Session... |
#[allow(dead_code)]
pub fn send(self) {
if self.receipt_request.is_some() {
let request = self.receipt_request.unwrap();
self.session.state.outstanding_receipts.insert(
request.id,
OutstandingReceipt::new(
self.frame.clone()
... | {
MessageBuilder {
session: session,
frame: frame,
receipt_request: None
}
} | identifier_body |
message_builder.rs | use session::{Session, ReceiptRequest, OutstandingReceipt};
use frame::Frame;
use option_setter::OptionSetter;
pub struct MessageBuilder<'a> {
pub session: &'a mut Session,
pub frame: Frame,
pub receipt_request: Option<ReceiptRequest>
}
impl<'a> MessageBuilder<'a> {
pub fn new(session: &'a mut Session... | where T: OptionSetter<MessageBuilder<'a>>
{
option_setter.set_option(self)
}
} |
#[allow(dead_code)]
pub fn with<T>(self, option_setter: T) -> MessageBuilder<'a> | random_line_split |
ModuleCache.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
* Copyright (C) 2017 Hendrik van Essen
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
"""
import os
import sys
from shutil import copytree, ... | class ModuleCache(object):
_cache_dir = None
def __init__(self, cache_dir):
self._cache_dir = cache_dir
def get_entry(self, board, path):
cache_path = os.path.join(self._cache_dir, board, path)
ready_to_use_file = os.path.join(cache_path, ".ready_to_use")
if os.path.isfi... | from common import create_directories
| random_line_split |
ModuleCache.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
* Copyright (C) 2017 Hendrik van Essen
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
"""
import os
import sys
from shutil import copytree, ... |
else:
return None
def cache(self, path, board, name):
create_directories(self._cache_dir)
# only store if not in cache already
if self.get_entry(board, name) is None:
dest_in_cache = os.path.join(self._cache_dir, board, name)
copytree(path, ... | return cache_path | conditional_block |
ModuleCache.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
* Copyright (C) 2017 Hendrik van Essen
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
"""
import os
import sys
from shutil import copytree, ... | (object):
_cache_dir = None
def __init__(self, cache_dir):
self._cache_dir = cache_dir
def get_entry(self, board, path):
cache_path = os.path.join(self._cache_dir, board, path)
ready_to_use_file = os.path.join(cache_path, ".ready_to_use")
if os.path.isfile(ready_to_use_f... | ModuleCache | identifier_name |
ModuleCache.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
* Copyright (C) 2017 Hendrik van Essen
*
* This file is subject to the terms and conditions of the GNU Lesser
* General Public License v2.1. See the file LICENSE in the top level
* directory for more details.
"""
import os
import sys
from shutil import copytree, ... | # only store if not in cache already
if self.get_entry(board, name) is None:
dest_in_cache = os.path.join(self._cache_dir, board, name)
copytree(path, dest_in_cache)
# show that cached application/module is now ready to use
ready_file_path = os.path.joi... | _cache_dir = None
def __init__(self, cache_dir):
self._cache_dir = cache_dir
def get_entry(self, board, path):
cache_path = os.path.join(self._cache_dir, board, path)
ready_to_use_file = os.path.join(cache_path, ".ready_to_use")
if os.path.isfile(ready_to_use_file):
... | identifier_body |
index.d.ts | // Type definitions for bittorrent-protocol 3.1
// Project: https://github.com/webtorrent/bittorrent-protocol
// Definitions by: Feross Aboukhadijeh <https://github.com/feross>,
// Tomasz Łaziuk <https://github.com/tlaziuk>,
// H1b9b <https://github.com/h1b9b>
// Definitions: https://git... | new (): Wire;
(): Wire;
}
interface ExtensionConstructor {
new (wire: Wire): Extension;
}
interface Extension {
onHandshake?(infoHash: string, peerId: string, extensions: { [name: string]: boolean }): void;
onExtendedHandshake?(handshake: { [key: string]: any })... | declare const BittorrentProtocol: BittorrentProtocol.BittorrentProtocol;
declare namespace BittorrentProtocol {
interface BittorrentProtocol { | random_line_split |
filter_actions.js | "use strict";
var FilterDispatcher = require("../dispatcher/filter_dispatcher");
module.exports = {
changeDate: function changeDate(key, date) {
var pos = arguments.length <= 2 || arguments[2] === undefined ? "start" : arguments[2];
FilterDispatcher.handleChangeDate({
type: "CHANGE_DATE",
date:... | });
},
checkFilter: function checkFilter(filterBy, id, value) {
FilterDispatcher.handleCheckFilter({
type: "CHECK_FILTER",
filterBy: filterBy,
id: id,
value: value
});
},
changeKey: function changeKey(data) {
FilterDispatcher.handleKeyUpdate({
type: "CHANGE_KEY",
... | pos: pos | random_line_split |
classic.py | import sys
import time
import json
import logging
import random
import tornado.options
from tornado.options import define, options
from tornado import gen
define('srp_root',default='http://192.168.56.1')
#define('srp_root',default='https://remote-staging.utorrent.com')
#define('srp_root',default='https://remote.utorre... | ():
username = sys.argv[1]
password = sys.argv[2]
# check result..
#torrent = 'http://www.clearbits.net/get/503-control-alt-deus---made-of-fire.torrent'
hash = ''.join([random.choice( list('abcdef') + map(str,range(10)) ) for _ in range(40)])
torrent = 'magnet:?xt=urn:btih:%s' % hash
for _... | test_login | identifier_name |
classic.py | import sys
import time
import json
import logging
import random
import tornado.options
from tornado.options import define, options
from tornado import gen
define('srp_root',default='http://192.168.56.1')
#define('srp_root',default='https://remote-staging.utorrent.com')
#define('srp_root',default='https://remote.utorre... |
responses = yield gen.Multi( tasks )
logging.info('responses %s' % [r.code for r in responses])
if __name__ == '__main__':
ioloop = tornado.ioloop.IOLoop.instance()
test_login()
ioloop.start()
| link = torrent.webseed_link()
print torrent.get('name'), torrent.get('progress'), link
request = tornado.httpclient.HTTPRequest(link,
validate_cert=False)
tasks.append( gen.Task( httpclient.fetch, request ) ) | conditional_block |
classic.py | import sys
import time
import json
import logging
import random
import tornado.options
from tornado.options import define, options
from tornado import gen
define('srp_root',default='http://192.168.56.1')
#define('srp_root',default='https://remote-staging.utorrent.com')
#define('srp_root',default='https://remote.utorre... |
import tornado.ioloop
from falcon_api.session import Session
from falcon_api.util import asyncsleep
from falcon_api.classic import Client
import tornado.httpclient
httpclient = tornado.httpclient.AsyncHTTPClient(force_instance=True, max_clients=1)
@gen.engine
def test_login():
username = sys.argv[1]
passwor... | define('verbose',default=1, type=int)
tornado.options.parse_command_line()
if options.debug:
import pdb | random_line_split |
classic.py | import sys
import time
import json
import logging
import random
import tornado.options
from tornado.options import define, options
from tornado import gen
define('srp_root',default='http://192.168.56.1')
#define('srp_root',default='https://remote-staging.utorrent.com')
#define('srp_root',default='https://remote.utorre... | tasks.append( gen.Task( torrent.fetch_metadata ) )
responses = yield gen.Multi( tasks )
logging.info('responses %s' % [r.code for r in responses])
tasks = []
for hash, torrent in client.torrents.items():
if torrent.get('progress') == 1000:
for file in torrent.files:
... | username = sys.argv[1]
password = sys.argv[2]
# check result..
#torrent = 'http://www.clearbits.net/get/503-control-alt-deus---made-of-fire.torrent'
hash = ''.join([random.choice( list('abcdef') + map(str,range(10)) ) for _ in range(40)])
torrent = 'magnet:?xt=urn:btih:%s' % hash
for _ in rang... | identifier_body |
profile.js | import { Meteor } from "meteor/meteor";
import { Template } from "meteor/templating";
import { Roles } from "meteor/alanning:roles";
import { ReactiveVar } from "meteor/reactive-var";
import { Reaction } from "/client/api";
import { i18next } from "/client/api";
import * as Collections from "/lib/collections";
import ... | else if (user.profile && user.profile.name) {
return user.profile.name;
}
}
if (Roles.userIsInRole(user._id || user.userId, "account/profile",
Reaction.getShopId())) {
return i18next.t("accountsUI.guest", { defaultValue: "Guest" });
}
},
/**
* Returns the address book def... | {
return user.username;
} | conditional_block |
profile.js | import { Meteor } from "meteor/meteor";
import { Template } from "meteor/templating";
import { Roles } from "meteor/alanning:roles";
import { ReactiveVar } from "meteor/reactive-var";
import { Reaction } from "/client/api";
import { i18next } from "/client/api";
import * as Collections from "/lib/collections";
import ... | () {
const orderSub = Meteor.subscribe("AccountOrders", Meteor.userId());
if (orderSub.ready()) {
return Collections.Orders.find({
userId: Meteor.userId()
}, {
sort: {
createdAt: -1
},
limit: 25
});
}
},
/**
* User's account profile
* @r... | userOrders | identifier_name |
profile.js | import { Meteor } from "meteor/meteor";
import { Template } from "meteor/templating";
import { Roles } from "meteor/alanning:roles";
import { ReactiveVar } from "meteor/reactive-var";
import { Reaction } from "/client/api";
import { i18next } from "/client/api";
import * as Collections from "/lib/collections";
import ... | ,
/**
* User's order history
* @return {Array|null} an array of available orders for the user
*/
userOrders() {
const orderSub = Meteor.subscribe("AccountOrders", Meteor.userId());
if (orderSub.ready()) {
return Collections.Orders.find({
userId: Meteor.userId()
}, {
sor... | {
return Template.instance().userHasPassword.get();
} | identifier_body |
profile.js | import { Meteor } from "meteor/meteor";
import { Template } from "meteor/templating";
import { Roles } from "meteor/alanning:roles";
import { ReactiveVar } from "meteor/reactive-var";
import { Reaction } from "/client/api";
import { i18next } from "/client/api";
import * as Collections from "/lib/collections";
import ... | * User has password
* @return {Boolean} return true if the current user has a password, false otherwise
*/
userHasPassword() {
return Template.instance().userHasPassword.get();
},
/**
* User's order history
* @return {Array|null} an array of available orders for the user
*/
userOrders() {... | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2015 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This ... | from .email import EmailMatcher
from .email_name import EmailNameMatcher
SORTINGHAT_IDENTITIES_MATCHERS = {
'default' : EmailMatcher,
'email' : EmailMatcher,
'email-name' : EmailNameMatcher,
... |
from __future__ import absolute_import
from __future__ import unicode_literals
| random_line_split |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::ops;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin_until;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
use numtoa::NumToA;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor... | fn cursor_pos(&mut self) -> io::Result<(u16, u16)>;
}
impl<W: Write> DetectCursorPos for W {
fn cursor_pos(&mut self) -> io::Result<(u16, u16)> {
let delimiter = b'R';
let mut stdin = async_stdin_until(delimiter);
// Where is the cursor?
// Use `ESC [ 6 n`.
write!(self,... | /// Get the (1,1)-based cursor position from the terminal. | random_line_split |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::ops;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin_until;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
use numtoa::NumToA;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor... |
}
impl<W: Write> ops::DerefMut for HideCursor<W> {
fn deref_mut(&mut self) -> &mut W {
&mut self.output
}
}
impl<W: Write> Write for HideCursor<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.output.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
sel... | {
&self.output
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.