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
latest.rs
// Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors // See the README.md file at the top-level directory of this distribution. // // 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.o...
() { let mut core = Core::new().unwrap(); let client = Client::configure() .connector(HttpsConnector::new(4, &core.handle()).unwrap()) .build(&core.handle()); // Retrieve the latest comic. let work = xkcd::comics::latest(&client); let latest_comic = core.run(work).unwrap(); prin...
main
identifier_name
base.py
class Requirement(object): """ Requirements are the basis for Dominion. They define what needs to exist on a host/role, or perhaps what *mustn't* exist. Requirements are defined on Roles. """ creation_counter = 0 "The base class for requirements." def __init__(self, required=True, en...
if self.ensure == "removed": if hasattr(self, 'uninstall'): return self.uninstall()
return self.install()
conditional_block
base.py
class Requirement(object): """ Requirements are the basis for Dominion. They define what needs to exist on a host/role, or perhaps what *mustn't* exist. Requirements are defined on Roles. """ creation_counter = 0 "The base class for requirements." def __init__(self, required=True, en...
if self.ensure == "exists" or self.required: if hasattr(self, 'install'): return self.install() if self.ensure == "removed": if hasattr(self, 'uninstall'): return self.uninstall()
identifier_body
base.py
class
(object): """ Requirements are the basis for Dominion. They define what needs to exist on a host/role, or perhaps what *mustn't* exist. Requirements are defined on Roles. """ creation_counter = 0 "The base class for requirements." def __init__(self, required=True, ensure=None, depends=...
Requirement
identifier_name
base.py
class Requirement(object): """ Requirements are the basis for Dominion. They define what needs to exist on a host/role, or perhaps what *mustn't* exist. Requirements are defined on Roles. """ creation_counter = 0 "The base class for requirements." def __init__(self, required=True, ensu...
self.creation_counter = Requirement.creation_counter Requirement.creation_counter += 1 def __call__(self): self.apply() def apply(self): if self.ensure == "exists" or self.required: if hasattr(self, 'install'): return self.install() if self.e...
self.post = post or () # Increase the creation counter, and save our local copy.
random_line_split
inline-link.js
import { Link, LocationProvider } from '@reach/router'; import router from '@elementor/router'; import { arrayToClassName } from 'elementor-app/utils/utils.js'; import './inline-link.scss'; export default function InlineLink( props ) { const baseClassName = 'eps-inline-link', colorClassName = `${ baseClassName }-...
} InlineLink.propTypes = { className: PropTypes.string, children: PropTypes.string, url: PropTypes.string, target: PropTypes.string, rel: PropTypes.string, text: PropTypes.string, color: PropTypes.oneOf( [ 'primary', 'secondary', 'cta', 'link', 'disabled' ] ), underline: PropTypes.oneOf( [ 'none', 'hover', 'al...
</a> ); return props.url.includes( 'http' ) ? getExternalLink() : getRouterLink();
random_line_split
inline-link.js
import { Link, LocationProvider } from '@reach/router'; import router from '@elementor/router'; import { arrayToClassName } from 'elementor-app/utils/utils.js'; import './inline-link.scss'; export default function InlineLink( props )
</Link> </LocationProvider> ), getExternalLink = () => ( <a href={ props.url } target={ props.target } rel={ props.rel } className={ className } > { props.children } </a> ); return props.url.includes( 'http' ) ? getExternalLink() : getRouterLink(); } InlineLink.propTypes = ...
{ const baseClassName = 'eps-inline-link', colorClassName = `${ baseClassName }--color-${ props.color }`, underlineClassName = 'none' !== props.underline ? `${ baseClassName }--underline-${ props.underline }` : '', italicClassName = props.italic ? `${ baseClassName }--italic` : '', classes = [ baseClassName...
identifier_body
inline-link.js
import { Link, LocationProvider } from '@reach/router'; import router from '@elementor/router'; import { arrayToClassName } from 'elementor-app/utils/utils.js'; import './inline-link.scss'; export default function
( props ) { const baseClassName = 'eps-inline-link', colorClassName = `${ baseClassName }--color-${ props.color }`, underlineClassName = 'none' !== props.underline ? `${ baseClassName }--underline-${ props.underline }` : '', italicClassName = props.italic ? `${ baseClassName }--italic` : '', classes = [ bas...
InlineLink
identifier_name
ChooseGameAction.ts
import { GameAction, GameActionProperties } from './GameAction'; import AbilityContext = require('../AbilityContext'); import { Players } from '../Constants'; export interface ChooseGameChoices { [choice: string]: GameAction; } export interface ChooseActionProperties extends GameActionProperties { activePromp...
defaultProperties: ChooseActionProperties = { activePromptTitle: 'Select an action:', choices: {}, messages: {} }; constructor(properties: ChooseActionProperties | ((context: AbilityContext) => ChooseActionProperties)) { super(properties); } getProperties(context: Ab...
} export class ChooseGameAction extends GameAction { effect = 'choose between different actions';
random_line_split
ChooseGameAction.ts
import { GameAction, GameActionProperties } from './GameAction'; import AbilityContext = require('../AbilityContext'); import { Players } from '../Constants'; export interface ChooseGameChoices { [choice: string]: GameAction; } export interface ChooseActionProperties extends GameActionProperties { activePromp...
context.game.queueSimpleStep(() => properties.choices[choice].addEventsToArray(events, context)); } if(choices.length === 0) { return; } let target = properties.target; context.game.promptWithHandlerMenu(player, { activePromptTitle, context, choices, choi...
{ context.game.addMessage(properties.messages[choice], player, properties.target); }
conditional_block
ChooseGameAction.ts
import { GameAction, GameActionProperties } from './GameAction'; import AbilityContext = require('../AbilityContext'); import { Players } from '../Constants'; export interface ChooseGameChoices { [choice: string]: GameAction; } export interface ChooseActionProperties extends GameActionProperties { activePromp...
}
{ let properties = this.getProperties(context); return Object.values(properties.choices).some( gameAction => gameAction.hasTargetsChosenByInitiatingPlayer(context) ); }
identifier_body
ChooseGameAction.ts
import { GameAction, GameActionProperties } from './GameAction'; import AbilityContext = require('../AbilityContext'); import { Players } from '../Constants'; export interface ChooseGameChoices { [choice: string]: GameAction; } export interface ChooseActionProperties extends GameActionProperties { activePromp...
(context: AbilityContext, additionalProperties = {}): boolean { let properties = this.getProperties(context, additionalProperties); return Object.values(properties.choices).some( gameAction => gameAction.hasLegalTarget(context) ); } addEventsToArray(events: any[], context: A...
hasLegalTarget
identifier_name
environment-default.ts
import { Environment } from "./environment-type-def"; export const environmentDefault: Environment = { production: false, geoLocation: { timeoutMillis: 5000, firefoxWorkaroundTimeoutMillis: 8000, updateMillis: 5000 }, gastroLocationsUrl: "assets/GastroLocations.json", shoppi...
} };
random_line_split
api.js
import Telescope from 'meteor/nova:lib'; import Posts from "meteor/nova:posts"; import Comments from "meteor/nova:comments"; import Users from 'meteor/nova:users'; serveAPI = function(terms){ var posts = []; var parameters = Posts.parameters.get(terms); const postsCursor = Posts.find(parameters.selector, param...
}); commentsToDelete.reverse().forEach(function(index) { comments.splice(index,1); }); postOutput.comments = comments; posts.push(postOutput); }); return JSON.stringify(posts); };
commentsToDelete.push(index); } }
random_line_split
algo.js
; for(x in regionDatas){ regionDatas[x].queue = new Array(); regionDatas[x].resultArray = new Array(); } for(var i=1;i<=TOTAL_STUDENT;i++){ var student = new Student(); student.id = i; student.score = $('#score'+i).val(); student.home = $('#wishList'+i+'_0').val(); student.wish1 = $('...
shToResultArray(region, numberOfItems){ for(var k=0;k<numberOfItems;k++){ region.resultArray.push(region.queue.pop()); } assignStudentToRegion(region.homeName, region.resultArray); } // 將已經被分配到某地區的學生的 result attribute 指定為該地區。(resultArray[] 的 items 為學生,擁有 result ) function assignStudentToRegion(regionName, r...
identifier_body
algo.js
在算平均成績時不把他算進去 // 注意這裡只是預設值,當程式執行時,此預設值會被算出的值取代 // Fixed: 2014, Dec, 11 var not_here_student = 0; students = new Array(); avgScore = 0.0; for(x in regionDatas){ regionDatas[x].queue = new Array(); regionDatas[x].resultArray = new Array(); } for(var i=1;i<=TOTAL_STUDENT;i++){ var student = n...
ion, numberOfItems){ for(var k=0;k<numberOfItems;k++){ region.resultArray.push(region.queue.pop()); } assignStudentToRegion(region.homeName, region.resultArray); } /
conditional_block
algo.js
createDownloadableContent(); }); } // 初始化變數、將 html 清空 function initAlgo(){ // 有時會發生役男進來後,才臨時驗退的情形,我們會在其分數欄位填入 "NA" ,在算平均成績時不把他算進去 // 注意這裡只是預設值,當程式執行時,此預設值會被算出的值取代 // Fixed: 2014, Dec, 11 var not_here_student = 0; students = new Array(); avgScore = 0.0; for(x in regionDatas){ regionDatas[x].qu...
; } // TODO: 這邊改用 key hash 應該會漂亮、效能也更好 for(var i=0;i<regionDatasLength;i++){ if(students[k].wish1 == regionDatas[i].name){ regionDatas[i].queue.push(students[k]); } } } // Step 2: 將每個單位的 queue 裡面的學生互相比較,取出最適合此單位的學生放入此單位的 resultArray for(var i=0;i<regionDatasLength;i++){ va...
ontinue
identifier_name
algo.js
"); createDownloadableContent(); }); } // 初始化變數、將 html 清空 function initAlgo(){ // 有時會發生役男進來後,才臨時驗退的情形,我們會在其分數欄位填入 "NA" ,在算平均成績時不把他算進去 // 注意這裡只是預設值,當程式執行時,此預設值會被算出的值取代 // Fixed: 2014, Dec, 11 var not_here_student = 0; students = new Array(); avgScore = 0.0; for(x in regionDatas){ regionDatas[x...
// Step 1: 將學生加入其第N志願的 queue (N depend on round) var regionDatasLength = regionDatas.length; for(var k=0;k<TOTAL_STUDENT;k++){ // 如果學生已經分發到某的地點,就不須再分發,可跳過直接看下個學生。 if(students[k].result != NO_REGION_RESULT){ continue; } // TODO: 這邊改用 key hash 應該會漂亮、效能也更好 for(var i=0;i<regionDatasLength;i+...
}
random_line_split
PropertyAreaElement.ts
/* Copyright 2016 Sony Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agre...
} */ protected _getTemplateFilePath() { return ConstValue.TEMPLATE_FILE_PATH; } /** * プルダウンにJQueryMobileのスタイルを適応する。 * JQueryMobileのスタイルは、新たに生成したDOM要素には自動的には適応されないため、 * プルダウンをレンダリングした後に、この関数を利用する。 * ただし、...
{string
identifier_name
PropertyAreaElement.ts
/* Copyright 2016 Sony Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agre...
ので、全てプルダウンをレンダリングした後に1度だけ呼ぶこと。 * @param {JQuery} $target プルダウンを内包しているDOMのJQuery */ protected _adaptJqueryMobileStyleToPulldown($target: JQuery) { let pulldownContainerDomClass = ".custom-select"; $target.find(pulldownContainerDomClass).trigger('creat...
* プルダウンをレンダリングした後に、この関数を利用する。 * ただし、重たい処理な
identifier_body
PropertyAreaElement.ts
/* Copyright 2016 Sony Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agre...
/** * プルダウンにJQueryMobileのスタイルを適応する。 * JQueryMobileのスタイルは、新たに生成したDOM要素には自動的には適応されないため、 * プルダウンをレンダリングした後に、この関数を利用する。 * ただし、重たい処理なので、全てプルダウンをレンダリングした後に1度だけ呼ぶこと。 * @param {JQuery} $target プルダウンを内包しているDOMのJQuery */ protec...
* @return {string} */ protected _getTemplateFilePath() { return ConstValue.TEMPLATE_FILE_PATH; }
random_line_split
unused-async.rs
// edition:2018 // run-pass #![allow(dead_code)] #[must_use] //~^ WARNING `must_use` async fn test() -> i32 { 1 } struct Wowee {} impl Wowee { #[must_use] //~^ WARNING `must_use` async fn test_method() -> i32 { 1 } } /* FIXME(guswynn) update this test when async-fn-in-traits works trait...
#[must_use] async fn test_other_trait() -> i32 { WARNING must_use 1 } } */ fn main() { }
random_line_split
unused-async.rs
// edition:2018 // run-pass #![allow(dead_code)] #[must_use] //~^ WARNING `must_use` async fn test() -> i32 { 1 } struct Wowee {} impl Wowee { #[must_use] //~^ WARNING `must_use` async fn test_method() -> i32 { 1 } } /* FIXME(guswynn) update this test when async-fn-in-traits works trait...
{ }
identifier_body
unused-async.rs
// edition:2018 // run-pass #![allow(dead_code)] #[must_use] //~^ WARNING `must_use` async fn test() -> i32 { 1 } struct
{} impl Wowee { #[must_use] //~^ WARNING `must_use` async fn test_method() -> i32 { 1 } } /* FIXME(guswynn) update this test when async-fn-in-traits works trait Doer { #[must_use] async fn test_trait_method() -> i32; WARNING must_use async fn test_other_trait() -> i32; } impl...
Wowee
identifier_name
email.tsx
import { Box, Checkbox, Flex } from "@artsy/palette" import { Input } from "@artsy/reaction/dist/Components/Input" import { onChangeArticle } from "client/actions/edit/articleActions" import { CharacterLimit } from "client/components/character_limit" import { FormLabel } from "client/components/form_label" import { clo...
</Box> <Box pb={4}> <CharacterLimit label="Email Headline" limit={97} type="textarea" onChange={value => this.onChange("headline", value)} defaultValue={headline} /> </Box> ...
{ const { article, onChangeArticleAction } = this.props const emailMetadata = article.email_metadata || {} const { author, custom_text, headline, image_url } = emailMetadata return ( <div> <Flex flexDirection={["column", "row"]} justifyContent="space-between" ...
identifier_body
email.tsx
import { Box, Checkbox, Flex } from "@artsy/palette" import { Input } from "@artsy/reaction/dist/Components/Input" import { onChangeArticle } from "client/actions/edit/articleActions" import { CharacterLimit } from "client/components/character_limit" import { FormLabel } from "client/components/form_label" import { clo...
() { const { article, onChangeArticleAction } = this.props const emailMetadata = article.email_metadata || {} const { author, custom_text, headline, image_url } = emailMetadata return ( <div> <Flex flexDirection={["column", "row"]} justifyContent="space-between" ...
render
identifier_name
email.tsx
import { Box, Checkbox, Flex } from "@artsy/palette" import { Input } from "@artsy/reaction/dist/Components/Input" import { onChangeArticle } from "client/actions/edit/articleActions" import { CharacterLimit } from "client/components/character_limit"
import { connect } from "react-redux" import { DisplayProps } from "../index" import { EmailPreview } from "./preview/email_preview" const ImageUpload = require("client/apps/edit/components/admin/components/image_upload.coffee") export class DisplayEmail extends Component<DisplayProps> { onChange = (key, value) => {...
import { FormLabel } from "client/components/form_label" import { clone } from "lodash" import React, { Component } from "react"
random_line_split
filesearch.rs
This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] pub use self::FileMatch::*; use std::cell::RefCell; use std::collections::HashSet; use std::io::fs::PathExtensions; use std::io::fs; use std::os; use util::fs as myfs; pub enum FileMatch { ...
<'a> { pub sysroot: &'a Path, pub addl_lib_search_paths: &'a RefCell<Vec<Path>>, pub triple: &'a str, } impl<'a> FileSearch<'a> { pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) { let mut visited_dirs = HashSet::new(); let mut found = false; debug!("filesearch: ...
FileSearch
identifier_name
filesearch.rs
This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] pub use self::FileMatch::*; use std::cell::RefCell; use std::collections::HashSet; use std::io::fs::PathExtensions; use std::io::fs; use std::os; use util::fs as myfs; pub enum FileMatch { ...
fn make_target_lib_path(sysroot: &Path, target_triple: &str) -> Path { sysroot.join(&relative_target_lib_path(sysroot, target_triple)) } fn make_rustpkg_lib_path(sysroot: &Path, dir: &Path, triple: &str) -> Path { let mut p = dir.join(...
{ let mut p = Path::new(find_libdir(sysroot)); assert!(p.is_relative()); p.push(rustlibdir()); p.push(target_triple); p.push("lib"); p }
identifier_body
filesearch.rs
pub type pick<'a> = |path: &Path|: 'a -> FileMatch; pub struct FileSearch<'a> { pub sysroot: &'a Path, pub addl_lib_search_paths: &'a RefCell<Vec<Path>>, pub triple: &'a str, } impl<'a> FileSearch<'a> { pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) { let mut visited_dirs = Ha...
random_line_split
font_list.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 super::c_str_to_string; use crate::text::util::is_cjk; use fontconfig::fontconfig::{FcChar8, FcResultMatch, Fc...
else { panic!(); }; let mut index: libc::c_int = 0; let result = FcPatternGetInteger(*font, FC_INDEX.as_ptr() as *mut c_char, 0, &mut index); let index = if result == FcResultMatch { index } else { ...
{ c_str_to_string(file as *const c_char) }
conditional_block
font_list.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 super::c_str_to_string; use crate::text::util::is_cjk; use fontconfig::fontconfig::{FcChar8, FcResultMatch, FcSetSystem}; use fontconfig::fontconfig::{FcConfigGetCurrent, FcConfigGetFonts, FcConfigSubstitute}; use fontconfig::fontconfig::{FcDefaultSubstitute, FcFontMatch, FcNameParse, FcPatternGetString}; use fontc...
random_line_split
font_list.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 super::c_str_to_string; use crate::text::util::is_cjk; use fontconfig::fontconfig::{FcChar8, FcResultMatch, Fc...
{ let mut families = vec!["DejaVu Serif", "FreeSerif", "DejaVu Sans", "FreeSans"]; if let Some(codepoint) = codepoint { if is_cjk(codepoint) { families.push("TakaoPGothic"); families.push("Droid Sans Fallback"); families.push("WenQuanYi Micro Hei"); famil...
identifier_body
font_list.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 super::c_str_to_string; use crate::text::util::is_cjk; use fontconfig::fontconfig::{FcChar8, FcResultMatch, Fc...
<F>(family_name: &str, mut callback: F) where F: FnMut(String), { debug!("getting variations for {}", family_name); unsafe { let config = FcConfigGetCurrent(); let mut font_set = FcConfigGetFonts(config, FcSetSystem); let font_set_array_ptr = &mut font_set; let pattern = FcPa...
for_each_variation
identifier_name
AnimatedRotateComponent.js
/* @flow strict-local */ import React, { PureComponent } from 'react'; import type { Node as React$Node } from 'react'; import { Animated, Easing } from 'react-native'; import type { Style } from '../types'; type Props = $ReadOnly<{| style?: Style, children: React$Node, |}>; export default class AnimatedRotateCo...
return <Animated.View style={[animatedStyle, style]}>{children}</Animated.View>; } }
const animatedStyle = { transform: [{ rotate: rotation }] };
random_line_split
lib.rs
so anyone that can call out to C //! within an app can send and receive messages to other parts of the app. //! //! You could think of Carrier as a poor-(wo)man's nanomsg, however there are //! some key differences: //! //! 1. Carrier is in-memory only (so, inproc://). //! 2. Carrier only sends a message to one re...
/// Wipe out all queues pub fn wipe() { (*CONN).wipe(); } #[cfg(test)] mod tests { use ::std::thread; use super::*; use ::std::sync::{Arc, RwLock}; #[test] fn send_recv_simple() { send("sendrecv", Vec::from(String::from("this is a test").as_bytes())).unwrap(); send_string("s...
{ (*CONN).count() }
identifier_body
lib.rs
so anyone that can call out to C //! within an app can send and receive messages to other parts of the app. //! //! You could think of Carrier as a poor-(wo)man's nanomsg, however there are //! some key differences: //! //! 1. Carrier is in-memory only (so, inproc://). //! 2. Carrier only sends a message to one re...
(&self, val: i32) { let mut mguard = self.messages.write().expect("Queue.inc_messages() -- failed to grab write lock"); (*mguard) += val; } /// Increment the number of users this queue has by a certain amount (1). fn inc_users(&self, val: i32) { let mut uguard = self.users.write().e...
inc_messages
identifier_name
lib.rs
so anyone that can call out to C //! within an app can send and receive messages to other parts of the app. //! //! You could think of Carrier as a poor-(wo)man's nanomsg, however there are //! some key differences: //! //! 1. Carrier is in-memory only (so, inproc://). //! 2. Carrier only sends a message to one re...
else { let queue = Arc::new(Queue::new()); (*guard).insert(channel.clone(), queue.clone()); queue } } fn exists(&self, channel: &String) -> bool { let guard = self.queues.read().expect("Carrier.exists() -- failed to grab read lock"); (*guard).contain...
{ (*guard).get(channel).expect("Carrier.ensure() -- failed to grab map item").clone() }
conditional_block
lib.rs
so anyone that can call out to C //! within an app can send and receive messages to other parts of the app. //! //! You could think of Carrier as a poor-(wo)man's nanomsg, however there are //! some key differences: //! //! 1. Carrier is in-memory only (so, inproc://). //! 2. Carrier only sends a message to one re...
fn send_recv_simple() { send("sendrecv", Vec::from(String::from("this is a test").as_bytes())).unwrap(); send_string("sendrecv", String::from("this is another test")).unwrap(); let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap(); assert_eq!(next, "this is a ...
#[test]
random_line_split
models.py
from django.conf import settings from django.db import models from django.core.cache import cache from django.dispatch import receiver from seahub.base.fields import LowerCaseCharField from seahub.profile.settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT from registration.signals import user_registered cl...
(models.Manager): def add_or_update(self, username, nickname, intro, lang_code=None): """Add or update user profile. """ try: profile = self.get(user=username) profile.nickname = nickname profile.intro = intro profile.lang_code = lang_code ...
ProfileManager
identifier_name
models.py
from django.conf import settings from django.db import models from django.core.cache import cache from django.dispatch import receiver from seahub.base.fields import LowerCaseCharField from seahub.profile.settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT from registration.signals import user_registered cl...
from seahub.utils import normalize_cache_key user = kwargs['user'] key = normalize_cache_key(user.email, EMAIL_ID_CACHE_PREFIX) cache.set(key, user.id, EMAIL_ID_CACHE_TIMEOUT)
identifier_body
models.py
from django.conf import settings from django.db import models from django.core.cache import cache from django.dispatch import receiver from seahub.base.fields import LowerCaseCharField from seahub.profile.settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT from registration.signals import user_registered cl...
except Profile.DoesNotExist: return settings.LANGUAGE_CODE def delete_profile_by_user(self, username): self.filter(user=username).delete() class Profile(models.Model): user = models.EmailField(unique=True) nickname = models.CharField(max_length=64, blank=True) intro = mode...
return settings.LANGUAGE_CODE
conditional_block
models.py
from django.conf import settings from django.db import models from django.core.cache import cache from django.dispatch import receiver from seahub.base.fields import LowerCaseCharField from seahub.profile.settings import EMAIL_ID_CACHE_PREFIX, EMAIL_ID_CACHE_TIMEOUT from registration.signals import user_registered cl...
return super(ProfileManager, self).get(user=username) except Profile.DoesNotExist: return None def get_user_language(self, username): """Get user's language from profile. Return default language code if user has no preferred language. Arguments: ...
""" try:
random_line_split
MenuConversionTest.ts
import { describe, it } from '@ephox/bedrock-client'; import { assert } from 'chai'; import { Menu } from 'tinymce/core/api/ui/Ui'; import * as MenuConversion from 'tinymce/themes/silver/ui/menus/menu/MenuConversion'; describe('atomic.tinymce.themes.silver.menus.MenuConversionTest', () => { const buildMenuItem = (n...
}); });
random_line_split
HashSet.ts
import test from 'ava'; import { HashSetStructure, fromArray, values } from '../../src'; let set: HashSetStructure<string>; let set2: HashSetStructure<string>; let set3: HashSetStructure<string>; test.beforeEach(() => { set = fromArray(['A', 'B', 'C', 'D', 'E']); set3 = fromArray(['A', 'C', 'D', 'E', 'F']); set...
test('@@equals() returns false if the sets have differing members from each other', t => { t.false(set['@@equals'](set3)); t.false(set2['@@equals'](set3)); });
t.true(set['@@equals'](set2)); });
random_line_split
main.js
"use strict"; const os = require("os"); const fs = require("fs-extra-promise"); const Web = require("web"); const { Service } = require("service"); const { ServiceComBus } = require("servicecom"); const Monitor = require("./monitor"); const Configs = require("./controllers/configs"); const Config = require("./types/co...
this.addDisposable(Configs.instance); const routes = [].concat(Configs.instance.routes, ServiceCtrl.instance.routes, this.routes); await ServiceComBus.instance.start(Object.assign({ name: this.name, uri: this.config.bus.uri, publicKey: keys && keys.public, ...
{ keys = { private: await fs.readFileAsync(this.config.jwtprivate, "utf8"), public: await fs.readFileAsync(this.config.jwtpublic, "utf8") }; Token.instance.setKeys(keys); Config.setGlobalOpts({ publicKey: keys.public }); }
conditional_block
main.js
"use strict"; const os = require("os"); const fs = require("fs-extra-promise"); const Web = require("web"); const { Service } = require("service"); const { ServiceComBus } = require("servicecom"); const Monitor = require("./monitor"); const Configs = require("./controllers/configs"); const Config = require("./types/co...
} module.exports = Main;
{ notification.removeAllListeners("config.tagged"); this.log("info", "I'm offline!"); }
identifier_body
main.js
"use strict"; const os = require("os"); const fs = require("fs-extra-promise"); const Web = require("web"); const { Service } = require("service"); const { ServiceComBus } = require("servicecom");
const Db = require("./db"); const { notification } = require("typelib"); class Main extends Service { constructor(name, version) { super(name, version); } async onSetup() { await this.provide("REST", { uri: `http://${os.hostname()}:${this.config.port}` }); await...
const Monitor = require("./monitor"); const Configs = require("./controllers/configs"); const Config = require("./types/config"); const ServiceCtrl = require("./controllers/services"); const { Token } = require("auth");
random_line_split
main.js
"use strict"; const os = require("os"); const fs = require("fs-extra-promise"); const Web = require("web"); const { Service } = require("service"); const { ServiceComBus } = require("servicecom"); const Monitor = require("./monitor"); const Configs = require("./controllers/configs"); const Config = require("./types/co...
() { const dbConfig = { uri: this.config.mongo, name: this.name }; await Db.instance.connect(dbConfig); this.addDisposable(Db.instance); let keys; if (this.config.jwtprivate && this.config.jwtpublic) { keys = { private...
onOnline
identifier_name
std_vec.rs
use std::cmp::Ordering; impl<T> Collection for Vec<T> { type Item = T; } impl<T> RetainsOrder for Vec<T> {} impl<T> Sortable for Vec<T> { fn sort<F>(&mut self, f: F) where F: FnMut(&Self::Item, &Self::Item) -> Ordering, { self.sort_by(f); } } impl<T, O> SearchableByOrder<O> for V...
use super::{Collection, RetainsOrder, SearchableByOrder, SortOrder, Sortable, SortedInsert};
random_line_split
std_vec.rs
use super::{Collection, RetainsOrder, SearchableByOrder, SortOrder, Sortable, SortedInsert}; use std::cmp::Ordering; impl<T> Collection for Vec<T> { type Item = T; } impl<T> RetainsOrder for Vec<T> {} impl<T> Sortable for Vec<T> { fn sort<F>(&mut self, f: F) where F: FnMut(&Self::Item, &Self::Ite...
(&mut self, x: T) { let i = match self.search(&x) { Ok(i) => i, Err(i) => i, }; self.insert(i, x); } }
insert
identifier_name
std_vec.rs
use super::{Collection, RetainsOrder, SearchableByOrder, SortOrder, Sortable, SortedInsert}; use std::cmp::Ordering; impl<T> Collection for Vec<T> { type Item = T; } impl<T> RetainsOrder for Vec<T> {} impl<T> Sortable for Vec<T> { fn sort<F>(&mut self, f: F) where F: FnMut(&Self::Item, &Self::Ite...
}
{ let i = match self.search(&x) { Ok(i) => i, Err(i) => i, }; self.insert(i, x); }
identifier_body
view1.js
'use strict'; angular.module('myApp.viewPopular', ['ngRoute', 'movieApi']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/popular', { templateUrl: 'viewPopular/view1.html', controller: 'ViewPopularCtrl' }); }]) .c...
}; // $scope.showDetails = function (movie) { // var modalInstance = $modal.open({ // templateUrl: 'movieDetails.html', // controller: 'ViewDetailsCtrl', // resolve: { // movieId: functio...
{ TMDbService.movieSearch.get({ query: searchText //TODO: paging }, function (data) { data.results.forEach(function (item) { item.poster_path = $scope.configService.getPosterImageU...
conditional_block
view1.js
'use strict'; angular.module('myApp.viewPopular', ['ngRoute', 'movieApi']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/popular', { templateUrl: 'viewPopular/view1.html', controller: 'ViewPopularCtrl' }); }]) .c...
// }, function () { // //cancel // }); // }; $scope.loadMoreData(); }]); //angular.module('myApp.viewPopular') // .controller('ViewDetailsCtrl', [ // '$scope', // '$modalInstance', // 'TMDbService', // 'T...
// }); // // modalInstance.result.then(function (selectedItem) { // //ok
random_line_split
deviantart.py
import foauth.providers def draft10(service, token, r): headers = r.headers or {} headers[u'Authorization'] = u'OAuth %s' % token r.headers = headers return r class DeviantArt(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://deviantart.com/' docs_url = '...
(self, key): r = self.api(key, self.api_domain, u'/api/draft15/user/whoami') return r.json()[u'username']
get_user_id
identifier_name
deviantart.py
import foauth.providers def draft10(service, token, r): headers = r.headers or {} headers[u'Authorization'] = u'OAuth %s' % token r.headers = headers return r class DeviantArt(foauth.providers.OAuth2): # General info about the provider
provider_url = 'http://deviantart.com/' docs_url = 'http://www.deviantart.com/developers/' category = 'Pictures' # URLs to interact with the API authorize_url = 'https://www.deviantart.com/oauth2/draft15/authorize' access_token_url = 'https://www.deviantart.com/oauth2/draft15/token' api_domain ...
identifier_body
deviantart.py
import foauth.providers def draft10(service, token, r): headers = r.headers or {} headers[u'Authorization'] = u'OAuth %s' % token r.headers = headers return r class DeviantArt(foauth.providers.OAuth2): # General info about the provider provider_url = 'http://deviantart.com/' docs_url = '...
# URLs to interact with the API authorize_url = 'https://www.deviantart.com/oauth2/draft15/authorize' access_token_url = 'https://www.deviantart.com/oauth2/draft15/token' api_domain = 'www.deviantart.com' available_permissions = [ (None, 'read and write to your artwork'), ] bearer_...
category = 'Pictures'
random_line_split
jitload.py
'.join(hex(arg) for arg in arg_vals), hex(ret_ad)) return ret_ad, arg_vals return newfunc class CallbackHandler(object): "Handle a list of callback" def __init__(self): self.callbacks = {} # Key -> [callback list] def add_callback(self, name, callback): ...
elif jit_type == "gcc": from miasm2.jitter.jitcore_gcc import JitCore_Gcc as JitCore else: raise ValueError("Unknown jitter %s" % jit_type) except ImportError: raise RuntimeError('Unsupported jitter: %s' % jit_type) self.jit = JitCore...
from miasm2.jitter.jitcore_python import JitCore_Python as JitCore
conditional_block
jitload.py
def __eq__(self, to_cmp): if not isinstance(to_cmp, ExceptionHandle): return False return (self.except_flag == to_cmp.except_flag) class jitter: "Main class for JIT handling" C_Gen = CGen def __init__(self, ir_arch, jit_type="gcc"): """Init an instance of jitter. ...
"""Get unicode str from vm. @addr: address in memory @max_char: maximum len""" l = 0 tmp = addr while ((max_char is None or l < max_char) and self.vm.get_mem(tmp, 2) != "\x00\x00"): tmp += 2 l += 2 s = self.vm.get_mem(addr, l) ...
identifier_body
jitload.py
'.join(hex(arg) for arg in arg_vals), hex(ret_ad)) return ret_ad, arg_vals return newfunc class CallbackHandler(object): "Handle a list of callback" def __init__(self): self.callbacks = {} # Key -> [callback list] def add_callback(self, name, callback): ...
if old_pc != self.pc: return # Exceptions should never be activated before run assert(self.get_exception
# If a callback changed pc, re call every callback
random_line_split
jitload.py
'.join(hex(arg) for arg in arg_vals), hex(ret_ad)) return ret_ad, arg_vals return newfunc class CallbackHandler(object): "Handle a list of callback" def __init__(self): self.callbacks = {} # Key -> [callback list] def add_callback(self, name, callback): ...
(self, name, *args): """Call callbacks associated to key 'name' with arguments args. While callbacks return True, continue with next callback. Iterator on other results.""" res = True for c in self.get_callbacks(name): res = c(*args) if res is not True: ...
call_callbacks
identifier_name
regex_query.rs
use crate::error::TantivyError; use crate::query::{AutomatonWeight, Query, Weight}; use crate::schema::Field; use crate::Searcher; use std::clone::Clone; use std::sync::Arc; use tantivy_fst::Regex; /// A Regex Query matches all of the documents /// containing a specific term that matches /// a regex pattern. /// /// W...
) -> crate::Result<Box<dyn Weight>> { Ok(Box::new(self.specialized_weight())) } } #[cfg(test)] mod test { use super::RegexQuery; use crate::assert_nearly_equals; use crate::collector::TopDocs; use crate::schema::TEXT; use crate::schema::{Field, Schema}; use crate::{Index, IndexR...
impl Query for RegexQuery { fn weight( &self, _searcher: &Searcher, _scoring_enabled: bool,
random_line_split
regex_query.rs
use crate::error::TantivyError; use crate::query::{AutomatonWeight, Query, Weight}; use crate::schema::Field; use crate::Searcher; use std::clone::Clone; use std::sync::Arc; use tantivy_fst::Regex; /// A Regex Query matches all of the documents /// containing a specific term that matches /// a regex pattern. /// /// W...
<T: Into<Arc<Regex>>>(regex: T, field: Field) -> Self { RegexQuery { regex: regex.into(), field, } } fn specialized_weight(&self) -> AutomatonWeight<Regex> { AutomatonWeight::new(self.field, self.regex.clone()) } } impl Query for RegexQuery { fn weight( ...
from_regex
identifier_name
regex_query.rs
use crate::error::TantivyError; use crate::query::{AutomatonWeight, Query, Weight}; use crate::schema::Field; use crate::Searcher; use std::clone::Clone; use std::sync::Arc; use tantivy_fst::Regex; /// A Regex Query matches all of the documents /// containing a specific term that matches /// a regex pattern. /// /// W...
#[test] pub fn test_regex_query() -> crate::Result<()> { let (reader, field) = build_test_index()?; let matching_one = RegexQuery::from_pattern("jap[ao]n", field)?; let matching_zero = RegexQuery::from_pattern("jap[A-Z]n", field)?; verify_regex_query(matching_one, matching_zer...
{ let searcher = reader.searcher(); { let scored_docs = searcher .search(&query_matching_one, &TopDocs::with_limit(2)) .unwrap(); assert_eq!(scored_docs.len(), 1, "Expected only 1 document"); let (score, _) = scored_docs[0]; ...
identifier_body
visit-cancel.leaveline.guard.ts
import { Injectable } from '@angular/core'; import { CanDeactivate, ActivatedRoute, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { TranslateService } from '@ngx-translate/core'; import { TicketInfoContainerComponent } from '../container/ticke...
implements CanDeactivate<TicketInfoContainerComponent> { public confirmMsg: string; constructor(private confirmDialogService: ConfirmDialogService, private translate: TranslateService) { this.translate.get('ticketInfo.leaveVisitConfirmMsg').subscribe((res: string) => { this.confir...
VisitCancelLeavelineGuard
identifier_name
visit-cancel.leaveline.guard.ts
import { TicketInfoContainerComponent } from '../container/ticket-info-container.component'; import { ConfirmDialogService } from "../../shared/confirm-dialog/confirm-dialog.service"; @Injectable() export class VisitCancelLeavelineGuard implements CanDeactivate<TicketInfoContainerComponent> { public confirmMsg: ...
import { Injectable } from '@angular/core'; import { CanDeactivate, ActivatedRoute, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { TranslateService } from '@ngx-translate/core';
random_line_split
visit-cancel.leaveline.guard.ts
import { Injectable } from '@angular/core'; import { CanDeactivate, ActivatedRoute, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { TranslateService } from '@ngx-translate/core'; import { TicketInfoContainerComponent } from '../container/ticke...
else { return true; } } }
{ if (!component.isVisitCanceledOnce()) { this.confirmDialogService.activate(this.confirmMsg).then(res => { if (res === true) { component.setVisitCancelCalled(true); component.cancelVisit(); return tr...
conditional_block
ansitowin32.py
m = None if windll is not None: winterm = WinTerm() def is_stream_closed(stream): return not hasattr(stream, 'closed') or stream.closed def is_a_tty(stream): return hasattr(stream, 'isatty') and stream.isatty() class StreamWrapper(object): ''' Wraps a stream (such as stdout), ac...
if len(params) == 0: # defaults: if command in 'JKm': params = (0,) elif command in 'ABCD': params = (1,) return params def call_win32(self, command, params): if command == 'm': ...
# defaults: params = params + (1,) else: params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)
random_line_split
ansitowin32.py
m = None if windll is not None: winterm = WinTerm() def is_stream_closed(stream): return not hasattr(stream, 'closed') or stream.closed def is_a_tty(stream): return hasattr(stream, 'isatty') and stream.isatty() class StreamWrapper(object): ''' Wraps a stream (such as stdout), ac...
(self, text, start, end): if start < end: self.wrapped.write(text[start:end]) self.wrapped.flush() def convert_ansi(self, paramstring, command): if self.convert: params = self.extract_params(command, paramstring) self.call_win32(command, par...
write_plain_text
identifier_name
ansitowin32.py
m = None if windll is not None: winterm = WinTerm() def is_stream_closed(stream): return not hasattr(stream, 'closed') or stream.closed def is_a_tty(stream): return hasattr(stream, 'isatty') and stream.isatty() class StreamWrapper(object): ''' Wraps a stream (such as stdout), ac...
def reset_all(self): if self.convert: self.call_win32('m', (0,)) elif not self.strip and not is_stream_closed(self.wrapped): self.wrapped.write(Style.RESET_ALL) def write_and_convert(self, text): ''' Write the given text to our wrapped str...
self.reset_all()
conditional_block
ansitowin32.py
winterm = None if windll is not None: winterm = WinTerm() def is_stream_closed(stream): return not hasattr(stream, 'closed') or stream.closed def is_a_tty(stream): return hasattr(stream, 'isatty') and stream.isatty() class StreamWrapper(object): ''' Wraps a stream (such as stdou...
def write_plain_text(self, text, start, end): if start < end: self.wrapped.write(text[start:end]) self.wrapped.flush() def convert_ansi(self, paramstring, command): if self.convert: params = self.extract_params(command, paramstring) ...
''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 text = self.convert_osc(text) for match in self.ANSI_CSI_RE.finditer(text): start, end =...
identifier_body
node.py
import sys, os, json physical_addess = '' node_info = None def getMacAddress(): if sys.platform == 'win32': for line in os.popen("ipconfig /all"): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace('-',':') break else: ...
(new_node = False, userId = None): global physical_addess global node_info if not physical_addess: physical_addess = getMacAddress() f = open('node.json', 'r') node_info = json.loads(f.read()) f.close() node_info['physicalAddress'] = physical_addess if userId is not None: ...
get
identifier_name
node.py
import sys, os, json physical_addess = '' node_info = None def getMacAddress(): if sys.platform == 'win32': for line in os.popen("ipconfig /all"): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace('-',':') break else: ...
node_info.pop("id", None) return node_info def update(node): global node_info node_info = node f = open('node.json', 'w') serialized = json.dumps(node, sort_keys=True, indent=4, separators=(',', ': ')) f.write(serialized) f.close() return 1
if userId is not None: node_info['userId'] = userId if new_node:
random_line_split
node.py
import sys, os, json physical_addess = '' node_info = None def getMacAddress():
def get(new_node = False, userId = None): global physical_addess global node_info if not physical_addess: physical_addess = getMacAddress() f = open('node.json', 'r') node_info = json.loads(f.read()) f.close() node_info['physicalAddress'] = physical_addess if userId is not N...
if sys.platform == 'win32': for line in os.popen("ipconfig /all"): if line.lstrip().startswith('Physical Address'): mac = line.split(':')[1].strip().replace('-',':') break else: for line in os.popen("/sbin/ifconfig"): if line.find('Ether') > -1: ...
identifier_body
node.py
import sys, os, json physical_addess = '' node_info = None def getMacAddress(): if sys.platform == 'win32': for line in os.popen("ipconfig /all"): if line.lstrip().startswith('Physical Address'):
else: for line in os.popen("/sbin/ifconfig"): if line.find('Ether') > -1: mac = line.split()[4] break return mac def get(new_node = False, userId = None): global physical_addess global node_info if not physical_addess: physical_addess = getMacAd...
mac = line.split(':')[1].strip().replace('-',':') break
conditional_block
retrieve.py
"""Retrieves the paths to the required schedule files.""" from datetime import datetime import logging import pytz from unipath import Path # Setup Logging LOG = logging.getLogger(__name__) def
(tz_string): """Generates todays date as string (in format yyyy-mm-dd)""" schedule_tz = pytz.timezone(tz_string) today = datetime.now(schedule_tz) return today.strftime('%Y-%m-%d') def retrieve_schedule_file_paths(config): """Creates the path to the schedules from supplied config file.""" sche...
get_date
identifier_name
retrieve.py
"""Retrieves the paths to the required schedule files.""" from datetime import datetime import logging import pytz from unipath import Path # Setup Logging LOG = logging.getLogger(__name__) def get_date(tz_string): """Generates todays date as string (in format yyyy-mm-dd)""" schedule_tz = pytz.timezone(tz_...
# Return the final details return { 'a': Path(schedule_loc, file_name_a), 'p': Path(schedule_loc, file_name_p), 't': Path(schedule_loc, file_name_t), }
"""Creates the path to the schedules from supplied config file.""" schedule_loc = config['excel']['schedule_loc'] date = get_date(config['timezone']) # Assemble the details for the assistant schedule file_name_a = '{0}_{1}.{2}'.format( date, 'assistant', config['excel']['ext_a'] ) # A...
identifier_body
retrieve.py
"""Retrieves the paths to the required schedule files."""
import logging import pytz from unipath import Path # Setup Logging LOG = logging.getLogger(__name__) def get_date(tz_string): """Generates todays date as string (in format yyyy-mm-dd)""" schedule_tz = pytz.timezone(tz_string) today = datetime.now(schedule_tz) return today.strftime('%Y-%m-%d') def...
from datetime import datetime
random_line_split
l2_agent_extensions_manager.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
(agent_ext_manager.AgentExtensionsManager): """Manage l2 agent extensions. The handle_port and delete_port methods are guaranteed to be attributes of each extension because they have been marked as abc.abstractmethod in the extensions' abstract class. """ def __init__(self, conf): sup...
L2AgentExtensionsManager
identifier_name
l2_agent_extensions_manager.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
def delete_port(self, context, data): """Notify all agent extensions to delete port.""" for extension in self: if hasattr(extension.obj, 'delete_port'): extension.obj.delete_port(context, data) else: LOG.error( "Agent Exte...
if hasattr(extension.obj, 'handle_port'): extension.obj.handle_port(context, data) else: LOG.error( "Agent Extension '%(name)s' does not " "implement method handle_port", {'name': extension.name} )
conditional_block
l2_agent_extensions_manager.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
)
else: LOG.error( "Agent Extension '%(name)s' does not " "implement method delete_port", {'name': extension.name}
random_line_split
l2_agent_extensions_manager.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
"""Notify all agent extensions to delete port.""" for extension in self: if hasattr(extension.obj, 'delete_port'): extension.obj.delete_port(context, data) else: LOG.error( "Agent Extension '%(name)s' does not " "imp...
identifier_body
day22.rs
#[macro_use] extern crate clap; use clap::App; extern crate regex; use std::error::Error; use std::fs::File; use std::io::prelude::*; use regex::Regex; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; #[derive(Clone,Debug)] struct GameState { player : Character, boss : Character, ...
active_spells : Vec<Spell> } impl Character { fn new(hp : i32, damage : u32, mana : u32) -> Character { Character { hp : hp, damage : damage, armor : 0, mana : mana, mana_usage : 0, active_spells : Vec::new() } } } #...
armor : u32, mana : u32, mana_usage : u32,
random_line_split
day22.rs
#[macro_use] extern crate clap; use clap::App; extern crate regex; use std::error::Error; use std::fs::File; use std::io::prelude::*; use regex::Regex; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; #[derive(Clone,Debug)] struct GameState { player : Character, boss : Character, ...
(&mut self) { if !self.players_turn { let damage = std::cmp::max(1, self.boss.damage - self.player.armor); self.player.hp -= damage as i32; } } fn apply_spells(&mut self) { self.player.armor = 0; // Init to no shield for s in &mut self.player.active_spel...
apply_boss_damage
identifier_name
day22.rs
#[macro_use] extern crate clap; use clap::App; extern crate regex; use std::error::Error; use std::fs::File; use std::io::prelude::*; use regex::Regex; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; #[derive(Clone,Debug)] struct GameState { player : Character, boss : Character, ...
} mana_usage } fn build_spell_list() -> Vec<Spell> { let mut spells = Vec::new(); spells.push(Spell::new("Shield", 113, 0, 0, 7, 0, 6)); spells.push(Spell::new("Poison", 173, 3, 0, 0, 0, 6)); spells.push(Spell::new("Magic Missle", 53, 4, 0, 0, 0, 0)); spells.push(Spell:...
{ // Run boss code game.apply_boss_damage(); if game.player.hp > 0 { game.players_turn = true; // If neither player or boss won, start next round let new_mana_usage = find_min_mana_usage(game.clone(), spells, hard_mode); ...
conditional_block
day22.rs
#[macro_use] extern crate clap; use clap::App; extern crate regex; use std::error::Error; use std::fs::File; use std::io::prelude::*; use regex::Regex; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; #[derive(Clone,Debug)] struct GameState { player : Character, boss : Character, ...
fn add_spell(&mut self, spell : Spell) { self.player.mana -= spell.mana_cost; self.player.mana_usage += spell.mana_cost; if spell.turns > 0 { if spell.name == "Shield" || spell.name == "Recharge" { self.player.active_spells.push(spell); } else { ...
{ let mut on = false; for s in &self.player.active_spells { if s.name == spell.name { on = true; break; } } if !on { for s in &self.boss.active_spells { if s.name == spell.name { on =...
identifier_body
display.py
# Copyright 2018 Flight Lab authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
arguments=[ '--kiosk', self._index_file, '--new-window', '--incognito', '--noerrordialogs', '--user-data-dir={0}'.format(self._temp_path) ], restart_on_crash=True) def close(self): """Closes Chrome browser.""" self._chrome_app.stop() def show_message(self, m...
"""Class for displaying arbitrary content on a machine. The implementation assumes Chrome browser is available on given machine and use it to display generated html content in kiosk mode so it appears as an app and works on any platform. """ def __init__(self, chrome_path, *args, **kwargs): """Creates D...
identifier_body
display.py
# Copyright 2018 Flight Lab authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
(self): self._chrome_app.stop() self._chrome_app.start()
_relaunch
identifier_name
display.py
# Copyright 2018 Flight Lab authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
"""Class for displaying arbitrary content on a machine. The implementation assumes Chrome browser is available on given machine and use it to display generated html content in kiosk mode so it appears as an app and works on any platform. """ def __init__(self, chrome_path, *args, **kwargs): """Creates...
class Display(pattern.Closable):
random_line_split
conf.py
# -*- coding: utf-8 -*- # # Progdupeupl documentation build configuration file, created by # sphinx-quickstart on Sat Dec 07 17:25:18 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referrin...
random_line_split
mac_notification.py
# -*- coding: utf-8 -*- # This program 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 later version. # # This program is distributed ...
notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(info_text) notification.setDeliveryDate_(Foundation.NSDate.dateWithTimeInterval_sinceDate_( delay, Foundation.NSDate.date())) NSUserNotification...
identifier_body
mac_notification.py
# -*- coding: utf-8 -*- # This program 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 later version. # # This program is distributed ...
(title, subtitle, info_text, delay=0): notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(info_text) notification.setDeliveryDate_(Foundation.NSDate.dateWithTimeInterval_sinceDate_( delay, Founda...
notifyMac
identifier_name
mac_notification.py
# This program 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 later version. # # This program is distributed in the hope that it will...
# -*- coding: utf-8 -*-
random_line_split
ZmConvView2.ts
/* * T4Z - TypeScript 4 Zimlet * Copyright (C) 2017 ZeXtras S.r.l. * * This file is part of T4Z - TypeScript 4 Zimlet. * * This program 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, version 2 of * t...
extends ZmMailMsgView { }
ZmMailMsgCapsuleView
identifier_name
ZmConvView2.ts
/* * T4Z - TypeScript 4 Zimlet * Copyright (C) 2017 ZeXtras S.r.l.
* This file is part of T4Z - TypeScript 4 Zimlet. * * This program 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, version 2 of * the License. * * This program is distributed in the hope that it will b...
*
random_line_split
mesFonctions.js
function debounce(callback, delay) { var timer; return function () { var args = arguments; var context = this; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, delay) } } function throttle(callback, delay) { var last; var timer; return functi...
// ex. downloadFileJS('\ufeff' + rowTabs.join("\r\n").replace(/,/g, ";"), "lastexecvtom.csv", 'text/csv;charset:utf-8'); var downloadFileJS = function (content, fileName, mimeType) { var a = document.createElement('a'); mimeType = mimeType || 'application/octet-stream'; if (navigator.msSaveBlob) { // IE10 n...
// The download function takes a CSV string, the filename and mimeType as parameters // Scroll/look down at the bottom of this snippet to see how download is called // Pour avoir les accents et télécharger en CSV lisible par Excel, il faut rajouter le BOM dans content
random_line_split
mesFonctions.js
function debounce(callback, delay) { var timer; return function () { var args = arguments; var context = this; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, delay) } } function throttle(callback, delay) { var last; var timer; return functi...
xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response); } else { reject(xhr.statusText); } }; xhr.onerror = () => reject(xhr.statusText); xhr.send(obj.body); }); }; // Random Index moins un tableau d'index qu'on fournit en entrée function...
Object.keys(obj.headers).forEach(key => { xhr.setRequestHeader(key, obj.headers[key]); }); }
conditional_block
mesFonctions.js
function
(callback, delay) { var timer; return function () { var args = arguments; var context = this; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, delay) } } function throttle(callback, delay) { var last; var timer; return function () { var c...
debounce
identifier_name
mesFonctions.js
function debounce(callback, delay)
function throttle(callback, delay) { var last; var timer; return function () { var context = this; var now = +new Date(); var args = arguments; if (last && now < last + delay) { // le délai n'est pas écoulé on reset le timer clearTimeout(timer); timer = setTimeout(function () {...
{ var timer; return function () { var args = arguments; var context = this; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, delay) } }
identifier_body
query_breakdown_runner.ts
import {Progress, CancellationToken} from 'vscode'; import {exec} from 'child_process'; import {ResultJson} from './resultJson'; import * as config from './toolconfig.json'; /** * query_breakdown_runner contains the QueryBreakdownRunner class that is used to * run the backend (query_breakdown) jar file from VS code ...
// method that executes the query_breakdown program. It returns a promise as it is called asynchronously execute( filepath: string, progress: Progress<{message?: string | undefined}>, token: CancellationToken ): Promise<ResultJson[]> { if (token.isCancellationRequested) { return Promise.re...
{}
identifier_body