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 |
|---|---|---|---|---|
emulate.ts | ///<reference path="../.d.ts"/>
"use strict";
export class EmulateCommandBase {
constructor(private $platformService: IPlatformService) { }
executeCore(args: string[]): IFuture<void> {
return this.$platformService.deployOnEmulator(args[0]);
}
}
export class EmulateIosCommand extends EmulateCommandBase implemen... | (args: string[]): IFuture<void> {
return this.executeCore([this.$platformsData.availablePlatforms.Android]);
}
}
$injector.registerCommand("emulate|android", EmulateAndroidCommand);
| execute | identifier_name |
mv-elsewhere.py | #! /usr/bin/env python
# Copyright (C) 2012 dcodix
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fi... | else:
verbosemessage('COPYING: '+file1+' to '+dfile)
copy2(file1, dfile)
nfiles = nfiles + 1
else:
verbosemessage('NOT OVERRIDING: '+dfile)
pass
else:
if excludefile:
... | random_line_split | |
mv-elsewhere.py | #! /usr/bin/env python
# Copyright (C) 2012 dcodix
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fi... |
else:
if filemove:
printmessage(str(nfiles)+' files have been moved.')
else:
printmessage(str(nfiles)+' files have been copied.')
if __name__ == "__main__":
main()
| printmessage('No files have been moved or copied.') | conditional_block |
mv-elsewhere.py | #! /usr/bin/env python
# Copyright (C) 2012 dcodix
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fi... |
def main():
scriptname = 'mv-elsewhere.py'
dst = ''
filemove = False
override = False
readstdin = True
global verbose
global debuging
verbose = False
debuging = False
exclude = ''
excludelist = ''
#GET ARGS
parser = argparse.ArgumentParser(description='Move files')... | if debuging:
printmessage(logstring) | identifier_body |
mv-elsewhere.py | #! /usr/bin/env python
# Copyright (C) 2012 dcodix
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fi... | (logstring):
print('['+str(time.time())+'] '+logstring)
def verbosemessage(logstring):
if verbose:
printmessage(logstring)
def debugmessage(logstring):
if debuging:
printmessage(logstring)
def main():
scriptname = 'mv-elsewhere.py'
dst = ''
filemove = False
override = False
... | printmessage | identifier_name |
index.js | /**
*
* SelectField
*
*/
import React from 'react';
import { Field } from 'redux-form';
function | (props) {
let options;
if (props.options) {
options = props.options.map((option, index) => (
<option key={`option-${index}`} value={option[1]}>{option[0]}</option>
));
}
return (
<div className={`form-group col-xs-${props.width}`}>
<Field name={props.name} component="select" defaultValue... | SelectField | identifier_name |
index.js | /**
*
* SelectField
*
*/
import React from 'react';
import { Field } from 'redux-form';
function SelectField(props) |
SelectField.propTypes = {
name: React.PropTypes.string,
label: React.PropTypes.string,
options: React.PropTypes.array,
width: React.PropTypes.number,
required: React.PropTypes.bool,
default: React.PropTypes.string,
};
export default SelectField;
| {
let options;
if (props.options) {
options = props.options.map((option, index) => (
<option key={`option-${index}`} value={option[1]}>{option[0]}</option>
));
}
return (
<div className={`form-group col-xs-${props.width}`}>
<Field name={props.name} component="select" defaultValue={props.... | identifier_body |
index.js | /**
*
* SelectField
*
*/
import React from 'react';
import { Field } from 'redux-form';
function SelectField(props) {
let options;
if (props.options) {
options = props.options.map((option, index) => (
<option key={`option-${index}`} value={option[1]}>{option[0]}</option>
));
}
return (
<div ... | );
}
SelectField.propTypes = {
name: React.PropTypes.string,
label: React.PropTypes.string,
options: React.PropTypes.array,
width: React.PropTypes.number,
required: React.PropTypes.bool,
default: React.PropTypes.string,
};
export default SelectField; | </Field>
</div> | random_line_split |
index.js | /**
*
* SelectField
*
*/
import React from 'react';
import { Field } from 'redux-form';
function SelectField(props) {
let options;
if (props.options) |
return (
<div className={`form-group col-xs-${props.width}`}>
<Field name={props.name} component="select" defaultValue={props.default} id={props.label} required={props.required}>
<option key="option-default" value="" disabled>{props.label}</option>
{options}
</Field>
</div>
);
}... | {
options = props.options.map((option, index) => (
<option key={`option-${index}`} value={option[1]}>{option[0]}</option>
));
} | conditional_block |
kde-to-freedesktop.py | #!/usr/bin/env python
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2007 1&1 Internet AG, Germany, http://www.1and1.org
#
# License:
# LGPL: http://www.gnu.org/licenses/lgpl.html
# EPL: h... | (path, __func__):
try:
__func__(path)
except OSError, (errno, strerror):
print ERROR_STR % {'path' : path, 'error': strerror }
def removeall(path):
if not os.path.isdir(path):
return
files=os.listdir(path)
for x in files:
fullpath=os.path.join(path, x)
if os.path.isfile(fullpath):
... | rmgeneric | identifier_name |
kde-to-freedesktop.py | #!/usr/bin/env python
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2007 1&1 Internet AG, Germany, http://www.1and1.org
#
# License:
# LGPL: http://www.gnu.org/licenses/lgpl.html
# EPL: h... | parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Verbose output mode.")
parser.add_option("--input", "-i", action="store", dest="input", metavar="DIRECTORY", help="Input directory")
parser.add_option("--output", "-o", action="store", dest="output", metavar="DIRECTORY", help="Output ... | parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=False, help="Quiet output mode.") | random_line_split |
kde-to-freedesktop.py | #!/usr/bin/env python
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2007 1&1 Internet AG, Germany, http://www.1and1.org
#
# License:
# LGPL: http://www.gnu.org/licenses/lgpl.html
# EPL: h... |
for size in img_sizes:
kde_file = "%s/%sx%s/%s.png" % (options.input, size, size, kde)
fd_file = "%s/%sx%s/%s.png" % (options.output, size, size, fd)
if os.path.exists(kde_file):
fd_dir = os.path.dirname(fd_file)
if not os.path.exists(fd_dir):
os.makedirs(fd_dir)
shutil.copyf... | print " - Processing: %s -> %s" % (kde, fd) | conditional_block |
kde-to-freedesktop.py | #!/usr/bin/env python
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2007 1&1 Internet AG, Germany, http://www.1and1.org
#
# License:
# LGPL: http://www.gnu.org/licenses/lgpl.html
# EPL: h... |
def copy_file(kde, fd, options):
img_sizes = [16, 22, 32, 48, 64, 72, 96, 128]
found = []
notfound = []
if options.verbose:
print " - Processing: %s -> %s" % (kde, fd)
for size in img_sizes:
kde_file = "%s/%sx%s/%s.png" % (options.input, size, size, kde)
fd_file = "%s/%sx%s/%s.png" % (opt... | if not os.path.isdir(path):
return
files=os.listdir(path)
for x in files:
fullpath=os.path.join(path, x)
if os.path.isfile(fullpath):
f=os.remove
rmgeneric(fullpath, f)
elif os.path.isdir(fullpath):
removeall(fullpath)
f=os.rmdir
rmgeneric(fullpath, f) | identifier_body |
restyle_damage.rs | position of this node or its descendants has \
changed."]
#[doc = "Propagates both up and down the flow tree."]
const REPOSITION = 0x02,
#[doc = "Recompute the overflow regions (bounding box of object and all descendants)."]
#[doc = "Propagates down the flow tree becau... |
/// Supposing the *parent* of a flow with the given `position` property has
/// this damage, returns the damage that we should add to this flow.
pub fn damage_for_child(self,
parent_is_absolutely_positioned: bool,
child_is_absolutely_positioned: bool... | {
if child_is_absolutely_positioned {
self & (REPAINT | REPOSITION | STORE_OVERFLOW | REFLOW_OUT_OF_FLOW |
RESOLVE_GENERATED_CONTENT)
} else {
self & (REPAINT | REPOSITION | STORE_OVERFLOW | REFLOW | REFLOW_OUT_OF_FLOW |
RESOLVE_GENERATED_C... | identifier_body |
restyle_damage.rs | position of this node or its descendants has \
changed."]
#[doc = "Propagates both up and down the flow tree."]
const REPOSITION = 0x02,
#[doc = "Recompute the overflow regions (bounding box of object and all descendants)."]
#[doc = "Propagates down the flow tree becau... | () -> ServoRestyleDamage {
REPAINT | REPOSITION | STORE_OVERFLOW | BUBBLE_ISIZES | REFLOW_OUT_OF_FLOW | REFLOW |
RECONSTRUCT_FLOW
}
/// Returns a bitmask indicating that the frame needs to be reconstructed.
pub fn reconstruct() -> ServoRestyleDamage {
RECONSTRUCT_FLOW
}
... | rebuild_and_reflow | identifier_name |
restyle_damage.rs | position of this node or its descendants has \
changed."]
#[doc = "Propagates both up and down the flow tree."]
const REPOSITION = 0x02,
#[doc = "Recompute the overflow regions (bounding box of object and all descendants)."]
#[doc = "Propagates down the flow tree becau... |
}
}
/// Servo doesn't implement this optimization.
pub fn handled_for_descendants(self) -> Self {
Self::empty()
}
}
impl Default for ServoRestyleDamage {
fn default() -> Self {
Self::empty()
}
}
impl fmt::Display for ServoRestyleDamage {
fn fmt(&self, f: &mut fmt:... | {
// TODO(pcwalton): Take floatedness into account.
self & (REPAINT | REPOSITION | REFLOW)
} | conditional_block |
restyle_damage.rs | bounding box of object and all descendants)."]
#[doc = "Propagates down the flow tree because the computation is bottom-up."]
const STORE_OVERFLOW = 0x04,
#[doc = "Recompute intrinsic inline_sizes (minimum and preferred)."]
#[doc = "Propagates down the flow tree because the computation ... | get_position.flex_grow,
get_position.flex_shrink, | random_line_split | |
augmentations.py | np.ndarray]
ConfigDict = Mapping[Text, Any]
augment_config = dict(
view1=dict(
random_flip=False, # Random left/right flip
color_transform=dict(
apply_prob=1.0,
# Range of jittering
brightness=0.4,
contrast=0.4,
saturation=0.2,
... |
return x
out_apply = _color_jitter(image)
out_apply = jax.lax.cond(should_apply & should_apply_gs, out_apply,
to_grayscale, out_apply, lambda x: x)
return jnp.clip(out_apply, 0., 1.)
def random_flip(images, rng):
rngs = jax.random.split(rng, images.shape[0])
return jax.vmap(... | x = random_hue_cond((h_rng, x), idx) | conditional_block |
augmentations.py | np.ndarray]
ConfigDict = Mapping[Text, Any]
augment_config = dict(
view1=dict(
random_flip=False, # Random left/right flip
color_transform=dict(
apply_prob=1.0,
# Range of jittering
brightness=0.4,
contrast=0.4,
saturation=0.2,
... |
return cond_fn
random_brightness = functools.partial(
pix.random_brightness, max_delta=brightness)
random_contrast = functools.partial(
pix.random_contrast, lower=1-contrast, upper=1+contrast)
random_hue = functools.partial(pix.random_hue, max_delta=hue)
random_saturation = functools.partial(... | def clip(args):
return jax.tree_map(lambda arg: jnp.clip(arg, 0., 1.), args)
out = jax.lax.cond(should_apply & should_apply_color & (i == idx), args,
lambda a: clip(fn(*a)), args,
lambda a: identity_fn(*a))
return jax.lax.stop_gradient(out) | identifier_body |
augmentations.py | np.ndarray]
ConfigDict = Mapping[Text, Any]
augment_config = dict(
view1=dict(
random_flip=False, # Random left/right flip
color_transform=dict(
apply_prob=1.0,
# Range of jittering
brightness=0.4,
contrast=0.4,
saturation=0.2,
... | rng,
blur_div | random_line_split | |
augmentations.py | np.ndarray]
ConfigDict = Mapping[Text, Any]
augment_config = dict(
view1=dict(
random_flip=False, # Random left/right flip
color_transform=dict(
apply_prob=1.0,
# Range of jittering
brightness=0.4,
contrast=0.4,
saturation=0.2,
... | (images, rng):
rngs = jax.random.split(rng, images.shape[0])
return jax.vmap(pix.random_flip_left_right)(rngs, images)
def color_transform(images,
rng,
brightness=0.8,
contrast=0.8,
saturation=0.8,
hue=0.2,
... | random_flip | identifier_name |
Container.ts | import { Registration } from "./Models";
export class Container {
private registrations: Array<Registration> = [];
private createInstance<T extends object>(classType: {new (): T} | Function): T {
return Reflect.construct(classType, []);
}
private isItemRegistered(item: any) : boolean |
registerAbstraction<T, U extends T>(abstractClass: (new (...args: any[]) => T) | Function, implementedClass: { new (...args: any[]): U; }, singleton: boolean = false): Container {
const existingRegistration = this.registrations
.filter(existingRegistration =>
existingRegistrat... | {
const registrationMatch = this.registrations.filter(registration => registration.RegisteredInterface == item || registration.RegisteredClass == item)[0];
return registrationMatch != null;
} | identifier_body |
Container.ts | import { Registration } from "./Models";
export class Container {
private registrations: Array<Registration> = [];
private createInstance<T extends object>(classType: {new (): T} | Function): T {
return Reflect.construct(classType, []);
}
private isItemRegistered(item: any) : boolean {
... | const registration = new Registration();
registration.RegisteredClass = implementedClass;
registration.SingletonReference = singleton ? this.createInstance(implementedClass) : null;
this.registrations.push(registration);
return this;
}
resolve<T>(itemToResolve: (new (...... | registerClass<T>(implementedClass: { new (): T }, singleton: boolean = false): Container {
if(this.isItemRegistered(implementedClass)) throw `You cannot register a class more than once`; | random_line_split |
Container.ts | import { Registration } from "./Models";
export class Container {
private registrations: Array<Registration> = [];
private | <T extends object>(classType: {new (): T} | Function): T {
return Reflect.construct(classType, []);
}
private isItemRegistered(item: any) : boolean {
const registrationMatch = this.registrations.filter(registration => registration.RegisteredInterface == item || registration.RegisteredClass == i... | createInstance | identifier_name |
plugin_utils.py | import json
import datetime
import threading
from base_plugin import *
import base_plugin
#=============================================Messaging===================================
def send_message(recipient, message, mtype='chat'):
'''
Send a message to recipient.
:param recipient: The To field of your messa... |
return False
def on_presence(event, plugin):
'''
filter for join/part type events.
:param event: the event being filtered
:param plugin: the plugin hosting the filter
returns - true if a presence event, false otherwise.
'''
if event.Type in ["available", "unavailable"]:
return True
return False
... | return True | conditional_block |
plugin_utils.py | import json
import datetime
import threading
from base_plugin import *
import base_plugin
#=============================================Messaging===================================
def send_message(recipient, message, mtype='chat'):
'''
Send a message to recipient.
:param recipient: The To field of your messa... |
#=============================================FILE OPERATORS=====================================
def put_object_to_file(item, path):
'''
Syntactic sugar, write jsonified object to file.
:param item: Any json-able item.
:param path: path to log file.
'''
with open(path, 'w+') as f:
f.write(json.dumps(i... | '''
filter for join/part type events.
:param event: the event being filtered
:param plugin: the plugin hosting the filter
returns - true if a presence event, false otherwise.
'''
if event.Type in ["available", "unavailable"]:
return True
return False | identifier_body |
plugin_utils.py | import json
import datetime
import threading
from base_plugin import *
import base_plugin
#=============================================Messaging===================================
def send_message(recipient, message, mtype='chat'):
'''
Send a message to recipient.
:param recipient: The To field of your messa... |
def schedule_event(year, month, day, hour, minute, second, event, args=[]):
'''
Schedule an event by an absolute time
:param year: year of the event
:param month: month of the event
:param day: day of the event
:param hour: hour of the event
:param minute: minute of the event
:param second: seco... | delta = time - datetime.datetime.now()
threading.Timer(delta.total_seconds(), call_function_with_variable_arguments, [event, args]).start() | random_line_split |
plugin_utils.py | import json
import datetime
import threading
from base_plugin import *
import base_plugin
#=============================================Messaging===================================
def send_message(recipient, message, mtype='chat'):
'''
Send a message to recipient.
:param recipient: The To field of your messa... | (function, arguments):
'''
Takes functions, takes arguments, makes it fit.
:param function: The function to call
:param arguments: The argument list to make fit.
'''
iterator = len(arguments)
while True:
real_exception = None
try:
function(*(arguments[:iterator]))
return
except Exception as e... | call_function_with_variable_arguments | identifier_name |
branch.rs | use cpu::{self, Cpu, Version};
use cpu::interpreter_arm as arm;
use bitutils::sign_extend32;
fn instr_branch_exchange<V: Version>(cpu: &mut Cpu<V>, data: arm::Bx::Bf, link: bool) -> cpu::InstrStatus {
if !cpu::cond_passed(data.cond.get(), &cpu.cpsr) {
return cpu::InstrStatus::InBlock;
}
let addr =... | <V: Version>(cpu: &mut Cpu<V>, data: arm::Blx2::Bf) -> cpu::InstrStatus {
instr_branch_exchange(cpu, arm::Bx::new(data.val), true)
}
pub fn bx<V: Version>(cpu: &mut Cpu<V>, data: arm::Bx::Bf) -> cpu::InstrStatus {
instr_branch_exchange(cpu, data, false)
}
pub fn mod_blx<V: Version>(cpu: &mut Cpu<V>, data: arm... | blx | identifier_name |
branch.rs | use cpu::{self, Cpu, Version};
use cpu::interpreter_arm as arm;
use bitutils::sign_extend32;
fn instr_branch_exchange<V: Version>(cpu: &mut Cpu<V>, data: arm::Bx::Bf, link: bool) -> cpu::InstrStatus {
if !cpu::cond_passed(data.cond.get(), &cpu.cpsr) {
return cpu::InstrStatus::InBlock;
}
let addr =... | {
let signed_imm_24 = data.signed_imm_24.get();
let h_bit = data.h_bit.get();
cpu.regs[14] = cpu.regs[15] - 4;
cpu.cpsr.thumb_bit.set(1);
let pc = cpu.regs[15];
cpu.branch((pc as i32 + (sign_extend32(signed_imm_24, 24) << 2)) as u32 + (h_bit << 1));
cpu::InstrStatus::Branched
} | identifier_body | |
branch.rs | use cpu::{self, Cpu, Version};
use cpu::interpreter_arm as arm;
use bitutils::sign_extend32;
fn instr_branch_exchange<V: Version>(cpu: &mut Cpu<V>, data: arm::Bx::Bf, link: bool) -> cpu::InstrStatus {
if !cpu::cond_passed(data.cond.get(), &cpu.cpsr) {
return cpu::InstrStatus::InBlock;
}
let addr =... |
pub fn mod_blx<V: Version>(cpu: &mut Cpu<V>, data: arm::ModBlx::Bf) -> cpu::InstrStatus {
let signed_imm_24 = data.signed_imm_24.get();
let h_bit = data.h_bit.get();
cpu.regs[14] = cpu.regs[15] - 4;
cpu.cpsr.thumb_bit.set(1);
let pc = cpu.regs[15];
cpu.branch((pc as i32 + (sign_extend32(signe... | } | random_line_split |
branch.rs | use cpu::{self, Cpu, Version};
use cpu::interpreter_arm as arm;
use bitutils::sign_extend32;
fn instr_branch_exchange<V: Version>(cpu: &mut Cpu<V>, data: arm::Bx::Bf, link: bool) -> cpu::InstrStatus {
if !cpu::cond_passed(data.cond.get(), &cpu.cpsr) |
let addr = cpu.regs[data.rm.get() as usize];
if link {
cpu.regs[14] = cpu.regs[15] - 4;
}
cpu.cpsr.thumb_bit.set(bit!(addr, 0));
cpu.branch(addr & 0xFFFFFFFE);
cpu::InstrStatus::Branched
}
pub fn bbl<V: Version>(cpu: &mut Cpu<V>, data: arm::Bbl::Bf) -> cpu::InstrStatus {
if !cp... | {
return cpu::InstrStatus::InBlock;
} | conditional_block |
question2tex_chart.py | import logging
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from survey.exporter.tex.question2tex import Question2Tex
LOGGER = logging.getLogger(__name__)
class Question2TexChart(Question2Tex):
"""
This class permit to generate latex code directly from the Questi... | (self): # noqa: C901
r"""Return the options of the pie for: \pie[options]{data}"""
options = ""
if self.pos:
options += "pos={%s}," % self.pos
if self.explode:
options += "explode={%s}," % self.explode
if self.rotate:
options += f"rotate={self... | get_pie_options | identifier_name |
question2tex_chart.py | import logging
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from survey.exporter.tex.question2tex import Question2Tex
LOGGER = logging.getLogger(__name__)
class Question2TexChart(Question2Tex):
"""
This class permit to generate latex code directly from the Questi... |
if self.explode:
options += "explode={%s}," % self.explode
if self.rotate:
options += f"rotate={self.rotate},"
if self.radius:
options += f"radius={self.radius},"
if self.color:
options += f"color={self.get_colors()},"
if self.sum:... | options += "pos={%s}," % self.pos | conditional_block |
question2tex_chart.py | import logging
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from survey.exporter.tex.question2tex import Question2Tex
LOGGER = logging.getLogger(__name__)
class Question2TexChart(Question2Tex):
"""
This class permit to generate latex code directly from the Questi... | if self.text:
options += f"text={self.text},"
if self.style:
options += f"style={self.style},"
if self.type and self.type != "pie":
options += f"{self.type},"
# Removing last ','
options = options[:-1]
if options:
return f"[... | r"""Return the options of the pie for: \pie[options]{data}"""
options = ""
if self.pos:
options += "pos={%s}," % self.pos
if self.explode:
options += "explode={%s}," % self.explode
if self.rotate:
options += f"rotate={self.rotate},"
if self.rad... | identifier_body |
question2tex_chart.py | import logging
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from survey.exporter.tex.question2tex import Question2Tex
LOGGER = logging.getLogger(__name__)
class Question2TexChart(Question2Tex):
"""
This class permit to generate latex code directly from the Questi... | \\pie%s{
%s
}
\\end{tikzpicture}
\\caption{\\label{figure:q%d-%d}%s}
\\end{figure}
"""
def __init__(self, question, **options):
super().__init__(question, **options)
self.pos = options.get("pos")
self.rotate = options.get("rotate")
self.radius = options.get("... | random_line_split | |
CustomColorCell.style.tsx | import {makeStyles} from '@material-ui/core';
import {CremaTheme} from '../../../types/AppContextPropsType';
const useStyles = makeStyles((theme: CremaTheme) => ({
colorOption: {
position: 'relative',
overflow: 'hidden',
cursor: 'pointer',
border: `1px solid ${theme.palette.text.primary}`,
... | left: '50%',
top: '50%',
transform: 'translate(-50%, -50%)',
width: 20,
height: 20,
borderRadius: '50%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
overflow: 'hidden',
backgroundColor: '#fff',
color: theme.palette.primary.main,
},
te... | position: 'absolute',
| random_line_split |
validate.py | # -*- coding: utf-8 -*-
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
# --------------------------------------------------------------------------
# Blender 2.5 Extensions Framework
# --------------------------------------------------------------------------
#
# Authors:
# Doug Hammond
#
# This program is free software; yo... | return self.test_and(member, logic)
elif type(logic) is Logic_OR:
return self.test_or(member, logic)
elif type(logic) is Logic_Operator:
return self.test_operator(member, logic)
else:
# compare the value, I think using Logic_Operator() here
... | random_line_split | |
validate.py | # -*- coding: utf-8 -*-
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
# --------------------------------------------------------------------------
# Blender 2.5 Extensions Framework
# --------------------------------------------------------------------------
#
# Authors:
# Doug Hammond
#
# This program is free software; yo... | (dict):
pass
class Logician(object):
"""Given a subject and a dict that describes tests to perform on
its members, this class will evaluate True or False results for
each member/test pair. See the examples below for test syntax.
"""
subject = None
def __init__(self, subject):
self... | Logic_Operator | identifier_name |
validate.py | # -*- coding: utf-8 -*-
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
# --------------------------------------------------------------------------
# Blender 2.5 Extensions Framework
# --------------------------------------------------------------------------
#
# Authors:
# Doug Hammond
#
# This program is free software; yo... |
def get_member(self, member_name):
"""Get a member value from the subject object. Raise exception
if subject is None or member not found.
"""
if self.subject is None:
raise Exception('Cannot run tests on a subject which is None')
return getattr(self.subject, m... | self.subject = subject | identifier_body |
validate.py | # -*- coding: utf-8 -*-
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
# --------------------------------------------------------------------------
# Blender 2.5 Extensions Framework
# --------------------------------------------------------------------------
#
# Authors:
# Doug Hammond
#
# This program is free software; yo... |
# A couple of name aliases
class Validation(Logician):
pass
class Visibility(Logician):
pass
| result = self.test_logic(self.get_member(member_name), logic)
print('member %s is %s' % (member_name, result)) | conditional_block |
example.py | import scrapy
from congress.items import Article
class Example(scrapy.Spider):
'''Modeled after scrapy tutorial here:
https://doc.scrapy.org/en/latest/intro/tutorial.html
'''
# spider name should be name of website/source
name = 'example'
def start_requests(self):
# list of URLs or ... | (self, response):
'''to learn more about xpath selectors:
https://doc.scrapy.org/en/latest/topics/selectors.html
'''
language = response.xpath('//html/@lang').extract_first()
url = response.url
source = 'example' # spider name
# Select all quotes
quote... | parse | identifier_name |
example.py | import scrapy
from congress.items import Article
class Example(scrapy.Spider):
'''Modeled after scrapy tutorial here:
https://doc.scrapy.org/en/latest/intro/tutorial.html
'''
# spider name should be name of website/source
name = 'example'
def start_requests(self):
# list of URLs or ... |
# now we create our article item for a list of available fields see items.py
article = Article(
# Required fields
language=language,
url=url,
source=source,
text_blob=text_blob,
... | author = quote.xpath('.//small[contains(@class, "author")]').extract_first() | random_line_split |
example.py | import scrapy
from congress.items import Article
class Example(scrapy.Spider):
'''Modeled after scrapy tutorial here:
https://doc.scrapy.org/en/latest/intro/tutorial.html
'''
# spider name should be name of website/source
name = 'example'
def start_requests(self):
# list of URLs or ... |
def parse(self, response):
'''to learn more about xpath selectors:
https://doc.scrapy.org/en/latest/topics/selectors.html
'''
language = response.xpath('//html/@lang').extract_first()
url = response.url
source = 'example' # spider name
# Select all quote... | urls = [
'http://quotes.toscrape.com/page/1/'
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse) | identifier_body |
example.py | import scrapy
from congress.items import Article
class Example(scrapy.Spider):
'''Modeled after scrapy tutorial here:
https://doc.scrapy.org/en/latest/intro/tutorial.html
'''
# spider name should be name of website/source
name = 'example'
def start_requests(self):
# list of URLs or ... | yield article
| text_blob = quote.xpath('.//span/text()').extract_first()
# Using [contains@class] for illustrative purposes. We could have used
# @class="author" as well. This will return any small tag with class
# that contains the word "author"
author = quote.xpath('.//small[contain... | conditional_block |
test_page_breaks04.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | self.ignore_files = ['xl/printerSettings/printerSettings1.bin',
'xl/worksheets/_rels/sheet1.xml.rels']
self.ignore_elements = {'[Content_Types].xml': ['<Default Extension="bin"'],
'xl/worksheets/sheet1.xml': ['<pageMargins', '<pageSetup']}
... |
self.set_filename('page_breaks04.xlsx')
| random_line_split |
test_page_breaks04.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | (self):
"""Test the creation of a simple XlsxWriter file with page breaks."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.set_v_pagebreaks([1])
worksheet.write('A1', 'Foo')
workbook.close()
self.assertExcelEqual()
| test_create_file | identifier_name |
test_page_breaks04.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | """Test the creation of a simple XlsxWriter file with page breaks."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.set_v_pagebreaks([1])
worksheet.write('A1', 'Foo')
workbook.close()
self.assertExcelEqual() | identifier_body | |
all_2.js | var searchData=
[
['c',['C',['../struct_s_a_c_bitstream_1_1_channel_type.html#a31c32b34085c06a1c58d920ca28c17c9a5c9b81e6c191dc59f0f4680421cafa72',1,'SACBitstream::ChannelType']]],
['channel',['Channel',['../class_channel.html',1,'Channel'],['../class_channel.html#a3a5079024e870e5188f7af98772ae38c',1,'Channel::Chann... | ['chunkid',['chunkID',['../struct_w_a_v_file_1_1_header.html#a796a84d05ba0ddeb837804dff90b730b',1,'WAVFile::Header']]],
['chunksize',['chunksize',['../struct_w_a_v_file_1_1_header.html#aee17e466b00a8b1d274be731f58d5fc0',1,'WAVFile::Header']]],
['clear',['clear',['../class_output_device.html#a9c3515a8c1812a08bd74d... | ['chartoptions',['ChartOptions',['../struct_chart2_d_1_1_chart_options.html',1,'Chart2D']]],
['charts',['charts',['../class_effects_monitor.html#a2b5f5373404adac3f94bdab2f423d958',1,'EffectsMonitor']]], | random_line_split |
foo.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo {
... | random_line_split | |
foo.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 ... |
}
trait Tr2<X, Y: Tr> {
fn squid(&self, y: &Y, z: Self) -> Box<X>;
}
impl Tr2<Foo, Foo> for Foo {
fn squid(&self, y: &Foo, z: Foo) -> Box<Foo> {
box Foo { f: y.f + z.f + self.f }
}
}
enum En {
Var1,
Var2,
Var3(int, int, Foo)
}
fn main() {
let x = Foo { f: 237 };
let _f = x.b... | {
Foo{ f: self.f + x.f }
} | identifier_body |
foo.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 ... | (&self, y: &Foo, z: Foo) -> Box<Foo> {
box Foo { f: y.f + z.f + self.f }
}
}
enum En {
Var1,
Var2,
Var3(int, int, Foo)
}
fn main() {
let x = Foo { f: 237 };
let _f = x.bar();
let en = En::Var2;
let _ = match en {
En::Var1 => x.bar(),
En::Var2 => 34,
En:... | squid | identifier_name |
day02.rs | struct Keypad {
grid: KeyGrid,
cursor: (usize, usize),
}
type KeyGrid = Vec<Vec<Option<char>>>;
impl Keypad {
fn simple() -> Keypad {
let grid: KeyGrid = vec![vec![Some('1'), Some('2'), Some('3')],
vec![Some('4'), Some('5'), Some('6')],
... | {
let digit_commands: Vec<&str> = input.split("\n").collect();
let mut code: Vec<char> = vec![];
for command_set in digit_commands.clone() {
let mut keypad = Keypad::simple();
let digit = keypad.process(command_set);
code.push(digit);
}
println!("Simple Code is {:?}", code);... | identifier_body | |
day02.rs | struct Keypad {
grid: KeyGrid,
cursor: (usize, usize),
}
type KeyGrid = Vec<Vec<Option<char>>>;
impl Keypad {
fn simple() -> Keypad {
let grid: KeyGrid = vec![vec![Some('1'), Some('2'), Some('3')],
vec![Some('4'), Some('5'), Some('6')],
... | let digit = keypad.process(command_set);
code.push(digit);
}
println!("Simple Code is {:?}", code);
code.clear();
for command_set in digit_commands.clone() {
let mut keypad = Keypad::complicated();
let digit = keypad.process(command_set);
code.push(digit);
}
... | random_line_split | |
day02.rs | struct Keypad {
grid: KeyGrid,
cursor: (usize, usize),
}
type KeyGrid = Vec<Vec<Option<char>>>;
impl Keypad {
fn simple() -> Keypad {
let grid: KeyGrid = vec![vec![Some('1'), Some('2'), Some('3')],
vec![Some('4'), Some('5'), Some('6')],
... | (&mut self, commands: &str) -> char {
let mut x = self.cursor.1 as isize;
let mut y = self.cursor.0 as isize;
for step in commands.chars() {
match step {
'U' => {
let (x_, y_) = self.bound(x, y - 1).unwrap_or((x, y));
x = x_;
... | process | identifier_name |
icon-refresh.component.ts | import {Component} from '@angular/core';
@Component({
selector: 'lb-icon-refresh',
template: `
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-refresh" width="32" height="32" viewBox="0 0 24 24">
<path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7... | {}
| IconRefreshComponent | identifier_name |
icon-refresh.component.ts | import {Component} from '@angular/core';
@Component({
selector: 'lb-icon-refresh',
template: `
<svg xmlns="http://www.w3.org/2000/svg" class="icon icon-refresh" width="32" height="32" viewBox="0 0 24 24">
<path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7... |
export class IconRefreshComponent {} | random_line_split | |
generate_input_syntax.py | #!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
# Set the name of the application here and moose directory relative to the application
app_name = 'falcon'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..' 'moose... | # in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR) |
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory | random_line_split |
generate_input_syntax.py | #!/usr/bin/env python
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
# Set the name of the application here and moose directory relative to the application
app_name = 'falcon'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..' 'moose... |
if os.environ.has_key("FRAMEWORK_DIR"):
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, ap... | MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework') | conditional_block |
angular-gantt-drawtask-plugin.js | Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
'use strict';
angular.module('gantt.drawtask', ['gantt']).directive('ganttDrawTask', ['$document', 'ganttMouseOffset', 'moment', function(document, mouseOffset, moment) {
return {
restrict: 'E',
require: '... | /*
Project: angular-gantt v1.2.7 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com | random_line_split | |
angular-gantt-drawtask-plugin.js | /*
Project: angular-gantt v1.2.7 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
'use strict';
angular.module('gantt.drawtask', ['gantt']).directive(... |
if (scope.moveThreshold === undefined) {
scope.moveThreshold = 0;
}
api.directives.on.new(scope, function(directiveName, directiveScope, element) {
if (directiveName === 'ganttRow') {
var addNewTask = funct... |
scope.enabled = true;
}
| conditional_block |
role-playing-game.rs | use role_playing_game::*;
#[test]
fn test_reviving_dead_player() {
let dead_player = Player {
health: 0,
mana: Some(0),
level: 34,
};
let revived_player = dead_player
.revive()
.expect("reviving a dead player must return Some(player)");
assert_eq!(revived_player.... | assert_eq!(accomplished_wizard.cast_spell(MANA_COST), MANA_COST * 2);
assert_eq!(accomplished_wizard.health, HEALTH);
assert_eq!(accomplished_wizard.mana, Some(MANA - MANA_COST));
assert_eq!(accomplished_wizard.level, LEVEL);
}
#[test]
#[ignore]
fn test_cast_spell_with_insufficient_mana() {
let mut... | health: HEALTH,
mana: Some(MANA),
level: LEVEL,
};
| random_line_split |
role-playing-game.rs | use role_playing_game::*;
#[test]
fn test_reviving_dead_player() {
let dead_player = Player {
health: 0,
mana: Some(0),
level: 34,
};
let revived_player = dead_player
.revive()
.expect("reviving a dead player must return Some(player)");
assert_eq!(revived_player.... | () {
const MANA_COST: u32 = 10;
let mut underleveled_player = Player {
health: 87,
mana: None,
level: 6,
};
let clone = Player {
..underleveled_player
};
assert_eq!(underleveled_player.cast_spell(MANA_COST), 0);
assert_eq!(underleveled_player.health, clone.... | test_cast_spell_with_no_mana_pool | identifier_name |
role-playing-game.rs | use role_playing_game::*;
#[test]
fn test_reviving_dead_player() {
let dead_player = Player {
health: 0,
mana: Some(0),
level: 34,
};
let revived_player = dead_player
.revive()
.expect("reviving a dead player must return Some(player)");
assert_eq!(revived_player.... |
#[test]
#[ignore]
fn test_cast_spell_with_insufficient_mana() {
let mut no_mana_wizard = Player {
health: 56,
mana: Some(2),
level: 22,
};
// we want to clone so we can compare before-and-after effects of casting the spell,
// but we don't want to introduce that concept to the... | {
const HEALTH: u32 = 99;
const MANA: u32 = 100;
const LEVEL: u32 = 100;
const MANA_COST: u32 = 3;
let mut accomplished_wizard = Player {
health: HEALTH,
mana: Some(MANA),
level: LEVEL,
};
assert_eq!(accomplished_wizard.cast_spell(MANA_COST), MANA_COST * 2);
ass... | identifier_body |
r_li_renyi_ascii.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_li_renyi_ascii.py
-------------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
********************... | __date__ = 'February 2016'
__copyright__ = '(C) 2016, Médéric Ribreux'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from .r_li import checkMovingWindow, configFile, moveOutputTxtFile
def checkParameterValuesBeforeExecuting(alg, parameters, context):
return che... |
__author__ = 'Médéric Ribreux' | random_line_split |
r_li_renyi_ascii.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_li_renyi_ascii.py
-------------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
********************... | processCommand(alg, parameters, context, feedback):
configFile(alg, parameters, context, feedback, True)
def processOutputs(alg, parameters, context, feedback):
moveOutputTxtFile(alg, parameters, context)
| checkMovingWindow(alg, parameters, context, True)
def | identifier_body |
r_li_renyi_ascii.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_li_renyi_ascii.py
-------------------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
********************... | parameters, context, feedback):
moveOutputTxtFile(alg, parameters, context)
| sOutputs(alg, | identifier_name |
payment.py | (selection_add=[('paypal', 'Paypal')])
paypal_email_account = fields.Char('Paypal Email ID', required_if_provider='paypal', groups='base.group_user')
paypal_seller_account = fields.Char(
'Paypal Merchant ID', groups='base.group_user',
help='The Merchant ID is used to ensure communications coming... |
@api.multi
def _paypal_form_get_invalid_parameters(self, data):
invalid_parameters = []
_logger.info('Received a notification from Paypal with IPN version %s', data.get('notify_version'))
if data.get('test_ipn'):
_logger.warning(
'Received a notification fro... | reference, txn_id = data.get('item_number'), data.get('txn_id')
if not reference or not txn_id:
error_msg = _('Paypal: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id)
_logger.info(error_msg)
raise ValidationError(error_msg)
# find tx ... | identifier_body |
payment.py | (selection_add=[('paypal', 'Paypal')])
paypal_email_account = fields.Char('Paypal Email ID', required_if_provider='paypal', groups='base.group_user')
paypal_seller_account = fields.Char(
'Paypal Merchant ID', groups='base.group_user',
help='The Merchant ID is used to ensure communications coming... | (self, data):
reference, txn_id = data.get('item_number'), data.get('txn_id')
if not reference or not txn_id:
error_msg = _('Paypal: received data with missing reference (%s) or txn_id (%s)') % (reference, txn_id)
_logger.info(error_msg)
raise ValidationError(error_ms... | _paypal_form_get_tx_from_data | identifier_name |
payment.py | .Selection(selection_add=[('paypal', 'Paypal')])
paypal_email_account = fields.Char('Paypal Email ID', required_if_provider='paypal', groups='base.group_user')
paypal_seller_account = fields.Char(
'Paypal Merchant ID', groups='base.group_user',
help='The Merchant ID is used to ensure communicati... | if data.get('test_ipn'):
_logger.warning(
'Received a notification from Paypal using sandbox'
),
# TODO: txn_id: shoudl be false at draft, set afterwards, and verified with txn details
if self.acquirer_reference and data.get('txn_id') != self.acquirer_ref... | _logger.info('Received a notification from Paypal with IPN version %s', data.get('notify_version')) | random_line_split |
payment.py | (selection_add=[('paypal', 'Paypal')])
paypal_email_account = fields.Char('Paypal Email ID', required_if_provider='paypal', groups='base.group_user')
paypal_seller_account = fields.Char(
'Paypal Merchant ID', groups='base.group_user',
help='The Merchant ID is used to ensure communications coming... |
return invalid_parameters
@api.multi
def _paypal_form_validate(self, data):
status = data.get('payment_status')
res = {
'acquirer_reference': data.get('txn_id'),
'paypal_txn_type': data.get('payment_type'),
}
if status in ['Completed', 'Processe... | if data.get('receiver_email') != self.acquirer_id.paypal_email_account:
invalid_parameters.append(('receiver_email', data.get('receiver_email'), self.acquirer_id.paypal_email_account)) | conditional_block |
config.py | #-*- coding: utf-8 -*-
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SSL_DISVBLE = True
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_RECORD_QUERIES = True
... | credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
if getattr(cls, 'MAIL_USE_TLS', None):
secure = ()
mail_handler = SMTPHandler(
mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
fromaddr=cls.FLASKY_MAIL_SENDER,
toaddrs=[cls.FLASKY_ADMIN],
... | credentials = None
secure = None
if getattr(cls, 'MAIL_USERNAME', None) is not None: | random_line_split |
config.py | #-*- coding: utf-8 -*-
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SSL_DISVBLE = True
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_RECORD_QUERIES = True
... |
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \
'sql... | pass | identifier_body |
config.py | #-*- coding: utf-8 -*-
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SSL_DISVBLE = True
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_RECORD_QUERIES = True
... |
mail_handler = SMTPHandler(
mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
fromaddr=cls.FLASKY_MAIL_SENDER,
toaddrs=[cls.FLASKY_ADMIN],
subject=cls.FLASKY_MAIL_SUBJECT_PREFIX + ' Application Error',
credentials=credentials,
secure=secure)
... | secure = () | conditional_block |
config.py | #-*- coding: utf-8 -*-
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class | :
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
SSL_DISVBLE = True
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_RECORD_QUERIES = True
MAIL_SERVER = 'smtp.qq.com'
MAIL_PORT = 25
MAIL_USE_TLS = True
MAIL_USE_SSL = False
... | Config | identifier_name |
mod.rs | use std::collections::{HashMap, BTreeMap};
use std::f64;
use std::path::PathBuf;
use std::process::Command;
use chrono::NaiveDate;
// use std::process::Command;
use postgres::Connection;
use postgres::params::IntoConnectParams;
use nickel::{Nickel, HttpRouter, Router};
use super::data_structs::main_page_data::MainPa... | (&mut self, new_file: PathBuf) {
self.data_file = Some(new_file);
}
pub fn init(&mut self) {
// compile sass
// try to get file names
let temp_params = self.scss_params.clone();
let styles_dir = match temp_params.dir {
Some(d) => d,
None => "styles... | add_data_file | identifier_name |
mod.rs | use std::collections::{HashMap, BTreeMap};
use std::f64;
use std::path::PathBuf;
use std::process::Command;
use chrono::NaiveDate;
// use std::process::Command;
use postgres::Connection;
use postgres::params::IntoConnectParams;
use nickel::{Nickel, HttpRouter, Router};
use super::data_structs::main_page_data::MainPa... |
pub fn init(&mut self) {
// compile sass
// try to get file names
let temp_params = self.scss_params.clone();
let styles_dir = match temp_params.dir {
Some(d) => d,
None => "styles".to_owned(),
};
let scss_file = match temp_params.scss_file {
... | {
self.data_file = Some(new_file);
} | identifier_body |
mod.rs | use std::collections::{HashMap, BTreeMap};
use std::f64;
use std::path::PathBuf;
use std::process::Command;
use chrono::NaiveDate;
// use std::process::Command;
use postgres::Connection;
use postgres::params::IntoConnectParams;
use nickel::{Nickel, HttpRouter, Router};
use super::data_structs::main_page_data::MainPa... | fn main_page(&self) -> MainPageData {
if self.conn.is_none() {
panic!("No connection");
}
MainPageData { countries: Vec::new() }
}
}
impl ScssParams {
fn new() -> ScssParams {
ScssParams {
dir: None,
scss_file: None,
css_file: ... |
self.server.listen("127.0.0.1:6767");
} | random_line_split |
Complete_pt-PT.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="pt-PT" sourcelanguage="en">
<context>
<name>CmdCompleteConstraintAxle</name>
<message>
<location filename="../../Command.cpp" line="+42"/>
<source>Complete</source>
<translation>Concluído</translation>
<... | </context>
</TS> | random_line_split | |
configuration.py | from logger import log
import os
import gconf
import urllib
class Configuration(object):
def | (self):
self._config = {}
self._file_path = os.path.join(os.path.dirname(__file__), 'config',
'config.ini')
# Read Files
self._read_file()
def get_value(self, key):
if key in self._config:
log.debug("[Config] Getting Value for %s" % key)
... | __init__ | identifier_name |
configuration.py | from logger import log
import os
import gconf
import urllib
class Configuration(object):
def __init__(self):
self._config = {}
self._file_path = os.path.join(os.path.dirname(__file__), 'config',
'config.ini')
# Read Files
self._read_file()
def get_value(self, key... | value = value.replace("'", "")
if value.find(",") > -1:
self.set_value(name, [v.strip() for v in value.split(',')])
else:
self.set_value(name, value)
log.info("[Config] Config Map = %s", self._config) | random_line_split | |
configuration.py | from logger import log
import os
import gconf
import urllib
class Configuration(object):
| def set_value(self, key, value):
self._config[key] = value
self._write_file()
def _write_file(self):
f = file(self._file_path, "wb")
config_list = [("%s=%s\n" % (key, value)) for key,
value in self._config.iteritems()]
f.writelines(config_list)
f.clos... | def __init__(self):
self._config = {}
self._file_path = os.path.join(os.path.dirname(__file__), 'config',
'config.ini')
# Read Files
self._read_file()
def get_value(self, key):
if key in self._config:
log.debug("[Config] Getting Value for %s" % key)
... | identifier_body |
configuration.py | from logger import log
import os
import gconf
import urllib
class Configuration(object):
def __init__(self):
self._config = {}
self._file_path = os.path.join(os.path.dirname(__file__), 'config',
'config.ini')
# Read Files
self._read_file()
def get_value(self, key... |
elif value == "False":
return False
return value
else:
return None
def set_value(self, key, value):
self._config[key] = value
self._write_file()
def _write_file(self):
f = file(self._file_path, "wb")
config_list = [("... | return True | conditional_block |
lib.rs | //! A library for creating and modifying Tree structures.
//!
//! ## Overview
//! In this implementation, the `Tree` owns all of the `Node`s and all inter-`Node` relationships
//! are managed with `NodeId`s.
//!
//! `Tree`s in this library are "just" trees. They do not allow cycles. They do not allow
//! the creation... | //! use id_tree::InsertBehavior::*;
//!
//! // 0
//! // / \
//! // 1 2
//! // / \
//! // 3 4
//! let mut tree: Tree<i32> = TreeBuilder::new()
//! .with_node_capacity(5)
//! .build();
//!
//! let root_id: NodeId = tree.insert(Node::new(0), AsRoot).unwrap... | //!
//! fn main() { | random_line_split |
lib.rs | //! A library for creating and modifying Tree structures.
//!
//! ## Overview
//! In this implementation, the `Tree` owns all of the `Node`s and all inter-`Node` relationships
//! are managed with `NodeId`s.
//!
//! `Tree`s in this library are "just" trees. They do not allow cycles. They do not allow
//! the creation... | {
tree_id: ProcessUniqueId,
index: usize,
}
| NodeId | identifier_name |
building.py | FLAGS'] = src_group['LINKFLAGS'] + group['LINKFLAGS']
else:
src_group['LINKFLAGS'] = group['LINKFLAGS']
if group.has_key('LIBS'):
if src_group.has_key('LIBS'):
src_group['LIBS'] = src_group['LIBS'] + group['LIBS']
else:
src_group['LIBS'] = group['LIBS']
... | file_path_exist | identifier_name | |
building.py |
# add program path
env.PrependENVPath('PATH', rtconfig.EXEC_PATH)
# add library build action
act = SCons.Action.Action(BuildLibInstallAction, 'Install compiled library... $TARGET')
bld = Builder(action = act)
Env.Append(BUILDERS = {'BuildLib': bld})
# parse rtconfig.h to get used compone... | os.environ['PATH'] = rtconfig.EXEC_PATH + ":" + os.environ['PATH'] | conditional_block | |
building.py | .has_key('LIBS'): group['LIBS'] = group['LIBS'] + [GroupLibName(name, Env)]
else : group['LIBS'] = [GroupLibName(name, Env)]
if group.has_key('LIBPATH'): group['LIBPATH'] = group['LIBPATH'] + [GetCurrentDir()]
else : group['LIBPATH'] = [GetCurrentDir()]
if group.has_key('LIBS'):
Env... | source_list = target_list
# get source path
src_dir = []
for src in source_list:
src = src.replace(RTT_ROOT, '') | random_line_split | |
building.py | GroupLibName(name, env) + env['LIBSUFFIX']
def BuildLibInstallAction(target, source, env):
lib_name = GetOption('buildlib')
for Group in Projects:
if Group['name'] == lib_name:
lib_name = GroupLibFullName(Group['name'], env)
dst_name = os.path.join(Group['path'], lib_name)
... | global source_ext
source_ext = []
source_ext = ["h", "xpm"]
global source_list
global Rtt_Root
global Env
target_path = os.path.join(Dir('#').abspath, 'rt-thread')
if Env['PLATFORM'] == 'win32':
RTT_ROOT = Rtt_Root.lower()
else:
RTT_ROOT = Rtt_Root
if target_path.s... | identifier_body | |
login.component.ts | import {Component, OnInit, ViewChild, ElementRef, Renderer, AfterViewInit} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {ToastsManager} from 'ng2-toastr';
import {Router} from '@angular/router';
import {AuthService} from '../../auth/auth.service';
import {... | () {
this.email = new FormControl('', [Validators.required, this.emailValidator]);
this.password = new FormControl('', [Validators.required, Validators.minLength(6)]);
this.myForm = this.fb.group({
email : this.email,
password: this.password
});
// check if the user is logged in w... | ngOnInit | identifier_name |
login.component.ts | import {Component, OnInit, ViewChild, ElementRef, Renderer, AfterViewInit} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {ToastsManager} from 'ng2-toastr';
import {Router} from '@angular/router';
import {AuthService} from '../../auth/auth.service';
import {... |
// input validator to check if the email entered by the user is actually text in an email form
emailValidator(control) {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
if (!EMAIL_REGEXP.test(control.value)) {
return {invalidEm... | {
const user = new User(this.myForm.value.email, this.myForm.value.password);
this.authService.signin(user)
.subscribe(
data => {
// if the user credentials are correct, set the localStorage token and userId,
// we need these info in order to do stuff later when the user is sig... | identifier_body |
login.component.ts | import {Component, OnInit, ViewChild, ElementRef, Renderer, AfterViewInit} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {ToastsManager} from 'ng2-toastr';
import {Router} from '@angular/router';
import {AuthService} from '../../auth/auth.service';
import {... | email : this.email,
password: this.password
});
// check if the user is logged in while trying to access the login page, if the user is logged in, we redirect him to the form page
if (this.authService.isLoggedIn()) {
this.toastr.info('You are already logged in');
this.router.navig... | ngOnInit() {
this.email = new FormControl('', [Validators.required, this.emailValidator]);
this.password = new FormControl('', [Validators.required, Validators.minLength(6)]);
this.myForm = this.fb.group({ | random_line_split |
login.component.ts | import {Component, OnInit, ViewChild, ElementRef, Renderer, AfterViewInit} from '@angular/core';
import {FormGroup, FormControl, FormBuilder, Validators} from '@angular/forms';
import {ToastsManager} from 'ng2-toastr';
import {Router} from '@angular/router';
import {AuthService} from '../../auth/auth.service';
import {... |
}
ngAfterViewInit() {
setTimeout(() => {
this.renderer.invokeElementMethod(this.userEmail.nativeElement, 'focus', []);
}, 50);
}
// submit the login form with the user credentials and navigate the user to the index page of our app
onSubmit() {
const user = new User(this.myForm.value.email... | {
this.toastr.info('You are already logged in');
this.router.navigate(['/']);
} | conditional_block |
wunderkind-network-config.js | import {buildUrl} from '#ads/google/a4a/shared/url-builder';
import {Services} from '#service';
/**
* @implements {./ad-network-config.AdNetworkConfigDef}
*/
export class WunderkindNetworkConfig {
/**
* @param {!Element} autoAmpAdsElement
*/
constructor(autoAmpAdsElement) {
this.autoAmpAdsElement_ = a... | () {
const attributes = {
'type': 'wunderkind',
'data-ad': 'wunderkind',
'layout': 'responsive',
'height': '75vw',
'width': '100vw',
};
return attributes;
}
/** @override */
getDefaultAdConstraints() {
const viewportHeight = Services.viewportForDoc(
this.autoAm... | getAttributes | identifier_name |
wunderkind-network-config.js | import {buildUrl} from '#ads/google/a4a/shared/url-builder';
import {Services} from '#service';
/**
* @implements {./ad-network-config.AdNetworkConfigDef}
*/
export class WunderkindNetworkConfig {
/**
* @param {!Element} autoAmpAdsElement
*/
constructor(autoAmpAdsElement) {
this.autoAmpAdsElement_ = a... |
/** @override */
getConfigUrl() {
const docInfo = Services.documentInfoForDoc(this.autoAmpAdsElement_);
const websiteID = this.autoAmpAdsElement_.getAttribute('data-website-id');
return buildUrl(
'https://api.bounceexchange.com/bounce/amp',
{
'w_id': websiteID,
'calling_ur... | {
return true;
} | identifier_body |
wunderkind-network-config.js | import {buildUrl} from '#ads/google/a4a/shared/url-builder';
import {Services} from '#service';
/**
* @implements {./ad-network-config.AdNetworkConfigDef}
*/
export class WunderkindNetworkConfig {
/**
* @param {!Element} autoAmpAdsElement
*/
constructor(autoAmpAdsElement) {
this.autoAmpAdsElement_ = a... | filterConfig(config) {
return config;
}
/** @override */
getAttributes() {
const attributes = {
'type': 'wunderkind',
'data-ad': 'wunderkind',
'layout': 'responsive',
'height': '75vw',
'width': '100vw',
};
return attributes;
}
/** @override */
getDefaultAdCo... | 4096
);
}
/** @override */ | random_line_split |
split_on_dash.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2013 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... | if indices:
node.partition(indices) | random_line_split | |
split_on_dash.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2013 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... | def __init__(self):
Transformer.__init__(self, 245)
def process(self, mtree, options=None):
"""split into '-' separated subgroups (with required separator chars
around the dash)
"""
for node in mtree.unidentified_leaves():
indices = []
pattern = re.c... | identifier_body | |
split_on_dash.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2013 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... | (self, mtree, options=None):
"""split into '-' separated subgroups (with required separator chars
around the dash)
"""
for node in mtree.unidentified_leaves():
indices = []
pattern = re.compile(sep + '-' + sep)
match = pattern.search(node.value)
... | process | identifier_name |
split_on_dash.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2013 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... | indices = []
pattern = re.compile(sep + '-' + sep)
match = pattern.search(node.value)
while match:
span = match.span()
indices.extend([span[0], span[1]])
match = pattern.search(node.value, span[1])
if indices:
... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.