file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
str.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 std::alloc::{OncePool};
| #[test]
fn debug_char() {
let mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{:?}", 'a');
write!(&mut buf, "{:?}", 'ä');
write!(&mut buf, "{:?}", '日');
test!(&*buf == "'a''\\u{e4}''\\u{65e5}'");
}
#[test]
fn display_char() {
let mut buf = [0;... | random_line_split | |
topic-trending.component.js | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b)... | else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core"... | random_line_split | |
topic-trending.component.js | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b)... |
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
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) : de... | { this.constructor = d; } | identifier_body |
topic-trending.component.js | "use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b)... | (route, postService, topicService) {
var _this = _super.call(this) || this;
_this.route = route;
_this.postService = postService;
_this.topicService = topicService;
return _this;
}
TopicTrendingComponent.prototype.ngOnInit = function () {
var _this = this;
... | TopicTrendingComponent | identifier_name |
cards.py | from django.conf import settings
from ideascube.configuration import get_config
# For unittesting purpose, we need to mock the Catalog class.
# However, the mock is made in a fixture and at this moment, we don't
# know where the mocked catalog will be used.
# So the fixture mocks 'ideascube.serveradmin.catalog.Catalo... | ():
card_ids = settings.EXTRA_APP_CARDS
return [{'id': i} for i in card_ids]
def build_package_card_info():
package_card_info = []
catalog = catalog_mod.Catalog()
packages_to_display = catalog.list_installed(get_config('home-page', 'displayed-package-ids'))
for package in packages_to_display:... | build_extra_app_card_info | identifier_name |
cards.py | from django.conf import settings
from ideascube.configuration import get_config
# For unittesting purpose, we need to mock the Catalog class.
# However, the mock is made in a fixture and at this moment, we don't
# know where the mocked catalog will be used.
# So the fixture mocks 'ideascube.serveradmin.catalog.Catalo... |
return package_card_info
| card_info = {
'id': package.template_id,
'name': package.name,
'description': getattr(package, 'description', ''),
'lang': getattr(package, 'language', ''),
'package_id': package.id,
'is_staff': getattr(package, 'staff_only', False),
't... | conditional_block |
cards.py | from django.conf import settings
from ideascube.configuration import get_config
# For unittesting purpose, we need to mock the Catalog class.
# However, the mock is made in a fixture and at this moment, we don't
# know where the mocked catalog will be used.
# So the fixture mocks 'ideascube.serveradmin.catalog.Catalo... | return [{'id': i} for i in card_ids]
def build_package_card_info():
package_card_info = []
catalog = catalog_mod.Catalog()
packages_to_display = catalog.list_installed(get_config('home-page', 'displayed-package-ids'))
for package in packages_to_display:
card_info = {
'id': pac... |
def build_extra_app_card_info():
card_ids = settings.EXTRA_APP_CARDS | random_line_split |
cards.py | from django.conf import settings
from ideascube.configuration import get_config
# For unittesting purpose, we need to mock the Catalog class.
# However, the mock is made in a fixture and at this moment, we don't
# know where the mocked catalog will be used.
# So the fixture mocks 'ideascube.serveradmin.catalog.Catalo... |
def build_package_card_info():
package_card_info = []
catalog = catalog_mod.Catalog()
packages_to_display = catalog.list_installed(get_config('home-page', 'displayed-package-ids'))
for package in packages_to_display:
card_info = {
'id': package.template_id,
'name': pa... | card_ids = settings.EXTRA_APP_CARDS
return [{'id': i} for i in card_ids] | identifier_body |
timeentry.ts | import urljoin = require("url-join")
import * as angular from 'angular'
import * as interfaces from './interfaces'
declare var BASE_URL: string
class TimeEntryService implements interfaces.ITimeEntryService {
base_url: string
$http: angular.IHttpService
postfix: string
//constructor($http: ng.)
constructo... | (...urls : Array<string|number>) : string
{
var self = this;
return urljoin(self.base_url, self.postfix, ...urls);
}
}
angular.module('app').factory("TimeEntryService", ($http:angular.IHttpService) =>
{
return new TimeEntryService($http, BASE_URL);
})
| urlCreate | identifier_name |
timeentry.ts | import urljoin = require("url-join")
import * as angular from 'angular'
import * as interfaces from './interfaces'
declare var BASE_URL: string
class TimeEntryService implements interfaces.ITimeEntryService {
base_url: string
$http: angular.IHttpService
postfix: string
//constructor($http: ng.)
constructo... |
urlCreate(...urls : Array<string|number>) : string
{
var self = this;
return urljoin(self.base_url, self.postfix, ...urls);
}
}
angular.module('app').factory("TimeEntryService", ($http:angular.IHttpService) =>
{
return new TimeEntryService($http, BASE_URL);
}) | });
} | random_line_split |
debug_test.js | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// ... |
var message = new proto.jspb.test.Simple1();
message.setAString('foo');
assertObjectEquals({
$name: 'proto.jspb.test.Simple1',
'aString': 'foo',
'aRepeatedStringList': []
}, jspb.debug.dump(message));
message.setABoolean(true);
message.setARepeatedStringList(['1', '2']);
... | {
return;
} | conditional_block |
debug_test.js | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// ... | var extendable = new proto.jspb.test.HasExtensions();
extendable.setStr1('v1');
extendable.setStr2('v2');
extendable.setStr3('v3');
extendable.setExtension(proto.jspb.test.IsExtension.extField, extension);
assertObjectEquals({
'$name': 'proto.jspb.test.HasExtensions',
'str1': 'v1',
... | var extension = new proto.jspb.test.IsExtension();
extension.setExt1('ext1field'); | random_line_split |
fastq_split.py | #!/usr/bin/env python
"""
fastq_split.py [-n|--num_files N_FILES] <input filename> <output directory>
"""
import os
import sys
import math
from srt.fastq import *
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-n", "--num_files", dest="num_files",
help="Number of output files", type... | # Split reads
i = 0
for h,s,q in FastqFile(input_filename):
output_file[i].write(h,s,q)
i = (i+1) % options.num_files
# Close files
for _ in output_file:
_.close() | output_file = []
for i in xrange(options.num_files):
output_filename = format % (i+1)
output_file.append(FastqFile(output_filename, "w"))
| random_line_split |
fastq_split.py | #!/usr/bin/env python
"""
fastq_split.py [-n|--num_files N_FILES] <input filename> <output directory>
"""
import os
import sys
import math
from srt.fastq import *
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-n", "--num_files", dest="num_files",
help="Number of output files", type... |
# Close files
for _ in output_file:
_.close()
| output_file[i].write(h,s,q)
i = (i+1) % options.num_files | conditional_block |
add-instrument-dialog.tsx | import { observer } from "mobx-react";
import { BootstrapDialog, showDialog } from "eez-studio-ui/dialog";
import { Setup, setupState } from "home/setup";
import { action, observable, makeObservable } from "mobx";
const AddInstrumentDialog = observer(
class AddInstrumentDialog extends React.Component<
... | import React from "react";
| random_line_split | |
add-instrument-dialog.tsx | import React from "react";
import { observer } from "mobx-react";
import { BootstrapDialog, showDialog } from "eez-studio-ui/dialog";
import { Setup, setupState } from "home/setup";
import { action, observable, makeObservable } from "mobx";
const AddInstrumentDialog = observer(
class AddInstrumentDialog... | (props: { callback: (instrumentId: string) => void }) {
super(props);
makeObservable(this, {
open: observable,
onAdd: action.bound,
onCancel: action.bound
});
}
onAdd(instrumentId: string) {
this... | constructor | identifier_name |
add-instrument-dialog.tsx | import React from "react";
import { observer } from "mobx-react";
import { BootstrapDialog, showDialog } from "eez-studio-ui/dialog";
import { Setup, setupState } from "home/setup";
import { action, observable, makeObservable } from "mobx";
const AddInstrumentDialog = observer(
class AddInstrumentDialog... | {
setupState.reset();
showDialog(<AddInstrumentDialog callback={callback} />);
} | identifier_body | |
header_chain.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | {
genesis_header: Bytes, // special-case the genesis.
candidates: RwLock<BTreeMap<u64, Entry>>,
headers: RwLock<HashMap<H256, Bytes>>,
best_block: RwLock<BlockDescriptor>,
cht_roots: Mutex<Vec<H256>>,
}
impl HeaderChain {
/// Create a new header chain given this genesis block.
pub fn new(genesis: &[u8]) -> Sel... | HeaderChain | identifier_name |
header_chain.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | }
#[test]
fn reorganize() {
let spec = Spec::new_test();
let genesis_header = spec.genesis_header();
let chain = HeaderChain::new(&::rlp::encode(&genesis_header));
let mut parent_hash = genesis_header.hash();
let mut rolling_timestamp = genesis_header.timestamp();
for i in 1..6 {
let mut header = H... | assert!(chain.get_header(BlockId::Number(9000)).is_some());
assert!(chain.cht_root(2).is_some());
assert!(chain.cht_root(3).is_none()); | random_line_split |
general.rs | use std::fmt::Write;
use eew::*;
pub fn format_eew_full(eew: &EEW) -> String
{
let mut output = String::new();
write_unwrap!(&mut output, "[EEW: {} - {}]\n", eew.id, eew.number);
write_unwrap!(&mut output, "issue_pattern: {:?}, source: {:?}, kind: {:?}, \
issued_at: {:?}, occurred_at: {:?}, status: {:?}\n",... |
output
}
| {
write_unwrap!(&mut output, "epicenter_name: {}, epicenter: {:?}, \
depth: {:?}, magnitude: {:?}, maximum_intensity: {:?}, epicenter_accuracy: {:?}, \
depth_accuracy: {:?}, magnitude_accuracy: {:?}, epicenter_category: {:?}, \
warning_status: {:?}, intensity_change: {:?}, change_reason: {:?}\n",
detail.... | conditional_block |
general.rs | use std::fmt::Write;
use eew::*;
pub fn | (eew: &EEW) -> String
{
let mut output = String::new();
write_unwrap!(&mut output, "[EEW: {} - {}]\n", eew.id, eew.number);
write_unwrap!(&mut output, "issue_pattern: {:?}, source: {:?}, kind: {:?}, \
issued_at: {:?}, occurred_at: {:?}, status: {:?}\n",
eew.issue_pattern, eew.source, eew.kind, eew.issued_at, e... | format_eew_full | identifier_name |
general.rs | use std::fmt::Write;
use eew::*;
pub fn format_eew_full(eew: &EEW) -> String
| {
let mut output = String::new();
write_unwrap!(&mut output, "[EEW: {} - {}]\n", eew.id, eew.number);
write_unwrap!(&mut output, "issue_pattern: {:?}, source: {:?}, kind: {:?}, \
issued_at: {:?}, occurred_at: {:?}, status: {:?}\n",
eew.issue_pattern, eew.source, eew.kind, eew.issued_at, eew.occurred_at, eew.st... | identifier_body | |
general.rs | use std::fmt::Write;
use eew::*;
pub fn format_eew_full(eew: &EEW) -> String
{
let mut output = String::new();
write_unwrap!(&mut output, "[EEW: {} - {}]\n", eew.id, eew.number);
write_unwrap!(&mut output, "issue_pattern: {:?}, source: {:?}, kind: {:?}, \
issued_at: {:?}, occurred_at: {:?}, status: {:?}\n",... | detail.epicenter_name, detail.epicenter, detail.depth,
detail.magnitude, detail.maximum_intensity, detail.epicenter_accuracy,
detail.depth_accuracy, detail.magnitude_accuracy, detail.epicenter_category,
detail.warning_status, detail.intensity_change, detail.change_reason);
for area in detail.area_info.it... | depth: {:?}, magnitude: {:?}, maximum_intensity: {:?}, epicenter_accuracy: {:?}, \
depth_accuracy: {:?}, magnitude_accuracy: {:?}, epicenter_category: {:?}, \
warning_status: {:?}, intensity_change: {:?}, change_reason: {:?}\n", | random_line_split |
mosync-resource.js | /**
* @file mosync.resource.js
* @author Ali Sarrafi
*
* The library for loading Image resources into Mosync program from Javascript.
* This library only supports image resources and used together with the
* NativeUI library.
*/
/**
* The Resource handler submodule of the bridge module.
*/
mosync.resource =... |
};
| {
mosync.bridge.send(
mosync.resource.imageDownloadQueue[0],
null);
} | conditional_block |
mosync-resource.js | /**
* @file mosync.resource.js
* @author Ali Sarrafi
*
* The library for loading Image resources into Mosync program from Javascript.
* This library only supports image resources and used together with the
* NativeUI library.
*/
/**
* The Resource handler submodule of the bridge module.
*/
mosync.resource =... | */
mosync.resource.imageCallBackTable = {};
mosync.resource.imageIDTable = {};
mosync.resource.imageDownloadQueue = [];
/**
* Loads images into image handles for use in MoSync UI systems.
*
* @param imagePath relative path to the image file.
* @param imageID a custom ID used for refering to the image in JavaS... |
/**
* A Hash containing all registered callback functions for
* loadImage function. | random_line_split |
31.py | #!/usr/bin/python
from typing import List
"""
31. Next Permutation
https://leetcode.com/problems/next-permutation/
"""
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
best = None
for i in r... |
if not best:
nums[:] = sorted(nums)
else:
i, j = best
nums[i], nums[j] = nums[j], nums[i]
nums[:] = nums[:i+1] + sorted(nums[i+1:])
def main():
sol = Solution()
# [4, 2, 2, 0, 0, 2, 3]
# [4, 2, 0, 2, 3, 0, 2]
# [4, 2, 0, 3, 0, 2, ... | if (nums[i] < nums[j] and nums[j] < smallest):
smallest = nums[j]
best = i, j | conditional_block |
31.py | #!/usr/bin/python
from typing import List
"""
31. Next Permutation
https://leetcode.com/problems/next-permutation/
"""
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
best = None
for i in r... | ():
sol = Solution()
# [4, 2, 2, 0, 0, 2, 3]
# [4, 2, 0, 2, 3, 0, 2]
# [4, 2, 0, 3, 0, 2, 2]
a = [4, 2, 0, 2, 3, 2, 0]
sol.nextPermutation(a)
print(a)
return 0
if __name__ == '__main__':
raise SystemExit(main())
| main | identifier_name |
31.py | #!/usr/bin/python
from typing import List
"""
31. Next Permutation
https://leetcode.com/problems/next-permutation/
"""
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
best = None
for i in r... |
if __name__ == '__main__':
raise SystemExit(main())
| sol = Solution()
# [4, 2, 2, 0, 0, 2, 3]
# [4, 2, 0, 2, 3, 0, 2]
# [4, 2, 0, 3, 0, 2, 2]
a = [4, 2, 0, 2, 3, 2, 0]
sol.nextPermutation(a)
print(a)
return 0 | identifier_body |
31.py | #!/usr/bin/python
from typing import List
"""
31. Next Permutation | ERROR: type should be large_string, got "\nhttps://leetcode.com/problems/next-permutation/\n\"\"\"\n\n\nclass Solution:\n def nextPermutation(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n best = None\n for i in range(len(nums) - 1):\n smallest = 9999999\n for j in range(i + 1, len(nums)):\n if (nums[i] < nums[j] and nums[j] < smallest):\n smallest = nums[j]\n best = i, j\n\n if not best:\n nums[:] = sorted(nums)\n else:\n i, j = best\n nums[i], nums[j] = nums[j], nums[i]\n nums[:] = nums[:i+1] + sorted(nums[i+1:])\n\n\ndef main():\n sol = Solution()\n # [4, 2, 2, 0, 0, 2, 3]\n # [4, 2, 0, 2, 3, 0, 2]\n # [4, 2, 0, 3, 0, 2, 2]\n a = [4, 2, 0, 2, 3, 2, 0]\n sol.nextPermutation(a)\n print(a)\n return 0\n\n\nif __name__ == '__main__':\n raise SystemExit(main())" | random_line_split | |
main.rs | use std::io;
use std::rand;
use std::cmp::Ordering;
fn main() {
let secret_number = (rand::random::<u32>() % 100) + 1;
println!("Guess the number!");
loop {
println!("Please input your guess.");
let input = io::stdin().read_line()
.ok()
.expect("Fai... | {
if a < b {
Ordering::Less
} else if a > b {
Ordering::Greater
} else {
Ordering::Equal
}
} | identifier_body | |
main.rs | use std::io;
use std::rand;
use std::cmp::Ordering;
fn main() {
let secret_number = (rand::random::<u32>() % 100) + 1;
println!("Guess the number!");
loop {
println!("Please input your guess.");
let input = io::stdin().read_line()
.ok()
.expect("Fai... | };
println!("You guessed: {}", num);
match cmp(num, secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
return;
}
}
}
}
fn cmp(a: u32, b: u32) -> Ordering {
if a < ... | println!("Please input a number!");
continue;
} | random_line_split |
main.rs | use std::io;
use std::rand;
use std::cmp::Ordering;
fn | () {
let secret_number = (rand::random::<u32>() % 100) + 1;
println!("Guess the number!");
loop {
println!("Please input your guess.");
let input = io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.... | main | identifier_name |
manager.rs | /*use std::io::Write;
use dbus::{BusType, Connection, ConnectionItem, Error, Message, MessageItem, NameFlag};
use dbus::obj::{Argument, Interface, Method, ObjectPath, Property};
use constants::*;
pub struct Manager {
running: bool,
}
impl Manager {
pub fn new() -> Manager {
Manager { running: false ... | vec![],
vec![Argument::new("reply", "s")],
Box::new(|msg| {
Ok(vec!(MessageItem::Str(for... | let root_iface = Interface::new(vec![Method::new("Hello", | random_line_split |
assign_generic_numbers_gpcr.py | from django.conf import settings
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.PDB import *
from Bio.PDB.PDBIO import Select
from common.definitions import *
from protein.models import Protein, ProteinSegment
from residue.models import Residue
from structure.functions import BlastSearch... |
# pdb_file can be either a name/path or a handle to an open file
self.pdb_file = pdb_file
self.pdb_filename = pdb_filename
# if pdb 4 letter code is specified
self.pdb_code = pdb_code
# dictionary of 'MappedResidue' object storing information about ... | random_line_split | |
assign_generic_numbers_gpcr.py | from django.conf import settings
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.PDB import *
from Bio.PDB.PDBIO import Select
from common.definitions import *
from protein.models import Protein, ProteinSegment
from residue.models import Residue
from structure.functions import BlastSearch... | (self, prot_id, hsps, chain):
#find uniprot residue numbers corresponding to those in pdb file
q_seq = list(hsps.query)
tmp_seq = list(hsps.sbjct)
subj_counter = hsps.sbjct_start
q_counter = hsps.query_start
logger.info("{}\n{}".format(hsps.query, ... | map_blast_seq | identifier_name |
assign_generic_numbers_gpcr.py | from django.conf import settings
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.PDB import *
from Bio.PDB.PDBIO import Select
from common.definitions import *
from protein.models import Protein, ProteinSegment
from residue.models import Residue
from structure.functions import BlastSearch... |
def map_blast_seq (self, prot_id, hsps, chain):
#find uniprot residue numbers corresponding to those in pdb file
q_seq = list(hsps.query)
tmp_seq = list(hsps.sbjct)
subj_counter = hsps.sbjct_start
q_counter = hsps.query_start
logger.info("... | for res in self.residues[chain].keys():
if self.residues[chain][res].pos_in_aln == pos:
return res
return 0 | identifier_body |
assign_generic_numbers_gpcr.py | from django.conf import settings
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.PDB import *
from Bio.PDB.PDBIO import Select
from common.definitions import *
from protein.models import Protein, ProteinSegment
from residue.models import Residue
from structure.functions import BlastSearch... |
return self.get_annotated_structure()
def assign_generic_numbers_with_sequence_parser(self):
for chain in self.pdb_structure:
for residue in chain:
if chain.id in self.mapping:
if residue.id[1] in self.mapping[chain.id].keys():
... | if alignment == []:
continue
for hsps in alignment[1].hsps:
self.map_blast_seq(alignment[0], hsps, chain) | conditional_block |
math.rs |
use Vec3;
use cgmath::Vector2;
use cgmath::InnerSpace;
use cgmath::dot;
use std;
#[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
pub struct Rect<F> {
pub min : Vector2<F>,
pub max : Vector2<F>,
}
pub type RectI = Rect<i32>;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct LineSegment {
pub from:... |
}
}
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Plane {
pub normal: Vec3,
pub coefficient: f64,
}
impl Plane {
pub fn from_origin_normal(origin:Vec3, normal:Vec3) -> Plane {
Plane {
normal:normal,
coefficient: (normal.x * origin.x + normal.y * origin.y + normal... | {
Some((direction * ratio) + self.from)
} | conditional_block |
math.rs | use Vec3;
use cgmath::Vector2;
use cgmath::InnerSpace;
use cgmath::dot;
use std;
#[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
pub struct Rect<F> {
pub min : Vector2<F>,
pub max : Vector2<F>,
}
pub type RectI = Rect<i32>;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct LineSegment {
pub from: ... |
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Plane {
pub normal: Vec3,
pub coefficient: f64,
}
impl Plane {
pub fn from_origin_normal(origin:Vec3, normal:Vec3) -> Plane {
Plane {
normal:normal,
coefficient: (normal.x * origin.x + normal.y * origin.y + normal.z * orig... | } else {
Some((direction * ratio) + self.from)
}
}
} | random_line_split |
math.rs |
use Vec3;
use cgmath::Vector2;
use cgmath::InnerSpace;
use cgmath::dot;
use std;
#[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
pub struct Rect<F> {
pub min : Vector2<F>,
pub max : Vector2<F>,
}
pub type RectI = Rect<i32>;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct LineSegment {
pub from:... | (&self, plane:Plane) -> Option<Vec3> {
let direction = (self.to - self.from).normalize();
let denominator = dot(plane.normal, direction);
if denominator > -EPSILON && denominator < EPSILON {
return None
}
let numerator = -(dot(plane.normal, self.from) - plane.coeffic... | intersects | identifier_name |
math.js | function mathGame(){
var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.auto, 'math', {
preload: onPreload,
create: onCreate,
// resize:onResize
});
WebFontConfig = {
active: function() { game.time.events.add(Phaser.Timer.SECOND, createText, this); },
google: {
fami... | randomSum = game.rnd.between(0,2);
questionText.text = sumsArray[Math.min(Math.round((score-100)/400)+1,4)][randomSum][game.rnd.between(0,sumsArray[Math.min(Math.round((score-100)/400)+1,4)][randomSum].length-1)];
}
}
// }
| timeTween=game.add.tween(buttonMask);
timeTween.to({
x: -350
}, 9000, "Linear",true);
timeTween.onComplete.addOnce(function(){
gameOver("?");
}, this);
}
| conditional_block |
math.js | function mathGame(){
var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.auto, 'math', {
preload: onPreload,
create: onCreate,
// resize:onResize
});
WebFontConfig = {
active: function() { game.time.events.add(Phaser.Timer.SECOND, createText, this); },
google: {
fami... | gameOverSprite.frame = 0;
gameOverSprite.animations.add('left', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13], 10, true);
replay = game.add.button(game.width*.6, game.height*.1,"replay",replay,this);
replay.visable = false;
home = game.add.button(game.width*.75, game.height*.1, 'home', function onClick... | chalkBoard.width = game.width;
game.stage.disableVisibilityChange = true;
gameOverSprite = this.game.add.sprite(600, 300, 'myguy');
gameOverSprite.visible = false; | random_line_split |
math.js | function mathGame(){
var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.auto, 'math', {
preload: onPreload,
create: onCreate,
// resize:onResize
});
WebFontConfig = {
active: function() { game.time.events.add(Phaser.Timer.SECOND, createText, this); },
google: {
fami... | }
// }
| scoreText.text = "Score: "+score.toString()+"\nBest Score: "+topScore.toString();
if(buttonMask){
buttonMask.destroy();
game.tweens.removeAll();
}
buttonMask = game.add.graphics(game.width*.3,game.height*.4);
buttonMask.beginFill(0xffffff);
buttonMask.drawRect(0, 0, 400, 200... | identifier_body |
math.js | function | (){
var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.auto, 'math', {
preload: onPreload,
create: onCreate,
// resize:onResize
});
WebFontConfig = {
active: function() { game.time.events.add(Phaser.Timer.SECOND, createText, this); },
google: {
families: ['Frederick... | mathGame | identifier_name |
run_julia.py | import sys
import time
from mpi4py.futures import MPICommExecutor
x0 = -2.0
x1 = +2.0
y0 = -1.5
y1 = +1.5
w = 1600
h = 1200
dx = (x1 - x0) / w
dy = (y1 - y0) / h
def julia(x, y):
|
def julia_line(k):
line = bytearray(w)
y = y1 - k * dy
for j in range(w):
x = x0 + j * dx
line[j] = julia(x, y)
return line
def plot(image):
import warnings
warnings.simplefilter('ignore', UserWarning)
try:
from matplotlib import pyplot as plt
except ImportErro... | c = complex(0, 0.65)
z = complex(x, y)
n = 255
while abs(z) < 3 and n > 1:
z = z**2 + c
n -= 1
return n | identifier_body |
run_julia.py | import sys
import time
from mpi4py.futures import MPICommExecutor
x0 = -2.0
x1 = +2.0
y0 = -1.5
y1 = +1.5
w = 1600
h = 1200
dx = (x1 - x0) / w
dy = (y1 - y0) / h
def | (x, y):
c = complex(0, 0.65)
z = complex(x, y)
n = 255
while abs(z) < 3 and n > 1:
z = z**2 + c
n -= 1
return n
def julia_line(k):
line = bytearray(w)
y = y1 - k * dy
for j in range(w):
x = x0 + j * dx
line[j] = julia(x, y)
return line
def plot(image... | julia | identifier_name |
run_julia.py | import sys
import time
from mpi4py.futures import MPICommExecutor
x0 = -2.0
x1 = +2.0
y0 = -1.5
y1 = +1.5
w = 1600
h = 1200
dx = (x1 - x0) / w
dy = (y1 - y0) / h
def julia(x, y):
c = complex(0, 0.65)
z = complex(x, y)
n = 255
while abs(z) < 3 and n > 1:
z = z**2 + c
n -= 1
retur... | if __name__ == '__main__':
test_julia() | random_line_split | |
run_julia.py | import sys
import time
from mpi4py.futures import MPICommExecutor
x0 = -2.0
x1 = +2.0
y0 = -1.5
y1 = +1.5
w = 1600
h = 1200
dx = (x1 - x0) / w
dy = (y1 - y0) / h
def julia(x, y):
c = complex(0, 0.65)
z = complex(x, y)
n = 255
while abs(z) < 3 and n > 1:
z = z**2 + c
n -= 1
retur... |
if __name__ == '__main__':
test_julia()
| plot(image) | conditional_block |
constants.ts | export type FontScalePresets = {
majorSecond: Array<number>
minorThird: Array<number>
majorThird: Array<number>
perfectFourth: Array<number>
augmentedFourth: Array<number>
} | majorThird: [3.052, 2.441, 1.953, 1.563, 1.25, 1],
perfectFourth: [4.209, 3.157, 2.369, 1.777, 1.333, 1],
augmentedFourth: [5.653, 3.998, 2.827, 1.999, 1.414, 1],
} |
export const fontScalePresets: FontScalePresets = {
majorSecond: [1.802, 1.602, 1.424, 1.266, 1.125, 1],
minorThird: [2.488, 2.074, 1.728, 1.44, 1.2, 1], | random_line_split |
uint_macros.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | #![macro_escape]
#![doc(hidden)]
macro_rules! uint_module (($T:ty, $T_SIGNED:ty, $bits:expr) => (
#[unstable]
pub static BITS : uint = $bits;
#[unstable]
pub static BYTES : uint = ($bits / 8);
#[unstable]
pub static MIN: $T = 0 as $T;
#[unstable]
pub static MAX: $T = 0 as $T - 1 as $T;
)) | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
subdRender-1.py | #=====
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source cod... |
def doBound(self, args) :
geo = Reader.create( args['path'].value ).read()
return geo.bound()
def doRenderState(self, renderer, args) :
pass
def doRender(self, renderer, args) :
geo = Reader.create( args['path'].value ).read()
... | ParameterisedProcedural.__init__( self, "Renders a mesh as a subd." )
path = PathParameter( "path", "Path", "" )
self.parameters().addParameter( path ) | identifier_body |
subdRender-1.py | #=====
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: | #
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and... | random_line_split | |
subdRender-1.py | #=====
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source cod... | (self, renderer, args) :
geo = Reader.create( args['path'].value ).read()
geo.interpolation = "catmullClark"
geo.render( renderer )
# register
registerRunTimeTyped( subdRender )
| doRender | identifier_name |
modules.js | function su_reset_textbox(id, d, m, e) {
if (confirm(m+"\n\n"+d)) {
document.getElementById(id).value=d;
e.className='hidden';
su_enable_unload_confirm();
}
}
function su_textbox_value_changed(e, d, l) {
if (e.value==d)
document.getElementById(l).className='hidden';
else
document.getElementBy... | }
function su_disable_unload_confirm() {
window.onbeforeunload = null;
}
function su_confirm_unload_message() {
return suModulesModulesL10n.unloadConfirmMessage;
}
jQuery(document).ready(function() {
jQuery('input, textarea, select', 'div.su-module').change(su_enable_unload_confirm);
jQuery('form', '... | random_line_split | |
modules.js | function su_reset_textbox(id, d, m, e) {
if (confirm(m+"\n\n"+d)) {
document.getElementById(id).value=d;
e.className='hidden';
su_enable_unload_confirm();
}
}
function su_textbox_value_changed(e, d, l) {
if (e.value==d)
document.getElementById(l).className='hidden';
else
document.getElementBy... | (id) {
if (document.getElementById(id)) {
if (document.getElementById(id).style.display=='none')
Effect.BlindDown(id);
else
Effect.BlindUp(id);
}
return false;
}
function su_enable_unload_confirm() {
window.onbeforeunload = su_confirm_unload_message;
}
function su_disable_unload_confirm... | su_toggle_blind | identifier_name |
modules.js | function su_reset_textbox(id, d, m, e) {
if (confirm(m+"\n\n"+d)) {
document.getElementById(id).value=d;
e.className='hidden';
su_enable_unload_confirm();
}
}
function su_textbox_value_changed(e, d, l) {
if (e.value==d)
document.getElementById(l).className='hidden';
else
document.getElementBy... |
function su_enable_unload_confirm() {
window.onbeforeunload = su_confirm_unload_message;
}
function su_disable_unload_confirm() {
window.onbeforeunload = null;
}
function su_confirm_unload_message() {
return suModulesModulesL10n.unloadConfirmMessage;
}
jQuery(document).ready(function() {
jQuery(... | {
if (document.getElementById(id)) {
if (document.getElementById(id).style.display=='none')
Effect.BlindDown(id);
else
Effect.BlindUp(id);
}
return false;
} | identifier_body |
text.rs | use std::{env, process};
use yaml_rust::YamlLoader;
#[allow(dead_code)]
pub enum Errors {
GtkInitError,
ScreenshotUnsuccessful,
StrfTimeUnavailable,
PicturesFolderUnavailable,
ScreenshotSaveError,
ImageViewerError,
FileError,
ImgurUploadFailure,
ClipboardUnavailable,
MastodonIma... | {
let locators = YamlLoader::load_from_str(&loader()).unwrap();
let locator = &locators[0]["Error"];
let error = &locator["Error"].as_str().unwrap();
match code {
1..=31 => return format!("{} {}: {}", error, code, &locator[code].as_str().unwrap()),
_ => unreachable!("Internal Logic Erro... | identifier_body | |
text.rs | use std::{env, process};
use yaml_rust::YamlLoader;
#[allow(dead_code)]
pub enum | {
GtkInitError,
ScreenshotUnsuccessful,
StrfTimeUnavailable,
PicturesFolderUnavailable,
ScreenshotSaveError,
ImageViewerError,
FileError,
ImgurUploadFailure,
ClipboardUnavailable,
MastodonImageUnsuccessful,
MastodonTootUnsuccessful,
MastodonLoginError,
TwitterImageUn... | Errors | identifier_name |
text.rs | use std::{env, process};
use yaml_rust::YamlLoader;
#[allow(dead_code)]
pub enum Errors {
GtkInitError,
ScreenshotUnsuccessful,
StrfTimeUnavailable,
PicturesFolderUnavailable,
ScreenshotSaveError,
ImageViewerError,
FileError,
ImgurUploadFailure,
ClipboardUnavailable,
MastodonIma... | } else if lang.contains("de") {
return include_str!("../lang/de.yml").to_string();
} else if lang.contains("pl") {
return include_str!("../lang/pl.yml").to_string();
} else if lang.contains("pt") {
return include_str!("../lang/pt.yml").to_string();
} else if lang.contains("sv") {... | random_line_split | |
gandi_iface.py | #!/usr/bin/python
# Copyright 2013 Gandi SAS
#
# This file is part of Ansible
#
# Ansible 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 versio... |
elif state in ['created']:
json_output['state'] = 'created'
(changed, iface_data) = create_iface(module, gandi)
json_output['iface_data'] = iface_data
json_output['changed'] = changed
print json.dumps(json_output)
sys.exit(0)
from ansible.module_utils.basic import *
main()
| json_output['state'] = 'deleted'
(changed, iface_id) = delete_iface(module, gandi, iface_id)
json_output['iface_id'] = iface_id | conditional_block |
gandi_iface.py | #!/usr/bin/python
# Copyright 2013 Gandi SAS
#
# This file is part of Ansible
#
# Ansible 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 versio... | (module, driver, iface_id):
"""Delete an interface.
module: Ansible module object
driver: authenticated Gandi connection object
iface_id: int id of the interface
Returns a dictionary of with operation status.
"""
changed = False
pvlan = None
try:
iface = get_iface(driver,... | delete_iface | identifier_name |
gandi_iface.py | #!/usr/bin/python
# Copyright 2013 Gandi SAS
#
# This file is part of Ansible
#
# Ansible 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 versio... | def unexpected_error_msg(error):
"""Create an error string based on passed in error."""
# XXX : better error management
return error
def _get_by_name(name, entities):
find = [x for x in entities if x.name == name]
return find[0] if find else None
def _get_by_id(id, entities):
find = [x for x... | sys.exit(1)
| random_line_split |
gandi_iface.py | #!/usr/bin/python
# Copyright 2013 Gandi SAS
#
# This file is part of Ansible
#
# Ansible 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 versio... |
def _get_by_name(name, entities):
find = [x for x in entities if x.name == name]
return find[0] if find else None
def _get_by_id(id, entities):
find = [x for x in entities if x.id == id]
return find[0] if find else None
def get_datacenter(driver, name):
"""Get datacenter by name
"""
d... | """Create an error string based on passed in error."""
# XXX : better error management
return error | identifier_body |
misc.ts | /**
* 删除字符串开头的 UTF-8 BOM 字符
* @param content 要处理的字符串
*/
export function stripBOM(content: string) {
if (content.charCodeAt(0) === 0xfeff) {
content = content.substring(1)
}
return content
}
/**
* 生成指定长度的随机字符串
* @param length 要生成的字符串长度
*/
export function randomString(length: number) {
let result = ""
while... | * @param byteSize 要格式化的字节大小
* @example formatSize(1024) // "1.00KB"
*/
export function formatSize(byteSize: number) {
let unit: string
if (byteSize < 1000) {
unit = "B"
} else if (byteSize < 1024 * 1000) {
byteSize /= 1024
unit = "KB"
} else if (byteSize < 1024 * 1024 * 1000) {
byteSize /= 1024 * 1024
... | 格式化指定的字节大小
| identifier_name |
misc.ts | /**
* 删除字符串开头的 UTF-8 BOM 字符
* @param content 要处理的字符串
*/
export function stripBOM(content: string) {
if (content.charCodeAt(0) === 0xfeff) {
content = content.substring(1)
}
return content
}
/**
* 生成指定长度的随机字符串
* @param length 要生成的字符串长度
*/
export function randomString(length: number) {
let result = ""
while... | * @param item 要插入的值
* @param comparer 确定元素顺序的回调函数,如果函数返回 `true`,则将 `x` 排在 `y` 的前面,否则相反
* @param comparer.x 要比较的第一个元素
* @param comparer.y 要比较的第二个元素
*/
export function insertSorted<T>(sortedArray: T[], item: T, comparer: (x: T, y: T) => boolean) {
let start = 0
let end = sortedArray.length - 1
while (start <= end... | random_line_split | |
misc.ts | /**
* 删除字符串开头的 UTF-8 BOM 字符
* @param content 要处理的字符串
*/
export function stripBOM(content: string) {
if (content.charCodeAt(0) === 0 | ngth 要生成的字符串长度
*/
export function randomString(length: number) {
let result = ""
while (result.length < length) {
result += Math.random().toString(36).substring(2)
}
return result.substring(0, length)
}
/**
* 按顺序插入元素到已排序的数组中,如果值已存在则插入到存在的值之后
* @param sortedArray 已排序的数组
* @param item 要插入的值
* @param comparer ... | xfeff) {
content = content.substring(1)
}
return content
}
/**
* 生成指定长度的随机字符串
* @param le | identifier_body |
misc.ts | /**
* 删除字符串开头的 UTF-8 BOM 字符
* @param content 要处理的字符串
*/
export function stripBOM(content: string) {
if (content.charCodeAt(0) === 0xfeff) {
content = content.substring(1)
}
return content
}
/**
* 生成指定长度的随机字符串
* @param length 要生成的字符串长度
*/
export function randomString(length: number) {
let result = ""
while... | conditional_block | ||
facebook-events.service.spec.ts | /* | * Written by Augustinas Markevicius <augustinas.markevicius@dataswift.io> 1, 2017
*/
/* tslint:disable:no-unused-variable */
import { TestBed, async, inject } from '@angular/core/testing';
import { FacebookEventsService } from './facebook-events.service';
import { HatApiService } from '../core/services/hat-api.serv... | * Copyright (C) 2017 - 2019 DataSwift Ltd - All Rights Reserved
* 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/. | random_line_split |
videojs-playlist-ui.js | /*! @name videojs-playlist-ui @version 3.8.0 @license Apache-2.0 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('global/document'), require('video.js')) :
typeof define === 'function' && define.amd ? define(['global/document', 'video.... |
var version = "3.8.0";
var dom = videojs.dom || videojs;
var registerPlugin = videojs.registerPlugin || videojs.plugin; // Array#indexOf analog for IE8
var indexOf = function indexOf(array, target) {
for (var i = 0, length = array.length; i < length; i++) {
if (array[i] === target) {
retur... | {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
} | identifier_body |
videojs-playlist-ui.js | /*! @name videojs-playlist-ui @version 3.8.0 @license Apache-2.0 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('global/document'), require('video.js')) :
typeof define === 'function' && define.amd ? define(['global/document', 'video.... |
};
_proto2.createPlaylist_ = function createPlaylist_() {
var playlist = this.player_.playlist() || [];
var list = this.el_.querySelector('.vjs-playlist-item-list');
var overlay = this.el_.querySelector('.vjs-playlist-ad-overlay');
if (!list) {
list = document.createElement('o... | {
this.items.forEach(function (i) {
return i.dispose();
});
this.items.length = 0;
} | conditional_block |
videojs-playlist-ui.js | /*! @name videojs-playlist-ui @version 3.8.0 @license Apache-2.0 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('global/document'), require('video.js')) :
typeof define === 'function' && define.amd ? define(['global/document', 'video.... | (subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
var version = "3.8.0";
var dom = videojs.dom || videojs;
var registerPlugin = videojs.registerPlugin || videojs.plugin; // Array#indexOf ... | _inheritsLoose | identifier_name |
videojs-playlist-ui.js | /*! @name videojs-playlist-ui @version 3.8.0 @license Apache-2.0 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('global/document'), require('video.js')) :
typeof define === 'function' && define.amd ? define(['global/document', 'video.... | var selectedIndex = this.player_.playlist.currentItem();
if (this.items.length && selectedIndex >= 0) {
addSelectedClass(this.items[selectedIndex]);
var thumbnail = this.items[selectedIndex].$('.vjs-playlist-thumbnail');
if (thumbnail) {
dom.addClass(thumbnail, 'vjs-playl... | list.appendChild(overlay);
} // select the current playlist item
| random_line_split |
attendance-block.component.ts | import { Component, Input, OnChanges } from "@angular/core";
import { ActivityAttendance } from "../model/activity-attendance";
import { AttendanceLogicalStatus } from "../model/attendance-status";
/**
* Display attendance details of a single period for a participant as a compact block.
*/
@Component({
selector: "... | () {}
ngOnChanges() {
this.logicalCount =
this.attendanceData.individualLogicalStatusCounts.get(this.forChild) ??
{};
}
showTooltip() {
if (this.tooltipTimeout) {
clearTimeout(this.tooltipTimeout);
}
this.tooltipTimeout = setTimeout(() => (this.tooltip = true), 1000);
}
hid... | constructor | identifier_name |
attendance-block.component.ts | import { Component, Input, OnChanges } from "@angular/core";
import { ActivityAttendance } from "../model/activity-attendance";
import { AttendanceLogicalStatus } from "../model/attendance-status";
/**
* Display attendance details of a single period for a participant as a compact block.
*/
@Component({
selector: "... |
this.tooltipTimeout = setTimeout(() => (this.tooltip = false), 150);
}
get attendanceDescription(): string {
return `${this.logicalCount[this.LStatus.PRESENT]} / ${
(this.logicalCount[this.LStatus.PRESENT] || 0) +
(this.logicalCount[this.LStatus.ABSENT] || 0)
}`;
}
}
| {
clearTimeout(this.tooltipTimeout);
} | conditional_block |
attendance-block.component.ts | import { Component, Input, OnChanges } from "@angular/core";
import { ActivityAttendance } from "../model/activity-attendance";
import { AttendanceLogicalStatus } from "../model/attendance-status";
/**
* Display attendance details of a single period for a participant as a compact block.
*/
@Component({
selector: "... | clearTimeout(this.tooltipTimeout);
}
this.tooltipTimeout = setTimeout(() => (this.tooltip = true), 1000);
}
hideTooltip() {
if (this.tooltipTimeout) {
clearTimeout(this.tooltipTimeout);
}
this.tooltipTimeout = setTimeout(() => (this.tooltip = false), 150);
}
get attendanceDescrip... | {};
}
showTooltip() {
if (this.tooltipTimeout) { | random_line_split |
ShaderLoader.ts | /// <reference path="../typed/rx.jquery.d.ts"/>
/// <reference path='./ShaderText.ts'/>
class ShaderLoader {
private _shadersUrl: string;
private _regularVert: string;
private _utilsUrl: string
private _utilFrag: string;
private _initialMethodsUrl: string;
private _initialMethodsFrag: string;
constru... | } | }
interface ShaderResponse {
data: string; | random_line_split |
ShaderLoader.ts | /// <reference path="../typed/rx.jquery.d.ts"/>
/// <reference path='./ShaderText.ts'/>
class ShaderLoader {
private _shadersUrl: string;
private _regularVert: string;
private _utilsUrl: string
private _utilFrag: string;
private _initialMethodsUrl: string;
private _initialMethodsFrag: string;
constru... |
return $.getAsObservable<ShaderResponse>(this._shadersUrl + "plane.vert")
.map((shader) => shader.data)
.doOnNext((vert) => {
this._regularVert = vert
});
}
private utilFrag(): Rx.Observable<string> {
if (this._utilFrag === undefined) {
return $.getAsObservable<ShaderResponse>... | {
return Rx.Observable.just(this._regularVert);
} | conditional_block |
ShaderLoader.ts | /// <reference path="../typed/rx.jquery.d.ts"/>
/// <reference path='./ShaderText.ts'/>
class ShaderLoader {
private _shadersUrl: string;
private _regularVert: string;
private _utilsUrl: string
private _utilFrag: string;
private _initialMethodsUrl: string;
private _initialMethodsFrag: string;
constru... | (url: string): Rx.Observable<string> {
return $.getAsObservable<ShaderResponse>(this._shadersUrl + url + '.frag')
.map((shader) => shader.data)
.combineLatest(this.utilFrag(), (frag, util) => util.concat(frag));
}
private getPlane(): Rx.Observable<string> {
if (this._regularVert) {
return... | getFragment | identifier_name |
ShaderLoader.ts | /// <reference path="../typed/rx.jquery.d.ts"/>
/// <reference path='./ShaderText.ts'/>
class ShaderLoader {
private _shadersUrl: string;
private _regularVert: string;
private _utilsUrl: string
private _utilFrag: string;
private _initialMethodsUrl: string;
private _initialMethodsFrag: string;
constru... |
}
interface ShaderResponse {
data: string;
}
| {
if (this._utilFrag === undefined) {
return $.getAsObservable<ShaderResponse>(this._utilsUrl)
.map((shader) => shader.data)
.doOnNext((util) => this._utilFrag = util);
}
return Rx.Observable.just(this._utilFrag);
} | identifier_body |
commentActions.ts | // - Import react components
import moment from 'moment/moment'
import _ from 'lodash'
import {Map} from 'immutable'
// - Import domain
import { Comment } from 'src/core/domain/comments'
import { Post } from 'src/core/domain/posts'
import { SocialError } from 'src/core/domain/common'
// - Import action types
import {... | let uid: string = state.getIn(['authorize', 'uid'])
const currentUser = state.getIn(['user', 'info', uid])
let comment: Comment = {
score: 0,
creationDate: moment().unix(),
userDisplayName: currentUser.fullName,
userAvatar: currentUser.avatar,
userId: uid,
postId: newComm... |
const state: Map<string, any> = getState() | random_line_split |
commentActions.ts | // - Import react components
import moment from 'moment/moment'
import _ from 'lodash'
import {Map} from 'immutable'
// - Import domain
import { Comment } from 'src/core/domain/comments'
import { Post } from 'src/core/domain/posts'
import { SocialError } from 'src/core/domain/common'
// - Import action types
import {... |
}, (error: SocialError) => {
dispatch(globalActions.showMessage(error.message))
dispatch(globalActions.hideTopLoading())
})
}
}
/**
* Get all comments from database
*/
export const dbFetchComments = (ownerUserId: string, postId: string) => {
return {
type: CommentActionType.DB_... | {
dispatch(notifyActions.dbAddNotification(
{
description: 'Add comment on your post.',
url: `/${ownerPostUserId}/posts/${comment.postId}`,
notifyRecieverUserId: ownerPostUserId, notifierUserId: uid,
isSeen: false
}))
} | conditional_block |
result-sender.js | 'use strict';
const stream = require('stream');
const log = require('./log');
const svg2img = require('./svg-to-img');
function | (str) {
const newStream = new stream.Readable();
newStream._read = () => { newStream.push(str); newStream.push(null); };
return newStream;
}
function makeSend(format, askres, end) {
if (format === 'svg') {
return res => sendSVG(res, askres, end);
} else if (format === 'json') {
return res => sendJSON... | streamFromString | identifier_name |
result-sender.js | 'use strict';
const stream = require('stream');
const log = require('./log');
const svg2img = require('./svg-to-img');
function streamFromString(str) {
const newStream = new stream.Readable();
newStream._read = () => { newStream.push(str); newStream.push(null); };
return newStream;
}
function makeSend(format, ... |
module.exports = {
makeSend
};
| {
askres.setHeader('Content-Type', 'application/json');
askres.setHeader('Access-Control-Allow-Origin', '*');
end(null, {template: streamFromString(res)});
} | identifier_body |
result-sender.js | 'use strict';
const stream = require('stream');
const log = require('./log');
const svg2img = require('./svg-to-img');
function streamFromString(str) {
const newStream = new stream.Readable();
newStream._read = () => { newStream.push(str); newStream.push(null); };
return newStream;
}
function makeSend(format, ... | });
}
function sendJSON(res, askres, end) {
askres.setHeader('Content-Type', 'application/json');
askres.setHeader('Access-Control-Allow-Origin', '*');
end(null, {template: streamFromString(res)});
}
module.exports = {
makeSend
}; | } | random_line_split |
dom.ts | import {
SKIPPED_TAGS,
SKIPPED_CLASSES,
INLINE_TAGS,
} from './constants';
let customSkipSelector: string | undefined
/**
* Customize which elements to ignore.
* Pass undefined to remove custom selector.
*/
export function ignore(selector?: string) {
customSkipSelector = selector
}
/** Returns true if node... |
/**
* Returns the concatenated string of all preceding textNode within the block
* level element that the given node is in.
*/
export function getInlineContext(node?: Node | null, cache?: WeakMap<Node, string>): string {
let res = '';
while (node) {
if (!node.previousSibling) {
node = node.parentNode... | {
return INLINE_TAGS.indexOf( node.nodeName ) > -1;
} | identifier_body |
dom.ts | import {
SKIPPED_TAGS,
SKIPPED_CLASSES,
INLINE_TAGS,
} from './constants';
let customSkipSelector: string | undefined
/**
* Customize which elements to ignore.
* Pass undefined to remove custom selector.
*/
export function ignore(selector?: string) {
customSkipSelector = selector
}
/** Returns true if node... | (node?: Node | null, cache?: WeakMap<Node, string>): string {
let res = '';
while (node) {
if (!node.previousSibling) {
node = node.parentNode;
if (!node || !isInlineElement(node)) {
break;
}
} else {
node = node.previousSibling;
if (node.nodeType === Node.ELEMENT_NODE)... | getInlineContext | identifier_name |
dom.ts | import {
SKIPPED_TAGS,
SKIPPED_CLASSES,
INLINE_TAGS,
} from './constants';
let customSkipSelector: string | undefined
/**
* Customize which elements to ignore.
* Pass undefined to remove custom selector.
*/
export function ignore(selector?: string) {
customSkipSelector = selector
}
/** Returns true if node... | if (node.nodeType === Node.ELEMENT_NODE) {
if (!isInlineElement(node)) break;
while (node.lastChild) {
node = node.lastChild;
}
}
if (cache && cache.has(node)) {
res = cache.get(node) + res;
break;
} else if (node.nodeType === Node.TEXT_NODE) {
... | if (!node || !isInlineElement(node)) {
break;
}
} else {
node = node.previousSibling; | random_line_split |
dom.ts | import {
SKIPPED_TAGS,
SKIPPED_CLASSES,
INLINE_TAGS,
} from './constants';
let customSkipSelector: string | undefined
/**
* Customize which elements to ignore.
* Pass undefined to remove custom selector.
*/
export function ignore(selector?: string) {
customSkipSelector = selector
}
/** Returns true if node... |
}
}
if (cache && node) {
cache.set(node, res);
}
return res;
}
| {
res = node.nodeValue + res;
} | conditional_block |
string_expressions.rs | // 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... | (args: &[ArrayRef]) -> Result<StringArray> {
// downcast all arguments to strings
let args = downcast_vec!(args, StringArray).collect::<Result<Vec<&StringArray>>>()?;
// do not accept 0 arguments.
if args.len() == 0 {
return Err(DataFusionError::Internal(
"Concatenate was called with... | concatenate | identifier_name |
string_expressions.rs | // 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... |
}
Ok(builder.finish())
}
| {
builder.append_value(&owned_string)?;
} | conditional_block |
string_expressions.rs | // 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... | {
// downcast all arguments to strings
let args = downcast_vec!(args, StringArray).collect::<Result<Vec<&StringArray>>>()?;
// do not accept 0 arguments.
if args.len() == 0 {
return Err(DataFusionError::Internal(
"Concatenate was called with 0 arguments. It requires at least one."
... | identifier_body | |
string_expressions.rs | // 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... | if arg.is_null(index) {
is_null = true;
break; // short-circuit as we already know the result
} else {
owned_string.push_str(&arg.value(index));
}
}
if is_null {
builder.append_null()?;
} else {
... |
// if any is null, the result is null
let mut is_null = false;
for arg in &args { | random_line_split |
models.py | """
Object representing a helper file for an OCR app.
"""
import datetime
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User, related_nam... | (cls):
"""URL to view the object list"""
return "/ocrmodels/list/"
@classmethod
def get_create_url(cls):
"""URL to create a new object"""
return "/ocrmodels/create/"
| get_list_url | identifier_name |
models.py | """
Object representing a helper file for an OCR app.
"""
import datetime
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User, related_nam... |
@classmethod
def get_create_url(cls):
"""URL to create a new object"""
return "/ocrmodels/create/"
| """URL to view the object list"""
return "/ocrmodels/list/" | identifier_body |
models.py | """
Object representing a helper file for an OCR app.
"""
import datetime
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User, related_nam... | @classmethod
def get_create_url(cls):
"""URL to create a new object"""
return "/ocrmodels/create/" | random_line_split | |
models.py | """
Object representing a helper file for an OCR app.
"""
import datetime
from django.db import models
from django.contrib.auth.models import User
from tagging.fields import TagField
import tagging
class OcrModel(models.Model):
"""
OCR model objects.
"""
user = models.ForeignKey(User, related_nam... |
else:
self.updated_on = datetime.datetime.now()
super(OcrModel, self).save()
def get_absolute_url(self):
"""URL to view an object detail"""
return "/ocrmodels/show/%i/" % self.id
def get_update_url(self):
"""url to update an object detail"""
return ... | self.created_on = datetime.datetime.now() | conditional_block |
vaccines.js | import { fromJS, OrderedMap } from 'immutable';
const vaccines = fromJS([
{
name: 'AVA (BioThrax)',
id: '8b013618-439e-4829-b88f-98a44b420ee8',
diseases: ['Anthrax'],
},
{
name: 'VAR (Varivax)',
id: 'f3e08a56-003c-4b46-9dea-216298401ca0',
diseases: ['Varicella (Chickenpox)'],
},
{
... | {
name: 'Polio (Ipol)',
id: '9c1582f2-8a7b-4bae-8ba5-656efe33fb29',
diseases: ['Polio'],
},
{
name: 'Rabies (Imovax Rabies, RabAvert)',
id: '2bfeeb1f-b7a7-4ce6-aae1-72e840a93e2e',
diseases: ['Rabies'],
},
{
name: 'RV1 (Rotarix)',
id: '8ddfa840-7558-469a-a53b-19a40d016518',
... | diseases: ['Pneumococcal'],
}, | random_line_split |
Circle.ts | /* tslint:disable */
declare var Object: any;
export interface CircleInterface {
"id": string;
"name"?: string;
"leaderDevoteeId"?: string;
"created-on"?: Date;
"updated-on"?: Date; | "name": string;
"leaderDevoteeId": string;
"created-on": Date;
"updated-on": Date;
constructor(data?: CircleInterface) {
Object.assign(this, data);
}
/**
* The name of the model represented by this $resource,
* i.e. `Circle`.
*/
public static getModelName() {
return "Circle";
}
/**
... | }
export class Circle implements CircleInterface {
"id": string; | random_line_split |
Circle.ts | /* tslint:disable */
declare var Object: any;
export interface CircleInterface {
"id": string;
"name"?: string;
"leaderDevoteeId"?: string;
"created-on"?: Date;
"updated-on"?: Date;
}
export class Circle implements CircleInterface {
"id": string;
"name": string;
"leaderDevoteeId": string;
"created-o... | (data?: CircleInterface) {
Object.assign(this, data);
}
/**
* The name of the model represented by this $resource,
* i.e. `Circle`.
*/
public static getModelName() {
return "Circle";
}
/**
* @method factory
* @author Jonathan Casarrubias
* @license MIT
* This method creates an instanc... | constructor | identifier_name |
bithdtv.py | ###################################################################################################
# Author: Jodi Jones <venom@gen-x.co.nz>
# URL: https://github.com/VeNoMouS/Sick-Beard
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of t... | (self):
generic.TorrentProvider.__init__(self, "BitHDTV")
self.cache = BitHDTVCache(self)
self.name = "BitHDTV"
self.session = None
self.supportsBacklog = True
self.url = 'https://www.bit-hdtv.com/'
logger.log("[" + self.name + "] initializing...")
##... | __init__ | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.