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
test_copy_package_category.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test copying a package category in the library editor """ def
(library_editor, helpers): """ Copy package category with "New Library Element" wizard """ le = library_editor # Open "New Library Element" wizard le.action('libraryEditorActionNewElement').trigger(blocking=False) # Choose "Copy existing element" le.widget('libraryEditorNewElementWizar...
test
identifier_name
test_copy_package_category.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test copying a package category in the library editor """ def test(library_editor, helpers): """ Copy package category with "New Library Element" wizard """ le = library_editor # Open "New Library Element" wizard le.action('libraryEditorActio...
le.widget('libraryEditorNewElementWizardChooseTypePkgCatButton').click() # Choose category category_tree = le.widget('libraryEditorNewElementWizardCopyFromCategoriesTree') helpers.wait_for_model_items_count(category_tree, 1) category = category_tree.model().items().items[0] category_tree.select...
# Choose type of element
random_line_split
MediumFilter.tsx
import { Flex, Radio, RadioGroup, Toggle } from "@artsy/palette" import React, { FC } from "react" import { useArtworkFilterContext } from "../ArtworkFilterContext" export const MediumFilter: FC = () => { const { aggregations, counts, ...filterContext } = useArtworkFilterContext() const mediums = aggregations.find...
}, ]
random_line_split
aggregation_info.py
from util import hash256, hash_pks from copy import deepcopy class AggregationInfo: """ AggregationInfo represents information of how a tree of aggregate signatures was created. Different tress will result in different signatures, due to exponentiations required for security. An AggregationInfo i...
ret = "" for key, value in self.tree.items(): ret += ("(" + key[0].hex() + "," + key[1].serialize().hex() + "):\n" + hex(value) + "\n") return ret def __deepcopy__(self, memo): new_tree = deepcopy(self.tree, memo) new_mh = deepcopy(self.messag...
def __str__(self):
random_line_split
aggregation_info.py
from util import hash256, hash_pks from copy import deepcopy class AggregationInfo: """ AggregationInfo represents information of how a tree of aggregate signatures was created. Different tress will result in different signatures, due to exponentiations required for security. An AggregationInfo i...
@staticmethod def secure_merge_infos(colliding_infos): """ Infos are merged together with combination of exponents """ # Groups are sorted by message then pk then exponent # Each info object (and all of it's exponents) will be # exponentiated by one of the Ts ...
""" Infos are just merged together with no addition of exponents, since they are disjoint """ new_tree = {} for info in aggregation_infos: new_tree.update(info.tree) mh_pubkeys = [k for k, v in new_tree.items()] mh_pubkeys.sort() message_hash...
identifier_body
aggregation_info.py
from util import hash256, hash_pks from copy import deepcopy class AggregationInfo: """ AggregationInfo represents information of how a tree of aggregate signatures was created. Different tress will result in different signatures, due to exponentiations required for security. An AggregationInfo i...
(pk, message): return AggregationInfo.from_msg_hash(pk, hash256(message)) @staticmethod def simple_merge_infos(aggregation_infos): """ Infos are just merged together with no addition of exponents, since they are disjoint """ new_tree = {} for info in aggr...
from_msg
identifier_name
aggregation_info.py
from util import hash256, hash_pks from copy import deepcopy class AggregationInfo: """ AggregationInfo represents information of how a tree of aggregate signatures was created. Different tress will result in different signatures, due to exponentiations required for security. An AggregationInfo i...
mh_pubkeys = [k for k, v in new_tree.items()] mh_pubkeys.sort() message_hashes = [message_hash for (message_hash, public_key) in mh_pubkeys] public_keys = [public_key for (message_hash, public_key) in mh_pubkeys] return Aggregatio...
for key, value in colliding_infos[i].tree.items(): if key not in new_tree: # This message & pk have not been included yet new_tree[key] = (value * computed_Ts[i]) % order else: # This message and pk are already included, so mult...
conditional_block
Presentation.py
# Copyright (C) 2013 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). """ Presentation utilities. """ from . import trgfile class PresLog(object): # Basic log file reading. def __init__(self,logfile,part='events'): '''part can be 'events' or 'trials' for the first or sec...
self.atstart=False yield fields def __del__(self): self.close() def close(self): if self.log: self.log.close() self.log=None class PresLogfile(trgfile.trgfile): def __init__(self,logfile,part='events'): self.PL=PresLog(logfile,part) trgfile.trgfile.__init__(self,self.PL) self.preamble['Sfreq'...
if self.atstart: continue else: break
conditional_block
Presentation.py
# Copyright (C) 2013 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). """ Presentation utilities. """ from . import trgfile class PresLog(object): # Basic log file reading. def __init__(self,logfile,part='events'): '''part can be 'events' or 'trials' for the first or sec...
fields=line.rstrip('\r\n').split('\t') if len(fields)<=1: # Only at the start skip empty line(s) if self.atstart: continue else: break self.atstart=False yield fields def __del__(self): self.close() def close(self): if self.log: self.log.close() self.log=None class PresLogfile(trgfi...
self.header_fields=fields self.atstart=True break def __iter__(self): for line in self.log:
random_line_split
Presentation.py
# Copyright (C) 2013 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). """ Presentation utilities. """ from . import trgfile class PresLog(object): # Basic log file reading. def __init__(self,logfile,part='events'): '''part can be 'events' or 'trials' for the first or sec...
(self,logfile,part='events'): self.PL=PresLog(logfile,part) trgfile.trgfile.__init__(self,self.PL) self.preamble['Sfreq']=10000.0 def rdr(self): for fields in self.reader: data=dict(zip(self.PL.header_fields,fields)) point=int(data['Time']) description=data['Event Type'] try: code=int(data['Cod...
__init__
identifier_name
Presentation.py
# Copyright (C) 2013 Bernd Feige # This file is part of avg_q and released under the GPL v3 (see avg_q/COPYING). """ Presentation utilities. """ from . import trgfile class PresLog(object): # Basic log file reading. def __init__(self,logfile,part='events'): '''part can be 'events' or 'trials' for the first or sec...
# We are calculating backwards from the time the log was written, which is given # in local time, and it may happen that a DST switch occurred between start and end. # Most plots, simply working for a given time from the start, are totally okay if you don't # mind that the end times are still in the old frame, ...
def __init__(self,logfile,part='events'): self.PL=PresLog(logfile,part) trgfile.trgfile.__init__(self,self.PL) self.preamble['Sfreq']=10000.0 def rdr(self): for fields in self.reader: data=dict(zip(self.PL.header_fields,fields)) point=int(data['Time']) description=data['Event Type'] try: code=i...
identifier_body
issue-85155.rs
// This is a test with a setup similar to issue 85155, which triggers a const eval error: a const // argument value is outside the range expected by the `stdarch` intrinsic. // // It's not the exact code mentioned in that issue because it depends both on `stdarch` intrinsics // only available on x64, and internal imple...
() { // This function triggers a PME whenever the const argument does not fit in 1-bit. post_monomorphization_error::stdarch_intrinsic::<2>(); //~^ NOTE the above error was encountered while instantiating }
main
identifier_name
issue-85155.rs
// This is a test with a setup similar to issue 85155, which triggers a const eval error: a const // argument value is outside the range expected by the `stdarch` intrinsic. // // It's not the exact code mentioned in that issue because it depends both on `stdarch` intrinsics // only available on x64, and internal imple...
{ // This function triggers a PME whenever the const argument does not fit in 1-bit. post_monomorphization_error::stdarch_intrinsic::<2>(); //~^ NOTE the above error was encountered while instantiating }
identifier_body
issue-85155.rs
// This is a test with a setup similar to issue 85155, which triggers a const eval error: a const // argument value is outside the range expected by the `stdarch` intrinsic. // // It's not the exact code mentioned in that issue because it depends both on `stdarch` intrinsics // only available on x64, and internal imple...
extern crate post_monomorphization_error; fn main() { // This function triggers a PME whenever the const argument does not fit in 1-bit. post_monomorphization_error::stdarch_intrinsic::<2>(); //~^ NOTE the above error was encountered while instantiating }
// depending on the const argument value, like the `stdarch` intrinsics would. // // aux-build: post_monomorphization_error.rs // build-fail: this is a post-monomorphization error, it passes check runs and requires building // to actually fail.
random_line_split
no-caller.js
/** * @fileoverview Rule to flag use of arguments.callee and arguments.caller. * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.ex...
};
{ return { MemberExpression(node) { const objectName = node.object.name, propertyName = node.property.name; if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/u)) { context.rep...
identifier_body
no-caller.js
/** * @fileoverview Rule to flag use of arguments.callee and arguments.caller. * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.ex...
} }; } };
{ context.report({ node, messageId: "unexpected", data: { prop: propertyName } }); }
conditional_block
no-caller.js
/** * @fileoverview Rule to flag use of arguments.callee and arguments.caller. * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.ex...
(context) { return { MemberExpression(node) { const objectName = node.object.name, propertyName = node.property.name; if (objectName === "arguments" && !node.computed && propertyName && propertyName.match(/^calle[er]$/u)) { c...
create
identifier_name
no-caller.js
/** * @fileoverview Rule to flag use of arguments.callee and arguments.caller. * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.ex...
recommended: false, url: "https://eslint.org/docs/rules/no-caller" }, schema: [], messages: { unexpected: "Avoid arguments.{{prop}}." } }, create(context) { return { MemberExpression(node) { const object...
docs: { description: "disallow the use of `arguments.caller` or `arguments.callee`",
random_line_split
FileUnit.ts
import {IFileUnit} from '../../../../../../shared/models/units/IFileUnit'; import {IFile} from '../../../../../../shared/models/mediaManager/IFile'; import {ICourse} from '../../../../../../shared/models/ICourse'; import {IChatRoom} from '../../../../../../shared/models/IChatRoom'; export class FileUnit implements IFi...
_course: any; name: string; description: string; type: string; __t: string; progressable: boolean; weight: number; updatedAt: string; createdAt: string; visible: boolean; unitCreator: any; chatRoom: IChatRoom; files: IFile[] = []; fileUnitType: string; constructor(_course: ICourse) { ...
_id: any;
random_line_split
FileUnit.ts
import {IFileUnit} from '../../../../../../shared/models/units/IFileUnit'; import {IFile} from '../../../../../../shared/models/mediaManager/IFile'; import {ICourse} from '../../../../../../shared/models/ICourse'; import {IChatRoom} from '../../../../../../shared/models/IChatRoom'; export class FileUnit implements IFi...
(_course: ICourse) { this._course = _course; this.__t = 'file'; this.fileUnitType = 'file'; this.progressable = false; this.weight = 0; } }
constructor
identifier_name
atomic_umin_acqrel.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_umin_acqrel; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T; struct A<T> { v: UnsafeCell<T> } un...
} type T = isize; macro_rules! atomic_umin_acqrel_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>::new(value); let data: Arc<A<T>> = Arc::<A<T>>::new(a); let clone: Arc<A<T>> = data.clone(); thread::spawn(move || { let dst: *mu...
{ A { v: UnsafeCell::<T>::new(v) } }
identifier_body
atomic_umin_acqrel.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_umin_acqrel; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread;
// pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T; struct A<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T> { A { v: UnsafeCell::<T>::new(v) } } } type T = isize; macro_rules! atomic_umin_acqrel_test { ($init:expr, $value:ex...
random_line_split
atomic_umin_acqrel.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_umin_acqrel; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T; struct
<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T> { A { v: UnsafeCell::<T>::new(v) } } } type T = isize; macro_rules! atomic_umin_acqrel_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>:...
A
identifier_name
images.py
# -*- coding: utf-8 -*- """ Contains classes to handle images related things # Requires PIL """ from hyde.plugin import Plugin import re import Image class ImageSizerPlugin(Plugin): """ Each HTML page is modified to add width and height for images if they are not already specified. """ def __in...
(self, resource, text): """ When the resource is generated, search for img tag and specify their sizes. Some img tags may be missed, this is not a perfect parser. """ try: mode = self.site.config.mode except AttributeError: mode = "product...
text_resource_complete
identifier_name
images.py
# -*- coding: utf-8 -*- """ Contains classes to handle images related things # Requires PIL """ from hyde.plugin import Plugin import re import Image class ImageSizerPlugin(Plugin): """ Each HTML page is modified to add width and height for images if they are not already specified. """ def __in...
if src not in self.cache: if src.startswith(self.site.config.media_url): path = src[len(self.site.config.media_url):].lstrip("/") path = self.site.config.media_root_path.child(path) image = self.site.content.resource_from_relative_deploy_path(path) ...
self.logger.warn("[%s] has an img tag without src attribute" % resource) return "" # Nothing
conditional_block
images.py
# -*- coding: utf-8 -*- """ Contains classes to handle images related things # Requires PIL """ from hyde.plugin import Plugin import re import Image class ImageSizerPlugin(Plugin):
image = self.site.content.resource_from_relative_deploy_path(path) elif re.match(r'([a-z]+://|//).*', src): # Not a local link return "" # Nothing elif src.startswith("/"): # Absolute resource path = src.lstrip...
""" Each HTML page is modified to add width and height for images if they are not already specified. """ def __init__(self, site): super(ImageSizerPlugin, self).__init__(site) self.cache = {} def _handle_img(self, resource, src, width, height): """Determine what should be a...
identifier_body
images.py
# -*- coding: utf-8 -*- """ Contains classes to handle images related things # Requires PIL """
from hyde.plugin import Plugin import re import Image class ImageSizerPlugin(Plugin): """ Each HTML page is modified to add width and height for images if they are not already specified. """ def __init__(self, site): super(ImageSizerPlugin, self).__init__(site) self.cache = {} ...
random_line_split
characterdata.rs
Mutation, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, ...
} // https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult { self.ReplaceData(offset, count, DOMString::new()) } // https://dom.spec.whatwg.org/#dom-characterdata-replacedata fn ReplaceData(&self, offset: u32,...
self.ReplaceData(offset, 0, arg)
random_line_split
characterdata.rs
, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: ...
(&self) -> u32 { self.data.borrow().encode_utf16().count() as u32 } // https://dom.spec.whatwg.org/#dom-characterdata-substringdata fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> { let data = self.data.borrow(); // Step 1. let mut substring = String:...
Length
identifier_name
characterdata.rs
, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: ...
fn content_changed(&self) { let node = self.upcast::<Node>(); node.dirty(NodeDamage::OtherNodeDamage); } } impl CharacterDataMethods for CharacterData { // https://dom.spec.whatwg.org/#dom-characterdata-data fn Data(&self) -> DOMString { self.data.borrow().clone() } /...
{ self.data.borrow_mut().push_str(data); self.content_changed(); }
identifier_body
characterdata.rs
, Node, NodeDamage}; use dom::processinginstruction::ProcessingInstruction; use dom::text::Text; use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; // https://dom.spec.whatwg.org/#characterdata #[dom_struct] pub struct CharacterData { node: Node, data: ...
, NodeTypeId::CharacterData(CharacterDataTypeId::Text) => { DomRoot::upcast(Text::new(data, &document)) }, _ => unreachable!(), } } #[inline] pub fn data(&self) -> Ref<DOMString> { self.data.borrow() } #[inline] pub fn append_...
{ let pi = self.downcast::<ProcessingInstruction>().unwrap(); DomRoot::upcast(ProcessingInstruction::new(pi.Target(), data, &document)) }
conditional_block
las.rs
//! Source las points. use std::io::{Read, Seek}; use std::path::Path; use las; use Result; use point::{Intensity, Point, ScanDirection}; use source::{FileSource, Source}; impl<R: Read + Seek> Source for las::Reader<R> { fn source(&mut self, want: usize) -> Result<Option<Vec<Point>>> { let mut points = ...
; impl From<las::Point> for Point { fn from(point: las::Point) -> Point { Point { x: point.x, y: point.y, z: point.z, intensity: Intensity::from_u16(point.intensity), return_number: Some(point.return_number.as_u8() as usize), number_of...
LasConfig
identifier_name
las.rs
//! Source las points. use std::io::{Read, Seek}; use std::path::Path; use las; use Result; use point::{Intensity, Point, ScanDirection}; use source::{FileSource, Source}; impl<R: Read + Seek> Source for las::Reader<R> { fn source(&mut self, want: usize) -> Result<Option<Vec<Point>>> { let mut points = ...
number_of_returns: Some(point.number_of_returns.as_u8() as usize), gps_time: point.gps_time, scan_direction: match point.scan_direction { las::point::ScanDirection::Forward => ScanDirection::Forward, las::point::ScanDirection::Backward => ScanDirection...
y: point.y, z: point.z, intensity: Intensity::from_u16(point.intensity), return_number: Some(point.return_number.as_u8() as usize),
random_line_split
plot_tsl.py
#!/usr/bin/python import sys import re import numpy as np import matplotlib.pyplot as plt import argparse remove_comments = re.compile("(?!\#)", re.VERBOSE) parser = argparse.ArgumentParser() parser.add_argument("-f", nargs=1, default=None) parser.add_argument("files", nargs='*') args = parser.parse_args() if len(...
ax.legend() plt.ylabel(field) plt.xlabel(header[1]) plt.draw() plt.show()
ax.plot(fn[:, 1], fn[:, fno], label=args.files[i])
conditional_block
plot_tsl.py
import sys import re import numpy as np import matplotlib.pyplot as plt import argparse remove_comments = re.compile("(?!\#)", re.VERBOSE) parser = argparse.ArgumentParser() parser.add_argument("-f", nargs=1, default=None) parser.add_argument("files", nargs='*') args = parser.parse_args() if len(args.files) < 1: ...
#!/usr/bin/python
random_line_split
index.js
var express = require('express'); var request = require('request'); var rp = require('rp'); var config = require('../../config') var router = express.Router(); var twilio = require('twilio'); var mysql = require('mysql'); var connection = mysql.createConnection(config.mysqlConfig); /* GET home page. */ router.get('/'...
-\d{4}-\d{4}$/; if(!req.body.phonenumber.match(regex)){ return res.json({"response" : "Please input a correct phone number. (000-0000-0000)"}); } request.post({url:"https://www.google.com/recaptcha/api/siteverify", form:{"secret" : config.captchasecret, "response" : req.body['g-recaptcha-response']}...
n({"response" : "Please complete recaptcha."}); } var regex = /^\d{3}
conditional_block
index.js
var express = require('express'); var request = require('request'); var rp = require('rp'); var config = require('../../config') var router = express.Router(); var twilio = require('twilio'); var mysql = require('mysql'); var connection = mysql.createConnection(config.mysqlConfig); /* GET home page. */ router.get('/'...
router.post('/enlist', function(req, res, next) { if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) { return res.json({"response" : "Please complete recaptcha."}); } var regex = /^\d{3}-\d{4}-\d{4}$/; if(!re...
});
random_line_split
main.py
crawl_num = 0 call_log_url = "http://nm.189.cn/selfservice/bill/xdQuery" today = date.today() missing_list = [] pos_missing = [] search_month = [x for x in range(0, -6, -1)] for each_month in search_month: query_date = today + relativedelta(months=each_month)...
key, level, message, result = self.phone_bill_get(month, resp) if level != 0 or result['bill_amount'] == '' or result['bill_amount'] == '0.00': missing_list.append(month) continue phone_bill.append(result) if len(missing_list) == 6: ...
conditional_block
main.py
if retry_times >= 0: aid_time_dict.update({retry_times: time.time()}) elif now_time < end_time: loop_time = aid_time_dict.get(0, time.time()) left_time = end_time - loop_time self.random_sleep(left_time) els...
identifier_body
main.py
if retry_times >= 0: aid_time_dict.update({retry_times: time.time()}) elif now_time < end_time: loop_time = aid_time_dict.get(0, time.time()) left_time = end_time - loop_time self.random_sleep(left_time) els...
identifier_name
main.py
"success" else: pass else: self.log('crawler', "request_error", tel_info_res) return 9, "website_busy_error" def send_verify_request(self, **kwargs): """ 請求發送短信,或是下載圖片,或是同時發送請求 return status_key: str, 狀態碼金鑰,參考status_c...
code, key, resp = self.post(call_log_url, data=json.dumps(call_log_data), headers=header) if code: missing_flag = True elif 'POR-2102' in resp.text: # 无查询结果,这个月没有数据 missing_flag = False else: ...
retry_times = self.max_retry log_for_retry = [] while 1: log_for_retry.append((1, retry_times)) retry_times -= 1
random_line_split
index.d.ts
// TypeScript Version: 2.3 /// <reference types="jquery" /> declare namespace JQuerySortable { interface Position { top: number; left: number; } type Dimensions = number[]; interface ContainerGroup { $document: JQuery; containerDimensions: Dimensions[] contai...
// Type definitions for jQuery Sortable v0.9.12 // Project: http://johnny.github.io/jquery-sortable/ // Definitions by: Nathan Pitman <https://github.com/Seltzer> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
random_line_split
doc_views_types.ts
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not u...
} export type AngularScope = IScope; export type ElasticSearchHit<T = unknown> = SearchResponse<T>['hits']['hits'][number]; export interface FieldMapping { filterable?: boolean; scripted?: boolean; rowCount?: number; type: string; name: string; } export type DocViewFilterFn = ( mapping: FieldMapping | s...
import { IndexPattern } from '../../../../../../../src/plugins/data/public'; export interface AngularDirective { controller: (...injectedServices: any[]) => void; template: string;
random_line_split
FileProcessing.py
# encoding=utf-8 import codecs import sys from src.view.FileProcessingOutput import FileProcessingOutput class FileProcessing(): def __init__(self): self.fileProcessingOutput = FileProcessingOutput() def read_input_file(self, file_path, file_type): ''' Lectura de archivo y procesamie...
_splitted_line = line.split(':') if len(_splitted_line) < 3: self.fileProcessingOutput.print_error_format_not_correct(line_counter) sys.exit() return True
sys.exit()
random_line_split
FileProcessing.py
# encoding=utf-8 import codecs import sys from src.view.FileProcessingOutput import FileProcessingOutput class FileProcessing(): def __init__(self): self.fileProcessingOutput = FileProcessingOutput() def read_input_file(self, file_path, file_type): ''' Lectura de archivo y procesamie...
return True
self.fileProcessingOutput.print_error_format_not_correct(line_counter) sys.exit()
conditional_block
FileProcessing.py
# encoding=utf-8 import codecs import sys from src.view.FileProcessingOutput import FileProcessingOutput class FileProcessing(): def
(self): self.fileProcessingOutput = FileProcessingOutput() def read_input_file(self, file_path, file_type): ''' Lectura de archivo y procesamiento de archivos :param file_path: :return: file_lines ''' file_lines = [] line_counter = 0 self.fil...
__init__
identifier_name
FileProcessing.py
# encoding=utf-8 import codecs import sys from src.view.FileProcessingOutput import FileProcessingOutput class FileProcessing(): def __init__(self):
def read_input_file(self, file_path, file_type): ''' Lectura de archivo y procesamiento de archivos :param file_path: :return: file_lines ''' file_lines = [] line_counter = 0 self.fileProcessingOutput.print_reading_file(file_path) try: ...
self.fileProcessingOutput = FileProcessingOutput()
identifier_body
createModalComponent.js
import React, { Component, PropTypes } from 'react'; import { findDOMNode } from 'react-dom'; import Marty from 'marty'; import cx from 'classnames'; import Portal from 'react-portal'; import styles from './Modal.css'; const baseZIndex = 900; export class Modal extends Component { handleModalClick = (e) => { if...
() { return ( <Modal ref="innerComponent" isOpen={this.app.modalStore.isOpen(this.props.id)} zIndex={this.app.modalStore.getZOffset(this.props.id)} {...this.props} /> ); }, }); ModalContainer.prototype.open = function() { this.refs.innerComponent.handleOpenModal(...
done
identifier_name
createModalComponent.js
import React, { Component, PropTypes } from 'react'; import { findDOMNode } from 'react-dom'; import Marty from 'marty'; import cx from 'classnames'; import Portal from 'react-portal'; import styles from './Modal.css'; const baseZIndex = 900; export class Modal extends Component { handleModalClick = (e) => { if...
return ( <Portal isOpened={isOpen}> <div className={styles.modal} style={localStyle} ref="modal" onMouseDown={this.handleModalClick}> <div className={styles.dialog} style={dialogStyle}> <div className={bodyClasses}> {this.props.children} </div> ...
{ const { isOpen, width, marginTop, kind, zIndex } = this.props; if (!isOpen) { return null; } const dialogStyle = { width, marginTop, }; const bodyClasses = cx(styles.body, { [styles.rounded]: kind === 'rounded', }); const localStyle = { zIndex: baseZIn...
identifier_body
createModalComponent.js
import React, { Component, PropTypes } from 'react'; import { findDOMNode } from 'react-dom'; import Marty from 'marty'; import cx from 'classnames'; import Portal from 'react-portal'; import styles from './Modal.css'; const baseZIndex = 900; export class Modal extends Component { handleModalClick = (e) => { if...
const dialogStyle = { width, marginTop, }; const bodyClasses = cx(styles.body, { [styles.rounded]: kind === 'rounded', }); const localStyle = { zIndex: baseZIndex + zIndex, }; return ( <Portal isOpened={isOpen}> <div className={styles.modal} style={...
{ return null; }
conditional_block
createModalComponent.js
import React, { Component, PropTypes } from 'react'; import { findDOMNode } from 'react-dom'; import Marty from 'marty'; import cx from 'classnames'; import Portal from 'react-portal'; import styles from './Modal.css'; const baseZIndex = 900; export class Modal extends Component { handleModalClick = (e) => { if...
return class ThisModal extends Component { render() { return ( <ModalContainer ref="modal" id={thisId} {...this.props}> {ModalHeader && <ModalHeader />} <ModalBody {...this.props} close={this.close.bind(this)} open={this.open.bind(this)} ...
const thisId = ++uniqueId;
random_line_split
f64.rs
() -> f64 { NEG_INFINITY } #[inline] fn zero() -> f64 { 0.0 } #[inline] fn neg_zero() -> f64 { -0.0 } #[inline] fn one() -> f64 { 1.0 } /// Returns `true` if the number is NaN. #[inline] fn is_nan(self) -> bool { self != self } /// Returns `true` if the number is infinite. ...
random_line_split
f64.rs
const MAX_10_EXP: int = 308; #[stable] pub const NAN: f64 = 0.0_f64/0.0_f64; #[stable] pub const INFINITY: f64 = 1.0_f64/0.0_f64; #[stable] pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. #[unstable = "naming scheme needs to be revisited"] pub mod consts { // FIXME: replace with mat...
#[inline] #[deprecated] fn max_value() -> f64 { MAX_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; let mut ex...
{ MIN_POS_VALUE }
identifier_body
f64.rs
pub const MAX_10_EXP: int = 308; #[stable] pub const NAN: f64 = 0.0_f64/0.0_f64; #[stable] pub const INFINITY: f64 = 1.0_f64/0.0_f64; #[stable] pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. #[unstable = "naming scheme needs to be revisited"] pub mod consts { // FIXME: replace with ...
() -> f64 { MAX_VALUE } /// Returns the mantissa, exponent and sign as integers. fn integer_decode(self) -> (u64, i16, i8) { let bits: u64 = unsafe { mem::transmute(self) }; let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 }; let mut exponent: i16 = ((bits >>
max_value
identifier_name
f64.rs
pub const MAX_10_EXP: int = 308; #[stable] pub const NAN: f64 = 0.0_f64/0.0_f64; #[stable] pub const INFINITY: f64 = 1.0_f64/0.0_f64; #[stable] pub const NEG_INFINITY: f64 = -1.0_f64/0.0_f64; /// Various useful constants. #[unstable = "naming scheme needs to be revisited"] pub mod consts { // FIXME: replace with ...
else { -1 }; let mut exponent: i16 = ((bits >>
{ 1 }
conditional_block
time.rs
use std::marker::PhantomData; use chrono; use super::Module; use crate::{Color, Powerline, Style}; pub struct Time<S: TimeScheme> { time_format: &'static str, scheme: PhantomData<S>, } pub trait TimeScheme { const TIME_BG: Color; const TIME_FG: Color; } impl<S: TimeScheme> Time<S> { pub fn new(...
} impl<S: TimeScheme> Module for Time<S> { fn append_segments(&mut self, powerline: &mut Powerline) { let now = chrono::offset::Local::now().format(self.time_format); powerline.add_segment(now, Style::simple(S::TIME_FG, S::TIME_BG)); } }
random_line_split
time.rs
use std::marker::PhantomData; use chrono; use super::Module; use crate::{Color, Powerline, Style}; pub struct Time<S: TimeScheme> { time_format: &'static str, scheme: PhantomData<S>, } pub trait TimeScheme { const TIME_BG: Color; const TIME_FG: Color; } impl<S: TimeScheme> Time<S> { pub fn new(...
(time_format: &'static str) -> Time<S> { Time { time_format, scheme: PhantomData } } } impl<S: TimeScheme> Module for Time<S> { fn append_segments(&mut self, powerline: &mut Powerline) { let now = chrono::offset::Local::now().format(self.time_format); powerline.add_segment(now, Style::...
with_time_format
identifier_name
time.rs
use std::marker::PhantomData; use chrono; use super::Module; use crate::{Color, Powerline, Style}; pub struct Time<S: TimeScheme> { time_format: &'static str, scheme: PhantomData<S>, } pub trait TimeScheme { const TIME_BG: Color; const TIME_FG: Color; } impl<S: TimeScheme> Time<S> { pub fn new(...
pub fn with_time_format(time_format: &'static str) -> Time<S> { Time { time_format, scheme: PhantomData } } } impl<S: TimeScheme> Module for Time<S> { fn append_segments(&mut self, powerline: &mut Powerline) { let now = chrono::offset::Local::now().format(self.time_format); power...
{ Time { time_format: "%H:%M:%S", scheme: PhantomData } }
identifier_body
preferences.py
# =============================================================================== # Copyright 2014 Jake Ross # # 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...
# ============= EOF =============================================
v = View( VGroup( Item("host"), Item("port"), show_border=True, label="Dashboard Server" ) ) return v
identifier_body
preferences.py
# =============================================================================== # Copyright 2014 Jake Ross # # 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...
class DashboardClientPreferences(BasePreferencesHelper): preferences_path = "pychron.dashboard.client" host = Str port = Int class DashboardClientPreferencesPane(PreferencesPane): model_factory = DashboardClientPreferences category = "Dashboard" def traits_view(self): v = View( ...
def traits_view(self): v = View(Item("use_dashboard_client")) return v
random_line_split
preferences.py
# =============================================================================== # Copyright 2014 Jake Ross # # 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...
(PreferencesPane): model_factory = ExperimentDashboardClientPreferences category = "Experiment" def traits_view(self): v = View(Item("use_dashboard_client")) return v class DashboardClientPreferences(BasePreferencesHelper): preferences_path = "pychron.dashboard.client" host = Str ...
ExperimentDashboardClientPreferencesPane
identifier_name
sexgalaxy.py
# -*- coding: utf-8 -*- import sys PY3 = False if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int if PY3: import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo else: import urlparse # Usamos...
fanart=scrapedthumbnail, url=scrapedurl, thumbnail=scrapedthumbnail, plot=scrapedplot)) next_page = scrapertools.find_single_match(data, '<div class="nav-previous"><a href="([^"]+)"') if next_page != "": itemlist.append(item.clone(action="lista", title="[COLOR blue]Página Si...
itemlist.append(item.clone(action="findvideos", title=scrapedtitle, contentTitle=scrapedtitle,
random_line_split
sexgalaxy.py
# -*- coding: utf-8 -*- import sys PY3 = False if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int if PY3: import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo else: import urlparse # Usamos...
ger.info() itemlist = [] data = httptools.downloadpage(item.url).data data = re.sub(r"\n|\r|\t|amp;|\s{2}|&nbsp;", "", data) patron = '<a href="([^"]+)" rel="nofollow[^<]+>(?:|<strong> |)(?:Streaming|Download)' matches = scrapertools.find_multiple_matches(data, patron) for url in matches: ...
identifier_body
sexgalaxy.py
# -*- coding: utf-8 -*- import sys PY3 = False if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int if PY3: import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo else: import urlparse # Usamos...
next_page = scrapertools.find_single_match(data, '<div class="nav-previous"><a href="([^"]+)"') if next_page != "": itemlist.append(item.clone(action="lista", title="[COLOR blue]Página Siguiente >>[/COLOR]", url=next_page)) return itemlist def findvideos(item): logger.info() itemlist = [] ...
rapedplot = "" if not "manyvids" in scrapedtitle: itemlist.append(item.clone(action="findvideos", title=scrapedtitle, contentTitle=scrapedtitle, fanart=scrapedthumbnail, url=scrapedurl, thumbnail=scrapedthumbnail, plot=scrapedplot))
conditional_block
sexgalaxy.py
# -*- coding: utf-8 -*- import sys PY3 = False if sys.version_info[0] >= 3: PY3 = True; unicode = str; unichr = chr; long = int if PY3: import urllib.parse as urlparse # Es muy lento en PY2. En PY3 es nativo else: import urlparse # Usamos...
tem): logger.info() itemlist = [] autoplay.init(item.channel, list_servers, list_quality) itemlist.append(item.clone(title="Peliculas", action="lista", url=host + "/full-movies/")) itemlist.append(item.clone(title="Peliculas JAV", action="lista", url=host + "/jav-movies/")) itemlist.append(ite...
inlist(i
identifier_name
lmcurvefit.py
#!/usr/bin/env python # Author: Richard Bradshaw, R.T.Bradshaw@soton.ac.uk # Module to fit various curves to provided x/y data # Current available curves: Linear, Gaussian, Lorentzian, Voigt # Requirements: lmfit, numpy, matplotlib (as dependencies of lmfit) from lmfit.models import LinearModel,GaussianModel,Lorent...
except AttributeError: raise FitError("""You don't seem to have a composite model - run make_mod() first!""") def plots(self, **kwargs): """Returns matplotlib axes with original data, fitted function & initial model. Usage: self.plots([*...
self.xs = data[0] self.ys = data[1] try: self.total_fit = self._compmod.fit(self.ys, self._pars, x=self.xs) self.composite_fits = self.total_fit.eval_components(x=self.xs)
random_line_split
lmcurvefit.py
#!/usr/bin/env python # Author: Richard Bradshaw, R.T.Bradshaw@soton.ac.uk # Module to fit various curves to provided x/y data # Current available curves: Linear, Gaussian, Lorentzian, Voigt # Requirements: lmfit, numpy, matplotlib (as dependencies of lmfit) from lmfit.models import LinearModel,GaussianModel,Lorent...
def init_params(self, prefix='', center=0, sigma=10, amplitude=10): """Usage: self.init_params([prefix='', center=0, sigma=10, amplitude=10]) Sets initial guess parameters for the model defined with 'prefix'.""" self._pars[prefix+'center'].set(center) self._pars[prefix+'sigma']....
"""Prints lmfit fit report for the current object""" try: return self.total_fit.fit_report() except AttributeError: return "No composite fit yet performed for this object."
identifier_body
lmcurvefit.py
#!/usr/bin/env python # Author: Richard Bradshaw, R.T.Bradshaw@soton.ac.uk # Module to fit various curves to provided x/y data # Current available curves: Linear, Gaussian, Lorentzian, Voigt # Requirements: lmfit, numpy, matplotlib (as dependencies of lmfit) from lmfit.models import LinearModel,GaussianModel,Lorent...
def __str__(self): """Prints lmfit fit report for the current object""" try: return self.total_fit.fit_report() except AttributeError: return "No composite fit yet performed for this object." def init_params(self, prefix='', center=0, sigma=10, amplitude=10): ...
self._pars.update(fit._mod.make_params())
conditional_block
lmcurvefit.py
#!/usr/bin/env python # Author: Richard Bradshaw, R.T.Bradshaw@soton.ac.uk # Module to fit various curves to provided x/y data # Current available curves: Linear, Gaussian, Lorentzian, Voigt # Requirements: lmfit, numpy, matplotlib (as dependencies of lmfit) from lmfit.models import LinearModel,GaussianModel,Lorent...
(self, data): """Usage: Fit(data). Initialises data as xs and ys attributes. Data should be a 2d numpy array of x and y values.""" if len(data) != 2: raise FitError("""Your data is formatted incorrectly - it should be a 2D array of all x-, ...
__init__
identifier_name
appspecificinformation.py
from lxml import etree from healthvaultlib.utils.xmlutils import XmlUtils from healthvaultlib.itemtypes.healthrecorditem import HealthRecordItem class AppspecificInformation(HealthRecordItem): def __init__(self, thing_xml=None): super(AppspecificInformation, self).__init__() self.type_id = 'a503...
(self): return 'AppspecificInformation' def parse_thing(self): super(AppspecificInformation, self).parse_thing() xmlutils = XmlUtils(self.thing_xml) def write_xml(self): thing = super(AppspecificInformation, self).write_xml() data_xml = etree.Element('data-xml') ...
__str__
identifier_name
appspecificinformation.py
from lxml import etree from healthvaultlib.utils.xmlutils import XmlUtils from healthvaultlib.itemtypes.healthrecorditem import HealthRecordItem class AppspecificInformation(HealthRecordItem): def __init__(self, thing_xml=None): super(AppspecificInformation, self).__init__() self.type_id = 'a503...
def __str__(self): return 'AppspecificInformation' def parse_thing(self): super(AppspecificInformation, self).parse_thing() xmlutils = XmlUtils(self.thing_xml) def write_xml(self): thing = super(AppspecificInformation, self).write_xml() data_xml = etree.Element('d...
self.thing_xml = thing_xml self.parse_thing()
conditional_block
appspecificinformation.py
from lxml import etree from healthvaultlib.utils.xmlutils import XmlUtils from healthvaultlib.itemtypes.healthrecorditem import HealthRecordItem class AppspecificInformation(HealthRecordItem): def __init__(self, thing_xml=None): super(AppspecificInformation, self).__init__() self.type_id = 'a503...
def parse_thing(self): super(AppspecificInformation, self).parse_thing() xmlutils = XmlUtils(self.thing_xml) def write_xml(self): thing = super(AppspecificInformation, self).write_xml() data_xml = etree.Element('data-xml') appspecificinformation = etree.Element('appspe...
return 'AppspecificInformation'
identifier_body
appspecificinformation.py
from lxml import etree from healthvaultlib.utils.xmlutils import XmlUtils from healthvaultlib.itemtypes.healthrecorditem import HealthRecordItem
def __init__(self, thing_xml=None): super(AppspecificInformation, self).__init__() self.type_id = 'a5033c9d-08cf-4204-9bd3-cb412ce39fc0' if thing_xml is not None: self.thing_xml = thing_xml self.parse_thing() def __str__(self): return 'AppspecificInforma...
class AppspecificInformation(HealthRecordItem):
random_line_split
employee.py
015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import getdate, validate_email_add, today from frappe.model.naming import make_autoname from frappe import throw, _ import frappe.permis...
def autoname(self): naming_method = frappe.db.get_value("HR Settings", None, "emp_created_by") if not naming_method: throw(_("Please setup Employee Naming System in Human Resource > HR Settings")) else: if naming_method == 'Naming Series': self.name = make_autoname(self.naming_series + '.####') el...
self.get("__onload").salary_structure_exists = frappe.db.get_value("Salary Structure", {"employee": self.name, "is_active": "Yes", "docstatus": ["!=", 2]})
identifier_body
employee.py
015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import getdate, validate_email_add, today from frappe.model.naming import make_autoname from frappe import throw, _ import frappe.permis...
(self): if self.status == 'Left' and not self.relieving_date: throw(_("Please enter relieving date.")) def validate_for_enabled_user_id(self): if not self.status == 'Active': return enabled = frappe.db.sql("""select name from `tabUser` where name=%s and enabled=1""", self.user_id) if not enabled: ...
validate_status
identifier_name
employee.py
015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import getdate, validate_email_add, today from frappe.model.naming import make_autoname from frappe import throw, _ import frappe.permis...
# copy details like Fullname, DOB and Image to User if self.employee_name and not (user.first_name and user.last_name): employee_name = self.employee_name.split(" ") if len(employee_name) >= 3: user.last_name = " ".join(employee_name[2:]) user.middle_name = employee_name[1] elif len(employee_name...
user.add_roles("Employee")
conditional_block
employee.py
2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import getdate, validate_email_add, today from frappe.model.naming import make_autoname from frappe import throw, _ import frappe.permi...
bulk=True) def get_employees_who_are_born_today(): """Get Employee properties whose birthday is today.""" return frappe.db.sql("""select name, personal_email, company_email, user_id, employee_name from tabEmployee where day(date_of_birth) = day(%(date)s) and month(date_of_birth) = month(%(date)s) and statu...
message=_("""Today is {0}'s birthday!""").format(e.employee_name), reply_to=e.company_email or e.personal_email or e.user_id,
random_line_split
seq2seq_model.py
.pdf """ def __init__(self, source_vocab_size, target_vocab_size, buckets, size, num_layers, max_gradient_norm, batch_size, learning_rate, learning_rate_decay_factor, use_lstm=False, num_samples=512, forward_only=False): """Create the model. Args: source_...
Args: data: a tuple of size len(self.buckets) in which each element contains lists of pairs of input and output data that we use to create a batch. bucket_id: integer, which bucket to get the batch for.
random_line_split
seq2seq_model.py
paper: http://arxiv.org/abs/1412.7449 - please look there for details, or into the seq2seq library for complete model implementation. This class also allows to use GRU cells in addition to LSTM cells, and sampled softmax to handle large output vocabulary size. A single-layer version of this model, but with bi-...
# Since our targets are decoder inputs shifted by one, we need one more. last_target = self.decoder_inputs[decoder_size].name input_feed[last_target] = np.zeros([self.batch_size], dtype=np.int32) # Output feed: depends on whether we do a backward step or not. if not forward_only: output_fee...
input_feed[self.decoder_inputs[l].name] = decoder_inputs[l] input_feed[self.target_weights[l].name] = target_weights[l]
conditional_block
seq2seq_model.py
paper: http://arxiv.org/abs/1412.7449 - please look there for details, or into the seq2seq library for complete model implementation. This class also allows to use GRU cells in addition to LSTM cells, and sampled softmax to handle large output vocabulary size. A single-layer version of this model, but with bi-...
softmax_loss_function = sampled_loss # Create the internal multi-layer cell for our RNN. single_cell = rnn_cell.GRUCell(size) if use_lstm: single_cell = rnn_cell.BasicLSTMCell(size) cell = single_cell if num_layers > 1: cell = rnn_cell.MultiRNNCell([single_cell] * num_layers) ...
with tf.device("/cpu:0"): labels = tf.reshape(labels, [-1, 1]) return tf.nn.sampled_softmax_loss(w_t, b, inputs, labels, num_samples, self.target_vocab_size)
identifier_body
seq2seq_model.py
paper: http://arxiv.org/abs/1412.7449 - please look there for details, or into the seq2seq library for complete model implementation. This class also allows to use GRU cells in addition to LSTM cells, and sampled softmax to handle large output vocabulary size. A single-layer version of this model, but with bi-...
(self, session, encoder_inputs, decoder_inputs, target_weights, bucket_id, forward_only): """Run a step of the model feeding the given inputs. Args: session: tensorflow session to use. encoder_inputs: list of numpy int vectors to feed as encoder inputs. decoder_inputs: list of nump...
step
identifier_name
__init__.py
"""Normalize whitespace and Unicode forms in Python 3. Functions: normalize_space() -- collapse whitespace and trim normalize_unicode() -- return specified Unicode normal form """ __author__ = 'Tom Elliott' __copyright__ = 'Copyright ©️ 2017 New York University' __license__ = 'See LICENSE.txt' __version__ = '0.3' im...
compatible.encode('ascii', 'namereplace'))) raise ValueError(msg) return normalized
normalized.encode('ascii', 'namereplace'), compatibility_target, compatible,
random_line_split
__init__.py
"""Normalize whitespace and Unicode forms in Python 3. Functions: normalize_space() -- collapse whitespace and trim normalize_unicode() -- return specified Unicode normal form """ __author__ = 'Tom Elliott' __copyright__ = 'Copyright ©️ 2017 New York University' __license__ = 'See LICENSE.txt' __version__ = '0.3' im...
str, target='NFC', check_compatible=False): """Normalize Unicode form. Keyword arguments: * v: the Unicode string to normalize * target: the targeted normalization form as a string expected by unicodedata.normalize(). No checking is done on the value of this argument. ...
malize_unicode(v:
identifier_name
__init__.py
"""Normalize whitespace and Unicode forms in Python 3. Functions: normalize_space() -- collapse whitespace and trim normalize_unicode() -- return specified Unicode normal form """ __author__ = 'Tom Elliott' __copyright__ = 'Copyright ©️ 2017 New York University' __license__ = 'See LICENSE.txt' __version__ = '0.3' im...
if check_compatible: if target == 'NFC': compatibility_target = 'NFKC' elif target == 'NFD': compatibility_target = 'NFKD' elif target == 'NFKC': compatibility_target = 'NFC' elif target == 'NFKD': compatibility_target = 'NFD' c...
Normalize Unicode form. Keyword arguments: * v: the Unicode string to normalize * target: the targeted normalization form as a string expected by unicodedata.normalize(). No checking is done on the value of this argument. * check_compatible: detect differences in canon...
identifier_body
__init__.py
"""Normalize whitespace and Unicode forms in Python 3. Functions: normalize_space() -- collapse whitespace and trim normalize_unicode() -- return specified Unicode normal form """ __author__ = 'Tom Elliott' __copyright__ = 'Copyright ©️ 2017 New York University' __license__ = 'See LICENSE.txt' __version__ = '0.3' im...
else: token = preserve[0] normed = [] for chunk in v.split(token): normed.append(normalize_space(chunk, preserve[1:])) s = token.join(normed) logger.debug('s: {}'.format(repr(s))) if not trim: if v != s: first = '' last = '' ...
' '.join(v.split())
conditional_block
app.module.ts
//our root app component import {NgModule} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' import {App} from './app.component' import {ViewportModule} from "./viewport/viewport.module" import {OtherModule} from "./other/other.module" import {MyRoutingModule} from "./app-routing.module" impo...
export class AppModule {}
random_line_split
app.module.ts
//our root app component import {NgModule} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' import {App} from './app.component' import {ViewportModule} from "./viewport/viewport.module" import {OtherModule} from "./other/other.module" import {MyRoutingModule} from "./app-routing.module" impo...
{}
AppModule
identifier_name
html_emitter.py
("Defined types", {"class": "module-types-header", "id": mod.module_name + "-defined-types"},2,True) for (typename, td) in mod.typedefs.items(): types_div += ht.h4(typename,{"class": "module-type-name","id": "type-" + ht.gen_html_id(typename)},2,True) types_div += ht.para(ht.add_tag("span","descr...
s += " "*level + "</ul>\n" elif typename in YangDocDefs.integer_types: if 'range' in typedoc.attrs['restrictions']: s += " "*level + "<ul>\n" s += " "*level + "<li>range:\n" s += " "*
"""Create and return documentation based on the type. Expands compound types.""" ht = html_helper.HTMLHelper() s = "" # emit type-specific attributes typename = typedoc.typename s += ht.para(ht.add_tag("span", "type",{"class": "statement-info-label"}) + ": " + typename,{"class": "statement-info-text"},le...
identifier_body
html_emitter.py
notes = "" if statement.attrs['is_key']: notes += " (list key)" if statement.attrs['config']: notes += " (rw)" else: notes += " (ro)" keyword = statement.keyword + notes s_div += ht.para(ht.add_tag("span", "nodetype",{"class": "statement-info-label"}) + ": " + keyword,{"class":...
gen_nav
identifier_name
html_emitter.py
+= ht.h4(statement_name, {"class": "statement-name","id":statement.attrs['id']},level,True) # node description if 'desc' in statement.attrs: s_div += ht.para(ht.add_tag("span", "description",{"class": "statement-info-label"}) + ":<br />" + statement.attrs['desc'],{"class": "statement-info-text"},level,T...
nav += gen_nav(child, root_mod, level)
conditional_block
html_emitter.py
3("Defined types", {"class": "module-types-header", "id": mod.module_name + "-defined-types"},2,True) for (typename, td) in mod.typedefs.items(): types_div += ht.h4(typename,{"class": "module-type-name","id": "type-" + ht.gen_html_id(typename)},2,True) types_div += ht.para(ht.add_tag("span","desc...
return s def gen_type_info(typedoc, level=1): """Create and return documentation based on the type. Expands compound types.""" ht = html_helper.HTMLHelper() s = "" # emit type-specific attributes typename = typedoc.typename s += ht.para(ht.add_tag("span", "type",{"class": "statement-info-label"}) ...
doc_title = ctx.opts.doc_title s = populate_template(doc_title, docs, navs, navids)
random_line_split
control_views.py
from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic.base import TemplateView def in_students_group(user): if user:
return False def in_teachers_group(user): if user: return user.groups.filter(name='Profesores').exists() return False class NewControlView(TemplateView): template_name = 'new_control.html' def get_context_data(self, **kwargs): context = super(NewControlView, self).get_context_d...
return user.groups.filter(name='Alumnos').exists()
conditional_block
control_views.py
from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic.base import TemplateView def in_students_group(user): if user: return user.groups.filter(name='Alumnos').exists() return False def
(user): if user: return user.groups.filter(name='Profesores').exists() return False class NewControlView(TemplateView): template_name = 'new_control.html' def get_context_data(self, **kwargs): context = super(NewControlView, self).get_context_data(**kwargs) # form = CrearTarea...
in_teachers_group
identifier_name
control_views.py
from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic.base import TemplateView def in_students_group(user): if user: return user.groups.filter(name='Alumnos').exists() return False def in_teachers_group(user): i...
class NewControlView(TemplateView): template_name = 'new_control.html' def get_context_data(self, **kwargs): context = super(NewControlView, self).get_context_data(**kwargs) # form = CrearTareaForm() # context['crear_homework_form'] = form # context['courses'] = self.request.use...
random_line_split
control_views.py
from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from django.views.generic.base import TemplateView def in_students_group(user):
def in_teachers_group(user): if user: return user.groups.filter(name='Profesores').exists() return False class NewControlView(TemplateView): template_name = 'new_control.html' def get_context_data(self, **kwargs): context = super(NewControlView, self).get_context_data(**kwargs) ...
if user: return user.groups.filter(name='Alumnos').exists() return False
identifier_body
basic.ts
import {} from "mocha"; const expect = require("expect"); import { kernel, exec, JupyterKernel } from "./common"; describe("compute 2+3 using python2", function() { this.timeout(10000); let k: JupyterKernel; it("creates a python2 kernel", function() { k = kernel("test-python2"); }); it("spawn", async...
it("closes the kernel", function() { k.close(); expect(k.get_state()).toBe("closed"); }); });
it("evaluate 2/3", async function() { expect(await exec(k, "2/3")).toEqual('{"text/plain":"0.6666666666666666"}'); });
random_line_split
pdf2txt.py
#!/usr/bin/env python3 """ Program that convert a pdf to a text file using Tesseract OCR. The pdf file is first converted to a png file using ghostscript, then the png file if processed by Tesseract. """ import os import subprocess import glob import platform import argparse parser = argparse.ArgumentParser(descri...
print('Text extracted form file: {}'.format(filename)) except: print('error extracting text with file {}'.format(filename)) with open(log_file, 'a') as logfile: logfile.write('Error with file (exception raised): {}\n'.format(filename)) # report errors def pdf_to_png(pdf_file,short_name,png_path,page...
""" Extract the text from a set of png files. The png files associated to a single pdf file are numbered according to the page, they share the same short_name. """ png_in = os.path.join(pngpath,short_name) # Iterate over the pages of the document (different png files) for pngfile in glob.glob(png_in+'*'): pat...
identifier_body
pdf2txt.py
#!/usr/bin/env python3 """ Program that convert a pdf to a text file using Tesseract OCR. The pdf file is first converted to a png file using ghostscript, then the png file if processed by Tesseract. """ import os import subprocess import glob import platform import argparse parser = argparse.ArgumentParser(descri...
def pdf_to_png(pdf_file,short_name,png_path,page_limit=4): """ Convert the pdf to png, each page of the pdf gives a different png file.""" out_name = short_name+'.%d.png' out_file = os.path.join(png_path,out_name) if platform.system() == 'Windows': cmd_pdf2png = ('gswin32c -dSAFER -dNOPAUSE -q -r300x300 -sDEVI...
path,filename = os.path.split(pngfile) txtfile = filename[0:-4] #+'.txt' txt_out = os.path.join(txtpath,txtfile) try: cmd_png2txt = 'tesseract '+ pngfile +' '+txt_out+ ' -l fra+eng' proc_results = subprocess.run(cmd_png2txt.split(), stdout=subprocess.PIPE,timeout=60) if proc_results.returncode: print...
conditional_block
pdf2txt.py
#!/usr/bin/env python3 """ Program that convert a pdf to a text file using Tesseract OCR. The pdf file is first converted to a png file using ghostscript, then the png file if processed by Tesseract. """ import os import subprocess import glob import platform import argparse parser = argparse.ArgumentParser(descri...
txt_path = os.path.join(PDF_PATH,'txt') if not os.path.exists(png_path): os.makedirs(png_path) if not os.path.exists(txt_path): os.makedirs(txt_path) # Loop over all the file in the pdf folder nb_files = len(list(glob.glob(os.path.join(PDF_PATH,'*.pdf')))) for idx,pdf_file in enumerate(glob.glob(os.path.j...
logfile.write('Logfile produced by pdf2txt.py\n') # init paths png_path = os.path.join(PDF_PATH,'png')
random_line_split
pdf2txt.py
#!/usr/bin/env python3 """ Program that convert a pdf to a text file using Tesseract OCR. The pdf file is first converted to a png file using ghostscript, then the png file if processed by Tesseract. """ import os import subprocess import glob import platform import argparse parser = argparse.ArgumentParser(descri...
(pdf_file,short_name,png_path,page_limit=4): """ Convert the pdf to png, each page of the pdf gives a different png file.""" out_name = short_name+'.%d.png' out_file = os.path.join(png_path,out_name) if platform.system() == 'Windows': cmd_pdf2png = ('gswin32c -dSAFER -dNOPAUSE -q -r300x300 -sDEVICE=pnggray -dBATC...
pdf_to_png
identifier_name