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 |
|---|---|---|---|---|
glusterfs.py | GlusterFS'
VERSION = '1.3.0'
def __init__(self, execute=processutils.execute, *args, **kwargs):
self._remotefsclient = None
super(GlusterfsDriver, self).__init__(*args, **kwargs)
self.configuration.append_config_values(volume_opts)
root_helper = utils.get_root_helper()
s... |
@remotefs_drv.locked_volume_id_operation
def extend_volume(self, volume, size_gb):
volume_path = self.local_path(volume)
info = self._qemu_img_info(volume_path, volume['name'])
backing_fmt = info.file_format
if backing_fmt not in ['raw', 'qcow2']:
msg = _('Unrecog... | """Disallow connection from connector."""
pass | identifier_body |
page.js | import $ from 'jquery';
import _ from 'lodash';
import FontFaceObserver from 'fontfaceobserver';
import React from 'react';
import ReactDom from 'react-dom';
import { IndexLink } from 'react-router';
import ReactVTT from '../../common/components/ReactVTT';
import VideoTrack from '../../common/components/VideoTrack';
... | (props) {
super(props);
var track = this.fetchTrack();
var font = this.fetchFont();
this.state = {
track: track,
font: font,
isPlaying: false,
trackIsLoaded: !!track,
fontIsLoaded: false,
cues: {},
activeCue: null,
currentTime: 0
};
this.updateT... | constructor | identifier_name |
page.js | import $ from 'jquery';
import _ from 'lodash';
import FontFaceObserver from 'fontfaceobserver';
import React from 'react';
import ReactDom from 'react-dom';
import { IndexLink } from 'react-router';
import ReactVTT from '../../common/components/ReactVTT';
import VideoTrack from '../../common/components/VideoTrack';
... | return (
<div id="content" className={ styles.content }>
<style>
{ fontFace }
</style>
<IndexLink id="back" className={ styles.back } to="/"></IndexLink>
{ overlay }
</div>
);
}
return (
<div id="content" className={ styles.c... | if(this.isLoading()) { | random_line_split |
page.js | import $ from 'jquery';
import _ from 'lodash';
import FontFaceObserver from 'fontfaceobserver';
import React from 'react';
import ReactDom from 'react-dom';
import { IndexLink } from 'react-router';
import ReactVTT from '../../common/components/ReactVTT';
import VideoTrack from '../../common/components/VideoTrack';
... |
this.setState(updates);
// FIXME maybe avoid doing the above work by checking isPlaying earlier
if(updates.activeCue && this.state.isPlaying) {
ReactDom.render(<VideoTrack data={ ReactVTT.separate(this.state.activeCue) } currentTime={ this.state.currentTime } color={ this.state.font.color }/>, docu... | {
updates.activeCue = this.state.cues.activeCues[0];
} | conditional_block |
page.js | import $ from 'jquery';
import _ from 'lodash';
import FontFaceObserver from 'fontfaceobserver';
import React from 'react';
import ReactDom from 'react-dom';
import { IndexLink } from 'react-router';
import ReactVTT from '../../common/components/ReactVTT';
import VideoTrack from '../../common/components/VideoTrack';
... |
componentDidMount() {
var self = this;
var $document = $(document);
$document.on('keyup click touch', this.handleTogglePlay);
// wait for our font to load and then update when it has
// pretty hacky
var font = new FontFaceObserver(this.props.params.id);
font.load(null, 5000)
.then(... | {
this.initRecording();
} | identifier_body |
KmlTourFlyTo.js | define([
'../Core/BoundingSphere',
'../Core/combine',
'../Core/defined',
'../Core/EasingFunction'
], function(
BoundingSphere,
combine,
defined,
EasingFunction) {
'use strict';
/**
* @alias KmlTourFlyTo
* @constructor
... | (duration, flyToMode, view) {
this.type = 'KmlTourFlyTo';
this.blocking = true;
this.activeCamera = null;
this.activeCallback = null;
this.duration = duration;
this.view = view;
this.flyToMode = flyToMode;
}
/**
* Play this playlist entr... | KmlTourFlyTo | identifier_name |
KmlTourFlyTo.js | define([
'../Core/BoundingSphere',
'../Core/combine',
'../Core/defined',
'../Core/EasingFunction'
], function(
BoundingSphere,
combine,
defined,
EasingFunction) {
'use strict';
/**
* @alias KmlTourFlyTo
* @constructor
... |
/**
* Play this playlist entry
*
* @param {KmlTourFlyTo~DoneCallback} done function which will be called when playback ends
* @param {Camera} camera Cesium camera
* @param {Object} [cameraOptions] which will be merged with camera flyTo options. See {@link Camera#flyTo}
*/
... | {
this.type = 'KmlTourFlyTo';
this.blocking = true;
this.activeCamera = null;
this.activeCallback = null;
this.duration = duration;
this.view = view;
this.flyToMode = flyToMode;
} | identifier_body |
KmlTourFlyTo.js | define([
'../Core/BoundingSphere',
'../Core/combine',
'../Core/defined',
'../Core/EasingFunction'
], function(
BoundingSphere,
combine,
defined,
EasingFunction) {
'use strict';
/**
* @alias KmlTourFlyTo
* @constructor
... |
};
/**
* Returns options for {@link Camera#flyTo} or {@link Camera#flyToBoundingSphere}
* depends on this.view type.
*
* @param {Object} cameraOptions options to merge with generated. See {@link Camera#flyTo}
* @returns {Object} {@link Camera#flyTo} or {@link Camera#flyToBound... | {
this.activeCallback(true);
} | conditional_block |
KmlTourFlyTo.js | define([
'../Core/BoundingSphere',
'../Core/combine',
'../Core/defined',
'../Core/EasingFunction'
], function(
BoundingSphere,
combine,
defined,
EasingFunction) {
'use strict';
/**
* @alias KmlTourFlyTo
* @constructor
... | }
if (defined(cameraOptions)) {
options = combine(options, cameraOptions);
}
return options;
};
/**
* A function that will be executed when the flight completes.
* @callback KmlTourFlyTo~DoneCallback
*
* @param {Boolean} terminated tr... | options.offset = this.view.headingPitchRange;
| random_line_split |
init.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// @ignoreDep v8-profiler
import 'symbol-observable';
const isWarningEnabled = require('../utilities/config').isWarni... |
process.on('exit', exitHandler.bind(null, { cleanup: true }));
process.on('SIGINT', exitHandler.bind(null, { exit: true }));
process.on('uncaughtException', exitHandler.bind(null, { exit: true }));
}
resolve('@angular/cli', { basedir: process.cwd() },
function (error: Error, projectLocalCli: string) {
le... | {
if (options.cleanup) {
const cpuProfile = profiler.stopProfiling();
fs.writeFileSync(path.resolve(process.cwd(), process.env.NG_CLI_PROFILING) + '.cpuprofile',
JSON.stringify(cpuProfile));
}
if (options.exit) {
process.exit();
}
} | identifier_body |
init.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// @ignoreDep v8-profiler
import 'symbol-observable';
const isWarningEnabled = require('../utilities/config').isWarni... | (cwd?: string) {
cwd = cwd || process.cwd();
do {
const packageJsonPath = path.join(cwd, 'node_modules/@angular/cli/package.json');
if (fs.existsSync(packageJsonPath)) {
const content = fs.readFileSync(packageJsonPath, 'utf-8');
if (content) {
const json = JSON.parse(content);
i... | _fromPackageJson | identifier_name |
init.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// @ignoreDep v8-profiler
import 'symbol-observable';
const isWarningEnabled = require('../utilities/config').isWarni... | if (process.argv[2] !== 'completion') {
// eslint-disable-next-line no-console
console.log(warning);
} else {
// eslint-disable-next-line no-console
console.error(warning);
process.exit(1);
}
}
// No error implies a projectLocalCli... | version (${localVersion}). The local Angular CLI version is used.
To disable this warning use "ng set --global warnings.versionMismatch=false".
`);
// Don't show warning colorised on `ng completion` | random_line_split |
init.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// @ignoreDep v8-profiler
import 'symbol-observable';
const isWarningEnabled = require('../utilities/config').isWarni... |
}
}
// Check the parent.
cwd = path.dirname(cwd);
} while (cwd != path.dirname(cwd));
return null;
}
// Check if we need to profile this CLI run.
if (process.env['NG_CLI_PROFILING']) {
const profiler = require('v8-profiler');
profiler.startProfiling();
function exitHandler(options: any,... | {
return new SemVer(json['version']);
} | conditional_block |
fullscreen.rs | mod support;
use glutin::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::monitor::{MonitorHandle, VideoMode};
use glutin::window::{Fullscreen, WindowBuilder};
use std::io::{stdin, stdout, Write};
fn main() |
let wb = WindowBuilder::new().with_title("Hello world!").with_fullscreen(fullscreen.clone());
let windowed_context = glutin::ContextBuilder::new().build_windowed(wb, &el).unwrap();
let windowed_context = unsafe { windowed_context.make_current().unwrap() };
let gl = support::load(&windowed_context.con... | {
let el = EventLoop::new();
print!("Please choose the fullscreen mode: (1) exclusive, (2) borderless: ");
stdout().flush().unwrap();
let mut num = String::new();
stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let fullscreen = Some... | identifier_body |
fullscreen.rs | mod support;
use glutin::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::monitor::{MonitorHandle, VideoMode};
use glutin::window::{Fullscreen, WindowBuilder};
use std::io::{stdin, stdout, Write};
fn main() {
let el = EventLoop... | println!("Using {:?}", monitor.name());
monitor
}
fn prompt_for_video_mode(monitor: &MonitorHandle) -> VideoMode {
for (i, video_mode) in monitor.video_modes().enumerate() {
println!("Video mode #{}: {}", i, video_mode);
}
print!("Please write the number of the video mode to use: ");
... | let monitor = el.available_monitors().nth(num).expect("Please enter a valid ID");
| random_line_split |
fullscreen.rs | mod support;
use glutin::event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::monitor::{MonitorHandle, VideoMode};
use glutin::window::{Fullscreen, WindowBuilder};
use std::io::{stdin, stdout, Write};
fn main() {
let el = EventLoop... | (monitor: &MonitorHandle) -> VideoMode {
for (i, video_mode) in monitor.video_modes().enumerate() {
println!("Video mode #{}: {}", i, video_mode);
}
print!("Please write the number of the video mode to use: ");
stdout().flush().unwrap();
let mut num = String::new();
stdin().read_line(&... | prompt_for_video_mode | identifier_name |
mysql.rs | use crate::prelude::*;
#[cfg(feature = "db-diesel-mysql")]
mod diesel_mysql {
use super::*;
use ::diesel::{
deserialize::{self, FromSql},
mysql::Mysql,
serialize::{self, IsNull, Output, ToSql},
sql_types::Numeric,
};
use std::io::Write;
use std::str::FromStr;
im... |
#[test]
fn read_numeric_type() {
let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
for &(precision, scale, sent, expected) in TEST_DECIMALS.iter() {
let items: Vec<Test> = sql_query(format!(
... | {
let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
// Test NULL
let items: Vec<NullableTest> = sql_query("SELECT CAST(NULL AS DECIMAL) AS value")
.load(&connection)
.expect("Unable to query value");... | identifier_body |
mysql.rs | use crate::prelude::*;
#[cfg(feature = "db-diesel-mysql")]
mod diesel_mysql {
use super::*;
use ::diesel::{
deserialize::{self, FromSql},
mysql::Mysql,
serialize::{self, IsNull, Output, ToSql},
sql_types::Numeric,
};
use std::io::Write;
use std::str::FromStr;
im... | () {
let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
// Test NULL
let items: Vec<NullableTest> = sql_query("SELECT CAST(NULL AS DECIMAL) AS value")
.load(&connection)
.expect("Unable to query value... | test_null | identifier_name |
mysql.rs | use crate::prelude::*;
#[cfg(feature = "db-diesel-mysql")]
mod diesel_mysql {
use super::*;
use ::diesel::{
deserialize::{self, FromSql},
mysql::Mysql,
serialize::{self, IsNull, Output, ToSql},
sql_types::Numeric,
};
use std::io::Write;
use std::str::FromStr;
im... |
"mysql://root@127.0.0.1/mysql".to_string()
}
#[test]
fn test_null() {
let connection = diesel::MysqlConnection::establish(&get_mysql_url()).expect("Establish connection");
// Test NULL
let items: Vec<NullableTest> = sql_query("SELECT CAST(NULL A... | {
return url;
} | conditional_block |
mysql.rs | use crate::prelude::*;
#[cfg(feature = "db-diesel-mysql")]
mod diesel_mysql {
use super::*;
use ::diesel::{
deserialize::{self, FromSql},
mysql::Mysql,
serialize::{self, IsNull, Output, ToSql},
sql_types::Numeric,
};
use std::io::Write;
use std::str::FromStr;
im... | }
pub static TEST_DECIMALS: &[(u32, u32, &str, &str)] = &[
// precision, scale, sent, expected
(1, 0, "1", "1"),
(6, 2, "1", "1.00"),
(6, 2, "9999.99", "9999.99"),
(35, 6, "3950.123456", "3950.123456"),
(10, 2, "3950.123456", "3950... | let value = row.get("value")?;
Ok(NullableTest { value })
} | random_line_split |
api.service.ts | import { OpaqueToken, Injectable } from '@angular/core'
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { TickerData } from './models/ticker-data.model';
const GET_TICKER_URL: string = 'https://api.cryptonator.com/api/ticker/';
@Injectable()
expor... | (private http: Http) {
}
getTickerData(base: string, target: string): Observable<{ ticker: TickerData, success: boolean }> {
return this.get<{ ticker: TickerData, success: boolean }>(`${GET_TICKER_URL}${base}-${target}`);
}
private get<TReturnType>(url: string): Observable<TReturnType> {
... | constructor | identifier_name |
api.service.ts | import { OpaqueToken, Injectable } from '@angular/core'
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { TickerData } from './models/ticker-data.model';
const GET_TICKER_URL: string = 'https://api.cryptonator.com/api/ticker/';
@Injectable()
expor... | }
} |
private get<TReturnType>(url: string): Observable<TReturnType> {
return this.http.get(url, new RequestOptions({ headers: this.headers, body: '' }))
.map(res => <TReturnType>res.json())
.catch(x => Observable.throw(x)); | random_line_split |
api.service.ts | import { OpaqueToken, Injectable } from '@angular/core'
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { TickerData } from './models/ticker-data.model';
const GET_TICKER_URL: string = 'https://api.cryptonator.com/api/ticker/';
@Injectable()
expor... |
getTickerData(base: string, target: string): Observable<{ ticker: TickerData, success: boolean }> {
return this.get<{ ticker: TickerData, success: boolean }>(`${GET_TICKER_URL}${base}-${target}`);
}
private get<TReturnType>(url: string): Observable<TReturnType> {
return this.http.get(url,... | {
} | identifier_body |
gauge.rs | use std::f64;
use std::mem;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug)]
pub struct Gauge {
value: AtomicU64,
}
impl Gauge {
pub fn new() -> Gauge {
let bits = unsafe { mem::transmute(f64::NAN) };
Gauge { value: AtomicU64::new(bits) }
}
pub fn clear(&mut self) {
... | () {
let mut c: Gauge = Gauge::new();
let s1 = c.snapshot();
c.set(1f64);
let s2 = c.snapshot();
assert!(f64::is_nan(s1));
assert!(s2 == 1f64);
}
}
| snapshot | identifier_name |
gauge.rs | use std::f64;
use std::mem;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug)]
pub struct Gauge {
value: AtomicU64,
}
impl Gauge {
pub fn new() -> Gauge {
let bits = unsafe { mem::transmute(f64::NAN) };
Gauge { value: AtomicU64::new(bits) }
}
pub fn clear(&mut self) |
pub fn set(&mut self, value: f64) {
let bits = unsafe { mem::transmute(value) };
self.value.store(bits, Ordering::Relaxed);
}
pub fn snapshot(&self) -> f64 {
let bits = self.value.load(Ordering::Relaxed);
unsafe { mem::transmute(bits) }
}
}
#[cfg(test)]
mod test {
... | {
let bits = unsafe { mem::transmute(f64::NAN) };
self.value.store(bits, Ordering::Relaxed);
} | identifier_body |
gauge.rs | use std::f64;
use std::mem;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug)]
pub struct Gauge {
value: AtomicU64,
}
impl Gauge {
pub fn new() -> Gauge {
let bits = unsafe { mem::transmute(f64::NAN) };
Gauge { value: AtomicU64::new(bits) }
}
pub fn clear(&mut self) {
... |
#[test]
fn snapshot() {
let mut c: Gauge = Gauge::new();
let s1 = c.snapshot();
c.set(1f64);
let s2 = c.snapshot();
assert!(f64::is_nan(s1));
assert!(s2 == 1f64);
}
} |
use std::f64; | random_line_split |
genericitesource0.rs | // A est un type concret.
struct A;
// Lorsque nous déclarons `Single`, la première occurrence de `A` n'est
// pas précédée du type générique `<A>`. Le type `Single` et `A` sont donc
// concrets.
struct Single(A);
// ^ Voici la première occurrence du type `A`.
// En revanche, ici, `<T>` précède la premiè... | {
// `Single` est un type concret et prend explicitement un paramètre
// de type `A`.
let _s = Single(A);
// On créé une variable nommée `_char` de type `SingleGen<char>`
// et on lui assigne la valeur `SingleGen('a')`.
// Le type requis du paramètre passé pour cette instance de `SingleGen`
... | n main() | identifier_name |
genericitesource0.rs | // A est un type concret.
struct A;
// Lorsque nous déclarons `Single`, la première occurrence de `A` n'est
// pas précédée du type générique `<A>`. Le type `Single` et `A` sont donc
// concrets.
struct Single(A); | // `SingleGen` est générique. Puisque le type `T` est générique, cela pourrait être
// "n'importe quoi", y compris le type concret `A` déclaré au début du fichier.
struct SingleGen<T>(T);
fn main() {
// `Single` est un type concret et prend explicitement un paramètre
// de type `A`.
let _s = Single(A);
... | // ^ Voici la première occurrence du type `A`.
// En revanche, ici, `<T>` précède la première occurrence `T`, donc le type | random_line_split |
generate_metadata_pkl.py | import argparse
import glob
import re
import cPickle as pickle
from dicom.sequence import Sequence
from log import print_to_file
from paths import LOGS_PATH, TRAIN_DATA_PATH, TEST_DATA_PATH
def read_slice(path):
return pickle.load(open(path))['data']
def convert_to_number(value):
value = str(value)
tr... |
filename = data_path.split('/')[-2] + '_metadata.pkl'
with open(filename, 'w') as f:
pickle.dump(metadata_dict, f)
print 'saved to ', filename
return metadata_dict
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
required = parser.add_argument_group('r... | metadata_dict[pid][pd['slice_id']] = pd['metadata'] | conditional_block |
generate_metadata_pkl.py | import argparse
import glob
import re
import cPickle as pickle
from dicom.sequence import Sequence
from log import print_to_file
from paths import LOGS_PATH, TRAIN_DATA_PATH, TEST_DATA_PATH
def read_slice(path):
return pickle.load(open(path))['data']
def convert_to_number(value):
value = str(value)
tr... | return float(value)
else:
return int(value)
except:
pass
return value
def clean_metadata(metadatadict):
# Do cleaning
keys = sorted(list(metadatadict.keys()))
for key in keys:
value = metadatadict[key]
if key == 'PatientAge':
meta... | random_line_split | |
generate_metadata_pkl.py | import argparse
import glob
import re
import cPickle as pickle
from dicom.sequence import Sequence
from log import print_to_file
from paths import LOGS_PATH, TRAIN_DATA_PATH, TEST_DATA_PATH
def read_slice(path):
return pickle.load(open(path))['data']
def convert_to_number(value):
value = str(value)
tr... |
def get_patient_data(patient_data_path):
patient_data = []
spaths = sorted(glob.glob(patient_data_path + r'/*.pkl'),
key=lambda x: int(re.search(r'/*_(\d+)\.pkl$', x).group(1)))
pid = re.search(r'/(\d+)/study$', patient_data_path).group(1)
for s in spaths:
slice_id = re.se... | d = pickle.load(open(path))['metadata'][0]
metadata = clean_metadata(d)
return metadata | identifier_body |
generate_metadata_pkl.py | import argparse
import glob
import re
import cPickle as pickle
from dicom.sequence import Sequence
from log import print_to_file
from paths import LOGS_PATH, TRAIN_DATA_PATH, TEST_DATA_PATH
def read_slice(path):
return pickle.load(open(path))['data']
def convert_to_number(value):
value = str(value)
tr... | (data_path):
patient_paths = sorted(glob.glob(data_path + '*/study'))
metadata_dict = {}
for p in patient_paths:
patient_data, pid = get_patient_data(p)
print "patient", pid
metadata_dict[pid] = dict()
for pd in patient_data:
metadata_dict[pid][pd['slice_id']] = p... | get_metadata | identifier_name |
vreyeparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VREyeParame... | (&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new(self.offset.get())
}
// https://w3c.github.io/webvr/#dom-vreyeparameters-fieldofview
fn FieldOfView(&self) -> Root<VRFieldOfView> {
Root::from_ref(&*self.fov)
}
// https://w3c.github.io/webvr/#dom-vreyeparameters... | Offset | identifier_name |
vreyeparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VREyeParame... |
}
impl VREyeParametersMethods for VREyeParameters {
#[allow(unsafe_code)]
// https://w3c.github.io/webvr/#dom-vreyeparameters-offset
unsafe fn Offset(&self, _cx: *mut JSContext) -> NonZero<*mut JSObject> {
NonZero::new(self.offset.get())
}
// https://w3c.github.io/webvr/#dom-vreyeparamete... | {
reflect_dom_object(box VREyeParameters::new_inherited(parameters, global),
global,
VREyeParametersBinding::Wrap)
} | identifier_body |
vreyeparameters.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 core::nonzero::NonZero;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::VREyeParame... |
pub fn new(parameters: WebVREyeParameters, global: &GlobalScope) -> Root<VREyeParameters> {
reflect_dom_object(box VREyeParameters::new_inherited(parameters, global),
global,
VREyeParametersBinding::Wrap)
}
}
impl VREyeParametersMethods for VREyePa... | result.offset.set(slice_to_array_buffer_view(global.get_cx(), &result.parameters.borrow().offset));
}
result
} | random_line_split |
card-list.component.ts | import {Component, OnInit} from "angular2/core";
import {NgClass} from 'angular2/common';
import {CardItemComponent} from "./card-item.component";
import {CardItem} from "./card-item";
import {WeatherService} from "./weather.service";
import {Observable} from 'rxjs/Rx';
import "gsap";
import {AlertService} from "./aler... |
updateCardInfos(t){
let self = this;
this.cardItems.map(item => {
this._weatherService.searchWeatherInfo(item.cityName)
.subscribe(
data => {
item.currentTemperature = data.main.temp;
}
);
... | {
event.stopPropagation();
this.inView = !inView;
if (inView == false){
TweenMax.staggerTo( $(".card"), 1, {y:-250, zIndex:100, ease:Bounce.easeOut}, 0.1);
TweenMax.staggerTo( $(".card"), 1, {rotationY:-180, repeat:1, yoyo:true}, 0.1);
} else {
Tween... | identifier_body |
card-list.component.ts | import {Component, OnInit} from "angular2/core";
import {NgClass} from 'angular2/common';
import {CardItemComponent} from "./card-item.component";
import {CardItem} from "./card-item";
import {WeatherService} from "./weather.service";
import {Observable} from 'rxjs/Rx';
import "gsap";
import {AlertService} from "./aler... | selector: 'card-list',
template: `
<a href="#" class="nav-toggle" [ngClass]="{active: inView}" (click)="slideWrapper($event, inView)"><span></span></a>
<div class="card-wrapper" >
<card-item *ngFor="#cardItemLocal of cardItems" [item]="cardItemLocal" [inView]="inView" [(need... | declare var Bounce:any;
@Component({ | random_line_split |
card-list.component.ts | import {Component, OnInit} from "angular2/core";
import {NgClass} from 'angular2/common';
import {CardItemComponent} from "./card-item.component";
import {CardItem} from "./card-item";
import {WeatherService} from "./weather.service";
import {Observable} from 'rxjs/Rx';
import "gsap";
import {AlertService} from "./aler... | (newState) {
this.isOn = newState;
}
slideWrapper(event, inView){
event.stopPropagation();
this.inView = !inView;
if (inView == false){
TweenMax.staggerTo( $(".card"), 1, {y:-250, zIndex:100, ease:Bounce.easeOut}, 0.1);
TweenMax.staggerTo( $(".card"), 1... | toggle | identifier_name |
card-list.component.ts | import {Component, OnInit} from "angular2/core";
import {NgClass} from 'angular2/common';
import {CardItemComponent} from "./card-item.component";
import {CardItem} from "./card-item";
import {WeatherService} from "./weather.service";
import {Observable} from 'rxjs/Rx';
import "gsap";
import {AlertService} from "./aler... |
}
updateCardInfos(t){
let self = this;
this.cardItems.map(item => {
this._weatherService.searchWeatherInfo(item.cityName)
.subscribe(
data => {
item.currentTemperature = data.main.temp;
}
... | {
TweenMax.staggerTo( $(".card"), 1, { y:0, zIndex:0, ease:Bounce.easeOut });
} | conditional_block |
snagfilms_scraper.py | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... | url = urlparse.urljoin(self.base_url, '/apis/v2/user/login.json')
data = {'email': self.username, 'password': self.password, 'rememberMe': True}
referer = urlparse.urljoin(self.base_url, '/login')
headers = {'Content-Type': 'application/json', 'Referer': referer}
headers.update(XHR)
... | identifier_body | |
snagfilms_scraper.py | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... |
hosters.append(hoster)
hosters.sort(key=lambda x: x.get('extra', ''), reverse=True)
return hosters
def _get_episode_url(self, season_url, video):
episode_pattern = 'data-title\s*=\s*"Season\s+0*%s\s+Episode\s+0*%s[^>]*data-permalink\s*=\s*"(... | hoster['extra'] = match.group(1) | conditional_block |
snagfilms_scraper.py | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... | (self, video):
source_url = self.get_url(video)
hosters = []
if source_url and source_url != FORCE_NO_MATCH:
page_url = urlparse.urljoin(self.base_url, source_url)
html = self._http_get(page_url, cache_limit=.5)
fragment = dom_parser.parse_dom(html, 'div', {'c... | get_sources | identifier_name |
snagfilms_scraper.py | """
SALTS XBMC Addon
Copyright (C) 2014 tknorris
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
T... |
def _get_episode_url(self, season_url, video):
episode_pattern = 'data-title\s*=\s*"Season\s+0*%s\s+Episode\s+0*%s[^>]*data-permalink\s*=\s*"([^"]+)' % (video.season, video.episode)
title_pattern = 'data-title\s*=\s*"Season\s+\d+\s+Episode\s+\d+\s*(?P<title>[^"]+)[^>]+data-permalink\s*=\s*"(?P<url>... | hosters.sort(key=lambda x: x.get('extra', ''), reverse=True)
return hosters | random_line_split |
index.js | import React from "react";
// import fetch from "isomorphic-fetch";
// lets us dispatch() functions from API calls
import thunkMiddleware from "redux-thunk";
// neat middleware that logs actions
import { createLogger } from "redux-logger";
import { render } from "react-dom";
import { Provider } from 'react-redux';
impo... | {
runtime.register();
} | conditional_block | |
index.js | import React from "react";
// import fetch from "isomorphic-fetch";
// lets us dispatch() functions from API calls
import thunkMiddleware from "redux-thunk";
// neat middleware that logs actions
import { createLogger } from "redux-logger";
import { render } from "react-dom";
import { Provider } from 'react-redux';
impo... | render(
<Provider store={store}>
<BrowserRouter>
<AppComponent />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
if ('serviceWorker' in navigator) {
runtime.register();
} | loggerMiddleware,
thunkMiddleware
));
| random_line_split |
main.rs | use rand::{thread_rng, seq::SliceRandom};
use mcc4::*; | let game = ConnectFour::<BitState>::new(7, 6).unwrap();
let human_player = HumanPlayer::new();
let ai_player = TreeSearchPlayer::new(&game);
let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_player), Box::new(ai_player)];
players.shuffle(&mut thread_rng());
println!("\x1B[2J\... |
fn main() {
env_logger::init(); | random_line_split |
main.rs | use rand::{thread_rng, seq::SliceRandom};
use mcc4::*;
fn main() {
env_logger::init();
let game = ConnectFour::<BitState>::new(7, 6).unwrap();
let human_player = HumanPlayer::new();
let ai_player = TreeSearchPlayer::new(&game);
let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_p... |
};
}
}
| {} | conditional_block |
main.rs | use rand::{thread_rng, seq::SliceRandom};
use mcc4::*;
fn | () {
env_logger::init();
let game = ConnectFour::<BitState>::new(7, 6).unwrap();
let human_player = HumanPlayer::new();
let ai_player = TreeSearchPlayer::new(&game);
let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_player), Box::new(ai_player)];
players.shuffle(&mut thread_rn... | main | identifier_name |
main.rs | use rand::{thread_rng, seq::SliceRandom};
use mcc4::*;
fn main() | }
| {
env_logger::init();
let game = ConnectFour::<BitState>::new(7, 6).unwrap();
let human_player = HumanPlayer::new();
let ai_player = TreeSearchPlayer::new(&game);
let mut players: Vec<Box<PlayerTrait<Game=_>>> = vec![Box::new(human_player), Box::new(ai_player)];
players.shuffle(&mut thread_rng()... | identifier_body |
display.js | function updateImprovementsDisplay(i) {
updateDisplay(
'desc_improvements',
`improvements: ${i}`
);
}
function updateGenerationsDisplay(g) {
updateDisplay(
'desc_generations',
`generations: ${g}`
);
}
function updateBestSimilarityDisplay(s) {
updateDisplay(
'best_desc_similarity',
`$... |
function updateScratchTemperatureDisplay(t) {
updateDisplay(
'scratch_desc_temp',
`temperature: ${t}`
);
}
function updateScratchPhasePercentageDisplay(tries, max) {
const percentDone = (100 * tries / max).toFixed()
updateDisplay(
'scratch_desc_phase_percentage',
`phase progress: ${percentDon... | {
updateDisplay(
'scratch_desc_phasenum',
`phase: ${id + 1} / ${n}`
);
} | identifier_body |
display.js | function updateImprovementsDisplay(i) {
updateDisplay(
'desc_improvements',
`improvements: ${i}`
);
}
function updateGenerationsDisplay(g) {
updateDisplay( |
function updateBestSimilarityDisplay(s) {
updateDisplay(
'best_desc_similarity',
`${s}% similar`
);
}
function updateScratchSimilarityDisplay(s) {
updateDisplay(
'scratch_desc_similarity',
`${s}% similar`
);
}
function updateScratchPhaseIdDisplay(id, n) {
updateDisplay(
'scratch_desc_ph... | 'desc_generations',
`generations: ${g}`
);
} | random_line_split |
display.js | function updateImprovementsDisplay(i) {
updateDisplay(
'desc_improvements',
`improvements: ${i}`
);
}
function updateGenerationsDisplay(g) {
updateDisplay(
'desc_generations',
`generations: ${g}`
);
}
function updateBestSimilarityDisplay(s) {
updateDisplay(
'best_desc_similarity',
`$... | (id, n) {
updateDisplay(
'scratch_desc_phasenum',
`phase: ${id + 1} / ${n}`
);
}
function updateScratchTemperatureDisplay(t) {
updateDisplay(
'scratch_desc_temp',
`temperature: ${t}`
);
}
function updateScratchPhasePercentageDisplay(tries, max) {
const percentDone = (100 * tries / max).toFix... | updateScratchPhaseIdDisplay | identifier_name |
test_transmuters.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import warnings
import unittest
import os
from pymatgen.alchemy.transmuters import CifTransmuter, PoscarTransmuter
from pymatgen.alchemy.filters import ContainsSpecieFilter
from pymatgen.transformations.standa... |
#test the filter
tsc.apply_filter(ContainsSpecieFilter(['Zn2+', 'Be2+', 'Mn4+'],
strict_compare=True, AND=False))
self.assertEqual(len(tsc), 8)
self.assertEqual(tsc.transformed_structures[0].as_dict()[
'history']... | tsc = PoscarTransmuter.from_filenames(
[os.path.join(test_dir, "POSCAR")])
tsc.append_transformation(RemoveSpeciesTransformation('O'))
self.assertEqual(len(tsc[0].final_structure), 8)
tsc.append_transformation(SubstitutionTransformation({"Fe":
... | identifier_body |
test_transmuters.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import warnings
import unittest
import os
from pymatgen.alchemy.transmuters import CifTransmuter, PoscarTransmuter
from pymatgen.alchemy.filters import ContainsSpecieFilter
from pymatgen.transformations.standa... | unittest.main() | conditional_block | |
test_transmuters.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import warnings
import unittest
import os
from pymatgen.alchemy.transmuters import CifTransmuter, PoscarTransmuter
from pymatgen.alchemy.filters import ContainsSpecieFilter
from pymatgen.transformations.standa... |
class CifTransmuterTest(unittest.TestCase):
def setUp(self):
warnings.simplefilter("ignore")
def tearDown(self):
warnings.simplefilter("default")
def test_init(self):
trans = []
trans.append(SubstitutionTransformation({"Fe": "Mn", "Fe2+": "Mn2+"}))
tsc = CifTransm... |
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..",
'test_files') | random_line_split |
test_transmuters.py | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import warnings
import unittest
import os
from pymatgen.alchemy.transmuters import CifTransmuter, PoscarTransmuter
from pymatgen.alchemy.filters import ContainsSpecieFilter
from pymatgen.transformations.standa... | (unittest.TestCase):
def test_init(self):
trans = []
trans.append(SubstitutionTransformation({"Fe": "Mn"}))
tsc = PoscarTransmuter.from_filenames([os.path.join(test_dir,
"POSCAR"),
os.... | PoscarTransmuterTest | identifier_name |
main.js | //This is a addon for habbitRPG.com
//every time when you visit vice website it report to habbitRPG and you loose HP.
var Widget = require("widget").Widget;
var tabs = require('sdk/tabs');
var notifications = require("sdk/notifications");
var Url = require("sdk/url");
var Prefs = require("sdk/simple-prefs").p... |
//add event listener on every tab
tabs.on('open', function(tab){
tab.on('ready', function(tab){
let host = (new Url.URL(tab.url)).host;
if (is_vice_host(host)&&is_penalty_time()) {
//punish user
notifications.notify({
... | panel: info_panel
});
| random_line_split |
main.js | //This is a addon for habbitRPG.com
//every time when you visit vice website it report to habbitRPG and you loose HP.
var Widget = require("widget").Widget;
var tabs = require('sdk/tabs');
var notifications = require("sdk/notifications");
var Url = require("sdk/url");
var Prefs = require("sdk/simple-prefs").p... |
var is_penalty_time = function (){
var current_time = new Date();
var time = current_time.getHours();
if(Prefs.penaltystart>Prefs.penaltyend||Prefs.penaltyend>24){
notifications.notify({
title: _("HabitRPG"),
text: _("time_format_wrong")
return (false);
... | {
let benList = Prefs.benHost.split(",");
return (benList.some(function(v){
let patt = new RegExp(v);
return (patt.test(host));
}));
} | identifier_body |
main.js | //This is a addon for habbitRPG.com
//every time when you visit vice website it report to habbitRPG and you loose HP.
var Widget = require("widget").Widget;
var tabs = require('sdk/tabs');
var notifications = require("sdk/notifications");
var Url = require("sdk/url");
var Prefs = require("sdk/simple-prefs").p... |
return (parseInt(Prefs.penaltystart)<=time&&time<=parseInt(Prefs.penaltyend));
};
exports.main = function()
{
let api = new API;
//mini panel, contain health and XP bars, opens on click on widget
let info_panel = Panel({
focus: false,
width:240,
height:90,
... | {
notifications.notify({
title: _("HabitRPG"),
text: _("time_format_wrong")
return (false);
})
} | conditional_block |
main.js | //This is a addon for habbitRPG.com
//every time when you visit vice website it report to habbitRPG and you loose HP.
var Widget = require("widget").Widget;
var tabs = require('sdk/tabs');
var notifications = require("sdk/notifications");
var Url = require("sdk/url");
var Prefs = require("sdk/simple-prefs").p... | (host){
let benList = Prefs.benHost.split(",");
return (benList.some(function(v){
let patt = new RegExp(v);
return (patt.test(host));
}));
}
var is_penalty_time = function (){
var current_time = new Date();
var time = current_time.getHours();
if(Prefs.penaltystart>Pref... | is_benefical_host | identifier_name |
collection-student.ts | import { Component, ViewChild, ElementRef } from '@angular/core';
import { Refresher, NavParams, NavController } from 'ionic-angular';
import { TranslateService } from 'ng2-translate/ng2-translate';
import {Page} from "../../../model/page";
import {CollectionService} from "../../../providers/collection.service";
impor... | (collectionCard): void {
this.ionicService.showLoading(this.translateService.instant('APP.WAIT'));
this.collectionService.getCollectionDetails(collectionCard.id).subscribe(
((value: Array<Card>)=> {
let allCards : Array<Card> = value;
let assignedCardsIds = Array();
let finalCards ... | goToCollectionDetail | identifier_name |
collection-student.ts | import { Component, ViewChild, ElementRef } from '@angular/core';
import { Refresher, NavParams, NavController } from 'ionic-angular';
import { TranslateService } from 'ng2-translate/ng2-translate';
import {Page} from "../../../model/page";
import {CollectionService} from "../../../providers/collection.service";
impor... |
/**
* Fires when the page appears on the screen.
* Used to get all the data needed in page
*/
public ionViewDidEnter(): void {
this.ionicService.showLoading(this.translateService.instant('APP.WAIT'));
this.getCollections();
}
/**
* This method returns the collection list of the
* cur... | {
} | identifier_body |
collection-student.ts | import { Component, ViewChild, ElementRef } from '@angular/core';
import { Refresher, NavParams, NavController } from 'ionic-angular';
import { TranslateService } from 'ng2-translate/ng2-translate';
import {Page} from "../../../model/page";
import {CollectionService} from "../../../providers/collection.service";
impor... |
declare let google;
@Component({
selector: 'page-collection-student',
templateUrl: './collection-student.html'
})
export class CollectionSpage {
@ViewChild('map') mapElement: ElementRef;
public collectionCards: Array<CollectionCard>;
constructor(
public navParams: NavParams,
public translateServ... | import {Card} from "../../../model/card"; | random_line_split |
collection-student.ts | import { Component, ViewChild, ElementRef } from '@angular/core';
import { Refresher, NavParams, NavController } from 'ionic-angular';
import { TranslateService } from 'ng2-translate/ng2-translate';
import {Page} from "../../../model/page";
import {CollectionService} from "../../../providers/collection.service";
impor... |
else {
finalCards.push(allCard);
}
});
});
this.navController.push(CollectionStudentDetail, { cards: finalCards, collectionCard: collectionCard })
}),
error => {
this.ionicService.showAlert(this.translateService.instant('APP.ERROR'), e... | {
finalCards.push(unknownCard);
} | conditional_block |
feedbackStatusbarItem.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
if (TwitterFeedbackService.VIA_NAME) {
length += ` via @${TwitterFeedbackService.VIA_NAME}`.length;
}
return 280 - length;
}
}
export class FeedbackStatusbarConribution extends Disposable implements IWorkbenchContribution {
private static readonly TOGGLE_FEEDBACK_COMMAND = 'help.tweetFeedback';
privat... | {
TwitterFeedbackService.HASHTAGS.forEach(element => {
length += element.length + 2;
});
} | conditional_block |
feedbackStatusbarItem.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | import { CATEGORIES } from 'vs/workbench/common/actions';
import { HIDE_NOTIFICATIONS_CENTER, HIDE_NOTIFICATION_TOAST } from 'vs/workbench/browser/parts/notifications/notificationsCommands';
import { isIOS } from 'vs/base/common/platform';
class TwitterFeedbackService implements IFeedbackDelegate {
private static TW... | import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { URI } from 'vs/base/common/uri';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions'; | random_line_split |
feedbackStatusbarItem.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | extends Disposable implements IWorkbenchContribution {
private static readonly TOGGLE_FEEDBACK_COMMAND = 'help.tweetFeedback';
private widget: FeedbackWidget | undefined;
private entry: IStatusbarEntryAccessor | undefined;
constructor(
@IStatusbarService private readonly statusbarService: IStatusbarService,
... | FeedbackStatusbarConribution | identifier_name |
feedbackStatusbarItem.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
private toggleFeedback(): void {
if (!this.widget) {
this.widget = this._register(this.instantiationService.createInstance(FeedbackWidget, {
feedbackService: this.instantiationService.createInstance(TwitterFeedbackService)
}));
this._register(this.widget.onDidChangeVisibility(visible => this.entry!.up... | {
// Status entry
this.entry = this._register(this.statusbarService.addEntry(this.getStatusEntry(), 'status.feedback', StatusbarAlignment.RIGHT, -100 /* towards the end of the right hand side */));
// Command to toggle
CommandsRegistry.registerCommand(FeedbackStatusbarConribution.TOGGLE_FEEDBACK_COMMAND, () =... | identifier_body |
bundle-map-floor2.js | , 11, 11, 11, 11, 11, 11, 11, 12, 12, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12],
[ 12, 10, 10, 10, 10, 10, 10, 10, 10, 10, 12, 12, 0, 0, 13, 13, 13, 13, 13, 13, 13, 0, 0, 12],
[ 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 12, 12, 0, 0, 14, 1... | {
if (!gbox.getObject("foes","third1")&&!gbox.getObject("foes","third2")&&!gbox.getObject("foes","third3")&&!gbox.getObject("foes","third4")) { // check them. If beaten...
gbox.getObject("walls","sidedoor").doOpen();
tilemaps.queststatus["floor2untrapped"]=true; // Set the quest as done...
ma... | conditional_block | |
bundle-map-floor2.js | ", audio:"beep", talk:["Use the B button to interact","with objects, that means that you can","open doors, tresaure chests, talk","with villagers etc."]}
]
}
},{
object:"dialogues",
property:"soul",
value:{
endgame:true, font:"small", skipkey:"a", esckey:null, who: noface,
scenes:[
... | }
if (tilemaps.queststatus["floor1eyeswitch"]&&!tilemaps.queststatus["bosskey"]) {
maingame.addEnemy("fifth1","octo",3,4,true);
maingame.addEnemy("fifth2","octo",5,4,true);
maingame.addEnemy("fifth3","octo",6,4,true);
maingame.addEnemy("fifth4","octo",7,4,true);
tilemaps | maingame.setTileInMap(14,6,4,false);
}
if (!tilemaps.queststatus["floor2arrows"]) {
maingame.addChest(19,6,null,false,"arrow",null,0); | random_line_split |
settings.py | # Django settings for nadbproj project.
import os.path
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'orac... | 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'zx!582g59qwpwdnds)8b$pm(v-03jgpiq1e1(ix&iyvw*)$_yi'
# List of callables that know how to import templates from various sou... | # various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder', | random_line_split |
x2fair.js | function fixedbsmenu(){
if(jQuery(window).width() < 604){
//Static Top
document.onscroll = function() {
if( jQuery(window).scrollTop() > jQuery('header').height() ) {
jQuery('nav#navigation').addClass('fixednav');
}
else {
j... |
function onLoadClick(){
if(jQuery(window).width() > 700){
//Static Top
if( jQuery(window).scrollTop() > jQuery('header').height() ) {
jQuery('.header_inner').addClass('nav_logo_wrapper');
jQuery('.alternative_logo').show();
} else {
jQuery('.hea... | {
if(jQuery(window).width() > 700){
//Static Top
document.onscroll = function() {
if( jQuery(window).scrollTop() > jQuery('header').height() ) {
jQuery('.header_inner').addClass('nav_logo_wrapper');
jQuery('.alternative_logo').show();
} ... | identifier_body |
x2fair.js | function fixedbsmenu(){
if(jQuery(window).width() < 604){
//Static Top
document.onscroll = function() {
if( jQuery(window).scrollTop() > jQuery('header').height() ) {
jQuery('nav#navigation').addClass('fixednav');
}
else {
j... |
}
});
jQuery('.post').addClass('hiddenAnimation').viewportChecker({
classToAdd: 'visibleAnimation animated fadeIn',
offset: 400
});
jQuery('#html, #css, #php, #jquery, #boostrap, #wordpress').circliful();
});
jQuery(window).resize(function() {
fixedbsme... | {
jQuery('html,body').animate({scrollTop: target.offset().top}, 1000);
return false;
} | conditional_block |
x2fair.js | function | (){
if(jQuery(window).width() < 604){
//Static Top
document.onscroll = function() {
if( jQuery(window).scrollTop() > jQuery('header').height() ) {
jQuery('nav#navigation').addClass('fixednav');
}
else {
jQuery('nav#navigatio... | fixedbsmenu | identifier_name |
x2fair.js | function fixedbsmenu(){
if(jQuery(window).width() < 604){
//Static Top
document.onscroll = function() {
if( jQuery(window).scrollTop() > jQuery('header').height() ) {
jQuery('nav#navigation').addClass('fixednav');
}
else {
j... | }
function fixedbsmenu767(){
if(jQuery(window).width() > 700){
//Static Top
document.onscroll = function() {
if( jQuery(window).scrollTop() > jQuery('header').height() ) {
jQuery('.header_inner').addClass('nav_logo_wrapper');
jQuery('.alternative_... | random_line_split | |
gatsby-browser.js | // Taken from https://github.com/netlify/netlify-identity-widget
const routes = /(confirmation|invite|recovery|email_change)_token=([^&]+)/
const errorRoute = /error=access_denied&error_description=403/
const accessTokenRoute = /access_token=/
exports.onInitialClientRender = (
_,
{ enableIdentityWidget = true, pub... | import(`netlify-identity-widget`).then(
({ default: netlifyIdentityWidget }) => {
netlifyIdentityWidget.on(`init`, user => {
if (!user) {
netlifyIdentityWidget.on(`login`, () => {
document.location.href = `${__PATH_PREFIX__}/${publicPath}/`
})
... | random_line_split | |
gatsby-browser.js | // Taken from https://github.com/netlify/netlify-identity-widget
const routes = /(confirmation|invite|recovery|email_change)_token=([^&]+)/
const errorRoute = /error=access_denied&error_description=403/
const accessTokenRoute = /access_token=/
exports.onInitialClientRender = (
_,
{ enableIdentityWidget = true, pub... |
})
netlifyIdentityWidget.init()
}
)
}
}
| {
netlifyIdentityWidget.on(`login`, () => {
document.location.href = `${__PATH_PREFIX__}/${publicPath}/`
})
} | conditional_block |
functions_6.js | _max',['../classlibcmaes_1_1pli.html#a448fafe7f77fdc145e2a84bce4656a21',1,'libcmaes::pli']]],
['get_5ferr_5fmin',['get_err_min',['../classlibcmaes_1_1pli.html#ad924eec733a154be4626b64c84cf64e8',1,'libcmaes::pli']]],
['get_5fexploit',['get_exploit',['../classlibcmaes_1_1SurrogateStrategy.html#a6ace0824acd6ef15af0e6d... | ['get_5fmax_5fiter',['get_max_iter',['../classlibcmaes_1_1Parameters.html#a95b8ff475b28b2cbf89cd147ab09eeee',1,'libcmaes::Parameters']]],
['get_5fmaximize',['get_maximize',['../classlibcmaes_1_1Parameters.html#afec66b0ca5465b81498189e2cc8a14dc',1,'libcmaes::Parameters']]],
['get_5fmt_5ffeval',['get_mt_feval',['..... | ['get_5fmax_5ffevals',['get_max_fevals',['../classlibcmaes_1_1Parameters.html#af738c73caee922feff43ba29218ea8ad',1,'libcmaes::Parameters']]], | random_line_split |
service.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# CherryMusic - a standalone music server
# Copyright (c) 2012 - 2014 Tom Wallroth & Tilman Boerner
#
# Project page:
# http://fomori.org/cherrymusic/
# Sources on github:
# http://github.com/devsnd/cherrymusic/
#
# CherryMusic is based on
# jPlayer (GPL/MIT licens... |
In general, don't create cyclic dependencies. It's bad for your brain and
also a sure sign of a problematic program architecture. When confronted
with a mutual dependency, extract a third class from one of the offenders
for both to depend on.
"""
pass
__provider_factories = {}
__providercache... | cycle; when it is allowed, in its constructor, to access a dependency
that's also part of the cycle, a singularity is spawned which implodes the
universe. This exception is raised to prevent that. | random_line_split |
service.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# CherryMusic - a standalone music server
# Copyright (c) 2012 - 2014 Tom Wallroth & Tilman Boerner
#
# Project page:
# http://fomori.org/cherrymusic/
# Sources on github:
# http://github.com/devsnd/cherrymusic/
#
# CherryMusic is based on
# jPlayer (GPL/MIT licens... |
return self.provider
class Python2OldStyleClass:
"""In Python2, I am a ``classobj`` which is not the same as a ``type``."""
pass
| return self.provider(*self.args, **self.kwargs) | conditional_block |
service.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# CherryMusic - a standalone music server
# Copyright (c) 2012 - 2014 Tom Wallroth & Tilman Boerner
#
# Project page:
# http://fomori.org/cherrymusic/
# Sources on github:
# http://github.com/devsnd/cherrymusic/
#
# CherryMusic is based on
# jPlayer (GPL/MIT licens... | (self, handle):
self.handle = handle
def __repr__(self):
return '{0}({1!r})'.format(self.__class__.__name__, self.handle)
def __get__(self, instance, owner):
return get(self.handle)
def user(**requirements):
""" Class deocrator to inject service providers as attributes into the
... | __init__ | identifier_name |
service.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# CherryMusic - a standalone music server
# Copyright (c) 2012 - 2014 Tom Wallroth & Tilman Boerner
#
# Project page:
# http://fomori.org/cherrymusic/
# Sources on github:
# http://github.com/devsnd/cherrymusic/
#
# CherryMusic is based on
# jPlayer (GPL/MIT licens... |
class Python2OldStyleClass:
"""In Python2, I am a ``classobj`` which is not the same as a ``type``."""
pass
| """ Return a provider instance.
Raises : :cls:`MutualDependencyBreak`
If called recursively within the same thread, which happens
when mutually dependent providers try to instantiate each other.
"""
if self.lock.locked():
raise MutualDependencyBre... | identifier_body |
opts.rs |
/// True if we should show borders on all layers and tiles for
/// debugging purposes (`--show-debug-borders`).
pub show_debug_borders: bool,
/// True if we should show borders on all fragments for debugging purposes
/// (`--show-debug-fragment-borders`).
pub show_debug_fragment_borders: bool,... | /// browser engines.
pub bubble_inline_sizes_separately: bool, | random_line_split | |
opts.rs | ,
dump_display_list: false,
dump_display_list_optimized: false,
relayout_event: false,
validate_display_list_geometry: false,
profile_tasks: false,
resources_path: None,
sniff_mime_types: false,
disable_share_style_cache: false,
}
}
pub fn from_cmdlin... | {
EXPERIMENTAL_ENABLED.store(new_value, Ordering::SeqCst);
} | identifier_body | |
opts.rs | "GPU painting"),
getopts::optopt("o", "output", "Output file", "output.png"),
getopts::optopt("s", "size", "Size of tiles", "512"),
getopts::optopt("", "device-pixel-ratio", "Device pixels per px", ""),
getopts::optflag("e", "experimental", "Enable experimental web features"),
g... | get | identifier_name | |
server.rs | //! Shadowsocks Local Tunnel Server
use std::{io, sync::Arc, time::Duration};
use futures::{future, FutureExt};
use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr};
use crate::local::{context::ServiceContext, loadbalancing::PingBalancer};
use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel};
... | impl Tunnel {
/// Create a new Tunnel server forwarding to `forward_addr`
pub fn new(forward_addr: Address) -> Tunnel {
let context = ServiceContext::new();
Tunnel::with_context(Arc::new(context), forward_addr)
}
/// Create a new Tunnel server with context
pub fn with_context(contex... | mode: Mode,
udp_expiry_duration: Option<Duration>,
udp_capacity: Option<usize>,
}
| random_line_split |
server.rs | //! Shadowsocks Local Tunnel Server
use std::{io, sync::Arc, time::Duration};
use futures::{future, FutureExt};
use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr};
use crate::local::{context::ServiceContext, loadbalancing::PingBalancer};
use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel};
... | (forward_addr: Address) -> Tunnel {
let context = ServiceContext::new();
Tunnel::with_context(Arc::new(context), forward_addr)
}
/// Create a new Tunnel server with context
pub fn with_context(context: Arc<ServiceContext>, forward_addr: Address) -> Tunnel {
Tunnel {
cont... | new | identifier_name |
server.rs | //! Shadowsocks Local Tunnel Server
use std::{io, sync::Arc, time::Duration};
use futures::{future, FutureExt};
use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr};
use crate::local::{context::ServiceContext, loadbalancing::PingBalancer};
use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel};
... |
if self.mode.enable_udp() {
vfut.push(self.run_udp_tunnel(udp_addr, balancer).boxed());
}
let (res, ..) = future::select_all(vfut).await;
res
}
async fn run_tcp_tunnel(&self, client_config: &ServerAddr, balancer: PingBalancer) -> io::Result<()> {
run_tcp_t... | {
vfut.push(self.run_tcp_tunnel(tcp_addr, balancer.clone()).boxed());
} | conditional_block |
server.rs | //! Shadowsocks Local Tunnel Server
use std::{io, sync::Arc, time::Duration};
use futures::{future, FutureExt};
use shadowsocks::{config::Mode, relay::socks5::Address, ServerAddr};
use crate::local::{context::ServiceContext, loadbalancing::PingBalancer};
use super::{tcprelay::run_tcp_tunnel, udprelay::UdpTunnel};
... |
/// Set server mode
pub fn set_mode(&mut self, mode: Mode) {
self.mode = mode;
}
/// Start serving
pub async fn run(self, tcp_addr: &ServerAddr, udp_addr: &ServerAddr, balancer: PingBalancer) -> io::Result<()> {
let mut vfut = Vec::new();
if self.mode.enable_tcp() {
... | {
self.udp_capacity = Some(c);
} | identifier_body |
uobjnew.py | #!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# uobjnew Summarize object allocations in high-level languages.
# For Linux, uses BCC, eBPF.
#
# USAGE: uobjnew [-h] [-T TOP] [-v] {java,ruby,c} pid [interval]
#
# Copyright 2016 Sasha Goldshtein
# Licensed under the Apache License, Version 2.0 ... | # Ruby
#
elif args.language == "ruby":
create_template = """
int THETHING_alloc_entry(struct pt_regs *ctx) {
struct key_t key = { .name = "THETHING" };
struct val_t *valp, zero = {};
u64 size = 0;
bpf_usdt_readarg(1, ctx, &size);
valp = allocs.lookup_or_init(&key, &zero);
valp->total_size +=... | usdt.enable_probe("object__alloc", "alloc_entry")
# | random_line_split |
uobjnew.py | #!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
#
# uobjnew Summarize object allocations in high-level languages.
# For Linux, uses BCC, eBPF.
#
# USAGE: uobjnew [-h] [-T TOP] [-v] {java,ruby,c} pid [interval]
#
# Copyright 2016 Sasha Goldshtein
# Licensed under the Apache License, Version 2.0 ... |
bpf = BPF(text=program, usdt_contexts=[usdt])
if args.language == "c":
bpf.attach_uprobe(name="c", sym="malloc", fn_name="alloc_entry",
pid=args.pid)
exit_signaled = False
print("Tracing allocations in process %d (language: %s)... Ctrl-C to quit." %
(args.pid, args.language or "none")... | print(usdt.get_text())
print(program) | conditional_block |
timeSync.ts | import { ServerTimeApi } from '../api';
import { SagaIterator } from 'redux-saga';
import { delay, put, call, take, fork, takeLatest, race } from 'redux-saga/effects';
import { SyncTime } from '../actions';
import moment from 'moment-timezone';
function* fetchServerTimeSaga(): SagaIterator {
try {
yield put(Sync... |
delayTime += 1000;
yield delay(Math.min(delayTime, 10000));
}
}
export function* watchSyncTime(): SagaIterator {
yield fork(initialSync);
yield takeLatest(SyncTime.start, fetchServerTimeSaga);
}
| {
return;
} | conditional_block |
timeSync.ts | import { ServerTimeApi } from '../api';
import { SagaIterator } from 'redux-saga';
import { delay, put, call, take, fork, takeLatest, race } from 'redux-saga/effects';
import { SyncTime } from '../actions';
import moment from 'moment-timezone';
function* fetchServerTimeSaga(): SagaIterator {
try {
yield put(Sync... |
yield put(SyncTime.success({ result: diff }));
} catch (error) {
console.error(error, 'error updating upcoming');
yield put(SyncTime.failure({ error }));
}
}
export function* initialSync(): SagaIterator {
// keeps trying with ramp up delay until success (up to 10 sec)
let delayTime = 1000;
whil... | const serverTime: moment.Moment = yield call(ServerTimeApi.fetchServerTime);
const diff = serverTime.diff(moment.utc()); | random_line_split |
gulpfile.js | var gulp = require('gulp');
var mainBowerFiles = require('main-bower-files');
var bower = require('gulp-bower');
var uglify = require('gulp-uglify');
var mincss = require('gulp-cssmin');
var concat = require('gulp-concat');
var ignore = require('gulp-ignore');
var del = require('del');
var lib = 'wwwroot/dist';
v... | });
gulp.task('default', ['bundleFront'], function () {
return;
}); | .pipe(gulp.dest(lib+'/js/bundle/')); | random_line_split |
design_pattern-chain_of_command.rs | #![crate_type = "bin"]
//! Example of design pattern inspired from PHP code of
//! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html
//!
//! Tested with rust-1.41.1-nightly
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/m... |
}
struct UserCommand;
impl UserCommand {
fn new() -> UserCommand {
UserCommand
}
}
impl Command for UserCommand {
fn on_command(&self, name: &str, args: &[&str]) {
if name == "addUser" {
println!("UserCommand handling '{}' with args {:?}.", name, args);
}
}
}
struct MailCommand;
impl MailCommand {
fn n... | {
for command in self.commands.iter() {
command.on_command(name, args);
}
} | identifier_body |
design_pattern-chain_of_command.rs | #![crate_type = "bin"]
//! Example of design pattern inspired from PHP code of
//! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html
//!
//! Tested with rust-1.41.1-nightly
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/m... | () -> CommandChain<'a> {
CommandChain{commands: Vec::new()}
}
fn add_command(&mut self, command: Box<dyn Command + 'a>) {
self.commands.push(command);
}
fn run_command(&self, name: &str, args: &[&str]) {
for command in self.commands.iter() {
command.on_command(name, args);
}
}
}
struct UserCommand;
imp... | new | identifier_name |
design_pattern-chain_of_command.rs | #![crate_type = "bin"]
//! Example of design pattern inspired from PHP code of
//! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html
//!
//! Tested with rust-1.41.1-nightly
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/m... | else if name == "mail" {
println!("MailCommand handling '{}' with args {:?}.", name, args);
}
}
}
fn main() {
let mut cc = CommandChain::new();
cc.add_command(Box::new(UserCommand::new()));
cc.add_command(Box::new(MailCommand::new()));
cc.run_command("addUser", &["Toto", "users"]);
cc.run_command("mail", &[... | {
println!("MailCommand handling '{}' with args {:?}.", name, args);
} | conditional_block |
design_pattern-chain_of_command.rs | #![crate_type = "bin"]
//! Example of design pattern inspired from PHP code of
//! http://codersview.blogspot.fr/2009/05/chain-of-command-pattern-using-php.html
//!
//! Tested with rust-1.41.1-nightly
//!
//! @author Eliovir <http://github.com/~eliovir>
//!
//! @license MIT license <http://www.opensource.org/licenses/m... | }
}
struct MailCommand;
impl MailCommand {
fn new() -> MailCommand {
MailCommand
}
}
impl Command for MailCommand {
fn on_command(&self, name: &str, args: &[&str]) {
if name == "addUser" {
println!("MailCommand handling '{}' with args {:?}.", name, args);
} else if name == "mail" {
println!("MailComman... | random_line_split | |
blacklisted_domain_ip.py | import os
import urllib.request
import zipfile
from _socket import timeout
from http.client import IncompleteRead
from io import BytesIO
from urllib.parse import urlparse
import _socket
_socket.setdefaulttimeout(10) # set timeout
def ransomware_and_malware_domain_check(list_of_domains):
while True:
try:... |
list_of_mal_domains = []
for n in list_of:
if n and not n.startswith("#"):
list_of_mal_domains.append(n.strip())
while True:
try:
list_of = urllib.request.urlopen(
"https://ransomwaretracker.abuse.ch/downloads/RW_URLBL.txt").read().decode(
... | random_line_split | |
blacklisted_domain_ip.py | import os
import urllib.request
import zipfile
from _socket import timeout
from http.client import IncompleteRead
from io import BytesIO
from urllib.parse import urlparse
import _socket
_socket.setdefaulttimeout(10) # set timeout
def | (list_of_domains):
while True:
try:
list_of = urllib.request.urlopen(
"https://ransomwaretracker.abuse.ch/downloads/RW_DOMBL.txt").read().decode(
errors='replace').strip().split("\n")
except IncompleteRead:
continue
except timeout:
... | ransomware_and_malware_domain_check | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.