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 |
|---|---|---|---|---|
core.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | {}
/// Extern functions operating on Flow.
extern {
pub fn FlowGetLastTimeAsParts(flow: &Flow, secs: *mut u64, usecs: *mut u64);
}
/// Rust implementation of Flow.
impl Flow {
/// Return the time of the last flow update as a `Duration`
/// since the epoch.
pub fn get_last_time(&mut self) -> std::tim... | Flow | identifier_name |
core.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
}
}
/// AppLayerDecoderEventsSetEventRaw wrapper.
pub fn sc_app_layer_decoder_events_set_event_raw(
events: *mut *mut AppLayerDecoderEvents, event: u8)
{
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsSetEventRaw)(events, event);
}
}
}
/// AppLayerDecoderEventsFree... | {
(c.DetectEngineStateFree)(state);
} | conditional_block |
core.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
/// Opaque flow type (defined in C)
pub enum Flow {}
/// Extern functions operating on Flow.
extern {
pub fn FlowGetLastTimeAsParts(flow: &Flow, secs: *mut u64, usecs: *mut u64);
}
/// Rust implementation of Flow.
impl Flow {
/// Return the time of the last flow update as a `Duration`
/// since the epo... | {
unsafe {
if let Some(c) = SC {
(c.AppLayerDecoderEventsFreeEvents)(events);
}
}
} | identifier_body |
core.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
//
// Function types for calls into C.
//
#[allow(non_snake_case)]
pub type SCLogMessageFunc =
extern "C" fn(level: std::os::raw::c_int,
filename: *const std::os::raw::c_char,
line: std::os::raw::c_uint,
function: *const std::os::raw::c_char,
... | } | random_line_split |
test_number_to_bytes.py | import unittest
from katas.beta.number_to_bytes import to_bytes
class NumberToBytesTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(to_bytes(0), ['00000000'])
def test_equals_2(self):
self.assertEqual(to_bytes(1), ['00000001'])
def test_equals_3(self):
self.a... |
def test_equals_7(self):
self.assertEqual(to_bytes(0x1020304),
['00000001', '00000010', '00000011', '00000100']) | random_line_split | |
test_number_to_bytes.py | import unittest
from katas.beta.number_to_bytes import to_bytes
class NumberToBytesTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(to_bytes(0), ['00000000'])
def test_equals_2(self):
self.assertEqual(to_bytes(1), ['00000001'])
def test_equals_3(self):
self.a... | self.assertEqual(to_bytes(0x1020304),
['00000001', '00000010', '00000011', '00000100']) | identifier_body | |
test_number_to_bytes.py | import unittest
from katas.beta.number_to_bytes import to_bytes
class | (unittest.TestCase):
def test_equals(self):
self.assertEqual(to_bytes(0), ['00000000'])
def test_equals_2(self):
self.assertEqual(to_bytes(1), ['00000001'])
def test_equals_3(self):
self.assertEqual(to_bytes(257), ['00000001', '00000001'])
def test_equals_4(self):
self... | NumberToBytesTestCase | identifier_name |
tokenizer.ts | the id of the first opening bracket that is closed by this bracket.
* Otherwise, it is -1.
*/
readonly bracketId: OpeningBracketId,
/**
* If this token is an opening bracket, this just contains `bracketId`.
* If this token is a closing bracket, this lists all opening bracket ids, that it closes.
* O... |
private lineIdx = 0;
private line: string | null = null;
private lineCharOffset = 0;
private lineTokens: LineTokens | null = null;
private lineTokenOffset = 0;
public setPosition(lineIdx: number, column: number): void {
// We must not jump into a token!
if (lineIdx === this.lineIdx) {
this.lineCharOffse... | {
this.textBufferLineCount = textModel.getLineCount();
this.textBufferLastLineLength = textModel.getLineLength(this.textBufferLineCount);
} | identifier_body |
tokenizer.ts | Text = 0,
OpeningBracket = 1,
ClosingBracket = 2,
}
export type OpeningBracketId = number;
export class Token {
constructor(
readonly length: Length,
readonly kind: TokenKind,
/**
* If this token is an opening bracket, this is the id of the opening bracket.
* If this token is a closing bracket, this i... |
getText(): string;
}
export const enum TokenKind { | random_line_split | |
tokenizer.ts | is the id of the first opening bracket that is closed by this bracket.
* Otherwise, it is -1.
*/
readonly bracketId: OpeningBracketId,
/**
* If this token is an opening bracket, this just contains `bracketId`.
* If this token is a closing bracket, this lists all opening bracket ids, that it closes.
... | (lineIdx: number, column: number): void {
// We must not jump into a token!
if (lineIdx === this.lineIdx) {
this.lineCharOffset = column;
this.lineTokenOffset = this.lineCharOffset === 0 ? 0 : this.lineTokens!.findTokenIndexAtOffset(this.lineCharOffset);
} else {
this.lineIdx = lineIdx;
this.lineCharO... | setPosition | identifier_name |
tokenizer.ts | the id of the first opening bracket that is closed by this bracket.
* Otherwise, it is -1.
*/
readonly bracketId: OpeningBracketId,
/**
* If this token is an opening bracket, this just contains `bracketId`.
* If this token is a closing bracket, this lists all opening bracket ids, that it closes.
* O... |
lengthHeuristic += endOffset - this.lineCharOffset;
if (peekedBracketToken) {
// Don't skip the entire token, as a single token could contain multiple brackets.
if (startLineIdx !== this.lineIdx || startLineCharOffset !== this.lineCharOffset) {
// There is text before the bracket
this.... | {
const languageId = lineTokens.getLanguageId(this.lineTokenOffset);
const text = this.line.substring(this.lineCharOffset, endOffset);
const brackets = this.bracketTokens.getSingleLanguageBracketTokens(languageId);
const regexp = brackets.regExpGlobal;
if (regexp) {
regexp.lastIndex = 0;... | conditional_block |
cargo_doc.rs | use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;
use core::PackageIdSpec;
use core::source::Source;
use ops;
use sources::PathSource;
use util::{CargoResult, human};
pub struct DocOptions<'a, 'b: 'a> {
pub open_result: bool,
pub compile_opts: ops::CompileOptions<'a, ... | let package = try!(source.root_package());
let mut lib_names = HashSet::new();
let mut bin_names = HashSet::new();
if options.compile_opts.spec.is_none() {
for target in package.targets().iter().filter(|t| t.documented()) {
if target.is_lib() {
assert!(lib_names.inse... | try!(source.update()); | random_line_split |
cargo_doc.rs | use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;
use core::PackageIdSpec;
use core::source::Source;
use ops;
use sources::PathSource;
use util::{CargoResult, human};
pub struct DocOptions<'a, 'b: 'a> {
pub open_result: bool,
pub compile_opts: ops::CompileOptions<'a, ... |
#[cfg(target_os = "macos")]
fn open_docs(path: &Path) {
match Command::new("open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
| {
match Command::new("start").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
} | identifier_body |
cargo_doc.rs | use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;
use core::PackageIdSpec;
use core::source::Source;
use ops;
use sources::PathSource;
use util::{CargoResult, human};
pub struct DocOptions<'a, 'b: 'a> {
pub open_result: bool,
pub compile_opts: ops::CompileOptions<'a, ... | (path: &Path) {
match Command::new("start").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
#[cfg(target_os = "macos")]
fn open_docs(path: &Path) {
match Command::new("open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
}
| open_docs | identifier_name |
cargo_doc.rs | use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;
use core::PackageIdSpec;
use core::source::Source;
use ops;
use sources::PathSource;
use util::{CargoResult, human};
pub struct DocOptions<'a, 'b: 'a> {
pub open_result: bool,
pub compile_opts: ops::CompileOptions<'a, ... |
}
Ok(())
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
fn open_docs(path: &Path) {
// trying xdg-open
match Command::new("xdg-open").arg(path).status() {
Ok(_) => return,
Err(_) => ()
};
// trying gnome-open
match Command::new("gnome-open").arg(path).stat... | {
open_docs(&path);
} | conditional_block |
index.js | 'use strict';
var fs = require('fs'),
path = require('path');
// path.basename('/foo/bar/baz/asdf/quux.html', '.html') = quux
// path.dirname('/foo/bar/baz/asdf/quux.html') = /foo/bar/baz/asdf/
// path.parse('/home/user/dir/file.txt')
// returns
// {
// root : "/",
// dir : "/ho... |
});
});
if (pending === 1) {
done(null, results);
} else {
--pending;
}
});
};
var layers = function(dir){
var results = walk(dir, function(err, results){
if (err) {
throw err;
}
results = JSON.stringify(re... | {
if (file[0] !== '_') {
results[layer].push(file);
} else {
results[layer].push(file.slice(1, -5));
}
} | conditional_block |
index.js | 'use strict';
var fs = require('fs'),
path = require('path');
// path.basename('/foo/bar/baz/asdf/quux.html', '.html') = quux
// path.dirname('/foo/bar/baz/asdf/quux.html') = /foo/bar/baz/asdf/
// path.parse('/home/user/dir/file.txt')
// returns
// {
// root : "/",
// dir : "/ho... | });
}
module.exports = layers; | return results; | random_line_split |
kinvey.config.ts | import { Crypto } from './../utils/crypto';
export class KinveyConfig {
private _APP_ID = 'kid_HkVC5wlSe';
private _APP_SECRET = '52680624648749d087ebe3ef84bd8542';
private _APP_MASTER = 'd580dbb3e2df4867b3423c293a1edc94';
private _AUTHORIZATION_STRING = `${this._APP_ID}:${this._APP_SECRET}`;
priva... |
private loadBase64AuthKeys(): void {
this._AUTH_STRING_COMMON = Crypto.encryptToBase64(this._AUTHORIZATION_STRING_MASTER);
this._AUTH_STRING_USERS = Crypto.encryptToBase64(this._AUTHORIZATION_STRING);
}
}
| {
return `${this._COLLECTIONS_URL}${collectionName}/${filter ? '?query=' + filter : ''}`;
} | identifier_body |
kinvey.config.ts | import { Crypto } from './../utils/crypto';
export class KinveyConfig {
private _APP_ID = 'kid_HkVC5wlSe';
private _APP_SECRET = '52680624648749d087ebe3ef84bd8542';
private _APP_MASTER = 'd580dbb3e2df4867b3423c293a1edc94';
private _AUTHORIZATION_STRING = `${this._APP_ID}:${this._APP_SECRET}`;
priva... | public getCollectionUrl(collectionName: string, filter?: string) {
return `${this._COLLECTIONS_URL}${collectionName}/${filter ? '?query=' + filter : ''}`;
}
private loadBase64AuthKeys(): void {
this._AUTH_STRING_COMMON = Crypto.encryptToBase64(this._AUTHORIZATION_STRING_MASTER);
thi... | return `${this._USERS_URL}${filter ? '?query=' + filter : ''}`;
}
| random_line_split |
kinvey.config.ts | import { Crypto } from './../utils/crypto';
export class KinveyConfig {
private _APP_ID = 'kid_HkVC5wlSe';
private _APP_SECRET = '52680624648749d087ebe3ef84bd8542';
private _APP_MASTER = 'd580dbb3e2df4867b3423c293a1edc94';
private _AUTHORIZATION_STRING = `${this._APP_ID}:${this._APP_SECRET}`;
priva... | (filter?: string) {
return `${this._USERS_URL}${filter ? '?query=' + filter : ''}`;
}
public getCollectionUrl(collectionName: string, filter?: string) {
return `${this._COLLECTIONS_URL}${collectionName}/${filter ? '?query=' + filter : ''}`;
}
private loadBase64AuthKeys(): void {
... | getUsersUrl | identifier_name |
descriptor_props.py | False)
self.deferred = kwargs.get("deferred", False)
self.group = kwargs.get("group", None)
self.comparator_factory = kwargs.pop(
"comparator_factory", self.__class__.Comparator
)
self._generated_composite_accessor = None
if "info" in kwargs:
self... | (self):
"""Initialization which occurs after the :class:`.Composite`
has been associated with its parent mapper.
"""
self._setup_arguments_on_columns()
_COMPOSITE_FGET = object()
def _create_descriptor(self):
"""Create the Python descriptor that will serve as
t... | do_init | identifier_name |
descriptor_props.py | ", False)
self.deferred = kwargs.get("deferred", False)
self.group = kwargs.get("group", None)
self.comparator_factory = kwargs.pop(
"comparator_factory", self.__class__.Comparator
)
self._generated_composite_accessor = None
if "info" in kwargs:
se... | return [
a.column if isinstance(a, MappedColumn) else a
for a in self.attrs
if isinstance(a, (schema.Column, MappedColumn))
]
@property
def mapper_property_to_assign(self) -> Optional["MapperProperty[_T]"]:
return self
@property
def columns_t... | @property
@util.preload_module("orm.properties")
def columns(self):
MappedColumn = util.preloaded.orm_properties.MappedColumn | random_line_split |
descriptor_props.py | False)
self.deferred = kwargs.get("deferred", False)
self.group = kwargs.get("group", None)
self.comparator_factory = kwargs.pop(
"comparator_factory", self.__class__.Comparator
)
self._generated_composite_accessor = None
if "info" in kwargs:
|
util.set_creation_order(self)
self._create_descriptor()
def instrument_class(self, mapper):
super().instrument_class(mapper)
self._setup_event_handlers()
def _composite_values_from_instance(self, value):
if self._generated_composite_accessor:
return self._... | self.info = kwargs.pop("info") | conditional_block |
descriptor_props.py |
def fget(obj):
return getattr(obj, self.name)
self.descriptor = property(fget=fget, fset=fset, fdel=fdel)
proxy_attr = attributes.create_proxied_attribute(self.descriptor)(
self.parent.class_,
self.key,
self.descriptor,
... | delattr(obj, self.name) | identifier_body | |
react.d.ts | // react.d.ts
// function createRef<T>(): RefObject<T>
// export const fail = <T>(message: string): T => {
// throw message;
// }
// let fromStage: Stage = stages
// .filter(s => s.id === stageRelation.fromId)
// .shift() || fail<Stage>('Should have found at least one stage.');
// interface F<P> ... | rest?: any;
}
declare interface NodeModule {
hot: {
accept(dependencies: string[], callback: (updatedDependencies: string[]) => void): void;
accept(dependency: string, callback: () => void): void;
accept(errHandler?: (err: any) => void): void;
decline(dependencies?: string[]): void;
/... | description?: string;
statusCode?: number; | random_line_split |
react.d.ts | // react.d.ts
// function createRef<T>(): RefObject<T>
// export const fail = <T>(message: string): T => {
// throw message;
// }
// let fromStage: Stage = stages
// .filter(s => s.id === stageRelation.fromId)
// .shift() || fail<Stage>('Should have found at least one stage.');
// interface F<P> ... | <P, S> {
setState<K extends keyof S>(f: (prevState: S, props: P) => Pick<S, K>, callback?: () => any): void;
}
// function setState<T, K extends keyof T>(obj: T, state: Pick<T, K>) {
// for (let k in state) {
// obj[k] = state[k];
// }
// }
// setState<K extends keyof S>(f: (prevState: S, props: P) ... | Component | identifier_name |
q_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
utils::argmax_first,
traces,
Differentiable,
Enumerable,
Function,
Handler,
Parameterised,
};
use std::ops::Index;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(cra... | {
td_error: f64,
}
/// Watkins' Q-learning with eligibility traces.
///
/// # References
/// - Watkins, C. J. C. H. (1989). Learning from Delayed Rewards. Ph.D. thesis,
/// Cambridge University.
/// - Watkins, C. J. C. H., Dayan, P. (1992). Q-learning. Machine Learning,
/// 8:279–292.
#[derive(Clone, Debug, Param... | Response | identifier_name |
q_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
utils::argmax_first,
traces,
Differentiable,
Enumerable,
Function,
Handler,
Parameterised,
};
use std::ops::Index;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(cra... |
residual
} else {
let ns = t.to.state();
let (_, nqs_max) = self.fa_theta.find_max((ns,));
let residual = t.reward + self.gamma * nqs_max - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
... | let s = t.from.state();
let qs = self.fa_theta.evaluate((s,));
let qsa = qs[t.action];
let grad_s = self.fa_theta.grad((s, t.action));
// Update trace:
if t.action != argmax_first(qs).0 { self.trace.reset(); }
self.trace.update(&grad_s);
let td_error =... | identifier_body |
q_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
utils::argmax_first,
traces,
Differentiable,
Enumerable,
Function,
Handler,
Parameterised,
};
use std::ops::Index;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(cra... |
Ok(Response { td_error, })
}
}
| let ns = t.to.state();
let (_, nqs_max) = self.fa_theta.find_max((ns,));
let residual = t.reward + self.gamma * nqs_max - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.alpha * residual,
jacobian: &self.trace,
})... | conditional_block |
q_lambda.rs | use crate::{
domains::Transition,
fa::ScaledGradientUpdate,
utils::argmax_first,
traces,
Differentiable,
Enumerable,
Function,
Handler,
Parameterised,
};
use std::ops::Index;
#[derive(Clone, Debug)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(cra... | self.trace.reset();
residual
} else {
let ns = t.to.state();
let (_, nqs_max) = self.fa_theta.find_max((ns,));
let residual = t.reward + self.gamma * nqs_max - qsa;
self.fa_theta.handle(ScaledGradientUpdate {
alpha: self.... | jacobian: &self.trace,
}).map_err(|_| ())?;
| random_line_split |
baseinputnumber.js | function baseinputnumber(widget_id, url, skin, parameters)
{
// Will be using "self" throughout for the various flavors of "this"
// so for consistency ...
self = this
// Initialization
self.widget_id = widget_id
// Store on brightness or fallback to a default
// Parameters may come in ... | (self, minvalue, maxvalue, stepvalue, state)
{
//alert(self.maxvalue)
self.set_field(self, "MinValue", minvalue)
self.set_field(self, "MaxValue", maxvalue)
self.set_field(self, "minValue", self.format_number(self,minvalue))
self.set_field(self, "maxValue", self.format_number(... | set_options | identifier_name |
baseinputnumber.js | function baseinputnumber(widget_id, url, skin, parameters)
| ]
// Define callbacks for entities - this model allows a widget to monitor multiple entities if needed
// Initial will be called when the dashboard loads and state has been gathered for the entity
// Update will be called every time an update occurs for that entity
self.On... | {
// Will be using "self" throughout for the various flavors of "this"
// so for consistency ...
self = this
// Initialization
self.widget_id = widget_id
// Store on brightness or fallback to a default
// Parameters may come in useful later on
self.parameters = parameters
self... | identifier_body |
baseinputnumber.js | function baseinputnumber(widget_id, url, skin, parameters)
{
// Will be using "self" throughout for the various flavors of "this"
// so for consistency ...
self = this
// Initialization
self.widget_id = widget_id
// Store on brightness or fallback to a default
// Parameters may come in ... |
function OnStateAvailable(self, state)
{
self.state = state.state
self.minvalue = state.attributes.min
self.maxvalue = state.attributes.max
self.stepvalue = state.attributes.step
set_options(self, self.minvalue, self.maxvalue, self.stepvalue, state)
set_value(sel... | // state is the initial state
// Methods | random_line_split |
baseinputnumber.js | function baseinputnumber(widget_id, url, skin, parameters)
{
// Will be using "self" throughout for the various flavors of "this"
// so for consistency ...
self = this
// Initialization
self.widget_id = widget_id
// Store on brightness or fallback to a default
// Parameters may come in ... |
// Finally, call the parent constructor to get things moving
WidgetBase.call(self, widget_id, url, skin, parameters, monitored_entities, callbacks)
// Function Definitions
// The StateAvailable function will be called when
// self.state[<entity>] has valid information for the requested entity
... | {
var monitored_entities = []
} | conditional_block |
auth.selectors.ts | /**
* Copyright (C) 2021 3D Repo Ltd
*
* 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 pro... | *
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import { createSelector } from 'reselect';
const selectAuthDomain = (state) => state.auth2;
export const selectIsAuthenticated = createSelector(
selectAuthDoma... | * GNU Affero General Public License for more details. | random_line_split |
test_po2sub.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytest import importorskip
from translate.convert import po2sub
from translate.convert import test_convert
from translate.misc import wStringIO
from translate.storage import po
# Technically subtitles can also use an older gaupol
importorskip("aeidon")
class Test... | (self, subsource, posource):
"""helper that merges po translations to subtitle source without
requiring files"""
inputfile = wStringIO.StringIO(posource)
inputpo = po.pofile(inputfile)
templatefile = wStringIO.StringIO(subsource)
convertor = po2sub.resub(templatefile, inp... | merge2sub | identifier_name |
test_po2sub.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytest import importorskip
from translate.convert import po2sub
from translate.convert import test_convert
from translate.misc import wStringIO
from translate.storage import po
# Technically subtitles can also use an older gaupol
importorskip("aeidon")
class Test... |
def merge2sub(self, subsource, posource):
"""helper that merges po translations to subtitle source without
requiring files"""
inputfile = wStringIO.StringIO(posource)
inputpo = po.pofile(inputfile)
templatefile = wStringIO.StringIO(subsource)
convertor = po2sub.resu... | """helper that converts po source to subtitle source without requiring
files"""
inputfile = wStringIO.StringIO(posource)
inputpo = po.pofile(inputfile)
convertor = po2sub.resub()
outputsub = convertor.convertstore(inputpo)
return outputsub | identifier_body |
test_po2sub.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pytest import importorskip | from translate.misc import wStringIO
from translate.storage import po
# Technically subtitles can also use an older gaupol
importorskip("aeidon")
class TestPO2Sub:
def po2sub(self, posource):
"""helper that converts po source to subtitle source without requiring
files"""
inputfile = wSt... |
from translate.convert import po2sub
from translate.convert import test_convert | random_line_split |
main.js | import React from 'react'
import ReactDOM from 'react-dom'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { useRouterHistory } from 'react-router'
import {
mySyncHistoryWithStore,
default as createStore
} from './store/createStore'
import AppContainer from './containers/AppContainer'
imp... | }
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = (routerKey = null) => {
const routes = require('./routes/index').default(store)
// TODO, uncomment this before p... | } | random_line_split |
main.js | import React from 'react'
import ReactDOM from 'react-dom'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import { useRouterHistory } from 'react-router'
import {
mySyncHistoryWithStore,
default as createStore
} from './store/createStore'
import AppContainer from './containers/AppContainer'
imp... |
// ========================================================
// Go!
// ========================================================
render()
| {
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react')
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
render = () => {
try {
renderApp(Math.random())
} catch (error) {
renderError(error)
}
}
module.hot.accept(['./routes/in... | conditional_block |
node-tests.ts | NotThrow(() => {
if (false) { throw "a hammer at your face"; }
}, undefined, "What the...*crunch*");
////////////////////////////////////////////////////
/// File system tests : http://nodejs.org/api/fs.html
////////////////////////////////////////////////////
fs.writeFile("thebible.txt",
"Do unto others as yo... |
});
///////////////////////////////////////////////////////
/// Buffer tests : https://nodejs.org/api/buffer.html
///////////////////////////////////////////////////////
function bufferTests() {
var utf8Buffer = new Buffer('test');
var base64Buffer = new Buffer('','base64');
var octets: Uint8Array = nul... | {
errno = err.errno;
} | conditional_block |
node-tests.ts | NotThrow(() => {
if (false) { throw "a hammer at your face"; }
}, undefined, "What the...*crunch*");
////////////////////////////////////////////////////
/// File system tests : http://nodejs.org/api/fs.html
////////////////////////////////////////////////////
fs.writeFile("thebible.txt",
"Do unto others as yo... |
////////////////////////////////////////////////////
/// TLS tests : http://nodejs.org/api/tls.html
////////////////////////////////////////////////////
var ctx: tls.SecureContext = tls.createSecureContext({
key: "NOT REALLY A KEY",
cert: "SOME CERTIFICATE",
});
var blah = ctx.context;
/////////////////////... | {
var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]);
var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]);
var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key);
var cipherBuffers:Buffer[] = [];
cipherBuffers.push(cipher.update(clearText));
cipherB... | identifier_body |
node-tests.ts | import * as url from 'url';
import * as util from 'util';
import * as crypto from 'crypto';
import * as tls from 'tls';
import * as http from 'http';
import * as net from 'net';
import * as dgram from 'dgram';
import * as querystring from 'querystring';
import * as path from 'path';
assert(1 + 1 - 2 === 0, "The univer... | import * as assert from 'assert';
import * as fs from 'fs';
import * as events from 'events';
import * as zlib from 'zlib'; | random_line_split | |
node-tests.ts | NotThrow(() => {
if (false) { throw "a hammer at your face"; }
}, undefined, "What the...*crunch*");
////////////////////////////////////////////////////
/// File system tests : http://nodejs.org/api/fs.html
////////////////////////////////////////////////////
fs.writeFile("thebible.txt",
"Do unto others as yo... | () {
var utf8Buffer = new Buffer('test');
var base64Buffer = new Buffer('','base64');
var octets: Uint8Array = null;
var octetBuffer = new Buffer(octets);
console.log(Buffer.isBuffer(octetBuffer));
console.log(Buffer.isEncoding('utf8'));
console.log(Buffer.byteLength('xyz123'));
console.... | bufferTests | identifier_name |
markdown.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (_ob: *buf, text: *buf, lang: *buf, opaque: *libc::c_void) {
unsafe {
if text.is_null() || lang.is_null() { return }
let (test, shouldfail, ignore) =
vec::raw::buf_as_slice((*lang).data,
(*lang).size as uint, |lang| {
... | block | identifier_name |
markdown.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
let (test, shouldfail, ignore) =
vec::raw::buf_as_slice((*lang).data,
(*lang).size as uint, |lang| {
let s = str::from_utf8(lang);
(s.contains("rust"), s.contains("should_fail"),
s.contains("... | { return } | conditional_block |
markdown.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | static MKDEXT_AUTOLINK: libc::c_uint = 1 << 3;
static MKDEXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
type sd_markdown = libc::c_void; // this is opaque to us
struct sd_callbacks {
blockcode: extern "C" fn(*buf, *buf, *buf, *libc::c_void),
other: [libc::size_t, ..25],
}
struct html_toc_data {
header_count:... | static MKDEXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 0;
static MKDEXT_TABLES: libc::c_uint = 1 << 1;
static MKDEXT_FENCED_CODE: libc::c_uint = 1 << 2; | random_line_split |
react-d3-graph-tests.tsx | import * as React from 'react';
import { Graph, Link, Node } from 'react-d3-graph';
const nodes = [
{ id: 'node1', labelProperty: 'id' },
{ id: 'node2', name: 'node2Name' },
{
id: 'node3',
size: {
width: 100,
height: 200,
},
},
];
type INode = typeof nod... | (): React.ReactElement {
return (
<div>
<Graph
ref={this.ref}
id="test"
data={{
nodes,
links,
focusedNodeId: 'node1',
}}
... | render | identifier_name |
react-d3-graph-tests.tsx | import * as React from 'react';
import { Graph, Link, Node } from 'react-d3-graph';
const nodes = [
{ id: 'node1', labelProperty: 'id' },
{ id: 'node2', name: 'node2Name' },
{
id: 'node3',
size: {
width: 100,
height: 200,
},
},
];
type INode = typeof nod... | return (
<div>
<Graph
ref={this.ref}
id="test"
data={{
nodes,
links,
focusedNodeId: 'node1',
}}
config={{
... |
export class Example extends React.Component {
ref: React.MutableRefObject<Graph<INode, ILink> | null> = React.createRef();
render(): React.ReactElement { | random_line_split |
ManifestDetailsLink.tsx | import React from 'react';
import { IManifest, ReactInjector, AccountService } from '@spinnaker/core';
import { get, trim } from 'lodash';
const UNMAPPED_K8S_RESOURCE_STATE_KEY = 'kubernetesResource';
export interface IManifestDetailsProps {
manifest: IManifest;
linkName: string;
accountId: string;
} | url: string;
}
export class ManifestDetailsLink extends React.Component<IManifestDetailsProps, IManifestDetailsState> {
private spinnakerKindStateMap: { [k: string]: string } = {
// keys from clouddriver's KubernetesSpinnakerKindMap
serverGroupManagers: 'serverGroupManager',
serverGroups: 'serverGroup'... |
export interface IManifestDetailsState { | random_line_split |
ManifestDetailsLink.tsx | import React from 'react';
import { IManifest, ReactInjector, AccountService } from '@spinnaker/core';
import { get, trim } from 'lodash';
const UNMAPPED_K8S_RESOURCE_STATE_KEY = 'kubernetesResource';
export interface IManifestDetailsProps {
manifest: IManifest;
linkName: string;
accountId: string;
}
export in... |
public render() {
if (this.canOpen()) {
return (
<a href={this.state.url} className="clickable">
{this.props.linkName}
</a>
);
} else {
return null;
}
}
}
| {
const kind: string = get(this.props, ['manifest', 'manifest', 'kind'], '');
const { accountId } = this.props;
AccountService.getAccountDetails(accountId).then((account) => {
const spinnakerKind = this.spinnakerKindFromKubernetesKind(kind, account.spinnakerKindMap);
const stateKey = this.spinna... | identifier_body |
ManifestDetailsLink.tsx | import React from 'react';
import { IManifest, ReactInjector, AccountService } from '@spinnaker/core';
import { get, trim } from 'lodash';
const UNMAPPED_K8S_RESOURCE_STATE_KEY = 'kubernetesResource';
export interface IManifestDetailsProps {
manifest: IManifest;
linkName: string;
accountId: string;
}
export in... | else {
return null;
}
}
}
| {
return (
<a href={this.state.url} className="clickable">
{this.props.linkName}
</a>
);
} | conditional_block |
ManifestDetailsLink.tsx | import React from 'react';
import { IManifest, ReactInjector, AccountService } from '@spinnaker/core';
import { get, trim } from 'lodash';
const UNMAPPED_K8S_RESOURCE_STATE_KEY = 'kubernetesResource';
export interface IManifestDetailsProps {
manifest: IManifest;
linkName: string;
accountId: string;
}
export in... | (): boolean {
return !!this.props.manifest.manifest && !!this.state.url;
}
private spinnakerKindFromKubernetesKind(kind: string, kindMap: { [k: string]: string }) {
const foundKind = Object.keys(kindMap).find((k) => k.toLowerCase() === kind.toLowerCase());
return kindMap[foundKind];
}
private reso... | canOpen | identifier_name |
port.ts | import { Service } from 'libs/typedi';
import { action, computed, observable } from 'mobx';
import { Coordinates } from 'core/interfaces';
import { Node } from 'core/models/graph/node';
import { Port, InteractionState } from 'core/models/graph/port';
@Service()
export default class PortInteractions {
@observable
... | this.endPosition = {
...startPosition,
};
this.fromPort = port;
this.startPosition = startPosition;
this.isDragging = true;
return startPosition;
};
private canConnect(from: Port, to: Port) {
return true;
}
@action
attemptToConnect = (port: Port) => {};
@action
handl... | random_line_split | |
port.ts | import { Service } from 'libs/typedi';
import { action, computed, observable } from 'mobx';
import { Coordinates } from 'core/interfaces';
import { Node } from 'core/models/graph/node';
import { Port, InteractionState } from 'core/models/graph/port';
@Service()
export default class PortInteractions {
@observable
... |
@action
beginDragFromClick = (startEvent: MouseEvent, port: Port) => {
if (this.isDragging) {
return;
}
const startPosition = this.beginDrag(port);
const { pageX: startPageX, pageY: startPageY } = startEvent;
const handleMouseMove = (event: MouseEvent) => {
const delta = { x: sta... | {
return { startPosition: this.startPosition, endPosition: this.endPosition };
} | identifier_body |
port.ts | import { Service } from 'libs/typedi';
import { action, computed, observable } from 'mobx';
import { Coordinates } from 'core/interfaces';
import { Node } from 'core/models/graph/node';
import { Port, InteractionState } from 'core/models/graph/port';
@Service()
export default class | {
@observable
isDragging = false;
@observable
startPosition: Coordinates = { x: 0, y: 0 };
@observable
endPosition: Coordinates = { x: 0, y: 0 };
@observable
fromPort: Port | null = null;
@action
handleMouseEnter(port: Port) {
if (!this.isDragging) {
port.interactionState = Interaction... | PortInteractions | identifier_name |
port.ts | import { Service } from 'libs/typedi';
import { action, computed, observable } from 'mobx';
import { Coordinates } from 'core/interfaces';
import { Node } from 'core/models/graph/node';
import { Port, InteractionState } from 'core/models/graph/port';
@Service()
export default class PortInteractions {
@observable
... |
const startPosition = this.beginDrag(port);
const { pageX: startPageX, pageY: startPageY } = startEvent;
const handleMouseMove = (event: MouseEvent) => {
const delta = { x: startPageX - event.pageX, y: startPageY - event.pageY };
this.endPosition = { x: startPosition.x - delta.x, y: startPosi... | {
return;
} | conditional_block |
tableBody.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _style = require('antd/lib/icon/style');
var _icon = require('antd/lib/icon');
var _icon2 = _interopRequireDefault(_icon);
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _inte... |
(0, _createClass3.default)(TBody, [{
key: 'render',
value: function render() {
var _this2 = this;
var _props = this.props;
var dataSource = _props.dataSource;
var _props$locale = _props.locale;
var locale = _props$locale === undefined ? {} : _props$locale;
return _react... | {
(0, _classCallCheck3.default)(this, TBody);
var _this = (0, _possibleConstructorReturn3.default)(this, (TBody.__proto__ || (0, _getPrototypeOf2.default)(TBody)).call(this, props));
_this.state = {};
return _this;
} | identifier_body |
tableBody.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _style = require('antd/lib/icon/style');
var _icon = require('antd/lib/icon');
|
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel... | var _icon2 = _interopRequireDefault(_icon);
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2); | random_line_split |
tableBody.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _style = require('antd/lib/icon/style');
var _icon = require('antd/lib/icon');
var _icon2 = _interopRequireDefault(_icon);
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _inte... | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TBody = (_temp = _class = function (_React$Component) {
(0, _inherits3.default)(TBody, _React$Component);
function TBody(props) {
(0, _classCallCheck3.default)(this, TBody);
var _this = (0, _possibleConstructorReturn3.default)(this, (TB... | _interopRequireDefault | identifier_name |
foreign2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { } | identifier_body | |
foreign2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () { }
| main | identifier_name |
foreign2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub fn main() { } | }
| random_line_split |
goals.ts | import { test, useSpectron } from '../../helpers/spectron';
import { addSource } from '../../helpers/modules/sources';
import { logIn } from '../../helpers/spectron/user';
import { FormMonkey } from '../../helpers/form-monkey';
import { waitForWidgetSettingsSync } from '../../helpers/widget-helpers';
useSpectron();
t... | (goalType: string) {
test.skip(`${goalType} create and delete`, async t => {
const client = t.context.app.client;
if (!(await logIn(t))) return;
await addSource(goalType, goalType, false);
// end goal if it's already exist
if (await (await client.$('button=End Goal')).isDisplayed()) {
await... | testGoal | identifier_name |
goals.ts | import { test, useSpectron } from '../../helpers/spectron';
import { addSource } from '../../helpers/modules/sources';
import { logIn } from '../../helpers/spectron/user';
import { FormMonkey } from '../../helpers/form-monkey';
import { waitForWidgetSettingsSync } from '../../helpers/widget-helpers';
useSpectron();
t... | text_color: '#FFFFFF',
bar_text_color: '#F8E71C',
font: 'Open Sans',
};
await formMonkey.fill(testSet2);
await waitForWidgetSettingsSync(t);
t.true(await formMonkey.includes(testSet2));
});
} | random_line_split | |
goals.ts | import { test, useSpectron } from '../../helpers/spectron';
import { addSource } from '../../helpers/modules/sources';
import { logIn } from '../../helpers/spectron/user';
import { FormMonkey } from '../../helpers/form-monkey';
import { waitForWidgetSettingsSync } from '../../helpers/widget-helpers';
useSpectron();
t... | await (await client.$('button=Start Goal')).click();
await (await client.$('button=End Goal')).waitForDisplayed();
t.true(await (await client.$('span=My Goal')).isExisting());
await (await client.$('button=End Goal')).click();
await (await client.$('button=Start Goal')).waitForDisplayed({ timeout: 2... | {
test.skip(`${goalType} create and delete`, async t => {
const client = t.context.app.client;
if (!(await logIn(t))) return;
await addSource(goalType, goalType, false);
// end goal if it's already exist
if (await (await client.$('button=End Goal')).isDisplayed()) {
await (await client.$('b... | identifier_body |
pilotTools.py | ( 'Timeout after %s seconds on transfer request for "%s"' % ( str( timeout ), url ) )
if timeout:
signal.alarm( 0 )
raise x
class ObjectLoader( object ):
""" Simplified class for loading objects from a DIRAC installation.
Example:
ol = ObjectLoader()
object, modulePath = ol.loadObj... |
# No command could be instantitated
return None, None
class Logger( object ):
""" Basic logger object, for use inside the pilot. Just using print.
"""
def __init__( self, name = 'Pilot', debugFlag = False, pilotOutput = 'pilot.out' ):
self.debugFlag = debugFlag
self.name = name
self.out = pilo... | diracExtensions = []
for ext in params.extensions:
if not ext.endswith( 'DIRAC' ):
diracExtensions.append( ext + 'DIRAC' )
else:
diracExtensions.append( ext )
diracExtensions += ['DIRAC']
ol = ObjectLoader( diracExtensions, log )
for module in modules:
commandObject, mo... | conditional_block |
pilotTools.py | ( 'Timeout after %s seconds on transfer request for "%s"' % ( str( timeout ), url ) )
if timeout:
signal.alarm( 0 )
raise x
class ObjectLoader( object ):
""" Simplified class for loading objects from a DIRAC installation.
Example:
ol = ObjectLoader()
object, modulePath = ol.loadObj... | self.commandExtensions = []
self.commands = ['GetPilotVersion | """ Class that holds the structure with all the parameters to be used across all the commands
"""
MAX_CYCLES = 10
def __init__( self ):
""" c'tor
param names and defaults are defined here
"""
self.rootPath = os.getcwd()
self.originalRootPath = os.getcwd()
self.pilotRootPath = os.ge... | identifier_body |
pilotTools.py | ########################################################################
""" A set of common tools to be used in pilot commands
"""
import sys
import time
import os
import pickle
import getopt
import imp
import types
import urllib2
import signal
__RCSID__ = '$Id$'
def printVersion( log ):
log.info( "Running %s" ... | random_line_split | ||
pilotTools.py | ( *args ):
raise Exception( 'Timeout' )
def retrieveUrlTimeout( url, fileName, log, timeout = 0 ):
"""
Retrieve remote url to local file, with timeout wrapper
"""
urlData = ''
if timeout:
signal.signal( signal.SIGALRM, alarmTimeoutHandler )
# set timeout alarm
signal.alarm( timeout + 5 )
try... | alarmTimeoutHandler | identifier_name | |
get_access_token.py | # -*- coding: utf-8 -*-
__author__ = 'lxr0827'
import pymysql,requests,json
import datetime
#定时运行该脚本获取accesstoken,记录到accesstoken module里
#test | AccessTokenURL = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + APPID + '&secret=' + SECRET
r = requests.get(AccessTokenURL)
if (r.status_code == requests.codes.ok): # @UndefinedVariable
res = json.loads(r.text)
if res.get('errcode') == None:
accessToken = res['access_... | APPID = "wx243dd553e7ab9da7"
SECRET = "57f109fd1cce0913a76a1700f94c4e2d"
| random_line_split |
get_access_token.py | # -*- coding: utf-8 -*-
__author__ = 'lxr0827'
import pymysql,requests,json
import datetime
#定时运行该脚本获取accesstoken,记录到accesstoken module里
#test
APPID = "wx243dd553e7ab9da7"
SECRET = "57f109fd1cce0913a76a1700f94c4e2d"
AccessTokenURL = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + APPID... | updateStr = "update WeInterc_accesstoken set accessToken = '%s',getTokenTime = '%s'where id = 1" % (accessToken, nowTime)
print(updateStr)
cur.execute(updateStr)
conn.commit()
cur.close()
conn.close()
| conditional_block | |
erlang_rust_port.rs | // see erlang_rust_port.erl
extern crate erl_ext;
extern crate getopts;
use getopts::Options;
use erl_ext::{Decoder,Encoder,Error};
use std::io;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("u", "utf8-atoms", "Use utf-8 atoms featu... | {
loop {
assert!(true == try!(decoder.read_prelude()));
let term = try!(decoder.decode_term());
try!(encoder.write_prelude());
try!(encoder.encode_term(term));
try!(encoder.flush());
}
} | identifier_body | |
erlang_rust_port.rs | // see erlang_rust_port.erl | extern crate erl_ext;
extern crate getopts;
use getopts::Options;
use erl_ext::{Decoder,Encoder,Error};
use std::io;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("u", "utf8-atoms", "Use utf-8 atoms feature");
opts.optflag("s", "... | random_line_split | |
erlang_rust_port.rs | // see erlang_rust_port.erl
extern crate erl_ext;
extern crate getopts;
use getopts::Options;
use erl_ext::{Decoder,Encoder,Error};
use std::io;
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("u", "utf8-atoms", "Use utf-8 atoms featu... | <R: io::Read>(mut decoder: Decoder<R>, mut encoder: Encoder) -> Result<(), Error> {
loop {
assert!(true == try!(decoder.read_prelude()));
let term = try!(decoder.decode_term());
try!(encoder.write_prelude());
try!(encoder.encode_term(term));
try!(encoder.flush());
}
}
| read_write_loop | identifier_name |
plot_kmeans_digits.py | """
===========================================================
A demo of K-Means clustering on the handwritten digits data
===========================================================
In this example with compare the various initialization strategies for
K-means in terms of runtime and quality of the results.
As the ... | plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', s=169, linewidths=3,
color='w', zorder=10)
plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n'
'Centroids are marked with white cross')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.ytick... | plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
# Plot the centroids as a white X
centroids = kmeans.cluster_centers_ | random_line_split |
plot_kmeans_digits.py | """
===========================================================
A demo of K-Means clustering on the handwritten digits data
===========================================================
In this example with compare the various initialization strategies for
K-means in terms of runtime and quality of the results.
As the ... |
bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10),
name="k-means++", data=data)
bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10),
name="random", data=data)
# in this case the seeding of the centers is deterministic, hence we run the
# kmeans algori... | t0 = time()
estimator.fit(data)
print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f'
% (name, (time() - t0), estimator.inertia_,
metrics.homogeneity_score(labels, estimator.labels_),
metrics.completeness_score(labels, estimator.labels_),
metrics.... | identifier_body |
plot_kmeans_digits.py | """
===========================================================
A demo of K-Means clustering on the handwritten digits data
===========================================================
In this example with compare the various initialization strategies for
K-means in terms of runtime and quality of the results.
As the ... | (estimator, name, data):
t0 = time()
estimator.fit(data)
print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f'
% (name, (time() - t0), estimator.inertia_,
metrics.homogeneity_score(labels, estimator.labels_),
metrics.completeness_score(labels, estimator.la... | bench_k_means | identifier_name |
aplus.js | define(function(require) {
/**
* The Promises/A+ compliance test suite
*
* Converted from https://github.com/promises-aplus/promises-tests
* Thanks @domenic and A+ team for this massive work!
**/
require('spec/base/promiseSpec/aplus/2.1.2');
require('spec/base/promiseSpec/aplus/2.1.3');
require('s... | require('spec/base/promiseSpec/aplus/2.3.2');
require('spec/base/promiseSpec/aplus/2.3.3');
require('spec/base/promiseSpec/aplus/2.3.4');
}); | random_line_split | |
navbar.js | (function Nav() {
var Nav = React.createClass({
displayName: "Nav",
render: function () {
var self = this;
return React.createElement(
"nav",
{ className: "navbar navbar-inverse" },
React.createElement(
"div",
{ className: "container-fluid" },
React.createElement(
"div",
... | );
},
changeLanguage: function changeLanguage(ev) {
//ev.preventDefault()
i18n.language(ev.target.dataset.language);
}
});
var Brand = React.createClass({
displayName: "Brand",
render: function () {
return React.createElement(
"a",
{ className: "navbar-brand", href: "#" },
React.cr... | ) | random_line_split |
navbar.js | (function Nav() {
var Nav = React.createClass({
displayName: "Nav",
render: function () {
var self = this;
return React.createElement(
"nav",
{ className: "navbar navbar-inverse" },
React.createElement(
"div",
{ className: "container-fluid" },
React.createElement(
"div",
... |
});
},
render: function render() {
var value = this.getValue(this.props.i18n);
return React.createElement(
"span",
this.props,
value,
this.props.children
);
},
getValue: function getValue(key) {
return i18n.get(key);
}
});
ReactDOM.render(React.createElement(Nav, null), docu... | {
self.forceUpdate();
} | conditional_block |
home.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PageLink } from '../security/model/pagelink';
import { User } from '../security/model/user';
import { LoginService } from '../security/login/login.service';
import { GlobalService } from '../core/global.service';
impor... | (private router: Router, private loginService: LoginService,
private globalService: GlobalService, private authorizationService: AuthorizationService,private sanitizer:DomSanitizer) {
this.backgroundImg = sanitizer.bypassSecurityTrustStyle('url(../../app/resources/images/background.jpg)');
}
ngOnInit() {... | constructor | identifier_name |
home.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PageLink } from '../security/model/pagelink';
import { User } from '../security/model/user';
import { LoginService } from '../security/login/login.service';
import { GlobalService } from '../core/global.service';
impor... |
else if(sessionStorage.getItem('userLoggedIn'))
{
//console.log("************************* gobal service oops.. check sessionStorage : "+sessionStorage.getItem('loggedInUser')+" | "+sessionStorage.getItem('userLoggedIn'));
this.globalService.userLoggedIn = true;
this.globalService.logge... | {
//console.log("globalServic is enabled - "+this.globalService.userLoggedIn);
userLoggedIn = this.globalService.userLoggedIn;
return userLoggedIn;
} | conditional_block |
home.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PageLink } from '../security/model/pagelink';
import { User } from '../security/model/user';
import { LoginService } from '../security/login/login.service';
import { GlobalService } from '../core/global.service';
impor... |
ngOnInit() {
}
get userLoggedIn(): boolean {
//console.log("checking user logged in");
let userLoggedIn = false;
if(this.globalService.userLoggedIn)
{
//console.log("globalServic is enabled - "+this.globalService.userLoggedIn);
userLoggedIn = this.globalService.userLoggedIn;
r... | {
this.backgroundImg = sanitizer.bypassSecurityTrustStyle('url(../../app/resources/images/background.jpg)');
} | identifier_body |
home.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { PageLink } from '../security/model/pagelink';
import { User } from '../security/model/user';
import { LoginService } from '../security/login/login.service';
import { GlobalService } from '../core/global.service';
impor... |
}
logout() {
sessionStorage.clear();
localStorage.clear();
this.router.navigate(['']);
this.loginService.logout().subscribe(() => {
window.location.reload();
},
error => {
});
}
changePassword() {
this.router.navigate(['changePassword']);
}
/*analytics() {
this.r... | this.globalService.userLoggedIn = true;
this.globalService.loggedInUser = JSON.parse(sessionStorage.getItem('loggedInUser'));
return (sessionStorage.getItem('userLoggedIn')==='true');
} | random_line_split |
dom_manipulation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::event::{EventBubbles, E... | {
let msg = MainThreadScriptMsg::Common(CommonScriptMsg::Task(
ScriptThreadEventCategory::ScriptEvent,
Box::new(canceller.wrap_task(task)),
));
self.0.send(msg).map_err(|_| ())
}
}
impl DOMManipulationTaskSource {
pub fn queue_event(&self,
... | ) -> Result<(), ()>
where
T: TaskOnce + 'static, | random_line_split |
dom_manipulation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::event::{EventBubbles, E... | (pub Sender<MainThreadScriptMsg>);
impl fmt::Debug for DOMManipulationTaskSource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "DOMManipulationTaskSource(...)")
}
}
impl TaskSource for DOMManipulationTaskSource {
fn queue_with_canceller<T>(
&self,
task: T,
... | DOMManipulationTaskSource | identifier_name |
dom_manipulation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::inheritance::Castable;
use dom::bindings::refcounted::Trusted;
use dom::event::{EventBubbles, E... |
}
| {
let target = Trusted::new(target);
let _ = self.queue(SimpleEventTask { target, name }, window.upcast());
} | identifier_body |
run.py | #!/usr/bin/env python3
# coding: utf-8
#
import re
import os
import time
import argparse
import yaml
import bunch
import uiautomator2 as u2
from logzero import logger
CLICK = "click"
# swipe
SWIPE_UP = "swipe_up"
SWIPE_RIGHT = "swipe_right"
SWIPE_LEFT = "swipe_left"
SWIPE_DOWN = "swipe_down"
SCREENSHOT = "screensh... | ("Author:", cf.author)
print("Description:", cf.description)
print("Package:", cf.package)
logger.debug("action_delay: %.1f / %.1f", cf.action_before_delay, cf.action_after_delay)
app = d.session(cf.package)
for step in cf.steps:
time.sleep(cf.action_before_delay)
run_step(cf, app, ... | unch(cf)
print | conditional_block |
run.py | #!/usr/bin/env python3
# coding: utf-8
#
import re
import os
import time
import argparse
import yaml
import bunch
import uiautomator2 as u2
from logzero import logger
CLICK = "click"
# swipe
SWIPE_UP = "swipe_up"
SWIPE_RIGHT = "swipe_right"
SWIPE_LEFT = "swipe_left"
SWIPE_DOWN = "swipe_down"
SCREENSHOT = "screensh... | n, step: str):
logger.info("Step: %s", step)
oper, body = split_step(step)
logger.debug("parse as: %s %s", oper, body)
if oper == CLICK:
app.xpath(body).click()
elif oper == SWIPE_RIGHT:
app.xpath(body).swipe("right")
elif oper == SWIPE_UP:
app.xpath(body).swipe("up")
... | 2.Sessio | identifier_name |
run.py | #!/usr/bin/env python3
# coding: utf-8
#
import re
import os
import time
import argparse
import yaml
import bunch
import uiautomator2 as u2
from logzero import logger
CLICK = "click"
# swipe
SWIPE_UP = "swipe_up"
SWIPE_RIGHT = "swipe_right"
SWIPE_LEFT = "swipe_left"
SWIPE_DOWN = "swipe_down"
SCREENSHOT = "screensh... | arser = argparse.ArgumentParser()
parser.add_argument("-c", "--command", help="run single step command")
parser.add_argument("-s", "--serial", help="run single step command")
parser.add_argument("conf_filename", default="test.yml", nargs="?", help="config filename")
args = parser.parse_args()
d = u... | p | identifier_body |
run.py | #!/usr/bin/env python3
# coding: utf-8
#
import re
import os
import time
import argparse
import yaml
import bunch
import uiautomator2 as u2
from logzero import logger
CLICK = "click"
# swipe
SWIPE_UP = "swipe_up"
SWIPE_RIGHT = "swipe_right"
SWIPE_LEFT = "swipe_left"
SWIPE_DOWN = "swipe_down"
SCREENSHOT = "screensh... | d.xpath.watch_background(2.0)
cf = yaml.load(read_file_content(conf_filename), Loader=yaml.SafeLoader)
default = {
"output_directory": "output",
"action_before_delay": 0,
"action_after_delay": 0,
"skip_cleanup": False,
}
for k, v in default.items():
cf.setdef... | d.healthcheck()
d.xpath.when("允许").click() | random_line_split |
linearize-data.py | (blk_hdr):
hash = calc_hdr_hash(blk_hdr)
hash = bufreverse(hash)
hash = wordreverse(hash)
hash_str = hash.hex()
return hash_str
def get_blk_dt(blk_hdr):
members = struct.unpack("<I", blk_hdr[68:68+4])
nTime = members[0]
dt = datetime.datetime.fromtimestamp(nTime)
dt_ym = datetime.da... | calc_hash_str | identifier_name | |
linearize-data.py | map(blkindex):
blkmap = {}
for height,hash in enumerate(blkindex):
blkmap[hash] = height
return blkmap
# This gets the first block file ID that exists from the input block
# file directory.
def getFirstBlockFileId(block_dir_path):
# First, this sets up a pattern to search for block files, for
... | self.writeBlock(inhdr, blk_hdr, rawblock)
# See if we can catch up to prior out-of-order blocks
while self.blkCountOut in self.blockExtents: | random_line_split | |
linearize-data.py | = calc_hdr_hash(blk_hdr)
hash = bufreverse(hash)
hash = wordreverse(hash)
hash_str = hash.hex()
return hash_str
def get_blk_dt(blk_hdr):
members = struct.unpack("<I", blk_hdr[68:68+4])
nTime = members[0]
dt = datetime.datetime.fromtimestamp(nTime)
dt_ym = datetime.datetime(dt.year, dt.... |
def inFileName(self, fn):
return os.path.join(self.settings['input'], "blk%05d.dat" % fn)
def fetchBlock(self, extent):
'''Fetch block contents from disk given extents'''
with open(self.inFileName(extent.fn), "rb") as f:
f.seek(extent.offset)
return f.read(exte... | print('%i blocks scanned, %i blocks written (of %i, %.1f%% complete)' %
(self.blkCountIn, self.blkCountOut, len(self.blkindex), 100.0 * self.blkCountOut / len(self.blkindex))) | conditional_block |
linearize-data.py | = calc_hdr_hash(blk_hdr)
hash = bufreverse(hash)
hash = wordreverse(hash)
hash_str = hash.hex()
return hash_str
def get_blk_dt(blk_hdr):
members = struct.unpack("<I", blk_hdr[68:68+4])
nTime = members[0]
dt = datetime.datetime.fromtimestamp(nTime)
dt_ym = datetime.datetime(dt.year, dt.... | self.maxOutSz = settings['max_out_sz']
if 'output' in settings:
self.fileOutput = False
if settings['file_timestamp'] != 0:
self.setFileTime = True
if settings['split_timestamp'] != 0:
self.timestampSplit = True
# Extents and cache for out-of-o... | self.settings = settings
self.blkindex = blkindex
self.blkmap = blkmap
# Get first occurring block file id - for pruned nodes this
# will not necessarily be 0
self.inFn = getFirstBlockFileId(self.settings['input'])
self.inF = None
self.outFn = 0
self.outs... | identifier_body |
htmltablerowelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::htmlelement::HTMLElement;
pub struct HTMLTableRowEle... |
pub fn DeleteCell(&mut self, _index: i32) -> ErrorResult {
Ok(())
}
pub fn Align(&self) -> DOMString {
None
}
pub fn SetAlign(&self, _align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Ch(&self) -> DOMString {
None
}
pub fn SetCh(&self, _ch: &DOM... | random_line_split | |
htmltablerowelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::htmlelement::HTMLElement;
pub struct HTMLTableRowEle... | (&self) -> DOMString {
None
}
pub fn SetCh(&self, _ch: &DOMString) -> ErrorResult {
Ok(())
}
pub fn ChOff(&self) -> DOMString {
None
}
pub fn SetChOff(&self, _ch_off: &DOMString) -> ErrorResult {
Ok(())
}
pub fn VAlign(&self) -> DOMString {
Non... | Ch | identifier_name |
htmltablerowelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::htmlelement::HTMLElement;
pub struct HTMLTableRowEle... |
pub fn Align(&self) -> DOMString {
None
}
pub fn SetAlign(&self, _align: &DOMString) -> ErrorResult {
Ok(())
}
pub fn Ch(&self) -> DOMString {
None
}
pub fn SetCh(&self, _ch: &DOMString) -> ErrorResult {
Ok(())
}
pub fn ChOff(&self) -> DOMString ... | {
Ok(())
} | identifier_body |
node_curves.py | Dr. D Studios - Software Disclaimer
#
# Copyright 2009 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios), its
# affiliates and/or its licensors.
#
###############################################################################
"""
This module will help TD's to convert houdini animation curve to nuke or maya
... |
else:
msg = "%s not exists in scene !" % node.path()
rodin_logger.error(msg)
raise KipBaseError(msg)
return all_anim_curves
# Copyright 2008-2012 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios)
#
# This file is part of anim-studio-tools.
#
# anim-studio-t... | if each_prm.isTimeDependent():
if len(each_prm.keyframes()) > 0:
curve_dict = {}
if not curve_dict.has_key(each_prm.name()):
curve_dict[each_prm.name()]=each_prm.keyframes()
else:
... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.