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 |
|---|---|---|---|---|
button.rs | #![feature(used)]
#![no_std]
extern crate cortex_m;
extern crate panic_abort;
extern crate stm32f30x_hal as hal;
use hal::prelude::*;
use hal::stm32f30x;
use hal::spi::Spi;
fn main() | led.set_low();
} else {
led.set_high();
}
}
}
| {
let cp = cortex_m::Peripherals::take().unwrap();
let dp = stm32f30x::Peripherals::take().unwrap();
let mut flash = dp.FLASH.constrain();
let mut rcc = dp.RCC.constrain();
let clocks = rcc.cfgr.freeze(&mut flash.acr);
let mut gpiob = dp.GPIOB.split(&mut rcc.ahb);
let mut gpioc = dp.GPIOC... | identifier_body |
0005_auto_20170402_1502.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-02 15:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('talks', '0004_auto_20170326_1755'),
]
operations = [
migrations.AlterField(... | name='view_count',
field=models.PositiveIntegerField(default=0, verbose_name='view count'),
),
migrations.AlterField(
model_name='talk',
name='vote_count',
field=models.PositiveIntegerField(default=0, verbose_name='vote count'),
),
... | migrations.AlterField(
model_name='talk', | random_line_split |
0005_auto_20170402_1502.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-02 15:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| ]
| dependencies = [
('talks', '0004_auto_20170326_1755'),
]
operations = [
migrations.AlterField(
model_name='talk',
name='fav_count',
field=models.PositiveIntegerField(default=0, verbose_name='favorite count'),
),
migrations.AlterField(
... | identifier_body |
0005_auto_20170402_1502.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-02 15:02
from __future__ import unicode_literals
from django.db import migrations, models
class | (migrations.Migration):
dependencies = [
('talks', '0004_auto_20170326_1755'),
]
operations = [
migrations.AlterField(
model_name='talk',
name='fav_count',
field=models.PositiveIntegerField(default=0, verbose_name='favorite count'),
),
mi... | Migration | identifier_name |
ref_cell.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use core::marker::{Sync, NoSend, PhantomData, Send};
use core::ops::{Deref, DerefMut, Drop};
use cell::{Cell};
/// T... | <'a, T: ?Sized+'a> {
cell: &'a RefCell<T>,
_marker: NoSend,
}
unsafe impl<'a, T: Sync+?Sized> Sync for RefCellBorrow<'a, T> { }
impl<'a, T: ?Sized> Deref for RefCellBorrow<'a, T> {
type Target = T;
fn deref(&self) -> &T {
&self.cell.inner().data
}
}
impl<'a, T: ?Sized> Drop for RefCellBor... | RefCellBorrow | identifier_name |
ref_cell.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use core::marker::{Sync, NoSend, PhantomData, Send};
use core::ops::{Deref, DerefMut, Drop};
use cell::{Cell};
/// T... | impl<'a, T: ?Sized> Deref for RefCellBorrow<'a, T> {
type Target = T;
fn deref(&self) -> &T {
&self.cell.inner().data
}
}
impl<'a, T: ?Sized> Drop for RefCellBorrow<'a, T> {
fn drop(&mut self) {
let inner = self.cell.inner();
inner.status = match inner.status {
RefCe... |
unsafe impl<'a, T: Sync+?Sized> Sync for RefCellBorrow<'a, T> { }
| random_line_split |
user.module.ts | // Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | {
}
| UserModule | identifier_name |
user.module.ts | // Copyright Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed t... | ],
exports: [
UserComponent
],
})
export class UserModule {
} | UserComponent,
ChangePasswordComponent,
NewUserModalComponent | random_line_split |
places_sidebar.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | self, show_desktop: bool) {
unsafe { ffi::gtk_places_sidebar_set_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_desktop)) }
}
pub fn get_show_desktop(&self) -> bool {
unsafe { to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) }
... | t_show_desktop(& | identifier_name |
places_sidebar.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | pub fn get_show_enter_location(&self) -> bool {
unsafe { to_bool(ffi::gtk_places_sidebar_get_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) }
}
}
impl_drop!(PlacesSidebar);
impl_TraitWidget!(PlacesSidebar);
impl gtk::ContainerTrait for PlacesSidebar {}
impl gtk::BinTrait for PlacesSide... | unsafe { ffi::gtk_places_sidebar_set_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()),
to_gboolean(show_enter_location)) }
}
| identifier_body |
places_sidebar.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | use gtk::{self, ffi};
use gtk::FFIWidget;
use gtk::cast::GTK_PLACES_SIDEBAR;
use glib::{to_bool, to_gboolean};
struct_Widget!(PlacesSidebar);
impl PlacesSidebar {
pub fn new() -> Option<PlacesSidebar> {
let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() };
check_pointer!(tmp_pointer, PlacesS... |
//! GtkPlacesSidebar — Sidebar that displays frequently-used places in the file system
| random_line_split |
importFromString.ts | // ==LICENSE-BEGIN==
// Copyright 2017 European Digital Reading Lab. All rights reserved.
// Licensed to the Readium Foundation under one or more contributor license agreements.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file exposed on Github (readium) in the proj... | manifest: string,
baseFileUrl: string, // MUST be file://
): SagaGenerator<[publicationDoc: PublicationDocument, alreadyImported: boolean]> {
// const baseUrl = baseFileUrl.startsWith("file://") ? baseFileUrl : ("file://" + baseFileUrl.replace(/\\/g, "/"));
const packagePath = yield* callTyped(packageF... | const debug = debug_("readium-desktop:main#saga/api/publication/importFromStringService");
export function* importFromStringService( | random_line_split |
importFromString.ts | // ==LICENSE-BEGIN==
// Copyright 2017 European Digital Reading Lab. All rights reserved.
// Licensed to the Readium Foundation under one or more contributor license agreements.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file exposed on Github (readium) in the proj... |
return [undefined, false];
}
| {
debug("package path is empty");
} | conditional_block |
__init__.py | from __future__ import unicode_literals
import logging
# Logging configuration
log = logging.getLogger(__name__) # noqa
log.addHandler(logging.NullHandler()) # noqa
from netmiko.ssh_dispatcher import ConnectHandler
from netmiko.ssh_dispatcher import ssh_dispatcher
from netmiko.ssh_dispatcher import redispatch
from ne... | NetmikoAuthError = NetMikoAuthenticationException
__version__ = '2.0.1'
__all__ = ('ConnectHandler', 'ssh_dispatcher', 'platforms', 'SCPConn', 'FileTransfer',
'NetMikoTimeoutException', 'NetMikoAuthenticationException',
'NetmikoTimeoutError', 'NetmikoAuthError', 'InLineTransfer', 'redispatch',
... | NetmikoTimeoutError = NetMikoTimeoutException | random_line_split |
mod.rs | // Copyright 2013 The rust-glib authors.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except ac... |
pub type gssize = libc::ssize_t;
pub type gsize = libc::size_t;
pub type gintptr = libc::intptr_t;
pub type guintptr = libc::uintptr_t; | pub type guint64 = u64; | random_line_split |
select.js | `select` будет по умолчанию равно
* переменной `value`.
* * `group`: Выражение для вычисления результата, который будет использоваться для группирования элементов
* `option` используя DOM элемент `<optgroup>`.
* * `trackexpr`: Используется при работе с объектами и массивами. Результат выполнения эт... | .$setV | identifier_name | |
select.js | create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate =jqLite(document.createElement('optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for(var i = 0, children = element.children(), i... | existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
| conditional_block | |
select.js | * Это продемонстрировано в примере ниже.
*
* Примечание: `ngOptions` предоставляет итератор для элемента `<option>` который должен использоваться вместо
* {@link ng.directive:ngRepeat ngRepeat} когда необходимо привязать модель `select` не к строковому значению.
* Это потому, что элемент option в настоящее врем... | * вложить его в элемент `<select>`. Этот элемент будет соответствовать значению null или опции «not selected». | random_line_split | |
select.js | ="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
... | OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element a... | 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_jemalloc)]
#![feature(box_syntax)] | #![deny(unsafe_code)]
#[allow(unused_extern_crates)]
#[cfg(not(target_os = "windows"))]
extern crate alloc_jemalloc;
extern crate hbs_pow;
extern crate ipc_channel;
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate profile_traits;
#[cfg(target_os = "linux")]
extern crate regex;
#[cfg(target_o... | #![feature(iter_arith)]
#![feature(plugin)]
#![plugin(plugins)]
| random_line_split |
error.rs | use std::c_str::CString;
use std::error;
use std::fmt;
use std::str;
use libc;
use libc::c_int;
use {raw, ErrorCode};
/// A structure to represent errors coming out of libgit2.
pub struct Error {
raw: raw::git_error,
}
impl Error {
/// Returns the last error, or `None` if one is not available.
pub fn las... |
}
impl error::Error for Error {
fn description(&self) -> &str {
unsafe { str::from_c_str(self.raw.message as *const _) }
}
fn detail(&self) -> Option<String> { Some(self.message()) }
}
impl fmt::Show for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "[... | {
let cstr = unsafe { CString::new(self.raw.message as *const _, false) };
String::from_utf8_lossy(cstr.as_bytes_no_nul()).to_string()
} | identifier_body |
error.rs | use std::c_str::CString;
use std::error;
use std::fmt;
use std::str;
use libc;
use libc::c_int;
use {raw, ErrorCode};
/// A structure to represent errors coming out of libgit2.
pub struct Error {
raw: raw::git_error,
}
impl Error {
/// Returns the last error, or `None` if one is not available.
pub fn las... | GIT_EUSER,
GIT_EBAREREPO,
GIT_EUNBORNBRANCH,
GIT_EUNMERGED,
GIT_ENONFASTFORWARD,
GIT_EINVALIDSPEC,
GIT_EMERGECONFLICT,
GIT_ELOCKED,
GIT_EMODIFIED,
GIT_PASSTHROUGH,
GIT_ITEROVER
)
... | GIT_ERROR,
GIT_ENOTFOUND,
GIT_EEXISTS,
GIT_EAMBIGUOUS,
GIT_EBUFS, | random_line_split |
error.rs | use std::c_str::CString;
use std::error;
use std::fmt;
use std::str;
use libc;
use libc::c_int;
use {raw, ErrorCode};
/// A structure to represent errors coming out of libgit2.
pub struct Error {
raw: raw::git_error,
}
impl Error {
/// Returns the last error, or `None` if one is not available.
pub fn las... | (&self) -> &str {
unsafe { str::from_c_str(self.raw.message as *const _) }
}
fn detail(&self) -> Option<String> { Some(self.message()) }
}
impl fmt::Show for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "[{}] ", self.raw.klass));
let cstr = unsafe {... | description | identifier_name |
linked-list.rs | use vec_arena::Arena;
/// The null index, akin to null pointers.
///
/// Just like a null pointer indicates an address no object is ever stored at,
/// the null index indicates an index no object is ever stored at.
///
/// Number `!0` is the largest possible value representable by `usize`.
const NULL: usize = !0;
str... | assert!(list.remove(one) == 1);
assert!(list.remove(twenty) == 20);
// The list is now [2, 3, 10, 30].
assert!(list.len() == 4);
assert!(list.pop_front() == 2);
assert!(list.pop_front() == 3);
assert!(list.pop_front() == 10);
assert!(list.pop_front() == 30);
// The list is now []... | assert!(list.len() == 6);
| random_line_split |
linked-list.rs | use vec_arena::Arena;
/// The null index, akin to null pointers.
///
/// Just like a null pointer indicates an address no object is ever stored at,
/// the null index indicates an index no object is ever stored at.
///
/// Number `!0` is the largest possible value representable by `usize`.
const NULL: usize = !0;
str... | <T> {
/// Previous node in the list.
prev: usize,
/// Next node in the list.
next: usize,
/// Actual value stored in node.
value: T,
}
struct List<T> {
/// This is where nodes are stored.
arena: Arena<Node<T>>,
/// First node in the list.
head: usize,
/// Last node in th... | Node | identifier_name |
linked-list.rs | use vec_arena::Arena;
/// The null index, akin to null pointers.
///
/// Just like a null pointer indicates an address no object is ever stored at,
/// the null index indicates an index no object is ever stored at.
///
/// Number `!0` is the largest possible value representable by `usize`.
const NULL: usize = !0;
str... |
if b != NULL {
self.arena[b].prev = a;
}
}
/// Appends `value` to the back of the list.
fn push_back(&mut self, value: T) -> usize {
let node = self.arena.insert(Node {
prev: NULL,
next: NULL,
value: value,
});
let ta... | {
self.arena[a].next = b;
} | conditional_block |
linked-list.rs | use vec_arena::Arena;
/// The null index, akin to null pointers.
///
/// Just like a null pointer indicates an address no object is ever stored at,
/// the null index indicates an index no object is ever stored at.
///
/// Number `!0` is the largest possible value representable by `usize`.
const NULL: usize = !0;
str... |
/// Links nodes `a` and `b` together, so that `a` comes before `b` in the list.
fn link(&mut self, a: usize, b: usize) {
if a != NULL {
self.arena[a].next = b;
}
if b != NULL {
self.arena[b].prev = a;
}
}
/// Appends `value` to the back of the l... | {
self.arena.len()
} | identifier_body |
poller.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
agent_error::ImlAgentError,
http_comms::{
agent_client::AgentClient,
session::{Sessions, State},
},
};
use futures::{future, F... | name: PluginName,
now: Instant,
) -> impl Future<Output = Result<(), ImlAgentError>> {
tracing::trace!("handling state for {:?}: {:?}, ", name, state);
match state {
State::Active(a) if a.instant <= now && a.in_flight.is_none() => {
tracing::trace!("starting poll for {:?}:", name);
... | sessions: Sessions, | random_line_split |
poller.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
agent_error::ImlAgentError,
http_comms::{
agent_client::AgentClient,
session::{Sessions, State},
},
};
use futures::{future, F... | match r {
Ok(_) => {
sessions.reset_active(&name).await;
Ok(())
}
Err(_) => sessions.terminate_session(&name, &id).await,
}
})
.boxed()
}
St... | {
tracing::trace!("handling state for {:?}: {:?}, ", name, state);
match state {
State::Active(a) if a.instant <= now && a.in_flight.is_none() => {
tracing::trace!("starting poll for {:?}:", name);
let (rx, fut) = a.session.poll();
a.in_flight = Some(rx);
... | identifier_body |
poller.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
agent_error::ImlAgentError,
http_comms::{
agent_client::AgentClient,
session::{Sessions, State},
},
};
use futures::{future, F... |
Err(_) => sessions.terminate_session(&name, &id).await,
}
})
.boxed()
}
State::Active(a) if a.instant + a.session.deadline() <= now && a.in_flight.is_some() => {
tracing::trace!("Dropping poll for {:?}; deadline exceeded", name);
... | {
sessions.reset_active(&name).await;
Ok(())
} | conditional_block |
poller.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{
agent_error::ImlAgentError,
http_comms::{
agent_client::AgentClient,
session::{Sessions, State},
},
};
use futures::{future, F... | (
state: &mut State,
agent_client: AgentClient,
sessions: Sessions,
name: PluginName,
now: Instant,
) -> impl Future<Output = Result<(), ImlAgentError>> {
tracing::trace!("handling state for {:?}: {:?}, ", name, state);
match state {
State::Active(a) if a.instant <= now && a.in_flig... | handle_state | identifier_name |
ami2stomp-get.py | #!/usr/bin/env python
# vim: set expandtab shiftwidth=4:
# http://www.voip-info.org/wiki/view/asterisk+manager+events
import sys,time
import simplejson as json
from stompy.simple import Client
import ConfigParser
config = ConfigParser.ConfigParser()
devel_config = ConfigParser.ConfigParser()
config.read('/opt/ucall/... |
stomp.disconnect()
| message = stomp.get()
print message.body | conditional_block |
ami2stomp-get.py | #!/usr/bin/env python
# vim: set expandtab shiftwidth=4:
# http://www.voip-info.org/wiki/view/asterisk+manager+events
import sys,time
import simplejson as json
from stompy.simple import Client
import ConfigParser
config = ConfigParser.ConfigParser()
devel_config = ConfigParser.ConfigParser()
config.read('/opt/ucall/... |
stomp.disconnect() | random_line_split | |
fileNaming.py | """
You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.
Return an array of names that will... |
else:
for x in range(1, 16):
if "{}({})".format(name, x) not in new_names:
new_names.append("{}({})".format(name, x))
break
return new_names
if __name__ == '__main__':
print fileNaming(["doc", "doc", "image", "doc(1)", "doc"]) | new_names.append(name) | conditional_block |
fileNaming.py | """
You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.
Return an array of names that will... |
Guaranteed constraints:
5 <= names.length <= 15,
1 <= names[i].length <= 15.
[output] array.string
"""
def fileNaming(names):
new_names = []
for name in names:
if name not in new_names:
new_names.append(name)
else:
for x in range(1, 16):
if "{}({})".f... | [execution time limit] 4 seconds (py)
[input] array.string names | random_line_split |
fileNaming.py | """
You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.
Return an array of names that will... |
if __name__ == '__main__':
print fileNaming(["doc", "doc", "image", "doc(1)", "doc"]) | new_names = []
for name in names:
if name not in new_names:
new_names.append(name)
else:
for x in range(1, 16):
if "{}({})".format(name, x) not in new_names:
new_names.append("{}({})".format(name, x))
break
return ... | identifier_body |
fileNaming.py | """
You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet.
Return an array of names that will... | (names):
new_names = []
for name in names:
if name not in new_names:
new_names.append(name)
else:
for x in range(1, 16):
if "{}({})".format(name, x) not in new_names:
new_names.append("{}({})".format(name, x))
break... | fileNaming | identifier_name |
physics.rs | use std::collections::HashMap;
use cgmath::{EuclideanVector};
use specs;
use world as w;
const CELL_SIZE: f32 = 1.0;
const OFFSETS: [(i32, i32); 9] = [(0, 0),
(1, 0), (0, 1), (-1, 0), (0, -1),
(1, 1), (1, -1), (-1, 1), (-1, -1)];
#[derive(Debug, Eq, Hash, PartialEq)]
pub struct Cell(i32, i32);
pub struct Sy... |
}
// clean up and delete more stuff
for (_, vec) in self.grid.iter_mut() {
for (e, damage) in vec.drain(..) {
let c = collision.get_mut(e).unwrap();
if c.health > damage {
c.health -= damage;
}else {
... | {
arg.delete(ent);
} | conditional_block |
physics.rs | use std::collections::HashMap;
use cgmath::{EuclideanVector};
use specs;
use world as w;
const CELL_SIZE: f32 = 1.0;
const OFFSETS: [(i32, i32); 9] = [(0, 0),
(1, 0), (0, 1), (-1, 0), (0, -1),
(1, 1), (1, -1), (-1, 1), (-1, -1)];
#[derive(Debug, Eq, Hash, PartialEq)]
pub struct Cell(i32, i32);
pub struct Sy... | () -> System {
System {
grid: HashMap::new(),
}
}
}
impl specs::System<super::Delta> for System {
fn run(&mut self, arg: specs::RunArg, _: super::Delta) {
use specs::Join;
let mut empty = Vec::new();
let (space, mut collision, entities) = arg.fetch(|w|
... | new | identifier_name |
physics.rs | use std::collections::HashMap;
use cgmath::{EuclideanVector};
use specs;
use world as w;
const CELL_SIZE: f32 = 1.0;
const OFFSETS: [(i32, i32); 9] = [(0, 0),
(1, 0), (0, 1), (-1, 0), (0, -1),
(1, 1), (1, -1), (-1, 1), (-1, -1)];
#[derive(Debug, Eq, Hash, PartialEq)]
pub struct Cell(i32, i32);
pub struct Sy... | }else {
arg.delete(ent);
}
}
// clean up and delete more stuff
for (_, vec) in self.grid.iter_mut() {
for (e, damage) in vec.drain(..) {
let c = collision.get_mut(e).unwrap();
if c.health > damage {
... | }
if col.health > damage {
self.grid.entry(cell).or_insert(Vec::new()).push((ent, damage)); | random_line_split |
sqlite2mysql.py | to the sqlite database file
tablePrefix a string to prefix the table names when copying to mysql database
pathToSettingsFile path to a settings file with logging and database information (yaml file)
-h, --help show this help message
-v, --version show version
-s, --... | (arguments=None):
"""
The main function used when ``yaml_to_database.py`` when installed as a cl tool
"""
# setup the command-line util settings
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="WARNING",
options_first=False,
projectName=False
... | main | identifier_name |
sqlite2mysql.py | path to the sqlite database file
tablePrefix a string to prefix the table names when copying to mysql database
pathToSettingsFile path to a settings file with logging and database information (yaml file)
-h, --help show this help message
-v, --version show version
-... | if table == "sqlite_sequence":
continue
# CREATE TABLE collection_books (folder_id, fingerprint, primary key(folder_id, fingerprint));
# GENEREATE THE MYSQL CREATE STATEMENTS FOR EACH TABLE
cur.execute(
"SELECT sql FROM sqlite_master WHERE... | """*copy the contents of the sqlite database into the mysql database*
See class docstring for usage
"""
from fundamentals.renderer import list_of_dictionaries
from fundamentals.mysql import directory_script_runner
self.log.debug('starting the ``convert_sqlite_to_mysql`` method')... | identifier_body |
sqlite2mysql.py | path to the sqlite database file
tablePrefix a string to prefix the table names when copying to mysql database
pathToSettingsFile path to a settings file with logging and database information (yaml file)
-h, --help show this help message
-v, --version show version
-... |
log.debug('%s = %s' % (varname, val,))
from fundamentals.mysql import sqlite2mysql
converter = sqlite2mysql(
log=log,
settings=settings,
pathToSqlite=pathToSqliteDB,
tablePrefix=tablePrefix,
dbConn=dbConn
)
converter.convert_sqlite_to_mysql()
return... | dbConn = val | conditional_block |
sqlite2mysql.py | path to the sqlite database file
tablePrefix a string to prefix the table names when copying to mysql database
pathToSettingsFile path to a settings file with logging and database information (yaml file)
-h, --help show this help message
-v, --version show version
-... | if table == "sqlite_sequence":
continue
# CREATE TABLE collection_books (folder_id, fingerprint, primary key(folder_id, fingerprint));
# GENEREATE THE MYSQL CREATE STATEMENTS FOR EACH TABLE
cur.execute(
"SELECT sql FROM sqlite_master WHERE... | for table in tables:
table = table['name'] | random_line_split |
ngx-gallery.component.spec.ts | import { NgxGalleryImage } from './ngx-gallery-image.model';
import { } from 'jasmine';
import { Renderer, SimpleChange } from '@angular/core';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import {
NgxGalleryComponent, NgxGalleryActionComponent, NgxGalleryImageComponent, NgxGalleryThumbnailsCo... | ];
comp.options = [ new NgxGalleryOptions({}) ];
fixture.detectChanges();
el = fixture.debugElement.nativeElement;
});
it('should create component', () => {
expect(fixture.componentInstance).toBeTruthy();
});
it('should return true from canShowNext if there are... | medium: 'assets/3-medium.jpg',
big: 'assets/3-big.jpg'
}) | random_line_split |
static-method-xcrate.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 result: int = read(~"5");
assert!(result == 5);
assert!(readMaybeRenamed(~"false") == Some(false));
assert!(readMaybeRenamed(~"foo") == None::<bool>);
} | identifier_body | |
static-method-xcrate.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 result: int = read(~"5");
assert!(result == 5);
assert!(readMaybeRenamed(~"false") == Some(false));
assert!(readMaybeRenamed(~"foo") == None::<bool>);
}
| main | identifier_name |
static-method-xcrate.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// xfail-fast
// aux-build:static-methods-crate.rs
extern mod static_methods_crate;
use... | random_line_split | |
urls.py | from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^register/$', views.register,name="register"),
# url('^logout', views.logout_view,name="logout"),
# url('^login', views.logout_view,name="login"),
url(r'^password_change/$','django.contrib.auth.views.pa... | url(r'^logout/$', 'django.contrib.auth.views.logout',
{'next_page': '/'}),
url(r'^', include('django.contrib.auth.urls')),
url(r'^myprofile/$', views.myprofile, name='myprofile'),
url(r'^users/$', views.user_profilelist, name='user_profilelist'),
url(r'^... | url(r'^password_change/done',
'django.contrib.auth.views.password_change_done',
{'template_name':'profiles/password_change_done.html'}),
url(r'^login/$', 'django.contrib.auth.views.login'), | random_line_split |
channel.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from wtforms import validators
from jinja2 import Markup
from studio.core.engines import db
from riitc.models import NaviModel, ChannelModel
from .base import BaseView
from .forms import CKTextAreaField
class Navi(BaseView):
column_labels = {'name... | urn Markup('<ol>' + lis + '</ol>')
column_formatters = {
'channels': _list_channels,
}
def __init__(self, **kwargs):
super(Navi, self).__init__(NaviModel, db.session, **kwargs)
def create_form(self, obj=None):
form = super(Navi, self).create_form()
delattr(form, 'date_... | %s</li>' % (channel)
ret | conditional_block |
channel.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from wtforms import validators
from jinja2 import Markup
from studio.core.engines import db
from riitc.models import NaviModel, ChannelModel
from .base import BaseView
from .forms import CKTextAreaField
class Navi(BaseView):
column_labels = {'name... | delattr(form, 'channels')
delattr(form, 'all_articles')
delattr(form, 'date_created')
return form | random_line_split | |
channel.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from wtforms import validators
from jinja2 import Markup
from studio.core.engines import db
from riitc.models import NaviModel, ChannelModel
from .base import BaseView
from .forms import CKTextAreaField
class Navi(BaseView):
column_labels = {'name... | nnel(BaseView):
create_template = 'panel/channel_edit.html'
edit_template = 'panel/channel_edit.html'
column_labels = {'name': '名称',
'parent': '主分类(本身为主分类,不填写)',
'summary': '简介',
'date_created': '创建时间'}
column_searchable_list = ['name', ]
... | (Navi, self).edit_form(obj=obj)
delattr(form, 'date_created')
return form
class Cha | identifier_body |
channel.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from wtforms import validators
from jinja2 import Markup
from studio.core.engines import db
from riitc.models import NaviModel, ChannelModel
from .base import BaseView
from .forms import CKTextAreaField
class Navi(BaseView):
column_labels = {'name... | annelModel, db.session, **kwargs)
def create_form(self, obj=None):
form = super(Channel, self).create_form()
delattr(form, 'articles')
delattr(form, 'channels')
delattr(form, 'all_articles')
delattr(form, 'date_created')
return form
def edit_form(self, obj=None)... | nit__(Ch | identifier_name |
mainwindow.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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,... |
def __set_layout(self):
exit_action = QAction(QIcon(':exit-game.png'),
'&Quit',
self)
exit_action.setShortcut('Ctrl+Q')
exit_action.setStatusTip('Quit game')
exit_action.triggered.connect(PyQt4.QtGui.qApp.quit)
i... | self.controller = controller
self.__set_layout() | random_line_split |
mainwindow.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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,... |
class MainWindow(QMainWindow):
"""
Class for displaying main window
.. versionadded:: 0.5
"""
def __init__(self, application, surface_manager, qt_app, parent, flags,
controller):
"""
Default constructor
"""
super().__init__(parent, flags)
... | """
Show main window
"""
main_window = MainWindow(self.application,
self.application.surface_manager,
self.qt_app,
None,
Qt.FramelessWindowHint,
... | identifier_body |
mainwindow.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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,... |
def __show_map_window(self):
"""
Show map window
"""
self.map_window.construct_scene()
def __show_message_window(self, character):
"""
Show message display
:param character: character which events to display
:type character: Character
"... | player = start_dialog.player_character
intro_text = self.controller.setup_world(self.application.world,
player)
player.register_for_updates(self.map_window.hit_points_widget)
self.map_window.hit_points_widget.show_hit_points(play... | conditional_block |
mainwindow.py | # -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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,... | ():
"""
Class for Qt User Interface
.. versionadded:: 0.9
"""
def __init__(self, application):
"""
Default constructor
"""
super().__init__()
self.application = application
self.splash_screen = None
self.qt_app = QApplication([])
# s... | QtUserInterface | identifier_name |
Stacked100.js | /**
* 100% stacked area are multi-series area charts where categories are stacked (percentage
* values) on top of each other, with an additional category 'Others' that is used to sum
* up the various categories for each series to a perfect 100%.
*/
Ext.define('KitchenSink.view.charts.area.Stacked100', {
extend:... | path: 'classic/samples/view/charts/area/Stacked100Controller.js'
}, {
type: 'Store',
path: 'classic/samples/store/Browsers.js'
}],
// </example>
width: 650,
tbar: [
'->',
{
text: 'Preview',
handler: 'onPreview'
}
],
it... | },
otherContent: [{
type: 'Controller', | random_line_split |
values.rs | ` in CSS syntax and return a string.
///
/// (This is a convenience wrapper for `to_css` and probably should not be overridden.)
#[inline]
fn to_css_string(&self) -> String {
let mut s = String::new();
self.to_css(&mut CssWriter::new(&mut s)).unwrap();
s
}
}
impl<'a, T> ToCs... |
self.inner.write_str(s)
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
if let Some(prefix) = self.prefix.take() {
// See comment in `write_str`.
if !prefix.is_empty() {
self.inner.write_str(prefix)?;
}
}
se... | {
// We are going to write things, but first we need to write
// the prefix that was set by `SequenceWriter::item`.
if !prefix.is_empty() {
self.inner.write_str(prefix)?;
}
} | conditional_block |
values.rs | self` in CSS syntax and return a string.
///
/// (This is a convenience wrapper for `to_css` and probably should not be overridden.)
#[inline]
fn to_css_string(&self) -> String {
let mut s = String::new();
self.to_css(&mut CssWriter::new(&mut s)).unwrap();
s
}
}
impl<'a, T> ... | self.inner.write_str(s)
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
if let Some(prefix) = self.prefix.take() {
// See comment in `write_str`.
if !prefix.is_empty() {
self.inner.write_str(prefix)?;
}
}
sel... | if !prefix.is_empty() {
self.inner.write_str(prefix)?;
}
} | random_line_split |
values.rs | ` in CSS syntax and return a string.
///
/// (This is a convenience wrapper for `to_css` and probably should not be overridden.)
#[inline]
fn to_css_string(&self) -> String {
let mut s = String::new();
self.to_css(&mut CssWriter::new(&mut s)).unwrap();
s
}
}
impl<'a, T> ToCs... |
#[inline]
fn write_item<F>(&mut self, f: F) -> fmt::Result
where
F: FnOnce(&mut CssWriter<'b, W>) -> fmt::Result
{
let old_prefix = self.inner.prefix;
if old_prefix.is_none() {
// If there is no prefix in the inner writer, a previous
// call to this meth... | {
if inner.prefix.is_none() {
// See comment in `item`.
inner.prefix = Some("");
}
Self { inner, separator }
} | identifier_body |
values.rs | separator as necessary.
///
/// See SequenceWriter::item.
#[inline]
pub fn raw_item(&mut self, item: &str) -> fmt::Result {
self.write_item(|inner| inner.write_str(item))
}
}
/// Type used as the associated type in the `OneOrMoreSeparated` trait on a
/// type to indicate that a serialized ... | is_ok | identifier_name | |
v1.js | /**
* Copyright 2015 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 appli... | * // 3. To install the client library and Application Default Credentials library, run:
* // 'npm install googleapis --save'
* var google = require('googleapis');
* var vision = google.vision('v1');
*
* google.auth.getApplicationDefault(function(err, authClient) {
* if (err) {
... | { // eslint-disable-line
var self = this;
self._options = options || {};
self.images = {
/**
* vision.images.annotate
*
* @desc Run image detection and annotation for a batch of images.
*
* @example
* // PRE-REQUISITES:
* // ---------------
* // 1. If not already done... | identifier_body |
v1.js | /**
* Copyright 2015 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 appli... | */
function Vision(options) { // eslint-disable-line
var self = this;
self._options = options || {};
self.images = {
/**
* vision.images.annotate
*
* @desc Run image detection and annotation for a batch of images.
*
* @example
* // PRE-REQUISITES:
* // ---------------
... | * @variation v1
* @param {object=} options Options for Vision | random_line_split |
v1.js | /**
* Copyright 2015 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 appli... | (options) { // eslint-disable-line
var self = this;
self._options = options || {};
self.images = {
/**
* vision.images.annotate
*
* @desc Run image detection and annotation for a batch of images.
*
* @example
* // PRE-REQUISITES:
* // ---------------
* // 1. If not al... | Vision | identifier_name |
rest-controller.ts | import { App, Console } from '@lyrics/core';
import { Route, Controller, Inject } from '@lyrics/annotation';
import { Request, Response, JsonResponse } from '@lyrics/http';
import { BaseController } from '@lyrics/controller';
@Controller('/rest')
export class RestControlle... | ()
{
return new JsonResponse({ message: 'REST get route action.' }, 200);
}
@Route('/post', {
type: 'POST',
requirements: {
body: {
id: 'number',
surname: 'string',
name: ['string', 'null'],
},
h... | indexAction | identifier_name |
rest-controller.ts | import { App, Console } from '@lyrics/core';
import { Route, Controller, Inject } from '@lyrics/annotation';
import { Request, Response, JsonResponse } from '@lyrics/http';
import { BaseController } from '@lyrics/controller';
@Controller('/rest')
export class RestControlle... | }
@Route('/get', {
type: 'GET'
})
indexAction()
{
return new JsonResponse({ message: 'REST get route action.' }, 200);
}
@Route('/post', {
type: 'POST',
requirements: {
body: {
id: 'number',
surname: 'string',
... | random_line_split | |
rest-controller.ts | import { App, Console } from '@lyrics/core';
import { Route, Controller, Inject } from '@lyrics/annotation';
import { Request, Response, JsonResponse } from '@lyrics/http';
import { BaseController } from '@lyrics/controller';
@Controller('/rest')
export class RestControlle... |
@Route('/post', {
type: 'POST',
requirements: {
body: {
id: 'number',
surname: 'string',
name: ['string', 'null'],
},
headers: { Token: 'string' }
}
})
createAction(request: Request)
{
... | {
return new JsonResponse({ message: 'REST get route action.' }, 200);
} | identifier_body |
crs.js | const {PI} = Math
import SphericalMercator from './sphericalmercator'
import Transformation from './transformation'
class | {
constructor(opts) {
this.projection = new SphericalMercator()
this.tileSize = 256 + 256 * (opts.zoom % 1)
const earthRadius = 6378137
const scale = 0.5 / (PI * earthRadius);
this.transformation = new Transformation(scale, 0.5, -scale, 0.5)
}
// @method scale(zoom: Number): Number
// Returns the sca... | CRS | identifier_name |
crs.js | const {PI} = Math
import SphericalMercator from './sphericalmercator'
import Transformation from './transformation'
class CRS {
constructor(opts) {
this.projection = new SphericalMercator()
this.tileSize = 256 + 256 * (opts.zoom % 1)
const earthRadius = 6378137
const scale = 0.5 / (PI * earthRadius);
thi... | // Inverse of `scale()`, returns the zoom level corresponding to a scale
// factor of `scale`.
zoom(scale) {
return Math.log(scale / this.tileSize) / Math.LN2;
}
// @method latLngToPoint(latlng: LatLng, zoom: Number): Point
// Projects geographical coordinates into pixel coordinates for a given zoom.
latLngT... |
// @method zoom(scale: Number): Number | random_line_split |
fileutil.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import shu... |
return {
'linecount': lambda srcs: sum(line_count(src) for src in srcs),
'filecount': lambda srcs: len(srcs),
'filesize': lambda srcs: sum(os.path.getsize(src) for src in srcs),
'nosize': lambda srcs: 0,
}
| with open(filename, 'rb') as fh:
return sum(1 for line in fh) | identifier_body |
fileutil.py | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import shu... | (filename):
with open(filename, 'rb') as fh:
return sum(1 for line in fh)
return {
'linecount': lambda srcs: sum(line_count(src) for src in srcs),
'filecount': lambda srcs: len(srcs),
'filesize': lambda srcs: sum(os.path.getsize(src) for src in srcs),
'nosize': lambda srcs: 0,
}
| line_count | identifier_name |
conftest.py | import pytest
import sys
pytest_plugins = "pytester",
import os, py
pid = os.getpid()
def pytest_addoption(parser):
parser.addoption('--lsof',
action="store_true", dest="lsof", default=False,
help=("run FD checks if lsof is available"))
def pytest_configure(config):
config.addinivalue_... | (item, __multicall__):
item._oldir.chdir()
if hasattr(item.config, '_numfiles'):
x = __multicall__.execute()
check_open_files(item.config)
return x
def pytest_generate_tests(metafunc):
multi = getattr(metafunc.function, 'multi', None)
if multi is not None:
assert len(mul... | pytest_runtest_teardown | identifier_name |
conftest.py | import pytest
import sys
pytest_plugins = "pytester",
import os, py
pid = os.getpid()
def pytest_addoption(parser):
parser.addoption('--lsof',
action="store_true", dest="lsof", default=False,
help=("run FD checks if lsof is available"))
def pytest_configure(config):
config.addinivalue_... | def pytest_runtest_setup(item):
item._oldir = py.path.local()
def pytest_runtest_teardown(item, __multicall__):
item._oldir.chdir()
if hasattr(item.config, '_numfiles'):
x = __multicall__.execute()
check_open_files(item.config)
return x
def pytest_generate_tests(metafunc):
mult... | # update numfile so that the overall test run continuess
config._numfiles = len(lines2)
raise AssertionError("\n".join(error))
@pytest.mark.tryfirst # XXX rather do item.addfinalizer | random_line_split |
conftest.py | import pytest
import sys
pytest_plugins = "pytester",
import os, py
pid = os.getpid()
def pytest_addoption(parser):
parser.addoption('--lsof',
action="store_true", dest="lsof", default=False,
help=("run FD checks if lsof is available"))
def pytest_configure(config):
config.addinivalue_... |
pytest.skip("no suitable %s found" % (name,))
return executable
| return executable | conditional_block |
conftest.py | import pytest
import sys
pytest_plugins = "pytester",
import os, py
pid = os.getpid()
def pytest_addoption(parser):
|
def pytest_configure(config):
config.addinivalue_line("markers",
"multi(arg=[value1,value2, ...]): call the test function "
"multiple times with arg=value1, then with arg=value2, ... "
)
if config.getvalue("lsof"):
try:
out = py.process.cmdexec("lsof -p %d" % pid)
... | parser.addoption('--lsof',
action="store_true", dest="lsof", default=False,
help=("run FD checks if lsof is available")) | identifier_body |
forms.py | #
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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
#
# Unle... | (forms.SelfHandlingForm):
source_type = forms.ChoiceField(
label=_('Namespace Definition Source'),
choices=[('file', _('Metadata Definition File')),
('raw', _('Direct Input'))],
widget=forms.ThemableSelectWidget(
attrs={'class': 'switchable', 'data-slug': 'source... | CreateNamespaceForm | identifier_name |
forms.py | #
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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
#
# Unle... |
namespace = json.loads(ns_str)
if data['public']:
namespace['visibility'] = 'public'
else:
namespace['visibility'] = 'private'
namespace['protected'] = data['protected']
for protected_prop in constants.METADEFS_PROTECTED_PRO... | ns_str = data['direct_input'] | conditional_block |
forms.py | #
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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
#
# Unle... | public = forms.BooleanField(label=_("Public"), required=False)
protected = forms.BooleanField(label=_("Protected"), required=False)
def handle(self, request, data):
try:
params = {
'visibility': 'public' if data['public'] else 'private',
'protected': data['pr... | identifier_body | |
forms.py | #
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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
#
# Unle... | msg = _('Resource types updated for namespace %s.')
msg %= namespace_name
messages.success(request, msg)
except Exception:
msg = _('Error updating resource types for namespace %s.')
msg %= namespace_name
exceptions.handle(request, msg)
... | self.request, namespace_name, selected_type) | random_line_split |
BaseEntity.ts | import {Toolkit} from "./Toolkit";
/**
* @author Dylan Vorster
*/
export class BaseListener{
lockChanged?(entity: BaseEntity<BaseListener>,locked: boolean): void;
}
export class BaseEntity<T extends BaseListener>{
public listeners:{[s: string]: T};
public id: string;
public locked: boolean;
constructor(id?:... |
clearListeners(){
this.listeners = {};
}
public deSerialize(data){
this.id = data.id;
}
public serialize(){
return {
id: this.id,
}
}
public iterateListeners(cb: (t: T) => any){
for (var i in this.listeners){
cb(this.listeners[i]);
}
}
public removeListener(listener: string){
... | {
return this.id;
} | identifier_body |
BaseEntity.ts | import {Toolkit} from "./Toolkit";
/**
* @author Dylan Vorster
*/
export class BaseListener{
lockChanged?(entity: BaseEntity<BaseListener>,locked: boolean): void;
}
export class BaseEntity<T extends BaseListener>{
public listeners:{[s: string]: T};
public id: string;
public locked: boolean;
constructor(id?:... | (data){
this.id = data.id;
}
public serialize(){
return {
id: this.id,
}
}
public iterateListeners(cb: (t: T) => any){
for (var i in this.listeners){
cb(this.listeners[i]);
}
}
public removeListener(listener: string){
if (this.listeners[listener]){
delete this.listeners[listener];
... | deSerialize | identifier_name |
BaseEntity.ts | import {Toolkit} from "./Toolkit";
/**
* @author Dylan Vorster
*/
export class BaseListener{
lockChanged?(entity: BaseEntity<BaseListener>,locked: boolean): void;
}
export class BaseEntity<T extends BaseListener>{
public listeners:{[s: string]: T};
public id: string;
public locked: boolean;
constructor(id?:... |
return false;
}
public addListener(listener: T): string{
var uid = Toolkit.UID();
this.listeners[uid] = listener;
return uid;
}
public isLocked(): boolean{
return this.locked;
}
public setLocked(locked: boolean = true){
this.locked = locked;
this.iterateListeners((listener) => {
if (listen... | {
delete this.listeners[listener];
return true;
} | conditional_block |
BaseEntity.ts | import {Toolkit} from "./Toolkit";
/**
* @author Dylan Vorster
*/
export class BaseListener{
lockChanged?(entity: BaseEntity<BaseListener>,locked: boolean): void;
}
export class BaseEntity<T extends BaseListener>{
public listeners:{[s: string]: T};
public id: string;
public locked: boolean; | this.listeners = {};
this.id = id || Toolkit.UID();
this.locked = false;
}
getID(){
return this.id;
}
clearListeners(){
this.listeners = {};
}
public deSerialize(data){
this.id = data.id;
}
public serialize(){
return {
id: this.id,
}
}
public iterateListeners(cb: (t: T) => any){
... |
constructor(id?:string){ | random_line_split |
openstackcloud.py | requests a version, and it's not found, and a different one
# openstack.cloud does know about is found, that's a warning in
# openstack.cloud.
if config_version:
if min_major and config_major < min_major:
raise exc.OpenStackCloudException(
"Versio... | _get_project_id_param_dict | identifier_name | |
openstackcloud.py | self.auth = self.config.get_auth_args()
self.default_interface = self.config.get_interface()
self.force_ipv4 = self.config.force_ipv4
(self.verify, self.cert) = self.config.get_requests_verify_args()
# Turn off urllib3 warnings about insecure certs if we have
# explicit... | self.name = self.config.name | random_line_split | |
openstackcloud.py | # fall back to whatever it was before
self._SERVER_AGE = self.config.get_cache_resource_expiration(
'server', self._SERVER_AGE)
self._PORT_AGE = self.config.get_cache_resource_expiration(
'port', self._PORT_AGE)
self._FLOAT_AGE = self.config.get_cache_resource_exp... |
# If there are user, project or domain settings in the incoming auth
# dict, strip out both id and name so that a user can say:
# cloud.connect_as(project_name='foo')
# and have that work with clouds that have a project_id set in their
# config.
for prefix in ('user... | params['auth'].pop(name_key, None)
params['auth'].pop(id_key, None) | conditional_block |
openstackcloud.py | elif isinstance(version, six.string_types + (tuple,)):
return int(version[0])
return version
def _get_versioned_client(
self, service_type, min_version=None, max_version=None):
config_version = self.config.get_api_version(service_type)
config_major = self._ge... | project_info = munch.Munch(
id=project_id,
name=None,
domain_id=None,
domain_name=None,
)
if not project_id or project_id == self.current_project_id:
# If we don't have a project_id parameter, it means a user is
# directly asking wh... | identifier_body | |
include.js | (function () {
var
oLoginViewModel,
oSettingsViewModel
;
AfterLogicApi.addPluginHook('view-model-defined', function (sViewModelName, oViewModel) {
if (oViewModel && ('CLoginViewModel' === sViewModelName))
{
oLoginViewModel = oViewModel;
}
if (oViewMo... |
});
}()); | {
oData['StopExecuteResponse'] = true;
AfterLogicApi.showPopup(VerifyTokenPopup, [this.oParams.Email, oLoginViewModel]);
} | conditional_block |
include.js | (function () {
var
oLoginViewModel,
oSettingsViewModel
;
AfterLogicApi.addPluginHook('view-model-defined', function (sViewModelName, oViewModel) {
if (oViewModel && ('CLoginViewModel' === sViewModelName))
{
oLoginViewModel = oViewModel;
}
if (oViewMo... |
AfterLogicApi.addPluginHook('ajax-default-response', function (sAction, oData) {
if (('SystemLogin' === sAction && oData.Result != false && oData.ContinueAuth != true))
{
oData['StopExecuteResponse'] = true;
AfterLogicApi.showPopup(VerifyTokenPopup, [this.oParam... | });
| random_line_split |
HTMLOptionElement-impl.js | "use strict";
const HTMLElementImpl = require("./HTMLElement-impl").implementation;
const { stripAndCollapseASCIIWhitespace } = require("../helpers/strings");
const { domSymbolTree } = require("../helpers/internal-constants");
const { closest } = require("../helpers/traversal");
const { formOwner } = require("../helpe... |
}
return select;
}
get form() {
return formOwner(this);
}
get text() {
// TODO is not correctly excluding script and SVG script descendants
return stripAndCollapseASCIIWhitespace(this.textContent);
}
set text(value) {
this.textContent = value;
}
// https://html.spec.whatwg.or... | {
return null;
} | conditional_block |
HTMLOptionElement-impl.js | "use strict";
const HTMLElementImpl = require("./HTMLElement-impl").implementation;
const { stripAndCollapseASCIIWhitespace } = require("../helpers/strings");
const { domSymbolTree } = require("../helpers/internal-constants");
const { closest } = require("../helpers/traversal");
const { formOwner } = require("../helpe... | extends HTMLElementImpl {
constructor(globalObject, args, privateData) {
super(globalObject, args, privateData);
// whenever selectedness is set to true, make sure all
// other options set selectedness to false
this._selectedness = false;
this._dirtyness = false;
}
_removeOtherSelectedness(... | HTMLOptionElementImpl | identifier_name |
HTMLOptionElement-impl.js | "use strict";
const HTMLElementImpl = require("./HTMLElement-impl").implementation;
const { stripAndCollapseASCIIWhitespace } = require("../helpers/strings");
const { domSymbolTree } = require("../helpers/internal-constants");
const { closest } = require("../helpers/traversal");
const { formOwner } = require("../helpe... |
get text() {
// TODO is not correctly excluding script and SVG script descendants
return stripAndCollapseASCIIWhitespace(this.textContent);
}
set text(value) {
this.textContent = value;
}
// https://html.spec.whatwg.org/multipage/form-elements.html#concept-option-value
_getValue() {
if (t... | {
return formOwner(this);
} | identifier_body |
HTMLOptionElement-impl.js | "use strict";
const HTMLElementImpl = require("./HTMLElement-impl").implementation;
const { stripAndCollapseASCIIWhitespace } = require("../helpers/strings");
const { domSymbolTree } = require("../helpers/internal-constants");
const { closest } = require("../helpers/traversal");
const { formOwner } = require("../helpe... |
module.exports = {
implementation: HTMLOptionElementImpl
}; | } | random_line_split |
index.js | 'use strict';
const url = require('url');
const _ = {
map: require('lodash/map'),
trimStart: require('lodash/trimStart'),
sortBy: require('lodash/sortBy'),
isString: require('lodash/isString'),
forEach: require('lodash/forEach'),
remove: require('lodash/remove'),
has... | ;
function treefyByPathname(urls){
let host = urls[0].host;
let tree = {
branch: []
};
_.forEach(urls, function(urlObj){
let pathparts = _.split(urlObj.pathname, '/');
_.remove(pathparts, function(name) {
return name === '';
});
pathparts.unshift(host);
let node = tree;
_.fo... | {
if(_.isString(link)){
return url.parse(link);
}
return url.parse(link.url);
} | identifier_body |
index.js | 'use strict';
const url = require('url');
const _ = {
map: require('lodash/map'),
trimStart: require('lodash/trimStart'),
sortBy: require('lodash/sortBy'),
isString: require('lodash/isString'),
forEach: require('lodash/forEach'),
remove: require('lodash/remove'),
has... | if(index === -1){
index = node.branch.push({
name: name,
count: 0
}) - 1;
}
let branchNode = node.branch[index];
branchNode.count += 1;
return branchNode;
};
function linkDirectories(urls){
let treeList = treefy(urls);
_.forEach(treeList, linkDirectory);
return treeList;
};
func... | if(_.has(node, 'branch') === false){
node.branch = [];
}
let index = _.findIndex(node.branch, function(o) { return o.name === name; }); | random_line_split |
index.js | 'use strict';
const url = require('url');
const _ = {
map: require('lodash/map'),
trimStart: require('lodash/trimStart'),
sortBy: require('lodash/sortBy'),
isString: require('lodash/isString'),
forEach: require('lodash/forEach'),
remove: require('lodash/remove'),
has... | (urls){
let domains = exports.domain(urls);
return _.map(domains, function(domain){
return exports.treefyByPathname(domain);
});
};
function domain(links){
links = _.map(links, parse);
let domains = _.groupBy(links, function(link){
return _.trimStart(link.hostname, 'www.');
});
domains = _.sort... | treefy | identifier_name |
index.js | 'use strict';
const url = require('url');
const _ = {
map: require('lodash/map'),
trimStart: require('lodash/trimStart'),
sortBy: require('lodash/sortBy'),
isString: require('lodash/isString'),
forEach: require('lodash/forEach'),
remove: require('lodash/remove'),
has... |
return url.parse(link.url);
};
function treefyByPathname(urls){
let host = urls[0].host;
let tree = {
branch: []
};
_.forEach(urls, function(urlObj){
let pathparts = _.split(urlObj.pathname, '/');
_.remove(pathparts, function(name) {
return name === '';
});
pathparts.unshift(host)... | {
return url.parse(link);
} | conditional_block |
json_dumper.rs | // Copyright 2016 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 ... | use rls_data::{self, Analysis, CompilationOptions, CratePreludeData, Def, DefKind, Impl, Import,
MacroRef, Ref, RefKind, Relation};
use rls_span::{Column, Row};
#[derive(Debug)]
pub struct Access {
pub reachable: bool,
pub public: bool,
}
pub struct JsonDumper<O: DumpOutput> {
result: Analy... | random_line_split | |
json_dumper.rs | // Copyright 2016 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 ... |
}
| {
self.result.impls.push(data);
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.