file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
template_installer.rs | // Copyright (C) 2020 Jason Ish
//
// 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 limitation the rights to use, copy, modify, merge, publish,
// ... | {
debug!("Checking for template \"{}\"", template);
match client.get_template(template).await {
Err(err) => {
warn!("Failed to check if template {} exists: {}", template, err);
}
Ok(None) => {
debug!("Did not find template for \"{}\", will install", template);
... | identifier_body | |
template_installer.rs | // Copyright (C) 2020 Jason Ish
//
// 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 limitation the rights to use, copy, modify, merge, publish,
// ... | (client: &Client, template: &str) -> Result<()> {
debug!("Checking for template \"{}\"", template);
match client.get_template(template).await {
Err(err) => {
warn!("Failed to check if template {} exists: {}", template, err);
}
Ok(None) => {
debug!("Did not find te... | install_template | identifier_name |
template_installer.rs | // Copyright (C) 2020 Jason Ish
//
// 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 limitation the rights to use, copy, modify, merge, publish,
// ... | debug!("Checking for template \"{}\"", template);
match client.get_template(template).await {
Err(err) => {
warn!("Failed to check if template {} exists: {}", template, err);
}
Ok(None) => {
debug!("Did not find template for \"{}\", will install", template);
... | use anyhow::anyhow;
use anyhow::Result;
pub async fn install_template(client: &Client, template: &str) -> Result<()> { | random_line_split |
template_installer.rs | // Copyright (C) 2020 Jason Ish
//
// 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 limitation the rights to use, copy, modify, merge, publish,
// ... |
};
let version = client.get_version().await?;
if version.major < 7 {
return Err(anyhow!(
"Elasticsearch version {} not supported",
version.version
));
}
let template_string = {
if version.major >= 7 {
crate::resource::get_string("elastic... | {
debug!("Found template for \"{}\"", template);
return Ok(());
} | conditional_block |
index.d.ts | // Type definitions for tough-cookie 2.3
// Project: https://github.com/salesforce/tough-cookie
// Definitions by: Leonard Thieu <https://github.com/leonard-thieu>
// LiJinyao <https://github.com/LiJinyao>
// Michael Wei <https://github.com/no2chem>
// Definitions: https://github.com/Def... | {
static parse(cookieString: string, options?: Cookie.ParseOptions): Cookie | undefined;
static fromJSON(strOrObj: string | object): Cookie | null;
constructor(properties?: Cookie.Properties);
// TODO: Some of the following properties might actually be nullable.
key: string;
value: string;
... | Cookie | identifier_name |
index.d.ts | // Type definitions for tough-cookie 2.3
// Project: https://github.com/salesforce/tough-cookie
// Definitions by: Leonard Thieu <https://github.com/leonard-thieu>
// LiJinyao <https://github.com/LiJinyao>
// Michael Wei <https://github.com/no2chem>
// Definitions: https://github.com/Def... | export function cookieCompare(a: Cookie, b: Cookie): number;
export function permuteDomain(domain: string): string[];
export function permutePath(path: string): string[];
// region Cookie
export class Cookie {
static parse(cookieString: string, options?: Cookie.ParseOptions): Cookie | undefined;
static fro... | */
export function fromJSON(string: string): Cookie;
export function getPublicSuffix(hostname: string): string | null;
| random_line_split |
panel.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nebula, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | (horizon.Panel):
name = "Instances & Volumes"
slug = 'instances_and_volumes'
dashboard.Nova.register(InstancesAndVolumes)
| InstancesAndVolumes | identifier_name |
panel.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nebula, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | dashboard.Nova.register(InstancesAndVolumes) | random_line_split | |
panel.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nebula, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... |
dashboard.Nova.register(InstancesAndVolumes)
| name = "Instances & Volumes"
slug = 'instances_and_volumes' | identifier_body |
netbeans8.js | (function(root, factory) {
if (typeof define === 'function' && define.amd) | else if (typeof exports === 'object') {
module.exports = factory();
} else {
var lastName = root,
namespace = 'allColors.ideaColorThemes.netbeans8'.split('.');
for (var i = 0; i < namespace.length; i++) {
if (lastName[namespace[i]] === undefined) {
l... | {
define([], factory);
} | conditional_block |
netbeans8.js | (function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
var lastName = root,
namespace = 'allColors.ideaColorThemes.netbeans8'.split('.');
for... | '#a0a9f9',
'#ffc8c8',
'#b7b7b7',
'#ce7b00',
'#d25252',
'#868686',
'#808080',
'#ffded8',
'#ffc8bd',
'#d6d6d6',
'#cbcbcb',
'#c8f2c8',
'#baeeba',
'#bccff9',
'#f5f7f0',
'#ff0000',
'#e9e9e9... | return [
'#a1f2ac',
'#eeeeee',
'#ffffff',
'#cccccc', | random_line_split |
Users.js | /**
* Users collection.
* Initializes Users collection and provides methods
* for accessing the collection.
* */
users = "Users";
Users = new Mongo.Collection(users);
/**
* Schema for Users
*/
Users.attachSchema(new SimpleSchema({
userName:{
label: "Username",
type: String,
optional: false,
... | group: users,
placeholder: "First Name"
}
},
lastName:{
label: "Last Name",
type: String,
optional: true,
autoform:{
group: users,
placeholder: "Last Name"
}
},
email:{
label: "Email",
type: String,
optional: false,
unique: true,
autoform:{
... | label: "First Name",
type: String,
optional: true,
autoform:{ | random_line_split |
filter.rs | use crate::fns::FnMut1;
use core::fmt;
use core::pin::Pin;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_project_lite::pin_project;
pin_project! {
/// Stre... | (&self) -> (usize, Option<usize>) {
let pending_len = if self.pending_item.is_some() { 1 } else { 0 };
let (_, upper) = self.stream.size_hint();
let upper = match upper {
Some(x) => x.checked_add(pending_len),
None => None,
};
(0, upper) // can't know a lo... | size_hint | identifier_name |
filter.rs | use crate::fns::FnMut1;
use core::fmt;
use core::pin::Pin;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_project_lite::pin_project;
pin_project! {
/// Stre... | ;
let (_, upper) = self.stream.size_hint();
let upper = match upper {
Some(x) => x.checked_add(pending_len),
None => None,
};
(0, upper) // can't know a lower bound, due to the predicate
}
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature ... | { 0 } | conditional_block |
filter.rs | use crate::fns::FnMut1;
use core::fmt;
use core::pin::Pin;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_project_lite::pin_project;
pin_project! {
/// Stre... | {
type Item = St::Item;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<St::Item>> {
let mut this = self.project();
Poll::Ready(loop {
if let Some(fut) = this.pending_fut.as_mut().as_pin_mut() {
let res = ready!(fut.poll(cx));
... | F: for<'a> FnMut1<&'a St::Item, Output = Fut>,
Fut: Future<Output = bool>, | random_line_split |
filter.rs | use crate::fns::FnMut1;
use core::fmt;
use core::pin::Pin;
use futures_core::future::Future;
use futures_core::ready;
use futures_core::stream::{FusedStream, Stream};
use futures_core::task::{Context, Poll};
#[cfg(feature = "sink")]
use futures_sink::Sink;
use pin_project_lite::pin_project;
pin_project! {
/// Stre... |
}
// Forwarding impl of Sink from the underlying stream
#[cfg(feature = "sink")]
impl<S, Fut, F, Item> Sink<Item> for Filter<S, Fut, F>
where
S: Stream + Sink<Item>,
F: FnMut(&S::Item) -> Fut,
Fut: Future<Output = bool>,
{
type Error = S::Error;
delegate_sink!(stream, Item);
}
| {
let pending_len = if self.pending_item.is_some() { 1 } else { 0 };
let (_, upper) = self.stream.size_hint();
let upper = match upper {
Some(x) => x.checked_add(pending_len),
None => None,
};
(0, upper) // can't know a lower bound, due to the predicate
... | identifier_body |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Vasp(MakefilePackage):
"""
The Vienna Ab initio Simulation Package (VASP)
... |
def build(self, spec, prefix):
if '+cuda' in self.spec:
make('gpu', 'gpu_ncl')
else:
make('std', 'gam', 'ncl')
def install(self, spec, prefix):
install_tree('bin/', prefix.bin)
| spec = self.spec
cpp_options = ['-DMPI -DMPI_BLOCK=8000',
'-Duse_collective', '-DCACHE_SIZE=4000',
'-Davoidalloc', '-Duse_bse_te',
'-Dtbdyn', '-Duse_shmem']
if '%nvhpc' in self.spec:
cpp_options.extend(['-DHOST=\\"LinuxPGI... | identifier_body |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Vasp(MakefilePackage):
"""
The Vienna Ab initio Simulation Package (VASP)
... | (self, spack_env):
spec = self.spec
cpp_options = ['-DMPI -DMPI_BLOCK=8000',
'-Duse_collective', '-DCACHE_SIZE=4000',
'-Davoidalloc', '-Duse_bse_te',
'-Dtbdyn', '-Duse_shmem']
if '%nvhpc' in self.spec:
cpp_options.... | setup_build_environment | identifier_name |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Vasp(MakefilePackage):
"""
The Vienna Ab initio Simulation Package (VASP)
... |
conflicts('%gcc@:8', msg='GFortran before 9.x does not support all features needed to build VASP')
conflicts('+vaspsol', when='+cuda', msg='+vaspsol only available for CPU')
conflicts('+openmp', when='@:6.1.1', msg='openmp support started from 6.2')
parallel = False
def edit(self, spec, prefix):
... | random_line_split | |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
from spack import *
class Vasp(MakefilePackage):
"""
The Vienna Ab initio Simulation Package (VASP)
... |
if spec.satisfies('%gcc@10:'):
fflags.append('-fallow-argument-mismatch')
# Finally
spack_env.set('CPP_OPTIONS', ' '.join(cpp_options))
spack_env.set('CFLAGS', ' '.join(cflags))
spack_env.set('FFLAGS', ' '.join(fflags))
def build(self, spec, prefix):
i... | cpp_options.append('-Dsol_compat') | conditional_block |
htmloptionscollection.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::HTMLCo... |
// Step 3
if node == before_node {
return Ok(());
}
}
// Step 4
let reference_node = before.and_then(|before| {
match before {
HTMLElementOrLong::HTMLElement(element) => Some(Root::upcast::<Node>(element)),
... | {
return Err(Error::NotFound);
} | conditional_block |
htmloptionscollection.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::HTMLCo... | self.upcast().IndexedGetter(index as u32).map(Root::upcast::<Node>)
}
}
});
// Step 5
let parent = if let Some(reference_node) = reference_node.r() {
reference_node.GetParentNode().unwrap()
} else {
root
};
... | random_line_split | |
htmloptionscollection.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::HTMLCo... | (&self) -> Vec<DOMString> {
self.upcast().SupportedPropertyNames()
}
// FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of
// HTMLOptionsCollection) implements IndexedGetter.
// https://github.com/servo/servo/issues/5875
//
// https://dom.spec.whatwg.o... | SupportedPropertyNames | identifier_name |
htmloptionscollection.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
use dom::bindings::codegen::Bindings::HTMLCo... |
// https://html.spec.whatwg.org/multipage/#dom-htmloptionscollection-setter
fn IndexedSetter(&self, index: u32, value: Option<&HTMLOptionElement>) -> ErrorResult {
if let Some(value) = value {
// Step 2
let length = self.upcast().Length();
// Step 3
let... | {
self.upcast().IndexedGetter(index)
} | identifier_body |
mem.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/. */
//! Memory profiling functions.
use ipc_channel::ipc::{self, IpcReceiver};
use ipc_channel::router::ROUTER;
use p... |
#[cfg(target_os = "linux")]
fn page_size() -> usize {
unsafe {
::libc::sysconf(::libc::_SC_PAGESIZE) as usize
}
}
#[cfg(target_os = "linux")]
fn proc_self_statm_field(field: usize) -> Option<usize> {
use std::fs::File;
use std::io::Read;
let mut... | ($e:expr) => (match $e { Some(e) => e, None => return None })
); | random_line_split |
mem.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/. */
//! Memory profiling functions.
use ipc_channel::ipc::{self, IpcReceiver};
use ipc_channel::router::ROUTER;
use p... |
extern {
fn je_mallctl(name: *const c_char, oldp: *mut c_void, oldlenp: *mut size_t,
newp: *mut c_void, newlen: size_t) -> c_int;
}
fn jemalloc_stat(value_name: &str) -> Option<usize> {
// Before we request the measurement of interest, we first send an "epoch"
... | {
None
} | identifier_body |
mem.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/. */
//! Memory profiling functions.
use ipc_channel::ipc::{self, IpcReceiver};
use ipc_channel::router::ROUTER;
use p... | (period: Option<f64>) -> ProfilerChan {
let (chan, port) = ipc::channel().unwrap();
// Create the timer thread if a period was provided.
if let Some(period) = period {
let chan = chan.clone();
spawn_named("Memory profiler timer".to_owned(), move || {
loop... | create | identifier_name |
StackedBarChart.stories.tsx | import React from "react"
import { StackedBarChart } from "./StackedBarChart.js"
import {
SampleColumnSlugs,
SynthesizeFruitTable,
SynthesizeGDPTable,
} from "../../coreTable/OwidTableSynthesizers.js"
export default {
title: "StackedBarChart",
component: StackedBarChart,
}
export const ColumnsAsSe... | return (
<svg width={600} height={600}>
<StackedBarChart
manager={{ table, selection: table.sampleEntityName(1) }}
/>
</svg>
)
}
export const EntitiesAsSeries = (): JSX.Element => {
const table = SynthesizeGDPTable({ entityCount: 5 })
const manage... | const table = SynthesizeFruitTable()
| random_line_split |
google.js | // TODO: Add tests
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
import authConfig from '../credentials.json';
import init from '../init';
import { upsert } from '../../lib/util';
function | () {
// serialize user into the session
init();
passport.use(new GoogleStrategy(
authConfig.google,
(accessToken, refreshToken, profile, done) => {
const params = {
email: profile.emails[0].value,
external_auth_type: 'google',
};
const data = {
first_name: profil... | passportInit | identifier_name |
google.js | // TODO: Add tests
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
import authConfig from '../credentials.json';
import init from '../init';
import { upsert } from '../../lib/util';
function passportInit() |
passportInit();
export default passport;
| {
// serialize user into the session
init();
passport.use(new GoogleStrategy(
authConfig.google,
(accessToken, refreshToken, profile, done) => {
const params = {
email: profile.emails[0].value,
external_auth_type: 'google',
};
const data = {
first_name: profile.n... | identifier_body |
google.js | // TODO: Add tests
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
import authConfig from '../credentials.json';
import init from '../init';
import { upsert } from '../../lib/util';
function passportInit() {
// serialize user into the session
init();
... | const params = {
email: profile.emails[0].value,
external_auth_type: 'google',
};
const data = {
first_name: profile.name.givenName,
last_name: profile.name.familyName,
email: profile.emails.length && profile.emails[0].value,
photo_url: profile.photos.le... | authConfig.google,
(accessToken, refreshToken, profile, done) => { | random_line_split |
bug-2470-bounds-check-overflow-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn main() {
let x = ~[1u,2u,3u];
// This should cause a bounds-check failure, but may not if we do our
// bounds checking by comparing a scaled index value to the vector's
// length (in bytes), because the scaling of the index will cause it to
// wrap around to a small number.
let idx = uint::... | // except according to those terms.
// xfail-test
// error-pattern:index out of bounds
| random_line_split |
bug-2470-bounds-check-overflow-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x = ~[1u,2u,3u];
// This should cause a bounds-check failure, but may not if we do our
// bounds checking by comparing a scaled index value to the vector's
// length (in bytes), because the scaling of the index will cause it to
// wrap around to a small number.
let idx = uint::max_val... | main | identifier_name |
bug-2470-bounds-check-overflow-2.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = ~[1u,2u,3u];
// This should cause a bounds-check failure, but may not if we do our
// bounds checking by comparing a scaled index value to the vector's
// length (in bytes), because the scaling of the index will cause it to
// wrap around to a small number.
let idx = uint::max_value ... | identifier_body | |
world.rs | use crate::{
ai, animations, components, desc, flags::Flags, item, spatial::Spatial, spec::EntitySpawn,
stats, world_cache::WorldCache, Distribution, ExternalEntity, Location, Rng, WorldSkeleton,
};
use calx::seeded_rng;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
pub const GAME_VERSION... | (&mut self) {
let mut spawns = self.world_cache.drain_spawns();
spawns.retain(|s| !self.generated_spawns.contains(s));
let seed = self.rng_seed();
for (loc, s) in &spawns {
// Create one-off RNG from just the spawn info, will always run the same for same info.
le... | generate_world_spawns | identifier_name |
world.rs | use crate::{
ai, animations, components, desc, flags::Flags, item, spatial::Spatial, spec::EntitySpawn,
stats, world_cache::WorldCache, Distribution, ExternalEntity, Location, Rng, WorldSkeleton,
};
use calx::seeded_rng;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
pub const GAME_VERSION... | impl World {
pub fn new(world_seed: &WorldSeed) -> World {
let mut ret = World {
version: GAME_VERSION.to_string(),
ecs: Default::default(),
world_cache: WorldCache::new(world_seed.rng_seed, world_seed.world_skeleton.clone()),
generated_spawns: Default::defaul... | pub(crate) rng: Rng,
}
| random_line_split |
cabi_x86_64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
fn x86_64_ty(ccx: &CrateContext,
ty: Type,
is_mem_cls: |cls: &[RegClass]| -> bool,
ind_attr: A... | {
fn llvec_len(cls: &[RegClass]) -> uint {
let mut len = 1u;
for c in cls.iter() {
if *c != SSEUp {
break;
}
len += 1u;
}
return len;
}
let mut tys = Vec::new();
let mut i = 0u;
let e = cls.len();
while i < e {
... | identifier_body |
cabi_x86_64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | }
}
fn classify_ty(ty: Type) -> Vec<RegClass> {
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return (off + a - 1u) / a * a;
}
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGet... | random_line_split | |
cabi_x86_64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (ty: Type) -> Vec<RegClass> {
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return (off + a - 1u) / a * a;
}
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref(... | classify_ty | identifier_name |
ListVariable.py | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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 limitation the rights to use, copy, modify, merge, publish,
... |
test.write(SConstruct_path, """\
from SCons.Variables.ListVariable import ListVariable
LV = ListVariable
from SCons.Variables import ListVariable
list_of_libs = Split('x11 gl qt ical')
optsfile = 'scons.variables'
opts = Variables(optsfile, args=ARGUMENTS)
opts.AddVariables(
ListVariable('shared',
... | result = test.stdout().split('\n')
r = result[1:len(expect)+1]
assert r == expect, (r, expect) | identifier_body |
ListVariable.py | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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 limitation the rights to use, copy, modify, merge, publish,
... | (expect):
result = test.stdout().split('\n')
r = result[1:len(expect)+1]
assert r == expect, (r, expect)
test.write(SConstruct_path, """\
from SCons.Variables.ListVariable import ListVariable
LV = ListVariable
from SCons.Variables import ListVariable
list_of_libs = Split('x11 gl qt ical')
optsfile = '... | check | identifier_name |
ListVariable.py | #!/usr/bin/env python
#
# __COPYRIGHT__
#
# 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 limitation the rights to use, copy, modify, merge, publish,
... | # vim: set expandtab tabstop=4 shiftwidth=4: | # End: | random_line_split |
SimplePopover.js | import React, { Component } from 'react';
import OnClickOutside from 'react-onclickoutside';
import './SimplePopover.scss';
| position: 'absolute',
top: `${position.bottom + TOOLTIP_MARGIN}px`,
left: `${(position.left + (position.width / 2)) - (popoverWidth / 2)}px`,
});
const getPopoverOnBottomLeftStyle = (position, popoverWidth) => ({
position: 'absolute',
top: `${position.bottom + TOOLTIP_MARGIN}px`,
left: `${(position.left - ... | const TOOLTIP_MARGIN = 10;
const getPopoverOnBottomStyle = (position, popoverWidth) => ({ | random_line_split |
SimplePopover.js | import React, { Component } from 'react';
import OnClickOutside from 'react-onclickoutside';
import './SimplePopover.scss';
const TOOLTIP_MARGIN = 10;
const getPopoverOnBottomStyle = (position, popoverWidth) => ({
position: 'absolute',
top: `${position.bottom + TOOLTIP_MARGIN}px`,
left: `${(position.left + (pos... | else if (appearOn === 'bottom-left') {
style = getPopoverOnBottomLeftStyle(pos, popoverWidth);
} else if(appearOn === 'bottom') {
style = getPopoverOnBottomStyle(pos, popoverWidth);
}
return (
<div className={className} style={style} ref={this.handleRef}>
<p className={`${classNa... | {
style = getPopoverOnRightStyle(pos, popoverWidth, popoverHeight);
} | conditional_block |
SimplePopover.js | import React, { Component } from 'react';
import OnClickOutside from 'react-onclickoutside';
import './SimplePopover.scss';
const TOOLTIP_MARGIN = 10;
const getPopoverOnBottomStyle = (position, popoverWidth) => ({
position: 'absolute',
top: `${position.bottom + TOOLTIP_MARGIN}px`,
left: `${(position.left + (pos... | () {
const { pos, className, title, content, appearOn } = this.props;
const popoverWidth = this.state.el ? this.state.el.clientWidth : 0;
const popoverHeight = this.state.el ? this.state.el.clientHeight : 0;
let style;
if (appearOn === 'right') {
style = getPopoverOnRightStyle(pos, popoverWi... | render | identifier_name |
user.ts | import * as express from 'express';
import { default as User } from '../../models/User';
import * as jwt from 'jsonwebtoken';
const Token = require('../util/token');
const userRouter = express.Router();
//when user clicks "login button"
userRouter.post('/users', (req, res) => {
const user = new User();
user.firs... |
return User.findById(user._id, (err, user) => {
res.status(201).json(user);
});
});
});
module.exports = userRouter; | { return res.status(400).send(err); } | conditional_block |
user.ts | import * as express from 'express';
import { default as User } from '../../models/User';
import * as jwt from 'jsonwebtoken';
const Token = require('../util/token');
const userRouter = express.Router();
//when user clicks "login button"
userRouter.post('/users', (req, res) => {
const user = new User();
user.firs... |
return User.findById(user._id, (err, user) => {
res.status(201).json(user);
});
});
});
module.exports = userRouter; | user.profile.website = req.body.website;
user.save((err) => {
if (err) { return res.status(400).send(err); } | random_line_split |
app.js | require('./modules/config');
require('./modules/controllers');
require('./modules/services');
let initialized = false;
function | (path, query, attribute){
var value = path.split("/").slice(-1).pop();
query.equalTo(attribute, value);
return query
}
const app = angular.module('Kinvey', [
'ionic',
'kinvey',
'config',
'controllers',
'services'
]);
app.config(function($logProvider) {
'ngInject';
// Enable log
$logProvider.deb... | constructQuery | identifier_name |
app.js | require('./modules/config');
require('./modules/controllers');
require('./modules/services');
let initialized = false;
function constructQuery(path, query, attribute){
var value = path.split("/").slice(-1).pop();
query.equalTo(attribute, value);
return query
}
const app = angular.module('Kinvey', [
'ionic',
... |
});
$ionicPlatform.ready(function() {
const cordova = window.cordova;
const StatusBar = window.StatusBar;
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (cordova && cordova.plugins.Keyboard) {
cordova.plugins.Keyboar... | {
event.preventDefault();
// Login
Auth.login().then(function() {
$state.go(toState.name, toParams);
});
} | conditional_block |
app.js | require('./modules/config');
require('./modules/controllers');
require('./modules/services');
let initialized = false;
function constructQuery(path, query, attribute) |
const app = angular.module('Kinvey', [
'ionic',
'kinvey',
'config',
'controllers',
'services'
]);
app.config(function($logProvider) {
'ngInject';
// Enable log
$logProvider.debugEnabled(true);
});
app.config(function($stateProvider) {
'ngInject';
// Setup the states
$stateProvider
.state... | {
var value = path.split("/").slice(-1).pop();
query.equalTo(attribute, value);
return query
} | identifier_body |
app.js | require('./modules/config');
require('./modules/controllers');
require('./modules/services');
let initialized = false;
function constructQuery(path, query, attribute){
var value = path.split("/").slice(-1).pop();
query.equalTo(attribute, value);
return query
}
const app = angular.module('Kinvey', [
'ionic',
... | // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (cordova && cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (StatusBar) {
S... | $ionicPlatform.ready(function() {
const cordova = window.cordova;
const StatusBar = window.StatusBar;
| random_line_split |
notebook_utils.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (sequence,
synth=midi_synth.synthesize,
sample_rate=_DEFAULT_SAMPLE_RATE,
**synth_args):
"""Creates an interactive player for a synthesized note sequence.
This function should only be called from a Jupyter notebook.
Args:
sequence: A music_pb2.NoteSequen... | play_sequence | identifier_name |
notebook_utils.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | """Creates an interactive player for a synthesized note sequence.
This function should only be called from a Jupyter notebook.
Args:
sequence: A music_pb2.NoteSequence to synthesize and play.
synth: A synthesis function that takes a sequence and sample rate as input.
sample_rate: The sample rate at wh... | identifier_body | |
notebook_utils.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
def play_sequence(sequence,
synth=midi_synth.synthesize,
sample_rate=_DEFAULT_SAMPLE_RATE,
**synth_args):
"""Creates an interactive player for a synthesized note sequence.
This function should only be called from a Jupyter notebook.
Args:
sequence: A mu... |
_DEFAULT_SAMPLE_RATE = 44100
| random_line_split |
plugin.js | tinymce.PluginManager.add('tabpanel', function(editor, url) {
var walker = tinymce.dom.TreeWalker;
editor.ui.registry.addNestedMenuItem('tabpanel', {
//icon: 'tabpanel',
text: "Tabs",
tooltip: "Tabs",
getSubmenuItems: function () {
return [
{
... | editor.dom.add(panels,'section',{id:'tab'+nb,class:'tab-pane',role:'tabpanel'},'<p>color'+nb+'</p>');
}
}
},
{
type: 'menuitem',
//icon: 'tab',
text: "Remov... | nb = tabs.children.length;
nb++;
editor.dom.add(tabs,'li',false,'<a role="tab" href="#tab'+nb+'" aria-controls="tab'+nb+'" data-toggle="tab"><img class="img-responsive" src="#" alt="color'+nb+'" width="250" height="250" /><span>Co... | random_line_split |
plugin.js | tinymce.PluginManager.add('tabpanel', function(editor, url) {
var walker = tinymce.dom.TreeWalker;
editor.ui.registry.addNestedMenuItem('tabpanel', {
//icon: 'tabpanel',
text: "Tabs",
tooltip: "Tabs",
getSubmenuItems: function () {
return [
{
... |
}
}
];
}
});
});
// Load the required translation files
tinymce.PluginManager.requireLangPack('tabpanel', 'en_EN,fr_FR'); | {
let tabs = editor.dom.select('.nav-tabs',tabpanels)[0],
panels = editor.dom.select('.tab-content',tabpanels)[0];
tinymce.activeEditor.dom.remove(tinymce.activeEditor.dom.select('li:last-child',tabs));
... | conditional_block |
__openerp__.py | ###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the ... | # GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
{
'name': 'XMLRPC Ope... | # (at your option) any later version.
#
# This program 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 | random_line_split |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
// used to create fake backend
import { fakeBackendProvider } from './_helpers/index';
import { MockBackend, MockConnection ... | HomeComponent,
AboutComponent,
LoginComponent,
routedComponents,
RegisterComponent,
DashboardComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule,
],
providers: [
AuthGuard,
AlertService,
AuthenticationService,
LoggerService,
... | AlertComponent, | random_line_split |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
// used to create fake backend
import { fakeBackendProvider } from './_helpers/index';
import { MockBackend, MockConnection ... | { }
| AppModule | identifier_name |
possible_browser.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.internal.app import possible_app
class PossibleBrowser(possible_app.PossibleApp):
"""A browser that can be controlled.
Call Create() to... | (self, credentials_path):
self._credentials_path = credentials_path
| SetCredentialsPath | identifier_name |
possible_browser.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.internal.app import possible_app
class PossibleBrowser(possible_app.PossibleApp):
"""A browser that can be controlled.
Call Create() to... |
def _InitPlatformIfNeeded(self):
raise NotImplementedError()
def Create(self, finder_options):
raise NotImplementedError()
def SupportsOptions(self, browser_options):
"""Tests for extension support."""
raise NotImplementedError()
def IsRemote(self):
return False
def RunRemote(self):
... | return self._supports_tab_control | identifier_body |
possible_browser.py | # Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.internal.app import possible_app
class PossibleBrowser(possible_app.PossibleApp):
"""A browser that can be controlled.
Call Create() to... | def SetCredentialsPath(self, credentials_path):
self._credentials_path = credentials_path | random_line_split | |
customBlockHandler.ts | import { Process, BlockHandler } from '../blockHandlers';
import { isSpaceOrTab, peek } from '../blockHelper';
import { unescapeString } from '../common';
import { CustomBlockNode, BlockNode } from '../node';
const reClosingCustomBlock = /^\$\$$/;
export const customBlock: BlockHandler = {
| (parser, container: CustomBlockNode) {
const line = parser.currentLine;
const match = line.match(reClosingCustomBlock);
if (match) {
// closing custom block
parser.lastLineLength = match[0].length;
parser.finalize(container as BlockNode, parser.lineNumber);
return Process.Finished;
... | continue | identifier_name |
customBlockHandler.ts | import { Process, BlockHandler } from '../blockHandlers';
import { isSpaceOrTab, peek } from '../blockHelper';
import { unescapeString } from '../common';
import { CustomBlockNode, BlockNode } from '../node';
const reClosingCustomBlock = /^\$\$$/;
export const customBlock: BlockHandler = {
continue(parser, containe... |
// skip optional spaces of custom block offset
let i = container.offset;
while (i > 0 && isSpaceOrTab(peek(line, parser.offset))) {
parser.advanceOffset(1, true);
i--;
}
return Process.Go;
},
finalize(_, block: CustomBlockNode) {
if (block.stringContent === null) {
return;... | {
// closing custom block
parser.lastLineLength = match[0].length;
parser.finalize(container as BlockNode, parser.lineNumber);
return Process.Finished;
} | conditional_block |
customBlockHandler.ts | import { Process, BlockHandler } from '../blockHandlers';
import { isSpaceOrTab, peek } from '../blockHelper';
import { unescapeString } from '../common';
import { CustomBlockNode, BlockNode } from '../node';
const reClosingCustomBlock = /^\$\$$/;
export const customBlock: BlockHandler = {
continue(parser, containe... | ,
finalize(_, block: CustomBlockNode) {
if (block.stringContent === null) {
return;
}
// first line becomes info string
const content = block.stringContent;
const newlinePos = content.indexOf('\n');
const firstLine = content.slice(0, newlinePos);
const rest = content.slice(newlinePos... | {
const line = parser.currentLine;
const match = line.match(reClosingCustomBlock);
if (match) {
// closing custom block
parser.lastLineLength = match[0].length;
parser.finalize(container as BlockNode, parser.lineNumber);
return Process.Finished;
}
// skip optional spaces of c... | identifier_body |
customBlockHandler.ts | import { Process, BlockHandler } from '../blockHandlers';
import { isSpaceOrTab, peek } from '../blockHelper';
import { unescapeString } from '../common';
import { CustomBlockNode, BlockNode } from '../node';
const reClosingCustomBlock = /^\$\$$/;
export const customBlock: BlockHandler = {
continue(parser, containe... | },
acceptsLines: true,
}; | random_line_split | |
pe598-split-divisibilities.py | #!/usr/bin/env python
# coding=utf-8
"""598. Split Divisibilities
https://projecteuler.net/problem=598
Consider the number 48.
There are five pairs of integers $a$ and $b$ ($a \leq b$) such that $a \times
b=48$: (1,48), (2,24), (3,16), (4,12) and (6,8).
It can be seen that both 6 and 8 have 4 divisors.
So of th... | You are given $C(10!)=3$: (1680, 2160), (1800, 2016) and (1890,1920).
Find $C(100!)$
""" | random_line_split | |
test.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | pass
class TestCase(unittest.TestCase):
"""Test case base class for all unit tests."""
def setUp(self):
"""Run before each test method to initialize test environment."""
super(TestCase, self).setUp()
fake_flags.set_defaults(FLAGS)
flags.parse_args([], default_config_files... |
class TestingException(Exception): | random_line_split |
test.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... |
def flags(self, **kw):
"""Override flag variables for a test."""
for k, v in kw.iteritems():
FLAGS.set_override(k, v)
def start_service(self, name, host=None, **kwargs):
host = host and host or uuid.uuid4().hex
kwargs.setdefault('host', host)
kwargs.setdefa... | """Runs after each test method to tear down test environment."""
try:
self.mox.UnsetStubs()
self.stubs.UnsetAll()
self.stubs.SmartUnsetAll()
self.mox.VerifyAll()
super(TestCase, self).tearDown()
finally:
# Reset any overridden flags... | identifier_body |
test.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | (self, condition, msg):
self.condition = condition
self.message = msg
def __call__(self, func):
@functools.wraps(func)
def _skipper(*args, **kw):
"""Wrapped skipper function."""
if self.condition:
raise nose.SkipTest(self.message)
... | __init__ | identifier_name |
test.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... |
def flags(self, **kw):
"""Override flag variables for a test."""
for k, v in kw.iteritems():
FLAGS.set_override(k, v)
def start_service(self, name, host=None, **kwargs):
host = host and host or uuid.uuid4().hex
kwargs.setdefault('host', host)
kwargs.setdefa... | del self.__dict__[key] | conditional_block |
web-storage.js |
function encode (value) {
if (Object.prototype.toString.call(value) === '[object Date]') {
return '__q_date|' + value.toUTCString()
}
if (Object.prototype.toString.call(value) === '[object RegExp]') {
return '__q_expr|' + value.source
}
if (typeof value === 'number') {
return '__q_numb|' + value
... |
}
}),
getAllStorageItems = generateFunctions((type) => {
let
lengthFn = getStorageLength[type],
storage = window[type + 'Storage'],
getItemFn = getStorageItem[type]
return () => {
let
result = {},
key,
length = lengthFn()
for (let i = 0; i < leng... | {
return getItemFn(storage.key(index))
} | conditional_block |
web-storage.js |
function encode (value) {
if (Object.prototype.toString.call(value) === '[object Date]') {
return '__q_date|' + value.toUTCString()
}
if (Object.prototype.toString.call(value) === '[object RegExp]') {
return '__q_expr|' + value.source
}
if (typeof value === 'number') {
return '__q_numb|' + value
... |
let
hasStorageItem = generateFunctions(
(type) => (key) => window[type + 'Storage'].getItem(key) !== null
),
getStorageLength = generateFunctions(
(type) => () => window[type + 'Storage'].length
),
getStorageItem = generateFunctions((type) => {
let
hasFn = hasStorageItem[type],
sto... | {
return {
local: fn('local'),
session: fn('session')
}
} | identifier_body |
web-storage.js |
function encode (value) {
if (Object.prototype.toString.call(value) === '[object Date]') {
return '__q_date|' + value.toUTCString()
}
if (Object.prototype.toString.call(value) === '[object RegExp]') {
return '__q_expr|' + value.source
}
if (typeof value === 'number') {
return '__q_numb|' + value
... | (fn) {
return {
local: fn('local'),
session: fn('session')
}
}
let
hasStorageItem = generateFunctions(
(type) => (key) => window[type + 'Storage'].getItem(key) !== null
),
getStorageLength = generateFunctions(
(type) => () => window[type + 'Storage'].length
),
getStorageItem = generate... | generateFunctions | identifier_name |
web-storage.js | function encode (value) {
if (Object.prototype.toString.call(value) === '[object Date]') {
return '__q_date|' + value.toUTCString()
}
if (Object.prototype.toString.call(value) === '[object RegExp]') {
return '__q_expr|' + value.source
}
if (typeof value === 'number') {
return '__q_numb|' + value
... |
for (let i = 0; i < length; i++) {
key = storage.key(i)
result[key] = getItemFn(key)
}
return result
}
}),
setStorageItem = generateFunctions((type) => {
let storage = window[type + 'Storage']
return (key, value) => { storage.setItem(key, encode(value)) }
}),
re... | result = {},
key,
length = lengthFn() | random_line_split |
viewport.rs | //! Provides a utility method for calculating native viewport size when the window is resized.
use ppu::{SCREEN_WIDTH, SCREEN_HEIGHT};
/// A simple rectangle
pub struct | {
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
}
impl Viewport {
/// Calculates a viewport to use for a window of the given size.
///
/// The returned viewport will have the native SNES aspect ratio and still fill the window on at
/// least one axis. Basically, this calculates the b... | Viewport | identifier_name |
viewport.rs | //! Provides a utility method for calculating native viewport size when the window is resized.
use ppu::{SCREEN_WIDTH, SCREEN_HEIGHT};
/// A simple rectangle
pub struct Viewport {
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
}
impl Viewport {
/// Calculates a viewport to use for a window of th... | else {
// Too high
view_w = w;
view_h = w / NATIVE_RATIO;
}
let border_x = (w - view_w).round() as u32 / 2;
let border_y = (h - view_h).round() as u32 / 2;
let view_w = view_w.round() as u32;
let view_h = view_h.round() as u32;
Viewp... | {
// Too wide
view_h = h;
view_w = h * NATIVE_RATIO;
} | conditional_block |
viewport.rs | //! Provides a utility method for calculating native viewport size when the window is resized.
use ppu::{SCREEN_WIDTH, SCREEN_HEIGHT};
/// A simple rectangle
pub struct Viewport {
pub x: u32,
pub y: u32,
pub w: u32, | }
impl Viewport {
/// Calculates a viewport to use for a window of the given size.
///
/// The returned viewport will have the native SNES aspect ratio and still fill the window on at
/// least one axis. Basically, this calculates the black bars to apply to the window to make the
/// center have th... | pub h: u32, | random_line_split |
config.rs | use toml;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(Debug, Deserialize)]
pub struct Config {
pub uplink: Uplink,
pub plugins: Option<Vec<Plugin>>,
}
#[derive(Debug, Deserialize)]
pub struct Uplink {
pub ip: String,
pub port: i32,
pub protocol: String,
pub hos... | () -> Result<Result<Config, toml::de::Error>, ::std::io::Error> {
let file = File::open("etc/nero.toml")?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
Ok(toml::from_str(&contents))
}
| load | identifier_name |
config.rs | use toml;
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
#[derive(Debug, Deserialize)]
pub struct Config {
pub uplink: Uplink,
pub plugins: Option<Vec<Plugin>>,
}
#[derive(Debug, Deserialize)]
pub struct Uplink {
pub ip: String,
pub port: i32,
pub protocol: String,
pub hos... |
let cfg: Config = toml::from_str(&contents)?;
Ok(cfg.uplink.protocol)
}
pub fn load() -> Result<Result<Config, toml::de::Error>, ::std::io::Error> {
let file = File::open("etc/nero.toml")?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(... | let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?; | random_line_split |
alunos.component.ts | import { Component, OnInit } from '@angular/core';
import { Aluno } from './shared/aluno.model';
import { AlunoService } from './shared/aluno.service';
@Component({
selector: 'app-alunos',
templateUrl: './alunos.component.html',
styleUrls: ['./alunos.component.css'],
})
export class AlunosComponent implements On... |
});
}
public ngOnInit(): void {
this.alunoService.getAlunos()
.then(value => this.alunos = value)
.catch(reason => alert(reason.json().failure || reason));
}
}
| {
alert(reason);
} | conditional_block |
alunos.component.ts | import { Component, OnInit } from '@angular/core';
import { Aluno } from './shared/aluno.model';
import { AlunoService } from './shared/aluno.service';
@Component({
selector: 'app-alunos',
templateUrl: './alunos.component.html',
styleUrls: ['./alunos.component.css'],
})
export class AlunosComponent implements On... | (): void {
this.alunoService.getAlunos()
.then(value => this.alunos = value)
.catch(reason => alert(reason.json().failure || reason));
}
}
| ngOnInit | identifier_name |
alunos.component.ts | import { Component, OnInit } from '@angular/core';
import { Aluno } from './shared/aluno.model';
import { AlunoService } from './shared/aluno.service';
@Component({
selector: 'app-alunos',
templateUrl: './alunos.component.html',
styleUrls: ['./alunos.component.css'],
})
export class AlunosComponent implements On... |
}
| {
this.alunoService.getAlunos()
.then(value => this.alunos = value)
.catch(reason => alert(reason.json().failure || reason));
} | identifier_body |
alunos.component.ts | import { Component, OnInit } from '@angular/core';
import { Aluno } from './shared/aluno.model';
import { AlunoService } from './shared/aluno.service';
@Component({
selector: 'app-alunos',
templateUrl: './alunos.component.html',
styleUrls: ['./alunos.component.css'],
})
export class AlunosComponent implements On... | }
} | random_line_split | |
synonyms.py | #Synonyms experiment. Pass a string to see its "synonyms"
from pyspark.sql import SparkSession, Row
from pyspark.ml.feature import Word2Vec, Tokenizer, StopWordsRemover, Word2VecModel
import sys;
from string import punctuation
def strip_punctuation(arr):
return [''.join(c for c in s if c not in punctuation) for s ... | main() | conditional_block | |
synonyms.py | #Synonyms experiment. Pass a string to see its "synonyms"
from pyspark.sql import SparkSession, Row
from pyspark.ml.feature import Word2Vec, Tokenizer, StopWordsRemover, Word2VecModel
import sys;
from string import punctuation
def strip_punctuation(arr):
return [''.join(c for c in s if c not in punctuation) for s ... | model = Word2VecModel.load("word2vec-model")
synonyms = model.findSynonyms(sys.argv[1], 10)
synonyms.show(truncate=False)
# for word, cosine_distance in synonyms:
# print("{}: {}".format(word, cosine_distance))
if __name__ == '__main__':
main() | #model.save("word2vec-model") | random_line_split |
synonyms.py | #Synonyms experiment. Pass a string to see its "synonyms"
from pyspark.sql import SparkSession, Row
from pyspark.ml.feature import Word2Vec, Tokenizer, StopWordsRemover, Word2VecModel
import sys;
from string import punctuation
def strip_punctuation(arr):
return [''.join(c for c in s if c not in punctuation) for s ... | ():
spark = SparkSession.builder \
.appName("Spark CV-job ad matching") \
.config("spark.some.config.option", "some-value") \
.master("local[*]") \
.getOrCreate()
df_categories = spark.read.json("allcategories4rdd/allcategories.jsonl")
tokenizer = Tokenizer(inputCol="skillT... | main | identifier_name |
synonyms.py | #Synonyms experiment. Pass a string to see its "synonyms"
from pyspark.sql import SparkSession, Row
from pyspark.ml.feature import Word2Vec, Tokenizer, StopWordsRemover, Word2VecModel
import sys;
from string import punctuation
def strip_punctuation(arr):
return [''.join(c for c in s if c not in punctuation) for s ... |
if __name__ == '__main__':
main()
| spark = SparkSession.builder \
.appName("Spark CV-job ad matching") \
.config("spark.some.config.option", "some-value") \
.master("local[*]") \
.getOrCreate()
df_categories = spark.read.json("allcategories4rdd/allcategories.jsonl")
tokenizer = Tokenizer(inputCol="skillText", ou... | identifier_body |
profiles.js | import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Loader from 'jsx/Loader';
import FilterableDataTable from 'jsx/FilterableDataTable';
/**
* Profiles Component.
*
* @description Genomic Browser Profiles tab.
*
* @author Alizée Wickenheiser
* @version 1.0.0
*
*/
class Profiles e... | label: 'PSCID',
show: true,
filter: {
name: 'PSCID',
type: 'text',
},
},
{
label: 'Sex',
show: true,
filter: {
name: 'Sex',
type: 'select',
options: {
Male: 'Male',
Female: 'Fema... | },
{ | random_line_split |
profiles.js | import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Loader from 'jsx/Loader';
import FilterableDataTable from 'jsx/FilterableDataTable';
/**
* Profiles Component.
*
* @description Genomic Browser Profiles tab.
*
* @author Alizée Wickenheiser
* @version 1.0.0
*
*/
class Profiles e... | props) {
super(props);
this.state = {
data: {},
fieldOptions: {},
error: false,
isLoaded: false,
};
this.fetchData = this.fetchData.bind(this);
this.formatColumn = this.formatColumn.bind(this);
}
/**
* Fetch data when component mounts.
*/
componentDidMount() {
... | onstructor( | identifier_name |
profiles.js | import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Loader from 'jsx/Loader';
import FilterableDataTable from 'jsx/FilterableDataTable';
/**
* Profiles Component.
*
* @description Genomic Browser Profiles tab.
*
* @author Alizée Wickenheiser
* @version 1.0.0
*
*/
class Profiles e... |
/**
* Fetch data when component mounts.
*/
componentDidMount() {
this.fetchData();
}
/**
* Retrieve data from the provided URL and save it in state.
*/
fetchData() {
fetch(
`${this.props.baseURL}/genomic_browser/Profiles`,
{
method: 'GET',
credentials: 'same-o... |
super(props);
this.state = {
data: {},
fieldOptions: {},
error: false,
isLoaded: false,
};
this.fetchData = this.fetchData.bind(this);
this.formatColumn = this.formatColumn.bind(this);
}
| identifier_body |
assignment5.py | import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import tree
from subprocess import call
# https://archive.ics.uci.edu/ml/machine-learning-databases/mushroom/agaricus-lepiota.names
#
# TODO: Load up the mushroom dataset into dataframe 'X'
# Verify you did it ... | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=7)
#
# TODO: Create an DT classifier. No need to set any parameters
model = tree.DecisionTreeClassifier()
#
# TODO: train the classifier on the training data / labels:
# TODO: score the classifier on the testing data / labels:
model... | # Your test size can be 30% with random_state 7
# Use variable names: X_train, X_test, y_train, y_test | random_line_split |
task.js | /** @jsx html */
import { html } from '../../../snabbdom-jsx';
import Type from 'union-type';
import { bind, pipe, isBoolean, targetValue, targetChecked } from './helpers';
import { KEY_ENTER } from './constants';
// model : {id: Number, title: String, done: Boolean, editing: Boolean, editingValue: String }
... | (handler, e) {
if(e.keyCode === KEY_ENTER)
handler(Action.CommitEdit(e.target.value))
}
const view = ({model, handler, onRemove}) =>
<li
key={model.id}
class-completed={!!model.done && !model.editing}
class-editing={model.editing}>
<div selector=".view">
<input
... | onInput | identifier_name |
task.js | /** @jsx html */
import { html } from '../../../snabbdom-jsx';
import Type from 'union-type';
import { bind, pipe, isBoolean, targetValue, targetChecked } from './helpers';
import { KEY_ENTER } from './constants';
// model : {id: Number, title: String, done: Boolean, editing: Boolean, editingValue: String }
... |
export default { view, init, update, Action }
| {
return Action.case({
Toggle : done => ({...task, done}),
StartEdit : () => ({...task, editing: true, editingValue: task.title}),
CommitEdit : title => ({...task, title, editing: false, editingValue: ''}),
CancelEdit : title => ({...task, editing: false, editingValue: ''})
}, acti... | identifier_body |
task.js | /** @jsx html */
import { html } from '../../../snabbdom-jsx';
import Type from 'union-type';
import { bind, pipe, isBoolean, targetValue, targetChecked } from './helpers';
import { KEY_ENTER } from './constants';
// model : {id: Number, title: String, done: Boolean, editing: Boolean, editingValue: String }
... | }
function update(task, action) {
return Action.case({
Toggle : done => ({...task, done}),
StartEdit : () => ({...task, editing: true, editingValue: task.title}),
CommitEdit : title => ({...task, title, editing: false, editingValue: ''}),
CancelEdit : title => ({...task, editing: fa... | return { id, title, done: false, editing: false, editingValue: '' };
| random_line_split |
userinfo.js | const { Command } = require("klasa");
const { MessageEmbed } = require("discord.js");
const statusList = {
online: "online",
idle: "idle",
dnd: "in do not disturb"
};
module.exports = class extends Command {
| (...args) {
super(...args, {
name: "userinfo",
enabled: true,
runIn: ["text"],
aliases: ["user"],
description: "Get a user's information",
usage: "<user:usersearch>",
extendedHelp: "Need Discord info on a specific user? I got yo... | constructor | identifier_name |
userinfo.js | const { Command } = require("klasa");
const { MessageEmbed } = require("discord.js");
const statusList = {
online: "online",
idle: "idle",
dnd: "in do not disturb"
};
module.exports = class extends Command {
constructor(...args) {
super(...args, {
name: "userinfo",
enab... | .setFooter(msg.guild.name, msg.guild.iconURL())
.setThumbnail(user.user.displayAvatarURL())
.setAuthor(user.user.tag);
if (userActivity != null) {
embed.setDescription(`Currently ${status}${userActivity}`);
}
embed.addField("ID", user.id,... |
const embed = new MessageEmbed()
.setTimestamp() | random_line_split |
userinfo.js | const { Command } = require("klasa");
const { MessageEmbed } = require("discord.js");
const statusList = {
online: "online",
idle: "idle",
dnd: "in do not disturb"
};
module.exports = class extends Command {
constructor(...args) {
super(...args, {
name: "userinfo",
enab... |
const embed = new MessageEmbed()
.setTimestamp()
.setFooter(msg.guild.name, msg.guild.iconURL())
.setThumbnail(user.user.displayAvatarURL())
.setAuthor(user.user.tag);
if (userActivity != null) {
embed.setDescription(`Currently ${status}${us... | {
lastMsgTime = "No message found...";
} | conditional_block |
userinfo.js | const { Command } = require("klasa");
const { MessageEmbed } = require("discord.js");
const statusList = {
online: "online",
idle: "idle",
dnd: "in do not disturb"
};
module.exports = class extends Command {
constructor(...args) {
super(...args, {
name: "userinfo",
enab... |
}; | {
user = msg.guild.members.cache.get(user.id);
var userActivity = null;
// If presence intent is enabled, grab presence activity for display.
if (user.presence.clientStatus != null) {
var status = statusList[user.presence.status] || "offline";
var activity = user... | identifier_body |
ND280Transform_CSVEvtList.py | from GangaCore.GPIDev.Schema import *
from GangaCore.GPIDev.Lib.Tasks.common import *
from GangaCore.GPIDev.Lib.Tasks.ITransform import ITransform
from GangaCore.GPIDev.Lib.Job.Job import JobError
from GangaCore.GPIDev.Lib.Registry.JobRegistry import JobRegistrySlice, JobRegistrySliceProxy
from GangaCore.Core.exception... | (self):
"""Create new units if required given the inputdata"""
# call parent for chaining
super(ND280Transform_CSVEvtList,self).createUnits()
# Look at the application schema and check if there is a csvfile variable
try:
csvfile = self.application.csvfile
except... | createUnits | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.