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 |
|---|---|---|---|---|
smtpmock.py | # -*- coding: utf-8 -*-
"""
2016-01-20 Cornelius Kölbel <cornelius@privacyidea.org>
Support STARTTLS mock
2015-01-30 Cornelius Kölbel <cornelius@privacyidea.org>
Change responses.py to be able to run with SMTP
Original responses.py is:
Copyright 2013 Dropbox, Inc.
Licensed under the Apache Lic... | self._patcher.stop()
self._patcher2.stop()
self._patcher3.stop()
self._patcher4.stop()
self._patcher5.stop()
self._patcher6.stop()
self._patcher7.stop()
self._patcher8.stop()
# expose default mock namespace
mock = _default_mock = SmtpMock()
__all__ = []
... | random_line_split | |
smtpmock.py | # -*- coding: utf-8 -*-
"""
2016-01-20 Cornelius Kölbel <cornelius@privacyidea.org>
Support STARTTLS mock
2015-01-30 Cornelius Kölbel <cornelius@privacyidea.org>
Change responses.py to be able to run with SMTP
Original responses.py is:
Copyright 2013 Dropbox, Inc.
Licensed under the Apache Lic... | MTP, server, *a, **kwargs):
return self._on_init(SMTP, server, *a, **kwargs)
self._patcher3 = mock.patch('smtplib.SMTP.__init__',
unbound_on_init)
self._patcher3.start()
def unbound_on_debuglevel(SMTP, level, *a, **kwargs):
return sel... | bound_on_init(S | identifier_name |
smtpmock.py | # -*- coding: utf-8 -*-
"""
2016-01-20 Cornelius Kölbel <cornelius@privacyidea.org>
Support STARTTLS mock
2015-01-30 Cornelius Kölbel <cornelius@privacyidea.org>
Change responses.py to be able to run with SMTP
Original responses.py is:
Copyright 2013 Dropbox, Inc.
Licensed under the Apache Lic... | # mangle request packet
self.timeout = kwargs.get("timeout", 10)
self.port = kwargs.get("port", 25)
self.esmtp_features = {}
return None
@staticmethod
def _on_debuglevel(SMTP_instance, level):
return None
@staticmethod
def _on_quit(SMTP_instance):
... | lf.smtp_ssl = True
| conditional_block |
smtpmock.py | # -*- coding: utf-8 -*-
"""
2016-01-20 Cornelius Kölbel <cornelius@privacyidea.org>
Support STARTTLS mock
2015-01-30 Cornelius Kölbel <cornelius@privacyidea.org>
Change responses.py to be able to run with SMTP
Original responses.py is:
Copyright 2013 Dropbox, Inc.
Licensed under the Apache Lic... | @staticmethod
def _on_debuglevel(SMTP_instance, level):
return None
@staticmethod
def _on_quit(SMTP_instance):
return None
def _on_starttls(self, SMTP_instance):
if self.exception:
raise SMTPException("MOCK TLS ERROR")
if not self.support_tls:
... | TP_instance = args[0]
host = args[1]
if isinstance(SMTP_instance, smtplib.SMTP_SSL):
# in case we need sth. to do with SMTL_SSL
self.smtp_ssl = True
# mangle request packet
self.timeout = kwargs.get("timeout", 10)
self.port = kwargs.get("port", 25)
... | identifier_body |
slider.ts | {
this._removeGlobalEventMouseUpListener();
}
this._tooltip.jigsawFloatCloseTrigger = 'mouseleave';
}
/**
* 父组件
* @private
*/
private _slider: JigsawSlider;
constructor(private _render: Renderer2, @Host() @Inject(forwardRef(() => JigsawSlider)) slider: any,
... | };
richMark.labelStyle = {
bottom: this._transformValueToPos(mark.value) + "%",
"margin-bottom": margi | conditional_block | |
slider.ts | Value(pos: { x: number, y: number }): number {
// 更新取得的滑动条尺寸.
this._slider._refresh();
const dimensions = this._slider._dimensions;
// bottom 在dom中的位置.
const offset = this._slider.vertical ? dimensions.bottom : dimensions.left;
const size = this._slider.vertical ? dimens... | 多触点
*
* @NoMarkForCheckRequired
*/
@Input()
public get value(): number | ArrayCollection<number> {
// 兼容返回单个值, 和多触点的数组;
if (this._$value.length == 1) {
return this._$value[0];
} else {
return this._$value;
}
}
public set value(value... | ider的当前值, 类型 number | ArrayCollection<number> 支持 | identifier_body |
slider.ts | () {
this._offset = this._slider._transformValueToPos(this.value);
this._setHandleStyle();
}
private _offset: number = 0;
/**
* @internal
*/
public _$handleStyle = {};
private _setHandleStyle() {
if (isNaN(this._offset)) {
return;
}
if... | _valueToPos | identifier_name | |
slider.ts | 中其他文本,造成鼠标放开后还可以拖拽的奇怪现象;
event.stopPropagation();
event.preventDefault();
const pos = {
x: event["clientX"],
y: event["clientY"]
};
let newValue = this._transformPosToValue(pos);
if (this.value === newValue) {
return;
}
... | // 设置标记. | random_line_split | |
flow.py | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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
#
# ... | def __len__(self):
"""Returns how many items are in this flow."""
def __str__(self):
lines = ["%s: %s" % (reflection.get_class_name(self), self.name)]
lines.append("%s" % (len(self)))
return "; ".join(lines)
@abc.abstractmethod
def add(self, *items):
"""Adds a g... | return self._name
@abc.abstractmethod | random_line_split |
flow.py | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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
#
# ... | (self):
"""Returns how many items are in this flow."""
def __str__(self):
lines = ["%s: %s" % (reflection.get_class_name(self), self.name)]
lines.append("%s" % (len(self)))
return "; ".join(lines)
@abc.abstractmethod
def add(self, *items):
"""Adds a given item/items... | __len__ | identifier_name |
flow.py | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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
#
# ... |
@abc.abstractproperty
def provides(self):
"""Browse argument names provided by the flow."""
| """Browse argument requirement names this flow requires to run.""" | identifier_body |
app.module.ts | import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { SwingModule } from 'angular2-swing';
import {Application} from './app.component';
import {NgModule, ErrorHandler} from '@angular/core';
import {Storage} from '@ionic/storage';
import {IonicApp, IonicModule,... | SwingModule,
IonicModule.forRoot(Application)
],
bootstrap: [IonicApp],
providers: [
{provide: ErrorHandler, useClass: IonicErrorHandler},
Storage,
...PROVIDERS
]
})
export class AppModule {} | random_line_split | |
app.module.ts | import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { SwingModule } from 'angular2-swing';
import {Application} from './app.component';
import {NgModule, ErrorHandler} from '@angular/core';
import {Storage} from '@ionic/storage';
import {IonicApp, IonicModule,... | {} | AppModule | identifier_name |
authorization_code.py | #! /usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
from .base import AuthenticationMixinBase
from . import GrantFailed
# We need to get urlencode from urllib.parse in Python 3, but fall back to
# urllib in Python 2
try:
from urllib.parse import urlencode
except ImportError:
from ... |
if state:
query['state'] = state
return url + urlencode(query)
def exchange_code(self, code, redirect):
"""Perform the exchange step for the code from the redirected user."""
code, headers, resp = self.call_grant(
'/oauth/access_token', {
"... | query['redirect_uri'] = redirect | conditional_block |
authorization_code.py | #! /usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
from .base import AuthenticationMixinBase
from . import GrantFailed
# We need to get urlencode from urllib.parse in Python 3, but fall back to
# urllib in Python 2
try:
from urllib.parse import urlencode
except ImportError:
from ... | (self, code, redirect):
"""Perform the exchange step for the code from the redirected user."""
code, headers, resp = self.call_grant(
'/oauth/access_token', {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect
... | exchange_code | identifier_name |
authorization_code.py | #! /usr/bin/env python | from __future__ import absolute_import
from .base import AuthenticationMixinBase
from . import GrantFailed
# We need to get urlencode from urllib.parse in Python 3, but fall back to
# urllib in Python 2
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
try:
basestri... | # encoding: utf-8
| random_line_split |
authorization_code.py | #! /usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
from .base import AuthenticationMixinBase
from . import GrantFailed
# We need to get urlencode from urllib.parse in Python 3, but fall back to
# urllib in Python 2
try:
from urllib.parse import urlencode
except ImportError:
from ... | if state:
query['state'] = state
return url + urlencode(query)
def exchange_code(self, code, redirect):
"""Perform the exchange step for the code from the redirected user."""
code, headers, resp = self.call_grant(
'/oauth/access_token', {
"gr... | """Implement helpers for the Authorization Code grant for OAuth2."""
def auth_url(self, scope, redirect, state):
"""Get the url to direct a user to authenticate."""
url = self.API_ROOT + "/oauth/authorize?"
query = {
"response_type": "code",
"client_id": self.app_in... | identifier_body |
client-policies.ts | /// <reference path="../apimanPlugin.ts"/>
/// <reference path="../rpc.ts"/>
module Apiman {
export var ClientPoliciesController = _module.controller("Apiman.ClientPoliciesController",
['$q', '$scope', '$location', 'PageLifecycle', 'ClientEntityLoader', 'OrgSvcs', 'Dialogs', '$routeParams', 'Configura... | }, reject);
})
});
PageLifecycle.loadPage('ClientPolicies', 'clientView', pageData, $scope, function() {
PageLifecycle.setPageTitle('client-policies', [ $scope.client.name ]);
});
}])
} | resolve(policies);
| random_line_split |
client-policies.ts | /// <reference path="../apimanPlugin.ts"/>
/// <reference path="../rpc.ts"/>
module Apiman {
export var ClientPoliciesController = _module.controller("Apiman.ClientPoliciesController",
['$q', '$scope', '$location', 'PageLifecycle', 'ClientEntityLoader', 'OrgSvcs', 'Dialogs', '$routeParams', 'Configura... |
});
};
$scope.removePolicy = function(policy) {
Dialogs.confirm('Confirm Remove Policy', 'Do you really want to remove this policy from the client app?', function() {
OrgSvcs.delete({ organizationId: params.org, entityType: 'clients', e... | {
$scope.policies.splice(index, 1);
} | conditional_block |
AttributesProcessor.ts | /*
* Copyright The OpenTelemetry Authors
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or... | }
}
/**
* {@link AttributesProcessor} that filters by allowed attribute names and drops any names that are not in the
* allow list.
*/
export class FilteringAttributesProcessor extends AttributesProcessor {
constructor(private _allowedAttributeNames: string[]) {
super();
}
process(incoming: Attributes,... | return incoming; | random_line_split |
AttributesProcessor.ts | /*
* Copyright The OpenTelemetry Authors
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or... |
}
export class NoopAttributesProcessor extends AttributesProcessor {
process(incoming: Attributes, _context?: Context) {
return incoming;
}
}
/**
* {@link AttributesProcessor} that filters by allowed attribute names and drops any names that are not in the
* allow list.
*/
export class FilteringAttributesP... | {
return NOOP;
} | identifier_body |
AttributesProcessor.ts | /*
* Copyright The OpenTelemetry Authors
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or... | (incoming: Attributes, _context?: Context) {
return incoming;
}
}
/**
* {@link AttributesProcessor} that filters by allowed attribute names and drops any names that are not in the
* allow list.
*/
export class FilteringAttributesProcessor extends AttributesProcessor {
constructor(private _allowedAttributeNa... | process | identifier_name |
theme.js | $(function () {
$(window).scroll(function() {
if ($(".navbar").offset().top>30) {
$(".navbar-fixed-top").addClass("sticky");
}
else { |
// Flex
if ($(".flexslider").length) {
$('.flexslider').flexslider();
}
servicesOptions.initialize();
staticHeader.initialize();
portfolioItem.initialize();
// segun esto corrige el pedo del dropdown en tablets and such
// hay que testearlo!
$('.dropdown-toggle').click(... | $(".navbar-fixed-top").removeClass("sticky");
}
}); | random_line_split |
theme.js | $(function () {
$(window).scroll(function() {
if ($(".navbar").offset().top>30) {
$(".navbar-fixed-top").addClass("sticky");
}
else |
});
// Flex
if ($(".flexslider").length) {
$('.flexslider').flexslider();
}
servicesOptions.initialize();
staticHeader.initialize();
portfolioItem.initialize();
// segun esto corrige el pedo del dropdown en tablets and such
// hay que testearlo!
$('.dropdown-toggle... | {
$(".navbar-fixed-top").removeClass("sticky");
} | conditional_block |
vscalefsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::VSCALEFSD, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM5)), operand3: Some(Direct(XMM2)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Zero), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98,... | vscalefsd_1 | identifier_name |
vscalefsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vscalefsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::VSCALEFSD, operand1: Some(Direct(XMM6)), operand2: Some(Dir... |
fn vscalefsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::VSCALEFSD, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: Some(Indirect(ECX, Some(OperandSize::Qword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K... | random_line_split | |
vscalefsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vscalefsd_1() |
fn vscalefsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::VSCALEFSD, operand1: Some(Direct(XMM1)), operand2: Some(Direct(XMM7)), operand3: Some(Indirect(ECX, Some(OperandSize::Qword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::... | {
run_test(&Instruction { mnemonic: Mnemonic::VSCALEFSD, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM5)), operand3: Some(Direct(XMM2)), operand4: None, lock: false, rounding_mode: Some(RoundingMode::Zero), merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 24... | identifier_body |
fetch.rs | use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct | {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Fetch dependencies of a package from the network.
Usage:
cargo fetch [options]
Options:
-h, --help Print this message
--manifest-path ... | Options | identifier_name |
fetch.rs | use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static str... | {
try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path));
try!(ops::fetch(&root, config).map_err(|e| {
CliError::from... | identifier_body | |
fetch.rs | use cargo::ops;
use cargo::util::{CliResult, CliError, Config};
use cargo::util::important_paths::find_root_manifest_for_cwd;
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_verbose: bool,
flag_quiet: bool,
flag_color: Option<String>,
}
pub const USAGE: &'static str... | available. The network is never touched after a `cargo fetch` unless
the lockfile changes.
If the lockfile is not available, then this is the equivalent of
`cargo generate-lockfile`. A lockfile is generated and dependencies are also
all updated.
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option... | --color WHEN Coloring: auto, always, never
If a lockfile is available, this command will ensure that all of the git
dependencies and/or registries dependencies are downloaded and locally | random_line_split |
Login.py | # !/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import base64
import re
import json
import hashlib
'''该登录程序是参考网上写的'''
cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.ins... | _ = urllib.quote(username)
username = base64.encodestring(username_)[:-1]
return username
def enableCookie():
cookiejar = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cookiejar)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(op... | username | identifier_name |
Login.py | # !/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import base64
import re
import json
import hashlib
'''该登录程序是参考网上写的'''
cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.ins... | wd ):
url = 'http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.18)'
#enableCookie()
try:
servertime, nonce = get_servertime()
except:
return
global postdata
postdata['servertime'] = servertime
postdata['nonce'] = nonce
postdata['su'] = get_user(username)
... | PCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cookiejar)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
def login( username, p | identifier_body |
Login.py | # !/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import urllib2
import cookielib
import base64
import re
import json
import hashlib
'''该登录程序是参考网上写的'''
cj = cookielib.LWPCookieJar()
cookie_support = urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.ins... | urllib2.urlopen(login_url)
print "Login success!"
return True
except:
print 'Login error!'
return False | login_url = p.search(text).group(1)
#print login_url | random_line_split |
mod.rs | #![stable(feature = "futures_api", since = "1.36.0")]
//! Asynchronous values.
use crate::{
ops::{Generator, GeneratorState},
pin::Pin,
ptr::NonNull,
task::{Context, Poll},
};
mod future;
mod into_future;
mod pending;
mod poll_fn;
mod ready;
#[stable(feature = "futures_api", since = "1.36.0")]
pub u... | <'a, 'b>(cx: ResumeTy) -> &'a mut Context<'b> {
// SAFETY: the caller must guarantee that `cx.0` is a valid pointer
// that fulfills all the requirements for a mutable reference.
unsafe { &mut *cx.0.as_ptr().cast() }
}
| get_context | identifier_name |
mod.rs | #![stable(feature = "futures_api", since = "1.36.0")]
//! Asynchronous values.
use crate::{
ops::{Generator, GeneratorState},
pin::Pin,
ptr::NonNull,
task::{Context, Poll},
};
mod future;
mod into_future;
mod pending;
mod poll_fn;
mod ready;
#[stable(feature = "futures_api", since = "1.36.0")]
pub u... | } | unsafe { &mut *cx.0.as_ptr().cast() } | random_line_split |
results.js | : 'render',
label : 'Start Render',
timing : true
}, {
key : 'SpeedIndex',
label : 'SpeedIndex'
}, {
key : 'domElements',
label : 'Number of DOM Elements'
}, {
key : 'docTime',
label : 'Document Complete',
timing : true
}, {
key : 'fullyLoaded',
la... | ( date, key, type ) {
var returnValue;
if ( key.key !== 'requests' ) {
returnValue = {
value : date.response.data.median[ type ] ?
date.response.data.median[ type ][ key.key ] :
0,
allowed : date.allowedUrl
};
} else {
r... | getNormalizedDate | identifier_name |
results.js | : 'render',
label : 'Start Render',
timing : true
}, {
key : 'SpeedIndex',
label : 'SpeedIndex'
}, {
key : 'domElements',
label : 'Number of DOM Elements'
}, {
key : 'docTime',
label : 'Document Complete',
timing : true
}, {
key : 'fullyLoaded',
la... | } );
items.each( renderGraph );
items.exit().remove()
}
function renderGraph( data ) {
var containerEl = this.querySelector( '.resultGraphs--item--container' );
var margin = { top : 25, right : 0, bottom : 30, left : 0 };
var width = containerEl.clientWidth - margin.left - margin.r... | {
var resultGraphs = d3.select( container );
var normalizedData = _getNormalizedData( data );
var items = resultGraphs.selectAll( '.resultGraphs--item' )
.data( normalizedData );
items.enter()
.append( 'li' )
.attr( 'class', 'resultGraphs--item' )
... | identifier_body |
results.js | : 'render',
label : 'Start Render',
timing : true
}, {
key : 'SpeedIndex',
label : 'SpeedIndex'
}, {
key : 'domElements',
label : 'Number of DOM Elements'
}, {
key : 'docTime',
label : 'Document Complete',
timing : true
}, {
key : 'fullyLoaded',
la... | listContainer.appendChild( detailBox );
detailBox.style.left = ( bBox.x + bBox.width / 2 - detailBox.getBoundingClientRect().width / 2 ) + 'px';
detailBox.style.top = ( bBox.y + bBox.height + detailBox.getBoundingClientRect().height ) + 'px';
}
function renderTable( container, data ) {
var table =... | random_line_split | |
results.js | allowed : date.allowedUrl
};
} else {
returnValue = {
value : date.response.data.median[ type ] ?
date.response.data.median[ type ][ key.key ][ 0 ] :
0,
allowed : date.allowedUrl
};
}
if ( key.timing ) {
returnVa... | {
var allVsNoneData = [ result.data[ 0 ], result.data[ 1 ] ];
renderTable( '#resultTable--allVsNone', allVsNoneData );
renderGraphs( '#resultGraphs--allVsNone', allVsNoneData );
var noneVsEachData = result.data.slice( 1 );
renderTable( '#resultTable--noneVsEach', no... | conditional_block | |
Module.ts | import * as AdhTopLevelStateModule from "../TopLevelState/Module";
import * as AdhTopLevelState from "../TopLevelState/TopLevelState";
import * as AdhEmbed from "./Embed";
export var moduleName = "adhEmbed";
export var register = (angular) => {
angular
.module(moduleName, [
"pascalprecht.tr... |
}])
.provider("adhEmbed", AdhEmbed.Provider)
.directive("href", ["adhConfig", "$location", "$rootScope", AdhEmbed.hrefDirective])
.filter("adhCanonicalUrl", ["adhConfig", AdhEmbed.canonicalUrl]);
};
| {
adhConfig.locale = params.locale;
} | conditional_block |
Module.ts | import * as AdhTopLevelStateModule from "../TopLevelState/Module";
import * as AdhTopLevelState from "../TopLevelState/TopLevelState"; |
export var moduleName = "adhEmbed";
export var register = (angular) => {
angular
.module(moduleName, [
"pascalprecht.translate",
AdhTopLevelStateModule.moduleName
])
.config(["adhTopLevelStateProvider", (adhTopLevelStateProvider : AdhTopLevelState.Provider) => {
... |
import * as AdhEmbed from "./Embed";
| random_line_split |
getobject.py | # Copyright (c) 2013-2016 Hewlett Packard Enterprise Development LP
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# thi... |
return {self.args['source']: {'md5': md5_digest.hexdigest(),
'sha1': sha_digest.hexdigest(),
'size': bytes_written}}
| self.log.error('rejecting download due to ETag MD5 mismatch '
'(expected: %s, actual: %s)',
etag, md5_digest.hexdigest())
raise RuntimeError('downloaded file appears to be corrupt '
'(expected MD5: {0}, actu... | conditional_block |
getobject.py | # Copyright (c) 2013-2016 Hewlett Packard Enterprise Development LP
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# thi... | (S3Request, FileTransferProgressBarMixin):
DESCRIPTION = 'Retrieve objects from the server'
ARGS = [Arg('source', metavar='BUCKET/KEY', route_to=None,
help='the object to download (required)'),
Arg('-o', dest='dest', metavar='PATH', route_to=None,
default='.', help=''... | GetObject | identifier_name |
getobject.py | # Copyright (c) 2013-2016 Hewlett Packard Enterprise Development LP
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# thi... | pbar.finish()
# Integrity checks
if content_length and bytes_written != int(content_length):
self.log.error('rejecting download due to Content-Length size '
'mismatch (expected: %i, actual: %i)',
content_length, bytes_written)
... | self.preprocess()
bytes_written = 0
md5_digest = hashlib.md5()
sha_digest = hashlib.sha1()
response = self.send()
content_length = response.headers.get('Content-Length')
if content_length:
pbar = self.get_progressbar(label=self.args['source'],
... | identifier_body |
getobject.py | # Copyright (c) 2013-2016 Hewlett Packard Enterprise Development LP
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# thi... | if content_length and bytes_written != int(content_length):
self.log.error('rejecting download due to Content-Length size '
'mismatch (expected: %i, actual: %i)',
content_length, bytes_written)
raise RuntimeError('downloaded file appe... | self.args['dest'].flush()
pbar.finish()
# Integrity checks | random_line_split |
nb_NO.js | module.exports = {
accepted: ':attribute må være akseptert.',
alpha: ':attribute feltet kan kun inneholde alfabetiske tegn.',
alpha_dash: ':attribute feltet kan kun inneholde alfanumeriske tegn, i tillegg til bindestreker og understreker.',
alpha_num: ':attribute feltet må være alfanumerisk.',
between: ':attr... | present: 'The :attribute field must be present (but can be empty).',
required: ':attribute feltet er påkrevd.',
required_if: ':attribute er påkrevd når :other er :value.',
same: ':attribute og :same må være like.',
size: {
numeric: ':attribute må ha størrelsen :size.',
string: ':attribute må ha :size ... | 'not_in': 'Den oppgitte verdien for :attribute er ugyldig.',
numeric: ':attribute må være et tall.', | random_line_split |
app.py | import os
import module
from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory
from werkzeug import secure_filename
from functools import wraps
app = Flask(__name__)
# Configure upload locations
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = se... | (f):
"""
Python function wrapper, used on functions that require being logged in to
view. Run before a function's body is run.
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if "authenticated" not in session or not session["authenticated"] or \
"username" not in sessi... | login_required | identifier_name |
app.py | import os
import module
from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory
from werkzeug import secure_filename
from functools import wraps
app = Flask(__name__)
# Configure upload locations
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = se... | @app.route("/upload", methods=["GET","POST"])
@app.route("/upload/", methods=["GET","POST"])
@login_required
def upload():
if request.method == "POST":
file = request.files["upload_bot"]
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.s... | @login_required
def download():
return render_template('download.html', USERNAME=session['username']) # For when the Jinja is configured
| random_line_split |
app.py | import os
import module
from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory
from werkzeug import secure_filename
from functools import wraps
app = Flask(__name__)
# Configure upload locations
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = se... |
return f(*args, **kwargs)
return decorated_function
def redirect_if_logged_in(f):
"""
Python function wrapper, used on functions to redirect to other pages if
the user is already logged in. Run before a function's body is run.
"""
@wraps(f)
def decorated_function(*args, **kwargs):
... | session.clear()
return redirect(url_for("login")) | conditional_block |
app.py | import os
import module
from flask import Flask, render_template, request, session, redirect, url_for, send_from_directory
from werkzeug import secure_filename
from functools import wraps
app = Flask(__name__)
# Configure upload locations
app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = se... |
@app.route("/register", methods=["POST"])
@app.route("/register/", methods=["POST"])
@redirect_if_logged_in
def register():
REQUIRED = ["username", "pass", "pass2"]
for form_elem in REQUIRED:
if form_elem not in request.form:
return redirect(url_for("home"))
if request.form["pass"] != ... | session.clear()
return redirect(url_for("login")) | identifier_body |
ActionsheetContent.tsx | import React, { memo, forwardRef } from 'react';
import { Modal } from '../../composites/Modal';
import type { IActionsheetContentProps } from './types';
import { usePropsResolution } from '../../../hooks';
import { Animated, PanResponder } from 'react-native';
import { ModalContext } from '../Modal/Context';
import Bo... |
},
})
).current;
return (
<>
{!hideDragIndicator ? (
<>
{/* To increase the draggable area */}
<Box py={5} {...panResponder.panHandlers} collapsable={false} />
</>
) : null}
<Modal.Content {...reso... | {
Animated.spring(pan, {
toValue: { x: 0, y: 0 },
overshootClamping: true,
useNativeDriver: true,
}).start();
} | conditional_block |
ActionsheetContent.tsx | import React, { memo, forwardRef } from 'react';
import { Modal } from '../../composites/Modal';
import type { IActionsheetContentProps } from './types';
import { usePropsResolution } from '../../../hooks';
import { Animated, PanResponder } from 'react-native';
import { ModalContext } from '../Modal/Context';
import Bo... | }
return (
<Animated.View
style={{
transform: [{ translateY: pan.y }],
width: '100%',
}}
onLayout={(event) => {
const { height } = event.nativeEvent.layout;
sheetHeight.current = height;
}}
pointerEvents="box-none"
>
<Content
child... | return null; | random_line_split |
google-map.ts | import { Component, OnInit, Input } from '@angular/core';
import { LoadingController, NavController } from 'ionic-angular';
import { Geolocation } from 'ionic-native';
import { Observable } from 'rxjs/Observable';
import { OriginLocationComponent } from '../origin-location/origin-location';
// import { AvailableProvide... |
centerLocation(location){
if (location){
this.map.panTo(location)
} else {
this.getLocation().subscribe(currentLocation => {
this.map.panTo(currentLocation)
})
}
}
}
| {
let mapOptions = {
center: location,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
}
let mapEl = document.getElementById('map');
let map = new google.maps.Map(mapEl, mapOptions);
return map;
} | identifier_body |
google-map.ts | import { Component, OnInit, Input } from '@angular/core';
import { LoadingController, NavController } from 'ionic-angular';
import { Geolocation } from 'ionic-native';
import { Observable } from 'rxjs/Observable';
import { OriginLocationComponent } from '../origin-location/origin-location';
// import { AvailableProvide... | } | random_line_split | |
google-map.ts | import { Component, OnInit, Input } from '@angular/core';
import { LoadingController, NavController } from 'ionic-angular';
import { Geolocation } from 'ionic-native';
import { Observable } from 'rxjs/Observable';
import { OriginLocationComponent } from '../origin-location/origin-location';
// import { AvailableProvide... | (){
this.map = this.createMap();
this.addMapEventListeners();
this.getLocation().subscribe(location => {
this.centerLocation(location)
})
}
addMapEventListeners(){
google.maps.event.addListener(this.map, 'dragstart', ()=>{
this.isMapIdle = false;
})
google.maps.event.addLi... | ngOnInit | identifier_name |
google-map.ts | import { Component, OnInit, Input } from '@angular/core';
import { LoadingController, NavController } from 'ionic-angular';
import { Geolocation } from 'ionic-native';
import { Observable } from 'rxjs/Observable';
import { OriginLocationComponent } from '../origin-location/origin-location';
// import { AvailableProvide... | else {
this.getLocation().subscribe(currentLocation => {
this.map.panTo(currentLocation)
})
}
}
}
| {
this.map.panTo(location)
} | conditional_block |
github.ts | var ref = new Firebase("https://ng2-projects.firebaseio.com");
const GIT_API = 'https://api.github.com/repos/angular/angular/';
const TRAVIS_API = 'https://api.travis-ci.org/repos/angular/angular/';
function gitToken() {
if (ref.getAuth()) {
return (<any>ref.getAuth()).github.accessToken
}
return null;
... |
switch (name) {
case 'priority':
case 'effort':
case 'comp':
case 'cla':
case 'pr_state':
case 'pr_action':
case 'cust':
case 'hotlist':
case 'issue_state':
case 'type':
(<any>issue)[name] = ((<any>issue)[name] ? (<any>issu... | {
name = 'issue_state';
} | conditional_block |
github.ts | var ref = new Firebase("https://ng2-projects.firebaseio.com");
const GIT_API = 'https://api.github.com/repos/angular/angular/';
const TRAVIS_API = 'https://api.travis-ci.org/repos/angular/angular/';
function gitToken() {
if (ref.getAuth()) {
return (<any>ref.getAuth()).github.accessToken
}
return null;
... |
var fetchPage = (page: number) => {
var http = new XMLHttpRequest();
var url = buildUrl('/repos/angular/angular/issues', {
per_page: 100,
page: page
});
urlGET(url, gitToken(), (status, data) => {
if(status == 200) {
var issues: Array<Issue> = data;
... | random_line_split | |
github.ts | var ref = new Firebase("https://ng2-projects.firebaseio.com");
const GIT_API = 'https://api.github.com/repos/angular/angular/';
const TRAVIS_API = 'https://api.travis-ci.org/repos/angular/angular/';
function gitToken() {
if (ref.getAuth()) {
return (<any>ref.getAuth()).github.accessToken
}
return null;
... | () {
for(var issueNo in this.previousIssues) {
if (!this.issues[issueNo]) {
this.onRemovedIssue(this.previousIssues[issueNo]);
}
}
for(var prNo in this.previousPrs) {
if (!this.prs[prNo]) {
this.onRemovedIssue(this.previousPrs[prNo]);
}
}
}
_parseLabels(issue... | _notifyRemoves | identifier_name |
cmac.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
... | if self._ctx is None:
raise AlreadyFinalized("Context was already finalized.")
if not isinstance(data, bytes):
raise TypeError("data must be bytes.")
self._ctx.update(data)
def finalize(self):
if self._ctx is None:
raise AlreadyFinalized("Context ... | def __init__(self, algorithm, backend, ctx=None):
if not isinstance(backend, CMACBackend):
raise UnsupportedAlgorithm(
"Backend object does not implement CMACBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
if not isinstance(algorithm, ciphers.Bloc... | identifier_body |
cmac.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
... |
ctx, self._ctx = self._ctx, None
ctx.verify(signature)
def copy(self):
if self._ctx is None:
raise AlreadyFinalized("Context was already finalized.")
return CMAC(
self._algorithm,
backend=self._backend,
ctx=self._ctx.copy()
)... | raise AlreadyFinalized("Context was already finalized.") | conditional_block |
cmac.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
... | (self):
if self._ctx is None:
raise AlreadyFinalized("Context was already finalized.")
digest = self._ctx.finalize()
self._ctx = None
return digest
def verify(self, signature):
if not isinstance(signature, bytes):
raise TypeError("signature must be by... | finalize | identifier_name |
cmac.py | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import (
... | if self._ctx is None:
raise AlreadyFinalized("Context was already finalized.")
digest = self._ctx.finalize()
self._ctx = None
return digest
def verify(self, signature):
if not isinstance(signature, bytes):
raise TypeError("signature must be bytes.")
... |
def finalize(self): | random_line_split |
group__eth__mac__interface__gr.js | checksum_offload_rx_tcp", "group__eth__mac__interface__gr.html#a730d6be6a7b868e0690d9548e77b7aae", null ],
[ "checksum_offload_rx_icmp", "group__eth__mac__interface__gr.html#a142179445bfdbaaaf0d451f277fb0e96", null ],
[ "checksum_offload_tx_ip4", "group__eth__mac__interface__gr.html#ac787d70407ce70e287249... | [ "ARM_ETH_MAC_Initialize", "group__eth__mac__interface__gr.html#gacf42d11b171cd032f0ec1de6db2b6832", null ],
[ "ARM_ETH_MAC_Uninitialize", "group__eth__mac__interface__gr.html#gacb2c2ae06f32328775bffbdeaaabfb5d", null ],
[ "ARM_ETH_MAC_PowerControl", "group__eth__mac__interface__gr.html#ga346fef040a0e9ba... | random_line_split | |
autotest.py | ("Log]")
util.pexpect_close(mavproxy)
util.pexpect_close(sil)
log.close()
print("Saved log for %s to %s" % (atype, logfile))
return True
def build_all():
'''run the build_all.sh script'''
print("Running build_all.sh")
if util.run_cmd(util.reltopdir('Tools/scripts/build_all.sh'), dir=ut... | self.date = time.asctime()
self.githash = util.run_cmd('git rev-parse HEAD', output=True, dir=util.reltopdir('.')).strip()
self.tests = []
self.files = []
self.images = [] | identifier_body | |
autotest.py | changes git branch, which can change the script while running
orig=util.reltopdir('Tools/scripts/build_binaries.sh')
copy=util.reltopdir('./build_binaries.sh')
shutil.copyfile(orig, copy)
shutil.copymode(orig, copy)
if util.run_cmd(copy, dir=util.reltopdir('.')) != 0:
print("Failed build_bi... | import glob
for f in glob.glob(util.reltopdir('../buildlogs/%s' % pattern)):
self.addfile(name, os.path.basename(f))
def addglobimage(self, name, pattern): | random_line_split | |
autotest.py | 'build.APMrover2',
'defaults.APMrover2',
'drive.APMrover2',
'logs.APMrover2',
'build2560.ArduCopter',
'build.ArduCopter',
'defaults.ArduCopter',
'fly.ArduCopter',
'logs.ArduCopter',
'convertgpx',
]
skipsteps = opts.skip.split(',')
# ensure we catch timeouts
signal.signal(sig... | if fnmatch.fnmatch(s.lower(), a.lower()):
matched.append(s) | conditional_block | |
autotest.py | if i == 0:
numlogs = 0
else:
numlogs = int(mavproxy.match.group(1))
for i in range(numlogs):
mavproxy.expect("Log (\d+)")
lognums.append(int(mavproxy.match.group(1)))
mavproxy.expect("Log]")
for i in range(numlogs):
print("Dumping log %u (i=%u)" % (lognums[i],... | (self, name | __init__ | identifier_name |
index.js | "use strict";
const helper = require("../../../helper.js");
const mw = helper.requireModule('./mw/cors/index');
const assert = require('assert');
describe("Unit test for: mw - cors", function () {
let req = {
"soajs": {
"registry": {
"serviceConfig": {
"cors... | }); | });
}); | random_line_split |
vs.py | # -*- coding: utf-8 -*-
"""
pygments.styles.vs
~~~~~~~~~~~~~~~~~~
Simple style with MS Visual Studio colors.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
""" | from pygments.token import Keyword, Name, Comment, String, Error, \
Operator, Generic
class VisualStudioStyle(Style):
background_color = "#ffffff"
default_style = ""
styles = {
Comment: "#008000",
Comment.Preproc: "#0000ff",
Keyword: ... |
from pygments.style import Style | random_line_split |
vs.py | # -*- coding: utf-8 -*-
"""
pygments.styles.vs
~~~~~~~~~~~~~~~~~~
Simple style with MS Visual Studio colors.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Co... | (Style):
background_color = "#ffffff"
default_style = ""
styles = {
Comment: "#008000",
Comment.Preproc: "#0000ff",
Keyword: "#0000ff",
Operator.Word: "#0000ff",
Keyword.Type: "#2b91af",
... | VisualStudioStyle | identifier_name |
vs.py | # -*- coding: utf-8 -*-
"""
pygments.styles.vs
~~~~~~~~~~~~~~~~~~
Simple style with MS Visual Studio colors.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Co... | background_color = "#ffffff"
default_style = ""
styles = {
Comment: "#008000",
Comment.Preproc: "#0000ff",
Keyword: "#0000ff",
Operator.Word: "#0000ff",
Keyword.Type: "#2b91af",
Name.Class: ... | identifier_body | |
wunderground.py | import urllib2, json, time, sys
from datetime import date, datetime
from dateutil.rrule import rrule, DAILY
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", dest="fahrenheit", action="store", default=False, type="string", help="Convert to FAHRENHEIT")
parser.add_option("-e", dest="end"... | print "Is your token correct?"
url.close()
sys.exit()
try:
for mean in parsed_json['history']['observations']:
if fahrenheit:
total += float(mean['tempi'])
else:
total += float(mean['tempm'])
count += 1
temp = (total / count)
print dt.strftime("%Y-%m-%d") + "," + str(temp)
exc... | print "Error reading URL " + wunderground_url | random_line_split |
wunderground.py | import urllib2, json, time, sys
from datetime import date, datetime
from dateutil.rrule import rrule, DAILY
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", dest="fahrenheit", action="store", default=False, type="string", help="Convert to FAHRENHEIT")
parser.add_option("-e", dest="end"... |
count += 1
temp = (total / count)
print dt.strftime("%Y-%m-%d") + "," + str(temp)
except:
print "Error retrieving temperature records for start date " + str(start) + " end date " + str(end)
url.close()
time.sleep(10)
| total += float(mean['tempm']) | conditional_block |
youtube.py | ector para Youtube
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re
import urllib
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import jsontools as json... |
signature = js_signature([sig])
url += "&signature=" + signature
url = url.replace(",", "%2C")
video_urls.append(["("+fmt_value[key]+") [youtube]", url])
except:
import traceback
logger.info(traceback.f... | urljs = scrapertools.find_single_match(youtube_page_data, '"assets":.*?"js":\s*"([^"]+)"')
urljs = urljs.replace("\\", "")
if urljs:
if not re.search(r'https?://', urljs):
urljs = urlparse.urljoin("https://www.yo... | conditional_block |
youtube.py | ector para Youtube
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re
import urllib
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import jsontools as json... | video_urls.reverse()
for video_url in video_urls:
logger.info(str(video_url))
return video_urls
def remove_additional_ending_delimiter(data):
pos = data.find("};")
if pos != -1:
data = data[:pos + 1]
return dat... |
video_id = scrapertools.find_single_match(page_url, 'v=([A-z0-9_-]{11})')
video_urls = extract_videos(video_id) | random_line_split |
youtube.py | ector para Youtube
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re
import urllib
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import jsontools as json... |
def remove_additional_ending_delimiter(data):
pos = data.find("};")
if pos != -1:
data = data[:pos + 1]
return data
def normalize_url(url):
if url[0:2] == "//": ... | logger.info("(page_url='%s')" % page_url)
if not page_url.startswith("http"):
page_url = "http://www.youtube.com/watch?v=%s" % page_url
logger.info(" page_url->'%s'" % page_url)
video_id = scrapertools.find_single_match(page_url, 'v=([A-z0-9_-]{11})')
video_urls = extract_videos(video_id)
... | identifier_body |
youtube.py | ector para Youtube
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import re
import urllib
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import jsontools as json... | (data):
pos = data.find("};")
if pos != -1:
data = data[:pos + 1]
return data
def normalize_url(url):
if url[0:2] == "//":
url = "h... | remove_additional_ending_delimiter | identifier_name |
mlp.py | import sys
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import f1_score,accuracy_score, recall_score, precision_score
import scipy
from random import shuffle
def | (filename):
f = open(filename)
x = []
y = []
for line in f:
v = line.rstrip('\n').split(',')
vf = [float(i) for i in v[:-1]]
x.append(vf)
y.append(float(v[-1]))
return x,y
def inductor(x,y):
clf = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(20, ... | load_dataset | identifier_name |
mlp.py | import sys
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import f1_score,accuracy_score, recall_score, precision_score
import scipy
from random import shuffle
def load_dataset(filename):
f = open(filename)
x = []
... |
print("predicting ...")
ypred = clf.predict(xtest)
print "(accuracy : %4.3f) "%(accuracy_score(ytest,ypred))
print "(f1 : %4.3f) "%(f1_score(ytest,ypred, average='weighted'))
print "(recall : %4.3f) "%(recall_score(ytest,ypred,average='weighted'))
print "(prec... | fname = sys.argv[1]
print("loading data ..")
x,y = load_dataset(fname)
x = np.array(x)
y = np.array(y)
n = len(x)
kf = StratifiedKFold(n_splits=3, shuffle=True)
for train_index, test_index in kf.split(x,y):
shuffle(train_index)
shuffle(test_index)
xtrain = x[train... | conditional_block |
mlp.py | import sys
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import f1_score,accuracy_score, recall_score, precision_score
import scipy
from random import shuffle
def load_dataset(filename):
f = open(filename)
x = []
... | kf = StratifiedKFold(n_splits=3, shuffle=True)
for train_index, test_index in kf.split(x,y):
shuffle(train_index)
shuffle(test_index)
xtrain = x[train_index]
ytrain = y[train_index]
xtest = x[test_index]
ytest = y[test_index]
print("training ...")
... | x,y = load_dataset(fname)
x = np.array(x)
y = np.array(y)
n = len(x) | random_line_split |
mlp.py | import sys
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import f1_score,accuracy_score, recall_score, precision_score
import scipy
from random import shuffle
def load_dataset(filename):
f = open(filename)
x = []
... |
if __name__ == '__main__':
fname = sys.argv[1]
print("loading data ..")
x,y = load_dataset(fname)
x = np.array(x)
y = np.array(y)
n = len(x)
kf = StratifiedKFold(n_splits=3, shuffle=True)
for train_index, test_index in kf.split(x,y):
shuffle(train_index)
shuffle(te... | clf = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(20, 8), max_iter=1000,random_state=1)
clf.fit(x,y)
return clf | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... |
default_app_config = 'geonode.people.PeopleAppConfig'
| super(PeopleAppConfig, self).ready() | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | (self):
super(PeopleAppConfig, self).ready()
default_app_config = 'geonode.people.PeopleAppConfig'
| ready | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | #
#########################################################################
from django.utils.translation import ugettext_noop as _
from geonode.notifications_helper import NotificationsAppConfigBase
class PeopleAppConfig(NotificationsAppConfigBase):
name = 'geonode.people'
NOTIFICATIONS = (("user_follow", _(... | random_line_split | |
mod.rs | /*
* 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 ... |
}
/// A wrapper around std::stringstream to build a diagnostic.
pub struct DiagnosticBuilder {
/// The level.
pub level: DiagnosticLevel,
/// The span of the diagnostic.
pub span: Span,
/// The in progress message.
pub message: String,
}
impl DiagnosticBuilder {
pub fn new(level: Diagno... | {
DiagnosticBuilder::new(DiagnosticLevel::Help, span)
} | identifier_body |
mod.rs | /*
* 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 ... | {
/// The level.
pub level: DiagnosticLevel,
/// The span of the diagnostic.
pub span: Span,
/// The in progress message.
pub message: String,
}
impl DiagnosticBuilder {
pub fn new(level: DiagnosticLevel, span: Span) -> DiagnosticBuilder {
DiagnosticBuilder {
level,
... | DiagnosticBuilder | identifier_name |
mod.rs | /*
* 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 ... | Warning = 30,
Note = 40,
Help = 50,
}
/// A compiler diagnostic.
#[repr(C)]
#[derive(Object, Debug)]
#[ref_name = "Diagnostic"]
#[type_key = "Diagnostic"]
pub struct DiagnosticNode {
pub base: Object,
/// The level.
pub level: DiagnosticLevel,
/// The span at which to report an error.
p... | pub enum DiagnosticLevel {
Bug = 10,
Error = 20, | random_line_split |
Constants.ts | export const enum CardType {
FaceUp,
FaceDown,
Hand
};
export const enum CardState {
Default,
Playable,
Invalid
};
export const SUIT: any = {
SPADE: 0,
DIAMOND: 1,
CLOVER: 2,
HEART: 3
};
export const FACE: any = {
JACK: 11,
QUEEN: 12,
KING: 13,
ACE: 14
};
expo... | },
HOVER: {
COLOR: 'rgb(0,200,0)'
},
SELECTED: {
COLOR: 'rgb(139,0,0)'
}
};
export const DECK: any = {
MAX_RENDER: 3,
X: -90,
Y: -35
};
export const PILE: any = {
MAX_RENDER: 3,
X: 10,
Y: -35
};
export const PLAYER: any = {
X: -80,
Y: 300,
FACEU... | WIDTH: 80,
BORDER_COLOR: 'black',
INVISIBLE: {
COLOR: 'red',
OPACITY: 0.3 | random_line_split |
ete_extract.py | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the... | print(e.in_seqs, e.out_seqs) | conditional_block | |
ete_extract.py | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the... | (extract_args_p):
extract_args = extract_args_p.add_argument_group('TREE EDIT OPTIONS')
extract_args.add_argument("--orthologs", dest="orthologs",
nargs="*",
help="")
extract_args.add_argument("--duplications", dest="duplications",
... | populate_args | identifier_name |
ete_extract.py | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the... | from .. import Tree, PhyloTree
for nw in src_tree_iterator(args):
if args.orthologs is not None:
t = PhyloTree(nw)
for e in t.get_descendant_evol_events():
print(e.in_seqs, e.out_seqs) | identifier_body | |
ete_extract.py | # #START_LICENSE###########################################################
#
#
# This file is part of the Environment for Tree Exploration program
# (ETE). http://etetoolkit.org
#
# ETE is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the... |
from .common import src_tree_iterator
DESC = ""
def populate_args(extract_args_p):
extract_args = extract_args_p.add_argument_group('TREE EDIT OPTIONS')
extract_args.add_argument("--orthologs", dest="orthologs",
nargs="*",
help="")
extract_a... | from __future__ import print_function | random_line_split |
index.ts | // Copyright 2018, Google, LLC.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wr... | export function ml(options: ml_v1.Options): ml_v1.Ml;
export function ml<T = ml_v1.Ml>(
this: GoogleConfigurable, versionOrOptions: 'v1'|ml_v1.Options) {
return getAPI<T>('ml', versionOrOptions, VERSIONS, this);
} | };
export function ml(version: 'v1'): ml_v1.Ml; | random_line_split |
index.ts | // Copyright 2018, Google, LLC.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wr... | {
return getAPI<T>('ml', versionOrOptions, VERSIONS, this);
} | identifier_body | |
index.ts | // Copyright 2018, Google, LLC.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wr... | <T = ml_v1.Ml>(
this: GoogleConfigurable, versionOrOptions: 'v1'|ml_v1.Options) {
return getAPI<T>('ml', versionOrOptions, VERSIONS, this);
}
| ml | identifier_name |
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'underscore';
import babel from 'babel-core/browser';
import esprima from 'esprima';
import escodegen from 'escodegen';
import estraverse from 'estraverse';
import Codemirror from 'react-codemirror';
import classNames from 'classnames';
import ... | () {
this._renderPreview();
},
render() {
const {
sourceCode,
transCode,
tab,
transError
} = this.state;
const showSource = (tab === TAB_SOURCE);
const cmOptions = {
lineNumbers: true,
readOnly: !showSource,
mode: 'jsx',
theme: 'material',
t... | componentDidUpdate | identifier_name |
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'underscore';
import babel from 'babel-core/browser';
import esprima from 'esprima';
import escodegen from 'escodegen';
import estraverse from 'estraverse';
import Codemirror from 'react-codemirror';
import classNames from 'classnames';
import ... | ,
_onTransClick() {
this.setState({
tab: TAB_TRANSCODE
});
},
_setSource(sourceCode) {
localStorage.setItem('sourceCode', sourceCode);
const dependencies = [];
let transCode;
let transError;
try {
const es5trans = babel.transform(sourceCode);
let uniqueId = 0;
... | {
this.setState({
tab: TAB_SOURCE
});
} | identifier_body |
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'underscore';
import babel from 'babel-core/browser';
import esprima from 'esprima';
import escodegen from 'escodegen';
import estraverse from 'estraverse';
import Codemirror from 'react-codemirror';
import classNames from 'classnames';
import ... |
}
catch (e) {
globalUtils.error('Fatal error rendering preview: ', e);
}
}
});
ReactDOM.render(<LiveDemoApp />, document.getElementById('editor'));
// const newProgram = {
// type: 'Program',
// body: [
// {
// type: 'CallExpression',
// callee: {
// type: 'FunctionEx... | {
ReactDOM.render(<div className='otsLiveDemoApp-error'>{error.toString()}</div>, document.getElementById('preview'));
} | conditional_block |
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'underscore';
import babel from 'babel-core/browser';
import esprima from 'esprima';
import escodegen from 'escodegen';
import estraverse from 'estraverse';
import Codemirror from 'react-codemirror';
import classNames from 'classnames';
import ... | return {
sourceCode: '',
transCode: '',
transError: '',
tab: TAB_SOURCE,
func: function() { }
};
},
componentWillMount() {
this._setSource(localStorage.getItem('sourceCode') || '');
},
componentDidMount() {
this._renderPreview();
},
componentDidUpdate() {
th... |
const LiveDemoApp = React.createClass({
getInitialState() { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.