file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
QueuingHandler.ts | import { AbstractHandler } from './AbstractHandler';
import * as AWS from 'aws-sdk';
import { Request } from '../Request';
import { InternalServerError } from '../Errors';
import { Response } from '../Response';
import { AmazonResourceName, SQSQueueARN } from '../Utilities';
import { QueuingHandlerConfig } from '../Con... | }
/**
* Sends an empty 200 OK response. If your handler needs to return something different, you can override this
* method.
* @param {Response} response
* @param {AWS.SQS.SendMessageResult} data The response from SQS. This may be null, if the message was not
... | } | random_line_split |
QueuingHandler.ts | import { AbstractHandler } from './AbstractHandler';
import * as AWS from 'aws-sdk';
import { Request } from '../Request';
import { InternalServerError } from '../Errors';
import { Response } from '../Response';
import { AmazonResourceName, SQSQueueARN } from '../Utilities';
import { QueuingHandlerConfig } from '../Con... | (sqsData: AWS.SQS.SendMessageResult): Promise<any> {
if (this.config.notifySNSTopic) {
// Build our SNS publish params.
const params: AWS.SNS.PublishInput = this.buildSNSMessage(
AmazonResourceName.normalize(this.config.notifySNSTopic),
sqsData
... | publishToSNS | identifier_name |
QueuingHandler.ts | import { AbstractHandler } from './AbstractHandler';
import * as AWS from 'aws-sdk';
import { Request } from '../Request';
import { InternalServerError } from '../Errors';
import { Response } from '../Response';
import { AmazonResourceName, SQSQueueARN } from '../Utilities';
import { QueuingHandlerConfig } from '../Con... | else {
// There's no message to queue, so lets not do anything.
return Promise.resolve(null);
}
})
.then((data: AWS.SQS.SendMessageResult) => {
return this.sendResponse(response, data);
})
}
/**
* You can override this method... | {
// Send request to SQS
let param = this.buildSQSmessage();
let sqs = new AWS.SQS;
return sqs.sendMessage(param)
.promise()
.then((data: AWS.SQS.SendMessageResult) => {
// Send a SNS notifica... | conditional_block |
filepath-utils.ts | import { lstatSync } from 'fs';
import { sep } from 'path';
const reNormalize = sep !== '/' ? new RegExp(sep.replace(/\\/g, '\\\\'), 'g') : null;
| import logUtils from '../utils/log-utils';
const log = logUtils.log;
const normalizePath = function(path: string): string {
if (reNormalize) {
path = path.replace(reNormalize, '/');
}
return path;
}
const createFileTestFunc = function(absolutePaths: string[], debugStr?: string): (path: s... | random_line_split | |
filepath-utils.ts |
import { lstatSync } from 'fs';
import { sep } from 'path';
const reNormalize = sep !== '/' ? new RegExp(sep.replace(/\\/g, '\\\\'), 'g') : null;
import logUtils from '../utils/log-utils';
const log = logUtils.log;
const normalizePath = function(path: string): string {
if (reNormalize) |
return path;
}
const createFileTestFunc = function(absolutePaths: string[], debugStr?: string): (path: string) => boolean {
debugStr = debugStr || '';
const reTest = absolutePaths.map(function(absolutePath) {
return new RegExp('^' + absolutePath.replace(/\./g, '\\.') + '$');
});
... | {
path = path.replace(reNormalize, '/');
} | conditional_block |
utility.ts | const boolType = "boolean"
const funType = "function";
const stringType = "string";
export function isFunction(obj: any) {
if (!obj)
return null;
return typeof obj === funType;
}
export function isUndefined(obj: any) {
return obj === undefined;
}
export function getFullDateFormated() {
function getTime(timeDig... | }
return htmlTemplate;
}
}
(<any>getTemplate).interpolateReg = "{{key}}";
export function getHtmlAsString(htmlPath: any) {
let fs = require('fs');
let path = require('path');
let strinfData = fs.readFileSync(path.resolve(`${__dirname}/${htmlPath}`), 'utf-8');
return strinfData;
} | htmlTemplate = htmlTemplate.replace(reg, data[keys[i]]); | random_line_split |
utility.ts | const boolType = "boolean"
const funType = "function";
const stringType = "string";
export function isFunction(obj: any) {
if (!obj)
return null;
return typeof obj === funType;
}
export function isUndefined(obj: any) {
return obj === undefined;
}
export function getFullDateFormated() {
function getTime(timeDig... |
export function isBoolean(obj: any) {
if (!obj)
return null;
return typeof obj === boolType;
}
export function isString(obj: any) {
if (!obj)
return null;
return typeof obj === stringType;
}
export function getTemplate(htmlTemplate: string) {
return function (data: any) {
let keys = Object.keys(data);
... | {
return obj === null;
} | identifier_body |
utility.ts | const boolType = "boolean"
const funType = "function";
const stringType = "string";
export function isFunction(obj: any) {
if (!obj)
return null;
return typeof obj === funType;
}
export function isUndefined(obj: any) {
return obj === undefined;
}
export function getFullDateFormated() {
function | (timeDigit: number) {
return timeDigit < 9 ? `0${timeDigit}` : timeDigit;
}
const date = new Date();
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}-${getTime(date.getHours() + 1)}:${getTime(date.getMinutes() + 1)}`;
}
export function isNull(obj: any) {
return obj === null;
}
export funct... | getTime | identifier_name |
reshaped_breakout.py | from control4.misc.console_utils import call_and_print,Message
import os.path as osp
from control4.core.rollout import rollout
from control4.algs.save_load_utils import get_mdp,construct_agent,load_agent_and_mdp
from control4.maths.discount import discount
from control4.config import floatX
import numpy as np
from coll... |
init,traj = rollout(mdp, agent, max_steps,save_arrs=save_arrs)
o = np.concatenate([init["o"]]+traj["o"][:-1])
c = np.concatenate(traj["c"])
v = np.concatenate(traj['v'])
paths.append(Path(o,c,v))
# Regression
oall = np.concatenate([path.o for path in paths],axis=0).astype(floa... | print "%i/%i done"%(i_path,num_trajs) | conditional_block |
reshaped_breakout.py | from control4.misc.console_utils import call_and_print,Message
import os.path as osp
from control4.core.rollout import rollout
from control4.algs.save_load_utils import get_mdp,construct_agent,load_agent_and_mdp
from control4.maths.discount import discount
from control4.config import floatX
import numpy as np
from coll... |
_,arrs = rollout(mdp,agent,max_steps,save_arrs=("c",),callback=plot_callback)
| mdp.plot(arrs)
# vs.append(arrs['v'].sum())
vs.append(f(arrs['o'][:,goodinds]).sum())
cs.append(arrs['c'].sum())
if len(vs) > 1:
delta = cs[-1] + gamma * vs[-2] - vs[-1]
deltas.append(delta)
if len(vs) % 4 == 0:
plt.cla()
plt.plot(cs,'b')
plt.p... | identifier_body |
reshaped_breakout.py | from control4.misc.console_utils import call_and_print,Message
import os.path as osp
from control4.core.rollout import rollout
from control4.algs.save_load_utils import get_mdp,construct_agent,load_agent_and_mdp
from control4.maths.discount import discount
from control4.config import floatX
import numpy as np
from coll... | (arrs):
mdp.plot(arrs)
# vs.append(arrs['v'].sum())
vs.append(f(arrs['o'][:,goodinds]).sum())
cs.append(arrs['c'].sum())
if len(vs) > 1:
delta = cs[-1] + gamma * vs[-2] - vs[-1]
deltas.append(delta)
if len(vs) % 4 == 0:
plt.cla()
plt.plot(cs,'b')
... | plot_callback | identifier_name |
reshaped_breakout.py | from control4.misc.console_utils import call_and_print,Message
import os.path as osp
from control4.core.rollout import rollout
from control4.algs.save_load_utils import get_mdp,construct_agent,load_agent_and_mdp
from control4.maths.discount import discount
from control4.config import floatX
import numpy as np
from coll... | paths = []
for i_path in xrange(num_trajs):
if i_path % 20 == 0:
print "%i/%i done"%(i_path,num_trajs)
init,traj = rollout(mdp, agent, max_steps,save_arrs=save_arrs)
o = np.concatenate([init["o"]]+traj["o"][:-1])
c = np.concatenate(traj["c"])
v = np.concatenat... | save_arrs = ["o","c",'v']
with Message("Doing rollouts"): | random_line_split |
committed.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | else {
output_commits.push(over_commit);
}
}
sum_commits(output_commits, input_commits)
}
/// Vector of input commitments to verify.
fn inputs_committed(&self) -> Vec<Commitment>;
/// Vector of output commitments to verify.
fn outputs_committed(&self) -> Vec<Commitment>;
/// Vector of kernel exces... | {
input_commits.push(over_commit);
} | conditional_block |
committed.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... |
}
/// Utility to sum positive and negative commitments, eliminating zero values
pub fn sum_commits(
mut positive: Vec<Commitment>,
mut negative: Vec<Commitment>,
) -> Result<Commitment, Error> {
let zero_commit = secp_static::commit_to_zero_value();
positive.retain(|x| *x != zero_commit);
negative.retain(|x| *x ... | {
// Sum all input|output|overage commitments.
let utxo_sum = self.sum_commitments(overage)?;
// Sum the kernel excesses accounting for the kernel offset.
let (kernel_sum, kernel_sum_plus_offset) = self.sum_kernel_excesses(&kernel_offset)?;
if utxo_sum != kernel_sum_plus_offset {
return Err(Error::Kernel... | identifier_body |
committed.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | (e: keychain::Error) -> Error {
Error::Keychain(e)
}
}
/// Implemented by types that hold inputs and outputs (and kernels)
/// containing Pedersen commitments.
/// Handles the collection of the commitments as well as their
/// summing, taking potential explicit overages of fees into account.
pub trait Committed {
... | from | identifier_name |
committed.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! The Committed trait and associated errors.
use failure::Fail;
us... | // 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, software | random_line_split |
error.rs | use std::old_io::IoError;
use std::error::Error;
use std::fmt;
pub type ProtobufResult<T> = Result<T, ProtobufError>;
#[derive(Debug,Eq,PartialEq)]
pub enum ProtobufError {
IoError(IoError),
WireError(String),
}
impl fmt::Display for ProtobufError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
... | (&self) -> Option<&Error> {
match self {
&ProtobufError::IoError(ref e) => Some(e as &Error),
&ProtobufError::WireError(..) => None,
}
}
}
| cause | identifier_name |
error.rs | use std::old_io::IoError;
use std::error::Error;
use std::fmt;
pub type ProtobufResult<T> = Result<T, ProtobufError>;
#[derive(Debug,Eq,PartialEq)]
pub enum ProtobufError { | }
impl fmt::Display for ProtobufError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
impl Error for ProtobufError {
fn description(&self) -> &str {
match self {
// not sure that cause should be included in message
&ProtobufErro... | IoError(IoError),
WireError(String), | random_line_split |
error.rs | use std::old_io::IoError;
use std::error::Error;
use std::fmt;
pub type ProtobufResult<T> = Result<T, ProtobufError>;
#[derive(Debug,Eq,PartialEq)]
pub enum ProtobufError {
IoError(IoError),
WireError(String),
}
impl fmt::Display for ProtobufError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
impl Error for ProtobufError {
fn description(&self) -> &str {
match self {
// not sure that cause should be included in message
&ProtobufError::IoError(ref e) => e.description(),
&ProtobufError::WireError(ref e) => e.as_slice(),
}
}
fn cause(&self) -... | {
fmt::Debug::fmt(self, f)
} | identifier_body |
types.rs | use byteorder::{BigEndian, WriteBytesExt};
use protobuf::Message;
use std::io::Write;
use crate::protocol;
#[derive(Debug, PartialEq, Eq)]
pub enum MercuryMethod {
Get,
Sub,
Unsub,
Send,
}
#[derive(Debug)]
pub struct MercuryRequest {
pub method: MercuryMethod,
pub uri: String,
pub content... | (&self) -> u8 {
match *self {
MercuryMethod::Get | MercuryMethod::Send => 0xb2,
MercuryMethod::Sub => 0xb3,
MercuryMethod::Unsub => 0xb4,
}
}
}
impl MercuryRequest {
pub fn encode(&self, seq: &[u8]) -> Vec<u8> {
let mut packet = Vec::new();
pa... | command | identifier_name |
types.rs | use byteorder::{BigEndian, WriteBytesExt};
use protobuf::Message;
use std::io::Write;
use crate::protocol;
#[derive(Debug, PartialEq, Eq)]
pub enum MercuryMethod {
Get,
Sub,
Unsub,
Send,
}
#[derive(Debug)]
pub struct MercuryRequest {
pub method: MercuryMethod,
pub uri: String,
pub content... | header.write_to_writer(&mut packet).unwrap();
for p in &self.payload {
packet.write_u16::<BigEndian>(p.len() as u16).unwrap();
packet.write(p).unwrap();
}
packet
}
} | random_line_split | |
queryutils.py |
from msaf.models import dbsession, Sample, Marker, Batch
from msaf.lib.analytics import SampleSet
from itertools import cycle
import yaml
def load_yaml(yaml_text):
d = yaml.load( yaml_text )
instances = {}
for k in d:
if k == 'selector':
instances['selector'] = Selector.from_dic... |
def dump(self):
d = self.to_dict()
return yaml.dump( d )
def get_sample_ids(self, db):
""" return sample ids; db is SQLa dbsession handler """
pass
def get_marker_ids(self):
""" return marker ids; db is SQLa dbsession handler """
# self.markers is name
... | d = yaml.load( yaml_text )
selector = Selector.from_dict( d )
return selector | identifier_body |
queryutils.py |
from msaf.models import dbsession, Sample, Marker, Batch
from msaf.lib.analytics import SampleSet
from itertools import cycle
import yaml
def load_yaml(yaml_text):
d = yaml.load( yaml_text )
instances = {}
for k in d:
if k == 'selector':
instances['selector'] = Selector.from_dic... |
sample_ids = []
sample_selector = self.samples[label]
for spec in sample_selector:
if 'query' in spec:
if '$' in spec['query']:
raise RuntimeError('query most not an advance one')
... | pass | conditional_block |
queryutils.py |
from msaf.models import dbsession, Sample, Marker, Batch
from msaf.lib.analytics import SampleSet
from itertools import cycle
import yaml
def load_yaml(yaml_text):
d = yaml.load( yaml_text )
instances = {}
for k in d:
if k == 'selector':
instances['selector'] = Selector.from_dic... | (object):
def __init__(self):
self.spatial = 0
self.temporal = 0
self.differentiation = 0
@staticmethod
def from_dict(d):
differentiation = Differentiation()
differentiation.spatial = d['spatial']
differentiation.temporal = d['temporal']
differentiat... | Differentiation | identifier_name |
queryutils.py | from msaf.models import dbsession, Sample, Marker, Batch
from msaf.lib.analytics import SampleSet
from itertools import cycle
import yaml
def load_yaml(yaml_text):
d = yaml.load( yaml_text )
instances = {}
for k in d:
if k == 'selector':
instances['selector'] = Selector.from_dict(... |
@staticmethod
def load(yaml_text):
pass
def dump(self):
pass
class Differentiation(object):
def __init__(self):
self.spatial = 0
self.temporal = 0
self.differentiation = 0
@staticmethod
def from_dict(d):
differentiation = Differentiation()
... | return filter_params
def to_dict(self):
pass | random_line_split |
test_distribute.py | from pathlib import Path
from subprocess import (PIPE, Popen)
import fnmatch
import shutil
import os
def test_distribute(tmp_path):
"""
Check that the scripts to compute a trajectory are generated correctly
"""
cmd1 = "distribute_jobs.py -i test/test_files/input_test_distribute_derivative_couplings.ym... |
def check_scripts():
"""
Check that the distribution scripts were created correctly
"""
paths = fnmatch.filter(os.listdir('.'), "chunk*")
# Check that the files are created correctly
files = ["launch.sh", "chunk_xyz*", "input.yml"]
for p in paths:
p = Path(p)
for f in fil... | """
Execute the distribute script and check that if finish succesfully.
"""
try:
p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
out, err = p.communicate()
if err:
raise RuntimeError(err)
check_scripts()
finally:
remove_chunk_folder() | identifier_body |
test_distribute.py | from pathlib import Path
from subprocess import (PIPE, Popen)
import fnmatch
import shutil
import os
def test_distribute(tmp_path):
"""
Check that the scripts to compute a trajectory are generated correctly
"""
cmd1 = "distribute_jobs.py -i test/test_files/input_test_distribute_derivative_couplings.ym... | out, err = p.communicate()
if err:
raise RuntimeError(err)
check_scripts()
finally:
remove_chunk_folder()
def check_scripts():
"""
Check that the distribution scripts were created correctly
"""
paths = fnmatch.filter(os.listdir('.'), "chunk*")
# Che... | p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) | random_line_split |
test_distribute.py | from pathlib import Path
from subprocess import (PIPE, Popen)
import fnmatch
import shutil
import os
def test_distribute(tmp_path):
"""
Check that the scripts to compute a trajectory are generated correctly
"""
cmd1 = "distribute_jobs.py -i test/test_files/input_test_distribute_derivative_couplings.ym... |
def remove_chunk_folder():
""" Remove resulting scripts """
for path in fnmatch.filter(os.listdir('.'), "chunk*"):
shutil.rmtree(path)
| p = Path(p)
for f in files:
try:
next(p.glob(f))
except StopIteration:
msg = f"There is not file: {f}"
print(msg)
raise RuntimeError(msg) | conditional_block |
test_distribute.py | from pathlib import Path
from subprocess import (PIPE, Popen)
import fnmatch
import shutil
import os
def test_distribute(tmp_path):
"""
Check that the scripts to compute a trajectory are generated correctly
"""
cmd1 = "distribute_jobs.py -i test/test_files/input_test_distribute_derivative_couplings.ym... | ():
""" Remove resulting scripts """
for path in fnmatch.filter(os.listdir('.'), "chunk*"):
shutil.rmtree(path)
| remove_chunk_folder | identifier_name |
models.py | from __future__ import unicode_literals
from django.db import models
class Person(models.Model):
""" Person model """
gender_choices = (
('male', 'Male'),
('female', 'Female')
)
firstName = models.CharField(max_length=50, blank=True, null=True)
surname = models.CharField(max_lengt... |
@property
def suggested_friends(self):
""" Property for list of suggested friends """
exclude_pks = list(self.friends.all().values_list('pk', flat=True))
exclude_pks.append(self.pk)
suggested_friends = []
for person in Person.objects.exclude(pk__in=exclude_pks):
... | """ Property for list of friends of friends """
persons = Person.objects.filter(pk__in=self.friends.all()).values_list(
'friends', flat=True).distinct()
return persons | identifier_body |
models.py | from __future__ import unicode_literals
from django.db import models
class Person(models.Model):
""" Person model """
gender_choices = (
('male', 'Male'),
('female', 'Female')
)
firstName = models.CharField(max_length=50, blank=True, null=True)
surname = models.CharField(max_lengt... | (self):
return self.full_name
@property
def friends_of_friends(self):
""" Property for list of friends of friends """
persons = Person.objects.filter(pk__in=self.friends.all()).values_list(
'friends', flat=True).distinct()
return persons
@property
def sugges... | __unicode__ | identifier_name |
models.py | from __future__ import unicode_literals
from django.db import models
class Person(models.Model):
""" Person model """
gender_choices = (
('male', 'Male'),
('female', 'Female')
)
firstName = models.CharField(max_length=50, blank=True, null=True)
surname = models.CharField(max_lengt... |
return suggested_friends
| suggested_friends.append(person.pk) | conditional_block |
models.py | from __future__ import unicode_literals
from django.db import models
class Person(models.Model):
""" Person model """
gender_choices = (
('male', 'Male'),
('female', 'Female')
)
firstName = models.CharField(max_length=50, blank=True, null=True)
surname = models.CharField(max_lengt... | def friends_of_friends(self):
""" Property for list of friends of friends """
persons = Person.objects.filter(pk__in=self.friends.all()).values_list(
'friends', flat=True).distinct()
return persons
@property
def suggested_friends(self):
""" Property for list of s... |
def __unicode__(self):
return self.full_name
@property | random_line_split |
prometheus.py | from kvmagent import kvmagent
from zstacklib.utils import jsonobject
from zstacklib.utils import http
from zstacklib.utils import log
from zstacklib.utils.bash import *
from zstacklib.utils import linux
from zstacklib.utils import thread
from jinja2 import Template
import os.path
import re
import time
import traceback
... | (self):
class Collector(object):
def collect(self):
try:
ret = []
for c in kvmagent.metric_collectors:
ret.extend(c())
return ret
except Exception as e:
content = ... | install_colletor | identifier_name |
prometheus.py | from kvmagent import kvmagent
from zstacklib.utils import jsonobject
from zstacklib.utils import http
from zstacklib.utils import log
from zstacklib.utils.bash import *
from zstacklib.utils import linux
from zstacklib.utils import thread
from jinja2 import Template
import os.path
import re
import time
import traceback
... |
def install_colletor(self):
class Collector(object):
def collect(self):
try:
ret = []
for c in kvmagent.metric_collectors:
ret.extend(c())
return ret
except Exception as e:
... | cmd = jsonobject.loads(req[http.REQUEST_BODY])
rsp = kvmagent.AgentResponse()
eths = bash_o("ls /sys/class/net").split()
interfaces = []
for eth in eths:
eth = eth.strip(' \t\n\r')
if eth == 'lo': continue
elif eth.startswith('vnic'): continue
... | identifier_body |
prometheus.py | from kvmagent import kvmagent
from zstacklib.utils import jsonobject
from zstacklib.utils import http
from zstacklib.utils import log
from zstacklib.utils.bash import *
from zstacklib.utils import linux
from zstacklib.utils import thread
from jinja2 import Template
import os.path |
logger = log.get_logger(__name__)
class PrometheusPlugin(kvmagent.KvmAgent):
COLLECTD_PATH = "/prometheus/collectdexporter/start"
@kvmagent.replyerror
@in_bash
def start_collectd_exporter(self, req):
cmd = jsonobject.loads(req[http.REQUEST_BODY])
rsp = kvmagent.AgentResponse()
... | import re
import time
import traceback
from prometheus_client.core import GaugeMetricFamily,REGISTRY
from prometheus_client import start_http_server | random_line_split |
prometheus.py | from kvmagent import kvmagent
from zstacklib.utils import jsonobject
from zstacklib.utils import http
from zstacklib.utils import log
from zstacklib.utils.bash import *
from zstacklib.utils import linux
from zstacklib.utils import thread
from jinja2 import Template
import os.path
import re
import time
import traceback
... |
else:
interfaces.append(eth)
conf_path = os.path.join(os.path.dirname(cmd.binaryPath), 'collectd.conf')
conf = '''Interval {{INTERVAL}}
FQDNLookup false
LoadPlugin syslog
LoadPlugin aggregation
LoadPlugin cpu
LoadPlugin disk
LoadPlugin interface
LoadPlugin memory
LoadPlug... | continue | conditional_block |
tests.rs | use super::*;
#[test]
fn test_struct_info_roundtrip() {
let s = ItemEnum::Struct(Struct {
struct_type: StructType::Plain,
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let struct_json = se... | impls: vec![],
});
let union_json = serde_json::to_string(&u).unwrap();
let de_u = serde_json::from_str(&union_json).unwrap();
assert_eq!(u, de_u);
} | random_line_split | |
tests.rs | use super::*;
#[test]
fn test_struct_info_roundtrip() {
let s = ItemEnum::Struct(Struct {
struct_type: StructType::Plain,
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let struct_json = se... | {
let u = ItemEnum::Union(Union {
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let union_json = serde_json::to_string(&u).unwrap();
let de_u = serde_json::from_str(&union_json).unwrap();
... | identifier_body | |
tests.rs | use super::*;
#[test]
fn test_struct_info_roundtrip() {
let s = ItemEnum::Struct(Struct {
struct_type: StructType::Plain,
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let struct_json = se... | () {
let u = ItemEnum::Union(Union {
generics: Generics { params: vec![], where_predicates: vec![] },
fields_stripped: false,
fields: vec![],
impls: vec![],
});
let union_json = serde_json::to_string(&u).unwrap();
let de_u = serde_json::from_str(&union_json).unwrap();
... | test_union_info_roundtrip | identifier_name |
year.ts | import {Component, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
@Component({
selector: 'ngl-date-year',
templateUrl: './year.jade',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class | {
// How many years before and after the current one are selectable in dropdown
@Input() numYearsBefore: number = 100;
@Input() numYearsAfter: number = 10;
year: number;
@Input('year') set setYear(year: string | number) {
this.year = +year;
}
@Output() yearChange = new EventEmitter();
get range(... | NglDatepickerYear | identifier_name |
year.ts | import {Component, Input, Output, EventEmitter, ChangeDetectionStrategy} from '@angular/core';
@Component({
selector: 'ngl-date-year',
templateUrl: './year.jade',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NglDatepickerYear {
// How many years before and after the current one are selecta... | get range(): number[] {
const currentYear = (new Date()).getFullYear();
const firstYear = Math.min(currentYear - this.numYearsBefore, this.year);
const size = Math.max(currentYear + this.numYearsAfter, this.year) - firstYear;
return Array.apply(null, {length: size + 1}).map((value: any, index: number)... | @Output() yearChange = new EventEmitter();
| random_line_split |
01_RedditlistCrawler.py | import requests
from bs4 import BeautifulSoup
import urllib2 # require python 2.0
"""
1. Get all subreddit name from redditlist.com
using urllib and BeautifulSoup library
"""
def get_subreddit_list(max_pages):
"""
Get all of the top ~4000 subreddits
from http://www.redditlist.com
... |
print("Collect "+str(subreddits_count)+" subreddits")
# Query on 33 PAGES of http://www.redditlist.com
get_subreddit_list(33) | subreddit_url = "http://reddit.com/r/"
if subreddit_url in subreddit:
print subreddit[20:]
#subreddit_list.append(subreddit[20:])
with open("./Resources/subreddit_list.txt", "a") as myfile:
# comment (important)
myfile.write("{} \n".format(subr... | conditional_block |
01_RedditlistCrawler.py | import requests
from bs4 import BeautifulSoup
import urllib2 # require python 2.0
"""
1. Get all subreddit name from redditlist.com
using urllib and BeautifulSoup library
"""
def get_subreddit_list(max_pages):
"""
Get all of the top ~4000 subreddits
from http://www.redditlist.com
... | url = "http://www.redditlist.com?page="+str(page)
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
for link in soup.findAll("a",{"class":"sfw"}):
href = link.get("href")
subs.append(href)
... | else: | random_line_split |
01_RedditlistCrawler.py | import requests
from bs4 import BeautifulSoup
import urllib2 # require python 2.0
"""
1. Get all subreddit name from redditlist.com
using urllib and BeautifulSoup library
"""
def | (max_pages):
"""
Get all of the top ~4000 subreddits
from http://www.redditlist.com
"""
page = 1
subs = []
print("Getting subreddits...")
while page <= max_pages:
print("Crawling Page "+ str(page))
if page == 1 :
url = "http://www.redditlist.com"
... | get_subreddit_list | identifier_name |
01_RedditlistCrawler.py | import requests
from bs4 import BeautifulSoup
import urllib2 # require python 2.0
"""
1. Get all subreddit name from redditlist.com
using urllib and BeautifulSoup library
"""
def get_subreddit_list(max_pages):
|
# Query on 33 PAGES of http://www.redditlist.com
get_subreddit_list(33) | """
Get all of the top ~4000 subreddits
from http://www.redditlist.com
"""
page = 1
subs = []
print("Getting subreddits...")
while page <= max_pages:
print("Crawling Page "+ str(page))
if page == 1 :
url = "http://www.redditlist.com"
else:
... | identifier_body |
Stack.js | "use strict";
var LinkedList_1 = require('./LinkedList');
var Stack = (function () {
function Stack(contents) {
if (contents === void 0) { contents = null; }
this.list = new LinkedList_1.LinkedList(contents);
}
Stack.prototype.each = function (e) {
this.list.each(e);
};
Stack... | Stack.prototype.count = function () {
return this.list.count();
};
Stack.prototype.toArray = function () {
return this.list.toArray();
};
return Stack;
}());
exports.Stack = Stack;
//# sourceMappingURL=Stack.js.map | this.list.add(item);
}
}; | random_line_split |
Stack.js | "use strict";
var LinkedList_1 = require('./LinkedList');
var Stack = (function () {
function | (contents) {
if (contents === void 0) { contents = null; }
this.list = new LinkedList_1.LinkedList(contents);
}
Stack.prototype.each = function (e) {
this.list.each(e);
};
Stack.prototype.peek = function () {
return this.list.first();
};
Stack.prototype.pop = func... | Stack | identifier_name |
Stack.js | "use strict";
var LinkedList_1 = require('./LinkedList');
var Stack = (function () {
function Stack(contents) |
Stack.prototype.each = function (e) {
this.list.each(e);
};
Stack.prototype.peek = function () {
return this.list.first();
};
Stack.prototype.pop = function () {
var item = this.list.last();
if (item) {
this.list.remove(item);
}
return ite... | {
if (contents === void 0) { contents = null; }
this.list = new LinkedList_1.LinkedList(contents);
} | identifier_body |
Stack.js | "use strict";
var LinkedList_1 = require('./LinkedList');
var Stack = (function () {
function Stack(contents) {
if (contents === void 0) { contents = null; }
this.list = new LinkedList_1.LinkedList(contents);
}
Stack.prototype.each = function (e) {
this.list.each(e);
};
Stack... |
else {
this.list.add(item);
}
};
Stack.prototype.count = function () {
return this.list.count();
};
Stack.prototype.toArray = function () {
return this.list.toArray();
};
return Stack;
}());
exports.Stack = Stack;
//# sourceMappingURL=Stack.js.map | {
this.list.insertBefore(this.list.first(), item);
} | conditional_block |
Products.js | import React from 'react';
import PropTypes from 'prop-types';
import { connect} from 'react-redux';
import UmsgContainer from '../containers/UmsgContainer';
import Sidebar from '../components/Sidebar'
import Item from '../components/Item'
import { fetchCategory, searchItems } from '../store/actions/items'
class Prod... |
}
refresh() {
const { params } = this.props;
if (params.category) {
fetchCategory(params.category);
} else {
searchItems(encodeURIComponent(params.search));
}
}
render() {
const {items, isLoading} = this.props;
let content = items.map(i => (<Item key={i.get('_id')} item={i} ... | {
this.refresh();
} | conditional_block |
Products.js | import React from 'react';
import PropTypes from 'prop-types';
import { connect} from 'react-redux';
import UmsgContainer from '../containers/UmsgContainer';
import Sidebar from '../components/Sidebar'
import Item from '../components/Item'
import { fetchCategory, searchItems } from '../store/actions/items'
class Prod... | () {
this.refresh();
}
componentDidUpdate(nextProps) {
if (nextProps.params !== this.props.params) {
this.refresh();
}
}
refresh() {
const { params } = this.props;
if (params.category) {
fetchCategory(params.category);
} else {
searchItems(encodeURIComponent(params.sear... | componentDidMount | identifier_name |
Products.js | import React from 'react';
import PropTypes from 'prop-types';
import { connect} from 'react-redux';
import UmsgContainer from '../containers/UmsgContainer';
import Sidebar from '../components/Sidebar'
import Item from '../components/Item'
import { fetchCategory, searchItems } from '../store/actions/items'
class Prod... | items: PropTypes.array.isRequired,
isLoading: PropTypes.bool.isRequired
};
const mapStatetoProps = store => {
return ({
items: store.itemReducer.data,
isLoading: store.itemReducer.isLoading
});
};
export default connect(mapStatetoProps)(Products); | Products.propTypes = {
params: PropTypes.object.isRequired, | random_line_split |
Products.js | import React from 'react';
import PropTypes from 'prop-types';
import { connect} from 'react-redux';
import UmsgContainer from '../containers/UmsgContainer';
import Sidebar from '../components/Sidebar'
import Item from '../components/Item'
import { fetchCategory, searchItems } from '../store/actions/items'
class Prod... |
}
Products.propTypes = {
params: PropTypes.object.isRequired,
items: PropTypes.array.isRequired,
isLoading: PropTypes.bool.isRequired
};
const mapStatetoProps = store => {
return ({
items: store.itemReducer.data,
isLoading: store.itemReducer.isLoading
});
};
export default connect(mapStatetoProps)... | {
const {items, isLoading} = this.props;
let content = items.map(i => (<Item key={i.get('_id')} item={i} />));
if (items.length === 0) {
content = (<h3>No items found with search "{this.props.params.search}"</h3>);
}
return (
<div>
<Sidebar {...this.props}/>
<UmsgContaine... | identifier_body |
demo06.py | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from __future__ import print_function
import fixpath
import colorama
from colorama import Fore, Back, Style
from random import randint, choice
from string import printable
# Fore, Back and Style are convenience classes for the constant ANSI str... | main() | conditional_block | |
demo06.py | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from __future__ import print_function
import fixpath
import colorama
from colorama import Fore, Back, Style
from random import randint, choice
from string import printable
# Fore, Back and Style are convenience classes for the constant ANSI str... |
if __name__ == '__main__':
main()
| colorama.init()
# gratuitous use of lambda.
pos = lambda y, x: '\x1b[%d;%dH' % (y, x)
# draw a white border.
print(Back.WHITE, end='')
print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='')
for y in range(MINY, 1+MAXY):
print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='')
print('%s%s'... | identifier_body |
demo06.py | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from __future__ import print_function
import fixpath
import colorama
from colorama import Fore, Back, Style
from random import randint, choice
from string import printable
# Fore, Back and Style are convenience classes for the constant ANSI str... | # draw some blinky lights for a while.
for i in range(PASSES):
print('%s%s%s%s%s' % (pos(randint(1+MINY,MAXY-1), randint(1+MINX,MAXX-1)), choice(FORES), choice(BACKS), choice(STYLES), choice(CHARS)), end='')
# put cursor to top, left, and set color to white-on-black with normal brightness.
print... | print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='')
for y in range(MINY, 1+MAXY):
print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='')
print('%s%s' % (pos(MAXY, MINX), ' '*MAXX), end='') | random_line_split |
demo06.py | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from __future__ import print_function
import fixpath
import colorama
from colorama import Fore, Back, Style
from random import randint, choice
from string import printable
# Fore, Back and Style are convenience classes for the constant ANSI str... | ():
colorama.init()
# gratuitous use of lambda.
pos = lambda y, x: '\x1b[%d;%dH' % (y, x)
# draw a white border.
print(Back.WHITE, end='')
print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='')
for y in range(MINY, 1+MAXY):
print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='')
prin... | main | identifier_name |
utils.ts | import { parse, Url, URL } from 'url';
import { RequestOptions } from 'http';
import { HttpsAgent } from './https-agent';
import { WithUrl } from './request';
import * as zlib from 'zlib';
const socks = require('socks-wrapper');
export function rewrite(url: string): string {
if (!/^\w+:/.test(url)) {
if (url.su... | (url: string | WithUrl) {
const href = typeof url === 'string' ? url : url.url;
return <URL>(<any>parse(rewrite(href)));
}
interface WithKey {
[key: string]: any;
}
export function pickAssign(target: WithKey, source: WithKey, keys: string[]) {
if (source) {
for (const key of keys) {
if (source[key] ... | parseUrl | identifier_name |
utils.ts | import { parse, Url, URL } from 'url';
import { RequestOptions } from 'http';
import { HttpsAgent } from './https-agent';
import { WithUrl } from './request';
import * as zlib from 'zlib';
const socks = require('socks-wrapper');
export function rewrite(url: string): string {
if (!/^\w+:/.test(url)) {
if (url.su... |
export function inflate(content: Buffer, encoding: string): Promise<Buffer> {
return new Promise(resolve => {
if (encoding === 'gzip') {
zlib.gunzip(content, function(err, buf) {
if (err) throw err;
resolve(buf);
});
} else {
zlib.inflate(content, function(err, buf) {
... | {
const keyLower = key.toLowerCase();
const header: Header = [key, value];
for (let i = 0; i < headers.length; i++) {
const nameLower = headers[i][0].toLowerCase();
if (keyLower === nameLower) {
headers[i] = header;
return;
}
if (keyLower < nameLower) {
headers.splice(i, 0, head... | identifier_body |
utils.ts | import { parse, Url, URL } from 'url';
import { RequestOptions } from 'http';
import { HttpsAgent } from './https-agent';
import { WithUrl } from './request';
import * as zlib from 'zlib';
const socks = require('socks-wrapper');
export function rewrite(url: string): string {
if (!/^\w+:/.test(url)) {
if (url.su... |
export function setHeader(
headers: Header[],
key: string,
value: string | number
) {
const keyLower = key.toLowerCase();
const header: Header = [key, value];
for (let i = 0; i < headers.length; i++) {
const nameLower = headers[i][0].toLowerCase();
if (keyLower === nameLower) {
headers[i] = ... | export type Header = [string, string | number]; | random_line_split |
utils.ts | import { parse, Url, URL } from 'url';
import { RequestOptions } from 'http';
import { HttpsAgent } from './https-agent';
import { WithUrl } from './request';
import * as zlib from 'zlib';
const socks = require('socks-wrapper');
export function rewrite(url: string): string {
if (!/^\w+:/.test(url)) {
if (url.su... |
}
}
| {
const agent = new HttpsAgent({ proxy, servername: <string>url.host });
request.port = request.port || 443;
request.agent = agent;
} | conditional_block |
netperf.py | """
Run latency & thruput tests on various server configurations.
"""
import glob
import os.path
import shutil
import time
from openmdao.main.mp_util import read_server_config
from openmdao.main.objserverfactory import connect, start_server
from openmdao.util.fileutil import onerror
MESSAGE_DATA = []
def init_mess... |
factory.cleanup()
server_proc.terminate(timeout=10)
# Add results.
for size, latency, thruput in results:
if size not in latency_results:
latency_results[size] = []
latency_results[size].app... | factory.release(server) | conditional_block |
netperf.py | """
Run latency & thruput tests on various server configurations.
"""
import glob
import os.path
import shutil
import time
from openmdao.main.mp_util import read_server_config
from openmdao.main.objserverfactory import connect, start_server
from openmdao.util.fileutil import onerror
MESSAGE_DATA = []
def init_mess... | latency_results[size] = []
latency_results[size].append(latency)
if size not in thruput_results:
thruput_results[size] = []
thruput_results[size].append(thruput)
# Write out results in X, Y1, Y2, ... format... | # Add results.
for size, latency, thruput in results:
if size not in latency_results: | random_line_split |
netperf.py | """
Run latency & thruput tests on various server configurations.
"""
import glob
import os.path
import shutil
import time
from openmdao.main.mp_util import read_server_config
from openmdao.main.objserverfactory import connect, start_server
from openmdao.util.fileutil import onerror
MESSAGE_DATA = []
def init_mess... |
def run_test(name, server):
""" Run latency & bandwidth test on `server`. """
for i in range(10):
server.echo(MESSAGE_DATA[0]) # 'prime' the connection.
results = []
reps = 1000
for msg in MESSAGE_DATA:
start = time.time()
for i in range(reps):
server.echo(ms... | """ Initialize message data for various sizes. """
for i in range(21):
MESSAGE_DATA.append(' ' * (1 << i)) | identifier_body |
netperf.py | """
Run latency & thruput tests on various server configurations.
"""
import glob
import os.path
import shutil
import time
from openmdao.main.mp_util import read_server_config
from openmdao.main.objserverfactory import connect, start_server
from openmdao.util.fileutil import onerror
MESSAGE_DATA = []
def init_mess... | ():
""" Run latency & thruput tests on various server configurations. """
init_messages()
latency_results = {}
thruput_results = {}
# For each configuration...
count = 0
for authkey in ('PublicKey', 'UnEncrypted'):
for ip_port in (-1, 0):
for hops in (1, 2):
... | main | identifier_name |
plugin.py | """
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... | serializer_class = PluginSerializer
def get_queryset(self, *args, **kwargs):
return Plugin.objects.all()
#if 'available_plugins' in request.session:
# if request.session['available_plugins'] == None:
# request.session['available_plugins'] = ['backup']
#else:
... | identifier_body | |
plugin.py | """
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... | # 'available': request.session['available_plugins']
# }
#return Response(data) | random_line_split | |
plugin.py | """
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... | (rfc.GenericView):
serializer_class = PluginSerializer
def get_queryset(self, *args, **kwargs):
return Plugin.objects.all()
#if 'available_plugins' in request.session:
# if request.session['available_plugins'] == None:
# request.session['available_plugins'] = ['backu... | PluginView | identifier_name |
app.js | var server = require('./server').http,
player = require('./player'),
port = 8000,
filesToLoad = [];
function | (exitp) {
process.stdout.write("\n_____________________________________________________________________________________ \n ");
process.stdout.write(" superplay by Jalal Hejazi 2014 ( sourcecode: github.com/jalalhejazi/superplay ) ");
process.stdout.write("\n______________________________________________... | printHelp | identifier_name |
app.js | var server = require('./server').http,
player = require('./player'),
port = 8000,
filesToLoad = [];
function printHelp(exitp) {
process.stdout.write("\n_____________________________________________________________________________________ \n ");
process.stdout.write(" superplay by Jalal Hejazi 20... | process.on('SIGINT', function() {
process.exit(1);
});
/* And off we go ...
*/
if (typeof player.setup === 'function') {
player.setup();
}
filesToLoad.forEach(player.addFile);
process.stdout.write("Firing up the superplay HTTP server on port " + port + "\n");
server.listen(port);
if (player.files.length ==... | player.cleanup();
}
process.stdout.write("buh-bye!\n");
});
| random_line_split |
app.js | var server = require('./server').http,
player = require('./player'),
port = 8000,
filesToLoad = [];
function printHelp(exitp) {
process.stdout.write("\n_____________________________________________________________________________________ \n ");
process.stdout.write(" superplay by Jalal Hejazi 20... |
filesToLoad.forEach(player.addFile);
process.stdout.write("Firing up the superplay HTTP server on port " + port + "\n");
server.listen(port);
if (player.files.length === 0) {
process.stderr.write("No media files served! \n");
process.stderr.write("Add some media at the command-line: use cp or scp \n");
} | {
player.setup();
} | conditional_block |
app.js | var server = require('./server').http,
player = require('./player'),
port = 8000,
filesToLoad = [];
function printHelp(exitp) |
/* Parse command-line options, first two args are the process.
*/
for (var i = 2, argv = process.argv, len = argv.length; i < len; i++) {
switch (argv[i]) {
case '-h':
case '--help':
printHelp(true);
break;
case '-p':
case '--port':
var p = pars... | {
process.stdout.write("\n_____________________________________________________________________________________ \n ");
process.stdout.write(" superplay by Jalal Hejazi 2014 ( sourcecode: github.com/jalalhejazi/superplay ) ");
process.stdout.write("\n______________________________________________________... | identifier_body |
test-missionlog.js | const should = require('should');
const MissionLog = require('../lib/log').MissionLog;
const Severity = require('../lib/Severity');
describe('MissionLog', function () {
it('should test the properties', function () {
const Log = new MissionLog();
Log.should.have.property('severities').with.lengthOf(... | const defaultSeverity = Log.getDefaultSeverity();
should(defaultSeverity.name).equal(newSeverity.name);
});
it('should try to add a severity twice', function() {
const firstSeverity = new Severity('UnitTesting');
const secondSeverity = new Severity('UnitTesting');
const ... |
const Log = new MissionLog();
Log.setDefaultSeverity(newSeverity);
| random_line_split |
DateTimeDropdownPicker.tsx | /* tslint:disable:no-console */
import 'babel-polyfill';
import 'ts-helpers';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DateTimeDropdownPicker } from '../../src';
import moment = require('moment');
export class Index extends React.Component<any, any> {
constructor(p... |
}
ReactDOM.render(<Index />, document.getElementById('root'));
| {
return (
<div>
<DateTimeDropdownPicker
selectedDate = {this.state.date}
onTimeSelectionChanged={(newDate) => this.setState({date: newDate})}
isValidDate={this.isValidaDate.bind(this)}
></DateTimeDrop... | identifier_body |
DateTimeDropdownPicker.tsx | /* tslint:disable:no-console */
import 'babel-polyfill';
import 'ts-helpers';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DateTimeDropdownPicker } from '../../src';
import moment = require('moment');
export class Index extends React.Component<any, any> {
constructor(p... | };
}
public isValidaDate = (date: Date) => {
return date >= moment().toDate();
}
public render() {
return (
<div>
<DateTimeDropdownPicker
selectedDate = {this.state.date}
onTimeSelectionChanged={(ne... | date: new Date(today.getFullYear(), today.getMonth(), today.getDate() + 90)
| random_line_split |
DateTimeDropdownPicker.tsx | /* tslint:disable:no-console */
import 'babel-polyfill';
import 'ts-helpers';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DateTimeDropdownPicker } from '../../src';
import moment = require('moment');
export class | extends React.Component<any, any> {
constructor(props) {
super(props);
const today: Date = moment().toDate();
this.state = {
date: new Date(today.getFullYear(), today.getMonth(), today.getDate() + 90)
};
}
public isValidaDate = (date: Date) => {
... | Index | identifier_name |
Note.tsx | import cx from 'classnames'
import * as R from 'ramda'
import * as React from 'react'
import * as M from '@material-ui/core'
import {
JsonSchema,
doesTypeMatchSchema,
schemaTypeToHumanString,
} from 'utils/json-schema'
import { JsonValue, COLUMN_IDS, EMPTY_VALUE, RowData } from './constants'
const useStyles = ... | ({ humanReadableSchema, schema }: TypeHelpProps) {
if (humanReadableSchema === 'undefined')
return <>Key/value is not restricted by schema</>
return (
<div>
Value should be of {humanReadableSchema} type
{!!schema?.description && <p>{schema.description}</p>}
</div>
)
}
interface NoteValue... | TypeHelp | identifier_name |
Note.tsx | import cx from 'classnames'
import * as R from 'ramda'
import * as React from 'react'
import * as M from '@material-ui/core'
import {
JsonSchema,
doesTypeMatchSchema,
schemaTypeToHumanString,
} from 'utils/json-schema'
import { JsonValue, COLUMN_IDS, EMPTY_VALUE, RowData } from './constants'
const useStyles = ... |
return null
}
| {
return <NoteValue value={value} schema={data.valueSchema} />
} | conditional_block |
Note.tsx | import cx from 'classnames'
import * as R from 'ramda'
import * as React from 'react'
import * as M from '@material-ui/core'
import {
JsonSchema,
doesTypeMatchSchema,
schemaTypeToHumanString,
} from 'utils/json-schema'
import { JsonValue, COLUMN_IDS, EMPTY_VALUE, RowData } from './constants'
const useStyles = ... |
const humanReadableSchema = schemaTypeToHumanString(schema)
const mismatch = value !== EMPTY_VALUE && !doesTypeMatchSchema(value, schema)
return (
<M.Tooltip title={<TypeHelp {...{ humanReadableSchema, schema }} />}>
<span
className={cx(classes.default, {
[classes.mismatch]: mismatch... | const classes = useStyles() | random_line_split |
Note.tsx | import cx from 'classnames'
import * as R from 'ramda'
import * as React from 'react'
import * as M from '@material-ui/core'
import {
JsonSchema,
doesTypeMatchSchema,
schemaTypeToHumanString,
} from 'utils/json-schema'
import { JsonValue, COLUMN_IDS, EMPTY_VALUE, RowData } from './constants'
const useStyles = ... | {
if (columnId === COLUMN_IDS.VALUE) {
return <NoteValue value={value} schema={data.valueSchema} />
}
return null
} | identifier_body | |
base.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | (self, ds, variable_manager=None, loader=None):
''' walk the input datastructure and assign any values '''
assert ds is not None
# cache the datastructure internally
setattr(self, '_ds', ds)
# the variable manager class is used to manage and merge variables
# down to a... | load_data | identifier_name |
base.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... |
def get_variable_manager(self):
return self._variable_manager
def _validate_attributes(self, ds):
'''
Ensures that there are no keys in the datastructure which do
not map to attributes for this object.
'''
valid_attrs = frozenset(name for name in self._get_bas... | return self._loader | identifier_body |
base.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... |
base_attributes[name] = value
return base_attributes
def _initialize_base_attributes(self):
# each class knows attributes set upon it, see Task.py for example
self._attributes = dict()
for (name, value) in self._get_base_attributes().items():
getter = pa... | name = name[1:] | conditional_block |
base.py | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible 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) an... | value = set()
else:
if not isinstance(value, (list, set)):
value = [ value ]
if not isinstance(value, set):
value = set(value)
e... | raise AnsibleParserError("the field '%s' is required, and cannot have empty values" % (name,), obj=self.get_ds())
elif attribute.isa == 'set':
if value is None: | random_line_split |
lists2.py | def no_extreme(listed):
"""
Takes a list and chops off extreme ends
"""
del listed[0]
del listed[-1:]
return listed
def better_no_extreme(listed):
"""
why better ? For starters , does not modify original list
"""
return listed[1:-1]
t = ['a','b','c']
print t
print '\n'
print 'pop any element : by t.pop(1) ... |
str2=raw_input("\nEnter a line to be separated into words : ")
listr2 = str2.split()#separated at spaces
print listr2
print 'You can split a line into words by changing the parameter as str2.split(parameter)'
print 'this splits at - '
print 'joining statement : '
delimeter=' '
print delimeter.join(listr2)
print '\n... |
str = raw_input("\nEnter a string to be converted to list : ")
listr = list(str)
print listr | random_line_split |
lists2.py | def no_extreme(listed):
"""
Takes a list and chops off extreme ends
"""
del listed[0]
del listed[-1:]
return listed
def | (listed):
"""
why better ? For starters , does not modify original list
"""
return listed[1:-1]
t = ['a','b','c']
print t
print '\n'
print 'pop any element : by t.pop(1) or t.remove(\'b\') or del t[1]'
del t[1]
print t
st = ['a','b','c','d','e','f']
print st
del st[1:3]
print 'del t[1:3] works as well : ', st
p... | better_no_extreme | identifier_name |
lists2.py | def no_extreme(listed):
|
def better_no_extreme(listed):
"""
why better ? For starters , does not modify original list
"""
return listed[1:-1]
t = ['a','b','c']
print t
print '\n'
print 'pop any element : by t.pop(1) or t.remove(\'b\') or del t[1]'
del t[1]
print t
st = ['a','b','c','d','e','f']
print st
del st[1:3]
print 'del t[1:3] w... | """
Takes a list and chops off extreme ends
"""
del listed[0]
del listed[-1:]
return listed | identifier_body |
EnvironmentVariable58StateElement.py | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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.
#
# PySCAP is ... | MODEL_MAP = {
'tag_name': 'environmentvariable58_state',
'elements': [
{'tag_name': 'pid', 'class': 'scap.model.oval_5.defs.EntityObjectType', 'min': 0, 'max': 1},
{'tag_name': 'name', 'class': 'scap.model.oval_5.defs.EntityObjectType', 'min': 0, 'max': 1},
{'tag_name... | identifier_body | |
EnvironmentVariable58StateElement.py | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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.
#
# PySCAP is ... | } | ], | random_line_split |
EnvironmentVariable58StateElement.py | # Copyright 2016 Casey Jaymes
# This file is part of PySCAP.
#
# PySCAP 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.
#
# PySCAP is ... | (StateType):
MODEL_MAP = {
'tag_name': 'environmentvariable58_state',
'elements': [
{'tag_name': 'pid', 'class': 'scap.model.oval_5.defs.EntityObjectType', 'min': 0, 'max': 1},
{'tag_name': 'name', 'class': 'scap.model.oval_5.defs.EntityObjectType', 'min': 0, 'max': 1},
... | EnvironmentVariable58StateElement | identifier_name |
response.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal as D
class | (object):
"""A convenient wrapper to manipulate the Nexmo json response.
The class makes it easy to retrieve information about sent messages, total
price, etc.
Example::
>>> response = nexmo.send_sms(frm, to, txt)
>>> print response.total_price
0.15
>>> print response.... | NexmoResponse | identifier_name |
response.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal as D
class NexmoResponse(object):
|
class NexmoMessage(object):
"""A wrapper to manipulate a single `message` entry in a Nexmo response.
When a text messages is sent in several parts, Nexmo will return a status
for each and everyone of them.
The class does nothing more than simply wrapping the json data for easy
access.
"""
... | """A convenient wrapper to manipulate the Nexmo json response.
The class makes it easy to retrieve information about sent messages, total
price, etc.
Example::
>>> response = nexmo.send_sms(frm, to, txt)
>>> print response.total_price
0.15
>>> print response.remaining_bala... | identifier_body |
response.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from decimal import Decimal as D
class NexmoResponse(object):
"""A convenient wrapper to manipulate the Nexmo json response.
The class makes it easy to retrieve information about sent messages, total
price, etc.
Example::
>>>... |
The class only handles successfull responses, since errors raise
exceptions in the :class:`~Nexmo` class.
"""
def __init__(self, json_data):
self.messages = [NexmoMessage(data) for data in json_data['messages']]
self.message_count = len(self.messages)
self.total_price = sum(ms... | >>> for message in response.messages:
... print message.message_id, message.message_price
00000124 0.05
00000125 0.05
00000126 0.05 | random_line_split |
serializers.py | from django.contrib.auth import get_user_model
from django.db import models
from imagekit.cachefiles import ImageCacheFile
from imagekit.registry import generator_registry
from imagekit.templatetags.imagekit import DEFAULT_THUMBNAIL_GENERATOR
from rest_framework import serializers
User = get_user_model()
class Thumb... |
class AvatarSerializer(serializers.ModelSerializer):
# Override default field_mapping to map ImageField to HyperlinkedImageField.
# As there is only one field this is the only mapping needed.
field_mapping = {
models.ImageField: ThumbnailField,
}
class Meta:
model = User
... | if not image.name:
return None
request = self.context.get('request', None)
if request is None:
return image.url
kwargs = self.get_generator_kwargs(request.query_params)
if kwargs.get('width') or kwargs.get('height'):
image = self.generate_thumbnail(i... | identifier_body |
serializers.py | from django.contrib.auth import get_user_model
from django.db import models
from imagekit.cachefiles import ImageCacheFile
from imagekit.registry import generator_registry
from imagekit.templatetags.imagekit import DEFAULT_THUMBNAIL_GENERATOR
from rest_framework import serializers
User = get_user_model()
class Thumb... | :
model = User
fields = ('avatar',)
| Meta | identifier_name |
serializers.py | from django.contrib.auth import get_user_model
from django.db import models
from imagekit.cachefiles import ImageCacheFile
from imagekit.registry import generator_registry
from imagekit.templatetags.imagekit import DEFAULT_THUMBNAIL_GENERATOR
from rest_framework import serializers
User = get_user_model()
class Thumb... | def to_native(self, image):
if not image.name:
return None
request = self.context.get('request', None)
if request is None:
return image.url
kwargs = self.get_generator_kwargs(request.query_params)
if kwargs.get('width') or kwargs.get('height'):
... | self.generator_id,
source=source,
**kwargs)
return ImageCacheFile(generator)
| random_line_split |
serializers.py | from django.contrib.auth import get_user_model
from django.db import models
from imagekit.cachefiles import ImageCacheFile
from imagekit.registry import generator_registry
from imagekit.templatetags.imagekit import DEFAULT_THUMBNAIL_GENERATOR
from rest_framework import serializers
User = get_user_model()
class Thumb... |
request = self.context.get('request', None)
if request is None:
return image.url
kwargs = self.get_generator_kwargs(request.query_params)
if kwargs.get('width') or kwargs.get('height'):
image = self.generate_thumbnail(image, **kwargs)
return request.bu... | return None | conditional_block |
test_user.py | from shuttl.tests import testbase
from shuttl.Models.User import User, UserDataTakenException, NoOrganizationException, ToManyOrganizations
from shuttl.Models.organization import Organization
from shuttl.Models.Reseller import Reseller | self.reseller = Reseller(name ="test4", url="test2.com")
self.reseller.save()
pass
def test_create(self):
organization = Organization(name="Test", reseller=self.reseller)
organization.save()
organization = Organization.Get(name="Test", vendor=self.reseller)
d... |
class UserTestCase(testbase.BaseTest):
def _setUp(self): | random_line_split |
test_user.py | from shuttl.tests import testbase
from shuttl.Models.User import User, UserDataTakenException, NoOrganizationException, ToManyOrganizations
from shuttl.Models.organization import Organization
from shuttl.Models.Reseller import Reseller
class UserTestCase(testbase.BaseTest):
def _setUp(self):
self.reselle... |
def test_password(self):
org = Organization.Create(name="Test", reseller=self.reseller)
usr = User.Create(organization=org, username="Tester", email="blah@blah.com", password="Bullshit")
oldPW = usr.password
self.assertNotEqual(usr.password, "Bullshit")
self.assertTrue(usr.... | organization = Organization(name="Test", reseller=self.reseller)
organization.save()
organization = Organization.Get(name="Test", vendor=self.reseller)
data = dict(organization=organization, username="Tester", email="Test@tesi.com", password="Things")
user = User.Create(**data)
s... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.