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 |
|---|---|---|---|---|
link.tsx | import React from "react";
import { Link as ReachRouterLink } from "@reach/router";
interface ILinkProps {
to: string;
rawLink?: boolean;
className?: string;
targetBlank?: boolean;
children: React.ReactNode;
}
export const Link = (props: ILinkProps) => {
const { to, className, targetBlank, children } = pr... | {...targetBlankProps}>
{children}
</a>
);
} else {
return (
<ReachRouterLink to={to} className={className}>
{children}
</ReachRouterLink>
);
}
};
| {
const targetBlankProps = targetBlank
? {
rel: "noopener noreferrer",
target: "_blank"
}
: {};
return (
<a href={to} className={className} | conditional_block |
link.tsx | import React from "react";
import { Link as ReachRouterLink } from "@reach/router";
interface ILinkProps {
to: string;
rawLink?: boolean;
className?: string;
targetBlank?: boolean;
children: React.ReactNode;
}
export const Link = (props: ILinkProps) => {
const { to, className, targetBlank, children } = pr... | } else {
return (
<ReachRouterLink to={to} className={className}>
{children}
</ReachRouterLink>
);
}
}; | return (
<a href={to} className={className} {...targetBlankProps}>
{children}
</a>
); | random_line_split |
dump_worksheet.py | sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "A... | self._fileobj_name = create_temporary_file()
self._shared_date = SharedDate()
self._string_builder = self._parent.strings_table_builder
def get_temporary_file(self, filename):
if filename in self._descriptors_cache:
fobj = self._descriptors_cache[filename]
#... | self._fileobj_header_name = create_temporary_file(suffix='.header')
self._fileobj_content_name = create_temporary_file(suffix='.content') | random_line_split |
dump_worksheet.py | sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "A... | if isinstance(cell, bool):
dtype = 'boolean'
elif isinstance(cell, NUMERIC_TYPES):
dtype = 'numeric'
elif isinstance(cell, (datetime.datetime, datetime.date)):
dtype = 'datetime'
cell = self._shared_date.datetime_to_juli... | """
:param row: iterable containing values to append
:type row: iterable
"""
doc = self._get_content_generator()
self._max_row += 1
span = len(row)
self._max_col = max(self._max_col, span)
row_idx = self._max_row
attrs = {'r': '%d' % row_idx,
... | identifier_body |
dump_worksheet.py | , and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITH... |
elif isinstance(cell, NUMERIC_TYPES):
dtype = 'numeric'
elif isinstance(cell, (datetime.datetime, datetime.date)):
dtype = 'datetime'
cell = self._shared_date.datetime_to_julian(cell)
attributes['s'] = STYLES[dtype]['style']
... | dtype = 'boolean' | conditional_block |
dump_worksheet.py | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# @license: http://www.opensource.org/licenses/mit-license.php
# @author: see AUTHORS file
"""Write wo... | _write_worksheets | identifier_name | |
docker.rs | use std::io;
use std::io::prelude::*;
use std::mem;
use std::process::{Output, Command, Stdio, ExitStatus};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use wait_timeout::ChildExt;
pub struct Container {
id: String,
}
impl Container {
pub fn new(cmd: &str,
... | else {
let s = output_lossy.chars().take(1024).collect::<String>();
debug!("output (truncated): {}...", s);
}
}
Ok((status, output, timeout))
}
}
fn append(into: &Mutex<Vec<u8>>, from: &mut Read) {
let mut buf = [0; 1024];
while let Ok(amt) = fro... | {
debug!("output: {}", output_lossy);
} | conditional_block |
docker.rs | use std::io;
use std::io::prelude::*;
use std::mem;
use std::process::{Output, Command, Stdio, ExitStatus};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use wait_timeout::ChildExt;
pub struct | {
id: String,
}
impl Container {
pub fn new(cmd: &str,
args: &[String],
env: &[(String, String)],
name: &str) -> io::Result<Container> {
let out = try!(run(Command::new("docker")
.arg("create")
... | Container | identifier_name |
docker.rs | use std::io;
use std::io::prelude::*;
use std::mem;
use std::process::{Output, Command, Stdio, ExitStatus};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use wait_timeout::ChildExt;
pub struct Container {
id: String,
}
impl Container {
pub fn new(cmd: &str,
... | }
into.lock().unwrap().extend_from_slice(&buf[..amt]);
}
}
impl Drop for Container {
fn drop(&mut self) {
run(Command::new("docker")
.arg("rm")
.arg("--force")
.arg(&self.id)).unwrap();
}
}
fn run(cmd: &mut Command) -> io:... | if amt == 0 {
break | random_line_split |
docker.rs | use std::io;
use std::io::prelude::*;
use std::mem;
use std::process::{Output, Command, Stdio, ExitStatus};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use wait_timeout::ChildExt;
pub struct Container {
id: String,
}
impl Container {
pub fn new(cmd: &str,
... | let sink2 = sink.clone();
let stderr = thread::spawn(move || append(&sink2, &mut stderr));
let (status, timeout) = match try!(cmd.wait_timeout(timeout)) {
Some(status) => {
debug!("finished before timeout");
// TODO: document this
(uns... | {
let mut cmd = Command::new("docker");
cmd.arg("start")
.arg("--attach")
.arg("--interactive")
.arg(&self.id)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
debug!("attaching with {:?}", cmd);
let... | identifier_body |
export_to_three.js.py | FaceMaterial());
//set transforms
model.position = myGeom.getPosition()
model.rotation = myGeom.getRotation()
model.scale = myGeom.getScale()
//set selection tags colours
myGeom.autoColor()
More details on this exporter and more js examples here:
https://github.com/orgicus/three.js
Have fun!
This script requires ... |
else:
code += '\tuv( %.6f, %.6f, %.6f, %.6f, %.6f, %.6f);\n' % (uv['a'].x, uv['a'].y, uv['b'].x, uv['b'].y, uv['c'].x, uv['c'].y)
ncount += 1
uvcount += 1
code +='\n\tthis.computeCentroids();\n\tthis.computeNormals(true);\n'
#selection... | code += '\tuv( %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f, %.6f);\n' % (uv['a'].x, uv['a'].y, uv['b'].x, uv['b'].y, uv['b'].x, uv['b'].y, uv['c'].x, uv['c'].y) | conditional_block |
export_to_three.js.py | FaceMaterial());
//set transforms
model.position = myGeom.getPosition()
model.rotation = myGeom.getRotation()
model.scale = myGeom.getScale()
//set selection tags colours
myGeom.autoColor()
More details on this exporter and more js examples here:
https://github.com/orgicus/three.js
Have fun!
This script requires ... | ():
if not op: return
if op.GetType() != 5100:
print 'Selected Object is not an editable mesh'
return
unit = 0.001#for scale
fps = doc.GetFps()
bd = doc.GetRenderBaseDraw()
scr = bd.GetFrameScreen()
rd = doc.GetActiveRenderData()
name = op.GetName()
classna... | Export | identifier_name |
export_to_three.js.py | FaceMaterial());
//set transforms
model.position = myGeom.getPosition()
model.rotation = myGeom.getRotation()
model.scale = myGeom.getScale()
//set selection tags colours
myGeom.autoColor()
More details on this exporter and more js examples here:
https://github.com/orgicus/three.js
Have fun!
This script requires ... | def GetMesh(code):
# goto 0
doc.SetTime(c4d.BaseTime(0, fps))
c4d.DrawViews( c4d.DA_ONLY_ACTIVE_VIEW|c4d.DA_NO_THREAD|c4d.DA_NO_REDUCTION|c4d.DA_STATICBREAK )
c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
doc.SetTime(doc.GetTime())
c4d.EventAdd(c4d.EVENT_ANIMATE)
S... | if not op: return
if op.GetType() != 5100:
print 'Selected Object is not an editable mesh'
return
unit = 0.001#for scale
fps = doc.GetFps()
bd = doc.GetRenderBaseDraw()
scr = bd.GetFrameScreen()
rd = doc.GetActiveRenderData()
name = op.GetName()
classname = cle... | identifier_body |
export_to_three.js.py | .MeshFaceMaterial());
//set transforms
model.position = myGeom.getPosition()
model.rotation = myGeom.getRotation()
model.scale = myGeom.getScale()
//set selection tags colours
myGeom.autoColor()
More details on this exporter and more js examples here:
https://github.com/orgicus/three.js
Have fun!
This script requ... | sel = tag.GetSelection()
selName = clean(tag.GetName())
ids = sel.GetAll(op.GetPointCount())
indices = [i for i, e in enumerate(ids) if e != 0]
code += '\tscope.selections["'+selName+'"] = '+str(indices)+';\n'
code += '\n... | random_line_split | |
titan-nm.ts | import NetRegexes from '../../../../../resources/netregexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
export type Data = Ra... | },
outputStrings: {
breakGaolOn: {
en: 'Break Gaol on ${player}',
de: 'Zerstöre das Gefängnis von ${player}',
fr: 'Brisez la geôle sur ${player}',
ja: '${player}にジェイル',
cn: '石牢点${player}',
ko: '${player} 돌감옥 해제',
},
gaolOnYo... | if (matches.target !== data.me)
return output.breakGaolOn!({ player: data.ShortName(matches.target) });
return output.gaolOnYou!(); | random_line_split |
__openerp__.py | # -*- coding: utf-8 -*-
# Copyright© 2016 ICTSTUDIO <http://www.ictstudio.eu>
# Copyright 2016 ACSONE SA/NV (<http://acsone.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
{
'name': "MIS Builder Cost Center Filter", | 'version': '8.0.1.0.0',
'category': 'Reporting',
'summary': """
Add Cost Center filters to MIS Reports
""",
'author':
'ICTSTUDIO,'
'ACSONE SA/NV,'
'Odoo Community Association (OCA)',
'website': "http://www.ictstudio.eu",
'license': 'AGPL-3',
'depends': [
... | random_line_split | |
signals.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND ... |
## HANDLERS ##
def _create_bookmarks(sender, instance, *args, **kwargs):
create_bookmarks(instance)
def _delete_bookmarks(sender, instance, *args, **kwargs):
delete_bookmarks(instance)
## API ##
def manage_bookmarks(cls, enabled=True):
"""Connects handlers for bookmarks management.
This handle... | random_line_split | |
signals.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND ... | (sender, instance, *args, **kwargs):
delete_bookmarks(instance)
## API ##
def manage_bookmarks(cls, enabled=True):
"""Connects handlers for bookmarks management.
This handler could be used to automatically create a related bookmark list
on given model class instance creation. i.e.:
>> ma... | _delete_bookmarks | identifier_name |
signals.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND ... |
else:
post_save.disconnect(_create_bookmarks, cls, dispatch_uid=create_dispatch_uid)
pre_delete.disconnect(_delete_bookmarks, cls, dispatch_uid=delete_dispatch_uid)
## CONNECTIONS ##
manage_author_permissions(Menu)
manage_author_permissions(Link)
manage_author_permissions(Bookmark)
mana... | post_save.connect(_create_bookmarks, cls, dispatch_uid=create_dispatch_uid)
pre_delete.connect(_delete_bookmarks, cls, dispatch_uid=delete_dispatch_uid) | conditional_block |
signals.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND ... |
def _delete_bookmarks(sender, instance, *args, **kwargs):
delete_bookmarks(instance)
## API ##
def manage_bookmarks(cls, enabled=True):
"""Connects handlers for bookmarks management.
This handler could be used to automatically create a related bookmark list
on given model class instance creatio... | create_bookmarks(instance) | identifier_body |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations
// Generics bounds in Rust
// A trait which implements the print marker: `{:?}`.
use std::fmt::Debug;
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Rectangle {
fn area(&self) -> f64 { self.lengt... | let rectangle = Rectangle { length: 3.0, height: 4.0 };
let _triangle = Triangle { length: 3.0, height: 4.0 };
print_debug(&rectangle);
println!("Area: {}", area(&rectangle));
//print_debug(&_triangle);
//println!("Area: {}", area(&_triangle));
// ^ TODO: Try uncommenting these.
// | ... | identifier_body | |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations
// Generics bounds in Rust
// A trait which implements the print marker: `{:?}`.
use std::fmt::Debug;
trait HasArea {
fn area(&self) -> f64;
}
impl HasArea for Rectangle {
fn ar | self) -> f64 { self.length * self.height }
}
#[derive(Debug)]
struct Rectangle { length: f64, height: f64 }
#[allow(dead_code)]
struct Triangle { length: f64, height: f64 }
// The generic `T` must implement `Debug`. Regardless
// of type, this will work properly.
fn print_debug<T: Debug>(t: &T) {
println!("{:?}"... | ea(& | identifier_name |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations
// Generics bounds in Rust
// A trait which implements the print marker: `{:?}`.
use std::fmt::Debug;
trait HasArea {
fn area(&self) -> f64; | }
#[derive(Debug)]
struct Rectangle { length: f64, height: f64 }
#[allow(dead_code)]
struct Triangle { length: f64, height: f64 }
// The generic `T` must implement `Debug`. Regardless
// of type, this will work properly.
fn print_debug<T: Debug>(t: &T) {
println!("{:?}", t);
}
// `T` must implement `HasArea`. A... | }
impl HasArea for Rectangle {
fn area(&self) -> f64 { self.length * self.height } | random_line_split |
tokenize.py | #!/usr/bin/python -tt
#
# Copyright 2009-2010 Facebook, 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
#
# Unless required by applicab... | (self, stop_at_end=True):
tokens = []
while True:
token = self.getNextToken(stop_at_end)
if token == None:
break
tokens.append(token)
return tokens
def getNextToken(self, stop_at_end=True):
# If we don't currently have any tokens... | getTokens | identifier_name |
tokenize.py | #!/usr/bin/python -tt
#
# Copyright 2009-2010 Facebook, 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
#
# Unless required by applicab... | raise PartialTokenError(tokenizer.getPartialToken(), msg)
class QuoteState(State):
def __init__(self, quote_char, escape_chars = '\\'):
State.__init__(self)
self.quote = quote_char
self.escapeChars = escape_chars
def handleChar(self, tokenizer, char):
if char == self.q... | msg = 'unterminated escape sequence' | random_line_split |
tokenize.py | #!/usr/bin/python -tt
#
# Copyright 2009-2010 Facebook, 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
#
# Unless required by applicab... |
char = self.value[self.index]
self.index += 1
state = self.stateStack[-1]
state.handleChar(self, char)
def pushState(self, state):
self.stateStack.append(state)
def popState(self):
self.stateStack.pop()
if not self.stateStack:
raise Except... | if self.__processedEnd:
raise IndexError()
self.__processedEnd = True
state = self.stateStack[-1]
state.handleEnd(self)
return | conditional_block |
tokenize.py | #!/usr/bin/python -tt
#
# Copyright 2009-2010 Facebook, 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
#
# Unless required by applicab... |
def handleEnd(self, tokenizer):
msg = 'unterminated quote'
raise PartialTokenError(tokenizer.getPartialToken(), msg)
class NormalState(State):
def __init__(self):
State.__init__(self)
self.quoteChars = '"\''
self.escapeChars = '\\'
self.delimChars = ' \t\n'
... | if char == self.quote:
tokenizer.popState()
elif char in self.escapeChars:
tokenizer.pushState(EscapeState())
else:
tokenizer.addToToken(char) | identifier_body |
gpu_types.rs | pub enum BoxShadowStretchMode {
Stretch = 0,
Simple = 1,
}
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "capture", derive(Serialize))]
#[cfg_attr(feature = "replay", derive(Deserialize))]
pub enum BlurDirection {
Horizontal = 0,
Vertical,
}
#[derive(Debug)]
#[repr(C)]
#[cfg_attr(fea... | pub texture_layer: f32,
pub user_data: [f32; 3], | random_line_split | |
gpu_types.rs | replay", derive(Deserialize))]
#[repr(C)]
pub struct ClipMaskInstance {
pub render_task_address: RenderTaskAddress,
pub scroll_node_data_index: ClipScrollNodeIndex,
pub segment: i32,
pub clip_data_address: GpuCacheAddress,
pub resource_address: GpuCacheAddress,
}
/// A border corner dot or dash dra... | {
request.push([
top_left.x,
top_left.y,
top_right.x,
top_right.y,
]);
request.push([
bottom_left.x,
bottom_left.y,
bottom_right.x,
bottom_right.y,
... | conditional_block | |
gpu_types.rs | the texture width.
const _SEGMENT_GUARD: usize = (1 << SEGMENT_BITS) * VECS_PER_SEGMENT - MAX_VERTEX_TEXTURE_WIDTH;
const EDGE_FLAG_BITS: usize = 4;
const BRUSH_FLAG_BITS: usize = 4;
const CLIP_SCROLL_INDEX_BITS: usize = INT_BITS - EDGE_FLAG_BITS - BRUSH_FLAG_BITS;
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct ... | {
next: i32,
}
impl ZBufferIdGenerator {
pub fn new() -> Self {
ZBufferIdGenerator {
next: 0
}
}
pub fn next(&mut self) -> ZBufferId {
let id = ZBufferId(self.next);
self.next += 1;
id
}
}
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "cap... | ZBufferIdGenerator | identifier_name |
main.rs | extern crate config;
extern crate rand;
extern crate clap;
extern crate nix;
extern crate sys_info;
extern crate anyhow;
extern crate flate2;
extern crate tar;
#[macro_use]
extern crate lazy_static;
#[cfg(target_os = "linux")]
extern crate gtk;
#[cfg(target_os = "linux")]
extern crate libappindicator;
#[cfg(target_os... | else {
handle_file_upload(config, &path);
}
}
}
fn handle_file_upload(config: DropConfig, file: &Path) {
if !file.exists() {
println!("File does not exist! ({:?})", file);
std::process::exit(1);
} else {
let filename = util::generate_filename(&config, file.file_name().map(|s| util::from_os... | {
let archive = archive_directory(&path);
handle_file_upload(config, &archive.as_path())
} | conditional_block |
main.rs | extern crate config;
extern crate rand;
extern crate clap;
extern crate nix;
extern crate sys_info;
extern crate anyhow;
extern crate flate2;
extern crate tar;
#[macro_use]
extern crate lazy_static;
#[cfg(target_os = "linux")]
extern crate gtk;
#[cfg(target_os = "linux")]
extern crate libappindicator;
#[cfg(target_os... |
fn capture_screencast(config: &DropConfig) -> PathBuf {
let out_file_name = util::generate_filename(config, None, Some(config.video_format.clone()));
let out_file = Path::new(&config.dir).join(out_file_name);
capture::screencast(out_file.as_path(), config);
out_file
}
fn handle_file(config: DropConfig, match... | {
let out_file_name = util::generate_filename(config, None, Some("png".to_string()));
let out_file = Path::new(&config.dir).join(out_file_name);
capture::screenshot(out_file.as_path(), config);
out_file
} | identifier_body |
main.rs | extern crate config;
extern crate rand;
extern crate clap;
extern crate nix;
extern crate sys_info;
extern crate anyhow;
extern crate flate2;
extern crate tar;
#[macro_use]
extern crate lazy_static;
#[cfg(target_os = "linux")]
extern crate gtk;
#[cfg(target_os = "linux")]
extern crate libappindicator;
#[cfg(target_os... | (config: &DropConfig, file: &Path, filename: Option<String>) -> String {
if config.local || config.aws_bucket.is_none() || config.aws_key.is_none() || config.aws_secret.is_none() {
format!("file://{}", util::path_to_str(file.canonicalize().unwrap().as_path()))
} else {
aws::upload_file_to_s3(&config, &file,... | handle_upload_and_produce_url | identifier_name |
main.rs | extern crate config;
extern crate rand;
extern crate clap;
extern crate nix;
extern crate sys_info;
extern crate anyhow;
extern crate flate2;
extern crate tar;
#[macro_use]
extern crate lazy_static;
#[cfg(target_os = "linux")]
extern crate gtk;
#[cfg(target_os = "linux")]
extern crate libappindicator;
#[cfg(target_os... | let url = handle_upload_and_produce_url(&config, &file, Some(filename.clone()));
clip::copy_to_clipboard(url.clone());
if config.notifications {
notify::send_upload_notification(filename, &config);
}
println!("{}", url);
}
}
fn archive_directory(file: &Path) -> PathBuf {
let archive_path ... | } else {
let filename = util::generate_filename(&config, file.file_name().map(|s| util::from_os_str(s)), None); | random_line_split |
mod.rs | pub mod g2d;
pub mod g3d;
use time;
pub trait Drawable {
fn draw(&self);
}
pub struct | {
pub width: u32,
pub height: u32,
pub refresh_rate: u16,
pub bits_per_pixel: u16
}
pub struct Monitor {
pub virtual_y: u32,
pub virtual_x: u32,
pub name: String,
pub display_modes: Vec<DisplayMode>
}
pub struct Graphics {
pub display_mode: DisplayMode,
pub frame_id: u32,
... | DisplayMode | identifier_name |
mod.rs | pub mod g2d;
pub mod g3d;
use time;
pub trait Drawable {
fn draw(&self);
}
pub struct DisplayMode {
pub width: u32,
pub height: u32,
pub refresh_rate: u16,
pub bits_per_pixel: u16
}
pub struct Monitor {
pub virtual_y: u32,
pub virtual_x: u32, | }
pub struct Graphics {
pub display_mode: DisplayMode,
pub frame_id: u32,
pub delta_time: time::Duration,
pub fps: u16,
pub monitors: Vec<Monitor>,
pub should_close: bool
}
impl Graphics {
pub fn new(width: u32, height: u32, title: &str) -> Self {
Graphics {
display_mod... | pub name: String,
pub display_modes: Vec<DisplayMode> | random_line_split |
enum-null-pointer-opt.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | assert_eq!(size_of::<Foo>(), size_of::<Option<Foo>>());
assert_eq!(size_of::<Bar>(), size_of::<Option<Bar>>());
// and tuples
assert_eq!(size_of::<(u8, Box<isize>)>(), size_of::<Option<(u8, Box<isize>)>>());
// and fixed-size arrays
assert_eq!(size_of::<[Box<isize>; 1]>(), size_of::<Option<[Box<... | struct Bar(Box<isize>);
// Should apply through structs | random_line_split |
enum-null-pointer-opt.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
_a: Box<isize>
}
struct Bar(Box<isize>);
// Should apply through structs
assert_eq!(size_of::<Foo>(), size_of::<Option<Foo>>());
assert_eq!(size_of::<Bar>(), size_of::<Option<Bar>>());
// and tuples
assert_eq!(size_of::<(u8, Box<isize>)>(), size_of::<Option<(u8, Box<isize>)>>());... | Foo | identifier_name |
ParsedMessagePart.ts | import { utf8Length, utf8Substring } from '@d-fischer/shared-utils';
import type { CheermoteDisplayInfo } from './BaseCheermoteList';
import type { ChatEmote } from './ChatEmote';
export interface ParsedMessageTextPart {
type: 'text';
position: number;
length: number;
text: string;
}
export interface ParsedMessag... |
return result;
}
| {
result.push({
type: 'text',
position: currentPosition,
length: messageLength - currentPosition,
text: utf8Substring(message, currentPosition)
});
} | conditional_block |
ParsedMessagePart.ts | import { utf8Length, utf8Substring } from '@d-fischer/shared-utils';
import type { CheermoteDisplayInfo } from './BaseCheermoteList';
import type { ChatEmote } from './ChatEmote';
export interface ParsedMessageTextPart {
type: 'text';
position: number;
length: number;
text: string;
}
export interface ParsedMessag... | (message: string, otherPositions: ParsedMessagePart[]): ParsedMessagePart[] {
const messageLength = utf8Length(message);
if (!otherPositions.length) {
return [
{
type: 'text',
position: 0,
length: messageLength,
text: message
}
];
}
const result: ParsedMessagePart[] = [];
let currentPosi... | fillTextPositions | identifier_name |
ParsedMessagePart.ts | import { utf8Length, utf8Substring } from '@d-fischer/shared-utils';
import type { CheermoteDisplayInfo } from './BaseCheermoteList';
import type { ChatEmote } from './ChatEmote';
export interface ParsedMessageTextPart {
type: 'text';
position: number;
length: number;
text: string;
}
export interface ParsedMessag... | {
type: 'text',
position: 0,
length: messageLength,
text: message
}
];
}
const result: ParsedMessagePart[] = [];
let currentPosition = 0;
for (const token of otherPositions) {
if (token.position > currentPosition) {
result.push({
type: 'text',
position: currentPosition,
le... | export function fillTextPositions(message: string, otherPositions: ParsedMessagePart[]): ParsedMessagePart[] {
const messageLength = utf8Length(message);
if (!otherPositions.length) {
return [ | random_line_split |
ParsedMessagePart.ts | import { utf8Length, utf8Substring } from '@d-fischer/shared-utils';
import type { CheermoteDisplayInfo } from './BaseCheermoteList';
import type { ChatEmote } from './ChatEmote';
export interface ParsedMessageTextPart {
type: 'text';
position: number;
length: number;
text: string;
}
export interface ParsedMessag... | position: currentPosition,
length: token.position - currentPosition,
text: utf8Substring(message, currentPosition, token.position)
});
}
result.push(token);
currentPosition = token.position + token.length;
}
if (currentPosition < messageLength) {
result.push({
type: 'text',
position: cur... | {
const messageLength = utf8Length(message);
if (!otherPositions.length) {
return [
{
type: 'text',
position: 0,
length: messageLength,
text: message
}
];
}
const result: ParsedMessagePart[] = [];
let currentPosition = 0;
for (const token of otherPositions) {
if (token.position > cur... | identifier_body |
views.py | import datetime
import time
import calendar
from django.core.urlresolvers import reverse
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render, redirect
from rolepermissi... | (request):
if request.method == 'POST':
event = McEvent(owner=request.user.mcuser)
form = McEventForm(request.POST, instance=event)
if (form.is_valid()):
form.save()
return redirect(reverse('mccalendar:event_detail', args=[event.id]))
else:
form = McEventForm(request.POST, instance=e... | create_event | identifier_name |
views.py | import datetime
import time
import calendar
from django.core.urlresolvers import reverse
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render, redirect
from rolepermissi... | return render(request, 'mccalendar/month.html', context)
@login_required
def day(request, year=None, month=None, day=None):
year = int(year) if year else time.localtime()[0]
month = int(month) if month else time.localtime()[1]
events = McEvent.objects.filter(
start_date__lte=datetime.date(year, month, d... | 'month_name': month_names[month-1],
'month_days': lst,
} | random_line_split |
views.py | import datetime
import time
import calendar
from django.core.urlresolvers import reverse
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render, redirect
from rolepermissi... | cal.setfirstweekday(calendar.SUNDAY)
month_days = cal.itermonthdays(year, month)
events = []
lst=[[]]
week = 0
for day in month_days:
entries = current = False
if day:
events = McEvent.objects.filter(
start_date__lte=datetime.date(year, month, day),
end_date__gte=datetime... | year = int(year) if year else time.localtime()[0]
month = int(month) if month else time.localtime()[1]
#apply next/previous if applicable
if change in ('next', 'prev'):
if change=='next':
month = month+1
if month == 13:
month = 1
year += 1
elif change=='prev':
month = mo... | identifier_body |
views.py | import datetime
import time
import calendar
from django.core.urlresolvers import reverse
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render, redirect
from rolepermissi... |
context = {
'form':form,
'form_url': reverse('mccalendar:create_event')
}
return render(request, 'mccalendar/edit_event.html', context)
@login_required
@has_role_decorator('staff')
def edit_event(request, event_id=None):
try:
event = McEvent.objects.get(id=event_id)
except McEvent.DoesNotExist:
... | form = McEventForm() | conditional_block |
gcp_spanner_instance_info.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... |
def collection(module):
return "https://spanner.googleapis.com/v1/projects/{project}/instances".format(**module.params)
def fetch_list(module, link):
auth = GcpSession(module, 'spanner')
return auth.list(link, return_if_object, array_name='instances')
def return_if_object(module, response):
# If ... | module = GcpModule(argument_spec=dict())
if module._name == 'gcp_spanner_instance_facts':
module.deprecate("The 'gcp_spanner_instance_facts' module has been renamed to 'gcp_spanner_instance_info'", version='2.13')
if not module.params['scopes']:
module.params['scopes'] = ['https://www.googleap... | identifier_body |
gcp_spanner_instance_info.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | return result
if __name__ == "__main__":
main() | random_line_split | |
gcp_spanner_instance_info.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | ():
module = GcpModule(argument_spec=dict())
if module._name == 'gcp_spanner_instance_facts':
module.deprecate("The 'gcp_spanner_instance_facts' module has been renamed to 'gcp_spanner_instance_info'", version='2.13')
if not module.params['scopes']:
module.params['scopes'] = ['https://www.... | main | identifier_name |
gcp_spanner_instance_info.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... |
return_value = {'resources': fetch_list(module, collection(module))}
module.exit_json(**return_value)
def collection(module):
return "https://spanner.googleapis.com/v1/projects/{project}/instances".format(**module.params)
def fetch_list(module, link):
auth = GcpSession(module, 'spanner')
retur... | module.params['scopes'] = ['https://www.googleapis.com/auth/spanner.admin'] | conditional_block |
gulpfile.js | var gulp = require('gulp');
var plumber = require('gulp-plumber');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
gulp.task('scripts', function() {
return gulp.src('public/js/scripts.js')
.... | preserveComments: 'license'
}))
.pipe(rename({extname: '.min.js'}))
.pipe(gulp.dest('public/js'));
});
gulp.task('styles', function() {
return gulp.src('scss/styles.scss')
.pipe(plumber(plumber({
errorHandler: function (err) {
consol... | }
})))
.pipe(uglify({
| random_line_split |
security_group_view_result.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | """
_attribute_map = {
'network_interfaces': {'key': 'networkInterfaces', 'type': '[SecurityGroupNetworkInterface]'},
}
def __init__(self, network_interfaces=None):
super(SecurityGroupViewResult, self).__init__()
self.network_interfaces = network_interfaces | list[~azure.mgmt.network.v2017_09_01.models.SecurityGroupNetworkInterface] | random_line_split |
security_group_view_result.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | """The information about security rules applied to the specified VM.
:param network_interfaces: List of network interfaces on the specified VM.
:type network_interfaces:
list[~azure.mgmt.network.v2017_09_01.models.SecurityGroupNetworkInterface]
"""
_attribute_map = {
'network_interfaces':... | identifier_body | |
security_group_view_result.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | (self, network_interfaces=None):
super(SecurityGroupViewResult, self).__init__()
self.network_interfaces = network_interfaces
| __init__ | identifier_name |
optimizer.rs | use std::collections::BTreeMap;
use crate::structs::Op::*;
use crate::structs::{Op, OpStream};
impl OpStream {
pub fn optimize(&mut self) {
let mut i = 0;
while i < self.ops.len() {
match self.ops[i..] {
[Add(a), Add(b), ..] => {
self.ops[i] = Add(a.... | map.remove(&0).unwrap_or(0),
map.into_iter().collect(),
))
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use crate::structs::Op::*;
use crate::structs::OpStream;
#[test]
fn test_opstream_optimize() {
let mut opstream =... | {
let mut map = BTreeMap::<isize, u8>::new();
let mut rel_index = 0;
for op in &self.ops {
match *op {
Add(x) => {
map.insert(rel_index, map.get(&rel_index).unwrap_or(&0).wrapping_add(x));
}
Mov(x) => {
... | identifier_body |
optimizer.rs | use std::collections::BTreeMap;
use crate::structs::Op::*;
use crate::structs::{Op, OpStream};
impl OpStream {
pub fn optimize(&mut self) {
let mut i = 0;
while i < self.ops.len() {
match self.ops[i..] {
[Add(a), Add(b), ..] => {
self.ops[i] = Add(a.... | () {
let mut opstream = OpStream {
ops: vec![Loop(OpStream {
ops: vec![Add(0x01), Mov(3), Add(0xff), Mov(-3)],
})],
};
opstream.optimize();
assert_eq!(
opstream,
OpStream {
ops: vec![Transfer(1, vec![(3, 255... | test_opstream_optimize_transfer | identifier_name |
optimizer.rs | use std::collections::BTreeMap;
use crate::structs::Op::*;
use crate::structs::{Op, OpStream};
impl OpStream {
pub fn optimize(&mut self) {
let mut i = 0;
while i < self.ops.len() {
match self.ops[i..] {
[Add(a), Add(b), ..] => {
self.ops[i] = Add(a.... |
#[test]
fn test_opstream_optimize() {
let mut opstream = OpStream {
ops: vec![
Mov(1),
Mov(1),
Add(0x01),
Add(0xff),
Add(0xff),
Mov(1),
Mov(-1),
Loop(OpStream {
... |
#[cfg(test)]
mod tests {
use crate::structs::Op::*;
use crate::structs::OpStream; | random_line_split |
Query.js | Ext.define('Planche.lib.Query', {
constructor : function(query){
Ext.apply(this, query);
},
getPrevRecordSetSQL : function(){
this.start -= this.end;
if(this.start < 0) this.start = 0;
return this.getSQL();
},
getNextRecordSetSQL : function(){
this.start += this.end;
return... |
return this.raw;
},
getTokens : function(){
return this.tokens;
},
isSelectQuery : function(){
return this.selectQuery;
},
isDelimiter : function(){
return this.delimiter;
},
hasNext : function(){
return this.raw.length > this.end ? true : false;
},
setRecords : fun... | return this.raw;
}
},
getRawSQL : function(){
| random_line_split |
Query.js | Ext.define('Planche.lib.Query', {
constructor : function(query){
Ext.apply(this, query);
},
getPrevRecordSetSQL : function(){
this.start -= this.end;
if(this.start < 0) this.start = 0;
return this.getSQL();
},
getNextRecordSetSQL : function(){
this.start += this.end;
return... |
else {
return this.raw;
}
},
getRawSQL : function(){
return this.raw;
},
getTokens : function(){
return this.tokens;
},
isSelectQuery : function(){
return this.selectQuery;
},
isDelimiter : function(){
return this.delimiter;
},
hasNext : function(){
re... | {
return this.sql + ' LIMIT ' + this.start + ", " + this.end;
} | conditional_block |
http_server.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 foxbox_taxonomy::manager::*;
use hyper::net::{ NetworkListener };
use iron::{ AfterMiddleware, Chain, Handler,
HttpServerFactory, Iron, IronResult, Request,
Response, ServerFactory };
use iron_cors::CORS;
use iron::error::{ IronError };
use iron::method::Method;
use iron::status::Status;
us... | random_line_split | |
http_server.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 foxbox_taxonomy::manager::*;
use hyper::net::{ NetworkListener };
use iron::{ AfterMiddleware, Chain, Handler,... | // Taxonomy router paths. Keep in sync with taxonomy_router.rs
(vec![Method::Get, Method::Post], "api/v1/services".to_owned()),
(vec![Method::Post, Method::Delete], "api/v1/services/tags".to_owned()),
(vec![Method::Get, Method::Post], "api/v1/channels".to_owned()),
... | {
let taxonomy_chain = taxonomy_router::create(self.controller.clone(),
adapter_api);
let users_manager = self.controller.get_users_manager();
let mut mount = Mount::new();
mount.mount("/", static_router::create(users_manager.clone()... | identifier_body |
http_server.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 foxbox_taxonomy::manager::*;
use hyper::net::{ NetworkListener };
use iron::{ AfterMiddleware, Chain, Handler,... |
}
}
fn start_server<TListener, T>(addrs: Vec<SocketAddr>, chain: Chain, factory: T)
where TListener: NetworkListener + Send + 'static,
T: ServerFactory<TListener> + Send + 'static {
thread::Builder::new().name("HttpServer".to_owned())
.spawn(move || {
Iron::new... | {
start_server(addrs, chain, HttpServerFactory {});
} | conditional_block |
http_server.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 foxbox_taxonomy::manager::*;
use hyper::net::{ NetworkListener };
use iron::{ AfterMiddleware, Chain, Handler,... | (&mut self, adapter_api: &Arc<AdapterManager>) {
let taxonomy_chain = taxonomy_router::create(self.controller.clone(),
adapter_api);
let users_manager = self.controller.get_users_manager();
let mut mount = Mount::new();
mount.mount("... | start | identifier_name |
join.js | var _ = require('lodash');
// var debug = require('debug')('mgenerate:array');
/**
* $join operator takes an array and an `sep` separator string and concats
* the elements of the array (cast to string) separated by `sep`.
* The default `sep` is the empty string ''.
*
* @example Returns the string "foo-bar-baz".
... | else {
replacement = '$missing';
}
return evaluator(replacement, true);
};
| {
replacement = _.join(options.array, options.sep);
} | conditional_block |
join.js | var _ = require('lodash');
// var debug = require('debug')('mgenerate:array');
/**
* $join operator takes an array and an `sep` separator string and concats
* the elements of the array (cast to string) separated by `sep`.
* The default `sep` is the empty string ''.
*
* @example Returns the string "foo-bar-baz".
... | } else {
replacement = '$missing';
}
return evaluator(replacement, true);
}; | sep: ''
})
);
if (_.isArray(options.array) && _.isString(options.sep)) {
replacement = _.join(options.array, options.sep); | random_line_split |
phpcomposer.py |
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# W... | "type": "vcs",
"url": "https://github.com/Seldaek/monolog"
},
{
"type": "pear",
"url": "https://pear2.php.net"
},
{
"type": "package",
"package": {
"name": "smarty/smarty",
"version": ... | "verify_peer": "true"
}
}
},
{ | random_line_split |
phpcomposer.py |
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# W... |
else:
# use the bare repr
package.asserted_licenses.append(models.AssertedLicense(license=repr(licenses)))
return package
def author_mapper(authors_content, package):
"""
Update package authors and return package.
https://getcomposer.org/doc/04-schema.md#authors
"""
auth... | package.asserted_licenses.append(models.AssertedLicense(license=repr(lic))) | conditional_block |
phpcomposer.py |
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# W... | (authors_content, package):
"""
Update package authors and return package.
https://getcomposer.org/doc/04-schema.md#authors
"""
authors = []
for name, email, url in parse_person(authors_content):
authors.append(models.Party(type=models.party_person, name=name, email=email, url=url))
... | author_mapper | identifier_name |
phpcomposer.py |
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# W... |
def vendor_mapper(package):
"""
Vender is part of name element.
https://getcomposer.org/doc/04-schema.md#name
"""
name = package.name
if name and '/' in name:
vendors = name.split('/')
if vendors[0]:
package.vendors = [models.Party(name=vendors[0])]
return pack... | """
Update support and bug tracking url.
https://getcomposer.org/doc/04-schema.md#support
"""
package.support_contacts = [support.get('email')]
package.bug_tracking_url = support.get('issues')
package.code_view_url = support.get('source')
return package | identifier_body |
mn_wizard_step4_controller.js | (function () {
"use strict";
angular
.module('mnWizard')
.controller('mnWizardStep4Controller', mnWizardStep4Controller);
function mnWizardStep4Controller($scope, $state, mnWizardStep4Service, pools, mnPromiseHelper) {
var vm = this;
vm.isEnterprise = pools.isEnterprise;
vm.sendStat... | () {
if (pools.isEnterprise) {
vm.form.agree.$setValidity('required', !!vm.register.agree);
}
if (vm.form.$invalid || vm.viewLoading) {
return;
}
vm.register.email && mnWizardStep4Service.postEmail(vm.register);
var promise = mnWizardStep4Service.pos... | onSubmit | identifier_name |
mn_wizard_step4_controller.js | (function () {
"use strict";
angular
.module('mnWizard')
.controller('mnWizardStep4Controller', mnWizardStep4Controller);
function mnWizardStep4Controller($scope, $state, mnWizardStep4Service, pools, mnPromiseHelper) | return;
}
vm.register.email && mnWizardStep4Service.postEmail(vm.register);
var promise = mnWizardStep4Service.postStats({sendStats: vm.sendStats});
mnPromiseHelper(vm, promise)
.showErrorsSensitiveSpinner()
.catchErrors()
.getPromise()
... | {
var vm = this;
vm.isEnterprise = pools.isEnterprise;
vm.sendStats = true;
vm.onSubmit = onSubmit;
vm.register = {
email: '',
firstname: '',
lastname: '',
company: '',
version: (pools.implementationVersion || 'unknown')
};
function on... | identifier_body |
mn_wizard_step4_controller.js | (function () {
"use strict";
angular
.module('mnWizard')
.controller('mnWizardStep4Controller', mnWizardStep4Controller);
function mnWizardStep4Controller($scope, $state, mnWizardStep4Service, pools, mnPromiseHelper) {
var vm = this;
vm.isEnterprise = pools.isEnterprise; | vm.onSubmit = onSubmit;
vm.register = {
email: '',
firstname: '',
lastname: '',
company: '',
version: (pools.implementationVersion || 'unknown')
};
function onSubmit() {
if (pools.isEnterprise) {
vm.form.agree.$setValidity('required', !... | vm.sendStats = true; | random_line_split |
mn_wizard_step4_controller.js | (function () {
"use strict";
angular
.module('mnWizard')
.controller('mnWizardStep4Controller', mnWizardStep4Controller);
function mnWizardStep4Controller($scope, $state, mnWizardStep4Service, pools, mnPromiseHelper) {
var vm = this;
vm.isEnterprise = pools.isEnterprise;
vm.sendStat... |
vm.register.email && mnWizardStep4Service.postEmail(vm.register);
var promise = mnWizardStep4Service.postStats({sendStats: vm.sendStats});
mnPromiseHelper(vm, promise)
.showErrorsSensitiveSpinner()
.catchErrors()
.getPromise()
.then(function () {
... | {
return;
} | conditional_block |
test_monotone.py | """
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reas... | (clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}... | _fake_clock_call | identifier_name |
test_monotone.py | """
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reas... |
else:
expected_resolution = 1.0
info = get_clock_info("monotonic")
resolution, info.resolution = info.resolution, None
assert info == expected_info
assert resolution - expected_resolution == pytest.approx(0.0)
assert len(calls) == 1
assert calls[0]... | expected_resolution = 1e-09 | conditional_block |
test_monotone.py | """
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reas... |
return _apply_timespec
class TestSimpleNamespace(object):
"""
Tests for L{_SimpleNamespace}.
"""
def test_init(self):
"""
The initializer updates the instance's C{__dict__} with its
keyword arguments.
"""
namespace = _api._SimpleNamespace(x=1)
ass... | calls = []
def _fake_clock_call(clock_id, timespec):
calls.append((clock_id, timespec))
timespec[0] = goal_timespec[0]
return 0
monkeypatch.setattr(_api, name, _fake_clock_call)
return calls | identifier_body |
test_monotone.py | """
Tests for L{monotone}.
"""
from hypothesis import given, strategies as st
import errno
from monotone import get_clock_info, monotonic
from monotone import _api, _bindings
import os
import platform
import pytest
needs_posix = pytest.mark.skipif(
os.name == "posix" and platform.system() == "Darwin",
reas... | # nanoseconds (offset by a billion) iff the resolution is accurate
# to the nanosecond.
expected = float(clock_gettime_spec['tv_sec']) + (
clock_gettime_spec['tv_nsec'] * 1e-09)
result = monotonic()
assert result - expected == pytest.approx(0.0)
assert clock_gettime_calls[0][0] == _bi... | # we a float, representing the current seconds plus the | random_line_split |
write-letter.ts | import { sample } from '../../sample';
import { ExerciseTypes } from '../exercises';
import { capitalizeFirstLetter } from '../word/helpers';
import { AbstractExerciseGroup } from './abstract-exercise-group.interface';
export class WriteLetter extends AbstractExerciseGroup {
protected | () {
if (!this.newLetter) {
return [];
}
const letter = this.newLetter.toLowerCase();
const version = sample(['a', 'b'], 1);
return [
this.createExercise(ExerciseTypes.InfoScreenWithSounds, {
type: 'ExplanationText',
text: 'Schreiben Sie den Buchstaben.',
sound:... | generateExercises | identifier_name |
write-letter.ts | import { sample } from '../../sample';
import { ExerciseTypes } from '../exercises';
import { capitalizeFirstLetter } from '../word/helpers';
import { AbstractExerciseGroup } from './abstract-exercise-group.interface';
export class WriteLetter extends AbstractExerciseGroup {
protected generateExercises() {
if (!... | type: 'WriteLetter',
letter: capitalizeFirstLetter(letter)
}),
this.createExercise(ExerciseTypes.Canvas, {
type: 'WriteLetter',
letter: capitalizeFirstLetter(letter)
}),
this.createExercise(ExerciseTypes.Canvas, {
... | : [
this.createExercise(ExerciseTypes.Canvas, { | random_line_split |
write-letter.ts | import { sample } from '../../sample';
import { ExerciseTypes } from '../exercises';
import { capitalizeFirstLetter } from '../word/helpers';
import { AbstractExerciseGroup } from './abstract-exercise-group.interface';
export class WriteLetter extends AbstractExerciseGroup {
protected generateExercises() | : [
this.createExercise(ExerciseTypes.Canvas, {
type: 'WriteLetter',
letter: capitalizeFirstLetter(letter)
}),
this.createExercise(ExerciseTypes.Canvas, {
type: 'WriteLetter',
letter: capitalizeFirstLetter(letter)
... | {
if (!this.newLetter) {
return [];
}
const letter = this.newLetter.toLowerCase();
const version = sample(['a', 'b'], 1);
return [
this.createExercise(ExerciseTypes.InfoScreenWithSounds, {
type: 'ExplanationText',
text: 'Schreiben Sie den Buchstaben.',
sound: `e... | identifier_body |
write-letter.ts | import { sample } from '../../sample';
import { ExerciseTypes } from '../exercises';
import { capitalizeFirstLetter } from '../word/helpers';
import { AbstractExerciseGroup } from './abstract-exercise-group.interface';
export class WriteLetter extends AbstractExerciseGroup {
protected generateExercises() {
if (!... |
const letter = this.newLetter.toLowerCase();
const version = sample(['a', 'b'], 1);
return [
this.createExercise(ExerciseTypes.InfoScreenWithSounds, {
type: 'ExplanationText',
text: 'Schreiben Sie den Buchstaben.',
sound: `exercises_schreiben_sie_den_buchstaben_${version}`
... | {
return [];
} | conditional_block |
raii_mutex_table.rs | use parking_lot::Mutex;
use std::cmp::Eq;
use std::collections::HashSet;
use std::hash::Hash;
pub struct | <K> {
map: Mutex<HashSet<K>>,
}
pub struct RAIIMutexGuard<'a, K>
where
K: Eq + Clone + Hash,
{
parent: &'a RAIIMutexTable<K>,
key: K,
}
impl<K> RAIIMutexTable<K>
where
K: Eq + Clone + Hash,
{
pub fn new() -> RAIIMutexTable<K> {
RAIIMutexTable {
map: Mutex::new(HashSet::new(... | RAIIMutexTable | identifier_name |
raii_mutex_table.rs | use parking_lot::Mutex;
use std::cmp::Eq;
use std::collections::HashSet;
use std::hash::Hash;
pub struct RAIIMutexTable<K> {
map: Mutex<HashSet<K>>,
}
pub struct RAIIMutexGuard<'a, K>
where
K: Eq + Clone + Hash,
{
parent: &'a RAIIMutexTable<K>,
key: K,
}
impl<K> RAIIMutexTable<K>
where
K: Eq + Cl... |
}
}
pub fn unlock(&self, key: &K) {
let mut map_guard = self.map.lock();
debug_assert!(map_guard.contains(key));
map_guard.remove(key);
}
}
impl<'a, K> Drop for RAIIMutexGuard<'a, K>
where
K: Eq + Clone + Hash,
{
fn drop(&mut self) {
self.parent.unlock(&sel... | {
map_guard.insert(k.clone());
return RAIIMutexGuard {
parent: self,
key: k,
};
} | conditional_block |
raii_mutex_table.rs | use parking_lot::Mutex;
use std::cmp::Eq;
use std::collections::HashSet;
use std::hash::Hash;
pub struct RAIIMutexTable<K> {
map: Mutex<HashSet<K>>,
}
pub struct RAIIMutexGuard<'a, K>
where
K: Eq + Clone + Hash,
{
parent: &'a RAIIMutexTable<K>,
key: K,
}
impl<K> RAIIMutexTable<K>
where
K: Eq + Cl... | where
K: Eq + Clone + Hash,
{
fn drop(&mut self) {
self.parent.unlock(&self.key)
}
} | }
impl<'a, K> Drop for RAIIMutexGuard<'a, K> | random_line_split |
raii_mutex_table.rs | use parking_lot::Mutex;
use std::cmp::Eq;
use std::collections::HashSet;
use std::hash::Hash;
pub struct RAIIMutexTable<K> {
map: Mutex<HashSet<K>>,
}
pub struct RAIIMutexGuard<'a, K>
where
K: Eq + Clone + Hash,
{
parent: &'a RAIIMutexTable<K>,
key: K,
}
impl<K> RAIIMutexTable<K>
where
K: Eq + Cl... |
}
| {
self.parent.unlock(&self.key)
} | identifier_body |
plotit.py | import numpy as np
import os
import sys
import os.path as op
import matplotlib as mpl
import mpl.pyplot as plt
import palettable.colorbrewer as pal
from datetime import datetime
from cycler import cycler
#plt.rc('axes', prop_cycle=cycler('color', pal.qualitative.Dark2_8.mpl_colors)+
# cycler('marker',['D','o','v','... |
reg = ["Register"]
ksorder += reg
#KS complete
ko=[prec[0]+" "+ rd for rd in ksorder]+[prec[1]+" "+ rd for rd in ksorder]
fig, (ax1,ax2) = plt.subplots(1,2, figsize=(14,8))
plt.suptitle("KS",fontsize='large', fontweight="bold")
ax1.loglog(KSall[:,0],KSall[:,1], KSall[:,0], KSall[:,2], KSall[:,0], KSall[:,3])
ax1.hol... | plotfile = op.join(thispath,"heatComplete.pdf")
ax2.set_xlim([heat[0,0],heat[-1,0]])
plt.savefig(plotfile, bbox_inches='tight') | random_line_split |
plotit.py | import numpy as np
import os
import sys
import os.path as op
import matplotlib as mpl
import mpl.pyplot as plt
import palettable.colorbrewer as pal
from datetime import datetime
from cycler import cycler
#plt.rc('axes', prop_cycle=cycler('color', pal.qualitative.Dark2_8.mpl_colors)+
# cycler('marker',['D','o','v','... |
ax2.semilogx(mpi[:,0],mpi[:,-2],mpi[:,0],mpi[:,-1])
ax1.hold(True)
ax1.legend(mpiLabels, loc='upper left', fontsize='medium')
ax2.legend(["Classic", "Shared"], loc='upper left', fontsize='medium')
ax1.grid(alpha=0.5)
ax2.grid(alpha=0.5)
ax1.set_ylabel(ylbl)
ax2.set_ylabel("Speedup vs MPI")
ax1.set_xlabel(xlbl... | ax1.loglog(mpi[:,0],mpi[:,i+1])
ax1.hold(True) | conditional_block |
test_xem.py | #!/usr/bin/env python2.7
# Author: echel0n <echel0n@sickrage.ca>
# URL: https://sickrage.ca
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of t... | (self):
"""
Populates the showList with shows from the database
"""
for s in [s['doc'] for s in sickrage.app.main_db.db.all('tv_shows', with_doc=True)]:
try:
curShow = TVShow(int(s["indexer"]), int(s["indexer_id"]))
curShow.saveToDB()
... | loadShowsFromDB | identifier_name |
test_xem.py | #!/usr/bin/env python2.7
# Author: echel0n <echel0n@sickrage.ca>
# URL: https://sickrage.ca
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of t... |
if __name__ == "__main__":
print "=================="
print "STARTING - XEM SCENE NUMBERING TESTS"
print "=================="
print "######################################################################"
unittest.main()
| name = "Game.of.Thrones.S03.720p.HDTV.x264-CtrlHD"
release = "Game of Thrones"
# m = re.match('(?P<ep_ab_num>(?>\d{1,3})(?![ip])).+', name)
escaped_name = re.sub('\\\\[\\s.-]', '\W+', re.escape(release))
curRegex = '^' + escaped_name + '\W+(?:(?:S\d[\dE._ -])|(?:\d\d?x)|(?:\d{4}\W\d\d\... | identifier_body |
test_xem.py | #!/usr/bin/env python2.7
# Author: echel0n <echel0n@sickrage.ca>
# URL: https://sickrage.ca
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify | #
# SickRage is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along wi... | # it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. | random_line_split |
test_xem.py | #!/usr/bin/env python2.7
# Author: echel0n <echel0n@sickrage.ca>
# URL: https://sickrage.ca
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of t... |
def test_formating(self):
name = "Game.of.Thrones.S03.720p.HDTV.x264-CtrlHD"
release = "Game of Thrones"
# m = re.match('(?P<ep_ab_num>(?>\d{1,3})(?![ip])).+', name)
escaped_name = re.sub('\\\\[\\s.-]', '\W+', re.escape(release))
curRegex = '^' + escaped_name + '\W+(?:(?:... | try:
curShow = TVShow(int(s["indexer"]), int(s["indexer_id"]))
curShow.saveToDB()
curShow.loadFromDB(skipNFO=True)
sickrage.app.showlist.append(curShow)
except Exception as e:
print "There was an error creating the show" | conditional_block |
SOC.py | #
# Copyright (c) 2009-2015, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El, math, time
m = 10
cutoff = 1000
output = Tru... | n = s.Height()
if output:
El.Print( s, "s" )
El.Print( z, "z" )
El.Print( orders, "orders" )
El.Print( firstInds, "firstInds" )
# Compute the (Jordan) determinants and number of non-positive SOC members
# ========================================================================
sDets = El.SOCDets( s, orders, fi... | s, z, orders, firstInds = ConstructPrimalDual(m) | random_line_split |
SOC.py | #
# Copyright (c) 2009-2015, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El, math, time
m = 10
cutoff = 1000
output = Tru... | firstInds.Set( i+m, 0, m )
firstInds.Set( i+2*m, 0, 2*m )
return s, z, orders, firstInds
s, z, orders, firstInds = ConstructPrimalDual(m)
n = s.Height()
if output:
El.Print( s, "s" )
El.Print( z, "z" )
El.Print( orders, "orders" )
El.Print( firstInds, "firstInds" )
# Compute the (Jordan) determinan... | s = El.DistMultiVec()
z = El.DistMultiVec()
orders = El.DistMultiVec(El.iTag)
firstInds = El.DistMultiVec(El.iTag)
sampleRad = 1./math.sqrt(1.*m)
El.Uniform( s, 3*m, 1, 0, sampleRad )
El.Uniform( z, 3*m, 1, 0, sampleRad )
s.Set( 0, 0, 2. )
s.Set( m, 0, 3. )
s.Set( 2*m, 0, 4. )
z.Set( 0, 0, 5. )
z.... | identifier_body |
SOC.py | #
# Copyright (c) 2009-2015, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El, math, time
m = 10
cutoff = 1000
output = Tru... |
El.Print( p, "s + alpha y" )
El.Print( pDets, "det(s + alpha y)" )
# Require the user to press a button before the figures are closed
El.Finalize()
if worldSize == 1:
raw_input('Press Enter to exit')
| print "maximum step in cone is:", alpha | conditional_block |
SOC.py | #
# Copyright (c) 2009-2015, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El, math, time
m = 10
cutoff = 1000
output = Tru... | (m):
s = El.DistMultiVec()
z = El.DistMultiVec()
orders = El.DistMultiVec(El.iTag)
firstInds = El.DistMultiVec(El.iTag)
sampleRad = 1./math.sqrt(1.*m)
El.Uniform( s, 3*m, 1, 0, sampleRad )
El.Uniform( z, 3*m, 1, 0, sampleRad )
s.Set( 0, 0, 2. )
s.Set( m, 0, 3. )
s.Set( 2*m, 0, 4. )
z.Set( 0, 0, 5.... | ConstructPrimalDual | identifier_name |
mod.rs | llfn = cx.get_fn(instance);
let mir = cx.tcx().instance_mir(instance.def);
let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
debug!("fn_abi: {:?}", fn_abi);
let debug_context = cx.create_function_debug_context(instance, &fn_abi, llfn, &mir);
let start_llbb = Bx::append_block(cx, ... | {
// As the storage for the indirect argument lives during
// the whole function call, we just copy the fat pointer.
let llarg = bx.get_param(llarg_idx);
llarg_idx += 1;
let llextra = bx.get_param(llarg_idx);
llarg_idx += 1;... | conditional_block | |
mod.rs |
use self::operand::{OperandRef, OperandValue};
/// Master context for codegenning from MIR.
pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
instance: Instance<'tcx>,
mir: &'tcx mir::Body<'tcx>,
debug_context: Option<FunctionDebugContext<Bx::DIScope, Bx::DILocation>>,
llfn: Bx::Funct... | use rustc_middle::mir::traversal; | random_line_split | |
mod.rs | cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
/// When targeting MSVC, this stores the cleanup info for each funclet BB.
/// This is initialized at the same time as the `landing_pads` entry for the
/// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
funcl... | <'tcx, V> {
Place(PlaceRef<'tcx, V>),
/// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
/// `*p` is the fat pointer that references the actual unsized place.
/// Every time it is initialized, we have to reallocate the place
/// and update the fat pointer. That's the reason why it... | LocalRef | identifier_name |
local_data.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 ... | assert!(*(local_data_get(my_key).get()) == ~"parent data");
assert!(*(local_data_get(my_key).get()) == ~"parent data");
}
}
#[test]
fn test_tls_overwrite() {
unsafe {
fn my_key(_x: @~str) { }
local_data_set(my_key, @~"first data");
local_data_set(my_key, @~"next data"); ... | }
}
// Must work multiple times
assert!(*(local_data_get(my_key).get()) == ~"parent data"); | random_line_split |
local_data.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 ... | () {
unsafe {
fn my_key(_x: @~str) { }
local_data_set(my_key, @~"weasel");
assert!(*(local_data_pop(my_key).get()) == ~"weasel");
// Pop must remove the data from the map.
assert!(local_data_pop(my_key).is_none());
}
}
#[test]
fn test_tls_modify() {
unsafe {
... | test_tls_pop | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.