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 |
|---|---|---|---|---|
test_graphrbac.py | # coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#---------------------------------------------------------------------... | elf):
user = self.graphrbac_client.users.create(
azure.graphrbac.models.UserCreateParameters(
user_principal_name="testbuddy@{}".format(self.settings.AD_DOMAIN),
account_enabled=False,
display_name='Test Buddy',
mail_nickname='testbudd... | st_graphrbac_users(s | identifier_name |
test_graphrbac.py | # coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for | import azure.graphrbac
from testutils.common_recordingtestcase import record
from tests.mgmt_testcase import HttpStatusCode, AzureMgmtTestCase
class GraphRbacTest(AzureMgmtTestCase):
def setUp(self):
super(GraphRbacTest, self).setUp()
self.graphrbac_client = self.create_basic_client(
... | # license information.
#--------------------------------------------------------------------------
import unittest
| random_line_split |
no-access.component.spec.ts | import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AngularSvgIconModule } from 'angular-svg-icon';
import { HttpClientModule } from '@angular/common/http';
import { configureTests } from 'app/app.test.configuration'; | describe('NoAccessComponent', () => {
let component: NoAccessComponent;
let fixture: ComponentFixture<NoAccessComponent>;
let debugElement;
beforeEach(done => {
const configure = (testBed: TestBed) => {
testBed.configureTestingModule({
imports: [RouterTestingModule, AngularSvgIconModule, Htt... | import { NoAccessComponent } from './no-access.component';
| random_line_split |
tests.py | # -*- encoding: utf-8 -*-
"""
Tests for django.core.servers.
"""
from __future__ import unicode_literals
import os
import socket
try:
from urllib.request import urlopen, HTTPError
except ImportError: # Python 2
from urllib2 import urlopen, HTTPError
from django.core.exceptions import ImproperlyConfigured
... |
def test_view(self):
"""
Ensure that the LiveServerTestCase serves views.
Refs #2879.
"""
f = self.urlopen('/example_view/')
self.assertEqual(f.read(), b'example view')
def test_static_files(self):
"""
Ensure that the LiveServerTestCase serves s... | self.fail('Expected 404 response') | conditional_block |
tests.py | # -*- encoding: utf-8 -*-
"""
Tests for django.core.servers.
"""
from __future__ import unicode_literals
import os
import socket
try:
from urllib.request import urlopen, HTTPError
except ImportError: # Python 2
from urllib2 import urlopen, HTTPError
from django.core.exceptions import ImproperlyConfigured
... |
@classmethod
def tearDownClass(cls):
# Restore original settings
cls.settings_override.disable()
super(LiveServerBase, cls).tearDownClass()
def urlopen(self, url):
return urlopen(self.live_server_url + url)
class LiveServerAddress(LiveServerBase):
"""
Ensure that... | cls.settings_override = override_settings(**TEST_SETTINGS)
cls.settings_override.enable()
super(LiveServerBase, cls).setUpClass() | identifier_body |
tests.py | # -*- encoding: utf-8 -*-
"""
Tests for django.core.servers.
"""
from __future__ import unicode_literals
import os
import socket
try:
from urllib.request import urlopen, HTTPError
except ImportError: # Python 2
from urllib2 import urlopen, HTTPError
from django.core.exceptions import ImproperlyConfigured
... | self.assertEqual(f.read().rstrip(b'\r\n'), b'example static file')
def test_media_files(self):
"""
Ensure that the LiveServerTestCase serves media files.
Refs #2879.
"""
f = self.urlopen('/media/example_media_file.txt')
self.assertEqual(f.read().rstrip(b'\r\n... | f = self.urlopen('/static/example_static_file.txt') | random_line_split |
tests.py | # -*- encoding: utf-8 -*-
"""
Tests for django.core.servers.
"""
from __future__ import unicode_literals
import os
import socket
try:
from urllib.request import urlopen, HTTPError
except ImportError: # Python 2
from urllib2 import urlopen, HTTPError
from django.core.exceptions import ImproperlyConfigured
... | (cls, address, exception):
os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = address
try:
super(LiveServerAddress, cls).setUpClass()
raise Exception("The line above should have raised an exception")
except exception:
pass
finally:
super(LiveS... | raises_exception | identifier_name |
timeline.js | $(frappe.render_template("timeline",
{ image: frappe.user_info(user).image, fullname: user_fullname })).appendTo(this.parent);
this.list = this.wrapper.find(".timeline-items");
this.input = this.wrapper.find(".form-control");
this.button = this.wrapper.find(".btn-go")
.on("click", function() {
if(me.... | else {
c.comment_html = c.comment;
c.comment_html = frappe.utils.strip_whitespace(c.comment_html);
}
}
},
set_icon_and_color: function(c) {
c.icon = {
"Email": "octicon octicon-mail",
"Chat": "octicon octicon-comment-discussion",
"Phone": "octicon octicon-device-mobile",
"SMS": "octicon oc... | {
c.comment_html = frappe.markdown(__(c.comment));
} | conditional_block |
timeline.js | = $(frappe.render_template("timeline",
{ image: frappe.user_info(user).image, fullname: user_fullname })).appendTo(this.parent);
this.list = this.wrapper.find(".timeline-items");
this.input = this.wrapper.find(".form-control");
this.button = this.wrapper.find(".btn-go")
.on("click", function() {
if(m... | // find the email tor reply to
me.get_comments().forEach(function(c) {
if(c.name==name) {
last_email = c;
return false;
}
});
// make the composer
new frappe.views.CommunicationComposer({
doc: me.frm.doc,
txt: "",
frm: me.frm,
last_email: last_email
});
});
},
p... | random_line_split | |
request.ts | body when serialized for the server.
*
* @experimental
*/
export type HttpSerializedBody = ArrayBuffer | Blob | FormData | string;
/**
* A subset of the allowed values for `XMLHttpRequest.responseType` supported by
* {@link HttpClient}.
*
* @experimental
*/
export type HttpResponseType = 'arraybuffer' | 'blob... |
// If options have been passed, interpret them.
if (options) {
// Normalize reportProgress and withCredentials.
this.reportProgress = !!options.reportProgress;
this.withCredentials = !!options.withCredentials;
// Override default response type of 'json' if one is provided.
if (!... | {
// No body required, options are the third argument. The body stays null.
options = third as HttpRequestInit;
} | conditional_block |
request.ts | body when serialized for the server.
*
* @experimental
*/
export type HttpSerializedBody = ArrayBuffer | Blob | FormData | string;
/**
* A subset of the allowed values for `XMLHttpRequest.responseType` supported by
* {@link HttpClient}.
*
* @experimental
*/
export type HttpResponseType = 'arraybuffer' | 'blob... |
/**
* Safely assert whether the given value is a Blob.
*
* In some execution environments Blob is not defined.
*/
function isBlob(value: any): value is Blob {
return typeof Blob !== 'undefined' && value instanceof Blob;
}
/**
* Safely assert whether the given value is a FormData instance.
*
* In some execut... | {
return typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;
} | identifier_body |
request.ts | body when serialized for the server.
*
* @experimental
*/
export type HttpSerializedBody = ArrayBuffer | Blob | FormData | string;
/**
* A subset of the allowed values for `XMLHttpRequest.responseType` supported by
* {@link HttpClient}.
*
* @experimental
*/
export type HttpResponseType = 'arraybuffer' | 'blob... | (): HttpSerializedBody|null {
// If no body is present, no need to serialize it.
if (this.body === null) {
return null;
}
// Check whether the body is already in a serialized form. If so,
// it can just be returned directly.
if (isArrayBuffer(this.body) || isBlob(this.body) || isFormData(t... | serializeBody | identifier_name |
request.ts | body when serialized for the server.
*
* @experimental
*/
export type HttpSerializedBody = ArrayBuffer | Blob | FormData | string;
/**
* A subset of the allowed values for `XMLHttpRequest.responseType` supported by
* {@link HttpClient}.
*
* @experimental
*/
export type HttpResponseType = 'arraybuffer' | 'blob... | clone(): HttpRequest<T>;
clone(update: HttpRequestInit): HttpRequest<T>;
clone<V>(update: HttpRequestClone<V>): HttpRequest<V>;
clone(update: HttpRequestClone<any> = {}): HttpRequest<any> {
// For method, url, and responseType, take the current value unless
// it is overridden in the update hash.
co... | random_line_split | |
ars_tf_policy.py | # Code in this file is copied and adapted from
# https://github.com/openai/evolution-strategies-starter.
import gym
import numpy as np
import tree
import ray
import ray.experimental.tf_utils
from ray.rllib.agents.es.es_tf_policy import make_session
from ray.rllib.models import ModelCatalog
from ray.rllib.policy.polic... |
# Policy network.
self.dist_class, dist_dim = ModelCatalog.get_action_dist(
self.action_space, self.config["model"], dist_type="deterministic")
self.model = ModelCatalog.get_model_v2(
obs_space=self.preprocessor.observation_space,
action_space=self.action_s... | if not tf1.executing_eagerly():
tf1.enable_eager_execution()
self.sess = self.inputs = None | conditional_block |
ars_tf_policy.py | # Code in this file is copied and adapted from
# https://github.com/openai/evolution-strategies-starter.
import gym
import numpy as np
import tree
import ray
import ray.experimental.tf_utils
from ray.rllib.agents.es.es_tf_policy import make_session
from ray.rllib.models import ModelCatalog
from ray.rllib.policy.polic... |
def set_flat_weights(self, x):
self.variables.set_flat(x)
def get_flat_weights(self):
return self.variables.get_flat()
| return self.set_flat_weights(state["state"]) | identifier_body |
ars_tf_policy.py | # Code in this file is copied and adapted from
# https://github.com/openai/evolution-strategies-starter.
import gym
import numpy as np
import tree
import ray
import ray.experimental.tf_utils
from ray.rllib.agents.es.es_tf_policy import make_session
from ray.rllib.models import ModelCatalog
from ray.rllib.policy.polic... | (self):
return self.variables.get_flat()
| get_flat_weights | identifier_name |
ars_tf_policy.py | # Code in this file is copied and adapted from
# https://github.com/openai/evolution-strategies-starter.
import gym
import numpy as np
import tree
import ray
import ray.experimental.tf_utils
from ray.rllib.agents.es.es_tf_policy import make_session
from ray.rllib.models import ModelCatalog
from ray.rllib.policy.polic... | dist = self.dist_class(dist_inputs, self.model)
actions = dist.sample()
actions = tree.map_structure(lambda a: a.numpy(), actions)
# Graph mode.
else:
actions = self.sess.run(
self.sampler, feed_dict={self.inputs: observation})
act... | # Eager mode.
if not self.sess:
dist_inputs, _ = self.model({SampleBatch.CUR_OBS: observation}) | random_line_split |
commands.rs | use river::River;
pub use river::PeekResult;
/// Push command - stateless
///
/// Used to push messages to rivers like this:
///
/// ```
/// john::PushCommand::new().execute("river_name", "message");
/// ```
pub struct PushCommand;
impl PushCommand {
/// Constructor ::new()
///
/// Creates new instance of... |
/// Used to execute push command, specifying a river name and message
/// This can be called multiple times with different arguments
/// since PushCommand is stateless
pub fn execute(&self, river: &str, message: &str) {
River::new(river).push(message);
}
}
/// Peek command - stateless
///... | {
PushCommand
} | identifier_body |
commands.rs | use river::River;
pub use river::PeekResult;
/// Push command - stateless
///
/// Used to push messages to rivers like this:
///
/// ```
/// john::PushCommand::new().execute("river_name", "message");
/// ```
pub struct PushCommand;
impl PushCommand {
/// Constructor ::new()
///
/// Creates new instance of... | pub fn execute(&self, river: &str) {
River::new(river).destroy();
}
} | random_line_split | |
commands.rs | use river::River;
pub use river::PeekResult;
/// Push command - stateless
///
/// Used to push messages to rivers like this:
///
/// ```
/// john::PushCommand::new().execute("river_name", "message");
/// ```
pub struct PushCommand;
impl PushCommand {
/// Constructor ::new()
///
/// Creates new instance of... | (&self, river: &str) {
River::new(river).destroy();
}
}
| execute | identifier_name |
day_6.rs | use std::fmt;
use std::iter::FromIterator;
use std::ops::Add;
#[derive(PartialEq)]
pub enum List<T> {
Empty,
Cons(T, Box<List<T>>),
}
impl <T> List<T> {
pub fn empty() -> Self {
List::Empty
}
pub fn head(&self) -> Option<&T> {
match self {
&List::Empty => None,
... | (&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "{}", self.to_string())
}
}
impl <T: ToString> ToString for List<T> {
fn to_string(&self) -> String {
fn internal<E: ToString>(list: &List<E>) -> String {
match list {
&List::Empty => "".to_ow... | fmt | identifier_name |
day_6.rs | use std::fmt;
use std::iter::FromIterator;
use std::ops::Add;
#[derive(PartialEq)]
pub enum List<T> {
Empty,
Cons(T, Box<List<T>>),
}
impl <T> List<T> {
pub fn empty() -> Self |
pub fn head(&self) -> Option<&T> {
match self {
&List::Empty => None,
&List::Cons(ref head, _) => Some(&head)
}
}
pub fn tail(self) -> Self {
match self {
List::Empty => self,
List::Cons(_, tail) => *tail
}
}
}
impl <T> ... | {
List::Empty
} | identifier_body |
day_6.rs | use std::fmt;
use std::iter::FromIterator;
use std::ops::Add;
#[derive(PartialEq)]
pub enum List<T> {
Empty,
Cons(T, Box<List<T>>),
}
impl <T> List<T> {
pub fn empty() -> Self {
List::Empty
}
| match self {
&List::Empty => None,
&List::Cons(ref head, _) => Some(&head)
}
}
pub fn tail(self) -> Self {
match self {
List::Empty => self,
List::Cons(_, tail) => *tail
}
}
}
impl <T> Add<T> for List<T> {
type Output = Se... | pub fn head(&self) -> Option<&T> { | random_line_split |
rdfdiff.py | #!/usr/bin/env python
"""
RDF Graph Isomorphism Tester
Author: Sean B. Palmer, inamidst.com
Uses the pyrple algorithm
Requirements:
Python2.4+
http://inamidst.com/proj/rdf/ntriples.py
Usage: ./rdfdiff.py <ntriplesP> <ntriplesQ>
"""
import sys, re, urllib
import ntriples
from ntriples import bNode
ntriples.r_uri... | (self, term, done=False):
return tuple(sorted(self.vhashtriples(term, done)))
def vhashtriples(self, term, done):
for t in self.triples:
if term in t: yield tuple(self.vhashtriple(t, term, done))
def vhashtriple(self, triple, term, done):
for p in xrange(3):
if not isinstance... | vhash | identifier_name |
rdfdiff.py | #!/usr/bin/env python
"""
RDF Graph Isomorphism Tester
Author: Sean B. Palmer, inamidst.com
Uses the pyrple algorithm
Requirements:
Python2.4+
http://inamidst.com/proj/rdf/ntriples.py
Usage: ./rdfdiff.py <ntriplesP> <ntriplesQ> | from ntriples import bNode
ntriples.r_uriref = re.compile(r'<([^\s"<>]+)>')
class Graph(object):
def __init__(self, uri=None, content=None):
self.triples = set()
if uri:
self.parse(uri)
elif content:
self.parse_string(content)
def parse(self, uri):
class Sink(object)... | """
import sys, re, urllib
import ntriples | random_line_split |
rdfdiff.py | #!/usr/bin/env python
"""
RDF Graph Isomorphism Tester
Author: Sean B. Palmer, inamidst.com
Uses the pyrple algorithm
Requirements:
Python2.4+
http://inamidst.com/proj/rdf/ntriples.py
Usage: ./rdfdiff.py <ntriplesP> <ntriplesQ>
"""
import sys, re, urllib
import ntriples
from ntriples import bNode
ntriples.r_uri... |
def vhash(self, term, done=False):
return tuple(sorted(self.vhashtriples(term, done)))
def vhashtriples(self, term, done):
for t in self.triples:
if term in t: yield tuple(self.vhashtriple(t, term, done))
def vhashtriple(self, triple, term, done):
for p in xrange(3):
if ... | g = ((isinstance(t, bNode) and self.vhash(t)) or t for t in triple)
yield hash(tuple(g)) | conditional_block |
rdfdiff.py | #!/usr/bin/env python
"""
RDF Graph Isomorphism Tester
Author: Sean B. Palmer, inamidst.com
Uses the pyrple algorithm
Requirements:
Python2.4+
http://inamidst.com/proj/rdf/ntriples.py
Usage: ./rdfdiff.py <ntriplesP> <ntriplesQ>
"""
import sys, re, urllib
import ntriples
from ntriples import bNode
ntriples.r_uri... |
if __name__=="__main__":
main()
| result = compare(sys.argv[1], sys.argv[2])
print ('no', 'yes')[result] | identifier_body |
syncResult.service.ts | import { Injectable } from '@angular/core';
import { SyncResult } from 'app/model/syncResult'
import { Log } from 'app/model/log'
import { LogItem } from 'app/model/logItem'
@Injectable()
export class SyncResultService
{
syncResultService : any;
constructor()
{
this.syncResultService = (window as ... | ()
{
return this.syncResultService.getResultsAsText();
}
}
| getResultsAsText | identifier_name |
syncResult.service.ts | import { Injectable } from '@angular/core';
import { SyncResult } from 'app/model/syncResult'
import { Log } from 'app/model/log'
import { LogItem } from 'app/model/logItem'
@Injectable()
export class SyncResultService
{
syncResultService : any;
constructor()
{
this.syncResultService = (window as ... |
}
else
{
success = false;
}
return success;
}
// TODO cache
// TODO move translation into shared service
getResults() : SyncResult[]
{
var results = [];
var syncResults = this.syncResultService.getResults();
// Translat... | {
var syncResult = syncResults[i];
success &= syncResult.success;
} | conditional_block |
syncResult.service.ts | import { Injectable } from '@angular/core';
import { SyncResult } from 'app/model/syncResult'
import { Log } from 'app/model/log'
import { LogItem } from 'app/model/logItem'
@Injectable()
export class SyncResultService
{
syncResultService : any;
constructor()
|
// TODO cache
// TODO should be ab
// TODO shouldnt be needed, drop
isSuccess() : boolean
{
var success;
var syncResults = this.syncResultService.getResults();
if (syncResults.length > 0)
{
success = true;
for (var i = 0; i < syncResults.len... | {
this.syncResultService = (window as any).syncResultService;
} | identifier_body |
syncResult.service.ts | import { Injectable } from '@angular/core';
import { SyncResult } from 'app/model/syncResult'
import { Log } from 'app/model/log'
import { LogItem } from 'app/model/logItem'
@Injectable()
export class SyncResultService |
constructor()
{
this.syncResultService = (window as any).syncResultService;
}
// TODO cache
// TODO should be ab
// TODO shouldnt be needed, drop
isSuccess() : boolean
{
var success;
var syncResults = this.syncResultService.getResults();
if (syncResults... | {
syncResultService : any; | random_line_split |
optimizers.py | # Code in this file is copied and adapted from
# https://github.com/openai/evolution-strategies-starter.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
class Optimizer(object):
def __init__(self, policy):
|
def update(self, globalg):
self.t += 1
step = self._compute_step(globalg)
theta = self.policy.get_weights()
ratio = np.linalg.norm(step) / np.linalg.norm(theta)
return theta + step, ratio
def _compute_step(self, globalg):
raise NotImplementedError
class SGD(O... | self.policy = policy
self.dim = policy.num_params
self.t = 0 | identifier_body |
optimizers.py | # Code in this file is copied and adapted from
# https://github.com/openai/evolution-strategies-starter.
from __future__ import absolute_import |
class Optimizer(object):
def __init__(self, policy):
self.policy = policy
self.dim = policy.num_params
self.t = 0
def update(self, globalg):
self.t += 1
step = self._compute_step(globalg)
theta = self.policy.get_weights()
ratio = np.linalg.norm(step) / ... | from __future__ import division
from __future__ import print_function
import numpy as np | random_line_split |
optimizers.py | # Code in this file is copied and adapted from
# https://github.com/openai/evolution-strategies-starter.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
class Optimizer(object):
def __init__(self, policy):
self.policy = poli... | (Optimizer):
def __init__(self, policy, stepsize, momentum=0.0):
Optimizer.__init__(self, policy)
self.v = np.zeros(self.dim, dtype=np.float32)
self.stepsize, self.momentum = stepsize, momentum
def _compute_step(self, globalg):
self.v = self.momentum * self.v + (1. - self.moment... | SGD | identifier_name |
mymodel.py | from sqlalchemy import (
Column,
Index,
Integer,
Text,
LargeBinary,
Unicode,
ForeignKey,
Table
)
from sqlalchemy.orm import relationship
from .meta import Base
class User(Base):
"""This class defines a User model."""
__tablename__ = 'users'
id = Column(Integer, primary_key... | (Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
phone = Column(Unicode)
email = Column(Unicode)
picture = Column(LargeBinary)
pic_mime = Column(Text)
user = Column(Integer, ForeignKey('users.id'))
class Category(Base):
__tablename__... | AddressBook | identifier_name |
mymodel.py | from sqlalchemy import (
Column,
Index,
Integer,
Text,
LargeBinary,
Unicode,
ForeignKey,
Table
)
from sqlalchemy.orm import relationship
| __tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(Unicode, unique=True)
password = Column(Unicode)
sub_user = Column(Unicode)
address_rel = relationship('AddressBook')
attr_assoc_rel = relationship('UserAttributeLink')
class AddressBook(Base):
__tablename... | from .meta import Base
class User(Base):
"""This class defines a User model.""" | random_line_split |
mymodel.py | from sqlalchemy import (
Column,
Index,
Integer,
Text,
LargeBinary,
Unicode,
ForeignKey,
Table
)
from sqlalchemy.orm import relationship
from .meta import Base
class User(Base):
|
class AddressBook(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
phone = Column(Unicode)
email = Column(Unicode)
picture = Column(LargeBinary)
pic_mime = Column(Text)
user = Column(Integer, ForeignKey('users.id'))
class Category(Base... | """This class defines a User model."""
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(Unicode, unique=True)
password = Column(Unicode)
sub_user = Column(Unicode)
address_rel = relationship('AddressBook')
attr_assoc_rel = relationship('UserAttributeLink') | identifier_body |
AppView.js | const { Router } = require('director');
const ReactDOM = require('react-dom');
const { computed, observable } = require('../../core');
const React = require('../../react');
const { Todo, todos } = require('./model');
const { StatsView } = require('./StatsView');
const { TodoView } = require('./TodoView');
const { ca... |
}
}
cat(__filename).providesEach({
AppView,
});
ReactDOM.render(
<AppView/>,
document.getElementById("main")
);
module.exports = {
AppView,
} | {
todos.add(new Todo(this.newTodoTitle.$));
this.newTodoTitle.$ = "";
} | conditional_block |
AppView.js | const { Router } = require('director');
const ReactDOM = require('react-dom');
const { computed, observable } = require('../../core');
const React = require('../../react');
const { Todo, todos } = require('./model');
const { StatsView } = require('./StatsView');
const { TodoView } = require('./TodoView');
const { ca... | </ul>
</section>
<footer className="footer" style={this.footerStyle}>
<StatsView todoFilter={ this.todoFilter }/>
</footer>
</section>
</div>;
}
createOnEnter(event) {
if (event.key === "Enter" && this.newTo... | {
return <div>
<section className="todoAppView">
<header className="header">
<h1>todos</h1>
<input className="new-todo"
placeholder="What needs to be done?"
autoFocus
value={ this.newTo... | identifier_body |
AppView.js | const { Router } = require('director');
const ReactDOM = require('react-dom');
const { computed, observable } = require('../../core');
const React = require('../../react');
const { Todo, todos } = require('./model');
const { StatsView } = require('./StatsView');
const { TodoView } = require('./TodoView');
const { ca... | placeholder="What needs to be done?"
autoFocus
value={ this.newTodoTitle }
onKeyPress={ this.createOnEnter.bind(this) }
/>
</header>
<section className="main">
<inp... | <h1>todos</h1>
<input className="new-todo" | random_line_split |
AppView.js | const { Router } = require('director');
const ReactDOM = require('react-dom');
const { computed, observable } = require('../../core');
const React = require('../../react');
const { Todo, todos } = require('./model');
const { StatsView } = require('./StatsView');
const { TodoView } = require('./TodoView');
const { ca... | (event) {
if (event.key === "Enter" && this.newTodoTitle.$.trim().length) {
todos.add(new Todo(this.newTodoTitle.$));
this.newTodoTitle.$ = "";
}
}
}
cat(__filename).providesEach({
AppView,
});
ReactDOM.render(
<AppView/>,
document.getElementById("main")
);
module.exports = {
AppView,
} | createOnEnter | identifier_name |
GoogleJson.py | #!/usr/bin/python
import urllib2
import tempfile
import json
# pprint to print json data on screen
from pprint import pprint | # fetching Google data
url = "http://finance.google.com/finance/info?q=rpower"
response = urllib2.urlopen(url)
#storing google data in temp file
temp_html = tempfile.NamedTemporaryFile(mode='w+')
temp_html.write(response.read())
temp_html.seek(0)
# deleting unnecessary characters and making valid json temp file
temp_... | random_line_split | |
GoogleJson.py | #!/usr/bin/python
import urllib2
import tempfile
import json
# pprint to print json data on screen
from pprint import pprint
# fetching Google data
url = "http://finance.google.com/finance/info?q=rpower"
response = urllib2.urlopen(url)
#storing google data in temp file
temp_html = tempfile.NamedTemporaryFile(mode='... |
temp_html.close()
temp_json.seek(0)
# reading the json data from file
data = json.load(temp_json)
# printing json data stored in variable
# print "pretty print"
# pprint(data)
print "Fetched Data"
print data[0]['c_fix'] # change fix decimal
print data[0]['ccol'] # ??? usuall "chr"
print data[0]['cp_fix'] # closing... | for word in delete_list:
line = line.replace(word, "")
temp_json.write(line) | conditional_block |
main.rs | // This example implements the queens problem:
// https://en.wikipedia.org/wiki/Eight_queens_puzzle
// using an evolutionary algorithm.
extern crate rand;
extern crate simplelog;
// internal crates
extern crate darwin_rs;
use rand::Rng;
use simplelog::{SimpleLogger, LogLevelFilter, Config};
// internal modules
use ... | () {
println!("Darwin test: queens problem");
let _ = SimpleLogger::init(LogLevelFilter::Info, Config::default());
let queens = SimulationBuilder::<Queens>::new()
.fitness(0.0)
.threads(2)
.add_multiple_populations(make_all_populations(100, 8))
.finalize();
match queen... | main | identifier_name |
main.rs | // This example implements the queens problem:
// https://en.wikipedia.org/wiki/Eight_queens_puzzle
// using an evolutionary algorithm.
extern crate rand;
extern crate simplelog;
// internal crates
extern crate darwin_rs;
use rand::Rng;
use simplelog::{SimpleLogger, LogLevelFilter, Config};
// internal modules
use ... |
// left
num_of_collisions += one_trace(board, row, col, 0, -1);
// left top
num_of_collisions += one_trace(board, row, col, -1, -1);
num_of_collisions
}
fn make_population(count: u32) -> Vec<Queens> {
let mut result = Vec::new();
for _ in 0..count {
result.push(
Que... | {
let mut num_of_collisions = 0;
// up
num_of_collisions += one_trace(board, row, col, -1, 0);
// up right
num_of_collisions += one_trace(board, row, col, -1, 1);
// right
num_of_collisions += one_trace(board, row, col, 0, 1);
// right down
num_of_collisions += one_trace(board, r... | identifier_body |
main.rs | // This example implements the queens problem:
// https://en.wikipedia.org/wiki/Eight_queens_puzzle
// using an evolutionary algorithm.
extern crate rand;
extern crate simplelog;
// internal crates
extern crate darwin_rs;
use rand::Rng;
use simplelog::{SimpleLogger, LogLevelFilter, Config};
// internal modules
use ... | .finalize().unwrap();
result.push(pop);
}
result
}
// implement trait functions mutate and calculate_fitness:
impl Individual for Queens {
fn mutate(&mut self) {
let mut rng = rand::thread_rng();
let mut index1: usize = rng.gen_range(0, self.board.len());
let ... | random_line_split | |
setup.py | """
decorstate
~~~~~~~~~~
Simple "state machines" with Python decorators.
:copyright: (c) 2015-2017 Andrew Hawker
:license: Apache 2.0, see LICENSE for more details.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='decorstate',
... | ) | 'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
) | random_line_split |
cache.js |
/*!
* Ext JS Connect
* Copyright(c) 2010 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Buffer = require('buffer').Buffer;
/**
* Cache in memory for the given `cacheDuration`.
*
* @param {Number} cacheDuration
* @return {Function}
* @api public
*/
module.exports = function cache(cacheD... | () {
var resp = cache[key];
var headers = resp.headers;
headers["Content-Length"] = resp.body.length;
if (localQueue) {
// Send everyone in the wait queue the response.
for (var i = 0, l = localQueue.length; i < l; i++) {
... | serve | identifier_name |
cache.js |
/*!
* Ext JS Connect
* Copyright(c) 2010 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Buffer = require('buffer').Buffer;
/**
* Cache in memory for the given `cacheDuration`.
*
* @param {Number} cacheDuration
* @return {Function}
* @api public
*/
module.exports = function cache(cacheD... |
};
next();
};
}; | {
// When the timeout is zero, just kill it right away
delete cache[key];
} | conditional_block |
cache.js |
/*!
* Ext JS Connect
* Copyright(c) 2010 Sencha Inc.
* MIT Licensed
*/
/**
* Module dependencies.
*/
var Buffer = require('buffer').Buffer;
/**
* Cache in memory for the given `cacheDuration`.
*
* @param {Number} cacheDuration
* @return {Function}
* @api public
*/
module.exports = function cache(cacheD... |
// If there is a cache-hit, serve it right away!
if (cache[key]) {
serve();
return;
}
var localQueue = queue[key];
if (localQueue) {
localQueue[localQueue.length] = res;
return;
}
localQueue = queue[key] = [res];
... | {
var resp = cache[key];
var headers = resp.headers;
headers["Content-Length"] = resp.body.length;
if (localQueue) {
// Send everyone in the wait queue the response.
for (var i = 0, l = localQueue.length; i < l; i++) {
... | identifier_body |
cache.js | /*!
* Ext JS Connect
* Copyright(c) 2010 Sencha Inc.
* MIT Licensed
*/ | /**
* Module dependencies.
*/
var Buffer = require('buffer').Buffer;
/**
* Cache in memory for the given `cacheDuration`.
*
* @param {Number} cacheDuration
* @return {Function}
* @api public
*/
module.exports = function cache(cacheDuration){
var cache = {},
queue = {};
return function cache(... | random_line_split | |
mod.rs | //! Defines the trait implemented by all textured values
use std::ops::{Add, Mul};
use film::Colorf;
pub use self::image::Image;
pub use self::animated_image::AnimatedImage;
pub mod image;
pub mod animated_image;
/// scalars or Colors can be computed on some image texture
/// or procedural generator
pub trait Text... | impl ConstantColor {
pub fn new(val: Colorf) -> ConstantColor {
ConstantColor { val: val }
}
}
impl Texture for ConstantColor {
fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 {
self.val.luminance()
}
fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf {
self.val
... | random_line_split | |
mod.rs | //! Defines the trait implemented by all textured values
use std::ops::{Add, Mul};
use film::Colorf;
pub use self::image::Image;
pub use self::animated_image::AnimatedImage;
pub mod image;
pub mod animated_image;
/// scalars or Colors can be computed on some image texture
/// or procedural generator
pub trait Text... | <T, F>(x: f32, y: f32, get: F) -> T
where T: Copy + Add<T, Output=T> + Mul<f32, Output=T>,
F: Fn(u32, u32) -> T
{
let p00 = (x as u32, y as u32);
let p10 = (p00.0 + 1, p00.1);
let p01 = (p00.0, p00.1 + 1);
let p11 = (p00.0 + 1, p00.1 + 1);
let s00 = get(p00.0, p00.1);
let s10 = ge... | bilinear_interpolate | identifier_name |
mod.rs | //! Defines the trait implemented by all textured values
use std::ops::{Add, Mul};
use film::Colorf;
pub use self::image::Image;
pub use self::animated_image::AnimatedImage;
pub mod image;
pub mod animated_image;
/// scalars or Colors can be computed on some image texture
/// or procedural generator
pub trait Text... |
}
pub struct UVColor;
impl Texture for UVColor {
fn sample_f32(&self, u: f32, v: f32, _: f32) -> f32 {
Colorf::new(u, v, 0.0).luminance()
}
fn sample_color(&self, u: f32, v: f32, _: f32) -> Colorf {
Colorf::new(u, v, 0.0)
}
}
| {
self.val
} | identifier_body |
commons.py | # -*- coding: utf-8 -*-
"""
Common structures and functions used by other scripts.
"""
from xml.etree import cElementTree as ET
str_to_entailment = {'none': 0,
'entailment': 1,
'paraphrase': 2}
entailment_to_str = {v: k for k, v in str_to_entailment.items()}
class Pair(obj... | self.h = h
self.id = id_
self.entailment = entailment
self.similarity = similarity
def read_xml(filename, need_labels):
'''
Read an RTE XML file and return a list of Pair objects.
:param filename: name of the file to read
:param need_labels: boolean indicating if labels... | :param entailment: int indicating entailment class
:param similarity: float
'''
self.t = t | random_line_split |
commons.py | # -*- coding: utf-8 -*-
"""
Common structures and functions used by other scripts.
"""
from xml.etree import cElementTree as ET
str_to_entailment = {'none': 0,
'entailment': 1,
'paraphrase': 2}
entailment_to_str = {v: k for k, v in str_to_entailment.items()}
class Pair(obj... |
else:
ent_value = None
if 'similarity' in attribs:
similarity = float(attribs['similarity'])
else:
similarity = None
if need_labels and similarity is None and ent_value is None:
msg = 'Missing both entailment and similarity values for p... | ent_string = attribs['entailment'].lower()
try:
ent_value = str_to_entailment[ent_string]
except ValueError:
msg = 'Unexpected value for attribute "entailment" at pair {}: {}'
raise ValueError(msg.format(id_, ent_string)) | conditional_block |
commons.py | # -*- coding: utf-8 -*-
"""
Common structures and functions used by other scripts.
"""
from xml.etree import cElementTree as ET
str_to_entailment = {'none': 0,
'entailment': 1,
'paraphrase': 2}
entailment_to_str = {v: k for k, v in str_to_entailment.items()}
class Pair(obj... | (filename, need_labels):
'''
Read an RTE XML file and return a list of Pair objects.
:param filename: name of the file to read
:param need_labels: boolean indicating if labels should be present
'''
pairs = []
tree = ET.parse(filename)
root = tree.getroot()
for xml_pair in root.iter(... | read_xml | identifier_name |
commons.py | # -*- coding: utf-8 -*-
"""
Common structures and functions used by other scripts.
"""
from xml.etree import cElementTree as ET
str_to_entailment = {'none': 0,
'entailment': 1,
'paraphrase': 2}
entailment_to_str = {v: k for k, v in str_to_entailment.items()}
class Pair(obj... |
def read_xml(filename, need_labels):
'''
Read an RTE XML file and return a list of Pair objects.
:param filename: name of the file to read
:param need_labels: boolean indicating if labels should be present
'''
pairs = []
tree = ET.parse(filename)
root = tree.getroot()
for xml_pai... | '''
:param t: string with the text
:param h: string with the hypothesis
:param id_: int indicating id in the original file
:param entailment: int indicating entailment class
:param similarity: float
'''
self.t = t
self.h = h
self.id = id_
s... | identifier_body |
packet.rs | use std::io;
use byteorder::{ReadBytesExt, WriteBytesExt};
use protocol::raknet::packet::Packet;
use protocol::raknet::types;
use protocol::raknet::{NetworkSerializable, NetworkDeserializable, NetworkSize};
macro_rules! define_mcpe_packets {
($(($id:expr, $name:ident) => {$($field_name:ident: $field_type:ty),*}),+... | }
impl Into<PacketTypes> for $name {
fn into(self) -> PacketTypes {
PacketTypes::$name(self)
}
}
)+
)
}
define_mcpe_packets!(
(0x01, Login) => {
protocol: u32,
edition: u8
}
); |
fn packet_id(&self) -> u8 {
$id as u8
} | random_line_split |
uint64.js | export const plus = (f, l) => {
let next = {};
if (typeof l === 'number') {
next.low = l;
next.high = 0;
} else if (typeof l === 'object') {
if (l.high && l.low && l.unsigned) {
next = l;
} else |
}
return {
high: f.high + next.high,
low: f.low + next.low,
unsigned: true
};
};
export const generateKeyString = (uint64Object) => {
if (typeof uint64Object === 'number') {
return uint64Object.toString();
}
if (typeof uint64Object === 'object' && typeof uint64Object.high === 'number') {
... | {
throw new Error('Not a uint64 data');
} | conditional_block |
uint64.js | export const plus = (f, l) => {
let next = {};
if (typeof l === 'number') {
next.low = l;
next.high = 0;
} else if (typeof l === 'object') {
if (l.high && l.low && l.unsigned) {
next = l;
} else {
throw new Error('Not a uint64 data');
}
}
return {
high: f.high + next.high,
... |
return Symbol(uint64Object).toString();
}; | } | random_line_split |
index.d.ts | import * as React from "react";
import ReactToolbox from "../index";
export interface AppBarTheme {
/**
* Used for the component root element.
*/
appBar?: string;
/**
* Added to the root element when the app bar is fixed.
*/
fixed?: string;
/**
* Added to the root element when the app bar is f... | extends React.Component<AppBarProps, {}> { }
export default AppBar;
| AppBar | identifier_name |
index.d.ts | import * as React from "react";
import ReactToolbox from "../index";
export interface AppBarTheme {
/**
* Used for the component root element.
*/
appBar?: string;
/**
* Added to the root element when the app bar is fixed.
*/
fixed?: string;
/**
* Added to the root element when the app bar is f... | }
export class AppBar extends React.Component<AppBarProps, {}> { }
export default AppBar; | /**
* Classnames object defining the component style.
*/
theme?: AppBarTheme; | random_line_split |
entry.py | import os
from inspect import signature
from . import db
from . import settings
class Entry:
def __init__(self, id_=None, author=None, date=None, body=None, body_html=None, url=None,
plus=None, media_url=None, tags=None, is_nsfw=None, entry_id=None, type_=None):
self.id_ = id_
se... | (self):
if not self.entry_id: # if entry_id is not none it's a comment
return db.DB.count_comments(self.id_)
@property
def media_ext(self):
if self.media_url:
_, ext = os.path.splitext(self.media_url)
if len(ext) > 4 and '?' in ext: # fix for urls with '?'
... | comments_count | identifier_name |
entry.py | import os
from inspect import signature
from . import db
from . import settings
class Entry:
def __init__(self, id_=None, author=None, date=None, body=None, body_html=None, url=None,
plus=None, media_url=None, tags=None, is_nsfw=None, entry_id=None, type_=None):
|
def __iter__(self):
return self.attrs_gen()
def attrs_gen(self):
attrs = list(signature(self.__init__).parameters.keys()) # attributes from __init__()
return (getattr(self, attr) for attr in attrs[:11])
def __str__(self):
if self.entry_id:
return '{}_{}'.form... | self.id_ = id_
self.author = author
self.date = date
self.body = body
self.body_html = body_html
self.url = url
self.plus = plus
self.media_url = media_url
self.tags = tags
self.is_nsfw = is_nsfw
self.entry_id = entry_id # only for comment... | identifier_body |
entry.py | import os
from inspect import signature
from . import db
from . import settings
class Entry:
def __init__(self, id_=None, author=None, date=None, body=None, body_html=None, url=None,
plus=None, media_url=None, tags=None, is_nsfw=None, entry_id=None, type_=None):
self.id_ = id_
se... |
return ext
else:
return None
@property
def local_file_path(self):
path = settings.FILES_DIR_NAME
ext = self.media_ext
if self.media_url and ext:
if self.is_nsfw:
path = os.path.join(path, settings.NSFW_DIR_NAME)
i... | ext = '.webm' | conditional_block |
entry.py | import os
from inspect import signature
from . import db
from . import settings
class Entry:
def __init__(self, id_=None, author=None, date=None, body=None, body_html=None, url=None,
plus=None, media_url=None, tags=None, is_nsfw=None, entry_id=None, type_=None):
self.id_ = id_
se... | ext = '.webm'
return ext
else:
return None
@property
def local_file_path(self):
path = settings.FILES_DIR_NAME
ext = self.media_ext
if self.media_url and ext:
if self.is_nsfw:
path = os.path.join(path, settings... | elif not ext and 'gfycat.com' in self.media_url: | random_line_split |
index.js | var createBackoff = require('./backoff').createBackoff;
var WebSocketImpl = (typeof(WebSocket) !== "undefined")
? WebSocket
: require('ws');
class WebSocketClient {
/**
* @param url DOMString The URL to which to connect; this should be the URL to which the WebSocket server will respond.
* @param protocol... |
get onmessage () { return this.listeners['onmessage']; }
/**
* An event listener to be called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data. The event is a simple one with the name "open".
* @param listener EventListener
*... | { this.listeners['onmessage'] = listener; } | identifier_body |
index.js | var createBackoff = require('./backoff').createBackoff;
var WebSocketImpl = (typeof(WebSocket) !== "undefined")
? WebSocket
: require('ws');
class WebSocketClient {
/**
* @param url DOMString The URL to which to connect; this should be the URL to which the WebSocket server will respond.
* @param protocol... | * The current state of the connection; this is one of the Ready state constants.
* @type unsigned short
* @readonly
*/
get readyState () { return this.ws.readyState; }
/**
* A string indicating the type of binary data being transmitted by the
* connection. This should be either "blob" if DOM Blob... | */
get bufferedAmount () { return this.ws.bufferedAmount; }
/** | random_line_split |
index.js | var createBackoff = require('./backoff').createBackoff;
var WebSocketImpl = (typeof(WebSocket) !== "undefined")
? WebSocket
: require('ws');
class WebSocketClient {
/**
* @param url DOMString The URL to which to connect; this should be the URL to which the WebSocket server will respond.
* @param protocol... |
if (this.isReconnect && this.listeners['onreconnect']) {
this.listeners['onreconnect'].apply(null, arguments);
}
this.isReconnect = false;
}
/**
* The number of bytes of data that have been queued using calls to send()
* but not yet transmitted to the network. This value does not reset t... | {
this.listeners['onopen'].apply(null, arguments);
} | conditional_block |
index.js | var createBackoff = require('./backoff').createBackoff;
var WebSocketImpl = (typeof(WebSocket) !== "undefined")
? WebSocket
: require('ws');
class WebSocketClient {
/**
* @param url DOMString The URL to which to connect; this should be the URL to which the WebSocket server will respond.
* @param protocol... | () { return this.listeners['onopen']; }
/**
* @param listener EventListener
*/
set onreconnect (listener) { this.listeners['onreconnect'] = listener; }
get onreconnect () { return this.listeners['onreconnect']; }
}
/**
* The connection is not yet open.
*/
WebSocketClient.CONNECTING = WebSocketImpl.CON... | onopen | identifier_name |
forms.py | from flask_wtf import Form
from wtforms import TextField, DecimalField, TextAreaField, DateField, validators, PasswordField, BooleanField
class CommentForm(Form):
text = TextField('Title', [validators.Required()])
text2 = TextAreaField('Body')
longitude = DecimalField('Longitude')
latitude = DecimalFie... | password = PasswordField('Password', [validators.Required()]) | identifier_body | |
forms.py | from flask_wtf import Form
from wtforms import TextField, DecimalField, TextAreaField, DateField, validators, PasswordField, BooleanField
class CommentForm(Form):
text = TextField('Title', [validators.Required()])
text2 = TextAreaField('Body')
longitude = DecimalField('Longitude')
latitude = DecimalFie... | password = PasswordField('Password', [validators.Required()])
class PasswordResetForm(Form):
username = TextField('Username')
email = TextField('eMail')
class PasswordChangeForm(Form):
password = PasswordField('Password', [validators.Required()]) |
class LoginForm(Form):
username = TextField('Username', [validators.Required()]) | random_line_split |
forms.py | from flask_wtf import Form
from wtforms import TextField, DecimalField, TextAreaField, DateField, validators, PasswordField, BooleanField
class CommentForm(Form):
text = TextField('Title', [validators.Required()])
text2 = TextAreaField('Body')
longitude = DecimalField('Longitude')
latitude = DecimalFie... | (Form):
username = TextField('Username', [validators.Required()])
password = PasswordField('Password', [validators.Required(), validators.EqualTo('confirm', message='Passwords must match')])
confirm = PasswordField('Confirm Password', [validators.Required()])
email = TextField('eMail', [validators.Requi... | SignupForm | identifier_name |
namespaced-enum-emulate-flat.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | A | B(_) | C { .. } => {}
}
}
mod nest {
pub use self::Bar::*;
pub enum Bar {
D,
E(int),
F { a: int },
}
impl Bar {
pub fn foo() {}
}
}
fn _f2(f: Bar) {
match f {
D | E(_) | F { .. } => {}
}
}
fn main() {} | fn _f(f: Foo) {
match f { | random_line_split |
namespaced-enum-emulate-flat.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
fn main() {}
| {} | conditional_block |
namespaced-enum-emulate-flat.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
D,
E(int),
F { a: int },
}
impl Bar {
pub fn foo() {}
}
}
fn _f2(f: Bar) {
match f {
D | E(_) | F { .. } => {}
}
}
fn main() {}
| Bar | identifier_name |
questions.py | # -*- coding: utf-8 -*-
"""
Module that implements the questions types
"""
import json
from . import errors
def question_factory(kind, *args, **kwargs):
for clazz in (Text, Password, Confirm, List, Checkbox):
if clazz.kind == kind:
return clazz(*args, **kwargs)
raise errors.UnknownQuesti... |
class Text(Question):
kind = 'text'
class Password(Question):
kind = 'password'
class Confirm(Question):
kind = 'confirm'
def __init__(self, name, default=False, **kwargs):
super(Confirm, self).__init__(name, default=default, **kwargs)
class List(Question):
kind = 'list'
class Ch... | if callable(prop):
return prop(self.answers, *args, **kwargs)
if isinstance(prop, str):
return prop.format(**self.answers)
return prop | identifier_body |
questions.py | # -*- coding: utf-8 -*-
"""
Module that implements the questions types
"""
import json
from . import errors
def question_factory(kind, *args, **kwargs):
for clazz in (Text, Password, Confirm, List, Checkbox):
if clazz.kind == kind:
return clazz(*args, **kwargs)
raise errors.UnknownQuesti... | (object):
kind = 'base question'
def __init__(self,
name,
message='',
choices=None,
default=None,
ignore=False,
validate=True):
self.name = name
self._message = message
self._choices = ... | Question | identifier_name |
questions.py | # -*- coding: utf-8 -*-
"""
Module that implements the questions types
"""
import json
from . import errors
def question_factory(kind, *args, **kwargs):
for clazz in (Text, Password, Confirm, List, Checkbox):
if clazz.kind == kind:
return clazz(*args, **kwargs)
raise errors.UnknownQuesti... |
if isinstance(prop, str):
return prop.format(**self.answers)
return prop
class Text(Question):
kind = 'text'
class Password(Question):
kind = 'password'
class Confirm(Question):
kind = 'confirm'
def __init__(self, name, default=False, **kwargs):
super(Confirm,... | return prop(self.answers, *args, **kwargs) | conditional_block |
questions.py | # -*- coding: utf-8 -*-
"""
Module that implements the questions types
"""
import json
from . import errors
def question_factory(kind, *args, **kwargs):
for clazz in (Text, Password, Confirm, List, Checkbox):
if clazz.kind == kind:
return clazz(*args, **kwargs)
raise errors.UnknownQuesti... | return prop
class Text(Question):
kind = 'text'
class Password(Question):
kind = 'password'
class Confirm(Question):
kind = 'confirm'
def __init__(self, name, default=False, **kwargs):
super(Confirm, self).__init__(name, default=default, **kwargs)
class List(Question):
kind ... | return prop.format(**self.answers) | random_line_split |
event-tap-debug.js | YUI.add('event-tap', function (Y, NAME) {
/**
The tap module provides a gesture events, "tap", which normalizes user interactions
across touch and mouse or pointer based input devices. This can be used by application developers
to build input device agnostic components which behave the same in response to either touc... | (subscription, handles, subset, context) {
handles = subset ? handles : [ handles.START, handles.MOVE, handles.END, handles.CANCEL ];
Y.Array.each(handles, function (item, index, array) {
var handle = subscription[item];
if (handle) {
handle.detach();
subscription[item]... | detachHelper | identifier_name |
event-tap-debug.js | YUI.add('event-tap', function (Y, NAME) {
/**
The tap module provides a gesture events, "tap", which normalizes user interactions
across touch and mouse or pointer based input devices. This can be used by application developers
to build input device agnostic components which behave the same in response to either touc... |
/**
Sets up a "tap" event, that is fired on touch devices in response to a tap event (finger down, finder up).
This event can be used instead of listening for click events which have a 500ms delay on most touch devices.
This event can also be listened for using node.delegate().
@event tap
@param type {string} "tap"... | {
handles = subset ? handles : [ handles.START, handles.MOVE, handles.END, handles.CANCEL ];
Y.Array.each(handles, function (item, index, array) {
var handle = subscription[item];
if (handle) {
handle.detach();
subscription[item] = null;
}
});
} | identifier_body |
event-tap-debug.js | YUI.add('event-tap', function (Y, NAME) {
/**
The tap module provides a gesture events, "tap", which normalizes user interactions
across touch and mouse or pointer based input devices. This can be used by application developers
to build input device agnostic components which behave the same in response to either touc... |
//Possibly outdated issue: something is off with the move that it attaches it but never triggers the handler
subscription[HANDLES.MOVE] = node.once(EVT_MOVE, this.touchMove, this, node, subscription, notifier, delegate, context);
subscription[HANDLES.END] = node.once(EVT_END, this.touchEnd, th... | {
context.startXY = [ event.pageX, event.pageY ];
} | conditional_block |
event-tap-debug.js | YUI.add('event-tap', function (Y, NAME) {
/**
The tap module provides a gesture events, "tap", which normalizes user interactions
across touch and mouse or pointer based input devices. This can be used by application developers
to build input device agnostic components which behave the same in response to either touc... | //move ways to quit early to the top.
// no right clicks
if (event.button && event.button === 3) {
return;
}
// for now just support a 1 finger count (later enhance via config)
if (event.touches && event.touches.length !== 1) {
return;
}
... | random_line_split | |
operation.ts | import ocl from './ocl'
import STLSurf from './stlsurf'
import CylCutter from './cylcutter'
import BallCutter from './ballcutter'
import BullCutter from './bullcutter'
import ConeCutter from './conecutter'
type Cutter = CylCutter | BallCutter | BullCutter | ConeCutter
class Operation {
protected surface?: STLSur... |
}
export default Operation | {
if (!this.cutter) return
if (this.cutter instanceof CylCutter) {
this.actualClass.setCylCutter(this.cutter.actualClass)
} else if (this.cutter instanceof BallCutter) {
this.actualClass.setBallCutter(this.cutter.actualClass)
} else if (this.cutter instanceof Bull... | identifier_body |
operation.ts | import ocl from './ocl'
import STLSurf from './stlsurf'
import CylCutter from './cylcutter'
import BallCutter from './ballcutter'
import BullCutter from './bullcutter'
import ConeCutter from './conecutter'
type Cutter = CylCutter | BallCutter | BullCutter | ConeCutter
class Operation {
protected surface?: STLSur... | (sampling: number) {
this.sampling = sampling
}
protected setCutterOnActualClass() {
if (!this.cutter) return
if (this.cutter instanceof CylCutter) {
this.actualClass.setCylCutter(this.cutter.actualClass)
} else if (this.cutter instanceof BallCutter) {
th... | setSampling | identifier_name |
operation.ts | import ocl from './ocl'
import STLSurf from './stlsurf'
import CylCutter from './cylcutter'
import BallCutter from './ballcutter'
import BullCutter from './bullcutter'
import ConeCutter from './conecutter'
type Cutter = CylCutter | BallCutter | BullCutter | ConeCutter
class Operation {
protected surface?: STLSur... | } else if (this.cutter instanceof BullCutter) {
this.actualClass.setBullCutter(this.cutter.actualClass)
} else if (this.cutter instanceof ConeCutter) {
this.actualClass.setConeCutter(this.cutter.actualClass)
}
}
}
export default Operation | this.actualClass.setBallCutter(this.cutter.actualClass) | random_line_split |
operation.ts | import ocl from './ocl'
import STLSurf from './stlsurf'
import CylCutter from './cylcutter'
import BallCutter from './ballcutter'
import BullCutter from './bullcutter'
import ConeCutter from './conecutter'
type Cutter = CylCutter | BallCutter | BullCutter | ConeCutter
class Operation {
protected surface?: STLSur... | else if (this.cutter instanceof BullCutter) {
this.actualClass.setBullCutter(this.cutter.actualClass)
} else if (this.cutter instanceof ConeCutter) {
this.actualClass.setConeCutter(this.cutter.actualClass)
}
}
}
export default Operation | {
this.actualClass.setBallCutter(this.cutter.actualClass)
} | conditional_block |
waitForExist.js | /**
*
* Wait for an element (selected by css selector) for the provided amount of
* milliseconds to be present within the DOM. Returns true if the selector
* matches at least one element that exists in the DOM, otherwise throws an
* error. If the reverse flag is true, the command will instead return true
* if the... |
}
return result !== reverse
})
}, ms, errorMsg)
}
export default waitForExist
| {
result = result && val
} | conditional_block |
waitForExist.js | /**
*
* Wait for an element (selected by css selector) for the provided amount of
* milliseconds to be present within the DOM. Returns true if the selector
* matches at least one element that exists in the DOM, otherwise throws an
* error. If the reverse flag is true, the command will instead return true
* if the... | form.submit();
notification.waitForExist(5000); // same as `browser.waitForExist('.notification', 5000)`
expect(notification.getText()).to.be.equal('Data transmitted successfully!')
});
* </example>
*
* @alias browser.waitForExist
* @param {String} selector element selector to wait for... | it('should display a notification message after successful form submit', function () {
var form = $('form');
var notification = $('.notification');
| random_line_split |
slave.py | #!/usr/bin/env python3
# Requires PyAudio and PySpeech.
import speech_recognition as sr
from fuzzywuzzy import fuzz
from time import ctime
import time
import os
from subprocess import Popen
from gtts import gTTS
import sys
import pyjokes
import SR
import sys
#stderr = open('slave.log', 'w')
#sys.stderr = stderr
devnu... |
# tts = gTTS(text=text, lang='en')
# tts.save("audio.mp3")
# Popen(["mpg321", "audio.mp3"], stdout=devnull, stderr=devnull)
def nearest_word(word, words):
max = 0
for w in words:
d = fuzz.ratio(w, word)
if d > max:
new = w
max = d
return (new, max)
r = sr.Recognizer()
#r.energy_threshold = 2
while True... | print(">", text) | identifier_body |
slave.py | #!/usr/bin/env python3
# Requires PyAudio and PySpeech.
import speech_recognition as sr
from fuzzywuzzy import fuzz
from time import ctime
import time
import os
from subprocess import Popen
from gtts import gTTS
import sys
import pyjokes
import SR
import sys
#stderr = open('slave.log', 'w')
#sys.stderr = stderr
devnu... | (word, words):
max = 0
for w in words:
d = fuzz.ratio(w, word)
if d > max:
new = w
max = d
return (new, max)
r = sr.Recognizer()
#r.energy_threshold = 2
while True:
speak("Alan, what do you want me to do?")
# Record Audio
with sr.Microphone() as source:
print("Say something!")
r.adjust_for_amb... | nearest_word | identifier_name |
slave.py | #!/usr/bin/env python3
# Requires PyAudio and PySpeech.
import speech_recognition as sr
from fuzzywuzzy import fuzz
from time import ctime
import time
import os
from subprocess import Popen
from gtts import gTTS
import sys
import pyjokes
import SR
import sys | say = 1
run = 2
exe = 3
fun = 4
cti = ctime()
#joke = pyjokes.get_joke()
cmds = {
"amazon" : (web, "http://amazon.co.uk/"),
"calculator": (run, "galculator"),
"chess" : (run, "xboard"),
"commands" : (exe, "xxx"),
"dictation" : (web, "https://dictation.io/"),
"files" : (run, "pcmanfm"),
"googl... | #stderr = open('slave.log', 'w')
#sys.stderr = stderr
devnull = open(os.devnull, 'w')
browser = "google-chrome"
web = 0 | random_line_split |
slave.py | #!/usr/bin/env python3
# Requires PyAudio and PySpeech.
import speech_recognition as sr
from fuzzywuzzy import fuzz
from time import ctime
import time
import os
from subprocess import Popen
from gtts import gTTS
import sys
import pyjokes
import SR
import sys
#stderr = open('slave.log', 'w')
#sys.stderr = stderr
devnu... |
else:
try:
Popen(text)
except FileNotFoundError:
speak("I don't know, really I don't. Sorry")
| Popen(p) | conditional_block |
includes.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... | */
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'includes',
})
export class IncludesPipe implements PipeTransform {
public transform(items: any[], item: any): boolean {
return items?.includes(item);
}
} | * 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/>. | random_line_split |
includes.pipe.ts | /*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* 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 ... | implements PipeTransform {
public transform(items: any[], item: any): boolean {
return items?.includes(item);
}
}
| IncludesPipe | identifier_name |
ViewFrog.py | #!/usr/bin/env python
"""
"""
import vtk
def view_frog(fileName, tissues):
colors = vtk.vtkNamedColors()
tissueMap = CreateTissueMap()
colorLut = CreateFrogLut()
# Setup render window, renderer, and interactor.
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWind... | main() | conditional_block | |
ViewFrog.py | #!/usr/bin/env python
"""
"""
import vtk
def view_frog(fileName, tissues):
colors = vtk.vtkNamedColors()
tissueMap = CreateTissueMap()
colorLut = CreateFrogLut()
# Setup render window, renderer, and interactor.
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWind... | colorLut.SetTableValue(9, colors.GetColor4d("peru")) # l_intestine
colorLut.SetTableValue(10, colors.GetColor4d("pink")) # liver
colorLut.SetTableValue(11, colors.GetColor4d("powder_blue")) # lung
colorLut.SetTableValue(12, colors.GetColor4d("carrot")) # nerve
colorLut.SetTableValue(13, colors.G... | random_line_split | |
ViewFrog.py | #!/usr/bin/env python
"""
"""
import vtk
def view_frog(fileName, tissues):
colors = vtk.vtkNamedColors()
tissueMap = CreateTissueMap()
colorLut = CreateFrogLut()
# Setup render window, renderer, and interactor.
renderer = vtk.vtkRenderer()
renderWindow = vtk.vtkRenderWindow()
renderWind... |
def CreateFrogLut():
colors = vtk.vtkNamedColors()
colorLut = vtk.vtkLookupTable()
colorLut.SetNumberOfColors(17)
colorLut.SetTableRange(0, 16)
colorLut.Build()
colorLut.SetTableValue(0, 0, 0, 0, 0)
colorLut.SetTableValue(1, colors.GetColor4d("salmon")) # blood
colorLut.SetTableVal... | import argparse
description = 'The complete frog without skin.'
epilogue = '''
For Figure 12-9b in the VTK Book:
Specify these tissues as parameters after the file name:
blood brain duodenum eyeRetina eyeWhite heart ileum kidney intestine liver lung nerve skeleton spleen stomach
'''
pa... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.