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 |
|---|---|---|---|---|
exceptions.py | # Copyright (c) 2017 Presslabs SRL
#
# Licensed under the Apache License, Version 2.0 (the "License"); | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing per... | # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# | random_line_split |
exceptions.py | # Copyright (c) 2017 Presslabs SRL
#
# 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 writ... | (APIException):
status_code = status.HTTP_409_CONFLICT
default_detail = 'The request could not be completed due to a conflict ' \
'with the current state of the resource.'
| APIConflictException | identifier_name |
exceptions.py | # Copyright (c) 2017 Presslabs SRL
#
# 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 writ... | status_code = status.HTTP_409_CONFLICT
default_detail = 'The request could not be completed due to a conflict ' \
'with the current state of the resource.' | identifier_body | |
poll.rs | use error::MioResult;
use io::IoHandle;
use os;
use os::token::Token;
use os::event;
pub struct Poll {
selector: os::Selector,
events: os::Events
}
impl Poll {
pub fn new() -> MioResult<Poll> {
Ok(Poll {
selector: try!(os::Selector::new()),
events: os::Events::new()
... | pub fn poll(&mut self, timeout_ms: usize) -> MioResult<usize> {
try!(self.selector.select(&mut self.events, timeout_ms));
Ok(self.events.len())
}
pub fn event(&self, idx: usize) -> event::IoEvent {
self.events.get(idx)
}
pub fn iter(&self) -> EventsIterator {
Events... | random_line_split | |
poll.rs | use error::MioResult;
use io::IoHandle;
use os;
use os::token::Token;
use os::event;
pub struct Poll {
selector: os::Selector,
events: os::Events
}
impl Poll {
pub fn new() -> MioResult<Poll> {
Ok(Poll {
selector: try!(os::Selector::new()),
events: os::Events::new()
... |
}
}
| {
self.index += 1;
Some(self.events.get(self.index - 1))
} | conditional_block |
poll.rs | use error::MioResult;
use io::IoHandle;
use os;
use os::token::Token;
use os::event;
pub struct Poll {
selector: os::Selector,
events: os::Events
}
impl Poll {
pub fn new() -> MioResult<Poll> {
Ok(Poll {
selector: try!(os::Selector::new()),
events: os::Events::new()
... | (&mut self, timeout_ms: usize) -> MioResult<usize> {
try!(self.selector.select(&mut self.events, timeout_ms));
Ok(self.events.len())
}
pub fn event(&self, idx: usize) -> event::IoEvent {
self.events.get(idx)
}
pub fn iter(&self) -> EventsIterator {
EventsIterator { even... | poll | identifier_name |
poll.rs | use error::MioResult;
use io::IoHandle;
use os;
use os::token::Token;
use os::event;
pub struct Poll {
selector: os::Selector,
events: os::Events
}
impl Poll {
pub fn new() -> MioResult<Poll> {
Ok(Poll {
selector: try!(os::Selector::new()),
events: os::Events::new()
... |
pub fn poll(&mut self, timeout_ms: usize) -> MioResult<usize> {
try!(self.selector.select(&mut self.events, timeout_ms));
Ok(self.events.len())
}
pub fn event(&self, idx: usize) -> event::IoEvent {
self.events.get(idx)
}
pub fn iter(&self) -> EventsIterator {
Even... | {
debug!("deregistering IO with poller");
// Deregister interests for this socket
try!(self.selector.deregister(io.desc()));
Ok(())
} | identifier_body |
chrome_trace.rs | ::{Sample, SampleType, StrCow, TracePayloadT};
use serde::Deserialize;
use serde_json;
use std::io::{Error as IOError, Read, Write};
use std::iter::Iterator;
pub enum OutputFormat {
/// Output the samples as a JSON array. Each array entry is an object
/// describing the sample.
JsonArray,
}
#[derive(Debu... | {
let entries = ChromeTraceArrayEntries::deserialize(samples).map_err(Error::Json)?;
Vec::try_from(entries)
} | identifier_body | |
chrome_trace.rs | http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governin... | result.push(sample_to_entry(&sample, false));
}
}
}
ChromeTraceArrayEntries::Array(result)
}
}
// temporary while TryFrom is still nightly.
pub trait XiTryFrom<T>: Sized {
type Error;
fn try_from(value: T) -> Result<Self, Self::Error>;
}
fn t... | random_line_split | |
chrome_trace.rs | http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing pe... | (sample: &Sample, begin: bool) -> &'static str {
match sample.sample_type {
SampleType::Instant => "i",
SampleType::Duration => if begin { "B" } else { "E" },
}
}
fn sample_to_entry(sample: &Sample, begin: bool) -> ChromeTraceArrayEntry {
ChromeTraceArrayEntry {
name: sample.name.cl... | event_type | identifier_name |
lib.rs | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Mattis Marjak (mattis.marjak@gmail.com)
*
* 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, including without limit... | extern crate time;
mod timer;
mod storage;
#[macro_use]
mod macros;
#[cfg(test)]
mod test;
pub use timer::{Timer, TimerAction};
pub use storage::{TimerStorage, TimerEvent}; | trivial_casts, trivial_numeric_casts, unsafe_code,
unstable_features, unused_import_braces, unused_qualifications)]
#[macro_use]
extern crate log; | random_line_split |
generator.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
*/
import {parseDurationToMs} from './duration';
import {Filesystem} from './filesystem';
import {globToRegex} from './... |
return a + b;
} | {
return a + '/' + b;
} | conditional_block |
generator.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
*/
import {parseDurationToMs} from './duration';
import {Filesystem} from './filesystem';
import {globToRegex} from './... |
// Figure out the patterns.
const patterns = (group.resources.urls || [])
.map(
glob => glob.startsWith('/') || glob.indexOf('://') !== -1 ?
glob :
joinUrls(this.baseHref, glob))... | {
const seenMap = new Set<string>();
return Promise.all((config.assetGroups || []).map(async(group) => {
const fileMatcher = globListToMatcher(group.resources.files || []);
const versionedMatcher = globListToMatcher(group.resources.versionedFiles || []);
const allFiles = (await this.fs.list('... | identifier_body |
generator.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
*/
import {parseDurationToMs} from './duration';
import {Filesystem} from './filesystem';
import {globToRegex} from './... | (config: Config, hashTable: {[file: string]: string | undefined}):
Promise<Object[]> {
const seenMap = new Set<string>();
return Promise.all((config.assetGroups || []).map(async(group) => {
const fileMatcher = globListToMatcher(group.resources.files || []);
const versionedMatcher = globListToM... | processAssetGroups | identifier_name |
generator.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
*/
import {parseDurationToMs} from './duration';
import {Filesystem} from './filesystem';
import {globToRegex} from './... | const plainFiles = allFiles.filter(fileMatcher).filter(file => !seenMap.has(file));
plainFiles.forEach(file => seenMap.add(file));
// Add the hashes.
await plainFiles.reduce(async(previous, file) => {
await previous;
const hash = await this.fs.hash(file);
hashTable[joinU... | versionedFiles.forEach(file => seenMap.add(file));
| random_line_split |
p501.rs | // use std::collections::HashMap;
use common::iter;
use std::thread;
use std::sync::Arc;
use std::sync::mpsc;
use tempfile::NamedTempFileOptions;
use std::io::Write;
use std::io::BufReader;
use tempfile::NamedTempFile;
use std::io::BufRead;
fn prim_vec(max: &u64) -> NamedTempFile {
let mut named_temp_file = NamedT... | }
named_temp_file
}
pub fn exe(max: u64) -> u64 {
let tmp_file = prim_vec(&max);
//;
let primes = BufReader::new(tmp_file.reopen().unwrap())
.lines()
.map(|l| &l.unwrap().parse::<u64>().unwrap());
println!("素数生成完了");
let count_1: u64 = (&primes.cloned()).take_while(|&a|... | for i in iter::prime_iter().take_while(|i| i < &prime_max) {
writeln!(&mut named_temp_file, "{}", i);
| random_line_split |
p501.rs | // use std::collections::HashMap;
use common::iter;
use std::thread;
use std::sync::Arc;
use std::sync::mpsc;
use tempfile::NamedTempFileOptions;
use std::io::Write;
use std::io::BufReader;
use tempfile::NamedTempFile;
use std::io::BufRead;
fn prim_vec(max: &u64) -> NamedTempFile {
let mut named_temp_file = NamedT... | (max: u64) -> u64 {
let tmp_file = prim_vec(&max);
//;
let primes = BufReader::new(tmp_file.reopen().unwrap())
.lines()
.map(|l| &l.unwrap().parse::<u64>().unwrap());
println!("素数生成完了");
let count_1: u64 = (&primes.cloned()).take_while(|&a| a * a * a * a * a * a * a < max)
// ... | exe | identifier_name |
p501.rs | // use std::collections::HashMap;
use common::iter;
use std::thread;
use std::sync::Arc;
use std::sync::mpsc;
use tempfile::NamedTempFileOptions;
use std::io::Write;
use std::io::BufReader;
use tempfile::NamedTempFile;
use std::io::BufRead;
fn prim_vec(max: &u64) -> NamedTempFile {
let mut named_temp_file = NamedT... | fn exe_100_bench(b: &mut Bencher) {
b.iter(|| super::exe(100));
}
#[test]
fn exe_1_000_test() {
assert_eq!(super::exe(1_000), 180);
}
#[bench]
fn exe_1_000_bench(b: &mut Bencher) {
b.iter(|| super::exe(1_000));
}
// test prob501_600::prob501_510::p501::tests::ex... | (super::exe(100), 10);
}
#[bench]
| identifier_body |
int8array_builder.ts | // DO NOT EDIT. Generated from templates/neuroglancer/util/typedarray_builder.template.ts.
/**
* @license
* Copyright 2016 Google Inc.
* 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
*
... | (other: ArrayLike<number>) {
let {length} = this;
this.resize(length + other.length);
this.data.set(other, length);
}
};
| appendArray | identifier_name |
int8array_builder.ts | // DO NOT EDIT. Generated from templates/neuroglancer/util/typedarray_builder.template.ts.
/**
* @license
* Copyright 2016 Google Inc.
* 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
*
... | * See the License for the specific language governing permissions and
* limitations under the License.
*/
export class Int8ArrayBuilder {
length = 0;
data: Int8Array;
constructor(initialCapacity: number = 16) { this.data = new Int8Array(initialCapacity); }
resize(newLength: number) {
let {data} = this... | * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split |
int8array_builder.ts | // DO NOT EDIT. Generated from templates/neuroglancer/util/typedarray_builder.template.ts.
/**
* @license
* Copyright 2016 Google Inc.
* 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
*
... |
this.length = newLength;
}
get view() {
let {data} = this;
return new Int8Array(data.buffer, data.byteOffset, this.length);
}
shrinkToFit() { this.data = new Int8Array(this.view); }
clear() { this.length = 0; }
appendArray(other: ArrayLike<number>) {
let {length} = this;
this.resize... | {
let newData = new Int8Array(Math.max(newLength, data.length * 2));
newData.set(data.subarray(0, this.length));
this.data = newData;
} | conditional_block |
int8array_builder.ts | // DO NOT EDIT. Generated from templates/neuroglancer/util/typedarray_builder.template.ts.
/**
* @license
* Copyright 2016 Google Inc.
* 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
*
... |
resize(newLength: number) {
let {data} = this;
if (newLength > data.length) {
let newData = new Int8Array(Math.max(newLength, data.length * 2));
newData.set(data.subarray(0, this.length));
this.data = newData;
}
this.length = newLength;
}
get view() {
let {data} = this;
... | { this.data = new Int8Array(initialCapacity); } | identifier_body |
result-list.js | 'use strict';
import ResponseHandler from './response-handler';
import retrieve from './retrieve';
class ResultList {
constructor(search, options, onSuccess, onFailure) {
this._search = search;
this._options = options;
this._onSuccess = onSuccess;
this._onFailure = onFailure;
this._requestPromi... |
previous() {
if (this._options.page <= 1) {
throw new Error('There is no previous page');
}
const previousPage = this._options.page -= 1;
if (this._requestPromises[previousPage]) {
return this._requestPromises[previousPage];
}
return this._get();
}
_get() {
const page... | {
const nextPage = this._options.page += 1;
if (this._requestPromises[nextPage]) {
return this._requestPromises[nextPage];
}
return this._get();
} | identifier_body |
result-list.js | 'use strict';
import ResponseHandler from './response-handler';
import retrieve from './retrieve';
class ResultList {
constructor(search, options, onSuccess, onFailure) {
this._search = search;
this._options = options;
this._onSuccess = onSuccess;
this._onFailure = onFailure;
this._requestPromi... |
return this._get();
}
previous() {
if (this._options.page <= 1) {
throw new Error('There is no previous page');
}
const previousPage = this._options.page -= 1;
if (this._requestPromises[previousPage]) {
return this._requestPromises[previousPage];
}
return this._get();
... | {
return this._requestPromises[nextPage];
} | conditional_block |
result-list.js | 'use strict';
import ResponseHandler from './response-handler';
import retrieve from './retrieve';
class ResultList {
constructor(search, options, onSuccess, onFailure) {
this._search = search;
this._options = options;
this._onSuccess = onSuccess;
this._onFailure = onFailure;
this._requestPromi... | export default ResultList; | random_line_split | |
result-list.js | 'use strict';
import ResponseHandler from './response-handler';
import retrieve from './retrieve';
class ResultList {
constructor(search, options, onSuccess, onFailure) {
this._search = search;
this._options = options;
this._onSuccess = onSuccess;
this._onFailure = onFailure;
this._requestPromi... | (page, perPage) {
return res => {
const resHndlr = new ResponseHandler(res, page, perPage, this._onSuccess);
return resHndlr.success();
};
}
_failure(page, perPage) {
return res => {
const resHndlr = new ResponseHandler(res, page, perPage, this._onFailure);
return resHndlr.failu... | _success | identifier_name |
mem_init.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... |
/// Helper function to initialize memory.
/// Copies `.data` sections in to RAM and initializes `.bss` sections to zero.
#[inline(always)]
pub fn init_data() {
unsafe {
let mut load_addr: *const u32 = &_data_load;
let mut mem_addr: *mut u32 = &mut _data;
while mem_addr < &mut _edata as *mut u32 {
... | {
set_stack_limit( unsafe { (&_eglobals as *const u32) } as u32);
} | identifier_body |
mem_init.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | () {
unsafe {
let mut load_addr: *const u32 = &_data_load;
let mut mem_addr: *mut u32 = &mut _data;
while mem_addr < &mut _edata as *mut u32 {
*mem_addr = *load_addr;
mem_addr = ((mem_addr as u32) + 4) as *mut u32;
load_addr = ((load_addr as u32) + 4) as *const u32;
}
mem_addr =... | init_data | identifier_name |
mem_init.rs | // Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// 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.o... | set_stack_limit( unsafe { (&_eglobals as *const u32) } as u32);
}
/// Helper function to initialize memory.
/// Copies `.data` sections in to RAM and initializes `.bss` sections to zero.
#[inline(always)]
pub fn init_data() {
unsafe {
let mut load_addr: *const u32 = &_data_load;
let mut mem_addr: *mut u32 ... |
/// Helper function to initialise the stack limit.
#[inline(always)]
pub fn init_stack() { | random_line_split |
PatchManifestStageForm.tsx | import { capitalize, get, isEmpty, map } from 'lodash';
import React from 'react';
import type { Option } from 'react-select';
import type { IArtifact, IExpectedArtifact, IFormikStageConfigInjectedProps } from '@spinnaker/core';
import {
ArtifactTypePatterns,
RadioButtonInput,
StageArtifactSelectorDelegate,
St... | (props: IPatchManifestStageConfigFormProps & IFormikStageConfigInjectedProps) {
super(props);
const patchBody: any[] = get(props.formik.values, 'patchBody');
const isTextManifest: boolean = get(props.formik.values, 'source') === ManifestSource.TEXT;
this.state = {
rawManifest: !isEmpty(patchBody) ... | constructor | identifier_name |
PatchManifestStageForm.tsx | import { capitalize, get, isEmpty, map } from 'lodash';
import React from 'react';
import type { Option } from 'react-select';
import type { IArtifact, IExpectedArtifact, IFormikStageConfigInjectedProps } from '@spinnaker/core';
import {
ArtifactTypePatterns,
RadioButtonInput,
StageArtifactSelectorDelegate,
St... |
private onManifestArtifactSelected = (expectedArtifactId: string): void => {
this.props.formik.setFieldValue('manifestArtifactId', expectedArtifactId);
this.props.formik.setFieldValue('manifestArtifact', null);
};
private onManifestArtifactEdited = (artifact: IArtifact) => {
this.props.formik.setFi... | {
super(props);
const patchBody: any[] = get(props.formik.values, 'patchBody');
const isTextManifest: boolean = get(props.formik.values, 'source') === ManifestSource.TEXT;
this.state = {
rawManifest: !isEmpty(patchBody) && isTextManifest ? yamlDocumentsToString(patchBody) : '',
};
} | identifier_body |
PatchManifestStageForm.tsx | import { capitalize, get, isEmpty, map } from 'lodash';
import React from 'react';
import type { Option } from 'react-select';
import type { IArtifact, IExpectedArtifact, IFormikStageConfigInjectedProps } from '@spinnaker/core';
import {
ArtifactTypePatterns,
RadioButtonInput,
StageArtifactSelectorDelegate,
St... | );
}
} | </div> | random_line_split |
checks.py | from django.conf import settings
from django.core.checks import Error, register
@register
def check_threshold(app_configs, **kwargs):
'''
Checks if THRESHOLD is set on settings.py
'''
errors = []
if not hasattr(settings, 'THRESHOLD'):
|
return errors
@register
def check_aws_credentials(app_configs, **kwargs):
'''
Checks if THRESHOLD is set on settings.py
'''
errors = []
expected = ('AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_STORAGE_BUCKET_NAME')
for exp in expected:
if not hasattr(settings, exp):
... | errors.append(Error(
'settings must have the threshold for clustering',
hint='Add THRESHOLD=0.0005 to your settings.py file',
obj=settings,
id='aedes.e_001'
)) | conditional_block |
checks.py | from django.conf import settings
from django.core.checks import Error, register
| errors = []
if not hasattr(settings, 'THRESHOLD'):
errors.append(Error(
'settings must have the threshold for clustering',
hint='Add THRESHOLD=0.0005 to your settings.py file',
obj=settings,
id='aedes.e_001'
))
return errors
@register
def che... | @register
def check_threshold(app_configs, **kwargs):
'''
Checks if THRESHOLD is set on settings.py
''' | random_line_split |
checks.py | from django.conf import settings
from django.core.checks import Error, register
@register
def check_threshold(app_configs, **kwargs):
|
@register
def check_aws_credentials(app_configs, **kwargs):
'''
Checks if THRESHOLD is set on settings.py
'''
errors = []
expected = ('AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_STORAGE_BUCKET_NAME')
for exp in expected:
if not hasattr(settings, exp):
errors.append... | '''
Checks if THRESHOLD is set on settings.py
'''
errors = []
if not hasattr(settings, 'THRESHOLD'):
errors.append(Error(
'settings must have the threshold for clustering',
hint='Add THRESHOLD=0.0005 to your settings.py file',
obj=settings,
id='aed... | identifier_body |
checks.py | from django.conf import settings
from django.core.checks import Error, register
@register
def | (app_configs, **kwargs):
'''
Checks if THRESHOLD is set on settings.py
'''
errors = []
if not hasattr(settings, 'THRESHOLD'):
errors.append(Error(
'settings must have the threshold for clustering',
hint='Add THRESHOLD=0.0005 to your settings.py file',
obj=... | check_threshold | identifier_name |
lib.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/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![cfg_attr(fea... | {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
} | identifier_body | |
lib.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/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![cfg_attr(fea... | #[cfg(feature = "non-geckolib")]
pub mod non_geckolib;
pub mod opts;
pub mod persistent_list;
pub mod prefs;
pub mod print_tree;
pub mod range;
pub mod resource_files;
pub mod str;
pub mod thread;
pub mod thread_state;
pub mod threadpool;
pub mod tid;
pub mod time;
pub mod vec;
pub mod workqueue;
pub fn breakpoint() {... | pub mod logical_geometry;
#[macro_use] pub mod mem; | random_line_split |
lib.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/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![cfg_attr(fea... | () {
unsafe { ::std::intrinsics::breakpoint() };
}
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T: 'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
| breakpoint | identifier_name |
PyCOBRA_run.py | import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import c, e, m_p
import matplotlib.pyplot as plt
plt.switch_backend('TkAgg')
plt.ion()
from PyCOBRA_accelerator import TwissMap
from PyCOBRA_beam import Bunch, gaussian_generator
R = 6911./(2*np.pi)
energy = 26e9
gamma = np.sqrt(1 + (e*energy/(... |
plt.close()
| for m in one_turn_map:
m.kick(bunch)
ax1.scatter(bunch.x, bunch.xp, c='g', lw=0.1)
ax2.scatter(bunch.y, bunch.yp, c='g', lw=0.1)
ax3.scatter(bunch.z, bunch.dp, c='g', lw=0.1)
ax1.plot(np.mean(bunch.x), np.mean(bunch.xp), 'ro')
ax2.plot(np.mean(bunch.y), np.mean(bunch.yp), 'ro')
ax3.plo... | conditional_block |
PyCOBRA_run.py | import numpy as np
import matplotlib.pyplot as plt
from scipy.constants import c, e, m_p
import matplotlib.pyplot as plt
plt.switch_backend('TkAgg')
plt.ion()
from PyCOBRA_accelerator import TwissMap
from PyCOBRA_beam import Bunch, gaussian_generator
R = 6911./(2*np.pi)
energy = 26e9
gamma = np.sqrt(1 + (e*energy/(... | plt.draw()
[ax.cla() for ax in [ax1, ax2, ax3]]
plt.close() | random_line_split | |
cloned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::clone::Clone;
// #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub enum Option<T> {
// /// No value
// #[stable(feature = "rust1", since = "... |
}
type T = i32; // T: Clone
#[test]
fn cloned_test1() {
let a: A<T> = A { value: 68 };
let x: Option<&A<T>> = Some::<&A<T>>(&a);
let cloned: Option<A<T>> = x.cloned();
assert_eq!(x.unwrap().value, 68);
assert_eq!(cloned.unwrap().value, 68);
}
}
| {
A { value: self.value }
} | identifier_body |
cloned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::clone::Clone;
// #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub enum Option<T> {
// /// No value
// #[stable(feature = "rust1", since = "... | fn clone(&self) -> Self
{
A { value: self.value }
}
}
type T = i32; // T: Clone
#[test]
fn cloned_test1() {
let a: A<T> = A { value: 68 };
let x: Option<&A<T>> = Some::<&A<T>>(&a);
let cloned: Option<A<T>> = x.cloned();
assert_eq!(x.unwrap().value, 68);
assert_eq!(cloned.unwrap().value,... | struct A<T> {
value: T
}
impl Clone for A<T> { | random_line_split |
cloned.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::clone::Clone;
// #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub enum Option<T> {
// /// No value
// #[stable(feature = "rust1", since = "... | () {
let a: A<T> = A { value: 68 };
let x: Option<&A<T>> = Some::<&A<T>>(&a);
let cloned: Option<A<T>> = x.cloned();
assert_eq!(x.unwrap().value, 68);
assert_eq!(cloned.unwrap().value, 68);
}
}
| cloned_test1 | identifier_name |
test.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Command = require('../ember-cli/lib/models/command');
const test_1 = require("../tasks/test");
const config_1 = require("../models/config");
const common_tags_1 = require("common-tags");
const config = config_1.CliConfig.fromProject() ||... | description: 'Log progress to the console while in progress.'
},
{
name: 'browsers',
type: String,
description: 'Override which browsers tests are run against.'
},
{
name: 'colors',
type: Boolean,
descrip... | type: Boolean,
default: testConfigDefaults['progress'], | random_line_split |
test.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Command = require('../ember-cli/lib/models/command');
const test_1 = require("../tasks/test");
const config_1 = require("../models/config");
const common_tags_1 = require("common-tags");
const config = config_1.CliConfig.fromProject() ||... |
return testTask.run(commandOptions);
}
});
TestCommand.overrideCore = true;
exports.default = TestCommand;
//# sourceMappingURL=/users/hansl/sources/angular-cli/commands/test.js.map | {
// if not watching ensure karma is doing a single run
commandOptions.singleRun = true;
} | conditional_block |
executer.rs | use std::error;
use std::process;
use crate::command::error::CommandError;
use crate::config;
use crate::output;
use super::super::Executer as ParamsExecuter;
use super::{Arguments, Program};
pub struct Executer<'c> {
config: &'c config::command::ParamsConfig,
}
impl<'c> Executer<'c> {
pub fn from_config(co... |
}
| {
&self.config
} | identifier_body |
executer.rs | use std::error;
use std::process;
use crate::command::error::CommandError;
use crate::config;
use crate::output;
use super::super::Executer as ParamsExecuter;
use super::{Arguments, Program};
pub struct Executer<'c> {
config: &'c config::command::ParamsConfig,
}
impl<'c> Executer<'c> {
pub fn from_config(co... | }
} | random_line_split | |
executer.rs | use std::error;
use std::process;
use crate::command::error::CommandError;
use crate::config;
use crate::output;
use super::super::Executer as ParamsExecuter;
use super::{Arguments, Program};
pub struct Executer<'c> {
config: &'c config::command::ParamsConfig,
}
impl<'c> Executer<'c> {
pub fn from_config(co... | (
&self,
program: &'c Program<'c>,
args: &'c Arguments<'c>,
) -> Result<(), Box<dyn error::Error>> {
trace!("command::params::exec::Executer::run");
info!("exec: {} {}", program, args.join(" "));
let params = self.params().await?;
let mut cmd = process::Comma... | run | identifier_name |
executer.rs | use std::error;
use std::process;
use crate::command::error::CommandError;
use crate::config;
use crate::output;
use super::super::Executer as ParamsExecuter;
use super::{Arguments, Program};
pub struct Executer<'c> {
config: &'c config::command::ParamsConfig,
}
impl<'c> Executer<'c> {
pub fn from_config(co... | else {
output::PrintLine::error(&format!(
"Command exit with status code: {}",
output.code().unwrap_or(0)
));
Err(Box::new(CommandError::Unknown))
}
}
}
impl<'c> ParamsExecuter for Executer<'c> {
fn config(&self) -> &config::command::... | {
Ok(())
} | conditional_block |
raw_building.py | return
cls_bases = [ancestor.__name__ for ancestor in python_cls.__bases__]
ast_klass = build_class(cls_name, cls_bases, python_cls.__doc__)
func.instance_attrs['__class__'] = [ast_klass]
_marker = object()
def attach_dummy_node(node, name, runtime_object=_marker):
"""create a dummy node and... | (func, args=None):
"""add given arguments to local
args is a list that may contains nested lists
(i.e. def func(a, (b, c, d)): ...)
"""
if args is None:
args = func.args.args
if func.args.vararg:
func.set_local(func.args.vararg, func.args)
if func.args.kwarg:
... | register_arguments | identifier_name |
raw_building.py | return
cls_bases = [ancestor.__name__ for ancestor in python_cls.__bases__]
ast_klass = build_class(cls_name, cls_bases, python_cls.__doc__)
func.instance_attrs['__class__'] = [ast_klass]
_marker = object()
def attach_dummy_node(node, name, runtime_object=_marker):
"""create a dummy node and... |
def register_arguments(func, args=None):
"""add given arguments to local
args is a list that may contains nested lists
(i.e. def func(a, (b, c, d)): ...)
"""
if args is None:
args = func.args.args
if func.args.vararg:
func.set_local(func.args.vararg, func.args)
... | """create and initialize an astroid ImportFrom import statement"""
return nodes.ImportFrom(fromname, [(name, None) for name in names]) | identifier_body |
raw_building.py | return
cls_bases = [ancestor.__name__ for ancestor in python_cls.__bases__]
ast_klass = build_class(cls_name, cls_bases, python_cls.__doc__)
func.instance_attrs['__class__'] = [ast_klass]
_marker = object()
def attach_dummy_node(node, name, runtime_object=_marker):
"""create a dummy node and... |
def object_build_class(node, member, localname):
"""create astroid for a living class object"""
basenames = [base.__name__ for base in member.__bases__]
return _base_class_object_build(node, member, basenames,
localname=localname)
def object_build_function(node, memb... | if isinstance(arg, nodes.Name):
func.set_local(arg.name, arg)
else:
register_arguments(func, arg.elts) | conditional_block |
raw_building.py | :
return
cls_bases = [ancestor.__name__ for ancestor in python_cls.__bases__]
ast_klass = build_class(cls_name, cls_bases, python_cls.__doc__)
func.instance_attrs['__class__'] = [ast_klass]
_marker = object()
def attach_dummy_node(node, name, runtime_object=_marker):
"""create a dummy node a... | argsnode.defaults[-1].parent = argsnode
argsnode.kwarg = None
argsnode.vararg = None
argsnode.parent = func
if args:
register_arguments(func)
return func
def build_from_import(fromname, names):
"""create and initialize an astroid ImportFrom import statement"""
return nodes.... | argsnode.defaults.append(nodes.const_factory(default)) | random_line_split |
task-comm-11.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn main() {
let (p, ch) = comm::stream();
let _child = task::spawn(proc() start(&ch) );
let _c = p.recv();
}
| {
let (_p, ch) = comm::stream();
c.send(ch);
} | identifier_body |
task-comm-11.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. | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
extern mod extra;
use std::comm;
use std::task;
fn start(c: &comm::Chan... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
task-comm-11.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 (p, ch) = comm::stream();
let _child = task::spawn(proc() start(&ch) );
let _c = p.recv();
}
| main | identifier_name |
scope_table_builder.rs | //! Build the scope table and make sure all variables/symbols can be resolved |
use driver::interner::Ident;
use driver::session;
use driver::symbol_table::SymbolTable;
use front::ast::*;
use front::ast::visit::*;
struct ScopeTableBuilder<'a> {
current_scope: Option<NodeId>,
current_symbol: Option<Ident>,
sytbl: &'a SymbolTable
}
impl<'a> ScopeTableBuilder<'a> {
fn new(sytbl: &... | random_line_split | |
scope_table_builder.rs | //! Build the scope table and make sure all variables/symbols can be resolved
use driver::interner::Ident;
use driver::session;
use driver::symbol_table::SymbolTable;
use front::ast::*;
use front::ast::visit::*;
struct ScopeTableBuilder<'a> {
current_scope: Option<NodeId>,
current_symbol: Option<Ident>,
... |
}
// Continue walking the expression
walk_expression(self, expr)
}
}
pub fn run(program: &[Node<Symbol>]) {
let symbol_table = &session().symbol_table;
let mut visitor = ScopeTableBuilder::new(symbol_table);
walk_program(&mut visitor, program);
session().abort_if_errors()... | {} | conditional_block |
scope_table_builder.rs | //! Build the scope table and make sure all variables/symbols can be resolved
use driver::interner::Ident;
use driver::session;
use driver::symbol_table::SymbolTable;
use front::ast::*;
use front::ast::visit::*;
struct ScopeTableBuilder<'a> {
current_scope: Option<NodeId>,
current_symbol: Option<Ident>,
... | (&self, expr: &Node<Expression>) {
// Get function name
let name = if let Expression::Variable { ref name } = **expr {
name
} else {
fatal_at!("cannot call non-function"; expr);
return
};
// Look up the symbol in the symbol table
let s... | resolve_call | identifier_name |
scope_table_builder.rs | //! Build the scope table and make sure all variables/symbols can be resolved
use driver::interner::Ident;
use driver::session;
use driver::symbol_table::SymbolTable;
use front::ast::*;
use front::ast::visit::*;
struct ScopeTableBuilder<'a> {
current_scope: Option<NodeId>,
current_symbol: Option<Ident>,
... |
fn visit_expression(&mut self, expr: &'v Node<Expression>) {
match **expr {
Expression::Call { ref func, .. } => {
self.resolve_call(func);
return // Don't visit sub-expressions
},
Expression::Variable { ref name } => {
s... | {
if let Statement::Declaration { ref binding, .. } = **stmt {
self.resolve_declaration(binding);
}
walk_statement(self, stmt)
} | identifier_body |
album.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import { Album } from '../_models';
@Injectable()
export class AlbumService {
constructor(private http: Http) { }
... |
});
}
public getUserById(id: number): Observable<Album[]> {
return this.http.get('http://localhost:8090/api/users/' + id, this.jwt())
.map((response: Response) => {
let user = response.json();
return user;
})
.catch((e) => {
if (e.st... | {
return Observable.throw('Unauthorized');
} | conditional_block |
album.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import { Album } from '../_models';
@Injectable()
export class AlbumService {
constructor(private http: Http) |
public getAll(): Observable<Album[]> {
return this.http.get('http://localhost:8090/api/albums', this.jwt())
.map((response: Response) => {
let albums = response.json();
return albums;
})
.catch((e) => {
if (e.status === 401) {
re... | { } | identifier_body |
album.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import { Album } from '../_models';
@Injectable()
export class AlbumService {
constructor(private http: Http) { }
... | () {
// create authorization header with jwt token
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
let headers = new Headers({'Content-Type': 'application/json'});
headers.append('Authorization', 'Bearer ' + curr... | jwt | identifier_name |
album.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import { Album } from '../_models';
@Injectable()
export class AlbumService {
constructor(private http: Http) { }
... | }
});
}
public getUserById(id: number): Observable<Album[]> {
return this.http.get('http://localhost:8090/api/users/' + id, this.jwt())
.map((response: Response) => {
let user = response.json();
return user;
})
.catch((e) => {
... | if (e.status === 401) {
return Observable.throw('Unauthorized'); | random_line_split |
issue-11709.rs | // run-pass
#![allow(dead_code)]
// ignore-pretty issue #37199
// Don't panic on blocks without results
// There are several tests in this run-pass that raised
// when this bug was opened. The cases where the compiler
// panics before the fix have a comment.
struct S {x:()}
fn test(slot: &mut Option<Box<dyn FnMut() ... | () {
// {} would break
let _r = {};
let mut slot = None;
// `{ test(...); }` would break
let _s : S = S{ x: { test(&mut slot); } };
let _b = not(true);
}
| main | identifier_name |
issue-11709.rs | // run-pass
#![allow(dead_code)]
// ignore-pretty issue #37199
// Don't panic on blocks without results
// There are several tests in this run-pass that raised
// when this bug was opened. The cases where the compiler
// panics before the fix have a comment.
struct S {x:()}
fn test(slot: &mut Option<Box<dyn FnMut() ... | else {
// `panic!(...)` would break
panic!("Break the compiler");
}
}
pub fn main() {
// {} would break
let _r = {};
let mut slot = None;
// `{ test(...); }` would break
let _s : S = S{ x: { test(&mut slot); } };
let _b = not(true);
}
| {
!b
} | conditional_block |
issue-11709.rs | // run-pass
#![allow(dead_code)]
// ignore-pretty issue #37199
// Don't panic on blocks without results
// There are several tests in this run-pass that raised
// when this bug was opened. The cases where the compiler
// panics before the fix have a comment.
struct S {x:()}
fn test(slot: &mut Option<Box<dyn FnMut() ... |
let _b = not(true);
} | // `{ test(...); }` would break
let _s : S = S{ x: { test(&mut slot); } }; | random_line_split |
genericRestParameters1.ts | // @declaration: true
declare let f1: (...x: [number, string, boolean]) => void;
declare let f2: (x0: number, x1: string, x2: boolean) => void;
f1 = f2;
f2 = f1;
declare const t3: [number, string, boolean];
declare const t2: [string, boolean];
declare const t1: [boolean];
declare const t0: [];
declare ... |
function callr<T extends unknown[], U>(args: T, f: (...args: T) => U) {
return f(...args);
}
declare function f15(a: string, b: number): string | number;
declare function f16<A, B>(a: A, b: B): A | B;
let x20 = call((x, y) => x + y, 10, 20); // number
let x21 = call((x, y) => x + y, 10, "hello"); //... | {
return f(...args);
} | identifier_body |
genericRestParameters1.ts | // @declaration: true
declare let f1: (...x: [number, string, boolean]) => void;
declare let f2: (x0: number, x1: string, x2: boolean) => void;
f1 = f2;
f2 = f1;
declare const t3: [number, string, boolean];
declare const t2: [string, boolean];
declare const t1: [boolean];
declare const t0: [];
declare ... |
const z10 = f11(42, "hello", true); // [42, "hello", true]
const z11 = f11(42, "hello"); // [42, "hello"]
const z12 = f11(42); // [42]
const z13 = f11(); // []
const z14 = f11(...t3); // [number, string, boolean]
const z15 = f11(42, ...t2); // [42, string, boolean]
const z16 = f11(42, "hello", ...t1); //... | let x4 = f10(...u, ...v); // (string | number)[]
}
declare function f11<T extends (string | number | boolean)[]>(...args: T): T;
| random_line_split |
genericRestParameters1.ts | // @declaration: true
declare let f1: (...x: [number, string, boolean]) => void;
declare let f2: (x0: number, x1: string, x2: boolean) => void;
f1 = f2;
f2 = f1;
declare const t3: [number, string, boolean];
declare const t2: [string, boolean];
declare const t1: [boolean];
declare const t0: [];
declare ... | <T extends unknown[], U>(args: T, f: (...args: T) => U) {
return f(...args);
}
declare function f15(a: string, b: number): string | number;
declare function f16<A, B>(a: A, b: B): A | B;
let x20 = call((x, y) => x + y, 10, 20); // number
let x21 = call((x, y) => x + y, 10, "hello"); // string
let x22 =... | callr | identifier_name |
setup.ts | import fs from "fs";
import path from "path";
import { BrowserWindow, ipcMain, WebContents } from "electron";
import type * as ExtensionsModule from "eez-studio-shared/extensions/extensions";
import { IExtension } from "eez-studio-shared/extensions/extension";
import { delay } from "eez-studio-shared/util";
i... | win.loadURL(`file://${__dirname}/../setup/setup.html`);
win.show();
ipcMain.on("startSetup", async event => {
await doSetup(event.sender);
win.close();
resolve();
});
});
} | });
require("@electron/remote/main").enable(win.webContents);
win.setMenu(null);
| random_line_split |
setup.ts | import fs from "fs";
import path from "path";
import { BrowserWindow, ipcMain, WebContents } from "electron";
import type * as ExtensionsModule from "eez-studio-shared/extensions/extensions";
import { IExtension } from "eez-studio-shared/extensions/extension";
import { delay } from "eez-studio-shared/util";
i... |
});
webContents.send(
"setupMessage",
`Installing ${fileList.length} extensions`
);
const { installExtension } =
require("eez-studio-shared/extensions/extensions") as typeof ExtensionsModule;
for (let i = 0; i < fileList.length; i++) {
const filePath =... | {
fileList.push(filePath);
} | conditional_block |
setup.ts | import fs from "fs";
import path from "path";
import { BrowserWindow, ipcMain, WebContents } from "electron";
import type * as ExtensionsModule from "eez-studio-shared/extensions/extensions";
import { IExtension } from "eez-studio-shared/extensions/extension";
import { delay } from "eez-studio-shared/util";
i... | (
webContents: WebContents,
resourcesPath: string,
extensionsFolderPath: string
) {
webContents.send("setupMessage", "Making extensions folder");
await makeFolder(extensionsFolderPath);
await delay(500);
const fileList: string[] = [];
fs.readdirSync(resourcesPath).forEach(fi... | setupExtensions | identifier_name |
setup.ts | import fs from "fs";
import path from "path";
import { BrowserWindow, ipcMain, WebContents } from "electron";
import type * as ExtensionsModule from "eez-studio-shared/extensions/extensions";
import { IExtension } from "eez-studio-shared/extensions/extension";
import { delay } from "eez-studio-shared/util";
i... | width: 600,
height: 200,
backgroundColor: "#333",
show: false
});
require("@electron/remote/main").enable(win.webContents);
win.setMenu(null);
win.loadURL(`file://${__dirname}/../setup/setup.html`);
win.show();
... | {
return new Promise<void>(resolve => {
if (isDev || !isAnySetupRequired()) {
const { loadExtensions } =
require("eez-studio-shared/extensions/extensions") as typeof ExtensionsModule;
loadExtensions([]);
resolve();
return;
}
... | identifier_body |
game.ts | import { Component, HostListener, OnInit } from '@angular/core';
import { Platform, AlertController, IonicPage, ModalController, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
impor... |
facebookLogin() {
let _this2 = this;
let provider = new firebase.auth.FacebookAuthProvider();
if (this.googleUser != '') {
this.googleUser.linkWithPopup(provider).then(function(result) {
// Accounts successfully linked.
// var credential = result.credential;
_this2.facebook... | {
let _this2 = this;
firebase.auth().signOut().then(function() {
_this2.googleUser = '';
}).catch(function(error) {
});
} | identifier_body |
game.ts | import { Component, HostListener, OnInit } from '@angular/core';
import { Platform, AlertController, IonicPage, ModalController, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
impor... |
}
}
]
});
alert.present();
}
}
viewLeaderboard() {
let modal = this.modalCtrl.create(LeaderboardPage);
modal.present();
}
}
| {
this.highScores.push({
name: data.name,
score: scoreInt
});
this.score = "submitted";
} | conditional_block |
game.ts | import { Component, HostListener, OnInit } from '@angular/core';
import { Platform, AlertController, IonicPage, ModalController, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
impor... | implements OnInit {
highScores: FirebaseListObservable<any[]>;
facebookUser: any;
googleUser: any;
score: string;
counter: number;
adReady: boolean;
rewardReady: boolean;
admobid: AdMobType;
@HostListener('window:gameScore', ['$event'])
testListener(event) {
this.counter += 1;
console.log(... | GamePage | identifier_name |
game.ts | import { Component, HostListener, OnInit } from '@angular/core';
import { Platform, AlertController, IonicPage, ModalController, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
impor... | this.googleUser.linkWithPopup(provider).then(function(result) {
// Accounts successfully linked.
// var credential = result.credential;
_this2.facebookUser = result.user;
}).catch(function(error) {
// Handle Errors here.
});
} else {
provider.setCustomParamete... | facebookLogin() {
let _this2 = this;
let provider = new firebase.auth.FacebookAuthProvider();
if (this.googleUser != '') { | random_line_split |
schemas.js | /**
* UserCountry schema
* @type {SimpleSchema}
*/
Schemas.UserCountry = new SimpleSchema({
name: {
type: String
},
code: {
type: String,
regEx: /^[A-Z]{2}$/
}
});
/**
* UserProfile
* @type {SimpleSchema}
*/
Schemas.UserProfile = new SimpleSchema({
picture: {
... | });
}
},
optional: true
},
emails: {
type: [Object],
// this must be optional if you also use other login services like facebook,
// but if you use only accounts-password, then it can be required
optional: true
},
"emails.$.addr... | Meteor.call("validUserName", this.value, function (error, result) {
if (result) {
Meteor.users.simpleSchema().namedContext("setUsername").addInvalidKeys([{name: "username", type: "notUnique"}]);
} | random_line_split |
empty-enum.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
pub type EmptyConstified = u32;
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum | {
__bindgen_cannot_repr_c_on_empty_enum = 0,
}
pub mod EmptyModule {
pub type Type = u32;
}
#[repr(i8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum EmptyClassRustified {
__bindgen_cannot_repr_c_on_empty_enum = 0,
}
pub type EmptyClassConstified = i8;
pub mod EmptyClassModule {
pub type ... | EmptyRustified | identifier_name |
empty-enum.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
pub type EmptyConstified = u32;
#[repr(u32)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum EmptyRustified {
__bindgen_cannot_repr_c_on_empty_enum = 0, | pub mod EmptyModule {
pub type Type = u32;
}
#[repr(i8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum EmptyClassRustified {
__bindgen_cannot_repr_c_on_empty_enum = 0,
}
pub type EmptyClassConstified = i8;
pub mod EmptyClassModule {
pub type Type = i8;
}
#[repr(i8)]
#[derive(Debug, Copy, Clone... | } | random_line_split |
video.component.spec.ts | /* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { StoreService } from './../../core/store.service';
import { ScoreService } from './../../core/score.ser... | imports: [
RouterTestingModule,
StoreModule.provideStore(rootReducer),
SharedModule
],
providers: [ScoreService, StoreService]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AdminVideoComponent);
component = fixture.compo... | beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AdminVideoComponent, TimerComponent, NextComponent ], | random_line_split |
logstash_plugin.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Loic Blot <loic.blot@unix-experience.fr>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.... |
module.exit_json(changed=changed, cmd=cmd, name=name, state=state, stdout=out, stderr=err)
if __name__ == '__main__':
main()
| changed, cmd, out, err = remove_plugin(module, plugin_bin, name) | conditional_block |
logstash_plugin.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Loic Blot <loic.blot@unix-experience.fr>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.... | logstash_plugin:
state: present
name: logstash-input-syslog
version: '3.2.0'
- name: Uninstall Logstash plugin
logstash_plugin:
state: absent
name: logstash-filter-multiline
'''
from ansible.module_utils.basic import AnsibleModule
PACKAGE_STATE_MAP = dict(
present="install",
absent="... | - name: Install specific version of a plugin | random_line_split |
logstash_plugin.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Loic Blot <loic.blot@unix-experience.fr>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.... | (module, plugin_bin, plugin_name, version, proxy_host, proxy_port):
cmd_args = [plugin_bin, PACKAGE_STATE_MAP["present"], plugin_name]
if version:
cmd_args.append("--version %s" % version)
if proxy_host and proxy_port:
cmd_args.append("-DproxyHost=%s -DproxyPort=%s" % (proxy_host, proxy_po... | install_plugin | identifier_name |
logstash_plugin.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Loic Blot <loic.blot@unix-experience.fr>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.... |
def remove_plugin(module, plugin_bin, plugin_name):
cmd_args = [plugin_bin, PACKAGE_STATE_MAP["absent"], plugin_name]
cmd = " ".join(cmd_args)
if module.check_mode:
rc, out, err = 0, "check mode", ""
else:
rc, out, err = module.run_command(cmd)
if rc != 0:
reason = pars... | cmd_args = [plugin_bin, PACKAGE_STATE_MAP["present"], plugin_name]
if version:
cmd_args.append("--version %s" % version)
if proxy_host and proxy_port:
cmd_args.append("-DproxyHost=%s -DproxyPort=%s" % (proxy_host, proxy_port))
cmd = " ".join(cmd_args)
if module.check_mode:
rc... | identifier_body |
index.js | 'use strict'; // dont touch
var plugin = []; // dont touch
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch
// [General]
this.name = "GiveMeMinionsToo"; // Name of plugin REQUIRED
this.author... | console.log("[Console] Turned " + s + " plugin");
return;
} else if (split[1] = "kill") {
try {
clearTimeout(gameServer.intervalTM)
console.log("[Console] Successevly forced killed give me minions");
return;
} catch (e) {
console.log("[Console] Failed to kill the givememinions plugin")
... | this.addToHelp[0] = "gmm : Give me minions command"; // help command add-on (adds this string to the help command)
this.command[0] = function(gameServer,split) {
if (split[1] == "power") {
gameServer.GMMpower = !gameServer.GMMpower;
var s = gameServer.GMMpower ? "on" : "off"; | random_line_split |
index.js | 'use strict'; // dont touch
var plugin = []; // dont touch
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch
// [General]
this.name = "GiveMeMinionsToo"; // Name of plugin REQUIRED
this.author... | else if (gameServer.clients[i].playerTracker.socket.remoteAddress && gameServer.clients[i] && gameServer.gmpid.indexOf(gameServer.clients[i].playerTracker.pID) == -1 && !gameServer.clients[i].playerTracker.owner) {
newrandom[a] = gameServer.clients[i].playerTracker;
a ++;
}
}
var item = newrandom[Mat... | {
newrandom[a] = gameServer.clients[i].playerTracker;
a ++;
} | conditional_block |
dataset.js | (bigQuery, id) {
var methods = {
/**
* Create a dataset.
*
* @example
* dataset.create(function(err, dataset, apiResponse) {
* if (!err) {
* // The dataset was created successfully.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Pro... | Dataset | identifier_name | |
dataset.js | IPEDS universe'
* };
*
* dataset.setMetadata(metadata, function(err, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.setMetadata(metadata).then(function(data) {
* var apiResponse = data[0];
* });
*/
setMetad... | * These methods can be auto-paginated.
*/ | random_line_split | |
dataset.js | create: true,
/**
* Check if the dataset exists.
*
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this
* request.
* @param {boolean} callback.exists - Whether the dataset exists or not.
*
* @examp... | {
var methods = {
/**
* Create a dataset.
*
* @example
* dataset.create(function(err, dataset, apiResponse) {
* if (!err) {
* // The dataset was created successfully.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //... | identifier_body | |
dataset.js | successfully.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* dataset.create().then(function(data) {
* var dataset = data[0];
* var apiResponse = data[1];
* });
*/
create: true,
/**
* Check if the dataset exis... |
var body = extend(true, {}, options, {
tableReference: {
datasetId: this.id,
projectId: this.bigQuery.projectId,
tableId: id
}
});
if (is.string(options.schema)) {
body.schema = Table.createSchemaFromString_(options.schema);
}
if (is.array(options.schema)) {
body.schema =... | {
callback = options;
options = {};
} | conditional_block |
Gruntfile.js | /* global module:false */
module.exports = function(grunt) {
var port = grunt.option('port') || 8000;
var base = grunt.option('base') || '.';
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner:
'/*!\n' +
' * reveal.js <%= pkg.version %> (<%= grunt.te... | },
options: {
livereload: true
}
}
});
// Dependencies
grunt.loadNpmTasks( 'grunt-contrib-qunit' );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-contrib-cssmin' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.loadNp... | },
markdown: {
files: [ '*.md' ] | random_line_split |
scc.py | # coding=utf-8
# Author: Idan Gutman
# Modified by jkaberg, https://github.com/jkaberg for SceneAccess
# URL: https://sick-rage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the F... | (TorrentProvider): # pylint: disable=too-many-instance-attributes
def __init__(self):
TorrentProvider.__init__(self, "SceneAccess")
self.username = None
self.password = None
self.minseed = None
self.minleech = None
self.cache = tvcache.TVCache(self) # only poll ... | SCCProvider | identifier_name |
scc.py | # coding=utf-8
# Author: Idan Gutman
# Modified by jkaberg, https://github.com/jkaberg for SceneAccess
# URL: https://sick-rage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the F... |
if not data:
continue
with BS4Parser(data, 'html5lib') as html:
torrent_table = html.find('table', id='torrents-table')
torrent_rows = torrent_table('tr') if torrent_table else []
# Continue only if at lea... | results = []
if not self.login():
return results
for mode in search_strings:
items = []
if mode != 'RSS':
logger.log("Search Mode: {0}".format(mode), logger.DEBUG)
for search_string in search_strings[mode]:
if mode != 'RSS'... | identifier_body |
scc.py | # coding=utf-8
# Author: Idan Gutman
# Modified by jkaberg, https://github.com/jkaberg for SceneAccess
# URL: https://sick-rage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the F... |
with BS4Parser(data, 'html5lib') as html:
torrent_table = html.find('table', id='torrents-table')
torrent_rows = torrent_table('tr') if torrent_table else []
# Continue only if at least one Release is found
if len(torrent... | continue | conditional_block |
scc.py | # coding=utf-8
# Author: Idan Gutman
# Modified by jkaberg, https://github.com/jkaberg for SceneAccess
# URL: https://sick-rage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify | # (at your option) any later version.
#
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the ... | # it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or | random_line_split |
packed-struct-transmute.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 ... | struct Foo {
bar: u8,
baz: uint
}
#[deriving(Show)]
struct Oof {
rab: u8,
zab: uint
}
fn main() {
let foo = Foo { bar: 1, baz: 10 };
unsafe {
let oof: Oof = mem::transmute(foo);
println!("{}", oof);
}
} | random_line_split | |
packed-struct-transmute.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 foo = Foo { bar: 1, baz: 10 };
unsafe {
let oof: Oof = mem::transmute(foo);
println!("{}", oof);
}
}
| main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.