file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
child_ps.rs | use kekbit::api::ReadError::*;
use kekbit::api::{EncoderHandler, Reader, Writer};
use kekbit::core::*;
use log::{error, info};
use nix::sys::wait::waitpid;
use nix::unistd::{fork, getpid, ForkResult};
use simple_logger::SimpleLogger;
use std::path::Path;
use std::process::exit;
use std::result::Result;
const ITERATION... | () -> Result<(), ()> {
info!("Creating reader porcess ...{}", getpid());
let mut reader = try_shm_reader(&Path::new(Q_PATH), 1000, 2000, 200).unwrap();
let mut stop = false;
let mut msg_count = 0;
while !stop {
match reader.try_read() {
Ok(Some(_)) => msg_count += 1,
... | run_reader | identifier_name |
identity.py | """Identity related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required, permission_required, user_passes_test
)
from django.shortcuts import render
from django.template.loader import render_to_str... | where=["admin_quota.username=%s" % where],
tables=["admin_quota", "admin_domain"],
order_by=["%s%s" % (sort_dir, sort_order)]
)
else:
if db_type == "postgres":
select = (
"(admin_quota.bytes::float / (CAS... | select={"quota_value__bytes": "admin_quota.bytes"}, | random_line_split |
identity.py | """Identity related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required, permission_required, user_passes_test
)
from django.shortcuts import render
from django.template.loader import render_to_str... |
@login_required
@permission_required("core.add_user")
@reversion.create_revision()
def newaccount(request):
"""Create a new account."""
return AccountWizard(request).process()
@login_required
@permission_required("core.change_user")
@reversion.create_revision()
def editaccount(request, pk):
account = U... | accs = User.objects.filter(is_superuser=False) \
.exclude(groups__name="SimpleUsers")
res = [a.username for a in accs.all()]
return render_to_json_response(res) | identifier_body |
identity.py | """Identity related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required, permission_required, user_passes_test
)
from django.shortcuts import render
from django.template.loader import render_to_str... |
page = get_listing_page(mboxes, request.GET.get("page", 1))
context = {
"headers": render_to_string(
"admin/identities_quota_headers.html", {}, request
)
}
if page is None:
context["length"] = 0
else:
context["rows"] = render_to_string(
"admin... | raise BadRequest(_("Invalid request")) | conditional_block |
identity.py | """Identity related views."""
from reversion import revisions as reversion
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.decorators import (
login_required, permission_required, user_passes_test
)
from django.shortcuts import render
from django.template.loader import render_to_str... | (request, pk):
account = User.objects.get(pk=pk)
if not request.user.can_access(account):
raise PermDeniedException
mb = account.mailbox if hasattr(account, "mailbox") else None
instances = {
"general": account, "profile": account, "mail": mb, "perms": account
}
results = signal... | editaccount | identifier_name |
heartbeat.js | (function($, wprss_admin_heartbeat){
/**
* Returns the IDs of the feed sources shown on the current page
*/
var getFeedSourceIDS = function() {
var ids = [];
$('table.wp-list-table tbody tr').each( function(){
if ( $(this).hasClass('no-items') ) return;
ids.push( $(this).attr('id').split('-')[1] );
... |
// If we were waiting, we are not anymore. Remove the waiting class
if ( waiting ) {
itemsCol.removeClass('waiting');
}
// Update the error icon
var errorsCol = row.find('td.column-errors');
var errorIcon = errorsCol.find('i.fa');
errorIcon.toggleClass( 'wprss-show', feed_source['errors'] !... | {
// Update the count and the icon appropriately
itemCount.text( feed_source['items'] );
icon.toggleClass( 'wprss-show', feed_source['updating'] );
} | conditional_block |
heartbeat.js | (function($, wprss_admin_heartbeat){
/**
* Returns the IDs of the feed sources shown on the current page
*/
var getFeedSourceIDS = function() {
var ids = [];
$('table.wp-list-table tbody tr').each( function(){
if ( $(this).hasClass('no-items') ) return;
ids.push( $(this).attr('id').split('-')[1] );
... | var stopUpdating = icon.hasClass('wprss-show') && !feed_source['updating'];
// Check if the item count changed
var itemCountChanged = feed_source['items'] != itemCount.text();
// Check if we are waiting for the item count to update
var waiting = itemsCol.hasClass('waiting');
// Check if the updat... | random_line_split | |
parser.py | import numpy as np
import re
import os
def GetBlocks(filename):
|
print("Test...")
l=GetBlocks(r'C:\Users\silvanamorreale\Documents\GitHub\Lab3.2\parser test.txt')
print(l)
| '''
prende il filename e ritorna la lista [[[pt1.x,pt1.y],...],[blocco2],...]
'''
f=open(filename)
block=False
lastlist=[]
listone=[]
for i in f:
print(i)
if(re.match(r"[\d\.]+e[\+\-][\d]+\t[\d\.]+e[\+\-][\d]+", i)):
print("entrato")
block=True
... | identifier_body |
parser.py | import numpy as np
import re
import os
def GetBlocks(filename):
'''
prende il filename e ritorna la lista [[[pt1.x,pt1.y],...],[blocco2],...]
'''
f=open(filename)
block=False
lastlist=[]
listone=[]
for i in f:
print(i)
if(re.match(r"[\d\.]+e[\+\-][\d]+\t[\d\.]+e[\+\-][\... |
else:
if(block):
listone.append(lastlist)
lastlist=[]
block=False
return listone
print("Test...")
l=GetBlocks(r'C:\Users\silvanamorreale\Documents\GitHub\Lab3.2\parser test.txt')
print(l)
| print("entrato")
block=True
slast=re.findall(r"[\d\.]+e[\+\-][\d]+", i)
lastlist.append(list(map(float, slast))) | conditional_block |
parser.py | import numpy as np
import re
import os
def GetBlocks(filename):
'''
prende il filename e ritorna la lista [[[pt1.x,pt1.y],...],[blocco2],...]
'''
f=open(filename)
block=False
lastlist=[]
listone=[]
for i in f:
print(i)
if(re.match(r"[\d\.]+e[\+\-][\d]+\t[\d\.]+e[\+\-][\... | l=GetBlocks(r'C:\Users\silvanamorreale\Documents\GitHub\Lab3.2\parser test.txt')
print(l) | print("Test...")
| random_line_split |
parser.py | import numpy as np
import re
import os
def | (filename):
'''
prende il filename e ritorna la lista [[[pt1.x,pt1.y],...],[blocco2],...]
'''
f=open(filename)
block=False
lastlist=[]
listone=[]
for i in f:
print(i)
if(re.match(r"[\d\.]+e[\+\-][\d]+\t[\d\.]+e[\+\-][\d]+", i)):
print("entrato")
bl... | GetBlocks | identifier_name |
views.py | from django.http import HttpResponse
from django.core.cache import cache
from EventSubscriptions.models import EventWithSubscriptions
import requests
'''
This view provides the final result requested from the exercise. It first looks for it in the cache; if the result is
not there, it calls the class "EventWithSubscri... |
return HttpResponse(result, content_type='application/json')
else:
return HttpResponse("Unrecognized method")
| obj = EventWithSubscriptions(event_id)
result = obj.perform_and_combine_responses()
# if the method gives us a response code or an Exception, we do not store the result in the cache
if type(result) is int:
return HttpResponse("Server returned with the following error ... | conditional_block |
views.py | from django.http import HttpResponse
from django.core.cache import cache
from EventSubscriptions.models import EventWithSubscriptions
import requests
'''
This view provides the final result requested from the exercise. It first looks for it in the cache; if the result is
not there, it calls the class "EventWithSubscri... | else:
return HttpResponse("Unrecognized method")
| if req.method == 'GET': # we process GET requests only
if req.path.split('/')[2] == '': # it is mandatory to insert characters for the event_id
return HttpResponse("The path must be: \"/events-with-subscriptions/EVENT_ID\"")
event_id = req.path.split('/')[2]
key = 'event-with-... | identifier_body |
views.py | from django.http import HttpResponse
from django.core.cache import cache
from EventSubscriptions.models import EventWithSubscriptions
import requests
'''
This view provides the final result requested from the exercise. It first looks for it in the cache; if the result is
not there, it calls the class "EventWithSubscri... | (req):
if req.method == 'GET': # we process GET requests only
if req.path.split('/')[2] == '': # it is mandatory to insert characters for the event_id
return HttpResponse("The path must be: \"/events-with-subscriptions/EVENT_ID\"")
event_id = req.path.split('/')[2]
key = '... | event_subscriptions | identifier_name |
views.py | from django.http import HttpResponse | import requests
'''
This view provides the final result requested from the exercise. It first looks for it in the cache; if the result is
not there, it calls the class "EventWithSubscriptions" in order to perform the query. If the response is successful,
is being stored inside the cache. Cache timeout is 4.2 minutes (... | from django.core.cache import cache
from EventSubscriptions.models import EventWithSubscriptions | random_line_split |
CovEst.py | """Module containing routines for estimating covariance models.
"""
import math
from pyvol.tseries.Transforms import SeqXform
import CovUtils
class CovEstimator:
"""Base class illustrating the API covariance estimators should follow
All covariance estimators should subclass this class and override ... | -------------------------------------------------------
PURPOSE: Finish doing estimation on data in a given query.
Subclasses may override if desired.
"""
_ignore = self, query
def Estimate(self, args, query, line):
... | -- query: A Sequence.TimeSeq object with raw data for estimation.
| random_line_split |
CovEst.py | """Module containing routines for estimating covariance models.
"""
import math
from pyvol.tseries.Transforms import SeqXform
import CovUtils
class CovEstimator:
"""Base class illustrating the API covariance estimators should follow
All covariance estimators should subclass this class and override ... | (self, args, query, line):
"""Estimate volatility
INPUTS:
-- args: Dictionary where keys are columns in query and values
are the values for the current line.
-- query: Full TimeSeq object containing past data that ca... | Estimate | identifier_name |
CovEst.py | """Module containing routines for estimating covariance models.
"""
import math
from pyvol.tseries.Transforms import SeqXform
import CovUtils
class CovEstimator:
"""Base class illustrating the API covariance estimators should follow
All covariance estimators should subclass this class and override ... |
returns = [row[c] for row in query.data[startLine:line]]
volEst = math.sqrt(CovUtils.Var(returns))
return volEst
class ThirteenWeekLookbackEstimator(FixedLookackCovEstimator):
"Just like FixedLookackCovEstimator but with lookback of 13 weeks."
def __init__(self, *args, **kw):
... | return None | conditional_block |
CovEst.py | """Module containing routines for estimating covariance models.
"""
import math
from pyvol.tseries.Transforms import SeqXform
import CovUtils
class CovEstimator:
"""Base class illustrating the API covariance estimators should follow
All covariance estimators should subclass this class and override ... |
def Shutdown(self, query):
"Finish doing estimation."
self.estimator.Shutdown(query)
def ProcessRowInSeq(self, args, query, line):
"Call our estimator and return results."
volEst = self.estimator.Estimate(args, query, line)
return [volEst]
class S... | "Prepare to start doing estimation."
self.estimator.Startup(query) | identifier_body |
ProjectContainer.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
firebaseConnect,
isLoaded,
isEmpty,
dataToJS
} from 'react-redux-firebase';
import LoadingSpinner from '../../../../../Components/LoadingSpinner';
import classes from './ProjectC... | extends Component {
static propTypes = {
project: PropTypes.object,
params: PropTypes.object.isRequired
};
render () {
const { project, params } = this.props;
if (isEmpty(project)) {
return <div>Project not found</div>
}
if (!isLoaded(project)) {... | Project | identifier_name |
ProjectContainer.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
firebaseConnect,
isLoaded,
isEmpty,
dataToJS
} from 'react-redux-firebase';
import LoadingSpinner from '../../../../../Components/LoadingSpinner';
import classes from './ProjectC... | <pre>{JSON.stringify(project, null, 2)}</pre>
</div>
)
}
} | return (
<div className={classes.container}>
<h2>Project Container</h2>
<pre>Project Key: {params.projectname}</pre> | random_line_split |
ProjectContainer.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
firebaseConnect,
isLoaded,
isEmpty,
dataToJS
} from 'react-redux-firebase';
import LoadingSpinner from '../../../../../Components/LoadingSpinner';
import classes from './ProjectC... |
} | {
const { project, params } = this.props;
if (isEmpty(project)) {
return <div>Project not found</div>
}
if (!isLoaded(project)) {
return <LoadingSpinner />
}
return (
<div className={classes.container}>
<h2>Project Cont... | identifier_body |
ProjectContainer.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
firebaseConnect,
isLoaded,
isEmpty,
dataToJS
} from 'react-redux-firebase';
import LoadingSpinner from '../../../../../Components/LoadingSpinner';
import classes from './ProjectC... |
if (!isLoaded(project)) {
return <LoadingSpinner />
}
return (
<div className={classes.container}>
<h2>Project Container</h2>
<pre>Project Key: {params.projectname}</pre>
<pre>{JSON.stringify(project, null, 2)}</pre>
... | {
return <div>Project not found</div>
} | conditional_block |
q1.py | def solve(N, R, P, S):
if max([R, P, S]) > 2**(N-1): return "IMPOSSIBLE"
if N > 2 and max([R, P, S]) == 2**(N-1): return "IMPOSSIBLE"
min_val = min([R, P, S])
rep = 2**N//3
if min_val < rep: return "IMPOSSIBLE"
if N == 1:
tmp = ""
if P: tmp += "P"
if R: tmp += "R"
... |
elif R == 2: return "PRRS"
else: return "PSRS"
else:
preP = P//2
preR = R//2
preS = S//2
if preP < P-preP: preP += 1
elif preR < R-preR: preR += 1
else: preS += 1
ans = solve(N-1, preR, preP, preS) + solve(N-1, R-preR, P-preP, S-preS)
retu... | return "PRPS" | conditional_block |
q1.py | def solve(N, R, P, S):
if max([R, P, S]) > 2**(N-1): return "IMPOSSIBLE"
if N > 2 and max([R, P, S]) == 2**(N-1): return "IMPOSSIBLE"
min_val = min([R, P, S])
rep = 2**N//3
if min_val < rep: return "IMPOSSIBLE"
if N == 1:
tmp = ""
if P: tmp += "P"
if R: tmp += "R"
... | if P == 2: return "PRPS"
elif R == 2: return "PRRS"
else: return "PSRS"
else:
preP = P//2
preR = R//2
preS = S//2
if preP < P-preP: preP += 1
elif preR < R-preR: preR += 1
else: preS += 1
ans = solve(N-1, preR, preP, preS) + solve(N-1, ... | random_line_split | |
q1.py | def solve(N, R, P, S):
| elif preR < R-preR: preR += 1
else: preS += 1
ans = solve(N-1, preR, preP, preS) + solve(N-1, R-preR, P-preP, S-preS)
return ans
for case in range(1, eval(input()) + 1):
N, R, P, S = map(int, input().split())
print("Case #{}: {}".format(case, solve(N, R, P, S)))
| if max([R, P, S]) > 2**(N-1): return "IMPOSSIBLE"
if N > 2 and max([R, P, S]) == 2**(N-1): return "IMPOSSIBLE"
min_val = min([R, P, S])
rep = 2**N//3
if min_val < rep: return "IMPOSSIBLE"
if N == 1:
tmp = ""
if P: tmp += "P"
if R: tmp += "R"
if S: tmp += "S"
r... | identifier_body |
q1.py | def | (N, R, P, S):
if max([R, P, S]) > 2**(N-1): return "IMPOSSIBLE"
if N > 2 and max([R, P, S]) == 2**(N-1): return "IMPOSSIBLE"
min_val = min([R, P, S])
rep = 2**N//3
if min_val < rep: return "IMPOSSIBLE"
if N == 1:
tmp = ""
if P: tmp += "P"
if R: tmp += "R"
if S: tm... | solve | identifier_name |
index.ts | namespace webgl_2d_geometry_matrix_transform_with_projection {
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
let canvas = <HTMLCanvasElement>document.getElementById("canvas");
webglLessonsHelper.setupLesson(canvas);
let gl = canvas.getContext("we... | l) {
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
0, -100,
150, 125,
-175, 100]),
gl.STATIC_DRAW);
}
main();
} | tGeometry(g | identifier_name |
index.ts | namespace webgl_2d_geometry_matrix_transform_with_projection {
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
let canvas = <HTMLCanvasElement>document.getElementById("canvas");
webglLessonsHelper.setupLesson(canvas);
let gl = canvas.getContext("we... | // setup GLSL program
let program = webglUtils.createProgramFromScripts(gl, ["2d-vertex-shader", "2d-fragment-shader"]);
gl.useProgram(program);
// look up where the vertex data needs to go.
let positionLocation = gl.getAttribLocation(program, "a_position");
// lookup u... | webglLessonsHelper.showNeedWebGL(canvas);
return;
}
| conditional_block |
index.ts | namespace webgl_2d_geometry_matrix_transform_with_projection {
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
let canvas = <HTMLCanvasElement>document.getElementById("canvas");
webglLessonsHelper.setupLesson(canvas);
let gl = canvas.getContext("we... | // set the color
gl.uniform4fv(colorLocation, color);
let projectionMatrix = m3.projection(
gl.canvas.clientWidth, gl.canvas.clientHeight);
// Compute the matrix
let matrix = m3.projection(gl.canvas.clientWidth, gl.canvas.clientHeight);
... | // set the resolution
gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height);
| random_line_split |
index.ts | namespace webgl_2d_geometry_matrix_transform_with_projection {
function main() {
// Get A WebGL context
/** @type {HTMLCanvasElement} */
let canvas = <HTMLCanvasElement>document.getElementById("canvas");
webglLessonsHelper.setupLesson(canvas);
let gl = canvas.getContext("we... | function updatePosition(index) {
return function (event, ui) {
translation[index] = ui.value;
drawScene();
}
}
// Draw a the scene.
function drawScene() {
webglUtils.resizeCanvasToDisplaySize(gl.canvas);
//... | return function (event, ui) {
scale[index] = ui.value;
drawScene();
}
}
| identifier_body |
snack-bar-container.d.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 { ComponentRef, EmbeddedViewRef, NgZone, OnDestroy, Renderer2, ElementRef, ChangeDetectorRef } from '@angular/c... | */
private _completeExit();
/** Convert the class list to a array of classes it can apply to the dom */
private _getCssClasses(classList);
} | * errors where we end up removing an element which is in the middle of an animation. | random_line_split |
snack-bar-container.d.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 { ComponentRef, EmbeddedViewRef, NgZone, OnDestroy, Renderer2, ElementRef, ChangeDetectorRef } from '@angular/c... | extends BasePortalOutlet implements OnDestroy {
private _ngZone;
private _renderer;
private _elementRef;
private _changeDetectorRef;
/** Whether the component has been destroyed. */
private _destroyed;
/** The portal outlet inside of this container into which the snack bar content will be l... | MatSnackBarContainer | identifier_name |
settings.py | #!/usr/bin/env python
import os
import django
# Base paths
DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
SITE_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
# Debugging
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS =... |
# Media
STATIC_ROOT = os.path.join(SITE_ROOT, 'media')
STATIC_URL = '/site_media/'
ADMIN_MEDIA_PREFIX = '/site_media/admin/'
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'compressor.finders.CompressorFinder',
)
#... | TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
USE_I18N = True
USE_L10N = True | random_line_split |
o63_orwpceGetSetOfCodes.js | #!/usr/bin/env node
'use strict';
const emulatorUtils = require('../rpcEmulatorUtils');
const VDM = require('../../../VDM/prototypes/vdm');
const _ = require('lodash');
const RPC_EMULATOR_MODEL = [
{
id: 'ORWPCE_GET_SET_OF_CODES',
name: 'ORWPCE GET SET OF CODES',
function: 'GETSET^ORWPCE2... | (res) {
return res;
},
},
];
module.exports.rpcEmulatorModel = RPC_EMULATOR_MODEL;
| toReturnValue | identifier_name |
o63_orwpceGetSetOfCodes.js | #!/usr/bin/env node
'use strict';
const emulatorUtils = require('../rpcEmulatorUtils');
const VDM = require('../../../VDM/prototypes/vdm');
const _ = require('lodash');
const RPC_EMULATOR_MODEL = [
{
id: 'ORWPCE_GET_SET_OF_CODES',
name: 'ORWPCE GET SET OF CODES',
function: 'GETSET^ORWPCE2... | },
];
module.exports.rpcEmulatorModel = RPC_EMULATOR_MODEL; | toReturnValue(res) {
return res;
}, | random_line_split |
o63_orwpceGetSetOfCodes.js | #!/usr/bin/env node
'use strict';
const emulatorUtils = require('../rpcEmulatorUtils');
const VDM = require('../../../VDM/prototypes/vdm');
const _ = require('lodash');
const RPC_EMULATOR_MODEL = [
{
id: 'ORWPCE_GET_SET_OF_CODES',
name: 'ORWPCE GET SET OF CODES',
function: 'GETSET^ORWPCE2... | ,
},
];
module.exports.rpcEmulatorModel = RPC_EMULATOR_MODEL;
| {
return res;
} | identifier_body |
meta.ts | import { State } from '@oh-my-rpg/state-meta'
import * as RichText from '@oh-my-rpg/rich-text-format'
function render_meta_infos(metas: {[k: string]: string | number | undefined}): RichText.Document {
const $doc_list = RichText.unordered_list()
Object.keys(metas).forEach((prop: string) => {
$doc_list.pushRawNod... | (m: State, extra: {[k: string]: string | number | undefined} = {}): RichText.Document {
const meta_infos = extra
meta_infos['internal user id'] = m.uuid
meta_infos['telemetry allowed'] = String(m.allow_telemetry)
if (m.email) meta_infos['email'] = m.email
const $doc = RichText.span()
.pushText('Account infos:'... | render_account_info | identifier_name |
meta.ts | import { State } from '@oh-my-rpg/state-meta'
import * as RichText from '@oh-my-rpg/rich-text-format' | const $doc_list = RichText.unordered_list()
Object.keys(metas).forEach((prop: string) => {
$doc_list.pushRawNode(
RichText.span().pushText(prop + ': ' + metas[prop]).done(),
prop
)
})
return $doc_list.done()
}
function render_account_info(m: State, extra: {[k: string]: string | number | undefined} = {... |
function render_meta_infos(metas: {[k: string]: string | number | undefined}): RichText.Document { | random_line_split |
meta.ts | import { State } from '@oh-my-rpg/state-meta'
import * as RichText from '@oh-my-rpg/rich-text-format'
function render_meta_infos(metas: {[k: string]: string | number | undefined}): RichText.Document |
function render_account_info(m: State, extra: {[k: string]: string | number | undefined} = {}): RichText.Document {
const meta_infos = extra
meta_infos['internal user id'] = m.uuid
meta_infos['telemetry allowed'] = String(m.allow_telemetry)
if (m.email) meta_infos['email'] = m.email
const $doc = RichText.span... | {
const $doc_list = RichText.unordered_list()
Object.keys(metas).forEach((prop: string) => {
$doc_list.pushRawNode(
RichText.span().pushText(prop + ': ' + metas[prop]).done(),
prop
)
})
return $doc_list.done()
} | identifier_body |
config.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2012, Nachi Ueno, NTT MCL, Inc.
# 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://ww... | help=_("Default L3 flavor to use")),
cfg.StrOpt('supported_extension_aliases', default='',
help=_("Supported extension aliases")),
cfg.StrOpt('extension_map', default='',
help=_("A list of extensions, per plugin, to load.")),
]
proxy_plugin_opts = [
cfg.StrOpt('... | help=_("List of L3 plugins to load")),
cfg.StrOpt('default_flavor', default='',
help=_("Default flavor to use")),
cfg.StrOpt('default_l3_flavor', default='', | random_line_split |
search.js | 'use strict';
app.controller('SearchCtrl', function ($scope, $routeParams, Post){
$scope.posts = [];
$scope.previewChars = 5;
var pageNum = $routeParams.pageNumber || 1;
$scope.currentPage = pageNum;
$scope.searchTerm = $routeParams.searchTerm;
$scope.search = function(pageNum) {
... | return "#/posts/search/" + $scope.searchTerm + "/" + ($scope.currentPage - 1);
};
$scope.showOlderPostsUrl = function (){
return "#/posts/search/" + $scope.searchTerm + "/" + ($scope.currentPage + 1);
};
$scope.search(pageNum);
}); | };
$scope.showNewerPostsUrl = function (){ | random_line_split |
base.py | import abc
import json
import codecs
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
from rest_framework.parsers import BaseParser
from rest_framework import status
from rest_framework.exceptions import ParseError, APIException
from common.utils import get_logger
logger =... | 据处理
"""
new_row_data = {}
serializer_fields = self.serializer_cls().fields
for k, v in row_data.items():
if isinstance(v, list) or isinstance(v, dict) or isinstance(v, str) and k.strip() and v.strip():
# 解决类似disk_info为字符串的'{}'的问题
if not isinsta... | 构建json数据后的行数 | identifier_name |
base.py | import abc
import json
import codecs
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
from rest_framework.parsers import BaseParser
from rest_framework import status
from rest_framework.exceptions import ParseError, APIException
from common.utils import get_logger
logger =... |
@abc.abstractmethod
def generate_rows(self, stream_data):
raise NotImplemented
def get_column_titles(self, rows):
return next(rows)
def convert_to_field_names(self, column_titles):
fields_map = {}
fields = self.serializer_cls().fields
fields_map.update({v.labe... | stream_data = stream.read()
stream_data = stream_data.strip(codecs.BOM_UTF8)
return stream_data | identifier_body |
base.py | import abc
import json
import codecs
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
from rest_framework.parsers import BaseParser
from rest_framework import status
from rest_framework.exceptions import ParseError, APIException
from common.utils import get_logger
logger =... | w_data = self.process_row_data(row_data)
data.append(row_data)
return data
def parse(self, stream, media_type=None, parser_context=None):
parser_context = parser_context or {}
try:
view = parser_context['view']
meta = view.request.META
self.s... | ro | conditional_block |
base.py | import abc
import json
import codecs
from rest_framework import serializers
from django.utils.translation import ugettext_lazy as _
from rest_framework.parsers import BaseParser
from rest_framework import status
from rest_framework.exceptions import ParseError, APIException
from common.utils import get_logger
logger =... | field_names = self.convert_to_field_names(column_titles)
data = self.generate_data(field_names, rows)
return data
except Exception as e:
logger.error(e, exc_info=True)
raise ParseError('Parse error! ({})'.format(self.media_type)) | rows = self.generate_rows(stream_data)
column_titles = self.get_column_titles(rows) | random_line_split |
run.rs | use std::env;
use std::fs::{read_link};
use std::io::{stdout, stderr};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use libc::pid_t;
use argparse::{ArgumentParser, Store, List, StoreTrue};
use unshare::{Command};
use container::uidmap::{map_users};
use super::setup;
use super::Wrapper;
use path_util::PathEx... | .add_argument("command", Store,
"Command to run inside the container");
ap.refer(&mut args)
.add_argument("args", List,
"Arguments for the command");
ap.stop_on_first_argument(true);
match ap.parse(cmdline, &mut stdout(), &mut stderr()) {
... | {
let mut container: String = "".to_string();
let mut command: String = "".to_string();
let mut args = Vec::<String>::new();
let mut copy = false;
{
let mut ap = ArgumentParser::new();
ap.set_description("
Runs arbitrary command inside the container
");
... | identifier_body |
run.rs | use std::env;
use std::fs::{read_link};
use std::io::{stdout, stderr};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use libc::pid_t;
use argparse::{ArgumentParser, Store, List, StoreTrue};
use unshare::{Command};
use container::uidmap::{map_users};
use super::setup;
use super::Wrapper;
use path_util::PathEx... | Ok(s) => Ok(convert_status(s)),
Err(e) => Err(format!("Error running {:?}: {}", cmd, e)),
}
} | }
match cmd.status() { | random_line_split |
run.rs | use std::env;
use std::fs::{read_link};
use std::io::{stdout, stderr};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use libc::pid_t;
use argparse::{ArgumentParser, Store, List, StoreTrue};
use unshare::{Command};
use container::uidmap::{map_users};
use super::setup;
use super::Wrapper;
use path_util::PathEx... | (wrapper: &Wrapper, cmdline: Vec<String>, user_ns: bool)
-> Result<i32, String>
{
let mut container: String = "".to_string();
let mut command: String = "".to_string();
let mut args = Vec::<String>::new();
let mut copy = false;
{
let mut ap = ArgumentParser::new();
ap.set_descript... | run_command_cmd | identifier_name |
api.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 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 later... | (cls, id_):
"""Get reference from an ID."""
return 'https://cds.cern.ch/api/keywords/{0}'.format(str(id_))
class Category(Record):
"""Define API for a category."""
_schema = 'categories/category-v1.0.0.json'
@classmethod
def create(cls, data, id_=None, **kwargs):
"""Create a ... | get_ref | identifier_name |
api.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 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 later... |
class Keyword(Record):
"""Define API for a keywords."""
_schema = 'keywords/keyword-v1.0.0.json'
@classmethod
def create(cls, data, id_=None, **kwargs):
"""Create a keyword."""
data['$schema'] = current_jsonschemas.path_to_url(cls._schema)
key_id = data.get('key_id', None)
... | from invenio_jsonschemas import current_jsonschemas
from .minters import kwid_minter | random_line_split |
api.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 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 later... |
class Category(Record):
"""Define API for a category."""
_schema = 'categories/category-v1.0.0.json'
@classmethod
def create(cls, data, id_=None, **kwargs):
"""Create a category."""
data['$schema'] = current_jsonschemas.path_to_url(cls._schema)
data['suggest_name'] = {
... | """Get reference from an ID."""
return 'https://cds.cern.ch/api/keywords/{0}'.format(str(id_)) | identifier_body |
api.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 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 later... |
data['suggest_name'] = {
'input': name,
'payload': {
'key_id': key_id,
'name': name
},
}
return super(Keyword, cls).create(data=data, id_=id_, **kwargs)
@property
def ref(self):
"""Get the url."""
retu... | id_ = uuid.uuid4()
kwid_minter(id_, data) | conditional_block |
__init__.py | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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 re... |
This decorator applies a testtools attr for each service that gets
exercised by a test case.
"""
def decorator(f):
known_services = get_service_list()
for service in args:
if service not in known_services:
raise InvalidServiceTag('%s is not a valid service' ... | return service_list
def services(*args):
"""A decorator used to set an attr for each service used in a test case | random_line_split |
__init__.py | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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 re... | (f):
known_services = get_service_list()
for service in args:
if service not in known_services:
raise InvalidServiceTag('%s is not a valid service' % service)
decorators.attr(type=list(args))(f)
@functools.wraps(f)
def wrapper(*func_args, **func_kwar... | decorator | identifier_name |
__init__.py | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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 re... |
return f(*func_args, **func_kwargs)
return wrapper
return decorator
def requires_ext(**kwargs):
"""A decorator to skip tests if an extension is not enabled
@param extension
@param service
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*func_ar... | msg = 'Skipped because the %s service is not available' % (
service)
raise testtools.TestCase.skipException(msg) | conditional_block |
__init__.py | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# 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 re... |
return wrapper
return decorator
def requires_ext(**kwargs):
"""A decorator to skip tests if an extension is not enabled
@param extension
@param service
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*func_args, **func_kwargs):
if not is_extens... | service_list = get_service_list()
for service in args:
if not service_list[service]:
msg = 'Skipped because the %s service is not available' % (
service)
raise testtools.TestCase.skipException(msg)
return f(*func_ar... | identifier_body |
issue-30438-b.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 ... | <'a> {
s: &'a String
}
impl <'a> Index<usize> for Test<'a> {
type Output = Test<'a>;
fn index(&self, _: usize) -> &Self::Output {
&Test { s: &self.s}
//~^ ERROR: borrowed value does not live long enough
}
}
fn main() {
let s = "Hello World".to_string();
let test = Test{s: &s};
... | Test | identifier_name |
issue-30438-b.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | //
// 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Modified regr... | // http://rust-lang.org/COPYRIGHT. | random_line_split |
IconButton.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as ComponentHelpers from '../../components/helpers/helpers.js';
import * as LitHtml from '../../lit-html/lit-html.js';
import {Icon} from './Ico... |
connectedCallback(): void {
this.#shadow.adoptedStyleSheets = [iconButtonStyles];
}
#onClickHandler(event: Event): void {
if (this.#clickHandler) {
event.preventDefault();
this.#clickHandler();
}
}
#render(): void {
const buttonClasses = LitHtml.Directives.classMap({
'ico... | {
return {
groups: this.#groups.map(group => ({...group})), // Ensure we make a deep copy.
accessibleName: this.#accessibleName,
clickHandler: this.#clickHandler,
leadingText: this.#leadingText,
trailingText: this.#trailingText,
compact: this.#compact,
};
} | identifier_body |
IconButton.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as ComponentHelpers from '../../components/helpers/helpers.js';
import * as LitHtml from '../../lit-html/lit-html.js';
import {Icon} from './Ico... | trailingText?: string;
accessibleName?: string;
compact?: boolean;
}
export class IconButton extends HTMLElement {
static readonly litTagName = LitHtml.literal`icon-button`;
readonly #shadow = this.attachShadow({mode: 'open'});
#clickHandler: undefined|(() => void) = undefined;
#groups: IconWithTextData[... |
export interface IconButtonData {
clickHandler?: () => void;
groups: IconWithTextData[];
leadingText?: string; | random_line_split |
IconButton.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as ComponentHelpers from '../../components/helpers/helpers.js';
import * as LitHtml from '../../lit-html/lit-html.js';
import {Icon} from './Ico... |
}
#render(): void {
const buttonClasses = LitHtml.Directives.classMap({
'icon-button': true,
'with-click-handler': Boolean(this.#clickHandler),
'compact': this.#compact,
});
const filteredGroups = this.#groups.filter(counter => counter.text !== undefined)
... | {
event.preventDefault();
this.#clickHandler();
} | conditional_block |
IconButton.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as ComponentHelpers from '../../components/helpers/helpers.js';
import * as LitHtml from '../../lit-html/lit-html.js';
import {Icon} from './Ico... | extends HTMLElement {
static readonly litTagName = LitHtml.literal`icon-button`;
readonly #shadow = this.attachShadow({mode: 'open'});
#clickHandler: undefined|(() => void) = undefined;
#groups: IconWithTextData[] = [];
#compact: boolean = false;
#leadingText: string = '';
#trailingText: string = '';
#... | IconButton | identifier_name |
mod.rs | /*!
* Normalization processes a parse tree until it is in suitable form to
* be converted to the more canonical form. This is done as a series of
* passes, each contained in their own module below.
*/
use grammar::parse_tree as pt;
use grammar::repr as r;
pub type NormResult<T> = Result<T, NormError>;
#[derive(C... | mod resolve;
// Expands macros and expressions
//
// X = ...1 Comma<X> (X Y Z) ...2
//
// to
//
// X = ...1 `Comma<X>` `(X Y Z)` ...2
// `Comma_X`: Vec<<X>> = ...;
// `(X Y Z)` = X Y Z;
//
// AFTER THIS POINT: No more macros, macro references, guarded
// alternatives, repeats, or expr symbols, though t... |
// Resolve identifiers into terminals/nonterminals etc. | random_line_split |
mod.rs | /*!
* Normalization processes a parse tree until it is in suitable form to
* be converted to the more canonical form. This is done as a series of
* passes, each contained in their own module below.
*/
use grammar::parse_tree as pt;
use grammar::repr as r;
pub type NormResult<T> = Result<T, NormError>;
#[derive(C... |
let grammar = try!(resolve::resolve(grammar));
let grammar = try!(macro_expand::expand_macros(grammar));
let grammar = try!(token_check::validate(grammar));
let types = try!(tyinfer::infer_types(&grammar));
lower::lower(grammar, types)
}
// These are executed *IN ORDER*:
// Check most safety cond... | { try!(prevalidate::validate(&grammar)); } | conditional_block |
mod.rs | /*!
* Normalization processes a parse tree until it is in suitable form to
* be converted to the more canonical form. This is done as a series of
* passes, each contained in their own module below.
*/
use grammar::parse_tree as pt;
use grammar::repr as r;
pub type NormResult<T> = Result<T, NormError>;
#[derive(C... | (grammar: pt::Grammar, validate: bool) -> NormResult<r::Grammar> {
if validate { try!(prevalidate::validate(&grammar)); }
let grammar = try!(resolve::resolve(grammar));
let grammar = try!(macro_expand::expand_macros(grammar));
let grammar = try!(token_check::validate(grammar));
let types = try!(tyin... | normalize_helper | identifier_name |
mod.rs | /*!
* Normalization processes a parse tree until it is in suitable form to
* be converted to the more canonical form. This is done as a series of
* passes, each contained in their own module below.
*/
use grammar::parse_tree as pt;
use grammar::repr as r;
pub type NormResult<T> = Result<T, NormError>;
#[derive(C... |
fn normalize_helper(grammar: pt::Grammar, validate: bool) -> NormResult<r::Grammar> {
if validate { try!(prevalidate::validate(&grammar)); }
let grammar = try!(resolve::resolve(grammar));
let grammar = try!(macro_expand::expand_macros(grammar));
let grammar = try!(token_check::validate(grammar));
... | {
normalize_helper(grammar, false)
} | identifier_body |
messages.py | # Copyright (C) 2007-2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at you... | """The representation of an email message."""
message_id = Attribute("""The message's Message-ID header.""")
message_id_hash = Attribute("""The unique SHA1 hash of the message.""")
path = Attribute("""The filesystem path to the message object.""") | identifier_body | |
messages.py | # Copyright (C) 2007-2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at you... | (message_id_hash):
"""Return the message with the matching X-Message-ID-Hash.
:param message_id_hash: The X-Message-ID-Hash header contents to
search for.
:returns: The message, or None if no matching message was found.
"""
def delete_message(message_id):
... | get_message_by_hash | identifier_name |
messages.py | # Copyright (C) 2007-2012 by the Free Software Foundation, Inc.
#
# This file is part of GNU Mailman.
#
# GNU Mailman is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at you... | internet facing interface for the message store. This can be considered a
globally unique URI to the message.
For example, a message with the following headers:
Message-ID: <87myycy5eh.fsf@uwakimon.sk.tsukuba.ac.jp>
Date: Wed, 04 Jul 2007 16:49:58 +0900
List-Archive: http://archive.example.co... | X-Message-ID-Hash header can be used to retrieve the message from the | random_line_split |
trainer.rs | extern crate rand;
use super::super::Grid;
use super::*;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use rand::Rng;
pub fn evaluate_parallel(
n_threads: i32,
problems: &Vec<Grid<Clue>>,
param: EvaluatorParam,
) -> Vec<Option<f64>> {
let res = Arc::new(Mutex::new(vec![None; problems.le... | }
let ret = res.lock().unwrap().clone();
ret
}
pub fn evaluate_score(score: &[Option<f64>], expected: &[f64]) -> f64 {
let mut sx = 0.0f64;
let mut sxx = 0.0f64;
let mut sy = 0.0f64;
let mut sxy = 0.0f64;
let mut n = 0.0f64;
for i in 0..score.len() {
if let Some(x) = score[... | th.join().unwrap(); | random_line_split |
trainer.rs | extern crate rand;
use super::super::Grid;
use super::*;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use rand::Rng;
pub fn | (
n_threads: i32,
problems: &Vec<Grid<Clue>>,
param: EvaluatorParam,
) -> Vec<Option<f64>> {
let res = Arc::new(Mutex::new(vec![None; problems.len()]));
let checked = Arc::new(Mutex::new(0));
let mut threads = vec![];
for _ in 0..n_threads {
let problems = problems.clone();
... | evaluate_parallel | identifier_name |
trainer.rs | extern crate rand;
use super::super::Grid;
use super::*;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use rand::Rng;
pub fn evaluate_parallel(
n_threads: i32,
problems: &Vec<Grid<Clue>>,
param: EvaluatorParam,
) -> Vec<Option<f64>> {
let res = Arc::new(Mutex::new(vec![None; problems.le... | rng.shuffle(&mut move_cand);
for mv in move_cand {
let mut param2 = param;
*param_value(&mut param2, mv.0) += mv.1;
let score2 = evaluate_score(&evaluate_parallel(n_threads, problems, param2), expected);
if current_score > score2 || rng.gen::<f64>() < (... | {
let n_threads = 10;
let mut param = start;
let mut current_score =
evaluate_score(&evaluate_parallel(n_threads, problems, param), expected);
let mut temp = 0.001f64;
let mut rng = rand::thread_rng();
for _ in 0..500 {
let mut move_cand = vec![];
for i in 0..10 {
... | identifier_body |
to_css.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cg;
use darling::{Error, FromMetaItem};
use quote::Tokens;
use syn::{self, DeriveInput, Ident};
use synstructu... | #[derive(Default, FromDeriveInput)]
struct CssInputAttrs {
derive_debug: bool,
function: Option<Function>,
comma: bool,
}
#[darling(attributes(css), default)]
#[derive(Default, FromVariant)]
pub struct CssVariantAttrs {
pub function: Option<Function>,
pub iterable: bool,
pub comma: bool,
pu... |
#[darling(attributes(css), default)] | random_line_split |
to_css.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cg;
use darling::{Error, FromMetaItem};
use quote::Tokens;
use syn::{self, DeriveInput, Ident};
use synstructu... | (name: &str) -> Result<Self, Error> {
let name = syn::parse_ident(name).map_err(Error::custom)?;
Ok(Self { name: Some(name) })
}
}
| from_string | identifier_name |
prefixSumComputer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public insertValues(insertIndex: number, insertValues: Uint32Array): void {
insertIndex = toUint32(insertIndex);
const oldValues = this.values;
const oldPrefixSum = this.prefixSum;
const insertValuesLen = insertValues.length;
if (insertValuesLen === 0) {
return;
}
this.values = new Uint32Array(old... | {
return this.values.length;
} | identifier_body |
prefixSumComputer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | public getTotalValue(): number {
if (this.values.length === 0) {
return 0;
}
return this.getAccumulatedValue(this.values.length - 1);
}
public getAccumulatedValue(index: number): number {
if (index < 0) {
return 0;
}
index = toUint32(index);
if (index <= this.prefixSumValidIndex) {
return t... | if (this.prefixSumValidIndex >= 0) {
this.prefixSum.set(oldPrefixSum.subarray(0, this.prefixSumValidIndex + 1));
}
}
| random_line_split |
prefixSumComputer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): number {
if (this.values.length === 0) {
return 0;
}
return this.getAccumulatedValue(this.values.length - 1);
}
public getAccumulatedValue(index: number): number {
if (index < 0) {
return 0;
}
index = toUint32(index);
if (index <= this.prefixSumValidIndex) {
return this.prefixSum[index];... | getTotalValue | identifier_name |
prefixSumComputer.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
if (index >= this.values.length) {
index = this.values.length - 1;
}
for (let i = startIndex; i <= index; i++) {
this.prefixSum[i] = this.prefixSum[i - 1] + this.values[i];
}
this.prefixSumValidIndex = Math.max(this.prefixSumValidIndex, index);
return this.prefixSum[index];
}
public getIndexOf(a... | {
this.prefixSum[0] = this.values[0];
startIndex++;
} | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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 applicable law or... | "Table",
"UpdateRowRequest",
"Workspace",
"View",
) | "LookupDetails",
"RelationshipDetails",
"Row", | random_line_split |
PointerData.ts | /*
* Point
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* 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
*... | implements IPoint
{
/**
* X position.
* @property x
* @type Number
**/
public x:number;
/**
* Y position.
* @property y
* @type number
**/
public y:number;
/**
* @property inBounds
* @type boolean
*/
public inBounds:boolean = false;
public target:any = null;
posEvtObj:any = null;
rawX ... | PointerData | identifier_name |
PointerData.ts | /*
* Point
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* 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
*... | */
import IPoint from "./../../interface/IVector2";
import NumberUtil from "./../../util/NumberUtil";
/**
* @module easelts
*/
/**
* Represents a point on a 2 dimensional x / y coordinate system.
*
* <h4>Example</h4>
*
* var point = new createjs.Point(0, 100);
*
* @class Point
* @param {Number} [x=0]... | random_line_split | |
input-tests.rs | extern crate tiny_http;
use std::io::{Read, Write};
use std::sync::mpsc;
use std::net::Shutdown;
use std::thread;
#[allow(dead_code)]
mod support;
#[test]
fn basic_string_input() {
let (server, client) = support::new_one_server_one_client();
{
let mut client = client;
(write!(client, "GET / ... |
#[test]
fn expect_100_continue() {
let (server, client) = support::new_one_server_one_client();
let mut client = client;
(write!(client, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nExpect: 100-continue\r\nContent-Type: text/plain; charset=utf8\r\nContent-Length: 5\r\n\r\n")).unwrap();
... | {
let (server, client) = support::new_one_server_one_client();
{
let mut client = client;
(write!(client, "GET / HTTP/1.1\r\nHost: localhost\r\nContent-Type: text/plain; charset=utf8\r\nContent-Length: 3\r\n\r\nhello")).unwrap();
}
let mut request = server.recv().unwrap();
let mut... | identifier_body |
input-tests.rs | extern crate tiny_http;
use std::io::{Read, Write};
use std::sync::mpsc;
use std::net::Shutdown;
use std::thread;
#[allow(dead_code)]
mod support;
#[test]
fn basic_string_input() {
let (server, client) = support::new_one_server_one_client();
{
let mut client = client;
(write!(client, "GET / ... | () {
let (server, client) = support::new_one_server_one_client();
let mut client = client;
(write!(client, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nExpect: 100-continue\r\nContent-Type: text/plain; charset=utf8\r\nContent-Length: 5\r\n\r\n")).unwrap();
client.flush().unwrap();
le... | expect_100_continue | identifier_name |
input-tests.rs | extern crate tiny_http;
use std::io::{Read, Write};
use std::sync::mpsc;
use std::net::Shutdown;
use std::thread;
#[allow(dead_code)]
mod support;
#[test]
fn basic_string_input() {
let (server, client) = support::new_one_server_one_client();
{
let mut client = client;
(write!(client, "GET / ... | fn unsupported_expect_header() {
let mut client = support::new_client_to_hello_world_server();
(write!(client, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nExpect: 189-dummy\r\nContent-Type: text/plain; charset=utf8\r\n\r\n")).unwrap();
// client.set_keepalive(Some(3)).unwrap(); FIXME: reena... | #[test] | random_line_split |
sim_plot.py | import sys
from ocelot.adaptors.genesis import *
from ocelot.cpbd.elements import Element, Quadrupole, RBend, Drift, Undulator
from ocelot import MagneticLattice
from ocelot.cpbd.beam import Beam
from ocelot.cpbd.optics import *
import numpy.fft as fft
from sim_info import SimInfo, RunInfo
#params = {'backend': 'ps... |
ax1.plot(t, power_av, 'b')
ax2.plot(x, spec_av, 'b')
plt.show() | random_line_split | |
sim_plot.py | import sys
from ocelot.adaptors.genesis import *
from ocelot.cpbd.elements import Element, Quadrupole, RBend, Drift, Undulator
from ocelot import MagneticLattice
from ocelot.cpbd.beam import Beam
from ocelot.cpbd.optics import *
import numpy.fft as fft
from sim_info import SimInfo, RunInfo
#params = {'backend': 'ps... |
p2, = ax2.plot(x, y, color='black', alpha = 0.4)
ax2.set_xlim(x[0],x[-1])
ax3.set_xlim(x[0],x[-1])
x_ticks = ax2.get_xticks()[1:]
x2 = h*c/(x_ticks) * 1.e9 # coordinates in nm
ax3.set_xticks(x_ticks)
ax3.set_xticklabels(["%.4f" % z for z in x2])
ax1.plot(t, power_av, 'b')
ax2.p... | spec_av += y / len(runs) | conditional_block |
diagnostics.rs | /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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![a... | E0284, // cannot resolve type
E0285, // overflow evaluation builtin bounds
E0296, // malformed recursion limit attribute
E0297, // refutable pattern in for loop binding
E0298, // mismatched types between arms
E0299, // mismatched types between arms
E0300, // unexpanded macro
E0301, // ca... | E0282, // unable to infer enough type information about
E0283, // cannot resolve type | random_line_split |
comment_controller.js | var models = require('../models/models.js');
exports.ownershipRequired = function (req, res, next) {
models.Quiz.find({
where: {
id: Number(req.comment.QuizId)
}
}).then(function (quiz) {
if (quiz) {
var objQuizOwner = quiz.UserId;
var logUser = req.session.user.id;
var isAdmin = req.session.user.i... | req.comment.save({ fields: ["publicado"] }).then(function () {
res.redirect('/quizes/' + req.params.quizId);
}).catch(function (error) { next(error) });
}; | random_line_split | |
comment_controller.js | var models = require('../models/models.js');
exports.ownershipRequired = function (req, res, next) {
models.Quiz.find({
where: {
id: Number(req.comment.QuizId)
}
}).then(function (quiz) {
if (quiz) {
var objQuizOwner = quiz.UserId;
var logUser = req.session.user.id;
var isAdmin = req.session.user.i... | else {
comment.save().then(
function () { res.redirect('/quizes/' + req.params.quizId); });
}
}
).catch(function (error) { next(error); });
};
exports.publish = function (req, res) {
req.comment.publicado = true;
req.comment.save({ fields: ["publicado"] }).then(function () {
res.redirect('/quizes/... | {
res.render('comments/new.ejs', { comment: comment, errors: err.errors });
} | conditional_block |
main.rs | extern crate num;
use num::traits::{PrimInt, Zero};
fn | <T: PrimInt + Zero>(cs: &[T], x: T) -> T {
cs.iter()
.rev()
.fold(Zero::zero(), |acc: T, c| (acc * x) + (*c))
}
fn main() {
println!("{}", horner(&[-19i32, 7, -4, 6], 3i32)); // 128
}
#[cfg(test)]
mod tests {
use super::horner;
#[test]
fn test() {
assert_eq!(horner(&[-19i3... | horner | identifier_name |
main.rs | extern crate num;
use num::traits::{PrimInt, Zero};
fn horner<T: PrimInt + Zero>(cs: &[T], x: T) -> T {
cs.iter()
.rev()
.fold(Zero::zero(), |acc: T, c| (acc * x) + (*c))
}
fn main() {
println!("{}", horner(&[-19i32, 7, -4, 6], 3i32)); // 128
}
#[cfg(test)]
mod tests {
use super::horner;... | assert_eq!(horner(&[-19i32, 7, -4, 6], 3i32), 128);
assert_eq!(horner(&[-1i32, 7, -4, 6], 0i32), -1);
assert_eq!(horner(&[-0i32, 3], 100i32), 300);
assert_eq!(horner(&[-20i32, 7, 1], 10i32), 150);
assert_eq!(horner(&[-19i32, 7, -4, 0], 5i32), -84);
}
} | fn test() { | random_line_split |
main.rs | extern crate num;
use num::traits::{PrimInt, Zero};
fn horner<T: PrimInt + Zero>(cs: &[T], x: T) -> T |
fn main() {
println!("{}", horner(&[-19i32, 7, -4, 6], 3i32)); // 128
}
#[cfg(test)]
mod tests {
use super::horner;
#[test]
fn test() {
assert_eq!(horner(&[-19i32, 7, -4, 6], 3i32), 128);
assert_eq!(horner(&[-1i32, 7, -4, 6], 0i32), -1);
assert_eq!(horner(&[-0i32, 3], 100i32)... | {
cs.iter()
.rev()
.fold(Zero::zero(), |acc: T, c| (acc * x) + (*c))
} | identifier_body |
chain_workflow_generator.py | import random
import numpy
from graph_diff.nirvana_object_model.workflow import Workflow
from .standard_workflow_generator import StandardWorkflowGenerator
class ChainWorkflowGenerator(StandardWorkflowGenerator):
"""Generator for chained workflows"""
def __init__(self):
super().__init__()
s... |
for _ in range(0, chain_number):
prev_block = self.types_of_block[0]
prev_number = workflow.add_block(prev_block)
for new_block in self.types_of_block[1:]:
new_number = workflow.add_block(new_block)
workflow.add_connection_by_execution(prev_b... | workflow = Workflow()
chain_number = numpy.random.geometric(p=1 / self.chain_number) + 1 | random_line_split |
chain_workflow_generator.py | import random
import numpy
from graph_diff.nirvana_object_model.workflow import Workflow
from .standard_workflow_generator import StandardWorkflowGenerator
class ChainWorkflowGenerator(StandardWorkflowGenerator):
"""Generator for chained workflows"""
def __init__(self):
super().__init__()
s... |
from_block = self.types_of_block[from_block_num]
to_block = self.types_of_block[to_block_num]
workflow.add_connection_by_execution(from_block, from_num, to_block, to_num)
return workflow
def generate_blocks(self,
min_block_num=8,
... | from_block_num, to_block_num = to_block_num, from_block_num
from_num, to_num = to_num, from_num | conditional_block |
chain_workflow_generator.py | import random
import numpy
from graph_diff.nirvana_object_model.workflow import Workflow
from .standard_workflow_generator import StandardWorkflowGenerator
class ChainWorkflowGenerator(StandardWorkflowGenerator):
"""Generator for chained workflows"""
def __init__(self):
|
def generate_workflow(self) -> Workflow:
"""
Generates workflow by set a given set of blocks.
If types not given they may be generated.
chain_number is a number of the chains, distribution is geometric
with settable expectation.
Then chain_number chains are created... | super().__init__()
self.chain_number = None | identifier_body |
chain_workflow_generator.py | import random
import numpy
from graph_diff.nirvana_object_model.workflow import Workflow
from .standard_workflow_generator import StandardWorkflowGenerator
class ChainWorkflowGenerator(StandardWorkflowGenerator):
"""Generator for chained workflows"""
def __init__(self):
super().__init__()
s... | (self,
min_block_num=8,
max_block_num=12,
chain_number=20,
min_input_output_number=0,
max_input_output_number=3,
min_key_value_number=0,
max_key_value_n... | generate_blocks | identifier_name |
resolver.js | "use strict";
var Resolver = require("enhanced-resolve/lib/Resolver");
var SyncNodeJsInputFileSystem = require("enhanced-resolve/lib/SyncNodeJsInputFileSystem");
var CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem");
var UnsafeCachePlugin = require("enhanced-resolve/lib/UnsafeCachePlugin");... | else if (Array.isArray(root)) {
return function () {
root.forEach(function (root) {
this.apply(new ModulesInRootPlugin(name, root));
}, this);
};
}
return function () {};
}
function makeResolver(options) {
var fileSystem = new CachedInputFileSystem(ne... | {
return new ModulesInRootPlugin(name, root);
} | conditional_block |
resolver.js | "use strict";
var Resolver = require("enhanced-resolve/lib/Resolver");
var SyncNodeJsInputFileSystem = require("enhanced-resolve/lib/SyncNodeJsInputFileSystem");
var CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem");
var UnsafeCachePlugin = require("enhanced-resolve/lib/UnsafeCachePlugin");... | //# sourceMappingURL=resolver.js.map | random_line_split | |
resolver.js | "use strict";
var Resolver = require("enhanced-resolve/lib/Resolver");
var SyncNodeJsInputFileSystem = require("enhanced-resolve/lib/SyncNodeJsInputFileSystem");
var CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem");
var UnsafeCachePlugin = require("enhanced-resolve/lib/UnsafeCachePlugin");... | (options) {
var fileSystem = new CachedInputFileSystem(new SyncNodeJsInputFileSystem(), 60000);
var resolver = new Resolver(fileSystem);
resolver.apply(new UnsafeCachePlugin(options.resolve.unsafeCache), options.resolve.packageAlias ? new DirectoryDescriptionFileFieldAliasPlugin("package.json", options.reso... | makeResolver | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.