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
0005_auto_20150802_0303.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals
class Migration(migrations.Migration): dependencies = [ ('imager_profile', '0004_auto_20150802_0153'), ] operations = [ migrations.RemoveField( model_name='imagerprofile', name='name', ), migrations.AddField( model_name='imagerprofile', ...
from django.db import models, migrations
random_line_split
init-twice-retains-filter.rs
extern crate env_logger; extern crate log; use std::env; use std::process; use std::str; fn main() { if env::var("YOU_ARE_TESTING_NOW").is_ok() { // Init from the env (which should set the max level to `Debug`) env_logger::init(); assert_eq!(log::LevelFilter::Debug, log::max_level()); ...
println!("test failed: {}", out.status); println!("--- stdout\n{}", str::from_utf8(&out.stdout).unwrap()); println!("--- stderr\n{}", str::from_utf8(&out.stderr).unwrap()); process::exit(1); }
{ return; }
conditional_block
init-twice-retains-filter.rs
extern crate env_logger; extern crate log; use std::env; use std::process; use std::str; fn
() { if env::var("YOU_ARE_TESTING_NOW").is_ok() { // Init from the env (which should set the max level to `Debug`) env_logger::init(); assert_eq!(log::LevelFilter::Debug, log::max_level()); // Init again using a different max level // This shouldn't clobber the level that w...
main
identifier_name
init-twice-retains-filter.rs
extern crate env_logger; extern crate log; use std::env; use std::process; use std::str; fn main() { if env::var("YOU_ARE_TESTING_NOW").is_ok() { // Init from the env (which should set the max level to `Debug`) env_logger::init(); assert_eq!(log::LevelFilter::Debug, log::max_level());
.parse_filters("info") .try_init() .unwrap_err(); assert_eq!(log::LevelFilter::Debug, log::max_level()); return; } let exe = env::current_exe().unwrap(); let out = process::Command::new(exe) .env("YOU_ARE_TESTING_NOW", "1") .env("RUST_LOG...
// Init again using a different max level // This shouldn't clobber the level that was previously set env_logger::Builder::new()
random_line_split
init-twice-retains-filter.rs
extern crate env_logger; extern crate log; use std::env; use std::process; use std::str; fn main()
.env("YOU_ARE_TESTING_NOW", "1") .env("RUST_LOG", "debug") .output() .unwrap_or_else(|e| panic!("Unable to start child process: {}", e)); if out.status.success() { return; } println!("test failed: {}", out.status); println!("--- stdout\n{}", str::from_utf8(&out.s...
{ if env::var("YOU_ARE_TESTING_NOW").is_ok() { // Init from the env (which should set the max level to `Debug`) env_logger::init(); assert_eq!(log::LevelFilter::Debug, log::max_level()); // Init again using a different max level // This shouldn't clobber the level that was ...
identifier_body
badges.js
class AchievementEvt { constructor(subType, payload) { this.type = 'achievements'; this.subType = subType; this.payload = payload; } }; /** * generate PageVisitEvt * @param {string} * @returns {AchievementEvt} */ export class PageVisitEvt extends AchievementEvt { constructor(pag...
extends AchievementEvt { constructor(targetRange) { super('time-travel', targetRange); } }; // TODO // clickedOnNotification from SW - just after action [fast hand, tchin tchin, chain reaction] // ensure all ui event are processed - OK [mood entry, page visits, past, future, forgot password] await TES...
TimeTravelEvt
identifier_name
badges.js
class AchievementEvt { constructor(subType, payload) { this.type = 'achievements'; this.subType = subType; this.payload = payload; } }; /** * generate PageVisitEvt * @param {string} * @returns {AchievementEvt} */ export class PageVisitEvt extends AchievementEvt { constructor(pag...
} }; // TODO // clickedOnNotification from SW - just after action [fast hand, tchin tchin, chain reaction] // ensure all ui event are processed - OK [mood entry, page visits, past, future, forgot password] await TEST [duck face] KO [duck face] // snackbar for achievements + animation const badgesConfig = { ba...
* @returns {AchievementEvt} */ export class TimeTravelEvt extends AchievementEvt { constructor(targetRange) { super('time-travel', targetRange);
random_line_split
badges.js
class AchievementEvt { constructor(subType, payload) { this.type = 'achievements'; this.subType = subType; this.payload = payload; } }; /** * generate PageVisitEvt * @param {string} * @returns {AchievementEvt} */ export class PageVisitEvt extends AchievementEvt { constructor(pag...
}; // TODO // clickedOnNotification from SW - just after action [fast hand, tchin tchin, chain reaction] // ensure all ui event are processed - OK [mood entry, page visits, past, future, forgot password] await TEST [duck face] KO [duck face] // snackbar for achievements + animation const badgesConfig = { badgesA...
{ super('time-travel', targetRange); }
identifier_body
app.component.ts
import { Component, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { select, Store } from '@ngrx/store'; import { first, switchMap } from 'rxjs/operators'; import { combineLatest } from 'rxjs'; import * as chart_moment from 'chart.js/node_modules/moment'; import 'moment/lo...
}); this.store .pipe(select(UserTagsSelectors.getTheme)) .subscribe(themeName => this.styleService.useTheme(themeName)); this.translateService.onLangChange .pipe( switchMap(() => this.store.pipe( select(UserTagsSelectors.getTimeFormat), first(), ...
chart_moment.locale(language); chart_moment.updateLocale(language, { longDateFormat: Utils.getMomentLongDateFormat(language, timeFormat), });
random_line_split
app.component.ts
import { Component, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { select, Store } from '@ngrx/store'; import { first, switchMap } from 'rxjs/operators'; import { combineLatest } from 'rxjs'; import * as chart_moment from 'chart.js/node_modules/moment'; import 'moment/lo...
() { this.store.pipe(select(UserTagsSelectors.getInterfaceLanguage)).subscribe(language => { this.translateService.use(language); }); this.store.pipe(select(UserTagsSelectors.getTimeFormat)).subscribe(timeFormat => { this.dateTimeFormatterService.updateFormatters(timeFormat); }); // se...
configureInterface
identifier_name
RowRepeaterFilter-dbg.js
/*! * SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5) * (c) Copyright 2009-2014 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ /* ---------------------------------------------------------------------------------- * Hint: This is a derived (generat...
* Getter for property <code>filters</code>. * The set of filter objects. * * Default value is empty/<code>undefined</code> * * @return {object} the value of property <code>filters</code> * @public * @name sap.ui.commons.RowRepeaterFilter#getFilters * @function */ /** * Setter for property <code>filters</cod...
random_line_split
test_defaults.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe, unittest from frappe.defaults import * class TestDefaults(unittest.TestCase): def test_global(self): clear_user_default("key1") set_global_default("key1", "value1") self.assertEqual(get_global_defaul...
def test_global_if_not_user(self): set_global_default("key4", "value4") self.assertEqual(get_user_default("key4"), "value4") def test_clear(self): set_user_default("key5", "value5") self.assertEqual(get_user_default("key5"), "value5") clear_user_default("key5") self.assertEqual(get_user_default("key5"), ...
random_line_split
test_defaults.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe, unittest from frappe.defaults import * class TestDefaults(unittest.TestCase): def test_global(self): clear_user_default("key1") set_global_default("key1", "value1") self.assertEqual(get_global_defaul...
(self): self.assertEqual(get_global_default("language"), "en") self.assertEqual(get_user_default("language"), "en") self.assertEqual(get_user_default_as_list("language"), ["en"]) old_user = frappe.session.user user = 'test@example.com' frappe.set_user(user) perm_doc = frappe.get_doc(dict( doctype='Us...
test_user_permission_on_defaults
identifier_name
test_defaults.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: MIT. See LICENSE import frappe, unittest from frappe.defaults import * class TestDefaults(unittest.TestCase): def test_global(self): clear_user_default("key1") set_global_default("key1", "value1") self.assertEqual(get_global_defaul...
def test_clear_global(self): set_global_default("key6", "value6") self.assertEqual(get_user_default("key6"), "value6") clear_default("key6", value="value6") self.assertEqual(get_user_default("key6"), None) def test_user_permission_on_defaults(self): self.assertEqual(get_global_default("language"), "en")...
set_user_default("key5", "value5") self.assertEqual(get_user_default("key5"), "value5") clear_user_default("key5") self.assertEqual(get_user_default("key5"), None)
identifier_body
stanza.py
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2012 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.stanza import Message from sleekxmpp.util import unicode from sleekxmpp.thirdparty import OrderedDict from sleekxmpp.xmlstream im...
return '' def del_body(self, lang=None): if lang is None: lang = self.get_lang() bodies = self.xml.findall('{%s}body' % XHTML_NS) for body in bodies: if body.attrib.get('{%s}lang' % self.xml_ns, self.get_lang()) == lang: self.xml.remove(body)...
if body.attrib.get('{%s}lang' % self.xml_ns, self.get_lang()) == lang: result = [] result.append(body.text if body.text else '') for child in body: result.append(tostring(child, xmlns=XHTML_NS)) result.append(body.ta...
conditional_block
stanza.py
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2012 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.stanza import Message from sleekxmpp.util import unicode from sleekxmpp.thirdparty import OrderedDict from sleekxmpp.xmlstream im...
XHTML_NS = 'http://www.w3.org/1999/xhtml' class XHTML_IM(ElementBase): namespace = 'http://jabber.org/protocol/xhtml-im' name = 'html' interfaces = set(['body']) lang_interfaces = set(['body']) plugin_attrib = name def set_body(self, content, lang=None): if lang is None: ...
random_line_split
stanza.py
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2012 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.stanza import Message from sleekxmpp.util import unicode from sleekxmpp.thirdparty import OrderedDict from sleekxmpp.xmlstream im...
result = [] result.append(body.text if body.text else '') for child in body: result.append(tostring(child, xmlns=XHTML_NS)) result.append(body.tail if body.tail else '') return ''.join(result) ...
"""Return the contents of the HTML body.""" if lang is None: lang = self.get_lang() bodies = self.xml.findall('{%s}body' % XHTML_NS) if lang == '*': result = OrderedDict() for body in bodies: body_lang = body.attrib.get('{%s}lang' % self.xml_...
identifier_body
stanza.py
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2012 Nathanael C. Fritz This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.stanza import Message from sleekxmpp.util import unicode from sleekxmpp.thirdparty import OrderedDict from sleekxmpp.xmlstream im...
(self, lang=None): if lang is None: lang = self.get_lang() bodies = self.xml.findall('{%s}body' % XHTML_NS) for body in bodies: if body.attrib.get('{%s}lang' % self.xml_ns, self.get_lang()) == lang: self.xml.remove(body) return
del_body
identifier_name
editActor.component.ts
import { Component } from "@angular/core"; import { Actor } from "./actor.entity"; import { Router, ActivatedRoute } from "@angular/router"; import { ActorsService } from "./actors.service"; import { HttpClient } from "app/HttpClient/HttpClient"; @Component({ selector: 'editActor', templateUrl: './editActor.compon...
getActor(id) { this.actorsService.getActor(id).subscribe( actorDetail => { this.actordetail = actorDetail; this.firstnameActor = this.actordetail.firstName; this.lastnameActor = this.actordetail.lastName; this.birthdateActor = this.actordetail.datePerson; this.natio...
{ let personId = activatedRoute.snapshot.params['id']; this.getActor(personId); }
identifier_body
editActor.component.ts
import { Component } from "@angular/core"; import { Actor } from "./actor.entity"; import { Router, ActivatedRoute } from "@angular/router"; import { ActorsService } from "./actors.service"; import { HttpClient } from "app/HttpClient/HttpClient"; @Component({ selector: 'editActor', templateUrl: './editActor.compon...
(private http: HttpClient, private router: Router, activatedRoute: ActivatedRoute, private actorsService: ActorsService) { let personId = activatedRoute.snapshot.params['id']; this.getActor(personId); } getActor(id) { this.actorsService.getActor(id).subscribe( actorDetail => { this.actor...
constructor
identifier_name
editActor.component.ts
import { Component } from "@angular/core"; import { Actor } from "./actor.entity"; import { Router, ActivatedRoute } from "@angular/router"; import { ActorsService } from "./actors.service"; import { HttpClient } from "app/HttpClient/HttpClient"; @Component({ selector: 'editActor', templateUrl: './editActor.compon...
firstnameActor: string = ''; lastnameActor: string = ''; birthdateActor: string = ''; formData: Actor = { personId: 0, firstName: "Cargando...", lastName: "Cargando...", datePerson: "Cargando...", nationality: "Cargando...", photo: "https://localhost:8443/"+this.actordetail.photo }; ...
random_line_split
admin.py
from urllib import quote from django import forms from django.contrib import admin from django.db import models from django.utils.html import escape, format_html from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from pycon.sponsorship.models import SponsorLevel, Spo...
def save_related(self, request, form, formsets, change): super(SponsorAdmin, self).save_related(request, form, formsets, change) obj = form.instance obj.save() class BenefitAdmin(admin.ModelAdmin): inlines = [BenefitLevelInline, BenefitPackageInline] list_display = ['name', 'type...
benefit_name = benefit['name'] field_name = benefit['field_name'] def func_generator(ben): def column_func(obj): return getattr(obj, ben['field_name']) column_func.short_description = ben['column_title'] column_func.boolean = True column_f...
conditional_block
admin.py
from urllib import quote from django import forms from django.contrib import admin from django.db import models from django.utils.html import escape, format_html from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from pycon.sponsorship.models import SponsorLevel, Spo...
column_func.short_description = ben['column_title'] column_func.boolean = True column_func.admin_order_field = ben['field_name'] return column_func list_display.append(func_generator(benefit)) list_filter.append(field_name) def save_related(self, req...
return getattr(obj, ben['field_name'])
identifier_body
admin.py
from urllib import quote from django import forms from django.contrib import admin from django.db import models from django.utils.html import escape, format_html from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from pycon.sponsorship.models import SponsorLevel, Spo...
actions = [email_selected_sponsors_action] list_per_page = 1000000 # Do not limit sponsors per page, just one big page fieldsets = [ (None, { "fields": ["name", "applicant", "level", ("active", "approval_time"), "packages", "external_url", "display_url", "twitter_...
save_on_top = True
random_line_split
admin.py
from urllib import quote from django import forms from django.contrib import admin from django.db import models from django.utils.html import escape, format_html from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from pycon.sponsorship.models import SponsorLevel, Spo...
(obj): return getattr(obj, ben['field_name']) column_func.short_description = ben['column_title'] column_func.boolean = True column_func.admin_order_field = ben['field_name'] return column_func list_display.append(func_generator(benefit)) l...
column_func
identifier_name
redundant_field_names.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::{meets_msrv, msrvs}; use rustc_ast::ast::{Expr, ExprKind}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_middle::lint::in_external_macro; use rustc_semver::RustcVersion; use rustc_session::{declare_tool_lint...
REDUNDANT_FIELD_NAMES, field.span, "redundant field names in struct initialization", "replace it with", field.ident.to_string(), Applicability::MachineA...
{ if !meets_msrv(self.msrv.as_ref(), &msrvs::FIELD_INIT_SHORTHAND) { return; } if in_external_macro(cx.sess, expr.span) { return; } if let ExprKind::Struct(ref se) = expr.kind { for field in &se.fields { if field.is_shorthand {...
identifier_body
redundant_field_names.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::{meets_msrv, msrvs}; use rustc_ast::ast::{Expr, ExprKind}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_middle::lint::in_external_macro; use rustc_semver::RustcVersion; use rustc_session::{declare_tool_lint...
if let ExprKind::Struct(ref se) = expr.kind { for field in &se.fields { if field.is_shorthand { continue; } if let ExprKind::Path(None, path) = &field.expr.kind { if path.segments.len() == 1 ...
{ return; }
conditional_block
redundant_field_names.rs
use clippy_utils::diagnostics::span_lint_and_sugg;
use rustc_middle::lint::in_external_macro; use rustc_semver::RustcVersion; use rustc_session::{declare_tool_lint, impl_lint_pass}; declare_clippy_lint! { /// ### What it does /// Checks for fields in struct literals where shorthands /// could be used. /// /// ### Why is this bad? /// If the fie...
use clippy_utils::{meets_msrv, msrvs}; use rustc_ast::ast::{Expr, ExprKind}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass};
random_line_split
redundant_field_names.rs
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::{meets_msrv, msrvs}; use rustc_ast::ast::{Expr, ExprKind}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_middle::lint::in_external_macro; use rustc_semver::RustcVersion; use rustc_session::{declare_tool_lint...
{ msrv: Option<RustcVersion>, } impl RedundantFieldNames { #[must_use] pub fn new(msrv: Option<RustcVersion>) -> Self { Self { msrv } } } impl_lint_pass!(RedundantFieldNames => [REDUNDANT_FIELD_NAMES]); impl EarlyLintPass for RedundantFieldNames { fn check_expr(&mut self, cx: &EarlyConte...
RedundantFieldNames
identifier_name
end-node-no-outgoing-connection-validator.ts
import { IContainer } from '../../model/IContainer'; import { Process } from '../../model/Process'; import { ProcessEnd } from '../../model/ProcessEnd'; import { Type } from '../../util/type'; import { ElementValidatorBase } from '../element-validator-base'; import { ValidationMessage } from '../validation-message'; im...
return ValidationResult.VALID; } }
{ return new ValidationResult(ValidationMessage.ERROR_PROCESS_END_OUTGOING_CONNECTION, false, invalidNodes); }
conditional_block
end-node-no-outgoing-connection-validator.ts
import { IContainer } from '../../model/IContainer'; import { Process } from '../../model/Process'; import { ProcessEnd } from '../../model/ProcessEnd'; import { Type } from '../../util/type'; import { ElementValidatorBase } from '../element-validator-base'; import { ValidationMessage } from '../validation-message'; im...
@Validator(Process) export class EndNodeNoOutgoingConnectionValidator extends ElementValidatorBase<Process> { public validate(element: Process, contents: IContainer[]): ValidationResult { const invalidNodes: IContainer[] = contents .filter((element: IContainer) => Type.is(element, ProcessEnd)) ...
random_line_split
end-node-no-outgoing-connection-validator.ts
import { IContainer } from '../../model/IContainer'; import { Process } from '../../model/Process'; import { ProcessEnd } from '../../model/ProcessEnd'; import { Type } from '../../util/type'; import { ElementValidatorBase } from '../element-validator-base'; import { ValidationMessage } from '../validation-message'; im...
extends ElementValidatorBase<Process> { public validate(element: Process, contents: IContainer[]): ValidationResult { const invalidNodes: IContainer[] = contents .filter((element: IContainer) => Type.is(element, ProcessEnd)) .filter((element: ProcessEnd) => element.outgoingConnectio...
EndNodeNoOutgoingConnectionValidator
identifier_name
plain.py
import os import shutil import filecmp from dotgit.plugin import Plugin class PlainPlugin(Plugin): def __init__(self, *args, **kwargs): self.hard = kwargs.pop('hard', False) super().__init__(*args, **kwargs) def setup_data(self): pass # copies file from outside the repo to the r...
(self, source, dest): if self.hard: shutil.copy2(source, dest) else: os.symlink(source, dest) # if not in hard mode, checks if symlink points to file in repo # if in hard mode, a bit-by-bit comparison is made to compare the files def samefile(self, repo_file, ext_fil...
remove
identifier_name
plain.py
import os import shutil import filecmp from dotgit.plugin import Plugin class PlainPlugin(Plugin): def __init__(self, *args, **kwargs): self.hard = kwargs.pop('hard', False) super().__init__(*args, **kwargs) def setup_data(self): pass # copies file from outside the repo to the r...
else: os.symlink(source, dest) # if not in hard mode, checks if symlink points to file in repo # if in hard mode, a bit-by-bit comparison is made to compare the files def samefile(self, repo_file, ext_file): if self.hard: if os.path.islink(ext_file): ...
shutil.copy2(source, dest)
conditional_block
plain.py
import os import shutil import filecmp
from dotgit.plugin import Plugin class PlainPlugin(Plugin): def __init__(self, *args, **kwargs): self.hard = kwargs.pop('hard', False) super().__init__(*args, **kwargs) def setup_data(self): pass # copies file from outside the repo to the repo def apply(self, source, dest): ...
random_line_split
plain.py
import os import shutil import filecmp from dotgit.plugin import Plugin class PlainPlugin(Plugin):
# if not in hard mode, checks if symlink points to file in repo # if in hard mode, a bit-by-bit comparison is made to compare the files def samefile(self, repo_file, ext_file): if self.hard: if os.path.islink(ext_file): return False if not os.path.exists(repo_...
def __init__(self, *args, **kwargs): self.hard = kwargs.pop('hard', False) super().__init__(*args, **kwargs) def setup_data(self): pass # copies file from outside the repo to the repo def apply(self, source, dest): shutil.copy2(source, dest) # if not in hard mode, crea...
identifier_body
snmpv3.rs
use crate::rparser::*; use crate::snmp::parse_pdu_enveloppe_version; use crate::{gen_get_variants, Variant}; use snmp_parser::{parse_snmp_v3, SecurityModel}; pub struct SNMPv3Builder {} impl RBuilder for SNMPv3Builder { fn build(&self) -> Box<dyn RParser>
fn get_l4_probe(&self) -> Option<ProbeL4> { Some(snmpv3_probe) } } pub struct SNMPv3Parser<'a> { _name: Option<&'a [u8]>, version: u8, req_flags: u8, security_model: SecurityModel, } impl<'a> From<SecurityModel> for Variant<'a> { fn from(input: SecurityModel) -> Self { inp...
{ Box::new(SNMPv3Parser::new(b"SNMPv3")) }
identifier_body
snmpv3.rs
use crate::rparser::*; use crate::snmp::parse_pdu_enveloppe_version; use crate::{gen_get_variants, Variant}; use snmp_parser::{parse_snmp_v3, SecurityModel}; pub struct SNMPv3Builder {} impl RBuilder for SNMPv3Builder { fn build(&self) -> Box<dyn RParser> { Box::new(SNMPv3Parser::new(b"SNMPv3")) } ...
(&mut self, data: &[u8], _direction: Direction) -> ParseResult { match parse_snmp_v3(data) { Ok((_rem, r)) => { debug!("parse_snmp_v3: {:?}", r); self.version = r.version as u8; self.req_flags = r.header_data.msg_flags; self.security_mo...
parse_l4
identifier_name
snmpv3.rs
use crate::rparser::*; use crate::snmp::parse_pdu_enveloppe_version; use crate::{gen_get_variants, Variant}; use snmp_parser::{parse_snmp_v3, SecurityModel}; pub struct SNMPv3Builder {} impl RBuilder for SNMPv3Builder { fn build(&self) -> Box<dyn RParser> { Box::new(SNMPv3Parser::new(b"SNMPv3")) } ...
} } gen_get_variants! {SNMPv3Parser, "snmpv3.", version => into, encrypted => |s| { Some(Variant::Bool(s.req_flags & 0b010 != 0)) }, security_model => into, } } pub fn snmpv3_probe(i: &[u8], _l4info: &L4Info) -> ProbeResult { if i.len() <= 2 { return ProbeRes...
{ warn!("parse_snmp_v3 failed: {:?}", e); ParseResult::Error }
conditional_block
snmpv3.rs
use crate::rparser::*; use crate::snmp::parse_pdu_enveloppe_version; use crate::{gen_get_variants, Variant}; use snmp_parser::{parse_snmp_v3, SecurityModel}; pub struct SNMPv3Builder {} impl RBuilder for SNMPv3Builder { fn build(&self) -> Box<dyn RParser> { Box::new(SNMPv3Parser::new(b"SNMPv3")) } ...
version: u8, req_flags: u8, security_model: SecurityModel, } impl<'a> From<SecurityModel> for Variant<'a> { fn from(input: SecurityModel) -> Self { input.0.into() } } impl<'a> SNMPv3Parser<'a> { pub fn new(name: &'a [u8]) -> SNMPv3Parser<'a> { SNMPv3Parser { _name: ...
} pub struct SNMPv3Parser<'a> { _name: Option<&'a [u8]>,
random_line_split
generateProptypes.ts
import * as path from 'path'; import * as fse from 'fs-extra'; import * as ttp from 'typescript-to-proptypes'; import * as prettier from 'prettier'; import * as globCallback from 'glob'; import { promisify } from 'util'; import * as _ from 'lodash'; import { fixBabelGeneratorIssues, fixLineEndings } from '../docs/scrip...
} return undefined; }, }); if (proptypes.body.length === 0) { return GenerateResult.NoComponent; } proptypes.body.forEach(component => { component.types.forEach(prop => { if (prop.name === 'classes' && prop.jsDoc) { prop.jsDoc += '\nSee [CSS API](#css) below for more deta...
random_line_split
generateProptypes.ts
import * as path from 'path'; import * as fse from 'fs-extra'; import * as ttp from 'typescript-to-proptypes'; import * as prettier from 'prettier'; import * as globCallback from 'glob'; import { promisify } from 'util'; import * as _ from 'lodash'; import { fixBabelGeneratorIssues, fixLineEndings } from '../docs/scrip...
( tsFile: string, jsFile: string, program: ttp.ts.Program, ): Promise<GenerateResult> { const proptypes = ttp.parseFromProgram(tsFile, program, { shouldResolveObject: ({ name }) => { if (name.toLowerCase().endsWith('classes') || name === 'theme' || name.endsWith('Props')) { return false; ...
generateProptypes
identifier_name
generateProptypes.ts
import * as path from 'path'; import * as fse from 'fs-extra'; import * as ttp from 'typescript-to-proptypes'; import * as prettier from 'prettier'; import * as globCallback from 'glob'; import { promisify } from 'util'; import * as _ from 'lodash'; import { fixBabelGeneratorIssues, fixLineEndings } from '../docs/scrip...
console.log('--- Summary ---'); const groups = _.groupBy(results, x => x); _.forOwn(groups, (count, key) => { console.log('%s: %d', GenerateResult[(key as unknown) as GenerateResult], count.length); }); console.log('Total: %d', results.length); } run().catch(error => { console.error(error); proce...
{ files.forEach((file, index) => { console.log('%s - %s', GenerateResult[results[index]], path.basename(file, '.d.ts')); }); }
conditional_block
generateProptypes.ts
import * as path from 'path'; import * as fse from 'fs-extra'; import * as ttp from 'typescript-to-proptypes'; import * as prettier from 'prettier'; import * as globCallback from 'glob'; import { promisify } from 'util'; import * as _ from 'lodash'; import { fixBabelGeneratorIssues, fixLineEndings } from '../docs/scrip...
const folderName = path.basename(path.dirname(filePath)); const fileName = path.basename(filePath, '.d.ts'); return fileName === folderName; }); const program = ttp.createProgram(files, tsconfig); const promises = files.map<Promise<GenerateResult>>(async tsFile => { const jsFile = tsFil...
{ // Matches files where the folder and file both start with uppercase letters // Example: AppBar/AppBar.d.ts const allFiles = await Promise.all( [ path.resolve(__dirname, '../packages/material-ui/src'), path.resolve(__dirname, '../packages/material-ui-lab/src'), ].map(folderPath => glo...
identifier_body
spectralcoord.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from asdf.tags.core import NDArrayType from astropy.coordinates.spectral_coordinate import SpectralCoord from astropy.io.misc.asdf.types import AstropyType from astropy.io.misc.asdf.tags.unit.unit import UnitType __all__ = ['Spec...
if spec_coord.target is not None: node['target'] = spec_coord.target return node raise TypeError(f"'{spec_coord}' is not a valid SpectralCoord") @classmethod def from_tree(cls, node, ctx): if isinstance(node, SpectralCoord): return node ...
node['observer'] = spec_coord.observer
conditional_block
spectralcoord.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from asdf.tags.core import NDArrayType from astropy.coordinates.spectral_coordinate import SpectralCoord from astropy.io.misc.asdf.types import AstropyType from astropy.io.misc.asdf.tags.unit.unit import UnitType __all__ = ['Spec...
(cls, node, ctx): if isinstance(node, SpectralCoord): return node unit = UnitType.from_tree(node['unit'], ctx) value = node['value'] observer = node['observer'] if 'observer' in node else None target = node['target'] if 'observer' in node else None if isinsta...
from_tree
identifier_name
spectralcoord.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from asdf.tags.core import NDArrayType from astropy.coordinates.spectral_coordinate import SpectralCoord from astropy.io.misc.asdf.types import AstropyType from astropy.io.misc.asdf.tags.unit.unit import UnitType __all__ = ['Spec...
@classmethod def from_tree(cls, node, ctx): if isinstance(node, SpectralCoord): return node unit = UnitType.from_tree(node['unit'], ctx) value = node['value'] observer = node['observer'] if 'observer' in node else None target = node['target'] if 'observer' in...
""" ASDF tag implementation used to serialize/derialize SpectralCoord objects """ name = 'coordinates/spectralcoord' types = [SpectralCoord] version = '1.0.0' @classmethod def to_tree(cls, spec_coord, ctx): node = {} if isinstance(spec_coord, SpectralCoord): node...
identifier_body
spectralcoord.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from asdf.tags.core import NDArrayType from astropy.coordinates.spectral_coordinate import SpectralCoord from astropy.io.misc.asdf.types import AstropyType from astropy.io.misc.asdf.tags.unit.unit import UnitType __all__ = ['Spec...
node['unit'] = spec_coord.unit if spec_coord.observer is not None: node['observer'] = spec_coord.observer if spec_coord.target is not None: node['target'] = spec_coord.target return node raise TypeError(f"'{spec_coord}' is not a val...
node['value'] = spec_coord.value
random_line_split
index.js
/* global React */ /* global ReactQuill */ 'use strict'; var Editor = React.createClass({ getInitialState: function() { return { theme: 'snow', enabled: true, readOnly: false, value: '<h1>It works!</h1>', events: [] }; }, formatRange: function(range) { return range ? [range.start, range.en...
'Selection: ('+selection+')' ) ) ); }, renderSidebar: function() { return ( React.DOM.div({ style: { overflow:'hidden', float:'right' }}, React.DOM.textarea({ style: { display:'block', width:300, height:300 }, value: this.state.value, onChange: this.onTextareaChange }), ...
random_line_split
select.jqueryui.js
/*! jQuery UI styling wrapper for Select * ©2018 SpryMedia Ltd - datatables.net/license */ (function( factory ){ if ( typeof define === 'function' && define.amd ) { // AMD define( ['jquery', 'datatables.net-jqui', 'datatables.net-select'], function ( $ ) { return factory( $, window, document ); } ); } el...
$ = require('datatables.net-jqui')(root, $).$; } if ( ! $.fn.dataTable.select ) { require('datatables.net-select')(root, $); } return factory( $, root, root.document ); }; } else { // Browser factory( jQuery, window, document ); } }(function( $, window, document, undefined ) { return $.f...
if ( ! $ || ! $.fn.dataTable ) {
random_line_split
select.jqueryui.js
/*! jQuery UI styling wrapper for Select * ©2018 SpryMedia Ltd - datatables.net/license */ (function( factory ){ if ( typeof define === 'function' && define.amd ) { // AMD define( ['jquery', 'datatables.net-jqui', 'datatables.net-select'], function ( $ ) { return factory( $, window, document ); } ); } el...
}(function( $, window, document, undefined ) { return $.fn.dataTable; }));
// Browser factory( jQuery, window, document ); }
conditional_block
outdated-include-devdependencies.js
var common = require("../common-tap.js") var test = require("tap").test var npm = require("../../") var mkdirp = require("mkdirp") var rimraf = require("rimraf") var mr = require("npm-registry-mock")
mkdirp.sync(cache) test("includes devDependencies in outdated", function (t) { process.chdir(pkg) mr({port : common.port}, function (er, s) { npm.load({cache: cache, registry: common.registry}, function () { npm.outdated(function (er, d) { t.equal("1.5.1", d[0][3]) s.close() t.end...
var path = require("path") // config var pkg = path.resolve(__dirname, "outdated-include-devdependencies") var cache = path.resolve(pkg, "cache")
random_line_split
xc_private_method_lib.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 ...
Variant1(x) | Variant2(x) => x } } }
random_line_split
xc_private_method_lib.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 ...
{ Variant1(int), Variant2(int) } impl Enum { fn static_meth_enum() -> Enum { Variant2(10) } fn meth_enum(&self) -> int { match *self { Variant1(x) | Variant2(x) => x } } }
Enum
identifier_name
xc_private_method_lib.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 meth_struct(&self) -> int { self.x } } pub enum Enum { Variant1(int), Variant2(int) } impl Enum { fn static_meth_enum() -> Enum { Variant2(10) } fn meth_enum(&self) -> int { match *self { Variant1(x) | Variant2(x) => x } } }...
{ Struct { x: 1 } }
identifier_body
directive_bind_html_with_js.js
(function () { "use strict"; angular.module('BuDirectives', []). directive('bindHtmlWithJs', ['$sce', '$parse', function ($sce, $parse) { /** * It removes script tags from html and inserts it into DOM. * * Testing: * html += '<script>alert(1234)</script><script type="text/javascript">alert(1234...
else { // doesn't work on ie... try { script.appendChild(document.createTextNode(element.innerText)); } // IE has funky script nodes catch (e) { script.text = element.innerText; } setTimeout(function () {doneWrapper()}, 10); } body.appendChild(script); ...
{ script.src = element.src; script.async = element.async; script.onload = script.onerror = function () { doneWrapper(); }; }
conditional_block
directive_bind_html_with_js.js
(function () { "use strict"; angular.module('BuDirectives', []). directive('bindHtmlWithJs', ['$sce', '$parse', function ($sce, $parse) { /** * It removes script tags from html and inserts it into DOM. * * Testing: * html += '<script>alert(1234)</script><script type="text/javascript">alert(1234...
return html; } /** * It's taken from AngularJS' jsonpReq function. * It's not ie < 9 compatible. * @param {DOMElement} element */ function evalScript(element) { var script = document.createElement('script'), body = document.body, doneWrapper = function() { script.on...
random_line_split
directive_bind_html_with_js.js
(function () { "use strict"; angular.module('BuDirectives', []). directive('bindHtmlWithJs', ['$sce', '$parse', function ($sce, $parse) { /** * It removes script tags from html and inserts it into DOM. * * Testing: * html += '<script>alert(1234)</script><script type="text/javascript">alert(1234...
$scope.$watch(getStringValue, function bindHtmlWithJsWatchAction(value) { var html = value ? $sce.getTrustedHtml(parsed($scope)) : ''; if (html) { html = handleScripts(html); } element.html(html || ''); }); }; }]). /* This filter is for demo only */ filter('trustAsHtml', ['$sce', f...
{ return (parsed($scope) || '').toString(); }
identifier_body
directive_bind_html_with_js.js
(function () { "use strict"; angular.module('BuDirectives', []). directive('bindHtmlWithJs', ['$sce', '$parse', function ($sce, $parse) { /** * It removes script tags from html and inserts it into DOM. * * Testing: * html += '<script>alert(1234)</script><script type="text/javascript">alert(1234...
(element) { var script = document.createElement('script'), body = document.body, doneWrapper = function() { script.onload = script.onerror = null; body.removeChild(script); }; script.type = 'text/javascript'; if (element.src) { script.src = element.src; script.as...
evalScript
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class
(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='TrackedPosition', fields=[ ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID...
Migration
identifier_name
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration):
migrations.CreateModel( name='TrackingKey', fields=[ ('key', models.CharField(max_length=32, primary_key=True, serialize=False)), ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)), ], options={ }, b...
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='TrackedPosition', fields=[ ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)), ...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
('start_time', models.DateTimeField()), ('end_time', models.DateTimeField(null=True, blank=True)), ('active', models.BooleanField(default=True)), ('viewkey', models.CharField(max_length=32)), ('is_cleaned', models.BooleanField(default=False...
fields=[ ('id', models.AutoField(serialize=False, auto_created=True, verbose_name='ID', primary_key=True)),
random_line_split
test_javac_plugin_integration.py
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from unittest import skipIf from pants_test.backend.jvm.tasks.jvm_compile.base_compile_integration_test import BaseCompileIT from pants_test.backend.jvm.tasks.missing_jvm_check import is_...
(self, expected_args, config, target): with self.temporary_workdir() as workdir: pants_run = self.run_pants_with_workdir( ["compile", f"{self.example_dir}:{target}"], workdir, config ) self.assert_success(pants_run) self.assertIn( "SimpleJavacP...
_do_test
identifier_name
test_javac_plugin_integration.py
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from unittest import skipIf from pants_test.backend.jvm.tasks.jvm_compile.base_compile_integration_test import BaseCompileIT from pants_test.backend.jvm.tasks.missing_jvm_check import is_...
"javac_plugins": ["simple_javac_plugin"], "javac_plugin_args": {"simple_javac_plugin": args}, } } # Must compile the plugin explicitly, since there's no dep. self._do_test(args, config, "global") def _do_test_local_with_global_args(self, args): ...
example_dir = "examples/src/java/org/pantsbuild/example/javac/plugin" def _do_test(self, expected_args, config, target): with self.temporary_workdir() as workdir: pants_run = self.run_pants_with_workdir( ["compile", f"{self.example_dir}:{target}"], workdir, config ) ...
identifier_body
test_javac_plugin_integration.py
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
from unittest import skipIf from pants_test.backend.jvm.tasks.jvm_compile.base_compile_integration_test import BaseCompileIT from pants_test.backend.jvm.tasks.missing_jvm_check import is_missing_jvm @skipIf(is_missing_jvm("1.8"), "no java 1.8 installation on testing machine") class JavacPluginIntegrationTest(BaseCo...
# Licensed under the Apache License, Version 2.0 (see LICENSE).
random_line_split
index.js
var glslifyBundle = require('glslify-bundle') var staticModule = require('static-module') var glslifyDeps = require('glslify-deps') var glslResolve = require('glsl-resolve') var through = require('through2') var nodeResolve = require('resolve') var extend = require('xtend') var path = requi...
module.exports.bundle = bundle function transform(jsFilename, browserifyOpts) { if (path.extname(jsFilename) === '.json') return through() var streamHasErrored = false // static-module is responsible for replacing any // calls to glslify in your JavaScript with a string // of our choosing – in this case, o...
var fs = require('fs') module.exports = transform
random_line_split
index.js
var glslifyBundle = require('glslify-bundle') var staticModule = require('static-module') var glslifyDeps = require('glslify-deps') var glslResolve = require('glsl-resolve') var through = require('through2') var nodeResolve = require('resolve') var extend = require('xtend') var path = requi...
var transform = require(target) transform(null, source, { post: true }, function(err, data) { if (err) throw err if (data) source = data next() }) } function postDone() { done(null, source, opts.inline ? files.slice(1) : files ...
if (err) return done(err) try { // Turn that dependency tree into a GLSL string, // stringified for use in our JavaScript. var source = glslifyBundle(tree) } catch(e) { return done(e) } // Finally, this applies our --post transforms next() function next() { va...
identifier_body
index.js
var glslifyBundle = require('glslify-bundle') var staticModule = require('static-module') var glslifyDeps = require('glslify-deps') var glslResolve = require('glsl-resolve') var through = require('through2') var nodeResolve = require('resolve') var extend = require('xtend') var path = requi...
(jsFilename, browserifyOpts) { if (path.extname(jsFilename) === '.json') return through() var streamHasErrored = false // static-module is responsible for replacing any // calls to glslify in your JavaScript with a string // of our choosing – in this case, our bundled glslify // shader source. var sm = ...
transform
identifier_name
test.js
/* eslint-env mocha */ var assert = require('assert') var resolveEnv = require('./') var cases = [ ['Simple test', 'Simple test', {}], ['Hello $NAME!', 'Hello world!', { NAME: 'world' }], ['[ $a1, $a2 ]', '[ 4, 8 ]', { a1: '4', a2: '8' }], ['http://$HOST:$PORT/', 'http://google.com:80/', { HOST: 'google.com',...
}) })
random_line_split
mod.rs
use epoll::*; use error::Result; use handler::*; use libc_sys::{sched_param, sched_setscheduler, rlimit, prlimit, RLIMIT_RTPRIO}; pub use nix::sys::signal::{Signal, SigSet}; use nix::sys::signalfd::{SignalFd, SFD_NONBLOCK}; use nix::{unistd, Errno}; use prop::*; use std::os::unix::io::AsRawFd; mod builder; pub use se...
(mut prop: P, sig_h: S, sig_mask: SigSet, sched_opt: Option<(sched_policy, sched_param)>) -> Result<()> { sched_opt.map(|(sched_policy, sched_param_i)| { // set sched policy unsafe { let mut rlim = rlimit { rlim_cur: sched_param_i.sched_priority as u64, rlim_max: sched_param...
run
identifier_name
mod.rs
use epoll::*; use error::Result; use handler::*; use libc_sys::{sched_param, sched_setscheduler, rlimit, prlimit, RLIMIT_RTPRIO}; pub use nix::sys::signal::{Signal, SigSet}; use nix::sys::signalfd::{SignalFd, SFD_NONBLOCK}; use nix::{unistd, Errno}; use prop::*; use std::os::unix::io::AsRawFd; mod builder; pub use se...
}
{ if ev.data == self.sigfd.as_raw_fd() as u64 { match self.sigfd.read_signal() { Ok(Some(sig)) => { self.sig_h.on_next(Signal::from_c_int(sig.ssi_signo as i32).unwrap()); match self.sig_h.next() { DaemonCmd::Reload => self.prop.reload(), DaemonCmd::Shutdown ...
identifier_body
mod.rs
use epoll::*; use error::Result; use handler::*; use libc_sys::{sched_param, sched_setscheduler, rlimit, prlimit, RLIMIT_RTPRIO}; pub use nix::sys::signal::{Signal, SigSet}; use nix::sys::signalfd::{SignalFd, SFD_NONBLOCK}; use nix::{unistd, Errno}; use prop::*;
mod builder; pub use self::builder::sched_policy; pub use libc_sys::{SCHED_FIFO, SCHED_RR, SCHED_OTHER}; /// WIP: New-style daemon /// http://man7.org/linux/man-pages/man7/daemon.7.html /// /// Missing: /// - Force exposing daemon interface via D-Bus along with a D-Bus service activation /// configuration file /// ...
use std::os::unix::io::AsRawFd;
random_line_split
dynamic_loading.py
import angr import claripy import logging l = logging.getLogger('angr.procedures.win32.dynamic_loading') class LoadLibraryA(angr.SimProcedure): def
(self, lib_ptr): lib = self.state.mem[lib_ptr].string.concrete return self.load(lib) def load(self, lib): if '.' not in lib: lib += '.dll' loaded = self.project.loader.dynamic_load(lib) if loaded is None: return 0 # Add simprocedures ...
run
identifier_name
dynamic_loading.py
import angr import claripy import logging l = logging.getLogger('angr.procedures.win32.dynamic_loading') class LoadLibraryA(angr.SimProcedure): def run(self, lib_ptr): lib = self.state.mem[lib_ptr].string.concrete return self.load(lib) def load(self, lib): if '.' not in lib: ...
def register(self, obj): # can be overridden for instrumentation self.project._register_object(obj) class LoadLibraryExW(LoadLibraryA): def run(self, lib_ptr, flag1, flag2): lib = self.state.mem[lib_ptr].wstring.concrete return self.load(lib) # if you subclass LoadLibraryA to provide r...
random_line_split
dynamic_loading.py
import angr import claripy import logging l = logging.getLogger('angr.procedures.win32.dynamic_loading') class LoadLibraryA(angr.SimProcedure): def run(self, lib_ptr): lib = self.state.mem[lib_ptr].string.concrete return self.load(lib) def load(self, lib): if '.' not in lib: ...
if sym is None: l.warning("GetProcAddress: object %s does not contain %s", obj.provides, name) return 0 sym = sym.resolve_forwarder() if sym is None: l.warning("GetProcAddress: forwarding failed for %s from %s", name, obj.provides) return 0 ...
sym = obj.get_symbol(name + suffix) if sym is not None: name = name + suffix break
conditional_block
dynamic_loading.py
import angr import claripy import logging l = logging.getLogger('angr.procedures.win32.dynamic_loading') class LoadLibraryA(angr.SimProcedure): def run(self, lib_ptr): lib = self.state.mem[lib_ptr].string.concrete return self.load(lib) def load(self, lib):
def register(self, obj): # can be overridden for instrumentation self.project._register_object(obj) class LoadLibraryExW(LoadLibraryA): def run(self, lib_ptr, flag1, flag2): lib = self.state.mem[lib_ptr].wstring.concrete return self.load(lib) # if you subclass LoadLibraryA to provide...
if '.' not in lib: lib += '.dll' loaded = self.project.loader.dynamic_load(lib) if loaded is None: return 0 # Add simprocedures for obj in loaded: self.register(obj) l.debug("Loaded %s", lib) return self.project.loader.find_object(lib...
identifier_body
htmlparagraphelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; use dom::bindings::js::Root; use dom::bindings:...
document: &Document) -> Root<HTMLParagraphElement> { Node::reflect_node(box HTMLParagraphElement::new_inherited(local_name, prefix, document), document, HTMLParagraphElementBinding::Wrap) } }
random_line_split
htmlparagraphelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; use dom::bindings::js::Root; use dom::bindings:...
{ htmlelement: HTMLElement } impl HTMLParagraphElement { fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLParagraphElement { HTMLParagraphElement { htmlelement: HTMLElement::new_inherite...
HTMLParagraphElement
identifier_name
htmlparagraphelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; use dom::bindings::js::Root; use dom::bindings:...
}
{ Node::reflect_node(box HTMLParagraphElement::new_inherited(local_name, prefix, document), document, HTMLParagraphElementBinding::Wrap) }
identifier_body
tasks.py
# -*- coding: utf-8 -*- """ flask.ext.hippocket.tasks ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013 by Sean Vieira. :license: MIT, see LICENSE for more details. """ from flask import Blueprint, Markup, request, render_template from itertools import chain from os import path from pkgutil import walk_p...
(app, apps_package="apps", module_name="routes", blueprint_name="routes", on_error=None): """Automatically load Blueprints from the specified package and registers them with Flask.""" if not apps_package: raise ValueError("No apps package provided - unable to begin autoload") if isinstance(apps_pa...
autoload
identifier_name
tasks.py
# -*- coding: utf-8 -*- """ flask.ext.hippocket.tasks ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013 by Sean Vieira. :license: MIT, see LICENSE for more details. """ from flask import Blueprint, Markup, request, render_template from itertools import chain from os import path from pkgutil import walk_p...
if isinstance(apps_package, basestring): package_code = import_string(apps_package) else: #: `apps_package` can be the already imported parent package #: (i.e. the following is a licit pattern):: #: #: import app_package #: # do something else with app...
raise ValueError("No apps package provided - unable to begin autoload")
conditional_block
tasks.py
# -*- coding: utf-8 -*- """ flask.ext.hippocket.tasks ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013 by Sean Vieira. :license: MIT, see LICENSE for more details. """ from flask import Blueprint, Markup, request, render_template from itertools import chain from os import path from pkgutil import walk_p...
root = apps_package apps_package = apps_package + u"." if not apps_package.endswith(".") else apps_package if on_error is None: on_error = lambda name: app.logger.warn("Unable to import {name}.".format(name=name)) _to_import = "{base}.{module}.{symbol}" import_template = lambda base: _to_i...
"""Automatically load Blueprints from the specified package and registers them with Flask.""" if not apps_package: raise ValueError("No apps package provided - unable to begin autoload") if isinstance(apps_package, basestring): package_code = import_string(apps_package) else: #: `a...
identifier_body
tasks.py
# -*- coding: utf-8 -*- """ flask.ext.hippocket.tasks ~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013 by Sean Vieira. :license: MIT, see LICENSE for more details. """ from flask import Blueprint, Markup, request, render_template from itertools import chain from os import path from pkgutil import walk_p...
sub_app_import_path = import_template(base=sub_app_name) sub_app = import_string(sub_app_import_path) if isinstance(sub_app, Blueprint): app.register_blueprint(sub_app) else: app.logger.warn(("Failed to register {name} - " "it does not match the ...
random_line_split
startTaskScheduler.ts
import { MONGODB_URI } from "../globals" import * as Agenda from "agenda" import { GitHubInstallation, InstallationSchedulerKeys } from "../db" import { getDB } from "../db/getDB" import logger from "../logger" import { tick } from "../peril" import { runTask } from "./runTask" /** The shape of data sent through peri...
} } } // This is the generic env runtime, it takes in a key from the above keys and // grabs all the installations which have that, then run their tasks async function runSchedulerFunc(key: InstallationSchedulerKeys) { return (_: any, done: any) => { done() // This works on both JSON based, and mongo ...
{ logger.error(`Task ${task} ${dangerfile} failed:`) logger.error(results.fails.map(f => f.message).join("\n")) logger.error(results.markdowns.join("\n")) }
conditional_block
startTaskScheduler.ts
import { MONGODB_URI } from "../globals" import * as Agenda from "agenda" import { GitHubInstallation, InstallationSchedulerKeys } from "../db" import { getDB } from "../db/getDB" import logger from "../logger" import { tick } from "../peril" import { runTask } from "./runTask" /** The shape of data sent through peri...
if (validInstallations.length) { logger.info(`Running the ${key} scheduler for ${validInstallations.length} installs`) } else { logger.info(`Skipping scheduler ${key} because nothing is subscribed`) } // Run the related task for the scheduler validInstallations.forEach(in...
{ return (_: any, done: any) => { done() // This works on both JSON based, and mongo based DBs const db = getDB() // Avoiding declaring this code as async db.getSchedulableInstallationsWithKey(key).then(installations => { const validInstallations = installations.filter(installation => { ...
identifier_body
startTaskScheduler.ts
import { MONGODB_URI } from "../globals" import * as Agenda from "agenda" import { GitHubInstallation, InstallationSchedulerKeys } from "../db" import { getDB } from "../db/getDB" import logger from "../logger" import { tick } from "../peril" import { runTask } from "./runTask" /** The shape of data sent through peri...
(key: InstallationSchedulerKeys) { return (_: any, done: any) => { done() // This works on both JSON based, and mongo based DBs const db = getDB() // Avoiding declaring this code as async db.getSchedulableInstallationsWithKey(key).then(installations => { const validInstallations = installati...
runSchedulerFunc
identifier_name
startTaskScheduler.ts
import { MONGODB_URI } from "../globals" import * as Agenda from "agenda" import { GitHubInstallation, InstallationSchedulerKeys } from "../db" import { getDB } from "../db/getDB" import logger from "../logger" import { tick } from "../peril" import { runTask } from "./runTask" /** The shape of data sent through peri...
const taskDangerfiles = installation.tasks[task] if (!taskDangerfiles) { logger.error(`Could not find the task: ${task} on installation ${installation.iID}`) logger.error(`All tasks: ${Object.keys(installation.tasks)}`) return } // Let tasks also be an array if you want, sure, why not? const dang...
*/ export const runTaskForInstallation = async (installation: GitHubInstallation, task: string, data: any) => { logger.info(`Running task ${task} for ${installation.login}:`)
random_line_split
gatefilter.py
""" gatefilter.py Driver function that creates an ARTView display and initiates Gatefilter. """ import os import sys from ..core import Variable, QtGui, QtCore from ..components import RadarDisplay, Menu from ._common import _add_all_advanced_tools, _parse_dir, _parse_field from ..plugins import GateFilter def
(DirIn=None, filename=None, field=None): """ artview execution for filtering gates radar display """ DirIn = _parse_dir(DirIn) app = QtGui.QApplication(sys.argv) # start Menu and initiate Vradar menu = Menu(DirIn, filename, mode=("Radar",), name="Menu") Vradar = menu.Vradar field ...
run
identifier_name
gatefilter.py
""" gatefilter.py Driver function that creates an ARTView display and initiates Gatefilter.
from ..core import Variable, QtGui, QtCore from ..components import RadarDisplay, Menu from ._common import _add_all_advanced_tools, _parse_dir, _parse_field from ..plugins import GateFilter def run(DirIn=None, filename=None, field=None): """ artview execution for filtering gates radar display """ Dir...
""" import os import sys
random_line_split
gatefilter.py
""" gatefilter.py Driver function that creates an ARTView display and initiates Gatefilter. """ import os import sys from ..core import Variable, QtGui, QtCore from ..components import RadarDisplay, Menu from ._common import _add_all_advanced_tools, _parse_dir, _parse_field from ..plugins import GateFilter def run(...
menu.addLayoutWidget(filt) # add graphical starts _add_all_advanced_tools(menu) menu.setGeometry(0, 0, 500, 300) # start program app.exec_()
""" artview execution for filtering gates radar display """ DirIn = _parse_dir(DirIn) app = QtGui.QApplication(sys.argv) # start Menu and initiate Vradar menu = Menu(DirIn, filename, mode=("Radar",), name="Menu") Vradar = menu.Vradar field = _parse_field(Vradar.value, field) # st...
identifier_body
L0UITestFailRun.ts
import ma = require('vsts-task-lib/mock-answer'); import tmrm = require('vsts-task-lib/mock-run'); import path = require('path'); let taskPath = path.join(__dirname, '..', 'vsmobilecentertest.js'); let tmr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath); tmr.setInput('enablePrepare', 'false'); tmr.setInput('...
tmr.setInput('devices', '1234abcd'); tmr.setInput('series', 'master'); tmr.setInput('dsymDir', '/path/to/dsym'); tmr.setInput('locale', 'user'); tmr.setInput('userDefinedLocale', 'nc_US'); tmr.setInput('artifactsDir', '/path/to/artifactsDir'); tmr.setInput('framework', 'uitest'); tmr.setInput('uitestBuildDir', '/path/t...
random_line_split
test_migrate_nova_auth.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack 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 requ...
(self): super(MigrateNovaAuth, self).setUp() self.config([test.etcdir('keystone.conf.sample'), test.testsdir('test_overrides.conf'), test.testsdir('backend_sql.conf')]) sql_util.setup_test_database() self.identity_api = identity_sql.Identity() ...
setUp
identifier_name
test_migrate_nova_auth.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack 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 requ...
for user in ['user1', 'user2', 'user3', 'user4']: users[user] = self.identity_api.get_user_by_name(user) tenants = {} for tenant in ['proj1', 'proj2', 'proj4']: tenants[tenant] = self.identity_api.get_tenant_by_name(tenant) membership_map = { 'user1'...
def setUp(self): super(MigrateNovaAuth, self).setUp() self.config([test.etcdir('keystone.conf.sample'), test.testsdir('test_overrides.conf'), test.testsdir('backend_sql.conf')]) sql_util.setup_test_database() self.identity_api = identity_sql.Iden...
identifier_body
test_migrate_nova_auth.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack 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 requ...
roles = self.identity_api.list_roles() role_names = set([role['name'] for role in roles]) self.assertEqual(role_names, set(['role2', 'role1', 'role3'])) assignment_map = { 'user1': {'proj1': ['role1', 'role2']}, 'user2': {'proj1': ['role1'], 'proj2': ['role1', ...
access = '%s:%s' % (tenant_id, ec2_cred['access_key']) cred = self.ec2_api.get_credential(access) actual = cred['secret'] expected = ec2_cred['secret_key'] self.assertEqual(expected, actual)
conditional_block
test_migrate_nova_auth.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack 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 requ...
for ec2_cred in FIXTURE['ec2_credentials']: user_id = users[ec2_cred['user_id']]['id'] for tenant_id in self.identity_api.get_tenants_for_user(user_id): access = '%s:%s' % (tenant_id, ec2_cred['access_key']) cred = self.ec2_api.get_credential(access) ...
random_line_split
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
} impl BlobMethods for Blob { // https://dev.w3.org/2006/webapi/FileAPI/#dfn-size fn Size(&self) -> u64 { match self.bytes { None => 0, Some(ref bytes) => bytes.len() as u64 } } // https://dev.w3.org/2006/webapi/FileAPI/#dfn-type fn Type(&self) -> DOMString ...
impl Blob { pub fn read_out_buffer(&self, send: Sender<Vec<u8>>) { send.send(self.bytes.clone().unwrap_or(vec![])).unwrap(); }
random_line_split
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
(string: &DOMString) -> bool { // Step 5.1 in Sec 5.1 of File API spec // http://dev.w3.org/2006/webapi/FileAPI/#constructorBlob return string.chars().all(|c| { c >= '\x20' && c <= '\x7E' }) } impl Blob { pub fn new_inherited(global: GlobalRef, type_: BlobTypeId, bytes: Option<...
is_ascii_printable
identifier_name
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
// Step 2 self.isClosed_.set(true); // TODO Step 3 if Blob URL Store is implemented } } impl FileDerived for Blob { fn is_file(&self) -> bool { match self.type_ { BlobTypeId::File => true, _ => false } } }
{ return; }
conditional_block
blob.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::BlobBinding; use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;...
} impl BlobMethods for Blob { // https://dev.w3.org/2006/webapi/FileAPI/#dfn-size fn Size(&self) -> u64 { match self.bytes { None => 0, Some(ref bytes) => bytes.len() as u64 } } // https://dev.w3.org/2006/webapi/FileAPI/#dfn-type fn Type(&self) -> DOMString...
{ send.send(self.bytes.clone().unwrap_or(vec![])).unwrap(); }
identifier_body
index.js
//index.js const AV = require('../../libs/av-weapp-min.js') var app = getApp() Page({ data: { motto: 'Hello World', userInfo: {} }, //事件处理函数 bindViewTap: function() { wx.navigateTo({ url: '../logs/logs' }) }, onLoad: function() { console.log('onLoad') this.saveUser() }, saveUser() {
hat = this //调用应用实例的方法获取全局数据 app.getUserInfo(function(userInfo) { //update data that.setData({ userInfo: userInfo }) wx.setStorage({ key: "userInfo", data: userInfo }) let nickName = that.data.userInfo.nickName let avatarUrl = that.data.userInfo.avatarUrl let gender = that.data.u...
var t
identifier_name