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 |
|---|---|---|---|---|
views.py | """Views fo the node settings page."""
# -*- coding: utf-8 -*-
from flask import request
import logging
from addons.dropbox.serializer import DropboxSerializer
from addons.base import generic_views
from website.project.decorators import must_have_addon, must_be_addon_authorizer
logger = logging.getLogger(__name__)
de... |
dropbox_get_config = generic_views.get_config(
SHORT_NAME,
DropboxSerializer
)
def _set_folder(node_addon, folder, auth):
uid = folder['id']
node_addon.set_folder(uid, auth=auth)
node_addon.save()
dropbox_set_config = generic_views.set_config(
SHORT_NAME,
FULL_NAME,
DropboxSerializer... | """ Returns all the subsequent folders under the folder id passed.
"""
folder_id = request.args.get('folder_id')
return node_addon.get_folders(folder_id=folder_id) | identifier_body |
tracts_sim.py | .2, 0.05] # Proportion of pedigree that will be new migrants
# MigPropMat = [[8, 0.1, 0], [12, 0, 0.1]]
DemeSwitch = 0.1 # Chance of child leaving deme of parents
rho = 1 # Recombination rate
##@@ AllAncestry = True is assumed to assign parents ie no ancestry means you
## are not a leaf
colordict = {'EUR':'red', 'NAT'... | samp_ind = samp_ind[0]
else:
print "Depth error: mutiple roots to the pedigree"
print samp_ind
sys.exit()
tracts_ind = samp_ind.to_tracts_indiv()
## We split the pedigree into maternal/paternal sides when simulating with
## PSMC
elif method ==... | start_time = time.time()
if i % 100 == 0:
print "Simulating individual", i, "of", numinds
if method == "forward":
P = ped.Pedigree(sampleind = None,
DemeSwitch = DemeSwitch,
MigPropMat = migmat,
pedfile = pedfile,
ancfile = an... | conditional_block |
tracts_sim.py | ination rate
##@@ AllAncestry = True is assumed to assign parents ie no ancestry means you
## are not a leaf
colordict = {'EUR':'red', 'NAT':'blue', 'AFR':'green'}
#colordict = {'EUR':'yellow', 'NAT':'green'}
#colordict = {0:'red', 1:'blue', 2:'green'}
#colordict = {'AFR':'red', 'EUR':'blue'}#, 2:'green'}
#ChromLen... | random_line_split | ||
hybridmulti.rs | // Copyright 2016 The Noise-rs Developers.
//
// 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 ... | () {
debug::render_noise_module3("hybridmulti.png", &HybridMulti::new(), 1024, 1024, 200);
}
| main | identifier_name |
hybridmulti.rs | // Copyright 2016 The Noise-rs Developers.
//
// 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 ... | extern crate noise;
use noise::HybridMulti;
mod debug;
fn main() {
debug::render_noise_module3("hybridmulti.png", &HybridMulti::new(), 1024, 1024, 200);
} |
//! An example of using the `HybridMulti` noise function
| random_line_split |
hybridmulti.rs | // Copyright 2016 The Noise-rs Developers.
//
// 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 ... | {
debug::render_noise_module3("hybridmulti.png", &HybridMulti::new(), 1024, 1024, 200);
} | identifier_body | |
jquery.ui.widget.js | prototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
// TODO remove widgetBaseClass, see #8155
widgetBaseClass: fullName,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine al... | handlerProxy | identifier_name | |
jquery.ui.widget.js | 're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inh... | {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) {
return;
}
return ( typeof ha... | identifier_body | |
jquery.ui.widget.js | the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( $.isFunction( value ) ) {
prototype[ prop ] = (function() {
var _super =... |
}
this._setOptions( options );
return this;
},
_setOptions: function( options | {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
} | conditional_block |
jquery.ui.widget.js | the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( $.isFunction( value ) ) {
prototype[ prop ] = (function() {
var _super =... | } else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
new object( options, this );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget... | returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
| random_line_split |
Gruntfile.js | module.exports = function ( grunt ) {
// Project configuration.
grunt.initConfig({
pkg : grunt.file.readJSON( 'package.json' ),
jshint : {
options: {
jshintrc: true
},
files : ['src/javascripts/**/*.js']
},
browserify : {
... | }
},
banner : {
files : ['dist/preamble.js'],
tasks : ['usebanner'],
options : {
interrupt : true
}
}
}
});
// Load the plugins
grunt.loadNpmTasks( 'grunt-cont... | files : ['src/javascripts/**/*.js'],
tasks : ['browserify'],
options : {
interrupt : true | random_line_split |
checker.py | )
slots.add(argIndex)
filledSlots.update(range(len(self.argument_names) - self.default_count, len(self.argument_names)))
filledKwOnlySlots.update(range(len(self.kw_only_argument_names) - self.kw_only_default_count,
len(self.kw_only_argument_names)))
... |
def different_forks(self, lnode, rnode):
"""True, if lnode and rnode are located on different forks of
IF/TRY."""
ancestor = self.get_common_ancestor(lnode, rnode)
if isinstance(ancestor, ast.If):
for fork in (ancestor.body, ancestor.orelse):
if self.on_... | return (self.descendant_of(lnode, items, parent) ^ self.descendant_of(rnode, items, parent)) | identifier_body |
checker.py | , 'parent') or not hasattr(rnode, 'parent'):
return
if (lnode.level > rnode.level):
return self.get_common_ancestor(lnode.parent, rnode, stop)
if (rnode.level > lnode.level):
return self.get_common_ancestor(lnode, rnode.parent, stop)
return self.get_common_anc... | else:
self.offset = (node_offset[0] + node_lineno + example.lineno,
node_offset[1] + example.indent + 4) | random_line_split | |
checker.py | (dict):
importStarred = False # set to True when import * is found
def __repr__(self):
scope_cls = self.__class__.__name__
return '<%s at 0x%x %s>' % (scope_cls, id(self), dict.__repr__(self))
class ClassScope(Scope):
pass
class FunctionScope(Scope):
"""Represents the name sco... | Scope | identifier_name | |
checker.py | _children
# expression contexts are node instances too, though being constants
LOAD = STORE = DEL = AUGLOAD = AUGSTORE = PARAM = ignore
# same for operators
AND = OR = ADD = SUB = MULT = DIV = MOD = POW = LSHIFT = RSHIFT = BITOR = BITXOR = BITAND = FLOORDIV = INVERT = \
NOT = UADD = USUB = E... | self.handle_node_store(node) | conditional_block | |
event.py | warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-130... |
return getattr(obj, self.slot, None)
def __set__(self, obj, value):
if value is None:
self.__delete__(obj)
return
if isinstance(value, (int, long, )):
# UTC timestamp
value = pytz.utc.localize(
datetime.datetime.fromtimestamp... | return self | conditional_block |
event.py | warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-130... |
def merge(self, other):
"""Merge messages."""
def ret_self():
self.objects.update(other.objects)
return [self]
if not self.mergeable(other):
return [self, other]
if self.event_type == CREATE:
if other.event_type == DELETE:
... | """Can this event be merged with other."""
if self.scheduled is not None:
return False
if self.subject != other.subject:
return False
if self.event_type == CREATE:
return other.event_type not in (DEACTIVATE, REMOVE)
if self.event_type == DELETE:
... | identifier_body |
event.py | warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-130... | (self):
"""Hash."""
return hash(self.verb)
# Define event types:
ADD = EventType('add', 'Add an object to subject')
CREATE = EventType('create', 'Create a new subject')
ACTIVATE = EventType('activate', 'Subject has no longer quarantines in system')
MODIFY = EventType('modify', 'Attributes has changed... | __hash__ | identifier_name |
event.py | warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-130... |
def merge(self, other):
"""Merge messages."""
def ret_self():
self.objects.update(other.objects)
return [self]
if not self.mergeable(other):
return [self, other]
if self.event_type == CREATE:
if other.event_type == DELETE:
... | if self.context != other.context:
return False
return True | random_line_split |
thirdeye.metric.table.js | $(document).ready(function() { | var currentTime = moment(cellObj.html())
var baselineTime = moment(cellObj.attr('title'))
cellObj.html(currentTime.tz(tz).format('YYYY-MM-DD HH:mm:ss z'))
cellObj.attr('title', baselineTime.tz(tz).format('YYYY-MM-DD HH:mm:ss z'))
// Click changes current value to that time
... | $(".metric-table-time").each(function(i, cell) {
var tz = getTimeZone();
var cellObj = $(cell) | random_line_split |
laupdate.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Distributed under the terms of MIT License (MIT)
import pywikibot
import time
from pywikibot.data.api import Request
import re
site = pywikibot.Site('fa', fam='wikipedia')
print "Fetching admins list"
data = Request(site=site, action="query", list="allusers", augroup="sysop",... | else:
adminsac.append(admin)
else:
acaction.sort()
dcaction.sort()
if re.search(ur"[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآ]", admin[0]):
admin = u"!!!!!!!!!!!!!!!!!!!!!!!!!!!" + admin
try:
adminsdiac[admin] = acaction[-1]
except:
... | acaction.append(actionmw["timestamp"].split("T")[0].replace("-", ""))
if len(acaction) >= 10:
if re.search(ur"[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآ]", admin[0]):
adminsac.append(u"!!!!!!!!!!!!!!!!!!!!!!!!!!!" + admin) | random_line_split |
laupdate.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Distributed under the terms of MIT License (MIT)
import pywikibot
import time
from pywikibot.data.api import Request
import re
site = pywikibot.Site('fa', fam='wikipedia')
print "Fetching admins list"
data = Request(site=site, action="query", list="allusers", augroup="sysop",... | )
dcaction.sort()
if re.search(ur"[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآ]", admin[0]):
admin = u"!!!!!!!!!!!!!!!!!!!!!!!!!!!" + admin
try:
adminsdiac[admin] = acaction[-1]
except:
adminsdiac[admin] = dcaction[-1]
pywikibot.output(admin)
adminsac.sort()... | if re.search(ur"[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآ]", admin[0]):
adminsac.append(u"!!!!!!!!!!!!!!!!!!!!!!!!!!!" + admin)
else:
adminsac.append(admin)
else:
acaction.sort( | conditional_block |
ActivityOverview.js | import React, { Component } from 'react';
import MePanel from '../components/panels/MePanel';
import { Segment } from 'semantic-ui-react'
import DetailedActivity from './activities/DetailedActivity';
import ActivityGraph from './activities/ActivityGraph';
class ActivityOverview extends Component {
constructor(prop... |
render() {
return (
<Segment.Group horizontal>
<Segment compact basic className="rt-statistics-segment">
<MePanel me={this.props.me} loading={this.props.loading} />
</Segment>
<Segment padded loading={this.props.loading} basic>
<ActivityGraph
loading... | {
let activity = this.props.activities.filter(activity => activity.activityId === activityId);
this.setState({ selectedActivity: activity.length > 0 ? activity[0] : null });
} | identifier_body |
ActivityOverview.js | import React, { Component } from 'react';
| import MePanel from '../components/panels/MePanel';
import { Segment } from 'semantic-ui-react'
import DetailedActivity from './activities/DetailedActivity';
import ActivityGraph from './activities/ActivityGraph';
class ActivityOverview extends Component {
constructor(props) {
super(props);
this.state = {
... | random_line_split | |
ActivityOverview.js | import React, { Component } from 'react';
import MePanel from '../components/panels/MePanel';
import { Segment } from 'semantic-ui-react'
import DetailedActivity from './activities/DetailedActivity';
import ActivityGraph from './activities/ActivityGraph';
class ActivityOverview extends Component {
| (props) {
super(props);
this.state = {
selectedActivity: {
activityId: "N/A",
averageHeartRate: 0,
date: null,
description: "N/A",
distance: 0,
maxHeartRate: 0,
pace: 0,
time: 0,
type: "N/A",
location: null
}
};
}
... | constructor | identifier_name |
servermessagearchive.ts | <name>ServerMessageArchive</name>
<message>
<source>Server Message Archive</source>
<translation>Серверный архив сообщений</translation>
</message>
<message>
<source>Allows to save the history of communications on the server</source>
<translation>Позволяет сохранять истор... | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ru" sourcelanguage="en">
<context> | random_line_split | |
quicklaunch_tr.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="tr"> | <location filename="../../../lxqtquicklaunch.cpp" line="214"/>
<source>Drop Error</source>
<translation>Bırakma Hatası</translation>
</message>
<message>
<location filename="../../../lxqtquicklaunch.cpp" line="215"/>
<source>File/URL '%1' cannot be embedded into... | <context>
<name>LXQtQuickLaunch</name>
<message> | random_line_split |
document-store.ts | import type {Observable} from 'rxjs'
import {getDraftId, isDraftId} from '../../util/draftUtils'
import {versionedClient} from '../../client/versionedClient'
import type {DocumentVersionEvent, Pair} from './document-pair/checkoutPair'
import {checkoutPair} from './document-pair/checkoutPair'
import createDeprecatedAPIs... |
export default {
...createDeprecatedAPIs(versionedClient), // Todo: can be removed in ~january 2020
checkoutPair: (idPair: IdPair): Pair => checkoutPair(idPair),
listenQuery,
resolveTypeForDocument,
pair: {
editState: (publishedId: string, type: string): Observable<EditStateFor> =>
editState(getI... | {
if (isDraftId(publishedId)) {
throw new Error('editOpsOf does not expect a draft id.')
}
return {publishedId, draftId: getDraftId(publishedId)}
} | identifier_body |
document-store.ts | import type {Observable} from 'rxjs'
import {getDraftId, isDraftId} from '../../util/draftUtils'
import {versionedClient} from '../../client/versionedClient'
import type {DocumentVersionEvent, Pair} from './document-pair/checkoutPair'
import {checkoutPair} from './document-pair/checkoutPair'
import createDeprecatedAPIs... |
return {publishedId, draftId: getDraftId(publishedId)}
}
export default {
...createDeprecatedAPIs(versionedClient), // Todo: can be removed in ~january 2020
checkoutPair: (idPair: IdPair): Pair => checkoutPair(idPair),
listenQuery,
resolveTypeForDocument,
pair: {
editState: (publishedId: string, typ... | {
throw new Error('editOpsOf does not expect a draft id.')
} | conditional_block |
document-store.ts | import type {Observable} from 'rxjs'
import {getDraftId, isDraftId} from '../../util/draftUtils'
import {versionedClient} from '../../client/versionedClient'
import type {DocumentVersionEvent, Pair} from './document-pair/checkoutPair'
import {checkoutPair} from './document-pair/checkoutPair'
import createDeprecatedAPIs... | if (isDraftId(publishedId)) {
throw new Error('editOpsOf does not expect a draft id.')
}
return {publishedId, draftId: getDraftId(publishedId)}
}
export default {
...createDeprecatedAPIs(versionedClient), // Todo: can be removed in ~january 2020
checkoutPair: (idPair: IdPair): Pair => checkoutPair(idPai... | function getIdPairFromPublished(publishedId: string): IdPair { | random_line_split |
document-store.ts | import type {Observable} from 'rxjs'
import {getDraftId, isDraftId} from '../../util/draftUtils'
import {versionedClient} from '../../client/versionedClient'
import type {DocumentVersionEvent, Pair} from './document-pair/checkoutPair'
import {checkoutPair} from './document-pair/checkoutPair'
import createDeprecatedAPIs... | (publishedId: string): IdPair {
if (isDraftId(publishedId)) {
throw new Error('editOpsOf does not expect a draft id.')
}
return {publishedId, draftId: getDraftId(publishedId)}
}
export default {
...createDeprecatedAPIs(versionedClient), // Todo: can be removed in ~january 2020
checkoutPair: (idPair: IdP... | getIdPairFromPublished | identifier_name |
index.js | var _ = require('lodash');
var express = require('express');
var fs = require('fs');
var grappling = require('grappling-hook');
var path = require('path');
var utils = require('keystone-utils');
/**
* Don't use process.cwd() as it breaks module encapsulation
* Instead, let's use module.parent if it's present, or the... | /* Deprecation / Change warnings for 0.4 */
Keystone.prototype.routes = function () {
throw new Error('keystone.routes(fn) has been removed, use keystone.set(\'routes\', fn)');
};
/**
* The exports object is an instance of Keystone.
*/
var keystone = module.exports = new Keystone();
/*
Note: until #1777 is compl... | Keystone.prototype.wrapHTMLError = require('./lib/core/wrapHTMLError');
| random_line_split |
index.js | var _ = require('lodash');
var express = require('express');
var fs = require('fs');
var grappling = require('grappling-hook');
var path = require('path');
var utils = require('keystone-utils');
/**
* Don't use process.cwd() as it breaks module encapsulation
* Instead, let's use module.parent if it's present, or the... |
};
/**
* Keystone version
*/
keystone.version = require('./package.json').version;
// Expose Modules
keystone.session = require('./lib/session');
| {
var dashes = '\n------------------------------------------------\n';
console.log(dashes + 'KeystoneJS: ' + type + ':\n\n' + msg + dashes);
} | conditional_block |
abdt_branch__t.py | , branch link
# [ C] can move bad_pre_review -> 'new' states without duplicating branches
# [ D] unique names and emails are returned in the order of most recent first
# [ E] all commits are shown when no arguments are supplied
# [ E] number of commits can be limited by max_commits argument
# [ E] number of commits can... |
self.assertTupleEqual(
author_names_emails[1],
(alice_user, alice_email))
# any_author_emails = branch.get_any_author_emails()
# self.assertEqual(any_author_emails[-1], alice_email)
# self.assertEqual(any_author_emails[-2], bob_email)
def test_E_NewCommits... | base, branch_name, branch = self._setup_for_untracked_branch()
alice_user = 'Alice'
alice_email = 'alice@server.test'
bob_user = 'Bob'
bob_email = 'bob@server.test'
self._dev_commit_new_empty_file('ALICE1', alice_user, alice_email)
self._dev_commit_new_empty_file('BOB1... | identifier_body |
abdt_branch__t.py | , branch link
# [ C] can move bad_pre_review -> 'new' states without duplicating branches
# [ D] unique names and emails are returned in the order of most recent first
# [ E] all commits are shown when no arguments are supplied
# [ E] number of commits can be limited by max_commits argument
# [ E] number of commits can... | (self, filename, user, email):
self._create_new_file(self.repo_dev, filename)
self.repo_dev('add', filename)
self.repo_dev(
'commit',
'-m',
filename,
'--author=' + '{} <{}>'.format(user, email))
def test_XB_UntrackedBranch(self):
abdt_... | _dev_commit_new_empty_file | identifier_name |
abdt_branch__t.py | , branch link
# [ C] can move bad_pre_review -> 'new' states without duplicating branches
# [ D] unique names and emails are returned in the order of most recent first
# [ E] all commits are shown when no arguments are supplied
# [ E] number of commits can be limited by max_commits argument
# [ E] number of commits can... |
# [ E] number of commits can be limited by max_commits argument
new_commits_str = branch.describe_new_commits(2)
new_commits = new_commits_str.splitlines()
self.assertEqual(3, len(new_commits))
self.assertTrue(new_commits[0].endswith('Commit 4'))
self.assertTrue(new_com... | self.assertTrue(line.endswith('Commit {}'.format(count)))
count -= 1 | conditional_block |
abdt_branch__t.py | and emails are returned in the order of most recent first
# [ E] all commits are shown when no arguments are supplied
# [ E] number of commits can be limited by max_commits argument
# [ E] number of commits can be limited by max_size argument
# [ ] can detect if review branch has new commits (after ff, merge, rebase)... | branch_url)
# should not raise
branch.verify_review_branch_base() | random_line_split | |
137_Single_Number_II.py | #!/usr/bin/env python
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum1, sum2, lb = 0, 0, min(nums)
mask1 = int('55555555', base=16)
mask2 = int('AAAAAAAA', base=16)
for num in nums:
sum1 += ((nu... |
# print('after mod: ', num, bin(sum1)[2:], bin(sum2)[2:])
return sum1 + (sum2 << 1) + lb
mask1 = int('55555555', base=16)
mask2 = int('AAAAAAAA', base=16)
nums1 = 2
int1 = (nums1 & mask1)
int2 = (nums1 & mask2) >> 1
nums = [0,1,0,1,0,1,99]
nums = [2,2,3,2]
nums = [2,2,5,5,1,5,1,1,0,2]
num... | sum2 ^= (3 << 2*i) | conditional_block |
137_Single_Number_II.py | #!/usr/bin/env python
class Solution:
def singleNumber(self, nums): | """
sum1, sum2, lb = 0, 0, min(nums)
mask1 = int('55555555', base=16)
mask2 = int('AAAAAAAA', base=16)
for num in nums:
sum1 += ((num - lb) & mask1)
sum2 += ((num - lb) & mask2) >> 1
# print('before mod: ', num, bin(sum1)[2:], bin(sum2)[2:])
... | """
:type nums: List[int]
:rtype: int | random_line_split |
137_Single_Number_II.py | #!/usr/bin/env python
class | :
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum1, sum2, lb = 0, 0, min(nums)
mask1 = int('55555555', base=16)
mask2 = int('AAAAAAAA', base=16)
for num in nums:
sum1 += ((num - lb) & mask1)
sum2 += ... | Solution | identifier_name |
137_Single_Number_II.py | #!/usr/bin/env python
class Solution:
def singleNumber(self, nums):
|
return sum1 + (sum2 << 1) + lb
mask1 = int('55555555', base=16)
mask2 = int('AAAAAAAA', base=16)
nums1 = 2
int1 = (nums1 & mask1)
int2 = (nums1 & mask2) >> 1
nums = [0,1,0,1,0,1,99]
nums = [2,2,3,2]
nums = [2,2,5,5,1,5,1,1,0,2]
nums = [-2,-2,1,1,-3,1,-3,-3,-4,-2]
print(int1)
print(int2)
sol = Solutio... | """
:type nums: List[int]
:rtype: int
"""
sum1, sum2, lb = 0, 0, min(nums)
mask1 = int('55555555', base=16)
mask2 = int('AAAAAAAA', base=16)
for num in nums:
sum1 += ((num - lb) & mask1)
sum2 += ((num - lb) & mask2) >> 1
# prin... | identifier_body |
browser.js | /* ========================================================================
* ZUI: browser.js
* http://zui.sexy
* ========================================================================
* Copyright (c) 2014 cnezsoft.com; Licensed MIT
* ======================================================================== */
... | {
var ie = this.ie,
$html = $('html');
$html.toggleClass('ie', ie)
.removeClass('ie-6 ie-7 ie-8 ie-9 ie-10');
if (ie)
{
$html.addClass('ie-' + ie)
.toggleClass('gt-ie-7 gte-ie-8 support-ie', ie >= 8)
.toggleClass('lt... | break;
}
}
}
this.ie = ie;
this.cssHelper();
};
// Append CSS class to html tag
Browser.prototype.cssHelper = function()
| conditional_block |
browser.js | /* ========================================================================
* ZUI: browser.js
* http://zui.sexy
* ========================================================================
* Copyright (c) 2014 cnezsoft.com; Licensed MIT
* ======================================================================== */
... |
$browseHappy.find('.content').html(this.browseHappyTip || browseHappyTip[$.clientLang() || 'zh_cn']);
}
};
// Detect it is IE, can given a version
Browser.prototype.isIE = function(version)
{
// var ie = /*@cc_on !@*/false;
var b = document.createElement('b');
... | } | random_line_split |
cloudresourcemanager_v3_generated_folders_delete_folder_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... | ():
# Create a client
client = resourcemanager_v3.FoldersAsyncClient()
# Initialize request argument(s)
request = resourcemanager_v3.DeleteFolderRequest(
name="name_value",
)
# Make the request
operation = client.delete_folder(request=request)
print("Waiting for operation to c... | sample_delete_folder | identifier_name |
cloudresourcemanager_v3_generated_folders_delete_folder_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... |
# [END cloudresourcemanager_v3_generated_Folders_DeleteFolder_async]
| client = resourcemanager_v3.FoldersAsyncClient()
# Initialize request argument(s)
request = resourcemanager_v3.DeleteFolderRequest(
name="name_value",
)
# Make the request
operation = client.delete_folder(request=request)
print("Waiting for operation to complete...")
response = a... | identifier_body |
cloudresourcemanager_v3_generated_folders_delete_folder_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... | async def sample_delete_folder():
# Create a client
client = resourcemanager_v3.FoldersAsyncClient()
# Initialize request argument(s)
request = resourcemanager_v3.DeleteFolderRequest(
name="name_value",
)
# Make the request
operation = client.delete_folder(request=request)
pri... | random_line_split | |
24_game_solve.rs | // http://rosettacode.org/wiki/24_game/Solve
// modeled after the scala solution
// http://rosettacode.org/wiki/24_game/Solve#Scala
#![feature(collections)]
#![feature(slice_patterns)]
extern crate num;
use num::rational::{Ratio, Rational};
use num::traits::Zero;
// convenience macro to create a fixed-sized vector
//... | () {
assert_eq!(
// without the rationals! macro
[Ratio::from_integer(1),
Ratio::from_integer(2),
Ratio::from_integer(3),
Ratio::from_integer(4)],
// with the rationals! macro
(rationals![1, 2, 3, 4]));
}
#[test]
#[ignore] // printing of rationals changed but seems wrong...
fn test_solv... | test_rationals_macro | identifier_name |
24_game_solve.rs | // http://rosettacode.org/wiki/24_game/Solve
// modeled after the scala solution
// http://rosettacode.org/wiki/24_game/Solve#Scala
#![feature(collections)]
#![feature(slice_patterns)]
extern crate num;
use num::rational::{Ratio, Rational};
use num::traits::Zero;
// convenience macro to create a fixed-sized vector
//... | }
rt
}
}
}
#[test]
fn test_rationals_macro() {
assert_eq!(
// without the rationals! macro
[Ratio::from_integer(1),
Ratio::from_integer(2),
Ratio::from_integer(3),
Ratio::from_integer(4)],
// with the rationals! macro
(rationals![1, 2, 3, 4]));
}
#[te... | random_line_split | |
24_game_solve.rs | // http://rosettacode.org/wiki/24_game/Solve
// modeled after the scala solution
// http://rosettacode.org/wiki/24_game/Solve#Scala
#![feature(collections)]
#![feature(slice_patterns)]
extern crate num;
use num::rational::{Ratio, Rational};
use num::traits::Zero;
// convenience macro to create a fixed-sized vector
//... | {
let mut r = rationals![1, 3, 7, 9];
assert_eq!(
solve(&mut r[..], 24),
Some("(9 / (3 / (1 + 7)))".to_string()));
} | identifier_body | |
mt_login_test.py | #! /usr/bin/python
import socket
from ansible.module_utils import mt_api
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
hostname=dict(required=True),
username=dict(required=True),
password=dict(required=True, no_log=True),
)... | main() | conditional_block | |
mt_login_test.py | #! /usr/bin/python
import socket
from ansible.module_utils import mt_api
from ansible.module_utils.basic import AnsibleModule
def main():
| except:
module.fail_json(
msg="Could not log into Mikrotik device. Check the username and password."
)
else:
module.fail_json(
msg="Could not access RouterOS api." + " Verify API service is enabled and not blocked by firewall."
)
# response = apiros.talk([b'/ip/address... | module = AnsibleModule(
argument_spec=dict(
hostname=dict(required=True),
username=dict(required=True),
password=dict(required=True, no_log=True),
)
)
hostname = module.params['hostname']
username = module.params['username']
password = module.params['password']
changed = False
... | identifier_body |
mt_login_test.py | #! /usr/bin/python
import socket
from ansible.module_utils import mt_api
from ansible.module_utils.basic import AnsibleModule
def | ():
module = AnsibleModule(
argument_spec=dict(
hostname=dict(required=True),
username=dict(required=True),
password=dict(required=True, no_log=True),
)
)
hostname = module.params['hostname']
username = module.params['username']
password = module.params['password']
changed = ... | main | identifier_name |
mt_login_test.py | #! /usr/bin/python
import socket
from ansible.module_utils import mt_api
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
hostname=dict(required=True),
username=dict(required=True),
password=dict(required=True, no_log=True),
)... | mk.login()
except:
module.fail_json(
msg="Could not log into Mikrotik device. Check the username and password."
)
else:
module.fail_json(
msg="Could not access RouterOS api." + " Verify API service is enabled and not blocked by firewall."
)
# response = apiros.ta... | mk = mt_api.Mikrotik(hostname,username,password)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((hostname, 8728))
if result == 0:
try: | random_line_split |
messages.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 {computeMsgId} from '@angular/compiler';
import {BLOCK_MARKER, ID_SEPARATOR, MEANING_SEPARATOR} from './consta... |
throw new Error(`Unterminated $localize metadata block in "${raw}".`);
} | {
if (raw[rawIndex] === '\\') {
rawIndex++;
} else if (cooked[cookedIndex] === BLOCK_MARKER) {
return cookedIndex;
}
} | conditional_block |
messages.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 {computeMsgId} from '@angular/compiler';
import {BLOCK_MARKER, ID_SEPARATOR, MEANING_SEPARATOR} from './consta... | ************************************************************************************************/
for (let cookedIndex = 1, rawIndex = 1; cookedIndex < cooked.length; cookedIndex++, rawIndex++) {
if (raw[rawIndex] === '\\') {
rawIndex++;
} else if (cooked[cookedIndex] === BLOCK_MARKER) {
return ... | export function findEndOfBlock(cooked: string, raw: string): number {
/************************************************************************************************
* This function is repeated in `src/localize/src/localize.ts` and the two should be kept in sync.
* (See that file for more explanation of why.) | random_line_split |
messages.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 {computeMsgId} from '@angular/compiler';
import {BLOCK_MARKER, ID_SEPARATOR, MEANING_SEPARATOR} from './consta... | (index: number) {
return index === 1 ? 'PH' : `PH_${index - 1}`;
}
/**
* Find the end of a "marked block" indicated by the first non-escaped colon.
*
* @param cooked The cooked string (where escaped chars have been processed)
* @param raw The raw string (where escape sequences are still in place)
*
* @returns ... | computePlaceholderName | identifier_name |
messages.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 {computeMsgId} from '@angular/compiler';
import {BLOCK_MARKER, ID_SEPARATOR, MEANING_SEPARATOR} from './consta... |
function computePlaceholderName(index: number) {
return index === 1 ? 'PH' : `PH_${index - 1}`;
}
/**
* Find the end of a "marked block" indicated by the first non-escaped colon.
*
* @param cooked The cooked string (where escaped chars have been processed)
* @param raw The raw string (where escape sequences a... | {
raw = raw || cooked;
if (raw.charAt(0) !== BLOCK_MARKER) {
return {text: cooked};
} else {
const endOfBlock = findEndOfBlock(cooked, raw);
return {
block: cooked.substring(1, endOfBlock),
text: cooked.substring(endOfBlock + 1),
};
}
} | identifier_body |
67a6ac9b727b_update_spatial_params.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
session.close()
def downgrade():
pass
| params = json.loads(slc.params)
if params.get("latitude"):
params["spatial"] = {
"lonCol": params.get("longitude"),
"latCol": params.get("latitude"),
"type": "latlong",
}
del params["latitude"]
del params["longitude"... | conditional_block |
67a6ac9b727b_update_spatial_params.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | ():
bind = op.get_bind()
session = db.Session(bind=bind)
for slc in session.query(Slice).filter(Slice.viz_type.like("deck_%")):
params = json.loads(slc.params)
if params.get("latitude"):
params["spatial"] = {
"lonCol": params.get("longitude"),
"la... | upgrade | identifier_name |
67a6ac9b727b_update_spatial_params.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | pass | identifier_body | |
67a6ac9b727b_update_spatial_params.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | params = json.loads(slc.params)
if params.get("latitude"):
params["spatial"] = {
"lonCol": params.get("longitude"),
"latCol": params.get("latitude"),
"type": "latlong",
}
del params["latitude"]
del params["lo... | random_line_split | |
index.tsx | import React, {
createContext,
FC,
ReactNode,
useContext,
useRef,
KeyboardEvent,
useState,
useEffect,
CSSProperties
} from "react";
import PropTypes, { ValidationMap } from "prop-types";
import classNames from "classnames";
import { IconArrowRight } from "@components/Icon";
import { AutoIncreasingCoun... | if (typeof key === "string") {
return key;
}
return ownKey;
}
function useItemId() {
const { current: id } = useRef(generateItemKey());
return id;
}
const CONFIRM_KEYS = ["Enter", " "];
export const CollapseItem: FC<CollapseItemProps> = props => {
const {
title,
children,
itemKey,
dis... | const { current: ownKey } = useRef<string>(generateItemKey()); | random_line_split |
index.tsx | import React, {
createContext,
FC,
ReactNode,
useContext,
useRef,
KeyboardEvent,
useState,
useEffect,
CSSProperties
} from "react";
import PropTypes, { ValidationMap } from "prop-types";
import classNames from "classnames";
import { IconArrowRight } from "@components/Icon";
import { AutoIncreasingCoun... | (key?: string) {
const { current: ownKey } = useRef<string>(generateItemKey());
if (typeof key === "string") {
return key;
}
return ownKey;
}
function useItemId() {
const { current: id } = useRef(generateItemKey());
return id;
}
const CONFIRM_KEYS = ["Enter", " "];
export const CollapseItem: FC<Colla... | useItemKey | identifier_name |
index.tsx | import React, {
createContext,
FC,
ReactNode,
useContext,
useRef,
KeyboardEvent,
useState,
useEffect,
CSSProperties
} from "react";
import PropTypes, { ValidationMap } from "prop-types";
import classNames from "classnames";
import { IconArrowRight } from "@components/Icon";
import { AutoIncreasingCoun... | return prevKeys.concat(key);
});
};
const onChangeForAccordion = (key: string) => {
invokeOnChange(key, ownActiveKeys);
setOwnActiveKeys(prevKeys => {
if (prevKeys.includes(key)) {
return [];
}
return [key];
});
};
if (accordion) {
return [ownActiveKeys, onCha... | {
const { activeKeys, onChange: onChangeFromProps, accordion = false } = props;
const [ownActiveKeys, setOwnActiveKeys] = useState<string[]>([]);
const invokeOnChange = (key: string, keys: string[]) =>
onChangeFromProps?.({
detail: { key, isActive: !keys.includes(key) }
});
if (activeKeys) {
... | identifier_body |
index.tsx | import React, {
createContext,
FC,
ReactNode,
useContext,
useRef,
KeyboardEvent,
useState,
useEffect,
CSSProperties
} from "react";
import PropTypes, { ValidationMap } from "prop-types";
import classNames from "classnames";
import { IconArrowRight } from "@components/Icon";
import { AutoIncreasingCoun... |
}, [isActive]);
useEffect(() => {
const transitToOpen = () => {
// max-height should be `0` here
// since we set max-height to `0` when close
// no need to force reflow
setActiveState("open");
setStyle({
maxHeight: contentRef.current?.scrollHeight
});
};
cons... | {
transitToCloseActive();
} | conditional_block |
community.component.ts |
/**
* @module Spectrum
*/ /** */
import { ISpectrumCommunity } from '../../interfaces/spectrum/community/community.interface';
import { ISpectrumLobby } from '../../interfaces/spectrum/community/chat/lobby.interface';
import { SpectrumLobby } from '../chat/lobby.component';
import { RSI } from "../../../index";
imp... |
/**
* Public getter for Lobbies in the Community
* @return array of Lobbies the bot can see in this community
*/
public get lobbies(): SpectrumLobby[] {
return this._lobbies;
}
public getLobbyById(id: number): SpectrumLobby {
let i = this._community.lobbies.findIndex((l... | {
this._community = co;
this._community.id = Number(co.id);
this._community.lobbies.forEach((l: ISpectrumLobby) => {
this._lobbies.push(new SpectrumLobby(l));
});
this._community.forum_channel_groups.forEach((group: ISpectrumChannelGroup) => {
group.chan... | identifier_body |
community.component.ts |
/**
* @module Spectrum
*/ /** */
import { ISpectrumCommunity } from '../../interfaces/spectrum/community/community.interface';
import { ISpectrumLobby } from '../../interfaces/spectrum/community/chat/lobby.interface';
import { SpectrumLobby } from '../chat/lobby.component';
import { RSI } from "../../../index";
imp... | (): ISpectrumChannelGroup[] {
return this._community.forum_channel_groups;
}
/**
* Finds a given channel in this community
*
* @param id the id of the channel
* @param channel the channel to look for
* @return SpectrumChannel or null if not found
*/
public getChannel(... | getChannelGroups | identifier_name |
community.component.ts | /**
* @module Spectrum
*/ /** */
import { ISpectrumCommunity } from '../../interfaces/spectrum/community/community.interface';
import { ISpectrumLobby } from '../../interfaces/spectrum/community/chat/lobby.interface';
import { SpectrumLobby } from '../chat/lobby.component';
import { RSI } from "../../../index";
impo... | public get channels(): SpectrumChannel[] {
return this._channels;
}
} | */ | random_line_split |
TemplatedWidget.ts | namespace Serenity {
@Serenity.Decorators.registerClass()
export class TemplatedWidget<TOptions> extends Widget<TOptions> {
protected idPrefix: string;
private static templateNames: Q.Dictionary<string> = {};
constructor(container: JQuery, options?: TOptions) {
s... | Widget>(id: string, type: { new (...args: any[]): TWidget }) {
return Serenity.WX.getWidget(this.byId(id), type);
}
private static noGeneric(s: string): string {
var dollar = s.indexOf('$');
if (dollar >= 0) {
return s.substr(0, dollar);
... | ID<T | identifier_name |
TemplatedWidget.ts | namespace Serenity {
@Serenity.Decorators.registerClass()
export class TemplatedWidget<TOptions> extends Widget<TOptions> {
protected idPrefix: string;
private static templateNames: Q.Dictionary<string> = {};
constructor(container: JQuery, options?: TOptions) {
s... |
protected getTemplate(): string {
var templateName = this.getTemplateName();
var script = $('script#Template_' + templateName);
if (script.length > 0) {
return script.html();
}
let template: string;
if (!Q.canLo... |
return null;
}
| identifier_body |
TemplatedWidget.ts | namespace Serenity {
@Serenity.Decorators.registerClass()
export class TemplatedWidget<TOptions> extends Widget<TOptions> {
protected idPrefix: string;
private static templateNames: Q.Dictionary<string> = {};
constructor(container: JQuery, options?: TOptions) {
s... |
name = TemplatedWidget.noGeneric((ss as any).getTypeName(type));
if (Q.canLoadScriptData('Template.' + name) ||
$('script#Template_' + name).length > 0) {
TemplatedWidget.templateNames[fullName] = name;
return name;
... |
templateNames[fullName] = name;
return name;
}
| conditional_block |
TemplatedWidget.ts | namespace Serenity {
@Serenity.Decorators.registerClass()
export class TemplatedWidget<TOptions> extends Widget<TOptions> {
protected idPrefix: string;
private static templateNames: Q.Dictionary<string> = {};
constructor(container: JQuery, options?: TOptions) {
s... | throw new Error(Q.format(
"Can't locate template for widget '{0}' with name '{1}'!",
(ss as any).getTypeName((ss as any).getInstanceType(this)), templateName));
}
return template;
}
}
} | if (template == null) {
| random_line_split |
migration.py | import logging
import time
import types
from autotest.client.shared import error
from virttest import utils_misc, utils_test, aexpect
def run(test, params, env):
"""
KVM migration test:
1) Get a live VM and clone it.
2) Verify that the source VM supports migration. If it does, proceed with
... | vm = env.get_vm(env, params.get("main_vm"))
vm.verify_alive()
session = vm.wait_for_login()
if stress_stop_cmd:
logging.warn("Killing background stress process "
... | """
This deamon will keep watch the status of stress in guest. If the stress
program is finished before migration this will restart it.
"""
while True:
bg = params.get("guest_stress_test_pid")
action = params.get("action")
if action == "run":
... | identifier_body |
migration.py | import logging
import time
import types
from autotest.client.shared import error
from virttest import utils_misc, utils_test, aexpect
def run(test, params, env):
"""
KVM migration test:
1) Get a live VM and clone it.
2) Verify that the source VM supports migration. If it does, proceed with
... | utils_misc.format_str_for_message(reference_output))
logging.info("Output after:" +
utils_misc.format_str_for_message(output))
raise error.TestFail("Command '%s' produced different output "
"be... | logging.info("Command output before migration differs from "
"command output after migration")
logging.info("Command: %s", test_command)
logging.info("Output before:" + | random_line_split |
migration.py | import logging
import time
import types
from autotest.client.shared import error
from virttest import utils_misc, utils_test, aexpect
def | (test, params, env):
"""
KVM migration test:
1) Get a live VM and clone it.
2) Verify that the source VM supports migration. If it does, proceed with
the test.
3) Send a migration command to the source VM and wait until it's finished.
4) Kill off the source VM.
3) Log into the d... | run | identifier_name |
migration.py | import logging
import time
import types
from autotest.client.shared import error
from virttest import utils_misc, utils_test, aexpect
def run(test, params, env):
"""
KVM migration test:
1) Get a live VM and clone it.
2) Verify that the source VM supports migration. If it does, proceed with
... |
finally:
# Kill the background process
if session2 and session2.is_alive():
bg_kill_cmd = params.get("migration_bg_kill_command", None)
if bg_kill_cmd is not None:
try:
session2.cmd(bg_kill_cmd)
... | logging.info("Command output before migration differs from "
"command output after migration")
logging.info("Command: %s", test_command)
logging.info("Output before:" +
utils_misc.format_str_for_message(reference_output))
... | conditional_block |
ex2.py | # A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print "I could have code like this." # and the comment after is ignored
| # You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run."
# Adding another few lines just for fun.
print 'Q: Why does the "#" in "print "Hi # there." not get ignored?'
# print 'The # in that code is inside a string, so it will put into the string until th... | random_line_split | |
core.py | #!/bin/python
'''
Library for formulating and solving game trees as linear programs.
'''
class Node(object):
'''Abstract class to represent a node in the game tree.'''
def solve(self):
'''
Should populate the solutions dictionary.
solutions: TerminalNode ==> list of lists of inequali... |
# functions which maintain CDF form of inequalities
def And(a, b):
output = []
for x in a:
for y in b:
output.append(x+y)
# must be tuple to be able to add together
return tuple(output)
def Or(a, b):
return a+b
def singleton(x):
# must be a list of lists
return ((x,)... | '''
Generator for all pairs of leaves l1, l2 st.
l1 and l2 are in different immediate subtrees.
Also includes these immediate subtrees roots i.e. this nodes
direct children.
So yields: (leftLeaf, rightLeaf, leftChild, rightChild, )
'''
for i in xrange(len(self.... | identifier_body |
core.py | #!/bin/python
'''
Library for formulating and solving game trees as linear programs.
'''
class Node(object):
'''Abstract class to represent a node in the game tree.'''
def solve(self):
'''
Should populate the solutions dictionary.
solutions: TerminalNode ==> list of lists of inequali... | def _gen_children(self):
'''
Generator for all pairs of leaves l1, l2 st.
l1 and l2 are in different immediate subtrees.
Also includes these immediate subtrees roots i.e. this nodes
direct children.
So yields: (leftLeaf, rightLeaf, leftChild, rightChild, )
... | self.solutions[rightLeaf] = Or(self.solutions[rightLeaf], reqRightWins)
| random_line_split |
core.py | #!/bin/python
'''
Library for formulating and solving game trees as linear programs.
'''
class Node(object):
'''Abstract class to represent a node in the game tree.'''
def solve(self):
'''
Should populate the solutions dictionary.
solutions: TerminalNode ==> list of lists of inequali... |
# at least 1 child, so solve all of them
for child in self.children:
child.solve()
for leaf in child.solutions:
self.solutions[leaf] = singleton(False)
# if only one child, there is no choice, so use decision makeing
# criteria of that child
... | return | conditional_block |
core.py | #!/bin/python
'''
Library for formulating and solving game trees as linear programs.
'''
class Node(object):
'''Abstract class to represent a node in the game tree.'''
def solve(self):
'''
Should populate the solutions dictionary.
solutions: TerminalNode ==> list of lists of inequali... | (x):
# must be a list of lists
return ((x,),)
| singleton | identifier_name |
automate_scrape.py | #! /usr/bin/python3
'''
automate_scrape.py - runs throught the online verision of the text book, 'Automate the boring stuff with python' and pulls out all of the projects and stores them in a file.
'''
import requests, os, bs4, sys
def page_download(web_page, chapter_num, no_project_count, no_chapter_projects):
... | '''
web_page = 'https://automatetheboringstuff.com/chapter1/'
page_download(web_page, 1, 0, [])
if __name__ == '__main__':
sys.exit(main()) |
def main():
'''
main | random_line_split |
automate_scrape.py | #! /usr/bin/python3
'''
automate_scrape.py - runs throught the online verision of the text book, 'Automate the boring stuff with python' and pulls out all of the projects and stores them in a file.
'''
import requests, os, bs4, sys
def page_download(web_page, chapter_num, no_project_count, no_chapter_projects):
... |
f.close()
chapter_num += 1
if chapter_num == 19:
print('\n{0} chapters where Practice Projects could not be found'.format(no_project_count))
print('Here is the list of those chapters:\n{0}'.format(no_chapter_projects))
print('='*20 + 'Done' + '='*20 +'\n')
return
... | f.write(el.get_text())
print('Writing text to file') | conditional_block |
automate_scrape.py | #! /usr/bin/python3
'''
automate_scrape.py - runs throught the online verision of the text book, 'Automate the boring stuff with python' and pulls out all of the projects and stores them in a file.
'''
import requests, os, bs4, sys
def page_download(web_page, chapter_num, no_project_count, no_chapter_projects):
... | (downloaded_page, chapter_num, no_project_count, no_chapter_projects):
'''
Takes a downloaded web page and pulls out the practice projects and writes them to a file. It then moves to the next chapter, gets that url. Counts the number of chapters where practice projects could not be found and stores those chapte... | chapter_loop_and_write | identifier_name |
automate_scrape.py | #! /usr/bin/python3
'''
automate_scrape.py - runs throught the online verision of the text book, 'Automate the boring stuff with python' and pulls out all of the projects and stores them in a file.
'''
import requests, os, bs4, sys
def page_download(web_page, chapter_num, no_project_count, no_chapter_projects):
... |
if chapter_num == 19:
print('\n{0} chapters where Practice Projects could not be found'.format(no_project_count))
print('Here is the list of those chapters:\n{0}'.format(no_chapter_projects))
print('='*20 + 'Done' + '='*20 +'\n')
return
next_link = soup.find('a', href='/chapter... | '''
Takes a downloaded web page and pulls out the practice projects and writes them to a file. It then moves to the next chapter, gets that url. Counts the number of chapters where practice projects could not be found and stores those chapters in a list.
'''
soup = downloaded_page
projects = soup.f... | identifier_body |
DouMeanView.js | /**
*
*/ | bodyStyle : 'background:#D8D8D8',
border : 1,
requires : [ 'Healthsurvey.view.searchengine.search.DouMeanController' ],
controller : 'DouMeanController',
initComponent : function() {
this.listeners = {
scope : 'controller',
afterrender : 'onAfterrender',
/*render: function(c){
c.getEl().on('cli... | Ext.define('Healthsurvey.view.searchengine.search.DouMeanView', {
extend : 'Ext.form.Label',
xtype : 'DouMeanView',
//margin : '1 1 1 1', | 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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | include!(concat!(env!("OUT_DIR"), "/gecko_properties.rs"));
}
macro_rules! reexport_computed_values {
( $( { $name: ident, $boxed: expr } )+ ) => {
/// Types for [computed values][computed].
///
/// [computed]: https://drafts.csswg.org/css-cascade/#computed
pub mod computed_valu... | pub mod gecko_properties { | 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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | <W, T>(
dest: &mut CssWriter<W>,
list: &[T],
) -> fmt::Result
where
W: Write,
T: ToCss,
{
if list.is_empty() {
return Ok(());
}
list[0].to_css(dest)?;
for item in list.iter().skip(1) {
dest.write_str(", ")?;
item.to_css(dest)?;
}
Ok(())
}
#[cfg(feature... | serialize_comma_separated_list | 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/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... |
}
| {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
} | identifier_body |
customer-payroll-exists.validator.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... |
if (isString(control.value) && control.value.trim().length === 0) {
return invalid;
}
return customerService.getCustomer(control.value, true)
.switchMap(customer => payrollService.findPayrollConfiguration(customer.identifier, true))
.map(config => null)
.catch(() => invalid);
};... | {
return Observable.of(null);
} | conditional_block |
customer-payroll-exists.validator.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | (customerService: CustomerService, payrollService: PayrollService): AsyncValidatorFn {
return (control: AbstractControl): Observable<any> => {
if (!control.dirty || !control.value || control.value.length === 0) {
return Observable.of(null);
}
if (isString(control.value) && control.value.trim().leng... | customerWithConfigExists | identifier_name |
customer-payroll-exists.validator.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | {
return (control: AbstractControl): Observable<any> => {
if (!control.dirty || !control.value || control.value.length === 0) {
return Observable.of(null);
}
if (isString(control.value) && control.value.trim().length === 0) {
return invalid;
}
return customerService.getCustomer(contr... | identifier_body | |
customer-payroll-exists.validator.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agr... | * limitations under the License.
*/
import {AbstractControl, AsyncValidatorFn} from '@angular/forms';
import {Observable} from 'rxjs/Observable';
import {CustomerService} from '../../../../services/customer/customer.service';
import {isString} from '../../../../common/validator/validators';
import {PayrollService} f... | random_line_split | |
ApplicationSettings.utils.ts | import i18next from 'i18next';
import { FormAppSetting } from '../AppSettings.types';
export const getErrorMessage = (newValue: string, t: i18next.TFunction) => {
try {
const obj = JSON.parse(newValue) as unknown;
if (!(obj instanceof Array)) {
return t('valuesMustBeAnArray');
}
let err = '';
... | return;
}
if (!keys.includes('value')) {
err = t('valueIsRequired');
return;
}
if (typeof setting.value !== 'string') {
err = t('valueMustBeAString');
return;
}
if (typeof setting.name !== 'string') {
err = t('nameMustBeAString');
... | const keys = Object.keys(setting);
if (!keys.includes('name')) {
err = t('nameIsRequired'); | random_line_split |
ApplicationSettings.utils.ts | import i18next from 'i18next';
import { FormAppSetting } from '../AppSettings.types';
export const getErrorMessage = (newValue: string, t: i18next.TFunction) => {
try {
const obj = JSON.parse(newValue) as unknown;
if (!(obj instanceof Array)) {
return t('valuesMustBeAnArray');
}
let err = '';
... |
if (typeof setting.name !== 'string') {
err = t('nameMustBeAString');
return;
}
if (setting.slotSetting && typeof setting.slotSetting !== 'boolean') {
err = t('slotSettingMustBeBoolean');
return;
}
const { name, value, slotSetting, ...improperProperties } =... | {
err = t('valueMustBeAString');
return;
} | conditional_block |
webdriverio-tests.ts | import * as webdriverio from "webdriverio";
import { assert } from "chai";
// Stub mocha functions
const { describe, it, before, after, beforeEach, afterEach } = null as any as {
[s: string]: ((s: string, cb: (done: any) => void) => void) & ((cb: (done: any) => void) => void) & { only: any, skip: any };
};
descri... | ) {
// Hooks don't have to return a value
}
};
hooks.onComplete = async () => {
// Hooks can return a promise but the promise can be void
};
hooks.afterTest = async () => {
// Hooks can have a promise with a result but it is not typically used
return false;
};
| nError( | identifier_name |
webdriverio-tests.ts | import * as webdriverio from "webdriverio";
import { assert } from "chai";
// Stub mocha functions
const { describe, it, before, after, beforeEach, afterEach } = null as any as {
[s: string]: ((s: string, cb: (done: any) => void) => void) & ((cb: (done: any) => void) => void) & { only: any, skip: any };
};
descri... | };
hooks.onComplete = async () => {
// Hooks can return a promise but the promise can be void
};
hooks.afterTest = async () => {
// Hooks can have a promise with a result but it is not typically used
return false;
};
|
// Hooks don't have to return a value
}
| identifier_body |
webdriverio-tests.ts | import * as webdriverio from "webdriverio";
import { assert } from "chai";
// Stub mocha functions
const { describe, it, before, after, beforeEach, afterEach } = null as any as {
[s: string]: ((s: string, cb: (done: any) => void) => void) & ((cb: (done: any) => void) => void) & { only: any, skip: any };
};
| await client.init();
});
it("should have the right title - the good old callback way", () => {
assert.equal(
browser
.url("/")
.getTitle(),
"WebdriverIO - Selenium 2.0 javascript bindings for nodejs"
);
});
it("should have... | describe("my webdriverio tests", () => {
let client: webdriverio.Client<void>;
before(async () => {
client = webdriverio.remote({ deprecationWarnings: true, desiredCapabilities: { browserName: "phantomjs" } }); | random_line_split |
createuser.py | # 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/.
"""
Create a user.
"""
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
... |
user = User.objects.create(username=username, email=email)
user.set_password(password)
user.save()
self.stdout.write("User {} created.".format(username))
| self.stdout.write("User {} already exists.".format(username))
return | conditional_block |
createuser.py | # 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/.
"""
Create a user.
"""
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
... | username = options["username"]
password = options["password"]
email = options["email"]
if User.objects.filter(username=username).exists():
self.stdout.write("User {} already exists.".format(username))
return
user = User.objects.create(username=username, email=em... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.