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
runtests.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # https://github.com/swistakm/django-rest-framework/blob/master/rest_framework/runtests/runtests.py import os import sys # fix sys path so we don't need to setup PYTHONPATH sys.path.append(os.path.join(os.path.dirname(__file__), "../..")) os.environ['DJANGO_SETTINGS_MODUL...
def main(): TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=2) if len(sys.argv) == 2: test_case = '.' + sys.argv[1] elif len(sys.argv) == 1: test_case = '' else: print(usage()) sys.exit(1) patch_for_test_db_setup() failures = test_run...
return """ Usage: python runtests.py [UnitTestClass].[method] You can pass the Class name of the `UnitTestClass` you want to test. Append a method name if you only want to test a specific method of that class. """
identifier_body
register.service.js
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl...
(_http) { this._http = _http; } RegService.prototype.ngOnInit = function () { }; RegService.prototype.getUsers = function () { return this._http.get('http://ankitesh.pythonanywhere.com/api/v1.0/get_books_data') .map(function (response) { return response.json(); }); }; ...
RegService
identifier_name
register.service.js
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Refl...
RegService.prototype.ngOnInit = function () { }; RegService.prototype.getUsers = function () { return this._http.get('http://ankitesh.pythonanywhere.com/api/v1.0/get_books_data') .map(function (response) { return response.json(); }); }; RegService.prototype.regUser = function (U...
{ this._http = _http; }
identifier_body
creader.rs
i.attrs.iter().all(|attr| { attr.name().get() != "phase" || attr.meta_item_list().map_or(false, |phases| { attr::contains_name(phases.as_slice(), "link") }) }) } fn visit_view_item(e: &mut Env, i: &ast::ViewItem) { if !should_link(i) { return; } ...
Loader { env: Env { sess: sess,
random_line_split
creader.rs
, cstore: &CStore) { let mut map = HashMap::new(); cstore.iter_crate_data(|cnum, data| { let crateid = data.crate_id(); let key = (crateid.name.clone(), crateid.path.clone()); map.find_or_insert_with(key, |_| Vec::new()).push(cnum); }); for ((name, _), dupes) in map.move_iter() ...
{ match existing_match(e, crate_id, hash) { None => { let id_hash = link::crate_id_hash(crate_id); let mut load_ctxt = loader::Context { sess: e.sess, span: span, ident: ident, crate_id: crate_id, id_hash...
identifier_body
creader.rs
_: ()) { visit_view_item(self, a); visit::walk_view_item(self, a, ()); } fn
(&mut self, a: &ast::Item, _: ()) { visit_item(self, a); visit::walk_item(self, a, ()); } } fn dump_crates(cstore: &CStore) { debug!("resolved crates:"); cstore.iter_crate_data_origins(|_, data, opt_source| { debug!("crate_id: {}", data.crate_id()); debug!(" cnum: {}", data...
visit_item
identifier_name
creader.rs
_: ()) { visit_view_item(self, a); visit::walk_view_item(self, a, ()); } fn visit_item(&mut self, a: &ast::Item, _: ()) { visit_item(self, a); visit::walk_item(self, a, ()); } } fn dump_crates(cstore: &CStore) { debug!("resolved crates:"); cstore.iter_crate_data_ori...
} } } fn should_link(i: &ast::ViewItem) -> bool { i.attrs.iter().all(|attr| { attr.name().get() != "phase" || attr.meta_item_list().map_or(false, |phases| { attr::contains_name(phases.as_slice(), "link") }) }) } fn visit_view_item(e: &mut Env, i: &a...
{ /* fallthrough */ }
conditional_block
parser_predictor.py
from typing import Dict, Any, List, Optional import numpy from allennlp.common.util import JsonDict from allennlp.data import DatasetReader from allennlp.models import Model from allennlp.predictors.predictor import Predictor import depccg.parsing from depccg.types import ScoringResult, Token from depccg.allennlp.pre...
Token.of_word(word) for word in output_dict['words'].split(' ') ] doc.append(tokens) dep_scores = numpy.array(output_dict['heads']) \ .reshape(output_dict['heads_shape']) \ .astype(numpy.float32) tag_scores ...
random_line_split
parser_predictor.py
from typing import Dict, Any, List, Optional import numpy from allennlp.common.util import JsonDict from allennlp.data import DatasetReader from allennlp.models import Model from allennlp.predictors.predictor import Predictor import depccg.parsing from depccg.types import ScoringResult, Token from depccg.allennlp.pre...
(self, output_dicts: List[Dict[str, Any]]) -> List[JsonDict]: categories = None score_results = [] doc = [] for output_dict in super()._make_json(output_dicts): if categories is None: categories = [ Category.parse(category) ...
_make_json
identifier_name
parser_predictor.py
from typing import Dict, Any, List, Optional import numpy from allennlp.common.util import JsonDict from allennlp.data import DatasetReader from allennlp.models import Model from allennlp.predictors.predictor import Predictor import depccg.parsing from depccg.types import ScoringResult, Token from depccg.allennlp.pre...
return output_dicts
tree_dict = json_of(tree) tree_dict['log_prob'] = log_prob output_dict['trees'].append(tree_dict)
conditional_block
parser_predictor.py
from typing import Dict, Any, List, Optional import numpy from allennlp.common.util import JsonDict from allennlp.data import DatasetReader from allennlp.models import Model from allennlp.predictors.predictor import Predictor import depccg.parsing from depccg.types import ScoringResult, Token from depccg.allennlp.pre...
.reshape(output_dict['head_tags_shape']) \ .astype(numpy.float32) score_results.append(ScoringResult(tag_scores, dep_scores)) if self.category_dict is not None: doc, score_results = depccg.parsing.apply_category_filters( doc, ...
categories = None score_results = [] doc = [] for output_dict in super()._make_json(output_dicts): if categories is None: categories = [ Category.parse(category) for category in output_dict['categories'] ] ...
identifier_body
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; /// An entity tag /// /// An Etag consists of a string enclosed by two literal double quotes. /// Preceding the first double quote is an optional weakness indicator, /// which always looks like this: W/ /// See also: https://tools.ietf.org/html/rfc7232#section-2.3 ...
} if slice.slice_chars(0, 3) == "W/\"" { if check_slice_validity(slice.slice_chars(3, length-1)) { return Ok(EntityTag { weak: true, tag: slice.slice_chars(3, length-1).to_string() }); } else { ...
{ return Err(()); }
conditional_block
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; /// An entity tag /// /// An Etag consists of a string enclosed by two literal double quotes. /// Preceding the first double quote is an optional weakness indicator, /// which always looks like this: W/ /// See also: https://tools.ietf.org/html/rfc7232#section-2.3 ...
} }
etag = "unmatched-dquotes2\"".parse(); assert_eq!(etag, Err(())); etag = "matched-\"dquotes\"".parse(); assert_eq!(etag, Err(()));
random_line_split
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; /// An entity tag /// /// An Etag consists of a string enclosed by two literal double quotes. /// Preceding the first double quote is an optional weakness indicator, /// which always looks like this: W/ /// See also: https://tools.ietf.org/html/rfc7232#section-2.3 ...
{ /// Weakness indicator for the tag pub weak: bool, /// The opaque string in between the DQUOTEs pub tag: String } impl Display for EntityTag { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if self.weak { try!(write!(fmt, "{}", "W/")); } write!(fmt, ...
EntityTag
identifier_name
entity.rs
use std::str::FromStr; use std::fmt::{self, Display}; /// An entity tag /// /// An Etag consists of a string enclosed by two literal double quotes. /// Preceding the first double quote is an optional weakness indicator, /// which always looks like this: W/ /// See also: https://tools.ietf.org/html/rfc7232#section-2.3 ...
} else { return Err(()); } } if slice.slice_chars(0, 3) == "W/\"" { if check_slice_validity(slice.slice_chars(3, length-1)) { return Ok(EntityTag { weak: true, tag: slice.slice_chars(3, length-1)...
{ let length: usize = s.len(); let slice = &s[..]; // Early exits: // 1. The string is empty, or, // 2. it doesn't terminate in a DQUOTE. if slice.is_empty() || !slice.ends_with("\"") { return Err(()); } // The etag is weak if its first char ...
identifier_body
main.rs
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; fn main() { let secret_number: u32 = rand::thread_rng().gen_range(1, 101); //println!("The secret number is {}", secret_number); println!("Guess the number!");
println!("Please enter your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect("Failed to read line."); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; println!("Y...
loop {
random_line_split
main.rs
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; fn
() { let secret_number: u32 = rand::thread_rng().gen_range(1, 101); //println!("The secret number is {}", secret_number); println!("Guess the number!"); loop { println!("Please enter your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) ...
main
identifier_name
main.rs
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; fn main()
println!("You guessed {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("Correct!"); break; } } } }...
{ let secret_number: u32 = rand::thread_rng().gen_range(1, 101); //println!("The secret number is {}", secret_number); println!("Guess the number!"); loop { println!("Please enter your guess."); let mut guess = String::new(); io::stdin().read_line(&mut guess) .ex...
identifier_body
home.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'my-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { active_view: string; constructor(pr...
ngOnInit() { this.setActiveViewFromRoute(); } setActiveView(av: string): void { this.active_view = av; } }
}
random_line_split
home.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'my-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { active_view: string; constructor(pr...
clickSign(): void { this.router.navigate(['/sign']); } clickBrowse(): void { this.router.navigate(['/browse']); } clickSearch(): void { this.router.navigate(['/search']); } private setActiveViewFromRoute(): void { let path_segs = this.route.snapshot.url; ...
{ this.router.navigate(['/']); }
identifier_body
home.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'my-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { active_view: string; constructor(pr...
console.log('ActiveView = '+this.active_view); } ngOnInit() { this.setActiveViewFromRoute(); } setActiveView(av: string): void { this.active_view = av; } }
{ this.setActiveView('welcome'); }
conditional_block
home.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'my-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { active_view: string; constructor(pr...
(av: string): void { this.active_view = av; } }
setActiveView
identifier_name
remove-form.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { FormService } from '../../../../shared/services/form.service'; import { AppService } from '../../../../shared/services/app.service'; @Component({ selector: 'respond-remove-form', templateUrl: 'remove-form.component.html', prov...
} }
random_line_split
remove-form.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { FormService } from '../../../../shared/services/form.service'; import { AppService } from '../../../../shared/services/app.service'; @Component({ selector: 'respond-remove-form', templateUrl: 'remove-form.component.html', prov...
(private _formService: FormService, private _appService: AppService) {} /** * Init */ ngOnInit() { this.model = { id: '', name: '' }; } /** * Hides the modal */ hide() { this._visible = false; this.onCancel.emit(null); } /** * Submits the form */ submi...
constructor
identifier_name
remove-form.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { FormService } from '../../../../shared/services/form.service'; import { AppService } from '../../../../shared/services/app.service'; @Component({ selector: 'respond-remove-form', templateUrl: 'remove-form.component.html', prov...
// outputs @Output() onCancel = new EventEmitter<any>(); @Output() onUpdate = new EventEmitter<any>(); @Output() onError = new EventEmitter<any>(); constructor (private _formService: FormService, private _appService: AppService) {} /** * Init */ ngOnInit() { this.model = { id: '', ...
{ // set visible this.model = form; }
identifier_body
SrvMoreToursInitInfoCommandSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { PokerCommandHeaderSerializer } from "../../core/serializers/PokerCommandHeaderSerializer"; import { PokerCommandHeader } from "../../core/data/PokerCommandHeader"; import { SrvMoreToursInitInfoCommand } from "../commands/SrvMoreToursIn...
(buffer: ArrayBufferBuilder, command: SrvMoreToursInitInfoCommand ): void { buffer.pointer += PokerCommandHeader.HEADER_SIZE_BYTES; SrvMoreToursInitInfoDataSerializer.serialize(buffer, command.data); PokerCommandHeaderSerializer.serialize(buffer, command.header); } public static deserialize(buffer: ArrayBu...
serialize
identifier_name
SrvMoreToursInitInfoCommandSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { PokerCommandHeaderSerializer } from "../../core/serializers/PokerCommandHeaderSerializer"; import { PokerCommandHeader } from "../../core/data/PokerCommandHeader"; import { SrvMoreToursInitInfoCommand } from "../commands/SrvMoreToursIni...
command.data = new SrvMoreToursInitInfoData(); SrvMoreToursInitInfoDataSerializer.deserialize(buffer, command.data); } }
random_line_split
make-flac.py
#!/usr/bin/env python # file: make-flac.py # vim:fileencoding=utf-8:fdm=marker:ft=python # # Copyright © 2012-2018 R.F. Smith <rsmith@xs4all.nl>. # SPDX-License-Identifier: MIT # Created: 2012-12-22T00:12:03+01:00 # Last modified: 2020-04-01T00:19:43+0200 """ Encodes WAV files from cdparanoia (“trackNN.cdda.wav”) to FL...
logging.debug(f"command line arguments = {sys.argv}") logging.debug(f"parsed arguments = {args}") # Check for required programs. try: sp.run(["flac"], stdout=sp.DEVNULL, stderr=sp.DEVNULL) logging.debug("found “flac”") except FileNotFoundError: logging.error("the program “fla...
logging.basicConfig( level=getattr(logging, args.log.upper(), None), format="%(levelname)s: %(message)s", )
random_line_split
make-flac.py
#!/usr/bin/env python # file: make-flac.py # vim:fileencoding=utf-8:fdm=marker:ft=python # # Copyright © 2012-2018 R.F. Smith <rsmith@xs4all.nl>. # SPDX-License-Identifier: MIT # Created: 2012-12-22T00:12:03+01:00 # Last modified: 2020-04-01T00:19:43+0200 """ Encodes WAV files from cdparanoia (“trackNN.cdda.wav”) to FL...
""" Use the flac(1) program to convert a music file to FLAC format. Arguments: idx: track index (starts from 0) data: album data dictionary Returns: A tuple containing the track index and return value of flac. """ num = idx + 1 ifn = f"track{num:02d}.cdda.wav" args ...
):
identifier_name
make-flac.py
#!/usr/bin/env python # file: make-flac.py # vim:fileencoding=utf-8:fdm=marker:ft=python # # Copyright © 2012-2018 R.F. Smith <rsmith@xs4all.nl>. # SPDX-License-Identifier: MIT # Created: 2012-12-22T00:12:03+01:00 # Last modified: 2020-04-01T00:19:43+0200 """ Encodes WAV files from cdparanoia (“trackNN.cdda.wav”) to FL...
ing.info("album name: " + data["title"]) logging.info("artist: " + data["artist"]) logging.info("year: " + str(data["year"])) logging.info("genre: " + data["genre"]) num = len(data["tracks"]) with cf.ThreadPoolExecutor(max_workers=os.cpu_count()) as tp: for idx, rv in tp.map(partial(runflac,...
t in keys: logging.error(f'key "{key}" not in "{tfn}"') sys.exit(1) logg
conditional_block
make-flac.py
#!/usr/bin/env python # file: make-flac.py # vim:fileencoding=utf-8:fdm=marker:ft=python # # Copyright © 2012-2018 R.F. Smith <rsmith@xs4all.nl>. # SPDX-License-Identifier: MIT # Created: 2012-12-22T00:12:03+01:00 # Last modified: 2020-04-01T00:19:43+0200 """ Encodes WAV files from cdparanoia (“trackNN.cdda.wav”) to FL...
f"-TTRACKNUM={num:02d}", "-o", f"track{num:02d}.flac", ifn, ] p = sp.run(args, stdout=sp.DEVNULL, stderr=sp.DEVNULL) return (idx, p.returncode) if __name__ == "__main__": main()
lac(1) program to convert a music file to FLAC format. Arguments: idx: track index (starts from 0) data: album data dictionary Returns: A tuple containing the track index and return value of flac. """ num = idx + 1 ifn = f"track{num:02d}.cdda.wav" args = [ "flac...
identifier_body
rtf.py
__license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' """ Edit metadata in RTF files. """ import re, cStringIO, codecs from calibre import force_unicode from calibre.ebooks.metadata import MetaInformation, string_to_authors title_pat = re.compile(r'\{\\info.*?\{\\title(.*?)(?<!\\)...
(stream): pat = re.compile(r'\\ansicpg(\d+)') match = pat.search(stream.read(512)) if match is not None: num = match.group(1) if num == '0': num = '1252' codec = 'cp'+num try: codecs.lookup(codec) return codec except: pa...
detect_codepage
identifier_name
rtf.py
__license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' """ Edit metadata in RTF files. """ import re, cStringIO, codecs from calibre import force_unicode from calibre.ebooks.metadata import MetaInformation, string_to_authors title_pat = re.compile(r'\{\\info.*?\{\\title(.*?)(?<!\\)...
def uni(match): return unichr(int(match.group(1))) raw = re.sub(r'\\u([0-9]{3,4}).', uni, raw) return raw def get_metadata(stream): """ Return metadata as a L{MetaInfo} object """ stream.seek(0) if stream.read(5) != r'{\rtf': return MetaInformation(_('Unknown')) bl...
return chr(int(match.group(1), 16)) raw = re.sub(r"\\'([a-fA-F0-9]{2})", codepage, raw) raw = raw.decode(codec)
random_line_split
rtf.py
__license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' """ Edit metadata in RTF files. """ import re, cStringIO, codecs from calibre import force_unicode from calibre.ebooks.metadata import MetaInformation, string_to_authors title_pat = re.compile(r'\{\\info.*?\{\\title(.*?)(?<!\\)...
author_match = author_pat.search(block) if author_match is not None: author = decode(author_match.group(1).strip(), cpg) else: author = None mi = MetaInformation(title) if author: mi.authors = string_to_authors(author) comment_match = comment_pat.search(block) if co...
title = _('Unknown')
conditional_block
rtf.py
__license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' """ Edit metadata in RTF files. """ import re, cStringIO, codecs from calibre import force_unicode from calibre.ebooks.metadata import MetaInformation, string_to_authors title_pat = re.compile(r'\{\\info.*?\{\\title(.*?)(?<!\\)...
raw = re.sub(r"\\'([a-fA-F0-9]{2})", codepage, raw) raw = raw.decode(codec) def uni(match): return unichr(int(match.group(1))) raw = re.sub(r'\\u([0-9]{3,4}).', uni, raw) return raw def get_metadata(stream): """ Return metadata as a L{MetaInfo} object """ stream.s...
return chr(int(match.group(1), 16))
identifier_body
data-table-checkbox-cell.component.ts
import { CdkCell, CdkColumnDef } from '@angular/cdk/table'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, HostBinding, Input, OnDestroy, OnInit, Renderer2, } from '@angular/core'; import { Subscription } from 'rxjs'; import { NovoDataTable } from '../data-table.component'...
(): boolean { return this.maxSelected && this.dataTable.state.selectedRows.size >= this.maxSelected && !this.checked; } constructor( public columnDef: CdkColumnDef, elementRef: ElementRef, renderer: Renderer2, public dataTable: NovoDataTable<T>, private ref: ChangeDetectorRef, ) { sup...
isAtLimit
identifier_name
data-table-checkbox-cell.component.ts
import { CdkCell, CdkColumnDef } from '@angular/cdk/table'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, HostBinding, Input, OnDestroy, OnInit, Renderer2, } from '@angular/core'; import { Subscription } from 'rxjs'; import { NovoDataTable } from '../data-table.component'...
} public getTooltip() { return this.isAtLimit ? 'More than ' + this.maxSelected + ' items are not able to be selected at one time' : ''; } public ngOnDestroy(): void { if (this.selectionSubscription) { this.selectionSubscription.unsubscribe(); } if (this.resetSubscription) { this....
{ this.dataTable.selectRow(this.row, 'onClick'); }
conditional_block
data-table-checkbox-cell.component.ts
import { CdkCell, CdkColumnDef } from '@angular/cdk/table'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, HostBinding, Input, OnDestroy, OnInit, Renderer2, } from '@angular/core'; import { Subscription } from 'rxjs'; import { NovoDataTable } from '../data-table.component'...
}
{ if (this.selectionSubscription) { this.selectionSubscription.unsubscribe(); } if (this.resetSubscription) { this.resetSubscription.unsubscribe(); } }
identifier_body
data-table-checkbox-cell.component.ts
import { CdkCell, CdkColumnDef } from '@angular/cdk/table'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, HostBinding, Input, OnDestroy, OnInit, Renderer2, } from '@angular/core'; import { Subscription } from 'rxjs'; import { NovoDataTable } from '../data-table.component'...
@Input() public row: T; @Input() public maxSelected: number = undefined; public checked: boolean = false; private selectionSubscription: Subscription; private resetSubscription: Subscription; get isAtLimit(): boolean { return this.maxSelected && this.dataTable.state.selectedRows.size >= this.maxS...
@HostBinding('attr.role') public role = 'gridcell';
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use ascii::AsciiString; use mercurial_types::{ blobs::HgBlobChangeset, HgBlob, HgChangesetId, HgFileNodeId, HgManif...
use thiserror::Error; #[derive(Debug)] pub enum StateOpenError { Heads, Bookmarks, Changesets, Filenodes, BonsaiGitMapping, BonsaiGlobalrevMapping, BonsaiSvnrevMapping, BonsaiHgMapping, Phases, HgMutationStore, SegmentedChangelog, } impl fmt::Display for StateOpenError { ...
}; use mononoke_types::{hash::Sha256, ChangesetId, FileType}; use std::fmt;
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![deny(warnings)] use ascii::AsciiString; use mercurial_types::{ blobs::HgBlobChangeset, HgBlob, HgChangesetId, HgFileNodeId, HgManif...
{ #[error("Error while opening state for {0}")] StateOpen(StateOpenError), #[error("Node id {0} is missing")] NodeMissing(HgNodeHash), #[error("Content missing nodeid {0}")] ContentMissing(HgNodeHash), #[error("Error while deserializing file contents retrieved from key '{0}'")] FileCont...
ErrorKind
identifier_name
datatypes.rs
use serde_json; use std::io; use std::string::FromUtf8Error; #[derive(Deserialize, Debug)] pub struct Event { pub version: String, pub event: String, pub data: DownloadComplete } #[derive(Deserialize, Debug)] pub struct
{ pub update_id: String, pub update_image: String, pub signature: String } #[derive(Debug)] pub enum Error { Custom(String), Io(io::Error), Json(serde_json::Error), Utf8(FromUtf8Error) } impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) ...
DownloadComplete
identifier_name
datatypes.rs
use serde_json; use std::io; use std::string::FromUtf8Error; #[derive(Deserialize, Debug)] pub struct Event { pub version: String, pub event: String, pub data: DownloadComplete } #[derive(Deserialize, Debug)] pub struct DownloadComplete { pub update_id: String, pub update_image: String, ...
impl From<io::Error> for Error { fn from(err: io::Error) -> Error { Error::Io(err) } } impl From<FromUtf8Error> for Error { fn from(err: FromUtf8Error) -> Error { Error::Utf8(err) } } impl From<serde_json::Error> for Error { fn from(err: serde_json::Error) -> Error { Error...
Io(io::Error), Json(serde_json::Error), Utf8(FromUtf8Error) }
random_line_split
datatypes.rs
use serde_json; use std::io; use std::string::FromUtf8Error; #[derive(Deserialize, Debug)] pub struct Event { pub version: String, pub event: String, pub data: DownloadComplete } #[derive(Deserialize, Debug)] pub struct DownloadComplete { pub update_id: String, pub update_image: String, ...
}
{ Error::Json(err) }
identifier_body
env.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
if len(z[0]) == 0: raise Exception("Error: incorrect format for env var: '%s'" % str(args[x])) del args[0] if len(z[1]) == 0: # value is not present, so delete it if z[0] in new_env: del new_env[z[0]] else: new_env[z[0]] = ...
break; # done with env args
conditional_block
env.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
(argv=None): parser = OptionParser(usage="Usage: %prog [options] [--] VAR=VALUE... command [options] arg1 arg2...") parser.add_option("-i", "--ignore-environment", action="store_true", default=False, help="Start with an empty environment (do not inherit current envir...
main
identifier_name
env.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
if new_env.get("VALGRIND") and new_env.get("VALGRIND_ALL"): # Python generates a lot of possibly-lost errors that are not errors, don't show them. args = [new_env.get("VALGRIND"), "--show-reachable=no", "--show-possibly-lost=no", "--error-exitcode=42"] + args p = subprocess.Pope...
raise Exception("Error: syntax error in command arguments")
random_line_split
env.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
if len(z[1]) == 0: # value is not present, so delete it if z[0] in new_env: del new_env[z[0]] else: new_env[z[0]] = z[1] if len(args) == 0 or len(args[0]) == 0: raise Exception("Error: syntax error in command arguments") if new_env.ge...
parser = OptionParser(usage="Usage: %prog [options] [--] VAR=VALUE... command [options] arg1 arg2...") parser.add_option("-i", "--ignore-environment", action="store_true", default=False, help="Start with an empty environment (do not inherit current environment)") (op...
identifier_body
share.ts
import {Component} from '@angular/core'; import {Platform} from 'ionic-angular'; import {SocialSharing} from 'ionic-native'; /* This component is intented to be as an easy and simple example of: http://ionicframework.com/docs/v2/native/social-sharing/ */ @Component({ templateUrl: 'build/pages/share/share.html'...
}); }; shareViaFacebook() { this.platform.ready().then(() => { if (SocialSharing.canShareVia("facebook")) { SocialSharing.shareViaFacebookWithPasteMessageHint(this.shareMsg, null, null, 'Paste your facebook comment!'); } }); }; }
{ SocialSharing.shareViaTwitter(this.shareMsg, null, null); }
conditional_block
share.ts
import {Component} from '@angular/core'; import {Platform} from 'ionic-angular'; import {SocialSharing} from 'ionic-native'; /* This component is intented to be as an easy and simple example of: http://ionicframework.com/docs/v2/native/social-sharing/ */ @Component({ templateUrl: 'build/pages/share/share.html'...
{ public shareMsg:string; constructor(private platform:Platform) { this.platform = platform; this.shareMsg = "Hey! I'm currently in a workshop at http://angularcamp.org starting an Ionic 2 app! @AngularCamp #AngularCamp"; } share() { this.platform.ready().then(() => { ...
SharePage
identifier_name
share.ts
import {Component} from '@angular/core'; import {Platform} from 'ionic-angular'; import {SocialSharing} from 'ionic-native'; /* This component is intented to be as an easy and simple example of: http://ionicframework.com/docs/v2/native/social-sharing/ */ @Component({
export class SharePage { public shareMsg:string; constructor(private platform:Platform) { this.platform = platform; this.shareMsg = "Hey! I'm currently in a workshop at http://angularcamp.org starting an Ionic 2 app! @AngularCamp #AngularCamp"; } share() { this.platform.ready(...
templateUrl: 'build/pages/share/share.html' })
random_line_split
functional.ts
const R = require('ramda'); /** * Function to find by id. */ export const findById = (id) => R.find(item => item._id === id); /** * returns a new Object result from assigning a new property to the object provided *
/** * Returns a new array of files where the file passed is filtered * file: the file to be filtered. */ export const filterFile = R.curry((id, files) => R.filter((item) => item._id !== id)(files)); /** * Returns a new array of files where one file has been replaced * id: id of the file to be replaced * getRe...
* * note: R.flip ensures the new property overrides the previous one if it existed. */ export const assign = R.flip(R.merge);
random_line_split
generate-ios-source-and-headers.py
#!/usr/bin/env python import subprocess import re import os import errno import collections import sys class Platform(object): pass sdk_re = re.compile(r'.*-sdk ([a-zA-Z0-9.]*)') def sdkinfo(sdkname): ret = {} for line in subprocess.Popen(['xcodebuild', '-sdk', sdkname, '-version'], stdout=subprocess.PI...
if __name__ == '__main__': main()
header.write('#include <%s_%s%s>\n' % (basename, arch, suffix))
conditional_block
generate-ios-source-and-headers.py
#!/usr/bin/env python import subprocess import re import os import errno import collections import sys class
(object): pass sdk_re = re.compile(r'.*-sdk ([a-zA-Z0-9.]*)') def sdkinfo(sdkname): ret = {} for line in subprocess.Popen(['xcodebuild', '-sdk', sdkname, '-version'], stdout=subprocess.PIPE).stdout: kv = line.strip().split(': ', 1) if len(kv) == 2: k,v = kv ret[k] =...
Platform
identifier_name
generate-ios-source-and-headers.py
#!/usr/bin/env python import subprocess import re import os import errno import collections import sys class Platform(object): pass sdk_re = re.compile(r'.*-sdk ([a-zA-Z0-9.]*)') def sdkinfo(sdkname):
sim_sdk_info = sdkinfo('iphonesimulator') device_sdk_info = sdkinfo('iphoneos') def latest_sdks(): latest_sim = None latest_device = None for line in subprocess.Popen(['xcodebuild', '-showsdks'], stdout=subprocess.PIPE).stdout: match = sdk_re.match(line) if match: if 'Simulato...
ret = {} for line in subprocess.Popen(['xcodebuild', '-sdk', sdkname, '-version'], stdout=subprocess.PIPE).stdout: kv = line.strip().split(': ', 1) if len(kv) == 2: k,v = kv ret[k] = v return ret
identifier_body
generate-ios-source-and-headers.py
#!/usr/bin/env python import subprocess import re import os import errno import collections import sys class Platform(object): pass sdk_re = re.compile(r'.*-sdk ([a-zA-Z0-9.]*)') def sdkinfo(sdkname): ret = {} for line in subprocess.Popen(['xcodebuild', '-sdk', sdkname, '-version'], stdout=subprocess.PI...
sim_sdk_info = sdkinfo('iphonesimulator') device_sdk_info = sdkinfo('iphoneos') def latest_sdks(): latest_sim = None latest_device = None for line in subprocess.Popen(['xcodebuild', '-showsdks'], stdout=subprocess.PIPE).stdout: match = sdk_re.match(line) if match: if 'Simulator...
ret[k] = v return ret
random_line_split
models.js
//models // models.AuthInfo = Backbone.Model.extend({ defaults: { 'name': '', // username, NOT trusted (comes from client) but helpful w/debugging and double check. 'cookie': '', // the full string of cookies from the user 'roomId': '' // the room the user is trying to get into } }); /** Commands **...
}); } process(result, this); return JSON.stringify(result); }; Backbone.Model.prototype.mport = function (data, silent) { //console.log("DATA FROM mport:\n
{ if (key !== 'collection' && source[key] instanceof Backbone.Collection) { targetObj.collections = targetObj.collections || {}; targetObj.collections[key] = {}; targetObj.collections[key].models = []; targetObj.collections[key].id = source[key].id || null; _.each(source[key].models, ...
conditional_block
models.js
//models // models.AuthInfo = Backbone.Model.extend({ defaults: { 'name': '', // username, NOT trusted (comes from client) but helpful w/debugging and double check. 'cookie': '', // the full string of cookies from the user 'roomId': '' // the room the user is trying to get into } }); /** Commands **...
(targetObj, source) { targetObj.id = source.id || null; targetObj.cid = source.cid || null; targetObj.attrs = source.toJSON(); _.each(source, function (value, key) { // since models store a reference to their collection // we need to make sure we don't create a circular refrence if (settings.rec...
process
identifier_name
models.js
({ command: 'openprivate', roomId: options.roomId, users: options.users }); } }); models.InitqueryCommand = models.Command.extend({ initialize: function(){ this.set({ command: 'initquery' }); } }); models.LogoutCommand = models.Command.extend({ initialize: function(){ this.set(...
{ targetObj.id = data.id || null; targetObj.set(data.attrs, {silent: silent}); // loop through each collection if (data.collections) { _.each(data.collections, function (collection, name) { targetObj[name].id = collection.id; _.each(collection.models, function (modelData, index) { var n...
identifier_body
models.js
// //models // models.AuthInfo = Backbone.Model.extend({ defaults: { 'name': '', // username, NOT trusted (comes from client) but helpful w/debugging and double check. 'cookie': '', // the full string of cookies from the user 'roomId': '' // the room the user is trying to get into } }); /** Commands...
}, initialize: function() { modelInit.apply(this,arguments); } }); models.NodeChatModelCS = models.NodeChatModel.extend({ initialize: function() { modelInit.apply(this,arguments); this.room = new models.ChatRoom(); } }); models.User = Backbone.Model.extend({ defaults: { 'name': '', 'si...
random_line_split
ru_RU.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ru_RU = require('gregorian-calendar-format/lib/locale/ru_RU'); var _ru_RU2 = _interopRequireDefault(_ru_RU); function
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { today: 'Сегодня', now: 'Сейчас', ok: 'Ok', clear: 'Очистить', month: 'Месяц', year: 'Год', monthSelect: 'Выберите месяц', yearSelect: 'Выберите год', decadeSelect: 'Выберите десятилетие', yearFormat: 'yyyy', date...
_interopRequireDefault
identifier_name
ru_RU.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ru_RU = require('gregorian-calendar-format/lib/locale/ru_RU'); var _ru_RU2 = _interopRequireDefault(_ru_RU); function _interopRequireDefault(obj)
exports.default = { today: 'Сегодня', now: 'Сейчас', ok: 'Ok', clear: 'Очистить', month: 'Месяц', year: 'Год', monthSelect: 'Выберите месяц', yearSelect: 'Выберите год', decadeSelect: 'Выберите десятилетие', yearFormat: 'yyyy', dateFormat: 'd-M-yyyy', monthFormat: 'MMMM', monthBeforeYear: tr...
{ return obj && obj.__esModule ? obj : { default: obj }; }
identifier_body
ru_RU.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ru_RU = require('gregorian-calendar-format/lib/locale/ru_RU'); var _ru_RU2 = _interopRequireDefault(_ru_RU); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { toda...
nextMonth: 'Следующий месяц (PageDown)', previousYear: 'Предыдущий год (Control + left)', nextYear: 'Следующий год (Control + right)', previousDecade: 'Предыдущее десятилетие', nextDecade: 'Следущее десятилетие', previousCentury: 'Предыдущий век', nextCentury: 'Следующий век', format: _ru_RU2.default };...
monthBeforeYear: true, previousMonth: 'Предыдущий месяц (PageUp)',
random_line_split
errata_corrige.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Modules used for ETL - Create User # Modules required: import os import xmlrpclib, sys, csv, ConfigParser from datetime import datetime # Set up parameters (for connection to Open ERP Database) ********************* config = ConfigParser.ConfigParser() file_config = o...
print "Partner updated"
random_line_split
errata_corrige.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Modules used for ETL - Create User # Modules required: import os import xmlrpclib, sys, csv, ConfigParser from datetime import datetime # Set up parameters (for connection to Open ERP Database) ********************* config = ConfigParser.ConfigParser() file_config = o...
result = sock.execute(dbname, uid, pwd, "quality.claim" , "correct_parent_partner") print "Partner updated"
conditional_block
track_list.js
rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. (function() { 'use strict'; Polymer('track-list', { /** * Initializes an element. This method is called automatically when the * element is ready. */ ready: function() {...
getCurrentTrack: function() { if (this.tracks.length === 0) return null; return this.tracks[this.currentTrackIndex]; }, /** * Returns the next (or previous) track in the track list. If there is no * next track, returns -1. * * @param {boolean} forward Specify direct...
* Returns the current track. * @param {AudioPlayer.TrackInfo} track TrackInfo of the current track. */
random_line_split
space.rs
use std::marker::PhantomData; use std::slice; use cgmath::{BaseFloat, Transform, Transform3}; use id::{Array, Id, Storage}; #[derive(Clone, Copy, Debug)] pub enum Parent<T> { None, Domestic(Id<Node<T>>), Foreign(Id<Skeleton<T>>, Id<Bone<T>>), } #[derive(Debug)] pub struct Node<T> { pub name : String, ...
(&mut self, id: Id<Node<T>>) -> &mut Node<T> { self.nodes.get_mut(id) } pub fn find_node(&self, name: &str) -> Option<Id<Node<T>>> { self.nodes.find_id(|n| n.name == name) } pub fn add_node(&mut self, name: String, parent: Parent<T>, local: T) -> Id<Node<T>> { ...
mut_node
identifier_name
space.rs
use std::marker::PhantomData; use std::slice;
None, Domestic(Id<Node<T>>), Foreign(Id<Skeleton<T>>, Id<Bone<T>>), } #[derive(Debug)] pub struct Node<T> { pub name : String, pub parent: Parent<T>, pub local: T, pub world: T, } #[derive(Debug)] pub struct Bone<T> { pub name : String, parent: Option<Id<Bone<T>>>, pub local: T...
use cgmath::{BaseFloat, Transform, Transform3}; use id::{Array, Id, Storage}; #[derive(Clone, Copy, Debug)] pub enum Parent<T> {
random_line_split
nodrop.rs
//! The **nodrop** crate from arrayvec use std::ops::{Deref, DerefMut}; use std::ptr; /// repr(u8) - Make sure the non-nullable pointer optimization does not occur! #[repr(u8)] enum Flag<T> { Alive(T), // Dummy u8 field below, again to beat the enum layout opt Dropped(u8), } /// A type holding **T** that...
(&mut self) { let n = self.0.get(); self.0.set(n + 1); } } { let _ = NoDrop::new([Bump(flag), Bump(flag)]); } assert_eq!(flag.get(), 0); // test something with the nullable pointer optimization flag.set(0); ...
drop
identifier_name
nodrop.rs
//! The **nodrop** crate from arrayvec use std::ops::{Deref, DerefMut}; use std::ptr; /// repr(u8) - Make sure the non-nullable pointer optimization does not occur! #[repr(u8)] enum Flag<T> { Alive(T), // Dummy u8 field below, again to beat the enum layout opt Dropped(u8), } /// A type holding **T** that...
// last one didn't drop. assert_eq!(flag.get(), 3); } }
drop(array.pop()); assert_eq!(flag.get(), 3); }
random_line_split
cursor.rs
)] pub struct SynomBuffer { // NOTE: Do not derive clone on this - there are raw pointers inside which // will be messed up. Moving the `SynomBuffer` itself is safe as the actual // backing slices won't be moved. data: Box<[Entry]>, } impl SynomBuffer { // NOTE: DO NOT MUTATE THE `Vec` RETURNED FRO...
(mut self, seq_delim: Delimiter) -> Option<SeqInfo<'a>> { // If we're not trying to enter a none-delimited sequence, we want to // ignore them. We have to make sure to _not_ ignore them when we want // to enter them, of course. For obvious reasons. if seq_delim != Delimiter::None { ...
seq
identifier_name
cursor.rs
)] pub struct SynomBuffer { // NOTE: Do not derive clone on this - there are raw pointers inside which // will be messed up. Moving the `SynomBuffer` itself is safe as the actual // backing slices won't be moved. data: Box<[Entry]>, } impl SynomBuffer { // NOTE: DO NOT MUTATE THE `Vec` RETURNED FRO...
_ => None } } /// If the cursor is pointing at a Term, return it and a cursor pointing at /// the next `TokenTree`. pub fn word(mut self) -> Option<(Cursor<'a>, Span, Term)> { self.ignore_none(); match *self.entry() { Entry::Term(span, sym) => { ...
{ // If we're not trying to enter a none-delimited sequence, we want to // ignore them. We have to make sure to _not_ ignore them when we want // to enter them, of course. For obvious reasons. if seq_delim != Delimiter::None { self.ignore_none(); } match *sel...
identifier_body
cursor.rs
(Debug)] pub struct SynomBuffer { // NOTE: Do not derive clone on this - there are raw pointers inside which // will be messed up. Moving the `SynomBuffer` itself is safe as the actual // backing slices won't be moved. data: Box<[Entry]>, } impl SynomBuffer { // NOTE: DO NOT MUTATE THE `Vec` RETURN...
static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry)); Cursor { ptr: &EMPTY_ENTRY.0, scope: &EMPTY_ENTRY.0, marker: PhantomData, } } /// This create method intelligently exits non-explicitly-entered /// ...
// This wrapper struct allows us to break the rules and put a `Sync` // object in global storage. struct UnsafeSyncEntry(Entry); unsafe impl Sync for UnsafeSyncEntry {}
random_line_split
uses-optimized-images.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or a...
extends ByteEfficiencyAudit { /** * @return {!AuditMeta} */ static get meta() { return { name: 'uses-optimized-images', description: 'Optimize images', informative: true, helpText: 'Optimized images load faster and consume less cellular data. ' + '[Learn more](https://deve...
UsesOptimizedImages
identifier_name
uses-optimized-images.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or a...
/** * @param {!Artifacts} artifacts * @return {!Audit.HeadingsResult} */ static audit_(artifacts) { const images = artifacts.OptimizedImages; const failedImages = []; const results = []; images.forEach(image => { if (image.failed) { failedImages.push(image); return; ...
const bytes = image.originalSize - image[type + 'Size']; const percent = 100 * bytes / image.originalSize; return {bytes, percent}; }
random_line_split
uses-optimized-images.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or a...
const url = URL.elideDataURI(image.url); const jpegSavings = UsesOptimizedImages.computeSavings(image, 'jpeg'); results.push({ url, fromProtocol: image.fromProtocol, isCrossOrigin: !image.isSameOrigin, preview: {url: image.url, mimeType: image.mimeType, type: 'thumbn...
{ return; }
conditional_block
skin-picker.ts
import Vue from "vue"; import { Component, Prop } from "vue-property-decorator"; import { ChampSelectState, default as ChampSelect, SkinItem } from "./champ-select"; import Root from "../root/root"; @Component export default class SkinPicker extends Vue { $root: Root; $parent: ChampSelect; @Prop() sta...
/** * Selects the specified summoner, optionally swapping the spells. */ selectSkin(skin: SkinItem) { if (!skin.ownership.owned) return; this.$root.request("/lol-champ-select/v1/session/my-selection", "PATCH", JSON.stringify({ selectedSkinId: skin.id })); ...
{ // Find ID of selected champion. const member = this.state.localPlayer; const act = this.$parent.getActions(member); const champId = (act ? act.championId : 0) || member.championId || member.championPickIntent; if (!champId) return []; // Also return unavailable skins,...
identifier_body
skin-picker.ts
import Vue from "vue"; import { Component, Prop } from "vue-property-decorator"; import { ChampSelectState, default as ChampSelect, SkinItem } from "./champ-select"; import Root from "../root/root"; @Component export default class SkinPicker extends Vue { $root: Root; $parent: ChampSelect; @Prop() sta...
* @returns the url to the splashart for the specified skin id */ getSkinImage(skin: SkinItem): string { const champ = this.$parent.championDetails[skin.championId]; if (!champ) return ""; return `background-image: url(https://ddragon.leagueoflegends.com/cdn/img/champion/splash/${c...
this.$emit("close"); } /**
random_line_split
skin-picker.ts
import Vue from "vue"; import { Component, Prop } from "vue-property-decorator"; import { ChampSelectState, default as ChampSelect, SkinItem } from "./champ-select"; import Root from "../root/root"; @Component export default class SkinPicker extends Vue { $root: Root; $parent: ChampSelect; @Prop() sta...
(skin: SkinItem) { if (!skin.ownership.owned) return; this.$root.request("/lol-champ-select/v1/session/my-selection", "PATCH", JSON.stringify({ selectedSkinId: skin.id })); this.$emit("close"); } /** * @returns the url to the splashart for the specified skin i...
selectSkin
identifier_name
Default.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2006 STZ-IDA, Germany, http://www.stz-ida.de 2007 Visionet GmbH, http://www.visionet.de License: LGPL: http://www.gnu.org/licenses/lgpl.html ...
else { if (rowInfo.selected) { style.backgroundColor = this._colors.bgcolSelected; } else { style.backgroundColor = (rowInfo.row % 2 == 0) ? this._colors.bgcolEven : this._colors.bgcolOdd; } } style.color = rowInfo.selected ? ...
{ style.backgroundColor = rowInfo.selected ? this._colors.bgcolFocusedSelected : this._colors.bgcolFocused; }
conditional_block
Default.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2006 STZ-IDA, Germany, http://www.stz-ida.de 2007 Visionet GmbH, http://www.visionet.de License: LGPL: http://www.gnu.org/licenses/lgpl.html ...
/* ***************************************************************************** PROPERTIES ***************************************************************************** */ properties : { /** Whether the focused row should be highlighted. */ highlightFocusRow : { check : "Boolean...
this._colors.colNormal = colorMgr.resolve("table-row"); this._colors.horLine = colorMgr.resolve("table-row-line"); },
random_line_split
mainMenu.ts
module $safeprojectname$.Client { export class MainMenu extends Phaser.State { background: Phaser.Sprite; logo: Phaser.Sprite; create() { this.background = this.add.sprite(0, 0, 'titlepage'); this.background.alpha = 0; this.logo = this.add.spr...
{ this.add.audio('click', 1, false).play(); this.add.tween(this.background).to({ alpha: 0 }, 2000, Phaser.Easing.Linear.None, true); var tween = this.add.tween(this.logo).to({ y: 800 }, 2000, Phaser.Easing.Linear.None, true); tween.onComplete.add(this.startG...
deOut()
identifier_name
mainMenu.ts
module $safeprojectname$.Client { export class MainMenu extends Phaser.State { background: Phaser.Sprite; logo: Phaser.Sprite; create() { this.background = this.add.sprite(0, 0, 'titlepage'); this.background.alpha = 0; this.logo = this.add.spr...
startGame() { this.game.state.start('Level01', true, false); } } }
this.add.audio('click', 1, false).play(); this.add.tween(this.background).to({ alpha: 0 }, 2000, Phaser.Easing.Linear.None, true); var tween = this.add.tween(this.logo).to({ y: 800 }, 2000, Phaser.Easing.Linear.None, true); tween.onComplete.add(this.startGame...
identifier_body
mainMenu.ts
module $safeprojectname$.Client { export class MainMenu extends Phaser.State { background: Phaser.Sprite; logo: Phaser.Sprite; create() { this.background = this.add.sprite(0, 0, 'titlepage'); this.background.alpha = 0; this.logo = this.add.spr...
} } }
startGame() { this.game.state.start('Level01', true, false);
random_line_split
main.py
import pygame import src.sprite as game pygame.init() screen = pygame.display.set_mode((400,300)) done = False GameUpdateList = [] GameRenderList = [] catapult = game.Sprite("data/img/catapult.png", 5) boulder = None catapultAnim = game.Animation(catapult, 96, 96, 5, 100) GameUpdateList.append(catapultAnim) GameR...
# Atualiza tempo dt = pygame.time.get_ticks() - last_time last_time = pygame.time.get_ticks() # Atualiza timer da catapulta em ms for obj in GameUpdateList: obj.update(dt) #catapultAnim.update(dt) shotBoulder(dt) for obj in GameRenderList: obj.render(screen) #catapultAnim.render(scr...
done = True
random_line_split
main.py
import pygame import src.sprite as game pygame.init() screen = pygame.display.set_mode((400,300)) done = False GameUpdateList = [] GameRenderList = [] catapult = game.Sprite("data/img/catapult.png", 5) boulder = None catapultAnim = game.Animation(catapult, 96, 96, 5, 100) GameUpdateList.append(catapultAnim) GameR...
(dt): global boulder if( catapultAnim.isReady() ): catapultAnim.pause = True catapultAnim.forceFrame() if(boulder == None): boulder = game.Sprite("data/img/boulder.png") boulder.pos[0] = 46 boulder.pos[1] = 7 GameRenderList.append(boulder) if(boulder != None): dt *= ...
shotBoulder
identifier_name
main.py
import pygame import src.sprite as game pygame.init() screen = pygame.display.set_mode((400,300)) done = False GameUpdateList = [] GameRenderList = [] catapult = game.Sprite("data/img/catapult.png", 5) boulder = None catapultAnim = game.Animation(catapult, 96, 96, 5, 100) GameUpdateList.append(catapultAnim) GameR...
# Testes -------------------------------------- last_time = pygame.time.get_ticks() while not done: screen.fill((255,255,255)) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # Atualiza tempo dt = pygame.time.get_ticks() - last_time last_time = pygame.time.get_ticks() ...
GameRenderList.remove(boulder) boulder = None catapultAnim.forceFrame(0) catapultAnim.pause = False
conditional_block
main.py
import pygame import src.sprite as game pygame.init() screen = pygame.display.set_mode((400,300)) done = False GameUpdateList = [] GameRenderList = [] catapult = game.Sprite("data/img/catapult.png", 5) boulder = None catapultAnim = game.Animation(catapult, 96, 96, 5, 100) GameUpdateList.append(catapultAnim) GameR...
# Testes -------------------------------------- last_time = pygame.time.get_ticks() while not done: screen.fill((255,255,255)) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # Atualiza tempo dt = pygame.time.get_ticks() - last_time last_time = pygame.time.get_ticks() ...
global boulder if( catapultAnim.isReady() ): catapultAnim.pause = True catapultAnim.forceFrame() if(boulder == None): boulder = game.Sprite("data/img/boulder.png") boulder.pos[0] = 46 boulder.pos[1] = 7 GameRenderList.append(boulder) if(boulder != None): dt *= 0.001 ...
identifier_body
codeblock.rs
use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET}; use config::Config; use std::cmp::min; use std::collections::HashSet; use syntect::easy::HighlightLines; use syntect::highlighting::{Color, Style, Theme}; use syntect::html::{styled_line_to_highlighted_html, IncludeBackground}; use syntect::parsing::Sy...
} // Now append the remainder. If the current item was not split, this will // append the entire item. if last_split != item.1.len() { result.push((item.0, &item.1[last_split..])); } } result } fn color_highlighted_lines(data: &mut [(Style, &str)], lines: ...
{ result.push((item.0, &item.1[last_split..split_at])); last_split = split_at; }
conditional_block
codeblock.rs
use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET}; use config::Config; use std::cmp::min; use std::collections::HashSet; use syntect::easy::HighlightLines; use syntect::highlighting::{Color, Style, Theme}; use syntect::html::{styled_line_to_highlighted_html, IncludeBackground}; use syntect::parsing::Sy...
(&mut self, text: &str) -> String { let highlighted = self.highlighter.highlight(text, self.extra_syntax_set.unwrap_or(&SYNTAX_SET)); let line_boundaries = self.find_line_boundaries(&highlighted); // First we make sure that `highlighted` is split at every line // boundary. T...
highlight
identifier_name
codeblock.rs
use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET}; use config::Config; use std::cmp::min; use std::collections::HashSet; use syntect::easy::HighlightLines; use syntect::highlighting::{Color, Style, Theme}; use syntect::html::{styled_line_to_highlighted_html, IncludeBackground}; use syntect::parsing::Sy...
} fn find_line_boundaries(&mut self, styled: &[(Style, &str)]) -> Vec<StyledIdx> { let mut boundaries = Vec::new(); for (vec_idx, (_style, s)) in styled.iter().enumerate() { for (str_idx, character) in s.char_indices() { if character == '\n' { bou...
styled_line_to_highlighted_html(&highlighted, self.background)
random_line_split
codeblock.rs
use config::highlighting::{get_highlighter, SYNTAX_SET, THEME_SET}; use config::Config; use std::cmp::min; use std::collections::HashSet; use syntect::easy::HighlightLines; use syntect::highlighting::{Color, Style, Theme}; use syntect::html::{styled_line_to_highlighted_html, IncludeBackground}; use syntect::parsing::Sy...
/// This function assumes that `line_boundaries` is sorted according to the `Ord` impl on /// the `StyledIdx` type. fn perform_split<'b>( split: &[(Style, &'b str)], line_boundaries: Vec<StyledIdx>, ) -> Vec<(Style, &'b str)> { let mut result = Vec::new(); let mut idxs_iter = line_boundaries.into_ite...
{ match idx { Some(idx) if idx.vec_idx == vec_idx => Some(idx.str_idx), _ => None, } }
identifier_body
predictor.rs
// The MIT License (MIT) // // Copyright (c) 2015 dinowernli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy...
/// Reverts the context tree to a previous state by undoing update /// operations. The specified size must be at most the current size. fn revert_to_history_size(&mut self, target_size: usize); /// Returns the probability, given the current history, that "bits" are the /// next observed symbols. fn predict...
random_line_split
twister.rs
use std::iter::Iterator; pub struct Twister { index: usize, state: [u32; 624], } impl Twister { pub fn new(seed: u32) -> Twister { let mut state = [0u32; 624]; state[0] = seed; for idx in 1..state.len() { state[idx] = (0x6c078965*(state[idx-1] ^ (state[idx-1] >> 30)) as...
fn first_10_0() { let t = Twister::new(0); let first_10 = t.take(10).collect::<Vec<u32>>(); let expected = vec![0x8c7f0aac, 0x97c4aa2f, 0xb716a675, 0xd821ccc0, 0x9a4eb343, 0xdba252fb, 0x8b7d76c3, 0xd8e57d67, 0x6c74a409, 0x9fa1ded3]; ...
assert_eq!(t.index, 0); assert_eq!(t.state[0], 0); } #[test]
random_line_split
twister.rs
use std::iter::Iterator; pub struct Twister { index: usize, state: [u32; 624], } impl Twister { pub fn new(seed: u32) -> Twister { let mut state = [0u32; 624]; state[0] = seed; for idx in 1..state.len() { state[idx] = (0x6c078965*(state[idx-1] ^ (state[idx-1] >> 30)) as...
fn generate_numbers(&mut self) { for idx in 0..self.state.len() { let y = (self.state[idx] & 0x80000000) + (self.state[(idx + 1) % self.state.len()] & 0x7fffffff); self.state[idx] = self.state[(idx + 397) % self.state.len()] ^ (y >> 1); if y % 2 != 0...
{ Twister { index: index, state: *state.clone() } }
identifier_body
twister.rs
use std::iter::Iterator; pub struct Twister { index: usize, state: [u32; 624], } impl Twister { pub fn new(seed: u32) -> Twister { let mut state = [0u32; 624]; state[0] = seed; for idx in 1..state.len() { state[idx] = (0x6c078965*(state[idx-1] ^ (state[idx-1] >> 30)) as...
() { let t = Twister::new(0); let first_10 = t.take(10).collect::<Vec<u32>>(); let expected = vec![0x8c7f0aac, 0x97c4aa2f, 0xb716a675, 0xd821ccc0, 0x9a4eb343, 0xdba252fb, 0x8b7d76c3, 0xd8e57d67, 0x6c74a409, 0x9fa1ded3]; assert_eq![f...
first_10_0
identifier_name
twister.rs
use std::iter::Iterator; pub struct Twister { index: usize, state: [u32; 624], } impl Twister { pub fn new(seed: u32) -> Twister { let mut state = [0u32; 624]; state[0] = seed; for idx in 1..state.len() { state[idx] = (0x6c078965*(state[idx-1] ^ (state[idx-1] >> 30)) as...
} } } impl Iterator for Twister { type Item = u32; fn next(&mut self) -> Option<u32> { if self.index == 0 { self.generate_numbers(); } let mut y = self.state[self.index]; y ^= y >> 11; y ^= y << 7 & 0x9d2c5680; y ^= y << 15 & 0xefc60000; ...
{ self.state[idx] ^= 0x9908b0df; }
conditional_block
configureUrlQuery-test.js
import configureUrlQuery from '../configureUrlQuery'; import urlQueryConfig from '../urlQueryConfig'; it('updates the singleton query object', () => { configureUrlQuery({ test: 99 }); expect(urlQueryConfig.test).toBe(99); configureUrlQuery({ history: 123 }); expect(urlQueryConfig.history).toBe(123); expect(...
expect(urlQueryConfig.keyValSeparator).toBe('-'); configureUrlQuery({ keyValSeparator: '--' }); expect(urlQueryConfig.entrySeparator).toBe('__'); expect(urlQueryConfig.keyValSeparator).toBe('--'); // Reset so it does not effect other tests configureUrlQuery({ entrySeparator: '_', keyValSeparator: '-' }); ...
configureUrlQuery({ entrySeparator: '__' }); expect(urlQueryConfig.entrySeparator).toBe('__');
random_line_split
config.js
const webpack = require('webpack'); const path = require('path'); const { merge } = require('webpack-merge'); const HTMLWebpackPlugin = require('html-webpack-plugin'); const rootPath = (exports.rootPath = path.join(__dirname, '..')); const srcPath = (exports.srcPath = path.join(rootPath, 'src')); const distPath = (exp...
exports.environment = environment; const baseConfig = (exports.baseConfig = { entry: { index: path.join(srcPath, 'index.js'), }, output: { path: distPath, }, resolve: { alias: { '@': srcPath, }, }, plugins: [ new webpack.EnvironmentPlugin({ ENVIRONMENT: environment, ...
{ environment = process.env.BUILD_ENV || 'test'; }
conditional_block
config.js
const webpack = require('webpack'); const path = require('path'); const { merge } = require('webpack-merge'); const HTMLWebpackPlugin = require('html-webpack-plugin'); const rootPath = (exports.rootPath = path.join(__dirname, '..')); const srcPath = (exports.srcPath = path.join(rootPath, 'src')); const distPath = (exp...
ENVIRONMENT: environment, }), new HTMLWebpackPlugin({ title: 'Vue App', template: path.join(srcPath, 'index.ejs'), favicon: path.join(rootPath, 'static/favicon.ico'), }), ], }); exports.devConfig = merge(baseConfig, {}); exports.prodConfig = merge(baseConfig, {});
}, plugins: [ new webpack.EnvironmentPlugin({
random_line_split