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 |
|---|---|---|---|---|
Enums.py | from enum import Enum
class EventType(Enum):
"""Enum containing the various types of events that can occur."""
CLIENT_READY = "CLIENT_READY"
CLIENT_RESUMED = "CLIENT_RESUMED"
MESSAGE_RECEIVED = "MESSAGE_RECEIVED"
SERVER_MESSAGE_RECEIVED = "SERVER_MESSAGE_RECEIVED"
PRIVATE_MESSAGE_RECEIVED = "... | """Enum containing the possible Redis storage scopes."""
GLOBAL = "GLOBAL"
PLUGIN = "PLUGIN"
SERVER = "SERVER"
CHANNEL = "CHANNEL"
USER = "USER" | identifier_body | |
Enums.py | from enum import Enum
class EventType(Enum):
"""Enum containing the various types of events that can occur."""
CLIENT_READY = "CLIENT_READY"
CLIENT_RESUMED = "CLIENT_RESUMED"
MESSAGE_RECEIVED = "MESSAGE_RECEIVED"
SERVER_MESSAGE_RECEIVED = "SERVER_MESSAGE_RECEIVED"
PRIVATE_MESSAGE_RECEIVED = "... |
MEMBER_JOINED_GROUP = "MEMBER_JOINED_GROUP"
MEMBER_REMOVED_FROM_GROUP = "MEMBER_REMOVED_FROM_GROUP"
SERVER_EMOJIS_UPDATED = "SERVER_EMOJIS_UPDATED"
class RedisStorageScope(Enum):
"""Enum containing the possible Redis storage scopes."""
GLOBAL = "GLOBAL"
PLUGIN = "PLUGIN"
SERVER = "SERVER... | VOICE_STATE_UPDATED = "VOICE_STATE_UPDATED"
REACTION_ADDED = "REACTION_ADDED"
REACTION_REMOVED = "REACTION_REMOVED"
REACTIONS_CLEARED = "REACTIONS_CLEARED" | random_line_split |
VDataTableHeader.ts | // Styles
import './VDataTableHeader.sass'
// Components
import VDataTableHeaderMobile from './VDataTableHeaderMobile'
import VDataTableHeaderDesktop from './VDataTableHeaderDesktop'
// Mixins
import header from './mixins/header'
// Utilities
import dedupeModelListeners from '../../util/dedupeModelListeners'
import ... | (h, { props, data, slots }) {
dedupeModelListeners(data)
const children = rebuildSlots(slots(), h)
data = mergeData(data, { props })
if (props.mobile) {
return h(VDataTableHeaderMobile, data, children)
} else {
return h(VDataTableHeaderDesktop, data, children)
}
},
})
| render | identifier_name |
VDataTableHeader.ts | // Styles
import './VDataTableHeader.sass'
// Components
import VDataTableHeaderMobile from './VDataTableHeaderMobile'
import VDataTableHeaderDesktop from './VDataTableHeaderDesktop'
// Mixins
import header from './mixins/header'
// Utilities
import dedupeModelListeners from '../../util/dedupeModelListeners'
import ... | ,
})
| {
dedupeModelListeners(data)
const children = rebuildSlots(slots(), h)
data = mergeData(data, { props })
if (props.mobile) {
return h(VDataTableHeaderMobile, data, children)
} else {
return h(VDataTableHeaderDesktop, data, children)
}
} | identifier_body |
VDataTableHeader.ts | // Styles
import './VDataTableHeader.sass'
// Components
import VDataTableHeaderMobile from './VDataTableHeaderMobile'
import VDataTableHeaderDesktop from './VDataTableHeaderDesktop'
// Mixins
import header from './mixins/header'
// Utilities
import dedupeModelListeners from '../../util/dedupeModelListeners'
import ... |
},
})
| {
return h(VDataTableHeaderDesktop, data, children)
} | conditional_block |
VDataTableHeader.ts | // Styles
import './VDataTableHeader.sass'
// Components
import VDataTableHeaderMobile from './VDataTableHeaderMobile'
import VDataTableHeaderDesktop from './VDataTableHeaderDesktop'
// Mixins
import header from './mixins/header'
// Utilities
import dedupeModelListeners from '../../util/dedupeModelListeners'
import ... | return h(VDataTableHeaderDesktop, data, children)
}
},
}) | return h(VDataTableHeaderMobile, data, children)
} else { | random_line_split |
log.py | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2015] Michał Szczygieł, M4GiK Software
#
# 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... | """
get_logger(logger_id).info(text)
def warning(logger_id, text):
"""
@parameter{logger_id,int} optional, id of the logger. If no logger_id is provided,
logs are anonymous.
@parameter{text,string} content of the log.
Prints warning log with @prm{text} content to log file of the user @prm{... | random_line_split | |
log.py | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2015] Michał Szczygieł, M4GiK Software
#
# 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... |
def exception(logger_id, text):
"""
@parameter{logger_id,int} optional, id of the logger. If no id is provided,
logs are anonymous.
@parameter{text,string} content of the log.
Prints exception log with @prm{text} content to log file of the user @prm{logger_id}.
"""
get_logger(logger_id).exc... | "
@parameter{logger_id,int} optional, id of the logger. If no logger_id is provided,
logs are anonymous.
@parameter{text,string} content of the log.
Prints warning log with @prm{text} content to log file of the user @prm{logger_id}.
"""
get_logger(logger_id).warning(text)
| identifier_body |
log.py | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2015] Michał Szczygieł, M4GiK Software
#
# 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... | else:
log_name = 'no_user'
logger_id = 0
if logger_id in active_loggers:
return logging.getLogger(log_name)
active_loggers.add(logger_id)
logger = logging.getLogger(log_name)
hdlr = logging.FileHandler(os.path.join(config.LOG_DIR, '%s.log' % log_name))
formatter = logging... | g_name = 'user_%d' % logger_id
| conditional_block |
log.py | # -*- coding: utf-8 -*-
# @COPYRIGHT_begin
#
# Copyright [2015] Michał Szczygieł, M4GiK Software
#
# 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... | ogger_id, text):
"""
@parameter{logger_id,int} optional, id of the logger. If no id is provided,
logs are anonymous.
@parameter{text,string} content of the log.
Prints exception log with @prm{text} content to log file of the user @prm{logger_id}.
"""
get_logger(logger_id).exception(text)
d... | ception(l | identifier_name |
app.js | /**
* @ngdoc overview
* @name ngmNutrition
* @description
* # ngmNutrition
*
* Main module of the application.
*/
angular
.module('ngmNutrition', [])
.config([ '$routeProvider', '$compileProvider', function ( $routeProvider, $compileProvider) {
// https://medium.com/swlh/improving-angular-performance-wit... | });
}]); | resolve: {
access: [ 'ngmAuth', function(ngmAuth) {
return ngmAuth.isAuthenticated();
}],
} | random_line_split |
main.rs | use std::ops::{Add, Sub, Mul, Div};
fn do_operation<F, V>(f: F, v1: V, v2: V) -> V
where
F: Fn(V, V) -> V,
V: Add + Sub + Mul + Div {
f(v1, v2)
}
pub fn rpn(raw: &str) -> f64 {
let mut stack = Vec::new();
for c in raw.split(' ') {
if let Some(i) = c.parse::<f64>().ok() {
... |
#[test]
fn long_equation() {
let mut eq = "2 ".to_string();
for _ in 0..2000000 {
eq.push_str("2 + ");
}
eq.push_str("1 +");
assert_eq!(4000003.0, rpn(&eq));
}
} | {
rpn("54 4 6 O + \\ /");
} | identifier_body |
main.rs | use std::ops::{Add, Sub, Mul, Div};
fn do_operation<F, V>(f: F, v1: V, v2: V) -> V
where
F: Fn(V, V) -> V,
V: Add + Sub + Mul + Div {
f(v1, v2)
}
pub fn rpn(raw: &str) -> f64 {
let mut stack = Vec::new();
for c in raw.split(' ') {
if let Some(i) = c.parse::<f64>().ok() {
... | () {
assert_eq!(-2503.0, rpn("2 0 /"));
}
#[test]
#[should_panic]
fn invalid_input_1() {
rpn("");
}
#[test]
#[should_panic]
fn invalid_input_2() {
rpn("14 4 6 8 + . /");
}
#[test]
#[should_panic]
fn invalid_input_3() {
rpn("POTATO");
... | divide_by_zero | identifier_name |
main.rs | use std::ops::{Add, Sub, Mul, Div};
fn do_operation<F, V>(f: F, v1: V, v2: V) -> V
where
F: Fn(V, V) -> V,
V: Add + Sub + Mul + Div {
f(v1, v2)
}
pub fn rpn(raw: &str) -> f64 {
let mut stack = Vec::new();
for c in raw.split(' ') {
if let Some(i) = c.parse::<f64>().ok() {
... | if r == 0.0
{
panic!("Division by zero not allowed");
}
do_operation(|l, r| l / r, l, r)
},
_ => panic!("Unknown character {:?}", c),
};
stack.push(result);
}
if stack.len() != 1
{... | "+" => do_operation(|l, r| l + r, l, r),
"-" => do_operation(|l, r| l - r, l, r),
"*" => do_operation(|l, r| l * r, l, r),
"/" =>
{ | random_line_split |
index.d.ts | // Type definitions for sails.io.js 1.0.1
// Project: http://sailsjs.org/documentation/reference/web-sockets/socket-client
// Definitions by: Arvitaly <https://github.com/arvitaly/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="socket.io-client"/>
declare namespace SailsIOJS... | headers?: Headers;
params?: any;
data?: any;
}
export interface JWR {
headers: Headers;
statusCode: number;
body: any;
error?: Error;
toString: () => string;
toPOJO: () => {
body: any;
headers: Headers;
s... | url: string;
method?: string; | random_line_split |
eth.rs | ()),
None => Err(errors::state_pruned()),
};
Box::new(future::done(res))
}
fn storage_at(&self, address: RpcH160, pos: RpcU256, num: Trailing<BlockNumber>) -> BoxFuture<RpcH256> {
let address: Address = RpcH160::into(address);
let position: U256 = RpcU256::into(pos);
let id = num.unwrap_or_default();
... |
if no_new_work_timeout > 0 && b.block().header().timestamp() + no_new_work_timeout < get_time().sec as u64 {
Err(errors::no_new_work())
} else if self.options.send_block_number_in_get_work {
let block_number = b.block().header().number(); | random_line_split | |
eth.rs | uture::ok(match num {
BlockNumber::Pending => Some(
self.miner.status().transactions_in_pending_block.into()
),
_ =>
self.client.block(num.into())
.map(|block| block.transactions_count().into())
}))
}
fn block_uncles_count_by_hash(&self, hash: RpcH256) -> BoxFuture<Option<RpcU256>> {
Box::n... | {
self.send_raw_transaction(raw)
} | identifier_body | |
eth.rs | ();
let result = pending_logs.into_iter()
.filter(|pair| filter.matches(&pair.1))
.map(|pair| {
let mut log = Log::from(pair.1);
log.transaction_hash = Some(pair.0.into());
log
})
.collect();
result
}
fn check_known<C>(client: &C, number: BlockNumber) -> Result<()> where C: MiningBlockChainClient ... | transaction_by_block_hash_and_index | identifier_name | |
MasteryEffectiveness.js | not be used for stat weights as stat weights already account for overhealing and it would throw off the calculation. It's also misleading for analysis for various reasons.
* Option D suffers from the same problems as option C, but with the benefits from option B.
* Option B is the best choice. It gets the right aver... | display: 'inline-block',
}} | random_line_split | |
MasteryEffectiveness.js | towards the tiny heals.
*
* B. Get average adjusted for healing amount.
* This gets the average based on the amount healed. This ignores the health pool of the target (and thus overhealing). A 999 tiny heals and 1 huge heal will lean more towards the huge heal.
*
* C. Get average adjusted for target health.
* Th... |
const heal = new HealingValue(event.amount, event.absorbed, event.overheal);
const applicableMasteryPercentage = this.statTracker.currentMasteryPercentage * masteryEffectiveness;
// The base healing of the spell (excluding any healing added by mastery)
const baseHealing = heal.raw / (1 + applicableMas... | {
if (!this._lastPlayerPositionUpdate) {
console.error('Received a heal before we know the player location. Can\'t process since player location is still unknown.', event);
return;
}
const isAbilityAffectedByMastery = ABILITIES_AFFECTED_BY_MASTERY.includes(event.ability.guid);
if (!isAbility... | identifier_body |
MasteryEffectiveness.js | towards the tiny heals.
*
* B. Get average adjusted for healing amount.
* This gets the average based on the amount healed. This ignores the health pool of the target (and thus overhealing). A 999 tiny heals and 1 huge heal will lean more towards the huge heal.
*
* C. Get average adjusted for target health.
* Th... |
}
processForMasteryEffectiveness(event) {
if (!this._lastPlayerPositionUpdate) {
console.error('Received a heal before we know the player location. Can\'t process since player location is still unknown.', event);
return;
}
const isAbilityAffectedByMastery = ABILITIES_AFFECTED_BY_MASTERY.in... | {
this.processForMasteryEffectiveness(event);
} | conditional_block |
MasteryEffectiveness.js | more towards the tiny heals.
*
* B. Get average adjusted for healing amount.
* This gets the average based on the amount healed. This ignores the health pool of the target (and thus overhealing). A 999 tiny heals and 1 huge heal will lean more towards the huge heal.
*
* C. Get average adjusted for target health.
... | (event) {
if (this.owner.toPlayer(event)) {
this.updatePlayerPosition(event);
}
}
on_heal(event) {
if (this.owner.toPlayer(event)) {
// Do this before checking if this was done by player so that self-heals will apply full mastery properly
this.updatePlayerPosition(event);
}
if... | on_energize | identifier_name |
drop_out.py | from quex.engine.generator.languages.address import Address
from quex.blackboard import E_EngineTypes, E_AcceptanceIDs, E_StateIndices, \
E_TransitionN, E_PostContextIDs, E_PreContextIDs, \
... | txt.append(' __quex_debug("backward input position %i detected\\n");\n' % \
TheAnalyzer.state_machine_id)
txt.append(" %s\n\n" % LanguageDB.INPUT_P_INCREMENT())
txt.append(" goto %s;\n" \
% LanguageDB.LABEL_NAME_BACKWARD_INPUT_PO... | # => TheAnalyzer.state_machine_id = id of the backward input position detector. | random_line_split |
drop_out.py | from quex.engine.generator.languages.address import Address
from quex.blackboard import E_EngineTypes, E_AcceptanceIDs, E_StateIndices, \
E_TransitionN, E_PostContextIDs, E_PreContextIDs, \
... | (txt, TheState, TheAnalyzer, DefineLabelF=True, MentionStateIndexF=True):
LanguageDB = Setup.language_db
if DefineLabelF:
txt.append(Address("$drop-out", TheState.index))
if MentionStateIndexF:
txt.append(" __quex_debug_drop_out(%i);\n" % TheState.index)
if TheAnalyzer.eng... | do | identifier_name |
drop_out.py | from quex.engine.generator.languages.address import Address
from quex.blackboard import E_EngineTypes, E_AcceptanceIDs, E_StateIndices, \
E_TransitionN, E_PostContextIDs, E_PreContextIDs, \
... |
else: register = None
case_list.append((LanguageDB.ACCEPTANCE(element.acceptance_id),
"%s %s" % \
(LanguageDB.POSITIONING(element.positioning, register),
LanguageDB.GOTO_TERMINAL(elem... | register = element.position_register | conditional_block |
drop_out.py | from quex.engine.generator.languages.address import Address
from quex.blackboard import E_EngineTypes, E_AcceptanceIDs, E_StateIndices, \
E_TransitionN, E_PostContextIDs, E_PreContextIDs, \
... | % LanguageDB.LABEL_NAME_BACKWARD_INPUT_POSITION_RETURN(TheAnalyzer.state_machine_id))
return
info = TheState.drop_out.trivialize()
# (1) Trivial Solution
if info is not None:
for i, easy in enumerate(info):
positioning_str = ""
if easy[1].posit... | LanguageDB = Setup.language_db
if DefineLabelF:
txt.append(Address("$drop-out", TheState.index))
if MentionStateIndexF:
txt.append(" __quex_debug_drop_out(%i);\n" % TheState.index)
if TheAnalyzer.engine_type == E_EngineTypes.BACKWARD_PRE_CONTEXT:
txt.append(" %s\n" ... | identifier_body |
basic_lib.rs | #![ warn( missing_docs ) ]
#![ warn( missing_debug_implementations ) ]
#![ allow( dead_code ) ]
// #![no_std]
//!
//! Tools for writing and runnint tests.
//!
//! # Sample
//! ``` rust
//! use wtest_basic::*;
//!
//! //
//!
//! fn _pass1()
//! {
//! assert_eq!( true, true );
//! }
//!
//! //
//!
//! fn _pass2()
//! ... | // $( #[test] fn paste!([< $Name _test >])() { $Name() } )*
// }
}
// /// Pass only if callback fails either returning error or panicing.
//
// pub fn should_throw< R, F : FnOnce() -> anyhow::Result< R > >( f : F ) -> anyhow::Result< R >
// {
// f()
// }
//
// #[panic_handler]
// fn panic( info : &core::pani... | random_line_split | |
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts... |
dest.write_str("at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
| {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
} | conditional_block |
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts... |
}
| {
dest.write_str("ellipse(")?;
if (self.semiaxis_x, self.semiaxis_y) != Default::default() {
self.semiaxis_x.to_css(dest)?;
dest.write_str(" ")?;
self.semiaxis_y.to_css(dest)?;
dest.write_str(" ")?;
}
dest.write_str("at ")?;
self.po... | identifier_body |
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts... | pub type BasicShape = GenericBasicShape<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// The computed value of `inset()`
pub type InsetRect = GenericInsetRect<LengthOrPercentage>;
/// A computed circle.
pub type Circle = GenericCircle<LengthOrPercentage, LengthOrPercentage, LengthOrPercentage>;
/// A... | random_line_split | |
basic_shape.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/. */
//! CSS handling for the computed value of
//! [`basic-shape`][basic-shape]s
//!
//! [basic-shape]: https://drafts... | <W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
dest.write_str("circle(")?;
self.radius.to_css(dest)?;
dest.write_str(" at ")?;
self.position.to_css(dest)?;
dest.write_str(")")
}
}
impl ToCss for Ellipse {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result wh... | to_css | identifier_name |
myutil.py | # -*- coding: utf-8 -*-
"""
This module put my utility functions
"""
__author__ = "Jiang Yu-Kuan <yukuan.jiang@gmail.com>"
__date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)"
import re
import os
import sys
#------------------------------------------------------------------------------
... | (string):
"""Return camel case string from a space-separated string.
Example
-------
>>> camel_case('good job')
'GoodJob'
"""
return ''.join(w.capitalize() for w in string.split())
def replace_punctuations(text):
"""Replace punctuation characters with abbreviations for a s... | camel_case | identifier_name |
myutil.py | # -*- coding: utf-8 -*-
"""
This module put my utility functions
"""
__author__ = "Jiang Yu-Kuan <yukuan.jiang@gmail.com>"
__date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)"
import re
import os
import sys
#------------------------------------------------------------------------------
... |
#------------------------------------------------------------------------------
# String
#------------------------------------------------------------------------------
def replace_chars(text, replaced_pairs='', deleted_chars=''):
"""Return a char replaced text.
Arguments
---------
text... | try:
_offset = int(eval(str))
except:
return False
return True | identifier_body |
myutil.py | # -*- coding: utf-8 -*-
"""
This module put my utility functions
"""
__author__ = "Jiang Yu-Kuan <yukuan.jiang@gmail.com>"
__date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)"
import re
import os
import sys
#------------------------------------------------------------------------------
... |
Example
-------
>>> c_identifier("Hello World")
'HelloWorld'
>>> c_identifier("Anti-Shake")
'Antishake'
"""
if ' ' in text:
text = camel_case(text)
text = re.sub(r'\+\d+', lambda x: x.group().replace('+', 'P'), text)
text = re.sub(r'\-\d+', lambda x: x.group()... | # For code generation
#------------------------------------------------------------------------------
def c_identifier(text):
"""Convert input text into an legal identifier in C.
| random_line_split |
myutil.py | # -*- coding: utf-8 -*-
"""
This module put my utility functions
"""
__author__ = "Jiang Yu-Kuan <yukuan.jiang@gmail.com>"
__date__ = "2016/02/08 (initial version) ~ 2019/04/17 (last revision)"
import re
import os
import sys
#------------------------------------------------------------------------------
... |
return text
def camel_case(string):
"""Return camel case string from a space-separated string.
Example
-------
>>> camel_case('good job')
'GoodJob'
"""
return ''.join(w.capitalize() for w in string.split())
def replace_punctuations(text):
"""Replace punctuation ... | text = text.replace(ch, '') | conditional_block |
selectors.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 cssparser::{Parser, ParserInput, ToCss};
use selectors::parser::SelectorList;
use style::selector_parser::{Sel... | <'i, 't>(input: &mut Parser<'i, 't>) -> Result<SelectorList<SelectorImpl>, ParseError<'i>> {
let mut ns = Namespaces::default();
ns.prefixes.insert("svg".into(), (ns!(svg), ()));
let parser = SelectorParser {
stylesheet_origin: Origin::UserAgent,
namespaces: &ns,
};
SelectorList::par... | parse_selector | identifier_name |
selectors.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 cssparser::{Parser, ParserInput, ToCss};
use selectors::parser::SelectorList;
use style::selector_parser::{Sel... |
#[test]
fn test_selectors() {
assert_roundtrip!(parse_selector, "div");
assert_roundtrip!(parse_selector, "svg|circle");
assert_roundtrip!(parse_selector, "p:before", "p::before");
assert_roundtrip!(parse_selector, "[border=\"0\"]:-servo-nonzero-border ~ ::-servo-details-summary");
}
| {
let mut ns = Namespaces::default();
ns.prefixes.insert("svg".into(), (ns!(svg), ()));
let parser = SelectorParser {
stylesheet_origin: Origin::UserAgent,
namespaces: &ns,
};
SelectorList::parse(&parser, input)
} | identifier_body |
selectors.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 cssparser::{Parser, ParserInput, ToCss};
use selectors::parser::SelectorList;
use style::selector_parser::{SelectorImpl, SelectorParser};
use style::stylesheets::{Origin, Namespaces... | random_line_split | |
stack.rs | // Copyright 2016 coroutine-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 accordi... |
return ret.map_err(StackError::IoError);
}
}
Err(StackError::ExceedsMaximumSize(max_stack_size - add))
}
}
unsafe impl Send for Stack {}
/// A very simple and straightforward implementation of `Stack`.
///
/// Allocates stack space using virtual memory, whose pages w... | {
if let Ok(stack) = ret {
ret = unsafe { sys::protect_stack(&stack) };
}
} | conditional_block |
stack.rs | // Copyright 2016 coroutine-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 accordi... |
}
/// Represents any kind of stack memory.
///
/// `FixedSizeStack` as well as `ProtectedFixedSizeStack`
/// can be used to allocate actual stack space.
#[derive(Debug)]
pub struct Stack {
top: *mut c_void,
bottom: *mut c_void,
}
impl Stack {
/// Creates a (non-owning) representation of some stack memory... | {
match *self {
StackError::ExceedsMaximumSize(_) => None,
StackError::IoError(ref e) => Some(e),
}
} | identifier_body |
stack.rs | // Copyright 2016 coroutine-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 accordi... | {
/// Contains the maximum amount of memory allowed to be allocated as stack space.
ExceedsMaximumSize(usize),
/// Returned if some kind of I/O error happens during allocation.
IoError(io::Error),
}
impl Display for StackError {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
match *sel... | StackError | identifier_name |
stack.rs | // Copyright 2016 coroutine-rs Developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 accordi... | assert_eq!(stack.len(), sys::min_stack_size());
unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
}
#[test]
fn stack_size_too_large() {
let stack_size = sys::max_stack_size() & !(sys::page_size() - 1);
match FixedSizeStack::new(stack_size) {
... | unsafe { write_bytes(stack.bottom() as *mut u8, 0x1d, stack.len()) };
let stack = ProtectedFixedSizeStack::new(0).unwrap(); | random_line_split |
Component.d.ts | import { Entity } from './Entity';
export interface ComponentCtor {
new (): Component;
}
/**
* Components are containers for state in Excalibur, the are meant to convey capabilities that an Entity posesses
*
* Implementations of Component must have a zero-arg constructor
*/
export declare abstract clas... | } | export declare class TagComponent<TypeName extends string, MaybeValueType extends string | symbol | number | boolean = never> extends Component<TypeName> {
readonly type: TypeName;
readonly value?: MaybeValueType;
constructor(type: TypeName, value?: MaybeValueType);
| random_line_split |
Component.d.ts | import { Entity } from './Entity';
export interface ComponentCtor {
new (): Component;
}
/**
* Components are containers for state in Excalibur, the are meant to convey capabilities that an Entity posesses
*
* Implementations of Component must have a zero-arg constructor
*/
export declare abstract clas... | <TypeName extends string, MaybeValueType extends string | symbol | number | boolean = never> extends Component<TypeName> {
readonly type: TypeName;
readonly value?: MaybeValueType;
constructor(type: TypeName, value?: MaybeValueType);
}
| TagComponent | identifier_name |
strings.py | """
sentry.utils.strings
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import base64
import zlib
from django.utils.encoding import smart_unicode
def truncatechars(value, arg):
... |
def strip(value):
if not value:
return ''
return smart_unicode(value).strip()
| return zlib.decompress(value, 16 + zlib.MAX_WBITS) | identifier_body |
strings.py | """
sentry.utils.strings
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import base64
import zlib
from django.utils.encoding import smart_unicode
def truncatechars(value, arg):
... |
return smart_unicode(value).strip()
| return '' | conditional_block |
strings.py | """
sentry.utils.strings
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import base64
import zlib
from django.utils.encoding import smart_unicode
def truncatechars(value, arg):
... | (value):
if not value:
return ''
return smart_unicode(value).strip()
| strip | identifier_name |
strings.py | """
sentry.utils.strings
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import base64
import zlib
from django.utils.encoding import smart_unicode
def truncatechars(value, arg):
... | return value
def compress(value):
return base64.b64encode(zlib.compress(value))
def decompress(value):
return zlib.decompress(base64.b64decode(value))
def gunzip(value):
return zlib.decompress(value, 16 + zlib.MAX_WBITS)
def strip(value):
if not value:
return ''
return smart_unic... | random_line_split | |
build.rs | //! This tiny build script ensures that rocket_codegen is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version ... | () {
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(f... | main | identifier_name |
build.rs | //! This tiny build script ensures that rocket_codegen is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version ... | if !ok_channel {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a nightly or dev version of Rust."));
print_version_err(&*version, &*date);
eprintln!("{}{}{}",
... | Yellow.paint(format!("{} ({})", MIN_VERSION, MIN_DATE)));
};
match (ok_channel, ok_version, ok_date) {
(Some(ok_channel), Some((ok_version, version)), Some((ok_date, date))) => { | random_line_split |
build.rs | //! This tiny build script ensures that rocket_codegen is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version ... |
},
_ => {
println!("cargo:warning={}", "Rocket was unable to check rustc compatibility.");
println!("cargo:warning={}", "Build may fail due to incompatible rustc version.");
}
}
}
| {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket codegen requires a more recent version of rustc."));
eprintln!("{}{}{}",
Blue.paint("Use `"),
White.paint("rustup u... | conditional_block |
build.rs | //! This tiny build script ensures that rocket_codegen is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version ... | eprintln!("{}{}{}",
Blue.paint("See the getting started guide ("),
White.paint("https://rocket.rs/guide/getting-started/"),
Blue.paint(") for more information."));
panic!("Aborting compilation due to incompatib... | {
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(form... | identifier_body |
UpdateResourceDialog.tsx | import { FC } from 'react';
import { useDispatch } from 'react-redux';
import { translate } from '@waldur/i18n';
import { closeModalDialog } from '@waldur/modal/actions';
import { showSuccess, showErrorResponse } from '@waldur/store/notify';
import { Resource } from '../types';
import { ResourceActionDialog } from '... |
dispatch(closeModalDialog());
} catch (e) {
dispatch(
showErrorResponse(
e,
translate('Unable to update {verboseName}.', {
verboseName,
}),
),
);
}
}}
dialogTitle={translate('Upda... | {
await reInitResource();
} | conditional_block |
UpdateResourceDialog.tsx | import { FC } from 'react';
import { useDispatch } from 'react-redux';
import { translate } from '@waldur/i18n';
import { closeModalDialog } from '@waldur/modal/actions';
import { showSuccess, showErrorResponse } from '@waldur/store/notify';
import { Resource } from '../types';
import { ResourceActionDialog } from '... | ('Update {resourceType} {resourceName}', {
resourceType: verboseName,
resourceName: resource.name,
})}
fields={fields}
initialValues={initialValues}
/>
);
};
| translate | identifier_name |
UpdateResourceDialog.tsx | import { FC } from 'react';
import { useDispatch } from 'react-redux';
import { translate } from '@waldur/i18n';
import { closeModalDialog } from '@waldur/modal/actions';
import { showSuccess, showErrorResponse } from '@waldur/store/notify';
import { Resource } from '../types';
import { ResourceActionDialog } from '... | resourceType: verboseName,
resourceName: resource.name,
})}
fields={fields}
initialValues={initialValues}
/>
);
}; | }
}}
dialogTitle={translate('Update {resourceType} {resourceName}', { | random_line_split |
UpdateResourceDialog.tsx | import { FC } from 'react';
import { useDispatch } from 'react-redux';
import { translate } from '@waldur/i18n';
import { closeModalDialog } from '@waldur/modal/actions';
import { showSuccess, showErrorResponse } from '@waldur/store/notify';
import { Resource } from '../types';
import { ResourceActionDialog } from '... | );
}
}
}
dialogTitle={translate('Update {resourceType} {resourceName}', {
resourceType: verboseName,
resourceName: resource.name,
})}
fields={fields}
initialValues={initialValues}
/>
);
};
| {
try {
await updateResource(resource.uuid, formData);
dispatch(
showSuccess(
translate('{verboseName} has been updated.', { verboseName }),
),
);
if (reInitResource) {
await reInitResource();
}
dispatc... | identifier_body |
IndexCard.js | var Card = require("./Card");
var CARDS = require("./cards");
var CARDNUM = require("./cardnum");
var api = require("../rpcapi");
var util = require("../util");
var state = require("../state");
var imgUtil = require("../img");
// INDEX -----------------------------------------------------------------------
function In... | Card.prototype.show.call(this);
state.toCard(this);
util.setHeader("Foxi");
util.setSubheader();
util.showBackButton(function() {
CARDS.CONNECTION.activate();
});
};
IndexCard.prototype.load = function() {
var card = this;
card.render('index');
$("a[data-card-link]").on('click', function() {
... | IndexCard.prototype.show = function() { | random_line_split |
IndexCard.js | var Card = require("./Card");
var CARDS = require("./cards");
var CARDNUM = require("./cardnum");
var api = require("../rpcapi");
var util = require("../util");
var state = require("../state");
var imgUtil = require("../img");
// INDEX -----------------------------------------------------------------------
function | () {
Card.call(this, CARDNUM.INDEX, "#card-index");
}
IndexCard.prototype = Object.create(Card.prototype);
IndexCard.prototype.show = function() {
Card.prototype.show.call(this);
state.toCard(this);
util.setHeader("Foxi");
util.setSubheader();
util.showBackButton(function() {
CARDS.CONNECTION.activate(... | IndexCard | identifier_name |
IndexCard.js | var Card = require("./Card");
var CARDS = require("./cards");
var CARDNUM = require("./cardnum");
var api = require("../rpcapi");
var util = require("../util");
var state = require("../state");
var imgUtil = require("../img");
// INDEX -----------------------------------------------------------------------
function In... |
IndexCard.prototype = Object.create(Card.prototype);
IndexCard.prototype.show = function() {
Card.prototype.show.call(this);
state.toCard(this);
util.setHeader("Foxi");
util.setSubheader();
util.showBackButton(function() {
CARDS.CONNECTION.activate();
});
};
IndexCard.prototype.load = function() {
... | {
Card.call(this, CARDNUM.INDEX, "#card-index");
} | identifier_body |
stream_frame_identifier.py | import av
import logging
import random
import sys
import time
import warnings
from livestreamer import Livestreamer
from experiments.test_detecting_in_lol_or_not import get_classifier, process_image
from ocr import ocr_image
logging.getLogger("libav.http").setLevel(logging.ERROR)
# Hide warnings from SKLearn from ... | streams = session.streams('http://www.twitch.tv/%s' % streamer)
if streams:
stream = streams['source']
container = av.open(stream.url)
video_stream = next(s for s in container.streams if s.type == b'video')
image = None
for packet in containe... | session = Livestreamer() | random_line_split |
stream_frame_identifier.py | import av
import logging
import random
import sys
import time
import warnings
from livestreamer import Livestreamer
from experiments.test_detecting_in_lol_or_not import get_classifier, process_image
from ocr import ocr_image
logging.getLogger("libav.http").setLevel(logging.ERROR)
# Hide warnings from SKLearn from ... |
else:
print "Randomly selecting a streamer..."
streamer = random.choice((
"tsm_doublelift",
"grossie_gore",
"wingsofdeath"
))
classifier = get_classifier()
is_in_lol = False
print "Waiting for streamer %s to join a game..." % streamer
w... | streamer = sys.argv[1] | conditional_block |
settings.tsx | import React, { useContext, useEffect } from "react";
import { useParams, useHistory, RouteProps } from "react-router-dom";
import styled from "styled-components";
import _get from "lodash/get";
import { Store } from "../store";
import {
FixedContainer,
Wrapper,
PageHeader,
PageActions
} from "../styled/common"... | return authActions
.updateProfile(values)
.then((d: any) => {
dispatch({
type: actionTypes.UPDATE_PROFILE_SUCCESS,
payload: _get(d, "data", {})
});
})
.catch((err: any) => {
dispatch({
type: actionTypes.UPDATE_PROFILE_FAILURE,
p... | const updateProfile = (values: any) => {
dispatch({ type: actionTypes.UPDATE_PROFILE_REQUEST, payload: {} }); | random_line_split |
AlfMenuGroup.js | /**
* Copyright (C) 2005-2016 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at ... | return declare([AlfDropDownMenu, AlfCore, CoreRwd], {
// TODO: There's an argument that this should actually extend (rather than wrap) the DropDownMenu to avoid needing to delegate the functions
/**
* The HTML template to use for the widget.
* @instance
* @type {string}... | random_line_split | |
AlfMenuGroup.js | /**
* Copyright (C) 2005-2016 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at ... |
}
}
},
/**
* Overrides the inherited function in order to address the additional Alfesco object
* placed in the chain between the Dojo menu objects.
*
* @instance
* @param {object} evt
*/
_onLeftArrow: function(evt) {
if... | {
this.alfLog("log", "Go to next item in menu bar");
menuBarAncestor.focusChild(next);
} | conditional_block |
AnimationManager.ts |
//Signals
this.onChange = new Kiwi.Signal;
this.onPlay = new Kiwi.Signal;
this.onStop = new Kiwi.Signal;
this.onUpdate = new Kiwi.Signal;
}
/**
* Dispatches callbacks each time an animation is told to play through this AnimationManager.
* Functions dispatched from this signal have ONE Paramete... | {
var defaultCells = [];
for (var i = 0; i < this._atlas.cells.length; i++) {
defaultCells.push(i);
}
this.currentAnimation = this.add('default', defaultCells, 0.1, true, false);
} | conditional_block | |
AnimationManager.ts | Dispatches callbacks each time an animation is told to play through this AnimationManager.
* Functions dispatched from this signal have ONE Parameter.
* One - The Animation object of that is now playing.
* @property onPlay
* @type Kiwi.Signal
* @public
*/
public onPlay: Kiwi.Signal;
/**
* Dispatches... | (index: number, name: string = this.currentAnimation.name): Kiwi.Animations.Animation {
return this._play(name, index);
}
/**
* An internal method used to actually play a Animation at a Index.
*
* @method _play
* @param name {string} The name of the animation that is to be switched to.
* @param [... | playAt | identifier_name |
AnimationManager.ts | to play through this AnimationManager.
* Functions dispatched from this signal have ONE Parameter.
* One - The Animation object of that is now playing.
* @property onPlay
* @type Kiwi.Signal
* @public
*/
public onPlay: Kiwi.Signal;
/**
* Dispatches callbacks each time an animation stops.
* Functi... | {
if (this.isPlaying === true) {
this.currentAnimation.stop();
this.onStop.dispatch(this.currentAnimation);
}
} | identifier_body | |
AnimationManager.ts | Dispatches callbacks each time an animation is told to play through this AnimationManager.
* Functions dispatched from this signal have ONE Parameter.
* One - The Animation object of that is now playing.
* @property onPlay
* @type Kiwi.Signal
* @public
*/
public onPlay: Kiwi.Signal;
/**
* Dispatches... |
if (index !== null)
this.currentAnimation.playAt(index);
else
this.currentAnimation.play();
this.onPlay.dispatch(this.currentAnimation);
this.updateCellIndex();
return this.currentAnimation;
}
/**
* Stops the current animation from playing.
*
* @method stop
* @public
*/
public ... | random_line_split | |
respond.py | # Add 'RESPOND' and 'M118' commands for sending messages to the host
#
# Copyright (C) 2018 Alec Plumb <alec@etherwalker.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
respond_types = {
'echo': 'echo:',
'command': '//',
'error' : '!!',
}
class HostResponder:
def __ini... |
if len(msg) > 5:
msg = msg[5:]
else:
msg = ''
gcmd.respond_raw("%s %s" % (self.default_prefix, msg))
cmd_RESPOND_help = ("Echo the message prepended with a prefix")
def cmd_RESPOND(self, gcmd):
respond_type = gcmd.get('TYPE', None)
prefix = self.d... | start = umsg.find('M118')
end = msg.rfind('*')
msg = msg[start:end] | conditional_block |
respond.py | # Add 'RESPOND' and 'M118' commands for sending messages to the host
#
# Copyright (C) 2018 Alec Plumb <alec@etherwalker.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
respond_types = {
'echo': 'echo:',
'command': '//',
'error' : '!!',
}
class HostResponder:
def __ini... |
cmd_RESPOND_help = ("Echo the message prepended with a prefix")
def cmd_RESPOND(self, gcmd):
respond_type = gcmd.get('TYPE', None)
prefix = self.default_prefix
if(respond_type != None):
respond_type = respond_type.lower()
if(respond_type in respond_types):
... | msg = gcmd.get_commandline()
umsg = msg.upper()
if not umsg.startswith('M118'):
# Parse out additional info if M118 recd during a print
start = umsg.find('M118')
end = msg.rfind('*')
msg = msg[start:end]
if len(msg) > 5:
msg = msg[5:]
... | identifier_body |
respond.py | # Add 'RESPOND' and 'M118' commands for sending messages to the host
#
# Copyright (C) 2018 Alec Plumb <alec@etherwalker.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
respond_types = {
'echo': 'echo:',
'command': '//',
'error' : '!!',
}
class HostResponder:
def __ini... | def load_config(config):
return HostResponder(config) | random_line_split | |
respond.py | # Add 'RESPOND' and 'M118' commands for sending messages to the host
#
# Copyright (C) 2018 Alec Plumb <alec@etherwalker.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
respond_types = {
'echo': 'echo:',
'command': '//',
'error' : '!!',
}
class HostResponder:
def __ini... | (self, gcmd):
msg = gcmd.get_commandline()
umsg = msg.upper()
if not umsg.startswith('M118'):
# Parse out additional info if M118 recd during a print
start = umsg.find('M118')
end = msg.rfind('*')
msg = msg[start:end]
if len(msg) > 5:
... | cmd_M118 | identifier_name |
app_chooser.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | } else {
Some(gtk::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
}
}
fn get_content_info(&self) -> Option<String> {
unsafe {
FromGlibPtr::borrow(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
... |
if tmp_pointer.is_null() {
None | random_line_split |
app_chooser.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
fn get_content_info(&self) -> Option<String> {
unsafe {
FromGlibPtr::borrow(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_wi... | {
let tmp_pointer = unsafe { ffi::gtk_app_chooser_get_app_info(GTK_APP_CHOOSER(self.unwrap_widget())) };
if tmp_pointer.is_null() {
None
} else {
Some(gtk::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
}
} | identifier_body |
app_chooser.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
}
fn get_content_info(&self) -> Option<String> {
unsafe {
FromGlibPtr::borrow(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unw... | {
Some(gtk::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget))
} | conditional_block |
app_chooser.rs | // This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | (&self) -> Option<String> {
unsafe {
FromGlibPtr::borrow(
ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget())))
}
}
fn refresh(&self) -> () {
unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) }
}
} | get_content_info | identifier_name |
mail.js | var mailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var config = require('../config');
var util = require('util');
var transport = mailer.createTransport(smtpTransport(config.mail_opts));
//域名domain没有的时留空,devMode下读取host | var SITE_ROOT_URL = 'http://' + ((config.domain && !config.devMode)?config.domain:(config.host+":"+config.port));
/**
* Send an email
* @param {Object} data 邮件对象
*/
var sendMail = function (data) {
//need_active_mail=false不发送邮件
if (!config.need_active_mail) {
return;
}
// 遍历邮件数组,发送每一封邮件,如果有发送失败的,就再压入数组,... | random_line_split | |
mail.js | var mailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');
var config = require('../config');
var util = require('util');
var transport = mailer.createTransport(smtpTransport(config.mail_opts));
//域名domain没有的时留空,devMode下读取host
var SITE_ROOT_URL = 'http://' +... | 串
* @param {String} name 接收人的用户名
*/
exports.sendActiveMail = function (who, token, name) {
var from = util.format('%s <%s>', config.name, config.mail_opts.auth.user);
var to = who;
var subject = config.name + '帐号激活';
var html = '<p>您好:' + name + '</p>' +
'<p>我们收到您在' + config.name + '的注册信息,请点击下面... | ng} who 接收人的邮件地址
* @param {String} token 重置用的token字符 | conditional_block |
macros.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/. */
//! Various macro helpers.
macro_rules! trivial_to_computed_value {
($name:ty) => {
impl $crate::valu... | ) -> Result<$name, ::style_traits::ParseError<'i>> {
try_match_ident_ignore_ascii_case! { input,
$( $css => Ok($name::$variant), )+
}
}
}
impl ::style_traits::values::ToCss for $name {
fn to_css<W>(&self, dest: &mut... | impl $crate::parser::Parse for $name {
fn parse<'i, 't>(
_context: &$crate::parser::ParserContext,
input: &mut ::cssparser::Parser<'i, 't>, | random_line_split |
proxy.py | import uuid
from path_helpers import path
import numpy as np
try:
from base_node_rpc.proxy import ConfigMixinBase, StateMixinBase
import arduino_helpers.hardware.teensy as teensy
from .node import (Proxy as _Proxy, I2cProxy as _I2cProxy,
SerialProxy as _SerialProxy)
class Prox... |
class Proxy(ProxyMixin, _Proxy):
pass
class I2cProxy(ProxyMixin, _I2cProxy):
pass
class SerialProxy(ProxyMixin, _SerialProxy):
pass
except (ImportError, TypeError):
Proxy = None
I2cProxy = None
SerialProxy = None
| '''
Mixin class to add convenience wrappers around methods of the generated
`node.Proxy` class.
For example, expose config and state getters/setters as attributes.
'''
host_package_name = str(path(__file__).parent.name.replace('_', '-'))
def __init__(self, *args, **kwar... | identifier_body |
proxy.py | import uuid
from path_helpers import path
import numpy as np
try:
from base_node_rpc.proxy import ConfigMixinBase, StateMixinBase
import arduino_helpers.hardware.teensy as teensy
from .node import (Proxy as _Proxy, I2cProxy as _I2cProxy,
SerialProxy as _SerialProxy)
class Prox... | (ProxyMixin, _SerialProxy):
pass
except (ImportError, TypeError):
Proxy = None
I2cProxy = None
SerialProxy = None
| SerialProxy | identifier_name |
proxy.py | import uuid
from path_helpers import path
import numpy as np
try:
from base_node_rpc.proxy import ConfigMixinBase, StateMixinBase
import arduino_helpers.hardware.teensy as teensy
from .node import (Proxy as _Proxy, I2cProxy as _I2cProxy,
SerialProxy as _SerialProxy)
class Prox... | I2cProxy = None
SerialProxy = None | random_line_split | |
stun.py | #!/usr/bin/env python
"""Simple STUN client for getting external IP address.
Based on stun.py from https://github.com/myers/html5_udp_to_server,
but heavily simplified (dropped Twisted dependency, only supports old RFC 3489)
"""
import os, socket, struct, math
BINDING_REQUEST = 0x0001
BINDING_RESPONSE = 0x0101
MAPPED... | """Simple STUN client for getting external IP address"""
def __init__(self, timeout=5, attempts=3):
self._timeout = timeout
self._attempts = attempts
self._transaction_id = b""
def get_ip(self, stun_host="", stun_port=3478, source_address="", source_port=54320):
"""Get exter... |
class StunClient(object): | random_line_split |
stun.py | #!/usr/bin/env python
"""Simple STUN client for getting external IP address.
Based on stun.py from https://github.com/myers/html5_udp_to_server,
but heavily simplified (dropped Twisted dependency, only supports old RFC 3489)
"""
import os, socket, struct, math
BINDING_REQUEST = 0x0001
BINDING_RESPONSE = 0x0101
MAPPED... | (self, stun_host="", stun_port=3478, source_address="", source_port=54320):
"""Get external IP address and port"""
if stun_host:
stun_servers = [(stun_host, stun_port)]
else:
stun_servers = STUN_SERVERS
# If no stun_host is specified, try more servers from STUN_S... | get_ip | identifier_name |
stun.py | #!/usr/bin/env python
"""Simple STUN client for getting external IP address.
Based on stun.py from https://github.com/myers/html5_udp_to_server,
but heavily simplified (dropped Twisted dependency, only supports old RFC 3489)
"""
import os, socket, struct, math
BINDING_REQUEST = 0x0001
BINDING_RESPONSE = 0x0101
MAPPED... |
def _parse_mapped_address(self, value):
"""Get IP address and port from MAPPED_ADDRESS attribute"""
family, recv_port = struct.unpack(">xBH", value[:4])
if family != FAMILY_IPV4:
raise ValueError("IPv6 is not supported!")
ip_address = socket.inet_ntoa(value[4:])
... | attr_type, length = struct.unpack(">2H", data[ptr:ptr + 4])
yield attr_type, length, data[ptr + 4:ptr + 4 + length], ptr + 20
attr_length = 4 + 4 * int(math.ceil(length / 4.0))
ptr += attr_length | conditional_block |
stun.py | #!/usr/bin/env python
"""Simple STUN client for getting external IP address.
Based on stun.py from https://github.com/myers/html5_udp_to_server,
but heavily simplified (dropped Twisted dependency, only supports old RFC 3489)
"""
import os, socket, struct, math
BINDING_REQUEST = 0x0001
BINDING_RESPONSE = 0x0101
MAPPED... |
def _generate_request(self):
"""Generate Binding Request"""
self._transaction_id = self._generate_id()
request = [struct.pack(">H", BINDING_REQUEST), # Message Type
struct.pack(">H", 0), # Message Length
self._transaction_id]
re... | """Generate random Transaction ID"""
return os.urandom(16) | identifier_body |
formatters.py | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py
__all__=('Formatter','DecimalFormatter')
__version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ '''
_... | while strFrac and strFrac[-1] in ['0',sep]: strFrac = strFrac[:-1]
else:
strFrac = ''
if self.comma is not None:
strNew = ''
while strInt:
left, right = strInt[0:-3], strInt[-3:]
if left == '':
#strN... | if strip: | random_line_split |
formatters.py | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py
__all__=('Formatter','DecimalFormatter')
__version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ '''
_... | (self, obj):
return self.pattern % obj
def __repr__(self):
return "%s('%s')" % (self.__class__.__name__, self.pattern)
def __call__(self, x):
return self.format(x)
_ld_re=re.compile(r'^\d*\.')
_tz_re=re.compile('0+$')
class DecimalFormatter(Formatter):
"""lets you specify how to bu... | format | identifier_name |
formatters.py | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py
__all__=('Formatter','DecimalFormatter')
__version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ '''
_... |
def format(self, obj):
return self.pattern % obj
def __repr__(self):
return "%s('%s')" % (self.__class__.__name__, self.pattern)
def __call__(self, x):
return self.format(x)
_ld_re=re.compile(r'^\d*\.')
_tz_re=re.compile('0+$')
class DecimalFormatter(Formatter):
"""lets you sp... | self.pattern = pattern | identifier_body |
formatters.py | #!/bin/env python
#Copyright ReportLab Europe Ltd. 2000-2012
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/lib/formatters.py
__all__=('Formatter','DecimalFormatter')
__version__=''' $Id: formatters.py 3959 2012-09-27 14:39:39Z robin $ '''
_... | def t(n, s, places=2, decimalSep='.', thousandSep=None, prefix=None, suffix=None):
f=DecimalFormatter(places,decimalSep,thousandSep,prefix,suffix)
r = f(n)
print("places=%2d dot=%-4s comma=%-4s prefix=%-4s suffix=%-4s result=%10s %s" %(f.places, f.dot, f.comma, f.prefix, f.suffix,r, r==s and 'OK... | conditional_block | |
tour.js | $ = require('jquery')
_ = require('lodash')
// require('bootstrap-tour')
var Dialog = require('../lib/dialogs.jsx')
var Tipit = new (function () {
this.makeTip = function (target, data) {
if (!$(target).length) {
console.warn("Skipping ttip to "+target+". Target not found.");
return;
}
var html = '<div... |
var el = $(html).css({ top: y, left: x }).appendTo('body');
if (x > $(window).width()/2) {
$(el).addClass('ttip-right');
}
$(el).find('.ttip-done').click(function () {
console.log('done');
$(el).fadeOut().remove();
});
$(el).one('click', function (e) {
console.log('click', $(e.target).find('.t... |
var x = $(target).offset().left+$(target).outerWidth()/2,
y = $(target).offset().top+$(target).outerHeight()/2; | random_line_split |
tour.js |
$ = require('jquery')
_ = require('lodash')
// require('bootstrap-tour')
var Dialog = require('../lib/dialogs.jsx')
var Tipit = new (function () {
this.makeTip = function (target, data) {
if (!$(target).length) |
var html = '<div class="ttip animate" data-id="1" data-target="menu">'+
'<div class="ttip-cta">'+
'<span class="ttip-center"></span>'+
'<span class="ttip-beacon"></span>'+
'</div>'+
'<div class="ttip-box">'+
'<div class="header">'+data.header+'</div>'+
'<p>'+data.text+'</p>'+
'<div clas... | {
console.warn("Skipping ttip to "+target+". Target not found.");
return;
} | conditional_block |
folder.d.ts | import { OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';
import { StorageService } from '../services/storage';
import { ComponentService } from '../services/componentService';
export declare class | {
name: string;
path: string;
content: any;
constructor(name: string, path: string, content: any);
}
export declare class OpenFolderComponent implements OnInit {
private _sanitize;
private route;
private componentService;
storageService: StorageService;
dialog: Electron.Dialog;
... | svg_file | identifier_name |
folder.d.ts | import { OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { DomSanitizer } from '@angular/platform-browser';
import { StorageService } from '../services/storage';
import { ComponentService } from '../services/componentService';
export declare class svg_file {
name: string;
... | copyData: Array<svg_file>;
searchOn: boolean;
clipboard: Electron.Clipboard;
webview: any;
developerMode: boolean;
constructor(_sanitize: DomSanitizer, route: ActivatedRoute, componentService: ComponentService, storageService: StorageService);
ngOnInit(): void;
showFiles(_dir: string): P... | drag_file: Electron.WebContents;
app: Electron.App;
data: Array<svg_file>; | random_line_split |
compareWithPreviousOutputs.check.js | /*
* Copyright 2016 Amadeus s.a.s.
* 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
* | * See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
const co = require("co");
const path = require("path");
const assertFilesEqual = require("../helpers/assertFilesEqual");
const exec = require("../helpers/exec");
module.exports = function (result... | * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split |
auto-dedup.rs | // run-pass
#![allow(unused_assignments)]
// Test that duplicate auto trait bounds in trait objects don't create new types.
#[allow(unused_assignments)]
use std::marker::Send as SendAlias;
// A dummy trait for the non-auto trait.
trait Trait {}
// A dummy struct to implement `Trait` and `Send`.
struct Struct;
impl... | (_: Box<dyn Trait + Send + SendAlias>) {}
impl dyn Trait + Send + Send {
fn do_nothing(&self) {}
}
fn main() {
// 1. Moving into a variable with more `Send`s and back.
let mut dyn_trait_send = Box::new(Struct) as Box<dyn Trait + Send>;
let dyn_trait_send_send: Box<dyn Trait + Send + Send> = dyn_trait_... | takes_dyn_trait_send_sendalias | identifier_name |
auto-dedup.rs | // run-pass
#![allow(unused_assignments)]
// Test that duplicate auto trait bounds in trait objects don't create new types.
#[allow(unused_assignments)]
use std::marker::Send as SendAlias;
// A dummy trait for the non-auto trait.
trait Trait {}
// A dummy struct to implement `Trait` and `Send`.
struct Struct;
impl... |
fn takes_dyn_trait_send_send(_: Box<dyn Trait + Send + Send>) {}
fn takes_dyn_trait_send_sendalias(_: Box<dyn Trait + Send + SendAlias>) {}
impl dyn Trait + Send + Send {
fn do_nothing(&self) {}
}
fn main() {
// 1. Moving into a variable with more `Send`s and back.
let mut dyn_trait_send = Box::new(Struc... | {} | identifier_body |
auto-dedup.rs | // run-pass
#![allow(unused_assignments)]
// Test that duplicate auto trait bounds in trait objects don't create new types.
#[allow(unused_assignments)]
use std::marker::Send as SendAlias;
// A dummy trait for the non-auto trait.
trait Trait {} | impl Trait for Struct {}
// These three functions should be equivalent.
fn takes_dyn_trait_send(_: Box<dyn Trait + Send>) {}
fn takes_dyn_trait_send_send(_: Box<dyn Trait + Send + Send>) {}
fn takes_dyn_trait_send_sendalias(_: Box<dyn Trait + Send + SendAlias>) {}
impl dyn Trait + Send + Send {
fn do_nothing(&sel... |
// A dummy struct to implement `Trait` and `Send`.
struct Struct;
| random_line_split |
endpoint.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 the License, or
// (at your option) any la... | pub host: String,
pub port: u16,
pub using_dapps_domains: bool,
}
#[derive(Debug, PartialEq, Clone)]
pub struct EndpointInfo {
pub name: String,
pub description: String,
pub version: String,
pub author: String,
pub icon_url: String,
}
pub type Endpoints = BTreeMap<String, Box<Endpoint>>;
pub type Handler = se... | use std::collections::BTreeMap;
#[derive(Debug, PartialEq, Default, Clone)]
pub struct EndpointPath {
pub app_id: String, | random_line_split |
endpoint.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 the License, or
// (at your option) any la... | (&self, path: EndpointPath, _control: hyper::Control) -> Box<Handler> {
self.to_handler(path)
}
}
| to_async_handler | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.