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
paragraph.tsx
import { Editor, EditorState, RichUtils } from "draft-js" import { debounce } from "lodash" import React, { Component } from "react" import ReactDOM from "react-dom" import styled from "styled-components" import { TextInputUrl } from "../components/text_input_url" import { TextNav } from "../components/text_nav" import...
setEditorState = () => { const { hasLinks, html } = this.props if (html) { return this.editorStateFromHTML(html) } else { return EditorState.createEmpty(decorators(hasLinks)) } } editorStateToHTML = (editorState: EditorState) => { const { allowEmptyLines, stripLinebreaks } = th...
{ super(props) this.allowedStyles = styleMapFromNodes( props.allowedStyles || allowedStylesParagraph ) this.state = { editorPosition: null, editorState: this.setEditorState(), html: props.html || "", showNav: false, showUrlInput: false, urlValue: "", } ...
identifier_body
paragraph.tsx
import { Editor, EditorState, RichUtils } from "draft-js" import { debounce } from "lodash" import React, { Component } from "react" import ReactDOM from "react-dom" import styled from "styled-components" import { TextInputUrl } from "../components/text_input_url" import { TextNav } from "../components/text_nav" import...
this.editor = ref }} spellCheck /> </div> </ParagraphContainer> ) } } const ParagraphContainer = styled.div` position: relative; `
onChange={this.onChange} placeholder={placeholder || "Start typing..."} readOnly={isReadOnly} ref={ref => {
random_line_split
iter.rs
use std::mem; struct
{ curr: uint, next: uint, } // Implement 'Iterator' for 'Fibonacci' impl Iterator<uint> for Fibonacci { // The 'Iterator' trait only requires the 'next' method to be defined. The // return type is 'Option<T>', 'None' is returned when the 'Iterator' is // over, otherwise the next value is returned ...
Fibonacci
identifier_name
iter.rs
use std::mem; struct Fibonacci { curr: uint, next: uint, } // Implement 'Iterator' for 'Fibonacci' impl Iterator<uint> for Fibonacci { // The 'Iterator' trait only requires the 'next' method to be defined. The // return type is 'Option<T>', 'None' is returned when the 'Iterator' is // over, otherw...
} // Returns a fibonacci sequence generator fn fibonacci() -> Fibonacci { Fibonacci { curr: 1, next: 1 } } fn main() { // Iterator that generates: 0, 1 and 2 let mut sequence = range(0u, 3); println!("Four consecutive `next` calls on range(0, 3)") println!("> {}", sequence.next()); println!(...
{ let new_next = self.curr + self.next; let new_curr = mem::replace(&mut self.next, new_next); // 'Some' is always returned, this is an infinite value generator Some(mem::replace(&mut self.curr, new_curr)) }
identifier_body
iter.rs
use std::mem; struct Fibonacci { curr: uint, next: uint, } // Implement 'Iterator' for 'Fibonacci' impl Iterator<uint> for Fibonacci { // The 'Iterator' trait only requires the 'next' method to be defined. The // return type is 'Option<T>', 'None' is returned when the 'Iterator' is // over, otherw...
let mut sequence = range(0u, 3); println!("Four consecutive `next` calls on range(0, 3)") println!("> {}", sequence.next()); println!("> {}", sequence.next()); println!("> {}", sequence.next()); println!("> {}", sequence.next()); // The for construct will iterate an 'Iterator' until it ret...
// Iterator that generates: 0, 1 and 2
random_line_split
test_bucketing.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(seq_len): data = mx.sym.Variable('data') label = mx.sym.Variable('softmax_label') embed = mx.sym.Embedding(data=data, input_dim=len_vocab, output_dim=num_embed, name='embed') stack.reset() outputs, states = stack.unroll(seq_len, inputs=embed, me...
sym_gen
identifier_name
test_bucketing.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
context=contexts) logging.info('Begin fit...') model.fit( train_data=data_train, eval_data=data_val, eval_metric=mx.metric.Perplexity(invalid_label), # Use Perplexity for multiclass classification. kvstore='device', optimizer='sgd', optimizer_params={'lea...
model = mx.mod.BucketingModule( sym_gen=sym_gen, default_bucket_key=data_train.default_bucket_key,
random_line_split
test_bucketing.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
contexts = mx.cpu(0) model = mx.mod.BucketingModule( sym_gen=sym_gen, default_bucket_key=data_train.default_bucket_key, context=contexts) logging.info('Begin fit...') model.fit( train_data=data_train, eval_data=data_val, eval_metric=mx.metric.Perplexit...
data = mx.sym.Variable('data') label = mx.sym.Variable('softmax_label') embed = mx.sym.Embedding(data=data, input_dim=len_vocab, output_dim=num_embed, name='embed') stack.reset() outputs, states = stack.unroll(seq_len, inputs=embed, merge_outputs=True) ...
identifier_body
test_bucketing.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
train_sent.append(train_sentence) val_sent.append(val_sentence) data_train = mx.rnn.BucketSentenceIter(train_sent, batch_size, buckets=buckets, invalid_label=invalid_label) data_val = mx.rnn.BucketSentenceIter(val_sent, batch_size, buckets=buckets, ...
train_sentence.append(randint(1, len_vocab)) val_sentence.append(randint(1, len_vocab))
conditional_block
file.ts
import {bindable, autoinject} from 'aurelia-framework'; import {ExampleContext} from './example-context'; let extensionLanguageMap = { js: 'javascript', html: 'markup' }; function getLanguage(filename) { let extension = (/\.(\w+)$/).exec(filename)[1].toLowerCase(); return extensionLanguageMap[extension]; } @...
}
{ let src = this.src, example = this.example; this.info = { name: src, moduleId: this.base + '/' + src.substr(0, src.indexOf('.')), language: getLanguage(src), url: 'dist/' + this.base + '/' + src, repoUrl: this.githubBase + '/dist/' + this.base + '/' + src }; if (thi...
identifier_body
file.ts
import {bindable, autoinject} from 'aurelia-framework'; import {ExampleContext} from './example-context'; let extensionLanguageMap = { js: 'javascript', html: 'markup' }; function getLanguage(filename) { let extension = (/\.(\w+)$/).exec(filename)[1].toLowerCase(); return extensionLanguageMap[extension]; } @...
example.model = this.info; example.result = example.view && example.model; } }
random_line_split
file.ts
import {bindable, autoinject} from 'aurelia-framework'; import {ExampleContext} from './example-context'; let extensionLanguageMap = { js: 'javascript', html: 'markup' }; function getLanguage(filename) { let extension = (/\.(\w+)$/).exec(filename)[1].toLowerCase(); return extensionLanguageMap[extension]; } @...
() { let src = this.src, example = this.example; this.info = { name: src, moduleId: this.base + '/' + src.substr(0, src.indexOf('.')), language: getLanguage(src), url: 'dist/' + this.base + '/' + src, repoUrl: this.githubBase + '/dist/' + this.base + '/' + src }; if (...
bind
identifier_name
get_all_networks.py
#!/usr/bin/env python # # Copyright 2016 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 requir...
def main(client): # Initialize appropriate service. network_service = client.GetService('NetworkService', version='v201805') networks = network_service.getAllNetworks() # Print out some information for each network. for network in networks: print('Network with network code "%s" and display name "%s" w...
""" # Import appropriate modules from the client library. from googleads import ad_manager
random_line_split
get_all_networks.py
#!/usr/bin/env python # # Copyright 2016 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 requir...
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client)
conditional_block
get_all_networks.py
#!/usr/bin/env python # # Copyright 2016 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 requir...
(client): # Initialize appropriate service. network_service = client.GetService('NetworkService', version='v201805') networks = network_service.getAllNetworks() # Print out some information for each network. for network in networks: print('Network with network code "%s" and display name "%s" was found.'...
main
identifier_name
get_all_networks.py
#!/usr/bin/env python # # Copyright 2016 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 requir...
if __name__ == '__main__': # Initialize client object. ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage() main(ad_manager_client)
network_service = client.GetService('NetworkService', version='v201805') networks = network_service.getAllNetworks() # Print out some information for each network. for network in networks: print('Network with network code "%s" and display name "%s" was found.' % (network['networkCode'], network['d...
identifier_body
test_python.py
# -*- coding: utf-8 -*- import unittest from kiwi.python import AttributeForwarder, slicerange, enum, strip_accents class SliceTest(unittest.TestCase): def genlist(self, limit, start, stop=None, step=None):
return list(slicerange(slice(start, stop, step), limit)) def testStop(self): self.assertEqual(self.genlist(10, 10), list(range(10))) self.assertEqual(self.genlist(10, -5), list(range(5))) self.assertEqual(self.genlist(10, -15), []) self.assertEqual(self.genlist(5, 10), list(...
if stop is None: stop = start start = None
random_line_split
test_python.py
# -*- coding: utf-8 -*- import unittest from kiwi.python import AttributeForwarder, slicerange, enum, strip_accents class SliceTest(unittest.TestCase):
def testStartStopStep(self): self.assertEqual(self.genlist(10, 0, 10, 2), list(range(10))[0:10:2]) class Status(enum): OPEN, CLOSE = range(2) class Color(enum): RED, GREEN, BLUE = range(3) class EnumTest(unittest.TestCase): def testEnums(self): self.assertTrue(issubclass(enum, in...
def genlist(self, limit, start, stop=None, step=None): if stop is None: stop = start start = None return list(slicerange(slice(start, stop, step), limit)) def testStop(self): self.assertEqual(self.genlist(10, 10), list(range(10))) self.assertEqual(self.genli...
identifier_body
test_python.py
# -*- coding: utf-8 -*- import unittest from kiwi.python import AttributeForwarder, slicerange, enum, strip_accents class SliceTest(unittest.TestCase): def genlist(self, limit, start, stop=None, step=None): if stop is None: stop = start start = None return list(slicerang...
(unittest.TestCase): def testStripAccents(self): for string, string_without_accentuation in [ # bytes ('áâãäåāăąàÁÂÃÄÅĀĂĄÀ'.encode(), b'aaaaaaaaaAAAAAAAAA'), ('èééêëēĕėęěĒĔĖĘĚ'.encode(), b'eeeeeeeeeeEEEEE'), ('ìíîïìĩīĭÌÍÎÏÌĨĪĬ'.encode(), b'iiiiiiiiIIIIIIII'), ...
StripAccentsTest
identifier_name
test_python.py
# -*- coding: utf-8 -*- import unittest from kiwi.python import AttributeForwarder, slicerange, enum, strip_accents class SliceTest(unittest.TestCase): def genlist(self, limit, start, stop=None, step=None): if stop is None: stop = start start = None return list(slicerang...
conditional_block
build.rs
.c", "hts_os.c", "md5.c", "multipart.c", "probaln.c", "realn.c", "regidx.c", "region.c", "sam.c", "synced_bcf_reader.c", "vcf_sweep.c", "tbx.c", "textutils.c", "thread_pool.c", "vcf.c", "vcfutils.c", "cram/cram_codecs.c", "cram/cram_decode.c", "cra...
} let use_lzma = env::var("CARGO_FEATURE_LZMA").is_ok(); if use_lzma { if let Ok(inc) = env::var("DEP_LZMA_INCLUDE").map(PathBuf::from) { cfg.include(inc); lib_list += " -llzma"; config_lines.push("#define HAVE_LIBBZ2 1"); config_lines.push("#ifndef _...
panic!("no DEP_LIBDEFLATE_INCLUDE"); }
conditional_block
build.rs
_expr.c", "hts_os.c", "md5.c", "multipart.c", "probaln.c", "realn.c", "regidx.c", "region.c", "sam.c", "synced_bcf_reader.c", "vcf_sweep.c", "tbx.c", "textutils.c", "thread_pool.c", "vcf.c", "vcfutils.c", "cram/cram_codecs.c", "cram/cram_decode.c", ...
"htscodecs/htscodecs/fqzcomp_qual.c", "htscodecs/htscodecs/htscodecs.c", "htscodecs/htscodecs/pack.c", "htscodecs/htscodecs/rANS_static4x16pr.c", "htscodecs/htscodecs/rANS_static.c", "htscodecs/htscodecs/rle.c", "htscodecs/htscodecs/tokenise_name3.c", ]; fn main() { let out = PathBuf::f...
"cram/mFILE.c", "cram/open_trace_file.c", "cram/pooled_alloc.c", "cram/string_alloc.c", "htscodecs/htscodecs/arith_dynamic.c",
random_line_split
build.rs
.c", "hts_os.c", "md5.c", "multipart.c", "probaln.c", "realn.c", "regidx.c", "region.c", "sam.c", "synced_bcf_reader.c", "vcf_sweep.c", "tbx.c", "textutils.c", "thread_pool.c", "vcf.c", "vcfutils.c", "cram/cram_codecs.c", "cram/cram_decode.c", "cra...
let c_file = out_htslib.join(f); cfg.file(&c_file); println!("cargo:rerun-if-changed={}", htslib.join(f).display()); } cfg.include(out.join("htslib")); let want_static = cfg!(feature = "static") || env::var("HTS_STATIC").is_ok(); if want_static { cfg.warnings(false).st...
let out = PathBuf::from(env::var("OUT_DIR").unwrap()); let htslib_copy = out.join("htslib"); if htslib_copy.exists() { std::fs::remove_dir_all(htslib_copy).unwrap(); } copy_directory("htslib", &out).unwrap(); // In build.rs cfg(target_os) does not give the target when cross-compiling;...
identifier_body
build.rs
.c", "hts_os.c", "md5.c", "multipart.c", "probaln.c", "realn.c", "regidx.c", "region.c", "sam.c", "synced_bcf_reader.c", "vcf_sweep.c", "tbx.c", "textutils.c", "thread_pool.c", "vcf.c", "vcfutils.c", "cram/cram_codecs.c", "cram/cram_decode.c", "cra...
) { let out = PathBuf::from(env::var("OUT_DIR").unwrap()); let htslib_copy = out.join("htslib"); if htslib_copy.exists() { std::fs::remove_dir_all(htslib_copy).unwrap(); } copy_directory("htslib", &out).unwrap(); // In build.rs cfg(target_os) does not give the target when cross-compili...
ain(
identifier_name
courselist.js
app.directive('modelanythingPluginsCourselist', [ "settings", "$location", "SessionService", "User", "Course", function( settings, $location, SessionService, User, Course ) { return { templateUrl: settings.widgets + 'modelanything/plugins/courselist.html', link: functio...
(array, attr, value) { for(var i = 0; i < array.length; i += 1) { if(array[i][attr] === value) { return i; } } } scope.class = "assignClass" scope.courseLocation = function(obj) { $location.path("courses/" + obj.currentTarget....
findWithAttr
identifier_name
courselist.js
app.directive('modelanythingPluginsCourselist', [ "settings", "$location", "SessionService", "User", "Course", function( settings, $location, SessionService, User, Course ) { return { templateUrl: settings.widgets + 'modelanything/plugins/courselist.html', link: functio...
scope.class = "assignClass" scope.courseLocation = function(obj) { $location.path("courses/" + obj.currentTarget.attributes.dataLocation.value); }; scope.$root.$on('addedCourse', function() { refresh(); }); } } } ]);
{ for(var i = 0; i < array.length; i += 1) { if(array[i][attr] === value) { return i; } } }
identifier_body
courselist.js
app.directive('modelanythingPluginsCourselist', [ "settings", "$location", "SessionService", "User", "Course", function( settings, $location, SessionService, User, Course ) { return { templateUrl: settings.widgets + 'modelanything/plugins/courselist.html', link: functio...
else if((session_user[0].role == "student") || (session_user[0].role == "teacher")) { scope.heading = "My courses"; } scope.pinnedCourses = []; if(user[0].courses_pinned.length > 0) { var allPinnedCourses = []; for (i = 0; i < u...
{ scope.heading = "All courses"; }
conditional_block
courselist.js
app.directive('modelanythingPluginsCourselist', [ "settings", "$location", "SessionService", "User", "Course", function( settings, $location, SessionService, User, Course ) { return { templateUrl: settings.widgets + 'modelanything/plugins/courselist.html', link: functio...
scope.heading = "My courses"; } scope.pinnedCourses = []; if(user[0].courses_pinned.length > 0) { var allPinnedCourses = []; for (i = 0; i < user[0].courses_pinned.length; i++) { currentObj = session_user[0].cou...
random_line_split
backboneApp.js
var Backbone = require('backbone'), _ = require('underscore'); global.App = {}; App.Task = Backbone.Model.extend({ url : 'http://localhost:9292/tasks/' + this.get('id'), defaults : { title: 'Untitled Task 1', done : false } }); App.TaskCollection = Backbone.collection.extend({ mod...
showList: function() { var tasks = new App.TaskCollection(); var view = new App.TaskCollectionView({collection: tasks}); $('body').html(view.render().el); } }); module.exports = App;
'(/)' : 'showList' },
random_line_split
tooltip.js
$$rAF.throttle(updatePosition); var mouseActive = false; var origin, position, panelPosition, panelRef, autohide, showTimeout, elementFocusedOnWindowBlur = null; // Set defaults setDefaults(); // Set parent aria-label. addAriaLabel(); // Remove the element from its current DOM po...
if (!scope.visibleWatcher) { onVisibleChanged(false);
random_line_split
tooltip.js
-label` to the parent if there isn't already one, if there isn't an // already present `aria-labelledby`, or if the previous `aria-label` was added by the // tooltip directive. if ( (!parent.attr('aria-label') && !parent.attr('aria-labelledby')) || parent.attr('md-labeled-by-tooltip') ...
{ var attachTo = angular.element(document.body); var panelAnimation = $mdPanel.newPanelAnimation() .openFrom(parent) .closeTo(parent) .withAnimation({ open: 'md-show', close: 'md-hide' }); var panelConfig = { ...
conditional_block
tooltip.js
relative to the parent element. Supports top, right, bottom, and left. * Defaults to bottom. */ function MdTooltipDirective($timeout, $window, $$rAF, $document, $interpolate, $mdUtil, $mdPanel, $$mdTooltipRegistry) { var ENTER_EVENTS = 'focus touchstart mouseenter'; var LEAVE_EVENTS = 'blur touchcan...
() { if (element[0] && 'MutationObserver' in $window) { var attributeObserver = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if (mutation.attributeName === 'md-visible' && !scope.visibleWatcher ) { scope.visibleWatche...
configureWatchers
identifier_name
tooltip.js
relative to the parent element. Supports top, right, bottom, and left. * Defaults to bottom. */ function MdTooltipDirective($timeout, $window, $$rAF, $document, $interpolate, $mdUtil, $mdPanel, $$mdTooltipRegistry) { var ENTER_EVENTS = 'focus touchstart mouseenter'; var LEAVE_EVENTS = 'blur touchcan...
.addPanelPosition(position.x, position.y); // If the panel has already been created, add the new origin class to // the panel element and update it's position with the panelPosition. if (panelRef && panelRef.panelEl) { panelRef.panelEl.addClass(origin); panelRef.updatePositi...
{ setDefaults(); // If the panel has already been created, remove the current origin // class from the panel element. if (panelRef && panelRef.panelEl) { panelRef.panelEl.removeClass(origin); } // Set the panel element origin class based off of the current // mdDirect...
identifier_body
recursiveFunctionTypes.js
//// [recursiveFunctionTypes.ts] function fn(): typeof fn { return 1; } var x: number = fn; // error var y: () => number = fn; // ok var f: () => typeof g; var g: () => typeof f; function f1(d: typeof f1) { } function f2(): typeof g2 { } function g2(): typeof f2 { } interface I<T> { } function f3(): I<typeof f3>...
declare function f7(a?: typeof f7): typeof f7; f7("", 3); // error (arity mismatch) f7(""); // ok (function takes an any param) f7(); // ok //// [recursiveFunctionTypes.js] function fn() { return 1; } var x = fn; // error var y = fn; // ok var f; var g; function f1(d) { } function f2() { } function g2() { } function ...
declare function f7(): typeof f7; declare function f7(a: typeof f7): () => number; declare function f7(a: number): number;
random_line_split
recursiveFunctionTypes.js
//// [recursiveFunctionTypes.ts] function fn(): typeof fn { return 1; } var x: number = fn; // error var y: () => number = fn; // ok var f: () => typeof g; var g: () => typeof f; function f1(d: typeof f1) { } function f2(): typeof g2 { } function g2(): typeof f2 { } interface I<T> { } function f3(): I<typeof f3>...
{ static g(t: typeof C.g){ } } C.g(3); // error var f4: () => typeof f4; f4 = 3; // error function f5() { return f5; } function f6(): typeof f6; function f6(a: typeof f6): () => number; function f6(a?: any) { return f6; } f6("", 3); // error (arity mismatch) f6(""); // ok (function takes an any param) f6(); /...
C
identifier_name
recursiveFunctionTypes.js
//// [recursiveFunctionTypes.ts] function fn(): typeof fn
var x: number = fn; // error var y: () => number = fn; // ok var f: () => typeof g; var g: () => typeof f; function f1(d: typeof f1) { } function f2(): typeof g2 { } function g2(): typeof f2 { } interface I<T> { } function f3(): I<typeof f3> { return f3; } var a: number = f3; // error class C { static g(...
{ return 1; }
identifier_body
drf.py
import six from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class EnumField(serializers.ChoiceField): default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')} def __init__(self, enum, **kwargs):
def get_choice_value(self, enum_value): return enum_value.value def to_internal_value(self, data): if isinstance(data, six.string_types) and data.isdigit(): data = int(data) try: value = self.enum.get(data).value except AttributeError: # .get() return...
self.enum = enum choices = ( (self.get_choice_value(enum_value), enum_value.label) for _, enum_value in enum.choices() ) super(EnumField, self).__init__(choices, **kwargs)
identifier_body
drf.py
import six from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class EnumField(serializers.ChoiceField): default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')} def __init__(self, enum, **kwargs): self.enum = enum choices =...
class NamedEnumField(EnumField): def get_choice_value(self, enum_value): return enum_value.name class Meta: swagger_schema_fields = {"type": "string"}
random_line_split
drf.py
import six from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class EnumField(serializers.ChoiceField): default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')} def __init__(self, enum, **kwargs): self.enum = enum choices =...
self.fail("invalid_choice", input=data) return value def to_representation(self, value): enum_value = self.enum.get(value) if enum_value is not None: return self.get_choice_value(enum_value) class NamedEnumField(EnumField): def get_choice_value(self, enum_val...
raise serializers.SkipField()
conditional_block
drf.py
import six from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class EnumField(serializers.ChoiceField): default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')} def __init__(self, enum, **kwargs): self.enum = enum choices =...
(self, data): if isinstance(data, six.string_types) and data.isdigit(): data = int(data) try: value = self.enum.get(data).value except AttributeError: # .get() returned None if not self.required: raise serializers.SkipField() self...
to_internal_value
identifier_name
ToolbarIcon.tsx
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import Glyph from './Glyph';
import {Tracked} from 'flipper-plugin'; type Props = React.ComponentProps<typeof ToolbarIconContainer> & { active?: boolean; icon: string; title: string; onClick: () => void; }; const ToolbarIconContainer = styled.div({ marginRight: 9, marginTop: -3, marginLeft: 4, position: 'relative', // for setting...
import Tooltip from './Tooltip'; import {colors} from './colors'; import styled from '@emotion/styled'; import React from 'react';
random_line_split
ToolbarIcon.tsx
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import Glyph from './Glyph'; import Tooltip from './Tooltip'; import {colors} from './colors'; import styled from ...
({active, icon, title, ...props}: Props) { return ( <Tooltip title={title}> <Tracked action={title}> <ToolbarIconContainer {...props}> <Glyph name={icon} size={16} color={ active ? colors.macOSTitleBarIconSelected ...
ToolbarIcon
identifier_name
ToolbarIcon.tsx
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import Glyph from './Glyph'; import Tooltip from './Tooltip'; import {colors} from './colors'; import styled from ...
{ return ( <Tooltip title={title}> <Tracked action={title}> <ToolbarIconContainer {...props}> <Glyph name={icon} size={16} color={ active ? colors.macOSTitleBarIconSelected : colors.macOSTitleBarIconActive ...
identifier_body
timelineTemplete.js
start--------------"); animation = null; }); } e.source.video.addEventListener('complete',function(){ e.source.video.stop(); console.log("----------------------video complete-----------------"); var animation2 = Ti.UI.createAnimation({ opacity:0, duration:1 }); e.source...
= dataArray[i].videoUrl; view.add(videoView); row.show(); rowArray.push(row); } return rowArray; };
conditional_block
timelineTemplete.js
.source == '[object TiUIImageView]'){ if(tableView.prependMovie != "none"){ tableView.prependMovie.stop(); tableView.prependMovie = e.source.video; console.log(e.source.video); console.log(tableView.prependMovie); console.log("-------------------------------------------------------"); } ...
width:Ti.UI.FILL, height:Ti.UI.SIZE, }); row.add(view); // if(i == 0){ // console.log(json.data.records[i]); // } // console.log(json.data.records[i]); var videoView = Ti.UI.createImageView({ top:5, height:300, width:300, image:dataArray[i].thumbnailUrl, }); /* 構造 5px...
var view = Ti.UI.createView({
random_line_split
lib.rs
/* Copyright (C) 2015 Yutaka Kamei */ #![feature(test)] extern crate urlparse; extern crate test; use urlparse::*; use test::Bencher; #[bench] fn bench_quote(b: &mut Bencher) { b.iter(|| quote("/a/テスト !/", &[b'/'])); } #[bench] fn bench_quote_plus(b: &mut Bencher) { b.iter(|| quote_plus("/a/テスト !/", &[b'/'...
cher) { b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/")); } #[bench] fn bench_unquote_plus(b: &mut Bencher) { b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/")); } #[bench] fn bench_parse_qs(b: &mut Bencher) { b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%E3%83%88+%E3%83%86%E3%82%B9%...
e(b: &mut Ben
identifier_name
lib.rs
/* Copyright (C) 2015 Yutaka Kamei */ #![feature(test)] extern crate urlparse; extern crate test; use urlparse::*; use test::Bencher; #[bench] fn bench_quote(b: &mut Bencher) { b.iter(|| quote("/a/テスト !/", &[b'/'])); } #[bench] fn bench_quote_plus(b: &mut Bencher) { b.iter(|| quote_plus("/a/テスト !/", &[b'/'...
}
query: Some("filter=%28%21%28cn%3Dbar%29%29".to_string()), .. url}; urlunparse(url) });
random_line_split
lib.rs
/* Copyright (C) 2015 Yutaka Kamei */ #![feature(test)] extern crate urlparse; extern crate test; use urlparse::*; use test::Bencher; #[bench] fn bench_quote(b: &mut Bencher) { b.iter(|| quote("/a/テスト !/", &[b'/'])); } #[bench] fn bench_quote_plus(b: &mut Bencher) {
fn bench_unquote(b: &mut Bencher) { b.iter(|| unquote("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/")); } #[bench] fn bench_unquote_plus(b: &mut Bencher) { b.iter(|| unquote_plus("/a/%E3%83%86%E3%82%B9%E3%83%88%20%21/")); } #[bench] fn bench_parse_qs(b: &mut Bencher) { b.iter(|| parse_qs("q=%E3%83%86%E3%82%B9%...
b.iter(|| quote_plus("/a/テスト !/", &[b'/'])); } #[bench]
identifier_body
linux_gl_hooks.rs
#![cfg(target_os = "linux")] #[link(name = "dl")] extern "C" {} use crate::gl; use const_cstr::const_cstr; use lazy_static::lazy_static; use libc::{c_char, c_int, c_ulong, c_void}; use libc_print::libc_println; use log::*; use std::ffi::CString; use std::sync::Once; use std::time::SystemTime; ///////////////////////...
y, width, height, gl::GL_RGBA, gl::GL_UNSIGNED_BYTE, std::mem::transmute(frame_buffer.as_ptr()), ); let mut num_black = 0; for y in 0..height { for x in 0..width { let i = (y * width + x) as usize; let (r, g, b) = ( ...
{ let cc = gl::get_capture_context(get_glx_proc_address); cc.capture_frame(); let x: gl::GLint = 0; let y: gl::GLint = 0; let width: gl::GLsizei = 400; let height: gl::GLsizei = 400; let bytes_per_pixel: usize = 4; let bytes_per_frame: usize = width as usize * height as usize * bytes_pe...
identifier_body
linux_gl_hooks.rs
#![cfg(target_os = "linux")] #[link(name = "dl")] extern "C" {} use crate::gl; use const_cstr::const_cstr; use lazy_static::lazy_static; use libc::{c_char, c_int, c_ulong, c_void}; use libc_print::libc_println; use log::*; use std::ffi::CString; use std::sync::Once; use std::time::SystemTime; ///////////////////////...
() { let cc = gl::get_capture_context(get_glx_proc_address); cc.capture_frame(); let x: gl::GLint = 0; let y: gl::GLint = 0; let width: gl::GLsizei = 400; let height: gl::GLsizei = 400; let bytes_per_pixel: usize = 4; let bytes_per_frame: usize = width as usize * height as usize * bytes...
capture_gl_frame
identifier_name
linux_gl_hooks.rs
#![cfg(target_os = "linux")] #[link(name = "dl")] extern "C" {} use crate::gl; use const_cstr::const_cstr; use lazy_static::lazy_static; use libc::{c_char, c_int, c_ulong, c_void}; use libc_print::libc_println; use log::*; use std::ffi::CString; use std::sync::Once; use std::time::SystemTime; ///////////////////////...
using } static HOOK_SWAPBUFFERS_ONCE: Once = Once::new(); /// If libGL.so.1 was loaded, and only once in the lifetime /// of this process, hook libGL functions for libcapsule usage. unsafe fn hook_if_needed() { if is_using_opengl() { HOOK_SWAPBUFFERS_ONCE.call_once(|| { info!("libGL usage...
{ dlclose(handle); }
conditional_block
linux_gl_hooks.rs
#![cfg(target_os = "linux")] #[link(name = "dl")] extern "C" {} use crate::gl; use const_cstr::const_cstr; use lazy_static::lazy_static; use libc::{c_char, c_int, c_ulong, c_void}; use libc_print::libc_println; use log::*; use std::ffi::CString; use std::sync::Once; use std::time::SystemTime; ///////////////////////...
let using = !handle.is_null(); if using { dlclose(handle); } using } static HOOK_SWAPBUFFERS_ONCE: Once = Once::new(); /// If libGL.so.1 was loaded, and only once in the lifetime /// of this process, hook libGL functions for libcapsule usage. unsafe fn hook_if_needed() { if is_using_opengl...
// modules are reference-counted. let handle = dlopen::next(const_cstr!("libGL.so.1").as_ptr(), RTLD_NOLOAD | RTLD_LAZY);
random_line_split
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
} impl PseudoElement { /// Returns the kind of cascade type that a given pseudo is going to use. /// /// In Gecko we only compute ::before and ::after eagerly. We save the rules /// for anonymous boxes separately, so we resolve them as precomputed /// pseudos. /// /// We resolve the others...
{ if !self.supports_user_action_state() { return false; } return pseudo_class.is_safe_user_action_state(); }
identifier_body
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
pub fn cascade_type(&self) -> PseudoElementCascadeType { if self.is_eager() { debug_assert!(!self.is_anon_box()); return PseudoElementCascadeType::Eager } if self.is_precomputed() { return PseudoElementCascadeType::Precomputed } PseudoEle...
/// pseudos. /// /// We resolve the others lazily, see `Servo_ResolvePseudoStyle`.
random_line_split
pseudo_element.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/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
(&self) -> bool { (self.flags() & structs::CSS_PSEUDO_ELEMENT_IS_FLEX_OR_GRID_ITEM) == 0 } /// Whether this pseudo-element is precomputed. #[inline] pub fn is_precomputed(&self) -> bool { self.is_anon_box() && !self.is_tree_pseudo_element() } /// Covert non-canonical pseudo-ele...
skip_item_based_display_fixup
identifier_name
control_slider.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/yeison/Documentos/python/developing/pinguino/pinguino-ide/qtgui/gide/bloques/widgets/control_slider.ui' # # Created: Wed Mar 4 01:39:58 2015 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this fi...
self.lineEdit_2.setReadOnly(True) self.lineEdit_2.setObjectName("lineEdit_2") self.gridLayout.addWidget(self.lineEdit_2, 0, 1, 1, 1) self.horizontalSlider = QtGui.QSlider(Frame) self.horizontalSlider.setCursor(QtCore.Qt.PointingHandCursor) self.horizontalSlider.setFocusPo...
def setupUi(self, Frame): Frame.setObjectName("Frame") Frame.resize(237, 36) Frame.setWindowTitle("") self.gridLayout = QtGui.QGridLayout(Frame) self.gridLayout.setSpacing(0) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout"...
identifier_body
control_slider.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/yeison/Documentos/python/developing/pinguino/pinguino-ide/qtgui/gide/bloques/widgets/control_slider.ui' # # Created: Wed Mar 4 01:39:58 2015 # by: pyside-uic 0.2.15 running on PySide 1.2.2 #
def setupUi(self, Frame): Frame.setObjectName("Frame") Frame.resize(237, 36) Frame.setWindowTitle("") self.gridLayout = QtGui.QGridLayout(Frame) self.gridLayout.setSpacing(0) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLay...
# WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui class Ui_Frame(object):
random_line_split
control_slider.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/yeison/Documentos/python/developing/pinguino/pinguino-ide/qtgui/gide/bloques/widgets/control_slider.ui' # # Created: Wed Mar 4 01:39:58 2015 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this fi...
(self, Frame): Frame.setObjectName("Frame") Frame.resize(237, 36) Frame.setWindowTitle("") self.gridLayout = QtGui.QGridLayout(Frame) self.gridLayout.setSpacing(0) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") s...
setupUi
identifier_name
dynamic_form.js
$( document ).ready( function() { 'use strict'; function validateEmail (email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function validateInput (str)...
function init() { $('form[data-dynamic_form]').bind('keypress', function (e) { if(e.keyCode == 13) return false; }); // Handles the signin process, basic validation $('form#new_user').on('submit', function () { var email = $('input#user_email').val(); var passw...
{ $('<div class="standalone_form--message" id="' + type+ '">' + msg + '</div>').insertAfter('.standalone_form--heading'); }
identifier_body
dynamic_form.js
$( document ).ready( function() { 'use strict'; function validateEmail (email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function validateInput (str)...
if ($('input[data-pwd-short]').length > 0 && $('input#user_password_confirmation').length > 0 && errors && !validatePassword(password)) { var msg = $('input#user_password').attr('data-pwd-short'); addError(msg, 'password-error'); errors = false; } if ($('input[data-pwd-matc...
{ var msg = $('input#user_password').attr('data-req-msg'); addError(msg, 'password-error'); errors = false; }
conditional_block
dynamic_form.js
$( document ).ready( function() { 'use strict'; function validateEmail (email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function validateInput (str)...
(msg, type) { $('<div class="standalone_form--message" id="' + type+ '">' + msg + '</div>').insertAfter('.standalone_form--heading'); } function init() { $('form[data-dynamic_form]').bind('keypress', function (e) { if(e.keyCode == 13) return false; }); // Handles the signin pro...
addError
identifier_name
dynamic_form.js
$( document ).ready( function() { 'use strict'; function validateEmail (email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } function validateInput (str)...
errors = false; } return errors; }); $('[data-dynamic_form]' ).find('input[name],select[name]').on( 'change', function() { var form = $(this).parents('[data-dynamic_form]'), url = form.data( 'dynamic_form' ), page = window.location.href.split('/')[window.locatio...
addError(msg, 'email-error');
random_line_split
pmc__utils_8c.js
var pmc__utils_8c = [ [ "char_replace", "pmc__utils_8c.html#aafd74bb6564c3c3c057175e5b7973fec", null ], [ "cmp_float", "pmc__utils_8c.html#a7051d2192267dcba608e4720c7b0187c", null ], [ "cmp_int32", "pmc__utils_8c.html#ad08429d28a59ccf2ac45c0f54a16c323", null ], [ "error", "pmc__utils_8c.html#a7e15c8e288...
[ "find_new_el", "pmc__utils_8c.html#a0fac58c8eda4e3ec6634f2273d6db252", null ], [ "print_rules", "pmc__utils_8c.html#ac0dfe064e97b8cbcb1ecfbc4355c15ac", null ], [ "read_line", "pmc__utils_8c.html#a777131faf4806e7eee788b65cab4a584", null ], [ "shift_char_p", "pmc__utils_8c.html#a3409419eecfac258ec7f1fb6...
[ "find_n_el", "pmc__utils_8c.html#a00060354a866563dd8b9df73eb3899c3", null ],
random_line_split
tests_params.py
#!/usr/bin/env python2.7 # encoding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Vers...
return suite class RemoteTest(CreateTest): def setUp(self): self.param1 = tika.parser.from_file(self.param1) def test_true(self): self.assertTrue(self.param1) def test_meta(self): self.assertTrue(self.param1['metadata']) def test_content(self): self.assertTrue(s...
suite.addTest(test_case(name, param1=param1, param2=param2))
conditional_block
tests_params.py
#!/usr/bin/env python2.7 # encoding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Vers...
(self, methodName='runTest', param1=None, param2=None): super(CreateTest, self).__init__(methodName) self.param1 = param1 @staticmethod def parameterize(test_case, param1=None, param2=None): testloader = unittest.TestLoader() testnames = testloader.getTestCaseNames(test_case) ...
__init__
identifier_name
tests_params.py
#!/usr/bin/env python2.7 # encoding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Vers...
try: suite.addTest(CreateTest.parameterize(RemoteTest,param1=x)) except IOError as e: print(e.strerror) unittest.TextTestRunner(verbosity=2).run(suite)
t_urls = list(test_url()) t_urls.pop(0) #remove header for x in t_urls:
random_line_split
tests_params.py
#!/usr/bin/env python2.7 # encoding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Vers...
@staticmethod def parameterize(test_case, param1=None, param2=None): testloader = unittest.TestLoader() testnames = testloader.getTestCaseNames(test_case) suite = unittest.TestSuite() for name in testnames: suite.addTest(test_case(name, param1=param1, param2=param2)...
super(CreateTest, self).__init__(methodName) self.param1 = param1
identifier_body
tens.py
## -*- coding: utf-8 -*- ## Copyright (c) 2015-2018, Exa Analytics Development Team ## Distributed under the terms of the Apache License 2.0 #import six ##import numpy as np #import pandas as pd #from io import StringIO ##from exa import Series, TypedMeta #from exa import TypedMeta #from exatomic.core import Editor, Te...
# labels.append(d[1]) # cols = ['xx','xy','xz','yx','yy','yz','zx','zy','zz'] # af = pd.DataFrame([df.loc[[i*5+1,i*5+2,i*5+3],:].unstack().values], \ # columns=cols) # af['frame'] = labels[0] if labels[0] != '' el...
# d = lbl.split('=')
random_line_split
constrain-trait.rs
// run-rustfix // check-only #[derive(Debug)] struct Demo { a: String } trait GetString { fn get_a(&self) -> &String; } trait UseString: std::fmt::Debug { fn use_string(&self) { println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found } } trait UseString2 { fn use_string(&...
} fn main() {}
{ let d = Demo { a: "test".to_string() }; d.use_string(); }
identifier_body
constrain-trait.rs
// run-rustfix // check-only #[derive(Debug)] struct Demo { a: String } trait GetString { fn get_a(&self) -> &String; } trait UseString: std::fmt::Debug { fn use_string(&self) { println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found } } trait UseString2 { fn use_string(&...
impl UseString2 for Demo {} #[cfg(test)] mod tests { use crate::{Demo, UseString}; #[test] fn it_works() { let d = Demo { a: "test".to_string() }; d.use_string(); } } fn main() {}
impl UseString for Demo {}
random_line_split
constrain-trait.rs
// run-rustfix // check-only #[derive(Debug)] struct Demo { a: String } trait GetString { fn get_a(&self) -> &String; } trait UseString: std::fmt::Debug { fn use_string(&self) { println!("{:?}", self.get_a()); //~ ERROR no method named `get_a` found } } trait UseString2 { fn use_string(&...
(&self) -> &String { &self.a } } impl UseString for Demo {} impl UseString2 for Demo {} #[cfg(test)] mod tests { use crate::{Demo, UseString}; #[test] fn it_works() { let d = Demo { a: "test".to_string() }; d.use_string(); } } fn main() {}
get_a
identifier_name
sparsemax.py
# Copyright 2016 The TensorFlow Authors. 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 applica...
(logits, name=None): """Computes sparsemax activations [1]. For each batch `i` and class `j` we have $$sparsemax[i, j] = max(logits[i, j] - tau(logits[i, :]), 0)$$ [1]: https://arxiv.org/abs/1602.02068 Args: logits: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. ...
sparsemax
identifier_name
sparsemax.py
# Copyright 2016 The TensorFlow Authors. 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 applica...
# minor and substacting the mean causes extra issues with inf and nan # input. z = logits # sort z z_sorted, _ = nn.top_k(z, k=dims) # calculate k(z) z_cumsum = math_ops.cumsum(z_sorted, axis=1) k = math_ops.range( 1, math_ops.cast(dims, logits.dtype) + 1, dtype=logits.dtype) ...
# to zero. However, in practise the numerical instability issues are very
random_line_split
sparsemax.py
# Copyright 2016 The TensorFlow Authors. 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 applica...
# In the paper, they call the logits z. # The mean(logits) can be substracted from logits to make the algorithm # more numerically stable. the instability in this algorithm comes mostly # from the z_cumsum. Substacting the mean will cause z_cumsum to be close # to zero. However, in practise the num...
"""Computes sparsemax activations [1]. For each batch `i` and class `j` we have $$sparsemax[i, j] = max(logits[i, j] - tau(logits[i, :]), 0)$$ [1]: https://arxiv.org/abs/1602.02068 Args: logits: A `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. name: A name for the...
identifier_body
bin_xlsx.ts
'if file is encrypted, try with specified pw') .option('-l, --list-sheets', 'list sheet names and exit') .option('-o, --output <file>', 'output to specified file') .option('-B, --xlsb', 'emit XLSB to <sheetname> or <file>.xlsb') .option('-M, --xlsm', 'emit XLSM to <sheetname> or <file>.xlsm') .option('-X, --xlsx...
workbook_formats.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } }); wb_formats_2.forEach(function(m) { if(program[m[0]] || isfmt(m[0])) { wb_fmt(); } }); if(seen) { } else if(program.formulae) opts.cellFormula = true; else opts.cellFormula = false; const wopts: X.WritingOptions = ({WTF:opts.WTF,...
{ if(!program.output) return false; const t = m.charAt(0) === "." ? m : "." + m; return program.output.slice(-t.length) === t; }
identifier_body
bin_xlsx.ts
'if file is encrypted, try with specified pw') .option('-l, --list-sheets', 'list sheet names and exit') .option('-o, --output <file>', 'output to specified file') .option('-B, --xlsb', 'emit XLSB to <sheetname> or <file>.xlsb') .option('-M, --xlsm', 'emit XLSM to <sheetname> or <file>.xlsm') .option('-X, --xlsx...
opts.cellNF = true; opts.cellHTML = true; opts.cellStyles = true; opts.sheetStubs = true; opts.cellDates = true; wopts.cellStyles = true; wopts.bookVBA = true; } if(program.sparse) opts.dense = false; else opts.dense = true; if(program.codepage) opts.codepage = +program.codepage; if(program.dev) { opts.WTF = t...
random_line_split
bin_xlsx.ts
('-S, --formulae', 'emit list of values and formulae') .option('-j, --json', 'emit formatted JSON (all fields text)') .option('-J, --raw-js', 'emit raw JS object (raw numbers)') .option('-A, --arrays', 'emit rows as JS objects (raw numbers)') .option('-H, --html', 'emit HTML to <sheetname> or <file>.html') ...
dump_props
identifier_name
filters.py
-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This pr...
if (count % 20) == 0: output.append(['', '']) return ['%-50s %s' % (l[0], l[1]) for l in output] else: return ['<< Binary bytes: %d >>' % len(data)] else: return output.strip().splitlines() def now(self): return ts_to_iso(int(10*time.time())/10...
if '\r\n\r\n' in data: head, tail = data.split('\r\n\r\n', 1) output = self.format_data(head, level) output[-1] += '\\r\\n' output.append('\\r\\n') if tail: output.extend(self.format_data(tail, level)) return output else: output = data.encode('string_escape').replac...
identifier_body
filters.py
-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This pr...
if http_hdr.group(1).upper() in ('POST', 'PUT'): # FIXME: This is a bit ugly add_headers.append('Connection: close') clean_headers.append(r'(?mi)^(Connection|Keep-Alive):') info['rawheaders'] = True for hdr_re in clean_headers: data = re.sub(hdr_re, 'X-Old-\\1', data) retur...
add_headers.append('Host: %s' % info.get('rewritehost')) clean_headers.append(r'(?mi)^(Host:)')
conditional_block
filters.py
-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This pr...
(self, http_hdr, data, info): clean_headers = [ r'(?mi)^(X-(PageKite|Forwarded)-(For|Proto|Port):)' ] add_headers = [ 'X-Forwarded-For: %s' % info.get('remote_ip', 'unknown'), 'X-Forwarded-Proto: %s' % (info.get('using_tls') and 'https' or 'http'), 'X-PageKite-Port: %s' % info.get('p...
filter_header_data_in
identifier_name
filters.py
-2020, the Beanstalks Project ehf. and Bjarni Runar Einarsson This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This pr...
class TunnelFilter: """Base class for watchers/filters for data going in/out of Tunnels.""" FILTERS = ('connected', 'data_in', 'data_out') IDLE_TIMEOUT = 1800 def __init__(self, ui): self.sid = {} self.ui = ui def clean_idle_sids(self, now=None): now = now or time.time() for sid in list(si...
import pagekite.logging as logging from pagekite.compat import *
random_line_split
tp.py
ussian[:, 4] == sigma] label = 'Gaussian, $\sigma=%.2f$' % sigma style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--' plot(gaussian[:, 3], gaussian[:, column_y], style,label=label) legend(loc=2) for sigmaD in C.bilateral_sigmaDs: for sigmaR in C.bilateral_sigmaRs: ...
read_image
identifier_name
tp.py
otsu = results['otsu'] plot(otsu[:, 3], otsu[:, column_y],'-.', label='otsu') legend(loc=2) for sigma in C.gaussian_sigmas: otsu = results['otsu_gaussian'] otsu = otsu[otsu[:, 4] == sigma] label = 'Otsu with gaussian, $\sigma=%.2f$' % sigma style='o'+C.colors[C.gaussian_sigm...
os.makedirs(C.output_dir) #image sets synthetic_images=[('borders','png'), ('borders_contrast','png'), ('gradient1','png'),
random_line_split
tp.py
= otsu[otsu[:, 4] == sigma] label = 'Otsu with gaussian, $\sigma=%.2f$' % sigma style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--' plot(otsu[:, 3], otsu[:, column_y], style,label=label) legend(loc=1) for sigmaD in C.bilateral_sigmaDs: for sigmaR in C.bilateral_sigmaRs:...
set_printoptions(precision=4, linewidth=150, suppress=True) # print values with less precision params = {'legend.fontsize': 8, 'legend.linewidth': 1, 'legend.labelspacing':0.2, 'legend.loc':2} rcParams.update(params) # change global plotting parameters if not os.path.exists(C.o...
identifier_body
tp.py
algorithm parameters to generate result images default_noise_level = 1.5 default_noise_level_mri = 1.5 default_gaussian_sigma = 1 default_gaussian_sigma_noise = 1.5 default_bilateral_sigma = (1, 7) default_bilateral_sigma_noise = (1.5, 7) default_number_of_bins = 256 # generate the plot fo...
for sigmaD in C.bilateral_sigmaDs: for sigmaR in C.bilateral_sigmaRs: bilateral= results['bilateral'] bilateral = bilateral[bilateral[:, 4] == sigmaD] bilateral = bilateral[bilateral[:, 5] == sigmaR] label = 'Bilateral, $\sigma_d=%.2f$, $\sigma_r=%.2f$' % (s...
gaussian = results['gaussian'] gaussian = gaussian[gaussian[:, 4] == sigma] label = 'Gaussian, $\sigma=%.2f$' % sigma style='o'+C.colors[C.gaussian_sigmas.index(sigma)]+'--' plot(gaussian[:, 3], gaussian[:, column_y], style,label=label) legend(loc=2)
conditional_block
extract_images_to_s3.py
import os import posixpath import random import string import logging import tempfile import time from .extract_images import ExtractImages logger = logging.getLogger(__name__) class ExtractImagesToS3(ExtractImages): ''' This KnowledgePostProcessor subclass extracts images from posts to S3. It is desig...
# for example, to handle multi-factor authentication. cmd = "aws s3 cp '{0}' {1}".format(tmp_path, fname_s3) logger.info("Uploading images to S3: {cmd}".format(cmd=cmd)) retval = os.system(cmd) if retval != 0: raise Exception('Problem uploading...
# Copy image to accessible folder on S3 fname_s3 = posixpath.join(self.s3_image_root, repo_name, fname_img) # Note: The following command may need to be prefixed with a login agent;
random_line_split
extract_images_to_s3.py
import os import posixpath import random import string import logging import tempfile import time from .extract_images import ExtractImages logger = logging.getLogger(__name__) class ExtractImagesToS3(ExtractImages): ''' This KnowledgePostProcessor subclass extracts images from posts to S3. It is desig...
fname_s3 = posixpath.join(self.s3_image_root, repo_name, fname_img) # Note: The following command may need to be prefixed with a login agent; # for example, to handle multi-factor authentication. cmd = "aws s3 cp '{0}' {1}".format(tmp_path, fname_s3) logger.in...
if is_ref: _, tmp_path = tempfile.mkstemp() with open(tmp_path, 'wb') as f: f.write(kp._read_ref(img_path)) else: tmp_path = img_path try: # Get image type img_ext = posixpath.splitext(img_path)[1] # Make random fi...
identifier_body
extract_images_to_s3.py
import os import posixpath import random import string import logging import tempfile import time from .extract_images import ExtractImages logger = logging.getLogger(__name__) class ExtractImagesToS3(ExtractImages): ''' This KnowledgePostProcessor subclass extracts images from posts to S3. It is desig...
return False def cleanup(self, kp): if kp._has_ref('images'): kp._drop_ref('images')
return True
conditional_block
extract_images_to_s3.py
import os import posixpath import random import string import logging import tempfile import time from .extract_images import ExtractImages logger = logging.getLogger(__name__) class
(ExtractImages): ''' This KnowledgePostProcessor subclass extracts images from posts to S3. It is designed to be used upon addition to a knowledge repository, which can reduce the size of repositories. It replaces local images with remote urls based on `http_image_root`. `s3_image_root` should ...
ExtractImagesToS3
identifier_name
SHA224.py
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to e...
return clone def new(self, data=None): return SHA224Hash(data) def new(data=None): """Return a fresh instance of the hash object. :Parameters: data : byte string The very first chunk of the message to hash. It is equivalent to an early call to `SHA224Hash.update()`...
raise ValueError("Error %d while copying SHA224" % result)
conditional_block
SHA224.py
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to e...
(self, data=None): state = VoidPointer() result = _raw_sha224_lib.SHA224_init(state.address_of()) if result: raise ValueError("Error %d while instantiating SHA224" % result) self._state = SmartPointer(state.get(), ...
__init__
identifier_name
SHA224.py
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to e...
def hexdigest(self): """Return the **printable** digest of the message that has been hashed so far. This method does not change the state of the hash object. :Return: A string of 2* `digest_size` characters. It contains only hexadecimal ASCII digits. """ return ...
"""Return the **binary** (non-printable) digest of the message that has been hashed so far. This method does not change the state of the hash object. You can continue updating the object after calling this function. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII ...
identifier_body
SHA224.py
# -*- coding: utf-8 -*- # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to e...
>>> m.update(a+b) :Parameters: data : byte string The next chunk of the message being hashed. """ expect_byte_string(data) result = _raw_sha224_lib.SHA224_update(self._state.get(), data, ...
random_line_split
run.ts
import chai from 'chai'; import { unlink, writeFileSync } from 'fs'; import { sync } from 'mkdirp'; import Mocha, { Reporter, ReporterConstructor } from 'mocha'; import { tmpdir } from 'os'; import { join } from 'path'; import { TestResults } from './entities'; import { Insomnia, InsomniaOptions } from './insomnia'; i...
// Clean up temp files mocha.files.forEach(file => { unlink(file, err => { if (err) { console.log('Failed to clean up test file', file, err); } }); }); }); } catch (err) { reject(err); } }); /** * Copy test to tmp dir and return the file ...
{ console.log(`Test files: ${JSON.stringify(mocha.files)}.`); return; }
conditional_block
user.component.ts
import { Component, OnInit } from "@angular/core"; import { CommonComponent } from "./common.component"; import { UserService } from "../services/resource.service"; import { MessageService } from "../services/message"; import { FormControl, Validators, FormGroup, FormBuilder } from "@angular/forms"; import { User, Mess...
onEdit(row, col, obj){ super.onEdit(row, col, obj); this.admin = obj.admin? "true": "false"; this.currentUser = _.cloneDeep(obj); this.oldUser = _.cloneDeep(obj); } }
{ this.currentUser = _.cloneDeep(obj); }
identifier_body
user.component.ts
import { Component, OnInit } from "@angular/core"; import { CommonComponent } from "./common.component"; import { UserService } from "../services/resource.service"; import { MessageService } from "../services/message"; import { FormControl, Validators, FormGroup, FormBuilder } from "@angular/forms"; import { User, Mess...
(): void { super.ngOnInit(); this.getRecords(); } getRecords(){ var callback = (result: any[]) : void => { this.users = result; this.eleActive = []; this.eleHovered = []; for (var i = 0; i < this.users.length; i++){ this.users[i].last_login_at = com.formatTime(this.users...
ngOnInit
identifier_name
user.component.ts
import { Component, OnInit } from "@angular/core"; import { CommonComponent } from "./common.component"; import { UserService } from "../services/resource.service"; import { MessageService } from "../services/message"; import { FormControl, Validators, FormGroup, FormBuilder } from "@angular/forms"; import { User, Mess...
} super._editRecord(this.userService, this.currentUser.user_name, this.oldUser, this.currentUser, callback, true, param); } deleteRecord(){ var callback = (result: any) : void => { if(result == "ok") { this.getRecords(); } } super._deleteRecord(this.userService, this.curren...
{ for( var i = 0; i < this.users.length; i++){ if (this.users[i].user_name == this.oldUser.user_name) { // this.users[r + this.itemNumPerPage * (this.curentP -1)] = _.cloneDeep(this.currentUser); //if don't clone, when click add user, the record editted last time will be set as e...
conditional_block
user.component.ts
import { Component, OnInit } from "@angular/core"; import { CommonComponent } from "./common.component"; import { UserService } from "../services/resource.service"; import { MessageService } from "../services/message"; import { FormControl, Validators, FormGroup, FormBuilder } from "@angular/forms"; import { User, Mess...
getRecords(){ var callback = (result: any[]) : void => { this.users = result; this.eleActive = []; this.eleHovered = []; for (var i = 0; i < this.users.length; i++){ this.users[i].last_login_at = com.formatTime(this.users[i].last_login_at); this.users[i].created_at = com.fo...
}
random_line_split
sr_mulher.py
# !/usr/bin/env python3 # -*- encoding: utf-8 -*- """ ERP+ """ __author__ = 'CVtek dev' __credits__ = [] __version__ = "1.0" __maintainer__ = "CVTek dev" __status__ = "Development" __model_name__ = 'sr_mulher.SRMulher' import auth, base_models from orm import * from form import * class SRMulher(Model, View): def
(self, **kargs): Model.__init__(self, **kargs) self.__name__ = 'sr_mulher' self.__title__ ='Inscrição e Identificação da Mulher' self.__model_name__ = __model_name__ self.__list_edit_mode__ = 'edit' self.__get_options__ = ['nome'] # define tambem o campo a ser mostrado n...
__init__
identifier_name
sr_mulher.py
# !/usr/bin/env python3 # -*- encoding: utf-8 -*- """ ERP+ """ __author__ = 'CVtek dev' __credits__ = [] __version__ = "1.0" __maintainer__ = "CVTek dev" __status__ = "Development" __model_name__ = 'sr_mulher.SRMulher' import auth, base_models from orm import * from form import * class SRMulher(Model, View):
self.estado = combo_field(view_order = 9, name = 'Estado', size = 40, default = 'active', options = [('active','Activo'), ('canceled','Cancelado')], onlist = True)
def __init__(self, **kargs): Model.__init__(self, **kargs) self.__name__ = 'sr_mulher' self.__title__ ='Inscrição e Identificação da Mulher' self.__model_name__ = __model_name__ self.__list_edit_mode__ = 'edit' self.__get_options__ = ['nome'] # define tambem o campo a ser...
identifier_body