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 |
|---|---|---|---|---|
ND280Transform_CSVEvtList.py | from GangaCore.GPIDev.Schema import *
from GangaCore.GPIDev.Lib.Tasks.common import *
from GangaCore.GPIDev.Lib.Tasks.ITransform import ITransform
from GangaCore.GPIDev.Lib.Job.Job import JobError
from GangaCore.GPIDev.Lib.Registry.JobRegistry import JobRegistrySlice, JobRegistrySliceProxy
from GangaCore.Core.exception... | from GangaND280.ND280Dataset.ND280Dataset import ND280LocalDataset
from GangaND280.ND280Splitter import splitCSVFile
import GangaCore.GPI as GPI
import os
logger = getLogger()
class ND280Transform_CSVEvtList(ITransform):
_schema = Schema(Version(1,0), dict(list(ITransform._schema.datadict.items()) + list({
... | random_line_split | |
ND280Transform_CSVEvtList.py | from GangaCore.GPIDev.Schema import *
from GangaCore.GPIDev.Lib.Tasks.common import *
from GangaCore.GPIDev.Lib.Tasks.ITransform import ITransform
from GangaCore.GPIDev.Lib.Job.Job import JobError
from GangaCore.GPIDev.Lib.Registry.JobRegistry import JobRegistrySlice, JobRegistrySliceProxy
from GangaCore.Core.exception... |
if not use_copy_output or not copy_output_ok:
unit = ND280Unit_CSVEvtList()
unit.inputdata = ND280LocalDataset()
for parent in parent_units:
# loop over the output files and add them to the ND280LocalDataset - THIS MIGHT NEED SOME WORK!
job = GPI.jobs(parent.ac... | return None | conditional_block |
ND280Transform_CSVEvtList.py | from GangaCore.GPIDev.Schema import *
from GangaCore.GPIDev.Lib.Tasks.common import *
from GangaCore.GPIDev.Lib.Tasks.ITransform import ITransform
from GangaCore.GPIDev.Lib.Job.Job import JobError
from GangaCore.GPIDev.Lib.Registry.JobRegistry import JobRegistrySlice, JobRegistrySliceProxy
from GangaCore.Core.exception... |
def createUnits(self):
"""Create new units if required given the inputdata"""
# call parent for chaining
super(ND280Transform_CSVEvtList,self).createUnits()
# Look at the application schema and check if there is a csvfile variable
try:
csvfile = self.application.... | super(ND280Transform_CSVEvtList,self).__init__() | identifier_body |
network.py | import numpy as np
import random
class NeuralNetwork():
def __init__(self, sizes):
# sizes is an array with the number of units in each layer
# [2,3,1] means w neurons of input, 3 in the hidden layer and 1 as output
self.num_layers = len(sizes)
self.sizes = sizes
# the syn... | (z):
return sigmoid(z) * (1-sigmoid(z))
| sigmoid_prime | identifier_name |
network.py | import numpy as np
import random
class NeuralNetwork():
def __init__(self, sizes):
# sizes is an array with the number of units in each layer
# [2,3,1] means w neurons of input, 3 in the hidden layer and 1 as output
self.num_layers = len(sizes)
self.sizes = sizes
# the syn... |
def separate_batches(self, training_data, batch_size):
random.shuffle(training_data)
n = len(training_data)
# extracts chunks of data from the training set
# the xrange function will return indices starting with 0 untill n, with a step size o batch_size
# batches, then, wil... | for b,w in zip(self.biases, self.weights):
a = sigmoid(np.dot(w, a) + b)
return a | identifier_body |
network.py | import numpy as np
import random
class NeuralNetwork():
def __init__(self, sizes):
# sizes is an array with the number of units in each layer
# [2,3,1] means w neurons of input, 3 in the hidden layer and 1 as output
self.num_layers = len(sizes)
self.sizes = sizes
# the syn... | delta = self.cost_derivative(activations[-1], y) * \
sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
for l in range(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
delta = np.dot(sel... | zs.append(z)
activation = sigmoid(z)
activations.append(activation)
# backward pass | random_line_split |
network.py | import numpy as np
import random
class NeuralNetwork():
def __init__(self, sizes):
# sizes is an array with the number of units in each layer
# [2,3,1] means w neurons of input, 3 in the hidden layer and 1 as output
self.num_layers = len(sizes)
self.sizes = sizes
# the syn... |
# backward pass
delta = self.cost_derivative(activations[-1], y) * \
sigmoid_prime(zs[-1])
nabla_b[-1] = delta
nabla_w[-1] = np.dot(delta, activations[-2].transpose())
for l in range(2, self.num_layers):
z = zs[-l]
sp = sigmoid_prime(z)
... | z = np.dot(w, activation)+b
zs.append(z)
activation = sigmoid(z)
activations.append(activation) | conditional_block |
cluster.component.ts | import { of, Subscription, timer as observableTimer } from 'rxjs';
import { catchError, filter, switchMap } from 'rxjs/operators';
import {
ChangeDetectionStrategy,
Component,
OnDestroy,
ViewChild,
ViewEncapsulation,
Inject,
AfterViewInit,
} from '@angular/core';
import { Location } from '@angular/common'... | () {
return !isNaN(this.cpuUsage) && !isNaN(this.ramUsage);
}
ngAfterViewInit() {
this.clusterId = this.route.snapshot.params.id;
this.getKube();
}
ngOnDestroy() {
this.subscriptions.unsubscribe();
}
combineAndFlatten(objOne, objTwo) {
const arr = [];
Object.keys(objOne).forEach(... | showUsageChart | identifier_name |
cluster.component.ts | import { of, Subscription, timer as observableTimer } from 'rxjs';
import { catchError, filter, switchMap } from 'rxjs/operators';
import {
ChangeDetectionStrategy,
Component,
OnDestroy,
ViewChild,
ViewEncapsulation,
Inject,
AfterViewInit,
} from '@angular/core';
import { Location } from '@angular/common'... | else {
// masters executing
this.masterTasksStatus = 'executing';
}
}
downloadPrivateKey() {
let a = document.createElement("a");
a.href = "data:," + this.kube.sshConfig.bootstrapPrivateKey;
a.setAttribute("download", this.kube.name + ".pem");
a.click();
}
orderTasks(a, b) {
... | {
// masters complete
this.masterTasksStatus = 'complete';
if (nodeTasks.every(this.taskComplete)) {
// masters AND nodes complete
this.nodeTasksStatus = 'complete';
this.clusterTasksStatus = 'executing';
} else {
// masters complete, nodes executing
thi... | conditional_block |
cluster.component.ts | import { of, Subscription, timer as observableTimer } from 'rxjs';
import { catchError, filter, switchMap } from 'rxjs/operators';
import {
ChangeDetectionStrategy,
Component,
OnDestroy,
ViewChild,
ViewEncapsulation,
Inject,
AfterViewInit,
} from '@angular/core';
import { Location } from '@angular/common'... |
taskComplete(task) {
return task.status == 'success';
}
viewTaskLog(taskId) {
const modal = this.dialog.open(TaskLogsComponent, {
width: '1080px',
data: { taskId: taskId, hostname: this.window.location.hostname }
});
}
setProvisioningStep(tasks) {
const masterPatt = /master/g;
... | {
task.showSteps = !task.showSteps;
if (this.expandedTaskIds.has(task.id)) {
this.expandedTaskIds.delete(task.id);
} else { this.expandedTaskIds.add(task.id); }
} | identifier_body |
cluster.component.ts | import { of, Subscription, timer as observableTimer } from 'rxjs';
import { catchError, filter, switchMap } from 'rxjs/operators';
import {
ChangeDetectionStrategy,
Component,
OnDestroy,
ViewChild,
ViewEncapsulation,
Inject,
AfterViewInit,
} from '@angular/core';
import { Location } from '@angular/common'... | arr.push(objTwo[key]);
});
return arr;
}
getKubeStatus(clusterId) {
// we should make Tasks a part of the Supergiant instance
// if we start using them outside of this
return this.util.fetch('/v1/api/kubes/' + clusterId + '/tasks');
}
toggleSteps(task) {
task.showSteps = !task.s... | });
Object.keys(objTwo).forEach((key) => { | random_line_split |
fields-definition.rs | // Copyright 2018 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 ... | fn main() {} | random_line_split | |
fields-definition.rs | // Copyright 2018 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 ... | {} | identifier_body | |
fields-definition.rs | // Copyright 2018 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 ... | {
a: u8,
$a: u8, // OK
}
}
macro_rules! legacy {
($a: ident) => {
struct Legacy {
a: u8,
$a: u8, //~ ERROR field `a` is already declared
}
}
}
modern!(a);
legacy!(a);
fn main() {}
| Modern | identifier_name |
kubernetescommand.ts | "use strict";
import * as del from "del";
import * as fs from "fs";
import * as tr from "azure-pipelines-task-lib/toolrunner";
import trm = require('azure-pipelines-task-lib/toolrunner');
import * as path from "path";
import * as tl from "azure-pipelines-task-lib/task";
import * as utils from "./utilities";
import Clus... |
function getCommandArguments(): string {
return tl.getInput("arguments", false);
}
export function isJsonOrYamlOutputFormatSupported(kubecommand): boolean {
var commandsThatDontSupportYamlAndJson: string[] = ["explain", "delete", "cluster-info", "top", "cordon", "uncordon", "drain", "describe", "logs", "atta... | {
var args: string[] = [];
var useConfigurationFile: boolean = tl.getBoolInput("useConfigurationFile", false);
if (useConfigurationFile) {
let configurationPath = tl.getPathInput("configuration", false);
var inlineConfiguration = tl.getInput("inline", false);
if (!tl.filePathSupplie... | identifier_body |
kubernetescommand.ts | "use strict";
import * as del from "del";
import * as fs from "fs";
import * as tr from "azure-pipelines-task-lib/toolrunner";
import trm = require('azure-pipelines-task-lib/toolrunner');
import * as path from "path";
import * as tl from "azure-pipelines-task-lib/task";
import * as utils from "./utilities";
import Clus... | args[1] = namespace;
}
return args;
} | if (namespace) {
args[0] = "-n"; | random_line_split |
kubernetescommand.ts | "use strict";
import * as del from "del";
import * as fs from "fs";
import * as tr from "azure-pipelines-task-lib/toolrunner";
import trm = require('azure-pipelines-task-lib/toolrunner');
import * as path from "path";
import * as tl from "azure-pipelines-task-lib/task";
import * as utils from "./utilities";
import Clus... |
else {
throw new Error(tl.loc('ConfigurationFileNotFound', configurationPath));
}
}
else if (inlineConfiguration) {
var tempInlineFile = utils.writeInlineConfigInTempPath(inlineConfiguration);
if (tl.exist(tempInlineFile)) {
... | {
args[0] = "-f";
args[1] = configurationPath;
} | conditional_block |
kubernetescommand.ts | "use strict";
import * as del from "del";
import * as fs from "fs";
import * as tr from "azure-pipelines-task-lib/toolrunner";
import trm = require('azure-pipelines-task-lib/toolrunner');
import * as path from "path";
import * as tl from "azure-pipelines-task-lib/task";
import * as utils from "./utilities";
import Clus... | (kubecommand): boolean {
var commandsThatDontSupportYamlAndJson: string[] = ["explain", "delete", "cluster-info", "top", "cordon", "uncordon", "drain", "describe", "logs", "attach", "exec", "port-forward", "proxy", "cp", "auth", "completion", "api-versions", "config", "help", "plugin", "rollout"];
if (commands... | isJsonOrYamlOutputFormatSupported | identifier_name |
base58.py | '''
Yescoin base58 encoding and decoding.
Based on https://yescointalk.org/index.php?topic=1026.0 (public domain)
'''
import hashlib
# for compatibility with following code...
class SHA256:
new = hashlib.sha256
if str != bytes:
# Python 3.x
def ord(c):
return c
def chr(n):
return byte... | (v):
"""b58encode a string, with 32-bit checksum"""
return b58encode(v + checksum(v))
def b58decode_chk(v):
"""decode a base58 string, check and remove checksum"""
result = b58decode(v)
if result is None:
return None
h3 = checksum(result[:-4])
if result[-4:] == checksum(result[:-4])... | b58encode_chk | identifier_name |
base58.py | '''
Yescoin base58 encoding and decoding.
Based on https://yescointalk.org/index.php?topic=1026.0 (public domain)
'''
import hashlib
# for compatibility with following code...
class SHA256:
new = hashlib.sha256
if str != bytes:
# Python 3.x
def ord(c):
return c
def chr(n):
return byte... |
if __name__ == '__main__':
# Test case (from http://gitorious.org/yescoin/python-base58.git)
assert get_bcaddress_version('15VjRaDX9zpbA8LVnbrCAFzrVzN7ixHNsC') is 0
_ohai = 'o hai'.encode('ascii')
_tmp = b58encode(_ohai)
assert _tmp == 'DYB3oMS'
assert b58decode(_tmp, 5) == _ohai
print("Te... | """ Returns None if strAddress is invalid. Otherwise returns integer version of address. """
addr = b58decode_chk(strAddress)
if addr is None or len(addr)!=21: return None
version = addr[0]
return ord(version) | identifier_body |
base58.py | '''
Yescoin base58 encoding and decoding.
Based on https://yescointalk.org/index.php?topic=1026.0 (public domain)
'''
import hashlib
# for compatibility with following code...
class SHA256:
new = hashlib.sha256
if str != bytes:
# Python 3.x
def ord(c):
return c
def chr(n):
return byte... |
result = bytes()
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + result
long_value = div
result = chr(long_value) + result
nPad = 0
for c in v:
if c == __b58chars[0]: nPad += 1
else: break
result = chr(0)*nPad + result
... | long_value += __b58chars.find(c) * (__b58base**i) | conditional_block |
base58.py | '''
Yescoin base58 encoding and decoding.
Based on https://yescointalk.org/index.php?topic=1026.0 (public domain)
'''
import hashlib
# for compatibility with following code...
class SHA256:
new = hashlib.sha256
if str != bytes:
# Python 3.x
def ord(c):
return c
def chr(n):
return byte... | return b58encode(v + checksum(v))
def b58decode_chk(v):
"""decode a base58 string, check and remove checksum"""
result = b58decode(v)
if result is None:
return None
h3 = checksum(result[:-4])
if result[-4:] == checksum(result[:-4]):
return result[:-4]
else:
return No... |
def b58encode_chk(v):
"""b58encode a string, with 32-bit checksum""" | random_line_split |
segment_hook.py | # -*- coding: utf-8 -*-
#
# 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
#... |
analytics.on_error = self.on_error
analytics.write_key = self.write_key
return analytics
def on_error(self, error, items):
"""
Handles error callbacks when using Segment with segment_debug_mode set to True
"""
self.log.error('Encountered Segment error: {segm... | self.log.info('Setting Segment analytics connection to debug mode') | conditional_block |
segment_hook.py | # -*- coding: utf-8 -*-
#
# 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
#... | (self):
self.log.info('Setting write key for Segment analytics connection')
analytics.debug = self.segment_debug_mode
if self.segment_debug_mode:
self.log.info('Setting Segment analytics connection to debug mode')
analytics.on_error = self.on_error
analytics.write_key... | get_conn | identifier_name |
segment_hook.py | # -*- coding: utf-8 -*-
#
# 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
#... | """
This module contains a Segment Hook
which allows you to connect to your Segment account,
retrieve data from it or write to that file.
NOTE: this hook also relies on the Segment analytics package:
https://github.com/segmentio/analytics-python
"""
import analytics
from airflow.hooks.base_hook import BaseHo... | random_line_split | |
segment_hook.py | # -*- coding: utf-8 -*-
#
# 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
#... | """
Handles error callbacks when using Segment with segment_debug_mode set to True
"""
self.log.error('Encountered Segment error: {segment_error} with '
'items: {with_items}'.format(segment_error=error,
with_items=items))... | identifier_body | |
0_setup.py | #!/usr/bin/python
#
# \file 0_setup.py
# \brief setup pacs_prim_list
# \date 2011-09-28 7:22GMT
# \author Jan Boon (Kaetemi)
# Python port of game data build pipeline.
# Setup pacs_prim_list
#
# NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
# Copyright (C) 2010 Winch Gate Property Limited
#
# This prog... | sys.path.append("../../configuration")
if os.path.isfile("log.log"):
os.remove("log.log")
log = open("log.log", "w")
from scripts import *
from buildsite import *
from process import *
from tools import *
from directories import *
printLog(log, "")
printLog(log, "-------")
printLog(log, "--- Setup pacs_prim_list")
p... | import time, sys, os, shutil, subprocess, distutils.dir_util | random_line_split |
0_setup.py | #!/usr/bin/python
#
# \file 0_setup.py
# \brief setup pacs_prim_list
# \date 2011-09-28 7:22GMT
# \author Jan Boon (Kaetemi)
# Python port of game data build pipeline.
# Setup pacs_prim_list
#
# NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
# Copyright (C) 2010 Winch Gate Property Limited
#
# This prog... |
# Setup build directories
printLog(log, ">>> Setup build directories <<<")
mkPath(log, DataCommonDirectory) # no choice
log.close()
# end of file
| mkPath(log, ExportBuildDirectory + "/" + dir) | conditional_block |
test_hpcp.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation ... |
suite = allTests(TestHPCP)
if __name__ == '__main__':
TextTestRunner(verbosity=2).run(suite)
| spectrum = specAlg(windowingAlg(frame))
(freqs, mags) = sPeaksAlg(spectrum)
hpcp = hpcpAlg(freqs,mags)
self.assertTrue(not any(numpy.isnan(hpcp)))
self.assertTrue(not any(numpy.isinf(hpcp)))
frame = fc(audio) | conditional_block |
test_hpcp.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation ... | (self):
self.assertConfigureFails(HPCP(), {'size':13})
def testHarmonics(self):
# Regression test for the 'harmonics' parameter
tone = 100. # arbitrary frequency [Hz]
freqs = [tone, tone*2, tone*3, tone*4]
mags = [1]*4
hpcpAlg = HPCP(minFrequency=50, maxFre... | testSizeNonmultiple12 | identifier_name |
test_hpcp.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation ... | # details.
#
# You should have received a copy of the Affero GNU General Public License
# version 3 along with this program. If not, see http://www.gnu.org/licenses/
from essentia_test import *
class TestHPCP(TestCase):
def testEmpty(self):
hpcp = HPCP()([], [])
self.assertEqualVec... | # option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
| random_line_split |
test_hpcp.py | #!/usr/bin/env python
# Copyright (C) 2006-2016 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Essentia
#
# Essentia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation ... |
def testSmallMinMaxRange(self):
self.assertConfigureFails(HPCP(), {'bandPreset':False, 'maxFrequency':200, 'minFrequency':1})
def testSizeNonmultiple12(self):
self.assertConfigureFails(HPCP(), {'size':13})
def testHarmonics(self):
# Regression test for the 'harmonics' pa... | self.assertConfigureFails(HPCP(), {'maxFrequency':1199, 'splitFrequency':1000}) | identifier_body |
functions.py | # twitter/functions.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
import tweepy
import wevote_functions.admin
from config.base import get_environment_variable
from exception.models import handle_exception
from wevote_functions.functions import positive_value_exists
logger = wevote_functions.admin.... | (twitter_user_id, twitter_handle=''):
status = ""
success = True
twitter_user_not_found_in_twitter = False
twitter_user_suspended_by_twitter = False
write_to_server_logs = False
# December 2021: Using the Twitter 1.1 API for OAuthHandler, since all other 2.0 apis that we need are not
# yet ... | retrieve_twitter_user_info | identifier_name |
functions.py | # twitter/functions.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
import tweepy
import wevote_functions.admin
from config.base import get_environment_variable
from exception.models import handle_exception
from wevote_functions.functions import positive_value_exists
logger = wevote_functions.admin.... |
twitter_handle_found = False
twitter_json = {}
from wevote_functions.functions import convert_to_int
twitter_user_id = convert_to_int(twitter_user_id)
try:
if positive_value_exists(twitter_handle):
twitter_user = api.get_user(screen_name=twitter_handle)
twitter_json... | twitter_handle = '' | conditional_block |
functions.py | # twitter/functions.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
import tweepy
import wevote_functions.admin
from config.base import get_environment_variable
from exception.models import handle_exception
from wevote_functions.functions import positive_value_exists
logger = wevote_functions.admin.... | status = ""
success = True
twitter_user_not_found_in_twitter = False
twitter_user_suspended_by_twitter = False
write_to_server_logs = False
# December 2021: Using the Twitter 1.1 API for OAuthHandler, since all other 2.0 apis that we need are not
# yet available.
# client = tweepy.Client(
... | identifier_body | |
functions.py | # twitter/functions.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
import tweepy
import wevote_functions.admin
from config.base import get_environment_variable
from exception.models import handle_exception
from wevote_functions.functions import positive_value_exists
logger = wevote_functions.admin.... | # access_token=TWITTER_ACCESS_TOKEN,
# access_token_secret=TWITTER_ACCESS_TOKEN_SECRET)
auth = tweepy.OAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)
api = tweepy.API(auth, timeout=10)
# Strip out the... | # client = tweepy.Client(
# consumer_key=TWITTER_CONSUMER_KEY,
# consumer_secret=TWITTER_CONSUMER_SECRET, | random_line_split |
main.rs | // @gbersac, @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/expert-system
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate regex;
mod parser;
mod parse_result;
mod s... |
/// Return the file name to parse in this execution.
fn args_parse() -> String {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("usage: {} file_name", args[0]);
std::process::exit(1)
}
args[1].clone()
}
fn resolve_and_print(
deps: &HashMap<char, ImplyPtr>,
initial_facts: &Set
) {
l... | {
let mut f = File::open(filename).unwrap();
let mut s = String::new();
let _ = f.read_to_string(&mut s);
s
} | identifier_body |
main.rs | // @gbersac, @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/expert-system
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate regex;
mod parser;
mod parse_result;
mod s... | println!("\nSolution according to those dependences:");
for initial_facts in &parsed.initial_facts {
resolve_and_print(&deps, initial_facts);
}
} | key, value.borrow().get_ident().unwrap());
} | random_line_split |
main.rs | // @gbersac, @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/expert-system
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate regex;
mod parser;
mod parse_result;
mod s... |
let parsed = parsed.unwrap();
let deps = solver::solve(&parsed);
println!("Query dependences:");
for (key, value) in &deps {
println!("For {} dependence tree is: {}",
key, value.borrow().get_ident().unwrap());
}
println!("\nSolution according to those dependences:");
for initial_fa... | {
println!("Parse error");
return ;
} | conditional_block |
main.rs | // @gbersac, @adjivas - github.com/adjivas. See the LICENSE
// file at the top-level directory of this distribution and at
// https://github.com/adjivas/expert-system
//
// This file may not be copied, modified, or distributed
// except according to those terms.
extern crate regex;
mod parser;
mod parse_result;
mod s... | () -> String {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("usage: {} file_name", args[0]);
std::process::exit(1)
}
args[1].clone()
}
fn resolve_and_print(
deps: &HashMap<char, ImplyPtr>,
initial_facts: &Set
) {
let initial_facts_str = initial_facts.true_fact_str();
println!("\nW... | args_parse | identifier_name |
regress-123437.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | ()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
testRegExp(statusmessages, patterns, strings, actualmatches, expectedmatches);
exitFunc ('test');
}
| test | identifier_name |
regress-123437.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | {
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
testRegExp(statusmessages, patterns, strings, actualmatches, expectedmatches);
exitFunc ('test');
} | identifier_body | |
regress-123437.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | *
* Contributor(s):
* waldemar, rogerl, pschwartau@netscape.com
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the ... | * Netscape Communications Corp.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved. | random_line_split |
app.js | var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser'); | var bodyParser = require('body-parser');
//var index = require('./routes/index');
//var users = require('./routes/users');
var pub_scr = require('./routes/dop.pubscr.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after pl... | random_line_split | |
validate-release.ts | import {task} from 'gulp';
import {readFileSync} from 'fs';
import {join} from 'path';
import {green, red} from 'chalk';
import {releasePackages} from './publish';
import {sync as glob} from 'glob';
import {buildConfig, sequenceTask} from 'lib-build-tools';
/** Path to the directory where all releases are created. */
... |
/**
* Checks an ES2015 bundle inside of a release package. Secondary entry-point bundles will be
* checked as well.
*/
function checkEs2015ReleaseBundle(bundlePath: string): string[] {
const bundleContent = readFileSync(bundlePath, 'utf8');
let failures: string[] = [];
if (inlineStylesSourcemapRegex.exec(bu... | {
return glob(join(releasesDir, packageName, 'esm2015/*.js'))
.reduce((failures: string[], bundlePath: string) => {
return failures.concat(checkEs2015ReleaseBundle(bundlePath));
}, []);
} | identifier_body |
validate-release.ts | import {task} from 'gulp';
import {readFileSync} from 'fs';
import {join} from 'path';
import {green, red} from 'chalk';
import {releasePackages} from './publish';
import {sync as glob} from 'glob';
import {buildConfig, sequenceTask} from 'lib-build-tools';
/** Path to the directory where all releases are created. */
... | .map((failures, index) => ({failures, packageName: releasePackages[index]}));
releaseFailures.forEach(({failures, packageName}) => {
failures.forEach(failure => console.error(red(`Failure (${packageName}): ${failure}`)));
});
if (releaseFailures.some(({failures}) => failures.length > 0)) {
// Throw ... | const releaseFailures = releasePackages
.map(packageName => checkReleasePackage(packageName)) | random_line_split |
validate-release.ts | import {task} from 'gulp';
import {readFileSync} from 'fs';
import {join} from 'path';
import {green, red} from 'chalk';
import {releasePackages} from './publish';
import {sync as glob} from 'glob';
import {buildConfig, sequenceTask} from 'lib-build-tools';
/** Path to the directory where all releases are created. */
... | (bundlePath: string): string[] {
const bundleContent = readFileSync(bundlePath, 'utf8');
let failures: string[] = [];
if (inlineStylesSourcemapRegex.exec(bundleContent) !== null) {
failures.push('Bundles contain sourcemap references in component styles.');
}
if (externalReferencesRegex.exec(bundleConten... | checkEs2015ReleaseBundle | identifier_name |
validate-release.ts | import {task} from 'gulp';
import {readFileSync} from 'fs';
import {join} from 'path';
import {green, red} from 'chalk';
import {releasePackages} from './publish';
import {sync as glob} from 'glob';
import {buildConfig, sequenceTask} from 'lib-build-tools';
/** Path to the directory where all releases are created. */
... | else {
console.log(green('Release output has been checked and everything looks fine.'));
}
});
/** Task that validates the given release package before releasing. */
function checkReleasePackage(packageName: string): string[] {
return glob(join(releasesDir, packageName, 'esm2015/*.js'))
.reduce((failures:... | {
// Throw an error to notify Gulp about the failures that have been detected.
throw 'Release output is not valid and not ready for being released.';
} | conditional_block |
animate.me.d.ts | export interface AnimateMeOptions {
readonly offset: number;
readonly reverse: boolean;
readonly animatedIn: string;
readonly offsetAttr: string;
readonly animationAttr: string;
readonly touchDisabled: boolean;
}
export declare class | {
options: AnimateMeOptions;
animated: HTMLElement[];
selector: string;
private win;
private winO;
private winH;
private offsets;
private isTouchDevice;
constructor(selector?: string, options?: Partial<AnimateMeOptions>);
setCurrentScroll: () => void;
setWindowDimensions: ()... | AnimateMe | identifier_name |
animate.me.d.ts | export interface AnimateMeOptions {
readonly offset: number;
readonly reverse: boolean;
readonly animatedIn: string;
readonly offsetAttr: string;
readonly animationAttr: string;
readonly touchDisabled: boolean;
}
export declare class AnimateMe {
options: AnimateMeOptions;
animated: HTMLE... | private listen;
private scrollListener;
private resizeListener;
}
export default AnimateMe; | random_line_split | |
xypath.py | #!/usr/bin/env python
""" musings on order of variables, x/y vs. col/row
Everyone agrees that col 2, row 1 is (2,1) which is xy ordered.
This works well with the name.
Remember that the usual iterators (over a list-of-lists)
is outer loop y first."""
from __future__ import absolute_import
import re
import messytables... | (self, *args, **kwargs):
return contrib_excel.pprint(self, *args, **kwargs)
def as_list(self, *args, **kwargs):
return contrib_excel.as_list(self, *args, **kwargs)
def filter_one(self, filter_by):
return contrib_excel.filter_one(self, filter_by)
def excel_locations(self, *args, **... | pprint | identifier_name |
xypath.py | #!/usr/bin/env python
""" musings on order of variables, x/y vs. col/row
Everyone agrees that col 2, row 1 is (2,1) which is xy ordered.
This works well with the name.
Remember that the usual iterators (over a list-of-lists)
is outer loop y first."""
from __future__ import absolute_import
import re
import messytables... | DOWN_RIGHT = (1, 1)
UP_LEFT = (-1, -1)
DOWN_LEFT = (-1, 1)
def cmp(x, y):
if x<y:
return -1
if x>y:
return 1
return 0
class XYPathError(Exception):
"""Problems with spreadsheet layouts should raise this or a descendant."""
pass
class JunctionError(RuntimeError, XYPathError):
... | LEFT = (-1, 0)
UP_RIGHT = (1, -1) | random_line_split |
xypath.py | #!/usr/bin/env python
""" musings on order of variables, x/y vs. col/row
Everyone agrees that col 2, row 1 is (2,1) which is xy ordered.
This works well with the name.
Remember that the usual iterators (over a list-of-lists)
is outer loop y first."""
from __future__ import absolute_import
import re
import messytables... |
def expand(self, direction, stop_before=None):
return self.fill(direction, stop_before=stop_before) | self
def fill(self, direction, stop_before=None):
"""Should give the same output as fill, except it
doesn't support non-cardinal directions or stop_before.
Twenty times faster... | """
Make a non-bag iterable of cells into a Bag. Some magic may be lost,
especially if it's zero length.
TODO: This should probably be part of the core __init__ class.
TODO: Don't do a piece-by-piece insertion, just slap the whole listed
iterable in, because this is slow.
... | identifier_body |
xypath.py | #!/usr/bin/env python
""" musings on order of variables, x/y vs. col/row
Everyone agrees that col 2, row 1 is (2,1) which is xy ordered.
This works well with the name.
Remember that the usual iterators (over a list-of-lists)
is outer loop y first."""
from __future__ import absolute_import
import re
import messytables... |
return newbag
def filter(self, filter_by):
"""
Returns a new bag containing only cells which match
the filter_by predicate.
filter_by can be:
a) a callable, which takes a cell as a parameter
and returns True if the cell should be returned,
suc... | if function(bag_cell, other_cell):
newbag.add(bag_cell)
break | conditional_block |
cast_lossless.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::in_constant;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_isize_or_usize;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, FloatTy, Ty};
use super::{utils, ... |
false
}
| {
if snip.starts_with('(') && snip.ends_with(')') {
return true;
}
} | conditional_block |
cast_lossless.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::in_constant;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_isize_or_usize;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, FloatTy, Ty};
use super::{utils, ... | (cx: &LateContext<'_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) -> bool {
// Do not suggest using From in consts/statics until it is valid to do so (see #2267).
if in_constant(cx, expr.hir_id) {
return false;
}
match (cast_from.is_integral(), cast_to.is_integral()) {
(true, ... | should_lint | identifier_name |
cast_lossless.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::in_constant;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_isize_or_usize;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, FloatTy, Ty};
use super::{utils, ... | span_lint_and_sugg(
cx,
CAST_LOSSLESS,
expr.span,
&format!(
"casting `{}` to `{}` may become silently lossy if you later change the type",
cast_from, cast_to
),
"try",
format!("{}::from({})", cast_to, sugg),
applicability,
)... | }
},
);
| random_line_split |
cast_lossless.rs | use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::in_constant;
use clippy_utils::source::snippet_opt;
use clippy_utils::ty::is_isize_or_usize;
use rustc_errors::Applicability;
use rustc_hir::{Expr, ExprKind};
use rustc_lint::LateContext;
use rustc_middle::ty::{self, FloatTy, Ty};
use super::{utils, ... |
fn should_strip_parens(cast_expr: &Expr<'_>, snip: &str) -> bool {
if let ExprKind::Binary(_, _, _) = cast_expr.kind {
if snip.starts_with('(') && snip.ends_with(')') {
return true;
}
}
false
}
| {
// Do not suggest using From in consts/statics until it is valid to do so (see #2267).
if in_constant(cx, expr.hir_id) {
return false;
}
match (cast_from.is_integral(), cast_to.is_integral()) {
(true, true) => {
let cast_signed_to_unsigned = cast_from.is_signed() && !cast_... | identifier_body |
minify.js | "use strict";
var to_ascii = typeof atob == "undefined" ? function(b64) {
return new Buffer(b64, "base64").toString();
} : atob;
var to_base64 = typeof btoa == "undefined" ? function(str) {
return new Buffer(str).toString("base64");
} : btoa;
function | (code) {
var match = /\n\/\/# sourceMappingURL=data:application\/json(;.*?)?;base64,(.*)/.exec(code);
if (!match) {
AST_Node.warn("inline source map not found");
return null;
}
return to_ascii(match[2]);
}
function set_shorthand(name, options, keys) {
if (options[name]) {
ke... | read_source_map | identifier_name |
minify.js | "use strict";
var to_ascii = typeof atob == "undefined" ? function(b64) {
return new Buffer(b64, "base64").toString();
} : atob;
var to_base64 = typeof btoa == "undefined" ? function(str) {
return new Buffer(str).toString("base64");
} : btoa;
function read_source_map(code) {
var match = /\n\/\/# sourceMap... | else {
options.parse = options.parse || {};
options.parse.toplevel = null;
for (var name in files) {
options.parse.filename = name;
options.parse.toplevel = parse(files[name], options.parse);
if (options.sourceMap && options.sourceMap.... | {
toplevel = files;
} | conditional_block |
minify.js | "use strict";
var to_ascii = typeof atob == "undefined" ? function(b64) {
return new Buffer(b64, "base64").toString();
} : atob;
var to_base64 = typeof btoa == "undefined" ? function(str) {
return new Buffer(str).toString("base64");
} : btoa;
function read_source_map(code) {
var match = /\n\/\/# sourceMap... | }
if (options.mangle) {
toplevel.figure_out_scope(options.mangle);
base54.reset();
toplevel.compute_char_frequency(options.mangle);
toplevel.mangle_names(options.mangle);
if (options.mangle.properties) {
toplevel = mangle_proper... | random_line_split | |
minify.js | "use strict";
var to_ascii = typeof atob == "undefined" ? function(b64) {
return new Buffer(b64, "base64").toString();
} : atob;
var to_base64 = typeof btoa == "undefined" ? function(str) {
return new Buffer(str).toString("base64");
} : btoa;
function read_source_map(code) {
var match = /\n\/\/# sourceMap... |
function minify(files, options) {
var warn_function = AST_Node.warn_function;
try {
if (typeof files == "string") {
files = [ files ];
}
options = defaults(options, {
compress: {},
ie8: false,
keep_fnames: false,
mangle: {},
... | {
if (options[name]) {
keys.forEach(function(key) {
if (options[key]) {
if (typeof options[key] != "object") options[key] = {};
if (!(name in options[key])) options[key][name] = options[name];
}
});
}
} | identifier_body |
basket.rs | use diesel::prelude::*;
use diesel;
use serde::{Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
use db::schema::baskets;
use db::schema::users;
use db::Db;
use model::{basket, AuthUser, PubUser, User};
use model::permissions::{has_permission, UserAction};
use routes::new::NewBasketForm;
use super::MAX_SL_L... | self.description.as_ref().map(AsRef::as_ref)
}
pub fn kind(&self) -> &str {
&self.kind
}
}
#[derive(Clone, Debug, Insertable)]
#[table_name = "baskets"]
pub struct NewBasket {
name: String,
user_id: i64,
description: Option<String>,
public: bool,
kind: String,
forke... | random_line_split | |
basket.rs | use diesel::prelude::*;
use diesel;
use serde::{Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
use db::schema::baskets;
use db::schema::users;
use db::Db;
use model::{basket, AuthUser, PubUser, User};
use model::permissions::{has_permission, UserAction};
use routes::new::NewBasketForm;
use super::MAX_SL_L... | else {
Some(new.description.trim().into())
};
let new_basket = NewBasket {
name: new.name,
user_id: user.id(),
description: description,
public: new.is_public,
kind: new.kind,
forked_from: None,
};
let... | {
None
} | conditional_block |
basket.rs | use diesel::prelude::*;
use diesel;
use serde::{Serialize, Serializer};
use std::fmt;
use std::ops::Deref;
use db::schema::baskets;
use db::schema::users;
use db::Db;
use model::{basket, AuthUser, PubUser, User};
use model::permissions::{has_permission, UserAction};
use routes::new::NewBasketForm;
use super::MAX_SL_L... | (
name: &str,
owner: &str,
auth_user: Option<&AuthUser>,
db: &Db,
) -> Option<Self> {
baskets::table
.inner_join(users::table)
.filter(baskets::name.eq(name))
.filter(users::username.eq(owner))
.first(&*db.conn())
.o... | load | identifier_name |
racingkings.py | """ The Racing Kings Variation"""
from pychess.Utils.const import RACINGKINGSCHESS, VARIANTS_OTHER_NONSTANDARD, \
A8, B8, C8, D8, E8, F8, G8, H8
from pychess.Utils.Board import Board
RACINGKINGSSTART = "8/8/8/8/8/8/krbnNBRK/qrbnNBRQ w - - 0 1"
RANK8 = (A8, B8, C8, D8, E8, F8, G8, H8)
class | (Board):
""" :Description: The Racing Kings variation is where the object of the game
is to bring your king to the eight row.
"""
variant = RACINGKINGSCHESS
__desc__ = _(
"In this game, check is entirely forbidden: not only is it forbidden\n" +
"to move ones king into check, but ... | RacingKingsBoard | identifier_name |
racingkings.py | """ The Racing Kings Variation"""
from pychess.Utils.const import RACINGKINGSCHESS, VARIANTS_OTHER_NONSTANDARD, \
A8, B8, C8, D8, E8, F8, G8, H8
from pychess.Utils.Board import Board
RACINGKINGSSTART = "8/8/8/8/8/8/krbnNBRK/qrbnNBRQ w - - 0 1"
RANK8 = (A8, B8, C8, D8, E8, F8, G8, H8)
class RacingKingsBoard(Boa... | return board.kings[board.color] in RANK8 and board.kings[board.color - 1] in RANK8 |
def test2KingInEightRow(board):
""" Test for a winning position """ | random_line_split |
racingkings.py | """ The Racing Kings Variation"""
from pychess.Utils.const import RACINGKINGSCHESS, VARIANTS_OTHER_NONSTANDARD, \
A8, B8, C8, D8, E8, F8, G8, H8
from pychess.Utils.Board import Board
RACINGKINGSSTART = "8/8/8/8/8/8/krbnNBRK/qrbnNBRQ w - - 0 1"
RANK8 = (A8, B8, C8, D8, E8, F8, G8, H8)
class RacingKingsBoard(Boa... | """ Test for a winning position """
return board.kings[board.color] in RANK8 and board.kings[board.color - 1] in RANK8 | identifier_body | |
racingkings.py | """ The Racing Kings Variation"""
from pychess.Utils.const import RACINGKINGSCHESS, VARIANTS_OTHER_NONSTANDARD, \
A8, B8, C8, D8, E8, F8, G8, H8
from pychess.Utils.Board import Board
RACINGKINGSSTART = "8/8/8/8/8/8/krbnNBRK/qrbnNBRQ w - - 0 1"
RANK8 = (A8, B8, C8, D8, E8, F8, G8, H8)
class RacingKingsBoard(Boa... |
else:
Board.__init__(self, setup=setup, lboard=lboard)
def testKingInEightRow(board):
""" Test for a winning position """
return board.kings[board.color - 1] in RANK8
def test2KingInEightRow(board):
""" Test for a winning position """
return board.kings[board.color] in RANK8 and... | Board.__init__(self, setup=RACINGKINGSSTART, lboard=lboard) | conditional_block |
old__TodoList.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions/index'
import { bindActionCreators } from 'redux'
/*** REDUX AWARE ***/
class TodoList extends Component {
renderList() { // since this is iterating, the todo is a single item from the overall array
... | }
//map action dispatch to a property??
function mapDispatchToProps(dispatch) {
// ??
// could possibly just throw the action creator inside
return bindActionCreators({ addTodo }, dispatch)
}
// can also assign connect function to an object and then export that instead
// literally connects react to redux
exp... | random_line_split | |
old__TodoList.js | import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions/index'
import { bindActionCreators } from 'redux'
/*** REDUX AWARE ***/
class TodoList extends Component {
| () { // since this is iterating, the todo is a single item from the overall array
return this.props.todos.map((todo) => {
return (
<li
/* on click, dispatch the ADD_TODO action */
onClick={() => this.props.addTodo(todo)}
>
{todo.name}
</li>
)
})
... | renderList | identifier_name |
usergroups_users.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | <R>(
client: &R,
token: &str,
request: &UpdateRequest<'_>,
) -> Result<UpdateResponse, UpdateError<R::Error>>
where
R: SlackWebRequestSender,
{
let params = vec![
Some(("token", token)),
Some(("usergroup", request.usergroup)),
Some(("users", request.users)),
request
... | update | identifier_name |
usergroups_users.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | Some(("token", token)),
Some(("usergroup", request.usergroup)),
Some(("users", request.users)),
request
.include_count
.map(|include_count| ("include_count", if include_count { "1" } else { "0" })),
];
let params = params.into_iter().filter_map(|x| x).coll... | where
R: SlackWebRequestSender,
{
let params = vec![ | random_line_split |
usergroups_users.rs | //=============================================================================
//
// WARNING: This file is AUTO-GENERATED
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/s... | {
let params = vec![
Some(("token", token)),
Some(("usergroup", request.usergroup)),
Some(("users", request.users)),
request
.include_count
.map(|include_count| ("include_count", if include_count { "1" } else { "0" })),
];
let params = params.into_iter... | identifier_body | |
nonnanfloat.rs | use std::cmp;
use num_traits::Float;
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct NonNaNFloat<F: Float>(F);
impl<F: Float> NonNaNFloat<F> {
pub fn new(v: F) -> Option<Self> {
if v.is_nan() {
Some(NonNaNFloat(v))
} else {
None
}
}
pub fn ... | () {
let mut v = [NonNaNFloat(5.1), NonNaNFloat(1.3)];
v.sort();
assert_eq!(v, [NonNaNFloat(1.3), NonNaNFloat(5.1)]);
}
}
| test_nonnanfloat | identifier_name |
nonnanfloat.rs | use std::cmp;
use num_traits::Float;
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct NonNaNFloat<F: Float>(F);
impl<F: Float> NonNaNFloat<F> {
pub fn new(v: F) -> Option<Self> {
if v.is_nan() {
Some(NonNaNFloat(v))
} else {
None
}
}
pub fn ... |
}
impl<F: Float> Eq for NonNaNFloat<F> {}
impl<F: Float> Ord for NonNaNFloat<F> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.partial_cmp(other).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_nonnanfloat() {
let mut v = [NonNaNFloat(5.1), NonNaNFlo... | {
let &NonNaNFloat(v) = self;
v
} | identifier_body |
nonnanfloat.rs | use std::cmp;
use num_traits::Float;
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct NonNaNFloat<F: Float>(F);
impl<F: Float> NonNaNFloat<F> {
pub fn new(v: F) -> Option<Self> {
if v.is_nan() | else {
None
}
}
pub fn unwrap(&self) -> F {
let &NonNaNFloat(v) = self;
v
}
}
impl<F: Float> Eq for NonNaNFloat<F> {}
impl<F: Float> Ord for NonNaNFloat<F> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.partial_cmp(other).unwrap()
}
}
#[cfg(t... | {
Some(NonNaNFloat(v))
} | conditional_block |
nonnanfloat.rs | use std::cmp;
use num_traits::Float;
#[derive(PartialOrd, PartialEq, Debug, Copy, Clone)]
pub struct NonNaNFloat<F: Float>(F);
impl<F: Float> NonNaNFloat<F> {
pub fn new(v: F) -> Option<Self> {
if v.is_nan() {
Some(NonNaNFloat(v)) |
pub fn unwrap(&self) -> F {
let &NonNaNFloat(v) = self;
v
}
}
impl<F: Float> Eq for NonNaNFloat<F> {}
impl<F: Float> Ord for NonNaNFloat<F> {
fn cmp(&self, other: &Self) -> cmp::Ordering {
self.partial_cmp(other).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
... | } else {
None
}
} | random_line_split |
apt.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::{self, Child};
use error_chain::ChainedError;
use errors::*;
use f... |
fn uninstall(&self, host: &Local, name: &str) -> FutureResult<Child, Error> {
let cmd = match command::factory() {
Ok(c) => c,
Err(e) => return future::err(format!("{}", e.display_chain()).into()),
};
cmd.exec(host, &["apt-get", "-y", "remove", name])
}
}
| {
let cmd = match command::factory() {
Ok(c) => c,
Err(e) => return future::err(format!("{}", e.display_chain()).into()),
};
cmd.exec(host, &["apt-get", "-y", "install", name])
} | identifier_body |
apt.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
| use futures::future::FutureResult;
use host::Host;
use host::local::Local;
use regex::Regex;
use std::process;
use super::PackageProvider;
use tokio_process::CommandExt;
pub struct Apt;
impl PackageProvider for Apt {
fn available() -> Result<bool> {
Ok(process::Command::new("/usr/bin/type")
.a... | use command::{self, Child};
use error_chain::ChainedError;
use errors::*;
use futures::{future, Future}; | random_line_split |
apt.rs | // Copyright 2015-2017 Intecture Developers.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.
use command::{self, Child};
use error_chain::ChainedError;
use errors::*;
use f... | ;
impl PackageProvider for Apt {
fn available() -> Result<bool> {
Ok(process::Command::new("/usr/bin/type")
.arg("apt-get")
.status()
.chain_err(|| "Could not determine provider availability")?
.success())
}
fn installed(&self, host: &Local, name: &s... | Apt | identifier_name |
boards.js | /* ========================================================================
* ZUI: boards.js
* http://zui.sexy
* ========================================================================
* Copyright (c) 2014 cnezsoft.com; Licensed MIT
* ======================================================================== */
(... | {
$('[data-toggle="boards"]').boards();
});
}(jQuery)); | $.fn.boards.Constructor = Boards;
$(function() | random_line_split |
boards.js | /* ========================================================================
* ZUI: boards.js
* http://zui.sexy
* ========================================================================
* Copyright (c) 2014 cnezsoft.com; Licensed MIT
* ======================================================================== */
(... | drop: function(e)
{
if (e.isNew)
{
var DROP = 'drop';
var result;
if (setting.hasOwnProperty(DROP) && $.isFunction(setting[DROP]))
{
result = setting[DROP](e);
... | var board = e.target.closest('.board').addClass('drop-in');
var shadow = board.find('.board-item-shadow');
var target = e.target;
$boards.addClass('drop-in').find('.board.drop-in').not(board).removeClass('drop-in');
shadow.insertBefore(... | conditional_block |
server.js | var
HTTP = require('http');
function testDuplicateRoutesError(test) {
var router = new HTTP_Router_Server();
router.get('/pokemon/:id/abilities', function handler() { });
try {
router.get('/pokemon/:whatever/abilities', function handler() { });
test.ok(false, 'This should have thrown an error');
test.done(... | test.ok(false, 'We should not be here');
response.send({ });
test.done();
});
Querier.get('/api/bar/123', { }, function finisher() { });
router.get('/baz/specific', function handler(request, response) {
test.equals(request.url, '/baz/specific');
response.send({ });
incrementCompleteCount();
});
rout... | random_line_split | |
server.js | var
HTTP = require('http');
function testDuplicateRoutesError(test) {
var router = new HTTP_Router_Server();
router.get('/pokemon/:id/abilities', function handler() { });
try {
router.get('/pokemon/:whatever/abilities', function handler() { });
test.ok(false, 'This should have thrown an error');
test.done(... | () {
complete_count++;
if (complete_count === expected) {
server.close();
test.done();
}
}
router.get('/foo/:id', function handler(... response) {
test.ok(false, 'We should not be here');
response.send({ });
test.done();
});
router.get('/foo/specific', function handler(request, response) {
t... | incrementCompleteCount | identifier_name |
server.js | var
HTTP = require('http');
function testDuplicateRoutesError(test) {
var router = new HTTP_Router_Server();
router.get('/pokemon/:id/abilities', function handler() { });
try {
router.get('/pokemon/:whatever/abilities', function handler() { });
test.ok(false, 'This should have thrown an error');
test.done(... |
function serve(test) {
// The router should trigger a response error
// if an invalid HTTP method was specified:
WithInvalidHTTPMethod: {
let mock_headers = { };
let mock_native_request = {
headers: mock_headers,
url: '/',
method: 'nonexistent_method'
};
let mock_request = (new HTTP_Reques... | {
var
router = new HTTP_Router_Server(),
server = HTTP.createServer(router.serve);
server.listen(Network_Mapper.createAPIMapping().http_port);
var
complete_count = 0,
expected = 4;
function incrementCompleteCount() {
complete_count++;
if (complete_count === expected) {
server.close();
... | identifier_body |
server.js | var
HTTP = require('http');
function testDuplicateRoutesError(test) {
var router = new HTTP_Router_Server();
router.get('/pokemon/:id/abilities', function handler() { });
try {
router.get('/pokemon/:whatever/abilities', function handler() { });
test.ok(false, 'This should have thrown an error');
test.done(... |
}
router.get('/foo/:id', function handler(... response) {
test.ok(false, 'We should not be here');
response.send({ });
test.done();
});
router.get('/foo/specific', function handler(request, response) {
test.equals(request.url, '/foo/specific');
response.send({ });
incrementCompleteCount();
});
Que... | {
server.close();
test.done();
} | conditional_block |
game.js | /*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* 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 condi... |
Misc.applyUrlSettings(globals);
g_services.globals = globals;
var server;
if (globals.haveServer) {
server = new GameServer();
g_services.server = server;
server.addEventListener('playerconnect', g_playerManager.startPlayer.bind(g_playerManager));
}
GameSupport.init(server, globals);
var ... | {
return new Player(g_services, netPlayer);
} | identifier_body |
game.js | /*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* 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 condi... |
};
Player.prototype.setTracks = function(data) {
this.tracks = data.tracks;
};
Player.prototype.setNote = function(data) {
if (this.tracks) {
var track = this.tracks[data.t];
if (track) {
track.rhythm[data.r] = data.n;
}
}
};
Player.prototype.handleNameMsg = function(msg) {
if (!msg.name) ... | {
this.elem.style.backgroundColor = this.color;
} | conditional_block |
game.js | /*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* 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 condi... | g_services.playerManager = g_playerManager;
g_services.cssParse = CSSParse;
g_services.misc = Misc;
var stop = false;
// You can set these from the URL with
// http://path/gameview.html?settings={name:value,name:value}
var globals = {
haveServer: true,
bpm: 120,
loopLength: 16,
force2d: f... | var g_services = {};
var g_playerManager = new PlayerManager(g_services); | random_line_split |
game.js | /*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* 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 condi... | () {
var currentTime = clock.getTime();
var currentQuarterBeat = Math.floor(currentTime / secondsPerQuarterBeat);
if (globals.debug) {
var beat = Math.floor(currentQuarterBeat / 4) % 4;
GameSupport.setStatus(
"\n ct: " + currentTime.toFixed(2).substr(-5) +
"\ncqb: " + curren... | process | identifier_name |
sendFeedbackMutation.test.ts | /* eslint-disable promise/always-return */
import { runAuthenticatedQuery } from "schema/v2/test/utils"
describe("Send Feedback", () => {
const feedback = {
id: "id",
message: "Catty message",
}
const query = `
mutation {
sendFeedback(input: {message: "Catty message"}) {
feedbackOrError {
... | })
}) | random_line_split | |
cargo_expand.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::env;
use std::error;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::Command;
use std::... | (&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::Io(ref err) => Some(err),
Error::Utf8(ref err) => Some(err),
Error::Compile(..) => None,
}
}
}
/// Use rustc to expand and pretty print the crate into a single file,
/// removing any macros in... | source | identifier_name |
cargo_expand.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::env;
use std::error;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::Command;
use std::... | cmd.arg("-Z");
cmd.arg("unstable-options");
cmd.arg("--pretty=expanded");
let output = cmd.output()?;
let src = from_utf8(&output.stdout)?.to_owned();
let error = from_utf8(&output.stderr)?.to_owned();
if src.len() == 0 {
Err(Error::Compile(error))
} else {
Ok(src)
... | cmd.arg("--"); | random_line_split |
cargo_expand.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::env;
use std::error;
use std::fmt;
use std::io;
use std::path::Path;
use std::process::Command;
use std::... |
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::Io(ref err) => Some(err),
Error::Utf8(ref err) => Some(err),
Error::Compile(..) => None,
}
}
}
/// Use rustc to expand and pretty print the crate... | {
match self {
Error::Io(ref err) => err.fmt(f),
Error::Utf8(ref err) => err.fmt(f),
Error::Compile(ref err) => write!(f, "{}", err),
}
} | identifier_body |
ProgressBar.js | import {style} from './ProgressBar.scss';
import React from 'react';
//
// Component
// -----------------------------------------------------------------------------
class ProgressBarView extends React.Component {
constructor(props) {
super(props);
}
static defaultProps = {
progress: 0,
showText: f... | <div className={style}>
<div className='progress'>
<div className='progress-bar' role='progressbar' aria-valuenow={rounded}
aria-valuemax='100' style={{width: `${rounded}%`}}>
{showText ? `${rounded}%` : null}
</div>
</div>
</div>
);
}
}
... | return ( | random_line_split |
ProgressBar.js | import {style} from './ProgressBar.scss';
import React from 'react';
//
// Component
// -----------------------------------------------------------------------------
class ProgressBarView extends React.Component {
constructor(props) {
super(props);
}
static defaultProps = {
progress: 0,
showText: f... | () {
const {progress, showText} = this.props;
const rounded = Math.round(progress);
return (
<div className={style}>
<div className='progress'>
<div className='progress-bar' role='progressbar' aria-valuenow={rounded}
aria-valuemax='100' style={{width: `${rounded}%`}}>
... | render | identifier_name |
type_of.rs | // Copyright 2012-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-MI... |
// Want refinements! (Or case classes, I guess
pub enum named_ty { a_struct, an_enum }
pub fn llvm_type_name(cx: &CrateContext,
what: named_ty,
did: ast::def_id,
tps: &[ty::t]) -> ~str {
let name = match what {
a_struct => { "struct" }
... | _ => ()
}
return llty;
} | random_line_split |
type_of.rs | // Copyright 2012-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-MI... | (cx: &CrateContext,
what: named_ty,
did: ast::def_id,
tps: &[ty::t]) -> ~str {
let name = match what {
a_struct => { "struct" }
an_enum => { "enum" }
};
let tstr = ppaux::parameterized(cx.tcx, ty::item_path_str(cx.tcx, did), N... | llvm_type_name | identifier_name |
currency_getter.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009 CamptoCamp. All rights reserved.
# @author Nicolas Bessi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publi... | raise UnknowClassError | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.