file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
views.py
from django.contrib.sites.models import Site from django.utils._os import safe_join from django.views.generic import TemplateView from skin.conf import settings from skin.template.loaders.util import get_site_skin class TemplateSkinView(TemplateView): """ A view that extends Djangos base TemplateView to allo...
def get_skin(self): return get_site_skin(site=Site.objects.get_current(), name=self.get_skin_name()) def get_skin_path(self): if self.skin_path is not None: return self.skin_path skin = self.get_skin() if skin is not None: return skin.path else...
if self.skin_name is None: return settings.SKIN_NAME else: return self.skin_name
identifier_body
views.py
from django.contrib.sites.models import Site from django.utils._os import safe_join from django.views.generic import TemplateView from skin.conf import settings from skin.template.loaders.util import get_site_skin class TemplateSkinView(TemplateView): """ A view that extends Djangos base TemplateView to allo...
(self): template_names = super(TemplateSkinView, self).get_template_names() skin_path = self.get_skin_path() skin_template_names = [] if skin_path is not None: for template_name in template_names: skin_template_names.append(safe_join(skin_path, template_name))...
get_template_names
identifier_name
views.py
from django.contrib.sites.models import Site from django.utils._os import safe_join from django.views.generic import TemplateView from skin.conf import settings from skin.template.loaders.util import get_site_skin class TemplateSkinView(TemplateView): """ A view that extends Djangos base TemplateView to allo...
else: return None def get_template_names(self): template_names = super(TemplateSkinView, self).get_template_names() skin_path = self.get_skin_path() skin_template_names = [] if skin_path is not None: for template_name in template_names: ...
return skin.path
conditional_block
views.py
from django.contrib.sites.models import Site from django.utils._os import safe_join from django.views.generic import TemplateView from skin.conf import settings from skin.template.loaders.util import get_site_skin class TemplateSkinView(TemplateView): """ A view that extends Djangos base TemplateView to allo...
skin_template_names.append(safe_join(skin_path, template_name)) return skin_template_names + template_names
template_names = super(TemplateSkinView, self).get_template_names() skin_path = self.get_skin_path() skin_template_names = [] if skin_path is not None: for template_name in template_names:
random_line_split
browser_jsonp.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Injectable} from '@angular/core'; let _nextRequestId = 0; export const JSONP_HOME = '__ng_jsonp__'; let _js...
} }
{ node.parentNode.removeChild(<Node>(node)); }
conditional_block
browser_jsonp.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Injectable} from '@angular/core'; let _nextRequestId = 0; export const JSONP_HOME = '__ng_jsonp__'; let _js...
(id: string): string { return `${JSONP_HOME}.${id}.finished`; } exposeConnection(id: string, connection: any) { const connections = _getJsonpConnections(); connections[id] = connection; } removeConnection(id: string) { const connections = _getJsonpConnections(); connections[id] = null; }...
requestCallback
identifier_name
browser_jsonp.ts
/** * @license * Copyright Google Inc. All Rights Reserved.
*/ import {Injectable} from '@angular/core'; let _nextRequestId = 0; export const JSONP_HOME = '__ng_jsonp__'; let _jsonpConnections: {[key: string]: any}|null = null; function _getJsonpConnections(): {[key: string]: any} { const w: {[key: string]: any} = typeof window == 'object' ? window : {}; if (_jsonpConne...
* * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license
random_line_split
0006_auto_20170918_1954.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-09-18 19:54 from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('coursedashboards', '0005_auto_20170915_2036'), ] operations = [ migrations.CreateModel( name='CourseOfferingMajor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verb...
Migration
identifier_name
0006_auto_20170918_1954.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-09-18 19:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
model_name='coursemajor', name='course', ), migrations.RemoveField( model_name='coursemajor', name='major', ), migrations.AlterField( model_name='course', name='curriculum', field=models.CharField(max_len...
dependencies = [ ('coursedashboards', '0005_auto_20170915_2036'), ] operations = [ migrations.CreateModel( name='CourseOfferingMajor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
identifier_body
0006_auto_20170918_1954.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-09-18 19:54
class Migration(migrations.Migration): dependencies = [ ('coursedashboards', '0005_auto_20170915_2036'), ] operations = [ migrations.CreateModel( name='CourseOfferingMajor', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, seria...
from django.db import migrations, models import django.db.models.deletion
random_line_split
assoc-type.rs
// Copyright 2018 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 ...
() { }
main
identifier_name
assoc-type.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we do not yet support elision in associated types, even // when there is just one name we could take from the impl header. #![allow(warnings)] trait MyTrait { type Output; } impl MyTrait for &i32 { ...
// 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 http://opensource.org/licenses/MIT>, at your
random_line_split
assoc-type.rs
// Copyright 2018 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 ...
{ }
identifier_body
views.py
import logging from django.shortcuts import get_object_or_404 from django.views.generic import ListView, DetailView from django.http import HttpResponsePermanentRedirect from django.conf import settings from django.core.urlresolvers import reverse from readthedocs.builds.models import Build, Version from readthedocs....
queryset = Build.objects.public(user=self.request.user, project=self.project) return queryset class BuildList(BuildBase, ListView): def get_context_data(self, **kwargs): context = super(BuildList, self).get_context_data(**kwargs) filter = BuildFilter(self.request.GET, queryset=s...
self.project = get_object_or_404( Project.objects.protected(self.request.user), slug=self.project_slug )
random_line_split
views.py
import logging from django.shortcuts import get_object_or_404 from django.views.generic import ListView, DetailView from django.http import HttpResponsePermanentRedirect from django.conf import settings from django.core.urlresolvers import reverse from readthedocs.builds.models import Build, Version from readthedocs....
# Old build view redirects def builds_redirect_list(request, project_slug): return HttpResponsePermanentRedirect(reverse('builds_project_list', args=[project_slug])) def builds_redirect_detail(request, project_slug, pk): return HttpResponsePermanentRedirect(reverse('builds_detail', args=[project_slug, pk]...
pk_url_kwarg = 'build_pk' def get_context_data(self, **kwargs): context = super(BuildDetail, self).get_context_data(**kwargs) context['project'] = self.project return context
identifier_body
views.py
import logging from django.shortcuts import get_object_or_404 from django.views.generic import ListView, DetailView from django.http import HttpResponsePermanentRedirect from django.conf import settings from django.core.urlresolvers import reverse from readthedocs.builds.models import Build, Version from readthedocs....
(request, project_slug, pk): return HttpResponsePermanentRedirect(reverse('builds_detail', args=[project_slug, pk]))
builds_redirect_detail
identifier_name
build.rs
use flapigen::{CppConfig, CppOptional, CppStrView, CppVariant, LanguageConfig}; use std::{env, path::Path}; fn
() { let out_dir = env::var("OUT_DIR").expect("no OUT_DIR, but cargo should provide it"); //ANCHOR: cpp_config let cpp_cfg = CppConfig::new( // ANCHOR: cpp_output Path::new("..").join("cpp-part").join("rust-api"), // ANCHOR_END: cpp_output "rust".into(), ) .cpp_option...
main
identifier_name
build.rs
use flapigen::{CppConfig, CppOptional, CppStrView, CppVariant, LanguageConfig}; use std::{env, path::Path}; fn main() { let out_dir = env::var("OUT_DIR").expect("no OUT_DIR, but cargo should provide it"); //ANCHOR: cpp_config let cpp_cfg = CppConfig::new( // ANCHOR: cpp_output Path::new(".....
"rust".into(), ) .cpp_optional(CppOptional::Boost) .cpp_variant(CppVariant::Boost) .cpp_str_view(CppStrView::Boost); //ANCHOR_END: cpp_config let swig_gen = flapigen::Generator::new(LanguageConfig::CppConfig(cpp_cfg)); swig_gen.expand( "c++-api-for-rust", // ANCHOR: r...
// ANCHOR_END: cpp_output
random_line_split
build.rs
use flapigen::{CppConfig, CppOptional, CppStrView, CppVariant, LanguageConfig}; use std::{env, path::Path}; fn main()
// ANCHOR: rust_output &Path::new(&out_dir).join("cpp_glue.rs"), // ANCHOR_END: rust_output ); println!( "cargo:rerun-if-changed={}", Path::new("src").join("cpp_glue.rs.in").display() ); }
{ let out_dir = env::var("OUT_DIR").expect("no OUT_DIR, but cargo should provide it"); //ANCHOR: cpp_config let cpp_cfg = CppConfig::new( // ANCHOR: cpp_output Path::new("..").join("cpp-part").join("rust-api"), // ANCHOR_END: cpp_output "rust".into(), ) .cpp_optional(...
identifier_body
test_htmlcontains.py
from ftw import ruleset, testrunner, http, errors import pytest import re import random import threading def
(ruleset, test): runner = testrunner.TestRunner() for stage in test.stages: runner.run_stage(stage) # Should return a test error because its searching before response def test_search1(): runner = testrunner.TestRunner() x = ruleset.Input(dest_addr="example.com",headers={"Host":"example.com"}) ...
test_logcontains
identifier_name
test_htmlcontains.py
from ftw import ruleset, testrunner, http, errors import pytest import re import random import threading def test_logcontains(ruleset, test): runner = testrunner.TestRunner() for stage in test.stages: runner.run_stage(stage) # Should return a test error because its searching before response def test_s...
http_ua = http.HttpUA() http_ua.send_request(x) runner.test_response(http_ua.response_object,re.compile('established to be used for')) # Should return a success because we found our regex def test_search4(): runner = testrunner.TestRunner() x = ruleset.Input(dest_addr="example.com",headers={...
# Should return a success because it is searching for a word not there def test_search3(): runner = testrunner.TestRunner() x = ruleset.Input(dest_addr="example.com",headers={"Host":"example.com"})
random_line_split
test_htmlcontains.py
from ftw import ruleset, testrunner, http, errors import pytest import re import random import threading def test_logcontains(ruleset, test): runner = testrunner.TestRunner() for stage in test.stages:
# Should return a test error because its searching before response def test_search1(): runner = testrunner.TestRunner() x = ruleset.Input(dest_addr="example.com",headers={"Host":"example.com"}) http_ua = http.HttpUA() with pytest.raises(errors.TestError): runner.test_response(http_ua.resp...
runner.run_stage(stage)
conditional_block
test_htmlcontains.py
from ftw import ruleset, testrunner, http, errors import pytest import re import random import threading def test_logcontains(ruleset, test): runner = testrunner.TestRunner() for stage in test.stages: runner.run_stage(stage) # Should return a test error because its searching before response def test_s...
# Should return a failure because it is searching for a word not there def test_search2(): runner = testrunner.TestRunner() x = ruleset.Input(dest_addr="example.com",headers={"Host":"example.com"}) http_ua = http.HttpUA() http_ua.send_request(x) with pytest.raises(AssertionError): ...
runner = testrunner.TestRunner() x = ruleset.Input(dest_addr="example.com",headers={"Host":"example.com"}) http_ua = http.HttpUA() with pytest.raises(errors.TestError): runner.test_response(http_ua.response_object,re.compile('dog'))
identifier_body
common.config.spec.ts
/// <reference path="../../../typings/index.d.ts" /> import Common from './common'; 'use strict'; let $module = angular.mock.module; let $inject = angular.mock.inject; let $dump = (arg: any): void => console.log(angular.mock.dump(arg)); describe('# Common Config', () => { beforeEach($module(Common)); describe(...
})); }); });
random_line_split
vec_resize_to_zero.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declar...
(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if_chain! { if let hir::ExprKind::MethodCall(path_segment, _, args, _) = expr.kind; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, method_def_id, &paths::VE...
check_expr
identifier_name
vec_resize_to_zero.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declar...
Applicability::MaybeIncorrect, ); }, ); } } } }
{ if_chain! { if let hir::ExprKind::MethodCall(path_segment, _, args, _) = expr.kind; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, method_def_id, &paths::VEC_RESIZE) && args.len() == 3; if let ExprKind:...
identifier_body
vec_resize_to_zero.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_ast::LitKind; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declar...
"clear()".to_string(), Applicability::MaybeIncorrect, ); }, ); } } } }
method_call_span, "...or you can empty the vector with",
random_line_split
main.js
var express = require('express'); var router = express.Router(); var Examples = require('../models/Example'); var data; //出来通用数据 router.use(function(req, res, next) { data = { examples: []
}; Examples.find().then(function(examples) { data.examples = examples; next(); }); }); router.get('/', function(req, res, next) { data.examples = req.query.examples || ''; data.count = 0; data.page = Number(req.query.page || 1); data.limit = 8; data.pages = 0; data.c...
random_line_split
sinon-tests.ts
/// <reference path="sinon-1.5.d.ts" /> function once(fn) { var returnValue, called = false; return function () { if (!called) { called = true; returnValue = fn.apply(this, arguments); } return returnValue; }; } function testOne() { var callback = sinon.spy(); var proxy = once(callback); proxy(); i...
var obj = { thisObj: true }; var callback = sinon.stub().returnsArg(1); var proxy = once(callback); var val = proxy.apply(callback, [1, 2, 3]); if (val == 2) { console.log("test5 returnsArg success"); } else { console.log("test5 returnsArg failure"); } } var objectUnderTest: any = { process: function (obj) { /...
var val = proxy.apply(callback, [1, 2, 3]); if (val == 42) { console.log("test4 returns success"); } else { console.log("test4 returns failure"); } } function testFive() {
random_line_split
sinon-tests.ts
/// <reference path="sinon-1.5.d.ts" /> function once(fn) { var returnValue, called = false; return function () { if (!called) { called = true; returnValue = fn.apply(this, arguments); } return returnValue; }; } function testOne() { var callback = sinon.spy(); var proxy = once(callback); proxy(); i...
() { var obj = { thisObj: true }; var callback = sinon.stub().returns(42); var proxy = once(callback); var val = proxy.apply(callback, [1, 2, 3]); if (val == 42) { console.log("test4 returns success"); } else { console.log("test4 returns failure"); } } function testFive() { var obj = { thisObj: true }; var call...
testFour
identifier_name
sinon-tests.ts
/// <reference path="sinon-1.5.d.ts" /> function once(fn)
function testOne() { var callback = sinon.spy(); var proxy = once(callback); proxy(); if (callback.calledOnce) { console.log("test1 calledOnce success"); } else { console.log("test1 calledOnce failure"); } } function testTwo() { var callback = sinon.spy(); var proxy = once(callback); proxy(); proxy(); if (c...
{ var returnValue, called = false; return function () { if (!called) { called = true; returnValue = fn.apply(this, arguments); } return returnValue; }; }
identifier_body
sinon-tests.ts
/// <reference path="sinon-1.5.d.ts" /> function once(fn) { var returnValue, called = false; return function () { if (!called) { called = true; returnValue = fn.apply(this, arguments); } return returnValue; }; } function testOne() { var callback = sinon.spy(); var proxy = once(callback); proxy(); i...
else { console.log("test3 calledOn failure"); } if (callback.calledWith(callback, 1, 2, 3)) { console.log("test3 calledWith success"); } else { console.log("test3 calledWith failure"); } } function testFour() { var obj = { thisObj: true }; var callback = sinon.stub().returns(42); var proxy = once(callback); var ...
{ console.log("test3 calledOn success"); }
conditional_block
options.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version ...
remove_unreferenced_ids: false, trim_ids: false, remove_text_attributes: false, remove_unused_coordinates: false, remove_default_attributes: false, remove_xmlns_xlink_attribute: false, remove_needless_attributes: false, remo...
{ CleaningOptions { remove_unused_defs: false, convert_shapes: false, remove_title: false, remove_desc: false, remove_metadata: false, remove_dupl_linear_gradients: false, remove_dupl_radial_gradients: false, remove_...
identifier_body
options.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version ...
() -> CleaningOptions { CleaningOptions { remove_unused_defs: false, convert_shapes: false, remove_title: false, remove_desc: false, remove_metadata: false, remove_dupl_linear_gradients: false, remove_dupl_radial_gradients: fals...
default
identifier_name
options.rs
// svgcleaner could help you to clean up your SVG files // from unnecessary data. // Copyright (C) 2012-2018 Evgeniy Reizner // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version ...
} // Should all be 'false'. impl Default for CleaningOptions { fn default() -> CleaningOptions { CleaningOptions { remove_unused_defs: false, convert_shapes: false, remove_title: false, remove_desc: false, remove_metadata: false, remov...
pub paths_coordinates_precision: u8, // 1..12 pub transforms_precision: u8,
random_line_split
smartnet2decode.py
%i" % self.rate self._syms_per_sec = 3600; options.samples_per_second = self.rate options.syms_per_sec = self._syms_per_sec options.gain_mu = 0.01 options.mu=0.5 options.omega_relative_limit = 0.3 options.syms_per_sec = self._syms_per_sec options.offset = options.centerfreq - options.freq print "C...
(self): self.setvolume(0) def unmute(self, volume): self.setvolume(volume) def getfreq(chanlist, cmd): if chanlist is None: if cmd < 0x2d0: freq = float(cmd * 0.025 + 851.0125) else: freq = None else: if chanlist.get(str(cmd), None) is not None: freq = float(chanlist[str(cmd)]) else: freq ...
mute
identifier_name
smartnet2decode.py
%i" % self.rate self._syms_per_sec = 3600; options.samples_per_second = self.rate options.syms_per_sec = self._syms_per_sec options.gain_mu = 0.01 options.mu=0.5 options.omega_relative_limit = 0.3 options.syms_per_sec = self._syms_per_sec options.offset = options.centerfreq - options.freq print "C...
self.connect(self.demod, self.start_correlator, self.smartnet_deinterleave, self.smartnet_crc) #hook up the audio patch if options.audio: self.audiorate = 48000 self.audiotaps = gr.firdes.low_pass(1, self.rate, 8000, 2000, gr.firdes.WIN_HANN) self.prefilter_decim = int(self.rate / self.audiorate) #mig...
self.connect(self.fs, self.demod)
conditional_block
smartnet2decode.py
%i" % self.rate self._syms_per_sec = 3600; options.samples_per_second = self.rate options.syms_per_sec = self._syms_per_sec options.gain_mu = 0.01 options.mu=0.5 options.omega_relative_limit = 0.3 options.syms_per_sec = self._syms_per_sec options.offset = options.centerfreq - options.freq print "C...
def getfreq(chanlist, cmd): if chanlist is None: if cmd < 0x2d0: freq = float(cmd * 0.025 + 851.0125) else: freq = None else: if chanlist.get(str(cmd), None) is not None: freq = float(chanlist[str(cmd)]) else: freq = None return freq def parsefreq(s, chanlist): retfreq = None [address, grou...
def unmute(self, volume): self.setvolume(volume)
random_line_split
smartnet2decode.py
self.centerfreq = options.centerfreq print "Tuning to: %fMHz" % (self.centerfreq - options.error) if not(self.tune(options.centerfreq - options.error)): print "Failed to set initial frequency" if options.gain is None: #set to halfway g = self.u.get_gain_range() options.gain = (g.start()+g.s...
gr.top_block.__init__(self) if options.filename is not None: self.fs = gr.file_source(gr.sizeof_gr_complex, options.filename) self.rate = options.rate else: self.u = uhd.usrp_source(options.addr, io_type=uhd.io_type.COMPLEX_FLOAT32, num_channels=1) if options.subdev is not None: ...
identifier_body
account-standing.tsx
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import ProfilePageExtraSectionTitle from 'components/profile-page-extra-section-title'; import UserAccountHistoryJson from 'interfaces/user-acc...
return <>{moment.duration(history.length, 'seconds').humanize()}</>; }; const content: Record<Column, (props: ColumnProps) => JSX.Element | null> = { action: ColumnAction, date: ColumnDate, description: ColumnDescription, length: ColumnLength, }; @observer export default class AccountStanding extends Reac...
{ return null; }
conditional_block
account-standing.tsx
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import ProfilePageExtraSectionTitle from 'components/profile-page-extra-section-title'; import UserAccountHistoryJson from 'interfaces/user-acc...
@computed get latest() { return this.props.controller.state.user.account_history.find((d) => d.type === 'silence'); } render() { return ( <div className='page-extra'> <ExtraHeader name={this.props.name} withEdit={false} /> {this.latest != null && ( <div className='pag...
{ return this.latest == null ? null : moment(this.latest.timestamp).add(this.latest.length, 'seconds'); }
identifier_body
account-standing.tsx
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import ProfilePageExtraSectionTitle from 'components/profile-page-extra-section-title'; import UserAccountHistoryJson from 'interfaces/user-acc...
() { return this.latest == null ? null : moment(this.latest.timestamp).add(this.latest.length, 'seconds'); } @computed get latest() { return this.props.controller.state.user.account_history.find((d) => d.type === 'silence'); } render() { return ( <div className='page-extra'> ...
endTime
identifier_name
account-standing.tsx
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. // See the LICENCE file in the repository root for full licence text. import ProfilePageExtraSectionTitle from 'components/profile-page-extra-section-title'; import UserAccountHistoryJson from 'interfaces/user-acc...
pattern={stripTags(osu.trans('users.show.extra.account_standing.bad_standing'))} /> </div> )} {this.endTime != null && this.endTime.isAfter() && ( <div className='page-extra__alert page-extra__alert--info'> <StringWithComponent map...
mappings={{ username: <strong>{this.props.controller.state.user.username}</strong> }} // TODO: remove stripTags once translations are updated
random_line_split
dm_eval.py
(Thread): def __init__(self, proc, p_args): super().__init__() self._proc = proc self._args = p_args self.errored = False self.error_msg = None def run(self): winloop = asyncio.ProactorEventLoop() future = self._proc(winloop, *self._args) try:...
WindowsProcessThread
identifier_name
dm_eval.py
chunks = byond_str.split(" ") if not len(chunks) > 1: return None chunks = chunks[0].split(".") # This is triggered alyways forever. So. Return null if format doesn't match. if len(chunks) != 2: return None try: major = int(chunks[0][2:]) minor = int(chunks[1...
if not segments["proc"]: segments["proc"] = "" output = self.DM_BOILERPLATE output = output.format(segments["pre_proc"], segments["proc"], segments["to_out"]) f.write(output) async def compile_dm(self, loop, instance_dir, major, minor): ""...
segments["to_out"] = ""
conditional_block
dm_eval.py
chunks = byond_str.split(" ") if not len(chunks) > 1: return None chunks = chunks[0].split(".") # This is triggered alyways forever. So. Return null if format doesn't match. if len(chunks) != 2: return None try: major = int(chunks[0][2:]) minor = int(chunks[1...
for expr in self._safety_expressions: if expr.search(code): raise BotError("Disallowed/dangerous code found. Aborting.", "validate_dm") def generate_dm(self, segments, instance_dir): """Generates the .dme file to be compiled.""" with open(f"{instance_dir}\\eval....
return code_segs def validate_dm(self, code): """Validates the code given for potential exploits."""
random_line_split
dm_eval.py
pre_proc"].endswith(";") and not code_segs["pre_proc"].endswith("}")): code_segs["pre_proc"] += ";" if (code_segs["proc"] and not code_segs["proc"].endswith(";") and not code_segs["proc"].endswith(";")): code_segs["proc"] += ";" if code_segs["to_out...
"""Reports the default version of BYOND used by dm_eval.""" await ctx.send(f"The default version of BYOND used for `dm_eval` is: {DEFAULT_MAJOR}.{DEFAULT_MINOR}.")
identifier_body
tungerDB.py
import sqlite3 import urllib import re from urllib.request import urlopen from bs4 import BeautifulSoup, NavigableString from phyllo.phyllo_logger import logger import nltk from itertools import cycle nltk.download('punkt') from nltk import sent_tokenize # Case 1: Sections split by numbers (Roman or not) followed b...
(): # The collection URL below. In this example, we have a link to Cicero. collURL = 'http://www.thelatinlibrary.com/tunger.html' collOpen = urllib.request.urlopen(collURL) collSOUP = BeautifulSoup(collOpen, 'html5lib') author = collSOUP.title.string.strip() colltitle = author.upper() date =...
main
identifier_name
tungerDB.py
import sqlite3 import urllib import re from urllib.request import urlopen from bs4 import BeautifulSoup, NavigableString from phyllo.phyllo_logger import logger import nltk from itertools import cycle nltk.download('punkt') from nltk import sent_tokenize # Case 1: Sections split by numbers (Roman or not) followed b...
getp = textsoup.find_all('p') parsecase1(getp, c, colltitle, title, author, date, url) logger.info("Program runs successfully.") if __name__ == '__main__': main()
collURL = 'http://www.thelatinlibrary.com/tunger.html' collOpen = urllib.request.urlopen(collURL) collSOUP = BeautifulSoup(collOpen, 'html5lib') author = collSOUP.title.string.strip() colltitle = author.upper() date = "1486" textsURL = [collURL] with sqlite3.connect('texts.db') as db: ...
identifier_body
tungerDB.py
import sqlite3 import urllib import re from urllib.request import urlopen from bs4 import BeautifulSoup, NavigableString from phyllo.phyllo_logger import logger import nltk from itertools import cycle nltk.download('punkt') from nltk import sent_tokenize # Case 1: Sections split by numbers (Roman or not) followed b...
if __name__ == '__main__': main()
random_line_split
tungerDB.py
import sqlite3 import urllib import re from urllib.request import urlopen from bs4 import BeautifulSoup, NavigableString from phyllo.phyllo_logger import logger import nltk from itertools import cycle nltk.download('punkt') from nltk import sent_tokenize # Case 1: Sections split by numbers (Roman or not) followed b...
# The split should not alter sections with no prefixed roman numeral. if len(text) > 1: i = 0 while text[i] is None: i += 1 chapter = text[i] i += 1 while text[i] is None: i += 1 passage = text[i].st...
text.remove(element)
conditional_block
app.js
import Ember from 'ember'; import Resolver from 'ember/resolver'; import loadInitializers from 'ember/load-initializers'; import config from './config/environment'; var App; Ember.MODEL_FACTORY_INJECTIONS = true; App = Ember.Application.extend({ modulePrefix: config.modulePrefix, podModulePrefix: config.podMo...
name: 'my-initializer', initialize: function(container, application) { console.log("Container", container); console.log("RootElement", application.rootElement); /*if (application.rootElement !== '#ember-application') { application.reopen({ rootElement: '#ember-appli...
}); App.initializer({
random_line_split
Backup.script.js
function clientEditRow(baseURL, elementID, dbID) { console.log("inside clientEditRow function, variables:", elementID, ",",dbID); var hostPort = "http://"; if (baseURL.port) { hostPort = baseURL.hostname.concat(':', baseURL.port); } else { hostPort = baseURL.hostname; } var URL = hostPort.concat(baseURL.p...
(baseURL, elementID, dbID) { console.log("inside clientDeleteRow function, variables:", baseURL, elementID,",", dbID); var protocol = "http://"; if (baseURL.port) { hostPort = protocol.concat(baseURL.hostname,':', baseURL.port); } else { hostPort = protocol.concat(baseURL.hostname); } var URL = hostPort.con...
clientDeleteRow
identifier_name
Backup.script.js
function clientEditRow(baseURL, elementID, dbID) { console.log("inside clientEditRow function, variables:", elementID, ",",dbID); var hostPort = "http://"; if (baseURL.port) { hostPort = baseURL.hostname.concat(':', baseURL.port); } else { hostPort = baseURL.hostname; } var URL = hostPort.concat(baseURL.p...
connection.addEventListener('load', function () { console.log("Request status:", connection.status); if ( connection.status < 400 ) return connection.responseText; else return undefined; }); }
connection.send(null);
random_line_split
Backup.script.js
function clientEditRow(baseURL, elementID, dbID) { console.log("inside clientEditRow function, variables:", elementID, ",",dbID); var hostPort = "http://"; if (baseURL.port) { hostPort = baseURL.hostname.concat(':', baseURL.port); } else { hostPort = baseURL.hostname; } var URL = hostPort.concat(baseURL.p...
function clientDeleteRow(baseURL, elementID, dbID) { console.log("inside clientDeleteRow function, variables:", baseURL, elementID,",", dbID); var protocol = "http://"; if (baseURL.port) { hostPort = protocol.concat(baseURL.hostname,':', baseURL.port); } else { hostPort = protocol.concat(baseURL.hostname);...
{ if ( ! (command == "edit" || command == "delete" )) { console.log ("Bad command:", command); return; } var protocol = "http://"; if (baseURL.port) { hostPort = protocol.concat(baseURL.hostname,':', baseURL.port); } else { hostPort = protocol.concat(baseURL.hostname); } var URL = hostPort.concat(baseURL.pat...
identifier_body
PhotoDeskPreview.tsx
import React from 'react'; import PropTypes from 'prop-types'; import {SelectBox} from './index'; function hasThumbnail(item) { return item.renditions && item.renditions.thumbnail; } /** * Media Preview - renders item thumbnail */ export const PhotoDeskPreview:React.StatelessComponent<any> = (props) => { co...
return ( <div className="sd-grid-item__thumb"> {preview} <SelectBox item={item} classes="sd-grid-item__checkbox" onMultiSelect={props.onMultiSelect} svc={props.svc}/> </div> ); }; PhotoDeskPreview.propTypes = { svc: PropTypes.object.isRequired, ...
{ preview = <img src={item.renditions.thumbnail.href} />; }
conditional_block
PhotoDeskPreview.tsx
import React from 'react'; import PropTypes from 'prop-types'; import {SelectBox} from './index'; function
(item) { return item.renditions && item.renditions.thumbnail; } /** * Media Preview - renders item thumbnail */ export const PhotoDeskPreview:React.StatelessComponent<any> = (props) => { const item = props.item; const classType = 'sd-grid-item__type-icon filetype-icon-' + props.item.type; let previe...
hasThumbnail
identifier_name
PhotoDeskPreview.tsx
import React from 'react'; import PropTypes from 'prop-types'; import {SelectBox} from './index'; function hasThumbnail(item)
/** * Media Preview - renders item thumbnail */ export const PhotoDeskPreview:React.StatelessComponent<any> = (props) => { const item = props.item; const classType = 'sd-grid-item__type-icon filetype-icon-' + props.item.type; let preview = <i className={classType} />; if (hasThumbnail(props.item))...
{ return item.renditions && item.renditions.thumbnail; }
identifier_body
PhotoDeskPreview.tsx
import React from 'react'; import PropTypes from 'prop-types'; import {SelectBox} from './index'; function hasThumbnail(item) { return item.renditions && item.renditions.thumbnail; } /** * Media Preview - renders item thumbnail */ export const PhotoDeskPreview:React.StatelessComponent<any> = (props) => { co...
svc: PropTypes.object.isRequired, onMultiSelect: PropTypes.func, item: PropTypes.any, };
random_line_split
artifact-summary.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ArtifactSummaryComponent } from "./artifact-summary.component"; import { of } from "rxjs"; import { NO_ERRORS_SCHEMA } from "@angular/core"; import { Artifact } from "../../../../../../ng-swagger-gen/models/artifact"; import { ProjectService } ...
() { return undefined; } }; let component: ArtifactSummaryComponent; let fixture: ComponentFixture<ArtifactSummaryComponent>; const mockActivatedRoute = { RouterparamMap: of({ get: (key) => 'value' }), snapshot: { params: { repo: "test", digest: "ABC", subscribe: ...
getIcon
identifier_name
artifact-summary.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ArtifactSummaryComponent } from "./artifact-summary.component"; import { of } from "rxjs"; import { NO_ERRORS_SCHEMA } from "@angular/core"; import { Artifact } from "../../../../../../ng-swagger-gen/models/artifact"; import { ProjectService } ...
declarations: [ ArtifactSummaryComponent ], schemas: [ NO_ERRORS_SCHEMA ], providers: [ { provide: AppConfigService, useValue: fakedAppConfigService }, { provide: Router, useValue: mockRouter }, { provide: ActivatedRoute, useValue: mockActivatedRoute...
beforeEach(() => { TestBed.configureTestingModule({ imports: [ SharedTestingModule, ],
random_line_split
artifact-summary.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ArtifactSummaryComponent } from "./artifact-summary.component"; import { of } from "rxjs"; import { NO_ERRORS_SCHEMA } from "@angular/core"; import { Artifact } from "../../../../../../ng-swagger-gen/models/artifact"; import { ProjectService } ...
}; let component: ArtifactSummaryComponent; let fixture: ComponentFixture<ArtifactSummaryComponent>; const mockActivatedRoute = { RouterparamMap: of({ get: (key) => 'value' }), snapshot: { params: { repo: "test", digest: "ABC", subscribe: () => { return of(null);...
{ return undefined; }
identifier_body
lossy.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
for Utf8LossyChunk { valid, broken } in self.chunks() { // If we successfully decoded the whole chunk as a valid string then // we can return a direct formatting of the string which will also // respect various formatting flags if possible. if valid.len() == sel...
{ return "".fmt(f) }
conditional_block
lossy.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
macro_rules! error { () => ({ unsafe { let r = Utf8LossyChunk { valid: core_str::from_utf8_unchecked(&self.source[0..i_]), broken: &self.source[i_..i], }; ...
if byte < 128 { } else { let w = core_str::utf8_char_width(byte);
random_line_split
lossy.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} /// Iterator over lossy UTF-8 string #[unstable(feature = "str_internals", issue = "0")] #[allow(missing_debug_implementations)] pub struct Utf8LossyChunksIter<'a> { source: &'a [u8], } #[unstable(feature = "str_internals", issue = "0")] #[derive(PartialEq, Eq, Debug)] pub struct Utf8LossyChunk<'a> { /// ...
{ Utf8LossyChunksIter { source: &self.bytes } }
identifier_body
lossy.rs
// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(xs: &[u8], i: usize) -> u8 { *xs.get(i).unwrap_or(&0) } let mut i = 0; while i < self.source.len() { let i_ = i; let byte = unsafe { *self.source.get_unchecked(i) }; i += 1; if byte < 128 { } else { let ...
safe_get
identifier_name
views.py
""" Django Views for service status app """ from __future__ import absolute_import import json import time from celery.exceptions import TimeoutError from django.http import HttpResponse from djcelery import celery from openedx.core.djangoapps.service_status.tasks import delayed_ping def index(_):
def celery_status(_): """ A view that returns Celery stats """ stats = celery.control.inspect().stats() or {} return HttpResponse(json.dumps(stats, indent=4), content_type="application/json") def celery_ping(_): """ A Simple view that checks if Celery can process...
""" An empty view """ return HttpResponse()
identifier_body
views.py
""" Django Views for service status app """ from __future__ import absolute_import import json import time from celery.exceptions import TimeoutError from django.http import HttpResponse from djcelery import celery from openedx.core.djangoapps.service_status.tasks import delayed_ping def index(_): """ An e...
A view that returns Celery stats """ stats = celery.control.inspect().stats() or {} return HttpResponse(json.dumps(stats, indent=4), content_type="application/json") def celery_ping(_): """ A Simple view that checks if Celery can process a simple task """ start ...
return HttpResponse() def celery_status(_): """
random_line_split
views.py
""" Django Views for service status app """ from __future__ import absolute_import import json import time from celery.exceptions import TimeoutError from django.http import HttpResponse from djcelery import celery from openedx.core.djangoapps.service_status.tasks import delayed_ping def index(_): """ An e...
(_): """ A view that returns Celery stats """ stats = celery.control.inspect().stats() or {} return HttpResponse(json.dumps(stats, indent=4), content_type="application/json") def celery_ping(_): """ A Simple view that checks if Celery can process a simple task "...
celery_status
identifier_name
register.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <bgamari@gmail.com> // // 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...
fn build_enum_variant(cx: &ExtCtxt, variant: &node::Variant) -> ast::Variant { let doc = match variant.docstring { Some(d) => d.node.name.to_string(), None => "no documentation".to_string(), }; let docstring = format!("`0x{:x}`. {}", variant.value.node, ...
vec!(P(item), copy_impl) } /// Build a variant of an `EnumField`
random_line_split
register.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <bgamari@gmail.com> // // 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...
<'a> { builder: &'a mut Builder, cx: &'a ExtCtxt<'a>, } impl<'a> node::RegVisitor for BuildRegStructs<'a> { fn visit_prim_reg(&mut self, path: &Vec<String>, reg: &node::Reg, fields: &Vec<node::Field>) { let width = match reg.ty { node::RegType::RegPrim(ref width, _) => width.node, ...
BuildRegStructs
identifier_name
register.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <bgamari@gmail.com> // // 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...
} impl<'a> BuildRegStructs<'a> { pub fn new(builder: &'a mut Builder, cx: &'a ExtCtxt<'a>) -> BuildRegStructs<'a> { BuildRegStructs {builder: builder, cx: cx} } } /// Build a field type if necessary (e.g. in the case of an `EnumField`) fn build_field_type(cx: &ExtCtxt, path: &Vec<String>, ...
{ let width = match reg.ty { node::RegType::RegPrim(ref width, _) => width.node, _ => panic!("visit_prim_reg called with non-primitive register"), }; for field in fields.iter() { for item in build_field_type(self.cx, path, reg, field).into_iter() { self.builder.push_item(item); ...
identifier_body
synonyms_en.js
'use strict'; //var bhl_url = "http://words.bighugelabs.com/api/2/d1cbb0c53ddabe240d726e3fc76b1491/"; var bhl_url = "http://words.bighugelabs.com/api/2/0791f67e8212761406e388ef91856024/"; var sel_x = 0, sel_y = 0; var word = ''; var help_paragraph_en = $('<p></p>').addClass('help-paragraph').text("Click the mouse or a...
}); } } function showTooltipEn(synonyms) { //var synonyms = JSON.parse(synonymsJSON); var tooltipDiv = $("<div class='tooltip'></div>"); $(tooltipDiv).css("top", sel_y); $(tooltipDiv).css("left", sel_x); var superTitle = $("<h2></h2>").text('Synonyms of "' + word + '"'); $(tooltipDiv).appen...
{ if (word.length > 0) { chrome.runtime.sendMessage({ method: 'GET', action: 'xhttp', url: bhl_url + word + "/json", format: 'application/json' }, function(responseText) { var synonyms = JSON.parse(responseText); if(synonyms.hasOwnProperty('error')) { showErrorTooltipEn(); } ...
identifier_body
synonyms_en.js
'use strict'; //var bhl_url = "http://words.bighugelabs.com/api/2/d1cbb0c53ddabe240d726e3fc76b1491/"; var bhl_url = "http://words.bighugelabs.com/api/2/0791f67e8212761406e388ef91856024/"; var sel_x = 0, sel_y = 0; var word = ''; var help_paragraph_en = $('<p></p>').addClass('help-paragraph').text("Click the mouse or a...
var title = $("<h3></h3>").text("Verb"); var par = $("<p></p>").text(synonymsList); $(tooltipDiv).append(title); $(tooltipDiv).append(par); } if (synonyms.hasOwnProperty("adjective")) { if ((synonyms.adjective.hasOwnProperty("syn")) && (synonyms.adjective.syn.length > 0...
{ var synonymsList = synonyms.verb.syn.join(", "); }
conditional_block
synonyms_en.js
'use strict'; //var bhl_url = "http://words.bighugelabs.com/api/2/d1cbb0c53ddabe240d726e3fc76b1491/"; var bhl_url = "http://words.bighugelabs.com/api/2/0791f67e8212761406e388ef91856024/"; var sel_x = 0, sel_y = 0; var word = ''; var help_paragraph_en = $('<p></p>').addClass('help-paragraph').text("Click the mouse or a...
$(tooltipDiv).append(par); } if (synonyms.hasOwnProperty("adverb")) { if ((synonyms.adverb.hasOwnProperty("syn")) && (synonyms.adverb.syn.length > 0) ) { var synonymsList = synonyms.adverb.syn.join(", "); } var title = $("<h3></h3>").text("Adverb"); var par = $...
} var title = $("<h3></h3>").text("Adjective"); var par = $("<p></p>").text(synonymsList); $(tooltipDiv).append(title);
random_line_split
synonyms_en.js
'use strict'; //var bhl_url = "http://words.bighugelabs.com/api/2/d1cbb0c53ddabe240d726e3fc76b1491/"; var bhl_url = "http://words.bighugelabs.com/api/2/0791f67e8212761406e388ef91856024/"; var sel_x = 0, sel_y = 0; var word = ''; var help_paragraph_en = $('<p></p>').addClass('help-paragraph').text("Click the mouse or a...
(e) { get_selection_en(); console.log("Word: " + word); } function get_selection_en() { var txt = ''; var zoomCoef = 1; chrome.storage.local.get({ 'token' : "", 'preferences' : {} }, function(results) { console.log("Antes de control de error: " + JSON.stringify(results)); if (!(chrome.runtime.last...
onDoubleClickEn
identifier_name
index.js
export default class PathWarp { /** * Register paper scope for PathWarp instance. * @param {paper.PaperScope} paper - Paper paper. * To run without canvas element (such as for SVG rendering), just * call `paper.setup()` before calling this. */ register(paper)
smoothCurves: PathWarp.smoothCurves, }); this.paper.CompoundPath.inject({ warpBetween, }); } /** * Warp source path between upper and lower * bounding paths. This will mutate the path. * @param {paper.CompoundPath|paper.CompoundPath} targetPath - Path to warp. It will be * trea...
{ if (!paper) { throw new Error('PathWarp requires PaperScope'); } this.paper = paper; this.paper.Point.inject({ toArray() { return [this.x, this.y]; }, }); const self = this; const warpBetween = function _warpBetween(topPath, bottomPath, options) { return ...
identifier_body
index.js
export default class PathWarp { /** * Register paper scope for PathWarp instance. * @param {paper.PaperScope} paper - Paper paper. * To run without canvas element (such as for SVG rendering), just * call `paper.setup()` before calling this. */ register(paper) { if (!paper) { throw new Error...
return topPoint.add(bottomPoint.subtract(topPoint).multiply(unitPoint.y)); }; } /** * Smoothes any vertexes along curves that are 'nearly' smooth. * @param {paper.Path} path - Path to be modified. * @param {number} toleranceDeg - Vertexes with angle difference less than * this are considered s...
{ return topPoint; }
conditional_block
index.js
export default class PathWarp { /** * Register paper scope for PathWarp instance. * @param {paper.PaperScope} paper - Paper paper. * To run without canvas element (such as for SVG rendering), just * call `paper.setup()` before calling this. */ register(paper) { if (!paper) { throw new Error(...
const tangent = segment.curve.getTangentAt(0.5); if (tangent != null) { const { angle } = tangent; const angleDiff = Math.abs(angle - prevAngle); if (angleDiff > 0.1 && angleDiff < toleranceDeg) { segment.smooth({ type: 'catmull-rom' }); } prevAngle = ang...
* this are considered smoothable (default 30). */ static smoothCurves(path, toleranceDeg = 30) { let prevAngle = path.lastCurve.getTangentAt(0.5).angle; for (const segment of path.segments) {
random_line_split
index.js
export default class PathWarp { /** * Register paper scope for PathWarp instance. * @param {paper.PaperScope} paper - Paper paper. * To run without canvas element (such as for SVG rendering), just * call `paper.setup()` before calling this. */
(paper) { if (!paper) { throw new Error('PathWarp requires PaperScope'); } this.paper = paper; this.paper.Point.inject({ toArray() { return [this.x, this.y]; }, }); const self = this; const warpBetween = function _warpBetween(topPath, bottomPath, options) { ...
register
identifier_name
MlmdUtils.ts
import { Api, Context, Execution, ExecutionCustomProperties, getResourcePropertyViaFallBack, ExecutionProperties, getResourceProperty, } from '@kubeflow/frontend'; import { GetContextByTypeAndNameRequest, GetExecutionsByContextRequest, } from '@kubeflow/frontend/src/mlmd/generated/ml_metadata/proto/me...
const request = new GetContextByTypeAndNameRequest(); request.setTypeName(type); request.setContextName(name); try { const res = await Api.getInstance().metadataStoreService.getContextByTypeAndName(request); const context = res.getContext(); if (context == null) { throw new Error('Cannot find ...
random_line_split
MlmdUtils.ts
import { Api, Context, Execution, ExecutionCustomProperties, getResourcePropertyViaFallBack, ExecutionProperties, getResourceProperty, } from '@kubeflow/frontend'; import { GetContextByTypeAndNameRequest, GetExecutionsByContextRequest, } from '@kubeflow/frontend/src/mlmd/generated/ml_metadata/proto/me...
(argoWorkflowName: string): Promise<Context> { return await getContext({ name: argoWorkflowName, type: 'KfpRun' }); } /** * @throws error when network error */ export async function getExecutionsFromContext(context: Context): Promise<Execution[]> { const request = new GetExecutionsByContextRequest(); request.s...
getKfpRunContext
identifier_name
MlmdUtils.ts
import { Api, Context, Execution, ExecutionCustomProperties, getResourcePropertyViaFallBack, ExecutionProperties, getResourceProperty, } from '@kubeflow/frontend'; import { GetContextByTypeAndNameRequest, GetExecutionsByContextRequest, } from '@kubeflow/frontend/src/mlmd/generated/ml_metadata/proto/me...
return context; } catch (err) { err.message = `Cannot find context with ${JSON.stringify(request.toObject())}: ` + err.message; throw err; } } /** * @throws error when network error, or not found */ export async function getTfxRunContext(argoWorkflowName: string): Promise<Context> { // argoPodName...
{ throw new Error('Cannot find specified context'); }
conditional_block
MlmdUtils.ts
import { Api, Context, Execution, ExecutionCustomProperties, getResourcePropertyViaFallBack, ExecutionProperties, getResourceProperty, } from '@kubeflow/frontend'; import { GetContextByTypeAndNameRequest, GetExecutionsByContextRequest, } from '@kubeflow/frontend/src/mlmd/generated/ml_metadata/proto/me...
export enum KfpExecutionProperties { KFP_POD_NAME = 'kfp_pod_name', } const EXECUTION_PROPERTY_REPOS = [ExecutionProperties, ExecutionCustomProperties]; export const ExecutionHelpers = { getWorkspace(execution: Execution): string | number | undefined { return ( getResourcePropertyViaFallBack(execution...
{ const request = new GetExecutionsByContextRequest(); request.setContextId(context.getId()); try { const res = await Api.getInstance().metadataStoreService.getExecutionsByContext(request); const list = res.getExecutionsList(); if (list == null) { throw new Error('response.getExecutionsList() is...
identifier_body
helpers.py
from distutils import spawn import mock import pytest import requests from pyepm import config as c config = c.get_default_config() has_solc = spawn.find_executable("solc") solc = pytest.mark.skipif(not has_solc, reason="solc compiler not found") COW_ADDRESS = '0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826' def is_h...
def mock_json_response(status_code=200, error=None, result=None): m = mock.MagicMock(spec=requests.Response) m.status_code = status_code base_json_response = {u'jsonrpc': u'2.0', u'id': u'c7c427a5-b6e9-4dbf-b218-a6f9d4f09246'} json_response = dict(base_json_response) if result: json_respon...
try: int(s, 16) return True except ValueError: return False
identifier_body
helpers.py
from distutils import spawn import mock import pytest import requests from pyepm import config as c config = c.get_default_config() has_solc = spawn.find_executable("solc") solc = pytest.mark.skipif(not has_solc, reason="solc compiler not found") COW_ADDRESS = '0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826' def is_h...
m.json.return_value = json_response return m
m.reason = 'Error Reason'
conditional_block
helpers.py
from distutils import spawn import mock import pytest import requests from pyepm import config as c config = c.get_default_config() has_solc = spawn.find_executable("solc") solc = pytest.mark.skipif(not has_solc, reason="solc compiler not found")
return True except ValueError: return False def mock_json_response(status_code=200, error=None, result=None): m = mock.MagicMock(spec=requests.Response) m.status_code = status_code base_json_response = {u'jsonrpc': u'2.0', u'id': u'c7c427a5-b6e9-4dbf-b218-a6f9d4f09246'} json_respons...
COW_ADDRESS = '0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826' def is_hex(s): try: int(s, 16)
random_line_split
helpers.py
from distutils import spawn import mock import pytest import requests from pyepm import config as c config = c.get_default_config() has_solc = spawn.find_executable("solc") solc = pytest.mark.skipif(not has_solc, reason="solc compiler not found") COW_ADDRESS = '0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826' def is_h...
(status_code=200, error=None, result=None): m = mock.MagicMock(spec=requests.Response) m.status_code = status_code base_json_response = {u'jsonrpc': u'2.0', u'id': u'c7c427a5-b6e9-4dbf-b218-a6f9d4f09246'} json_response = dict(base_json_response) if result: json_response[u'result'] = result ...
mock_json_response
identifier_name
mrp_production.py
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the...
workorder.cycle = cycle workorder.hour = wc.hour_nbr * cycle
cycle = int(math.ceil(cycle))
conditional_block
mrp_production.py
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the...
_inherit = 'mrp.production' def _get_workorder_in_product_lines( self, workcenter_lines, product_lines, properties=None): super(MrpProduction, self)._get_workorder_in_product_lines( workcenter_lines, product_lines, properties=properties) for workorder in workcenter_lines: ...
identifier_body
mrp_production.py
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the...
( self, workcenter_lines, product_lines, properties=None): super(MrpProduction, self)._get_workorder_in_product_lines( workcenter_lines, product_lines, properties=properties) for workorder in workcenter_lines: wc = workorder.routing_wc_line cycle = wc.cycl...
_get_workorder_in_product_lines
identifier_name
mrp_production.py
# -*- encoding: utf-8 -*- ############################################################################## # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the...
cycle = wc.cycle_nbr and (self.product_qty / wc.cycle_nbr) or 0 if self.company_id.complete_cycle: cycle = int(math.ceil(cycle)) workorder.cycle = cycle workorder.hour = wc.hour_nbr * cycle
super(MrpProduction, self)._get_workorder_in_product_lines( workcenter_lines, product_lines, properties=properties) for workorder in workcenter_lines: wc = workorder.routing_wc_line
random_line_split
pymonitor.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "pwxc" import os, sys, time, subprocess from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler def log(s): print('[Monitor] %s' % s) class MyFileSystemEventHander(FileSystemEventHandler): def __init__(self, fn)...
start_watch(path, None)
argv = sys.argv[1:] if not argv: print('Usage: ./pymonitor your-script.py') exit(0) if argv[0] != 'python': argv.insert(0, 'python') command = argv path = os.path.abspath('.')
conditional_block
pymonitor.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "pwxc" import os, sys, time, subprocess from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler def log(s):
class MyFileSystemEventHander(FileSystemEventHandler): def __init__(self, fn): super(MyFileSystemEventHander, self).__init__() self.restart = fn def on_any_event(self, event): if event.src_path.endswith('.py'): log('Python source file changed: %s' % event.src_path) ...
print('[Monitor] %s' % s)
identifier_body
pymonitor.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "pwxc" import os, sys, time, subprocess from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler def log(s): print('[Monitor] %s' % s) class MyFileSystemEventHander(FileSystemEventHandler): def __init__(self, fn)...
except KeyboardInterrupt: observer.stop() observer.join() if __name__ == '__main__': argv = sys.argv[1:] if not argv: print('Usage: ./pymonitor your-script.py') exit(0) if argv[0] != 'python': argv.insert(0, 'python') command = argv path = os.path.abspath('.'...
random_line_split
pymonitor.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "pwxc" import os, sys, time, subprocess from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler def log(s): print('[Monitor] %s' % s) class MyFileSystemEventHander(FileSystemEventHandler): def __init__(self, fn)...
(): kill_process() start_process() def start_watch(path, callback): observer = Observer() observer.schedule(MyFileSystemEventHander(restart_process), path, recursive=True) observer.start() log('Watching directory %s...' % path) start_process() try: while True: time.s...
restart_process
identifier_name
main.js
'use strict'; var BarChart = require('./charts/Bar.js'); var LineChart = require('./charts/Line.js'); var DonutChart = require('./charts/Donut.js'); var data = [{ label: 'Jan', data: 35 }, { label: 'Feb', data: 20 }, { label: 'Mar', data: 28 }, { label: 'Apr', data: 8 }, { ...
// Bar Chart var barChartConfig = { elementID: '#bar-chart', chartWidth: document.querySelector('.bar-chart-container').offsetWidth, chartHeight: 400, classes: { group: 'bar-group', bar: 'bar', label: 'labels' }, axis: { y: { ticks: 8 } }, margin: { top: 20, bot: 30, ...
{ return JSON.parse(JSON.stringify(obj)); }
identifier_body
main.js
'use strict'; var BarChart = require('./charts/Bar.js'); var LineChart = require('./charts/Line.js'); var DonutChart = require('./charts/Donut.js'); var data = [{ label: 'Jan', data: 35 }, { label: 'Feb', data: 20 }, { label: 'Mar', data: 28 }, { label: 'Apr', data: 8 }, { ...
}, ~~(Math.random() * 5000) + 5000); })(); // Line Chart var lineChartConfig = { elementID: '#line-chart', chartWidth: document.querySelector('.line-chart-container').offsetWidth, chartHeight: 400, axis: { y: { ticks: 8 } }, classes: { group: 'group', point: 'point', line: 'lin...
{ updateChart(updatedData.slice(~~(Math.random() * updatedData.length - 2))); }
conditional_block
main.js
'use strict'; var BarChart = require('./charts/Bar.js'); var LineChart = require('./charts/Line.js'); var DonutChart = require('./charts/Donut.js'); var data = [{ label: 'Jan', data: 35 }, { label: 'Feb', data: 20 }, { label: 'Mar', data: 28 }, { label: 'Apr', data: 8 }, { ...
(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; } function copy(obj) { return JSON.parse(JSON.stringify(obj)); } // Bar Chart var barChartConfig = { elementID: '#bar-chart', chartWidth: document.querySelector('.bar-chart-container'...
extend
identifier_name
main.js
'use strict'; var BarChart = require('./charts/Bar.js'); var LineChart = require('./charts/Line.js'); var DonutChart = require('./charts/Donut.js'); var data = [{ label: 'Jan', data: 35 }, { label: 'Feb', data: 20 }, { label: 'Mar', data: 28 }, { label: 'Apr', data: 8 }, { ...
left: 0, right: 0 } }; var donutChartConfig2 = extend(copy(donutChartConfig), { elementID: '#donut-chart2', colorScale: ['#2cc5c6', '#f1f3f2'] }); var donutChartConfig3 = extend(copy(donutChartConfig), { elementID: '#donut-chart3', colorScale: ['#58699A', '#f1f3f2'] }); var donutChart = new Don...
chartHeight: 150, colorScale: ['#56CB84', '#f1f3f2'], margin: { top: 0, bot: 0,
random_line_split