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 |
|---|---|---|---|---|
classify.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 ... | (stmt: &ast::Stmt) -> bool {
return match stmt.node {
ast::StmtDecl(d, _) => {
match d.node {
ast::DeclLocal(_) => true,
ast::DeclItem(_) => false
}
}
ast::StmtExpr(e, _) => { expr_requires_semi_to_be_stmt(e) }
ast::StmtSemi(..)... | stmt_ends_with_semi | identifier_name |
MarketplacePlugin.ts | /*
* Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope tha... |
export interface MarketplacePluginImage {
url: string;
title: string;
description: string;
}
export interface MarketplacePluginVideo {
title: string;
description: string;
url: string;
}
interface MarketplacePluginMedia {
screenshots: [MarketplacePluginImage];
videos?: [MarketplacePluginVideo] | [];
}... | random_line_split | |
PlotCursor.ts | /*
* Copyright 2018 TWO SIGMA OPEN SOURCE, 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 appl... | (event) {
const x = event.offsetX;
const y = event.offsetY;
const width = PlotStyleUtils.safeWidth(this.scope.jqsvg);
const height = PlotStyleUtils.safeHeight(this.scope.jqsvg);
const leftMargin = this.scope.layout.leftLayoutMargin;
const bottomMargin = this.scope.layout.bottomLayoutMargin;
... | render | identifier_name |
PlotCursor.ts | /*
* Copyright 2018 TWO SIGMA OPEN SOURCE, 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 appl... | }
clear() {
this.scope.svg.selectAll(".plot-cursor").remove();
this.scope.jqcontainer.find(".plot-cursorlabel").remove();
}
} | }); | random_line_split |
PlotCursor.ts | /*
* Copyright 2018 TWO SIGMA OPEN SOURCE, 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 appl... |
const model = this.scope.stdmodel;
const opt = model.yCursor;
const lMargin = this.scope.layout.leftLayoutMargin;
const rMargin = this.scope.layout.rightLayoutMargin;
const mapY = this.scope.plotRange.scr2dataY;
this.scope.jqcontainer.find("#" + id).remove();
const label = $(`<div id="${... | {
return;
} | conditional_block |
default.rs | // Copyright 2012-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-MI... | cx.span_fatal(span, "`Default` cannot be derived for enums, \
only structs")
}
_ => cx.bug("Non-static method in `deriving(Default)`")
};
} | random_line_split | |
default.rs | // Copyright 2012-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-MI... | (cx: &ExtCtxt,
span: Span,
mitem: @MetaItem,
in_items: ~[@Item])
-> ~[@Item] {
let trait_def = TraitDef {
cx: cx, span: span,
path: Path::new(~["std", "default", "Default"]),
additional_bounds: ~[],
... | expand_deriving_default | identifier_name |
default.rs | // Copyright 2012-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-MI... | Named(ref fields) => {
let default_fields = fields.map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
});
cx.expr_struct_ident(span, substr.type_ident, default_fields)
}
}
... | {
let default_ident = ~[
cx.ident_of("std"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
];
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), ~[]);
return match *substr.fields {
StaticStruct(_, ref summary) => {... | identifier_body |
index.js | import { loadTranslations } from "/imports/plugins/core/core/server/startup/i18n";
// import ar from "./ar.json";
// import bg from "./bg.json";
// import de from "./de.json";
// import el from "./el.json";
import en from "./en.json";
// import es from "./es.json";
// import fr from "./fr.json";
// import he from "./h... | // automated translation software
//
loadTranslations([en]);
// loadTranslations([ar, bg, de, el, en, es, fr, he, hr, it, my, nb, nl, pl, pt, ro, ru, sl, sv, tr, vi, zh]); |
//
// we want all the files in individual
// imports for easier handling by | random_line_split |
download_test.py | #! /usr/bin/env python
"""Unit tests for the image downloader."""
import unittest
import download
__author__ = "Nick Pascucci (npascut1@gmail.com)"
class DownloadTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_img_matcher(self):
html = """<html>
<bod... | html = """<html>
<body>
<b>Hi there!</b>
<img src="http://www.def.com/abcd-(myfile)[1].jpg">
</body>
</html>
"""
paths = download.get_image_paths(html)
assert paths == ["http://www.def.com/abcd-(myfile)[1].jpg"]
def test_extension_matcher(self):
filename = "abcdef.jpg"
assert down... | """
paths = download.get_image_paths(html)
assert paths == ["abcd-(myfile)[1].jpg"]
def test_img_matcher_http(self): | random_line_split |
download_test.py | #! /usr/bin/env python
"""Unit tests for the image downloader."""
import unittest
import download
__author__ = "Nick Pascucci (npascut1@gmail.com)"
class DownloadTest(unittest.TestCase):
def | (self):
pass
def tearDown(self):
pass
def test_img_matcher(self):
html = """<html>
<body>
<b>Hi there!</b>
<img src="abcd-(myfile)[1].jpg">
</body>
</html>
"""
paths = download.get_image_paths(html)
assert paths == ["abcd-(myfile)[1].jpg"]
def test_img_matcher_http(... | setUp | identifier_name |
download_test.py | #! /usr/bin/env python
"""Unit tests for the image downloader."""
import unittest
import download
__author__ = "Nick Pascucci (npascut1@gmail.com)"
class DownloadTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_img_matcher(self):
html = """<html>
<bod... | unittest.main() | conditional_block | |
download_test.py | #! /usr/bin/env python
"""Unit tests for the image downloader."""
import unittest
import download
__author__ = "Nick Pascucci (npascut1@gmail.com)"
class DownloadTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_img_matcher(self):
html = """<html>
<bod... |
def test_extension_matcher(self):
filename = "abcdef.jpg"
assert download.match_extension(filename)
filename = "abcdef.txt"
assert not download.match_extension(filename)
def test_sitename_matcher(self):
site = "http://www.xkcd.com/208/"
sitename = download.sitename(sit... | html = """<html>
<body>
<b>Hi there!</b>
<img src="http://www.def.com/abcd-(myfile)[1].jpg">
</body>
</html>
"""
paths = download.get_image_paths(html)
assert paths == ["http://www.def.com/abcd-(myfile)[1].jpg"] | identifier_body |
Woundy.py | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import os, os.path
from matplotlib import pyplot as plt
from pylab import get_cmap
import SimpleCV as cv
from glob import glob
# <codecell>
def show_img(img, ax = None): | plt.sca(ax)
nimg = img.getNumpy()
return plt.imshow(nimg, aspect='equal')
# <codecell>
path = '/home/will/Dropbox/burnimages/*.jpg'
norm_files = sorted(f for f in glob(path) if '-e' not in f)
masked_files = sorted(f for f in glob(path) if '-e' in f)
fig, axs = plt.subplots(6,6, figsize = (10,10))
for... | if ax is not None: | random_line_split |
Woundy.py | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import os, os.path
from matplotlib import pyplot as plt
from pylab import get_cmap
import SimpleCV as cv
from glob import glob
# <codecell>
def | (img, ax = None):
if ax is not None:
plt.sca(ax)
nimg = img.getNumpy()
return plt.imshow(nimg, aspect='equal')
# <codecell>
path = '/home/will/Dropbox/burnimages/*.jpg'
norm_files = sorted(f for f in glob(path) if '-e' not in f)
masked_files = sorted(f for f in glob(path) if '-e' in f)
fig, axs =... | show_img | identifier_name |
Woundy.py | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import os, os.path
from matplotlib import pyplot as plt
from pylab import get_cmap
import SimpleCV as cv
from glob import glob
# <codecell>
def show_img(img, ax = None):
if ax is not None:
plt.sca(ax)
nimg = img.getNumpy()
return pl... | ax.set_xticks([])
ax.set_yticks([])
ax.set_title(ratio)
fig.tight_layout()
# <codecell>
import pandas as pd
res_df = pd.DataFrame(sorted(results), columns = ['SampleTime', 'Ratio'])
dime_diameter = 18 #mm
dime_area = 3.141*(dime_diameter/2)**2
res_df['Area-mm2'] = dime_area*res_df['... | mask_img = cv.Image(mf)
norm_img = cv.Image(of)
dt = parse(fname.rsplit(os.sep,1)[1].replace('.jpg', '').replace('.',':'))
wound_mask, wound_blobs = make_wound_mask(norm_img, mask_img, cv.Color.GREEN,
minsize = 1000)
dime_mask, dime_blobs = make_wound_... | conditional_block |
Woundy.py | # -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
import os, os.path
from matplotlib import pyplot as plt
from pylab import get_cmap
import SimpleCV as cv
from glob import glob
# <codecell>
def show_img(img, ax = None):
|
# <codecell>
path = '/home/will/Dropbox/burnimages/*.jpg'
norm_files = sorted(f for f in glob(path) if '-e' not in f)
masked_files = sorted(f for f in glob(path) if '-e' in f)
fig, axs = plt.subplots(6,6, figsize = (10,10))
for f, ax in zip(norm_files, axs.flatten()):
img = cv.Image(f)
show_img(img, ax = ax... | if ax is not None:
plt.sca(ax)
nimg = img.getNumpy()
return plt.imshow(nimg, aspect='equal') | identifier_body |
photostack.js | ( array ) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
function Photostack(... | shuffleArr | identifier_name | |
photostack.js | ack.prototype.options = {};
Photostack.prototype._init = function() {
this.currentItem = this.items[ this.current ];
this._addNavigation();
this._getSizes();
this._initEvents();
}
Photostack.prototype._addNavigation = function() {
// add nav dots
this.nav = document.createElement( 'nav' )
var inner =... | if ( this._resizeTimeout ) {
clearTimeout( this._resizeTimeout );
}
this._resizeTimeout = setTimeout( delayed, 100 );
}
Photostack.prototype._resize = function() {
var self = this, callback = function() { self._shuffle( true ); }
this._getSizes();
if( this.started && this.flipped ) {
this._rotateIt... | var self = this;
function delayed() {
self._resize();
self._resizeTimeout = null;
} | random_line_split |
photostack.js | of possible positions
var grid = [];
// populate the positions grid
for( var i = 0; i < columns; ++i ) {
var col = grid[ i ] = [];
for( var j = 0; j < lines; ++j ) {
var xVal = j * (self.sizes.item.width * overlapFactor) - extraX,
yVal = i * (self.sizes.item.height * overlapFactor) -... | this.currentItem.addEventListener( transEndEventName, onEndTransitionFn );
}
| conditional_block | |
photostack.js |
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define... | {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
} | identifier_body | |
metric.rs | ).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Metric {
// Dim is either 1 or 2, for a 1D or 2D metric respectively.
dim: u8,
// Deriv is the scaling factor for the metric.
deriv: f64,
}
macro_rules! metric {
($name:ident, $dim:expr, $deriv:expr) => {
pub const... |
/// min_level returns the minimum level such that the metric is at most
/// the given value, or maxLevel (30) if there is no such level.
///
/// For example, MINLevel(0.1) returns the minimum level such that all cell diagonal
/// lengths are 0.1 or smaller. The returned value is always a valid lev... | {
// return math.Ldexp(m.Deriv, -m.Dim*level)
ldexp(self.deriv, -1 * (self.dim as i32) * (level as i32))
} | identifier_body |
metric.rs | ).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Metric {
// Dim is either 1 or 2, for a 1D or 2D metric respectively.
dim: u8,
// Deriv is the scaling factor for the metric.
deriv: f64,
}
macro_rules! metric {
($name:ident, $dim:expr, $deriv:expr) => {
pub const... | else if level < 0 {
0
} else {
level as u64
}
}
/// max_level returns the maximum level such that the metric is at least
/// the given value, or zero if there is no such level.
///
/// For example, MAXLevel(0.1) returns the maximum level such that all cells ... | {
MAX_LEVEL
} | conditional_block |
metric.rs | ).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Metric {
// Dim is either 1 or 2, for a 1D or 2D metric respectively.
dim: u8,
// Deriv is the scaling factor for the metric.
deriv: f64,
}
macro_rules! metric {
($name:ident, $dim:expr, $deriv:expr) => {
pub const... | let level = -ilogb(val / self.deriv) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32) {
MAX_LEVEL
} else if level < 0 {
0
} else {
level as u64
}
}
/// max_level returns the maximum level such that the metric is at least
/... | pub fn min_level(&self, val: f64) -> u64 {
if val < 0. {
return MAX_LEVEL;
}
| random_line_split |
metric.rs | ).
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Metric {
// Dim is either 1 or 2, for a 1D or 2D metric respectively.
dim: u8,
// Deriv is the scaling factor for the metric.
deriv: f64,
}
macro_rules! metric {
($name:ident, $dim:expr, $deriv:expr) => {
pub const... | (&self, val: f64) -> u64 {
if val < 0. {
return MAX_LEVEL;
}
let level = -ilogb(val / self.deriv) >> u64::from(self.dim - 1);
if level > (MAX_LEVEL as i32) {
MAX_LEVEL
} else if level < 0 {
0
} else {
level as u64
}... | min_level | identifier_name |
sort.rs | use std::collections::BTreeMap;
use std::convert::AsRef;
pub struct Sorter;
// ToDo: merge with Indexing?
impl Sorter {
pub fn sort<T, R>(values: R) -> Vec<T>
where
T: Clone + Ord,
R: AsRef<Vec<T>>,
{
let values: &Vec<T> = values.as_ref();
// Clone all elements
l... |
#[test]
fn test_sort_by_int_float() {
let (keys, vals) = Sorter::sort_by(&vec![3, 2, 1, 4, 1], &vec![1.1, 2.1, 3.1, 4.1, 5.1]);
assert_eq!(keys, vec![1, 1, 2, 3, 4]);
assert_eq!(vals, vec![3.1, 5.1, 2.1, 1.1, 4.1]);
}
}
| {
let (keys, vals) = Sorter::sort_by(&vec![3, 3, 1, 1, 1], &vec![1, 2, 3, 4, 5]);
assert_eq!(keys, vec![1, 1, 1, 3, 3]);
assert_eq!(vals, vec![3, 4, 5, 1, 2]);
} | identifier_body |
sort.rs | use std::collections::BTreeMap;
use std::convert::AsRef;
pub struct Sorter;
// ToDo: merge with Indexing?
impl Sorter {
pub fn sort<T, R>(values: R) -> Vec<T>
where
T: Clone + Ord,
R: AsRef<Vec<T>>,
{
let values: &Vec<T> = values.as_ref();
// Clone all elements
l... | }
(indexer, sorted)
}
/// Sort values by key returning sorted key and values
pub fn sort_by<T, U>(keys: &Vec<T>, values: &Vec<U>) -> (Vec<T>, Vec<U>)
where
T: Clone + Ord,
U: Clone,
{
let mut map: BTreeMap<T, Vec<U>> = BTreeMap::new();
for (k, v) in... | sorted.push(k.clone());
indexer.push(loc);
} | random_line_split |
sort.rs | use std::collections::BTreeMap;
use std::convert::AsRef;
pub struct Sorter;
// ToDo: merge with Indexing?
impl Sorter {
pub fn sort<T, R>(values: R) -> Vec<T>
where
T: Clone + Ord,
R: AsRef<Vec<T>>,
{
let values: &Vec<T> = values.as_ref();
// Clone all elements
l... | () {
let (indexer, sorted) = Sorter::argsort(&Vec::<i64>::new());
assert_eq!(indexer, vec![]);
assert_eq!(sorted, vec![]);
}
#[test]
fn test_argsort_int() {
let (indexer, sorted) = Sorter::argsort(&vec![2, 2, 2, 3, 3]);
assert_eq!(indexer, vec![0, 1, 2, 3, 4]);
... | test_argsort_empty | identifier_name |
harnesses.client.controller.js | 'use strict';
// Harnesses controller
angular.module('harnesses').controller('HarnessesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Harnesses',
function ($scope, $stateParams, $location, Authentication, Harnesses) {
$scope.authentication = Authentication;
// Create new Harness
... | else {
$scope.harness.$remove(function () {
$location.path('harnesses');
});
}
};
// Update existing Harness
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'harnessForm');
... | {
harness.$remove();
for (var i in $scope.harnesses) {
if ($scope.harnesses[i] === harness) {
$scope.harnesses.splice(i, 1);
}
}
} | conditional_block |
harnesses.client.controller.js | 'use strict';
// Harnesses controller
angular.module('harnesses').controller('HarnessesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Harnesses',
function ($scope, $stateParams, $location, Authentication, Harnesses) {
$scope.authentication = Authentication;
// Create new Harness
... | }
return capitalized;
}
modelCtrl.$parsers.push(capitalize);
capitalize(scope[attrs.ngModel]); // capitalize initial value
}
};
})
.filter('makeCaps',function(){
return function(input){
var capsInput = input.split(' '),
newInput = [];
angular... | modelCtrl.$setViewValue(capitalized);
modelCtrl.$render(); | random_line_split |
infer_util_test.py | # Copyright 2022 The Magenta 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | tf.test.main() | conditional_block | |
infer_util_test.py | # Copyright 2022 The Magenta 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | from __future__ import print_function
from magenta.models.onsets_frames_transcription import infer_util
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
class InferUtilTest(tf.test.TestCase):
def testProbsToPianorollViterbi(self):
frame_probs = np.array([[0.2, 0.1], [0.5, 0.1], ... | """Tests for metrics."""
from __future__ import absolute_import
from __future__ import division | random_line_split |
infer_util_test.py | # Copyright 2022 The Magenta 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | (self):
frame_probs = np.array([[0.2, 0.1], [0.5, 0.1], [0.5, 0.1], [0.8, 0.1]])
onset_probs = np.array([[0.1, 0.1], [0.1, 0.1], [0.9, 0.1], [0.1, 0.1]])
pianoroll = infer_util.probs_to_pianoroll_viterbi(frame_probs, onset_probs)
np.testing.assert_array_equal(
[[False, False], [False, False], [T... | testProbsToPianorollViterbi | identifier_name |
infer_util_test.py | # Copyright 2022 The Magenta 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
if __name__ == '__main__':
tf.test.main()
| frame_probs = np.array([[0.2, 0.1], [0.5, 0.1], [0.5, 0.1], [0.8, 0.1]])
onset_probs = np.array([[0.1, 0.1], [0.1, 0.1], [0.9, 0.1], [0.1, 0.1]])
pianoroll = infer_util.probs_to_pianoroll_viterbi(frame_probs, onset_probs)
np.testing.assert_array_equal(
[[False, False], [False, False], [True, False],... | identifier_body |
MessageWindow.py | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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 2
# of the License, or (at your option) ... | ():
global MessageWindow, PortraitWindow, ActionsWindow, OptionsWindow, MessageTA
Expand = GemRB.GetMessageWindowSize() & (GS_DIALOGMASK|GS_DIALOG)
hideflags = GemRB.HideGUI ()
if Expand:
GemRB.SetVar ("MessageWindow", MessageWindow.ID)
GemRB.SetVar ("PortraitWindow", -1)
GemRB.SetVar ("ActionsWindow", -1)... | UpdateControlStatus | identifier_name |
MessageWindow.py | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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 2
# of the License, or (at your option) ... | GUICommon.GameControl.SetStatus(IE_GUI_CONTROL_FOCUSED)
if hideflags:
GemRB.UnhideGUI ()
| global MessageWindow, PortraitWindow, ActionsWindow, OptionsWindow, MessageTA
Expand = GemRB.GetMessageWindowSize() & (GS_DIALOGMASK|GS_DIALOG)
hideflags = GemRB.HideGUI ()
if Expand:
GemRB.SetVar ("MessageWindow", MessageWindow.ID)
GemRB.SetVar ("PortraitWindow", -1)
GemRB.SetVar ("ActionsWindow", -1)
Gem... | identifier_body |
MessageWindow.py | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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 2
# of the License, or (at your option) ... | # GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# MessageWindow.py - scripts and GUI for main (walk) win... | random_line_split | |
MessageWindow.py | # -*-python-*-
# GemRB - Infinity Engine Emulator
# Copyright (C) 2003 The GemRB Project
#
# 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 2
# of the License, or (at your option) ... |
else:
GemRB.SetVar ("MessageWindow", -1)
GemRB.SetVar ("PortraitWindow", PortraitWindow.ID)
GemRB.SetVar ("ActionsWindow", ActionsWindow.ID)
GemRB.SetVar ("OptionsWindow", OptionsWindow.ID)
GUICommon.GameControl.SetStatus(IE_GUI_CONTROL_FOCUSED)
if hideflags:
GemRB.UnhideGUI ()
| GemRB.SetVar ("MessageWindow", MessageWindow.ID)
GemRB.SetVar ("PortraitWindow", -1)
GemRB.SetVar ("ActionsWindow", -1)
GemRB.SetVar ("OptionsWindow", -1)
MessageTA = GUIClasses.GTextArea(MessageWindow.ID, GemRB.GetVar ("MessageTextArea"))
MessageTA.SetStatus (IE_GUI_CONTROL_FOCUSED)
Label = MessageWindo... | conditional_block |
letter_frequency.rs | // http://rosettacode.org/wiki/Letter_frequency
#![cfg_attr(not(test), feature(io))]
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::{BufReader, Read};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
fn count_chars<T>(chars: T) -> HashMap<char, usize>
... | for letter in chars {
match map.entry(letter) {
Vacant(entry) => { entry.insert(1); },
Occupied(mut entry) => { *entry.get_mut() += 1; }
};
}
map
}
#[cfg(not(test))]
fn main() {
let file = File::open("resources/unixdict.txt").unwrap();
let reader = BufReader:... | {
let mut map: HashMap<char, usize> = HashMap::new(); | random_line_split |
letter_frequency.rs | // http://rosettacode.org/wiki/Letter_frequency
#![cfg_attr(not(test), feature(io))]
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::{BufReader, Read};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
fn count_chars<T>(chars: T) -> HashMap<char, usize>
... | () {
let map = count_chars("aaaabbbbc".chars());
assert!(map.len() == 3);
assert!(map[&'a'] == 4);
assert!(map[&'b'] == 4);
assert!(map[&'c'] == 1);
}
| test_basic | identifier_name |
letter_frequency.rs | // http://rosettacode.org/wiki/Letter_frequency
#![cfg_attr(not(test), feature(io))]
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::{BufReader, Read};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
fn count_chars<T>(chars: T) -> HashMap<char, usize>
... |
#[cfg(not(test))]
fn main() {
let file = File::open("resources/unixdict.txt").unwrap();
let reader = BufReader::new(file);
println!("{:?}", count_chars(reader.chars().map(|c| c.unwrap())));
}
#[test]
fn test_empty() {
let map = count_chars("".chars());
assert!(map.len() == 0);
}
#[test]
fn test... | {
let mut map: HashMap<char, usize> = HashMap::new();
for letter in chars {
match map.entry(letter) {
Vacant(entry) => { entry.insert(1); },
Occupied(mut entry) => { *entry.get_mut() += 1; }
};
}
map
} | identifier_body |
letter_frequency.rs | // http://rosettacode.org/wiki/Letter_frequency
#![cfg_attr(not(test), feature(io))]
#[cfg(not(test))]
use std::fs::File;
#[cfg(not(test))]
use std::io::{BufReader, Read};
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
fn count_chars<T>(chars: T) -> HashMap<char, usize>
... | ,
Occupied(mut entry) => { *entry.get_mut() += 1; }
};
}
map
}
#[cfg(not(test))]
fn main() {
let file = File::open("resources/unixdict.txt").unwrap();
let reader = BufReader::new(file);
println!("{:?}", count_chars(reader.chars().map(|c| c.unwrap())));
}
#[test]
fn test_empty(... | { entry.insert(1); } | conditional_block |
simple_earley.rs | use bongo::grammar::{
build, BaseElementTypes, Elem, Grammar, NonTerminal, ProdElement, Terminal,
};
use bongo::parsers::earley::parse;
use bongo::parsers::{tree::TreeOwner, Token};
use bongo::start_grammar::wrap_grammar_with_start;
use bongo::utils::Name;
fn main() | ProdElement::new_with_name(
Name::new("contents"),
Elem::NonTerm(a_nt.clone()),
),
ProdElement::new_empty(Elem::Term(rp_t.clone())),
],
);
});
})
.unwrap();
let g = wrap_grammar_with_start(g).unwrap();
eprintln!("Grammar: {}", g.to_pretty... | {
let a_nt = NonTerminal::new("a");
let lp_t = Terminal::new("LPAREN");
let rp_t = Terminal::new("RPAREN");
let v_t = Terminal::new("VALUE");
let g: Grammar<BaseElementTypes> = build(&a_nt, |b| {
b.add_rule(&a_nt, |br| {
br.add_prod_with_elems(
&Name::new("value"),
(),
vec![P... | identifier_body |
simple_earley.rs | use bongo::grammar::{
build, BaseElementTypes, Elem, Grammar, NonTerminal, ProdElement, Terminal,
};
use bongo::parsers::earley::parse;
use bongo::parsers::{tree::TreeOwner, Token};
use bongo::start_grammar::wrap_grammar_with_start;
use bongo::utils::Name;
fn main() {
let a_nt = NonTerminal::new("a");
let lp_t =... | )
.add_prod_with_elems(
&Name::new("parens"),
(),
vec![
ProdElement::new_empty(Elem::Term(lp_t.clone())),
ProdElement::new_with_name(
Name::new("contents"),
Elem::NonTerm(a_nt.clone()),
),
ProdElement::new_empty(Elem::Te... | Elem::Term(v_t.clone()),
)], | random_line_split |
simple_earley.rs | use bongo::grammar::{
build, BaseElementTypes, Elem, Grammar, NonTerminal, ProdElement, Terminal,
};
use bongo::parsers::earley::parse;
use bongo::parsers::{tree::TreeOwner, Token};
use bongo::start_grammar::wrap_grammar_with_start;
use bongo::utils::Name;
fn | () {
let a_nt = NonTerminal::new("a");
let lp_t = Terminal::new("LPAREN");
let rp_t = Terminal::new("RPAREN");
let v_t = Terminal::new("VALUE");
let g: Grammar<BaseElementTypes> = build(&a_nt, |b| {
b.add_rule(&a_nt, |br| {
br.add_prod_with_elems(
&Name::new("value"),
(),
vec... | main | identifier_name |
main.rs | fn main() {
let s1 = gives_ownership(); // gives_ownership 将返回值
// 转移给 s1
let s2 = String::from("hello"); // s2 进入作用域
let s3 = takes_and_gives_back(s2); // s2 被移动到
// takes_and_gives_back 中,
... | identifier_body | ||
main.rs | fn main() {
let s1 = gives_ownership(); // gives_ownership 将返回值
// 转移给 s1
let s2 = String::from("hello"); // s2 进入作用域
let s3 = takes_and_gives_back(s2); // s2 被移动到
// takes_and_gives_back 中,
... | identifier_name | ||
main.rs | fn main() {
let s1 = gives_ownership(); // gives_ownership 将返回值
// 转移给 s1
let s2 = String::from("hello"); // s2 进入作用域
let s3 = takes_and_gives_back(s2); // s2 被移动到
// takes_and_gives_back 中,
... | let some_string = String::from("yours"); // some_string 进入作用域.
some_string // 返回 some_string
// 并移出给调用的函数
//
}
// takes_and_gives_back 将传入字符串并返回该值
fn takes_and_gives_back(a_string: String) ... |
fn gives_ownership() -> String { // gives_ownership 会将
// 返回值移动给
// 调用它的函数
| random_line_split |
lib.rs | //! Nursery for slog-rs
//!
//! This crate is forever unstable, and contains things that
//! at a given moment are useful but not final.
#![warn(missing_docs)]
extern crate slog;
use slog::*;
use std::result;
/// `Drain` that switches destination of error
///
/// Logs everything to drain `D1`, but in case of it repo... | /// Create `Failover`
pub fn new(drain1: D1, drain2: D2) -> Self {
Failover {
drain1: drain1,
drain2: drain2,
}
}
}
impl<D1, D2, E2, O> Drain for Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
type Ok = O;
type Err = D2::Err;
... | random_line_split | |
lib.rs | //! Nursery for slog-rs
//!
//! This crate is forever unstable, and contains things that
//! at a given moment are useful but not final.
#![warn(missing_docs)]
extern crate slog;
use slog::*;
use std::result;
/// `Drain` that switches destination of error
///
/// Logs everything to drain `D1`, but in case of it repo... | <D1: Drain, D2: Drain>
{
drain1: D1,
drain2: D2,
}
impl<D1: Drain, D2: Drain, O> Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
/// Create `Failover`
pub fn new(drain1: D1, drain2: D2) -> Self {
Failover {
drain1: drain1,
drain2: drain2,
... | Failover | identifier_name |
lib.rs | //! Nursery for slog-rs
//!
//! This crate is forever unstable, and contains things that
//! at a given moment are useful but not final.
#![warn(missing_docs)]
extern crate slog;
use slog::*;
use std::result;
/// `Drain` that switches destination of error
///
/// Logs everything to drain `D1`, but in case of it repo... |
}
/// Failover logging to secondary drain on primary's failure
///
/// Create `Failover` drain
pub fn failover<D1: Drain, D2: Drain, O>(d1: D1, d2: D2) -> Failover<D1, D2>
where
D1 : Drain<Ok = O>,
D2 : Drain<Ok = O>,
{
Failover::new(d1, d2)
}
| {
match self.drain1.log(info, logger_values) {
Ok(ok) => Ok(ok),
Err(_) => self.drain2.log(info, logger_values),
}
} | identifier_body |
initdatabase.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import mysql.connector
import time
import datetime
conn = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="drupal")
cann = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="content_delivery_weather") |
cursor.execute("""SELECT uid, mail FROM users""")
rows = cursor.fetchall()
for row in rows:
if row[0] != 0:
print('{0} : {1} '.format(row[0], row[1]))
#print('UPDATE new_v4_users_probes_edit SET email = {0} WHERE uid = {1}'.format(row[1], row[0]))
cursar.execute("""UPDATE new_v4_users_probes_ed... | cursor = conn.cursor()
cursar = cann.cursor() | random_line_split |
initdatabase.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import mysql.connector
import time
import datetime
conn = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="drupal")
cann = mysql.connector.connect(host="localhost",user="spike",password="valentine", database="content_delivery_weather")... |
cursar.execute("""SELECT probename, probeid FROM new_v4_sonde""")
rows = cursar.fetchall()
for row in rows:
cursar.execute("""SHOW TABLES LIKE %s""",("%" + row[0] + "%",))
rowsbis = cursar.fetchall()
for rowbis in rowsbis:
result = rowbis[0].split("_")
month = 1 + int(result[4])
s = "01/" ... | if row[0] != 0:
print('{0} : {1} '.format(row[0], row[1]))
#print('UPDATE new_v4_users_probes_edit SET email = {0} WHERE uid = {1}'.format(row[1], row[0]))
cursar.execute("""UPDATE new_v4_users_probes_edit SET email = %s WHERE userid = %s""",(row[1], row[0])) | conditional_block |
PILTest.py | '''
Created on May 21, 2016
@author: zlp
'''
# import Image
hello = 100
class PILTest(object):
hello = 200
def __init__(self, name):
self._name = name
def printName(self):
print self._name
def printHelloInClass(self):
print self.hello
class2 = PILTest... | doctest.testmod()
class Test1(object):
name = 'haha'
def __init__(self,name2):
self.name2 = name2
t1 = Test1('xiaozhu')
t2 = Test1('xiaoYu')
# print t1.name
# print t1.name2
# print t2.name
# print t2.name2
# t1.name = 'HEIHEI!'
# print t1.name
# print t2.name
print 'T1\'s name is ',Test1.name | import doctest | random_line_split |
PILTest.py | '''
Created on May 21, 2016
@author: zlp
'''
# import Image
hello = 100
class PILTest(object):
hello = 200
def __init__(self, name):
self._name = name
def printName(self):
|
def printHelloInClass(self):
print self.hello
class2 = PILTest('hahah')
# print 'Print hello value: %d' % hello
# class2.printHelloInClass()
# def make_counter():
# count = 0
# def counter():
# nonlocal count
# count += 1
# return count
# return counter
#... | print self._name | identifier_body |
PILTest.py | '''
Created on May 21, 2016
@author: zlp
'''
# import Image
hello = 100
class PILTest(object):
hello = 200
def __init__(self, name):
self._name = name
def printName(self):
print self._name
def printHelloInClass(self):
print self.hello
class2 = PILTest... | (self,max):
self.__max = max
def __iter__(self):
self.a = 0
self.b = 1
return self
def next(self):
result = self.a
if result > self.__max:
raise StopIteration
self.a, self.b = self.b, self.a+self.b
return result
#... | __init__ | identifier_name |
PILTest.py | '''
Created on May 21, 2016
@author: zlp
'''
# import Image
hello = 100
class PILTest(object):
hello = 200
def __init__(self, name):
self._name = name
def printName(self):
print self._name
def printHelloInClass(self):
print self.hello
class2 = PILTest... |
# print k,v
def outside(func):
def wrapper(*args, **kw):
print 'Outside sheel'
return func(*args,**kw)
return wrapper
@outside
def log(func):
def wrapper(*args, **kw):
print 'Hello'
return func(*args, **kw)
return wrapper
@log
def simplePrint(str1):
... | pass | conditional_block |
usuario.js | var direccion = '/api/Usuarios/' + sessionStorage.userId + '?access_token=' + sessionStorage.userToken;
var nombre;
/* Eliminar los valores de sesión */
function e | ){
sessionStorage.removeItem("userToken");
sessionStorage.removeItem("userId");
sessionStorage.removeItem("userTtl");
sessionStorage.removeItem("userCreated");
sessionStorage.removeItem("userNombre");
sessionStorage.removeItem("userApellidos");
sessionStorage.removeItem("userDni");
sessionStorage.removeItem("u... | liminarStorage( | identifier_name |
usuario.js | var direccion = '/api/Usuarios/' + sessionStorage.userId + '?access_token=' + sessionStorage.userToken;
var nombre;
/* Eliminar los valores de sesión */
function eliminarStorage(){
sessionStorage.removeItem("userToken");
sessionStorage.removeItem("userId");
sessionStorage.removeItem("userTtl");
sessionStorage.rem... | $("#botonPerfilAdmin").html(nombre);
$('#mensajeInicio').html("BIENVENIDO " + sessionStorage.userNombre + " A LA APLICACIÓN DE GESTIÓN DEL VIAJE DE ESTUDIOS");
}else{
console.log("Error Inicio");
eliminarStorage();
window.location.href = "../index.html";
}
}).fail(function (xhr){
console.l... |
$.ajax({
async: true,
dataType: 'json',
data: datos,
method: metodo,
url: url,
}).done(function (respuesta){
if(typeof(respuesta.id) !== undefined){
sessionStorage.userNombre = respuesta.Nombre;
sessionStorage.userApellidos = respuesta.Apellidos;
sessionStorage.userDni = respuesta.DNI;
s... | identifier_body |
usuario.js | var direccion = '/api/Usuarios/' + sessionStorage.userId + '?access_token=' + sessionStorage.userToken;
var nombre;
/* Eliminar los valores de sesión */
function eliminarStorage(){
sessionStorage.removeItem("userToken");
sessionStorage.removeItem("userId");
sessionStorage.removeItem("userTtl");
sessionStorage.rem... | }) | random_line_split | |
usuario.js | var direccion = '/api/Usuarios/' + sessionStorage.userId + '?access_token=' + sessionStorage.userToken;
var nombre;
/* Eliminar los valores de sesión */
function eliminarStorage(){
sessionStorage.removeItem("userToken");
sessionStorage.removeItem("userId");
sessionStorage.removeItem("userTtl");
sessionStorage.rem... | ).fail(function (xhr){
console.log("Error Inicio");
eliminarStorage();
window.location.href = "../index.html";
});
}
$(document).ready(function() {
$("#botonSalir").click(function(){
eliminarStorage();
window.location.href = "../index.html";
});
$("#botonPerfil").click(function(){
window.locat... | console.log("Error Inicio");
eliminarStorage();
window.location.href = "../index.html";
}
} | conditional_block |
collision-resolver.ts | import { Enemy } from '../enemies/enemy';
import { Coin } from '../levels/coin';
import { Player } from '../player/player';
import {Rectangle} from '../core/geometry/rectangle';
import {DetailedCollisionState} from '../core/geometry/detailed-collision-state';
export class CollisionResolver {
| () {}
checkCollision(currentSectors: any, player: Player) {
if (currentSectors.length > 0) {
this.handlePlayerCoinCollision(player, currentSectors[0].coins);
currentSectors.forEach(sector => {
this.handlePlayerEnemyCollision(player, sector.enemies);
});
}
}
private handlePlaye... | constructor | identifier_name |
collision-resolver.ts | import { Enemy } from '../enemies/enemy';
import { Coin } from '../levels/coin';
import { Player } from '../player/player';
import {Rectangle} from '../core/geometry/rectangle';
import {DetailedCollisionState} from '../core/geometry/detailed-collision-state';
export class CollisionResolver {
constructor() {}
che... |
private getEnvironmentCollisionState(player: Player, collisionBox) {
const depth = player.collisionBox.getIntersectionDepth(collisionBox);
const collisionState = new DetailedCollisionState();
if (!depth.isZero()) {
const isVerticalCollision = Math.abs(depth.y) < Math.abs(depth.x);
const isH... | {
player.collisionState.clear();
levelGeometry.forEach(collisionItem => {
const newCollisionState = this.getEnvironmentCollisionState(player, collisionItem);
player.collisionState.updateState(newCollisionState);
});
} | identifier_body |
collision-resolver.ts | import { Enemy } from '../enemies/enemy';
import { Coin } from '../levels/coin';
import { Player } from '../player/player';
import {Rectangle} from '../core/geometry/rectangle';
import {DetailedCollisionState} from '../core/geometry/detailed-collision-state';
export class CollisionResolver {
constructor() {}
che... |
});
}
handlePlayerLevelGeometryCollision(player: Player, levelGeometry) {
player.collisionState.clear();
levelGeometry.forEach(collisionItem => {
const newCollisionState = this.getEnvironmentCollisionState(player, collisionItem);
player.collisionState.updateState(newCollisionState);
}... | {
player.takeDamage();
} | conditional_block |
collision-resolver.ts | import { Enemy } from '../enemies/enemy';
import { Coin } from '../levels/coin';
import { Player } from '../player/player';
import {Rectangle} from '../core/geometry/rectangle';
import {DetailedCollisionState} from '../core/geometry/detailed-collision-state';
export class CollisionResolver {
constructor() {}
che... | const newCollisionState = this.getEnvironmentCollisionState(player, collisionItem);
player.collisionState.updateState(newCollisionState);
});
}
private getEnvironmentCollisionState(player: Player, collisionBox) {
const depth = player.collisionBox.getIntersectionDepth(collisionBox);
const co... | handlePlayerLevelGeometryCollision(player: Player, levelGeometry) {
player.collisionState.clear();
levelGeometry.forEach(collisionItem => { | random_line_split |
search_bar.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/index';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.onInputChange = this.onIn... |
render() {
return(
<form onSubmit={this.onFormSubmit} className="input-group">
<input
placeholder="Give a five-day forecast in your favorite cities"
className="form-control"
value={this.state.term}
onChange={this.onInputChange}
/>
<span class... | {
event.preventDefault();
//We need to fetch data
this.props.fetchWeather(this.state.term);
//Reset the search bar
this.setState({ term: '' });
} | identifier_body |
search_bar.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/index';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.onInputChange = this.onIn... | event.preventDefault();
//We need to fetch data
this.props.fetchWeather(this.state.term);
//Reset the search bar
this.setState({ term: '' });
}
render() {
return(
<form onSubmit={this.onFormSubmit} className="input-group">
<input
placeholder="Give a five-day forecas... | random_line_split | |
search_bar.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/index';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.onInputChange = this.onIn... | () {
return(
<form onSubmit={this.onFormSubmit} className="input-group">
<input
placeholder="Give a five-day forecast in your favorite cities"
className="form-control"
value={this.state.term}
onChange={this.onInputChange}
/>
<span className="inpu... | render | identifier_name |
content.py | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _, pgettext_lazy
class ContentBase(models.Model):
"""
Base class for models that share content attributes
The attributes added by this mixin are ``title``, ``description``,
``content`` and ``is_visible`... | (self, *args, **kwargs):
""" Save the object to the database """
super(self.__class__, self).save(*args, **kwargs)
| save | identifier_name |
content.py | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _, pgettext_lazy
class ContentBase(models.Model):
"""
Base class for models that share content attributes
The attributes added by this mixin are ``title``, ``description``,
``content`` and ``is_visible`... |
def save(self, *args, **kwargs):
""" Save the object to the database """
super(self.__class__, self).save(*args, **kwargs)
| abstract = True | identifier_body |
content.py | # coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _, pgettext_lazy
class ContentBase(models.Model):
"""
Base class for models that share content attributes | The attributes added by this mixin are ``title``, ``description``,
``content`` and ``is_visible``.
Attributes:
:is_visible: whether the content should be displayed by normal users
:title: title of the content, at most 192 characters
:description: most content objects have a descript... | random_line_split | |
oLanguage.oPaginate.js | // DATA_TEMPLATE: js_data
oTest.fnStart( "oLanguage.oPaginate" );
/* Note that the paging language information only has relevence in full numbers */
$(document).ready( function () {
/* Check the default */
var oTable = $('#example').dataTable( {
"aaData": gaaData,
"sPaginationType": "full_numbers"
} ... | "aaData": gaaData,
"sPaginationType": "full_numbers",
"oLanguage": {
"oPaginate": {
"sFirst": "unit1",
"sPrevious": "test2",
"sNext": "unit3",
"sLast": "test4"
}
}
} );
oSettings = oTable.fnSettings();
},
function () {
var bReturn =... | oSession.fnRestore();
oTable = $('#example').dataTable( {
| random_line_split |
deriving-cmp-generic-struct-enum.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// no-pretty-expanded FIXME #15189
// pretty-expanded FIXME #23616
#[derive(PartialEq, Eq, PartialOrd, Ord)]
enum ES<T> {
ES1 { x: T },
ES2 { x: T, y: T }
}
pub fn main() {
let (es11, es12, es21, es22) ... | // 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 http://opensource.org/licenses/MIT>, at your | random_line_split |
deriving-cmp-generic-struct-enum.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 eq = i == j;
let (lt, le) = (i < j, i <= j);
let (gt, ge) = (i > j, i >= j);
// PartialEq
assert_eq!(*es1 == *es2, eq);
assert_eq!(*es1 != *es2, !eq);
// PartialOrd
assert_eq!(*es1 < *es2, lt);
assert_eq!(*... | {
let (es11, es12, es21, es22) = (ES::ES1 {
x: 1
}, ES::ES1 {
x: 2
}, ES::ES2 {
x: 1,
y: 1
}, ES::ES2 {
x: 1,
y: 2
});
// in order for both PartialOrd and Ord
let ess = [es11, es12, es21, es22];
for (i, es1) in ess.iter().enumerate() {
... | identifier_body |
deriving-cmp-generic-struct-enum.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 (es11, es12, es21, es22) = (ES::ES1 {
x: 1
}, ES::ES1 {
x: 2
}, ES::ES2 {
x: 1,
y: 1
}, ES::ES2 {
x: 1,
y: 2
});
// in order for both PartialOrd and Ord
let ess = [es11, es12, es21, es22];
for (i, es1) in ess.iter().enumerate() {... | main | identifier_name |
dircmpdel.py | import os
import errno
def delete_file(file_name, dry=False):
if dry:
print(' DRY DELETED: {}'.format(file_name))
else:
os.remove(file_name)
try:
dirname = os.path.dirname(file_name)
os.rmdir(dirname)
print(' DELETED DIR: {}'.format(dirname))
... | import argparse
parser = argparse.ArgumentParser(
description='Utility for deleting duplicate files found by dircmp'
)
parser.add_argument('file')
parser.add_argument('--no-prompt',
action='store_false', default=True, dest='prompt')
parser.add_argument('-d', '--dry'... | conditional_block | |
dircmpdel.py | import os
import errno
def | (file_name, dry=False):
if dry:
print(' DRY DELETED: {}'.format(file_name))
else:
os.remove(file_name)
try:
dirname = os.path.dirname(file_name)
os.rmdir(dirname)
print(' DELETED DIR: {}'.format(dirname))
except OSError as ex:
... | delete_file | identifier_name |
dircmpdel.py | import os
import errno
def delete_file(file_name, dry=False):
if dry:
print(' DRY DELETED: {}'.format(file_name))
else:
os.remove(file_name)
try:
dirname = os.path.dirname(file_name)
os.rmdir(dirname)
print(' DELETED DIR: {}'.format(dirname))
... | checked_proper_cwd = True
print('Deleting duplicates of {}'.format(file_name))
else:
if prompt:
while True:
resp = input(' Delete {}? '.format(file_name))
resp = resp.lower()
... | ''.format(file_name)) | random_line_split |
dircmpdel.py | import os
import errno
def delete_file(file_name, dry=False):
|
def run_dircmpdel(dircmp_file, prompt=True, dry=False):
"""
Parse dircmp file for groups of file names to be deleted.
"""
with open(dircmp_file) as fp:
lines = fp.read()
groups = lines.strip().split('\n\n')
print('Found {} duplicate groups'.format(len(groups)))
groups = (group.sp... | if dry:
print(' DRY DELETED: {}'.format(file_name))
else:
os.remove(file_name)
try:
dirname = os.path.dirname(file_name)
os.rmdir(dirname)
print(' DELETED DIR: {}'.format(dirname))
except OSError as ex:
if ex.errno != errno.ENOTEM... | identifier_body |
expr-if-fail.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 ... | () { let x = if false { fail!() } else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
let x = if true { 10 } else { fail!() };
assert!((x == 10));
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail!() } else { 10 };
assert!((x == 10));
}
pub fn main() { test_if_fail(); test_el... | test_if_fail | identifier_name |
expr-if-fail.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 ... |
fn test_else_fail() {
let x = if true { 10 } else { fail!() };
assert!((x == 10));
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail!() } else { 10 };
assert!((x == 10));
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
| { let x = if false { fail!() } else { 10 }; assert!((x == 10)); } | identifier_body |
expr-if-fail.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 | // option. This file may not be copied, modified, or distributed
// except according to those terms.
fn test_if_fail() { let x = if false { fail!() } else { 10 }; assert!((x == 10)); }
fn test_else_fail() {
let x = if true { 10 } else { fail!() };
assert!((x == 10));
}
fn test_elseif_fail() {
let x = if ... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
expr-if-fail.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 ... | else { fail!() };
assert!((x == 10));
}
fn test_elseif_fail() {
let x = if false { 0 } else if false { fail!() } else { 10 };
assert!((x == 10));
}
pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); }
| { 10 } | conditional_block |
gmpich2.py | ##
# Copyright 2012-2017 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... |
class Gmpich2(GccToolchain, Mpich2):
"""Compiler toolchain with GCC and MPICH2."""
NAME = 'gmpich2'
SUBTOOLCHAIN = GccToolchain.NAME | random_line_split | |
gmpich2.py | ##
# Copyright 2012-2017 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | """Compiler toolchain with GCC and MPICH2."""
NAME = 'gmpich2'
SUBTOOLCHAIN = GccToolchain.NAME | identifier_body | |
gmpich2.py | ##
# Copyright 2012-2017 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be),
# Flemish Research Foundation (F... | (GccToolchain, Mpich2):
"""Compiler toolchain with GCC and MPICH2."""
NAME = 'gmpich2'
SUBTOOLCHAIN = GccToolchain.NAME
| Gmpich2 | identifier_name |
closure-syntax.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T>() {}
trait Bar1 {}
impl Bar1 for proc() {}
trait Bar2 {}
impl Bar2 for proc(): Send {}
trait Bar3 {}
impl<'b> Bar3 for <'a>|&'a int|: 'b + Send -> &'a int {}
trait Bar4 {}
impl Bar4 for proc<'a>(&'a int) -> &'a int {}
struct Foo<'a> {
a: ||: 'a,
b: ||: 'static,
c: <'b>||: 'a,
d: ||: 'a + Share,... | foo | identifier_name |
closure-syntax.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
struct Foo<'a> {
a: ||: 'a,
b: ||: 'static,
c: <'b>||: 'a,
d: ||: 'a + Share,
e: <'b>|int|: 'a + Share -> &'b f32,
f: proc(),
g: proc(): 'static + Share,
h: proc<'b>(int): Share -> &'b f32,
}
fn f<'a>(a: &'a int, f: <'b>|&'b int| -> &'b int) -> &'a int {
f(a)
}
fn g<'a>(a: &'a int... | random_line_split | |
closure-syntax.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
trait Bar1 {}
impl Bar1 for proc() {}
trait Bar2 {}
impl Bar2 for proc(): Send {}
trait Bar3 {}
impl<'b> Bar3 for <'a>|&'a int|: 'b + Send -> &'a int {}
trait Bar4 {}
impl Bar4 for proc<'a>(&'a int) -> &'a int {}
struct Foo<'a> {
a: ||: 'a,
b: ||: 'static,
c: <'b>||: 'a,
d: ||: 'a + Share,
e: ... | {} | identifier_body |
seqpeek_view.py | #
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 ... | # See the License for the specific language governing permissions and
# limitations under the License.
#
from builtins import map
from builtins import str
from builtins import object
from copy import deepcopy
import logging
from bq_data_access.v2.seqpeek.seqpeek_interpro import InterProDataProvider
logger = logging.... | random_line_split | |
seqpeek_view.py | #
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 ... |
return result
def filter_protein_domains(match_array):
return [m for m in match_array if m['dbname'] == PROTEIN_DOMAIN_DB]
def get_table_row_id(tumor_type):
return "seqpeek_row_{0}".format(tumor_type)
def build_seqpeek_regions(protein_data):
return [{
'type': 'exon',
'start': 0,
... | result['cohort_size'] = None | conditional_block |
seqpeek_view.py | #
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 ... |
# TODO remove if not needed
def clean_track_mutations(mutations_array):
retval = []
for mutation in mutations_array:
cleaned = deepcopy(mutation)
cleaned[COORDINATE_FIELD_NAME] = int(mutation[COORDINATE_FIELD_NAME])
retval.append(cleaned)
return retval
def sort_track_mutations(... | sample_locations = set()
for mutation in track['mutations']:
sample_locations.add(mutation[COORDINATE_FIELD_NAME])
return len(sample_locations) | identifier_body |
seqpeek_view.py | #
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 ... | (track):
sample_ids = set()
for mutation in track['mutations']:
sample_ids.add(mutation[SAMPLE_ID_FIELD_NAME])
return len(sample_ids)
def get_number_of_mutated_positions(track):
sample_locations = set()
for mutation in track['mutations']:
sample_locations.add(mutation[COORDINATE_F... | get_number_of_unique_samples | identifier_name |
test_floating_ip.py | # #!/usr/bin/env python
#
# Copyright 2016 Sungard Availability Services
# Copyright 2016 Red Hat
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apa... | def fake_get_fip_service():
return [{'router_id': 'e24f8a37-1bb7-49e4-833c-049bb21986d2',
'status': 'ACTIVE',
'tenant_id': '54a00c50ee4c4396b2f8dc220a2bed57',
'floating_network_id':
'f41f399e-d63e-47c6-9a19-21c4e4fbbba0',
... |
@staticmethod | random_line_split |
test_floating_ip.py | # #!/usr/bin/env python
#
# Copyright 2016 Sungard Availability Services
# Copyright 2016 Red Hat
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apa... | (self):
super(_BaseTestFloatingIPPollster, self).setUp()
self.manager = manager.AgentManager()
plugin_base._get_keystone = mock.Mock()
class TestFloatingIPPollster(_BaseTestFloatingIPPollster):
def setUp(self):
super(TestFloatingIPPollster, self).setUp()
self.pollster = fl... | setUp | identifier_name |
test_floating_ip.py | # #!/usr/bin/env python
#
# Copyright 2016 Sungard Availability Services
# Copyright 2016 Red Hat
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apa... |
@staticmethod
def fake_get_fip_service():
return [{'router_id': 'e24f8a37-1bb7-49e4-833c-049bb21986d2',
'status': 'ACTIVE',
'tenant_id': '54a00c50ee4c4396b2f8dc220a2bed57',
'floating_network_id':
'f41f399e-d63e-47c6-9a19-21c4e4fb... | super(TestFloatingIPPollster, self).setUp()
self.pollster = floatingip.FloatingIPPollster()
fake_fip = self.fake_get_fip_service()
self.useFixture(mockpatch.Patch('ceilometer.neutron_client.Client.'
'fip_get_all',
re... | identifier_body |
Main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2013-2016 Frantisek Uhrecky
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, includ... | from PyQt4 import QtGui
import sys
from MainWindow import MainWindow
import os
from LoginDialog import LoginDialog
import AppSettings
import TransController
import shutil
import time
def ifNotExCreate(directory):
"""
If does not exists dir, create it.
@param directory: directory to che... | from DbController import DbController | random_line_split |
Main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2013-2016 Frantisek Uhrecky
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, includ... | (directory):
"""
If does not exists dir, create it.
@param directory: directory to check and create
"""
if (not os.path.exists(AppSettings.decodePath(directory))):
# missing data dir
logging.info("creating dir: '%s'", directory)
os.makedirs(AppSettin... | ifNotExCreate | identifier_name |
Main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2013-2016 Frantisek Uhrecky
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, includ... |
def main():
app = QtGui.QApplication(sys.argv)
logging.info("Absolute app root: '%s'", AppSettings.APP_ABS_ROOT)
# set application icon
app.setWindowIcon(QtGui.QIcon(AppSettings.APP_ICON_PATH))
# create neccessary paths if missing
ifNotExCreate(AppSettings.TMP_PATH)
ifNo... | """
If does not exists dir, create it.
@param directory: directory to check and create
"""
if (not os.path.exists(AppSettings.decodePath(directory))):
# missing data dir
logging.info("creating dir: '%s'", directory)
os.makedirs(AppSettings.decodePath(dir... | identifier_body |
Main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2013-2016 Frantisek Uhrecky
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, includ... |
# first backup database
backup_file = AppSettings.BACKUP_PATH + time.strftime("%Y-%m-%dT%H:%M:%S_", time.localtime()) + os.path.basename(db_path)
logging.info("backup file: '%s'", backup_file)
shutil.copyfile(AppSettings.decodePath(db_path), AppSettings.decodePath(backup_file))... | os.remove(AppSettings.BACKUP_PATH + backups[i]) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.