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 |
|---|---|---|---|---|
source_conversion_utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani,
# D. Monelli.
#
# The Hazard Modeller's Toolkit is free software: you can redistribute
# it and/or modify it under the terms of the GNU Affero Gene... | trace_str += ' %s %s %s,' % (point.longitude, point.latitude,
point.depth)
trace_str = trace_str.lstrip(' ')
return 'LINESTRING (' + trace_str.rstrip(',') + ')' | for point in edge: | random_line_split |
source_conversion_utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani,
# D. Monelli.
#
# The Hazard Modeller's Toolkit is free software: you can redistribute
# it and/or modify it under the terms of the GNU Affero Gene... |
def mag_scale_rel_to_hazardlib(mag_scale_rel, use_default=False):
"""
Returns the magnitude scaling relation in a format readable by
openquake.hazardlib
"""
if isinstance(mag_scale_rel, BaseMSR):
return mag_scale_rel
elif isinstance(mag_scale_rel, str):
if not mag_scale_rel in ... | raise ValueError('Rupture aspect ratio not defined!') | conditional_block |
source_conversion_utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani,
# D. Monelli.
#
# The Hazard Modeller's Toolkit is free software: you can redistribute
# it and/or modify it under the terms of the GNU Affero Gene... |
def simple_edge_to_wkt_linestring(edge):
'''
Coverts a simple fault trace to well-known text format
:param trace:
Fault trace as instance of :class: openquake.hazardlib.geo.line.Line
:returns:
Well-known text (WKT) Linstring representation of the trace
'''
trace_str = ""
... | '''
Coverts a simple fault trace to well-known text format
:param trace:
Fault trace as instance of :class: openquake.hazardlib.geo.line.Line
:returns:
Well-known text (WKT) Linstring representation of the trace
'''
trace_str = ""
for point in trace:
trace_str += ' %s %... | identifier_body |
source_conversion_utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2010-2017, GEM Foundation, G. Weatherill, M. Pagani,
# D. Monelli.
#
# The Hazard Modeller's Toolkit is free software: you can redistribute
# it and/or modify it under the terms of the GNU Affero Gene... | (hypo_depth_dist, use_default=False):
"""
Returns the hypocentral depth distribtuion as an instance of the :class:
openquake.hazardlib.pmf.
"""
if isinstance(hypo_depth_dist, PMF):
# Is already instance of PMF
return hypo_depth_dist
else:
if use_default:
# De... | hdd_to_pmf | identifier_name |
setup.py | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-usuario', | description='Extension to model User.',
long_description=README,
keywords = "django user",
url='https://github.com/dyachan/django-usuario',
author='Diego Yachan',
author_email='diego.yachan@gmail.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
... | version='0.4',
packages=['usuario'],
include_package_data=True,
license='MIT License', | random_line_split |
TextFontMetrics.js | import _ from 'lodash'
import {ATTR, hasAttributeFor} from './attributes'
const SUPER_SUB_FONT_RATIO = 0.65 // matches MS word according to http://en.wikipedia.org/wiki/Subscript_and_superscript
function calcFontScale(fontSize, unitsPerEm) {
return 1 / unitsPerEm * fontSize
}
function calcSuperSubFontSize(fontSiz... | se {
currentWidthPx += glyphAdvancePx
if(glyphAdvancePx > 0) index++
}
}
return {
cursorX: currentWidthPx,
index: index
}
},
/**
* Get the advance width in pixels for the given char or chars.
* @param {number} fontSize
* @param {object|Array} chars
* @retur... | return {
cursorX: currentWidthPx,
index: index
}
} el | conditional_block |
TextFontMetrics.js | import _ from 'lodash'
import {ATTR, hasAttributeFor} from './attributes'
const SUPER_SUB_FONT_RATIO = 0.65 // matches MS word according to http://en.wikipedia.org/wiki/Subscript_and_superscript
function calcFontScale(fontSize, unitsPerEm) {
return 1 / unitsPerEm * fontSize
}
function calcSuperSubFontSize(fontSiz... | /**
* Get the advance width in pixels for the given char or chars.
* @param {number} fontSize
* @param {object|Array} chars
* @return {number}
*/
advanceXForChars(fontSize, chars) {
let minFontSize = this.config.minFontSize
fontSize = fontSize > minFontSize ? fontSize : minFontSize
if(_.i... | let minFontSize = this.config.minFontSize
fontSize = fontSize > minFontSize ? fontSize : minFontSize
let currentWidthPx = 0
let index = 0
for(let i = 0; i < chars.length; i++) {
let glyphAdvancePx = this.replicaCharAdvance(chars[i], fontSize)
if(pixelValue < currentWidthPx + glyphAdvanceP... | identifier_body |
TextFontMetrics.js | import _ from 'lodash'
import {ATTR, hasAttributeFor} from './attributes'
const SUPER_SUB_FONT_RATIO = 0.65 // matches MS word according to http://en.wikipedia.org/wiki/Subscript_and_superscript
function calcFontScale(fontSize, unitsPerEm) {
return 1 / unitsPerEm * fontSize
}
function calcSuperSubFontSize(fontSiz... | * Get the font scale to convert between font units and pixels for the given font size.
* @param fontSize
* @return {number}
*/
fontScale(fontSize) {
return calcFontScale(fontSize, this.config.unitsPerEm)
},
/**
* Return the font size given the default font size and current attributes.
* @pa... |
/** | random_line_split |
TextFontMetrics.js | import _ from 'lodash'
import {ATTR, hasAttributeFor} from './attributes'
const SUPER_SUB_FONT_RATIO = 0.65 // matches MS word according to http://en.wikipedia.org/wiki/Subscript_and_superscript
function calcFontScale(fontSize, unitsPerEm) {
return 1 / unitsPerEm * fontSize
}
function calcSuperSubFontSize(fontSiz... | ntSize, chars) {
let minFontSize = this.config.minFontSize
fontSize = fontSize > minFontSize ? fontSize : minFontSize
if(_.isArray(chars)) {
return chars.reduce((currentWidthPx, char) => {
return currentWidthPx + this.replicaCharAdvance(char, fontSize)
}, 0)
} else {
return thi... | anceXForChars(fo | identifier_name |
logical_enclosures.py | # -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2016) Hewlett Packard Enterprise Development LP
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limi... | (self, id_or_uri, timeout=-1):
"""
Reapplies the appliance's configuration on enclosures for the logical enclosure by ID or uri. This includes
running the same configure steps that were performed as part of the enclosure add. A task is returned to the
caller which can be used to track th... | update_configuration | identifier_name |
logical_enclosures.py | # -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2016) Hewlett Packard Enterprise Development LP
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limi... | timeout:
Timeout in seconds. Wait task completion by default. The timeout does not abort the operation
in OneView, just stops waiting for its completion.
Returns: (dict) Updated logical enclosure
"""
return self._client.update(resource, timeout=timeo... | random_line_split | |
logical_enclosures.py | # -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2016) Hewlett Packard Enterprise Development LP
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limi... |
def generate_support_dump(self, information, id_or_uri, timeout=-1):
"""
Generates a support dump for the logical enclosure with the specified ID. A logical enclosure support dump
includes content for logical interconnects associated with that logical enclosure. By default, it also contain... | """
Updates the configuration script of the logical enclosure and on all enclosures in the logical enclosure with
the specified ID.
Args:
id_or_uri: Could be either the resource id or the resource uri
information: updated script
timeout: Timeout in seconds. W... | identifier_body |
cte.js | 'use strict';
const { expect } = require('chai');
const { getParsedSql } = require('./util');
describe('common table expressions', () => {
it('should support single CTE', () => {
const sql = `
WITH cte AS (SELECT 1)
SELECT * FROM cte
`.trim();
expect(getParsedSql(s... | const sql = `
WITH RECURSIVE cte(n) AS
(
SELECT 1
UNION
SELECT n + 1 FROM cte WHERE n < 5
)
SELECT * FROM cte
`.trim();
expect(getParsedSql(sql)).to.match(/^WITH RECURSIVE/);
});
}); | it('should support recursive CTE', () => { | random_line_split |
_available_endpoint_services_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/virtualNetworkAvailableEndpointServices'} # type: ignore
| request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response,... | identifier_body |
_available_endpoint_services_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_respo... | list_of_elem = cls(list_of_elem) | conditional_block |
_available_endpoint_services_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | }
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-06-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._... | 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError | random_line_split |
_available_endpoint_services_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | (next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: i... | prepare_request | identifier_name |
qhyper.test.ts | import { loadData } from '@common/load';
import { resolve } from 'path';
import { cl, select } from '@common/debug-select';
import { humanize } from '@common/humanize-time';
import { qhyper, useWasmBackends, clearBackends } from '..';
const qhyperLogs = select('qhyper');
const qhyperWarns = qhyperLogs("argument out ... | /**
* function qhyper(p, m, n, k, lower.tail = TRUE, log.p = FALSE)
* p = vector of probailities
* m = number of white balls in the population
* n = number of black balls in the population
* k = total number of balls drawn (k-x)=number of non-white balls
* lower.tail ... | random_line_split | |
factory.py | import sys
from apps.cowry.exceptions import PaymentMethodNotFound
from django.utils.importlib import import_module
def _load_from_module(path):
package, attr = path.rsplit('.', 1)
module = import_module(package)
return getattr(module, attr)
# TODO read django settings to find out what adapters to load.
... |
return payment_methods
def get_payment_method_ids(amount=None, currency='', country='', recurring=None, pm_ids=None):
payment_method_ids = []
for pm in get_payment_methods(amount=amount, currency=currency, country=country, recurring=recurring, pm_ids=pm_ids):
payment_method_ids.append(pm['id'])
... | payment_methods.append({'id': pm_id, 'name': pm_config.get('name')}) | conditional_block |
factory.py | import sys
from apps.cowry.exceptions import PaymentMethodNotFound
from django.utils.importlib import import_module
def | (path):
package, attr = path.rsplit('.', 1)
module = import_module(package)
return getattr(module, attr)
# TODO read django settings to find out what adapters to load.
# TODO Ensure not duplicate payment method names.
# ADAPTERS = getattr(settings, 'COWRY_ADAPTERS')
ADAPTERS = ('apps.cowry_docdata.adapters... | _load_from_module | identifier_name |
factory.py | import sys
from apps.cowry.exceptions import PaymentMethodNotFound
from django.utils.importlib import import_module
def _load_from_module(path):
package, attr = path.rsplit('.', 1)
module = import_module(package)
return getattr(module, attr)
# TODO read django settings to find out what adapters to load.
... |
def get_payment_methods(amount=None, currency='', country='', recurring=None, pm_ids=None):
payment_methods = []
for adapter in _adapters:
cur_payment_methods = adapter.get_payment_methods()
for pm_id in cur_payment_methods:
if pm_ids is None or pm_id in pm_ids:
# ... | adapter = _adapter_for_payment_method(payment_method_id)
payment = adapter.create_payment_object(order, payment_method_id, payment_submethod, amount, currency)
payment.save()
return payment | identifier_body |
factory.py | import sys
from apps.cowry.exceptions import PaymentMethodNotFound
from django.utils.importlib import import_module
def _load_from_module(path):
package, attr = path.rsplit('.', 1)
module = import_module(package)
return getattr(module, attr)
# TODO read django settings to find out what adapters to load.
... | max_amount = pm_config.get('max_amount', sys.maxint)
min_amount = pm_config.get('min_amount', 0)
restricted_currencies = pm_config.get('restricted_currencies', (currency,))
restricted_countries = pm_config.get('restricted_countries', (country,))
... | # Extract values from the configuration.
pm_config = cur_payment_methods[pm_id] | random_line_split |
task.py | #!/usr/bin/env python
#
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# 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://... |
_TASKS.pop(self.tid, None)
def stop(self):
self._stop = True
def start(tid, interval, repeat, func, *args, **kwargs):
"""
Start a new task
"""
LOG.info('start(tid=%s, interval=%s, repeat=%s, func=%s, args=%s, '
'kwargs=%s)', tid, interval, repeat, func.__name__, args... | if self._stop:
break
retval = self.func(*self.args, **self.kwargs)
if retval is not None:
break
time.sleep(self.interval) | conditional_block |
task.py | #!/usr/bin/env python
#
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# 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://... | (self, tid, interval, repeat, func, *args, **kwargs):
super(_Task, self).__init__()
self.tid = tid
self.interval = interval
self.repeat = repeat
self.func = func
self.args = args
self.kwargs = kwargs
self._stop = False
_TASKS[tid] = self
... | __init__ | identifier_name |
task.py | #!/usr/bin/env python
#
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# 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://... |
self._stop = False
_TASKS[tid] = self
self.start()
def run(self):
for dummy in range(self.repeat):
if self._stop:
break
retval = self.func(*self.args, **self.kwargs)
if retval is not None:
break
time.s... | random_line_split | |
task.py | #!/usr/bin/env python
#
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# 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://... | """
Stop all running tasks
"""
LOG.info('stop_all()')
for tid in _TASKS:
stop(tid)
if wait:
while _TASKS:
time.sleep(0.5) | identifier_body | |
__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .. import Provider as PhoneNumberProvider
class Provider(PhoneNumberProvider):
| phonenumber_prefixes = [134, 135, 136, 137, 138, 139, 147, 150,
151, 152, 157, 158, 159, 182, 187, 188,
130, 131, 132, 145, 155, 156, 185, 186,
145, 133, 153, 180, 181, 189]
formats = [str(i) + "########" for i in phonenumber_prefix... | identifier_body | |
__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .. import Provider as PhoneNumberProvider
| class Provider(PhoneNumberProvider):
phonenumber_prefixes = [134, 135, 136, 137, 138, 139, 147, 150,
151, 152, 157, 158, 159, 182, 187, 188,
130, 131, 132, 145, 155, 156, 185, 186,
145, 133, 153, 180, 181, 189]
formats = [str(i)... | random_line_split | |
__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .. import Provider as PhoneNumberProvider
class | (PhoneNumberProvider):
phonenumber_prefixes = [134, 135, 136, 137, 138, 139, 147, 150,
151, 152, 157, 158, 159, 182, 187, 188,
130, 131, 132, 145, 155, 156, 185, 186,
145, 133, 153, 180, 181, 189]
formats = [str(i) + "########" ... | Provider | identifier_name |
config.js | module.exports = {
development: {
baseUrl : "http://176.32.196.113:8000",
secret: 'c6ddbf5047efc9s4e0d8ff9a87f4b5acb92abb8sdd26662ff2ddc74e33d1e24e0af7ssaa904825ae632e967418s98b1effd06531s15637cdca372bff0004f035',
mongo_url: 'mongodb://127.0.0.1:27017/maeuticaAgenda',
SENDGRID_API_KE... | }; | random_line_split | |
brainfuck.rs | extern crate zaldinar_core;
use std::fmt;
use zaldinar_core::client::PluginRegister;
use zaldinar_core::events::CommandEvent;
const MAX_ITERATIONS: u32 = 134217728u32;
const MAX_OUTPUT: usize = 256usize;
#[derive(Debug)]
pub enum Error {
/// A right bracket was found with no unmatched left brackets preceding it... | next_instruction = target_position;
continue; // this avoids the automatic incrementing of next_instruction below.
}
},
}
next_instruction += 1;
}
if !done {
event.client.send_message(event.channel(), "Reached maximum i... | random_line_split | |
brainfuck.rs | extern crate zaldinar_core;
use std::fmt;
use zaldinar_core::client::PluginRegister;
use zaldinar_core::events::CommandEvent;
const MAX_ITERATIONS: u32 = 134217728u32;
const MAX_OUTPUT: usize = 256usize;
#[derive(Debug)]
pub enum Error {
/// A right bracket was found with no unmatched left brackets preceding it... | (event: &CommandEvent) {
let instructions = match parse_instructions(event) {
Ok(instructions) => instructions,
Err(e) => {
event.client.send_message(event.channel(), format!("Error: {}", e));
return;
}
};
// Program memory, max size is 2^15
let mut memor... | brainfuck | identifier_name |
brainfuck.rs | extern crate zaldinar_core;
use std::fmt;
use zaldinar_core::client::PluginRegister;
use zaldinar_core::events::CommandEvent;
const MAX_ITERATIONS: u32 = 134217728u32;
const MAX_OUTPUT: usize = 256usize;
#[derive(Debug)]
pub enum Error {
/// A right bracket was found with no unmatched left brackets preceding it... |
pub fn register(register: &mut PluginRegister) {
register.register_command("brainfuck", brainfuck);
}
fn escape_output(input: &str) -> String {
let mut result = String::with_capacity(input.len());
for c in input.chars() {
match c {
'\t' => result.push_str("\\t"),
'\r' => r... | {
let instructions = match parse_instructions(event) {
Ok(instructions) => instructions,
Err(e) => {
event.client.send_message(event.channel(), format!("Error: {}", e));
return;
}
};
// Program memory, max size is 2^15
let mut memory = [0u8; 32768];
/... | identifier_body |
brainfuck.rs | extern crate zaldinar_core;
use std::fmt;
use zaldinar_core::client::PluginRegister;
use zaldinar_core::events::CommandEvent;
const MAX_ITERATIONS: u32 = 134217728u32;
const MAX_OUTPUT: usize = 256usize;
#[derive(Debug)]
pub enum Error {
/// A right bracket was found with no unmatched left brackets preceding it... |
}
pub fn register(register: &mut PluginRegister) {
register.register_command("brainfuck", brainfuck);
}
fn escape_output(input: &str) -> String {
let mut result = String::with_capacity(input.len());
for c in input.chars() {
match c {
'\t' => result.push_str("\\t"),
'\r' =>... | {
event.client.send_message(event.channel(), format!("Output: {}", escape_output(&output)));
} | conditional_block |
openid.ts | import { Router } from 'express';
import { Issuer, Client, generators, errors } from 'openid-client';
import jwt from 'jsonwebtoken';
import ms from 'ms';
import { LocalAuthDriver } from './local';
import { getAuthProvider } from '../../auth';
import env from '../../env';
import { AuthenticationService, UsersService } ... | (user: User): Promise<void> {
return this.refresh(user);
}
async refresh(user: User): Promise<void> {
let authData = user.auth_data as AuthData;
if (typeof authData === 'string') {
try {
authData = JSON.parse(authData);
} catch {
logger.warn(`[OpenID] Session data isn't valid JSON: ${authData}`)... | login | identifier_name |
openid.ts | import { Router } from 'express';
import { Issuer, Client, generators, errors } from 'openid-client';
import jwt from 'jsonwebtoken';
import ms from 'ms';
import { LocalAuthDriver } from './local';
import { getAuthProvider } from '../../auth';
import env from '../../env';
import { AuthenticationService, UsersService } ... | }
generateCodeVerifier(): string {
return generators.codeVerifier();
}
async generateAuthUrl(codeVerifier: string, prompt = false): Promise<string> {
try {
const client = await this.client;
const codeChallenge = generators.codeChallenge(codeVerifier);
const paramsConfig = typeof this.config.params ==... | })
);
})
.catch(reject);
}); | random_line_split |
openid.ts | import { Router } from 'express';
import { Issuer, Client, generators, errors } from 'openid-client';
import jwt from 'jsonwebtoken';
import ms from 'ms';
import { LocalAuthDriver } from './local';
import { getAuthProvider } from '../../auth';
import env from '../../env';
import { AuthenticationService, UsersService } ... |
} catch (e) {
throw handleError(e);
}
}
}
}
const handleError = (e: any) => {
if (e instanceof errors.OPError) {
if (e.error === 'invalid_grant') {
// Invalid token
logger.trace(e, `[OpenID] Invalid grant`);
return new InvalidTokenException();
}
// Server response error
logger.trace(e,... | {
await this.usersService.updateOne(user.id, {
auth_data: JSON.stringify({ refreshToken: tokenSet.refresh_token }),
});
} | conditional_block |
openid.ts | import { Router } from 'express';
import { Issuer, Client, generators, errors } from 'openid-client';
import jwt from 'jsonwebtoken';
import ms from 'ms';
import { LocalAuthDriver } from './local';
import { getAuthProvider } from '../../auth';
import env from '../../env';
import { AuthenticationService, UsersService } ... |
async generateAuthUrl(codeVerifier: string, prompt = false): Promise<string> {
try {
const client = await this.client;
const codeChallenge = generators.codeChallenge(codeVerifier);
const paramsConfig = typeof this.config.params === 'object' ? this.config.params : {};
return client.authorizationUrl({
... | {
return generators.codeVerifier();
} | identifier_body |
calendar.js | import { withTracker } from 'meteor/react-meteor-data'
import HarptosDate from 'dream-date/calendar/harptos'
import HarptosCommonDate from 'dream-date/calendar/harptos-common'
import OdreianDate from 'dream-date/calendar/odreian'
import TideDate from 'dream-date/calendar/tide'
import GregorianDate from 'dream-date/cale... |
export const calendarList = Object.entries(calendars).map(([id, detail]) =>
Object.assign({ id }, detail),
)
const withCampaignDateConstructor = withTracker(({ campaignCalendarId }) => ({
CampaignDate: (calendars[campaignCalendarId] || calendars[defaultCalendarId])
.dateConstructor,
}))
const withCampaignCalenda... | dateConstructor: GregorianDate,
},
}
const defaultCalendarId = 'odreianV1' | random_line_split |
task_queue.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 https://mozilla.org/MPL/2.0/. */
//! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue).
use crate::dom::bindings::ce... | (&self) -> &crossbeam_channel::Receiver<T> {
// This is a new iteration of the event-loop, so we reset the "business" counter.
self.taken_task_counter.set(0);
// We want to be notified when the script-port is ready to receive.
// Hence that's the one we need to include in the select.
... | select | identifier_name |
task_queue.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 https://mozilla.org/MPL/2.0/. */
//! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue).
use crate::dom::bindings::ce... | _ => {
// A task that will not be throttled, start counting "business"
self.taken_task_counter
.set(self.taken_task_counter.get() + 1);
return false;
},
}
... | };
match task_source {
TaskSourceName::PerformanceTimeline => return true, | random_line_split |
task_queue.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 https://mozilla.org/MPL/2.0/. */
//! Machinery for [task-queue](https://html.spec.whatwg.org/multipage/#task-queue).
use crate::dom::bindings::ce... |
/// Process incoming tasks, immediately sending priority ones downstream,
/// and categorizing potential throttles.
fn process_incoming_tasks(&self, first_msg: T) {
let mut incoming = Vec::with_capacity(self.port.len() + 1);
if !first_msg.is_wake_up() {
incoming.push(first_msg)... | {
TaskQueue {
port,
wake_up_sender,
msg_queue: DomRefCell::new(VecDeque::new()),
taken_task_counter: Default::default(),
throttled: Default::default(),
}
} | identifier_body |
CustomSortOfGroups.ts | import {get} from 'lodash';
import {StageGroup} from '../directives/MonitoringGroup';
export type GroupSortOptions = Array<string>;
type OrderType = 'desc' | 'asc';
export type GroupSortConfig = {
default?: { field: string, order: OrderType },
allowed_fields_to_sort: GroupSortOptions
};
function isOrderType... |
const configForGroup = matchGroupToOrderConfig(group);
const customConfig: GroupSortConfig = get(config, configForGroup, null);
if (customConfig && customConfig.default && !isOrderType(customConfig.default.order)) {
console.warn(`Default sort order is not a valid string '${customConfig.default.or... | {
return null;
} | conditional_block |
CustomSortOfGroups.ts | import {get} from 'lodash';
import {StageGroup} from '../directives/MonitoringGroup';
export type GroupSortOptions = Array<string>;
type OrderType = 'desc' | 'asc';
export type GroupSortConfig = {
default?: { field: string, order: OrderType },
allowed_fields_to_sort: GroupSortOptions
};
function isOrderType... | } | console.warn(`Default sort order is not a valid string '${customConfig.default.order}'. Use 'asc' or 'desc'`);
customConfig.default.order = 'asc';
}
return customConfig; | random_line_split |
CustomSortOfGroups.ts | import {get} from 'lodash';
import {StageGroup} from '../directives/MonitoringGroup';
export type GroupSortOptions = Array<string>;
type OrderType = 'desc' | 'asc';
export type GroupSortConfig = {
default?: { field: string, order: OrderType },
allowed_fields_to_sort: GroupSortOptions
};
function isOrderType... | {
if (!group || !group._id || !group.type) {
return null;
}
const configForGroup = matchGroupToOrderConfig(group);
const customConfig: GroupSortConfig = get(config, configForGroup, null);
if (customConfig && customConfig.default && !isOrderType(customConfig.default.order)) {
consol... | identifier_body | |
CustomSortOfGroups.ts | import {get} from 'lodash';
import {StageGroup} from '../directives/MonitoringGroup';
export type GroupSortOptions = Array<string>;
type OrderType = 'desc' | 'asc';
export type GroupSortConfig = {
default?: { field: string, order: OrderType },
allowed_fields_to_sort: GroupSortOptions
};
function isOrderType... | (group: StageGroup) {
if (group._id.endsWith(':output')) {
return 'monitoring.output.sort';
} else if (group._id.endsWith(':scheduled')) {
return 'monitoring.scheduled.sort';
}
return 'monitoring.stage.sort';
}
export default function getCustomSortForGroup(config: any, group: StageGrou... | matchGroupToOrderConfig | identifier_name |
volk_math.py | #!/usr/bin/env python
from gnuradio import gr
from gnuradio import blocks
import argparse
from volk_test_funcs import *
try:
from gnuradio import blocks
except ImportError:
sys.stderr.write("This example requires gr-blocks.\n")
def multiply_const_cc(N):
k = 3.3
op = blocks.multiply_const_cc(k)
tb... | ():
avail_tests = [multiply_const_cc,
multiply_const_ff,
multiply_cc,
multiply_ff,
add_ff,
conjugate_cc,
multiply_conjugate_cc]
desc='Time an operation to compare with other implementations. \
... | main | identifier_name |
volk_math.py | #!/usr/bin/env python
from gnuradio import gr
from gnuradio import blocks
import argparse
from volk_test_funcs import *
try:
from gnuradio import blocks
except ImportError:
sys.stderr.write("This example requires gr-blocks.\n")
def multiply_const_cc(N):
k = 3.3
op = blocks.multiply_const_cc(k)
tb... |
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
| avail_tests = [multiply_const_cc,
multiply_const_ff,
multiply_cc,
multiply_ff,
add_ff,
conjugate_cc,
multiply_conjugate_cc]
desc='Time an operation to compare with other implementations. \
Th... | identifier_body |
volk_math.py | #!/usr/bin/env python
from gnuradio import gr
from gnuradio import blocks
import argparse
from volk_test_funcs import *
try:
from gnuradio import blocks
except ImportError:
sys.stderr.write("This example requires gr-blocks.\n")
def multiply_const_cc(N):
k = 3.3
op = blocks.multiply_const_cc(k)
tb... | except AttributeError:
print "\tCould not run test. Skipping."
return None
def main():
avail_tests = [multiply_const_cc,
multiply_const_ff,
multiply_cc,
multiply_ff,
add_ff,
conjugate_cc,
... | res = format_results(func.__name__, t)
return res | random_line_split |
volk_math.py | #!/usr/bin/env python
from gnuradio import gr
from gnuradio import blocks
import argparse
from volk_test_funcs import *
try:
from gnuradio import blocks
except ImportError:
sys.stderr.write("This example requires gr-blocks.\n")
def multiply_const_cc(N):
k = 3.3
op = blocks.multiply_const_cc(k)
tb... |
N = int(args.nitems)
iters = args.iterations
label = args.label
conn = create_connection(args.database)
new_table(conn, label)
if args.all:
tests = xrange(len(avail_tests))
else:
tests = args.tests
for test in tests:
res = run_tests(avail_tests[test], N, iter... | print "Available Tests to Run:"
print "\n".join(["\t{0}: {1}".format(i,f.__name__) for i,f in enumerate(avail_tests)])
sys.exit(0) | conditional_block |
group_server.py | #!/usr/bin/python
from subprocess import call
import sys
import os
from socket import *
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
###Broadcast according to client group
#Show ports associated with a particular group
file = "group_port.txt" ... | file.write(ip)
file.close()
#Writing IP ends here
#Encrypting the file with GPG key
call(["gpg", "-r", "trialuser@mailinator.com", "-e", file_name])
file_name = file_name+".gpg" #New file name
###Putting the file's content in buffer
f=open(file_name,"rb") #Opening file in read mode ... | file = open(file_name,"a") | random_line_split |
group_server.py | #!/usr/bin/python
from subprocess import call
import sys
import os
from socket import *
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
###Broadcast according to client group
#Show ports associated with a particular group
file = "group_port.txt" ... |
fl.close()
#If not written then write IP to file
if written !=1:
file = open(file_name,"a")
file.write(ip)
file.close()
#Writing IP ends here
#Encrypting the file with GPG key
call(["gpg", "-r", "trialuser@mailinator.com", "-e", file_name])
file_name = file_name+".gpg" #New file name
###Putting... | written = 1 | conditional_block |
issue-35668.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let a = (0..30).collect::<Vec<_>>();
for k in func(&a) {
println!("{}", k);
}
}
| main | identifier_name |
issue-35668.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let a = (0..30).collect::<Vec<_>>();
for k in func(&a) {
println!("{}", k);
}
} | identifier_body | |
issue-35668.rs | // Copyright 2016 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 |
fn func<'a, T>(a: &'a [T]) -> impl Iterator<Item=&'a T> {
a.iter().map(|a| a*a)
//~^ ERROR binary operation `*` cannot be applied to type `&T`
}
fn main() {
let a = (0..30).collect::<Vec<_>>();
for k in func(&a) {
println!("{}", k);
}
} | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
inspector.ts | import { invoke, invokeSync } from '@electron/internal/renderer/ipc-renderer-internal-utils'
window.onload = function () {
// Use menu API to show context menu.
window.InspectorFrontendHost!.showContextMenuAtPoint = createMenu
// correct for Chromium returning undefined for filesystem
window.Persistence!.File... | (project: string, path: string) {
project = 'file:///'
return `${project}${path}`
}
// The DOM implementation expects (message?: string) => boolean
(window.confirm as any) = function (message: string, title: string) {
return invokeSync('ELECTRON_INSPECTOR_CONFIRM', message, title) as boolean
}
const useEditMen... | completeURL | identifier_name |
inspector.ts | import { invoke, invokeSync } from '@electron/internal/renderer/ipc-renderer-internal-utils'
window.onload = function () {
// Use menu API to show context menu.
window.InspectorFrontendHost!.showContextMenuAtPoint = createMenu
// correct for Chromium returning undefined for filesystem
window.Persistence!.File... |
// The DOM implementation expects (message?: string) => boolean
(window.confirm as any) = function (message: string, title: string) {
return invokeSync('ELECTRON_INSPECTOR_CONFIRM', message, title) as boolean
}
const useEditMenuItems = function (x: number, y: number, items: any[]) {
return items.length === 0 && ... | {
project = 'file:///'
return `${project}${path}`
} | identifier_body |
inspector.ts | import { invoke, invokeSync } from '@electron/internal/renderer/ipc-renderer-internal-utils'
window.onload = function () {
// Use menu API to show context menu.
window.InspectorFrontendHost!.showContextMenuAtPoint = createMenu
// correct for Chromium returning undefined for filesystem
window.Persistence!.File... |
window.DevToolsAPI!.contextMenuCleared()
})
}
const showFileChooserDialog = function (callback: (blob: File) => void) {
invoke<[ string, any ]>('ELECTRON_INSPECTOR_SELECT_FILE').then(([path, data]) => {
if (path && data) {
callback(dataToHtml5FileObject(path, data))
}
})
}
const dataToHtml5Fi... | {
window.DevToolsAPI!.contextMenuItemSelected(id)
} | conditional_block |
inspector.ts | import { invoke, invokeSync } from '@electron/internal/renderer/ipc-renderer-internal-utils'
window.onload = function () {
// Use menu API to show context menu.
window.InspectorFrontendHost!.showContextMenuAtPoint = createMenu
// correct for Chromium returning undefined for filesystem |
// Use dialog API to override file chooser dialog.
window.UI!.createFileSelectorElement = createFileSelectorElement
}
// Extra / is needed as a result of MacOS requiring absolute paths
function completeURL (project: string, path: string) {
project = 'file:///'
return `${project}${path}`
}
// The DOM implemen... | window.Persistence!.FileSystemWorkspaceBinding.completeURL = completeURL | random_line_split |
powersource.py | from BinPy.Gates import *
class PowerSource:
"""
Models a Power Source from which various connectors can tap by connecting to it.
taps: The list of all connectors connected to this power source.
connect(): Takes in one or more connectors as input and connects them to the power source.
disconne... |
def connect(self, *connectors):
"""Takes in one or more connectors as an input and taps to the power source."""
for connector in connectors:
if not isinstance(connector, Connector):
raise Exception("Error: Input given is not a connector")
else:
... | self.taps = [] | identifier_body |
powersource.py | from BinPy.Gates import *
class PowerSource:
"""
Models a Power Source from which various connectors can tap by connecting to it.
taps: The list of all connectors connected to this power source.
connect(): Takes in one or more connectors as input and connects them to the power source.
disconne... | (self, *connectors):
"""
Takes in one or more connectors as an input and disconnects them from the power source.
A floating connector has a value of None.
A message is printed if a specified connector is not already tapping from this source.
"""
for connector in connecto... | disconnect | identifier_name |
powersource.py | from BinPy.Gates import *
class PowerSource:
"""
Models a Power Source from which various connectors can tap by connecting to it.
taps: The list of all connectors connected to this power source.
connect(): Takes in one or more connectors as input and connects them to the power source.
disconne... |
self.taps.append(connector)
connector.state = 1
connector.tap(self, 'output')
connector.trigger()
def disconnect(self, *connectors):
"""
Takes in one or more connectors as an input and disconnects them from the power source.
A... | raise Exception(
"ERROR: The connector is already an output of some other object") | conditional_block |
powersource.py | from BinPy.Gates import *
class PowerSource:
"""
Models a Power Source from which various connectors can tap by connecting to it.
taps: The list of all connectors connected to this power source.
| def __init__(self):
self.taps = []
def connect(self, *connectors):
"""Takes in one or more connectors as an input and taps to the power source."""
for connector in connectors:
if not isinstance(connector, Connector):
raise Exception("Error: Input given is not... | connect(): Takes in one or more connectors as input and connects them to the power source.
disconnect(): Takes in one or more connectors as input and disconnects them from the power source.
"""
| random_line_split |
settings.py | from __future__ import unicode_literals
import os.path
from django.utils._os import upath
TEST_ROOT = os.path.dirname(upath(__file__))
TESTFILES_PATH = os.path.join(TEST_ROOT, 'apps', 'test', 'static', 'test')
TEST_SETTINGS = {
'DEBUG': True,
'MEDIA_URL': '/media/',
'STATIC_URL': '/static/',
'MEDIA... | 'STATICFILES_FINDERS': [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
],
'INSTALLED_APPS': [
'django.contrib.staticfiles',
'staticfiles_test... | random_line_split | |
EditAddressModal.tsx | import { ChangeEvent, useState, useRef } from 'react';
import { c } from 'ttag';
import { updateAddress } from '@proton/shared/lib/api/addresses';
import { Address } from '@proton/shared/lib/interfaces';
import { FormModal, Row, Field, Label, Input, SimpleSquireEditor } from '../../components';
import { useApi, useLoad... |
};
const handleDisplayName = ({ target }: ChangeEvent<HTMLInputElement>) =>
updateModel({ ...model, displayName: target.value });
const handleSignature = (value: string) => updateModel({ ...model, signature: value });
const handleSubmit = async () => {
await api(
updateAd... | {
editorRef.current.value = model.signature;
} | conditional_block |
EditAddressModal.tsx | import { ChangeEvent, useState, useRef } from 'react';
import { c } from 'ttag';
import { updateAddress } from '@proton/shared/lib/api/addresses';
import { Address } from '@proton/shared/lib/interfaces';
import { FormModal, Row, Field, Label, Input, SimpleSquireEditor } from '../../components';
import { useApi, useLoad... | </Row>
<Row>
<Label>{c('Label').t`Display name`}</Label>
<Field>
<Input
value={model.displayName}
placeholder={c('Placeholder').t`Choose display name`}
onChange={handleDisp... | </div> | random_line_split |
Gruntfile.js | 'use strict';
module.exports = function(grunt) {
// Load all grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
jshint: {
js: {
src: ['Gruntfile.js', 'tasks/*.js']
},
options: {
report... | js: {
files: '<%= jshint.js.src %>',
tasks: ['jshint:js', 'jsbeautifier']
}
},
jsbeautifier: {
files: '<%= jshint.js.src %>',
options: {
js: {
braceStyle: 'collapse',
b... | jshintrc: '.jshintrc'
}
},
watch: { | random_line_split |
S15.5.4.16_A10.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: |
The String.prototype.toLowerCase.length property has the attribute
ReadOnly
es5id: 15.5.4.16_A10
description: >
Checking if varying the String.prototype.toLowerC... | //CHECK#2
if (String.prototype.toLowerCase.length !== __obj) {
$ERROR('#2: __obj = String.prototype.toLowerCase.length; String.prototype.toLowerCase.length = function(){return "shifted";}; String.prototype.toLowerCase.length === __obj. Actual: ' + String.prototype.toLowerCase.length);
}
//
///////////////////////////... |
////////////////////////////////////////////////////////////////////////////// | random_line_split |
S15.5.4.16_A10.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: |
The String.prototype.toLowerCase.length property has the attribute
ReadOnly
es5id: 15.5.4.16_A10
description: >
Checking if varying the String.prototype.toLowerC... |
//
//////////////////////////////////////////////////////////////////////////////
var __obj = String.prototype.toLowerCase.length;
verifyNotWritable(String.prototype.toLowerCase, "length", null, function() {
return "shifted";
});
//////////////////////////////////////////////////////////////////////////////
//CHE... | {
$ERROR('#1: String.prototype.toLowerCase.hasOwnProperty(\'length\') return true. Actual: ' + String.prototype.toLowerCase.hasOwnProperty('length'));
} | conditional_block |
load-module-test.js | const buster = require('buster')
const loadModule = require('../lib/utils').loadModule
buster.testCase('loadModule', { | buster.assert(module)
let result = module(123, 123)
buster.assert.near(result, 1.0, 1e-3)
},
'should load and return a module from /lib with path .': function () {
let module = loadModule('.', 'invalid-input-error')
buster.assert(module)
},
'should throw an error when path is contains ..':... | 'should load and return a module within the given directory': function () {
let module = loadModule('plugins', 'close-time-plugin') | random_line_split |
app.ts | // nativescript |
// app
import { NativeModule } from './native.module';
// let linkedInInitOptions : tnsOAuthModule.ITnsOAuthOptionsLinkedIn = {
// clientId: '81b04j6ndos3l6',
// clientSecret: 'PH2r0K7X8f7s4zs1',
// redirectUri: 'http://172.30.36.63:3000/login/',
// scope: ['r_basicprofile'] //Leave blank and the default sco... | import { platformNativeScriptDynamic } from 'nativescript-angular/platform';
import * as tnsOAuthModule from 'nativescript-oauth';
import * as app from 'application';
import SocialLogin = require("nativescript-social-login"); | random_line_split |
index.ts | /*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { shared as lspCommon } from '@salesforce/lightning-lsp-common';
import { Telemet... |
export async function activate(context: ExtensionContext) {
const extensionHRStart = process.hrtime();
console.log('Activation Mode: ' + getActivationMode());
// Run our auto detection routine before we activate
// 1) If activationMode is off, don't startup no matter what
if (getActivationMode() === 'off') ... | {
const config = workspace.getConfiguration('salesforcedx-vscode-lightning');
return config.get('activationMode') || 'autodetect'; // default to autodetect
} | identifier_body |
index.ts | /*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { shared as lspCommon } from '@salesforce/lightning-lsp-common';
import { Telemet... | (value: Uri): string {
if (/^win32/.test(process.platform)) {
// The *first* : is also being encoded which is not the standard for URI on Windows
// Here we transform it back to the standard way
return value.toString().replace('%3A', ':');
} else {
return value.toString();
}
}
function protocol2C... | code2ProtocolConverter | identifier_name |
index.ts | /*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { shared as lspCommon } from '@salesforce/lightning-lsp-common';
import { Telemet... |
// If activationMode === always, ignore workspace type and continue activating
// 4) If we get here, we either passed autodetect validation or activationMode == always
console.log('Aura Components Extension Activated');
console.log('WorkspaceType detected: ' + workspaceType);
// Initialize telemetry servic... | {
// If activationMode === autodetect and we don't have a valid workspace type, exit
console.log(
'Aura LSP - autodetect did not find a valid project structure, exiting....'
);
console.log('WorkspaceType detected: ' + workspaceType);
return;
} | conditional_block |
index.ts | /*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { shared as lspCommon } from '@salesforce/lightning-lsp-common';
import { Telemet... | const client = new LanguageClient(
'auraLanguageServer',
nls.localize('client_name'),
serverOptions,
clientOptions
);
client
.onReady()
.then(() => {
client.onNotification('salesforce/indexingStarted', startIndexing);
client.onNotification('salesforce/indexingEnded', endIndexi... |
// Create the language client and start the client. | random_line_split |
ssl-insecure-version.py | import ssl
from pyOpenSSL import SSL
ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv2)
SSL.Context(method=SSL.SSLv2_METHOD)
SSL.Context(method=SSL.SSLv23_METHOD)
herp_derp(ssl_version=ssl.PROTOCOL_SSLv2)
herp_derp(method=SSL.SSLv2_METHOD)
herp_derp(method=SSL.SSLv23_METHOD)
# strict tests
ssl.wrap_socket(ssl_version=s... |
def open_ssl_socket(version=SSL.SSLv23_METHOD):
pass
# this one will pass ok
def open_ssl_socket(version=SSL.TLSv1_1_METHOD):
pass
| pass | identifier_body |
ssl-insecure-version.py | import ssl
from pyOpenSSL import SSL
ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv2)
SSL.Context(method=SSL.SSLv2_METHOD)
SSL.Context(method=SSL.SSLv23_METHOD)
herp_derp(ssl_version=ssl.PROTOCOL_SSLv2)
herp_derp(method=SSL.SSLv2_METHOD)
herp_derp(method=SSL.SSLv23_METHOD)
# strict tests
ssl.wrap_socket(ssl_version=s... | pass | random_line_split | |
ssl-insecure-version.py | import ssl
from pyOpenSSL import SSL
ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv2)
SSL.Context(method=SSL.SSLv2_METHOD)
SSL.Context(method=SSL.SSLv23_METHOD)
herp_derp(ssl_version=ssl.PROTOCOL_SSLv2)
herp_derp(method=SSL.SSLv2_METHOD)
herp_derp(method=SSL.SSLv23_METHOD)
# strict tests
ssl.wrap_socket(ssl_version=s... | (version=SSL.TLSv1_1_METHOD):
pass
| open_ssl_socket | identifier_name |
sudoku.rs | // http://rosettacode.org/wiki/Sudoku
#![feature(core)]
#![feature(step_by)]
use std::fmt;
use std::str::FromStr;
const BOARD_WIDTH: usize = 9;
const BOARD_HEIGHT: usize = 9;
const GROUP_WIDTH: usize = 3;
const GROUP_HEIGHT: usize = 3;
const MAX_NUMBER: usize = 9;
type BITS = u16;
const MASK_ALL: BITS = 0x1ff;
const ... | () -> Sudoku {
Sudoku { map: [[MASK_ALL; BOARD_WIDTH]; BOARD_HEIGHT] }
}
fn get(&self, x: usize, y: usize) -> u32 {
match self.map[y][x].count_ones() {
0 => INVALID_CELL,
1 => self.map[y][x].trailing_zeros() + 1,
_ => 0
}
}
fn set(&mut self, ... | new | identifier_name |
sudoku.rs | // http://rosettacode.org/wiki/Sudoku
#![feature(core)]
#![feature(step_by)]
use std::fmt;
use std::str::FromStr;
const BOARD_WIDTH: usize = 9;
const BOARD_HEIGHT: usize = 9;
const GROUP_WIDTH: usize = 3;
const GROUP_HEIGHT: usize = 3;
const MAX_NUMBER: usize = 9;
type BITS = u16;
const MASK_ALL: BITS = 0x1ff;
const ... |
next
};
puzzle.map[next.unwrap()][x] = bit;
}
// Check each group
for y0 in (0..BOARD_HEIGHT).step_by(GROUP_WIDTH) {
for x0 in (0..BOARD_WIDTH).step_by(GROUP_HEIGHT) {
let next = {
... | { continue } | conditional_block |
sudoku.rs | // http://rosettacode.org/wiki/Sudoku
#![feature(core)]
#![feature(step_by)]
use std::fmt;
use std::str::FromStr;
const BOARD_WIDTH: usize = 9;
const BOARD_HEIGHT: usize = 9;
const GROUP_WIDTH: usize = 3;
const GROUP_HEIGHT: usize = 3;
const MAX_NUMBER: usize = 9;
type BITS = u16;
const MASK_ALL: BITS = 0x1ff;
const ... |
}
impl fmt::Display for Sudoku {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let hbar = "+---+---+---+";
for y in (0 .. BOARD_HEIGHT) {
if y % GROUP_HEIGHT == 0 {
try!(writeln!(f, "{}", hbar));
}
for x in (0 .. BOARD_WIDTH) {
... | {
let mut sudoku = Sudoku::new();
for (y, line) in s.lines().filter(|l| !l.is_empty()).enumerate() {
let line = line.trim_matches(|c: char| c.is_whitespace());
for (x, c) in line.chars().enumerate() {
if let Some(d) = c.to_digit(10) {
if d != ... | identifier_body |
sudoku.rs | // http://rosettacode.org/wiki/Sudoku
#![feature(core)]
#![feature(step_by)]
use std::fmt;
use std::str::FromStr;
const BOARD_WIDTH: usize = 9;
const BOARD_HEIGHT: usize = 9;
const GROUP_WIDTH: usize = 3;
const GROUP_HEIGHT: usize = 3;
const MAX_NUMBER: usize = 9;
type BITS = u16;
const MASK_ALL: BITS = 0x1ff;
const ... | for y in (0 .. BOARD_HEIGHT) {
let next = {
let mut it = (0 .. BOARD_WIDTH)
.filter(|&x| puzzle.map[y][x] & bit != 0);
let next = it.next();
if next.is_none() || it.next().is_some() { continue }
... | // Check each rows | random_line_split |
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/. */
#![cfg(test)]
#![feature(plugin, test)]
extern crate app_units;
extern crate cssparser;
extern crate euclid;
#[ma... | mod attr;
mod cache;
mod keyframes;
mod logical_geometry;
mod media_queries;
mod owning_handle;
mod parsing;
mod properties;
mod rule_tree;
mod str;
mod stylesheets;
mod stylist;
mod value;
mod viewport;
mod writing_modes {
use style::logical_geometry::WritingMode;
use style::properties::{INITIAL_SERVO_VALUES,... | extern crate style_traits;
extern crate test;
mod animated_properties; | random_line_split |
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/. */
#![cfg(test)]
#![feature(plugin, test)]
extern crate app_units;
extern crate cssparser;
extern crate euclid;
#[ma... |
}
| {
assert_eq!(get_writing_mode(INITIAL_SERVO_VALUES.get_inheritedbox()), WritingMode::empty())
} | identifier_body |
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/. */
#![cfg(test)]
#![feature(plugin, test)]
extern crate app_units;
extern crate cssparser;
extern crate euclid;
#[ma... | () {
assert_eq!(get_writing_mode(INITIAL_SERVO_VALUES.get_inheritedbox()), WritingMode::empty())
}
}
| initial_writing_mode_is_empty | identifier_name |
test.ts | import 'regenerator-runtime/runtime';
import path from 'path';
import rimraf from 'rimraf';
import randomString from '../lib/utils/crypto-random-string';
import { Application } from 'spectron';
const TEST_USERNAME = `sptest-${randomString(16)}@test.localhost.localdomain`;
const TEST_PASSWORD = randomString(22);
consol... | ? []
: result.value[firstOfType].slice(1)
);
} else if (Date.now() - tic < msTimeout) {
setTimeout(f, 100);
} else {
reject();
}
};
f();
});
};
const app: Application = new Application({
path: path.join(__dirname, '../node_modules/.bin/elec... |
if (result.value && firstOfType > -1) {
resolve(
'string' === typeof result.value | random_line_split |
ask.component.ts | import { Component, OnChanges, Input, Output, EventEmitter } from "ng-metadata/core"
@Component({
selector: "ask-cmp",
template: require('./askCmp.html') //WEBPACK MAGIC INLINE HTML
})
export class AskComponent implements OnChanges {
constructor() {
this.req = this.req || "Q";
this.txt = t... |
public okemit(txt) {
this.res.emit(txt); //emit use RxJS
}
ngOnChanges() { //old life-cycle $onChanges()
this.txt = this.val || "";
}
}
| {
this.txt = this.val || "";
} | identifier_body |
ask.component.ts | import { Component, OnChanges, Input, Output, EventEmitter } from "ng-metadata/core"
@Component({
selector: "ask-cmp",
template: require('./askCmp.html') //WEBPACK MAGIC INLINE HTML
})
export class AskComponent implements OnChanges {
constructor() {
this.req = this.req || "Q";
this.txt = t... |
public okemit(txt) {
this.res.emit(txt); //emit use RxJS
}
ngOnChanges() { //old life-cycle $onChanges()
this.txt = this.val || "";
}
} | random_line_split | |
ask.component.ts | import { Component, OnChanges, Input, Output, EventEmitter } from "ng-metadata/core"
@Component({
selector: "ask-cmp",
template: require('./askCmp.html') //WEBPACK MAGIC INLINE HTML
})
export class AskComponent implements OnChanges {
constructor() {
this.req = this.req || "Q";
this.txt = t... | (txt) {
this.res.emit(txt); //emit use RxJS
}
ngOnChanges() { //old life-cycle $onChanges()
this.txt = this.val || "";
}
}
| okemit | identifier_name |
ssh_keys.rs | use std::marker::PhantomData;
use hyper::method::Method;
use response;
use request::RequestBuilder;
use request::DoRequest;
impl<'t> RequestBuilder<'t, response::SshKeys> {
pub fn create(self, name: &str, pub_key: &str) -> RequestBuilder<'t, response::SshKey> {
// POST: "https://api.digitalocean.com/v2/a... |
pub fn destroy(self) -> RequestBuilder<'t, response::HeaderOnly> {
// DELETE: "https://api.digitalocean.com/v2/account/keys/$ID"
// OR
// DELETE: "https://api.digitalocean.com/v2/account/keys/$FINGER"
RequestBuilder {
method: Method::Delete,
auth: self.auth,
... | {
// PUT: "https://api.digitalocean.com/v2/account/keys/$ID"
// OR
// PUT: "https://api.digitalocean.com/v2/account/keys/$FINGER"
// body:
// "name" : "new_name"
RequestBuilder {
method: Method::Put,
url: self.url,
auth: self.auth,... | identifier_body |
ssh_keys.rs | use std::marker::PhantomData;
use hyper::method::Method;
use response;
use request::RequestBuilder;
use request::DoRequest;
impl<'t> RequestBuilder<'t, response::SshKeys> {
pub fn create(self, name: &str, pub_key: &str) -> RequestBuilder<'t, response::SshKey> {
// POST: "https://api.digitalocean.com/v2/a... | body: None,
}
}
}
impl<'t> DoRequest<response::SshKey> for RequestBuilder<'t, response::SshKey> {} | RequestBuilder {
method: Method::Delete,
auth: self.auth,
url: self.url,
resp_t: PhantomData, | random_line_split |
ssh_keys.rs | use std::marker::PhantomData;
use hyper::method::Method;
use response;
use request::RequestBuilder;
use request::DoRequest;
impl<'t> RequestBuilder<'t, response::SshKeys> {
pub fn create(self, name: &str, pub_key: &str) -> RequestBuilder<'t, response::SshKey> {
// POST: "https://api.digitalocean.com/v2/a... | (self, name: &str) -> RequestBuilder<'t, response::SshKey> {
// PUT: "https://api.digitalocean.com/v2/account/keys/$ID"
// OR
// PUT: "https://api.digitalocean.com/v2/account/keys/$FINGER"
// body:
// "name" : "new_name"
RequestBuilder {
method: Method::P... | update | identifier_name |
named_anon_conflict.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... | return None; // inapplicable
};
debug!("try_report_named_anon_conflict: named = {:?}", named);
debug!(
"try_report_named_anon_conflict: anon_arg_info = {:?}",
anon_arg_info
);
debug!(
"try_report_named_anon_conflict: region_info = ... | random_line_split | |
named_anon_conflict.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... |
}
| {
match *region {
ty::ReStatic => true,
ty::ReFree(ref free_region) => match free_region.bound_region {
ty::BrNamed(..) => true,
_ => false,
},
ty::ReEarlyBound(ebr) => ebr.has_name(),
_ => false,
}
} | identifier_body |
named_anon_conflict.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... | (&self) -> Option<ErrorReported> {
let (span, sub, sup) = self.get_regions();
debug!(
"try_report_named_anon_conflict(sub={:?}, sup={:?})",
sub,
sup
);
// Determine whether the sub and sup consist of one named region ('a)
// and one anonymous... | try_report_named_anon_conflict | identifier_name |
named_anon_conflict.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... | ;
debug!("try_report_named_anon_conflict: named = {:?}", named);
debug!(
"try_report_named_anon_conflict: anon_arg_info = {:?}",
anon_arg_info
);
debug!(
"try_report_named_anon_conflict: region_info = {:?}",
region_info
);
... | {
return None; // inapplicable
} | conditional_block |
models.py | import datetime
import hashlib
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.db import models, IntegrityError
from django.utils.translation import ugettext_lazy as _
from django.db.models import signals
from taggit.managers imp... |
def decline(self, user):
if not user.is_authenticated() or user == user.get_anonymous():
raise ValueError("You must log in to decline invitations")
if not user.email == self.email:
raise ValueError(
"You can't decline an invitation that wasn't for you")
... | if not user.is_authenticated() or user == user.get_anonymous():
raise ValueError("You must log in to accept invitations")
if not user.email == self.email:
raise ValueError(
"You can't accept an invitation that wasn't for you")
self.group.join(user, role=self.role)... | identifier_body |
models.py | import datetime
import hashlib
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.db import models, IntegrityError
from django.utils.translation import ugettext_lazy as _
from django.db.models import signals
from taggit.managers imp... | (self, user):
if not user.is_authenticated():
return False
return self.user_is_role(user, "manager")
def join(self, user, **kwargs):
if user == user.get_anonymous():
raise ValueError("The invited user cannot be anonymous")
member, created = GroupMember.object... | can_invite | identifier_name |
models.py | import datetime
import hashlib
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.db import models, IntegrityError
from django.utils.translation import ugettext_lazy as _
from django.db.models import signals
from taggit.managers imp... | raise ValueError(
"You can't decline an invitation that wasn't for you")
self.state = "declined"
self.save()
def group_pre_delete(instance, sender, **kwargs):
"""Make sure that the anonymous group is not deleted"""
if instance.name == 'anonymous':
raise Exce... | if not user.is_authenticated() or user == user.get_anonymous():
raise ValueError("You must log in to decline invitations")
if not user.email == self.email: | random_line_split |
models.py | import datetime
import hashlib
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.db import models, IntegrityError
from django.utils.translation import ugettext_lazy as _
from django.db.models import signals
from taggit.managers imp... |
return cls.objects.filter(groupmember__user=user)
return []
def __unicode__(self):
return self.title
def keyword_list(self):
"""
Returns a list of the Group's keywords.
"""
return [kw.name for kw in self.keywords.all()]
def resources(self, reso... | return cls.objects.all() | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.