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 |
|---|---|---|---|---|
conversation.ts | import * as models from "../models/models";
import * as jibe from '../service/jibe';
import * as logger from '../service/logger';
import * as drillplan from "../plugins/drillplan"
import * as botbuilder from 'botbuilder'
// Define an object for storing subscription information
class Subscription {
project: string... | (project: models.ProjectInfo, channelId: string, eventName: string) {
// look up event info in the events array
let event = drillplan.events.find((element) => {
return element.name === eventName;
});
if (!event) {
logger.Info("Unknown event requested: " + eventName);
return;
... | removeRoute | identifier_name |
conversation.ts | import * as models from "../models/models";
import * as jibe from '../service/jibe';
import * as logger from '../service/logger';
import * as drillplan from "../plugins/drillplan"
import * as botbuilder from 'botbuilder'
// Define an object for storing subscription information
class Subscription {
project: string... | botaddress: botaddress
}));
} else {
// add botaddress to an existing channel object
project.channels[chindex].botaddress = botaddress;
}
}
// Add a route to the given project
function addRoute(project: models.ProjectInfo, channelId: string, eventName: string) {
// look... | name: "",
id: channelId,
webhook: "", | random_line_split |
conversation.ts | import * as models from "../models/models";
import * as jibe from '../service/jibe';
import * as logger from '../service/logger';
import * as drillplan from "../plugins/drillplan"
import * as botbuilder from 'botbuilder'
// Define an object for storing subscription information
class Subscription {
project: string... |
// Retrieve list of subscriptions for a single project
async function getProjectSubscriptions(channelId: string, projectId: string): Promise<string[]> {
let project = await jibe.getProject(projectId);
return extractChannelSubscriptions(project, channelId);
}
// Retrieves the projectId of the project with the... | {
// fetch projects
let projects = await jibe.getProjectList();
// Generate subscription list for this channel
let subscriptions = projects.map((p) => {
let sub = new Subscription();
sub.project = p.name;
// retrieve routes to the specified channel
sub.events = extract... | identifier_body |
IndexedDictionary.ts | import * as Collections from 'typescript-collections';
export class IndexedDictionary<TKey, TValue> extends Collections.Dictionary<TKey, TValue> {
private _replaceDuplicateKeys: boolean;
private _throwErrorOnInvalidRemove: boolean;
protected internalKeys: Set<TKey> = new Set<TKey>();
constructor ()... |
public get replaceDuplicateKeys(): boolean {
return this._replaceDuplicateKeys;
}
public set replaceDuplicateKeys(value: boolean) {
this._replaceDuplicateKeys = value;
}
public get ThrowErrorOnInvalidRemove(): boolean
{
return this._throwErrorOnInvalidRemove;
... | {
return key;
} | identifier_body |
IndexedDictionary.ts | import * as Collections from 'typescript-collections';
export class IndexedDictionary<TKey, TValue> extends Collections.Dictionary<TKey, TValue> {
private _replaceDuplicateKeys: boolean;
private _throwErrorOnInvalidRemove: boolean;
protected internalKeys: Set<TKey> = new Set<TKey>();
constructor ()... | (key: TKey) {
return key;
}
public get replaceDuplicateKeys(): boolean {
return this._replaceDuplicateKeys;
}
public set replaceDuplicateKeys(value: boolean) {
this._replaceDuplicateKeys = value;
}
public get ThrowErrorOnInvalidRemove(): boolean
{
ret... | transformKey | identifier_name |
IndexedDictionary.ts | import * as Collections from 'typescript-collections';
export class IndexedDictionary<TKey, TValue> extends Collections.Dictionary<TKey, TValue> {
private _replaceDuplicateKeys: boolean;
private _throwErrorOnInvalidRemove: boolean;
protected internalKeys: Set<TKey> = new Set<TKey>();
constructor ()... |
}
public contains(key: TKey): boolean {
return super.containsKey(this.transformKey(key));
}
protected transformKey(key: TKey) {
return key;
}
public get replaceDuplicateKeys(): boolean {
return this._replaceDuplicateKeys;
}
public set replaceDup... | public add(key:TKey, value: TValue): void {
}
public addAt(index: number, key:TKey, value: TValue): void { | random_line_split |
backbone_storage.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2015, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#----------------------------------------... |
def _modelkey(typename, docid, modelid):
docid = encode_utf8(docid)
modelid = encode_utf8(modelid)
return 'bbmodel:%s:%s:%s' % (typename, docid, modelid)
def _parse_modelkey(key):
_, typename, docid, modelid = decode_utf8(key).split(":")
return typename, docid, modelid | docid = encode_utf8('doc:' + docid)
return docid | identifier_body |
backbone_storage.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2015, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#----------------------------------------... | from bokeh import protocol
from bokeh.document import Document
from bokeh.util.serialization import dump
from bokeh.util.string import decode_utf8, encode_utf8
from .abstract_backbone_storage import AbstractBackboneStorage
class BackboneStorage(AbstractBackboneStorage):
"""
"""
def pull(self, docid, typ... |
import logging
logger = logging.getLogger(__name__)
| random_line_split |
backbone_storage.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2015, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#----------------------------------------... |
attrs = [protocol.serialize_json(attr['attributes']) for attr in jsonobjs]
dkey = _dockey(docid)
data = dict(zip(keys, attrs))
self.mset(data)
self.sadd(dkey, *keys)
def del_obj(self, docid, m):
mkey = _modelkey(m.__view_model__, docid, m._id)
self.srem(_doc... | attr['attributes']['doc'] = docid | conditional_block |
backbone_storage.py | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2015, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#----------------------------------------... | (self, docid, *jsonobjs):
keys = [_modelkey(attr['type'],
docid,
attr['attributes']['id']) for attr in jsonobjs]
for attr in jsonobjs:
attr['attributes']['doc'] = docid
attrs = [protocol.serialize_json(attr['attributes']) fo... | push | identifier_name |
RPM.js | var RPM=function() {
var newRPM={};
//STACK
//TODO: use a pre existing stack object
newRPM.stack=[];
newRPM.Push = function(value) {
this.stack.push(value);
};
newRPM.Pop = function() {
return this.stack.pop();
};
newRPM.Peek = function( distance ) {
return this.stack[this.stack.length-1 - di... |
},
'-' : function() {
this.Swap();
this.Push(this.Pop()-this.Pop());
},
'/' : function() {
this.Swap();
this.Push(this.Pop()*this.Pop());
},
'*' : function() {
this.Swap();
this.Push(this.Pop()*this.Pop());
},
//Stack
'swap' : function() {
... | {
this.Push(this.Pop()+this.Pop());
} | conditional_block |
RPM.js | var RPM=function() {
var newRPM={};
//STACK
//TODO: use a pre existing stack object
newRPM.stack=[];
newRPM.Push = function(value) {
this.stack.push(value);
};
newRPM.Pop = function() {
return this.stack.pop();
};
newRPM.Peek = function( distance ) {
return this.stack[this.stack.length-1 - di... |
//PUBLIC METHODS
newRPM.Step=function(iterations){
for( var i=0; i<iterations; i++ ){
var value=this.splitScript[this.current];
if(this.operators[value]!==undefined){
this.operators[value].call(this);
} else {
if(!isNaN(value)){
value= +value;
}
this.Pu... | }; | random_line_split |
InfiniteLoader.d.ts | import { PureComponent, Validator, Requireable } from 'react'
import { Index, IndexRange } from '../../index';
export type InfiniteLoaderChildProps = {
onRowsRendered: (params: { startIndex: number, stopIndex: number }) => void,
registerChild: (registeredChild: any) => void
}
export type InfiniteLoaderProps =... | loadMoreRows: (params: IndexRange) => Promise<any>;
/**
* Minimum number of rows to be loaded at a time.
* This property can be used to batch requests to reduce HTTP requests.
*/
minimumBatchSize?: number;
/**
* Number of rows in list; can be arbitrary high number if actual number is... | * It should implement the following signature: ({ startIndex, stopIndex }): Promise
* The returned Promise should be resolved once row data has finished loading.
* It will be used to determine when to refresh the list with the newly-loaded data.
* This callback may be called multiple times in reacti... | random_line_split |
InfiniteLoader.d.ts | import { PureComponent, Validator, Requireable } from 'react'
import { Index, IndexRange } from '../../index';
export type InfiniteLoaderChildProps = {
onRowsRendered: (params: { startIndex: number, stopIndex: number }) => void,
registerChild: (registeredChild: any) => void
}
export type InfiniteLoaderProps =... | extends PureComponent<InfiniteLoaderProps> {
static propTypes: {
children: Validator<(props: InfiniteLoaderChildProps) => React.ReactNode>,
isRowLoaded: Validator<(params: Index) => boolean>,
loadMoreRows: Validator<(params: IndexRange) => Promise<any>>,
minimumBatchSize: Validator<... | InfiniteLoader | identifier_name |
mehi_local.py | ###############################
# Author : septicmk
# Date : 2015/07/25 16:14:09
# FileName : main.py | ################################
from lambdaimage import preprocess as prep
from lambdaimage import registration as reg
from lambdaimage import fusion as fus
from pyspark import SparkContext, SparkConf
from lambdaimage import lambdaimageContext
from lambdaimage.utils.tool import exeTime, log, showsize
from parseXML im... | random_line_split | |
test_stream_wrappers.py | import unittest
from streamlink.stream import StreamIOIterWrapper
class TestPluginStream(unittest.TestCase):
def test_iter(self):
def generator():
|
fd = StreamIOIterWrapper(generator())
self.assertEqual(fd.read(4096), b"1" * 4096)
self.assertEqual(fd.read(2048), b"1" * 2048)
self.assertEqual(fd.read(2048), b"1" * 2048)
self.assertEqual(fd.read(1), b"2")
self.assertEqual(fd.read(4095), b"2" * 4095)
self.asse... | yield b"1" * 8192
yield b"2" * 4096
yield b"3" * 2048 | identifier_body |
test_stream_wrappers.py | import unittest
from streamlink.stream import StreamIOIterWrapper
class TestPluginStream(unittest.TestCase):
def test_iter(self):
def generator():
yield b"1" * 8192
yield b"2" * 4096
yield b"3" * 2048
fd = StreamIOIterWrapper(generator())
self.assertEq... | self.assertEqual(fd.read(), b"3" * 512) | self.assertEqual(fd.read(1536), b"3" * 1536) | random_line_split |
test_stream_wrappers.py | import unittest
from streamlink.stream import StreamIOIterWrapper
class | (unittest.TestCase):
def test_iter(self):
def generator():
yield b"1" * 8192
yield b"2" * 4096
yield b"3" * 2048
fd = StreamIOIterWrapper(generator())
self.assertEqual(fd.read(4096), b"1" * 4096)
self.assertEqual(fd.read(2048), b"1" * 2048)
... | TestPluginStream | identifier_name |
SpinnerAdapter.ts | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. | *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the Licen... | * You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
view_ref.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ChangeDetectorRef} from '../change_detection/change_detector_ref';
/**
* Represents an Angular [view](guide... | * @see `ViewContainerRef`
*
* @usageNotes
*
* The following template breaks down into two separate `TemplateRef` instances,
* an outer one and an inner one.
*
* ```
* Count: {{items.length}}
* <ul>
* <li *ngFor="let item of items">{{item}}</li>
* </ul>
* ```
*
* This is the outer `TemplateRef`:
*
* ... | * removing nested views in a view container.
* | random_line_split |
mainEventbus.js | 'use strict';
import TyphonLoggedEvents from './TyphonLoggedEvents.js';
const eventbus = new TyphonLoggedEvents();
eventbus.setEventbusName('mainEventbus');
/**
* Exports an instance of `TyphonLoggedEvents` which adds asynchronous capabilities to `Backbone.Events` which is used
* as a main eventbus. Note that an... | * Note the above creation of `const eventbus` is a workaround for an ESDoc bug:
* https://github.com/esdoc/esdoc/issues/166
*
* Normally we can write `export default new TyphonLoggedEvents();`, but this currently breaks ESDoc.
*/
export default eventbus; | * | random_line_split |
class-properties.test.ts | import { COLORS, ColorProps, ColorTranslator } from './data/data';
import { RGBObject, HSLObject } from '../src/@types';
// Test class properties
COLORS.forEach((item: ColorProps): void => {
const instance1 = new ColorTranslator(item.rgbObject);
describe(`Test properties of ${JSON.stringify(item.rgbObject)}`... |
it('check CSS properties', (): void => {
expect(instance1.HEX).toBe(item.hex);
expect(instance1.HEXA).toBe(item.hexa);
expect(instance1.RGB).toBe(item.rgb);
expect(instance1.RGBA).toBe(item.rgba);
expect(instance1.HSL).toBe(item.hsl);
exp... | }); | random_line_split |
native.rs | use winapi::*;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Buffer(pub *mut ID3D11Buffer);
unsafe impl Send for Buffer {}
unsafe impl Sync for Buffer {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum Texture {
D1(*mut ID3D11Texture1D),
D2(*mut ID3D11Texture2D),
D3(*mut ID3D11... | pub struct Rtv(pub *mut ID3D11RenderTargetView);
unsafe impl Send for Rtv {}
unsafe impl Sync for Rtv {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Dsv(pub *mut ID3D11DepthStencilView);
unsafe impl Send for Dsv {}
unsafe impl Sync for Dsv {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub st... | unsafe impl Sync for Texture {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] | random_line_split |
native.rs | use winapi::*;
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Buffer(pub *mut ID3D11Buffer);
unsafe impl Send for Buffer {}
unsafe impl Sync for Buffer {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum Texture {
D1(*mut ID3D11Texture1D),
D2(*mut ID3D11Texture2D),
D3(*mut ID3D11... | (pub *mut ID3D11RenderTargetView);
unsafe impl Send for Rtv {}
unsafe impl Sync for Rtv {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Dsv(pub *mut ID3D11DepthStencilView);
unsafe impl Send for Dsv {}
unsafe impl Sync for Dsv {}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Srv(pub *... | Rtv | identifier_name |
plot_cluster.py | # -*- coding: utf-8 -*-
#
# spikeplot - plot_cluster.py
#
# Philipp Meier <pmeier82 at googlemail dot com>
# 2011-09-29
#
"""scatter plot for clustering data"""
__docformat__ = 'restructuredtext'
__all__ = ['cluster']
##---IMPORTS
from .common import COLOURS, save_figure, check_plotting_handle, mpl, plt
##---FUNC... | title : str
A title for the plot. No title if None or ''.
xlabel : str
A label for the x-axis. No label if None or ''.
ylabel : str
A label for the y-axis. No label if None or ''.
filename : str
It given and a valid path on the local system... | """plot a set of clusters with different colors each
:Parameters:
data : object
Preferably a dictionary with ndarray entries.
data_dim : tuple
A 2-tuple giving the dimension (entries per datapoint/columns) to
use for the scatter plot of the cluster.
plot_... | identifier_body |
plot_cluster.py | # -*- coding: utf-8 -*-
#
# spikeplot - plot_cluster.py
#
# Philipp Meier <pmeier82 at googlemail dot com>
# 2011-09-29
#
"""scatter plot for clustering data"""
__docformat__ = 'restructuredtext'
__all__ = ['cluster']
##---IMPORTS
from .common import COLOURS, save_figure, check_plotting_handle, mpl, plt
##---FUNC... |
return fig
##---MAIN
if __name__ == '__main__':
pass
| plt.show() | conditional_block |
plot_cluster.py | # -*- coding: utf-8 -*-
#
# spikeplot - plot_cluster.py
#
# Philipp Meier <pmeier82 at googlemail dot com>
# 2011-09-29
#
"""scatter plot for clustering data"""
__docformat__ = 'restructuredtext'
__all__ = ['cluster']
##---IMPORTS
from .common import COLOURS, save_figure, check_plotting_handle, mpl, plt
##---FUNC... | (data, data_dim=(0, 1), plot_handle=None, plot_mean=True,
colours=None, title=None, xlabel=None, ylabel=None, filename=None,
show=True):
"""plot a set of clusters with different colors each
:Parameters:
data : object
Preferably a dictionary with ndarray entries.
... | cluster | identifier_name |
plot_cluster.py | # -*- coding: utf-8 -*-
#
# spikeplot - plot_cluster.py
#
# Philipp Meier <pmeier82 at googlemail dot com>
# 2011-09-29
#
"""scatter plot for clustering data"""
__docformat__ = 'restructuredtext'
__all__ = ['cluster']
##---IMPORTS
from .common import COLOURS, save_figure, check_plotting_handle, mpl, plt
##---FUNC... | # produce plots
if filename is not None:
save_figure(fig, filename, '')
if show is True:
plt.show()
return fig
##---MAIN
if __name__ == '__main__':
pass | ax.set_ylabel(ylabel)
| random_line_split |
main.component.ts | import { Component, AfterViewInit } from '@angular/core';
import { TdLoadingService} from '@covalent/core';
import { ProjectsService } from '../../services';
@Component({
selector: 'rt-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss'],
viewProviders: [ ProjectsService ],
})
ex... | (): void {
this._loadingService.register('projects.load');
this._projectsService.query().subscribe((projects: Object[]) => {
this.projects = projects;
setTimeout(() => {
this._loadingService.resolve('projects.load');
}, 750);
});
}
setCurrentProject(currentProjectName: string)... | ngAfterViewInit | identifier_name |
main.component.ts | import { Component, AfterViewInit } from '@angular/core';
import { TdLoadingService} from '@covalent/core';
import { ProjectsService } from '../../services';
@Component({
selector: 'rt-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss'],
viewProviders: [ ProjectsService ],
})
ex... | constructor(private _projectsService: ProjectsService,
private _loadingService: TdLoadingService) { }
ngAfterViewInit(): void {
this._loadingService.register('projects.load');
this._projectsService.query().subscribe((projects: Object[]) => {
this.projects = projects;
setTimeout((... |
projects: Object[];
currentProjectName: string = 'Default Test Project';
| random_line_split |
main.component.ts | import { Component, AfterViewInit } from '@angular/core';
import { TdLoadingService} from '@covalent/core';
import { ProjectsService } from '../../services';
@Component({
selector: 'rt-main',
templateUrl: './main.component.html',
styleUrls: ['./main.component.scss'],
viewProviders: [ ProjectsService ],
})
ex... |
setCurrentProject(currentProjectName: string) {
this.currentProjectName = currentProjectName;
}
}
| {
this._loadingService.register('projects.load');
this._projectsService.query().subscribe((projects: Object[]) => {
this.projects = projects;
setTimeout(() => {
this._loadingService.resolve('projects.load');
}, 750);
});
} | identifier_body |
settings.py | """
Scrapy settings for RecipesScraper project.
"""
# Names
BOT_NAME = 'RecipesScraper'
SPIDER_MODULES = ['RecipesScraper.spiders']
NEWSPIDER_MODULE = 'RecipesScraper.spiders'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Disable cookies (enabled by default)
COOKIES_ENABLED = False
# Configure item pipelines
IT... | AUTOTHROTTLE_START_DELAY = 3
# The maximum download delay to be set in case of high latencies
AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
AUTOTHROTTLE_TARGET_CONCURRENCY = 2.0
# Enable showing throttling stats for every response received:
#AU... |
# Enable and configure the AutoThrottle extension (disabled by default)
AUTOTHROTTLE_ENABLED = True
# The initial download delay | random_line_split |
jquery.sticker.js | /*!
* jQuery Sticker - v0.4 - 7/26/2012
* https://github.com/chrisfranson/jquery-sticker
*
* Copyright (c) 2012 Chris Franson
* Dual licensed under the MIT and GPL licenses.
*/
(function($) {
var methods = {
init: function(options) {
var settings = {
yOffset: 0,
throttle: 10,
stopper: ... | ||
(settings.revertWindowWidth && $(window).width() <= settings.revertWindowWidth)
) {
$sticker.css({
position: $placeholder.css('position'),
left: $placeholder.css('left'),
top: $placeholder.css('top')
});
return;
}
// If the user has sc... | // change the $sticker's position to its original properties
if ( (settings.revertLeft && $placeholder.offset().left <= settings.revertLeft) | random_line_split |
jquery.sticker.js | /*!
* jQuery Sticker - v0.4 - 7/26/2012
* https://github.com/chrisfranson/jquery-sticker
*
* Copyright (c) 2012 Chris Franson
* Dual licensed under the MIT and GPL licenses.
*/
(function($) {
var methods = {
init: function(options) {
var settings = {
yOffset: 0,
throttle: 10,
stopper: ... | else {
// Show the placeholder so that the sticker's parents don't change their width or height
$placeholder.css($placeholder.data('spacing'));
// Set the sticker's position to fixed, and its left and top to the proper values
$sticker.css({
position: 'fixed',
... | {
// If a stopper is specified and the user has scrolled to the point where
// the bottom of the sticker would overlap the top of the stopper
if (settings.stopper && y >= stickerSettings.stopperTop) {
// Set the sticker's position to absolute, and its left and top to the proper values
... | conditional_block |
deployment.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | :type author: str
:param deployer: Who performed the deployment.
:type deployer: str
:param author_email: Author email.
:type author_email: str
:param start_time: Start time.
:type start_time: datetime
:param end_time: End time.
:type end_time: datetime
:param active: True if dep... | """User crendentials used for publishing activity.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind: Kind of resource.
:type kind: str
:ivar type... | identifier_body |
deployment.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | (self, kind=None, deployment_id=None, status=None, message=None, author=None, deployer=None, author_email=None, start_time=None, end_time=None, active=None, details=None):
super(Deployment, self).__init__(kind=kind)
self.deployment_id = deployment_id
self.status = status
self.message = m... | __init__ | identifier_name |
deployment.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for | #
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .proxy_only_resource import ProxyOnlyResource
class Deployment(ProxyOnlyResource):
"... | # license information. | random_line_split |
status_action_bar.js | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenu from './dropdown_menu';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure... | } else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick ... | {
const { status, me, intl, withDismiss } = this.props;
const reblogDisabled = status.get('visibility') === 'private' || status.get('visibility') === 'direct';
const mutingConversation = status.get('muted');
let menu = [];
let reblogIcon = 'retweet';
let replyIcon;
let replyTitle;
menu... | identifier_body |
status_action_bar.js | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenu from './dropdown_menu';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure... |
if (status.getIn(['account', 'id']) === me) {
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick });
} else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.p... | {
menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick });
menu.push(null);
} | conditional_block |
status_action_bar.js | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenu from './dropdown_menu';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure... | this.context.router.history.push(`/statuses/${this.props.status.get('id')}`);
}
handleReport = () => {
this.props.onReport(this.props.status);
}
handleConversationMuteClick = () => {
this.props.onMuteConversation(this.props.status);
}
render () {
const { status, me, intl, withDismiss } = ... | handleOpen = () => { | random_line_split |
status_action_bar.js | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import DropdownMenu from './dropdown_menu';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure... | extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
onReply: PropTypes.func,
onFavourite: PropTypes.func,
onReblog: PropTypes.func,
onDelete: PropTypes.func,
onMention: PropTypes.func,
... | StatusActionBar | identifier_name |
sudoku.rs | -> Sudoku |
pub fn from_vec(vec: &[[u8;9];9]) -> Sudoku {
let g = (0..9u).map(|i| {
(0..9u).map(|j| { vec[i][j] }).collect()
}).collect();
return Sudoku::new(g)
}
pub fn read(mut reader: &mut BufferedReader<StdReader>) -> Sudoku {
/* assert first line is exactly "9,9" */
... | {
return Sudoku { grid: g }
} | identifier_body |
sudoku.rs | -> Sudoku {
return Sudoku { grid: g }
}
pub fn from_vec(vec: &[[u8;9];9]) -> Sudoku {
let g = (0..9u).map(|i| {
(0..9u).map(|j| { vec[i][j] }).collect()
}).collect();
return Sudoku::new(g)
}
pub fn read(mut reader: &mut BufferedReader<StdReader>) -> Sudoku ... |
}
}
fn next_color(&mut self, row: u8, col: u8, start_color: u8) -> bool {
if start_color < 10u8 {
// colors not yet used
let mut avail = box Colors::new(start_color);
// drop colors already in use in neighbourhood
self.drop_colors(&mut *avail, r... | {
// no: redo this field aft recoloring pred; unless there is none
if ptr == 0u { panic!("No solution found for this sudoku"); }
ptr = ptr - 1u;
} | conditional_block |
sudoku.rs | ) -> Sudoku {
return Sudoku { grid: g }
}
pub fn from_vec(vec: &[[u8;9];9]) -> Sudoku {
let g = (0..9u).map(|i| {
(0..9u).map(|j| { vec[i][j] }).collect()
}).collect();
return Sudoku::new(g)
}
pub fn read(mut reader: &mut BufferedReader<StdReader>) -> Sudoku... | let mut work: Vec<(u8, u8)> = Vec::new(); /* queue of uncolored fields */
for row in 0u8..9u8 {
for col in 0u8..9u8 {
let color = self.grid[row as uint][col as uint];
if color == 0u8 {
work.push((row, col));
}
}
... |
// solve sudoku grid
pub fn solve(&mut self) { | random_line_split |
sudoku.rs | (g: grid) -> Sudoku {
return Sudoku { grid: g }
}
pub fn from_vec(vec: &[[u8;9];9]) -> Sudoku {
let g = (0..9u).map(|i| {
(0..9u).map(|j| { vec[i][j] }).collect()
}).collect();
return Sudoku::new(g)
}
pub fn read(mut reader: &mut BufferedReader<StdReader>) -... | new | identifier_name | |
digitConverter.ts | /**
* @description
* Convert Egnlish digits to Farsi
* | export function toFarsi (number: string): string {
const regex = /[0-9]/g
let result = number.replace(regex, function (char) {
return String.fromCharCode(char.charCodeAt(0) + 1728)
})
return result
}
/**
* @description
* Convert Farsi digits to Egnlish
*
* @param {string} number - reference number
* ... | * @param {string} number - reference number
* @returns {string} result - converted number
*/ | random_line_split |
digitConverter.ts | /**
* @description
* Convert Egnlish digits to Farsi
*
* @param {string} number - reference number
* @returns {string} result - converted number
*/
export function toFarsi (number: string): string {
const regex = /[0-9]/g
let result = number.replace(regex, function (char) {
return String.fromCharCode(char... | (number: string): string {
const regex = /[\u0660-\u0669\u06F0-\u06F9]/g
let result = number.replace(regex, (char) => {
return String.fromCharCode(char.charCodeAt(0) - 1728)
})
return result
}
| toEnglish | identifier_name |
digitConverter.ts | /**
* @description
* Convert Egnlish digits to Farsi
*
* @param {string} number - reference number
* @returns {string} result - converted number
*/
export function toFarsi (number: string): string {
const regex = /[0-9]/g
let result = number.replace(regex, function (char) {
return String.fromCharCode(char... | {
const regex = /[\u0660-\u0669\u06F0-\u06F9]/g
let result = number.replace(regex, (char) => {
return String.fromCharCode(char.charCodeAt(0) - 1728)
})
return result
} | identifier_body | |
slice-const-param-mismatch.rs | // revisions: full min
#![cfg_attr(full, feature(adt_const_params))]
#![cfg_attr(full, allow(incomplete_features))]
struct ConstString<const T: &'static str>;
//[min]~^ ERROR
struct ConstBytes<const T: &'static [u8]>;
//[min]~^ ERROR
pub fn main() {
let _: ConstString<"Hello"> = ConstString::<"Hello">;
let ... | } | random_line_split | |
slice-const-param-mismatch.rs | // revisions: full min
#![cfg_attr(full, feature(adt_const_params))]
#![cfg_attr(full, allow(incomplete_features))]
struct ConstString<const T: &'static str>;
//[min]~^ ERROR
struct ConstBytes<const T: &'static [u8]>;
//[min]~^ ERROR
pub fn | () {
let _: ConstString<"Hello"> = ConstString::<"Hello">;
let _: ConstString<"Hello"> = ConstString::<"World">; //[full]~ ERROR mismatched types
let _: ConstString<"ℇ㇈↦"> = ConstString::<"ℇ㇈↦">;
let _: ConstString<"ℇ㇈↦"> = ConstString::<"ℇ㇈↥">; //[full]~ ERROR mismatched types
let _: ConstBytes<b"A... | main | identifier_name |
perlin.py | (3.0 - sqrt(3.0)) / 6.0
_F3 = 1.0 / 3.0
_G3 = 1.0 / 6.0
class BaseNoise:
"""Noise abstract base class"""
permutation = (151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88... | """2D Perlin simplex noise.
Return a floating point value from -1 to 1 for the given x, y coordinate.
The same value is always returned for a given x, y pair unless the
permutation table changes (see randomize above).
"""
# Skew input space to determine which simplex (triangle) we are in
s = (x + y)... | identifier_body | |
perlin.py | ),(3,1,2,0),
(2,1,0,3),(0,0,0,0),(0,0,0,0),(0,0,0,0),(3,1,0,2),(0,0,0,0),(3,2,0,1),(3,2,1,0))
# Simplex skew constants
_F2 = 0.5 * (sqrt(3.0) - 1.0)
_G2 = (3.0 - sqrt(3.0)) / 6.0
_F3 = 1.0 / 3.0
_G3 = 1.0 / 6.0
class BaseNoise:
"""Noise abstract base class"""
permutation = (151,160,137,91,90,15,
... |
if period is not None:
self.randomize(period)
elif permutation_table is not None:
self.permutation = tuple(permutation_table) * 2
self.period = len(permutation_table)
def randomize(self, period=None):
"""Randomize the permutation table used by the noise functions. This
makes them generate a... | raise ValueError(
'Can specify either period or permutation_table, not both') | conditional_block |
perlin.py | the O(2^N) of classic Noise.
* Simplex noise has no noticeable directional artifacts. Simplex noise has
a well-defined and continuous gradient everywhere that can be computed
quite cheaply.
* Simplex noise is easy to implement in hardware."
"""
def noise2(self, x, y):
"""2D Perlin simplex noise.
... | for i in range(1, octaves):
| random_line_split | |
perlin.py | ),(3,1,2,0),
(2,1,0,3),(0,0,0,0),(0,0,0,0),(0,0,0,0),(3,1,0,2),(0,0,0,0),(3,2,0,1),(3,2,1,0))
# Simplex skew constants
_F2 = 0.5 * (sqrt(3.0) - 1.0)
_G2 = (3.0 - sqrt(3.0)) / 6.0
_F3 = 1.0 / 3.0
_G3 = 1.0 / 6.0
class BaseNoise:
"""Noise abstract base class"""
permutation = (151,160,137,91,90,15,
... | (self, period=None, permutation_table=None):
"""Initialize the noise generator. With no arguments, the default
period and permutation table are used (256). The default permutation
table generates the exact same noise pattern each time.
An integer period can be specified, to generate a random permutation
... | __init__ | identifier_name |
activity_stream_add_note.js | angular.module('app.utils.directives').directive('activityAddNote', activityAddNoteDirective);
function activityAddNoteDirective() {
return {
restrict: 'E',
scope: {
item: '=',
},
templateUrl: 'utils/directives/activity_stream_add_note.html',
controller: Activity... |
vm.note = new Note({gfk_content_type: contentType, gfk_object_id: vm.item.id, type: 0});
vm.addNote = addNote;
function addNote() {
if (vm.note.content) {
vm.note.$save(response => {
// Set user object to note to correctly show profile pic and name
// ... | {
contentType = vm.item.content_type.id;
} | conditional_block |
activity_stream_add_note.js | angular.module('app.utils.directives').directive('activityAddNote', activityAddNoteDirective);
function activityAddNoteDirective() {
return {
restrict: 'E',
scope: {
item: '=',
},
templateUrl: 'utils/directives/activity_stream_add_note.html',
controller: Activity... | });
vm.item.notes.unshift(response);
// 'Empty' the note object to be able to continue posting another
// note without having to refresh the page.
vm.note = new Note({gfk_content_type: vm.item.content_type, gfk_object_id: vm.item.id, type:... | {
let vm = this;
let contentType = vm.item.content_type;
if (typeof vm.item.content_type === 'object') {
contentType = vm.item.content_type.id;
}
vm.note = new Note({gfk_content_type: contentType, gfk_object_id: vm.item.id, type: 0});
vm.addNote = addNote;
function addNote() {
... | identifier_body |
activity_stream_add_note.js | angular.module('app.utils.directives').directive('activityAddNote', activityAddNoteDirective);
function | () {
return {
restrict: 'E',
scope: {
item: '=',
},
templateUrl: 'utils/directives/activity_stream_add_note.html',
controller: ActivityAddNoteController,
controllerAs: 'vm',
bindToController: true,
link: (scope, element, attrs) => {
... | activityAddNoteDirective | identifier_name |
activity_stream_add_note.js | angular.module('app.utils.directives').directive('activityAddNote', activityAddNoteDirective);
function activityAddNoteDirective() {
return {
restrict: 'E',
scope: {
item: '=',
},
templateUrl: 'utils/directives/activity_stream_add_note.html', | },
};
}
ActivityAddNoteController.$inject = ['$http', '$state', 'Note', 'User'];
function ActivityAddNoteController($http, $state, Note, User) {
let vm = this;
let contentType = vm.item.content_type;
if (typeof vm.item.content_type === 'object') {
contentType = vm.item.content_type.id... | controller: ActivityAddNoteController,
controllerAs: 'vm',
bindToController: true,
link: (scope, element, attrs) => {
element[0].focus(); | random_line_split |
filedeps.py | # ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | def console_output(self, targets):
files = set()
for target in targets:
if isinstance(target, TargetWithSources):
files.update(target.expand_files(recursive=False))
if isinstance(target, JvmApp):
files.update(itertools.chain(*[bundle.filemap.keys() for bundle in target.bundles]))
... | identifier_body | |
filedeps.py | # ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | (ConsoleTask):
def console_output(self, targets):
files = set()
for target in targets:
if isinstance(target, TargetWithSources):
files.update(target.expand_files(recursive=False))
if isinstance(target, JvmApp):
files.update(itertools.chain(*[bundle.filemap.keys() for bundle in targ... | FileDeps | identifier_name |
filedeps.py | # ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
if isinstance(target, JvmApp):
files.update(itertools.chain(*[bundle.filemap.keys() for bundle in target.bundles]))
return files
| files.update(target.expand_files(recursive=False)) | conditional_block |
filedeps.py | # ==================================================================================================
# Copyright 2012 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | if isinstance(target, TargetWithSources):
files.update(target.expand_files(recursive=False))
if isinstance(target, JvmApp):
files.update(itertools.chain(*[bundle.filemap.keys() for bundle in target.bundles]))
return files |
class FileDeps(ConsoleTask):
def console_output(self, targets):
files = set()
for target in targets: | random_line_split |
set-gas-price.js | /* eslint-env mocha */
"use strict";
var assert = require("chai").assert;
var setGasPrice = require("../src/set-gas-price");
describe("set-gas-price", function () {
var test = function (t) {
it(t.description, function (done) {
setGasPrice(t.rpc, function (err, gasPrice) {
t.assertions(err, gasPri... | }
}
},
assertions: function (err, gasPrice) {
assert.isTrue(err instanceof Error);
assert.isUndefined(gasPrice);
}
});
test({
description: "gasPrice is null",
rpc: {
eth: {
gasPrice: function (callback) {
callback(null, null);
}
}
... | rpc: {
eth: {
gasPrice: function (callback) {
callback(null, undefined); | random_line_split |
configurationResolver.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | export interface PromptStringInputInfo {
id: string;
type: 'promptString';
description: string;
default?: string;
}
export interface PickStringInputInfo {
id: string;
type: 'pickString';
description: string;
options: string[];
default?: string;
}
export interface CommandInputInfo {
id: string;
type: 'comma... | * Keys in the map will be of the format input:variableName or command:variableName.
*/
resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>): Promise<Map<string, string> | undefined>;
}
| random_line_split |
table_cell.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_blocks)]
use block::{BlockFlow, ISizeAndMarginsComputer, Margi... | {
/// Data common to all block flows.
pub block_flow: BlockFlow,
/// The column span of this cell.
pub column_span: u32,
/// Whether this cell is visible. If false, the value of `empty-cells` means that we must not
/// display this cell.
pub visible: bool,
}
impl TableCellFlow {
pub fn... | TableCellFlow | identifier_name |
table_cell.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_blocks)]
use block::{BlockFlow, ISizeAndMarginsComputer, Margi... |
fn repair_style(&mut self, new_style: &Arc<ComputedValues>) {
self.block_flow.repair_style(new_style)
}
fn compute_overflow(&self) -> Rect<Au> {
self.block_flow.compute_overflow()
}
fn iterate_through_fragment_border_boxes(&self,
itera... | {
if self.visible {
self.block_flow.build_display_list(layout_context)
}
} | identifier_body |
table_cell.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_blocks)]
use block::{BlockFlow, ISizeAndMarginsComputer, Margi... |
}
/// Recursively (top-down) determines the actual inline-size of child contexts and fragments.
/// When called on this context, the context has had its inline-size set by the parent table
/// row.
fn assign_inline_sizes(&mut self, layout_context: &LayoutContext) {
let _scope = layout_debu... | {
self.block_flow.base.intrinsic_inline_sizes.preferred_inline_size =
self.block_flow.base.intrinsic_inline_sizes.minimum_inline_size;
} | conditional_block |
table_cell.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_blocks)]
use block::{BlockFlow, ISizeAndMarginsComputer, Margi... | pub block_flow: BlockFlow,
/// The column span of this cell.
pub column_span: u32,
/// Whether this cell is visible. If false, the value of `empty-cells` means that we must not
/// display this cell.
pub visible: bool,
}
impl TableCellFlow {
pub fn from_node_fragment_and_visibility_flag(nod... | pub struct TableCellFlow {
/// Data common to all block flows. | random_line_split |
fieldController.js | app.controller('fieldController',function($scope,httpService,$state,$stateParams){
if($state.is('field-add')) | var load = function(){
httpService.getList('/api/crop')
.then(function(data){
$scope.crops = data.crops;
$scope.soils = data.soils;
$scope.stations = data.stations;
})
}
}
else if($state.is('field')){
var load = function(){
httpService.getList('/api/field')
.then(function(data)... | {
$scope.crop ={"selected":null};
$scope.field = {};
$scope.setFormScope = function(scope){
this.formScope = scope;
}
$scope.field.start_date = null;
$scope.field.irrigation_day = "";
$scope.addField = function(){
if(this.formScope.field_form.$valid){
console.log($scope.field);
htt... | conditional_block |
fieldController.js | app.controller('fieldController',function($scope,httpService,$state,$stateParams){
if($state.is('field-add')){
$scope.crop ={"selected":null};
$scope.field = {};
$scope.setFormScope = function(scope){
this.formScope = scope;
}
$scope.field.start_date = null;
$scope.field.irrigation_day = "";
... | $scope.stations = data.stations;
})
}
}else if($state.is('field')){
var load = function(){
httpService.getList('/api/field')
.then(function(data){
if(data.fields!=null){
$scope.fields = data.fields;
}else{
$scope.msg = 'No fields available!!';
}
})
}
$scope.... | httpService.getList('/api/crop')
.then(function(data){
$scope.crops = data.crops;
$scope.soils = data.soils; | random_line_split |
Main.tsx | import React, { FC } from 'react';
import { Redirect, Route } from 'react-router-dom';
import { IonIcon, IonLabel, IonRouterOutlet, IonTabBar, IonTabButton, IonTabs } from '@ionic/react';
import { ellipse, square, triangle } from 'ionicons/icons';
//
import '@/App.scss';
import Home from '@/pages/Home';
import Discover... | <Route path="/tabs/me" component={Me} />
</IonRouterOutlet>
<IonTabBar slot="bottom">
<IonTabButton tab="home" href="/tabs/home">
<IonIcon icon={triangle} />
<IonLabel>Home</IonLabel>
</IonTabButton>
<IonTabButton tab="disco... | random_line_split | |
newsworthy.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... | return [[]]
if data['hook']['event'] == EVENT_UNPUBLISHED:
logger.info("ignoring unpublish event on following data:\n{data}".format(data=data))
return [[]]
# we have to write to a temporary file because feed parser expect a file path
# FIXME: it would be bett... | random_line_split | |
newsworthy.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... | (webhooks.FeedingServiceWebhookAuth):
# FIXME: we can't use eve.auth.BasicAuth because eve uses flask.g.user
# internally and superdesk.audit too, resulting in conflict
def authorized(self, allowed_roles, resource, method):
"""Check that webhook data correspond to a known ingest provider
... | NewsworthyFeedingServiceAuth | identifier_name |
newsworthy.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... |
class NewsworthyFeedingService(FeedingService):
"""
Feeding Service class which can retrieve articles from Newsworthy web service
"""
NAME = 'newsworthy'
ERRORS = [IngestApiError.apiRequestError().get_error_description(),
SuperdeskIngestError.notConfiguredError().get_error_descrip... | provider['newsworthy_data'] = request.json
kwargs = {
'provider': provider,
'rule_set': update_ingest.get_provider_rule_set(provider),
'routing_scheme': update_ingest.get_provider_routing_scheme(provider)
}
update_ingest.update_provider... | conditional_block |
newsworthy.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import logg... | },
{
'id': 'password', 'type': 'password', 'label': 'Password',
'required': True
},
{
'id': 'secret', 'type': 'password', 'label': 'Shared Secret',
'placeholder': 'Shared Secret', 'required': False
},
]
def _update(self, pr... | """
Feeding Service class which can retrieve articles from Newsworthy web service
"""
NAME = 'newsworthy'
ERRORS = [IngestApiError.apiRequestError().get_error_description(),
SuperdeskIngestError.notConfiguredError().get_error_description()]
label = 'Newsworthy'
fields = [
... | identifier_body |
motivato.py | from .provider_base import ExternalPaymentProvider
from tapiriik.database import db
from tapiriik.settings import MOTIVATO_PREMIUM_USERS_LIST_URL
import requests
class MotivatoExternalPaymentProvider(ExternalPaymentProvider):
ID = "motivato"
def | (self, external_ids):
from tapiriik.services import Service, ServiceRecord
external_ids = [str(x) for x in external_ids]
connections = [ServiceRecord(x) for x in db.connections.find({"Service": "motivato", "ExternalID": {"$in": external_ids}})]
users = db.users.find({"ConnectedServices.ID": {"$in": [x._id for x... | RefreshPaymentStateForExternalIDs | identifier_name |
motivato.py | from .provider_base import ExternalPaymentProvider
from tapiriik.database import db
from tapiriik.settings import MOTIVATO_PREMIUM_USERS_LIST_URL
import requests
class MotivatoExternalPaymentProvider(ExternalPaymentProvider):
ID = "motivato"
def RefreshPaymentStateForExternalIDs(self, external_ids):
from tapiriik... |
ExternalPaymentProvider.Register(MotivatoExternalPaymentProvider()) |
# Bulk-remove these payments from users who don't own them (more or less - it'll leave anyone who switched remote accounts)
db.users.update({"_id": {"$nin": [x["_id"] for x in users]}}, {"$pull": {"ExternalPayments": {"_id": {"$in": [x["_id"] for x in payments]}}}}, multi=True)
# We don't bother unsetting users... | random_line_split |
motivato.py | from .provider_base import ExternalPaymentProvider
from tapiriik.database import db
from tapiriik.settings import MOTIVATO_PREMIUM_USERS_LIST_URL
import requests
class MotivatoExternalPaymentProvider(ExternalPaymentProvider):
ID = "motivato"
def RefreshPaymentStateForExternalIDs(self, external_ids):
from tapiriik... |
def RefreshPaymentState(self):
from tapiriik.services import ServiceRecord
from tapiriik.payments import Payments
from tapiriik.auth import User
external_ids = requests.get(MOTIVATO_PREMIUM_USERS_LIST_URL).json()
connections = [ServiceRecord(x) for x in db.connections.find({"Service": "motivato", "Externa... | my_connection = [x for x in connections if x._id in [y["ID"] for y in user["ConnectedServices"]]][0]
# Defer to the actual service module, where all the session stuff is set up
state = Service.FromID("motivato")._getPaymentState(my_connection)
self.ApplyPaymentState(user, state, my_connection.ExternalID, durat... | conditional_block |
motivato.py | from .provider_base import ExternalPaymentProvider
from tapiriik.database import db
from tapiriik.settings import MOTIVATO_PREMIUM_USERS_LIST_URL
import requests
class MotivatoExternalPaymentProvider(ExternalPaymentProvider):
ID = "motivato"
def RefreshPaymentStateForExternalIDs(self, external_ids):
from tapiriik... |
ExternalPaymentProvider.Register(MotivatoExternalPaymentProvider()) | from tapiriik.services import ServiceRecord
from tapiriik.payments import Payments
from tapiriik.auth import User
external_ids = requests.get(MOTIVATO_PREMIUM_USERS_LIST_URL).json()
connections = [ServiceRecord(x) for x in db.connections.find({"Service": "motivato", "ExternalID": {"$in": external_ids}})]
use... | identifier_body |
test_data.py | umm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWSumm... | # -- test add/get methods -------------------
def test_add_timeseries(self):
a = TimeSeries([1, 2, 3, 4, 5], name='test name', epoch=0,
sample_rate=1)
# test simple add using 'name'
data.add_timeseries(a)
assert 'test name' in globalv.DATA
assert ... | random_line_split | |
test_data.py | umm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWSumm... |
@classmethod
def teardown_class(cls):
# remove the temporary data
shutil.rmtree(cls._tempdir)
# -- test utilities -------------------------
def test_find_frame_type(self):
channel = Channel('L1:TEST-CHANNEL')
assert data.find_frame_type(channel) == 'L1_R'
cha... | target = os.path.join(cls._tempdir, os.path.basename(gwf))
download(gwf, target)
cls.FRAMES[channel].append(CacheEntry.from_T050017(target)) | conditional_block |
test_data.py | should have received a copy of the GNU General Public License
# along with GWSumm. If not, see <http://www.gnu.org/licenses/>.
"""Tests for `gwsumm.data`
"""
import os.path
import operator
import tempfile
import shutil
from collections import OrderedDict
from urllib.request import urlopen
import pytest
from nump... | a, _, _ = data.get_spectrum('H1:LOSC-STRAIN', LOSC_SEGMENTS,
cache=self.FRAMES['H1:LOSC-STRAIN'],
nproc=1)
b, _, _ = data.get_spectrum('H1:LOSC-STRAIN', LOSC_SEGMENTS,
format='asd',
... | identifier_body | |
test_data.py | umm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GWSumm... | (object):
"""Tests for :mod:`gwsumm.data`:
"""
@classmethod
def setup_class(cls):
cls.FRAMES = {}
cls._tempdir = tempfile.mkdtemp(prefix='gwsumm-test-data-')
# get data
for channel in LOSC_DATA:
cls.FRAMES[channel] = Cache()
for gwf in LOSC_DATA[ch... | TestData | identifier_name |
test.py | #!/usr/bin/env python3
# Copyright 2021 Anapaya Systems
#
# 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... | (self, cs_config: pathlib.Path):
with open(cs_config, "r") as f:
cfg = toml.load(f)
return cfg["metrics"]["prometheus"]
def _extract_skid(self, file: pathlib.Path):
out = subprocess.check_output(
['openssl', 'x509', '-in', file, '-noout', '-text'])
lines ... | _http_endpoint | identifier_name |
test.py | #!/usr/bin/env python3
# Copyright 2021 Anapaya Systems
#
# 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... | import time
from typing import List
import sys
from http import client
from plumbum import cli
from acceptance.common import base
from acceptance.common import docker
from acceptance.common import scion
from python.lib import scion_addr
import toml
logger = logging.getLogger(__name__)
class Test(base.TestBase):
... | random_line_split | |
test.py | #!/usr/bin/env python3
# Copyright 2021 Anapaya Systems
#
# 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... |
def _check_key_cert(self, cs_configs: List[pathlib.Path]):
not_ready = [*cs_configs]
for _ in range(5):
logger.info(
"Checking if all control servers have reloaded the key and certificate..."
)
for cs_config in not_ready:
conn = ... | raise Exception("renewed key does not differ from previous key") | conditional_block |
test.py | #!/usr/bin/env python3
# Copyright 2021 Anapaya Systems
#
# 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... |
def _run(self):
isd_ases = scion.ASList.load("%s/gen/as_list.yml" %
self.test_state.artifacts).all
cs_configs = self._cs_configs()
logger.info("==> Start renewal process")
for isd_as in isd_ases:
logging.info("===> Start renewal: %s... | if not self.nested_command:
try:
self.setup()
# Give some time for the topology to start.
time.sleep(10)
self._run()
finally:
self.teardown() | identifier_body |
syslogic.js | var ctx=document.getElementById("cvs").getContext("2d");
var timercount=200;
var timerctx;
var chrmtx=new Array();
var keywait=false;
window.onload=(function(){
clck=new Audio("cggsys/audio/pingpong1.mp3");
buzzer=new Audio("cggsys/audio/buzzer.mp3");
alerm=new Audio("cggsys/audio/alerm.wav");
//vraminit();
d... | (){
clearInterval(timerctx);
}
function peek(x,y){
//return chr;
}
function beep(mode){
switch(mode){
case 0:
buzzer.play();
break;
case 1:
clck.play();
break;
case 2:
alerm.play();
break;
default:
break;
}
}
function putc(chrcode,chrctx,cx,cy){
var i,j;
for(i=0;i<=chrctx[2]-1;i++){
for(j=0;j<... | cleartimer | identifier_name |
syslogic.js | var ctx=document.getElementById("cvs").getContext("2d");
var timercount=200;
var timerctx;
var chrmtx=new Array();
var keywait=false;
window.onload=(function(){
clck=new Audio("cggsys/audio/pingpong1.mp3");
buzzer=new Audio("cggsys/audio/buzzer.mp3");
alerm=new Audio("cggsys/audio/alerm.wav");
//vraminit();
d... |
function color(cc){
switch(cc){
case 0:
ctx.fillStyle="rgb(0,0,0)";
break;
case 1:
ctx.fillStyle="rgb(0,0,255)";
break;
case 2:
ctx.fillStyle="rgb(255,0,0)";
break;
case 3:
ctx.fillStyle="rgb(255,0,255)";
break;
case 4:
ctx.fillStyle="rgb(0,255,0)";
break;
case 5:
ctx.fillStyle="rgb(0,255,255)";
br... | {
var i,j;
for(i=0;i<=chrctx[2]-1;i++){
for(j=0;j<=chrctx[1]-1;j++){
if(chrcode[i*chrctx[1]+j]==1){
ctx.fillRect((cx+j)*4,(cy+i)*4,4,4);
}
}
}
} | identifier_body |
syslogic.js | var ctx=document.getElementById("cvs").getContext("2d");
var timercount=200;
var timerctx;
var chrmtx=new Array();
var keywait=false;
window.onload=(function(){
clck=new Audio("cggsys/audio/pingpong1.mp3");
buzzer=new Audio("cggsys/audio/buzzer.mp3");
alerm=new Audio("cggsys/audio/alerm.wav");
//vraminit();
d... |
}
}
}
function color(cc){
switch(cc){
case 0:
ctx.fillStyle="rgb(0,0,0)";
break;
case 1:
ctx.fillStyle="rgb(0,0,255)";
break;
case 2:
ctx.fillStyle="rgb(255,0,0)";
break;
case 3:
ctx.fillStyle="rgb(255,0,255)";
break;
case 4:
ctx.fillStyle="rgb(0,255,0)";
break;
case 5:
ctx.fillStyle="rgb(0... | {
ctx.fillRect((cx+j)*4,(cy+i)*4,4,4);
} | conditional_block |
syslogic.js | var ctx=document.getElementById("cvs").getContext("2d");
var timercount=200;
var timerctx;
var chrmtx=new Array();
var keywait=false;
window.onload=(function(){
clck=new Audio("cggsys/audio/pingpong1.mp3");
buzzer=new Audio("cggsys/audio/buzzer.mp3");
alerm=new Audio("cggsys/audio/alerm.wav");
//vraminit();
d... | } | }
function println(str){
ctx,fillStyle="rgb(255,255,255)";
ctx.font="16px 'MSSVbN'";
ctx.fillText(str,10,405);
| random_line_split |
htmlMode.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return htmlLanguageService.doComplete(document, position, htmlDocuments.get(document), options);
},
doHover(document: TextDocument, position: Position) {
return htmlLanguageService.doHover(document, position, htmlDocuments.get(document));
},
findDocumentHighlight(document: TextDocument, position: Positio... | {
options.hideAutoCompleteProposals = true;
} | conditional_block |
htmlMode.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | let doAutoComplete = settings && settings.html && settings.html.autoClosingTags;
if (doAutoComplete) {
options.hideAutoCompleteProposals = true;
}
return htmlLanguageService.doComplete(document, position, htmlDocuments.get(document), options);
},
doHover(document: TextDocument, position: Position) {... | random_line_split | |
htmlMode.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (document: TextDocument) {
return htmlLanguageService.findDocumentSymbols(document, htmlDocuments.get(document));
},
format(document: TextDocument, range: Range, formatParams: FormattingOptions, settings: Settings = globalSettings) {
let formatSettings: HTMLFormatConfiguration = settings && settings.html && s... | findDocumentSymbols | identifier_name |
htmlMode.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | ,
configure(options: any) {
globalSettings = options;
},
doComplete(document: TextDocument, position: Position, settings: Settings = globalSettings) {
let options = settings && settings.html && settings.html.suggest;
let doAutoComplete = settings && settings.html && settings.html.autoClosingTags;
if (... | {
return 'html';
} | identifier_body |
const-block-item.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
assert_eq!(BLOCK_USE, 100);
assert_eq!(BLOCK_PUB_USE, 200);
assert_eq!(BLOCK_STRUCT_DEF, 300);
assert_eq!(BLOCK_FN_DEF(390), 400);
assert_eq!(BLOCK_MACRO_RULES, 412);
}
| main | identifier_name |
const-block-item.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert_eq!(BLOCK_PUB_USE, 200);
assert_eq!(BLOCK_STRUCT_DEF, 300);
assert_eq!(BLOCK_FN_DEF(390), 400);
assert_eq!(BLOCK_MACRO_RULES, 412);
} | random_line_split | |
const-block-item.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
assert_eq!(BLOCK_USE, 100);
assert_eq!(BLOCK_PUB_USE, 200);
assert_eq!(BLOCK_STRUCT_DEF, 300);
assert_eq!(BLOCK_FN_DEF(390), 400);
assert_eq!(BLOCK_MACRO_RULES, 412);
} | identifier_body | |
Acao.js | // Representa um ação que pode ser desfeita e refeita
// A ação é associada a uma aba aberta
// Nas funções redo e undo, this se refere à aba associada à ação
function Acao(nome, redo, undo) {
var aba | a o nome da ação a ser desfeita na aba ativa (null caso nada possa ser desfeito)
Acao.getDesfazer = function () {
var aba, acao
aba = Interface.abaFoco
acao = aba.historico[aba.posHistorico-1]
if (aba.posHistorico > 0 && acao.undo)
return acao.nome
return null
}
// Retorna o nome da ação a ser refeita na aba at... | = Interface.abaFoco
this.id = String(Math.random())
this.nome = nome
this.redo = redo
this.undo = undo
if (aba.posHistorico < aba.historico.length)
aba.historico = aba.historico.slice(0, aba.posHistorico)
aba.historico.push(this)
aba.posHistorico = aba.historico.length
redo.call(aba)
aba.livro.modifica... | identifier_body |
Acao.js | // Representa um ação que pode ser desfeita e refeita
// A ação é associada a uma aba aberta
// Nas funções redo e undo, this se refere à aba associada à ação
function Acao(nome, | , undo) {
var aba = Interface.abaFoco
this.id = String(Math.random())
this.nome = nome
this.redo = redo
this.undo = undo
if (aba.posHistorico < aba.historico.length)
aba.historico = aba.historico.slice(0, aba.posHistorico)
aba.historico.push(this)
aba.posHistorico = aba.historico.length
redo.call(aba)
... | redo | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.