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 |
|---|---|---|---|---|
user-settings.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../../userShared/user.service';
import * as Rx from 'rxjs/Rx';
import * as firebase from 'firebase';
@Component({
templateUrl: './user-settings.component.html',
styleUrls: ['./user-settin... | () {
this.router.navigate(['/user']);
}
apply() {
this.userSVC.updateUserSettings(this.theUser);
this.router.navigate(['/user']);
}
}
| cancel | identifier_name |
user-settings.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../../userShared/user.service';
import * as Rx from 'rxjs/Rx';
import * as firebase from 'firebase';
@Component({
templateUrl: './user-settings.component.html',
styleUrls: ['./user-settin... | reportAbuse() {
this.router.navigate(['/user/settings/reportAbuse']);
}
cancel() {
this.router.navigate(['/user']);
}
apply() {
this.userSVC.updateUserSettings(this.theUser);
this.router.navigate(['/user']);
}
} | random_line_split | |
ForwardRenderStage.js | /**
* Forward renderer
*/
var ForwardRenderStage = PostProcessRenderStage.extend({
init: function() {
this._super();
this.debugActive = false;
this.debugger = null;
},
onPostRender: function(context, scene, camera) {
this._super(context, scene, camera);
if (this.debugActive) {
if (!this.debugger)
... |
// Draw shadowmaps
var size = 0.5;
var x = -1;
var y = 1 - size;
for (var i=0; i<scene.lights.length; i++) {
if (!scene.lights[i].enabled)
continue;
if (!scene.lights[i].shadowCasting)
continue;
if (!scene.lights[i].shadow)
continue;
if (scene.lights[i] instanceof DirectionalLight) ... | {
var vertices = [x,y,0, x,y+height,0, x+width,y+height,0, x+width,y,0];
var quad = new TrianglesRenderBuffer(context, [0, 1, 2, 0, 2, 3]);
quad.add('position', vertices, 3);
quad.add("uv0", [0,0, 0,1, 1,1, 1,0], 2);
return quad;
} | identifier_body |
ForwardRenderStage.js | /**
* Forward renderer
*/
var ForwardRenderStage = PostProcessRenderStage.extend({
init: function() {
this._super();
this.debugActive = false;
this.debugger = null;
},
onPostRender: function(context, scene, camera) {
this._super(context, scene, camera);
if (this.debugActive) {
if (!this.debugger)
... | this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.oitStage.transparencyWeight.texture });
}
// Draw depth stage, if enabled
if (this.generator.depthStage.enabled) {
this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.dept... | var y = -1;
if (this.generator.oitStage.enabled) {
this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: this.generator.oitStage.transparencyTarget.texture }); | random_line_split |
ForwardRenderStage.js | /**
* Forward renderer
*/
var ForwardRenderStage = PostProcessRenderStage.extend({
init: function() {
this._super();
this.debugActive = false;
this.debugger = null;
},
onPostRender: function(context, scene, camera) {
this._super(context, scene, camera);
if (this.debugActive) {
if (!this.debugger)
... | (x, y, width, height) {
var vertices = [x,y,0, x,y+height,0, x+width,y+height,0, x+width,y,0];
var quad = new TrianglesRenderBuffer(context, [0, 1, 2, 0, 2, 3]);
quad.add('position', vertices, 3);
quad.add("uv0", [0,0, 0,1, 1,1, 1,0], 2);
return quad;
}
// Draw shadowmaps
var size = 0.5;
var x =... | createQuad | identifier_name |
ForwardRenderStage.js | /**
* Forward renderer
*/
var ForwardRenderStage = PostProcessRenderStage.extend({
init: function() {
this._super();
this.debugActive = false;
this.debugger = null;
},
onPostRender: function(context, scene, camera) {
this._super(context, scene, camera);
if (this.debugActive) {
if (!this.debugger)
... |
// Draw depth stage, if enabled
if (this.generator.depthStage.enabled) {
this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.depthStage.target.texture });
}
}
});
| {
this.debugger.quads.push({ quad: createQuad(x, y, size, size), texture: this.generator.oitStage.transparencyTarget.texture });
this.debugger.quads.push({ quad: createQuad(x+=size, y, size, size), texture: this.generator.oitStage.transparencyWeight.texture });
} | conditional_block |
send_msg.rs | //! Client Node Example.
//!
//! The node sends a message (atom) to the specified erlang node.
//!
//! # Usage Examples
//!
//! ```bash
//! $ cargo run --example send_msg -- --help
//! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello
//! ```
extern crate clap;
extern crate ... | .parse()
.expect("Invalid epmd address");
let dest_proc = matches.value_of("DESTINATION").unwrap().to_string();
let message = matches.value_of("MESSAGE").unwrap().to_string();
let self_node0 = self_node.to_string();
let mut executor = InPlaceExecutor::new().unwrap();
let monitor = e... | random_line_split | |
send_msg.rs | //! Client Node Example.
//!
//! The node sends a message (atom) to the specified erlang node.
//!
//! # Usage Examples
//!
//! ```bash
//! $ cargo run --example send_msg -- --help
//! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello
//! ```
extern crate clap;
extern crate ... | {
let matches = App::new("send_msg")
.arg(
Arg::with_name("EPMD_HOST")
.short("h")
.takes_value(true)
.default_value("127.0.0.1"),
)
.arg(
Arg::with_name("EPMD_PORT")
.short("p")
.takes_va... | identifier_body | |
send_msg.rs | //! Client Node Example.
//!
//! The node sends a message (atom) to the specified erlang node.
//!
//! # Usage Examples
//!
//! ```bash
//! $ cargo run --example send_msg -- --help
//! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello
//! ```
extern crate clap;
extern crate ... |
})
.and_then(move |peer| {
// Sends a message to the peer node
println!("# Connected: {}", peer.name);
println!("# Distribution Flags: {:?}", peer.flags);
let tx = channel::sender(peer.stream);
let from_pid = eetf::... | {
Either::B(futures::failed(Error::new(
ErrorKind::NotFound,
"target node is not found",
)))
} | conditional_block |
send_msg.rs | //! Client Node Example.
//!
//! The node sends a message (atom) to the specified erlang node.
//!
//! # Usage Examples
//!
//! ```bash
//! $ cargo run --example send_msg -- --help
//! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello
//! ```
extern crate clap;
extern crate ... | () {
let matches = App::new("send_msg")
.arg(
Arg::with_name("EPMD_HOST")
.short("h")
.takes_value(true)
.default_value("127.0.0.1"),
)
.arg(
Arg::with_name("EPMD_PORT")
.short("p")
.takes... | main | identifier_name |
test_chart_format23.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | """Test the creation of an XlsxWriter file with chart formatting."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [108321024, 108328448]
data = [
[1, 2, 3, 4, 5],
... | identifier_body | |
test_chart_format23.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class | (ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename('chart_format23.xlsx')
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = Workbook(... | TestCompareXLSXFiles | identifier_name |
test_chart_format23.py | ###############################################################################
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompar... | workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [108321024, 108328448]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
... | self.set_filename('chart_format23.xlsx')
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
| random_line_split |
index.js | 'use strict';
var express = require("express");
var http = require("http");
var app = express();
var httpServer = http.Server(app);
var io = require('socket.io')(httpServer);
// Users array.
var users = [];
// Channels pre-defined array.
var channels = [
'Angular',
'React',
'Laravel',
'Symfony'
];
/... |
// Join event.
socket.on('join', function (data) {
// Join socket to channel.
socket.join(data.channel);
// Add user to users lists.
users.push({id: socket.id, name: data.user});
// Bind username to socket object.
socket.username = data.user;
// If so... | res.send(channels);
});
// On connection event.
io.on('connection', function (socket) { | random_line_split |
index.js | 'use strict';
var express = require("express");
var http = require("http");
var app = express();
var httpServer = http.Server(app);
var io = require('socket.io')(httpServer);
// Users array.
var users = [];
// Channels pre-defined array.
var channels = [
'Angular',
'React',
'Laravel',
'Symfony'
];
/... |
});
});
// Disconnect event.
socket.on('disconnect', function () {
// Check if user joined any room and clean users array.
users = users.filter(function (user) {
if (user.id == socket.id) {
return false;
}
return true
});... | {
// Format message.
var private_message = "(private) " + data.message.slice(to_user.length + 2);
// Send message to user who sent the message.
io.sockets.connected[socket.id].emit('message', {message: private_message, user: "me -> " + to_user});
... | conditional_block |
trait-coercion-generic.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let a = Struct { x: 1, y: 2 };
let b: Box<Trait<&'static str>> = box a;
b.f("Mary");
let c: &Trait<&'static str> = &a;
c.f("Joe");
} |
pub fn main() { | random_line_split |
trait-coercion-generic.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let a = Struct { x: 1, y: 2 };
let b: Box<Trait<&'static str>> = box a;
b.f("Mary");
let c: &Trait<&'static str> = &a;
c.f("Joe");
}
| main | identifier_name |
trait-coercion-generic.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
pub fn main() {
let a = Struct { x: 1, y: 2 };
let b: Box<Trait<&'static str>> = box a;
b.f("Mary");
let c: &Trait<&'static str> = &a;
c.f("Joe");
}
| {
println!("Hi, {}!", x);
} | identifier_body |
ErrorBoundary.tsx | import * as React from "react"
import { ErrorWithMetadata } from "v2/Utils/errors"
import createLogger from "v2/Utils/logger"
import { ErrorPage } from "v2/Components/ErrorPage"
import { AppContainer } from "v2/Apps/Components/AppContainer"
import { HorizontalPadding } from "v2/Apps/Components/HorizontalPadding"
import... | const message = error?.message || "Internal Server Error"
const detail = error.stack
/**
* Check to see if there's been a network error while asynchronously loading
* a dynamic webpack split chunk bundle. Can happen if a user is navigating
* between routes and their network connection goes o... | }
static getDerivedStateFromError(error: Error) { | random_line_split |
ErrorBoundary.tsx | import * as React from "react"
import { ErrorWithMetadata } from "v2/Utils/errors"
import createLogger from "v2/Utils/logger"
import { ErrorPage } from "v2/Components/ErrorPage"
import { AppContainer } from "v2/Apps/Components/AppContainer"
import { HorizontalPadding } from "v2/Apps/Components/HorizontalPadding"
import... |
}
static getDerivedStateFromError(error: Error) {
const message = error?.message || "Internal Server Error"
const detail = error.stack
/**
* Check to see if there's been a network error while asynchronously loading
* a dynamic webpack split chunk bundle. Can happen if a user is navigating
... | {
this.props.onCatch()
} | conditional_block |
ErrorBoundary.tsx | import * as React from "react"
import { ErrorWithMetadata } from "v2/Utils/errors"
import createLogger from "v2/Utils/logger"
import { ErrorPage } from "v2/Components/ErrorPage"
import { AppContainer } from "v2/Apps/Components/AppContainer"
import { HorizontalPadding } from "v2/Apps/Components/HorizontalPadding"
import... | (error: Error) {
const message = error?.message || "Internal Server Error"
const detail = error.stack
/**
* Check to see if there's been a network error while asynchronously loading
* a dynamic webpack split chunk bundle. Can happen if a user is navigating
* between routes and their network ... | getDerivedStateFromError | identifier_name |
ErrorBoundary.tsx | import * as React from "react"
import { ErrorWithMetadata } from "v2/Utils/errors"
import createLogger from "v2/Utils/logger"
import { ErrorPage } from "v2/Components/ErrorPage"
import { AppContainer } from "v2/Apps/Components/AppContainer"
import { HorizontalPadding } from "v2/Apps/Components/HorizontalPadding"
import... |
render() {
const {
asyncChunkLoadError,
detail,
genericError,
isError,
message,
} = this.state
if (isError) {
return (
<ThemeProviderV3>
<AppContainer my={4}>
<HorizontalPadding>
<RouterLink to="/" display="block" mb={4}>
... | {
const message = error?.message || "Internal Server Error"
const detail = error.stack
/**
* Check to see if there's been a network error while asynchronously loading
* a dynamic webpack split chunk bundle. Can happen if a user is navigating
* between routes and their network connection goes... | identifier_body |
basic_block.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn as_value(self) -> Value {
unsafe {
Value(llvm::LLVMBasicBlockAsValue(self.get()))
}
}
pub fn pred_iter(self) -> Preds<'static> {
self.as_value().user_iter()
.filter(|user| user.is_a_terminator_inst())
.map(|user| user.get_parent().unwrap(... | {
let BasicBlock(v) = *self; v
} | identifier_body |
basic_block.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (pub BasicBlockRef);
pub type Preds<'a> = Map<'a, Value, BasicBlock, Filter<'a, Value, Users>>;
/**
* Wrapper for LLVM BasicBlockRef
*/
impl BasicBlock {
pub fn get(&self) -> BasicBlockRef {
let BasicBlock(v) = *self; v
}
pub fn as_value(self) -> Value {
unsafe {
Value(llvm:... | BasicBlock | identifier_name |
basic_block.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
} | let mut iter = self.pred_iter();
match (iter.next(), iter.next()) {
(Some(first), None) => Some(first),
_ => None | random_line_split |
bwa.py | """BWA (https://github.com/lh3/bwa)
"""
import os
import signal
import subprocess
from bcbio.pipeline import config_utils
from bcbio import bam, utils
from bcbio.distributed import objectstore
from bcbio.distributed.transaction import file_transaction, tx_tmpdir
from bcbio.ngsalign import alignprep, novoalign, postali... | out_file = base + ".transcriptome" + ext
if utils.file_exists(out_file):
data = dd.set_transcriptome_bam(data, out_file)
return data
# bwa mem needs phred+33 quality, so convert if it is Illumina
if dd.get_quality_format(data).lower() == "illumina":
logger.info("bwa mem does not ... | work_bam = dd.get_work_bam(data)
base, ext = os.path.splitext(work_bam) | random_line_split |
bwa.py | """BWA (https://github.com/lh3/bwa)
"""
import os
import signal
import subprocess
from bcbio.pipeline import config_utils
from bcbio import bam, utils
from bcbio.distributed import objectstore
from bcbio.distributed.transaction import file_transaction, tx_tmpdir
from bcbio.ngsalign import alignprep, novoalign, postali... |
def fastq_size_output(fastq_file, tocheck):
head_count = 8000000
fastq_file = objectstore.cl_input(fastq_file)
gzip_cmd = "zcat {fastq_file}" if fastq_file.endswith(".gz") else "cat {fastq_file}"
cmd = (utils.local_path_export() + gzip_cmd + " | head -n {head_count} | "
"seqtk sample -s42 -... | from bcbio.heterogeneity import chromhacks
return len(chromhacks.get_hla_chroms(dd.get_ref_file(data))) != 0 | identifier_body |
bwa.py | """BWA (https://github.com/lh3/bwa)
"""
import os
import signal
import subprocess
from bcbio.pipeline import config_utils
from bcbio import bam, utils
from bcbio.distributed import objectstore
from bcbio.distributed.transaction import file_transaction, tx_tmpdir
from bcbio.ngsalign import alignprep, novoalign, postali... | (data):
"""
bwakit will corrupt the non-HLA alignments in a UMI collapsed BAM file
(see https://github.com/bcbio/bcbio-nextgen/issues/3069)
"""
return hla_on(data) and has_umi(data)
def _align_backtrack(fastq_file, pair_file, ref_file, out_file, names, rg_info, data):
"""Perform a BWA alignment... | needs_separate_hla | identifier_name |
bwa.py | """BWA (https://github.com/lh3/bwa)
"""
import os
import signal
import subprocess
from bcbio.pipeline import config_utils
from bcbio import bam, utils
from bcbio.distributed import objectstore
from bcbio.distributed.transaction import file_transaction, tx_tmpdir
from bcbio.ngsalign import alignprep, novoalign, postali... |
rg_info = novoalign.get_rg_info(names)
if not utils.file_exists(out_file) and (final_file is None or not utils.file_exists(final_file)):
# If we cannot do piping, use older bwa aln approach
if ("bwa-mem" not in dd.get_tools_on(data) and
("bwa-mem" in dd.get_tools_off(data) or not ... | fastq_file = alignprep.fastq_convert_pipe_cl(fastq_file, data)
if pair_file:
pair_file = alignprep.fastq_convert_pipe_cl(pair_file, data) | conditional_block |
auth.service.ts | module op.common {
'use strict';
export interface IAuthService {
register: (user: IUser) => ng.IPromise<string>;
login: (email: string, password: string) => ng.IPromise<string>;
logout: () => void;
}
class AuthService implements IAuthService {
/* @ngInject */
c... |
register(user: IUser): ng.IPromise<string> {
var deferred: ng.IDeferred<string> = this.$q.defer();
var requestConfig: ng.IRequestConfig = {
method: 'POST',
url: this.AUTH_URL + '/register',
headers: {
'Content-Type': '... | {
} | identifier_body |
auth.service.ts | module op.common {
'use strict';
export interface IAuthService {
register: (user: IUser) => ng.IPromise<string>;
login: (email: string, password: string) => ng.IPromise<string>;
logout: () => void;
}
class AuthService implements IAuthService {
/* @ngInject */
c... | }
// register LoginService
angular.module('op.common')
.service('AuthService', AuthService);
} | random_line_split | |
auth.service.ts | module op.common {
'use strict';
export interface IAuthService {
register: (user: IUser) => ng.IPromise<string>;
login: (email: string, password: string) => ng.IPromise<string>;
logout: () => void;
}
class AuthService implements IAuthService {
/* @ngInject */
| (public AUTH_URL: string,
public $window: ng.IWindowService,
public $http: ng.IHttpService,
public $q: ng.IQService,
public SessionService: op.common.ISessionService) {
}
register(user: IUser): ng.IPromise<string> {
... | constructor | identifier_name |
services.py | # Copyright 2016 IBM Corp.
# 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 app... | """Benchmark scenarios for Nova agents."""
@validation.required_services(consts.Service.NOVA)
@validation.required_openstack(admin=True)
@scenario.configure()
def list_services(self, host=None, binary=None):
"""List all nova services.
Measure the "nova service-list" command performance... | identifier_body | |
services.py | # Copyright 2016 IBM Corp.
# 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 app... | (utils.NovaScenario):
"""Benchmark scenarios for Nova agents."""
@validation.required_services(consts.Service.NOVA)
@validation.required_openstack(admin=True)
@scenario.configure()
def list_services(self, host=None, binary=None):
"""List all nova services.
Measure the "nova service... | NovaServices | identifier_name |
services.py | # Copyright 2016 IBM Corp.
# 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 app... | :param host: List nova services on host
:param binary: List nova services matching given binary
"""
self._list_services(host, binary) | random_line_split | |
jukebox_mpg123.py | # -*- coding: UTF-8 -*-
from django.core.management.base import BaseCommand
from optparse import make_option
import daemon
import daemon.pidfile
from signal import SIGTSTP, SIGTERM, SIGABRT
import sys, os, subprocess
import time
from jukebox.jukebox_core import api
class Command(BaseCommand):
daemon = None
pr... | (self, signal, action):
if not self.proc is None:
os.kill(self.proc.pid, SIGTERM)
if not self.daemon is None:
self.daemon.close()
sys.exit(0)
def skipSong(self, signal, action):
if not self.proc is None:
os.kill(self.proc.pid, SIGTERM)
| shutdown | identifier_name |
jukebox_mpg123.py | # -*- coding: UTF-8 -*-
from django.core.management.base import BaseCommand
from optparse import make_option
import daemon
import daemon.pidfile
from signal import SIGTSTP, SIGTERM, SIGABRT
import sys, os, subprocess
import time
from jukebox.jukebox_core import api
class Command(BaseCommand):
daemon = None
pr... |
print "Stopping daemon..."
pid = int(open(pidFile).read())
os.kill(pid, SIGTSTP)
print "Unregister player " + str(pid)
players_api = api.players()
players_api.remove(pid)
else:
self.print_help("jukebox_mpg123", "help")
d... | print "Daemon not running"
return | conditional_block |
jukebox_mpg123.py | # -*- coding: UTF-8 -*-
from django.core.management.base import BaseCommand
from optparse import make_option
import daemon
import daemon.pidfile
from signal import SIGTSTP, SIGTERM, SIGABRT
import sys, os, subprocess
import time
from jukebox.jukebox_core import api
class Command(BaseCommand):
| daemon = None
proc = None
mpg123 = None
option_list = BaseCommand.option_list + (
make_option(
"--start",
action="store_true",
dest="start",
help="Start mpg123 playback"
),
make_option(
"--stop",
action="store_t... | identifier_body | |
jukebox_mpg123.py | # -*- coding: UTF-8 -*-
from django.core.management.base import BaseCommand
from optparse import make_option
import daemon
import daemon.pidfile
from signal import SIGTSTP, SIGTERM, SIGABRT
import sys, os, subprocess
import time
from jukebox.jukebox_core import api
class Command(BaseCommand):
daemon = None
pr... | make_option(
"--start",
action="store_true",
dest="start",
help="Start mpg123 playback"
),
make_option(
"--stop",
action="store_true",
dest="stop",
help="Stop mpg123 playback"
),
)
de... | option_list = BaseCommand.option_list + ( | random_line_split |
graphql.d.ts | import { GraphQLCompositeType, GraphQLObjectType, GraphQLEnumValue, GraphQLSchema, GraphQLType, ASTNode, Location, ValueNode, OperationDefinitionNode, FieldNode, GraphQLField, DocumentNode } from "graphql";
declare module "graphql/utilities/buildASTSchema" {
function buildASTSchema(ast: DocumentNode, options?: {
... | export declare function isMetaFieldName(name: string): boolean;
export declare function withTypenameFieldAddedWhereNeeded(ast: ASTNode): any;
export declare function sourceAt(location: Location): string;
export declare function filePathForNode(node: ASTNode): string;
export declare function valueFromValueNode(valueNode... | random_line_split | |
array.rs | //! Generic-length array strategy.
// Adapted from proptest's array code
// Copyright 2017 Jason Lingle
use core::{marker::PhantomData, mem::MaybeUninit};
use proptest::{
strategy::{NewTree, Strategy, ValueTree},
test_runner::TestRunner,
};
#[must_use = "strategies do nothing unless used"]
#[derive(Clone, Co... | Self {
strategy,
_marker: PhantomData,
}
}
}
pub struct ArrayValueTree<T> {
tree: T,
shrinker: usize,
last_shrinker: Option<usize>,
}
impl<T, S, const LANES: usize> Strategy for UniformArrayStrategy<S, [T; LANES]>
where
T: core::fmt::Debug,
S: Strategy<V... | impl<S, T> UniformArrayStrategy<S, T> {
pub const fn new(strategy: S) -> Self { | random_line_split |
array.rs | //! Generic-length array strategy.
// Adapted from proptest's array code
// Copyright 2017 Jason Lingle
use core::{marker::PhantomData, mem::MaybeUninit};
use proptest::{
strategy::{NewTree, Strategy, ValueTree},
test_runner::TestRunner,
};
#[must_use = "strategies do nothing unless used"]
#[derive(Clone, Co... |
}
pub struct ArrayValueTree<T> {
tree: T,
shrinker: usize,
last_shrinker: Option<usize>,
}
impl<T, S, const LANES: usize> Strategy for UniformArrayStrategy<S, [T; LANES]>
where
T: core::fmt::Debug,
S: Strategy<Value = T>,
{
type Tree = ArrayValueTree<[S::Tree; LANES]>;
type Value = [T; LA... | {
Self {
strategy,
_marker: PhantomData,
}
} | identifier_body |
array.rs | //! Generic-length array strategy.
// Adapted from proptest's array code
// Copyright 2017 Jason Lingle
use core::{marker::PhantomData, mem::MaybeUninit};
use proptest::{
strategy::{NewTree, Strategy, ValueTree},
test_runner::TestRunner,
};
#[must_use = "strategies do nothing unless used"]
#[derive(Clone, Co... | <S, T> {
strategy: S,
_marker: PhantomData<T>,
}
impl<S, T> UniformArrayStrategy<S, T> {
pub const fn new(strategy: S) -> Self {
Self {
strategy,
_marker: PhantomData,
}
}
}
pub struct ArrayValueTree<T> {
tree: T,
shrinker: usize,
last_shrinker: Opti... | UniformArrayStrategy | identifier_name |
array.rs | //! Generic-length array strategy.
// Adapted from proptest's array code
// Copyright 2017 Jason Lingle
use core::{marker::PhantomData, mem::MaybeUninit};
use proptest::{
strategy::{NewTree, Strategy, ValueTree},
test_runner::TestRunner,
};
#[must_use = "strategies do nothing unless used"]
#[derive(Clone, Co... | else {
false
}
}
}
| {
self.shrinker = shrinker;
if self.tree[shrinker].complicate() {
true
} else {
self.last_shrinker = None;
false
}
} | conditional_block |
item_chooser.js | define([
'backbone',
'text!templates/item_chooser.tpl',
'models/item',
'models/trigger',
'models/instance',
'models/media',
'views/item_chooser_row',
'views/trigger_creator',
'vent',
'util', | Template,
Item,
Trigger,
Instance,
Media,
ItemChooserRowView,
TriggerCreatorView,
vent,
util
)
{
return Backbone.Marionette.CompositeView.extend(
{
template: _.template(Template),
itemView: ItemChooserRowView,
itemViewContainer: ".items",
itemViewOptions: function(model, index)
... | ],
function(
Backbone, | random_line_split |
item_chooser.js | define([
'backbone',
'text!templates/item_chooser.tpl',
'models/item',
'models/trigger',
'models/instance',
'models/media',
'views/item_chooser_row',
'views/trigger_creator',
'vent',
'util',
],
function(
Backbone,
Template,
Item,
Trigger,
Instance,
Media,
ItemChooserRowView,
TriggerC... |
else {
// If we've already rendered the main collection, just
// append the new items directly into the element.
var $container = this.getItemViewContainer(compositeView);
$container.find(".foot").before(itemView.el);
}
}
});
});
| {
compositeView.elBuffer.appendChild(itemView.el);
} | conditional_block |
getLocations.js | 'use strict';
/* INSTRUCCIONES
- Ejecutar getLocations
- Ejecutar correlateCines para a mano encontrar correlaciones.
*/
var request = require('request'),
cheerio = require('cheerio'),
mongoose = require('mongoose'),
md5 = require('md5'),
fs = require('fs'),
async = require('async'),
events... | }
}
//Añado el cine a la lista de cines
cines.push({
_id: md5(cineId),
cineId: cineId,
... | } else {
console.log(" --IMDB: " + nameIMDB + ' (Id: ' + idIMDB + ')');
correlados = (correlados == '') ? cineId + '##' + idIMDB : correlados + '$$' + cineId + '##' + idIMDB; | random_line_split |
getLocations.js | 'use strict';
/* INSTRUCCIONES
- Ejecutar getLocations
- Ejecutar correlateCines para a mano encontrar correlaciones.
*/
var request = require('request'),
cheerio = require('cheerio'),
mongoose = require('mongoose'),
md5 = require('md5'),
fs = require('fs'),
async = require('async'),
events... | t = /(\/cines\/)(.+)/;
var res = patt.exec(href);
if (res !== null) {
return res[2];
} else {
return null;
}
}
function extractIMDBId(href) {
var patt = /(.*\/)(ci[0-9]+)(\/.*)/;
var res = patt.exec(href);
if (res !== null) {
return res[2];
} else {
r... | var pat | identifier_name |
getLocations.js | 'use strict';
/* INSTRUCCIONES
- Ejecutar getLocations
- Ejecutar correlateCines para a mano encontrar correlaciones.
*/
var request = require('request'),
cheerio = require('cheerio'),
mongoose = require('mongoose'),
md5 = require('md5'),
fs = require('fs'),
async = require('async'),
events... |
var name = $(this).text().trim();
console.log(' ·Provincia: ' + name + ' (Id: ' + pId + ')');
provincias.push({
_id: md5(pId),
provinciaId: pId,
nombre: name,
ciudades: [],
actualizado: new Date().getT... | {
return false;
} | conditional_block |
getLocations.js | 'use strict';
/* INSTRUCCIONES
- Ejecutar getLocations
- Ejecutar correlateCines para a mano encontrar correlaciones.
*/
var request = require('request'),
cheerio = require('cheerio'),
mongoose = require('mongoose'),
md5 = require('md5'),
fs = require('fs'),
async = require('async'),
events... | l evento de actualizar provincias y ciudades en Mongo
eventEmitter.on('updateProvincias', function (misProvincias) {
//Limpio la colección de provincias
modelos.Provincia.remove({}, function (err) {
});
//Guardo en base de datos
modelos.Provincia.create(misProvincias, function (err) {
if (e... | var enlaceCiudad = urlBase + 'cines/' + provincia.provinciaId;
console.log(' -- Miro las ciudades del enlace: ' + enlaceCiudad);
//Saco el id de IMBD del cine
var codpost = codPostales[provincia.nombre];
//Lo consulto en IMDB
request(urlIMDB + codpost, function (err, response, body) {
... | identifier_body |
order.js | var OrderModel = require('./OrderModel');
function | (order) {
this.name = order.name;
this.sex = order.sex;
this.age = order.age;
this.mobile = order.mobile;
this.price = order.price;
this.userId = order.userId;
this.activityId = order.activityId;
this.activityTitle = order.activityTitle;
this.activityPic = order.activityPic;
this... | Order | identifier_name |
order.js | var OrderModel = require('./OrderModel');
function Order(order) {
this.name = order.name;
this.sex = order.sex;
this.age = order.age;
this.mobile = order.mobile;
this.price = order.price;
this.userId = order.userId;
this.activityId = order.activityId;
this.activityTitle = order.activity... | });
};
Order.getAll = function(skip, limit, callback) {
OrderModel.count(function(err, count) {
OrderModel.find({}, null, {skip: skip, limit: limit},function (err, orders) {
if(err) {
return callback(err);
}
callback(err, orders, count);
});
... | return callback(err);
}
callback(err, order); | random_line_split |
order.js | var OrderModel = require('./OrderModel');
function Order(order) {
this.name = order.name;
this.sex = order.sex;
this.age = order.age;
this.mobile = order.mobile;
this.price = order.price;
this.userId = order.userId;
this.activityId = order.activityId;
this.activityTitle = order.activity... |
callback(err, orders, count);
});
});
}; | {
return callback(err);
} | conditional_block |
order.js | var OrderModel = require('./OrderModel');
function Order(order) |
module.exports = Order;
Order.prototype.save = function(callback) {
var order = {
name: this.name,
sex: this.sex,
age: this.age,
mobile: this.mobile,
orderNo: new Date().getTime(),
price: this.price,
userId: this.userId,
activityId: this.activityId,... | {
this.name = order.name;
this.sex = order.sex;
this.age = order.age;
this.mobile = order.mobile;
this.price = order.price;
this.userId = order.userId;
this.activityId = order.activityId;
this.activityTitle = order.activityTitle;
this.activityPic = order.activityPic;
this.activit... | identifier_body |
set_pusher.rs | //! [POST /_matrix/client/r0/pushers/set](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-pushers-set)
use ruma_api::ruma_api;
use super::Pusher;
ruma_api! {
metadata {
description: "This endpoint allows the creation, modification and deletion of pushers for this user ID.",
... |
request {
/// The pusher to configure
#[serde(flatten)]
pub pusher: Pusher,
/// Controls if another pusher with the same pushkey and app id should be created.
/// See the spec for details.
#[serde(default)]
pub append: bool
}
response {}
error... | rate_limited: true,
requires_authentication: true,
} | random_line_split |
clean_mac_info_plist.py | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the KombatKoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
| outFile = "KombatKoin-Qt.app/Contents/Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", "");
fIn = open(inFile, "r... | inFile = bitcoinDir+"/share/qt/Info.plist" | random_line_split |
clean_mac_info_plist.py | #!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the KombatKoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
... |
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
newFileContent = s.substitute(VERSION=version,YEAR=date.today().year)
fOut = open(outFile, "w");
fOut.write(newFileContent);
print "Info.plist fresh created"
| lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", ""); | conditional_block |
lib.rs | //! rimd is a set of utilities to deal with midi messages and standard
//! midi files (SMF). It handles both standard midi messages and the meta
//! messages that are found in SMFs.
//!
//! rimd is fairly low level, and messages are stored and accessed in
//! their underlying format (i.e. a vector of u8s). There are... | {
Midi(MidiMessage),
Meta(MetaEvent),
}
impl fmt::Display for Event {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Event::Midi(ref m) => { write!(f, "{}", m) }
Event::Meta(ref m) => { write!(f, "{}", m) }
}
}
}
impl Event {
/// Retur... | Event | identifier_name |
lib.rs | //! rimd is a set of utilities to deal with midi messages and standard
//! midi files (SMF). It handles both standard midi messages and the meta
//! messages that are found in SMFs.
//!
//! rimd is fairly low level, and messages are stored and accessed in
//! their underlying format (i.e. a vector of u8s). There are... | fn from(err: MetaError) -> SMFError {
SMFError::MetaError(err)
}
}
impl From<FromUtf8Error> for SMFError {
fn from(_: FromUtf8Error) -> SMFError {
SMFError::InvalidSMFFile("Invalid UTF8 data in file")
}
}
impl error::Error for SMFError {
fn description(&self) -> &str {
matc... |
impl From<MetaError> for SMFError { | random_line_split |
lib.rs | //! rimd is a set of utilities to deal with midi messages and standard
//! midi files (SMF). It handles both standard midi messages and the meta
//! messages that are found in SMFs.
//!
//! rimd is fairly low level, and messages are stored and accessed in
//! their underlying format (i.e. a vector of u8s). There are... |
}
impl From<FromUtf8Error> for SMFError {
fn from(_: FromUtf8Error) -> SMFError {
SMFError::InvalidSMFFile("Invalid UTF8 data in file")
}
}
impl error::Error for SMFError {
fn description(&self) -> &str {
match *self {
SMFError::InvalidSMFFile(_) => "The SMF file was invalid",... | {
SMFError::MetaError(err)
} | identifier_body |
index.tsx | import * as React from 'react'
// import * as css from './styles.scss'
import styled from 'styled-components'
export interface P {
title?: string;
bolded?: boolean;
variant?: 'info' | 'normal' | 'primary' | 'success' | 'warning' | 'danger';
children?: JSX.Element[] | JSX.Element | string;
className?: string... | vertical-align: baseline;
font-weight: ${(props: P) => (props.bolded ? '700' : '400')};
color: $c-primary-color;
border: 1px solid $c-info-border;
background-color: $c-info-background;
`
export default class Badge extends React.PureComponent<P, {}> {
static defaultProps = {
title: '',
variant: 'no... | line-height: 1;
border-radius: 2px;
display: inline-block; | random_line_split |
index.tsx | import * as React from 'react'
// import * as css from './styles.scss'
import styled from 'styled-components'
export interface P {
title?: string;
bolded?: boolean;
variant?: 'info' | 'normal' | 'primary' | 'success' | 'warning' | 'danger';
children?: JSX.Element[] | JSX.Element | string;
className?: string... | extends React.PureComponent<P, {}> {
static defaultProps = {
title: '',
variant: 'normal',
className: '',
}
render () {
const { title, className, children, ...rest } = this.props
return (
<StyledBadge className={className} {...rest}>
{title || children}
</StyledBadge>
... | Badge | identifier_name |
Gruntfile.js | "use strict";
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
interval: 200,
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: false,
newcap: true,
noarg: ... | }
});
// npm tasks
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
// Default task.
grunt.registerTask('default', ['jshint']);
}; | files: ['<%= jshint.files.src %>'],
tasks: ['default'] | random_line_split |
NavigationUI.ts | /// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" />
/// <reference path="../../node_modules/rx/ts/rx.all.d.ts" />
import * as rx from "rx";
import * as vd from "virtual-dom";
import {EdgeDirection} from "../Edge";
import {Node} from "../Graph";
import {Container, Navigator} from "../Viewer";
import {U... |
btns.push(this.createVNode(direction, name));
}
return {name: this._name, vnode: vd.h(`div.NavigationUI`, btns)};
}).subscribe(this._container.domRenderer.render$);
}
protected _deactivate(): void {
this._disposable.dispose();
}
private create... | {
continue;
} | conditional_block |
NavigationUI.ts | /// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" />
/// <reference path="../../node_modules/rx/ts/rx.all.d.ts" />
import * as rx from "rx";
import * as vd from "virtual-dom";
import {EdgeDirection} from "../Edge";
import {Node} from "../Graph";
import {Container, Navigator} from "../Viewer";
import {U... | this._disposable = this._navigator.stateService.currentNode$.map((node: Node): IVNodeHash => {
let btns: vd.VNode[] = [];
for (let edge of node.edges) {
let direction: EdgeDirection = edge.data.direction;
let name: string = this._dirNames[direction];
... | protected _activate(): void { | random_line_split |
NavigationUI.ts | /// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" />
/// <reference path="../../node_modules/rx/ts/rx.all.d.ts" />
import * as rx from "rx";
import * as vd from "virtual-dom";
import {EdgeDirection} from "../Edge";
import {Node} from "../Graph";
import {Container, Navigator} from "../Viewer";
import {U... |
}
UIService.register(NavigationUI);
export default NavigationUI;
| {
return vd.h(`span.btn.Direction.Direction${name}`,
{onclick: (ev: Event): void => { this._navigator.moveDir(direction).first().subscribe(); }},
[]);
} | identifier_body |
NavigationUI.ts | /// <reference path="../../typings/virtual-dom/virtual-dom.d.ts" />
/// <reference path="../../node_modules/rx/ts/rx.all.d.ts" />
import * as rx from "rx";
import * as vd from "virtual-dom";
import {EdgeDirection} from "../Edge";
import {Node} from "../Graph";
import {Container, Navigator} from "../Viewer";
import {U... | (direction: EdgeDirection, name: string): vd.VNode {
return vd.h(`span.btn.Direction.Direction${name}`,
{onclick: (ev: Event): void => { this._navigator.moveDir(direction).first().subscribe(); }},
[]);
}
}
UIService.register(NavigationUI);
export default NavigationUI... | createVNode | identifier_name |
dynamicBindings.js | function testEval(x, y) {
x = 5;
eval("arguments[0] += 10");
assertEq(x, 15);
}
for (var i = 0; i < 5; i++)
testEval(3);
| eval("arguments[0] += 10");
assertEq(arguments[y], 13);
}
for (var i = 0; i < 5; i++)
testEvalWithArguments(3, 0);
function testNestedEval(x, y) {
x = 5;
eval("eval('arguments[0] += 10')");
assertEq(x, 15);
}
for (var i = 0; i < 5; i++)
testNestedEval(3);
function testWith(x, y) {
with ({}) {
argu... | function testEvalWithArguments(x, y) { | random_line_split |
dynamicBindings.js |
function testEval(x, y) |
for (var i = 0; i < 5; i++)
testEval(3);
function testEvalWithArguments(x, y) {
eval("arguments[0] += 10");
assertEq(arguments[y], 13);
}
for (var i = 0; i < 5; i++)
testEvalWithArguments(3, 0);
function testNestedEval(x, y) {
x = 5;
eval("eval('arguments[0] += 10')");
assertEq(x, 15);
}
for (var i = 0... | {
x = 5;
eval("arguments[0] += 10");
assertEq(x, 15);
} | identifier_body |
dynamicBindings.js |
function testEval(x, y) {
x = 5;
eval("arguments[0] += 10");
assertEq(x, 15);
}
for (var i = 0; i < 5; i++)
testEval(3);
function testEvalWithArguments(x, y) {
eval("arguments[0] += 10");
assertEq(arguments[y], 13);
}
for (var i = 0; i < 5; i++)
testEvalWithArguments(3, 0);
function | (x, y) {
x = 5;
eval("eval('arguments[0] += 10')");
assertEq(x, 15);
}
for (var i = 0; i < 5; i++)
testNestedEval(3);
function testWith(x, y) {
with ({}) {
arguments[0] += 10;
assertEq(x, 13);
}
}
for (var i = 0; i < 5; i++)
testWith(3);
| testNestedEval | identifier_name |
configuration.rs | //! Konfiguration Datei Managment
//!
use errors::*;
use std::fs::File;
use std::path::Path;
use std::io::Read;
pub struct Configuration;
impl Configuration {
/// Liest die Konfiguration
///
/// # Return values
///
/// Diese Funktion liefert ein Result. Das Result enthält die Konfiguration, als S... | ) -> Result<String> {
// TODO: In production nur Konfig von `/boot` verwenden!
let possible_paths = vec![
Path::new("/boot/xMZ-Mod-Touch.json"),
Path::new("/usr/share/xmz-mod-touch-server/xMZ-Mod-Touch.json.production"),
Path::new("xMZ-Mod-Touch.json"),
];
... | et_config( | identifier_name |
configuration.rs | //! Konfiguration Datei Managment
//!
use errors::*;
use std::fs::File;
use std::path::Path;
use std::io::Read;
pub struct Configuration;
impl Configuration {
/// Liest die Konfiguration
///
/// # Return values
///
/// Diese Funktion liefert ein Result. Das Result enthält die Konfiguration, als S... | }
Ok(ret)
}
}
|
match File::open(&p) {
Ok(mut file) => {
println!("Verwende Konfigurationsdatei: {}", p.display());
file.read_to_string(&mut ret)?;
}
Err(_) => panic!("Could not open file: {}", p.display()),
... | conditional_block |
configuration.rs | //! Konfiguration Datei Managment
//!
use errors::*;
use std::fs::File;
use std::path::Path;
use std::io::Read;
pub struct Configuration;
impl Configuration {
/// Liest die Konfiguration
///
/// # Return values
///
/// Diese Funktion liefert ein Result. Das Result enthält die Konfiguration, als S... | }
} | random_line_split | |
baseRequiredField.validator.ts | import { get, has, upperFirst } from 'lodash';
import { IPipeline, IStage, IStageOrTriggerTypeConfig, ITrigger } from 'core/domain';
import { IStageOrTriggerValidator, IValidatorConfig } from './PipelineConfigValidator';
export interface IRequiredField {
fieldName: string;
fieldLabel?: string;
}
export interface... | config: IStageOrTriggerTypeConfig,
): string {
if (!this.passesValidation(pipeline, stage, validationConfig)) {
return this.validationMessage(validationConfig, config);
}
return null;
}
protected abstract passesValidation(
pipeline: IPipeline,
stage: IStage | ITrigger,
validatio... | random_line_split | |
baseRequiredField.validator.ts | import { get, has, upperFirst } from 'lodash';
import { IPipeline, IStage, IStageOrTriggerTypeConfig, ITrigger } from 'core/domain';
import { IStageOrTriggerValidator, IValidatorConfig } from './PipelineConfigValidator';
export interface IRequiredField {
fieldName: string;
fieldLabel?: string;
}
export interface... |
return null;
}
protected abstract passesValidation(
pipeline: IPipeline,
stage: IStage | ITrigger,
validationConfig: IBaseRequiredFieldValidationConfig,
): boolean;
protected abstract validationMessage(
validationConfig: IBaseRequiredFieldValidationConfig,
config: IStageOrTriggerTypeC... | {
return this.validationMessage(validationConfig, config);
} | conditional_block |
baseRequiredField.validator.ts | import { get, has, upperFirst } from 'lodash';
import { IPipeline, IStage, IStageOrTriggerTypeConfig, ITrigger } from 'core/domain';
import { IStageOrTriggerValidator, IValidatorConfig } from './PipelineConfigValidator';
export interface IRequiredField {
fieldName: string;
fieldLabel?: string;
}
export interface... |
protected fieldIsValid(pipeline: IPipeline, stage: IStage | ITrigger, fieldName: string): boolean {
if (pipeline.strategy === true && ['cluster', 'regions', 'zones', 'credentials'].includes(fieldName)) {
return true;
}
const fieldExists = has(stage, fieldName);
const field: any = get(stage, f... | {
const fieldLabel: string = field.fieldLabel || field.fieldName;
return upperFirst(fieldLabel);
} | identifier_body |
baseRequiredField.validator.ts | import { get, has, upperFirst } from 'lodash';
import { IPipeline, IStage, IStageOrTriggerTypeConfig, ITrigger } from 'core/domain';
import { IStageOrTriggerValidator, IValidatorConfig } from './PipelineConfigValidator';
export interface IRequiredField {
fieldName: string;
fieldLabel?: string;
}
export interface... | (field: IRequiredField): string {
const fieldLabel: string = field.fieldLabel || field.fieldName;
return upperFirst(fieldLabel);
}
protected fieldIsValid(pipeline: IPipeline, stage: IStage | ITrigger, fieldName: string): boolean {
if (pipeline.strategy === true && ['cluster', 'regions', 'zones', 'crede... | printableFieldLabel | identifier_name |
end.js | const EventEmitter = require('events');
/**
* Ends the session. Uses session protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.end();
* };
*
* @method end
* @syntax .end([callback])
* @param {function} [callback] Optional callback function to be called when the command finishe... | }
this.emit('complete');
}
}
module.exports = End; | random_line_split | |
end.js | const EventEmitter = require('events');
/**
* Ends the session. Uses session protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.end();
* };
*
* @method end
* @syntax .end([callback])
* @param {function} [callback] Optional callback function to be called when the command finishe... | (callback) {
const client = this.client;
if (this.api.sessionId) {
this.api.session('delete', result => {
client.session.clearSession();
client.setApiProperty('sessionId', null);
this.complete(callback, result);
});
} else {
setImmediate(() => {
this.compl... | command | identifier_name |
end.js | const EventEmitter = require('events');
/**
* Ends the session. Uses session protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.end();
* };
*
* @method end
* @syntax .end([callback])
* @param {function} [callback] Optional callback function to be called when the command finishe... |
return this.client.api;
}
complete(callback, result) {
if (typeof callback === 'function') {
callback.call(this.api, result);
}
this.emit('complete');
}
}
module.exports = End;
| {
setImmediate(() => {
this.complete(callback, null);
});
} | conditional_block |
end.js | const EventEmitter = require('events');
/**
* Ends the session. Uses session protocol command.
*
* @example
* this.demoTest = function (browser) {
* browser.end();
* };
*
* @method end
* @syntax .end([callback])
* @param {function} [callback] Optional callback function to be called when the command finishe... |
complete(callback, result) {
if (typeof callback === 'function') {
callback.call(this.api, result);
}
this.emit('complete');
}
}
module.exports = End;
| {
const client = this.client;
if (this.api.sessionId) {
this.api.session('delete', result => {
client.session.clearSession();
client.setApiProperty('sessionId', null);
this.complete(callback, result);
});
} else {
setImmediate(() => {
this.complete(callbac... | identifier_body |
blob_samples_authentication_async.py | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... | (self):
# [START auth_from_connection_string]
from azure.storage.blob.aio import BlobServiceClient
blob_service_client = BlobServiceClient.from_connection_string(self.connection_string)
# [END auth_from_connection_string]
# [START auth_from_connection_string_container]
f... | auth_connection_string_async | identifier_name |
blob_samples_authentication_async.py | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... | # await sample.auth_active_directory()
await sample.auth_shared_access_signature_async()
await sample.auth_blob_url_async()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main()) | sample = AuthSamplesAsync()
# Uncomment the methods you want to execute.
await sample.auth_connection_string_async() | random_line_split |
blob_samples_authentication_async.py | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... |
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
| sample = AuthSamplesAsync()
# Uncomment the methods you want to execute.
await sample.auth_connection_string_async()
# await sample.auth_active_directory()
await sample.auth_shared_access_signature_async()
await sample.auth_blob_url_async() | identifier_body |
blob_samples_authentication_async.py | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... | loop = asyncio.get_event_loop()
loop.run_until_complete(main()) | conditional_block | |
win_tool.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility functions for Windows builds.
These functions are executed via gyp-win-tool when using the ninja generator.
"""
from ctypes imp... | (self, path):
"""Simple stamp command."""
open(path, 'w').close()
def ExecRecursiveMirror(self, source, dest):
"""Emulation of rm -rf out && cp -af in out."""
if os.path.exists(dest):
if os.path.isdir(dest):
shutil.rmtree(dest)
else:
os.unlink(dest)
if os.path.isdir(so... | ExecStamp | identifier_name |
win_tool.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility functions for Windows builds.
These functions are executed via gyp-win-tool when using the ninja generator.
"""
from ctypes imp... |
return popen.returncode
def ExecRcWrapper(self, arch, *args):
"""Filter logo banner from invocations of rc.exe. Older versions of RC
don't support the /nologo flag."""
env = self._GetEnv(arch)
popen = subprocess.Popen(args, shell=True, env=env,
stdout=subprocess.PIPE... | if (not line.startswith('Copyright (C) Microsoft Corporation') and
not line.startswith('Microsoft (R) Macro Assembler') and
not line.startswith(' Assembling: ') and
line):
print line | conditional_block |
win_tool.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved. | # Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility functions for Windows builds.
These functions are executed via gyp-win-tool when using the ninja generator.
"""
from ctypes import windll, wintypes
import os
import shutil
import subprocess
import sys
BA... | random_line_split | |
win_tool.py | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility functions for Windows builds.
These functions are executed via gyp-win-tool when using the ninja generator.
"""
from ctypes imp... |
def ExecAsmWrapper(self, arch, *args):
"""Filter logo banner from invocations of asm.exe."""
env = self._GetEnv(arch)
# MSVS doesn't assemble x64 asm files.
if arch == 'environment.x64':
return 0
popen = subprocess.Popen(args, shell=True, env=env,
stdout=subpro... | """Filter noisy filenames output from MIDL compile step that isn't
quietable via command line flags.
"""
args = ['midl', '/nologo'] + list(flags) + [
'/out', outdir,
'/tlb', tlb,
'/h', h,
'/dlldata', dlldata,
'/iid', iid,
'/proxy', proxy,
idl]
env ... | identifier_body |
detox-global-tests.ts | declare var describe: (test: string, callback: () => void) => void;
declare var beforeAll: (callback: () => void) => void;
declare var afterAll: (callback: () => void) => void;
declare var test: (test: string, callback: () => void) => void;
describe("Test", () => {
beforeAll(async () => {
await device.relo... | await element(by.id("scrollView")).swipe("down", "fast");
await element(by.type("UIPickerView")).setColumnToValue(1, "6");
await expect(
element(by.id("element").withAncestor(by.id("parent_element")))
).toNotExist();
await expect(
element(by.id("element")... | random_line_split | |
scipy_test.py | import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy.stats import multivariate_normal as mvn
norm.pdf(0)
# mean: loc, stddev: scale
norm.pdf(0, loc=5, scale=10)
r = np.random.randn(10)
# probability distribution function:
norm.pdf(r)
# log probability:
norm.log... | plt.show()
Y = np.fft.fft(y)
plt.plot(np.abs(Y))
plt.show()
2*np.pi*16/100
2*np.pi*48/100
2*np.pi*80/100 | plt.plot(x, y)
| random_line_split |
attribute-config.ts | /*
* Copyright (c) 2015-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red H... | (register: che.IRegisterService) {
register.directive('focusable', CheFocusable);
register.directive('cheAutoScroll', CheAutoScroll);
register.directive('cheListOnScrollBottom', CheListOnScrollBottom);
register.directive('cheReloadHref', CheReloadHref);
register.directive('cheFormatOutput', Che... | constructor | identifier_name |
attribute-config.ts | /*
* Copyright (c) 2015-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red H... |
register.directive('focusable', CheFocusable);
register.directive('cheAutoScroll', CheAutoScroll);
register.directive('cheListOnScrollBottom', CheListOnScrollBottom);
register.directive('cheReloadHref', CheReloadHref);
register.directive('cheFormatOutput', CheFormatOutput);
register.direct... | random_line_split | |
get_last_with_len.rs | //! lint on using `x.get(x.len() - 1)` instead of `x.last()`
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::SpanlessEq;
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Appli... |
}
| {
if_chain! {
// Is a method call
if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
// Method name is "get"
if path.ident.name == sym!(get);
// Argument 0 (the struct we're calling the method on) is a vector
if let Some(struct_ca... | identifier_body |
get_last_with_len.rs | //! lint on using `x.get(x.len() - 1)` instead of `x.last()`
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::SpanlessEq;
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Appli... | fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if_chain! {
// Is a method call
if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
// Method name is "get"
if path.ident.name == sym!(get);
// Argument 0 (the struct... | }
declare_lint_pass!(GetLastWithLen => [GET_LAST_WITH_LEN]);
impl<'tcx> LateLintPass<'tcx> for GetLastWithLen { | random_line_split |
get_last_with_len.rs | //! lint on using `x.get(x.len() - 1)` instead of `x.last()`
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::SpanlessEq;
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Appli... | (&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if_chain! {
// Is a method call
if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
// Method name is "get"
if path.ident.name == sym!(get);
// Argument 0 (the struct we're calling th... | check_expr | identifier_name |
IPostComponentProps.ts | import { Comment } from 'core/domain/comments'
import { Post } from 'core/domain/posts/post'
import {Map} from 'immutable'
export interface IPostComponentProps {
/**
* Post object
*/
post: Map<string, any>
/**
* Owner's post avatar
*
* @type {string}
* @memberof IPostComponentProps
*/
ava... | * Vote a post
*
* @memberof IPostComponentProps
*/
vote?: () => any
/**
* Delete a vote on the post
*
* @memberof IPostComponentProps
*/
unvote?: () => any
/**
* Delte a post
*
* @memberof IPostComponentProps
*/
delete?: (id: string) => any
/**
* Toggle comment disa... |
/** | random_line_split |
RootItem.js | import React from 'react';
import PropTypes from 'prop-types';
import style from 'PVWStyle/ReactWidgets/CompositePipelineWidget.mcss';
import ChildItem from './ChildItem';
/**
* This React component expect the following input properties:
* - model:
* Expect a LokkupTable instance that you want to render a... | () {
if (this.props.model.getColor(this.props.layer).length > 1) {
this.setState({
dropDown: !this.state.dropDown,
});
}
}
updateColorBy(event) {
this.props.model.setActiveColor(
this.props.layer,
event.target.dataset.color
);
this.toggleDropDown();
}
toggle... | toggleDropDown | identifier_name |
RootItem.js | import React from 'react';
import PropTypes from 'prop-types';
import style from 'PVWStyle/ReactWidgets/CompositePipelineWidget.mcss';
import ChildItem from './ChildItem';
/**
* This React component expect the following input properties:
* - model:
* Expect a LokkupTable instance that you want to render a... |
}
updateColorBy(event) {
this.props.model.setActiveColor(
this.props.layer,
event.target.dataset.color
);
this.toggleDropDown();
}
toggleEditMode() {
this.props.model.toggleEditMode(this.props.layer);
}
updateOpacity(e) {
this.props.model.setOpacity(this.props.layer, e.ta... | {
this.setState({
dropDown: !this.state.dropDown,
});
} | conditional_block |
RootItem.js | import React from 'react';
import PropTypes from 'prop-types';
import style from 'PVWStyle/ReactWidgets/CompositePipelineWidget.mcss';
import ChildItem from './ChildItem';
/**
* This React component expect the following input properties:
* - model:
* Expect a LokkupTable instance that you want to render a... |
toggleDropDown() {
if (this.props.model.getColor(this.props.layer).length > 1) {
this.setState({
dropDown: !this.state.dropDown,
});
}
}
updateColorBy(event) {
this.props.model.setActiveColor(
this.props.layer,
event.target.dataset.color
);
this.toggleDropDown... | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.