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 |
|---|---|---|---|---|
worker.js | 'use strict';
var _ = require('lodash');
var async = require('async');
var config = require('config');
var queue = require('./services/queue-service')(config);
var workers = require('./lib/workers');
var Message = require('./lib/message');
var process = function() {
queue.receiveMessage(function(err, data) {
i... | process();
setTimeout(poll, 30e3);
})(); | random_line_split | |
worker.js | 'use strict';
var _ = require('lodash');
var async = require('async');
var config = require('config');
var queue = require('./services/queue-service')(config);
var workers = require('./lib/workers');
var Message = require('./lib/message');
var process = function() {
queue.receiveMessage(function(err, data) {
i... |
});
} else {
console.log('No messages to process at this time');
}
});
};
console.log('Worker started');
(function poll() {
process();
setTimeout(poll, 30e3);
})();
| {
console.log('Done');
} | conditional_block |
trigger.tsx | import { Button, ScreenReaderText, Gridicon } from '@automattic/components';
import { useTranslate } from 'i18n-calypso';
import ButtonGroup from 'calypso/components/button-group';
import type { Moment } from 'moment';
import type { FunctionComponent, Ref } from 'react';
// eslint-disable-next-line @typescript-eslint/... | else {
dateRangeText = translate( '%(startDateText)s - %(endDateText)s', {
context: 'Date range text for DateRange input trigger',
args: {
startDateText,
endDateText,
},
} );
}
return (
<ButtonGroup className="date-range__trigger">
<Button
className="date-range__trigger-btn"
ref={ ... | {
dateRangeText = triggerText( startDateText, endDateText );
} | conditional_block |
trigger.tsx | import { Button, ScreenReaderText, Gridicon } from '@automattic/components';
import { useTranslate } from 'i18n-calypso';
import ButtonGroup from 'calypso/components/button-group';
import type { Moment } from 'moment';
import type { FunctionComponent, Ref } from 'react';
// eslint-disable-next-line @typescript-eslint/... | },
} );
}
return (
<ButtonGroup className="date-range__trigger">
<Button
className="date-range__trigger-btn"
ref={ buttonRef }
onClick={ onTriggerClick }
compact={ isCompact }
aria-haspopup={ true }
>
<Gridicon className="date-range__trigger-btn-icon" icon="calendar" aria-hidden=... | random_line_split | |
main.rs | use crossbeam_channel::{bounded, select};
use crossbeam_utils::thread;
fn | () {
let people = vec!["Anna", "Bob", "Cody", "Dave", "Eva"];
let (s, r) = bounded(1); // Make room for one unmatched send.
// Either send my name into the channel or receive someone else's, whatever happens first.
let seek = |name, s, r| {
select! {
recv(r) -> peer => println!("{} ... | main | identifier_name |
main.rs | let (s, r) = bounded(1); // Make room for one unmatched send.
// Either send my name into the channel or receive someone else's, whatever happens first.
let seek = |name, s, r| {
select! {
recv(r) -> peer => println!("{} received a message from {}.", name, peer.unwrap()),
se... | use crossbeam_channel::{bounded, select};
use crossbeam_utils::thread;
fn main() {
let people = vec!["Anna", "Bob", "Cody", "Dave", "Eva"]; | random_line_split | |
main.rs | use crossbeam_channel::{bounded, select};
use crossbeam_utils::thread;
fn main() {
let people = vec!["Anna", "Bob", "Cody", "Dave", "Eva"];
let (s, r) = bounded(1); // Make room for one unmatched send.
// Either send my name into the channel or receive someone else's, whatever happens first.
let seek ... | {
println!("No one received {}’s message.", name);
}
} | conditional_block | |
main.rs | use crossbeam_channel::{bounded, select};
use crossbeam_utils::thread;
fn main() | // Check if there is a pending send operation.
if let Ok(name) = r.try_recv() {
println!("No one received {}’s message.", name);
}
}
| {
let people = vec!["Anna", "Bob", "Cody", "Dave", "Eva"];
let (s, r) = bounded(1); // Make room for one unmatched send.
// Either send my name into the channel or receive someone else's, whatever happens first.
let seek = |name, s, r| {
select! {
recv(r) -> peer => println!("{} rec... | identifier_body |
botworker.ts | /**
* @module botbuilder-adapter-twilio-sms
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { BotWorker } from 'botkit';
import * as Twilio from 'twilio';
import { ConversationAccount, ChannelAccount } from 'botbuilder';
/**
* This is a specialized ... | */export class TwilioBotWorker extends BotWorker {
/**
* A copy of the Twilio API client.
*/
public api: Twilio.Twilio; // Twilio api
/**
* Start a conversation with a given user identified by their phone number. Useful for sending pro-active messages:
*
* ```javascript
* let... | * When using the TwilioAdapter with Botkit, all `bot` objects passed to handler functions will include these extensions. | random_line_split |
botworker.ts | /**
* @module botbuilder-adapter-twilio-sms
*/
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import { BotWorker } from 'botkit';
import * as Twilio from 'twilio';
import { ConversationAccount, ChannelAccount } from 'botbuilder';
/**
* This is a specialized ... | (userId: string): Promise<any> {
return this.changeContext({
channelId: 'twilio-sms',
conversation: { id: userId } as ConversationAccount,
bot: { id: this.controller.getConfig('twilio_number'), name: 'bot' },
user: { id: userId } as ChannelAccount
});
... | startConversationWithUser | identifier_name |
lexer.js | /*
* THIS FILE IS AUTO GENERATED FROM 'lib/lex/lexer.kep'
* DO NOT EDIT
*/
define(["require", "exports", "bennu/parse", "bennu/lang", "nu-stream/stream", "ecma-ast/token", "ecma-ast/position",
"./boolean_lexer", "./comment_lexer", "./identifier_lexer", "./line_terminator_lexer", "./null_lexer",
"./number_lexe... | }))), ((type3 = lexToken.RegularExpressionToken.create), (p = next(enterRegExpCtx,
regularExpressionLiteral)), p.map((function(x) {
return [type3, x];
})))),
token = choice(attempt(((type4 = lexToken.IdentifierToken), identifier.map((function(x) {
return [type... | return [type2, x]; | random_line_split |
oss-config-form.component.ts | import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Observable, of} from 'rxjs';
import {catchError, debounceTime, distinctUntilChanged, map, switchMap, take, tap} from 'rxjs/operators';
import {DashboardService} from '../../../shared/dashbo... |
const description = (collectorItem.description as string);
return description;
}
@Input()
set widgetConfig(widgetConfig: any) {
if (!widgetConfig) {
return;
}
this.widgetConfigId = widgetConfig.options.id;
this.ossConfigForm.get('ossJob').setValue(widgetConfig.collectorItemId);
}... | {
return '';
} | conditional_block |
oss-config-form.component.ts | import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Observable, of} from 'rxjs';
import {catchError, debounceTime, distinctUntilChanged, map, switchMap, take, tap} from 'rxjs/operators';
import {DashboardService} from '../../../shared/dashbo... | () {
this.dashboardService.dashboardConfig$.pipe(take(1),
map(dashboard => {
const ossCollector = dashboard.application.components[0].collectorItems.LibraryPolicy;
const savedCollectorOSS = ossCollector ? ossCollector[0].description : null;
if (savedCollectorOSS) {
const oss... | loadSavedOssJob | identifier_name |
oss-config-form.component.ts | import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Observable, of} from 'rxjs';
import {catchError, debounceTime, distinctUntilChanged, map, switchMap, take, tap} from 'rxjs/operators';
import {DashboardService} from '../../../shared/dashbo... | this.dashboardService.dashboardConfig$.pipe(take(1),
map(dashboard => {
return dashboard.application.components[0].id;
})).subscribe(componentId => this.componentId = componentId);
}
// convenience getter for easy access to form fields
get configForm() { return this.ossConfigForm.controls... | random_line_split | |
oss-config-form.component.ts | import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Observable, of} from 'rxjs';
import {catchError, debounceTime, distinctUntilChanged, map, switchMap, take, tap} from 'rxjs/operators';
import {DashboardService} from '../../../shared/dashbo... |
constructor(
public activeModal: NgbActiveModal,
public formBuilder: FormBuilder,
public collectorService: CollectorService,
public dashboardService: DashboardService,
) {
this.createForm();
}
ngOnInit() {
this.typeAheadResults = (text$: Observable<string>) =>
text$.pipe(
... | {
if (!widgetConfig) {
return;
}
this.widgetConfigId = widgetConfig.options.id;
this.ossConfigForm.get('ossJob').setValue(widgetConfig.collectorItemId);
} | identifier_body |
alt.js | (name) {
return name.replace(/[a-z]([A-Z])/g, function (i) {
return "" + i[0] + "_" + i[1].toLowerCase();
}).toUpperCase();
}
function uid(container, name) {
var count = 0;
var key = name;
while (Object.hasOwnProperty.call(container, key)) {
key = name + String(++count);
}
return key;
}
/* istan... | formatAsConstant | identifier_name | |
alt.js | (value, m) {
if (excluded.indexOf(m) !== -1) {
return value;
}
value[m] = obj[m];
return value;
}, {});
};
var AltStore = (function () {
function AltStore(dispatcher, model, state) {
var _this8 = this;
_classCallCheck(this, AltStore);
this[EE] = new EventEmitter();
this[LI... | else if (_this8[assumedEventHandler]) {
// onAction
handler = _this8[assumedEventHandler];
}
if (handler) {
_this8.bindAction(symbol, handler);
}
});
},
bindListeners: function bindListeners(obj) {
var _this8 = this;
Object.keys(obj).forEach(function (method... | {
// action
handler = _this8[action];
} | conditional_block |
alt.js |
/* istanbul ignore next */
function NoopClass() {}
var builtIns = Object.getOwnPropertyNames(NoopClass);
var builtInProto = Object.getOwnPropertyNames(NoopClass.prototype);
var getInternalMethods = function (obj, excluded) {
return Object.getOwnPropertyNames(obj).reduce(function (value, m) {
if (excluded.inde... | {
var count = 0;
var key = name;
while (Object.hasOwnProperty.call(container, key)) {
key = name + String(++count);
}
return key;
} | identifier_body | |
alt.js | (value, m) {
if (excluded.indexOf(m) !== -1) {
return value;
}
value[m] = obj[m];
return value;
}, {});
};
var AltStore = (function () {
function AltStore(dispatcher, model, state) {
var _this8 = this;
_classCallCheck(this, AltStore);
this[EE] = new EventEmitter();
this[LI... |
var saveInitialSnapshot = function (instance, key) {
var state = instance.stores[key][STATE_CONTAINER];
var initial = JSON.parse(instance[INIT_SNAPSHOT]);
initial[key] = state;
instance[INIT_SNAPSHOT] = JSON.stringify(initial);
};
var filterSnapshotOfStores = function (serializedSnapshot, storeNames) {
var ... | obj[key] = customSnapshot ? customSnapshot : store.getState();
return obj;
}, {}));
}; | random_line_split |
game.rs | use std::io;
use std::io::Stdin;
use std::error::Error;
use commands::InputCommand;
use game_state::GameState;
use settings::Setting;
use updates::Update;
use player::Player;
use action::Action;
use strategies::Strategy;
const CHARACTER: &str = "bixie";
#[derive(Debug)]
enum GameStatus {
New,
Started,
}
#[d... |
Setting::YourBotID(id) => {
if self.player.is_some() {
let mut player = self.player.take().unwrap();
player.set_id(id);
self.player = Some(player);
}
self.your_botid = Some(id);
... | {
self.player = Some(Player::new(name.clone()));
self.your_bot = Some(name);
} | conditional_block |
game.rs | use std::io;
use std::io::Stdin;
use std::error::Error;
use commands::InputCommand;
use game_state::GameState;
use settings::Setting;
use updates::Update;
use player::Player;
use action::Action;
use strategies::Strategy;
const CHARACTER: &str = "bixie";
#[derive(Debug)]
enum GameStatus {
New,
Started,
}
#[d... | self.parse_command(&command_str).unwrap();
match self.status {
GameStatus::New => (),
GameStatus::Started => {
if self.round == self.max_rounds.unwrap() {
continue;
}
}
}
... | self.stdin.read_line(&mut command_str).unwrap(); | random_line_split |
game.rs | use std::io;
use std::io::Stdin;
use std::error::Error;
use commands::InputCommand;
use game_state::GameState;
use settings::Setting;
use updates::Update;
use player::Player;
use action::Action;
use strategies::Strategy;
const CHARACTER: &str = "bixie";
#[derive(Debug)]
enum GameStatus {
New,
Started,
}
#[d... |
fn update_game_state(&mut self, state: String) {
// For now, the game will replace the current state whenever
// a new state is provided. Idealy the game should always store
// previous states and perform a diff with the provided state
// So it will have context (like the directio... | {
match action {
Action::Character(_) => println!("{}", self.character),
Action::Move(_) => {
// For now I'm just ignoring timebank management
// Todo: Use timebank information
self.strategy.run(self.state.clone())
}
}
... | identifier_body |
game.rs | use std::io;
use std::io::Stdin;
use std::error::Error;
use commands::InputCommand;
use game_state::GameState;
use settings::Setting;
use updates::Update;
use player::Player;
use action::Action;
use strategies::Strategy;
const CHARACTER: &str = "bixie";
#[derive(Debug)]
enum GameStatus {
New,
Started,
}
#[d... | (&mut self, cmd: &str) -> Result<(), &'static str> {
let command = InputCommand::new(cmd).unwrap();
match command {
InputCommand::Setting(val) => self.add_settings(val),
InputCommand::Update(val) => self.update_game(val),
InputCommand::Action(val) => self.perform_acti... | parse_command | identifier_name |
network_listener.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 https://mozilla.org/MPL/2.0/. */
//! The listener that encapsulates all state for an in-progress document request.
//! Any redirects that are enco... | (&mut self, msg: FetchResponseMsg) {
if self.should_send {
if let Err(e) = self.sender.send((self.pipeline_id, msg)) {
warn!(
"Failed to forward network message to pipeline {}: {:?}",
self.pipeline_id, e
);
}
... | send | identifier_name |
network_listener.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 https://mozilla.org/MPL/2.0/. */
//! The listener that encapsulates all state for an in-progress document request.
//! Any redirects that are enco... | Some(ref res_init_) => CoreResourceMsg::FetchRedirect(
self.request_builder.clone(),
res_init_.clone(),
ipc_sender,
None,
),
None => {
set_default_accept(Destination::Document, &mut listener.request_build... |
let msg = match self.res_init { | random_line_split |
rollovers.js | /**
Copyright 2011-2013 Here's A Hand Limited
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() {
$("input.yes").mouseover(function(){
$(this).attr('value','No');
$(this).removeClass('yes')
$(this).addClass('no')
});
$("input.yes").mouseout(function(){
$(this).attr('value','Yes');
$(this).removeClass('no')
$(this).addClass('yes')
});
$("input.no").mouseover(function(){
$(this).at... | limitations under the License.
**/ | random_line_split |
RSSCalendarService.ts | /**
* RSS Calendar Service
* Renders events from an RSS feed. It only renders events in the future, so not every plain old RSS feed will do, but
* calendar RSS feeds should work ok.
* Before anyone complains that I should have used a readily available RSS parser library, I tried almost
* every one I could find on ... | let events: ICalendarEvent[] = feed.items.map(item => {
let pubDate: Date = this.convertToDate(item.isoDate);
const eventItem: ICalendarEvent = {
title: item.title,
start: pubDate,
end: pubDate,
url: item.link,
allDay: false,
description:... | return parser.parseURL(parameterizedFeedUrl).then(feed => {
| random_line_split |
RSSCalendarService.ts | /**
* RSS Calendar Service
* Renders events from an RSS feed. It only renders events in the future, so not every plain old RSS feed will do, but
* calendar RSS feeds should work ok.
* Before anyone complains that I should have used a readily available RSS parser library, I tried almost
* every one I could find on ... |
public getEvents = (): Promise<ICalendarEvent[]> => {
const parameterizedFeedUrl: string = this.getCORSUrl(this.replaceTokens(this.FeedUrl, this.EventRange));
let parser = new RSSParser();
return parser.parseURL(parameterizedFeedUrl).then(feed => {
let events: ICalendarEvent[] = feed.items.map(i... | {
super();
this.Name = "RSS";
} | identifier_body |
RSSCalendarService.ts | /**
* RSS Calendar Service
* Renders events from an RSS feed. It only renders events in the future, so not every plain old RSS feed will do, but
* calendar RSS feeds should work ok.
* Before anyone complains that I should have used a readily available RSS parser library, I tried almost
* every one I could find on ... | extends BaseCalendarService implements ICalendarService {
constructor() {
super();
this.Name = "RSS";
}
public getEvents = (): Promise<ICalendarEvent[]> => {
const parameterizedFeedUrl: string = this.getCORSUrl(this.replaceTokens(this.FeedUrl, this.EventRange));
let parser = new RSSParser();
... | RSSCalendarService | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.contenttypes.models
class | (migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='ContentType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_le... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.contenttypes.models
class Migration(migrations.Migration):
| ('objects', django.contrib.contenttypes.models.ContentTypeManager()),
],
),
migrations.AlterUniqueTogether(
name='contenttype',
unique_together=set([('app_label', 'model')]),
),
]
| dependencies = [
]
operations = [
migrations.CreateModel(
name='ContentType',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=100)),
(... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.contenttypes.models
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='ContentType',
fields=... | unique_together=set([('app_label', 'model')]),
),
] | name='contenttype', | random_line_split |
jquery.counter.js | /*! jQuery.counter.js (jQuery Character and Word Counter plugin)
v2.2 (c) Wilkins Fernandez
MIT License
*/
(function($) {
$.fn.extend({
counter : function(options) {
var defaults = {
type : 'char', // {char || word}
count : 'down', // count {up || down} from or to the goal number
... | }
},
/* Checks to see if the goal number has been reached */
isGoalReached : function(e, _goal) {
if(noLimit) {
return false;
}
// Counting down
if(options.count === defaults.count) {
_goal = 0;
return (countIn... | random_line_split | |
errno.rs | use imp::errno as errno;
const ZMQ_HAUSNUMERO: i32 = 156384712;
pub const EACCES: i32 = errno::EACCES;
pub const EADDRINUSE: i32 = errno::EADDRINUSE;
pub const EAGAIN: i32 = errno::EAGAIN;
pub const EBUSY: i32 = errno::EBUSY;
pub const ECONNREFUSED: i32 = errno::ECONNREFUSED;
... | pub const EPROTO: i32 = errno::EPROTO;
pub const EPROTONOSUPPORT: i32 = errno::EPROTONOSUPPORT;
#[cfg(not(target_os = "windows"))]
pub const ENOTSUP: i32 = (ZMQ_HAUSNUMERO + 1);
#[cfg(target_os = "windows")]
pub const ENOTSUP: i32 = errno::ENOTSUP;
pub const ENOBUFS: i32 = errno:... | random_line_split | |
inbox.test.ts | import { inbox } from "../../src/reducers/index";
import { Api } from "../../src/actions/api";
import { DEFAULT_TEST_TASK } from "../testUtils";
import { IGroupedTaskViewState } from "../../src/model/SerenityState";
import { TaskState } from "../../src/model/index";
const INBOX_GROUP_KEY = {
name: "Inbox",
};
descr... | expect(inbox(stateWithDefaultTestTask, Api.Task.successfulCreateAction(inboxTask2))).toEqual(stateWithInboxTask2);
});
const completedInboxTask2 = {...inboxTask2, completed: true};
const stateWithCompletedInboxTask2: IGroupedTaskViewState = {
incomplete: [DEFAULT_TEST_TASK.id],
completed: [completedI... | random_line_split | |
cohort-search.component.spec.tsx | import * as React from 'react';
import { MemoryRouter } from 'react-router';
import { mount } from 'enzyme';
import { CohortBuilderApi, CriteriaType, Domain } from 'generated/fetch';
import { registerApiClient } from 'app/services/swagger-fetch-clients';
import {
currentCohortCriteriaStore,
currentCohortSearchCon... | };
currentCohortCriteriaStore.next([selection]);
await waitOneTickAndUpdate(wrapper);
wrapper.find('[data-test-id="cohort-search-back-arrow"]').simulate('click');
expect(
wrapper.find('[data-test-id="cohort-search-unsaved-message"]').length
).toBeGreaterThan(0);
});
}); | wrapper.find('[data-test-id="cohort-search-unsaved-message"]').length
).toBe(0);
const selection = {
...CriteriaStubVariables[1],
parameterId: 'test param id', | random_line_split |
index-server.js | // Run only by vendor node.
// In an ideal world this would be run in the same process/context of
// atom-shell but there are many hurdles atm, see
// https://github.com/atom/atom-shell/issues/533
// increase the libuv threadpool size to 1.5x the number of logical CPUs.
process.env.UV_THREADPOOL_SIZE = Math.ceil(Math.... |
function finish(err) {
if (err) throw err;
server.emit('ready');
logger.debug('Mapbox Studio @ http://localhost:'+tm.config().port+'/');
}
| {
if (err) throw err;
server = require('./lib/server');
if (config.shell) {
server.listen(tm.config().port, '127.0.0.1', finish);
} else {
server.listen(tm.config().port, finish);
}
} | identifier_body |
index-server.js | // Run only by vendor node.
// In an ideal world this would be run in the same process/context of
// atom-shell but there are many hurdles atm, see
// https://github.com/atom/atom-shell/issues/533
// increase the libuv threadpool size to 1.5x the number of logical CPUs.
process.env.UV_THREADPOOL_SIZE = Math.ceil(Math.... | ''
, ' Usage: mbstudio [options]'
, ''
, ' where [options] is any of:'
, ' --version - Returns running version then exits'
, ' --port - Port to run on (default: ' + config.port + ')'
, ' --cwd - Working directory to run within (default: ' + config.cwd + ')'
// TODO - are the... | config.cwd = path.resolve(config.cwd || process.env.HOME);
var logger = require('fastlog')('', 'debug', '<${timestamp}>');
var usage = function usage() {
var str = [ | random_line_split |
index-server.js | // Run only by vendor node.
// In an ideal world this would be run in the same process/context of
// atom-shell but there are many hurdles atm, see
// https://github.com/atom/atom-shell/issues/533
// increase the libuv threadpool size to 1.5x the number of logical CPUs.
process.env.UV_THREADPOOL_SIZE = Math.ceil(Math.... | (err) {
if (err) throw err;
server = require('./lib/server');
if (config.shell) {
server.listen(tm.config().port, '127.0.0.1', finish);
} else {
server.listen(tm.config().port, finish);
}
}
function finish(err) {
if (err) throw err;
server.emit('ready');
logger.debug('Ma... | listen | identifier_name |
ripple-effect.tsx | import { Component, ComponentInterface, Element, Host, Method, Prop, h, readTask, writeTask } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
@Component({
tag: 'ion-ripple-effect',
styleUrl: 'ripple-effect.scss',
shadow: true
})
export class RippleEffect implements ComponentInterfa... |
render() {
const mode = getIonMode(this);
return (
<Host
role="presentation"
class={{
[mode]: true,
'unbounded': this.unbounded
}}
>
</Host>
);
}
}
const removeRipple = (ripple: HTMLElement) => {
ripple.classList.add('fade-out');
setTi... | {
return this.type === 'unbounded';
} | identifier_body |
ripple-effect.tsx | import { Component, ComponentInterface, Element, Host, Method, Prop, h, readTask, writeTask } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
@Component({
tag: 'ion-ripple-effect',
styleUrl: 'ripple-effect.scss',
shadow: true
})
export class RippleEffect implements ComponentInterfa... | () {
const mode = getIonMode(this);
return (
<Host
role="presentation"
class={{
[mode]: true,
'unbounded': this.unbounded
}}
>
</Host>
);
}
}
const removeRipple = (ripple: HTMLElement) => {
ripple.classList.add('fade-out');
setTimeout(() =... | render | identifier_name |
ripple-effect.tsx | import { Component, ComponentInterface, Element, Host, Method, Prop, h, readTask, writeTask } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
@Component({
tag: 'ion-ripple-effect',
styleUrl: 'ripple-effect.scss',
shadow: true
})
export class RippleEffect implements ComponentInterfa... |
const styleX = posX - initialSize * 0.5;
const styleY = posY - initialSize * 0.5;
const moveX = width * 0.5 - posX;
const moveY = height * 0.5 - posY;
writeTask(() => {
const div = document.createElement('div');
div.classList.add('ripple-effect');
... | {
posX = width * 0.5;
posY = height * 0.5;
} | conditional_block |
ripple-effect.tsx | import { Component, ComponentInterface, Element, Host, Method, Prop, h, readTask, writeTask } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
@Component({
tag: 'ion-ripple-effect',
styleUrl: 'ripple-effect.scss',
shadow: true
})
export class RippleEffect implements ComponentInterfa... | }, 200);
};
const PADDING = 10;
const INITIAL_ORIGIN_SCALE = 0.5; | random_line_split | |
primitive_reuse_peer.rs | extern crate futures;
extern crate tokio_io;
use futures::future::ok;
use std::cell::RefCell;
use std::rc::Rc;
use super::{BoxedNewPeerFuture, Peer};
use std::io::{Error as IoError, Read, Write};
use tokio_io::{AsyncRead, AsyncWrite};
use super::{once, ConstructParams, PeerConstructor, Specifier};
use futures::Futu... | else {
unreachable!()
}
}
}
impl AsyncRead for PeerHandle {}
impl Write for PeerHandle {
fn write(&mut self, b: &[u8]) -> Result<usize, IoError> {
if let Some(ref mut x) = *self.0.borrow_mut().deref_mut() {
x.1.write(b)
} else {
unreachable!()
... | {
x.0.read(b)
} | conditional_block |
primitive_reuse_peer.rs | extern crate futures;
extern crate tokio_io;
use futures::future::ok;
use std::cell::RefCell;
use std::rc::Rc;
use super::{BoxedNewPeerFuture, Peer};
| use std::ops::DerefMut;
#[derive(Debug)]
pub struct Reuser(pub Rc<dyn Specifier>);
impl Specifier for Reuser {
fn construct(&self, p: ConstructParams) -> PeerConstructor {
let send_zero_msg_on_disconnect = p.program_options.reuser_send_zero_msg_on_disconnect;
let reuser = p.global(GlobalState::defa... | use std::io::{Error as IoError, Read, Write};
use tokio_io::{AsyncRead, AsyncWrite};
use super::{once, ConstructParams, PeerConstructor, Specifier};
use futures::Future; | random_line_split |
primitive_reuse_peer.rs | extern crate futures;
extern crate tokio_io;
use futures::future::ok;
use std::cell::RefCell;
use std::rc::Rc;
use super::{BoxedNewPeerFuture, Peer};
use std::io::{Error as IoError, Read, Write};
use tokio_io::{AsyncRead, AsyncWrite};
use super::{once, ConstructParams, PeerConstructor, Specifier};
use futures::Futu... |
specifier_boilerplate!(singleconnect has_subspec globalstate);
self_0_is_subspecifier!(...);
}
specifier_class!(
name = ReuserClass,
target = Reuser,
prefixes = ["reuse-raw:", "raw-reuse:"],
arg_handling = subspec,
overlay = true,
MessageBoundaryStatusDependsOnInnerType,
SingleConn... | {
let send_zero_msg_on_disconnect = p.program_options.reuser_send_zero_msg_on_disconnect;
let reuser = p.global(GlobalState::default).clone();
let mut reuser = reuser.clone();
let l2r = p.left_to_right.clone();
let inner = || self.0.construct(p).get_only_first_conn(l2r);
... | identifier_body |
primitive_reuse_peer.rs | extern crate futures;
extern crate tokio_io;
use futures::future::ok;
use std::cell::RefCell;
use std::rc::Rc;
use super::{BoxedNewPeerFuture, Peer};
use std::io::{Error as IoError, Read, Write};
use tokio_io::{AsyncRead, AsyncWrite};
use super::{once, ConstructParams, PeerConstructor, Specifier};
use futures::Futu... | (&mut self) -> futures::Poll<(), IoError> {
if self.1 {
let _ = self.write(b"");
}
if let Some(ref mut _x) = *self.0.borrow_mut().deref_mut() {
// Ignore shutdown attempts
Ok(futures::Async::Ready(()))
//_x.1.shutdown()
} else {
unr... | shutdown | identifier_name |
derive_from_xml_stream.rs | #[macro_use]
extern crate mws_derive;
#[macro_use]
extern crate mws;
extern crate chrono;
use chrono::{DateTime, Utc};
pub use mws::{result, xmlhelper};
#[test]
fn derive_struct() {
#[derive(Debug, PartialEq, Default, FromXmlStream)]
struct S {
a: String,
b: i32,
date: Option<DateTime<Utc>>,
}
te... | Units: String,
#[from_xml_stream(from_content)]
Value: String,
}
#[derive(Debug, PartialEq, Default, FromXmlStream)]
struct ItemDimensions {
Height: Value,
Length: Value,
Width: Value,
}
#[derive(Debug, PartialEq, Default, FromXmlStream)]
struct Products {
ItemDimensions: ItemD... | struct Value {
#[from_xml_stream(from_attr)] | random_line_split |
derive_from_xml_stream.rs | #[macro_use]
extern crate mws_derive;
#[macro_use]
extern crate mws;
extern crate chrono;
use chrono::{DateTime, Utc};
pub use mws::{result, xmlhelper};
#[test]
fn | () {
#[derive(Debug, PartialEq, Default, FromXmlStream)]
struct S {
a: String,
b: i32,
date: Option<DateTime<Utc>>,
}
test_decode!(
S,
r#"
<a>AAA</a>
<b>777</b>
<date>2016-11-03T00:09:40Z</date>
"#,
S {
a: "AAA".to_owned(),
b: 777,
date: Some("201... | derive_struct | identifier_name |
test.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | realf(); // $ExpectError
realf( new Complex64( 5.0, 3.0 ), 123 ); // $ExpectError
} | { | random_line_split |
gen_ic.py | # This file has to be run in pure Python mode!
# Imports from the CO𝘕CEPT code
from commons import *
from species import Component
from snapshot import save
# Create stationary, homogeneous matter distribution,
# perturbed with global, stationary sine wave along
# the x-direction.
w = user_params['_w']
ρ0 = user_pa... | # Save snapshot
save(component, initial_conditions) | for multi_index in component.J.multi_indices:
component.populate(zeros([gridsize]*3, dtype=float), 'J', multi_index)
for multi_index in component.ς.multi_indices:
component.populate(ones([gridsize]*3)*ρ*(1 + w)*σ, 'ς', multi_index)
| random_line_split |
gen_ic.py | # This file has to be run in pure Python mode!
# Imports from the CO𝘕CEPT code
from commons import *
from species import Component
from snapshot import save
# Create stationary, homogeneous matter distribution,
# perturbed with global, stationary sine wave along
# the x-direction.
w = user_params['_w']
ρ0 = user_pa... |
save(component, initial_conditions)
| late(ones([gridsize]*3)*ρ*(1 + w)*σ, 'ς', multi_index)
# Save snapshot | conditional_block |
app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import {RouterModule} from '@angular/router';
import {HttpModule} from '@angular/http';
import { AppComponent } from './app.component';
import { HeroDetailComponent } ... | { }
| AppModule | identifier_name |
app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import {RouterModule} from '@angular/router';
import {HttpModule} from '@angular/http'; |
import { AppComponent } from './app.component';
import { HeroDetailComponent } from './hero-detail.component';
import {HeroesComponent} from './heroes.component';
import {HeroService} from './hero.service';
import {DashboardComponent} from './dashboard.component';
@NgModule({
imports: [
BrowserMod... | random_line_split | |
15.2.3.3-2-28.js | /// Copyright (c) 2009 Microsoft Corporation
///
/// 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 of conditions and
/// ... | ES5Harness.registerTest({
id: "15.2.3.3-2-28",
path: "TestCases/chapter15/15.2/15.2.3/15.2.3.3/15.2.3.3-2-28.js",
description: "Object.getOwnPropertyDescriptor - argument 'P' is an integer that converts to a string (value is 123)",
test: function testcase() {
var obj = { "123": 1 };
... | /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
/// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
/// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| random_line_split |
itorndb.py | #!/usr/bin/env python
# coding=utf-8
"""围绕mysql官方python数据库驱动,对torndb极简改造
torndb原为facebook/tornado的一部分,自3.0版本后已经剥离成独立的开源项目"""
from __future__ import absolute_import, division, with_statement
import copy
import itertools
import logging
import os
import time
try:
from mysql import connector
except ImportError:
... | ute(cursor, query, args, kwargs)
column_names = [d[0] for d in cursor.description]
return [Row(itertools.izip(column_names, row)) for row in cursor]
finally:
cursor.close()
def get(self, query, *args, **kwargs):
"""返回唯一的查询结果"""
rows = self.query(query, *a... | try:
self._exec | conditional_block |
itorndb.py | #!/usr/bin/env python
# coding=utf-8
"""围绕mysql官方python数据库驱动,对torndb极简改造
torndb原为facebook/tornado的一部分,自3.0版本后已经剥离成独立的开源项目"""
from __future__ import absolute_import, division, with_statement
import copy
import itertools
import logging
import os
import time
try:
from mysql import connector
except ImportError:
... | self.reconnect()
except Exception:
logging.error("Cannot connect to MySQL on %s", self.host,
exc_info=True)
def __del__(self):
self.close()
def close(self):
"""关闭数据库连接"""
if getattr(self, "_db", None) is not None:
se... | args.get('host', '127.0.0.1')
self.database = kwargs.get('database', 'test')
self.port = int(kwargs.get('port', 3306))
self._user = kwargs.get('user', None)
self._passwd = kwargs.get(
'password', kwargs.get('passwd', None))
self.max_idle_time = float(kwargs.get('max_i... | identifier_body |
itorndb.py | #!/usr/bin/env python
# coding=utf-8
"""围绕mysql官方python数据库驱动,对torndb极简改造
torndb原为facebook/tornado的一部分,自3.0版本后已经剥离成独立的开源项目"""
from __future__ import absolute_import, division, with_statement
import copy
import itertools
import logging
import os
import time
try:
from mysql import connector
except ImportError:
... | r(self, "_db", None) is not None:
self._db.close()
self._db = None
def commit(self):
"""数据库操作提交"""
if getattr(self, "_db", None) is not None:
self._db.commit()
def rollback(self):
"""数据库操作回滚"""
if getattr(self, "_db", None) is not None:
... | getatt | identifier_name |
itorndb.py | #!/usr/bin/env python
# coding=utf-8
"""围绕mysql官方python数据库驱动,对torndb极简改造
torndb原为facebook/tornado的一部分,自3.0版本后已经剥离成独立的开源项目""" | import itertools
import logging
import os
import time
try:
from mysql import connector
except ImportError:
connector = None
version = "0.1"
version_info = (0, 1, 0, 0)
class Connection(object):
"""mysql连接轻量级工具"""
def __init__(self, **kwargs):
self.host = kwargs.get('host', '127.0.0.1')
... |
from __future__ import absolute_import, division, with_statement
import copy | random_line_split |
PersistenceEngine.py | import os
import sys
import time
'''
@author: msune,omoya,CarolinaFernandez
@@organization: i2CAT, OFELIA FP7
Persistence engine
Implementes driver-based persistence backend selection
'''
class PersistenceEngine():
#Default Class Attributes
_defaultParser = "RegexParser"
_defaultPersistence = ... |
@staticmethod
def load(tableName, pBackend, resolverMappings, parser=None, **kwargs):
return PersistenceEngine._getDriver(pBackend).load(tableName, resolverMappings, parser, **kwargs)
'''
Retrieves every Driver's PolicyRuleTable object for a given name.
This method should be seldom used.
... | return PersistenceEngine._getDriver(pBackend).save(obj, parser, **kwargs) | identifier_body |
PersistenceEngine.py | import os
import sys
import time
'''
@author: msune,omoya,CarolinaFernandez
@@organization: i2CAT, OFELIA FP7
Persistence engine
Implementes driver-based persistence backend selection
'''
class PersistenceEngine():
#Default Class Attributes
_defaultParser = "RegexParser"
_defaultPersistence = ... | except:
raise Exception(driverName + ' persistence driver not found in ' + PersistenceEngine.PATH_TO_DRIVERS)
elif driverName == "RAWFile":
PATH = PersistenceEngine.PATH_TO_DRIVERS + '.rawfile.RAWFile'
try:
exec('from ' + PATH + ' import RAWFile')
return RAWFile
except:
raise Exception(dri... | random_line_split | |
PersistenceEngine.py | import os
import sys
import time
'''
@author: msune,omoya,CarolinaFernandez
@@organization: i2CAT, OFELIA FP7
Persistence engine
Implementes driver-based persistence backend selection
'''
class | ():
#Default Class Attributes
_defaultParser = "RegexParser"
_defaultPersistence = "Django"
#Drivers
_drivers = ["Django","RAWFile"]
#Fill with appropiate path
PATH_TO_DRIVERS="backends"
def __init__(self):
raise Exception("Static class cannot be instanciated")
@staticmethod
def _getDriver(drive... | PersistenceEngine | identifier_name |
PersistenceEngine.py | import os
import sys
import time
'''
@author: msune,omoya,CarolinaFernandez
@@organization: i2CAT, OFELIA FP7
Persistence engine
Implementes driver-based persistence backend selection
'''
class PersistenceEngine():
#Default Class Attributes
_defaultParser = "RegexParser"
_defaultPersistence = ... |
@staticmethod
def save(obj, pBackend, parser=None, **kwargs):
return PersistenceEngine._getDriver(pBackend).save(obj, parser, **kwargs)
@staticmethod
def load(tableName, pBackend, resolverMappings, parser=None, **kwargs):
return PersistenceEngine._getDriver(pBackend).load(tableName, resolverMappings, parser,... | raise Exception(driverName + ' not supported') | conditional_block |
OutputTemplateBase.ts | import { Type } from 'class-transformer';
import { IsArray, IsBooleanOrInstance, IsInstance, IsOptional, ValidateNested } from '..';
import { TransformMessage } from '../decorators/transformation/TransformMessage';
import { IsStringOrInstance } from '../decorators/validation/IsStringOrInstance';
import { Card } from '.... | {
[key: string]: unknown;
@IsOptional()
@IsStringOrInstance(Message)
@TransformMessage()
message?: MessageValue;
@IsOptional()
@IsStringOrInstance(Message)
@Type(() => Message)
reprompt?: MessageValue;
@IsOptional()
@IsBooleanOrInstance(Listen)
@Type(() => Listen)
listen?: ListenValue;
... | OutputTemplateBase | identifier_name |
OutputTemplateBase.ts | import { Type } from 'class-transformer';
import { IsArray, IsBooleanOrInstance, IsInstance, IsOptional, ValidateNested } from '..';
import { TransformMessage } from '../decorators/transformation/TransformMessage';
import { IsStringOrInstance } from '../decorators/validation/IsStringOrInstance';
import { Card } from '.... | card?: Card;
@IsOptional()
@IsInstance(Carousel)
@ValidateNested()
@Type(() => Carousel)
carousel?: Carousel;
} | @ValidateNested()
@Type(() => Card) | random_line_split |
colon.py | #!/usr/bin/python3
"""Punctuation rules around colons and semi-colons."""
import wlint.punctuation
def | (name, colon):
rules = []
# a colon might be followed by a digit if it's time
if name == "colon":
rules.append(("{}.missing-space".format(name),
wlint.punctuation.make_pair_regex_rule(colon,
"[^\\s\\d]")))
elif na... | _colon_rule | identifier_name |
colon.py | #!/usr/bin/python3
"""Punctuation rules around colons and semi-colons."""
import wlint.punctuation
def _colon_rule(name, colon):
rules = []
# a colon might be followed by a digit if it's time
if name == "colon":
rules.append(("{}.missing-space".format(name),
wlint.punctuati... |
rules.append(("{}.preceeding-space".format(name),
wlint.punctuation.make_pair_regex_rule("\\s", colon)))
return rules
def _get_colon_rules():
rules = []
rules += _colon_rule("colon", ":")
rules += _colon_rule("semicolon", ";")
return rules
_COLON_RULES = _get_colon_rule... | rules.append(("{}.missing-space".format(name),
wlint.punctuation.make_pair_regex_rule(colon,
"\\S"))) | conditional_block |
colon.py | #!/usr/bin/python3
"""Punctuation rules around colons and semi-colons."""
import wlint.punctuation
def _colon_rule(name, colon):
rules = []
# a colon might be followed by a digit if it's time
if name == "colon":
rules.append(("{}.missing-space".format(name),
wlint.punctuati... | rules += _colon_rule("colon", ":")
rules += _colon_rule("semicolon", ";")
return rules
_COLON_RULES = _get_colon_rules() | def _get_colon_rules():
rules = [] | random_line_split |
colon.py | #!/usr/bin/python3
"""Punctuation rules around colons and semi-colons."""
import wlint.punctuation
def _colon_rule(name, colon):
rules = []
# a colon might be followed by a digit if it's time
if name == "colon":
rules.append(("{}.missing-space".format(name),
wlint.punctuati... |
_COLON_RULES = _get_colon_rules()
| rules = []
rules += _colon_rule("colon", ":")
rules += _colon_rule("semicolon", ";")
return rules | identifier_body |
index.js | var events = require('events'),
Event = new events.EventEmitter(),
moment = require('moment-timezone');
var App = {
"bot": global.Configuration.bot,
"Event": Event,
"Package": (function() {
var package = require('../package.json');
return {
"version": package.version,
"name": package... |
}
};
}());
| {
plugins[plugin](action, data, method);
} | conditional_block |
index.js | var events = require('events'),
Event = new events.EventEmitter(),
moment = require('moment-timezone');
var App = {
"bot": global.Configuration.bot,
"Event": Event,
"Package": (function() {
var package = require('../package.json');
return {
"version": package.version,
"name": package... | App,
function() {
var args = Array.prototype.slice.call(arguments);
// Add plugin name as sender
args.unshift('<' + plugin.name + '>');
// Add timestamp
args.unshift('[' + moment().format('YYYY-MM-DD hh:mma (ss.SSS)') + ']');
console.log.apply(null, args);
}
);
return... | var plugins = {};
global.Configuration.plugins.map(function(plugin) {
plugins[plugin.name] = require('./plugins/' + plugin.name)(
plugin.configuration, | random_line_split |
scmstore.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 std::io::Write;
use async_runtime::block_on;
use async_runtime::stream_to_iter as block_on_stream;
use clidispatch::errors;
use config... |
pub fn name() -> &'static str {
"debugscmstore"
}
pub fn doc() -> &'static str {
"test file and tree fetching using scmstore"
}
| {
let mut tree_builder = TreeStoreBuilder::new(config);
tree_builder = tree_builder.suffix("manifests");
let store = tree_builder.build()?;
let mut stdout = io.output();
let fetch_result = store.fetch_batch(keys.into_iter())?;
let (found, missing, _errors) = fetch_result.consume();
for co... | identifier_body |
scmstore.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 std::io::Write;
use async_runtime::block_on;
use async_runtime::stream_to_iter as block_on_stream;
use clidispatch::errors;
use config... | (opts: DebugScmStoreOpts, io: &IO, repo: Repo) -> Result<u8> {
if opts.python {
return Err(errors::FallbackToPython.into());
}
let mode = match opts.mode.as_ref() {
"file" => FetchMode::File,
"tree" => FetchMode::Tree,
_ => return Err(errors::Abort("'mode' must be one of 'fi... | run | identifier_name |
scmstore.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 std::io::Write;
use async_runtime::block_on;
use async_runtime::stream_to_iter as block_on_stream;
use clidispatch::errors;
use config... | Ok(())
}
pub fn name() -> &'static str {
"debugscmstore"
}
pub fn doc() -> &'static str {
"test file and tree fetching using scmstore"
} | random_line_split | |
wsgi.py | """
WSGI config for {{ project_name }} project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APP... | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "push_and_pull.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsg... | # Add the app code to the path
#sys.path.append(PROJECT_ROOT)
os.environ['CELERY_LOADER'] = 'django' | random_line_split |
PhoneticExtensions.js | *
* Copyright (c) 2009-2017 The MathJax Consortium
*
* 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 ap... | /*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/General/Regular/PhoneticExtensions.js | random_line_split | |
openvswitch_bridge.py | #!/usr/bin/python
#coding: utf-8 -*-
# (c) 2013, David Stygstra <david.stygstra@gmail.com>
#
# Portions copyright @ 2015 VMware, Inc.
#
# This file is part of Ansible
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... | changed = True
##
# Check if external ids would change.
current_external_ids = self.get_external_ids()
exp_external_ids = self.module.params['external_ids']
if exp_external_ids is not None:
for (key,... | (self.fail_mode != self.get_fail_mode())): | random_line_split |
openvswitch_bridge.py | #!/usr/bin/python
#coding: utf-8 -*-
# (c) 2013, David Stygstra <david.stygstra@gmail.com>
#
# Portions copyright @ 2015 VMware, Inc.
#
# This file is part of Ansible
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... | (self):
'''Create the bridge'''
rtc, _, err = self._vsctl(['add-br', self.bridge])
if rtc != 0:
self.module.fail_json(msg=err)
if self.fail_mode:
self.set_fail_mode()
def delete(self):
'''Delete the bridge'''
rtc, _, err = self._vsctl(['del-br... | add | identifier_name |
openvswitch_bridge.py | #!/usr/bin/python
#coding: utf-8 -*-
# (c) 2013, David Stygstra <david.stygstra@gmail.com>
#
# Portions copyright @ 2015 VMware, Inc.
#
# This file is part of Ansible
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... |
def set_fail_mode(self):
""" Set failure mode. """
if self.exists():
(rtc, _, err) = self._vsctl(['set-fail-mode', self.bridge,
self.fail_mode])
if rtc != 0:
self.module.fail_json(msg=err)
# pylint: disable=E0602
d... | """ Get failure mode. """
value = ''
if self.exists():
rtc, out, err = self._vsctl(['get-fail-mode', self.bridge])
if rtc != 0:
self.module.fail_json(msg=err)
value = out.strip("\n")
return value | identifier_body |
openvswitch_bridge.py | #!/usr/bin/python
#coding: utf-8 -*-
# (c) 2013, David Stygstra <david.stygstra@gmail.com>
#
# Portions copyright @ 2015 VMware, Inc.
#
# This file is part of Ansible
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Fre... |
elif self.state == 'present':
if not self.exists():
self.add()
changed = True
current_fail_mode = self.get_fail_mode()
if self.fail_mode and (self.fail_mode != current_fail_mode):
self.module.log( ... | self.delete()
changed = True | conditional_block |
field.rs | use std::str::FromStr;
use crate::parsers::parser;
use crate::parsers::sql::Env;
use crate::parsers::sql::Expr;
use crate::parsers::value::PqlValue;
#[derive(Debug, Default, Clone, PartialEq)]
pub struct | {
pub expr: Expr,
pub alias: Option<String>,
}
impl FromStr for Field {
type Err = anyhow::Error;
fn from_str(s: &str) -> anyhow::Result<Self> {
match parser::expressions::parse_field(s) {
Ok((_, field)) => Ok(field),
Err(nom::Err::Error(err)) => {
epri... | Field | identifier_name |
field.rs | use std::str::FromStr;
use crate::parsers::parser;
use crate::parsers::sql::Env;
use crate::parsers::sql::Expr;
use crate::parsers::value::PqlValue;
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Field {
pub expr: Expr,
pub alias: Option<String>,
}
impl FromStr for Field {
type Err = anyhow::Erro... | pub fn evaluate(self, env: &Env) -> PqlValue {
let value = self.expr.eval(&env);
value
}
pub fn rename(self) -> (String, Expr) {
if let Some(alias) = self.alias {
(alias, self.expr)
} else {
let alias = match &self.expr {
Expr::Selecto... | }
| random_line_split |
dashboard.component.ts | import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { SessionService } from '../../core/session/session.service';
import { IdleService } from '..... |
}
| this.logService.log('ngOnDestroy');
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
| identifier_body |
dashboard.component.ts | import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { SessionService } from '../../core/session/session.service';
import { IdleService } from '..... | mplements OnInit, OnDestroy {
constituentDomain$: Observable<ConstituentDomains>;
contactEventDomain$: Observable<ConstituentDomains>;
status$: Observable<ResponseStatus>;
ngUnsubscribe: Subject<void> = new Subject<void>();
constructor(private router: Router,
private sessionService: SessionService,
p... | shboardComponent i | identifier_name |
dashboard.component.ts | import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { SessionService } from '../../core/session/session.service';
import { IdleService } from '..... | import { MdSnackBar, MdSnackBarConfig } from '@angular/material';
import { DomainStoreService } from '../../state/store-services/domain-store.service';
import { DomainEnum } from '../../state/resources/resource.service';
import { ContactEventDomains } from '../../models/contact-events/domains/contact-event-domains.mode... | import { LogService } from '../../core/logging/log.service';
import { StatusStoreService } from '../../state/store-services/status-store.service';
import { ResponseStatus } from '../../core/models/request-response.models'; | random_line_split |
dashboard.component.ts | import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { SessionService } from '../../core/session/session.service';
import { IdleService } from '..... | }
}
logout() {
this.sessionService.logout();
this.idleService.stop();
}
ngOnDestroy() {
this.logService.log('ngOnDestroy');
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
| this.snackBar.open(status.message, 'OK', config);
}
| conditional_block |
businessarea.model.ts | import { JSONAPIResourceObject } from '../jsonapi/jsonapi-resource-object.model';
import { | name?: string;
reference?: string;
crossReference?: string;
description?: string;
color?: string;
date?: string;
status?: number;
commercialStatus?: number;
isAggregationEnabled?: boolean;
isNormalizationEnabled?: boolean;
updatedAt?: number;
}
export interface IBusinessareaRelationships {
inst... | JSONAPIToOneRelationshipObject,
JSONAPIToManyRelationshipObject
} from '../jsonapi/jsonapi-relationships-object.model';
export interface IBusinessareaAttributes { | random_line_split |
default.py | """
Default experiment for clean smp
Should be self-contained requiring now external packages or processes.
Robot: Point mass
World: open linear (1D) space
Task: null task: task performance is always null no matter what
Brain: null brain: just output null
Loss: 0
"""
import time
from smq.utils import make_column_... | } | ], | random_line_split |
AnchorLayout.js | <p>This is a layout that enables anchoring of contained elements relative to the container's dimensions.
* If the container is resized, all anchored items are automatically rerendered according to their
* <b><tt>{@link #anchor}</tt></b> rules.</p>
* <p>This class is intended to be extended or created via the layout... |
if (overflow && overflow != 'hidden' && !this.adjustmentPass) {
var newTargetSize = this.getLayoutTargetSize();
if (newTargetSize.width != size.width || newTargetSize.height != size.height){
this.adjustmentPass = true;
this.onLayout(container, target);
... | {
box = boxes[i];
box.component.setSize(box.width, box.height);
} | conditional_block |
AnchorLayout.js | * <p>This is a layout that enables anchoring of contained elements relative to the container's dimensions.
* If the container is resized, all anchored items are automatically rerendered according to their
* <b><tt>{@link #anchor}</tt></b> rules.</p>
* <p>This class is intended to be extended or created via the layo... |
// private
onLayout : function(container, target) {
Ext.layout.AnchorLayout.superclass.onLayout.call(this, container, target);
var size = this.getLayoutTargetSize(),
containerWidth = size.width,
containerHeight = size.height,
overflow = target.getStyle('over... | ret.width -= target.getPadding('lr');
ret.height -= target.getPadding('tb');
}
return ret;
}, | random_line_split |
fetch.ts | ') {
value = String(value);
}
return value;
}
function Headers ( headers?: any ): void {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (headers) {
Object.getOwnPropertyName... | }
// Avoid security warnings on getResponseHeader when not allowed by CORS
if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
return xhr.getResponseHeader('X-Request-URL');
}
return;
}
// Enable timeout:
var reqTimeout;
if (init && init... | random_line_split | |
fetch.ts | ') {
value = String(value);
}
return value;
}
function Headers ( headers?: any ): void {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (headers) {
Object.getOwnPropertyName... |
this._initBody(bodyInit);
this.type = 'default';
this.url = null;
this.status = options.status;
this.ok = this.status >= 200 && this.status < 300;
this.statusText = options.statusText;
this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
t... | {
options = {};
} | conditional_block |
fetch.ts | ') {
value = String(value);
}
return value;
}
function Headers ( headers?: any ): void {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (headers) {
Object.getOwnPropertyName... | ( blob ): Promise<any> {
var reader = new FileReader();
reader.readAsText(blob);
return fileReaderReady(reader);
}
var support = {
blob: 'FileReader' in self && 'Blob' in self && (function() {
try {
new Blob();
return true;
} catch(e) {
return false;
}
... | readBlobAsText | identifier_name |
fetch.ts | ') {
value = String(value);
}
return value;
}
function Headers ( headers?: any ): void {
this.map = {};
if (headers instanceof Headers) {
headers.forEach(function(value, name) {
this.append(name, value);
}, this);
} else if (headers) {
Object.getOwnPropertyName... |
function readBlobAsArrayBuffer ( blob ): Promise<any> {
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
return fileReaderReady(reader);
}
function readBlobAsText ( blob ): Promise<any> {
var reader = new FileReader();
reader.readAsText(blob);
return fileReaderReady(reader... | {
return new Promise(function(resolve, reject) {
reader.onload = function() {
resolve(reader.result);
}
reader.onerror = function() {
reject(reader.error);
}
});
} | identifier_body |
BezierPoint.ts | /*
* Copyright 2017 András Parditka.
*
* This file is part of Ecset.
*
* Ecset 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.
... | {
constructor(
public handleIn: Point,
public center: Point,
public handleOut: Point,
public id?: string,
) {
}
}
| ezierPoint | identifier_name |
BezierPoint.ts | /*
* Copyright 2017 András Parditka.
*
* This file is part of Ecset.
*
* Ecset 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.
... | }
|
}
| identifier_body |
BezierPoint.ts | /*
* Copyright 2017 András Parditka.
*
* This file is part of Ecset.
*
* Ecset 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.
... | public id?: string,
) {
}
} | random_line_split | |
garden_real.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pythymio
import random
from gardenworld import *
init('info2_1')
with pythymio.thymio(["acc"],[]) as Thym:
state = dict([])
state["time"] = 0
state["delay"] = 10
def | (evtid, evt_name, evt_args):
# https://www.thymio.org/en:thymioapi prox freq is 16Hz
if evt_name == "fwd.acc": # every 0.0625 sec
state["time"] += 0.0625
state["delay"] -= 1
if state["delay"] < 0:
if 7 < evt_args[1] < 14:
if evt_ar... | dispatch | identifier_name |
garden_real.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pythymio
import random
from gardenworld import *
init('info2_1')
with pythymio.thymio(["acc"],[]) as Thym:
state = dict([])
state["time"] = 0
state["delay"] = 10
def dispatch(evtid, evt_name, evt_args):
# https://www.thymio.org/en:thymioapi pr... |
else: # Wat?
print evt_name
# Now lets start the loopy thing
Thym.loop(dispatch)
print "state is %s" % state
print "Sayonara"
| if evt_args[0] > 10:
state["delay"] = 20
dp()
elif evt_args[0] < -10:
state["delay"] = 20
ra() | conditional_block |
garden_real.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pythymio
import random
from gardenworld import *
init('info2_1')
with pythymio.thymio(["acc"],[]) as Thym:
state = dict([])
state["time"] = 0
state["delay"] = 10
def dispatch(evtid, evt_name, evt_args):
# https://www.thymio.org/en:thymioapi pr... | ra()
else: # Wat?
print evt_name
# Now lets start the loopy thing
Thym.loop(dispatch)
print "state is %s" % state
print "Sayonara"
| if evt_name == "fwd.acc": # every 0.0625 sec
state["time"] += 0.0625
state["delay"] -= 1
if state["delay"] < 0:
if 7 < evt_args[1] < 14:
if evt_args[0] > 10:
state["delay"] = 20
tg()
... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.