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
jcarousel.responsive.js
(function($) { $(function() { var jcarousel = $('.jcarousel'); jcarousel .on('jcarousel:reload jcarousel:create', function () { var width = jcarousel.innerWidth(); if (width >= 600) { width = width / 3; } else if (widt...
return '<a href="#' + page + '">' + page + '</a>'; } }); }); })(jQuery);
item: function(page) {
random_line_split
login.component.ts
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import {UserService} from "../../services/user/user.service"; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [], styleUrls: ['./login.scss'],
encapsulation: ViewEncapsulation.None }) export class LoginComponent { public view: any = { authenticated: false, email: '', password: '' }; constructor(private router: Router, private userService: UserService) { } login() { // Probably should use an Angular 2 Re...
random_line_split
login.component.ts
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import {UserService} from "../../services/user/user.service"; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [], styleUrls: ['./login.scss'], encap...
else { this.router.navigateByUrl('/IdeaFlow'); } }, error => { console.log(error); }); return false; } }
{ this.router.navigateByUrl('/TeamSetup'); }
conditional_block
login.component.ts
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import {UserService} from "../../services/user/user.service"; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [], styleUrls: ['./login.scss'], encap...
(private router: Router, private userService: UserService) { } login() { // Probably should use an Angular 2 Resolver instead of this constructor logic, but that whole mechanism seems too weighty this.userService.getUsers() .subscribe( users => { // Uncomment the next statement if ...
constructor
identifier_name
login.component.ts
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import {UserService} from "../../services/user/user.service"; @Component({ selector: 'app-login', templateUrl: './login.component.html', providers: [], styleUrls: ['./login.scss'], encap...
login() { // Probably should use an Angular 2 Resolver instead of this constructor logic, but that whole mechanism seems too weighty this.userService.getUsers() .subscribe( users => { // Uncomment the next statement if you want to force routing to /TeamSetup // users.length...
{ }
identifier_body
config.rs
//! Utilities for managing the configuration of the website. //! //! The configuration should contain values that I expect to change. This way, I can edit them all //! in a single human-readable file instead of having to track down the values in the code. use std::fs::File; use std::io::prelude::*; use std::path::Path...
}
{ let test_config = String::from( r#" --- resume_link: http://google.com "#, ); let expected_config = Config { resume_link: Url::parse("http://google.com").unwrap(), }; assert_eq!( expected_config, super::parse_config(test_config.as...
identifier_body
config.rs
//! Utilities for managing the configuration of the website. //! //! The configuration should contain values that I expect to change. This way, I can edit them all //! in a single human-readable file instead of having to track down the values in the code. use std::fs::File; use std::io::prelude::*; use std::path::Path...
() { let test_config = String::from( r#" --- resume_link: http://google.com "#, ); let expected_config = Config { resume_link: Url::parse("http://google.com").unwrap(), }; assert_eq!( expected_config, super::parse_config(test_config...
load_config
identifier_name
config.rs
//! Utilities for managing the configuration of the website. //! //! The configuration should contain values that I expect to change. This way, I can edit them all //! in a single human-readable file instead of having to track down the values in the code. use std::fs::File;
use serde_yaml; use url::Url; use url_serde; use crate::errors::*; /// Configuration values for the website. #[derive(Debug, PartialEq, Deserialize)] pub struct Config { /// A link to a PDF copy of my Resume. #[serde(with = "url_serde")] pub resume_link: Url, } fn parse_config<R>(reader: R) -> Result<Con...
use std::io::prelude::*; use std::path::Path; use log::*; use serde::Deserialize;
random_line_split
authorize-steps.js
/** * Created by moshensky on 6/17/15. */ import {inject} from 'aurelia-dependency-injection'; import {Session} from './session'; import {Logger} from './logger'; import {Locale} from './locale'; import {Config} from './config'; import {Redirect} from 'aurelia-router'; class BaseAuthorizeStep { constructor(sessio...
() { } } @inject(Session, Logger) export class RolesAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.roles) { return this.session.userHasAtLeastOneRole(navigationInstruction.co...
canAccess
identifier_name
authorize-steps.js
/** * Created by moshensky on 6/17/15. */ import {inject} from 'aurelia-dependency-injection'; import {Session} from './session'; import {Logger} from './logger'; import {Locale} from './locale'; import {Config} from './config'; import {Redirect} from 'aurelia-router'; class BaseAuthorizeStep { constructor(sessio...
return false; } } } canAccess() { } } @inject(Session, Logger) export class RolesAuthorizeStep extends BaseAuthorizeStep { constructor(session, logger) { super(session, logger); } canAccess(navigationInstruction) { if (navigationInstruction.config.roles) { return this.se...
random_line_split
authorize-steps.js
/** * Created by moshensky on 6/17/15. */ import {inject} from 'aurelia-dependency-injection'; import {Session} from './session'; import {Logger} from './logger'; import {Locale} from './locale'; import {Config} from './config'; import {Redirect} from 'aurelia-router'; class BaseAuthorizeStep { constructor(sessio...
run(navigationInstruction, next) { if (!this.session.isUserLoggedIn() && navigationInstruction.config.route !== this.loginRoute) { this.logger.warn(this.locale.translate('pleaseLogin')); return next.cancel(new Redirect(this.loginRoute)); } let canAccess = this.authorize(navigationInstructio...
{ this.session = session; this.logger = logger; this.locale = Locale.Repository.default; this.loginRoute = Config.routerAuthStepOpts.loginRoute; }
identifier_body
authorize-steps.js
/** * Created by moshensky on 6/17/15. */ import {inject} from 'aurelia-dependency-injection'; import {Session} from './session'; import {Logger} from './logger'; import {Locale} from './locale'; import {Config} from './config'; import {Redirect} from 'aurelia-router'; class BaseAuthorizeStep { constructor(sessio...
let canAccess = this.authorize(navigationInstruction); if (canAccess === false) { this.logger.error(this.locale.translate('notAuthorized')); return next.cancel(); } return next(); } authorize(navigationInstruction) { if (navigationInstruction.parentInstruction === null) { r...
{ this.logger.warn(this.locale.translate('pleaseLogin')); return next.cancel(new Redirect(this.loginRoute)); }
conditional_block
actions.ts
"./jupyter-actions"; interface JupyterEditorState extends CodeEditorState { slideshow?: { state?: "built" | "building" | ""; url?: string; }; } import { JupyterActions } from "../../jupyter/browser-actions"; import { NotebookFrameActions } from "./cell-notebook/actions"; export class JupyterEditorActio...
this.setState({ is_saving: false }); } } protected async get_shell_spec( id: string ): Promise<undefined | { command: string; args: string[] }> { id = id; // not used // TODO: need to find out the file that corresponds to // socket and put in args. Can find with ps on the pid. // A...
random_line_split
actions.ts
if (type !== "jupyter_cell_notebook") { return; } // important to do this *before* the frame is rendered, // since it can cause changes during creation. this.get_frame_actions(id); }); for (const id in this._get_leaf_ids()) { const node = this._get_frame_node(id); ...
w_introspect():
identifier_name
actions.ts
} private init_new_frame(): void { this.store.on("new-frame", ({ id, type }) => { if (type !== "jupyter_cell_notebook") { return; } // important to do this *before* the frame is rendered, // since it can cause changes during creation. this.get_frame_actions(id); }); ...
const id = this.show_focused_frame_of_type( "jupyter_table_of_contents", "col", true, 1 / 3 ); // the click to select TOC focuses the active id back on the notebook await delay(0); if (this._state === "closed") return; this.set_active_id(id, true); }
identifier_body
amount-store.ts
import { Map, List, Iterable, Iterator } from 'immutable'; import { Amount, Metric } from './amount'; export interface AmountStore<K, V extends Metric> { store: Map<K, Amount<V>>; } export class AmountStore<K, V extends Metric> implements AmountStore<K, V> { constructor(store: Map<K, Amount<V>>) { this.store ...
} getStore() { return this.store; } }
random_line_split
amount-store.ts
import { Map, List, Iterable, Iterator } from 'immutable'; import { Amount, Metric } from './amount'; export interface AmountStore<K, V extends Metric> { store: Map<K, Amount<V>>; } export class AmountStore<K, V extends Metric> implements AmountStore<K, V> { constructor(store: Map<K, Amount<V>>) { this.store ...
}
{ return this.store; }
identifier_body
amount-store.ts
import { Map, List, Iterable, Iterator } from 'immutable'; import { Amount, Metric } from './amount'; export interface AmountStore<K, V extends Metric> { store: Map<K, Amount<V>>; } export class AmountStore<K, V extends Metric> implements AmountStore<K, V> { constructor(store: Map<K, Amount<V>>) { this.store ...
() { return this.store; } }
getStore
identifier_name
index.tsx
import { Zerotorescue } from 'CONTRIBUTORS'; import NewsRegularArticle from 'interface/NewsRegularArticle'; import React from 'react';
Because Warcraft Logs offers no way to access private logs through the API, your logs must either be unlisted or public if you want to analyze them. If your guild has private logs you will have to <a href="https://www.warcraftlogs.com/help/start/">upload your own logs</a> or change the existing logs to ...
export const title = 'A note about unlisted logs'; export default ( <NewsRegularArticle title={title} publishedAt="2017-01-31" publishedBy={Zerotorescue}>
random_line_split
os.rs
_, 0]; module = c::GetModuleHandleW(NTDLL_DLL.as_ptr()); if module != ptr::null_mut() { errnum ^= c::FACILITY_NT_BIT as i32; flags = c::FORMAT_MESSAGE_FROM_HMODULE; } } let res = c::FormatMessageW(flags | c::FORMAT_MESSAGE_FROM_SYSTE...
getpid
identifier_name
os.rs
sys::{c, cvt}; use sys::handle::Handle; use super::to_u16s; pub fn errno() -> i32 { unsafe { c::GetLastError() as i32 } } /// Gets a detailed string description for the given error number. pub fn error_string(mut errnum: i32) -> String { // This value is calculated from the macro // MAKELANGID(LANG_SYST...
else { joined.extend_from_slice(&v[..]); } } Ok(OsStringExt::from_wide(&joined[..])) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "path segment contains `\"`".fmt(f) } } impl StdError for JoinPathsError { fn descripti...
{ joined.push(b'"' as u16); joined.extend_from_slice(&v[..]); joined.push(b'"' as u16); }
conditional_block
os.rs
sys::{c, cvt}; use sys::handle::Handle; use super::to_u16s; pub fn errno() -> i32 { unsafe { c::GetLastError() as i32 } } /// Gets a detailed string description for the given error number. pub fn error_string(mut errnum: i32) -> String { // This value is calculated from the macro // MAKELANGID(LANG_SYST...
}; return Some(( OsStringExt::from_wide(&s[..pos]), OsStringExt::from_wide(&s[pos+1..]), )) } } } } impl Drop for Env { fn drop(&mut self) { unsafe { c::FreeEnvironmentStringsW(self.base); } ...
{ loop { unsafe { if *self.cur == 0 { return None } let p = &*self.cur as *const u16; let mut len = 0; while *p.offset(len) != 0 { len += 1; } let s = slice::from_raw_parts(p, len as u...
identifier_body
os.rs
use sys::{c, cvt}; use sys::handle::Handle; use super::to_u16s; pub fn errno() -> i32 { unsafe { c::GetLastError() as i32 } } /// Gets a detailed string description for the given error number. pub fn error_string(mut errnum: i32) -> String { // This value is calculated from the macro // MAKELANGID(LANG_S...
if !must_yield && in_progress.is_empty() { None } else { Some(super::os2path(&in_progress)) } } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item=T>, T: AsRef<OsStr> { ...
} else { in_progress.push(b) } }
random_line_split
base_props.rs
use crate::core::{Directedness, Graph}; use num_traits::{One, PrimInt, Unsigned, Zero}; use std::borrow::Borrow; /// A graph where new vertices can be added pub trait NewVertex: Graph { /// Adds a new vertex with the given weight to the graph. /// Returns the id of the new vertex. fn new_vertex_weighted(&mut self, ...
} rest_iter = iter.clone(); } count } }
{ self.edges_between(v2.borrow(), v.borrow()) .for_each(|_| inc()); }
conditional_block
base_props.rs
use crate::core::{Directedness, Graph}; use num_traits::{One, PrimInt, Unsigned, Zero}; use std::borrow::Borrow; /// A graph where new vertices can be added pub trait NewVertex: Graph { /// Adds a new vertex with the given weight to the graph. /// Returns the id of the new vertex. fn new_vertex_weighted(&mut self, ...
/// - No vertices are introduced or removed. /// /// ###`Err` properties: /// /// - The graph is unchanged. fn add_edge( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<(), ()> where Self::EdgeWeight: Default, { self.add_edge_weighted(source, sink, Self::Edg...
/// - Only the given edge is added to the graph. /// - Existing edges are unchanged.
random_line_split
base_props.rs
use crate::core::{Directedness, Graph}; use num_traits::{One, PrimInt, Unsigned, Zero}; use std::borrow::Borrow; /// A graph where new vertices can be added pub trait NewVertex: Graph { /// Adds a new vertex with the given weight to the graph. /// Returns the id of the new vertex. fn new_vertex_weighted(&mut self, ...
} /// A graph where vertices can be removed. /// /// Removing a vertex may invalidate existing vertices. pub trait RemoveVertex: Graph { /// Removes the given vertex from the graph, returning its weight. /// If the vertex still has edges incident on it, they are also removed, /// dropping their weights. fn remove...
{ self.new_vertex_weighted(Self::VertexWeight::default()) }
identifier_body
base_props.rs
use crate::core::{Directedness, Graph}; use num_traits::{One, PrimInt, Unsigned, Zero}; use std::borrow::Borrow; /// A graph where new vertices can be added pub trait NewVertex: Graph { /// Adds a new vertex with the given weight to the graph. /// Returns the id of the new vertex. fn new_vertex_weighted(&mut self, ...
( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, ) -> Result<(), ()> where Self::EdgeWeight: Default, { self.add_edge_weighted(source, sink, Self::EdgeWeight::default()) } } pub trait RemoveEdge: Graph { fn remove_edge_where_weight<F>( &mut self, source: impl Borrow<S...
add_edge
identifier_name
sw.js
/** * Copyright 2018 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applic...
workbox.precaching.precacheAndRoute([]); workbox.routing.registerRoute(/\.(?:html|css)$/, workbox.strategies.cacheFirst({ cacheName: 'pages', }) ); workbox.routing.registerRoute(/\.(?:png|gif|jpg)$/, workbox.strategies.cacheFirst({ cacheName: 'images', plugins: [ new workbox.expiration.Plugin...
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js');
random_line_split
signal-exit-status.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1] == "signal".to_owned() { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } else { let status = Process::status(args[0], ["signal".to_owned()]).unwrap(); // Windows does not have signa...
identifier_body
signal-exit-status.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // copyright 2013-2014 the rust project developers. see the copyright // file at the top...
// 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
random_line_split
signal-exit-status.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}
{ let status = Process::status(args[0], ["signal".to_owned()]).unwrap(); // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK). match status { ExitSignal(_) if cfg!(unix) => {}, ExitStatus(0xC0000028) if cfg!(windows) => {}, _ =>...
conditional_block
signal-exit-status.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1] == "signal".to_owned() { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } else { let status = Process::status(args[0], ["signal".to_owned()]).unwrap(); // Windows does not have si...
main
identifier_name
setup_plugin.py
.log("Configuring sysctl") with open('/etc/sysctl.conf', 'r') as f: sysctl = f.readlines() if sysvipc: cmd = str("sysctl %s=1" % ipc_setting) self.log('Executing: `%s`' % cmd) subprocess.Popen(shlex.split(cmd)).wait() if self._has_line(sysct...
_createJail
identifier_name
setup_plugin.py
''' Setups ezjail in the virtual machine ''' def run(self): base_dir = cherrypy.config.get('setup_plugin.jail_dir') dst_dir = '%s/flavours' % base_dir if not os.path.isdir(dst_dir): try: self.log("Creating folder `%s`." % dst_dir) os....
""" Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition. """ def __init__(self, bus, queue, outqueue, puck): super(self.__class__, self).__init__() self._stop = threading.Event() self.running = threading.Event() self.su...
identifier_body
setup_plugin.py
): # Stop it in case it commands = ['/etc/rc.d/pf stop', '/etc/rc.d/pf start'] for command in commands: self.log("Executing: `%s`" % command) subprocess.Popen(shlex.split(str(command))).wait() def setup_pf_conf(self, pf_conf): rules = self.vm.firewall ...
missing = set(rc_items.keys()) - set(rc_present) tpl = 'Adding to rc: `%s="%s"`' [self.log(tpl % (k, rc_items[k])) for k in missing] template = '%s="%s"\n' with open(rc_conf, 'a') as f: [f.write(template % (k,rc_items[k])) for k in missing] f.flush() ...
if line.startswith(k): rc_present.append(k) break
conditional_block
setup_plugin.py
"%s/installdata/authorized_keys" % path resolv_file = "%s/etc/resolv.conf" % path yum_file = "%s/installdata/yum_repo" % path rc_file = "%s/etc/rc.conf" % path host_file = "%s/etc/hosts" % path # Create /installdata and /etc folder. for p in ['%s...
random_line_split
riak_repl.py
import json import unicodedata from requests.exceptions import ConnectionError, Timeout from six import iteritems from datadog_checks.base import AgentCheck from datadog_checks.base.errors import CheckException class RiakReplCheck(AgentCheck): REPL_STATS = { "server_bytes_sent", "server_bytes_r...
return self.exists(obj[_key], nest) if nest else obj[_key]
conditional_block
riak_repl.py
import json import unicodedata from requests.exceptions import ConnectionError, Timeout from six import iteritems from datadog_checks.base import AgentCheck from datadog_checks.base.errors import CheckException class
(AgentCheck): REPL_STATS = { "server_bytes_sent", "server_bytes_recv", "server_connects", "server_connect_errors", "server_fullsyncs", "client_bytes_sent", "client_bytes_recv", "client_connects", "client_connect_errors", "client_redire...
RiakReplCheck
identifier_name
riak_repl.py
import json import unicodedata from requests.exceptions import ConnectionError, Timeout from six import iteritems from datadog_checks.base import AgentCheck from datadog_checks.base.errors import CheckException class RiakReplCheck(AgentCheck): REPL_STATS = { "server_bytes_sent", "server_bytes_r...
def exists(self, obj, nest): _key = nest.pop(0) if _key in obj: return self.exists(obj[_key], nest) if nest else obj[_key]
tags = [] if tags is None else tags try: self.gauge(name, float(value), tags=tags) return except ValueError: self.log.debug("metric name %s cannot be converted to a float: %s", name, value) try: self.gauge(name, unicodedata.numeric(value), tags=ta...
identifier_body
riak_repl.py
import json import unicodedata from requests.exceptions import ConnectionError, Timeout from six import iteritems from datadog_checks.base import AgentCheck from datadog_checks.base.errors import CheckException class RiakReplCheck(AgentCheck): REPL_STATS = { "server_bytes_sent", "server_bytes_r...
if stats['realtime_started'] is not None: for key, val in iteritems(stats['realtime_queue_stats']): if key in self.REALTIME_QUEUE_STATS: self.safe_submit_metric( "riak_repl.realtime_queue_stats." + key, val, tags=tags + ['cluster:%s' % clu...
cluster = stats['cluster_name'] for key, val in iteritems(stats): if key in self.REPL_STATS: self.safe_submit_metric("riak_repl." + key, val, tags=tags + ['cluster:%s' % cluster])
random_line_split
macros.rs
/// Equivalent to the `println!` macro except that a newline is not printed at /// the end of the message. /// /// Note that stdout is frequently line-buffered by default so it may be /// necessary to use `io::stdout().flush()` to ensure the output is emitted /// immediately. /// /// # Panics /// /// Panics if writing ...
#[cfg(test)] macro_rules! log { ($lvl:expr, $($args:tt)*) => ( if log_enabled!($lvl) { println!($($args)*) } ) } #[cfg(test)] macro_rules! assert_approx_eq { ($a:expr, $b:expr) => ({ let (a, b) = (&$a, &$b); assert!((*a - *b).abs() < 1.0e-6, "{} is not approximately ...
random_line_split
Login.tsx
import React from 'react' import { makeStyles, Button, TextField, FormControlLabel, Checkbox, Link, Grid, } from '@material-ui/core' import { Link as RouterLink } from 'react-router-dom' import AuthHeader from '../_common/AuthHeader' import AuthContent from '../_common/AuthContent' const Login: React.FC...
color="primary" className={classes.submit} > Sign In </Button> <Grid container> <Grid item xs> <Link component={RouterLink} to="/auth/recover" variant="body2"> Forgot password? </Link> </Grid> <Grid...
type="submit" fullWidth variant="contained"
random_line_split
bing.py
grad[grad>255] = 255 return grad.astype(np.uint8) def rgb_gradient(img): img = img.astype(float) h,w, nch = img.shape gradientX = np.zeros((h,w)) gradientY = np.zeros((h,w)) d1 = np.abs(img[:,1,:] - img[:,0,:]) gradientX[:,0] = np.max( d1, axis = 1) * 2 d2 = np.a...
elif o == "--num_bbs_per_size": try: params["num_win_psz"] = int(a) except Exception as e: print "Error while converting parameter --num_bb_per_size %s to int. Exception: %s."%(a,e) sys.exit(2) elif o == "--num_bbs": tr...
print "python bing.py --num_bbs_per_size 130 --num_bbs 1500 /path/to/dataset/parameters.json /path/to/image.jpg" sys.exit(0)
conditional_block
bing.py
grad[grad>255] = 255 return grad.astype(np.uint8) def rgb_gradient(img): img = img.astype(float) h,w, nch = img.shape gradientX = np.zeros((h,w)) gradientY = np.zeros((h,w)) d1 = np.abs(img[:,1,:] - img[:,0,:]) gradientX[:,0] = np.max( d1, axis = 1) * 2 d2 = np.a...
if (h > img_h * self.base_log) or (w > img_w * self.base_log): continue h = min(h, img_h) w = min(w, img_w) new_w = int(round(float(self.edge)*img_w/w)) new_h = int(round(float(self.edge)*img_h/h)) img_resized = cv2.resize(image,(ne...
def __init__(self, weights_1st_stage, scale_space_sizes_idxs, num_win_psz = 130, edge = EDGE, base_log = BASE_LOG, min_edge_log = MIN_EDGE_LOG, edge_log_range = EDGE_LOG_RANGE): self.filter_tig = FilterTIG() self.weights_1st_stage = weights_1st_stage self.filter_tig.update(self.weights_...
identifier_body
bing.py
(img, ksize): gray = cv2.cvtColor(img, cv2.cv.CV_BGR2GRAY) x = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=ksize) y = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=ksize) mag = magnitude(x,y) return mag def sobel_gradient_8u(img, ksize): grad = sobel_gradient(img, ksize) grad[grad<0] = 0 grad[grad>255] =...
sobel_gradient
identifier_name
bing.py
grad[grad>255] = 255 return grad.astype(np.uint8) def rgb_gradient(img): img = img.astype(float) h,w, nch = img.shape gradientX = np.zeros((h,w)) gradientY = np.zeros((h,w)) d1 = np.abs(img[:,1,:] - img[:,0,:]) gradientX[:,0] = np.max( d1, axis = 1) * 2 d2 = np.a...
new_w = int(round(float(self.edge)*img_w/w)) new_h = int(round(float(self.edge)*img_h/h)) img_resized = cv2.resize(image,(new_w,new_h)) grad = rgb_gradient(img_resized) match_map = self.filter_tig.match_template(grad) points = self.filter_tig.non_m...
h = round(pow(self.base_log, size_idx // self.edge_log_range + self.min_edge_log)) if (h > img_h * self.base_log) or (w > img_w * self.base_log): continue h = min(h, img_h) w = min(w, img_w)
random_line_split
area120tables_v1alpha1_generated_tables_service_list_tables_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# [END area120tables_v1alpha1_generated_TablesService_ListTables_async]
client = tables_v1alpha1.TablesServiceAsyncClient() # Initialize request argument(s) request = tables_v1alpha1.ListTablesRequest( ) # Make the request page_result = client.list_tables(request=request) # Handle the response async for response in page_result: print(response)
identifier_body
area120tables_v1alpha1_generated_tables_service_list_tables_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
(): # Create a client client = tables_v1alpha1.TablesServiceAsyncClient() # Initialize request argument(s) request = tables_v1alpha1.ListTablesRequest( ) # Make the request page_result = client.list_tables(request=request) # Handle the response async for response in page_result: ...
sample_list_tables
identifier_name
area120tables_v1alpha1_generated_tables_service_list_tables_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Snippet for ListTables # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-area120-tables # [START area120tabl...
# See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! #
random_line_split
area120tables_v1alpha1_generated_tables_service_list_tables_async.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# [END area120tables_v1alpha1_generated_TablesService_ListTables_async]
print(response)
conditional_block
encoding.ts
private decodeStreamPromise: Promise<void>; private bufferedChunks: Buffer[] = []; private bytesBuffered = 0; _write(chunk: Buffer, encoding: string, callback: (error: Error | null) => void): void { if (!Buffer.isBuffer(chunk)) { return callback(new Error('toDecodeStream(): data must be a buffer'))...
}, error => { this.emit('error', error); callback(error); }); } _final(callback: (error: Error | null) => void) { // normal finish if (this.decodeStream) { this.decodeStream.end(callback); } // we were still waiting for data to do the encoding // detection. thus, wra...
// signal to the outside our detected encoding // and final decoder stream resolve({ detected, stream: this.decodeStream });
random_line_split
encoding.ts
private decodeStreamPromise: Promise<void>; private bufferedChunks: Buffer[] = []; private bytesBuffered = 0;
(chunk: Buffer, encoding: string, callback: (error: Error | null) => void): void { if (!Buffer.isBuffer(chunk)) { return callback(new Error('toDecodeStream(): data must be a buffer')); } // if the decode stream is ready, we just write directly if (this.decodeStream) { this.decodeStream.write(...
_write
identifier_name
encoding.ts
private decodeStreamPromise: Promise<void>; private bufferedChunks: Buffer[] = []; private bytesBuffered = 0; _write(chunk: Buffer, encoding: string, callback: (error: Error | null) => void): void { if (!Buffer.isBuffer(chunk)) { return callback(new Error('toDecodeStream(): data must be a buffer'))...
}; // errors readable.on('error', reject); // pipe through readable.pipe(writer); }); } export function decode(buffer: Buffer, encoding: string): string { return iconv.decode(buffer, toNodeEncoding(encoding)); } export function encode(content: string | Buffer, encoding: string, options?: { addBOM?: boo...
{ // normal finish if (this.decodeStream) { this.decodeStream.end(callback); } // we were still waiting for data to do the encoding // detection. thus, wrap up starting the stream even // without all the data to get things going else { this._startDecodeStream(() => this.decodeStr...
identifier_body
index.js
var http = require("http"); var fs = require("fs"); var handlerNames = fs.readdirSync("./handlers"); handlerNames = handlerNames.map(function(file){return file.replace(".js", "")}); var argv = require('yargs') .usage('Usage: $0 <command> [options]') .demand('handler') .describe('handler', 'Choose a h...
var port = 8002; var server = http.createServer(handleRequest); server.listen(port, function () { console.log("Listening on: http://127.0.01:%s", port); });
{ handler(workFunction, function(err, data){ response.end(data); }); }
identifier_body
index.js
var http = require("http"); var fs = require("fs"); var handlerNames = fs.readdirSync("./handlers"); handlerNames = handlerNames.map(function(file){return file.replace(".js", "")}); var argv = require('yargs') .usage('Usage: $0 <command> [options]') .demand('handler') .describe('handler', 'Choose a h...
var workFunction = function(callback){ var delay = baseTime + (additionalTimePerQuery * pendingQueries); pendingQueries += 1; console.log(timestamp() + "\tWork Starting. Pending:\t" + pendingQueries + " Delay: " + delay); setTimeout(function(){ callback(null, "Hello World"); pendingQu...
}
random_line_split
index.js
var http = require("http"); var fs = require("fs"); var handlerNames = fs.readdirSync("./handlers"); handlerNames = handlerNames.map(function(file){return file.replace(".js", "")}); var argv = require('yargs') .usage('Usage: $0 <command> [options]') .demand('handler') .describe('handler', 'Choose a h...
var logMemory = function(){ console.log(timestamp() + "\t" + (process.memoryUsage().rss/(1024*1024)).toFixed(2) + " MB"); } setInterval(logMemory, 5000); if(typeof handler === "undefined"){ throw new Error("Unknown handler chosen"); } function handleRequest(request, response) { handler(workFunction, f...
{ throw new Error("Unknown handler '"+argv.handler+"'. Available Handlers: " + handlerNames.join(", ")) }
conditional_block
index.js
var http = require("http"); var fs = require("fs"); var handlerNames = fs.readdirSync("./handlers"); handlerNames = handlerNames.map(function(file){return file.replace(".js", "")}); var argv = require('yargs') .usage('Usage: $0 <command> [options]') .demand('handler') .describe('handler', 'Choose a h...
(request, response) { handler(workFunction, function(err, data){ response.end(data); }); } var port = 8002; var server = http.createServer(handleRequest); server.listen(port, function () { console.log("Listening on: http://127.0.01:%s", port); });
handleRequest
identifier_name
custom-mode-characteristics.component.ts
import { Component } from '@angular/core'; import { CustomModeCharacteristicsService } from './custom-mode-characteristics.service'; import { ChordCharacteristics } from './chord-characteristics'; import { Router } from '@angular/router'; @Component({ selector: 'custom-mode-characteristics', templateUrl: 'app/...
} onChordInversionSelected(inversion: string) { //Setting or unsetting a chord inversion in the selected characteristics. let isSet = this.selectedChordInversions.get(inversion); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chor...
{ this.selectedChordQualities.set(quality, !isSet); }
conditional_block
custom-mode-characteristics.component.ts
import { Component } from '@angular/core'; import { CustomModeCharacteristicsService } from './custom-mode-characteristics.service'; import { ChordCharacteristics } from './chord-characteristics'; import { Router } from '@angular/router'; @Component({ selector: 'custom-mode-characteristics', templateUrl: 'app/...
this.selectedChordInversions.set(inversion, !isSet); } } onStartTrainerButtonSelected() { // Building an array of selected chord qualities. If none were selected, // then all are available to be tested on and they are added to the array. let chordQualities: string[] = [ ]; this.selectedCh...
return; } else {
random_line_split
custom-mode-characteristics.component.ts
import { Component } from '@angular/core'; import { CustomModeCharacteristicsService } from './custom-mode-characteristics.service'; import { ChordCharacteristics } from './chord-characteristics'; import { Router } from '@angular/router'; @Component({ selector: 'custom-mode-characteristics', templateUrl: 'app/...
(private customModeCharacteristicsService: CustomModeCharacteristicsService, private router : Router) {} ngOnInit() { this.customModeCharacteristicsService.getCustomModeChordCharacteristics() .then(characteristics => this.initializeChordCharacteristics(characteristics)) .catch(error => window.alert(e...
constructor
identifier_name
custom-mode-characteristics.component.ts
import { Component } from '@angular/core'; import { CustomModeCharacteristicsService } from './custom-mode-characteristics.service'; import { ChordCharacteristics } from './chord-characteristics'; import { Router } from '@angular/router'; @Component({ selector: 'custom-mode-characteristics', templateUrl: 'app/...
onChordInversionSelected(inversion: string) { //Setting or unsetting a chord inversion in the selected characteristics. let isSet = this.selectedChordInversions.get(inversion); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord in...
{ //Setting or unsetting a chord quality in the selected characteristics. let isSet = this.selectedChordQualities.get(quality); if (isSet === undefined) { // If it can't find the value, then there is a bug. window.alert("Cannot select chord quality"); return; } else { this.se...
identifier_body
metrics.rs
use std::fmt; use std::time::Duration; use tic::Receiver; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Metric { Request, Processed, } impl fmt::Display for Metric { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} pub fn init(listen: Option<String>) -> Receiver<Metric> { let mut config = Receiver::<Metric>::configure() .batch_size(1) .capacity(4096) .poll_delay(Some(Duration::new(0, 1_000_000))) .service(true); if let Some(addr) = listen { info!("listening STATS {}", addr); ...
{ match *self { Metric::Request => write!(f, "request"), Metric::Processed => write!(f, "processed"), } }
identifier_body
metrics.rs
use std::fmt; use std::time::Duration; use tic::Receiver; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Metric { Request, Processed, } impl fmt::Display for Metric { fn
(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Metric::Request => write!(f, "request"), Metric::Processed => write!(f, "processed"), } } } pub fn init(listen: Option<String>) -> Receiver<Metric> { let mut config = Receiver::<Metric>::configure() ....
fmt
identifier_name
metrics.rs
use std::fmt; use std::time::Duration; use tic::Receiver; #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub enum Metric { Request, Processed, } impl fmt::Display for Metric { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self {
} } } pub fn init(listen: Option<String>) -> Receiver<Metric> { let mut config = Receiver::<Metric>::configure() .batch_size(1) .capacity(4096) .poll_delay(Some(Duration::new(0, 1_000_000))) .service(true); if let Some(addr) = listen { info!("listening STATS...
Metric::Request => write!(f, "request"), Metric::Processed => write!(f, "processed"),
random_line_split
FormElements.story.tsx
/** * @author Stéphane LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import { StoryHeading } from "@library/storybook/StoryHeading"; import { storiesOf } from "@storybook/react"; import React, { CSSProperties } from "react"; import { StoryContent } fr...
<Checkbox label="Option B" /> <Checkbox label="Option C" /> <Checkbox label="Option D" /> </CheckboxGroup> <StoryHeading>Toggles</StoryHeading> <div style={flexHelper().middle() as CSSProperties}> <StoryToggle accessible...
<CheckboxGroup label={"A sleuth of check boxes"}> <Checkbox label="Option A" />
random_line_split
FormElements.story.tsx
/** * @author Stéphane LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import { StoryHeading } from "@library/storybook/StoryHeading"; import { storiesOf } from "@storybook/react"; import React, { CSSProperties } from "react"; import { StoryContent } fr...
Omit<React.ComponentProps<typeof FormToggle>, "onChange">) { return ( <InputBlock label={props.accessibleLabel}> <FormToggle {...props} enabled={false} onChange={doNothing} /> </InputBlock> ); }
gle(props:
identifier_name
FormElements.story.tsx
/** * @author Stéphane LaFlèche <stephane.l@vanillaforums.com> * @copyright 2009-2019 Vanilla Forums Inc. * @license GPL-2.0-only */ import { StoryHeading } from "@library/storybook/StoryHeading"; import { storiesOf } from "@storybook/react"; import React, { CSSProperties } from "react"; import { StoryContent } fr...
turn ( <InputBlock label={props.accessibleLabel}> <FormToggle {...props} enabled={false} onChange={doNothing} /> </InputBlock> ); }
identifier_body
permissionstatus.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::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName}; use d...
impl Display for PermissionName { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", self.as_str()) } }
}
random_line_split
permissionstatus.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::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName}; use d...
}
{ write!(f, "{}", self.as_str()) }
identifier_body
permissionstatus.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::PermissionStatusBinding::{self, PermissionDescriptor, PermissionName}; use d...
(global: &GlobalScope, query: &PermissionDescriptor) -> DomRoot<PermissionStatus> { reflect_dom_object(Box::new(PermissionStatus::new_inherited(query.name)), global, PermissionStatusBinding::Wrap) } pub fn set_state(&self, state: PermissionState) { ...
new
identifier_name
polylinize.py
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w...
else: poly.append(connected_line) align_lines(line, connected_line) lines.remove(connected_line) line = connected_line else: break def find_polylines(lines, endpoint_hash): polylines = [] while lines: line = lines.pop...
poly.insert(0, connected_line)
conditional_block
polylinize.py
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w...
(svg): lines = get_lines(svg) print '%s line segments found' % len(lines) lines_by_width = defaultdict(list) for l in lines: lines_by_width[l.strokeWidth].append(l) del lines print '%s different stroke widths found:' % len(lines_by_width) for width, lines in lines_by_width.iteritem...
optimize
identifier_name
polylinize.py
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w...
l = len(lines) if l > 1: count += 1 return count def _del_line(self, key, line): self.endpoints[key].remove(line) if len(self.endpoints[key]) == 0: del self.endpoints[key] def remove_line(self, line): key = line.start_hash() ...
for key, lines in self.endpoints.iteritems():
random_line_split
polylinize.py
#!/usr/bin/env python # Convert line elements with overlapping endpoints into polylines in an # SVG file. import os import sys try: from lxml import etree except ImportError: import xml.etree.ElementTree as etree from collections import defaultdict from optparse import OptionParser SVG_NS = 'http://www.w...
def count_overlapping_points(self): count = 0 for key, lines in self.endpoints.iteritems(): l = len(lines) if l > 1: count += 1 return count def _del_line(self, key, line): self.endpoints[key].remove(line) if len(self.endpoints[k...
self.endpoints = defaultdict(list) for l in lines: self.endpoints[l.start_hash()].append(l) self.endpoints[l.end_hash()].append(l)
identifier_body
mdui.js
attr('disabled', true); // 禁用modal按钮 confirmModalInfo('正在处理,请稍后...', ' fa-spinner fa-spin '); //进行ajax处理 CommonAjax($(DelBtn).data('objurl'), 'GET', '', function (data) { if (data['status'] == '200') { confirmModalInfo(data['...
ModalClose() { var modal = $('#ConfirmModal');
conditional_block
mdui.js
= $('#ConfirmModal'); // 获取modal对象 modal.find('button').attr('disabled', true); // 禁用modal按钮 confirmModalInfo('正在处理,请稍后...', ' fa-spinner fa-spin '); //进行ajax处理 CommonAjax($(DelBtn).data('objurl'), 'GET', '', function (data) { if (...
/** * 提示信息弹出框关闭
random_line_split
mdui.js
//监听删除按钮点击事件 $('[data-toggle="doAjax"]').each(function () { $(this).click(function (e) { e.preventDefault(); var DelBtn = $(this); confirmModalOpen($(DelBtn).data('info')); // 提示信息 $('#ConfirmModal').find('#btnConfirm').click(function () { ...
param info 文字信息
identifier_name
mdui.js
} setTimeout(function () { window.location.replace(window.location.href); }, 2000); }) }) $('#ConfirmModal').on('hidden.bs.modal', function (e) { e.preventDefault(); ...
.ajax({ url: url, type: type, data: data, dataType: 'json', success: function (result) { success && success(r
identifier_body
polyfills.ts
/** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are * sorted by browsers. * 2. Application imports. Files impor...
* (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch * requestAnimationFrame (window as any).__Zone_disable_on_property = true; // * disable patch onProperty such as onclick (window as * any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable * patch specified eventNam...
* * The following flags will work for all browsers. *
random_line_split
url_monitor.py
#!/usr/bin/env python # -*- encoding:utf-8 -*- __author__ = 'kairong' #解决crontab中无法执行的问题 import sys reload(sys) sys.setdefaultencoding('utf8') import ConfigParser import MySQLdb import requests import re from socket import socket, SOCK_DGRAM, AF_INET from multiprocessing import Process ###函数声明区域 def get_localIP(): ...
"" return cf.get(main, name) def check_url(id, url, keyword, method='GET'): '''检查域名和关键词,并把结果写入db''' r = requests.get(url) if r.status_code <=400 and re.search(unicode(keyword), r.text): c_result = 0 else: c_result = 1 status_2_db(id, c_result) def status_2_db(id, status): ...
NET, SOCK_DGRAM) s.connect(('google.com', 0)) return s.getsockname()[0] def get_args(main, name): """获取配置"
identifier_body
url_monitor.py
#!/usr/bin/env python # -*- encoding:utf-8 -*- __author__ = 'kairong' #解决crontab中无法执行的问题 import sys reload(sys) sys.setdefaultencoding('utf8') import ConfigParser import MySQLdb import requests import re from socket import socket, SOCK_DGRAM, AF_INET from multiprocessing import Process ###函数声明区域 def get_localIP(): ...
词,并把结果写入db''' r = requests.get(url) if r.status_code <=400 and re.search(unicode(keyword), r.text): c_result = 0 else: c_result = 1 status_2_db(id, c_result) def status_2_db(id, status): '''把结果写入db''' conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd=db_pass, db='ur...
''检查域名和关键
identifier_name
url_monitor.py
#!/usr/bin/env python # -*- encoding:utf-8 -*- __author__ = 'kairong' #解决crontab中无法执行的问题 import sys reload(sys) sys.setdefaultencoding('utf8') import ConfigParser import MySQLdb import requests import re from socket import socket, SOCK_DGRAM, AF_INET from multiprocessing import Process ###函数声明区域 def get_localIP(): ...
cur = conn.cursor() cur.execute("select * from montior_url;") while True: line = cur.fetchone() if not line: break c_id, c_domain, c_location, c_method, c_keyword = line[0], line[1], line[2], line[3], line[4] c_url = "http://%s%s" % (c_domain,c_location) ...
conn.close() def main(): conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd='test', db='url_mon',charset='utf8')
random_line_split
url_monitor.py
#!/usr/bin/env python # -*- encoding:utf-8 -*- __author__ = 'kairong' #解决crontab中无法执行的问题 import sys reload(sys) sys.setdefaultencoding('utf8') import ConfigParser import MySQLdb import requests import re from socket import socket, SOCK_DGRAM, AF_INET from multiprocessing import Process ###函数声明区域 def get_localIP(): ...
ine[3], line[4] c_url = "http://%s%s" % (c_domain,c_location) if c_method == line[5]: c_post_d = line[6] Process(target=check_url, args=(c_id, c_url, c_keyword)).start() ###变量获取区域 local_ip = get_localIP() cf = ConfigParser.ConfigParser() cf.read("./local_config") db_hostname = get_...
2], l
conditional_block
outroTipoDeProducaoBibliografica.py
#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos d...
em='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes part...
rtesDoIt
identifier_name
outroTipoDeProducaoBibliografica.py
#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos d...
if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self....
random_line_split
outroTipoDeProducaoBibliografica.py
#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos d...
s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __st...
bjeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<l...
identifier_body
outroTipoDeProducaoBibliografica.py
#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos d...
lares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # -----------------------------...
return self else: # nao simi
conditional_block
__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pu...
* If store_id is set, then journal can be seen by users on that store and parent stores It also restrict edition, creation and unlink on: account.move, account.invoice and account.voucher. It is done with the same logic to journal. We do not limitate the "read" of this models because user should need to access those ...
This module also adds a store_id field on journal: * If store_id = False then journal can be seen by everyone
random_line_split
list-servers.controller.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Coden...
(): void { this.showDeleteConfirmation(this.serversSelectedNumber).then(() => { this.lodash.forEach(this.serversSelectedStatus, (server: IEnvironmentManagerMachineServer, name: string) => { delete this.servers[name]; }); this.deselectAllServers(); this.isBulkChecked = false; th...
deleteSelectedServers
identifier_name
list-servers.controller.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Coden...
}); } /** * @param {string} name */ changeServerSelection(name: string): void { this.serversSelectedStatus[name] = !this.serversSelectedStatus[name]; this.updateSelectedStatus(); } /** * Change bulk selection value */ changeBulkSelection(): void { if (this.isBulkChecked) { ...
{ this.isBulkChecked = false; }
conditional_block
list-servers.controller.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Coden...
}
{ let content = 'Would you like to delete '; if (numberToDelete > 1) { content += 'these ' + numberToDelete + ' servers?'; } else { content += 'this selected server?'; } return this.confirmDialogService.showConfirmDialog('Remove servers', content, 'Delete'); }
identifier_body
list-servers.controller.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Coden...
*/ addServer(reference: string, port: number, protocol: string): void { this.servers[reference] = { port: port, protocol: protocol, userScope: true }; this.updateSelectedStatus(); this.serversOnChange(); this.buildServersList(); } /** * Update server * * @param ...
* @param {string} reference * @param {number} port * @param {string} protocol
random_line_split
Vocabularies.js
import React, { PropTypes } from 'react' import SettingsList from './SettingsList' import { parseVocabulary } from '../../common/Vocabulary' export class Predictions extends React.Component { static propTypes = { token: PropTypes.string.isRequired, state: PropTypes.object.isRequired, actions: PropTypes.o...
/> </div> ) } } export default Predictions
actions={this.props.actions} onAddItem={this.addItem} onDeleteItem={this.deleteItem} onEditItem={this.editItem}
random_line_split
Vocabularies.js
import React, { PropTypes } from 'react' import SettingsList from './SettingsList' import { parseVocabulary } from '../../common/Vocabulary' export class Predictions extends React.Component { static propTypes = { token: PropTypes.string.isRequired, state: PropTypes.object.isRequired, actions: PropTypes.o...
else { actions.editItem(token, this.type, id, vocabulary); } }); }; render() { let state = this.props.state; return ( <div> <SettingsList state={state} type={this.type} actions={this.props.actions} onAddItem={this.addIt...
{ actions.editItemName(token, this.type, id, vocabulary); }
conditional_block
Vocabularies.js
import React, { PropTypes } from 'react' import SettingsList from './SettingsList' import { parseVocabulary } from '../../common/Vocabulary' export class Predictions extends React.Component { static propTypes = { token: PropTypes.string.isRequired, state: PropTypes.object.isRequired, actions: PropTypes.o...
} export default Predictions
{ let state = this.props.state; return ( <div> <SettingsList state={state} type={this.type} actions={this.props.actions} onAddItem={this.addItem} onDeleteItem={this.deleteItem} onEditItem={this.editItem} /> </div> ) }
identifier_body
Vocabularies.js
import React, { PropTypes } from 'react' import SettingsList from './SettingsList' import { parseVocabulary } from '../../common/Vocabulary' export class
extends React.Component { static propTypes = { token: PropTypes.string.isRequired, state: PropTypes.object.isRequired, actions: PropTypes.object.isRequired }; type = 'vocabularies'; addItem = (values) => { return parseVocabulary(values) .then((vocabulary) => { this.props.actions...
Predictions
identifier_name
maps.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { NgaModule } from '../../theme/nga.module'; import { routing } from './maps.routing'; import { Maps } from './maps.component'; import { BubbleMaps } from './compon...
{}
MapsModule
identifier_name
maps.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { NgaModule } from '../../theme/nga.module'; import { routing } from './maps.routing'; import { Maps } from './maps.component'; import { BubbleMaps } from './compon...
NgaModule, routing ], declarations: [ Maps, BubbleMaps, EsriMaps, GoogleMaps, LeafletMaps, LineMaps ], providers: [ BubbleMapsService, LineMapsService ] }) export class MapsModule {}
@NgModule({ imports: [ CommonModule, FormsModule,
random_line_split
contact-form.component.ts
import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { AlertsService } from '@jaspero/ng2-alerts'; import { AppStateService } from '../../../services/app-state.service'; import { ApiClient, Contact, Address, UpdateContactRequ...
(): Contact { return this._model; } constructor(private alertsService: AlertsService, private route: ActivatedRoute, private appState: AppStateService, private apiClient: ApiClient, private lookups: LookupsService) { this.model = new Contact(); this.model.address = new Address(); this.countryCtrl...
model
identifier_name
contact-form.component.ts
import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { AlertsService } from '@jaspero/ng2-alerts'; import { AppStateService } from '../../../services/app-state.service'; import { ApiClient, Contact, Address, UpdateContactRequ...
displayCountryFn(country: LookupEntry): string { return country ? country.description : ''; } save() { this.readonly = true; const request: UpdateContactRequest = new UpdateContactRequest(); request.firstName = this.model.firstName; request.lastName = this.model.lastName; request.email =...
}
random_line_split