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 |
|---|---|---|---|---|
markerclusterer.ts | /**
* Copyright 2021 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 agreed to... | (): void {
this.markers.forEach((marker) => marker.setMap(null));
this.clusters.forEach((cluster) => cluster.delete());
this.clusters = [];
}
protected renderClusters(): void {
// generate stats to pass to renderers
const stats = new ClusterStats(this.markers, this.clusters);
const map = th... | reset | identifier_name |
markerclusterer.ts | /**
* Copyright 2021 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 agreed to... |
}
/**
* Recalculates and draws all the marker clusters.
*/
public render(): void {
const map = this.getMap();
if (map instanceof google.maps.Map && this.getProjection()) {
google.maps.event.trigger(
this,
MarkerClustererEvents.CLUSTERING_BEGIN,
this
);
con... | {
this.render();
} | conditional_block |
markerclusterer.ts | /**
* Copyright 2021 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 agreed to... | renderer = new DefaultRenderer(),
onClusterClick = defaultOnClusterClickHandler,
}: MarkerClustererOptions) {
super();
this.markers = [...markers];
this.clusters = [];
this.algorithm = algorithm;
this.renderer = renderer;
this.onClusterClick = onClusterClick;
if (map) {
th... | map,
markers = [],
algorithm = new SuperClusterAlgorithm({}), | random_line_split |
markerclusterer.ts | /**
* Copyright 2021 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 agreed to... |
public addMarkers(markers: google.maps.Marker[], noDraw?: boolean): void {
markers.forEach((marker) => {
this.addMarker(marker, true);
});
if (!noDraw) {
this.render();
}
}
public removeMarker(marker: google.maps.Marker, noDraw?: boolean): boolean {
const index = this.markers.i... | {
if (this.markers.includes(marker)) {
return;
}
this.markers.push(marker);
if (!noDraw) {
this.render();
}
} | identifier_body |
ShadowBladesUptime.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import { SpellIcon } from 'interface';
import { formatPercentage } from 'common/format';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY'; | import Analyzer from 'parser/core/Analyzer';
import Enemies from 'parser/shared/modules/Enemies';
import BoringValueText from 'parser/ui/BoringValueText';
class ShadowBladesUptime extends Analyzer {
static dependencies = {
enemies: Enemies,
};
protected enemies!: Enemies;
statistic() {
const shadowB... | random_line_split | |
ShadowBladesUptime.tsx | import React from 'react';
import SPELLS from 'common/SPELLS';
import { SpellIcon } from 'interface';
import { formatPercentage } from 'common/format';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import Analyzer from 'parser/core/Analyzer';
import Enemie... | () {
const shadowBladesUptime = this.selectedCombatant.getBuffUptime(SPELLS.SHADOW_BLADES.id) / this.owner.fightDuration;
return (
<Statistic
size="flexible"
category={STATISTIC_CATEGORY.GENERAL}
>
<BoringValueText label={<><SpellIcon id={SPELLS.SHADOW_BLADES.id} /> Shadow Bl... | statistic | identifier_name |
solution.rs | use std::collections::HashMap;
// #[derive(Debug)]
// struct Solution {}
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
let mut sum: i32 = 0;
let table: HashMap<char, i32> = [
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100)... | // println!("{}", Solution::roman_to_int(String::from("MCMXCIV")));
// println!("{}", Solution::roman_to_int(String::from("MCDLXXVI")));
// } | random_line_split | |
solution.rs | use std::collections::HashMap;
// #[derive(Debug)]
// struct Solution {}
impl Solution {
pub fn roman_to_int(s: String) -> i32 {
let mut sum: i32 = 0;
let table: HashMap<char, i32> = [
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100)... |
// println!("{:?}", c);
}
return sum;
}
}
// fn main() {
// println!("{}", Solution::roman_to_int(String::from("IV")));
// println!("{}", Solution::roman_to_int(String::from("IX")));
// println!("{}", Solution::roman_to_int(String::from("VII")));
// println!("{}", Solu... | {
sum -= cv;
} | conditional_block |
solution.rs | use std::collections::HashMap;
// #[derive(Debug)]
// struct Solution {}
impl Solution {
pub fn roman_to_int(s: String) -> i32 | // println!("{:?}", c);
}
return sum;
}
}
// fn main() {
// println!("{}", Solution::roman_to_int(String::from("IV")));
// println!("{}", Solution::roman_to_int(String::from("IX")));
// println!("{}", Solution::roman_to_int(String::from("VII")));
// println!("{}", Solu... | {
let mut sum: i32 = 0;
let table: HashMap<char, i32> = [
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100),
('D', 500),
('M', 1000),
(' ', 0)]
.iter().cloned().collect();
for (c, n) in... | identifier_body |
solution.rs | use std::collections::HashMap;
// #[derive(Debug)]
// struct Solution {}
impl Solution {
pub fn | (s: String) -> i32 {
let mut sum: i32 = 0;
let table: HashMap<char, i32> = [
('I', 1),
('V', 5),
('X', 10),
('L', 50),
('C', 100),
('D', 500),
('M', 1000),
(' ', 0)]
.iter().cloned().collect();
... | roman_to_int | identifier_name |
utils.rs | use std::borrow::Cow;
use std::process;
use shellexpand;
use errors::*;
pub fn run(args: &Vec<String>) -> Result<process::ExitStatus> { |
let exit_status = process::Command::new(&args[0]).args(&args[1..]).status()?;
if !exit_status.success() {
bail!("command ended with {}", exit_status);
}
Ok(exit_status)
}
pub fn expanded_vec(v: &Vec<String>) -> Result<Vec<Cow<str>>> {
v.iter().map(|x| expanded(x)).collect()
}
pub fn exp... | let args: Vec<String> = expanded_vec(args)?
.into_iter()
.map(|x| x.into_owned())
.collect(); | random_line_split |
utils.rs | use std::borrow::Cow;
use std::process;
use shellexpand;
use errors::*;
pub fn run(args: &Vec<String>) -> Result<process::ExitStatus> {
let args: Vec<String> = expanded_vec(args)?
.into_iter()
.map(|x| x.into_owned())
.collect();
let exit_status = process::Command::new(&args[0]).args... |
Ok(exit_status)
}
pub fn expanded_vec(v: &Vec<String>) -> Result<Vec<Cow<str>>> {
v.iter().map(|x| expanded(x)).collect()
}
pub fn expanded<'a>(s: &'a str) -> Result<Cow<'a, str>> {
shellexpand::full(s).chain_err(|| {
format!("cannot perform tilde or envvar expansion on {}", s)
})
}
| {
bail!("command ended with {}", exit_status);
} | conditional_block |
utils.rs | use std::borrow::Cow;
use std::process;
use shellexpand;
use errors::*;
pub fn run(args: &Vec<String>) -> Result<process::ExitStatus> {
let args: Vec<String> = expanded_vec(args)?
.into_iter()
.map(|x| x.into_owned())
.collect();
let exit_status = process::Command::new(&args[0]).args... | {
shellexpand::full(s).chain_err(|| {
format!("cannot perform tilde or envvar expansion on {}", s)
})
} | identifier_body | |
utils.rs | use std::borrow::Cow;
use std::process;
use shellexpand;
use errors::*;
pub fn | (args: &Vec<String>) -> Result<process::ExitStatus> {
let args: Vec<String> = expanded_vec(args)?
.into_iter()
.map(|x| x.into_owned())
.collect();
let exit_status = process::Command::new(&args[0]).args(&args[1..]).status()?;
if !exit_status.success() {
bail!("command ended... | run | identifier_name |
main.js | (function($) {
//Mobile Dropdown Navigation
$('#menu-main-navigation').tinyNav({header: 'Navigation'});
//End
//Home-Page Boxes Ordering
$('.cell--bk-widget').insertAfter('.cell--square:eq(3)');
$('.cell--promo-bkg').insertAfter('.cell--square:eq(4)');
$('.cell--square').not(':firs... | () {
var formUrl = document.getElementById('form-url').value;
var checkInVal = document.getElementById('start_hidden').value;
var checkOutVal = document.getElementById('end_hidden').value;
var guestsVal = document.getElementsByName('guests')[0].value;
var areaVal = document.g... | bookOnlineUrl | identifier_name |
main.js | (function($) {
//Mobile Dropdown Navigation
$('#menu-main-navigation').tinyNav({header: 'Navigation'});
//End
//Home-Page Boxes Ordering
$('.cell--bk-widget').insertAfter('.cell--square:eq(3)');
$('.cell--promo-bkg').insertAfter('.cell--square:eq(4)');
$('.cell--square').not(':firs... | return false;
}
//End
//Newsletter Validation
function validate_signup(frm) {
var emailAddress = frm.Email.value;
var errorString = '';
if (emailAddress === '' || emailAddress.indexOf('@') == -1) {
errorString = 'Please enter your email address';
}
var els = frm.getElementsByTagName('input');... | {
var formUrl = document.getElementById('form-url').value;
var checkInVal = document.getElementById('start_hidden').value;
var checkOutVal = document.getElementById('end_hidden').value;
var guestsVal = document.getElementsByName('guests')[0].value;
var areaVal = document.getE... | identifier_body |
main.js | (function($) {
//Mobile Dropdown Navigation
$('#menu-main-navigation').tinyNav({header: 'Navigation'});
//End
//Home-Page Boxes Ordering
$('.cell--bk-widget').insertAfter('.cell--square:eq(3)');
$('.cell--promo-bkg').insertAfter('.cell--square:eq(4)');
$('.cell--square').not(':firs... |
// Our Places - Side Widget
$('.widget').on('click touch', '#our-places-btn', function() {
$('.widget').toggleClass('is-open');
});
//End
// Single Room Slider
$('.flexslider').flexslider({
animation: "slide",
initDelay: 1000
});
//End
// Gallery Pages
$('#galler... |
$('.cell__square-banner:eq(0), .cell__square-banner:eq(1)').css('margin-top', '3em');
//End | random_line_split |
main.js | (function($) {
//Mobile Dropdown Navigation
$('#menu-main-navigation').tinyNav({header: 'Navigation'});
//End
//Home-Page Boxes Ordering
$('.cell--bk-widget').insertAfter('.cell--square:eq(3)');
$('.cell--promo-bkg').insertAfter('.cell--square:eq(4)');
$('.cell--square').not(':firs... |
}
//End | {
imgs[0].src = imgs[0].src.slice(0, -3) + 'png';
} | conditional_block |
setup.py | #!/usr/bin/env python
# -*- coding:utf8 -*-
from setuptools import setup
import picuplib
setup(
name = 'picuplib',
packages = ['picuplib'],
version = picuplib.__version__,
description = 'Picflash upload library',
author = 'Arvedui', | 'Development Status :: 4 - Beta',
'Topic :: Software Development :: Libraries',
'Intended Audience :: Developers',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'License... | author_email = 'arvedui@posteo.de',
url = 'https://github.com/Arvedui/picuplib',
install_requires=['requests', 'requests-toolbelt'],
classifiers=[ | random_line_split |
GOBot.py | :
:type item_wdid:
"""
statements = []
for go_id, sub_df in this_go.groupby(level=0):
aspect = set(sub_df.index.get_level_values("aspect"))
assert len(aspect) == 1
aspect = list(aspect)[0]
level_wdid = go_props[aspect]
go_wdid = go_map[go_id]
statement =... | get_all_taxa | identifier_name | |
GOBot.py | is_reference=True))
else:
raise ValueError("curator not found: {}".format(curator))
# reference URL
# ref_url = "http://www.ebi.ac.uk/QuickGO/GAnnotation?protein={}".format(uniprot_id)
ref_url = "http://www.ebi.ac.uk/QuickGO/annotations?geneProductId=UniProtKB:... | reference = [wdi_core.WDTime(retrieved.strftime('+%Y-%m-%dT00:00:00Z'), prop_nr='P813', is_reference=True)]
# stated in pmid
if pmid:
if pmid in pmid_map:
reference.append(wdi_core.WDItemID(pmid_map[pmid], 'P248', is_reference=True))
else:
raise ValueError("article item ... | identifier_body | |
GOBot.py | raise ValueError("article item for pmid {} not found. skipping item".format(pmid))
# stated in uniprot-GOA Q28018111
reference.append(wdi_core.WDItemID('Q28018111', 'P248', is_reference=True))
# curator
if curator in curators_wdids:
reference.append(wdi_core.WDItemID(curators_wdids[curator], ... | # get all uniprot id -> wdid mappings, where found in taxon is this organism
prot_wdid_mapping = wdi_helpers.id_mapper(UNIPROT, (("P703", organism_wdid),))
# get all goID to wdid mappings
go_map = wdi_helpers.id_mapper("P686")
# Get GO terms from our local store for this taxon
colnames = ['db'... | if not organism_wdid:
raise ValueError("organism {} not found".format(taxon))
print("Running organism: {} {}".format(taxon, organism_wdid))
| random_line_split |
GOBot.py | .startswith("PMID:")])
if pmids:
for pmid in pmids:
reference = make_go_ref(curator, pmid_map, external_id, uniprot_id, evidence_wdid, retrieved,
pmid=pmid)
statement.references.append(ref... | raise ValueError("taxon is required") | conditional_block | |
Subject.d.ts | import { Operator } from './Operator'; | import { Observable } from './Observable';
import { Subscriber } from './Subscriber';
import { Subscription } from './Subscription';
export declare class Subject<T> extends Observable<T> implements Observer<T>, Subscription<T> {
_subscriptions: Subscription<T>[];
_unsubscribe: () => void;
static create<T>(s... | import { Observer } from './Observer'; | random_line_split |
Subject.d.ts | import { Operator } from './Operator';
import { Observer } from './Observer';
import { Observable } from './Observable';
import { Subscriber } from './Subscriber';
import { Subscription } from './Subscription';
export declare class | <T> extends Observable<T> implements Observer<T>, Subscription<T> {
_subscriptions: Subscription<T>[];
_unsubscribe: () => void;
static create<T>(source: Observable<T>, destination: Observer<T>): Subject<T>;
protected destination: Observer<T>;
observers: Observer<T>[];
isUnsubscribed: boolean;
... | Subject | identifier_name |
border.utils.ts | /*
* Copyright 2021 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to ... | };
export const resetBorder = (settingEdge: boolean): IStyleDeclaration => {
return settingEdge
? {
border: null,
}
: {
border: null,
borderTop: null,
borderRight: null,
borderBottom: null,
borderLeft: null,
};
}; | const { border, borderTop, borderRight, borderBottom, borderLeft } = style;
return !!(border || borderTop || borderRight || borderBottom || borderLeft); | random_line_split |
test_antelope_v1_client.py | import unittest
from antelope_catalog.data_sources.local import TEST_ROOT
from antelope_catalog import LcCatalog
from lcatools.interfaces import IndexRequired
cat = LcCatalog(TEST_ROOT)
ref = 'calrecycle.antelope'
cat.new_resource(ref, 'http://www.antelope-lca.net/uo-lca/api/', 'AntelopeV1Client',
... | (self):
with self.assertRaises(IndexRequired):
next(cat.query(ref).terminate('flows/87'))
def test_traversal(self):
ffs = cat.query(ref).get('fragments/47').traverse()
self.assertEqual(len(ffs), 14)
self.assertSetEqual({-0.5, -0.01163, -0.0102, 0.0, 0.5}, set(round(x.nod... | test_nonimpl | identifier_name |
test_antelope_v1_client.py | import unittest
from antelope_catalog.data_sources.local import TEST_ROOT
from antelope_catalog import LcCatalog
from lcatools.interfaces import IndexRequired
cat = LcCatalog(TEST_ROOT)
ref = 'calrecycle.antelope'
cat.new_resource(ref, 'http://www.antelope-lca.net/uo-lca/api/', 'AntelopeV1Client',
... |
if __name__ == '__main__':
unittest.main() | {0.0004522897, 0.0000733389, 0.0000419222, 0.0001582613})
self.assertAlmostEqual(lcia.total(), 0.0007258121306, places=12)
| random_line_split |
test_antelope_v1_client.py | import unittest
from antelope_catalog.data_sources.local import TEST_ROOT
from antelope_catalog import LcCatalog
from lcatools.interfaces import IndexRequired
cat = LcCatalog(TEST_ROOT)
ref = 'calrecycle.antelope'
cat.new_resource(ref, 'http://www.antelope-lca.net/uo-lca/api/', 'AntelopeV1Client',
... | unittest.main() | conditional_block | |
test_antelope_v1_client.py | import unittest
from antelope_catalog.data_sources.local import TEST_ROOT
from antelope_catalog import LcCatalog
from lcatools.interfaces import IndexRequired
cat = LcCatalog(TEST_ROOT)
ref = 'calrecycle.antelope'
cat.new_resource(ref, 'http://www.antelope-lca.net/uo-lca/api/', 'AntelopeV1Client',
... |
def test_stagename(self):
inv = ar.make_interface('inventory')
self.assertEqual(inv.get_stage_name('42'), 'Natural Gas')
self.assertEqual(inv.get_stage_name('47'), 'Natural Gas Supply')
self.assertEqual(inv.get_stage_name('81'), 'WWTP')
def test_impactcategory(self):
s... | self.assertEqual(len(ar.get_endpoint('stages')), 87) | identifier_body |
icon_content.py | '''
Created on August 19, 2013
@package: livedesk-sync
@copyright: 2013 Sourcefabric o.p.s.
@license: http://www.gnu.org/licenses/gpl-3.0.txt
@author: Martin Saturka
Content for icons of collaborators of chained blogs.
'''
import socket
import logging
from urllib.request import urlopen
from ally.api.model import Con... | def read(self, nbytes=None):
'''
@see: Content.read
'''
if not self._response:
try:
req = Request(self._url, headers={'User-Agent' : 'Magic Browser'})
self._response = urlopen(req)
except (HTTPError, socket.error) as e:
... |
self._url = contentURL
self._response = None
| random_line_split |
icon_content.py | '''
Created on August 19, 2013
@package: livedesk-sync
@copyright: 2013 Sourcefabric o.p.s.
@license: http://www.gnu.org/licenses/gpl-3.0.txt
@author: Martin Saturka
Content for icons of collaborators of chained blogs.
'''
import socket
import logging
from urllib.request import urlopen
from ally.api.model import Con... | (self, nbytes=None):
'''
@see: Content.read
'''
if not self._response:
try:
req = Request(self._url, headers={'User-Agent' : 'Magic Browser'})
self._response = urlopen(req)
except (HTTPError, socket.error) as e:
log... | read | identifier_name |
icon_content.py | '''
Created on August 19, 2013
@package: livedesk-sync
@copyright: 2013 Sourcefabric o.p.s.
@license: http://www.gnu.org/licenses/gpl-3.0.txt
@author: Martin Saturka
Content for icons of collaborators of chained blogs.
'''
import socket
import logging
from urllib.request import urlopen
from ally.api.model import Con... |
parsed = SplitResult(scheme, netloc, quote(path), quote(query), fragment)
if isinstance(contentURL, Request): contentURL.full_url = urlunsplit(parsed)
else: contentURL = urlunsplit(parsed)
self._url = contentURL
self._response = None
def read(self, nbytes=None):
''... | scheme = 'http' | conditional_block |
icon_content.py | '''
Created on August 19, 2013
@package: livedesk-sync
@copyright: 2013 Sourcefabric o.p.s.
@license: http://www.gnu.org/licenses/gpl-3.0.txt
@author: Martin Saturka
Content for icons of collaborators of chained blogs.
'''
import socket
import logging
from urllib.request import urlopen
from ally.api.model import Con... | if not self.length:
self.length = 0
if (not self._response) or self._response.closed:
return ''
try:
if nbytes:
return self._response.read(nbytes)
return self._response.read()
except (HTTPError, socket.error) as e:... | '''
@see: Content.read
'''
if not self._response:
try:
req = Request(self._url, headers={'User-Agent' : 'Magic Browser'})
self._response = urlopen(req)
except (HTTPError, socket.error) as e:
log.error('Can not read icon ima... | identifier_body |
app.module.ts | import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { ReleveHomeComponent} from './components/releveHome/releve.home.component';
import { EmptyComponent } from './components/empty/empty.component';
import { Rel... |
@NgModule({
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
,
NgbModule.forRoot()
],
declarations: [ EmptyComponent, ReleveHomeComponent, ReleveListComponent, ReleveCompteurListComponent, AddReleveComponent ]
})
export class RelevesModule {
} | import { AppRoutingModule } from './app.routes';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; | random_line_split |
app.module.ts | import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { ReleveHomeComponent} from './components/releveHome/releve.home.component';
import { EmptyComponent } from './components/empty/empty.component';
import { Rel... | {
}
| RelevesModule | identifier_name |
main.rs | #![feature(box_syntax)]
#![feature(asm)]
extern crate e2d2;
extern crate fnv;
extern crate time;
extern crate rand;
use e2d2::scheduler::*;
pub struct DepTask {
id: String,
deps: Vec<usize>,
}
impl Executable for DepTask {
fn execute(&mut self) {
println!("Task -- {}", self.id);
}
fn depen... | impl DepTask {
pub fn new(parent: usize, id: &str) -> DepTask {
DepTask {
id: String::from(id),
deps: vec![parent],
}
}
}
fn test_func(id: &str) {
println!("Base Task -- {}", id);
}
fn main() {
let mut sched = embedded_scheduler::EmbeddedScheduler::new();
le... | self.deps.clone()
}
} | random_line_split |
main.rs | #![feature(box_syntax)]
#![feature(asm)]
extern crate e2d2;
extern crate fnv;
extern crate time;
extern crate rand;
use e2d2::scheduler::*;
pub struct DepTask {
id: String,
deps: Vec<usize>,
}
impl Executable for DepTask {
fn execute(&mut self) {
println!("Task -- {}", self.id);
}
fn depen... | (id: &str) {
println!("Base Task -- {}", id);
}
fn main() {
let mut sched = embedded_scheduler::EmbeddedScheduler::new();
let handle0 = sched.add_task(|| test_func("task-0")).unwrap();
let other_handles = {
let mut prev_handle = handle0;
let mut nhandles: Vec<_> = (0..10).map(|_| 0).col... | test_func | identifier_name |
TcpDispatcher.py | import socket
import asyncore
import pickle
from minissl.AbstractConnection import AbstractConnection
class PickleStreamWrapper(asyncore.dispatcher_with_send, AbstractConnection):
"""Buffers a stream until it contains valid data serialized by pickle.
That is a big of an ugly glue code I had to come up with i... | (self):
"""Handle TCP accepts.
In this case if it is a valid accept a separate handler will be launched
that takes care of the rest of the messages being exchanged of the new
accepted connection.
"""
pair = self.accept()
if pair is not None:
sock, add... | handle_accept | identifier_name |
TcpDispatcher.py | import socket
import asyncore
import pickle
from minissl.AbstractConnection import AbstractConnection
class PickleStreamWrapper(asyncore.dispatcher_with_send, AbstractConnection):
"""Buffers a stream until it contains valid data serialized by pickle.
That is a big of an ugly glue code I had to come up with i... | if pair is not None:
sock, addr = pair
print 'Incoming connection from %s' % repr(addr)
wrapper = PickleStreamWrapper(sock)
wrapper.set_receive_handler(self.receive_callback) | accepted connection.
"""
pair = self.accept() | random_line_split |
TcpDispatcher.py | import socket
import asyncore
import pickle
from minissl.AbstractConnection import AbstractConnection
class PickleStreamWrapper(asyncore.dispatcher_with_send, AbstractConnection):
"""Buffers a stream until it contains valid data serialized by pickle.
That is a big of an ugly glue code I had to come up with i... | sock, addr = pair
print 'Incoming connection from %s' % repr(addr)
wrapper = PickleStreamWrapper(sock)
wrapper.set_receive_handler(self.receive_callback) | conditional_block | |
TcpDispatcher.py | import socket
import asyncore
import pickle
from minissl.AbstractConnection import AbstractConnection
class PickleStreamWrapper(asyncore.dispatcher_with_send, AbstractConnection):
"""Buffers a stream until it contains valid data serialized by pickle.
That is a big of an ugly glue code I had to come up with i... |
def handle_read(self):
new_data = self.recv(1024)
self.rx_buffer += new_data
try:
# try to load the buffer to see if we have something that pickle
# understands. If it worked out send the data upstream, if not do
# nothing and wait for the rest of the da... | """Creates a new PickleStream Wrapper for the underlying socket.
:param sock:
The underlying base socket
"""
asyncore.dispatcher_with_send.__init__(self, sock)
AbstractConnection.__init__(self)
self.rx_buffer = ''
self.tx_buffer = '' | identifier_body |
calculator.rs | pub fn num_words(words: &Vec<&str>) -> f32 {
let num_words;
num_words = words.len() as f32;
return num_words as f32;
}
pub fn word_mean(words: &Vec<&str>) -> f32 {
let word_mean: f32;
let mut word_length_total = 0;
let word_total = num_words(words) as f32;
for word in words {
word_length_tota... |
return (num_and, num_but, num_however, num_if, num_that, num_more, num_must, num_might, num_this, num_very);
} | } | random_line_split |
calculator.rs | pub fn num_words(words: &Vec<&str>) -> f32 {
let num_words;
num_words = words.len() as f32;
return num_words as f32;
}
pub fn word_mean(words: &Vec<&str>) -> f32 {
let word_mean: f32;
let mut word_length_total = 0;
let word_total = num_words(words) as f32;
for word in words {
word_length_tota... |
pub fn word_freq(words: &Vec<&str>) -> (i32, i32, i32, i32, i32, i32, i32, i32, i32, i32) {
let mut num_and = 0;
let mut num_but = 0;
let mut num_however = 0;
let mut num_if = 0;
let mut num_that = 0;
let mut num_more = 0;
let mut num_must = 0;
let mut num_might = 0;
let mut num_this = 0;
let mut num_very =... | {
let sent_mean: f32;
let sent_total;
sent_total = sentences.len() as f32;
let total_sent = sent_total as f32;
sent_mean = word_total / total_sent;
return sent_mean;
} | identifier_body |
calculator.rs | pub fn num_words(words: &Vec<&str>) -> f32 {
let num_words;
num_words = words.len() as f32;
return num_words as f32;
}
pub fn word_mean(words: &Vec<&str>) -> f32 {
let word_mean: f32;
let mut word_length_total = 0;
let word_total = num_words(words) as f32;
for word in words {
word_length_tota... | (word_total: &f32, sentences: &Vec<&str>) -> f32 {
let sent_mean: f32;
let sent_total;
sent_total = sentences.len() as f32;
let total_sent = sent_total as f32;
sent_mean = word_total / total_sent;
return sent_mean;
}
pub fn word_freq(words: &Vec<&str>) -> (i32, i32, i32, i32, i32, i32, i32, i32, i32, i32) {
... | sent_mean | identifier_name |
server.rs |
use common::err;
pub struct Server {
pub name: String,
cipher: Cipher,
suffix: Vec<u8>,
network: &Network
}
impl Server {
fn new(name: &str, cipher: &Cipher) -> Self {
Server {
name: name
}
}
fn set_suffix(&mut ... | (&self, method: &str, data: &Vec<u8>) -> Response {
match method {
"suffix" => self.suffix(&data),
"profile_for" => self.profile_for(&data),
_ => err
}
}
}
| receive | identifier_name |
server.rs |
use common::err;
pub struct Server {
pub name: String,
cipher: Cipher,
suffix: Vec<u8>,
network: &Network
}
impl Server {
fn new(name: &str, cipher: &Cipher) -> Self {
Server {
name: name
}
}
fn set_suffix(&mut ... |
fn suffix(&self, data: &Vec<u8>) -> Response {
let mut final_data = data.clone();
final_data.extend(&self.suffix);
let cipherdata = ertry!(self.cipher.encrypt(&final_data));
let conn = self.network.connect(&self.name, "server2");
conn.send(&cipherdata)
}
}
impl R... | {
let email_str = ertry!(ascii::raw_to_str(&email));
let user = User::new(&email, 10, "user");
let encoded = ertry!(user.encode());
let enc_raw = ertry!(ascii::str_to_raw(&encoded));
ertry!(self.cipher.encrypt(&enc_raw))
} | identifier_body |
server.rs | use common::err;
pub struct Server {
pub name: String,
cipher: Cipher,
suffix: Vec<u8>,
network: &Network
}
impl Server {
fn new(name: &str, cipher: &Cipher) -> Self {
Server {
name: name
} |
fn set_suffix(&mut self, data: &Vec<u8>) {
self.suffix = data.clone();
}
fn profile_for(&self, email: &Vec<u8>) -> Response {
let email_str = ertry!(ascii::raw_to_str(&email));
let user = User::new(&email, 10, "user");
let encoded = ertry!(user.encode());
let enc_r... | } | random_line_split |
plot_somas.py | #!/usr/bin/env python
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the fol... |
if __name__ == '__main__':
# define set of files containing relevant morphs
file_nms = [Path(SWC_PATH, file_nm) for file_nm in ['Soma_origin.swc',
'Soma_translated_1.swc',
'Soma_tr... | """Plot set of somas on same figure as spheres, each with different color."""
_, ax = matplotlib_utils.get_figure(new_fig=True, subplot=111,
params={'projection': '3d', 'aspect': 'equal'})
for s in somas:
matplotlib_utils.plot_sphere(ax, s.center, s.radius, color=... | identifier_body |
plot_somas.py | #!/usr/bin/env python
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the fol... |
plt.show()
if __name__ == '__main__':
# define set of files containing relevant morphs
file_nms = [Path(SWC_PATH, file_nm) for file_nm in ['Soma_origin.swc',
'Soma_translated_1.swc',
... | matplotlib_utils.plot_sphere(ax, s.center, s.radius, color=random_color(), alpha=1) | conditional_block |
plot_somas.py | #!/usr/bin/env python
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the fol... | ():
"""Random color generation."""
return np.random.rand(3, 1)
def plot_somas(somas):
"""Plot set of somas on same figure as spheres, each with different color."""
_, ax = matplotlib_utils.get_figure(new_fig=True, subplot=111,
params={'projection': '3d', 'aspect... | random_color | identifier_name |
plot_somas.py | #!/usr/bin/env python
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project | # Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in ... | # All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
# | random_line_split |
cbicqc_incoming.py | #!/usr/bin/env python3
"""
Rename and organize Horos QC exported data in <BIDS Root>/incoming and place in <BIDS Root>/sourcedata
AUTHOR
----
Mike Tyszka, Ph.D.
MIT License
Copyright (c) 2019 Mike Tyszka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated doc... |
if ds:
acq_date = ds.AcquisitionDate
else:
print('* DICOM header problem - returning %s' % acq_date)
return acq_date
if 'main' in __name__:
main() | """
Extract acquisition date from DICOM header
:param dcm_fname: DICOM filename
:return acq_date: str, acquisition date (YYYYMMDD)
"""
# Default return date
acq_date = '19010101'
if not os.path.isfile(dcm_fname):
print('* File not found - %s' % dcm_fname)
try:
ds = pyd... | identifier_body |
cbicqc_incoming.py | #!/usr/bin/env python3
"""
Rename and organize Horos QC exported data in <BIDS Root>/incoming and place in <BIDS Root>/sourcedata
AUTHOR
----
Mike Tyszka, Ph.D.
MIT License
Copyright (c) 2019 Mike Tyszka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated doc... | for inc_qc_dir in glob(os.path.join(incoming_dir, 'Qc*')):
print("")
print(" Processing {}".format(inc_qc_dir))
# There should be only one session subdirectory
dlist = list(glob(os.path.join(inc_qc_dir, '*')))
if len(dlist) > 0:
ses_dir = dlist[0]
... | # Move session subdirectories from Qc_*/<session dir> to Qc/<ScanDate>
print("Scanning for incoming QC studies")
| random_line_split |
cbicqc_incoming.py | #!/usr/bin/env python3
"""
Rename and organize Horos QC exported data in <BIDS Root>/incoming and place in <BIDS Root>/sourcedata
AUTHOR
----
Mike Tyszka, Ph.D.
MIT License
Copyright (c) 2019 Mike Tyszka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated doc... | (dcm_fname):
"""
Extract acquisition date from DICOM header
:param dcm_fname: DICOM filename
:return acq_date: str, acquisition date (YYYYMMDD)
"""
# Default return date
acq_date = '19010101'
if not os.path.isfile(dcm_fname):
print('* File not found - %s' % dcm_fname)
try:... | acquisition_date | identifier_name |
cbicqc_incoming.py | #!/usr/bin/env python3
"""
Rename and organize Horos QC exported data in <BIDS Root>/incoming and place in <BIDS Root>/sourcedata
AUTHOR
----
Mike Tyszka, Ph.D.
MIT License
Copyright (c) 2019 Mike Tyszka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated doc... |
try:
ds = pydicom.read_file(dcm_fname, force=True)
except IOError:
print("* Problem opening %s" % dcm_fname)
raise
except AttributeError:
print("* Problem opening %s" % dcm_fname)
raise
if ds:
acq_date = ds.AcquisitionDate
else:
print('* DIC... | print('* File not found - %s' % dcm_fname) | conditional_block |
Responses.py | # Author: Scott Philip (sp@scottphilip.com)
# Version: 1.2 (25 July 2017)
# Source: https://github.com/scottphilip/caller-lookup/
# Licence: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007)
from CallerLookup.Strings import CallerLookupLabel, CallerLookupKeys
from CallerLookup.Utils.Logs impor... |
if CallerLookupKeys.KEY_NAME in data:
result[CallerLookupLabel.NAME] = data[CallerLookupKeys.KEY_NAME]
result[CallerLookupLabel.RESULT] = CallerLookupLabel.SUCCESS
return result
| result[CallerLookupLabel.ADDRESS] = \
addresses[0][CallerLookupKeys.KEY_ADDRESS] | conditional_block |
Responses.py | # Author: Scott Philip (sp@scottphilip.com)
# Version: 1.2 (25 July 2017)
# Source: https://github.com/scottphilip/caller-lookup/
# Licence: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007)
from CallerLookup.Strings import CallerLookupLabel, CallerLookupKeys
from CallerLookup.Utils.Logs impor... | return result
data = data[CallerLookupKeys.KEY_DATA]
if len(data) == 0:
return result
data = data[0]
if CallerLookupKeys.KEY_SCORE in data:
result[CallerLookupLabel.SCORE] = round(data[CallerLookupKeys.KEY_SCORE] * 100)
if CallerLookupKeys.KEY_ADDRESSES in data:
ad... |
if data is None or CallerLookupKeys.KEY_DATA not in data: | random_line_split |
Responses.py | # Author: Scott Philip (sp@scottphilip.com)
# Version: 1.2 (25 July 2017)
# Source: https://github.com/scottphilip/caller-lookup/
# Licence: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007)
from CallerLookup.Strings import CallerLookupLabel, CallerLookupKeys
from CallerLookup.Utils.Logs impor... | (number, region):
return {CallerLookupLabel.RESULT: CallerLookupLabel.INVALID_NUMBER,
CallerLookupLabel.NUMBER: number,
CallerLookupLabel.REGION: region}
def get_response_error(ex):
result = {CallerLookupLabel.RESULT: CallerLookupLabel.ERROR,
CallerLookupLabel.MESSAGE: fo... | get_response_invalid | identifier_name |
Responses.py | # Author: Scott Philip (sp@scottphilip.com)
# Version: 1.2 (25 July 2017)
# Source: https://github.com/scottphilip/caller-lookup/
# Licence: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007)
from CallerLookup.Strings import CallerLookupLabel, CallerLookupKeys
from CallerLookup.Utils.Logs impor... | addresses[0][CallerLookupKeys.KEY_COUNTRY_CODE].upper()
if CallerLookupKeys.KEY_ADDRESS in addresses[0]:
result[CallerLookupLabel.ADDRESS] = \
addresses[0][CallerLookupKeys.KEY_ADDRESS]
if CallerLookupKeys.KEY_NAME in data:
result[CallerLo... | result = {CallerLookupLabel.RESULT: CallerLookupLabel.UNKNOWN,
CallerLookupLabel.SCORE: 100}
result.update(number_data)
if data is None or CallerLookupKeys.KEY_DATA not in data:
return result
data = data[CallerLookupKeys.KEY_DATA]
if len(data) == 0:
return result
data... | identifier_body |
ResourcesTypeResolverUtil.py | from resource_media_types import *
from ClientFile import ClientFile
from ClientFolder import ClientFolder
from queryResource import ClientQuery
class ResourcesTypeResolverUtil(object):
classes = {}
#classes[ClientAdhocDataView.__name__] = ResourceMediaType.ADHOC_DATA_VIEW_MIME
#classes[ClientAw... |
else:
ret = ResourcesTypeResolverUtil.classes.get(resource.__class__.__name__, None)
return ret | ret = ResourcesTypeResolverUtil.classes.get(resource, resource) | conditional_block |
ResourcesTypeResolverUtil.py | from resource_media_types import *
from ClientFile import ClientFile
from ClientFolder import ClientFolder
from queryResource import ClientQuery
class ResourcesTypeResolverUtil(object):
| #put(ClientVirtualDataSource.class, ResourceMediaType.VIRTUAL_DATA_SOURCE_MIME);
#put(ClientXmlaConnection.class, ResourceMediaType.XMLA_CONNECTION_MIME);
#put(ClientResourceLookup.class, ResourceMediaType.RESOURCE_LOOKUP_MIME);
#put(ClientDashboard.class, ResourceMediaType.DASHBOARD_MIME);
#put(Cli... | classes = {}
#classes[ClientAdhocDataView.__name__] = ResourceMediaType.ADHOC_DATA_VIEW_MIME
#classes[ClientAwsDataSource.__name__] = ResourceMediaType.AWS_DATA_SOURCE_MIME
#classes[ClientBeanDataSource.__name__] = ResourceMediaType.BEAN_DATA_SOURCE_MIME
#classes[ClientCustomDataSource.__name__] =... | identifier_body |
ResourcesTypeResolverUtil.py | from resource_media_types import *
from ClientFile import ClientFile |
classes = {}
#classes[ClientAdhocDataView.__name__] = ResourceMediaType.ADHOC_DATA_VIEW_MIME
#classes[ClientAwsDataSource.__name__] = ResourceMediaType.AWS_DATA_SOURCE_MIME
#classes[ClientBeanDataSource.__name__] = ResourceMediaType.BEAN_DATA_SOURCE_MIME
#classes[ClientCustomDataSource.__... | from ClientFolder import ClientFolder
from queryResource import ClientQuery
class ResourcesTypeResolverUtil(object): | random_line_split |
ResourcesTypeResolverUtil.py | from resource_media_types import *
from ClientFile import ClientFile
from ClientFolder import ClientFolder
from queryResource import ClientQuery
class | (object):
classes = {}
#classes[ClientAdhocDataView.__name__] = ResourceMediaType.ADHOC_DATA_VIEW_MIME
#classes[ClientAwsDataSource.__name__] = ResourceMediaType.AWS_DATA_SOURCE_MIME
#classes[ClientBeanDataSource.__name__] = ResourceMediaType.BEAN_DATA_SOURCE_MIME
#classes[ClientCustomDat... | ResourcesTypeResolverUtil | identifier_name |
autocomplete.ts | Value: '',
// No display since name === value
type: TYPE_CONSTANT,
}));
// Get the text from the cursor back
const cur = cm.getCursor();
const pos = CodeMirror.Pos(cur.line, cur.ch - MAX_HINT_LOOK_BACK);
const previousText = cm.getRange(pos, cur);
// See if we're allowed matching tags, vars, or both... | t matches: CodeMirror.Hint[] = [];
for (const item of completionItems) {
const name = typeof item === 'string' ? item : item.name;
const value = typeof item === 'string' ? '' : item.value ?? '';
const displayName = item.displayName || name;
let defaultFill = '';
if (isConstantCompletionItem(item... | identifier_body | |
autocomplete.ts | setupKeyMap(cm, { completeForce, completeIfAfterTagOrVarOpen });
});
/**
* Function to retrieve the list items
* @param cm
* @param options
* @returns {Promise.<{list: Array, from, to}>}
*/
function hint(cm: CodeMirror.EditorFromTextArea, options: ShowHintOptions) {
// Add type to all things (except constants... | pletionItem(item: C | identifier_name | |
autocomplete.ts | Tag;
const allowMatchingConstants = isInNothing;
// Define fallback segment to match everything or nothing
const fallbackSegment = options.showAllOnNoMatch ? '' : '__will_not_match_anything__';
// See if we're completing a variable name
const nameMatch = previousText.match(NAME_MATCH);
const nameMatchLong =... | turn matches;
}
}
/**
| conditional_block | |
autocomplete.ts | const nameMatchLong = previousText.match(NAME_MATCH_FLEXIBLE);
const nameSegment = nameMatch ? nameMatch[0] : fallbackSegment;
const nameSegmentLong = nameMatchLong ? nameMatchLong[0] : fallbackSegment;
const nameSegmentFull = previousText;
// Actually try to match the list of things
let lowPriorityMatches:... | const escapedString = escapeRegex(find);
const re = new RegExp(escapedString, 'gi');
return text.replace(re, matched => prefix + matched + suffix);
}
| random_line_split | |
lib.rs | ();
let m_int = m.to_int_poly();
let r = TernPoly::rand(params.get_n(),
params.get_n() / 3,
params.get_n() / 3,
&rand_ctx)
.unwrap();
let e = encrypt_poly(m_int.clone(), &r, kp.get_public()... | let max_len = params.max_msg_len();
let plain = ntru::rand::generate(max_len as u16, &rand_ctx).unwrap();
for plain_len in 0..max_len + 1 {
// Test single public key
let encrypted = ntru::encrypt(&plain[..plain_len as usize],
kp.get_public(),
... | {
let rng = RNG_DEFAULT;
let rand_ctx = ntru::rand::init(&rng).unwrap();
let kp = ntru::generate_key_pair(params, &rand_ctx).unwrap();
// Randomly choose the number of public keys for testing ntru::generate_multiple_key_pairs and
// ntru::generate_public
let num_pub_keys: usize = rand::thread_r... | identifier_body |
lib.rs |
}
d
}
fn gen_key_pair(seed: &str, params: &EncParams) -> KeyPair {
let seed_u8 = seed.as_bytes();
let rng = RNG_CTR_DRBG;
let rand_ctx = ntru::rand::init_det(&rng, seed_u8).unwrap();
ntru::generate_key_pair(params, &rand_ctx).unwrap()
}
fn sha1(input: &[u8]) -> [u8; 20] {
let mut hasher ... | {
d.set_coeff(i, -1)
} | conditional_block | |
lib.rs | params.get_n() / 3,
&rand_ctx)
.unwrap();
let m_int = m.to_int_poly();
let r = TernPoly::rand(params.get_n(),
params.get_n() / 3,
params.get_n() / 3,
... | // Encrypt a random message
let m = TernPoly::rand(params.get_n(),
params.get_n() / 3, | random_line_split | |
lib.rs | (seed: &str, params: &EncParams) -> KeyPair {
let seed_u8 = seed.as_bytes();
let rng = RNG_CTR_DRBG;
let rand_ctx = ntru::rand::init_det(&rng, seed_u8).unwrap();
ntru::generate_key_pair(params, &rand_ctx).unwrap()
}
fn sha1(input: &[u8]) -> [u8; 20] {
let mut hasher = Sha1::new();
hasher.input... | gen_key_pair | identifier_name | |
static-method-on-struct-and-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (arg1: int, arg2: int) -> int {
zzz();
arg1 + arg2
}
}
enum Enum {
Variant1 { x: int },
Variant2,
Variant3(f64, int, char),
}
impl Enum {
fn static_method(arg1: int, arg2: f64, arg3: uint) -> int {
zzz();
arg1
}
}
fn main() {
Struct::static_method(1, 2);
... | static_method | identifier_name |
static-method-on-struct-and-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | impl Enum {
fn static_method(arg1: int, arg2: f64, arg3: uint) -> int {
zzz();
arg1
}
}
fn main() {
Struct::static_method(1, 2);
Enum::static_method(-3, 4.5, 5);
}
fn zzz() {()} | Variant3(f64, int, char),
}
| random_line_split |
static-method-on-struct-and-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {()} | identifier_body | |
progParser.py | import xml.etree.ElementTree as ET
import csv
'''
Tara O'Kelly - G00322214,
Graph Theory Assignment,
Third Year, Graph Theory, Software Development.
A program to parse the xml file with data taken from http://timetable.gmit.ie/.
'''
# adapted from https://docs.python.org/3/library/xml.etree.elementtree.html
out = ... | print(d)
tree = ET.parse("prog"+d+".xml")
root = tree.getroot()
for child in root:
count = 0
ss = ""
row = []
s = child.text.split(" ", 3)
# course names that adhered to the common naming convention
if "BA" == s[1] or "BSc" == s[1] or s[1] == "BB" or s... | #dept = ["Centre for the Creative Arts and Media","Dept of Building and Civil Engineering","Dept of Computer Science & Applied Physics","Dept of Culinary Arts","Dept of Electronic and Electrical Engineering","Dept of Heritage and Tourism", "Dept of Life and Physical Sciences", "Dept of Mechanical and Industrial Enginee... | random_line_split |
progParser.py | import xml.etree.ElementTree as ET
import csv
'''
Tara O'Kelly - G00322214,
Graph Theory Assignment,
Third Year, Graph Theory, Software Development.
A program to parse the xml file with data taken from http://timetable.gmit.ie/.
'''
# adapted from https://docs.python.org/3/library/xml.etree.elementtree.html
out = ... |
# courses with no specified name
else:
for subs in s:
if count == 1:
ss += subs
if count > 1:
ss += " " + subs
count += 1
row = [ss, s[0], "Unknown", d]
out.writerow(row)
c +... | row = [s[3], s[0] + s[1], "SPA", d] | conditional_block |
test.ts | import * as path from 'path';
import * as glob from 'glob';
import * as webpack from 'webpack';
import { CliConfig } from '../config';
import { WebpackTestOptions } from '../webpack-test-config';
import { WebpackConfigOptions } from '../webpack-config';
/**
* Enumerate loaders and their dependencies from this file ... | const codeCoverageExclude = CliConfig.fromProject().get('test.codeCoverage.exclude');
let exclude: (string | RegExp)[] = [
/\.(e2e|spec)\.ts$/,
/node_modules/
];
if (codeCoverageExclude) {
codeCoverageExclude.forEach((excludeGlob: string) => {
const excludeFiles = glob
... | const extraPlugins: any[] = [];
if (buildOptions.codeCoverage && CliConfig.fromProject()) { | random_line_split |
test.ts | import * as path from 'path';
import * as glob from 'glob';
import * as webpack from 'webpack';
import { CliConfig } from '../config';
import { WebpackTestOptions } from '../webpack-test-config';
import { WebpackConfigOptions } from '../webpack-config';
/**
* Enumerate loaders and their dependencies from this file ... | });
}
extraRules.push({
test: /\.(js|ts)$/, loader: 'istanbul-instrumenter-loader',
options: { esModules: true },
enforce: 'post',
exclude
});
}
return {
devtool: buildOptions.sourcemaps ? 'inline-source-map' : 'eval',
entry: {
main: path.resolve(projectRoot... | {
const { projectRoot, buildOptions, appConfig } = wco;
const nodeModules = path.resolve(projectRoot, 'node_modules');
const extraRules: any[] = [];
const extraPlugins: any[] = [];
if (buildOptions.codeCoverage && CliConfig.fromProject()) {
const codeCoverageExclude = CliConfig.fromProject().get('test.c... | identifier_body |
test.ts | import * as path from 'path';
import * as glob from 'glob';
import * as webpack from 'webpack';
import { CliConfig } from '../config';
import { WebpackTestOptions } from '../webpack-test-config';
import { WebpackConfigOptions } from '../webpack-config';
/**
* Enumerate loaders and their dependencies from this file ... |
extraRules.push({
test: /\.(js|ts)$/, loader: 'istanbul-instrumenter-loader',
options: { esModules: true },
enforce: 'post',
exclude
});
}
return {
devtool: buildOptions.sourcemaps ? 'inline-source-map' : 'eval',
entry: {
main: path.resolve(projectRoot, appConfig.roo... | {
codeCoverageExclude.forEach((excludeGlob: string) => {
const excludeFiles = glob
.sync(path.join(projectRoot, excludeGlob), { nodir: true })
.map(file => path.normalize(file));
exclude.push(...excludeFiles);
});
} | conditional_block |
test.ts | import * as path from 'path';
import * as glob from 'glob';
import * as webpack from 'webpack';
import { CliConfig } from '../config';
import { WebpackTestOptions } from '../webpack-test-config';
import { WebpackConfigOptions } from '../webpack-config';
/**
* Enumerate loaders and their dependencies from this file ... | (wco: WebpackConfigOptions<WebpackTestOptions>) {
const { projectRoot, buildOptions, appConfig } = wco;
const nodeModules = path.resolve(projectRoot, 'node_modules');
const extraRules: any[] = [];
const extraPlugins: any[] = [];
if (buildOptions.codeCoverage && CliConfig.fromProject()) {
const codeCover... | getTestConfig | identifier_name |
097 Interleaving String.py | """
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
"""
__author__ = 'Danyang'
class Solution(object):
def isInterleave(self, s1, s2, s3):
... | (self, s1, s2, s3):
"""
dfs
Time Limit Exceeded
:param s1:
:param s2:
:param s3:
:return: boolean
"""
if not s3:
return True
letter = s3[0]
if s1 and s1[0] == letter:
if self.isInterleave(s1[1:],... | isInterleave_TLE | identifier_name |
097 Interleaving String.py | """
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
"""
__author__ = 'Danyang'
class Solution(object):
| thus, dp
f[i][j] represents s3[:i+j] comes from s1[:i] and s2[:j]
two possible conditions:
1. s[i+j] = s[i]
2. s[i+j] = s[j]
others are false
f[i][j] = f[i-1][j] if s3[i+j]==s1[i]
= f[i][j-1] if s3[i+j]==s2[j]
= false
... | def isInterleave(self, s1, s2, s3):
"""
dfs
dp
dp[i][j], for s3[:i+j] interleaved by s1[:i], s2[:j]
- d b b c a
- T F F F F F
a T F F F F F
a T T T T T F
b F T T F T F
c F F T T T T
c F F F T F T
notice t... | identifier_body |
097 Interleaving String.py | """
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
"""
__author__ = 'Danyang'
class Solution(object):
def isInterleave(self, s1, s2, s3):
... | if not dp[i][j]:
dp[i][j] = dp[i-1][j] and s3[i+j-1] == s1[i-1]
if not dp[i][j]:
dp[i][j] = dp[i][j-1] and s3[i+j-1] == s2[j-1]
return dp[-1][-1]
def isInterleave_TLE(self, s1, s2, s3):
"""
dfs
Time L... | random_line_split | |
097 Interleaving String.py | """
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
For example,
Given:
s1 = "aabcc",
s2 = "dbbca",
When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.
"""
__author__ = 'Danyang'
class Solution(object):
def isInterleave(self, s1, s2, s3):
... |
return False
if __name__ == "__main__":
assert Solution().isInterleave("aa", "ab", "abaa") == True
assert Solution().isInterleave("aabcc", "dbbca", "aadbbcbcac") == True
assert Solution().isInterleave("aabcc", "dbbca", "aadbbbaccc") == False | if self.isInterleave(s1, s2[1:], s3[1:]):
return True | conditional_block |
protocol.rs | ::io::net::tcp::TcpAcceptor;
use std::collections::{HashSet, HashMap};
use uuid::Uuid;
use stream::{Stream, Response, SockAddr, Callback, BroadcastFrom};
use broadcast::Broadcast;
use result::{GossipResult, GossipError, NotListening};
/// A health represents the current state of the cluster. This will be extremely us... | {
Green,
Yellow,
Red
}
/// An iterator that receives new broadcasts and iterates over them.
pub struct Incoming {
node_tx: Sender<BroadcastFrom>,
tx: Sender<(Broadcast, Stream)>,
rx: Receiver<(Broadcast, Stream)>,
listening: bool
}
impl Incoming {
pub fn new(node_tx: Sender<BroadcastF... | Health | identifier_name |
protocol.rs | ::io::net::tcp::TcpAcceptor;
use std::collections::{HashSet, HashMap};
use uuid::Uuid;
use stream::{Stream, Response, SockAddr, Callback, BroadcastFrom};
use broadcast::Broadcast;
use result::{GossipResult, GossipError, NotListening};
/// A health represents the current state of the cluster. This will be extremely us... |
}
#[cfg(test)]
mod | {
let (tx, rx) = channel();
let incoming = Incoming::new(self.tx.clone(), tx);
self.incoming_tx = Some(rx.recv());
incoming
} | identifier_body |
protocol.rs | , BroadcastFrom};
use broadcast::Broadcast;
use result::{GossipResult, GossipError, NotListening};
/// A health represents the current state of the cluster. This will be extremely useful
/// to ping the health of a cluster and determine the high-level status of it.
///
/// Green = Perfect state.
/// Yellow = Nodes are... | fn empty_member_set() {
let mut node = Node::new();
assert_eq!(node.members.len(), 0);
} | random_line_split | |
protocol.rs | ::io::net::tcp::TcpAcceptor;
use std::collections::{HashSet, HashMap};
use uuid::Uuid;
use stream::{Stream, Response, SockAddr, Callback, BroadcastFrom};
use broadcast::Broadcast;
use result::{GossipResult, GossipError, NotListening};
/// A health represents the current state of the cluster. This will be extremely us... | ,
Err(e) => println!("Error: {}", e)
}
}
}
}
struct ServerTask {
streams: HashMap<Peer, TcpStream>,
acceptor_tx: Sender<Broadcast>,
tx: Sender<TaskMessage>,
rx: Receiver<TaskMessage>
}
impl ServerTask {
pub fn new(host: String, port: u16) -> ServerTask {
... | {
// Handle the joining here...
let stream_send = s.clone();
let server = self.server_tx.clone();
spawn(proc() {
let stream = Stream::new(stream_send);
server.send(StreamMsg(stream.clone()));
... | conditional_block |
views.py | /}results.html')
def simple_search(request, template=None):
"""Elasticsearch-specific simple search view.
This view is for end user searching of the Knowledge Base and
Support Forum. Filtering options are limited to:
* product (`product=firefox`, for example, for only Firefox results)
* document t... |
t = template if request.MOBILE else 'search/form.html'
return cache_control(
render(request, t, {
'advanced': True,
'request': request,
'search_form': search_form}),
settings.SEARCH_CACHE_PERIOD)
# 4. Generate search.
cle... | return HttpResponse(
json.dumps({'error': _('Invalid search data.')}),
content_type=request.CONTENT_TYPE,
status=400) | conditional_block |
views.py | elif doc['model'] == 'questions_question':
summary = _build_es_excerpt(doc)
if not summary:
# We're excerpting only question_content, so if the query matched
# question_title or question_answer_content, then there won't be any
# question_co... | """Takes a paginated search and returns results List
Handles wiki documents, questions and contributor forum posts.
:arg pages: paginated S
:arg is_json: whether or not this is generated results for json output
:returns: list of dicts
"""
results = []
for rank, doc in enumerate(pages, pa... | identifier_body | |
views.py | /}results.html')
def simple_search(request, template=None):
"""Elasticsearch-specific simple search view.
This view is for end user searching of the Knowledge Base and
Support Forum. Filtering options are limited to:
* product (`product=firefox`, for example, for only Firefox results)
* document t... | # Note: num_voted (with a d) is a different field than num_votes
# (with an s). The former is a dropdown and the latter is an
# integer value.
if cleaned['num_voted'] == constants.INTERVAL_BEFORE:
question_f &= | question_f &= F(topic=t)
| random_line_split |
views.py | (resp, cache_period):
"""Inserts cache/expires headers"""
resp['Cache-Control'] = 'max-age=%s' % (cache_period * 60)
resp['Expires'] = (
(datetime.utcnow() + timedelta(minutes=cache_period))
.strftime('%A, %d %B %Y %H:%M:%S GMT'))
return resp
def _es_down_template(request, *args, **kwa... | cache_control | identifier_name | |
models.py | from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from project.database import Base
from project.database import db_session
from sqlalchemy.orm import relationship
from sqlalchemy_utils import EmailType
from flask.ext.babel import lazy_gettext as _
# FIXME: move to extensions
from flask.ext... |
def __repr__(self):
return self.role
class Profile(Base):
__tablename__ = 'profile'
id = Column(Integer, primary_key=True)
username = Column(String(50), unique=True, nullable=False, info={'label': _('username')})
password = Column(String(100), nullable=False, info={'label': _('password')})
group_list = Colu... | super(User_Role, self).__init__(**kwargs) | identifier_body |
models.py | from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from project.database import Base
from project.database import db_session
from sqlalchemy.orm import relationship
from sqlalchemy_utils import EmailType
from flask.ext.babel import lazy_gettext as _
# FIXME: move to extensions
from flask.ext... |
return False
def __unicode__(self):
return self.username
class Log(Base):
'''
table log
'''
__tablename__ = 'log_actions'
id = Column(Integer, primary_key=True)
log_date = Column(String(50), nullable=False, info={'label': _('date')})
log_desc = Column(String(300), info={'label': _('description')})
log_u... | return True | conditional_block |
models.py | from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from project.database import Base
from project.database import db_session
from sqlalchemy.orm import relationship
from sqlalchemy_utils import EmailType
from flask.ext.babel import lazy_gettext as _
# FIXME: move to extensions
from flask.ext... | city = Column(String(50), info={'label': _('city')})
creator = Column(Integer, info={'label': _('creator')})
def __init__(self, **kwargs):
super(Profile, self).__init__(**kwargs)
def __repr__(self):
return self.username
def can(self, roles):
for item in roles:
request_role = Roles.query.filter(Roles.... | lastName = Column(String(50), info={'label': _('last name')})
sex = Column(Boolean, info={'label': _('sex')})
birthday = Column(String(50), info={'label': _('birthday')})
avatar = Column(String(50), info={'label': _('avatar')})
country = Column(String(50), info={'label': _('country')}) | random_line_split |
models.py | from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from project.database import Base
from project.database import db_session
from sqlalchemy.orm import relationship
from sqlalchemy_utils import EmailType
from flask.ext.babel import lazy_gettext as _
# FIXME: move to extensions
from flask.ext... | (self):
return self.username
def can(self, roles):
for item in roles:
request_role = Roles.query.filter(Roles.role_name == item).first()
try:
user_have_role = User_Role.query.filter(
User_Role.role == request_role.id ,
User_Role.user == self.id
).first()
if user_have_role:
ret... | __repr__ | identifier_name |
project.config.ts | import {join} from 'path';
import {SeedConfig} from './seed.config';
import {InjectableDependency} from './seed.config.interfaces';
export class ProjectConfig extends SeedConfig {
PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR, 'tasks', 'project');
constructor() {
super();
// this.APP_TITLE = 'Put... | { src: `${this.ASSETS_SRC}/main.css`, inject: true },
];
}
} |
this.APP_ASSETS = [
// {src: `${this.ASSETS_SRC}/css/toastr.min.css`, inject: true},
// {src: `${this.APP_DEST}/assets/scss/global.css`, inject: true},
{ src: `${this.ASSETS_SRC}/bootstrap-material-design.css`, inject: true, vendor : false}, | random_line_split |
project.config.ts | import {join} from 'path';
import {SeedConfig} from './seed.config';
import {InjectableDependency} from './seed.config.interfaces';
export class | extends SeedConfig {
PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR, 'tasks', 'project');
constructor() {
super();
// this.APP_TITLE = 'Put name of your app here';
let additional_deps: InjectableDependency[] = [
// {src: 'jquery/dist/jquery.min.js', inject: 'libs'},
// {src: 'lodas... | ProjectConfig | identifier_name |
project.config.ts | import {join} from 'path';
import {SeedConfig} from './seed.config';
import {InjectableDependency} from './seed.config.interfaces';
export class ProjectConfig extends SeedConfig {
PROJECT_TASKS_DIR = join(process.cwd(), this.TOOLS_DIR, 'tasks', 'project');
constructor() |
}
| {
super();
// this.APP_TITLE = 'Put name of your app here';
let additional_deps: InjectableDependency[] = [
// {src: 'jquery/dist/jquery.min.js', inject: 'libs'},
// {src: 'lodash/lodash.min.js', inject: 'libs'},
];
const seedDependencies = this.NPM_DEPENDENCIES;
this.NPM_DEPENDENC... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.