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 |
|---|---|---|---|---|
fixunoproj.js | var fusepm = require('./fusepm');
module.exports = fixunoproj;
function fixunoproj () | }
else {
inc = ['./*.ux', './*.uno', './*.uxl'];
}
if (!obj.Version) {
obj.Version = "0.0.0";
}
obj.Includes = inc;
fusepm.save_unoproj(fn, obj);
}).catch(function (e) {
console.log(e);
});
} | {
var fn = fusepm.local_unoproj(".");
fusepm.read_unoproj(fn).then(function (obj) {
var inc = [];
if (obj.Includes) {
var re = /\//;
for (var i=0; i<obj.Includes.length;i++) {
if (obj.Includes[i] === '*') {
inc.push('./*.ux');
inc.push('./*.uno');
inc.push('./*.uxl');
}
else if (!... | identifier_body |
test_metadata_editing.py | import galaxy.model
from galaxy.model.orm import *
from base.twilltestcase import TwillTestCase
class TestMetadataEdit( TwillTestCase ):
def test_00_metadata_edit( self ):
"""test_metadata_edit: Testing metadata editing"""
self.logout()
self.login( email='test@bx.psu.edu' )
self.ne... |
latest_hda.dataset.refresh()
self.check_history_for_string( '1.bed' )
self.check_metadata_for_string( '1.bed uploaded file unspecified (\?) chromCol value="1" selected endCol value="3" is_strandCol value="true" checked', hid=1 )
"""test editing attributes"""
self.edit_hda_attrib... | dp.delete()
dp.flush() | conditional_block |
test_metadata_editing.py | import galaxy.model
from galaxy.model.orm import *
from base.twilltestcase import TwillTestCase
class | ( TwillTestCase ):
def test_00_metadata_edit( self ):
"""test_metadata_edit: Testing metadata editing"""
self.logout()
self.login( email='test@bx.psu.edu' )
self.new_history( name='Test Metadata Edit' )
global history1
history1 = galaxy.model.History.query() \
... | TestMetadataEdit | identifier_name |
test_metadata_editing.py | import galaxy.model
from galaxy.model.orm import *
from base.twilltestcase import TwillTestCase
class TestMetadataEdit( TwillTestCase ):
def test_00_metadata_edit( self ):
| """test editing attributes"""
self.edit_hda_attribute_info( hda_id=str( latest_hda.id ),
new_name='Testdata',
new_info="Uploaded my file",
new_dbkey='hg16',
... | """test_metadata_edit: Testing metadata editing"""
self.logout()
self.login( email='test@bx.psu.edu' )
self.new_history( name='Test Metadata Edit' )
global history1
history1 = galaxy.model.History.query() \
.order_by( desc( galaxy.model.History.table.c.create_time ) )... | identifier_body |
test_metadata_editing.py | import galaxy.model
from galaxy.model.orm import *
from base.twilltestcase import TwillTestCase
class TestMetadataEdit( TwillTestCase ):
def test_00_metadata_edit( self ):
"""test_metadata_edit: Testing metadata editing"""
self.logout()
self.login( email='test@bx.psu.edu' )
self.ne... | self.convert_format( hda_id=str( latest_hda.id ), target_type='gff' )
self.check_metadata_for_string( '"gff" selected="yes"', hid=1 )
"""test changing data type"""
self.change_datatype( hda_id=str( latest_hda.id ), datatype='gff3' )
self.check_metadata_for_string( 'gff3', hid=1 )... | """test Auto-detecting attributes"""
self.auto_detect_metadata( hda_id=str( latest_hda.id ) )
self.check_metadata_for_string('Testdata bed Uploaded my file hg16 "bed" selected="yes" "startCol" value="2" selected', hid=1 )
"""test converting formats""" | random_line_split |
monica.py | # !/bin/python
# -*- coding: latin-1 -*-
# Copyright (C) 2009-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your opt... |
# ======================================================= insert_cylinder
def insert_cylinder (plaque, nx, ny) :
hexa = plaque.getHexaIJK (nx, ny, 0)
xmin = 666 ; ymin = xmin ; zmin = xmin
xmax = -666 ; ymax = xmax ; zmax = xmax
tabv1 = []
for nv in range (8) :
node = he... | dmin = 1e+16
result = None
[ox, oy, oz] = get_center (quad)
nbre = grid.countQuad ()
for nro in range (nbre) :
q1 = grid.getQuad (nro)
if q1 != None :
[px, py, pz] = get_center (q1)
d2 = carre(px-ox) + carre(py-oy) + carre(pz-oz)
if (d2 < dmin) :
... | identifier_body |
monica.py | # !/bin/python
# -*- coding: latin-1 -*-
# Copyright (C) 2009-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your opt... |
print quad.getName () , px, py, pz, " -> ", result.getName()
return result
# ======================================================= insert_cylinder
def insert_cylinder (plaque, nx, ny) :
hexa = plaque.getHexaIJK (nx, ny, 0)
xmin = 666 ; ymin = xmin ; zmin = xmin
xmax = -666 ; ym... | result = q1
dmin = d2 | conditional_block |
monica.py | # !/bin/python
# -*- coding: latin-1 -*-
# Copyright (C) 2009-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your opt... | q1 = grid.getQuad (nro)
if q1 != None :
[px, py, pz] = get_center (q1)
d2 = carre(px-ox) + carre(py-oy) + carre(pz-oz)
if (d2 < dmin) :
result = q1
dmin = d2
print quad.getName () , px, py, pz, " -> ", result.getName()
return res... | dmin = 1e+16
result = None
[ox, oy, oz] = get_center (quad)
nbre = grid.countQuad ()
for nro in range (nbre) : | random_line_split |
monica.py | # !/bin/python
# -*- coding: latin-1 -*-
# Copyright (C) 2009-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your opt... | (grid, vertex) :
nbre = grid.countVertex()
dmin = 1e+6
result = None
px = vertex.getX()
py = vertex.getY()
pz = vertex.getZ()
for nro in range (nbre) :
v1 = grid.getVertex (nro)
d2 = carre(px-v1.getX()) + carre(py-v1.getY()) + carre(pz-v1.getZ())
if (d2 < dmin) :
... | nearest | identifier_name |
editor.js | /*
* Copyright (C) 2016 Daniel Hsing
* 2016 Ben Ockmore
* 2016 Max Prettyjohns
* 2016 Sean Burke
*
* This program 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 ... | (props) {
const {tabActive, editor, children} = props;
return (
<div>
<Row>
<Col md={12}>
{editor.title ?
<div>
<a
href=" "
title={editor.title.description}
>
<h1>
{`${editor.title.title} ${editor.name}`}
</h1>
</a>
</div> :
... | EditorContainer | identifier_name |
editor.js | /*
* Copyright (C) 2016 Daniel Hsing
* 2016 Ben Ockmore
* 2016 Max Prettyjohns
* 2016 Sean Burke
*
* This program 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 ... | {children}
</div>
);
}
EditorContainer.displayName = 'EditorContainer';
EditorContainer.propTypes = {
children: PropTypes.node.isRequired,
editor: PropTypes.shape({
id: PropTypes.number,
name: PropTypes.string,
title: PropTypes.object
}).isRequired,
tabActive: PropTypes.number.isRequired
};
export def... | </Row> | random_line_split |
editor.js | /*
* Copyright (C) 2016 Daniel Hsing
* 2016 Ben Ockmore
* 2016 Max Prettyjohns
* 2016 Sean Burke
*
* This program 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 ... | </h1>
}
</Col>
</Row>
<Row>
<Col md={12}>
<Nav bsStyle="tabs">
<NavItem
active={tabActive === 0}
href={`/editor/${editor.id}`}
>
Profile
</NavItem>
<NavItem
active={tabActive === 1}
href={`/editor/${editor.id}/revisions`}
>
... | {
const {tabActive, editor, children} = props;
return (
<div>
<Row>
<Col md={12}>
{editor.title ?
<div>
<a
href=" "
title={editor.title.description}
>
<h1>
{`${editor.title.title} ${editor.name}`}
</h1>
</a>
</div> :
<h1>
... | identifier_body |
conftest.py | import json
import os
from errata_tool import ErrataConnector, Erratum
from errata_tool.products import ProductList
import requests
import pytest
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
FIXTURES_DIR = os.path.join(TESTS_DIR, 'fixtures')
class MockResponse(object):
status_code = 200
encoding = ... | (self):
""" Return path to our static fixture file. """
return self.url.replace('https://errata.devel.redhat.com/',
os.path.join(FIXTURES_DIR,
'errata.devel.redhat.com/'))
def json(self):
try:
with open... | _fixture | identifier_name |
conftest.py | from errata_tool import ErrataConnector, Erratum
from errata_tool.products import ProductList
import requests
import pytest
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
FIXTURES_DIR = os.path.join(TESTS_DIR, 'fixtures')
class MockResponse(object):
status_code = 200
encoding = 'utf-8'
headers = ... | import json
import os | random_line_split | |
conftest.py | import json
import os
from errata_tool import ErrataConnector, Erratum
from errata_tool.products import ProductList
import requests
import pytest
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
FIXTURES_DIR = os.path.join(TESTS_DIR, 'fixtures')
class MockResponse(object):
| raise
@property
def text(self):
""" Return contents of our static fixture file. """
try:
with open(self._fixture) as fp:
return fp.read()
except IOError:
print('Try ./new-fixture.sh %s' % self.url)
raise
class RequestRec... | status_code = 200
encoding = 'utf-8'
headers = {'content-type': 'application/json; charset=utf-8'}
def raise_for_status(self):
pass
@property
def _fixture(self):
""" Return path to our static fixture file. """
return self.url.replace('https://errata.devel.redhat.com/',
... | identifier_body |
urls.py | # Copyright (C) 2010-2014 GRNET S.A.
#
# This program 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 your option) any later version.
#
# This program is distributed i... | """
Protect all url patterns from csrf attacks.
"""
_patterns = patterns(*args, **kwargs)
for entry in _patterns:
_patch_resolver(entry)
return _patterns | identifier_body | |
urls.py | # Copyright (C) 2010-2014 GRNET S.A.
#
# This program 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 your option) any later version.
#
# This program is distributed i... | # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.core import urlresolvers
from django.views.decorators import csrf
from django.conf.urls import patterns
def _patch_pattern(regex_pattern):
"""
Patch pattern ... | random_line_split | |
urls.py | # Copyright (C) 2010-2014 GRNET S.A.
#
# This program 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 your option) any later version.
#
# This program is distributed i... | (*args, **kwargs):
"""
Protect all url patterns from csrf attacks.
"""
_patterns = patterns(*args, **kwargs)
for entry in _patterns:
_patch_resolver(entry)
return _patterns
| api_patterns | identifier_name |
urls.py | # Copyright (C) 2010-2014 GRNET S.A.
#
# This program 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 your option) any later version.
#
# This program is distributed i... |
return _patterns
| _patch_resolver(entry) | conditional_block |
WorkflowEventModel.tsx | import * as React from 'react'
import { ValueLine, TypeContext, EntityDetail, RenderEntity } from '@framework/Lines'
import { WorkflowEventModel, WorkflowEventTaskModel, WorkflowEventTaskActionEval, WorkflowEventTaskConditionEval, WorkflowMessage, WorkflowEventType, TriggeredOn, WorkflowTimerEmbedded } from '../Signu... | (ctx: TypeContext<WorkflowEventModel>) {
if (!ctx.value.mainEntityType)
return <div className="alert alert-warning">{WorkflowMessage.ToUse0YouSouldSetTheWorkflow1.niceToString(ctx.niceName(e => e.task), ctx.niceName(e => e.mainEntityType))}</div>;
return (
<div>
<ValueLine ctx={ctx.su... | renderTaskModel | identifier_name |
WorkflowEventModel.tsx | import * as React from 'react'
import { ValueLine, TypeContext, EntityDetail, RenderEntity } from '@framework/Lines'
import { WorkflowEventModel, WorkflowEventTaskModel, WorkflowEventTaskActionEval, WorkflowEventTaskConditionEval, WorkflowMessage, WorkflowEventType, TriggeredOn, WorkflowTimerEmbedded } from '../Signu... | });
ctx.value.modified = true;
}
}
forceUpdate();
}
function getTypeComboItems() {
const ctx = p.ctx;
return isTimer(ctx.value.type!) ?
[WorkflowEventType.value(ctx.value.type!)] :
WorkflowEventType.values().filter(a => !isTimer(a)).map(a => WorkflowEve... | if (!ctx.value.task) {
ctx.value.task = WorkflowEventTaskModel.New({
triggeredOn: "Always",
action: WorkflowEventTaskActionEval.New(),
| random_line_split |
WorkflowEventModel.tsx | import * as React from 'react'
import { ValueLine, TypeContext, EntityDetail, RenderEntity } from '@framework/Lines'
import { WorkflowEventModel, WorkflowEventTaskModel, WorkflowEventTaskActionEval, WorkflowEventTaskConditionEval, WorkflowMessage, WorkflowEventType, TriggeredOn, WorkflowTimerEmbedded } from '../Signu... |
function isConditional() {
return p.ctx.value.task!.triggeredOn != TriggeredOn.value("Always");
}
function isTimer(type: WorkflowEventType) {
return type == "BoundaryForkTimer" ||
type == "BoundaryInterruptingTimer" ||
type == "IntermediateTimer";
}
React.useEffect(loadTask... | {
return (p.ctx.value.type == "ScheduledStart");
} | identifier_body |
load.py | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 14:45:26 2017
@author: leonidas
"""
import numpy as np
import operator
def classify(inputPoint,dataSet,labels,k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inputPoint,(dataSetSize,1))-dataSet
sqDiffMat = pow(diffMat,2)
sqDistances = sqDi... |
return train_lables,train_data
def classnumCut(fileName):
return int(fileName[0]) | train_lables.append(i)
train_data[i*100+j,:] = mat_to_vect('train/%s/%s.txt' %( i,j )) | conditional_block |
load.py | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 14:45:26 2017
@author: leonidas
"""
import numpy as np
import operator
def classify(inputPoint,dataSet,labels,k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inputPoint,(dataSetSize,1))-dataSet
sqDiffMat = pow(diffMat,2)
sqDistances = sqDi... |
def load_train_data():
train_lables = []
size = 100
train_data = np.zeros((size*10,1024))
for i in range(10):
for j in range(size):
train_lables.append(i)
train_data[i*100+j,:] = mat_to_vect('train/%s/%s.txt' %( i,j ))
return train_lables,train_... | vect = []
data = open(filename)
for i in range(32):
temp = data.readline()
for j in range(32):
try:
vect.append(int(temp[j]))
except(ValueError):
print temp[j],'error',ValueError
return vect | identifier_body |
load.py | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 14:45:26 2017
@author: leonidas
"""
import numpy as np
import operator
def classify(inputPoint,dataSet,labels,k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inputPoint,(dataSetSize,1))-dataSet
sqDiffMat = pow(diffMat,2)
sqDistances = sqDi... | for i in range(10):
for j in range(size):
train_lables.append(i)
train_data[i*100+j,:] = mat_to_vect('train/%s/%s.txt' %( i,j ))
return train_lables,train_data
def classnumCut(fileName):
return int(fileName[0]) | train_lables = []
size = 100
train_data = np.zeros((size*10,1024)) | random_line_split |
load.py | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 14:45:26 2017
@author: leonidas
"""
import numpy as np
import operator
def classify(inputPoint,dataSet,labels,k):
dataSetSize = dataSet.shape[0]
diffMat = np.tile(inputPoint,(dataSetSize,1))-dataSet
sqDiffMat = pow(diffMat,2)
sqDistances = sqDi... | (filename):
vect = []
data = open(filename)
for i in range(32):
temp = data.readline()
for j in range(32):
try:
vect.append(int(temp[j]))
except(ValueError):
print temp[j],'error',ValueError
return vect
def load_train_data():
... | mat_to_vect | identifier_name |
cy.js | /**
* @license
* Copyright Google Inc. 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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n) {
if... | ],
[
['yb', 'yh'],
,
],
[
['S', 'Ll', 'M', 'M', 'I', 'G', 'S'], ['Sul', 'Llun', 'Maw', 'Mer', 'Iau', 'Gwen', 'Sad'],
[
'Dydd Sul', 'Dydd Llun', 'Dydd Mawrth', 'Dydd Mercher', 'Dydd Iau', 'Dydd Gwener',
'Dydd Sadwrn'
],
['Su', 'Ll', ... | ['yb', 'yh'], | random_line_split |
cy.js | /**
* @license
* Copyright Google Inc. 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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n) |
export default [
'cy',
[
['b', 'h'],
['yb', 'yh'],
],
[
['yb', 'yh'],
,
],
[
['S', 'Ll', 'M', 'M', 'I', 'G', 'S'], ['Sul', 'Llun', 'Maw', 'Mer', 'Iau', 'Gwen', 'Sad'],
[
'Dydd Sul', 'Dydd Llun', 'Dydd Mawrth', 'Dydd Mercher', 'Dydd Iau... | {
if (n === 0)
return 0;
if (n === 1)
return 1;
if (n === 2)
return 2;
if (n === 3)
return 3;
if (n === 6)
return 4;
return 5;
} | identifier_body |
cy.js | /**
* @license
* Copyright Google Inc. 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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function | (n) {
if (n === 0)
return 0;
if (n === 1)
return 1;
if (n === 2)
return 2;
if (n === 3)
return 3;
if (n === 6)
return 4;
return 5;
}
export default [
'cy',
[
['b', 'h'],
['yb', 'yh'],
],
[
['yb', 'yh'],
,
... | plural | identifier_name |
uds_split.rs | #![warn(rust_2018_idioms)]
#![cfg(feature = "full")]
#![cfg(unix)]
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::UnixStream;
/// Checks that `UnixStream` can be split into a read half and a write half using
/// `UnixStream::split` and `UnixStream::split_mut`.
///
/// Verifies th... | (
read: &mut (dyn AsyncRead + Unpin),
write: &mut (dyn AsyncWrite + Unpin),
input: &[u8],
) -> std::io::Result<Vec<u8>> {
write.write_all(input).await?;
write.shutdown().await?;
let mut output = Vec::new();
read.read_to_end(&mut output).await?;
Ok(output)
}
| send_recv_all | identifier_name |
uds_split.rs | #![warn(rust_2018_idioms)]
#![cfg(feature = "full")]
#![cfg(unix)]
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::UnixStream;
/// Checks that `UnixStream` can be split into a read half and a write half using
/// `UnixStream::split` and `UnixStream::split_mut`.
///
/// Verifies th... | send_recv_all(&mut a_read, &mut a_write, b"A"),
send_recv_all(&mut b_read, &mut b_write, b"B"),
)
.await?;
assert_eq!(a_response, b"B");
assert_eq!(b_response, b"A");
Ok(())
}
async fn send_recv_all(
read: &mut (dyn AsyncRead + Unpin),
write: &mut (dyn AsyncWrite + Unpin),... | let (mut b_read, mut b_write) = b.split();
let (a_response, b_response) = futures::future::try_join( | random_line_split |
uds_split.rs | #![warn(rust_2018_idioms)]
#![cfg(feature = "full")]
#![cfg(unix)]
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::UnixStream;
/// Checks that `UnixStream` can be split into a read half and a write half using
/// `UnixStream::split` and `UnixStream::split_mut`.
///
/// Verifies th... |
async fn send_recv_all(
read: &mut (dyn AsyncRead + Unpin),
write: &mut (dyn AsyncWrite + Unpin),
input: &[u8],
) -> std::io::Result<Vec<u8>> {
write.write_all(input).await?;
write.shutdown().await?;
let mut output = Vec::new();
read.read_to_end(&mut output).await?;
Ok(output)
}
| {
let (mut a, mut b) = UnixStream::pair()?;
let (mut a_read, mut a_write) = a.split();
let (mut b_read, mut b_write) = b.split();
let (a_response, b_response) = futures::future::try_join(
send_recv_all(&mut a_read, &mut a_write, b"A"),
send_recv_all(&mut b_read, &mut b_write, b"B"),
... | identifier_body |
big.py | # Copyright 2019 DeepMind Technologies Limited
#
# 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 agr... | (self, mixed_strategy, return_exp=False):
"""Return best response and its superiority over the current strategy.
Args:
mixed_strategy: np.ndarray (distribution over strategies)
return_exp: bool, whether to return how much best response exploits the
given mixed strategy (default is False)
... | best_response | identifier_name |
big.py | # Copyright 2019 DeepMind Technologies Limited
#
# 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 agr... | action 1: avoid bar
Args:
n: int, number of players
c: float, threshold for `crowded' as a fraction of number of players
B: float, payoff for going to a crowded bar
S: float, payoff for staying at home
G: float, payoff for going to an uncrowded bar
seed: seed for random numb... |
See Section 3.1, The El Farol Stage Game in
http://www.econ.ed.ac.uk/papers/id186_esedps.pdf
action 0: go to bar | random_line_split |
big.py | # Copyright 2019 DeepMind Technologies Limited
#
# 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 agr... |
def payoff_tensor(self):
return self.pt
def get_payoffs_for_strategies(self, policies):
"""Return vector of payoffs for all players given list of strategies.
Args:
policies: list of integers indexing strategies for each player
Returns:
np.array (length num players) of payoffs
"""... | return self.pt.shape[1:] | identifier_body |
big.py | # Copyright 2019 DeepMind Technologies Limited
#
# 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 agr... |
elif go_to_bar and crowded:
pt[idx] = B
else:
pt[idx] = S
super().__init__(pt, seed)
| pt[idx] = G | conditional_block |
customRouteSettings.js | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CodeZu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//-------------------------------------... | method: constants.verbs.DELETE,
url: '{+tenantPod}api/commerce/settings/general/customroutes'
})
}); | updateCustomRouteSettings: Client.method({
method: constants.verbs.PUT,
url: '{+tenantPod}api/commerce/settings/general/customroutes?responseFields={responseFields}'
}),
deleteCustomRouteSettings: Client.method({ | random_line_split |
qt_compat.py | """
Provide a common way to import Qt classes used by pytest-qt in a unique manner,
abstracting API differences between PyQt5 and PySide2/6.
.. note:: This module is not part of pytest-qt public API, hence its interface
may change between releases and users should not rely on it.
Based on from https://github.com/epag... |
self.qDebug = QtCore.qDebug
self.qWarning = QtCore.qWarning
self.qCritical = QtCore.qCritical
self.qFatal = QtCore.qFatal
if self.is_pyside:
self.Signal = QtCore.Signal
self.Slot = QtCore.Slot
self.Property = QtCore.Property
elif sel... | self.qInfo = None | conditional_block |
qt_compat.py | """
Provide a common way to import Qt classes used by pytest-qt in a unique manner,
abstracting API differences between PyQt5 and PySide2/6.
.. note:: This module is not part of pytest-qt public API, hence its interface
may change between releases and users should not rely on it.
Based on from https://github.com/epag... | _import(name)
return True
except ModuleNotFoundError as e:
self._import_errors[name] = str(e)
return False
# Note, not importing only the root namespace because when uninstalling from conda,
# the namespace can still be there.
... | def _can_import(name):
try: | random_line_split |
qt_compat.py | """
Provide a common way to import Qt classes used by pytest-qt in a unique manner,
abstracting API differences between PyQt5 and PySide2/6.
.. note:: This module is not part of pytest-qt public API, hence its interface
may change between releases and users should not rely on it.
Based on from https://github.com/epag... | (self, obj, *args, **kwargs):
# exec was a keyword in Python 2, so PySide2 (and also PySide6 6.0)
# name the corresponding method "exec_" instead.
#
# The old _exec() alias is removed in PyQt6 and also deprecated as of
# PySide 6.1:
# https://codereview.qt-project.org/c/p... | exec | identifier_name |
qt_compat.py | """
Provide a common way to import Qt classes used by pytest-qt in a unique manner,
abstracting API differences between PyQt5 and PySide2/6.
.. note:: This module is not part of pytest-qt public API, hence its interface
may change between releases and users should not rely on it.
Based on from https://github.com/epag... |
class _QtApi:
"""
Interface to the underlying Qt API currently configured for pytest-qt.
This object lazily loads all class references and other objects when the ``set_qt_api`` method
gets called, providing a uniform way to access the Qt classes.
"""
def __init__(self):
self._import... | """Think call so we can mock it during testing"""
return __import__(name) | identifier_body |
project-list.ts | import {RenameModal} from './rename-modal';
import {ContextMenu} from 'context-menu/context-menu';
import {withModal, ApplicationState, Project, Notification, SelectedProject,
ProjectManager, I18N, EventAggregator, Subscription, autoinject, bindable} from '../../shared/index';
/**
* The project list, shown at the l... |
@withModal(RenameModal)
renameProject() {}
select(index: number) {
if (this.projectGrid.ctx.vGridCollection.length > index) {
this.selectedProject.set(this.projectGrid.ctx.vGridCollection[index]);
this.projectGrid.ctx.vGridSelection.select(index);
this.projectGrid.ctx.vGridGenerator.upda... | {
let projRow = $(clickedElement).closest('.vGrid-row')[0];
let rowNr = $(projRow).attr('row');
this.select(parseInt(rowNr, 0));
builder
.addItem({ title: this.i18n.tr('rename-project'), onClick: () => this.renameProject() })
.addItem({ title: this.i18n.tr('remove-project'), onClick: () => thi... | identifier_body |
project-list.ts | import {RenameModal} from './rename-modal';
import {ContextMenu} from 'context-menu/context-menu';
import {withModal, ApplicationState, Project, Notification, SelectedProject,
ProjectManager, I18N, EventAggregator, Subscription, autoinject, bindable} from '../../shared/index';
/**
* The project list, shown at the l... | return;
}
await this.projectManager.removeProject(this.selectedProject.current);
if (this.projectManager.state.projects.length > 0) {
this.selectedProject.set(this.projectManager.state.projects[0]);
} else {
this.selectedProject.set(null);
}
}
detached() {
this.projectRe... | }
if (!confirm(this.i18n.tr('confirm-remove-project'))) { | random_line_split |
project-list.ts | import {RenameModal} from './rename-modal';
import {ContextMenu} from 'context-menu/context-menu';
import {withModal, ApplicationState, Project, Notification, SelectedProject,
ProjectManager, I18N, EventAggregator, Subscription, autoinject, bindable} from '../../shared/index';
/**
* The project list, shown at the l... | else {
// select first row
this.select(0);
}
this.contextMenu.attach(this.gridDiv, (builder, clickedElement) => this.contextMenuActivated(builder, clickedElement));
});
}
contextMenuActivated(builder, clickedElement) {
let projRow = $(clickedElement).closest('.vGrid-row')[0];
... | {
let index = this.state.projects.findIndex(x => x.path === this.state.selectedProjectPath);
if (index > -1) {
this.select(index);
}
} | conditional_block |
project-list.ts | import {RenameModal} from './rename-modal';
import {ContextMenu} from 'context-menu/context-menu';
import {withModal, ApplicationState, Project, Notification, SelectedProject,
ProjectManager, I18N, EventAggregator, Subscription, autoinject, bindable} from '../../shared/index';
/**
* The project list, shown at the l... | {
@bindable disabled = false;
projectRemoved: Subscription;
projectAdded: Subscription;
gridDiv: Element;
projectGrid;
// keeps the index of the last selected row
lastSelectedRow = 0;
constructor(private state: ApplicationState,
private notification: Notification,
private p... | ProjectList | identifier_name |
ofrefsofrects.rs | !(a.is_some());
assert!(!a.is_none());
// Match is the most basic way of getting at an option.
// Note that x is now &Rect automatically, so we do not need 'ref x'.
match a {
Some(x) => println!("MATCH: x (from a) = {}. x is of type &Rect.", x),
None => panic!("a should not be None")
... | () {
// This is quite simple, but there is a wrinkle.
let r = Rect::demo();
let a = Some(&r);
let b : Option<&Rect> = None;
// For 'or', both options must be of the same type.
let c = a.or(b).unwrap();
assert_eq!(c.title, "first demo");
// Reset.
let a = Some(&r);
let b : Opti... | demo_logical_or_and_combinators | identifier_name |
ofrefsofrects.rs | !(a.is_some());
assert!(!a.is_none());
// Match is the most basic way of getting at an option.
// Note that x is now &Rect automatically, so we do not need 'ref x'.
match a {
Some(x) => println!("MATCH: x (from a) = {}. x is of type &Rect.", x),
None => panic!("a should not be None")
... | let x = a.unwrap_or_else(|| &r2);
assert!(x.title == "first demo");
// Let's make a None.
let a : Option<&Rect> = None;
let x = a.unwrap_or(&r2);
assert!(x.title == "second demo");
// let a : Option<&Rect> = None;
// let x = a.unwrap_or_default(); // Type needs to implement the De... | {
println!(">>> demo_unwrap");
let r = Rect::demo();
let r2 = Rect::demo2();
let a = Some(&r);
let x = a.unwrap();
println!("x = {}", x);
// These are all no-ops because is a Some.
let a = Some(&r);
let x = a.unwrap_or(&r2);
assert!(x.title == "first demo");
// Won't compi... | identifier_body |
ofrefsofrects.rs | !(a.is_some()); | match a {
Some(x) => println!("MATCH: x (from a) = {}. x is of type &Rect.", x),
None => panic!("a should not be None")
}
// If let is equivalent to a match where we do nothing in the None.
// Because x is automatically a borrow, both of these compile fine.
if let Some(x) = a {
... | assert!(!a.is_none());
// Match is the most basic way of getting at an option.
// Note that x is now &Rect automatically, so we do not need 'ref x'. | random_line_split |
mod.rs | // Copyright 2016 Alexander Reece
//
// 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... | ,
_ => Err(Error::ExpectedEnd),
}
}
}
impl<'a> From<Constant<'a>> for Child<'a> {
fn from(child: Constant<'a>) -> Self {
Child::Constant(child)
}
}
impl<'a> From<Domain<'a>> for Child<'a> {
fn from(child: Domain<'a>) -> Self {
Child::Domain(child)
}
}
impl<'a>... | {
let parser = try!(parser.parse(event));
Ok(match parser.child() {
Ok(child) => Parser::Finished(child.into()),
Err(parser) => Parser::Parsing(parser),
})
} | conditional_block |
mod.rs | // Copyright 2016 Alexander Reece
//
// 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... | use xml::reader::XmlEvent;
use {Class, Constant, Domain};
use parser::Error;
pub use self::inner::Parser as InnerParser;
#[derive(Debug)]
pub enum Child<'a> {
Constant(Constant<'a>),
Domain(Domain<'a>),
Class(Class<'a>),
}
#[derive(Debug)]
pub enum Parser<'a> {
Parsing(InnerParser<'a>),
Finished(... | random_line_split | |
mod.rs | // Copyright 2016 Alexander Reece
//
// 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... |
}
| {
Child::Class(child)
} | identifier_body |
mod.rs | // Copyright 2016 Alexander Reece
//
// 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... | (child: Domain<'a>) -> Self {
Child::Domain(child)
}
}
impl<'a> From<Class<'a>> for Child<'a> {
fn from(child: Class<'a>) -> Self {
Child::Class(child)
}
}
| from | identifier_name |
metrics.py | # Copyright 2020 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 agreed to in writing, ... |
output = i3d_model(videos)
return output
def calculate_fvd(real_activations, generated_activations):
return tfgan.eval.frechet_classifier_distance_from_activations(
real_activations, generated_activations)
def fvd(video_1, video_2):
video_1 = fvd_preprocess(video_1, (224, 224))
video_2 = fvd_prepr... | base_model = hub.load(module_spec)
input_tensor = base_model.graph.get_tensor_by_name('input_frames:0')
i3d_model = base_model.prune(input_tensor, 'RGB/inception_i3d/Mean:0') | conditional_block |
metrics.py | # Copyright 2020 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 agreed to in writing, ... |
def fvd_preprocess(videos, target_resolution):
videos = tf.convert_to_tensor(videos * 255.0, dtype=tf.float32)
videos_shape = videos.shape.as_list()
all_frames = tf.reshape(videos, [-1] + videos_shape[-3:])
resized_videos = tf.image.resize(all_frames, size=target_resolution)
target_shape = [videos_shape[0], ... | return np.mean(dist.numpy())
| random_line_split |
metrics.py | # Copyright 2020 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 agreed to in writing, ... |
def lpips(video_1, video_2):
video_1 = flatten_video(video_1)
video_2 = flatten_video(video_2)
dist = lpips_image(video_1, video_2)
return np.mean(dist.numpy())
def fvd_preprocess(videos, target_resolution):
videos = tf.convert_to_tensor(videos * 255.0, dtype=tf.float32)
videos_shape = videos.shape.as_... | global lpips_model
result = tf.convert_to_tensor(0.0)
return result | identifier_body |
metrics.py | # Copyright 2020 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 agreed to in writing, ... | (real_activations, generated_activations):
return tfgan.eval.frechet_classifier_distance_from_activations(
real_activations, generated_activations)
def fvd(video_1, video_2):
video_1 = fvd_preprocess(video_1, (224, 224))
video_2 = fvd_preprocess(video_2, (224, 224))
x = create_id3_embedding(video_1)
y... | calculate_fvd | identifier_name |
call_chain.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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 your option) any
// later version.
// Th... | }
pub fn get_height(&self) -> u64 {
self.chain.get_current_height()
}
pub fn get_pre_hash(&self) -> H256 {
*self.chain.current_hash.read()
}
pub fn get_contract_address(&self, hash: H256) -> H160 {
let receipt = self.chain.localized_receipt(hash).unwrap();
matc... |
pub fn add_block(&self, block: Block) {
self.chain.set_block(block); | random_line_split |
call_chain.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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 your option) any
// later version.
// Th... |
pub fn add_block(&self, block: Block) {
self.chain.set_block(block);
}
pub fn get_height(&self) -> u64 {
self.chain.get_current_height()
}
pub fn get_pre_hash(&self) -> H256 {
*self.chain.current_hash.read()
}
pub fn get_contract_address(&self, hash: H256) -> H1... | {
let (chain, st) = Chain::init_chain(db, genesis, sync_sender);
Callchain { chain: chain }
} | identifier_body |
call_chain.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program 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 your option) any
// later version.
// Th... | (&self) -> u64 {
self.chain.get_current_height()
}
pub fn get_pre_hash(&self) -> H256 {
*self.chain.current_hash.read()
}
pub fn get_contract_address(&self, hash: H256) -> H160 {
let receipt = self.chain.localized_receipt(hash).unwrap();
match receipt.contract_address {... | get_height | identifier_name |
import_mu.py | .context.scene.objects.link(obj)
return obj
def copy_spring(dst, src):
dst.spring = src.spring
dst.damper = src.damper
dst.targetPosition = src.targetPosition
def copy_friction(dst, src):
dst.extremumSlip = src.extremumSlip
dst.extremumValue = src.extremumValue
dst.asymptoteSlip = src.asym... | name = ".".join([clip.name, curve.path, subpath])
if name not in actions:
actions[name] = bpy.data.actions.new(name), obj
act, obj = actions[name]
if not create_fcurve(act, curve, propmap):
continue
for name in actions:
act, obj = actions[name]
... | subpath, propmap = propmap[0], propmap[1:]
if subpath != "obj":
obj = getattr (obj, subpath)
| random_line_split |
import_mu.py | .context.scene.objects.link(obj)
return obj
def copy_spring(dst, src):
dst.spring = src.spring
dst.damper = src.damper
dst.targetPosition = src.targetPosition
def copy_friction(dst, src):
dst.extremumSlip = src.extremumSlip
dst.extremumValue = src.extremumValue
dst.asymptoteSlip = src.asym... |
obj.parent = parent
for child | cobj = create_collider(mu, muobj)
cobj.parent = obj | conditional_block |
import_mu.py | .context.scene.objects.link(obj)
return obj
def copy_spring(dst, src):
dst.spring = src.spring
dst.damper = src.damper
dst.targetPosition = src.targetPosition
def copy_friction(dst, src):
dst.extremumSlip = src.extremumSlip
dst.extremumValue = src.extremumValue
dst.asymptoteSlip = src.asym... |
property_map = {
"m_LocalPosition.x": ("obj", "location", 0, 1),
"m_LocalPosition.y": ("obj", "location", 2, 1),
"m_LocalPosition.z": ("obj", "location", 1, 1),
"m_LocalRotation.x": ("obj", "rotation_quaternion", 1, -1),
"m_LocalRotation.y": ("obj", "rotation_quaternion", 3, -1),
"m_LocalRotat... | ltype = ('SPOT', 'SUN', 'POINT', 'AREA')[mulight.type]
light = bpy.data.lamps.new(transform.name, ltype)
light.color = mulight.color[:3]
light.distance = mulight.range
light.energy = mulight.intensity
if ltype == 'SPOT' and hasattr(mulight, "spotAngle"):
light.spot_size = mulight.spotAngle *... | identifier_body |
import_mu.py | (mu, uvs, mesh, name):
uvlay = mesh.uv_textures.new(name)
uvloop = mesh.uv_layers[name]
for i, uvl in enumerate(uvloop.data):
v = mesh.loops[i].vertex_index
uvl.uv = uvs[v]
def create_mesh(mu, mumesh, name):
mesh = bpy.data.meshes.new(name)
faces = []
for sm in mumesh.submeshes:... | create_uvs | identifier_name | |
token.js | import jwt from 'jsonwebtoken';
import tokens from './tokenStore';
const token = {
issue: (payload, secret, options, connectionString) => {
let database;
return tokens.connect(connectionString).then((db) => {
database = db;
return tokens.find(database, payload);
})
.then((record) => {
... | (token, secret) {
return new Promise((resolve, reject) => jwt.verify(token, secret, (err, decoded) => {
if (err) { return reject(err); }
return resolve(decoded);
}));
}
function sign(payload, secret, options) {
return new Promise((resolve) => {
let token = jwt.sign(payload, secret, options);
retu... | verify | identifier_name |
token.js | import jwt from 'jsonwebtoken';
import tokens from './tokenStore';
const token = {
issue: (payload, secret, options, connectionString) => {
let database;
return tokens.connect(connectionString).then((db) => {
database = db;
return tokens.find(database, payload);
})
.then((record) => {
... | }
module.exports = token; | return resolve(token);
}); | random_line_split |
token.js | import jwt from 'jsonwebtoken';
import tokens from './tokenStore';
const token = {
issue: (payload, secret, options, connectionString) => {
let database;
return tokens.connect(connectionString).then((db) => {
database = db;
return tokens.find(database, payload);
})
.then((record) => {
... |
return tokens.save(database, payload);
})
.then((record) => {
if (!record) { throw new Error('Failed to whitelist JWT.'); }
return sign(payload, secret, options);
});
},
revoke: (decodedToken, connectionString) =>
tokens.connect(connectionString)
.then((db) => tokens.remove(db... | { throw new Error('JWT already white listed.'); } | conditional_block |
token.js | import jwt from 'jsonwebtoken';
import tokens from './tokenStore';
const token = {
issue: (payload, secret, options, connectionString) => {
let database;
return tokens.connect(connectionString).then((db) => {
database = db;
return tokens.find(database, payload);
})
.then((record) => {
... |
function sign(payload, secret, options) {
return new Promise((resolve) => {
let token = jwt.sign(payload, secret, options);
return resolve(token);
});
}
module.exports = token;
| {
return new Promise((resolve, reject) => jwt.verify(token, secret, (err, decoded) => {
if (err) { return reject(err); }
return resolve(decoded);
}));
} | identifier_body |
deleteModal.component.tsx | /**
* Copyright (C) 2021 3D Repo Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This pro... | <DeleteIcon />
<DialogTitle>
<FormattedMessage
id="deleteModal.header"
defaultMessage={title}
/>
</DialogTitle>
<DialogContent>
<DialogContentText>
{message}
</DialogContentText>
</DialogContent>
<Actions>
<Button autoFocus type="submit" onClick={() => { onClickClose(); onClickCon... | }
export const DeleteModal = ({ onClickConfirm, onClickClose, title, message }: IDeleteModal) => (
<Container> | random_line_split |
mailTest.js | var Component = new Brick.Component();
Component.requires = {
mod: [
{name: '{C#MODNAME}', files: ['mail.js']}
]
};
Component.entryPoint = function(NS){
var Y = Brick.YUI,
COMPONENT = this,
SYS = Brick.mod.sys;
NS.MailTestWidget = Y.Base.create('MailTestWidget', SYS.AppWidget, ... | this._resultMailWidget = new NS.MailViewWidget({
srcNode: tp.append('resultMail', '<div></div>'),
mail: mail
});
},
hideResult: function(){
var widget = this._resultMailWidget;
if (!widget){
return;
... | showResult: function(mail){
var tp = this.template;
tp.show('resultPanel');
| random_line_split |
mailTest.js | var Component = new Brick.Component();
Component.requires = {
mod: [
{name: '{C#MODNAME}', files: ['mail.js']}
]
};
Component.entryPoint = function(NS){
var Y = Brick.YUI,
COMPONENT = this,
SYS = Brick.mod.sys;
NS.MailTestWidget = Y.Base.create('MailTestWidget', SYS.AppWidget, ... |
widget.destroy();
this._resultMailWidget = null;
this.template.hide('resultPanel');
}
}, {
ATTRS: {
component: {value: COMPONENT},
templateBlockName: {value: 'widget'},
},
CLICKS: {
send: 'sendTestMail'
... | {
return;
} | conditional_block |
UsersAdmin.js | /// <reference path="../../../../typings/tsd.d.ts" />
//NOTE: The angular app is initialised in ~/scripts/app/app.js
angular.module('app')
.factory('AdminService', function($http, HttpHelper) {
var fac = {};
fac.passwordRules = function() { return HttpHelper.get(['api/UsersAdmin/PasswordRules'].join(''))... |
vm.gridOptions = {
columnDefs: columnDefs,
enableSorting: true,
enableFilter: true,
enableColResize: true,
angularCompileRows: true
};
var getUsers = function() {
// Get users
// Promise to show a spinner ... | {
params.$scope.ageClicked = ageClicked;
return '<button class="btn btn-xs btn-info" ng-click="vm.assignSim(data)" >Simulators</button>';
} | identifier_body |
UsersAdmin.js | /// <reference path="../../../../typings/tsd.d.ts" />
//NOTE: The angular app is initialised in ~/scripts/app/app.js
angular.module('app')
.factory('AdminService', function($http, HttpHelper) {
var fac = {};
fac.passwordRules = function() { return HttpHelper.get(['api/UsersAdmin/PasswordRules'].join(''))... | else {
var reason = response.data.Errors[0] || 'An error occurred.';
toastr.error(reason, 'Password Error');
}
});
};
$scope.cancelResetPassword = function() {
$scope.vm.passwordUser = null;
};
// END Reset P... | {
getUsers();
$scope.cancelResetPassword();
toastr.info(['Password reset for ', user.UserName].join(''), 'Reset Password');
} | conditional_block |
UsersAdmin.js | /// <reference path="../../../../typings/tsd.d.ts" />
//NOTE: The angular app is initialised in ~/scripts/app/app.js
angular.module('app')
.factory('AdminService', function($http, HttpHelper) {
var fac = {};
fac.passwordRules = function() { return HttpHelper.get(['api/UsersAdmin/PasswordRules'].join(''))... | (params) {
params.$scope.ageClicked = ageClicked;
return '<button class="btn btn-xs btn-info" ng-click="vm.assignSim(data)" >Simulators</button>';
}
vm.gridOptions = {
columnDefs: columnDefs,
enableSorting: true,
enableFilter: true,
... | ageCellRendererFunc | identifier_name |
UsersAdmin.js | /// <reference path="../../../../typings/tsd.d.ts" />
//NOTE: The angular app is initialised in ~/scripts/app/app.js
angular.module('app')
.factory('AdminService', function($http, HttpHelper) {
var fac = {};
fac.passwordRules = function() { return HttpHelper.get(['api/UsersAdmin/PasswordRules'].join(''))... | }
vm.gridOptions = {
columnDefs: columnDefs,
enableSorting: true,
enableFilter: true,
enableColResize: true,
angularCompileRows: true
};
var getUsers = function() {
// Get users
// Promise to show ... | return '<button class="btn btn-xs btn-info" ng-click="vm.assignSim(data)" >Simulators</button>'; | random_line_split |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AlertModule } from 'ng2-bootstrap';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './... | BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule,
AuthModule,
AlertModule.forRoot(),
SharedModule.forRoot()
],
providers: [
AuthenticationService,
AuthenticatedGuard,
UserService
],
bootstrap: [AppComponent]
})
export class AppModule { } | imports: [ | random_line_split |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AlertModule } from 'ng2-bootstrap';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './... | { }
| AppModule | identifier_name |
cache.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/. */
//! A simple LRU cache.
use arrayvec::{Array, ArrayVec};
/// A LRU cache using a statically-sized array for stor... |
/// Remove an from the linked list.
///
/// Note: This only unlinks the entry from the list; it does not remove it from the array.
fn remove(&mut self, i: u16) {
let prev = self.entries[i as usize].prev;
let next = self.entries[i as usize].next;
if i == self.head {
... | {
let entry = Entry { val, prev: 0, next: 0 };
// If the cache is full, replace the oldest entry. Otherwise, add an entry.
let new_head = if self.entries.len() == self.entries.capacity() {
let i = self.pop_back();
self.entries[i as usize] = entry;
i
}... | identifier_body |
cache.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/. */
//! A simple LRU cache.
use arrayvec::{Array, ArrayVec};
/// A LRU cache using a statically-sized array for stor... | }
}
/// Insert a new entry at the head of the list.
fn push_front(&mut self, i: u16) {
if self.entries.len() == 1 {
self.tail = i;
} else {
self.entries[i as usize].next = self.head;
self.entries[self.head as usize].prev = i;
}
sel... | random_line_split | |
cache.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/. */
//! A simple LRU cache.
use arrayvec::{Array, ArrayVec};
/// A LRU cache using a statically-sized array for stor... | (&mut self) -> LRUCacheMutIterator<T, A> {
LRUCacheMutIterator {
pos: self.head,
done: self.entries.len() == 0,
cache: self,
}
}
/// Insert a given key in the cache.
pub fn insert(&mut self, val: T) {
let entry = Entry { val, prev: 0, next: 0 };
... | iter_mut | identifier_name |
cache.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/. */
//! A simple LRU cache.
use arrayvec::{Array, ArrayVec};
/// A LRU cache using a statically-sized array for stor... |
if i == self.tail {
self.tail = prev;
} else {
self.entries[next as usize].prev = prev;
}
}
/// Insert a new entry at the head of the list.
fn push_front(&mut self, i: u16) {
if self.entries.len() == 1 {
self.tail = i;
} else {
... | {
self.entries[prev as usize].next = next;
} | conditional_block |
describeGroups.js | /*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, O... | var ret = common.encode(common.DESCRIBEGROUP_API, version);
ret.groups = groups;
return ret;
}; | random_line_split | |
validation.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 your option) any la... | () {
// given
let server = serve_hosts(Some(vec!["localhost:8080".into()]));
// when
let response = request(server,
"\
GET /ui/ HTTP/1.1\r\n\
Host: localhost:8080\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned());
}
#[test]
fn should... | should_allow_valid_host | identifier_name |
validation.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 your option) any la... | // given
let server = serve_hosts(Some(vec!["localhost:8080".into()]));
// when
let response = request(server,
"\
POST /rpc HTTP/1.1\r\n\
Host: localhost:8080\r\n\
Origin: null\r\n\
Content-Type: application/json\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.sta... | random_line_split | |
validation.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 your option) any la... |
#[test]
fn should_serve_dapps_domains() {
// given
let server = serve_hosts(Some(vec!["localhost:8080".into()]));
// when
let response = request(server,
"\
GET / HTTP/1.1\r\n\
Host: ui.parity\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 200 OK".to... | {
// given
let server = serve_hosts(Some(vec!["localhost:8080".into()]));
// when
let response = request(server,
"\
GET /ui/ HTTP/1.1\r\n\
Host: localhost:8080\r\n\
Connection: close\r\n\
\r\n\
{}
"
);
// then
assert_eq!(response.status, "HTTP/1.1 200 OK".to_owned());
} | identifier_body |
main.rs | #![feature(plugin)]
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
mod primary_index;
mod secondary_index;
mod table;
mod find;
use std::fs::File;
use std::io::Read;
use serde_json::{Value, Error};
fn | () {
let db_path = "/data/testdb";
let mut t = table::Table::new("test_table", db_path);
t.create_secondary_index("Type", secondary_index::key_types::Str(20));
t.create_secondary_index("Name", secondary_index::key_types::Str(128));
t.create_secondary_index("X", secondary_index::key_types::F32);
... | main | identifier_name |
main.rs | #![feature(plugin)]
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
mod primary_index;
mod secondary_index;
mod table;
mod find;
use std::fs::File;
use std::io::Read;
use serde_json::{Value, Error};
fn main() {
let db_path = "/data/testdb";
let mut t = table::Table::... |
// load_dummy_data(&mut t);
println!("Get by id 3 {:?}", t.get(3));
println!("Get by id 4 {:?}", t.get(4));
println!("Get by id 33 {:?}", t.get(33));
println!("Get by id 333 {:?}, has an index of {:?}", t.get(333), t.get(333).get_id());
println!("Search index {:?}", t.secondary_indexes[0].ge... | t.create_secondary_index("X", secondary_index::key_types::F32);
t.create_secondary_index("Y", secondary_index::key_types::F32);
| random_line_split |
main.rs | #![feature(plugin)]
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
mod primary_index;
mod secondary_index;
mod table;
mod find;
use std::fs::File;
use std::io::Read;
use serde_json::{Value, Error};
fn main() | println!("Get by id 333 {:?}, has an index of {:?}", t.get(333), t.get(333).get_id());
println!("Search index {:?}", t.secondary_indexes[0].get("TEST", "TEST2"));
println!("{}", t.table_name);
}
fn load_dummy_data(t:&mut table::Table) {
// load json from thing
let mut s = String::new();
File... | {
let db_path = "/data/testdb";
let mut t = table::Table::new("test_table", db_path);
t.create_secondary_index("Type", secondary_index::key_types::Str(20));
t.create_secondary_index("Name", secondary_index::key_types::Str(128));
t.create_secondary_index("X", secondary_index::key_types::F32);
... | identifier_body |
noStringLiteralRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... |
super.visitElementAccessExpression(node);
}
}
function isValidIdentifier(token: string) {
const scanner = ts.createScanner(ts.ScriptTarget.ES5, false, ts.LanguageVariant.Standard, token);
scanner.scan();
// if we scanned to the end of the token, we can check if the scanned item was an identif... | {
const accessorText = argument.getText();
// the argument expression should be a string of length at least 2 (due to quote characters)
if (argument.kind === ts.SyntaxKind.StringLiteral && accessorText.length > 2) {
const unquotedAccessorText = accessorText.substring... | conditional_block |
noStringLiteralRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... | /* tslint:disable:object-literal-sort-keys */
public static metadata: Lint.IRuleMetadata = {
ruleName: "no-string-literal",
description: "Disallows object access via string literals.",
rationale: "Encourages using strongly-typed property access.",
optionsDescription: "Not configu... |
export class Rule extends Lint.Rules.AbstractRule { | random_line_split |
noStringLiteralRule.ts | /**
* @license
* Copyright 2013 Palantir Technologies, Inc.
*
* 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... | (node: ts.ElementAccessExpression) {
const argument = node.argumentExpression;
if (argument != null) {
const accessorText = argument.getText();
// the argument expression should be a string of length at least 2 (due to quote characters)
if (argument.kind === ts.Synta... | visitElementAccessExpression | identifier_name |
browsingcontext.rs | ;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra};
use js::jsapi::{Handle, HandleId, HandleObject, HandleValue};
use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject};
use js::jsapi::{JS... | (&self) {
self.active_document.set(None)
}
}
#[allow(unsafe_code)]
unsafe fn GetSubframeWindow(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId)
-> Option<Root<Window>> {
let index = get_array_index_from_id(cx, id)... | unset_active_document | identifier_name |
browsingcontext.rs | ;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra};
use js::jsapi::{Handle, HandleId, HandleObject, HandleValue};
use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject};
use js::jsapi::{JS... | #[allow(unsafe_code)]
unsafe extern "C" fn set(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
v: HandleValue,
receiver: HandleValue,
res: *mut ObjectOpResult)
-> ... | random_line_split | |
browsingcontext.rs | ;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra};
use js::jsapi::{Handle, HandleId, HandleObject, HandleValue};
use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject};
use js::jsapi::{JS... |
None
}
#[allow(unsafe_code)]
unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
mut desc: MutableHandle<PropertyDescriptor>)
... | {
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
let win = root_from_handleobject::<Window>(target.handle()).unwrap();
let mut found = false;
return win.IndexedGetter(index, &mut found);
} | conditional_block |
browsingcontext.rs | ;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra};
use js::jsapi::{Handle, HandleId, HandleObject, HandleValue};
use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject};
use js::jsapi::{JS... |
pub fn active_window(&self) -> Root<Window> {
Root::from_ref(self.active_document().window())
}
pub fn frame_element(&self) -> Option<&Element> {
self.frame_element.r()
}
pub fn window_proxy(&self) -> *mut JSObject {
let window_proxy = self.reflector.get_jsobject();
... | {
self.active_document.get()
} | identifier_body |
admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2013 Código Sur Sociedad Civil.
# All rights reserved.
#
# This file is part of Cyclope.
#
# Cyclope 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 Foundat... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from django.conf import settings
from django.contrib imp... | # (at your option) any later version.
#
# Cyclope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2013 Código Sur Sociedad Civil.
# All rights reserved.
#
# This file is part of Cyclope.
#
# Cyclope 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 Foundat... | forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MediaLibraryForm, self).__init__(*args, **kwargs)
author_choices = [('', '------')]
for author in Author.objects.all():
if media_model in [ctype.model_class()
for c... | ediaLibraryForm( | identifier_name |
admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2013 Código Sur Sociedad Civil.
# All rights reserved.
#
# This file is part of Cyclope.
#
# Cyclope 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 Foundat... | if hasattr(self, "image_file_initial"):
setattr(instance, f_field, self.image_file_initial)
else:
if hasattr(self, "media_file_initial"):
setattr(instance, f_field, self.media_... | bs_paths = {}
instance = super(MediaLibraryForm, self).save(commit=False)
image_file_field = instance.image_file_field
file_fields = [ instance.media_file_field ]
if image_file_field:
file_fields.append(image_file_field)
... | conditional_block |
admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2013 Código Sur Sociedad Civil.
# All rights reserved.
#
# This file is part of Cyclope.
#
# Cyclope 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 Foundat... | return form
has_thumbnail = [Picture, MovieClip, FlashMovie]
def media_admin_factory(media_model):
class MediaLibraryForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MediaLibraryForm, self).__init__(*args, **kwargs)
author_choices = [('', '------')]
... | edia_file_field = self.model.media_file_field
image_file_field = self.model.image_file_field
form = super(MediaAdmin, self).get_form(request, obj, **kwargs)
simple_widgets = False
if not request.user.is_superuser:
simple_widgets = True
form.base_fields[media_file_... | identifier_body |
cow.rs | #![allow(unused_imports)]
use geometry::prim::{Prim};
use geometry::prims::{Plane, Sphere, Triangle};
use light::light::{Light};
use light::lights::{PointLight, SphereLight};
use material::materials::{CookTorranceMaterial, FlatMaterial, PhongMaterial};
use material::Texture;
use material::textures::{CheckerTexture, Cu... | skybox: None
}
}
| {
let mut lights: Vec<Box<Light+Send+Sync>> = Vec::new();
lights.push(Box::new(SphereLight { position: Vec3 {x: 3.0, y: 10.0, z: 6.0}, color: Vec3::one(), radius: 5.0 }));
let red = CookTorranceMaterial { k_a: 0.0, k_d: 0.6, k_s: 1.0, k_sg: 0.2, k_tg: 0.0, gauss_constant: 30.0, roughness: 0.1, glossiness... | identifier_body |
cow.rs | #![allow(unused_imports)]
use geometry::prim::{Prim};
use geometry::prims::{Plane, Sphere, Triangle};
use light::light::{Light};
use light::lights::{PointLight, SphereLight};
use material::materials::{CookTorranceMaterial, FlatMaterial, PhongMaterial};
use material::Texture;
use material::textures::{CheckerTexture, Cu... | () -> Scene {
let mut lights: Vec<Box<Light+Send+Sync>> = Vec::new();
lights.push(Box::new(SphereLight { position: Vec3 {x: 3.0, y: 10.0, z: 6.0}, color: Vec3::one(), radius: 5.0 }));
let red = CookTorranceMaterial { k_a: 0.0, k_d: 0.6, k_s: 1.0, k_sg: 0.2, k_tg: 0.0, gauss_constant: 30.0, roughness: 0.1... | get_scene | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.