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 |
|---|---|---|---|---|
overlay.py | import math
import urwid
from mitmproxy.tools.console import common
from mitmproxy.tools.console import signals
from mitmproxy.tools.console import grideditor
class SimpleOverlay(urwid.Overlay):
def __init__(self, master, widget, parent, width, valign="middle"):
self.widget = widget
self.master ... |
return super().keypress(size, key)
def make_help(self):
text = []
keys = [
("enter", "choose option"),
("esc", "exit chooser"),
]
text.extend(common.format_keyvals(keys, key="key", val="text", indent=4))
return text
class OptionsOverlay(urw... | self.callback(self.choices[self.walker.index])
signals.pop_view_state.send(self) | conditional_block |
overlay.py | import math
import urwid
from mitmproxy.tools.console import common
from mitmproxy.tools.console import signals
from mitmproxy.tools.console import grideditor
class SimpleOverlay(urwid.Overlay):
def __init__(self, master, widget, parent, width, valign="middle"):
self.widget = widget
self.master ... | def keypress(self, size, key):
key = common.shortcuts(key)
if key == "enter":
self.callback(self.choices[self.walker.index])
signals.pop_view_state.send(self)
return super().keypress(size, key)
def make_help(self):
text = []
keys = [
(... | def selectable(self):
return True
| random_line_split |
overlay.py | import math
import urwid
from mitmproxy.tools.console import common
from mitmproxy.tools.console import signals
from mitmproxy.tools.console import grideditor
class SimpleOverlay(urwid.Overlay):
def __init__(self, master, widget, parent, width, valign="middle"):
self.widget = widget
self.master ... |
def keypress(self, size, key):
return key
class ChooserListWalker(urwid.ListWalker):
def __init__(self, choices, current):
self.index = 0
self.choices = choices
self.current = current
def _get(self, idx, focus):
c = self.choices[idx]
return Choice(c, focu... | return True | identifier_body |
overlay.py | import math
import urwid
from mitmproxy.tools.console import common
from mitmproxy.tools.console import signals
from mitmproxy.tools.console import grideditor
class SimpleOverlay(urwid.Overlay):
def __init__(self, master, widget, parent, width, valign="middle"):
self.widget = widget
self.master ... | (urwid.WidgetWrap):
def __init__(self, txt, focus, current):
if current:
s = "option_active_selected" if focus else "option_active"
else:
s = "option_selected" if focus else "text"
return super().__init__(
urwid.AttrWrap(
urwid.Padding(urwi... | Choice | identifier_name |
simple-data-table-demo.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { AppService } from '../../app.service';
import { SimpleDataHttpPageComponent } from '../../shared/simple-data-table/simple-data-http-page.component';
import { environment } from '../../../environments/environment';
@Component({
selector: 'c-sim... | {
this.param2.age = 15;
this.param2.name = 'admin';
this.param2.sex = '女';
this.hp2.search();
}
} | aram.age = 20;
this.param.name = 'admin23';
this.param.sex = '男';
this.pageList = [10, 15, 20];
this.hp.search();
}
search2() | identifier_body |
simple-data-table-demo.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { AppService } from '../../app.service';
import { SimpleDataHttpPageComponent } from '../../shared/simple-data-table/simple-data-http-page.component';
import { environment } from '../../../environments/environment';
@Component({
selector: 'c-sim... | this.param2.sex = '女';
this.hp2.search();
}
} | this.param2.name = 'admin'; | random_line_split |
simple-data-table-demo.component.ts | import { Component, OnInit, ViewChild } from '@angular/core';
import { AppService } from '../../app.service';
import { SimpleDataHttpPageComponent } from '../../shared/simple-data-table/simple-data-http-page.component';
import { environment } from '../../../environments/environment';
@Component({
selector: 'c-sim... | (private appService: AppService) {
this.appService.titleEventEmitter.emit("简单数据表格");
}
search() {
this.param.age = 20;
this.param.name = 'admin23';
this.param.sex = '男';
this.pageList = [10, 15, 20];
this.hp.search();
}
search2() {
this.param2.age = 15;
this.param2.name = '... | constructor | identifier_name |
views.py | """
SynLogistics AJAX JSON server interaction for common search boxes and
generic interactive components.
"""
#
# Copyright (C) by Wilco Baan Hofman <wilco@baanhofman.nl> 2011
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publis... |
products = Product.objects.filter(active=1)
products = products.filter(name__icontains=request.GET['query'])
products = products.filter(product_type=02)
products = products.order_by('name')
response = "{products:["
for product in products:
response += "{ id:'" + str(product.id) + "',n... | return HttpResponse("") | conditional_block |
views.py | """
SynLogistics AJAX JSON server interaction for common search boxes and
generic interactive components.
"""
#
# Copyright (C) by Wilco Baan Hofman <wilco@baanhofman.nl> 2011
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publis... | (request):
# Obscure errors ftw \o/
if not 'query' in request.GET:
return HttpResponse("")
accounts = Account.objects.filter(Q(number__icontains=request.GET['query']) \
| Q(name__icontains=request.GET['query']))
accounts.order_by('number')
response = "{accounts:["
for accou... | get_accounts | identifier_name |
views.py | """
SynLogistics AJAX JSON server interaction for common search boxes and
generic interactive components.
"""
#
# Copyright (C) by Wilco Baan Hofman <wilco@baanhofman.nl> 2011
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publis... | if not 'query' in request.GET:
return HttpResponse("")
products = Product.objects.filter(active=1)
products = products.filter(name__icontains=request.GET['query'])
products = products.filter(product_type=02)
products = products.order_by('name')
response = "{products:["
for product in p... | identifier_body | |
views.py | """
SynLogistics AJAX JSON server interaction for common search boxes and
generic interactive components.
"""
#
# Copyright (C) by Wilco Baan Hofman <wilco@baanhofman.nl> 2011
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publis... | # Obscure errors ftw \o/
if not 'query' in request.GET:
return HttpResponse("")
accounts = Account.objects.filter(Q(number__icontains=request.GET['query']) \
| Q(name__icontains=request.GET['query']))
accounts.order_by('number')
response = "{accounts:["
for account in accou... | @login_required
def get_accounts(request): | random_line_split |
factory.py | __author__ = 'adalekin'
import re
import requests
import hashlib
from PIL import Image, ImageOps
from cStringIO import StringIO
from xparse.parser import *
from xparse.utils import get_in_dict, set_in_dict
class URLExtractor(object):
def __init__(self, regex, parser_class):
self.regex = re.compile(rege... | results += url_extractor.extract(r.content, self.proxy, include_comments)
return results
class ThumbnailFactory(Factory):
IMAGE_FIELDS = ("thumbnail", ("user", "image"))
IMAGE_THUMBS = {
'standard': {'suffix': '@2x',
'size': (640, 640), },
'low': (320,... | if results:
return [results]
results = []
for url_extractor in self.rules: | random_line_split |
factory.py | __author__ = 'adalekin'
import re
import requests
import hashlib
from PIL import Image, ImageOps
from cStringIO import StringIO
from xparse.parser import *
from xparse.utils import get_in_dict, set_in_dict
class URLExtractor(object):
def __init__(self, regex, parser_class):
self.regex = re.compile(rege... |
def extract(self, url, include_comments=True):
r = requests.get(url, proxies={'http': self.proxy} if self.proxy else None, verify=False)
results = self.extract_from_url(r.url, include_comments)
if results:
return [results]
results = []
for url_extractor in sel... | result = url_extractor.extract_comments_from_url(url, self.proxy, until)
if result:
return result | conditional_block |
factory.py | __author__ = 'adalekin'
import re
import requests
import hashlib
from PIL import Image, ImageOps
from cStringIO import StringIO
from xparse.parser import *
from xparse.utils import get_in_dict, set_in_dict
class URLExtractor(object):
def __init__(self, regex, parser_class):
self.regex = re.compile(rege... | for url_extractor in self.rules:
result = url_extractor.extract_comments_from_url(url, self.proxy, until)
if result:
return result
def extract(self, url, include_comments=True):
r = requests.get(url, proxies={'http': self.proxy} if self.proxy else None, veri... | rules = (
URLExtractor(
'(?:http|https|)(?::\/\/|)(?:www.|)(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/ytscreeningroom\?v=|\/feeds\/api\/videos\/|\/user\S*[^\w\-\s]))([\w\-]{11})[a-z0-9;:@#?&%=+\/\$_.-]*',
YouTubeParser),
URLExtractor("https?://(www\.facebook\.com... | identifier_body |
factory.py | __author__ = 'adalekin'
import re
import requests
import hashlib
from PIL import Image, ImageOps
from cStringIO import StringIO
from xparse.parser import *
from xparse.utils import get_in_dict, set_in_dict
class URLExtractor(object):
def __init__(self, regex, parser_class):
self.regex = re.compile(rege... | (self, url, proxy=None, until=None):
for url_extractor in self.rules:
result = url_extractor.extract_comments_from_url(url, self.proxy, until)
if result:
return result
def extract(self, url, include_comments=True):
r = requests.get(url, proxies={'http': self... | extract_comments_from_url | identifier_name |
group_element_year.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | class GroupElementYearChildLeafFactory(GroupElementYearFactory):
child_element = factory.SubFactory(ElementLearningUnitYearFactory) | random_line_split | |
group_element_year.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... | ):
"""Generate a random string composed of digit between 1 and 6 included.
Each digit can be represented at most once in the string and they are sorted from smallest to greatest.
Ex: "", "156", "2", "456" and so on
"""
population = list(range(1, 7))
k = random.randint(0, len(population))
... | generate_block_value( | identifier_name |
group_element_year.py | ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core ... |
class GroupElementYearFactory(factory.django.DjangoModelFactory):
class Meta:
model = "base.GroupElementYear"
django_get_or_create = ('parent_element', 'child_element')
external_id = factory.fuzzy.FuzzyText(length=10, chars=string.digits)
changed = factory.fuzzy.FuzzyNaiveDateTime(datetim... | ""Generate a random string composed of digit between 1 and 6 included.
Each digit can be represented at most once in the string and they are sorted from smallest to greatest.
Ex: "", "156", "2", "456" and so on
"""
population = list(range(1, 7))
k = random.randint(0, len(population))
sample =... | identifier_body |
app.browser.module.ts | /**
* This file and `main.node.ts` are identical, at the moment(!)
* By splitting these, you're able to create logic, imports, etc that are "Platform" specific.
* If you want your code to be completely Universal and don't need that
* You can also just have 1 file, that is imported into both
* client.ts and server.... | {
}
| AppModule | identifier_name |
app.browser.module.ts | /**
* This file and `main.node.ts` are identical, at the moment(!)
* By splitting these, you're able to create logic, imports, etc that are "Platform" specific.
* If you want your code to be completely Universal and don't need that
* You can also just have 1 file, that is imported into both
* client.ts and server.... | */
@NgModule({
/** Root App Component */
bootstrap: [AppComponent],
/** Our Components */
declarations: [AppComponent, HomeComponent, RegisterComponent, LoginComponent, TasksComponent, UsersComponent, TaskComponent, PagenotfoundComponent, TaskEditComponent],
imports: [
/**
* NOTE: Needs to be your f... | import {Constants} from './shared/constants';
import {CommonService} from './shared/service';
/**
* Top-level NgModule "container" | random_line_split |
health.rs | use futures::future::ok;
use http::FutureHandled;
use http::ServerResponse;
use hyper;
use hyper::Request;
use hyper::Response;
use hyper::server::NewService;
use hyper::server::Service;
use std::io;
/// `/health` service returning OK status if microservice is running (obviously)
#[derive(Debug, Copy, Clone)]
pub stru... | type Response = Response;
type Error = hyper::Error;
type Future = FutureHandled;
fn call(&self, _req: Request) -> Self::Future {
box ok(ServerResponse::Data(HealthStatus::ok()).into())
}
}
#[derive(Debug, Copy, Clone, Serialize)]
struct HealthStatus {
status: &'static str,
}
impl Heal... | random_line_split | |
health.rs | use futures::future::ok;
use http::FutureHandled;
use http::ServerResponse;
use hyper;
use hyper::Request;
use hyper::Response;
use hyper::server::NewService;
use hyper::server::Service;
use std::io;
/// `/health` service returning OK status if microservice is running (obviously)
#[derive(Debug, Copy, Clone)]
pub stru... |
} | {
HealthStatus { status: "OK" }
} | identifier_body |
health.rs | use futures::future::ok;
use http::FutureHandled;
use http::ServerResponse;
use hyper;
use hyper::Request;
use hyper::Response;
use hyper::server::NewService;
use hyper::server::Service;
use std::io;
/// `/health` service returning OK status if microservice is running (obviously)
#[derive(Debug, Copy, Clone)]
pub stru... | {
status: &'static str,
}
impl HealthStatus {
fn ok() -> Self {
HealthStatus { status: "OK" }
}
} | HealthStatus | identifier_name |
mail.py | :
# lxml.clean version < 2.3.1 does not have a kill_tags attribute
# to remove in 2014
cleaner = clean.Cleaner(page_structure=True, style=False, safe_attrs_only=False, forms=False, remove_tags=tags_to_kill + tags_to_remove)
cleaned = cleaner.clean_html(src)
except Exception, e:
... |
# 5. \n back to <br/>
html = etree.tostring(root, pretty_print=True)
html = html.replace('__BR_TAG__', '<br />')
# 6. Misc cleaning :
# - ClEditor seems to love using <div><br /><div> -> replace with <br />
br_div_tags = re.compile(r'(<div>\s*<br\s*\/>\s*<\/div>)')
html = _replace_matchin... | elem.tail = elem.tail[:match.start()] + elem.tail[match.end():] | conditional_block |
mail.py | TypeError:
# lxml.clean version < 2.3.1 does not have a kill_tags attribute
# to remove in 2014
cleaner = clean.Cleaner(page_structure=True, style=False, safe_attrs_only=False, forms=False, remove_tags=tags_to_kill + tags_to_remove)
cleaned = cleaner.clean_html(src)
except Exception... | body (not necessarily <body>) starts.
"""
## (c) Fry-IT, www.fry-it.com, 2007
## <peter@fry-it.com>
## download here: http://www.peterbe.com/plog/html2plaintext
html = ustr(html)
tree = etree.fromstring(html, parser=etree.HTMLParser())
if body_id is not None:
source = tree.xpat... | random_line_split | |
mail.py | remove quoted text in nodes
quote_tags = re.compile(r'(\n(>)+[^\n\r]*)')
for node in root.getiterator():
if not node.text:
continue
node.text = _replace_matching_regex(quote_tags, node.text)
# 3. remove blockquotes
quotes = [el for el in root.getiterator(tag='blockquote')]
... | email_send | identifier_name | |
mail.py | .Cleaner(page_structure=True, style=False, safe_attrs_only=False, forms=False, remove_tags=tags_to_kill + tags_to_remove)
cleaned = cleaner.clean_html(src)
except Exception, e:
if isinstance(e, etree.ParserError) and 'empty' in str(e):
return ""
_logger.warning('html_sanitize fai... | """ Append extra content at the end of an HTML snippet, trying
to locate the end of the HTML document (</body>, </html>, or
EOF), and converting the provided content in html unless ``plaintext``
is False.
Content conversion can be done in two ways:
- wrapping it into a pre (prese... | identifier_body | |
borrowck-uniq-via-lend.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
struct F { f: G }
struct G { g: H }
struct H { h: ~int }
let mut v = F {f: G {g: H {h: ~3}}};
borrow(v.f.g.h);
}
fn aliased_imm() {
let mut v = ~3;
let _w = &v;
borrow(v);
}
fn aliased_const() {
let mut v = ~3;
let _w = &const v;
borrow(v);
}
fn aliased_mut() {
le... | local_recs | identifier_name |
borrowck-uniq-via-lend.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn local_rec() {
struct F { f: ~int }
let mut v = F {f: ~3};
borrow(v.f);
}
fn local_recs() {
struct F { f: G }
struct G { g: H }
struct H { h: ~int }
let mut v = F {f: G {g: H {h: ~3}}};
borrow(v.f.g.h);
}
fn aliased_imm() {
let mut v = ~3;
let _w = &v;
borrow(v);
}
fn al... | random_line_split | |
main.rs | extern crate serial;
extern crate num_cpus;
use std::io;
use std::io::{Read, BufReader, BufRead, Write};
use std::fs::File;
use std::str::FromStr;
use std::thread::sleep;
use std::time::Duration;
use std::num::ParseFloatError;
use std::collections::VecDeque;
use serial::prelude::*;
use serial::SerialDevice;
#[derive... |
let cpus = s.cpus as f64;
let di = (s.uptimes.back().unwrap().idle - s.uptimes.front().unwrap().idle) / cpus;
return Ok(1.0 - (di / du));
}
fn scale(v: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> u8 {
let mut f = (v - old_min) * (new_max - new_min) / (old_max - old_min) + new_min... | {
return Ok(0.0);
} | conditional_block |
main.rs | extern crate serial;
extern crate num_cpus;
use std::io;
use std::io::{Read, BufReader, BufRead, Write};
use std::fs::File;
use std::str::FromStr;
use std::thread::sleep;
use std::time::Duration;
use std::num::ParseFloatError;
use std::collections::VecDeque;
use serial::prelude::*;
use serial::SerialDevice;
#[derive... | return Some(*state);
}
Some(*state)
})
.filter_map(|state| {
let (total_option, avail_option) = state;
if let Some(total) = total_option {
if let Some(avail) = avail_option {
return Some((total, avail));
... | state.1 = Some(val.parse::<f64>().unwrap_or(0.0)); | random_line_split |
main.rs | extern crate serial;
extern crate num_cpus;
use std::io;
use std::io::{Read, BufReader, BufRead, Write};
use std::fs::File;
use std::str::FromStr;
use std::thread::sleep;
use std::time::Duration;
use std::num::ParseFloatError;
use std::collections::VecDeque;
use serial::prelude::*;
use serial::SerialDevice;
#[derive... |
fn scale(v: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> u8 {
let mut f = (v - old_min) * (new_max - new_min) / (old_max - old_min) + new_min;
f = f.min(new_max).max(new_min);
f as u8
}
fn send_info(port: &mut serial::SystemPort, cpu_used: f64, mem_used: f64) -> serial::Result<()> {
... | {
let last_uptime = uptime()?;
if s.uptimes.len() > WINDOW {
s.uptimes.pop_front();
}
s.uptimes.push_back(last_uptime);
let du = s.uptimes.back().unwrap().uptime - s.uptimes.front().unwrap().uptime;
if du < 0.001 {
return Ok(0.0);
}
let cpus = s.cpus as f64;
let di... | identifier_body |
main.rs | extern crate serial;
extern crate num_cpus;
use std::io;
use std::io::{Read, BufReader, BufRead, Write};
use std::fs::File;
use std::str::FromStr;
use std::thread::sleep;
use std::time::Duration;
use std::num::ParseFloatError;
use std::collections::VecDeque;
use serial::prelude::*;
use serial::SerialDevice;
#[derive... | () {
let mut port = open_serial_port().unwrap();
let mut cm = init_cpu_measurement().unwrap();
let delay = Duration::from_millis(100);
loop {
sleep(delay);
let cpu_usage = cpu_usage(&mut cm).unwrap();
let mem_usage = get_mem_usage().unwrap();
send_info(&mut port, cpu_usa... | main | identifier_name |
problem002.py | '''
Problem 2
19 October 2001
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, fin... | '''
import unittest
import timeit
def generate_fibonacci_sequence(limit=0):
a = 1
yield a
b = 1
yield b
i = 0
while(limit == 0 or a + b < limit):
i = a + b
a = b
b = i
yield i
'''
By considering the terms in t... |
----------------------------------------------------------
Created on 25.01.2012
@author: ahallmann
| random_line_split |
problem002.py | '''
Problem 2
19 October 2001
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, fin... |
'''
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
'''
def solve(limit=4000000):
msum = 0
for i in generate_fibonacci_sequence(limit):
if i % 2 == 0:
msum += i
return msum
... | i = a + b
a = b
b = i
yield i | conditional_block |
problem002.py | '''
Problem 2
19 October 2001
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, fin... | (limit=0):
a = 1
yield a
b = 1
yield b
i = 0
while(limit == 0 or a + b < limit):
i = a + b
a = b
b = i
yield i
'''
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find ... | generate_fibonacci_sequence | identifier_name |
problem002.py | '''
Problem 2
19 October 2001
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, fin... |
def test_answer(self):
self.assertEqual(4613732, solve())
# -----------------------------------------
def run():
return solve()
if __name__ == '__main__':
unittest.main()
if __name__ == '__main__':
t = timeit.Timer("run()", "from __main__ import run"... | self.assertEqual(44, solve(100)) | identifier_body |
test_mediachange.py | # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
import os
import tests
from . import lib
#############################################
# UI tests for details storage media change #
#############################################
def testMediaChange(app):
v... | appl.click()
app.click_alert_button("changes will take effect", "OK")
lib.utils.check(lambda: not appl.sensitive)
lib.utils.check(lambda: not entry.text)
# Shutdown the VM, verify change shows up
win.find("Shut Down", "push button").click()
run = win.find("Run", "push button")
lib.utils... | """
Test in the case of a running VM
"""
vmname = "test-many-devices"
app.open(show_console=vmname)
win = app.find_details_window(vmname, click_details=True)
hw = win.find("hw-list")
entry = win.find("media-entry")
appl = win.find("config-apply")
hw.find("IDE CDROM 1", "table cell")... | identifier_body |
test_mediachange.py | # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
import os
import tests
from . import lib
#############################################
# UI tests for details storage media change #
#############################################
def testMediaChange(app):
v... | lib.utils.check(lambda: not entry.text)
# Enter /dev/fdb, after apply it should change to pretty label
entry.set_text("/dev/fdb")
appl.click()
lib.utils.check(lambda: not appl.sensitive)
lib.utils.check(lambda:
entry.text == "Floppy_install_label (/dev/fdb)")
# Specify manual path
... | entry.click_secondary_icon()
lib.utils.check(lambda: not entry.text)
appl.click()
lib.utils.check(lambda: not appl.sensitive) | random_line_split |
test_mediachange.py | # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
import os
import tests
from . import lib
#############################################
# UI tests for details storage media change #
#############################################
def | (app):
vmname = "test-many-devices"
app.uri = tests.utils.URIs.test_remote
app.open(show_console=vmname)
win = app.find_details_window(vmname,
click_details=True, shutdown=True)
hw = win.find("hw-list")
tab = win.find("disk-tab")
combo = win.find("media-combo")
entry = win.fi... | testMediaChange | identifier_name |
objective-list-item.js | import { clickable, create, hasClass, isVisible, text } from 'ember-cli-page-object';
import { pageObjectFillInFroalaEditor, pageObjectFroalaEditorValue } from 'ilios-common';
import meshManager from './manage-objective-descriptors';
import competencyManager from './manage-objective-competency';
import meshDescriptors ... | hasTrashCan: isVisible('[data-icon="trash"]', { scope: '[data-test-actions]' }),
activate: clickable('[data-test-activate]', { scope: '[data-test-actions]' }),
isActive: isVisible('[data-icon="lightbulb-on"]', { scope: '[data-test-actions]' }),
deactivate: clickable('[data-test-deactivate]', { scope: '[data-tes... | },
competency,
meshDescriptors,
remove: clickable('[data-icon="trash"]', { scope: '[data-test-actions]' }), | random_line_split |
quality.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//TODO(eijebong): Remove this once typed headers figure out quality
// This is copy pasted from the old hyper hea... | (&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.item, fmt)?;
match self.quality.0 {
1000 => Ok(()),
0 => fmt.write_str("; q=0"),
mut x => {
fmt.write_str("; q=0.")?;
let mut digits = *b"000";
d... | fmt | identifier_name |
quality.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//TODO(eijebong): Remove this once typed headers figure out quality
// This is copy pasted from the old hyper hea... | {
HeaderValue::from_str(
&q.iter()
.map(|q| q.to_string())
.collect::<Vec<String>>()
.join(", "),
)
.unwrap()
} | identifier_body | |
quality.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//TODO(eijebong): Remove this once typed headers figure out quality
// This is copy pasted from the old hyper hea... | x /= 10;
digits[1] = (x % 10) as u8 + b'0';
x /= 10;
digits[0] = (x % 10) as u8 + b'0';
let s = str::from_utf8(&digits[..]).unwrap();
fmt.write_str(s.trim_right_matches('0'))
},
}
}
}
pub fn quality... | fmt.write_str("; q=0.")?;
let mut digits = *b"000";
digits[2] = (x % 10) as u8 + b'0'; | random_line_split |
HP_SN_IGMP_MIB_OID.py | # python | import HP_SN_IGMP_MIB
OIDMAP = {
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1': HP_SN_IGMP_MIB.snIgmpMIBObjects,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.1': HP_SN_IGMP_MIB.snIgmpQueryInterval,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.2': HP_SN_IGMP_MIB.snIgmpGroupMembershipTime,
'1.3.6.1.4.1.11.2.3.7.11.12.2.6.1.3.1.1': HP_SN_IGMP_MIB.snIgmp... | # This file is generated by a program (mib2py).
| random_line_split |
ammoToDmgPattern.py | # noinspection PyPackageRequirements
import wx
import gui.globalEvents as GE
import gui.mainFrame
from gui.contextMenu import ContextMenuSingle
from service.fit import Fit
class AmmoToDmgPattern(ContextMenuSingle):
visibilitySetting = 'ammoPattern'
def __init__(self):
self.mainFrame = gui.mainFrame... |
def getBitmap(self, callingWindow, context, mainItem):
return None
AmmoToDmgPattern.register()
| fitID = self.mainFrame.getActiveFit()
Fit.getInstance().setAsPattern(fitID, mainItem)
wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID,))) | identifier_body |
ammoToDmgPattern.py | # noinspection PyPackageRequirements
import wx
import gui.globalEvents as GE
import gui.mainFrame
from gui.contextMenu import ContextMenuSingle
from service.fit import Fit
class AmmoToDmgPattern(ContextMenuSingle):
visibilitySetting = 'ammoPattern'
def __init__(self):
self.mainFrame = gui.mainFrame... | (self, callingWindow, fullContext, mainItem, i):
fitID = self.mainFrame.getActiveFit()
Fit.getInstance().setAsPattern(fitID, mainItem)
wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID,)))
def getBitmap(self, callingWindow, context, mainItem):
return None
AmmoToDmgPattern.r... | activate | identifier_name |
ammoToDmgPattern.py | # noinspection PyPackageRequirements
import wx
import gui.globalEvents as GE
import gui.mainFrame
from gui.contextMenu import ContextMenuSingle
from service.fit import Fit
class AmmoToDmgPattern(ContextMenuSingle):
visibilitySetting = 'ammoPattern'
def __init__(self):
self.mainFrame = gui.mainFrame... |
for attr in ("emDamage", "thermalDamage", "explosiveDamage", "kineticDamage"):
if mainItem.getAttribute(attr) is not None:
return True
return False
def getText(self, callingWindow, itmContext, mainItem):
return "Set {} as Damage Pattern".format(itmContext if i... | return False | conditional_block |
ammoToDmgPattern.py | # noinspection PyPackageRequirements
import wx
import gui.globalEvents as GE
import gui.mainFrame
from gui.contextMenu import ContextMenuSingle
from service.fit import Fit
class AmmoToDmgPattern(ContextMenuSingle):
visibilitySetting = 'ammoPattern'
def __init__(self):
self.mainFrame = gui.mainFrame... | AmmoToDmgPattern.register() | random_line_split | |
Close.tsx | import {
BoostnoteIconProps,
BoostnoteIconStyledContainer
} from '../../lib/icons'
import React from 'react'
export const IconClose = (props: BoostnoteIconProps) => (
<BoostnoteIconStyledContainer>
<svg | {...props}
style={
props.size != null
? { ...props.style, width: props.size, height: props.size }
: props.style
}
>
<path
d='M38.414.586a2 2 0 010 2.828L22.328 19.499l16.087 16.086a2 2 0 01-1.244 3.407l-.17.007a1.992 1.992 0 01-1.414-.586L19.499 22.327 3.4... | width='1em'
height='1em'
viewBox='0 0 39 39' | random_line_split |
ConfirmationDialogController.ts | import { ConfirmationDialogParams } from './ConfirmationDialogParams';
class ConfirmationDialogController extends ConfirmationDialogParams {
private _injector: ng.auto.IInjectorService;
public $mdDialog: angular.material.IDialogService;
public theme: string;
constructor(
$mdDialog: angular.m... | dDialog.cancel();
}
}
angular
.module('pipConfirmationDialog')
.controller('pipConfirmationDialogController', ConfirmationDialogController); | this.$m | identifier_name |
ConfirmationDialogController.ts | import { ConfirmationDialogParams } from './ConfirmationDialogParams';
class ConfirmationDialogController extends ConfirmationDialogParams {
private _injector: ng.auto.IInjectorService;
public $mdDialog: angular.material.IDialogService;
public theme: string;
constructor(
$mdDialog: angular.m... | void {
this.$mdDialog.hide();
}
public onCancel(): void {
this.$mdDialog.cancel();
}
}
angular
.module('pipConfirmationDialog')
.controller('pipConfirmationDialogController', ConfirmationDialogController); | this.title || 'Confirm';
this.ok = this.ok || 'OK';
this.cancel = this.cancel || 'Cancel';
}
}
public onOk(): | conditional_block |
ConfirmationDialogController.ts | import { ConfirmationDialogParams } from './ConfirmationDialogParams';
class ConfirmationDialogController extends ConfirmationDialogParams {
private _injector: ng.auto.IInjectorService;
public $mdDialog: angular.material.IDialogService;
public theme: string;
constructor(
$mdDialog: angular.m... | this.$mdDialog.hide();
}
public onCancel(): void {
this.$mdDialog.cancel();
}
}
angular
.module('pipConfirmationDialog')
.controller('pipConfirmationDialogController', ConfirmationDialogController); | random_line_split | |
instance_group_helper.py | # Copyright 2020 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 in writing, ... | """ Build an object which is an instance of the InstanceGroup's subclass
"""
# try to build a zonal instance group
try:
instance_group_configs = self.get_instance_group_in_zone()
except Exception:
# It is not a single zone instance group
pass
... |
def build_instance_group(self) -> InstanceGroup: | random_line_split |
instance_group_helper.py | # Copyright 2020 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 in writing, ... |
# try to build a regional instance group
try:
self.get_instance_group_in_region()
except Exception as e:
raise e
else:
return RegionalManagedInstanceGroup(self.compute, self.project,
self.instance_group_... | return ZonalManagedInstanceGroup(self.compute,
self.project,
self.instance_group_name,
self.network,
self.subnetwork,
... | conditional_block |
instance_group_helper.py | # Copyright 2020 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 in writing, ... |
def build_instance_group(self) -> InstanceGroup:
""" Build an object which is an instance of the InstanceGroup's subclass
"""
# try to build a zonal instance group
try:
instance_group_configs = self.get_instance_group_in_zone()
except Exception:
# It... | """ Initialize an instance group helper object
Args:
compute: google compute engine
project: project ID
instance_group_name: name of the instance group
region: region of the instance group
zone: zone of the instance group
preserve_instance... | identifier_body |
instance_group_helper.py | # Copyright 2020 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 in writing, ... | (self) -> InstanceGroup:
""" Build an object which is an instance of the InstanceGroup's subclass
"""
# try to build a zonal instance group
try:
instance_group_configs = self.get_instance_group_in_zone()
except Exception:
# It is not a single zone instance... | build_instance_group | identifier_name |
blog-posts.service.spec.ts | import { TestBed, inject, async } from '@angular/core/testing';
import { BlogPostsService } from './blog-posts.service';
import { Post } from '../classes/post';
import { HttpClient, HttpClientModule, HttpRequest } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/com... | })));
}); | req.method === 'POST';
}, 'File Upload').flush(testResponseData);
| random_line_split |
load_ICD9_structure.py | import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def traverse(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
de... | (t, outfile):
for c in t.children:
print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile)
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes... | getEdges | identifier_name |
load_ICD9_structure.py | import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def traverse(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
de... |
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfil... | print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile) | conditional_block |
load_ICD9_structure.py | import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def traverse(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
de... |
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfile... | getEdges(c, outfile) | random_line_split |
load_ICD9_structure.py | import sys
import os
import subprocess
import string
printable = set(string.printable)
def sanitize(txt):
txt = ''.join(filter(lambda c: c in printable, txt))
return txt
def traverse(t, outfile):
print>>outfile, sanitize(t.code+'\t'+t.description)
for c in t.children:
traverse(c, outfile)
de... |
print 'cloning github repository sirrice/icd9.git'
subprocess.call('git clone https://github.com/sirrice/icd9.git', shell=1)
sys.path.append('icd9')
from icd9 import ICD9
tree = ICD9('icd9/codes.json')
toplevelnodes = tree.children
print 'creating name file'
outfile = file('code.names', 'w')
traverse(tree, outfil... | for c in t.children:
print >>outfile, sanitize(t.code+'\t'+c.code)
getEdges(c, outfile) | identifier_body |
role.py | # Copyright (c) 2015 Scopely, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at | # ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import logging
LOG = logging.getLogger(__name__)
class Role(object):
def __init__(self, session, data):
self._session = session
self.logical_name = data['L... | #
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF | random_line_split |
role.py | # Copyright (c) 2015 Scopely, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distrib... | (object):
def __init__(self, session, data):
self._session = session
self.logical_name = data['LogicalResourceId']
self.physical_name = data['PhysicalResourceId']
self.stack_arn = data['StackId']
self._iam = self._session.create_client('iam')
self._arn = None
@p... | Role | identifier_name |
role.py | # Copyright (c) 2015 Scopely, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distrib... |
return self._arn
| response = self._iam.get_role(
RoleName=self.physical_name)
LOG.debug(response)
self._arn = response['Role']['Arn']
LOG.debug('role_arn: %s', self._arn) | conditional_block |
role.py | # Copyright (c) 2015 Scopely, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distrib... | if self._arn is None:
response = self._iam.get_role(
RoleName=self.physical_name)
LOG.debug(response)
self._arn = response['Role']['Arn']
LOG.debug('role_arn: %s', self._arn)
return self._arn | identifier_body | |
issue-19367.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut a = (0, Some("right".to_string()));
let b = match a.1 {
Some(v) => {
a.1 = Some("wrong".to_string());
v
}
None => String::new()
};
println!("{}", b);
assert_eq!(b, "right");
let mut s = S{ o: Some("right".to_string()) };
let b = ... | main | identifier_name |
issue-19367.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let mut a = (0, Some("right".to_string()));
let b = match a.1 {
Some(v) => {
a.1 = Some("wrong".to_string());
v
}
None => String::new()
};
println!("{}", b);
assert_eq!(b, "right");
let mut s = S{ o: Some("right".to_string()) };
... | // Make sure we don't reuse the same alloca when matching
// on field of struct or tuple which we reassign in the match body. | random_line_split |
selector-native.js | Document';
var Selector = {
_types: {
esc: {
token: '\uE000',
re: /\\[:\[\]\(\)#\.\'\>+~"]/gi
},
attr: {
token: '\uE001',
re: /(\[[^\]]*\])/g
},
pseudo: {
token: '\uE002',
re: /(\([^\)]*\))/g
}... |
if (queries.length > 1) { // remove dupes and sort by doc order
ret = Selector._sort(Selector._deDupe(ret));
}
}
return (firstOnly) ? (ret[0] || null) : ret;
},
_replaceSelector: function(selector) {
var esc = Y.Selector._parse('esc', selecto... | {
result = fn(query[0], query[1], firstOnly);
if (!firstOnly) { // coerce DOM Collection to Array
result = Y.Array(result, 0, true);
}
if (result) {
ret = ret.concat(result);
}
} | conditional_block |
selector-native.js | Document';
var Selector = {
_types: {
esc: {
token: '\uE000',
re: /\\[:\[\]\(\)#\.\'\>+~"]/gi
},
attr: {
token: '\uE001',
re: /(\[[^\]]*\])/g
},
pseudo: {
token: '\uE002',
re: /(\([^\)]*\))/g
}... | if (selector.indexOf(',') > -1) {
selector = Y.Selector._replaceCommas(selector);
}
var groups = selector.split('\uE007'), // split on replaced comma token
queries = [],
prefix = '',
id,
i,
len;
if (node) {
... |
// allows element scoped queries to begin with combinator
// e.g. query('> p', document.body) === query('body > p')
_splitQueries: function(selector, node) { | random_line_split |
tasks.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (id: string): boolean {
return !!this.tasks[id];
}
public remove(id: string): void {
delete this.tasks[id];
}
public all(): Task[] {
return Object.keys(this.tasks).map(key => this.tasks[key]);
}
}
| exists | identifier_name |
tasks.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public exists(id: string): boolean {
return !!this.tasks[id];
}
public remove(id: string): void {
delete this.tasks[id];
}
public all(): Task[] {
return Object.keys(this.tasks).map(key => this.tasks[key]);
}
}
| {
return this.tasks[id];
} | identifier_body |
tasks.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved. | import NLS = require('vs/nls');
import * as Objects from 'vs/base/common/objects';
import { IStringDictionary, values } from 'vs/base/common/collections';
import * as Platform from 'vs/base/common/platform';
import * as Types from 'vs/base/common/types';
import * as Strings from 'vs/base/common/strings';
import * as U... | * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
| random_line_split |
tasks.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
if (name === null && trigger === null) {
this.status.state = ValidationState.Error;
this.log(NLS.localize('TaskParser.nameOrTrigger', 'A task must either define a name or a trigger.'));
return null;
}
let executable: Executable = json.executable ? (new ExecutableParser(this.logger, this.status)).parse(j... | {
trigger = <string[]>json.trigger;
} | conditional_block |
step-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { StepSearchService } from './step-search.service';
import { Step } from './step'; | import {StepsComponent} from './steps.component';
@Component({
moduleId: module.id,
selector: 'step-search',
templateUrl: 'step-search.component.html',
styleUrls: [ 'step-search.component.css' ],
providers: [StepSearchService]
})
export class StepSearchComponent implements OnInit {
steps: Observable<Step[]>... | random_line_split | |
step-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { StepSearchService } from './step-search.service';
import { Step } from './step';
import {StepsComponent}... |
gotoDetail(step: Step): void {
// let link = ['/detail', step.name];
// this.router.navigate(link);
//StepsComponent.selectedStep = step;
}
}
| {
document.getElementById('search-box').innerHTML="";
this.search("");
} | identifier_body |
step-search.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { StepSearchService } from './step-search.service';
import { Step } from './step';
import {StepsComponent}... | (
private StepSearchService: StepSearchService,
private router: Router) {}
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.steps = this.searchTerms
.debounceTime(300) // wait for 300ms pause in eve... | constructor | identifier_name |
audio.js | var redis = require('redis').createClient();
var uuid = require('node-uuid');
var mongoose = require('mongoose');
var request = require('request');
var Alarm = mongoose.model('Alarm');
var timeGen = function (){
var t = new Date;
var m = t.getMinutes(),
h = t.getHours()
return 1111;
}
var runnin... | redis.del('uuid:'+id);
redis.del('id:'+ids);
res.status(200).end();
next();
});
}
} |
res.status(404).end(); next();
}
| conditional_block |
audio.js | var redis = require('redis').createClient();
var uuid = require('node-uuid');
var mongoose = require('mongoose');
var request = require('request');
var Alarm = mongoose.model('Alarm');
var timeGen = function (){
var t = new Date;
var m = t.getMinutes(),
h = t.getHours()
return 1111;
}
var runnin... |
if(running_alarm_step_counter[uuid] % 2 == 0){
running_alarm_step_counter[uuid] += 1;
console.log('IGNORING REQUEST');
return res.send(500);
} else {
if(running_alarm_step && running_alarm_step[uuid] >= 0){
... | } | random_line_split |
tictactoe_entry.ts | /*{# Copyright (c) 2013 Turbulenz Limited #}*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/services/turbulenzservices.js") }}*/
/*{{ javascript("jslib/services/turbulenzbridge.js") }}*/
/*{{ javascript("jsli... | {
var application = Application.create();
TurbulenzEngine.onunload = function onUnloadFn()
{
application.shutdown();
};
application.init();
}; |
TurbulenzEngine.onload = function onloadFn() | random_line_split |
revisions_test.rs | extern crate gitters;
use gitters::objects;
use gitters::revisions;
#[test]
fn full_sha1_resolves_to_self() {
assert_eq!(
Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())),
revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21"));
}
#[test]
fn partial_sha1_resolves_... | () {
assert_eq!(
Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())),
revisions::resolve("d7698dd~3"));
}
#[test]
fn branch_resolves_to_sha1() {
assert_eq!(
Ok(objects::Name("41cf28e8cac50f5cfeda40cfbfdd049763541c5a".to_string())),
revisions::resolve("intro... | ancestor_specification_resolves_to_ancestor_sha1 | identifier_name |
revisions_test.rs | extern crate gitters;
use gitters::objects;
use gitters::revisions;
#[test]
fn full_sha1_resolves_to_self() {
assert_eq!(
Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())),
revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21"));
}
#[test]
fn partial_sha1_resolves_... |
#[test]
fn invalid_revision_does_not_resolve() {
assert_eq!(
Err(revisions::Error::InvalidRevision),
revisions::resolve("invalid"));
}
| {
assert_eq!(
Ok(objects::Name("41cf28e8cac50f5cfeda40cfbfdd049763541c5a".to_string())),
revisions::resolve("introduce-tests"));
} | identifier_body |
revisions_test.rs | extern crate gitters;
use gitters::objects;
use gitters::revisions;
#[test]
fn full_sha1_resolves_to_self() { | }
#[test]
fn partial_sha1_resolves_to_full_sha1_if_unambiguous() {
assert_eq!(
Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())),
revisions::resolve("4ddb0025e"));
}
#[test]
fn multiple_parent_specification_resolves_to_ancestor_sha1() {
assert_eq!(
Ok(objects::N... | assert_eq!(
Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())),
revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21")); | random_line_split |
locations.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | (self):
if self.is_default:
return
(Location.query
.filter(Location.is_default | (Location.id == self.id))
.update({'is_default': func.not_(Location.is_default)}, synchronize_session='fetch'))
def get_attribute_by_name(self, name):
return self.attributes.filter... | set_default | identifier_name |
locations.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... |
return buildings
| room_with_lat_lon = next((r for r in rooms if r.longitude and r.latitude), None)
if not room_with_lat_lon:
continue
buildings.append({'number': building_name,
'title': _(u'Building {}'.format(building_name)),
'longitude'... | conditional_block |
locations.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the | # WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Indico; if not, see <http://www.gnu.org/licenses/>.
from collect... | # License, or (at your option) any later version.
#
# Indico is distributed in the hope that it will be useful, but | random_line_split |
locations.py | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... |
id = db.Column(
db.Integer,
primary_key=True
)
name = db.Column(
db.String,
nullable=False,
unique=True,
index=True
)
is_default = db.Column(
db.Boolean,
nullable=False,
default=False
)
default_aspect_id = db.Column(
... | return cls.working_time_periods[-1][1] | identifier_body |
lookup-own-acsr-wo-getter.js | // Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-additional-properties-of-the-object.prototype-object
description: >
Behavior when "this" value defines a like-named accessor property without a
`get` method
i... | assert.sameValue(subject.__lookupGetter__('target'), undefined); | random_line_split | |
searchBar.component.ts | import { Component, Output, EventEmitter } from '@angular/core';
import { SearchQueryService } from './searchQuery.service'
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
@Component({
selector: 'search-bar',
// templateUrl: '../templates/search_category.html'
template: ... | this.resultsVisible = false;
}
onSelectCategory(category_id : number) : void
{
this.router.navigate(['category', category_id]);
this.resultsVisible = false;
// this.categorySelected.emit(category_id);
}
} | }
onBlur() : void
{ | random_line_split |
searchBar.component.ts | import { Component, Output, EventEmitter } from '@angular/core';
import { SearchQueryService } from './searchQuery.service'
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
@Component({
selector: 'search-bar',
// templateUrl: '../templates/search_category.html'
template: ... | () : void
{
this.resultsVisible = false;
}
onSelectCategory(category_id : number) : void
{
this.router.navigate(['category', category_id]);
this.resultsVisible = false;
// this.categorySelected.emit(category_id);
}
}
| onBlur | identifier_name |
searchBar.component.ts | import { Component, Output, EventEmitter } from '@angular/core';
import { SearchQueryService } from './searchQuery.service'
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
@Component({
selector: 'search-bar',
// templateUrl: '../templates/search_category.html'
template: ... |
onBlur() : void
{
this.resultsVisible = false;
}
onSelectCategory(category_id : number) : void
{
this.router.navigate(['category', category_id]);
this.resultsVisible = false;
// this.categorySelected.emit(category_id);
}
}
| {
this.searchResults = this.searchQueryService.searchForCategory(this.searchQuery);
this.resultsVisible = (this.searchQuery != undefined && this.searchQuery.length > 0);
} | identifier_body |
display_controller.rs | use std::thread;
use std::sync::{mpsc, Arc, Mutex};
use rustc_serialize::json;
use input_parser;
use channel::Channel;
use current_state::{self, CurrentState};
use rdispatcher::{Subscribe, SubscribeHandle, DispatchMessage, Broadcast, BroadcastHandle};
use dispatch_type::DispatchType;
use view::View;
use view_data::Vie... | (payload: &str, state: &CurrentState, current_view_data: &mut ViewData, all_view_data: &mut Vec<ViewData>) {
let channel_names = state.channel_names();
current_view_data.add_debug(format!("Channels: {}", channel_names.connect(", ")));
}
fn handle_user_input(payload: &str, state: &CurrentState, current_view_data:... | handle_list_channels | identifier_name |
display_controller.rs | use std::thread;
use std::sync::{mpsc, Arc, Mutex};
use rustc_serialize::json;
use input_parser;
use channel::Channel;
use current_state::{self, CurrentState};
use rdispatcher::{Subscribe, SubscribeHandle, DispatchMessage, Broadcast, BroadcastHandle};
use dispatch_type::DispatchType;
use view::View;
use view_data::Vie... | fn broadcast_handle(&mut self) -> BroadcastHandle<DispatchType> {
let (tx, rx) = mpsc::channel::<DispatchMessage<DispatchType>>();
self.broadcast_tx = Some(tx);
rx
}
} | }
impl Broadcast<DispatchType> for DisplayController { | random_line_split |
gruntfile.js | module.exports = function (grunt) {
"use strict";
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
// grunt-contrib-clean
clean: {
instrument: "<%= instrument.options.basePath %>"
},
// grunt-contrib-jshint
jshint: {
files: [... |
global.MODULE_ROOT = moduleRoot;
global.MODULE_ROOT_TESTS = __dirname + "/node_tests";
});
grunt.registerTask("beautify", ["jsbeautifier"]);
grunt.registerTask("cover", ["register_globals:coverage", "clean:instrument", "instrument", "lint", "mochaTest", "storeCoverage", "makeReport"]);
... | {
moduleRoot = __dirname;
} | conditional_block |
gruntfile.js | module.exports = function (grunt) {
"use strict";
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
// grunt-contrib-clean
clean: {
instrument: "<%= instrument.options.basePath %>"
},
// grunt-contrib-jshint
jshint: {
files: [... | }
});
grunt.loadNpmTasks("grunt-contrib-clean");
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.loadNpmTasks("grunt-istanbul");
grunt.loadNpmTasks("grunt-jsbeautifier");
grunt.loadNpmTasks("grunt-mocha-test");
grunt.registerTask("re... | files: ["<%= jshint.files %>"],
options: {
js: grunt.file.readJSON(".jsbeautifyrc")
} | random_line_split |
angular-permission-ng.js | /**
* angular-permission-ng
* Extension module of angular-permission for access control within angular-route
* @version v3.1.0 - 2016-05-15
* @link https://github.com/Narzerus/angular-permission
* @author Rafael Vidaurre <narzerus@gmail.com> (http://www.rafaelvidaurre.com), Blazej Krysiak
* <blazej.krysiak@gmai... | () {
$rootScope.$broadcast(TransitionEventNames.permissionStart, TransitionProperties.next);
}
/**
* Broadcasts "$routeChangePermissionAccepted" event from $rootScope
* @methodOf permission.ng.TransitionEvents
*/
function broadcastPermissionAcceptedEvent() {
$rootScope.$broadcast... | broadcastPermissionStartEvent | identifier_name |
angular-permission-ng.js | /**
* angular-permission-ng
* Extension module of angular-permission for access control within angular-route
* @version v3.1.0 - 2016-05-15
* @link https://github.com/Narzerus/angular-permission
* @author Rafael Vidaurre <narzerus@gmail.com> (http://www.rafaelvidaurre.com), Blazej Krysiak
* <blazej.krysiak@gmai... | }
/**
* Checks if route has set permissions restrictions
* @method
* @private
*
* @returns {boolean}
*/
function areSetRoutePermissions() {
return angular.isDefined(next.$$route.data) && angular.isDefined(next.$$route.data.permissions);
}
... | {
setTransitionProperties();
TransitionEvents.broadcastPermissionStartEvent();
var permissionMap = new PermissionMap({
only: next.$$route.data.permissions.only,
except: next.$$route.data.permissions.except,
redirectTo: next.$$route.data.permissions.redirectTo
... | conditional_block |
angular-permission-ng.js | /**
* angular-permission-ng
* Extension module of angular-permission for access control within angular-route
* @version v3.1.0 - 2016-05-15
* @link https://github.com/Narzerus/angular-permission
* @author Rafael Vidaurre <narzerus@gmail.com> (http://www.rafaelvidaurre.com), Blazej Krysiak
* <blazej.krysiak@gmai... | });
}
var ngPermission = angular
.module('permission.ng', ['permission', 'ngRoute'])
.run(run).name;
module.exports = ngPermission.name;
}(module || {}));
(function () {
'use strict';
/**
* Service responsible for managing and emitting events
* @name permission.ng.TransitionEvents
*... | } | random_line_split |
angular-permission-ng.js | /**
* angular-permission-ng
* Extension module of angular-permission for access control within angular-route
* @version v3.1.0 - 2016-05-15
* @link https://github.com/Narzerus/angular-permission
* @author Rafael Vidaurre <narzerus@gmail.com> (http://www.rafaelvidaurre.com), Blazej Krysiak
* <blazej.krysiak@gmai... |
/**
* Broadcasts "$routeChangePermissionStart" event from $rootScope
* @methodOf permission.ng.TransitionEvents
*/
function broadcastPermissionStartEvent() {
$rootScope.$broadcast(TransitionEventNames.permissionStart, TransitionProperties.next);
}
/**
* Broadcasts "$routeCha... | {
return isRouteChangePermissionStartDefaultPrevented();
} | identifier_body |
pipelineConfigurer.controller.spec.ts | import { IController, IControllerService, IQService, IRootScopeService, IScope, IWindowService } from 'angular';
import { ApplicationModelBuilder } from 'core/application/applicationModel.builder';
import { PipelineConfigService } from 'core/pipeline/config/services/PipelineConfigService';
import {
IDockerTrigger,
... | vm.updatePipelineConfig({ triggers: [inheritedDockerTrigger, githubTrigger] });
$scope.$apply();
expect($scope.pipeline.triggers.length).toBe(1);
expect($scope.pipeline.triggers).toEqual([githubTrigger]);
expect($scope.renderablePipeline.triggers).toEqual([inheritedDockerTrigger, githubT... | });
it('can add and remove a trigger to the pipeline config and plan', function() {
expect($scope.pipeline.triggers.length).toBe(0); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.