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 |
|---|---|---|---|---|
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize {
self.n
}
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait Even... | -> bool {
false
}
fn main() {
need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_t... | ed_to_use_this_value() | identifier_name |
fixes.py | #!/usr/bin/env python
import sys
def fix_terminator(tokens):
if not tokens:
return
last = tokens[-1]
if last not in ('.', '?', '!') and last.endswith('.'):
tokens[-1] = last[:-1]
tokens.append('.')
def balance_quotes(tokens):
|
def output(tokens):
if not tokens:
return
# fix_terminator(tokens)
balance_quotes(tokens)
print ' '.join(tokens)
prev = None
for line in sys.stdin:
tokens = line.split()
if len(tokens) == 1 and tokens[0] in ('"', "'", ')', ']'):
prev.append(tokens[0])
else:
output(prev)
prev = tokens
o... | count = tokens.count("'")
if not count:
return
processed = 0
for i, token in enumerate(tokens):
if token == "'":
if processed % 2 == 0 and (i == 0 or processed != count - 1):
tokens[i] = "`"
processed += 1 | identifier_body |
fixes.py | #!/usr/bin/env python
import sys
| tokens[-1] = last[:-1]
tokens.append('.')
def balance_quotes(tokens):
count = tokens.count("'")
if not count:
return
processed = 0
for i, token in enumerate(tokens):
if token == "'":
if processed % 2 == 0 and (i == 0 or processed != count - 1):
tokens[i] = "`"
processed += 1... | def fix_terminator(tokens):
if not tokens:
return
last = tokens[-1]
if last not in ('.', '?', '!') and last.endswith('.'): | random_line_split |
fixes.py | #!/usr/bin/env python
import sys
def fix_terminator(tokens):
if not tokens:
return
last = tokens[-1]
if last not in ('.', '?', '!') and last.endswith('.'):
tokens[-1] = last[:-1]
tokens.append('.')
def balance_quotes(tokens):
count = tokens.count("'")
if not count:
return
processed = 0
... |
output(prev)
| output(prev)
prev = tokens | conditional_block |
fixes.py | #!/usr/bin/env python
import sys
def fix_terminator(tokens):
if not tokens:
return
last = tokens[-1]
if last not in ('.', '?', '!') and last.endswith('.'):
tokens[-1] = last[:-1]
tokens.append('.')
def | (tokens):
count = tokens.count("'")
if not count:
return
processed = 0
for i, token in enumerate(tokens):
if token == "'":
if processed % 2 == 0 and (i == 0 or processed != count - 1):
tokens[i] = "`"
processed += 1
def output(tokens):
if not tokens:
return
# fix_terminator(... | balance_quotes | identifier_name |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
| fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1... | fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
| random_line_split |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool |
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
r... | {
self.width > other.width && self.height > other.height
} | identifier_body |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn | (&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
... | can_hold | identifier_name |
unit.tests.js | (function () {
window._paddingsTest = function () {
var test = function (padding) {
for (var len = 0; len <= 32; len++) {
var initialArray = random.default.getUint8Array(len);
var padded = padding.pad(initialArray, 16, random.default);
var padCount = padding.unpad(padded);
if (padCount == -1) {
... | var test = function (bytes, hex) {
return bh.byteArrayToHex(hashAlgorithms.md5.computeHash(bytes)) == hex;
};
var result = true;
result &= test([], 'd41d8cd98f00b204e9800998ecf8427e');
result &= test([255], '00594fd4f42ba43fc1ca0427a0576295');
result &= test(a40, '332f73d56f380cea8ab0d51e855bac41');
... | console.log(result ? 'Passed' : 'Failed');
};
window._md5Test = function () { | random_line_split |
jstree-tests.ts |
// gets version of lib
var version: string = $.jstree.version;
// create new instance
var instance1: JSTree = $('div').jstree();
$('div').jstree('open_node', '#branch');
// get existing reference
var existingReference: JSTree = $.jstree.reference('sds');
// advanced tree creation
var advancedTree = $("#briefcase... |
var coreThemes: JSTreeStaticDefaultsCoreThemes = {
ellipsis:true
};
// tree with new theme elipsis
var treeWithNewCoreProperties = $('#treeWithNewEllipsisProperties').jstree({
core: {
themes: coreThemes
}
}); | tree.get_path('nodeId', '/', true);
| random_line_split |
menu.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Overlay, ScrollStrategy} from '@angular/cdk/overlay';
import {
ChangeDetectionStrategy,
Component,
Elem... | (_depth: number) {
// TODO(crisbeto): MDC's styles come with elevation already and we haven't mapped our mixins
// to theirs. Disable the elevation stacking for now until everything has been mapped.
// The following unit tests should be re-enabled:
// - should not remove mat-elevation class from overlay... | setElevation | identifier_name |
menu.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Overlay, ScrollStrategy} from '@angular/cdk/overlay';
import {
ChangeDetectionStrategy,
Component,
Elem... | exportAs: 'matMenu',
animations: [
matMenuAnimations.transformMenu,
matMenuAnimations.fadeInItems
],
providers: [
{provide: MAT_MENU_PANEL, useExisting: MatMenu},
{provide: BaseMatMenu, useExisting: MatMenu},
]
})
export class MatMenu extends BaseMatMenu {
constructor(_elementRef: ElementRe... | templateUrl: 'menu.html',
styleUrls: ['menu.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None, | random_line_split |
menu.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Overlay, ScrollStrategy} from '@angular/cdk/overlay';
import {
ChangeDetectionStrategy,
Component,
Elem... |
setElevation(_depth: number) {
// TODO(crisbeto): MDC's styles come with elevation already and we haven't mapped our mixins
// to theirs. Disable the elevation stacking for now until everything has been mapped.
// The following unit tests should be re-enabled:
// - should not remove mat-elevation cl... | {
super(_elementRef, _ngZone, _defaultOptions);
} | identifier_body |
unassignedbugs.py | #!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('dat... |
# Archlinux
url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
# Com... | f = o.open(login_page, p)
data = f.read() | random_line_split |
unassignedbugs.py | #!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('dat... |
msg += '\n\nArchlinux: \n\n'
msg += parse_bugtrackerpage(url)
msg += '\n\nCommunity: \n\n'
msg += parse_bugtrackerpage(url2)
msg = msg.encode("utf8")
# send mail
server = smtplib.SMTP(smtpserver)
server.sendmail(fromaddr, toaddr,msg)
server.quit()
| print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
page = False
else:
... | identifier_body |
unassignedbugs.py | #!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('dat... |
print count
# print all found bugs
for f in data:
title = f.a['title'].replace('Assigned |','')
title = f.a['title'].replace('| 0%','')
msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title)
if pages == True:
new = "%s&pagenum=%s" ... | print soup.findAll('a',{'id': 'next'})
count += 1
pages = True | conditional_block |
unassignedbugs.py | #!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('dat... | (url,count=1):
print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
page = Fa... | parse_bugtrackerpage | identifier_name |
lib.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | //! ```
//! # use datafusion::prelude::*;
//! # use datafusion::error::Result;
//! # use arrow::record_batch::RecordBatch;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let mut ctx = ExecutionContext::new();
//!
//! ctx.register_csv("example", "tests/example.csv", CsvReadOptions::new())?;
//!
//! /... | //! and how to execute a query against a CSV using SQL:
//! | random_line_split |
DatabaseService.ts | import { Client, QueryResult } from 'pg';
export interface IDatabaseRow {
[columnName: string]: any;
}
class DatabaseService {
private readonly client: Client;
private connected: boolean = false;
constructor() {
this.client = new Client({
user: process.env.DATABASE_USERNAME,
... | else {
return false;
}
}
public isUniqueViolationOnConstraint(constraint: string): boolean {
if (this.type === ErrorType.UniqueViolation && this.constraint === constraint) {
return true;
} else {
return false;
}
}
}
| {
return true;
} | conditional_block |
DatabaseService.ts | import { Client, QueryResult } from 'pg';
export interface IDatabaseRow {
[columnName: string]: any;
}
class DatabaseService {
private readonly client: Client;
private connected: boolean = false;
constructor() {
this.client = new Client({
user: process.env.DATABASE_USERNAME,
... |
public isUniqueViolationOnConstraint(constraint: string): boolean {
if (this.type === ErrorType.UniqueViolation && this.constraint === constraint) {
return true;
} else {
return false;
}
}
}
| {
if (this.type === ErrorType.NotNullViolation
&& this.table === table && this.column === column) {
return true;
} else {
return false;
}
} | identifier_body |
DatabaseService.ts | import { Client, QueryResult } from 'pg';
export interface IDatabaseRow {
[columnName: string]: any;
}
class DatabaseService {
private readonly client: Client;
private connected: boolean = false;
constructor() {
this.client = new Client({
user: process.env.DATABASE_USERNAME,
... | (message: string, postgresError: any) {
super(message);
switch (postgresError.code) {
case '23502':
this.type = ErrorType.NotNullViolation;
break;
case '23505':
this.type = ErrorType.UniqueViolation;
break;
... | constructor | identifier_name |
DatabaseService.ts | import { Client, QueryResult } from 'pg';
export interface IDatabaseRow {
[columnName: string]: any;
}
class DatabaseService {
private readonly client: Client;
private connected: boolean = false;
constructor() {
this.client = new Client({
user: process.env.DATABASE_USERNAME,
... | }
public async bulkInsert(tableName: string, columnNames: string[], rows: any[][]): Promise<IDatabaseRow[]> {
const rowsPerInsert = 1000;
const query = `insert into ${tableName} (${columnNames.join()}) values`;
let allReturnedRows: any[] = [];
for (let i = 0; i < rows.length; i ... | random_line_split | |
express.ts | import grant from 'grant';
import session from 'express-session';
import { Request, Response, NextFunction } from 'express';
import { createDebug } from '@feathersjs/commons';
import { Application } from '@feathersjs/feathers';
import { AuthenticationResult } from '@feathersjs/authentication';
import {
Application as... | debug('Successful oAuth authentication, sending response');
await sendResponse(authResult);
} catch (error: any) {
debug('Received oAuth authentication error', error.stack);
await sendResponse(error);
}
});
authApp.use(grantApp);
app.set('grant', grantApp.confi... | random_line_split | |
express.ts | import grant from 'grant';
import session from 'express-session';
import { Request, Response, NextFunction } from 'express';
import { createDebug } from '@feathersjs/commons';
import { Application } from '@feathersjs/feathers';
import { AuthenticationResult } from '@feathersjs/authentication';
import {
Application as... | else {
res.json(data);
}
} catch (error: any) {
debug('oAuth error', error);
next(error);
}
};
try {
const payload = config.defaults.transport === 'session' ?
grant.response : req.query;
const authentication = {
... | {
throw data;
} | conditional_block |
tracebackcompat.py | import functools
import sys
import traceback
from stacked import Stacked
from .xtraceback import XTraceback
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equival... |
options["stream"] = file
return self._factory(etype, value, tb, limit, **options)
@functools.wraps(traceback.format_tb)
def format_tb(self, tb, limit=None, **options):
xtb = self._factory(None, None, tb, limit, **options)
return xtb.format_tb()
@functools.wraps(traceback.f... | file = sys.stderr | conditional_block |
tracebackcompat.py | import functools
import sys
import traceback
from stacked import Stacked
from .xtraceback import XTraceback
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equival... |
@functools.wraps(traceback.format_exception)
def format_exception(self, etype, value, tb, limit=None, **options):
xtb = self._factory(etype, value, tb, limit, **options)
return xtb.format_exception()
@functools.wraps(traceback.format_exc)
def format_exc(self, limit=None, **options):
... | xtb = self._factory(etype, value, None, **options)
return xtb.format_exception_only() | identifier_body |
tracebackcompat.py | import functools
import sys
import traceback
from stacked import Stacked
from .xtraceback import XTraceback
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equival... | @functools.wraps(traceback.format_exception_only)
def format_exception_only(self, etype, value, **options):
xtb = self._factory(etype, value, None, **options)
return xtb.format_exception_only()
@functools.wraps(traceback.format_exception)
def format_exception(self, etype, value, tb, lim... | return xtb.format_tb()
| random_line_split |
tracebackcompat.py | import functools
import sys
import traceback
from stacked import Stacked
from .xtraceback import XTraceback
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equival... | (self, tb, limit=None, file=None, **options):
xtb = self._print_factory(None, None, tb, limit, file, **options)
xtb.print_tb()
@functools.wraps(traceback.print_exception)
def print_exception(self, etype, value, tb, limit=None, file=None,
**options):
xtb = self._p... | print_tb | identifier_name |
media_queries.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/. */
//! Servo's media-query device and expression representation.
use app_units::Au;
use context::QuirksMode;
use css... | /// The kind of expression we're, just for unit testing.
///
/// Eventually this will become servo-only.
pub fn kind_for_testing(&self) -> &ExpressionKind {
&self.0
}
/// Parse a media expression of the form:
///
/// ```
/// (media-feature: media-value)
/// ```
///
... | random_line_split | |
media_queries.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/. */
//! Servo's media-query device and expression representation.
use app_units::Au;
use context::QuirksMode;
use css... | {
/// <http://dev.w3.org/csswg/mediaqueries-3/#width>
Width(Range<specified::Length>),
}
/// A single expression a per:
///
/// <http://dev.w3.org/csswg/mediaqueries-3/#media1>
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct Expression(pub ExpressionKind);
i... | ExpressionKind | identifier_name |
stats_tipster.py | import sys, os, inspect
from PyQt5.QtWidgets import QWidget, QTreeWidgetItem
from PyQt5 import uic
directory = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
sys.path.append(directory + "/lib")
from libstats import LibStats
from func_aux import paint_row, key_from_value
fro... |
def getMonths(self, year):
sMonths =[]
for i in self.years[year]:
sMonths.append(self.months[i])
return sMonths
| year = self.cmbYear.currentText()
sMonth = self.cmbMonth.currentText()
month = key_from_value(self.months, sMonth)
data = LibStats.getTipster(year, month)
self.treeMonth.clear()
items = []
for i in data:
item = QTreeWidgetItem(i)
item = paint_row... | identifier_body |
stats_tipster.py | import sys, os, inspect
from PyQt5.QtWidgets import QWidget, QTreeWidgetItem
from PyQt5 import uic
directory = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
sys.path.append(directory + "/lib")
from libstats import LibStats
from func_aux import paint_row, key_from_value
fro... | sMonths.append(self.months[i])
return sMonths |
def getMonths(self, year):
sMonths =[]
for i in self.years[year]: | random_line_split |
stats_tipster.py | import sys, os, inspect
from PyQt5.QtWidgets import QWidget, QTreeWidgetItem
from PyQt5 import uic
directory = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
sys.path.append(directory + "/lib")
from libstats import LibStats
from func_aux import paint_row, key_from_value
fro... | (self):
self.years, self.months = LibStats.getYears()
self.cmbYear.addItems(self.years.keys())
firstKey = next(iter(self.years))
self.cmbMonth.addItems(self.getMonths(firstKey))
data = LibStats.getTipster()
items = []
for i in data:
item = QTreeWidg... | initData | identifier_name |
stats_tipster.py | import sys, os, inspect
from PyQt5.QtWidgets import QWidget, QTreeWidgetItem
from PyQt5 import uic
directory = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
sys.path.append(directory + "/lib")
from libstats import LibStats
from func_aux import paint_row, key_from_value
fro... |
self.treeTotal.addTopLevelItems(items)
self.updateMonths()
def updateMonths(self):
year = self.cmbYear.currentText()
self.cmbMonth.clear()
self.cmbMonth.addItems(self.getMonths(year))
self.updateTree()
def updateTree(self):
year = self.cmbYear.current... | item = QTreeWidgetItem(i)
item = paint_row(item, i[5])
items.append(item) | conditional_block |
Font.js | lychee.define('Font').exports(function(lychee) {
var Class = function(spriteOrImages, settings) {
this.settings = lychee.extend({}, this.defaults, settings);
if (this.settings.kerning > this.settings.spacing) {
this.settings.kerning = this.settings.spacing;
}
this.__cache = {};
this.__images = null;
... |
}
},
__initSpriteXY: function() {
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var frame = this.settings.map[c];
var chr = {
id: this.settings.charset[c],
width: frame.width + this.settings.spacing * 2,
height: frame.height,
real: frame.width,
x: frame... | random_line_split | |
mainThreadTunnelService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
this._register(this.configurationService.onDidChangeConfiguration(async (e) => {
if (e.affectsConfiguration(PORT_AUTO_FORWARD_SETTING) || e.affectsConfiguration(PORT_AUTO_SOURCE_SETTING)) {
return this._proxy.$registerCandidateFinder(this.processFindingEnabled());
}
}));
this._register(this.tunnelSe... | random_line_split | |
mainThreadTunnelService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
async $onFoundNewCandidates(candidates: CandidatePort[]): Promise<void> {
this.remoteExplorerService.onFoundNewCandidates(candidates);
}
async $setTunnelProvider(features?: TunnelProviderFeatures): Promise<void> {
const tunnelProvider: ITunnelProvider = {
forwardPort: (tunnelOptions: TunnelOptions, tunnelC... | {
return (await this.tunnelService.tunnels).map(tunnel => {
return {
remoteAddress: { port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost },
localAddress: tunnel.localAddress,
privacy: tunnel.privacy,
protocol: tunnel.protocol
};
});
} | identifier_body |
mainThreadTunnelService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (providerHandle: number): Promise<void> {
this.portsAttributesProviders.delete(providerHandle);
}
async providePortAttributes(ports: number[], pid: number | undefined, commandLine: string | undefined, token: CancellationToken): Promise<ProvidedPortAttributes[]> {
if (this.portsAttributesProviders.size === 0) {
... | $unregisterPortsAttributesProvider | identifier_name |
mainThreadTunnelService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | else {
this._register(this.remoteExplorerService.onEnabledPortsFeatures(() => this._proxy.$registerCandidateFinder(this.configurationService.getValue(PORT_AUTO_FORWARD_SETTING))));
}
this._register(this.configurationService.onDidChangeConfiguration(async (e) => {
if (e.affectsConfiguration(PORT_AUTO_FORWARD_... | {
this._proxy.$registerCandidateFinder(this.processFindingEnabled());
} | conditional_block |
pl.js | /* | copy: 'Kopiuj',
copyError: 'Ustawienia bezpieczeństwa Twojej przeglądarki nie pozwalają na automatyczne kopiowanie tekstu. Użyj skrótu klawiszowego Ctrl/Cmd+C.',
cut: 'Wytnij',
cutError: 'Ustawienia bezpieczeństwa Twojej przeglądarki nie pozwalają na automatyczne wycinanie tekstu. Użyj skrótu klawiszowego Ctrl/Cmd+... | Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'clipboard', 'pl', { | random_line_split |
schema.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import {
GraphQ... | else {
return null;
}
}
);
var gameType = new GraphQLObjectType({
name: 'Game',
description: 'A treasure search game',
fields: () => ({
id: globalIdField('Game'),
hidingSpots: {
type: hidingSpotConnection,
description: 'Places where treasure might be hidden',
args: connecti... | {
return hidingSpotType;
} | conditional_block |
schema.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import {
GraphQ... | name: 'CheckHidingSpotForTreasure',
inputFields: {
id: { type: new GraphQLNonNull(GraphQLID) },
},
outputFields: {
hidingSpot: {
type: hidingSpotType,
resolve: ({localHidingSpotId}) => getHidingSpot(localHidingSpotId),
},
game: {
type: gameType,
resolve: () => getGame(),
... | random_line_split | |
tests.py | """
* Copyright (c) 2017 SUSE LLC
*
* openATTIC is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY W... |
@mock.patch('ceph_nfs.models.GaneshaExport.objects.filter')
def test_bucket_delete(self, filter_mock):
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
filter_mock.return_value = [4, 8, 15, 16, 23, 42]
response = self.clie... | make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
Settings_mock.RGW_API_USER_ID = 'admin'
response = self.client.delete('/api/ceph_radosgw/user/delete?uid=admin')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
... | identifier_body |
tests.py | """
* Copyright (c) 2017 SUSE LLC
*
* openATTIC is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY W... | 'bucket': 'my_data'
}))
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
filter_mock.return_value = [0, 8, 15]
response = self.client.get('/api/ceph_radosgw/bucket/get?bucket=test01')
content = json.load... | 'owner': 'floyd', | random_line_split |
tests.py | """
* Copyright (c) 2017 SUSE LLC
*
* openATTIC is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY W... | (self, Settings_mock):
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
Settings_mock.RGW_API_USER_ID = 'admin'
response = self.client.delete('/api/ceph_radosgw/user/delete?uid=admin')
self.assertEqual(response.status_code, ... | test_user_delete | identifier_name |
inMemoryRowModel.d.ts | // Type definitions for ag-grid v4.1.5
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ceolter/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
import { RowNode } from "../../entities/rowNode";
import { IInMemoryRowModel } from "../../interfaces/iInMemoryRowModel"... | implements IInMemoryRowModel {
private gridOptionsWrapper;
private columnController;
private filterManager;
private $scope;
private selectionController;
private eventService;
private context;
private filterStage;
private sortStage;
private flattenStage;
private groupStage;
... | InMemoryRowModel | identifier_name |
inMemoryRowModel.d.ts | // Type definitions for ag-grid v4.1.5
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ceolter/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
import { RowNode } from "../../entities/rowNode";
import { IInMemoryRowModel } from "../../interfaces/iInMemoryRowModel"... | getRowIndexAtPixel(pixelToMatch: number): number;
private isRowInPixel(rowNode, pixelToMatch);
getRowCombinedHeight(): number;
forEachNode(callback: Function): void;
forEachNodeAfterFilter(callback: Function): void;
forEachNodeAfterFilterAndSort(callback: Function): void;
private recursively... | getRow(index: number): RowNode;
getVirtualRowCount(): number;
getRowCount(): number; | random_line_split |
remove.ts | /*
Remove an item from the given user's shopping cart.
*/
import { isValidUUID } from "@cocalc/util/misc";
import getPool from "@cocalc/database/pool";
// we include the account_id to ensure here and in the query below
// to ensure there is an error if user A tries to delete an item
// from user B's shopping cart.
/... | (
account_id: string,
id: number
): Promise<number> {
if (!isValidUUID(account_id)) {
throw Error("account_id is invalid");
}
const pool = getPool();
const { rowCount } = await pool.query(
"UPDATE shopping_cart_items SET removed=NOW() WHERE account_id=$1 AND id=$2 AND removed IS NULL AND purchased I... | removeFromCart | identifier_name |
remove.ts | /*
Remove an item from the given user's shopping cart.
*/
import { isValidUUID } from "@cocalc/util/misc";
import getPool from "@cocalc/database/pool";
// we include the account_id to ensure here and in the query below
// to ensure there is an error if user A tries to delete an item
// from user B's shopping cart.
/... |
const pool = getPool();
const { rowCount } = await pool.query(
"UPDATE shopping_cart_items SET removed=NOW() WHERE account_id=$1 AND id=$2 AND removed IS NULL AND purchased IS NULL",
[account_id, id]
);
return rowCount;
}
| {
throw Error("account_id is invalid");
} | conditional_block |
remove.ts | /*
Remove an item from the given user's shopping cart.
*/
import { isValidUUID } from "@cocalc/util/misc";
import getPool from "@cocalc/database/pool";
// we include the account_id to ensure here and in the query below
// to ensure there is an error if user A tries to delete an item
// from user B's shopping cart.
/... | {
if (!isValidUUID(account_id)) {
throw Error("account_id is invalid");
}
const pool = getPool();
const { rowCount } = await pool.query(
"UPDATE shopping_cart_items SET removed=NOW() WHERE account_id=$1 AND id=$2 AND removed IS NULL AND purchased IS NULL",
[account_id, id]
);
return rowCount;
} | identifier_body | |
remove.ts | /*
Remove an item from the given user's shopping cart.
*/
import { isValidUUID } from "@cocalc/util/misc";
import getPool from "@cocalc/database/pool";
| // we include the account_id to ensure here and in the query below
// to ensure there is an error if user A tries to delete an item
// from user B's shopping cart.
// Returns number of items "removed", which on success is 0 or 1.
// 0 - item with that id wasn't in the cart
// 1 - item was changed.
// You can't rem... | random_line_split | |
test.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 ... |
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn next_test_ip6() -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function f... | {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
} | identifier_body |
test.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 ... | () -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.... | next_test_ip6 | identifier_name |
test.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 ... | else {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting... | {
env::temp_dir().join(string)
} | conditional_block |
test.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 ... | if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an i... | random_line_split | |
utils.py | import sys
import json
from datetime import timedelta, tzinfo
from io import BytesIO |
# Context manager for capturing stdout output. See
# https://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._bytesio = BytesIO()
return self
def __exi... | from yledl import execute_action, StreamFilters, IOContext, StreamAction, RD_SUCCESS
from yledl.io import random_elisa_ipv4
from yledl.http import HttpClient
from yledl.titleformatter import TitleFormatter | random_line_split |
utils.py | import sys
import json
from datetime import timedelta, tzinfo
from io import BytesIO
from yledl import execute_action, StreamFilters, IOContext, StreamAction, RD_SUCCESS
from yledl.io import random_elisa_ipv4
from yledl.http import HttpClient
from yledl.titleformatter import TitleFormatter
# Context manager for captu... |
def fetch_metadata(url, filters=StreamFilters(), meta_language=None):
return json.loads('\n'.join(
fetch(url, StreamAction.PRINT_METADATA, filters, meta_language)))
def fetch(url, action, filters, meta_language=None):
io = IOContext(destdir='/tmp/', metadata_language=meta_language,
... | return fetch(url, StreamAction.PRINT_EPISODE_PAGES, filters) | identifier_body |
utils.py | import sys
import json
from datetime import timedelta, tzinfo
from io import BytesIO
from yledl import execute_action, StreamFilters, IOContext, StreamAction, RD_SUCCESS
from yledl.io import random_elisa_ipv4
from yledl.http import HttpClient
from yledl.titleformatter import TitleFormatter
# Context manager for captu... | (url, action, filters, meta_language=None):
io = IOContext(destdir='/tmp/', metadata_language=meta_language,
x_forwarded_for=random_elisa_ipv4())
httpclient = HttpClient(io)
title_formatter = TitleFormatter()
with Capturing() as output:
res = execute_action(url,
... | fetch | identifier_name |
deriving-span-Zero-tuple-struct.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
| main | identifier_name |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
# Copyright (C) Zing contributors.
#
# This file is a part of the Zing project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship inf... | # This parser should ignore the --help flag, unless there is no subcommand
parser = ArgumentParser(add_help=False)
parser.add_argument("--version", action="version",
version=get_version())
# Print version and exit if --version present
args, remainder = parser.parse_known_arg... | runner_name = os.path.basename(sys.argv[0])
| random_line_split |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
# Copyright (C) Zing contributors.
#
# This file is a part of the Zing project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship inf... |
else:
resp = input("%sDo you wish to proceed? [Ny] " % redis_warning)
if resp not in ("y", "yes"):
print("RQ workers running, not proceeding.")
exit(2)
# Update settings to set queues to ASYNC = False.
for q in settings.RQ_QUEUES.itervalues():
... | print("Warning: %s" % redis_warning) | conditional_block |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
# Copyright (C) Zing contributors.
#
# This file is a part of the Zing project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship inf... |
def set_sync_mode(noinput=False):
"""Sets ASYNC = False on all redis worker queues
"""
from .core.utils.redis_rq import rq_workers_are_running
if rq_workers_are_running():
redis_warning = ("\nYou currently have RQ workers running.\n\n"
"Running in synchronous mode ma... | """Parse and run the `init` command
:param parser: `argparse.ArgumentParser` instance to use for parsing
:param settings_template: Template file for initializing settings from.
:param args: Arguments to call init command with.
"""
src_dir = os.path.abspath(os.path.dirname(__file__))
add_help_t... | identifier_body |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
# Copyright (C) Zing contributors.
#
# This file is a part of the Zing project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship inf... | (project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the user's configuration ... | configure_app | identifier_name |
angular-locale_haw-us.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"L\u0101pul... | return PLURAL_CATEGORY.OTHER;}
});
}]);
| { return PLURAL_CATEGORY.ONE; } | conditional_block |
angular-locale_haw-us.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"L\u0101pul... | "Now.",
"Kek."
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTi... | "Kep.",
"\u02bbOk.",
| random_line_split |
all.js | //= require jquery/jquery
//= require raphael
//= require_tree .
$(document).ready(function(){
function | (id,n,type,mod,size){
var top = $(id).position().top;
var height = $(id).height();
var width = $(id).width();
var center = width/2;
var R = 100;
var paper = Raphael(0, top, width, height);
xmod = 0;
for (i = 0; i < n; i++) {
var xmod = xmod + mod;
switch(type) {
case 1:
var... | arcs | identifier_name |
all.js | //= require jquery/jquery
//= require raphael
//= require_tree .
$(document).ready(function(){
function arcs(id,n,type,mod,size){
var top = $(id).position().top;
var height = $(id).height();
var width = $(id).width();
var center = width/2;
var R = 100;
var paper = Raphael(0, top, width, height);
xm... | break;
default:
var startx = center+xmod;
var starty = height+xmod;
break;
}
var path_string = ['m', startx, starty, 'a', elx, ely, 3, quad, dir, spin, angle];
var arcs = paper.path(path_string);
arcs.attr("stroke", "#4babe0");
arcs.toBack();
};... | var quad = 1; | random_line_split |
all.js | //= require jquery/jquery
//= require raphael
//= require_tree .
$(document).ready(function(){
function arcs(id,n,type,mod,size) | ;
// ElementID , number of arcs, arctype, offset, size
// TODO: ADD RESIZE EVENT
var a = arcs('#overview',5,1,15,1500);
var a = arcs('#overview',5,2,30,2500);
var a = arcs('#overview',5,3,15,2000);
var a = arcs('#overview',5,4,15,1000);
}); | {
var top = $(id).position().top;
var height = $(id).height();
var width = $(id).width();
var center = width/2;
var R = 100;
var paper = Raphael(0, top, width, height);
xmod = 0;
for (i = 0; i < n; i++) {
var xmod = xmod + mod;
switch(type) {
case 1:
var startx = center+xmo... | identifier_body |
pascal.py | """ Contains PascalVOC dataset and labels for different tasks """
import os
from os.path import dirname, basename
from io import BytesIO
import tarfile
import tempfile
from collections import defaultdict
import PIL
import tqdm
import numpy as np
import requests
from . import ImagesOpenset
class BasePascal(ImagesOp... |
train_ids = self._extract_ids(archive, 'train')
test_ids = self._extract_ids(archive, 'val')
images = np.array([self._extract_image(archive, self._image_path(name))
for name in [*train_ids, *test_ids]], dtype=object)
targets = np.array([... | data = archive.extractfile(class_file).read()
for row in data.decode().split('\n')[:-1]:
key = row.split()[0]
value = int(row.split()[1])
d[key].append(value) | conditional_block |
pascal.py | """ Contains PascalVOC dataset and labels for different tasks """
import os
from os.path import dirname, basename
from io import BytesIO
import tarfile
import tempfile
from collections import defaultdict
import PIL
import tqdm
import numpy as np
import requests
from . import ImagesOpenset
class BasePascal(ImagesOp... | """ Return the path to the .jpg image in the archive by its name """
return os.path.join(dirname(self.SETS_PATH), 'JPEGImages', name + '.jpg')
def _extract_image(self, archive, file):
data = archive.extractfile(file).read()
return PIL.Image.open(BytesIO(data))
def _extract_ids(... | def _name(self, path):
""" Return file name without format """
return basename(path).split('.')[0]
def _image_path(self, name): | random_line_split |
pascal.py | """ Contains PascalVOC dataset and labels for different tasks """
import os
from os.path import dirname, basename
from io import BytesIO
import tarfile
import tempfile
from collections import defaultdict
import PIL
import tqdm
import numpy as np
import requests
from . import ImagesOpenset
class | (ImagesOpenset):
""" The base class for PascalVOC dataset.
The archive contains 17125 images. Total size 1.9GB.
You can unpack the archive to the directory its been downloaded by specifing `unpack` flag.
Tracks of the PascalVOC challenge:
1. Classification
2. Detection
3. Segmen... | BasePascal | identifier_name |
pascal.py | """ Contains PascalVOC dataset and labels for different tasks """
import os
from os.path import dirname, basename
from io import BytesIO
import tarfile
import tempfile
from collections import defaultdict
import PIL
import tqdm
import numpy as np
import requests
from . import ImagesOpenset
class BasePascal(ImagesOp... | """ Contains 11540 images and corresponding classes
Notes
-----
- Labels are represented by the vector of size 20. '1' stands for the presence of at least one object from
coresponding class on the image. '-1' stands for the absence. '0' indicates that the object is presented,
but can hardly be dete... | identifier_body | |
GoogleSheetsDataImportService.js | /**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
| methods: [
{
name: 'getColumns',
javaType: 'String[]',
args: [
{
name: 'x',
type: 'Context',
},
{
name: 'importConfig',
type: 'foam.nanos.google.api.sheets.GoogleSheetsImportConfig'
}
]
},
{
name: 'import... | foam.INTERFACE({
package: 'foam.nanos.google.api.sheets',
name: 'GoogleSheetsDataImportService', | random_line_split |
parser.ts | import { calculateCheckCode } from './builder'
import { SENDER_ID, SOH } from './constants'
import { MessageType } from './enums'
import { bufferReadHex, bufferReadString } from './util'
// var OperationType = {
// SET: '00',
// MOMENTARY: '01'
// }
export interface ParsedHeaderInfo {
deviceId: number
type: num... | case 0xd6: {
// Power get response
const page = bufferReadHex(body, 5, 1)
if (page !== commandId[0]) {
throw new Error('wrong command response')
}
const result = bufferReadHex(body, 3, 1)
if (result !== 0x00) {
// page is actually result
throw new Error('Unsupported operation')
}
... | */
function parseCommandReply(commandId: number[], body: Buffer): string | number {
// console.log('command response', body, commandId)
switch (commandId[0]) { | random_line_split |
parser.ts | import { calculateCheckCode } from './builder'
import { SENDER_ID, SOH } from './constants'
import { MessageType } from './enums'
import { bufferReadHex, bufferReadString } from './util'
// var OperationType = {
// SET: '00',
// MOMENTARY: '01'
// }
export interface ParsedHeaderInfo {
deviceId: number
type: num... | (message: Buffer): ParsedHeaderInfo | undefined {
if (message.readUInt8(0) !== SOH || message.readUInt8(2) !== SENDER_ID) {
return undefined
}
const bodyLength = bufferReadHex(message, 5, 1)
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
return undefined
}
return {
deviceId: m... | parseMessageHeader | identifier_name |
parser.ts | import { calculateCheckCode } from './builder'
import { SENDER_ID, SOH } from './constants'
import { MessageType } from './enums'
import { bufferReadHex, bufferReadString } from './util'
// var OperationType = {
// SET: '00',
// MOMENTARY: '01'
// }
export interface ParsedHeaderInfo {
deviceId: number
type: num... |
function parseGetSetReply(body: Buffer) {
const result = bufferReadHex(body, 1, 1)
const page = bufferReadHex(body, 3, 1)
const opcode = bufferReadHex(body, 5, 1)
// const type = bufferReadHex(body, 7, 1)
// const maxValue = bufferReadHex(body, 9, 2)
const currentValue = bufferReadHex(body, 13, 2)
// check re... | {
// in hex: 01 30 _ID_ 30 _TYPE_ _LEN_ _LEN2_
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
throw new Error(`Message received with unknown type: ${type}`)
}
return {
type,
length: bufferReadHex(message, 5, 1),
}
} | identifier_body |
parser.ts | import { calculateCheckCode } from './builder'
import { SENDER_ID, SOH } from './constants'
import { MessageType } from './enums'
import { bufferReadHex, bufferReadString } from './util'
// var OperationType = {
// SET: '00',
// MOMENTARY: '01'
// }
export interface ParsedHeaderInfo {
deviceId: number
type: num... |
switch (headerProps.type) {
case MessageType.GetReply:
case MessageType.SetReply: {
const res = parseGetSetReply(body)
if (commandId[0] !== res.page || commandId[1] !== res.opcode) {
throw new Error('wrong command response')
}
return res.value
}
case MessageType.CommandReply:
return parse... | {
throw new Error(`Message body length incorrect. Got: ${body.length} Expected ${headerProps.length}`)
} | conditional_block |
test_setup.py | # -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from ade25.assetmanager.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of ade25.assetmanager into Plone."""
def setUp(self):
"""Custom shared utility setup ... | """Test that IAde25AssetmanagerLayer is registered."""
from ade25.assetmanager.interfaces import IAde25AssetmanagerLayer
from plone.browserlayer import utils
self.failUnless(IAde25AssetmanagerLayer in utils.registered_layers()) | identifier_body | |
test_setup.py | # -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from ade25.assetmanager.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of ade25.assetmanager into Plone."""
| """Custom shared utility setup for tests."""
self.portal = self.layer['portal']
self.installer = api.portal.get_tool('portal_quickinstaller')
def test_product_installed(self):
"""Test if ade25.assetmanager is installed with portal_quickinstaller."""
self.assertTrue(self.inst... | def setUp(self): | random_line_split |
test_setup.py | # -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from ade25.assetmanager.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of ade25.assetmanager into Plone."""
def setUp(self):
"""Custom shared utility setup ... | (self):
"""Test that IAde25AssetmanagerLayer is registered."""
from ade25.assetmanager.interfaces import IAde25AssetmanagerLayer
from plone.browserlayer import utils
self.failUnless(IAde25AssetmanagerLayer in utils.registered_layers())
| test_browserlayer | identifier_name |
datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... |
return None
def get_language(self):
"""Get DataCite language."""
if 'language' in self.xml:
return self.xml['language']
return None
def get_related_identifiers(self):
"""Get DataCite related identifiers."""
pass
def get_description(self, descri... | return self.xml['publicationYear'] | conditional_block |
datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... | if 'publicationYear' in self.xml:
return self.xml['publicationYear']
return None
def get_language(self):
"""Get DataCite language."""
if 'language' in self.xml:
return self.xml['language']
return None
def get_related_identifiers(self):
""... | """Get DataCite publication year.""" | random_line_split |
datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... |
def get_description(self, description_type='Abstract'):
"""Get DataCite description."""
if 'descriptions' in self.xml:
if isinstance(self.xml['descriptions']['description'], list):
for description in self.xml['descriptions']['description']:
if descri... | """Get DataCite related identifiers."""
pass | identifier_body |
datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... | (self):
"""Get DataCite titles."""
if 'titles' in self.xml:
return self.xml['titles']['title']
return None
def get_publisher(self):
"""Get DataCite publisher."""
if 'publisher' in self.xml:
return self.xml['publisher']
return None
def get... | get_titles | identifier_name |
Sigmoid.ts | /**
* @license
* Copyright 2021 Google LLC. 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 a... | export const sigmoid = unaryKernelFunc({opType: UnaryOpType.SIGMOID});
export const sigmoidConfig: KernelConfig = {
kernelName: Sigmoid,
backendName: 'webgpu',
kernelFunc: sigmoid,
}; |
import {KernelConfig, Sigmoid} from '@tensorflow/tfjs-core';
import {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';
import {UnaryOpType} from '../unary_op_util';
| random_line_split |
or_stack.rs | use l3::ast::*;
use std::ops::{Index, IndexMut};
use std::vec::Vec;
pub struct Frame {
pub global_index: usize,
pub e: usize,
pub cp: CodePtr,
pub b: usize,
pub bp: CodePtr,
pub tr: usize,
pub h: usize,
args: Vec<Addr>
}
impl Frame {
fn new(global_index: usize,
e: usize... | (&self, index: usize) -> &Self::Output {
self.args.index(index - 1)
}
}
impl IndexMut<usize> for Frame {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.args.index_mut(index - 1)
}
}
| index | identifier_name |
or_stack.rs | use l3::ast::*;
use std::ops::{Index, IndexMut};
use std::vec::Vec;
pub struct Frame {
pub global_index: usize,
pub e: usize,
pub cp: CodePtr,
pub b: usize,
pub bp: CodePtr,
pub tr: usize,
pub h: usize,
args: Vec<Addr>
}
impl Frame {
fn new(global_index: usize,
e: usize... | fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.0.index_mut(index)
}
}
impl Index<usize> for Frame {
type Output = Addr;
fn index(&self, index: usize) -> &Self::Output {
self.args.index(index - 1)
}
}
impl IndexMut<usize> for Frame {
fn index_mut(&mut self, i... | }
impl IndexMut<usize> for OrStack { | random_line_split |
ViewModel.ts | /// <reference path="lib/knockout.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
/// <reference path="Map.ts"/>
/// <reference path="Feed.ts"/>
/// <reference path="API.ts"/>
/// <reference path="Overlay.ts"/>
/// <reference path="Chart.ts"/>
interface IHashtag {
hashtag: string;
co... |
}
changeOverlay(newOverlay: string): void {
this.activeOverlay(newOverlay);
}
updateOnlineCount(): void {
this.onlineCount = ko.observable(1);
setInterval(() => {
this._api.getOnlineCount((count: number) => { this.onlineCount(count); });
}, 5000);
}
}
| {
$(tweet).slideUp(500);
} | conditional_block |
ViewModel.ts | /// <reference path="lib/knockout.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
/// <reference path="Map.ts"/>
/// <reference path="Feed.ts"/>
/// <reference path="API.ts"/>
/// <reference path="Overlay.ts"/>
/// <reference path="Chart.ts"/>
interface IHashtag {
hashtag: string;
co... | (tweet: Tweet): void {
this._map.addTweet(tweet);
this.latestTweets.unshift(tweet);
window.setTimeout(() => { this._map.removeTweet(this.latestTweets.pop()); }, 300000);
}
getLatestPictures(): Tweet[] {
return $.grep<Tweet>(this.latestTweets(), function(el: Tweet, index: number): boolean {
if (el.pictures... | addTweet | identifier_name |
ViewModel.ts | /// <reference path="lib/knockout.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
/// <reference path="Map.ts"/>
/// <reference path="Feed.ts"/>
/// <reference path="API.ts"/>
/// <reference path="Overlay.ts"/>
/// <reference path="Chart.ts"/>
interface IHashtag {
hashtag: string;
co... |
addTweet(tweet: Tweet): void {
this._map.addTweet(tweet);
this.latestTweets.unshift(tweet);
window.setTimeout(() => { this._map.removeTweet(this.latestTweets.pop()); }, 300000);
}
getLatestPictures(): Tweet[] {
return $.grep<Tweet>(this.latestTweets(), function(el: Tweet, index: number): boolean {
if (... | {
this._api = new API('http://tweet.alexurquhart.com/');
this.latestTweets = ko.observableArray([]);
this.topHashtags = ko.observableArray([]);
this.latestPictures = ko.computed(() => { return this.getLatestPictures(); });
this.lastTweet = ko.computed(() => { return this.latestTweets()[0]; });
// Set the o... | identifier_body |
ViewModel.ts | /// <reference path="lib/knockout.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
/// <reference path="Map.ts"/>
/// <reference path="Feed.ts"/>
/// <reference path="API.ts"/>
/// <reference path="Overlay.ts"/>
/// <reference path="Chart.ts"/>
interface IHashtag {
hashtag: string;
co... |
changeOverlay(newOverlay: string): void {
this.activeOverlay(newOverlay);
}
updateOnlineCount(): void {
this.onlineCount = ko.observable(1);
setInterval(() => {
this._api.getOnlineCount((count: number) => { this.onlineCount(count); });
}, 5000);
}
} | if (tweet.nodeType === 1) {
$(tweet).slideUp(500);
}
} | random_line_split |
telequebec.py | from .common import InfoExtractor
from ..utils import (
int_or_none,
smuggle_url,
)
class TeleQuebecIE(InfoExtractor):
_VALID_URL = r'https?://zonevideo\.telequebec\.tv/media/(?P<id>\d+)'
_TEST = {
'url': 'http://zonevideo.telequebec.tv/media/20984/le-couronnement-de-new-york/couronnement-de-n... | # coding: utf-8
from __future__ import unicode_literals
| random_line_split | |
telequebec.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
smuggle_url,
)
class TeleQuebecIE(InfoExtractor):
_VALID_URL = r'https?://zonevideo\.telequebec\.tv/media/(?P<id>\d+)'
_TEST = {
'url': 'http://zonevideo.telequebec.tv/... | media_id = self._match_id(url)
media_data = self._download_json(
'https://mnmedias.api.telequebec.tv/api/v2/media/' + media_id,
media_id)['media']
return {
'_type': 'url_transparent',
'id': media_id,
'url': smuggle_url('limelight:media:' + medi... | identifier_body | |
telequebec.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
smuggle_url,
)
class TeleQuebecIE(InfoExtractor):
_VALID_URL = r'https?://zonevideo\.telequebec\.tv/media/(?P<id>\d+)'
_TEST = {
'url': 'http://zonevideo.telequebec.tv/... | (self, url):
media_id = self._match_id(url)
media_data = self._download_json(
'https://mnmedias.api.telequebec.tv/api/v2/media/' + media_id,
media_id)['media']
return {
'_type': 'url_transparent',
'id': media_id,
'url': smuggle_url('lim... | _real_extract | identifier_name |
target.py | # Library for RTS2 JSON calls.
# (C) 2012 Petr Kubanek, Institute of Physics
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any... |
def create(name,ra,dec):
return json.getProxy().loadJson('/api/create_target', {'tn':name, 'ra':ra, 'dec':dec})['id']
| """Return array with targets matching given name or target ID"""
try:
return json.getProxy().loadJson('/api/tbyid',{'id':int(name)})['d']
except ValueError:
return json.getProxy().loadJson('/api/tbyname',{'n':name})['d'] | identifier_body |
target.py | # Library for RTS2 JSON calls.
# (C) 2012 Petr Kubanek, Institute of Physics
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any... | (self):
"""Load target data from JSON interface."""
if self.id is None:
name = None
return
try:
data = json.getProxy().loadJson('/api/tbyid',{'id':self.id})['d'][0]
self.name = data[1]
except Exception,ex:
self.name = None
def get(name):
"""Return array with targets matching given name or targe... | reload | identifier_name |
target.py | # Library for RTS2 JSON calls.
# (C) 2012 Petr Kubanek, Institute of Physics
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any... |
def get(name):
"""Return array with targets matching given name or target ID"""
try:
return json.getProxy().loadJson('/api/tbyid',{'id':int(name)})['d']
except ValueError:
return json.getProxy().loadJson('/api/tbyname',{'n':name})['d']
def create(name,ra,dec):
return json.getProxy().loadJson('/api/create_targ... | data = json.getProxy().loadJson('/api/tbyid',{'id':self.id})['d'][0]
self.name = data[1]
except Exception,ex:
self.name = None | random_line_split |
target.py | # Library for RTS2 JSON calls.
# (C) 2012 Petr Kubanek, Institute of Physics
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any... |
try:
data = json.getProxy().loadJson('/api/tbyid',{'id':self.id})['d'][0]
self.name = data[1]
except Exception,ex:
self.name = None
def get(name):
"""Return array with targets matching given name or target ID"""
try:
return json.getProxy().loadJson('/api/tbyid',{'id':int(name)})['d']
except ValueErr... | name = None
return | conditional_block |
lib.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/. */
#![crate_name = "skia"]
#![crate_type = "rlib"]
#![feature(libc)]
extern crate libc;
| SkiaGrContextRef,
SkiaGrGLSharedSurfaceRef,
SkiaGrGLNativeContextRef,
SkiaSkNativeSharedGLContextCreate,
SkiaSkNativeSharedGLContextRetain,
SkiaSkNativeSharedGLContextRelease,
SkiaSkNativeSharedGLContextGetFBOID,
SkiaSkNativeSharedGLContextStealSurface,
SkiaSkNativeSharedGLContextGet... | pub use skia::{
SkiaSkNativeSharedGLContextRef, | random_line_split |
base_handler.py | #!/usr/bin/env python3
# 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/.
#
# Copyright 2017-2019 - Edoardo Morassutto <edoardo.morassutto@gmail.com>
# Copyright 2017 - Luc... |
return request.files["file"].stream.read()
@staticmethod
def get_ip(request):
"""
Return the real IP of the client
:param request: The Request object
:return: A string with the IP of the client
"""
num_proxies = Config.num_proxies
if num_proxies ... | return None | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.