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 |
|---|---|---|---|---|
json_error_response.py | #!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 SmartBear Software
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
Unle... | (self):
properties = []
for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))
| __repr__ | identifier_name |
organization.js | const Promise = require('q');
const Resource = require('./resource');
/**
* Model to represent an organization.
* @type {Resource}
*/
class Organization extends Resource {
constructor(client, github, clientID) {
super(client);
this.id = clientID;
}
/**
* Return API endpoint for thi... | return this.post('repos', info)
.get('body');
}
}
module.exports = Organization; | createRepo(info) { | random_line_split |
organization.js | const Promise = require('q');
const Resource = require('./resource');
/**
* Model to represent an organization.
* @type {Resource}
*/
class Organization extends Resource {
constructor(client, github, clientID) {
super(client);
this.id = clientID;
}
/**
* Return API endpoint for thi... | () {
return this.get('')
.get('body');
}
// Edit this organization
edit(params) {
return this.patch('', params)
.get('body');
}
// Check membership
// https://developer.github.com/v3/orgs/members/#check-membership
isMember(user) {
return thi... | info | identifier_name |
organization.js | const Promise = require('q');
const Resource = require('./resource');
/**
* Model to represent an organization.
* @type {Resource}
*/
class Organization extends Resource {
constructor(client, github, clientID) {
super(client);
this.id = clientID;
}
/**
* Return API endpoint for thi... |
// Edit this organization
edit(params) {
return this.patch('', params)
.get('body');
}
// Check membership
// https://developer.github.com/v3/orgs/members/#check-membership
isMember(user) {
return this.get(`members/${user}`)
.then(() => {
retur... | {
return this.get('')
.get('body');
} | identifier_body |
views.py |
from utils.language import LANG_CHOICE
from .models import Contest, ContestProblem, ContestInvitation, ContestUserRating
from .tasks import add_participant_with_invitation
def time_formatter(seconds):
return "%d:%.2d:%.2d" % (seconds // 3600,
seconds % 3600 // 60,
... | self.full = False
else:
self.full = True
return super().dispatch(request, *args, **kwargs)
def get_queryset(self):
if self.full:
return User.objects.filter(rating__gt=0).order_by("-rating")
else:
return User.objects.filter(rating__gt=0).order_by("-rating")[:15]
def get_cont... | self.full = False
elif request.user.is_authenticated:
self.user = request.user | random_line_split |
views.py | from utils.language import LANG_CHOICE
from .models import Contest, ContestProblem, ContestInvitation, ContestUserRating
from .tasks import add_participant_with_invitation
def | (seconds):
return "%d:%.2d:%.2d" % (seconds // 3600,
seconds % 3600 // 60,
seconds % 60)
class DashboardView(BaseContestMixin, TemplateView):
template_name = 'contest/index.jinja2'
def test_func(self):
if self.privileged:
return True
return se... | time_formatter | identifier_name |
views.py | from utils.language import LANG_CHOICE
from .models import Contest, ContestProblem, ContestInvitation, ContestUserRating
from .tasks import add_participant_with_invitation
def time_formatter(seconds):
return "%d:%.2d:%.2d" % (seconds // 3600,
seconds % 3600 // 60,
... |
data['authors'] = self.contest.authors.all()
# color settings
data['level_colors'] = ["", "green", "teal", "blue", "orange", "red"]
return data
class ContestProblemDetail(BaseContestMixin, TemplateView):
template_name = 'contest/problem.jinja2'
def get_context_data(self, **kwargs):
data =... | problem.max_score = int(round(problem.max_score / 100 * problem.weight))
problem.avg_score = round(problem.avg_score / 100 * problem.weight, 1) | conditional_block |
views.py | from utils.language import LANG_CHOICE
from .models import Contest, ContestProblem, ContestInvitation, ContestUserRating
from .tasks import add_participant_with_invitation
def time_formatter(seconds):
return "%d:%.2d:%.2d" % (seconds // 3600,
seconds % 3600 // 60,
... | (View):
def post(self, request, cid):
if not request.user.is_authenticated:
messages.error(request, "请先登录。")
else:
contest = get_object_or_404(Contest, pk=cid)
if contest.access_level == 30 and contest.status == -1:
with transaction.atomic():
if not contest.contestparticipa... | if not request.user.is_authenticated:
messages.error(request, "请先登录。")
else:
invitation_code = request.POST.get('code', '')
try:
invitation = ContestInvitation.objects.get(code=invitation_code)
add_participant_with_invitation(cid, invitation.pk, request.user)
messages.succe... | identifier_body |
login.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Meta, Title } from "@angular/platform-browser";
import { AlertService, AuthenticateService } from '../../_services/index';
@Component({
moduleId: module.id,
templateUrl: 'login.component.html... |
}
|
this.loading = true;
this.authService.emailLogin(loginForm.value.username, loginForm.value.password)
.then((user) => {
console.log(user.uid+ ' Logged In');
// store user details and jwt token in local storage to keep user logged in between page refreshes
this... | identifier_body |
login.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Meta, Title } from "@angular/platform-browser";
import { AlertService, AuthenticateService } from '../../_services/index';
@Component({
moduleId: module.id,
templateUrl: 'login.component.html... | {
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
login(loginForm:any) {
this.loading = true;
console.log("Username - "+loginForm.value.username+" Password - "+loginForm.value.password);
t... | OnInit() | identifier_name |
login.component.ts | import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Meta, Title } from "@angular/platform-browser";
import { AlertService, AuthenticateService } from '../../_services/index';
@Component({
moduleId: module.id,
templateUrl: 'login.component.html... | alertClass: any;
constructor(meta: Meta, title: Title,
private route: ActivatedRoute,
private router: Router,
private authService: AuthenticateService,
private alertService: AlertService) {
title.setTitle('Login - Giftplush');
meta.addTags([
... | random_line_split | |
booking.service.ts | import { Injectable } from 'angular2/core';
import { BOOKINGS } from './mock-bookings';
import { Booking } from './booking';
@Injectable()
export class BookingService {
saveBooking(booking: Booking) {
BOOKINGS.push(booking);
}
removeBooking(bookingId: number) {
<<<<<<< HEAD
//BOOKINGS = BOOKINGS.filter(... | .then(bookings => bookings.filter(booking => booking.id === id)[0]
);
}
} | return Promise.resolve(BOOKINGS) | random_line_split |
booking.service.ts | import { Injectable } from 'angular2/core';
import { BOOKINGS } from './mock-bookings';
import { Booking } from './booking';
@Injectable()
export class BookingService {
saveBooking(booking: Booking) {
BOOKINGS.push(booking);
}
| (bookingId: number) {
<<<<<<< HEAD
//BOOKINGS = BOOKINGS.filter(booking => booking.id !== bookingId);
=======
BOOKINGS.filter(booking => booking.id !== bookingId);
>>>>>>> f40145abf0247fc688a8f41702de8cfe957473aa
}
getBookingsByRoom(roomId: number) {
return Promise.resolve(BOOKINGS)
.then(booking... | removeBooking | identifier_name |
booking.service.ts | import { Injectable } from 'angular2/core';
import { BOOKINGS } from './mock-bookings';
import { Booking } from './booking';
@Injectable()
export class BookingService {
saveBooking(booking: Booking) {
BOOKINGS.push(booking);
}
removeBooking(bookingId: number) |
}
| {
<<<<<<< HEAD
//BOOKINGS = BOOKINGS.filter(booking => booking.id !== bookingId);
=======
BOOKINGS.filter(booking => booking.id !== bookingId);
>>>>>>> f40145abf0247fc688a8f41702de8cfe957473aa
}
getBookingsByRoom(roomId: number) {
return Promise.resolve(BOOKINGS)
.then(bookings => bookings.filter... | identifier_body |
test_postprocessor_manager.py | # coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **GUI Test Cases.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 Fre... | def tearDown(self):
"""Run after each test."""
# Let's use a fresh registry, canvas, and dock for each test!
QgsMapLayerRegistry.instance().removeAllMapLayers()
DOCK.cboHazard.clear()
DOCK.cboExposure.clear()
# noinspection PyMethodMayBeStatic
def test_check_postproc... | set_jakarta_extent()
register_impact_functions()
| random_line_split |
test_postprocessor_manager.py | # coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **GUI Test Cases.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 Fre... | if __name__ == '__main__':
suite = unittest.makeSuite(PostprocessorManagerTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
| kens = str(line).split('\t')
tokens = tokens[1:]
total = 0
for token in tokens:
total += float(token.replace(',', ''))
assert total != 0, message
| conditional_block |
test_postprocessor_manager.py | # coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **GUI Test Cases.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 Fre... | (unittest.TestCase):
"""Test the postprocessor manager"""
# noinspection PyPep8Naming
def setUp(self):
"""Fixture run before all tests"""
os.environ['LANG'] = 'en'
DOCK.show_only_visible_layers_flag = True
load_standard_layers(DOCK)
DOCK.cboHazard.setCurrentIndex(0)
... | PostprocessorManagerTest | identifier_name |
test_postprocessor_manager.py | # coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **GUI Test Cases.**
Contact : ole.moller.nielsen@gmail.com
.. note:: 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 Fre... | for line in result.split('\n'):
if 'Entire area' in line:
tokens = str(line).split('\t')
tokens = tokens[1:]
total = 0
for token in tokens:
total += float(token.replace(',', ''))
assert total != 0, m... | "Check that the post processor does not add spurious report rows."""
# with KAB_NAME aggregation attribute defined in .keyword using
# kabupaten_jakarta_singlepart.shp
result, message = setup_scenario(
DOCK,
hazard='Continuous Flood',
exposure='Population',
... | identifier_body |
main.js | 'use strict';
| var start = Date.now(); // for browsers that don't support window.performance
function handleEvent(e) {
// e.timeStamp has different precision in Firefox v Chrome
var time;
if (window.performance) {
time = (window.performance.now() / 1000).toFixed(6);
} else {
time = ((Date.now() - start) / 1000).toFix... | var video = document.querySelector('video');
var data = document.querySelector('p#data'); | random_line_split |
main.js | 'use strict';
var video = document.querySelector('video');
var data = document.querySelector('p#data');
var start = Date.now(); // for browsers that don't support window.performance
function handleEvent(e) |
// Getting event names automatically by checking for video element
// properties such as onloadedmetadata doesn't work for Safari :(.
var events = [
'abort',
'autocomplete',
'autocompleteerror',
'beforecopy ',
'beforecut',
'beforepaste',
'blur',
'cancel',
'canplay',
'canplaythrough',
'change',
... | {
// e.timeStamp has different precision in Firefox v Chrome
var time;
if (window.performance) {
time = (window.performance.now() / 1000).toFixed(6);
} else {
time = ((Date.now() - start) / 1000).toFixed(3);
}
data.innerHTML = '<span class = "time">' + time + '</span>' + 's: ' +
e.type + '<br>' ... | identifier_body |
main.js | 'use strict';
var video = document.querySelector('video');
var data = document.querySelector('p#data');
var start = Date.now(); // for browsers that don't support window.performance
function | (e) {
// e.timeStamp has different precision in Firefox v Chrome
var time;
if (window.performance) {
time = (window.performance.now() / 1000).toFixed(6);
} else {
time = ((Date.now() - start) / 1000).toFixed(3);
}
data.innerHTML = '<span class = "time">' + time + '</span>' + 's: ' +
e.type + '<b... | handleEvent | identifier_name |
main.js | 'use strict';
var video = document.querySelector('video');
var data = document.querySelector('p#data');
var start = Date.now(); // for browsers that don't support window.performance
function handleEvent(e) {
// e.timeStamp has different precision in Firefox v Chrome
var time;
if (window.performance) {
time ... | {
video.addEventListener(events[i], handleEvent);
} | conditional_block | |
import.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | /// Blocks enacted by this import.
///
/// They should be ordered from oldest to newest.
pub enacted: Vec<H256>,
/// Number of blocks retracted by this import.
pub retracted: usize,
} | random_line_split | |
import.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | {
/// Traces to import.
pub traces: FlatBlockTraces,
/// Hash of traces block.
pub block_hash: H256,
/// Number of traces block.
pub block_number: BlockNumber,
/// Blocks enacted by this import.
///
/// They should be ordered from oldest to newest.
pub enacted: Vec<H256>,
/// Number of blocks retracted by t... | ImportRequest | identifier_name |
valorchat.server.socket.config.js | 'use strict';
| io.emit('ValorchatMessage', {
type: 'status',
text: 'Is now connected',
created: Date.now(),
profileImageURL: socket.request.user.profileImageURL,
username: socket.request.user.username
});
// Send a valorchat messages to all connected sockets when a message is received
socket.on('Valorchat... | // Create the valorchat configuration
module.exports = function (io, socket) {
// Emit the status event when a new socket client is connected | random_line_split |
once.rs | use consumer::*;
use stream::*;
/// A stream that emits an element exactly once.
///
/// This `struct` is created by the [`once()`] function. See its documentation
/// for more.
///
/// [`once()`]: fn.once.html
#[must_use = "stream adaptors are lazy and do nothing unless consumed"]
pub struct Once<T> {
value: T,
}... | <T>(value: T) -> Once<T> {
Once { value: value }
}
impl<T> Stream for Once<T> {
type Item = T;
fn consume<C>(self, mut consumer: C)
where C: Consumer<Self::Item>
{
consumer.emit(self.value);
}
}
| once | identifier_name |
once.rs | use consumer::*;
use stream::*;
/// A stream that emits an element exactly once.
///
/// This `struct` is created by the [`once()`] function. See its documentation
/// for more.
///
/// [`once()`]: fn.once.html
#[must_use = "stream adaptors are lazy and do nothing unless consumed"]
pub struct Once<T> {
value: T,
}... |
impl<T> Stream for Once<T> {
type Item = T;
fn consume<C>(self, mut consumer: C)
where C: Consumer<Self::Item>
{
consumer.emit(self.value);
}
}
| {
Once { value: value }
} | identifier_body |
once.rs | use consumer::*; | ///
/// This `struct` is created by the [`once()`] function. See its documentation
/// for more.
///
/// [`once()`]: fn.once.html
#[must_use = "stream adaptors are lazy and do nothing unless consumed"]
pub struct Once<T> {
value: T,
}
/// Creates a stream that emits an element exactly once.
///
/// # Examples
///
... | use stream::*;
/// A stream that emits an element exactly once. | random_line_split |
selection_range.rs | use serde::{Deserialize, Serialize};
use crate::{
PartialResultParams, Position, Range, StaticTextDocumentRegistrationOptions,
TextDocumentIdentifier, WorkDoneProgressOptions, WorkDoneProgressParams,
};
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
p... | }
impl From<SelectionRangeRegistrationOptions> for SelectionRangeProviderCapability {
fn from(from: SelectionRangeRegistrationOptions) -> Self {
Self::RegistrationOptions(from)
}
}
impl From<SelectionRangeOptions> for SelectionRangeProviderCapability {
fn from(from: SelectionRangeOptions) -> Self ... | pub enum SelectionRangeProviderCapability {
Simple(bool),
Options(SelectionRangeOptions),
RegistrationOptions(SelectionRangeRegistrationOptions), | random_line_split |
selection_range.rs | use serde::{Deserialize, Serialize};
use crate::{
PartialResultParams, Position, Range, StaticTextDocumentRegistrationOptions,
TextDocumentIdentifier, WorkDoneProgressOptions, WorkDoneProgressParams,
};
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
p... | {
/// The text document.
pub text_document: TextDocumentIdentifier,
/// The positions inside the text document.
pub positions: Vec<Position>,
#[serde(flatten)]
pub work_done_progress_params: WorkDoneProgressParams,
#[serde(flatten)]
pub partial_result_params: PartialResultParams,
}
... | SelectionRangeParams | identifier_name |
test_smilesparser_rdkit.py | # Copyright 2016 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | bt = Chem.rdchem.BondType.SINGLE
a.SetHybridization(Chem.rdchem.HybridizationType.SP2)
elif self.prevBond == '=':
bt = Chem.rdchem.BondType.DOUBLE
a.SetHybridization(Chem.rdchem.HybridizationType.SP2)
else:
raise RuntimeError
idx = self.mol.AddAtom(a)
i... | def __init__(self, smiles):
self.mol = Chem.RWMol()
self.parsed = smilesparser.SMILES.parseString(smiles)[0]
self.prevAtomIdx = None
self.prevBond = None
self.atomStack = []
self.ringClosures = {}
self.iterate_smiles(self.parsed.smiles)
def AddAtom(self, s):
a = Chem.Atom(element... | identifier_body |
test_smilesparser_rdkit.py | # Copyright 2016 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | s = ''.join(organic_symbol)
self.AddAtom(s)
def inspect_aromatic_symbol(self, aromatic_symbol, indent=0):
s = ''.join(aromatic_symbol)
a = self.AddAtom(s)
a.SetIsAromatic(True)
self.prevBond = ":"
def inspect_element_symbol(self, element_symbol, indent=0):
s = ''.join(element_symbol)
... | self.mol.AddBond(self.prevAtomIdx, idx, bt)
self.prevBond = None
def inspect_organic_symbol(self, organic_symbol, indent=0): | random_line_split |
test_smilesparser_rdkit.py | # Copyright 2016 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... |
self.prevAtomIdx = self.atomStack.pop()
def iterate_smiles(self, smiles, indent=0):
for item in smiles:
if isinstance(item, smilesparser.AST.Atom):
self.inspect_atom(item.atom, indent)
elif isinstance(item, smilesparser.AST.Chain):
self.inspect_chain(item.chain, indent)
eli... | if isinstance(item, smilesparser.AST.Bond):
self.inspect_bond(item.bond, indent+1)
elif isinstance(item, smilesparser.AST.SMILES):
self.iterate_smiles(item.smiles, indent+1)
else:
print " " * indent + item, dir(item) | conditional_block |
test_smilesparser_rdkit.py | # Copyright 2016 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... | :
def __init__(self, smiles):
self.mol = Chem.RWMol()
self.parsed = smilesparser.SMILES.parseString(smiles)[0]
self.prevAtomIdx = None
self.prevBond = None
self.atomStack = []
self.ringClosures = {}
self.iterate_smiles(self.parsed.smiles)
def AddAtom(self, s):
a = Chem.Atom(ele... | SMILES | identifier_name |
0001_config.py | from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BlockStructureConfiguration',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=Tr... | identifier_body | |
0001_config.py | from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
class | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BlockStructureConfiguration',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto... | Migration | identifier_name |
0001_config.py | from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BlockSt... | ('changed_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, editable=False, to=settings.AUTH_USER_MODEL, null=True, verbose_name='Changed by')),
],
options={
'db_table': 'block_structure_config',
},
),
] | ('cache_timeout_in_seconds', models.IntegerField(default=86400, null=True, blank=True)), | random_line_split |
ismaster.py | # Copyright 2014-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | (self, doc):
"""Parse an ismaster response from the server."""
self._server_type = _get_server_type(doc)
self._doc = doc
self._is_writable = self._server_type in (
SERVER_TYPE.RSPrimary,
SERVER_TYPE.Standalone,
SERVER_TYPE.Mongos)
self._is_rea... | __init__ | identifier_name |
ismaster.py | # Copyright 2014-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
if doc.get('isreplicaset'):
return SERVER_TYPE.RSGhost
elif doc.get('setName'):
if doc.get('hidden'):
return SERVER_TYPE.RSOther
elif doc.get('ismaster'):
return SERVER_TYPE.RSPrimary
elif doc.get('secondary'):
return SERVER_TYPE.RSSecondary
... | return SERVER_TYPE.Unknown | conditional_block |
ismaster.py | # Copyright 2014-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | def all_hosts(self):
"""List of hosts, passives, and arbiters known to this server."""
return set(imap(common.clean_node, itertools.chain(
self._doc.get('hosts', []),
self._doc.get('passives', []),
self._doc.get('arbiters', []))))
@property
def tags(self)... | __slots__ = ('_doc', '_server_type', '_is_writable', '_is_readable')
def __init__(self, doc):
"""Parse an ismaster response from the server."""
self._server_type = _get_server_type(doc)
self._doc = doc
self._is_writable = self._server_type in (
SERVER_TYPE.RSPrimary,
... | identifier_body |
ismaster.py | # Copyright 2014-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Parse a response to the 'ismaster' command."""
import itertools
from bson.py3compat import imap
from pymongo import common
from pymongo.... | # distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
prod_config_windows.py | # ***** BEGIN LICENSE BLOCK *****
# 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/.
# ***** END LICENSE BLOCK *****
# This is a template config file for web-platfor... | ],
"blob_uploader_auth_file" : os.path.join(os.getcwd(), "oauth.txt"),
"download_minidump_stackwalk": True,
} |
"buildbot_json_path": "buildprops.json",
"default_blob_upload_servers": [
"https://blobupload.elasticbeanstalk.com",
| random_line_split |
modified-original-unit-tests.ts | . If not, see <https://www.gnu.org/licenses/>.
*/
// This code is modified from a UserScript made to test GM_config
// Changes have been made to support strict typing and follow TSLint settings
// Original file (MIT-licensed): https://github.com/sizzlemctwizzle/UserScripts/blob/master/gm_config_unit_test.user.js
con... | ,
},
},
});
// Retrieve language setting
let lang = GM_config.getValue('lang', 'en') as 'en' | 'de';
// Fields in different languages
const langDefs = {
// Fields in English
en: {
lang: {
label: 'Choose Language',
type: 'select' as const,
options: ['en',... | {
// Empty all the input fields
if (this.wrapper) {
const inputs = this.wrapper.getElementsByTagName('input');
for (let i = 0, len = inputs.length; i < len; ++i) inputs[i].value = '';
}
} | identifier_body |
modified-original-unit-tests.ts | : {
type: 'checkbox',
default: false,
},
middleLeft: {
section: [],
type: 'checkbox',
default: false,
},
middleLeftMiddle: {
type: 'checkbox',
default: false,
},
middleRightMiddle: {
type: 'checkbox',
default: false,
},
... | k() { | identifier_name | |
modified-original-unit-tests.ts | . If not, see <https://www.gnu.org/licenses/>.
*/
// This code is modified from a UserScript made to test GM_config
// Changes have been made to support strict typing and follow TSLint settings
// Original file (MIT-licensed): https://github.com/sizzlemctwizzle/UserScripts/blob/master/gm_config_unit_test.user.js
con... | options: ['Carpenter', 'Truck Driver'],
default: 'Truck Driver',
},
bunchOtext: {
label: 'Bunch of Text',
type: 'textarea',
default: "I actually did't realize we had this field until recently...",
},
magic: {
label: 'Magic Button',
type: 'button',
... | labelPos: 'below', | random_line_split |
objectLiteralFunctionArgContextualTyping.js | //// [objectLiteralFunctionArgContextualTyping.ts]
interface I {
value: string;
toString: (t: string) => string;
}
function | (args: I) { }
f2({ hello: 1 }) // error
f2({ value: '' }) // missing toString satisfied by Object's member
f2({ value: '', what: 1 }) // missing toString satisfied by Object's member
f2({ toString: (s) => s }) // error, missing property value from ArgsString
f2({ toString: (s: string) => s }) // error, missing proper... | f2 | identifier_name |
objectLiteralFunctionArgContextualTyping.js | //// [objectLiteralFunctionArgContextualTyping.ts]
interface I {
value: string;
toString: (t: string) => string;
}
function f2(args: I) |
f2({ hello: 1 }) // error
f2({ value: '' }) // missing toString satisfied by Object's member
f2({ value: '', what: 1 }) // missing toString satisfied by Object's member
f2({ toString: (s) => s }) // error, missing property value from ArgsString
f2({ toString: (s: string) => s }) // error, missing property value from... | { } | identifier_body |
objectLiteralFunctionArgContextualTyping.js | //// [objectLiteralFunctionArgContextualTyping.ts]
interface I {
value: string;
toString: (t: string) => string;
}
function f2(args: I) { }
f2({ hello: 1 }) // error
f2({ value: '' }) // missing toString satisfied by Object's member
f2({ value: '', what: 1 }) // missing toString satisfied by Object's member
... | f2({ hello: 1 }); // error
f2({ value: '' }); // missing toString satisfied by Object's member
f2({ value: '', what: 1 }); // missing toString satisfied by Object's member
f2({ toString: function (s) { return s; } }); // error, missing property value from ArgsString
f2({ toString: function (s) { return s; } }); // err... |
//// [objectLiteralFunctionArgContextualTyping.js]
function f2(args) { } | random_line_split |
switchMap.ts | import {Observable} from '../Observable';
import {Observer} from '../Observer';
import {Subscription} from '../Subscription';
/**
* Flattens an "observable of observables", handling only one nested stream at a time.
*
* Marble diagram:
*
* ```text
* --+--------+---------------
* \ \
* \ ----1... |
// for the new value of outer stream invoke projection(value)
// which will create another inner stream.
// subscribe to this new inner stream and send its
// values to the destination observer
inner = projection(value).subscribe({
next: (x: U) => observer.next(x),
... | {
inner.unsubscribe();
} | conditional_block |
switchMap.ts | import {Observable} from '../Observable';
import {Observer} from '../Observer';
import {Subscription} from '../Subscription';
/**
* Flattens an "observable of observables", handling only one nested stream at a time.
*
* Marble diagram:
*
* ```text
* --+--------+---------------
* \ \
* \ ----1... | <T, U>(projection: (val: T) => Observable<U>): Observable<U> {
return Observable.create<U>((observer: Observer<U>) => {
let inner: Subscription<U> = null;
let outer: Subscription<T> = null;
outer = this.subscribe({
next: (value: T) => {
// if there is a current inner stream unsubscribe... | switchMap | identifier_name |
switchMap.ts | import {Observable} from '../Observable';
import {Observer} from '../Observer';
import {Subscription} from '../Subscription';
/**
* Flattens an "observable of observables", handling only one nested stream at a time.
*
* Marble diagram:
*
* ```text
* --+--------+---------------
* \ \
* \ ----1... | inner = projection(value).subscribe({
next: (x: U) => observer.next(x),
error: (err: any) => observer.error(err),
complete: () => {
if (inner.isStopped && outer.isStopped) {
observer.complete();
}
}
});
},
error:... | {
return Observable.create<U>((observer: Observer<U>) => {
let inner: Subscription<U> = null;
let outer: Subscription<T> = null;
outer = this.subscribe({
next: (value: T) => {
// if there is a current inner stream unsubscribe from it
if (inner && !inner.isUnsubscribed) {
... | identifier_body |
switchMap.ts | import {Observable} from '../Observable';
import {Observer} from '../Observer';
import {Subscription} from '../Subscription';
/**
* Flattens an "observable of observables", handling only one nested stream at a time.
*
* Marble diagram:
*
* ```text
* --+--------+---------------
* \ \
* \ ----1... | return Observable.create<U>((observer: Observer<U>) => {
let inner: Subscription<U> = null;
let outer: Subscription<T> = null;
outer = this.subscribe({
next: (value: T) => {
// if there is a current inner stream unsubscribe from it
if (inner && !inner.isUnsubscribed) {
... | export function switchMap<T, U>(projection: (val: T) => Observable<U>): Observable<U> {
| random_line_split |
processor.py | import csv
import decimal
import os
import datetime
from stocker.common.events import EventStreamNew, EventStockOpen, EventStockClose
from stocker.common.orders import OrderBuy, OrderSell
from stocker.common.utils import Stream
class CompanyProcessor(object):
def __init__(self, dirname, company_id):
self.... |
dates_set = set()
for company in companies:
dates_set.update(company.get_dates())
dates_ordered = sorted(dates_set, key=lambda date: datetime.datetime.strptime(date, "%Y-%m-%d"))
for date in dates_ordered:
self.__process_date(date, companies)
def __proce... | companies.append(CompanyProcessor(dirname, company)) | conditional_block |
processor.py | import csv
import decimal
import os
import datetime
from stocker.common.events import EventStreamNew, EventStockOpen, EventStockClose
from stocker.common.orders import OrderBuy, OrderSell
from stocker.common.utils import Stream
class CompanyProcessor(object):
def __init__(self, dirname, company_id):
self.... | expiration_date = timestamp + datetime.timedelta(days=1)
self.stream.add_event(
EventStreamNew(timestamp, OrderBuy(company_id, amount, limit_price, expiration_date)))
self.stream.add_event(
EventStreamNew(timestamp, OrderSell(company_id, amount, limit_price, expiration_da... | amount = int(row[3])
limit_price = decimal.Decimal(row[1].replace(',', '.'))
timestamp = datetime.datetime.strptime("%s %s" % (date, row[0]), "%Y-%m-%d %H:%M:%S") | random_line_split |
processor.py | import csv
import decimal
import os
import datetime
from stocker.common.events import EventStreamNew, EventStockOpen, EventStockClose
from stocker.common.orders import OrderBuy, OrderSell
from stocker.common.utils import Stream
class CompanyProcessor(object):
def __init__(self, dirname, company_id):
self.... |
class Processor(object):
def build_stream(self, dirname_in, filename_out):
self.stream = Stream()
self.stream.begin(filename_out)
self.__process_companies(dirname_in)
self.stream.end()
def __process_companies(self, dirname):
companies = []
for company in os.... | filename = os.path.join(self.dirname, date) + ".csv"
try:
with open(filename, 'r') as f:
for row in reversed(list(csv.reader(f, delimiter=';'))):
try:
desc = row[5]
if desc.startswith('TRANSAKCJA'):
... | identifier_body |
processor.py | import csv
import decimal
import os
import datetime
from stocker.common.events import EventStreamNew, EventStockOpen, EventStockClose
from stocker.common.orders import OrderBuy, OrderSell
from stocker.common.utils import Stream
class CompanyProcessor(object):
def __init__(self, dirname, company_id):
self.... | (self):
files = [os.path.splitext(fi)[0] for fi in os.walk(self.dirname).next()[2]]
return files
def get_row(self, date):
filename = os.path.join(self.dirname, date) + ".csv"
try:
with open(filename, 'r') as f:
for row in reversed(list(csv.reader(f, deli... | get_dates | identifier_name |
L0FailOnExpiredCertificate.ts | import * as ma from 'azure-pipelines-task-lib/mock-answer';
import * as tmrm from 'azure-pipelines-task-lib/mock-run';
import path = require('path');
import fs = require('fs');
import os = require('os');
let taskPath = path.join(__dirname, '..', 'preinstallcert.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunn... | (datetime: Date): string {
const dateSegments: string[] = datetime.toUTCString().split(' ');
if (dateSegments.length != 6) {
throw new Error('Expected 6 segments in the date string');
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
const ... | toOpensslString | identifier_name |
L0FailOnExpiredCertificate.ts | import * as ma from 'azure-pipelines-task-lib/mock-answer';
import * as tmrm from 'azure-pipelines-task-lib/mock-run';
import path = require('path');
import fs = require('fs');
import os = require('os');
let taskPath = path.join(__dirname, '..', 'preinstallcert.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunn... | {
const dateSegments: string[] = datetime.toUTCString().split(' ');
if (dateSegments.length != 6) {
throw new Error('Expected 6 segments in the date string');
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
const date = dateSegments[1];
... | identifier_body | |
L0FailOnExpiredCertificate.ts | import * as ma from 'azure-pipelines-task-lib/mock-answer';
import * as tmrm from 'azure-pipelines-task-lib/mock-run';
import path = require('path');
import fs = require('fs');
import os = require('os');
let taskPath = path.join(__dirname, '..', 'preinstallcert.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunn... | }
tr.registerMock('os', os);
tr.run();
// Return a UTC date in this format: "Nov 13 03:37:42 2018 GMT"
function toOpensslString(datetime: Date): string {
const dateSegments: string[] = datetime.toUTCString().split(' ');
if (dateSegments.length != 6) {
throw new Error('Expected 6 segments in the date ... | return 'darwin'; | random_line_split |
L0FailOnExpiredCertificate.ts | import * as ma from 'azure-pipelines-task-lib/mock-answer';
import * as tmrm from 'azure-pipelines-task-lib/mock-run';
import path = require('path');
import fs = require('fs');
import os = require('os');
let taskPath = path.join(__dirname, '..', 'preinstallcert.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunn... |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
const date = dateSegments[1];
const monthName = dateSegments[2];
const year = dateSegments[3];
const time = dateSegments[4];
return `${monthName} ${date} ${time} ${year} GMT`;
}
| {
throw new Error('Expected 6 segments in the date string');
} | conditional_block |
payables.server.controller.js | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
_ = require('lodash'),
async = require('async'),
Transaction = mongoose.model('Transaction'),
User = mongoose.model('User');
exports.list = function (req, res) {
Transact... | else {
var payables = [];
async.each(result, function (payable, done) {
// horrivel!
User.findById(payable._id.friend).select('id displayName').exec(function (err, friend) {
if (friend) {
payable._id.to = friend.displayName;
} else {
... | {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} | conditional_block |
payables.server.controller.js | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
_ = require('lodash'),
async = require('async'),
Transaction = mongoose.model('Transaction'),
User = mongoose.model('User');
exports.list = function (req, res) {
Transact... | .group({
_id: {
friend: {
$cond: [
{ $eq: ['$friend', req.user._id] },
'$user',
{ $ifNull: ['$friend', '$to'] }
]
}
},
total: {
$sum: {
$cond: [
{
$or: [
{ $and: [
... | random_line_split | |
base.rs | LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Codegen the completed AST to the LLVM IR.
//!
//! Some functions here, such as codegen_block and codegen_expr, return a value --
//! the result of the cod... |
cx.consume_stats().into_inner()
};
(stats, ModuleCodegen {
name: cgu_name.to_string(),
module_llvm: llvm_module,
kind: ModuleKind::Regular,
})
}
}
pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
let sect = match attrs.l... | {
cx.debuginfo_finalize();
} | conditional_block |
base.rs | LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Codegen the completed AST to the LLVM IR.
//!
//! Some functions here, such as codegen_block and codegen_expr, return a value --
//! the result of the cod... | cgu_name: InternedString)
-> (Stats, ModuleCodegen<ModuleLlvm>)
{
let backend = LlvmCodegenBackend(());
let cgu = tcx.codegen_unit(cgu_name);
// Instantiate monomorphizations without filling out definitions yet...
let llvm_module = backend.new_metadata(tcx.sess, &cgu_... | {
let start_time = Instant::now();
let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
tcx,
cgu_name,
... | identifier_body |
base.rs | LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Codegen the completed AST to the LLVM IR.
//!
//! Some functions here, such as codegen_block and codegen_expr, return a value --
//! the result of the cod... | (&mut self) -> Option<&'ll Value> {
let old = self.cur;
if let Some(old) = old {
self.cur = unsafe { (self.step)(old) };
}
old
}
}
pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
unsafe {
ValueIter {
cur: llvm::LLVMGetFirstGlobal... | next | identifier_name |
base.rs | LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Codegen the completed AST to the LLVM IR.
//!
//! Some functions here, such as codegen_block and codegen_expr, return a value --
//! the result of the cod... | // If this codegen unit contains the main function, also create the
// wrapper here
maybe_create_entry_wrapper::<Builder>(&cx);
// Run replace-all-uses-with for statics that need it
for &(old_g, new_g) in cx.statics_to_rauw().borrow().iter() {
... | }
| random_line_split |
missing_inline.rs | use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast;
use rustc_hir as hir;
use rustc_lint::{self, LateContext, LateLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// I... | ,
hir::ItemKind::Trait(ref _is_auto, ref _unsafe, ref _generics, _bounds, trait_items) => {
// note: we need to check if the trait is exported so we can't use
// `LateLintPass::check_trait_item` here.
for tit in trait_items {
let tit_ = cx.... | {
let desc = "a function";
let attrs = cx.tcx.hir().attrs(it.hir_id());
check_missing_inline_attrs(cx, attrs, it.span, desc);
} | conditional_block |
missing_inline.rs | use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast;
use rustc_hir as hir;
use rustc_lint::{self, LateContext, LateLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// I... | (&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx hir::ImplItem<'_>) {
use rustc_middle::ty::{ImplContainer, TraitContainer};
if rustc_middle::lint::in_external_macro(cx.sess(), impl_item.span) || is_executable_or_proc_macro(cx) {
return;
}
// If the item being implemente... | check_impl_item | identifier_name |
missing_inline.rs | use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast;
use rustc_hir as hir;
use rustc_lint::{self, LateContext, LateLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// I... | hir::ItemKind::Trait(ref _is_auto, ref _unsafe, ref _generics, _bounds, trait_items) => {
// note: we need to check if the trait is exported so we can't use
// `LateLintPass::check_trait_item` here.
for tit in trait_items {
let tit_ = cx.tc... | let desc = "a function";
let attrs = cx.tcx.hir().attrs(it.hir_id());
check_missing_inline_attrs(cx, attrs, it.span, desc);
}, | random_line_split |
missing_inline.rs | use clippy_utils::diagnostics::span_lint;
use rustc_ast::ast;
use rustc_hir as hir;
use rustc_lint::{self, LateContext, LateLintPass, LintContext};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::source_map::Span;
use rustc_span::sym;
declare_clippy_lint! {
/// ### What it does
/// I... | hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => {},
hir::TraitItemKind::Fn(..) => {
if tit.defaultness.has_value() {
// trait method with default body needs inline in case
... | {
if rustc_middle::lint::in_external_macro(cx.sess(), it.span) || is_executable_or_proc_macro(cx) {
return;
}
if !cx.access_levels.is_exported(it.def_id) {
return;
}
match it.kind {
hir::ItemKind::Fn(..) => {
let desc = "a func... | identifier_body |
gulpfile.js | var coveralls = require('gulp-coveralls');
var del = require('del');
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var karma = require('karma');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-ugli... | var minified = sources.replace('.js', '.min.js');
gulp.task('lint', function () {
return gulp.src(sources)
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(jshint.reporter('fail'));
});
gulp.task('test', function (done) {
new karma.Server({
configFile: __dirname + '/karm... | random_line_split | |
Head.tsx | import { Helmet } from 'react-helmet'
import { useDarkModeContext } from 'src/contexts/DarkModeContext'
const CURRENT_YEAR = new Date().getFullYear()
const Head = () => {
const {
values: { darkModeEnabled },
} = useDarkModeContext()
const faviconUrl = darkModeEnabled ? '/favicon-dark.png' : '/favicon.png'
... | <meta name='twitter:creator' content='@nimz_co' />
<meta
name='twitter:title'
content={`Confs.tech | All tech conferences in ${CURRENT_YEAR} and ${
CURRENT_YEAR + 1
}`}
/>
<meta
name='twitter:description'
content='Find your ne... | random_line_split | |
vmware_vmkernel_ip_config.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
host_system = host.keys()[0]
changed = configure_vmkernel_ip_address(host_system, vmk_name, ip_address, subnet_mask)
module.exit_json(changed=changed)
except vmodl.RuntimeFault as runtime_fault:
module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
... | module.fail_json(msg="Unable to locate Physical Host.") | conditional_block |
vmware_vmkernel_ip_config.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | ():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(vmk_name=dict(required=True, type='str'),
ip_address=dict(required=True, type='str'),
subnet_mask=dict(required=True, type='str')))
module = AnsibleModule(argument_spec=argument_spec, sup... | main | identifier_name |
vmware_vmkernel_ip_config.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
if __name__ == '__main__':
main() | random_line_split | |
vmware_vmkernel_ip_config.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Joseph Callen <jcallen () csc.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... |
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(vmk_name=dict(required=True, type='str'),
ip_address=dict(required=True, type='str'),
subnet_mask=dict(required=True, type='str')))
module = AnsibleModule(argument_spec=argumen... | host_config_manager = host_system.configManager
host_network_system = host_config_manager.networkSystem
for vnic in host_network_system.networkConfig.vnic:
if vnic.device == vmk_name:
spec = vnic.spec
if spec.ip.ipAddress != ip_address:
spec.ip.dhcp = False
... | identifier_body |
lights.py | #/usr/bin/env python
#-*- coding: utf-8 -*-
import re
import sys
from collections import namedtuple, defaultdict
from pyautocad import Autocad
from pyautocad import utils
LampEntry = namedtuple('LampEntry', 'number, mark, numxpower')
# \A1;2ARCTIC SMC/SAN 254 \S2х54/2,5;\P300 лк
def ite | ad, objects):
for obj in acad.iter_objects(('MText', 'MLeader'), block=objects):
try:
text = obj.TextString
except Exception:
continue
text = utils.unformat_mtext(text)
m = re.search(ur'(?P<num>\d+)(?P<mark>.*?)\\S(?P<num_power>.*?)/.*?;', text)
... | r_lamps(ac | identifier_name |
lights.py | #/usr/bin/env python
#-*- coding: utf-8 -*-
import re
import sys
from collections import namedtuple, defaultdict
from pyautocad import Autocad
from pyautocad import utils
LampEntry = namedtuple('LampEntry', 'number, mark, numxpower')
# \A1;2ARCTIC SMC/SAN 254 \S2х54/2,5;\P300 лк
def iter_lamps(acad, ob... |
def main():
acad = Autocad()
objects = None
if 'i' in sys.argv[1:]:
objects = acad.get_selection('Select objects')
lamps = defaultdict(int)
for lamp in iter_lamps(acad, objects):
lamps[lamp.mark] += int(lamp.number)
print '-' * 79
for mark, number in sorted(lamps.it... | :
text = obj.TextString
except Exception:
continue
text = utils.unformat_mtext(text)
m = re.search(ur'(?P<num>\d+)(?P<mark>.*?)\\S(?P<num_power>.*?)/.*?;', text)
if not m:
continue
print m.group('num'), m.group('mark'), m.group('num_pow... | conditional_block |
lights.py | #/usr/bin/env python
#-*- coding: utf-8 -*-
import re
import sys
from collections import namedtuple, defaultdict
from pyautocad import Autocad
from pyautocad import utils
LampEntry = namedtuple('LampEntry', 'number, mark, numxpower')
# \A1;2ARCTIC SMC/SAN 254 \S2х54/2,5;\P300 лк
def iter_lamps(acad, ob... |
def main():
acad = Autocad()
objects = None
if 'i' in sys.argv[1:]:
objects = acad.get_selection('Select objects')
lamps = defaultdict(int)
for lamp in iter_lamps(acad, objects):
lamps[lamp.mark] += int(lamp.number)
print '-' * 79
for mark, number in sorted(lamps.it... | obj in acad.iter_objects(('MText', 'MLeader'), block=objects):
try:
text = obj.TextString
except Exception:
continue
text = utils.unformat_mtext(text)
m = re.search(ur'(?P<num>\d+)(?P<mark>.*?)\\S(?P<num_power>.*?)/.*?;', text)
if not m:
... | identifier_body |
lights.py | #/usr/bin/env python
#-*- coding: utf-8 -*-
import re
import sys
from collections import namedtuple, defaultdict
from pyautocad import Autocad
from pyautocad import utils
LampEntry = namedtuple('LampEntry', 'number, mark, numxpower')
# \A1;2ARCTIC SMC/SAN 254 \S2х54/2,5;\P300 лк
def iter_lamps(acad, ob... | objects = None
if 'i' in sys.argv[1:]:
objects = acad.get_selection('Select objects')
lamps = defaultdict(int)
for lamp in iter_lamps(acad, objects):
lamps[lamp.mark] += int(lamp.number)
print '-' * 79
for mark, number in sorted(lamps.iteritems()):
print '%-20s | ... | yield LampEntry(m.group('num'), m.group('mark'), m.group('num_power'))
def main():
acad = Autocad()
| random_line_split |
TuxModalContainer.tsx | import React from 'react'
import classNames from 'classnames'
import CSSTransition from 'react-transition-group/CSSTransition'
import TransitionGroup from 'react-transition-group/TransitionGroup'
import toggleScroll from './toggle-scroll'
import { getState, setListener, State as StoreState, Modal } from './store'
impor... |
const { modals } = this.state
const lastModal = modals[modals.length - 1]
lastModal.onClose()
}
render() {
const { modals } = this.state
const hasModals = modals.length > 0
return (
<div className="ModalContainer">
<div
className={classNames(
'ModalCon... | {
return
} | conditional_block |
TuxModalContainer.tsx | import React from 'react'
import classNames from 'classnames'
import CSSTransition from 'react-transition-group/CSSTransition'
import TransitionGroup from 'react-transition-group/TransitionGroup'
import toggleScroll from './toggle-scroll'
import { getState, setListener, State as StoreState, Modal } from './store'
impor... | const { modals } = this.state
const lastModal = modals[modals.length - 1]
lastModal.onClose()
}
render() {
const { modals } = this.state
const hasModals = modals.length > 0
return (
<div className="ModalContainer">
<div
className={classNames(
'ModalConta... | random_line_split | |
TuxModalContainer.tsx | import React from 'react'
import classNames from 'classnames'
import CSSTransition from 'react-transition-group/CSSTransition'
import TransitionGroup from 'react-transition-group/TransitionGroup'
import toggleScroll from './toggle-scroll'
import { getState, setListener, State as StoreState, Modal } from './store'
impor... | () {
this.listener()
}
toggleScroll() {
const hasModals = this.state.modals.length > 0
toggleScroll(!hasModals)
}
onModalsChange = () => {
this.setState({ modals: getState() })
}
onClickBackdrop = (event: React.MouseEvent<any>) => {
if (event.target !== event.currentTarget) {
re... | componentWillUnmount | identifier_name |
TuxModalContainer.tsx | import React from 'react'
import classNames from 'classnames'
import CSSTransition from 'react-transition-group/CSSTransition'
import TransitionGroup from 'react-transition-group/TransitionGroup'
import toggleScroll from './toggle-scroll'
import { getState, setListener, State as StoreState, Modal } from './store'
impor... |
componentDidMount() {
this.listener = setListener(this.onModalsChange)
this.toggleScroll()
}
componentWillUnmount() {
this.listener()
}
toggleScroll() {
const hasModals = this.state.modals.length > 0
toggleScroll(!hasModals)
}
onModalsChange = () => {
this.setState({ modals: ... | {
this.toggleScroll()
} | identifier_body |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | (&mut self, c: Coordinates) -> Result<()> {
self.get_header_mut()
.insert("gps.coordinates", c.into())
.map(|_| ())
.chain_err(|| GPSEK::HeaderWriteError)
}
fn get_coordinates(&self) -> Result<Option<Coordinates>> {
match self.get_header().read("gps.coordinat... | set_coordinates | identifier_name |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... |
fn get_store() -> Store {
use libimagstore::file_abstraction::InMemoryFileAbstraction;
let backend = Box::new(InMemoryFileAbstraction::new());
Store::new_with_backend(PathBuf::from("/"), &None, backend).unwrap()
}
#[test]
fn test_set_gps() {
setup_logging();
l... | {
use env_logger;
let _ = env_logger::init().unwrap_or(());
} | identifier_body |
entry.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | let store = get_store();
let mut entry = store.create(PathBuf::from("test_setget_gps")).unwrap();
let coordinates = Coordinates {
latitude: GPSValue::new(0, 0, 0),
longitude: GPSValue::new(0, 0, 0),
};
let res = entry.set_coordinates(coordinates);
... | random_line_split | |
AttachmentPanelUi.js | /**
* conjoon
* (c) 2007-2015 conjoon.org
* licensing@conjoon.org
*
* conjoon
* Copyright (C) 2014 Thorsten Suckow-Homberg/conjoon.org
*
* This program is free software: you can redistribute it and/or modify | * published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program 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 th... | * it under the terms of the GNU Affero General Public License as | random_line_split |
App.tsx | import React from "react";
import cxs from "cxs/component";
import cxsStyles from "cxs";
import { Picture, FullsizePicture } from "../src";
const styles = cxsStyles({
border: "1px solid red",
boxShadow: "2px 2px 10px",
});
const Heading1 = cxs("h1")({
position: "relative",
textAlign: "center",
col... | srcSet:
"https://via.placeholder.com/500x250?text=Normal%20image 1x, https://via.placeholder.com/1000x500?text=Retina%20image 2x",
},
]}
cover="height"
center={true}
/>
</div>
... | },
{ | random_line_split |
ext-settings_menu.js |
closer.style.cssText = 'margin: 0; padding: 0; ' +
'position: fixed; top:0; bottom:0; left:0; right:0;' +
'z-index: 9990; ' +
(editor ? 'background-color: rgba(0, 0, 0, 0.3);' : '');
closer.addEventListener('click', function(e) {
if (!ignoreFocusOut) {
close();
... | {
ignoreFocusOut = ignore;
if (ignore) {
closer.style.pointerEvents = "none";
contentElement.style.pointerEvents = "auto";
}
} | identifier_body | |
ext-settings_menu.js | cs"],
Csound_Document: ["csd"],
Csound_Orchestra: ["orc"],
Csound_Score: ["sco"],
CSS: ["css"],
Curly: ["curly"],
D: ["d|di"],
Dart: ["dart"],
Diff: ["diff|patch"],
Dockerfile: ["^Dockerfile"],
Dot: ["dot"],
Drools: ["drl"],... |
var nameOverrides = {
ObjectiveC: "Objective-C",
CSharp: "C#",
golang: "Go",
C_Cpp: "C and C++",
Csound_Document: "Csound Document",
Csound_Orchestra: "Csound",
Csound_Score: "Csound Score",
coffee: "CoffeeScript",
HTML_Ruby: "HTML (Ruby)",
HTML_Elixir: "HTML (Elixir)",
FTL:... | random_line_split | |
ext-settings_menu.js | "scrollPastEnd",
items: [
{ caption : "None", value : 0 },
{ caption : "Half", value : 0.5 },
{ caption : "Full", value : 1 }
]
}
},
More: {
"Atomic soft tabs": {
path: "navigateWithinSoftTabs"
},
... | showSettingsMenu | identifier_name | |
ext-settings_menu.js | ByName = {};
exports.themes = themeData.map(function(data) {
var name = data[1] || data[0].replace(/ /g, "_").toLowerCase();
var theme = {
caption: data[0],
theme: "ace/theme/" + name,
isDark: data[2] == "dark",
name: name
};
exports.themesByName[name] = theme;
return... | {
control = ["div", {role: "group", "aria-labelledby": option.path + "-label"}, option.items.map(function(item) {
return ["button", {
value: item.value,
ace_selected_button: value == item.value,
'aria-pressed': value == item.valu... | conditional_block | |
main-ngcc.ts | #!/usr/bin/env node
/**
* @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 {mainNgcc} from './src/main';
import {parseCommandLineOptions} from './src/command_line_opt... |
process.exitCode = 0;
} catch (e: any) {
console.error((e as Error).stack || (e as Error).message);
process.exit(typeof e.code === 'number' ? e.code : 1);
}
})();
| {
const duration = Math.round((Date.now() - startTime) / 1000);
options.logger.debug(`Run ngcc in ${duration}s.`);
} | conditional_block |
main-ngcc.ts | #!/usr/bin/env node
/**
* @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 {mainNgcc} from './src/main';
import {parseCommandLineOptions} from './src/command_line_opt... | process.exit(typeof e.code === 'number' ? e.code : 1);
}
})(); | console.error((e as Error).stack || (e as Error).message); | random_line_split |
faBeer.js | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fas';
var iconName = 'beer';
var width = 448;
var height = 512;
var ligatures = [];
var unicode = 'f0fc';
var svgPathData = 'M368 96h-48V56c0-13.255-10.745-24-24-24H24C10.745 32 0 42.745 0 56v400c0 13.255 10.745 24 24 24h272c13.2... | exports.svgPathData = svgPathData; | exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode; | random_line_split |
RemotingProvider.js | @cfg {Object} actions
* Object literal defining the server side actions and methods. For example, if
* the Provider is configured with:
* <pre><code>
"actions":{ // each property within the 'actions' object represents a server side Class
"TestAction":[ // array of methods within each server side Cl... | else if(!this.url){
throw 'Error initializing RemotingProvider, no url configured.';
}
},
disconnect: function(){
if(this.connected){
this.connected = false;
this.fireEvent('disconnect', this);
}
},
onData: function(opt, success, xhr){
... | {
this.initAPI();
this.connected = true;
this.fireEvent('connect', this);
} | conditional_block |
RemotingProvider.js | @cfg {Object} actions
* Object literal defining the server side actions and methods. For example, if
* the Provider is configured with:
* <pre><code>
"actions":{ // each property within the 'actions' object represents a server side Class
"TestAction":[ // array of methods within each server side Cl... | * executing.
* @param {Ext.direct.RemotingProvider} provider
* @param {Ext.Direct.Transaction} transaction
*/
'beforecall',
/**
* @event call
* Fires immediately after the request to the server-... | random_line_split | |
script.js | /**
* 1. Building application menu.
* 2. Adding separator between submenu.
* 3. Build application menu with template.
*/ | /**
* Create menu instance.
*/
var menu = new Menu();
/**
* Create menu template.
*/
var template = [{
label: 'File',
submenu: [{
label: 'New'
}, {
label: 'Open'
}, {
type: 'separator'
}, {
label: 'Save'
}, {
label: 'Save As'
}, {
type: 'separator'
}, {
label: 'Print'
... | 'use strict';
const remote = require('electron').remote;
const Menu = remote.Menu;
| random_line_split |
test_qtxmlpatterns.py | import pytest
from qtpy import PYSIDE2, PYSIDE6, PYQT6
@pytest.mark.skipif((PYSIDE6 or PYQT6), reason="not available with qt 6.0") | assert QtXmlPatterns.QAbstractMessageHandler is not None
assert QtXmlPatterns.QAbstractUriResolver is not None
assert QtXmlPatterns.QAbstractXmlNodeModel is not None
assert QtXmlPatterns.QAbstractXmlReceiver is not None
if not PYSIDE2:
assert QtXmlPatterns.QSimpleXmlNodeModel is not None
... | def test_qtxmlpatterns():
"""Test the qtpy.QtXmlPatterns namespace"""
from qtpy import QtXmlPatterns | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.