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 |
|---|---|---|---|---|
mod.rs | mod block_on_serial_directory_create;
pub use block_on_serial_directory_create::block_on_serial_directory_create;
mod watch_device_directory;
pub use watch_device_directory::watch_device_directory;
use xactor::Actor;
use eyre::{
// eyre,
Result,
// Context as _,
};
#[xactor::message(result = "()")]
struc... |
}
#[async_trait::async_trait]
impl xactor::Handler<WatchDevices> for DevSerialWatcher {
#[instrument(skip(self, ctx, _msg))]
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: WatchDevices) -> () {
let result = self.watch_dev_serial().await;
if let Err(err) = result {
... | {
ctx.address().send(WatchDevices)?;
Ok(())
} | identifier_body |
mod.rs | mod block_on_serial_directory_create;
pub use block_on_serial_directory_create::block_on_serial_directory_create;
mod watch_device_directory;
pub use watch_device_directory::watch_device_directory;
use xactor::Actor;
use eyre::{
// eyre,
Result,
// Context as _,
};
#[xactor::message(result = "()")]
struc... | }
}
pub struct KlipperWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
#[async_trait::async_trait]
impl Actor for KlipperWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()> {
ctx.address().send(WatchDevices)?;
Ok(... | warn!("Error watching /dev/serial/by-id/ device files: {:?}", err);
ctx.stop(Some(err));
}; | random_line_split |
mod.rs | mod block_on_serial_directory_create;
pub use block_on_serial_directory_create::block_on_serial_directory_create;
mod watch_device_directory;
pub use watch_device_directory::watch_device_directory;
use xactor::Actor;
use eyre::{
// eyre,
Result,
// Context as _,
};
#[xactor::message(result = "()")]
struc... | ;
}
}
pub struct KlipperWatcher {
pub device_manager: crate::DeviceManagerAddr,
}
#[async_trait::async_trait]
impl Actor for KlipperWatcher {
#[instrument(skip(self, ctx))]
async fn started(&mut self, ctx: &mut xactor::Context<Self>) -> Result<()> {
ctx.address().send(WatchDevices)?;
O... | {
warn!("Error watching /dev/serial/by-id/ device files: {:?}", err);
ctx.stop(Some(err));
} | conditional_block |
mod.rs | mod block_on_serial_directory_create;
pub use block_on_serial_directory_create::block_on_serial_directory_create;
mod watch_device_directory;
pub use watch_device_directory::watch_device_directory;
use xactor::Actor;
use eyre::{
// eyre,
Result,
// Context as _,
};
#[xactor::message(result = "()")]
struc... | (&self) -> Result<()> {
// Normally serial ports are created at /dev/serial/by-id/
loop {
// /dev/serial is only created when a serial port is connected to the computer
block_on_serial_directory_create().await?;
// Once /dev/serial exists watch for new device files in... | watch_dev_serial | identifier_name |
about.py | #
# Copyright (C) 2006, 2013 Red Hat, Inc.
# Copyright (C) 2006 Daniel P. Berrange <berrange@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (... | vmmGObjectUI.__init__(self, "about.ui", "vmm-about")
self.builder.connect_signals({
"on_vmm_about_delete_event": self.close,
"on_vmm_about_response": self.close,
})
def show(self):
logging.debug("Showing about")
self.topwin.set_version(self.config.ge... | from virtManager.baseclass import vmmGObjectUI
class vmmAbout(vmmGObjectUI):
def __init__(self): | random_line_split |
about.py | #
# Copyright (C) 2006, 2013 Red Hat, Inc.
# Copyright (C) 2006 Daniel P. Berrange <berrange@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (... |
def show(self):
logging.debug("Showing about")
self.topwin.set_version(self.config.get_appversion())
self.topwin.present()
def close(self, ignore1=None, ignore2=None):
logging.debug("Closing about")
self.topwin.hide()
return 1
def _cleanup(self):
p... | vmmGObjectUI.__init__(self, "about.ui", "vmm-about")
self.builder.connect_signals({
"on_vmm_about_delete_event": self.close,
"on_vmm_about_response": self.close,
}) | identifier_body |
about.py | #
# Copyright (C) 2006, 2013 Red Hat, Inc.
# Copyright (C) 2006 Daniel P. Berrange <berrange@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (... | (self):
vmmGObjectUI.__init__(self, "about.ui", "vmm-about")
self.builder.connect_signals({
"on_vmm_about_delete_event": self.close,
"on_vmm_about_response": self.close,
})
def show(self):
logging.debug("Showing about")
self.topwin.set_version(self.c... | __init__ | identifier_name |
re_set.rs | 't always obvious to reason about.
///
/// # Limitations
///
/// Regex sets are limited to answering the following two questions:
///
/// 1. Does any regex in the set match?
/// 2. If so, which regexes in the set match?
///
/// As with the main `Regex` type, it is cheaper to ask (1) instead of (2)
/// since the matchin... | }
| random_line_split | |
Login.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../../actions/auth'
import './login.css'
import { Container, Grid, Segment, Input, Header, Button, Icon } from 'semantic-ui-react';
const styles = {
loginForm: {
height: '100%'
},
segment: {
... | placeholder='Enter your password' />
<Container textAlign='right' style={styles.container}>
<Button animated loading={this.state.isLoading} color='teal' onClick={this.handleSubmit.bind(this)}>
... | iconPosition='left' | random_line_split |
Login.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../../actions/auth'
import './login.css'
import { Container, Grid, Segment, Input, Header, Button, Icon } from 'semantic-ui-react';
const styles = {
loginForm: {
height: '100%'
},
segment: {
... |
}
function mapStateToProps({ auth }) {
return { auth }
}
export default connect(mapStateToProps, actions)(Login);
| {
return (
<div style={styles.loginForm}>
{this.renderLogin()}
</div>
)
} | identifier_body |
Login.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../../actions/auth'
import './login.css'
import { Container, Grid, Segment, Input, Header, Button, Icon } from 'semantic-ui-react';
const styles = {
loginForm: {
height: '100%'
},
segment: {
... | () {
this.toggleLoading();
this.props.login(this.state.user, this.state.password,(err,data)=>{
if(err) {
this.toggleLoading();
alert(data.msg);
} else {
this.props.history.push("/dashboard");
}
});
}
ha... | handleSubmit | identifier_name |
Login.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../../actions/auth'
import './login.css'
import { Container, Grid, Segment, Input, Header, Button, Icon } from 'semantic-ui-react';
const styles = {
loginForm: {
height: '100%'
},
segment: {
... |
}
componentWillMount() {
document.title = "Login";
}
renderLogin() {
return (
<div style={styles.loginForm}>
<Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'>
<Grid.Column style={styles.segment}>
... | {
this.handleSubmit();
} | conditional_block |
indexed_vec.rs | // Copyright 2016 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 ... | (&self) -> bool {
self.raw.is_empty()
}
#[inline]
pub fn into_iter(self) -> vec::IntoIter<T> {
self.raw.into_iter()
}
#[inline]
pub fn iter(&self) -> slice::Iter<T> {
self.raw.iter()
}
#[inline]
pub fn iter_mut(&mut self) -> slice::IterMut<T> {
self... | is_empty | identifier_name |
indexed_vec.rs | // Copyright 2016 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 ... | &self.raw[index.index()]
}
}
impl<I: Idx, T> IndexMut<I> for IndexVec<I, T> {
#[inline]
fn index_mut(&mut self, index: I) -> &mut T {
&mut self.raw[index.index()]
}
}
impl<I: Idx, T> Default for IndexVec<I, T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl... | type Output = T;
#[inline]
fn index(&self, index: I) -> &T { | random_line_split |
indexed_vec.rs | // Copyright 2016 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 ... |
}
impl<'a, I: Idx, T> IntoIterator for &'a mut IndexVec<I, T> {
type Item = &'a mut T;
type IntoIter = slice::IterMut<'a, T>;
#[inline]
fn into_iter(mut self) -> slice::IterMut<'a, T> {
self.raw.iter_mut()
}
}
| {
self.raw.iter()
} | identifier_body |
exampleNestedNgRepeat.js | 'use strict';
var examplesAppModule = require('../examplesApp');
/**
* @ngInject
*/
examplesAppModule
.controller('NestedNgRepeat', ['$timeout', '$scope', '$element', 'dragularService', function NestedNgRepeatCtrl($timeout, $scope, $element, dragularService) {
$timeout(function() { // timeount due to ngRepeat ... | return handle.classList.contains('row-handle');
}
});
dragularService($element.children(), {
nameSpace: 'cells',
moves: function excludeHandle (el, container, handle) {
return !handle.classList.contains('row-handle');
}
});
}, 0);
$scope.ite... | dragularService($element, {
nameSpace: 'rows',
moves: function rowOnly (el, container, handle) { | random_line_split |
Handshake.js | 'use strict';
//Require the encryption modules
const RSA = require('simple-encryption').RSA;
const AES = require('simple-encryption').AES;
//Error handler
const errorHandler = require('../error/errorHandler.js');
const errorList = require('../error/errorList.js');
//Export main function
module.exports = function(socket... |
//Callback to the caller with the challenge, sessionKey, and no error
callback(null, decrypted, sessionKey);
};
//Send a message
try {
socket.send(JSON.stringify({type: 'handshake', payload: encrypted}));
} catch(e) {
//Destroy socket
socket.close();
return;
}
};
| {
return callback(new errorList.HandshakeGeneric());
} | conditional_block |
Handshake.js | 'use strict';
//Require the encryption modules
const RSA = require('simple-encryption').RSA; | //Error handler
const errorHandler = require('../error/errorHandler.js');
const errorList = require('../error/errorList.js');
//Export main function
module.exports = function(socket, serverPublicKey, callback) {
//Generate a session key
const sessionKey = AES.generateKey();
//Encrypt it with the serverPublicKey
... | const AES = require('simple-encryption').AES; | random_line_split |
i18n_plural_pipe.ts | /**
* @license
* Copyright Google Inc. 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 {Pipe, PipeTransform} from '@angular/core';
import {isBlank} from '../facade/lang';
import {NgLocalization, g... | (private _localization: NgLocalization) {}
transform(value: number, pluralMap: {[count: string]: string}): string {
if (isBlank(value)) return '';
if (typeof pluralMap !== 'object' || pluralMap === null) {
throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap);
}
const key = getPluralC... | constructor | identifier_name |
i18n_plural_pipe.ts | /**
* @license
* Copyright Google Inc. 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 {Pipe, PipeTransform} from '@angular/core';
import {isBlank} from '../facade/lang';
import {NgLocalization, g... |
}
| {
if (isBlank(value)) return '';
if (typeof pluralMap !== 'object' || pluralMap === null) {
throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap);
}
const key = getPluralCategory(value, Object.keys(pluralMap), this._localization);
return pluralMap[key].replace(_INTERPOLATION_REGEXP,... | identifier_body |
i18n_plural_pipe.ts | /**
* @license
* Copyright Google Inc. 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 {Pipe, PipeTransform} from '@angular/core';
import {isBlank} from '../facade/lang';
import {NgLocalization, g... |
const key = getPluralCategory(value, Object.keys(pluralMap), this._localization);
return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString());
}
}
| {
throw new InvalidPipeArgumentError(I18nPluralPipe, pluralMap);
} | conditional_block |
i18n_plural_pipe.ts | /**
* @license
* Copyright Google Inc. 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 {Pipe, PipeTransform} from '@angular/core';
import {isBlank} from '../facade/lang';
import {NgLocalization, g... | *
* @experimental
*/
@Pipe({name: 'i18nPlural', pure: true})
export class I18nPluralPipe implements PipeTransform {
constructor(private _localization: NgLocalization) {}
transform(value: number, pluralMap: {[count: string]: string}): string {
if (isBlank(value)) return '';
if (typeof pluralMap !== 'obj... | * {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'} | random_line_split |
mimetype.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
nbformat
} from '@jupyterlab/coreutils';
/**
* The mime type service of a code editor.
*/
export
interface IEditorMimeTypeService {
/**
* Get a mime type for the given language info.
*
* @pa... | } | random_line_split | |
Media.tsx | import * as React from 'react';
import { Size } from './Modifiers';
import { Icon } from './Icon';
import { Content } from './Grid';
const BMedia = require('re-bulma/lib/components/media/media').default;
const BMediaContent = require('re-bulma/lib/components/media/media-content').default;
const BMediaLeft = r... | () {
return <BMedia {...this.props} />;
}
}
export class MediaContent extends React.PureComponent<MediaProps, void> {
render() {
return <BMediaContent {...this.props} />;
}
}
export class MediaLeft extends React.PureComponent<MediaProps, void> {
render() {
return <... | render | identifier_name |
Media.tsx | import * as React from 'react';
import { Size } from './Modifiers';
import { Icon } from './Icon';
import { Content } from './Grid';
const BMedia = require('re-bulma/lib/components/media/media').default;
const BMediaContent = require('re-bulma/lib/components/media/media-content').default;
const BMediaLeft = r... | }
export class MediaLeft extends React.PureComponent<MediaProps, void> {
render() {
return <BMediaLeft {...this.props} />;
}
}
export class MediaRight extends React.PureComponent<MediaProps, void> {
render() {
return <BMediaRight {...this.props} />;
}
}
interface MediaPa... | render() {
return <BMediaContent {...this.props} />;
}
| random_line_split |
test_utils.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 {browser} from 'protractor';
import {openBrowser, runBenchmark} from '../../../../dev-infra/benchmark/driver-... | ({id, prepare, setup, work}: {
id: string; prepare ? () : void; setup ? () : void; work(): void;
}) {
browser.rootEl = '#root';
return runBenchmark({
id: id,
url: '',
ignoreBrowserSynchronization: true,
params: [],
work: work,
prepare: prepare,
setup: setup
});
}
export function ope... | runTreeBenchmark | identifier_name |
test_utils.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 {browser} from 'protractor';
import {openBrowser, runBenchmark} from '../../../../dev-infra/benchmark/driver-util... | random_line_split | |
test_utils.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 {browser} from 'protractor';
import {openBrowser, runBenchmark} from '../../../../dev-infra/benchmark/driver-... |
export function openTreeBenchmark() {
browser.rootEl = '#root';
openBrowser({
url: '',
ignoreBrowserSynchronization: true,
params: [{name: 'depth', value: 4}],
});
}
| {
browser.rootEl = '#root';
return runBenchmark({
id: id,
url: '',
ignoreBrowserSynchronization: true,
params: [],
work: work,
prepare: prepare,
setup: setup
});
} | identifier_body |
lc0100_same_tree.py | """Leetcode 100. Same Tree
Easy
URL: https://leetcode.com/problems/same-tree/
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and
the nodes have the same value.
Example 1:
Input: 1 1
/ \ ... | main() | conditional_block | |
lc0100_same_tree.py | """Leetcode 100. Same Tree
Easy
URL: https://leetcode.com/problems/same-tree/
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and
the nodes have the same value.
Example 1:
Input: 1 1
/ \ ... | return False
# Recursively check left/right subtrees.
return (self.isSameTree(p.left, q.left) and
self.isSameTree(p.right, q.right))
class SolutionPreorderIter(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
... | """
:type p: TreeNode
:type q: TreeNode
:rtype: bool
Apply recursive preorder traversal to check same tree.
Time complexity: O(n).
Space complexity: O(n).
"""
# Check if both root don't exist.
if not p and not q:
return True
... | identifier_body |
lc0100_same_tree.py | """Leetcode 100. Same Tree
Easy
URL: https://leetcode.com/problems/same-tree/
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and
the nodes have the same value.
Example 1:
Input: 1 1
/ \ ... | (self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
Apply recursive preorder traversal to check same tree.
Time complexity: O(n).
Space complexity: O(n).
"""
# Check if both root don't exist.
if not p and not q:
... | isSameTree | identifier_name |
lc0100_same_tree.py | """Leetcode 100. Same Tree
Easy
URL: https://leetcode.com/problems/same-tree/
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and
the nodes have the same value.
Example 1:
Input: 1 1
/ \ ... | # Check if just one of roots exits.
if not cur_p or not cur_q:
return False
# If both exist, check their values are the same.
if cur_p.val != cur_q.val:
return False
# Add root's right and then left to stack, since stack is F... | continue
| random_line_split |
tcal.js | such as January or March
{'t': 'F', 'r': A_TCALCONF.months.join('|'), 'p': function (d_date, s_value) { for (var m = 0; m < 12; m++) if (A_TCALCONF.months[m] == s_value) { d_date.setMonth(m); return d_date; }}, 'g': function (d_date) { return A_TCALCONF.months[d_date.getMonth()]; }},
// Day of the month, 2 digits... |
function f_tcalResetTime (d_date) {
d_date.setMilliseconds(0);
d_date.setSeconds(0);
d_date.setMinutes(0);
d_date.setHours(12);
return d_date;
}
// closes calendar and returns all inputs to default state
function f_tcalCancel () {
var s_pfx = A_TCALCONF.cssprefix;
var e_cal = document.getEleme... | {
var s_units = (s_units == 'y' ? 'FullYear' : 'Month');
var d_result = new Date(d_date);
if (d_diff) {
d_result['set' + s_units](d_date['get' + s_units]() + d_diff);
if (d_result.getDate() != d_date.getDate())
d_result.setDate(0);
}
return ' onclick="f_tcalUpdate(' + d_result.valueOf() + (d_diff ... | identifier_body |
tcal.js | % 7] + '</th>';
s_html += '</tr>' ;
// print calendar table
var n_date, n_month, d_current = new Date(d_firstDay);
while (d_current.getMonth() == d_date.getMonth() ||
d_current.getMonth() == d_firstDay.getMonth()) {
s_html +='<tr>';
for (var n_wday = 0; n_wday < 7; n_wday++) {
a_class = [];
... | {
window.attachEvent('onload', f_func);
} | conditional_block | |
tcal.js | _selected)
d_selected = f_tcalParseDate(A_TCALCONF.selected, A_TCALCONF.format);
if (!d_selected)
d_selected = new Date(d_today);
// show calendar for passed or selected date
d_date = d_date ? f_tcalResetTime(d_date) : new Date(d_selected);
var d_firstDay = new Date(d_date);
d_firstDay.setDate(1);
... | f_tcalRemoveClass | identifier_name | |
tcal.js | ]|3[01]', 'p': function (d_date, n_value) { d_date.setDate(Number(n_value)); if (d_date.getDate() != n_value) d_date.setDate(0); return d_date }, 'g': function (d_date) { var n_date = d_date.getDate(); return n_date; }},
// A full textual representation of the day of the week
{'t': 'l', 'r': A_TCALCONF.longwdays.j... | continue;
| random_line_split | |
column_function.py | # This file is part of Osgende
# Copyright (C) 2017 Sarah Hoffmann
#
# This is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distribu... | compiler.preparer.quote(element.name)
)
class ColumnFunction(functions.FunctionElement):
__visit_name__ = 'function'
@property
def columns(self):
return FromClause.columns.fget(self)
def _populate_column_collection(self):
for name, t in self.column_names:
self... |
@compiles(FunctionColumn)
def _compile_function_column(element, compiler, **kw):
return "(%s).%s" % (
compiler.process(element.function, **kw), | random_line_split |
column_function.py | # This file is part of Osgende
# Copyright (C) 2017 Sarah Hoffmann
#
# This is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distribu... |
return co
@compiles(FunctionColumn)
def _compile_function_column(element, compiler, **kw):
return "(%s).%s" % (
compiler.process(element.function, **kw),
compiler.preparer.quote(element.name)
)
class ColumnFunction(functions.FunctionElement):
__visit_name__ = 'function'
@pr... | selectable._columns[co.key] = co | conditional_block |
column_function.py | # This file is part of Osgende
# Copyright (C) 2017 Sarah Hoffmann
#
# This is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distribu... | selectable._columns[co.key] = co
return co
@compiles(FunctionColumn)
def _compile_function_column(element, compiler, **kw):
return "(%s).%s" % (
compiler.process(element.function, **kw),
compiler.preparer.quote(element.name)
)
class ColumnFunction(functions.FunctionEleme... | def __init__(self, function, name, type_=None):
self.function = self.table = function
self.name = self.key = name
self.type_ = type_
self.is_literal = False
@property
def _from_objects(self):
return []
def _make_proxy(self, selectable, name=None, attach=True,
... | identifier_body |
column_function.py | # This file is part of Osgende
# Copyright (C) 2017 Sarah Hoffmann
#
# This is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or any later version.
#
# This program is distribu... | (self, function, name, type_=None):
self.function = self.table = function
self.name = self.key = name
self.type_ = type_
self.is_literal = False
@property
def _from_objects(self):
return []
def _make_proxy(self, selectable, name=None, attach=True,
... | __init__ | identifier_name |
test_util.py | from collections import OrderedDict
from datetime import date
from nose.tools import eq_, assert_true, assert_false
from mosql.compat import binary_type, text_type
from mosql.util import (
autoparam, build_set, build_where, param, ___,
_is_iterable_not_str,
)
def test_is_iterable_not_str():
# Iterable o... | eq_(gen, exp)
def test_build_set():
gen = build_set(OrderedDict([
('a', 1), ('b', True), ('c', date(2013, 4, 16)),
]))
eq_(gen, '"a"=1, "b"=TRUE, "c"=\'2013-04-16\'')
def test_build_set_prepared():
gen = build_set(OrderedDict([
('custom_param', param('myparam')), ('auto_param', a... | 'AND "using_alias" = %(using_alias)s') | random_line_split |
test_util.py | from collections import OrderedDict
from datetime import date
from nose.tools import eq_, assert_true, assert_false
from mosql.compat import binary_type, text_type
from mosql.util import (
autoparam, build_set, build_where, param, ___,
_is_iterable_not_str,
)
def test_is_iterable_not_str():
# Iterable o... | gen = build_set(OrderedDict([
('custom_param', param('myparam')), ('auto_param', autoparam),
]))
eq_(gen, '"custom_param"=%(myparam)s, "auto_param"=%(auto_param)s') | identifier_body | |
test_util.py | from collections import OrderedDict
from datetime import date
from nose.tools import eq_, assert_true, assert_false
from mosql.compat import binary_type, text_type
from mosql.util import (
autoparam, build_set, build_where, param, ___,
_is_iterable_not_str,
)
def test_is_iterable_not_str():
# Iterable o... | ():
gen = build_set(OrderedDict([
('a', 1), ('b', True), ('c', date(2013, 4, 16)),
]))
eq_(gen, '"a"=1, "b"=TRUE, "c"=\'2013-04-16\'')
def test_build_set_prepared():
gen = build_set(OrderedDict([
('custom_param', param('myparam')), ('auto_param', autoparam),
]))
eq_(gen, '"cust... | test_build_set | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of ... | pub mod cursor;
#[macro_use]
pub mod values;
pub mod viewport;
pub use values::ToCss; | random_line_split | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of ... | {}
// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
// / hidpi_ratio => ScreenPx
// / desktop_zoom => ViewportPx
// / pinch_zoom => PagePx
pub mod cursor;
#[macro_use]
pub mod values;
pub mod viewport;
pub use values::ToCss;
| PagePx | identifier_name |
color.rs | use crate::{
DocumentSelector, DynamicRegistrationClientCapabilities, PartialResultParams, Range,
TextDocumentIdentifier, TextEdit, WorkDoneProgressParams,
};
use serde::{Deserialize, Serialize};
pub type DocumentColorClientCapabilities = DynamicRegistrationClientCapabilities;
#[derive(Debug, Eq, PartialEq, C... | {
/// The text document
pub text_document: TextDocumentIdentifier,
#[serde(flatten)]
pub work_done_progress_params: WorkDoneProgressParams,
#[serde(flatten)]
pub partial_result_params: PartialResultParams,
}
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "cam... | DocumentColorParams | identifier_name |
color.rs | use crate::{
DocumentSelector, DynamicRegistrationClientCapabilities, PartialResultParams, Range,
TextDocumentIdentifier, TextEdit, WorkDoneProgressParams,
};
use serde::{Deserialize, Serialize};
pub type DocumentColorClientCapabilities = DynamicRegistrationClientCapabilities;
#[derive(Debug, Eq, PartialEq, C... |
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StaticTextDocumentColorProviderOptions {
/// A document selector to identify the scope of the registration. If set to null
/// the document selector provided on the client side will be used.
pub doc... | random_line_split | |
demo.py | import numpy as np
import hcn
from IPython import embed, get_ipython
import vtk_visualizer as vv
if __name__ == "__main__":
| #vv.plothh(res, block=True)
#s = m.create_surface_model(0.1)
#embed()
| m = hcn.Model3D.from_file("b4.obj", "m")
m = m.select_x(0, 1)
m = m.select_y(0, 1)
m = m.select_z(0.01, 1)
vv.plotxyz(m.to_array(), block=True)
sm = m.smoothed(knn=160, order=1)
vv.plotxyz(sm.to_array(), block=True)
vv.plotxyz(m.to_array(), block=True)
#vv.plotxyz(m.to_array(), block=Tru... | conditional_block |
demo.py | import numpy as np
import hcn
from IPython import embed, get_ipython
| m = m.select_x(0, 1)
m = m.select_y(0, 1)
m = m.select_z(0.01, 1)
vv.plotxyz(m.to_array(), block=True)
sm = m.smoothed(knn=160, order=1)
vv.plotxyz(sm.to_array(), block=True)
vv.plotxyz(m.to_array(), block=True)
#vv.plotxyz(m.to_array(), block=True)
#ch = m.get_convex_hull()
#vv.... | import vtk_visualizer as vv
if __name__ == "__main__":
m = hcn.Model3D.from_file("b4.obj", "m") | random_line_split |
x86.rs | // Copyright 2012-2015 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-MI... |
},
target_triple: target_triple,
cc_args: vec!("-m32".to_string()),
};
}
| {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
} | conditional_block |
x86.rs | // Copyright 2012-2015 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-MI... | (target_triple: String, target_os: abi::Os)
-> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\
-i32:32:32-i64:32:64\
... | get_target_strs | identifier_name |
x86.rs | // Copyright 2012-2015 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-MI... | target_triple: target_triple,
cc_args: vec!("-m32".to_string()),
};
} | random_line_split | |
x86.rs | // Copyright 2012-2015 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-MI... |
abi::OsWindows => {
"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32".to_string()
}
abi::OsLinux => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string()
}
abi::OsAndroid => {
"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:... | {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16\
-i32:32:32-i64:32:64\
-f32:32:32-f64:32:64-v64:64:64\
-v128:128:128-a:0:64-f80:128:128\... | identifier_body |
guildDelete.js | const excludedTables = ["blacklist", "musicCache", "timedEvents"];
const statPoster = require("../../modules/statPoster.js");
module.exports = async guild => {
let tables = await r.tableList().run();
for(let table of tables) {
let indexes = await r.table(table).indexList().run();
if(~indexes.indexOf("guildID")) r... | }
statPoster();
}; | await bot.createMessage(bot.config.bot.serverChannel, content);
} catch(err) {
console.error(`Failed to send message to server log: ${err.message}`);
} | random_line_split |
http2.rs | extern crate hyper;
extern crate futures;
extern crate tokio_tls;
extern crate native_tls;
extern crate tokio_core;
extern crate httpbis;
extern crate tls_api_openssl;
use std::thread;
use std::str::FromStr;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio_core::r... |
}
impl httpbis::Service for Proxy4Http2 {
fn start_request(&self, headers: httpbis::Headers, _req: httpbis::HttpPartStream)
-> httpbis::Response
{
let mut core = Core::new().expect("http2 backend client core error");
let handle = core.handle();
let backend_client = hyper::Clien... | {
Self {
routes: Arc::new(routes),
roundrobin_counter: Arc::new(AtomicUsize::new(0)),
}
} | identifier_body |
http2.rs | extern crate hyper;
extern crate futures;
extern crate tokio_tls;
extern crate native_tls;
extern crate tokio_core;
extern crate httpbis;
extern crate tls_api_openssl;
use std::thread;
use std::str::FromStr;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio_core::r... | let url = url_str.parse::<hyper::Uri>().expect("uri error");
let proxied_req = hyper::client::Request::new(
hyper::Method::from_str(headers.method()).expect("invalid method"), url);
let mut backend_req_headers = hyper::header::Headers::new();
for req_header in headers.0 {
... | // FIXME: only use index 0
let backend_index = self.roundrobin_counter.fetch_add(1, Ordering::Relaxed);
let backend_addr = self.routes[backend_index % self.routes.len()].clone();
let url_str = format!("http://{}{}", backend_addr, headers.path()); | random_line_split |
http2.rs | extern crate hyper;
extern crate futures;
extern crate tokio_tls;
extern crate native_tls;
extern crate tokio_core;
extern crate httpbis;
extern crate tls_api_openssl;
use std::thread;
use std::str::FromStr;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio_core::r... | (&self, headers: httpbis::Headers, _req: httpbis::HttpPartStream)
-> httpbis::Response
{
let mut core = Core::new().expect("http2 backend client core error");
let handle = core.handle();
let backend_client = hyper::Client::new(&handle);
// FIXME: only use index 0
let... | start_request | identifier_name |
group_detail_active.tsx | import React from "react";
import { t } from "../i18next_wrapper";
import { TaggedPointGroup, TaggedPoint, PointType, TaggedTool } from "farmbot";
import { DeleteButton } from "../ui/delete_button";
import { save, edit } from "../api/crud";
import { Paths } from "./paths";
import { ErrorBoundary } from "../error_bounda... |
}} />
<GroupSortSelection group={group} dispatch={dispatch}
pointsSelectedByGroup={this.pointsSelectedByGroup} />
<GroupMemberDisplay group={group} dispatch={dispatch}
pointsSelectedByGroup={this.pointsSelectedByGroup}
hovered={this.props.hovered}
iconDisplay={this.s... | {
this.props.dispatch(edit(this.props.group, { name: newGroupName }));
this.props.dispatch(save(this.props.group.uuid));
} | conditional_block |
group_detail_active.tsx | import React from "react";
import { t } from "../i18next_wrapper";
import { TaggedPointGroup, TaggedPoint, PointType, TaggedTool } from "farmbot";
import { DeleteButton } from "../ui/delete_button";
import { save, edit } from "../api/crud";
import { Paths } from "./paths";
import { ErrorBoundary } from "../error_bounda... |
componentWillUnmount = () =>
this.props.dispatch(setSelectionPointType(undefined));
toggleIconShow = () => this.setState({ iconDisplay: !this.state.iconDisplay });
render() {
const { group, dispatch } = this.props;
return <ErrorBoundary>
<label>{t("GROUP NAME")}</label>
<input
... | {
return pointsSelectedByGroup(this.props.group, this.props.allPoints);
} | identifier_body |
group_detail_active.tsx | import React from "react";
import { t } from "../i18next_wrapper";
import { TaggedPointGroup, TaggedPoint, PointType, TaggedTool } from "farmbot";
import { DeleteButton } from "../ui/delete_button";
import { save, edit } from "../api/crud";
import { Paths } from "./paths";
import { ErrorBoundary } from "../error_bounda... | render() {
const { group, dispatch } = this.props;
return <ErrorBoundary>
<label>{t("GROUP NAME")}</label>
<input
name="name"
defaultValue={group.body.name}
onBlur={e => {
const newGroupName = e.currentTarget.value;
if (newGroupName != "" && newGroupName... | random_line_split | |
group_detail_active.tsx | import React from "react";
import { t } from "../i18next_wrapper";
import { TaggedPointGroup, TaggedPoint, PointType, TaggedTool } from "farmbot";
import { DeleteButton } from "../ui/delete_button";
import { save, edit } from "../api/crud";
import { Paths } from "./paths";
import { ErrorBoundary } from "../error_bounda... | () {
return pointsSelectedByGroup(this.props.group, this.props.allPoints);
}
componentWillUnmount = () =>
this.props.dispatch(setSelectionPointType(undefined));
toggleIconShow = () => this.setState({ iconDisplay: !this.state.iconDisplay });
render() {
const { group, dispatch } = this.props;
r... | pointsSelectedByGroup | identifier_name |
test-scanl.ts | import {alphabetArray, expectEqual, LinkedListNode, LLNode, linkedListToList} from "../helpers";
import {scanl} from "../../src/list/scanl";
describe('#scanl', () => {
const unlinkedNodes = alphabetArray.map(char => ({data: char})) as LLNode[];
it('should return a list of successively reduced values from left to ... | data.data.charCodeAt(0) - ind2 === charCodeToTest
);
});
})
)
.toEqual(true);
});
it('should return an empty list when receiving an empty one', () => {
expectEqual(scanl(x => x * 2, 99, []), []);
expectEqual(scanl(x => x + 2, '99', ''), []);
});
}); | result.every(node => {
const nodesList: LinkedListNode[] = linkedListToList(node);
return alphabetArray.slice(alphabetArray.indexOf(node.data)).every((char, ind1) => {
const charCodeToTest = char.charCodeAt(0);
return nodesList.slice(ind1).every((data, ind2) => | random_line_split |
test.js | 'use strict';
/*
* Attention: let's add end-to-end tests instead of this!
* Check ./end-to-end/moro.tests.bats
*
*/
import test from 'ava';
import {
printSingleDayReport,
printAllDaysReport,
printSearchResults,
} from '../lib/utils/helpers.js';
const moment = require('moment');
const diff = (start, end) => ... | { date: '2017-03-15', workHours: diff('2017-03-15 09:10', '2017-03-15 17:10') },
];
t.pass(printAllDaysReport(reprotRecord));
});
test('printSearchResults runs without crashing', (t) => {
const searchResults = [
{ date: '2017-08-04', createdat: '17:00', note: '#Workrelated' },
{ date: '2017-08-04', c... | random_line_split | |
io.rs | use std::os::raw::{c_char, c_void};
use std::mem::transmute;
use super::CFixedString;
#[repr(C)]
pub enum | {
Ok,
Fail,
Converted,
Truncated,
OutOfData,
}
#[repr(C)]
pub struct CPDSaveState {
pub priv_data: *mut c_void,
pub write_int: fn(priv_data: *mut c_void, data: i64),
pub write_double: fn(priv_data: *mut c_void, data: f64),
pub write_string: fn(priv_data: *mut c_void, data: *const c... | LoadState | identifier_name |
io.rs | use std::os::raw::{c_char, c_void};
use std::mem::transmute;
use super::CFixedString;
#[repr(C)]
pub enum LoadState {
Ok,
Fail,
Converted,
Truncated,
OutOfData,
}
#[repr(C)]
pub struct CPDSaveState {
pub priv_data: *mut c_void,
pub write_int: fn(priv_data: *mut c_void, data: i64),
pub ... |
}
| {
let mut len: i32 = 0;
let len_state = ((*self.0).read_string_len)((*self.0).priv_data, &mut len);
match len_state {
LoadState::Fail => return LoadResult::Fail,
LoadState::OutOfData => return LoadResult::OutOfData,
_ => {}
}
let mut buf = vec!... | identifier_body |
io.rs | use std::os::raw::{c_char, c_void};
use std::mem::transmute;
use super::CFixedString;
#[repr(C)]
pub enum LoadState {
Ok,
Fail,
Converted,
Truncated,
OutOfData,
}
#[repr(C)]
pub struct CPDSaveState {
pub priv_data: *mut c_void,
pub write_int: fn(priv_data: *mut c_void, data: i64),
pub ... | pub fn new(api: *mut CPDLoadState) -> StateLoader<'a> {
unsafe { StateLoader(&mut *api) }
}
pub fn read_int(&mut self) -> LoadResult<i64> {
let mut res: i64 = 0;
let state = ((*self.0).read_int)((*self.0).priv_data, &mut res);
LoadResult::from_state(state, res)
}
pu... |
pub struct StateLoader<'a>(&'a mut CPDLoadState);
impl<'a> StateLoader<'a> { | random_line_split |
instr_kxnorb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn kxnorb_1() {
run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1... | {
run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K2)), operand3: Some(Direct(K5)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 237, 70, 205], OperandSize::Qword)
} | identifier_body | |
instr_kxnorb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K4)), operand3: Some(Direct(K4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 221, 70, 204], OperandSize::Dword)
}
#[test]
fn kxnorb_2... | kxnorb_1 | identifier_name |
instr_kxnorb.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*; |
#[test]
fn kxnorb_1() {
run_test(&Instruction { mnemonic: Mnemonic::KXNORB, operand1: Some(Direct(K1)), operand2: Some(Direct(K4)), operand3: Some(Direct(K4)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[197, 221, 70, 204], OperandSize::Dword)
}
... | use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test; | random_line_split |
cluster.rs | //! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CEr... | use rand;
use std::sync::atomic::{AtomicIsize, Ordering};
/// Load balancing strategy
#[derive(PartialEq)]
pub enum LoadBalancingStrategy {
/// Round Robin balancing strategy
RoundRobin,
/// Random balancing strategy
Random,
}
impl LoadBalancingStrategy {
/// Returns next value for selected load b... | use authenticators::Authenticator;
use compression::Compression;
use r2d2;
use transport::CDRSTransport; | random_line_split |
cluster.rs | //! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CEr... | <T> {
strategy: LoadBalancingStrategy,
nodes: Vec<T>,
i: AtomicIsize,
}
impl<T> LoadBalancer<T> {
/// Factory function which creates new `LoadBalancer` with provided strategy.
pub fn new(nodes: Vec<T>, strategy: LoadBalancingStrategy) -> LoadBalancer<T> {
LoadBalancer {
nodes: n... | LoadBalancer | identifier_name |
cluster.rs | //! This modules contains an implementation of [r2d2](https://github.com/sfackler/r2d2)
//! functionality of connection pools. To get more details about creating r2d2 pools
//! please refer to original documentation.
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CEr... |
/// Returns next node basing on provided strategy.
pub fn next(&self) -> Option<&T> {
let next = self.strategy
.next(&self.nodes, self.i.load(Ordering::Relaxed) as usize);
if self.strategy == LoadBalancingStrategy::RoundRobin {
self.i.fetch_add(1, Ordering::Relaxed);
... | {
LoadBalancer {
nodes: nodes,
strategy: strategy,
i: AtomicIsize::new(0),
}
} | identifier_body |
index.ts | import { AzureFunction, Context } from '@azure/functions'
import { performance } from 'perf_hooks'
import { ListSchoolsService } from './list-schools-service'
import { IFunctionTimer } from '../../azure/functions'
const functionName = 'ps-report-1-list-schools'
const timerTrigger: AzureFunction = async function (cont... |
const start = performance.now()
const meta = { processCount: 0, errorCount: 0 }
try {
const schoolListService = new ListSchoolsService(context.log)
const messages = await schoolListService.getSchoolMessages()
context.bindings.schoolMessages = messages
meta.processCount = messages.length
} catch... | {
// This function could potentially deliver a lot of work to do to the functions, and none of it is urgent. No surprises!
context.log(`${functionName}: timer is past due, exiting.`)
return
} | conditional_block |
index.ts | import { AzureFunction, Context } from '@azure/functions'
import { performance } from 'perf_hooks'
import { ListSchoolsService } from './list-schools-service'
import { IFunctionTimer } from '../../azure/functions'
const functionName = 'ps-report-1-list-schools'
const timerTrigger: AzureFunction = async function (cont... | export default timerTrigger | }
| random_line_split |
cors.ts | export interface CORSConfig {
allowOrigin?: string;
allowMethods?: string[];
allowHeaders?: string[];
allowCredentials?: boolean;
maxAge?: number;
}
export const generateCorsHeaders = (corsOptions: boolean | CORSConfig) => {
const defaultCorsHeader = {
'Access-Control-Allow-Origin': '*',
'Access-Co... | .map(methods => {
return methods.toUpperCase();
})
.join(', ');
}
if (corsOptions.allowOrigin) {
tmp['Access-Control-Allow-Origin'] = corsOptions.allowOrigin;
}
if (corsOptions.maxAge) {
tmp['Access-Control-Max-Age'] = corsOptions.maxAge;
}
if (corsOptions.allowHeaders) {
... | if (corsOptions.allowCredentials) {
tmp['Access-Control-Allow-Credentials'] = true;
}
if (corsOptions.allowMethods) {
tmp['Access-Control-Request-Method'] = corsOptions.allowMethods | random_line_split |
cors.ts | export interface CORSConfig {
allowOrigin?: string;
allowMethods?: string[];
allowHeaders?: string[];
allowCredentials?: boolean;
maxAge?: number;
}
export const generateCorsHeaders = (corsOptions: boolean | CORSConfig) => {
const defaultCorsHeader = {
'Access-Control-Allow-Origin': '*',
'Access-Co... |
if (corsOptions.allowMethods) {
tmp['Access-Control-Request-Method'] = corsOptions.allowMethods
.map(methods => {
return methods.toUpperCase();
})
.join(', ');
}
if (corsOptions.allowOrigin) {
tmp['Access-Control-Allow-Origin'] = corsOptions.allowOrigin;
}
if (corsOptions.ma... | {
tmp['Access-Control-Allow-Credentials'] = true;
} | conditional_block |
Repairing.py | #This file is distributed under the terms of the GNU General Public license.
#Copyright (C) 2011 Jekin Trivedi <jekintrivedi@gmail.com> (See the file COPYING for details).
from atlas import *
from physics import *
from physics import Quaternion
from physics import Vector3D
import server
class Repairing(server.Task):... | if square_distance(self.character.location, self.target().location) > self.target().location.bbox.square_bounding_radius():
self.progress = current_status
self.rate = 0
return self.next_tick(1.75)
# Some entity do not have status defined. If not present we assume tha... | # print "I am exhausted"
self.irrelevant()
return
| random_line_split |
Repairing.py | #This file is distributed under the terms of the GNU General Public license.
#Copyright (C) 2011 Jekin Trivedi <jekintrivedi@gmail.com> (See the file COPYING for details).
from atlas import *
from physics import *
from physics import Quaternion
from physics import Vector3D
import server
class Repairing(server.Task):... | if len(op) < 1:
sys.stderr.write("Repair task has no target in repair op")
# FIXME Use weak references, once we have them
self.target = server.world.get_object_ref(op[0].id)
self.tool = op.to
def tick_operation(self, op):
""" This method is called repeatedly, ea... | """A very simple Repair system for Repairing structures."""
materials = ["wood"]
def consume_materials (self) :
""" A method which gets the material to be consumed from the inventory & returns the consume operation """
for item in self.character.contains:
if item.type[0] == str(se... | identifier_body |
Repairing.py | #This file is distributed under the terms of the GNU General Public license.
#Copyright (C) 2011 Jekin Trivedi <jekintrivedi@gmail.com> (See the file COPYING for details).
from atlas import *
from physics import *
from physics import Quaternion
from physics import Vector3D
import server
class Repairing(server.Task):... | (self, op):
""" The repair op is FROM the the character,
TO the structure that is getting Repaired which we
term the target. """
if len(op) < 1:
sys.stderr.write("Repair task has no target in repair op")
# FIXME Use weak references, once we have them
... | repair_operation | identifier_name |
Repairing.py | #This file is distributed under the terms of the GNU General Public license.
#Copyright (C) 2011 Jekin Trivedi <jekintrivedi@gmail.com> (See the file COPYING for details).
from atlas import *
from physics import *
from physics import Quaternion
from physics import Vector3D
import server
class Repairing(server.Task):... |
else :
self.irrelevant()
else:
set = Operation("set", Entity(self.target().id, status = 1),
to = self.target())
res.append(set)
self.irrelevant()
self.progress = current_status
self.rate = 0.1 / 1.75
... | res.append(consume) | conditional_block |
custom_properties.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/. */
use cssparser::{Parser, ParserInput};
use servo_arc::Arc;
use style::custom_properties::{
CssEnvironment, Cus... | }
#[bench]
fn cascade_custom_simple(b: &mut Bencher) {
b.iter(|| {
let parent = cascade(&[("foo", "10px"), ("bar", "100px")], None);
test::black_box(cascade(
&[("baz", "calc(40em + 4px)"), ("bazz", "calc(30em + 4px)")],
parent.as_ref(),
))
})
}
| {
let declarations = name_and_value
.iter()
.map(|&(name, value)| {
let mut input = ParserInput::new(value);
let mut parser = Parser::new(&mut input);
let name = Name::from(name);
let value = CustomDeclarationValue::Value(SpecifiedValue::parse(&mut par... | identifier_body |
custom_properties.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/. */
use cssparser::{Parser, ParserInput};
use servo_arc::Arc;
use style::custom_properties::{
CssEnvironment, CustomPropertiesBuilder, CustomPropertiesMap, Name, SpecifiedValue,
};
use... | random_line_split | |
custom_properties.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/. */
use cssparser::{Parser, ParserInput};
use servo_arc::Arc;
use style::custom_properties::{
CssEnvironment, Cus... | (b: &mut Bencher) {
b.iter(|| {
let parent = cascade(&[("foo", "10px"), ("bar", "100px")], None);
test::black_box(cascade(
&[("baz", "calc(40em + 4px)"), ("bazz", "calc(30em + 4px)")],
parent.as_ref(),
))
})
}
| cascade_custom_simple | identifier_name |
symbol.rs | xt.modern() == SyntaxContext::empty() {
serializer.serialize_str(&self.name.as_str())
} else { // FIXME(jseyfried) intercrate hygiene
let mut string = "#".to_owned();
string.push_str(&self.name.as_str());
serializer.serialize_str(&string)
}
}
}
impl<'... |
impl<'de> Deserialize<'de> for Symbol {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
String::deserialize(deserializer).map(|s| Symbol::intern(&s))
}
}
impl<T: ::std::ops::Deref<Target=str>> PartialEq<T> for Symbol {
fn eq(&self, other: &T) -... | } | random_line_split |
symbol.rs | Result<Self, D::Error>
where D: Deserializer<'de>
{
let string = String::deserialize(deserializer)?;
Ok(if !string.starts_with('#') {
Ident::from_str(&string)
} else { // FIXME(jseyfried) intercrate hygiene
Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))... | with_interner | identifier_name | |
symbol.rs | xt.modern() == SyntaxContext::empty() {
serializer.serialize_str(&self.name.as_str())
} else { // FIXME(jseyfried) intercrate hygiene
let mut string = "#".to_owned();
string.push_str(&self.name.as_str());
serializer.serialize_str(&string)
}
}
}
impl<'... |
fn prefill(init: &[&str]) -> Self {
let mut this = Interner::new();
for &string in init {
this.intern(string);
}
this
}
pub fn intern(&mut self, string: &str) -> Symbol {
if let Some(&name) = self.names.get(string) {
return name;
}
... | {
Interner::default()
} | identifier_body |
symbol.rs | xt.modern() == SyntaxContext::empty() {
serializer.serialize_str(&self.name.as_str())
} else { // FIXME(jseyfried) intercrate hygiene
let mut string = "#".to_owned();
string.push_str(&self.name.as_str());
serializer.serialize_str(&string)
}
}
}
impl<'... | )
}
}
/// A symbol is an interned or gensymed string.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Symbol(u32);
// FIXME syntex
// The interner in thread-local, so `Symbol` shouldn't move between threads.
// impl !Send for Symbol { }
impl Symbol {
/// Maps a string to its interned ... | { // FIXME(jseyfried) intercrate hygiene
Ident::with_empty_ctxt(Symbol::gensym(&string[1..]))
} | conditional_block |
knight_tour.rs | extern crate nalgebra as na;
extern crate num;
use na::DMatrix;
use na::Scalar;
use na::dimension::Dynamic;
use std::fmt::Display;
use num::FromPrimitive;
const N: usize = 5; //map size N x N
trait ChessFunc {
fn isSafe(&self, x: isize, y: isize) -> bool;
fn solveKTUtil(
&mut self,
x: isize,
... |
fn isSafe(&self, x: isize, y: isize) -> bool {
let mut result = false;
//println!("({},{})", x, y);
match ((x + 1) as usize, (y + 1) as usize) {
(1...N, 1...N) => {
match self.iter().nth((y * N as isize + x) as usize) {
Some(sc) => {
... | {
for (idx, item) in self.iter().enumerate() {
print!("{position:>3}", position = item);
if idx % N == (N - 1) {
println!();
}
}
} | identifier_body |
knight_tour.rs | extern crate nalgebra as na;
extern crate num;
use na::DMatrix;
use na::Scalar;
use na::dimension::Dynamic;
use std::fmt::Display;
use num::FromPrimitive;
const N: usize = 5; //map size N x N
trait ChessFunc {
fn isSafe(&self, x: isize, y: isize) -> bool;
fn solveKTUtil(
&mut self,
x: isize,
... | }
if self.solveKTUtil(next_x, next_y, movei + 1, moves) {
result = true;
break;
} else {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
... | if self.isSafe(next_x, next_y) {
unsafe {
*self.get_unchecked_mut(next_x as usize, next_y as usize) =
FromPrimitive::from_usize(movei).unwrap(); | random_line_split |
knight_tour.rs | extern crate nalgebra as na;
extern crate num;
use na::DMatrix;
use na::Scalar;
use na::dimension::Dynamic;
use std::fmt::Display;
use num::FromPrimitive;
const N: usize = 5; //map size N x N
trait ChessFunc {
fn isSafe(&self, x: isize, y: isize) -> bool;
fn solveKTUtil(
&mut self,
x: isize,
... |
}
None => {}
};
}
_ => {}
}
//println!("({})", result);
result
}
}
fn main() {
let DimN = Dynamic::new(N); //from nalgebra make dynamic dimension in here make N dimension
let mut chessmap = DMatrix::fro... | {
result = true;
} | conditional_block |
knight_tour.rs | extern crate nalgebra as na;
extern crate num;
use na::DMatrix;
use na::Scalar;
use na::dimension::Dynamic;
use std::fmt::Display;
use num::FromPrimitive;
const N: usize = 5; //map size N x N
trait ChessFunc {
fn isSafe(&self, x: isize, y: isize) -> bool;
fn solveKTUtil(
&mut self,
x: isize,
... | () {
let DimN = Dynamic::new(N); //from nalgebra make dynamic dimension in here make N dimension
let mut chessmap = DMatrix::from_fn_generic(DimN, DimN, |r, c| match (r, c) {
(0, 0) => 0,
_ => -1,
}); //initialize matrix (0,0) set 0 and the others set -1
//chessmap.printSolution();
c... | main | identifier_name |
69b85d86968f_init2.py | """init2
Revision ID: 69b85d86968f
Revises: 9f83e778144c
Create Date: 2017-09-25 17:36:03.015859
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '69b85d86968f'
down_revision = '9f83e778144c'
branch_labels = None
depends_on = None
def upgrade():
# ### comm... | # ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'nick')
op.drop_column('users', 'member_since')
op.drop_column('users', 'major')
op.drop_column('users', 'last_seen')
op.drop_column('users', 'colleage')
... | op.add_column('users', sa.Column('nick', sa.String(length=64), nullable=True)) | random_line_split |
69b85d86968f_init2.py | """init2
Revision ID: 69b85d86968f
Revises: 9f83e778144c
Create Date: 2017-09-25 17:36:03.015859
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '69b85d86968f'
down_revision = '9f83e778144c'
branch_labels = None
depends_on = None
def upgrade():
# ### comm... | ():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'nick')
op.drop_column('users', 'member_since')
op.drop_column('users', 'major')
op.drop_column('users', 'last_seen')
op.drop_column('users', 'colleage')
op.drop_column('users', 'about_me')
# ### en... | downgrade | identifier_name |
69b85d86968f_init2.py | """init2
Revision ID: 69b85d86968f
Revises: 9f83e778144c
Create Date: 2017-09-25 17:36:03.015859
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '69b85d86968f'
down_revision = '9f83e778144c'
branch_labels = None
depends_on = None
def upgrade():
# ### comm... |
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('users', 'nick')
op.drop_column('users', 'member_since')
op.drop_column('users', 'major')
op.drop_column('users', 'last_seen')
op.drop_column('users', 'colleage')
op.drop_column('users', 'about_m... | op.add_column('users', sa.Column('about_me', sa.Text(), nullable=True))
op.add_column('users', sa.Column('colleage', sa.String(length=64), nullable=True))
op.add_column('users', sa.Column('last_seen', sa.DateTime(), nullable=True))
op.add_column('users', sa.Column('major', sa.String(length=64), nullable=Tru... | identifier_body |
apr.rs | #![allow(non_camel_case_types)]
use std::ffi::CString;
use std::marker::PhantomData;
use ffi;
use wrapper::{Wrapper, from_char_ptr, WrappedType, FromRaw};
pub enum HookOrder {
REALLY_FIRST, // run this hook first, before ANYTHING
FIRST, // run this hook first
MIDDLE, // run this hook somew... | {
unsafe {
ffi::apr_time_now()
}
} | identifier_body | |
apr.rs | #![allow(non_camel_case_types)]
use std::ffi::CString;
use std::marker::PhantomData;
use ffi;
use wrapper::{Wrapper, from_char_ptr, WrappedType, FromRaw};
pub enum HookOrder {
REALLY_FIRST, // run this hook first, before ANYTHING
FIRST, // run this hook first
MIDDLE, // run this hook somew... | <T: Into<Vec<u8>>, U: Into<Vec<u8>>>(&mut self, key: T, val: U) -> Result<(), ()> {
let key = match CString::new(key) {
Ok(s) => s,
Err(_) => return Err(())
};
let val = match CString::new(val) {
Ok(s) => s,
Err(_) => return Err(())
};
unsafe {
... | set | identifier_name |
apr.rs | #![allow(non_camel_case_types)]
use std::ffi::CString;
use std::marker::PhantomData;
use ffi;
use wrapper::{Wrapper, from_char_ptr, WrappedType, FromRaw};
pub enum HookOrder {
REALLY_FIRST, // run this hook first, before ANYTHING
FIRST, // run this hook first
MIDDLE, // run this hook somew... | } else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
if self.array_header.is_null() {
return (0, None);
}
let array_header: &ffi::apr_array_header_t = unsafe { &*self.array_header };
let rem = array_header.nelts as usize - self.next_idx;
(r... |
T::from_raw(elt as *mut <T as WrappedType>::wrapped_type) | random_line_split |
tailcut_delta_psi.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... | else:
# The cleaning algorithm failed to clean this image
# TODO: add a penalty
score_list.append(90.) # the worst score
# Compute the mean
if self.aggregation_method == "mean":
aggregated_score = np.arr... | tput_image_parameter_psi_rad = image_dict["img_ref_hillas_2_psi"]
reference_image_parameter_psi_rad = image_dict["img_cleaned_hillas_2_psi"]
delta_psi_rad = reference_image_parameter_psi_rad - output_image_parameter_psi_rad
normalized_delta_psi_deg = norm_angl... | conditional_block |
tailcut_delta_psi.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... |
def __init__(self, input_files, max_num_img=None, aggregation_method="mean"):
self.call_number = 0
# Init the wavelet class
self.cleaning_algorithm = Tailcut()
# Make the image list
self.input_files = input_files
self.max_num_img = max_num_img
self.aggrega... | jectiveFunction:
| identifier_name |
tailcut_delta_psi.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... | low_threshold = float(threshold_list[1])
if low_threshold > high_threshold:
# To avoid useless computation, reject solutions where low threshold is greater than high threshold
# (these solutions have the same result than the solution `low_threshold == high_thresh... | aggregated_score = float('inf')
try:
high_threshold = float(threshold_list[0]) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.