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 |
|---|---|---|---|---|
LookAround.js | /**
* Created by shuis on 2017/5/29.
*/
import React, { Component } from 'react';
import {
View,
Image,
FlatList,
TouchableWithoutFeedback
} from 'react-native';
import {TabBarIcon, TweetSeparator} from '../component/base';
import Tweet from '../component/Tweet';
import {public_timeline} from '../api/api';
... | tWillMount() {
this.props.navigation.setParams({
onPress:this._fetch,
})
}
componentDidMount() {
this._fetch();
}
_fetch = async () => {
try {
let res = await public_timeline();
this.setState({
data: res,
});
} catch (e) {
}
};
_renderItem = ({item... | props);
this.state = {
data: [],
showImageViewer: false,
image: [{url:''}],
}
}
componen | identifier_body |
LookAround.js | /**
* Created by shuis on 2017/5/29.
*/
import React, { Component } from 'react';
import {
View,
Image,
FlatList,
TouchableWithoutFeedback
} from 'react-native';
import {TabBarIcon, TweetSeparator} from '../component/base';
import Tweet from '../component/Tweet';
import {public_timeline} from '../api/api';
... | rn (
<View>
<FlatList
data = {this.state.data}
renderItem = {this._renderItem}
initialNumToRender = {6}
keyExtractor={this._keyExtractor}
ItemSeparatorComponent={this._renderSeparator}
/>
</View>
)
}
}
export default LookAround; | retu | identifier_name |
LookAround.js | /**
* Created by shuis on 2017/5/29.
*/
import React, { Component } from 'react';
import {
View,
Image,
FlatList,
TouchableWithoutFeedback
} from 'react-native';
import {TabBarIcon, TweetSeparator} from '../component/base';
import Tweet from '../component/Tweet';
import {public_timeline} from '../api/api';
... | )
}
}
export default LookAround; | </View> | random_line_split |
CoarseLocationUpdate.ts | import { Collection } from '../../utilities'
import Packet from './Packet'
import * as Types from '../types'
/**
* CoarseLocationUpdate Packet
*/
class CoarseLocationUpdate extends Packet {
/**
* Packet ID, this value is only unique per-frequency range, see key get
* method of Packet, plus the buffer helper... | ])
/**
* CoarseLocationUpdate constructor, can be passed either a fully
* initialized Packet Buffer or an object containing this Objects required
* parameters from {@link CoarseLocationUpdate.format}. Note that
* "agentData" blocks may be excluded if {@link build} is able to fetch the
* requirements... | ['location', { parameters: new Collection<string, any>([['x', Types.U8], ['y', Types.U8], ['z', Types.U8]]) }],
// tslint:disable-next-line:max-line-length
['index', { quantity: 1, parameters: new Collection<string, any>([['you', Types.S16], ['prey', Types.S16]]) }],
// tslint:disable-next-line:max-line... | random_line_split |
CoarseLocationUpdate.ts | import { Collection } from '../../utilities'
import Packet from './Packet'
import * as Types from '../types'
/**
* CoarseLocationUpdate Packet
*/
class | extends Packet {
/**
* Packet ID, this value is only unique per-frequency range, see key get
* method of Packet, plus the buffer helper of the network namespace for
* generating a lookup codes.
*
* @type {number}
*/
public static id: number = 6
/**
* Packet frequency. This value determines ... | CoarseLocationUpdate | identifier_name |
CoarseLocationUpdate.ts | import { Collection } from '../../utilities'
import Packet from './Packet'
import * as Types from '../types'
/**
* CoarseLocationUpdate Packet
*/
class CoarseLocationUpdate extends Packet {
/**
* Packet ID, this value is only unique per-frequency range, see key get
* method of Packet, plus the buffer helper... |
}
export default CoarseLocationUpdate
| {
super(data)
} | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-20 06:42
from __future__ import unicode_literals
import django.contrib.auth.models
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
class | (migrations.Migration):
initial = True
dependencies = [
('auth', '0007_alter_validators_add_error_messages'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=F... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-20 06:42
from __future__ import unicode_literals
import django.contrib.auth.models
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
| ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('profile_picture_url', models.CharField(max_length=200)),
('major', models.CharField(max_length=50)),
('groups', models.ManyToManyField(blank=True, help_... | initial = True
dependencies = [
('auth', '0007_alter_validators_add_error_messages'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-02-20 06:42
from __future__ import unicode_literals
import django.contrib.auth.models
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependenc... | operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('l... | random_line_split | |
analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async]
| client = data_v1beta.BetaAnalyticsDataAsyncClient()
# Initialize request argument(s)
request = data_v1beta.BatchRunPivotReportsRequest(
)
# Make the request
response = await client.batch_run_pivot_reports(request=request)
# Handle the response
print(response) | identifier_body |
analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | ():
# Create a client
client = data_v1beta.BetaAnalyticsDataAsyncClient()
# Initialize request argument(s)
request = data_v1beta.BatchRunPivotReportsRequest(
)
# Make the request
response = await client.batch_run_pivot_reports(request=request)
# Handle the response
print(response)... | sample_batch_run_pivot_reports | identifier_name |
analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
async def sample_batch_run_pivot_reports():
# Create a client
client = data_v1beta.BetaAnalyticsDataAsyncClient()
# Initialize request argument(s)
request = data_v1beta.BatchRunPivotReportsRequest(
)
# Make the request
response = await client.batch_run_pivot_reports(request=request)
... | random_line_split | |
context_reaction_block.js | ').split('context-blockform-region-')[1];
var blocks = [];
$('tr', $(this)).each(function() {
var bid = $(this).attr('id');
blocks.push(bid);
});
Drupal.contextBlockForm.state[region] = blocks;
});
// Serialize here and set form element value.
$('form input.context-b... | });
};
// Tabledrag
// Add additional handlers to update our blocks.
$.each(Drupal.settings.tableDrag, function(base) {
var table = $('#' + base + ':not(.processed)', blockForm);
if (table && table.is('.context-blockform-region')) {
table.addClass('processed');
table.bind('mouseup', fun... | if ($('table.context-blockform-region tr#'+bid).size() === 0) {
$(this).parents('div.form-item').eq(0).show();
} | random_line_split |
aws.py | from typing import Dict, List, NamedTuple
import pykube.objects
import requests
import pendulum
from urllib.parse import urlparse
from boto import ec2
from ..context import Context
from k8s_snapshots.snapshot import Snapshot
from .abstract import NewSnapshotIdentifier, SnapshotStatus
from ..errors import SnapshotCreate... |
def get_connection(ctx: Context, region):
connection = ec2.connect_to_region(region)
return connection
| connection = get_connection(ctx, snapshot.disk.region)
connection.delete_snapshot(snapshot.name) | identifier_body |
aws.py | from typing import Dict, List, NamedTuple
import pykube.objects
import requests
import pendulum
from urllib.parse import urlparse
from boto import ec2
from ..context import Context
from k8s_snapshots.snapshot import Snapshot
from .abstract import NewSnapshotIdentifier, SnapshotStatus
from ..errors import SnapshotCreate... | class AWSDiskIdentifier(NamedTuple):
region: str
volume_id: str
def get_current_region(ctx):
"""Get the current region from the metadata service.
"""
if not ctx.config['aws_region']:
response = requests.get(
'http://169.254.169.254/latest/meta-data/placement/availability-zone',... | return bool(volume.obj['spec'].get('awsElasticBlockStore'))
| random_line_split |
aws.py | from typing import Dict, List, NamedTuple
import pykube.objects
import requests
import pendulum
from urllib.parse import urlparse
from boto import ec2
from ..context import Context
from k8s_snapshots.snapshot import Snapshot
from .abstract import NewSnapshotIdentifier, SnapshotStatus
from ..errors import SnapshotCreate... | (config):
"""Ensure the config of this backend is correct.
manual volumes are validated by the backend
- for aws, google cloud, need different data, say, region or zone.
"""
pass
def supports_volume(volume: pykube.objects.PersistentVolume):
return bool(volume.obj['spec'].get('awsElasticBl... | validate_config | identifier_name |
aws.py | from typing import Dict, List, NamedTuple
import pykube.objects
import requests
import pendulum
from urllib.parse import urlparse
from boto import ec2
from ..context import Context
from k8s_snapshots.snapshot import Snapshot
from .abstract import NewSnapshotIdentifier, SnapshotStatus
from ..errors import SnapshotCreate... |
else:
raise NotImplementedError()
def set_snapshot_labels(
ctx: Context,
snapshot_identifier: NewSnapshotIdentifier,
labels: Dict
):
connection = get_connection(ctx, snapshot_identifier['region'])
connection.create_tags([snapshot_identifier['id']], labels)
def delete_snapshot(
c... | raise SnapshotCreateError(snapshot['status']) | conditional_block |
bkCoreManager.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by appl... | "#FFFF7F0E", // orange
"#FF2CA02C", // green
"#FFD62728", // red
"#FF9467BD", // purple
"#FF8C564B", // brown
"#FFE377C2", // pink
"#FF7F7F7F", // gray
"#FFBCBD22", // pear
"#FF17BECF", // aqua
"#FFAEC7E8",
"#... | random_line_split | |
bkCoreManager.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by appl... |
return this.theme;
}
},
getTheme: function (): string {
return this._prefs.getTheme();
},
getBkApp: function () {
return this._bkAppImpl;
}
};
export default bkCoreManager;
| {
return "default";
} | conditional_block |
hello.rs | #![feature(proc_macro)]
extern crate hayaku_http;
extern crate hayaku_path;
#[macro_use]
extern crate serde_derive; |
use hayaku_http::{Http, Request, Response};
use hayaku_path::Router;
use std::sync::Arc;
fn main() {
let addr = "127.0.0.1:3000".parse().unwrap();
let mut router = Router::new();
router.get("/", Arc::new(hello_handler)).unwrap();
router.get("/plaintext", Arc::new(plain_handler)).unwrap();
router... | extern crate serde_json; | random_line_split |
hello.rs | #![feature(proc_macro)]
extern crate hayaku_http;
extern crate hayaku_path;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use hayaku_http::{Http, Request, Response};
use hayaku_path::Router;
use std::sync::Arc;
fn main() {
let addr = "127.0.0.1:3000".parse().unwrap();
let mut router = Ro... | {
message: String,
}
fn json_handler(_req: &Request, res: &mut Response, _ctx: &()) {
let msg = Message { message: "Hello, World!".to_string() };
let data = serde_json::to_vec(&msg).unwrap();
res.add_header("Content-Type".to_string(), "application/json".to_string());
res.body(&data);
}
| Message | identifier_name |
hello.rs | #![feature(proc_macro)]
extern crate hayaku_http;
extern crate hayaku_path;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use hayaku_http::{Http, Request, Response};
use hayaku_path::Router;
use std::sync::Arc;
fn main() {
let addr = "127.0.0.1:3000".parse().unwrap();
let mut router = Ro... | {
let msg = Message { message: "Hello, World!".to_string() };
let data = serde_json::to_vec(&msg).unwrap();
res.add_header("Content-Type".to_string(), "application/json".to_string());
res.body(&data);
} | identifier_body | |
evaluationhandler.py | # -*- coding: utf-8 -*-
#
# Copyright 2014-2022 BigML
#
# 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 ... | (self):
"""Initializes the EvaluationHandler. This class is intended to be
used as a mixin on ResourceHandler, that inherits its
attributes and basic method from BigMLConnection, and must not be
instantiated independently.
"""
self.evaluation_url = self.url + EV... | __init__ | identifier_name |
evaluationhandler.py | # -*- coding: utf-8 -*-
#
# Copyright 2014-2022 BigML
#
# 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 ... | from bigml.api_handlers.resourcehandler import check_resource_type
from bigml.constants import SUPERVISED_PATHS, TIME_SERIES_PATH, EVALUATION_PATH
class EvaluationHandlerMixin(ResourceHandlerMixin):
"""This class is used by the BigML class as
a mixin that provides the REST calls models. It should not
... | import json
from bigml.api_handlers.resourcehandler import ResourceHandlerMixin | random_line_split |
evaluationhandler.py | # -*- coding: utf-8 -*-
#
# Copyright 2014-2022 BigML
#
# 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 ... |
return
def get_evaluation(self, evaluation, query_string=''):
"""Retrieves an evaluation.
The evaluation parameter should be a string containing the
evaluation id or the dict returned by create_evaluation.
As evaluation is an evolving object that is processed
... | body = json.dumps(create_args)
return self._create(self.evaluation_url, body) | conditional_block |
evaluationhandler.py | # -*- coding: utf-8 -*-
#
# Copyright 2014-2022 BigML
#
# 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 ... | if args is not None:
create_args.update(args)
model_types = SUPERVISED_PATHS[:]
model_types.append(TIME_SERIES_PATH)
origin_resources_checked = self.check_origins(
dataset, model, create_args, model_types=model_types,
wait_time=wait_time, retries=ret... | """This class is used by the BigML class as
a mixin that provides the REST calls models. It should not
be instantiated independently.
"""
def __init__(self):
"""Initializes the EvaluationHandler. This class is intended to be
used as a mixin on ResourceHandler, that inherits its... | identifier_body |
es2020IntlAPIs.ts | // @target: es2020
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation
const count = 26254.39;
const date = new Date("2012-05-24");
function log(locale: string) {
console.log(
`${new Intl.DateTimeFormat(locale).format(date)} ${new Intl.N... | console.log(regionNamesInEnglish.of('US'));
// expected output: "United States"
console.log(regionNamesInTraditionalChinese.of('US'));
// expected output: "美國"
const locales1 = ['ban', 'id-u-co-pinyin', 'de-ID'];
const options1 = { localeMatcher: 'lookup' } as const;
console.log(Intl.DisplayNames.supportedLocalesOf(l... | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames
const regionNamesInEnglish = new Intl.DisplayNames(['en'], { type: 'region' });
const regionNamesInTraditionalChinese = new Intl.DisplayNames(['zh-Hant'], { type: 'region' });
| random_line_split |
es2020IntlAPIs.ts | // @target: es2020
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation
const count = 26254.39;
const date = new Date("2012-05-24");
function log(locale: string) |
log("en-US");
// expected output: 5/24/2012 26,254.39
log("de-DE");
// expected output: 24.5.2012 26.254,39
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat
const rtf1 = new Intl.RelativeTimeFormat('en', { style: 'narrow' });
console.log(rtf1.format(3, 'qu... | {
console.log(
`${new Intl.DateTimeFormat(locale).format(date)} ${new Intl.NumberFormat(locale).format(count)}`
);
} | identifier_body |
es2020IntlAPIs.ts | // @target: es2020
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation
const count = 26254.39;
const date = new Date("2012-05-24");
function | (locale: string) {
console.log(
`${new Intl.DateTimeFormat(locale).format(date)} ${new Intl.NumberFormat(locale).format(count)}`
);
}
log("en-US");
// expected output: 5/24/2012 26,254.39
log("de-DE");
// expected output: 24.5.2012 26.254,39
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Referenc... | log | identifier_name |
chess.js | function drawChart(len){
var box = document.createElement('div');
box.setAttribute('style','width:500px;height:500px;border:1px solid black;display:flex;flex-direction:column');
for(var i=0; i<len; i++){
var row = document.createElement('div');
if(i<len-1){
row.setAttribute('style','... | }
for(var j=0; j<len; j++){
var col = document.createElement('div');
if(i%2===0){
if(j%2===0){
col.setAttribute('style','background-color:white; flex: 1;');
}
else{
col.setAttribute('style','background-color:black; flex: 1;');
}
... | row.setAttribute('style','display:flex;box-sizing: border-box; flex: 1;'); | random_line_split |
chess.js | function drawChart(len){
var box = document.createElement('div');
box.setAttribute('style','width:500px;height:500px;border:1px solid black;display:flex;flex-direction:column');
for(var i=0; i<len; i++) | if(j%2===0){
col.setAttribute('style','background-color:black; flex: 1;');
}
else{
col.setAttribute('style','background-color:white; flex: 1;');
}
}
row.appendChild(col);
}
box.appendChild(row);
}
document.body.appendCh... | {
var row = document.createElement('div');
if(i<len-1){
row.setAttribute('style','border-bottom:1px solid black;display:flex;box-sizing: border-box; flex: 1;');
}
else{
row.setAttribute('style','display:flex;box-sizing: border-box; flex: 1;');
}
for(var j=0; j<len; j++... | conditional_block |
chess.js | function drawChart(len) | else{
col.setAttribute('style','background-color:black; flex: 1;');
}
}else{
if(j%2===0){
col.setAttribute('style','background-color:black; flex: 1;');
}
else{
col.setAttribute('style','background-color:white; flex: 1;');
... | {
var box = document.createElement('div');
box.setAttribute('style','width:500px;height:500px;border:1px solid black;display:flex;flex-direction:column');
for(var i=0; i<len; i++){
var row = document.createElement('div');
if(i<len-1){
row.setAttribute('style','border-bottom:1px solid... | identifier_body |
chess.js | function | (len){
var box = document.createElement('div');
box.setAttribute('style','width:500px;height:500px;border:1px solid black;display:flex;flex-direction:column');
for(var i=0; i<len; i++){
var row = document.createElement('div');
if(i<len-1){
row.setAttribute('style','border-bottom:1px ... | drawChart | identifier_name |
RomanNumerals.ts | export module RomanNumerals {
export function toRoman(number: number): string {
if ((number < 0) || (number > 3999)) throw new RangeError();
if (number < 1) return "";
if (number >= 1000) return `M${toRoman(number - 1000)}`;
if (number >= 900) return `CM${toRoman(number - 900)}... | }
} | random_line_split | |
RomanNumerals.ts | export module RomanNumerals {
export function toRoman(number: number): string {
| } |
if ((number < 0) || (number > 3999)) throw new RangeError();
if (number < 1) return "";
if (number >= 1000) return `M${toRoman(number - 1000)}`;
if (number >= 900) return `CM${toRoman(number - 900)}`;
if (number >= 500) return `D${toRoman(number - 500)}`;
if (number... | identifier_body |
RomanNumerals.ts | export module RomanNumerals {
export function to | umber: number): string {
if ((number < 0) || (number > 3999)) throw new RangeError();
if (number < 1) return "";
if (number >= 1000) return `M${toRoman(number - 1000)}`;
if (number >= 900) return `CM${toRoman(number - 900)}`;
if (number >= 500) return `D${toRoman(number - 50... | Roman(n | identifier_name |
role.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
desk_properties = ("search_bar", "notifications", "chat", "list_sidebar",
"bulk_actions", "view_switcher", "form_sideba... |
def on_update(self):
'''update system user desk access if this has changed in this update'''
if frappe.flags.in_install: return
if self.has_value_changed('desk_access'):
for user_name in get_users(self.name):
user = frappe.get_doc('User', user_name)
user_type = user.user_type
user.set_system_use... | frappe.db.sql("delete from `tabHas Role` where role = %s", self.name)
frappe.clear_cache() | identifier_body |
role.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
desk_properties = ("search_bar", "notifications", "chat", "list_sidebar", | frappe.throw(frappe._("Standard roles cannot be renamed"))
def after_insert(self):
frappe.cache().hdel('roles', 'Administrator')
def validate(self):
if self.disabled:
self.disable_role()
else:
self.set_desk_properties()
def disable_role(self):
if self.name in ("Guest", "Administrator", "System Ma... | "bulk_actions", "view_switcher", "form_sidebar", "timeline", "dashboard")
class Role(Document):
def before_rename(self, old, new, merge=False):
if old in ("Guest", "Administrator", "System Manager", "All"): | random_line_split |
role.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
desk_properties = ("search_bar", "notifications", "chat", "list_sidebar",
"bulk_actions", "view_switcher", "form_sideba... |
def after_insert(self):
frappe.cache().hdel('roles', 'Administrator')
def validate(self):
if self.disabled:
self.disable_role()
else:
self.set_desk_properties()
def disable_role(self):
if self.name in ("Guest", "Administrator", "System Manager", "All"):
frappe.throw(frappe._("Standard roles cann... | frappe.throw(frappe._("Standard roles cannot be renamed")) | conditional_block |
role.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
desk_properties = ("search_bar", "notifications", "chat", "list_sidebar",
"bulk_actions", "view_switcher", "form_sideba... | (role, field='email'):
''' Get information of all users that have been assigned this role '''
users = frappe.get_list("Has Role", filters={"role": role, "parenttype": "User"},
fields=["parent as user_name"])
return get_user_info(users, field)
def get_user_info(users, field='email'):
''' Fetch details about user... | get_info_based_on_role | identifier_name |
buffer.rs | use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError};
use buffer::Mapping as BufferMapping;
use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
| #[derive(Debug)]
pub struct UniformBuffer<T> where T: Copy + Send + 'static {
buffer: BufferView<T>,
}
/// Mapping of a buffer in memory.
pub struct Mapping<'a, T> {
mapping: BufferMapping<'a, T>,
}
/// Same as `UniformBuffer` but doesn't contain any information about the type.
#[derive(Debug)]
pub struct Typ... | use std::ops::{Deref, DerefMut};
use backend::Facade;
/// Buffer that contains a uniform block. | random_line_split |
buffer.rs | use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError};
use buffer::Mapping as BufferMapping;
use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
use std::ops::{Deref, DerefMut};
use backend::Facade;
/// Buffer that contains a uniform block.
#[derive(Debug)]
pub struct UniformB... | (&mut self) -> &mut D {
&mut self.mapping.deref_mut()[0]
}
}
impl<T> DerefMut for UniformBuffer<T> where T: Send + Copy + 'static {
fn deref_mut(&mut self) -> &mut BufferView<T> {
&mut self.buffer
}
}
impl<'a, T> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Send + Copy +... | deref_mut | identifier_name |
buffer.rs | use buffer::{BufferView, BufferViewAny, BufferType, BufferCreationError};
use buffer::Mapping as BufferMapping;
use uniforms::{AsUniformValue, UniformValue, UniformBlock, UniformType};
use std::ops::{Deref, DerefMut};
use backend::Facade;
/// Buffer that contains a uniform block.
#[derive(Debug)]
pub struct UniformB... |
}
impl<'a, T> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Send + Copy + 'static {
fn as_uniform_value(&self) -> UniformValue {
UniformValue::Block(self.buffer.as_slice_any(), <T as UniformBlock>::matches)
}
fn matches(_: &UniformType) -> bool {
false
}
}
| {
&mut self.buffer
} | identifier_body |
lib.rs | value.
pub fn ok(value: T) -> Promise<T, E> {
Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) }
}
/// Creates a new promise that has already been rejected with the given error.
pub fn err(error: E) -> Promise<T, E> {
Promise { node: Box::new(promise_node::Immediate::n... | {
Err(self.0.clone())
} | identifier_body | |
lib.rs | .then_else(|r| {
match r {
Ok(v) => func(v),
Err(e) => Promise::err(e),
}
})
}
/// Like `then_else()` but for a `func` that returns a direct value rather than a promise. As an
/// optimization, execution of `func` is delayed until its result i... | {
// If there is still an event other than the head event, then there must have
// been a memory leak.
let remaining_events = event_loop.events.borrow().len();
if remaining_events > 1 {
::std::mem::forget(event_loop)... | conditional_block | |
lib.rs | E: 'static
{
node: Box<PromiseNode<T, E>>,
}
impl<T, E> Promise<T, E> {
/// Creates a new promise that has already been fulfilled with the given value.
pub fn ok(value: T) -> Promise<T, E> {
Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) }
}
/// Creates a new p... | Err(e) => Err(func(e)),
}
})
}
/// Maps errors into a more general type.
pub fn lift<E1>(self) -> Promise<T, E1>
where E: Into<E1>
{
self.map_err(|e| e.into())
}
/// Returns a new promise that resolves when either `self` or `other` resolves. ... | random_line_split | |
lib.rs | E: 'static
{
node: Box<PromiseNode<T, E>>,
}
impl<T, E> Promise<T, E> {
/// Creates a new promise that has already been fulfilled with the given value.
pub fn ok(value: T) -> Promise<T, E> {
Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) }
}
/// Creates a new p... | (::std::marker::PhantomData<*mut u8>); // impl !Sync for WaitScope {}
/// The result of `Promise::fork()`. Allows branches to be created. Dropping the `ForkedPromise`
/// along with any branches created through `add_branch()` will cancel the computation.
pub struct ForkedPromise<T, E>
where T: 'static + Clone,
... | WaitScope | identifier_name |
test_cli_workbooks.py | # Copyright 2014 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... |
def test_delete_with_multi_names(self):
self.call(workbook_cmd.Delete, app_args=['name1', 'name2'])
self.assertEqual(2, self.client.workbooks.delete.call_count)
self.assertEqual(
[mock.call('name1'), mock.call('name2')],
self.client.workbooks.delete.call_args_list
... | self.call(workbook_cmd.Delete, app_args=['name'])
self.client.workbooks.delete.assert_called_once_with('name') | identifier_body |
test_cli_workbooks.py | # Copyright 2014 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | @mock.patch('argparse.open', create=True)
def test_validate(self, mock_open):
self.client.workbooks.validate.return_value = {'valid': True}
result = self.call(workbook_cmd.Validate, app_args=['wb.yaml'])
self.assertEqual((True, None), result[1])
@mock.patch('argparse.open', create... | self.call(workbook_cmd.GetDefinition, app_args=['name'])
self.app.stdout.write.assert_called_with(WB_DEF)
| random_line_split |
test_cli_workbooks.py | # Copyright 2014 - Mirantis, Inc.
# Copyright 2015 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | (self, mock_open):
self.client.workbooks.validate.return_value = {'valid': True}
result = self.call(workbook_cmd.Validate, app_args=['wb.yaml'])
self.assertEqual((True, None), result[1])
@mock.patch('argparse.open', create=True)
def test_validate_failed(self, mock_open):
self.... | test_validate | identifier_name |
app.component.spec.ts | /* tslint:disable: max-line-length */
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { MaterialModule } from '@angular/material';
import { AppComponent } from './app.component';
import ... | ],
providers: [],
declarations: [AppComponent, DashboardComponent, NotFound404Component]
});
});
it('should contain app text', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toContainText('hohu');
}))... | random_line_split | |
soundcloud.py | '/(?:preview|playlist)/0/30/', f['url'])
if preview:
format_id_list.append('preview')
abr = f.get('abr')
if abr:
f['abr'] = int(abr)
if protocol == 'hls':
protocol = 'm3u8' if ext == 'aac' else 'm3u8_native'
else... | return {
'_type': 'playlist',
'id': playlist_id,
'title': playlist_title,
'entries': entries, | random_line_split | |
soundcloud.py | _count': int,
'like_count': int,
'comment_count': int,
'repost_count': int,
},
},
# downloadable song
{
'url': 'https://soundcloud.com/oddsamples/bus-brakes',
'md5': '7624f2351f8a3b2e7cd51522496e7631',
... | self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or 'YUKXoArFcqrlQn9tfNHvvyfnDISj04zk'
@classmethod
def _resolv_url(cls, url):
return SoundcloudIE._API_V2_BASE + 'resolve?url=' + url
def _extract_info_dict(self, info, full_title=None, secret_token=None):
track_i... | lize(self):
| identifier_name |
soundcloud.py | format_urls
def add_format(f, protocol, is_preview=False):
mobj = re.search(r'\.(?P<abr>\d+)\.(?P<ext>[0-9a-z]{3,4})(?=[/?])', stream_url)
if mobj:
for k, v in mobj.groupdict().items():
if not f.get(k):
f[k] = v
fo... | conditional_block | ||
soundcloud.py | ': int,
'like_count': int,
'comment_count': int,
'repost_count': int,
},
},
# downloadable song
{
'url': 'https://soundcloud.com/oddsamples/bus-brakes',
'md5': '7624f2351f8a3b2e7cd51522496e7631',
'inf... | 'format_id': 'download',
'ext': urlhandle_detect_ext(urlh) or 'mp3',
'filesize': int_or_none(urlh.headers.get('Content-Length')),
'url': format_url,
'preference': 10,
})
d... | ompat_str(info['id'])
title = info['title']
format_urls = set()
formats = []
query = {'client_id': self._CLIENT_ID}
if secret_token:
query['secret_token'] = secret_token
if info.get('downloadable') and info.get('has_downloads_left'):
download_url... | identifier_body |
facility.rs | #[cfg(feature = "serde-serialize")]
use serde::{Serialize, Serializer};
use std::convert::TryFrom;
use thiserror::Error;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
#[allow(non_camel_case_types)]
/// Syslog facilities. Taken From RFC 5424, but I've heard that some platforms mix these around.
/// Na... |
/// Convert a syslog facility into a unique string representation
pub fn as_str(self) -> &'static str {
match self {
SyslogFacility::LOG_KERN => "kern",
SyslogFacility::LOG_USER => "user",
SyslogFacility::LOG_MAIL => "mail",
SyslogFacility::LOG_DAEMON =>... | {
Self::try_from(i).ok()
} | identifier_body |
facility.rs | #[cfg(feature = "serde-serialize")]
use serde::{Serialize, Serializer};
use std::convert::TryFrom;
use thiserror::Error;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
#[allow(non_camel_case_types)]
/// Syslog facilities. Taken From RFC 5424, but I've heard that some platforms mix these around.
/// Na... | LOG_CLOCKD = 15,
LOG_LOCAL0 = 16,
LOG_LOCAL1 = 17,
LOG_LOCAL2 = 18,
LOG_LOCAL3 = 19,
LOG_LOCAL4 = 20,
LOG_LOCAL5 = 21,
LOG_LOCAL6 = 22,
LOG_LOCAL7 = 23,
}
#[derive(Debug, Error)]
pub enum SyslogFacilityError {
#[error("integer does not correspond to a known facility")]
Inval... | LOG_AUTHPRIV = 10,
LOG_FTP = 11,
LOG_NTP = 12,
LOG_AUDIT = 13,
LOG_ALERT = 14, | random_line_split |
facility.rs | #[cfg(feature = "serde-serialize")]
use serde::{Serialize, Serializer};
use std::convert::TryFrom;
use thiserror::Error;
#[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
#[allow(non_camel_case_types)]
/// Syslog facilities. Taken From RFC 5424, but I've heard that some platforms mix these around.
/// Na... | {
#[error("integer does not correspond to a known facility")]
InvalidInteger,
}
impl TryFrom<i32> for SyslogFacility {
type Error = SyslogFacilityError;
#[inline(always)]
fn try_from(i: i32) -> Result<SyslogFacility, Self::Error> {
Ok(match i {
0 => SyslogFacility::LOG_KERN,
... | SyslogFacilityError | identifier_name |
index.ts | import {Component} from 'malevic';
import {getContext} from 'malevic/dom';
interface StateWrapper<T> {
state: T;
setState(newState: Partial<T>): void;
}
type UseStateFn<T> = (initialState: T) => StateWrapper<T>;
let currentUseStateFn: UseStateFn<any> = null;
export function useState<T extends {[prop: string... |
store.state = {...store.state, ...newState};
refresh();
};
return {
state: store.state,
setState,
};
};
let lock = true;
const prevUseStateFn = currentUseStateFn;
currentUseStateFn = us... | {
throw new Error(
'Setting state during unboxing causes infinite loop',
);
} | conditional_block |
index.ts | import {Component} from 'malevic';
import {getContext} from 'malevic/dom';
interface StateWrapper<T> {
state: T;
setState(newState: Partial<T>): void;
}
type UseStateFn<T> = (initialState: T) => StateWrapper<T>;
let currentUseStateFn: UseStateFn<any> = null;
export function useState<T extends {[prop: string... |
export function withState<T extends Component>(type: T): T {
const Stateful: any = (props: any, ...children: any) => {
const context = getContext();
const useState: UseStateFn<T> = (initial: T) => {
if (!context) {
return {state: initial, setState: null};
}... | {
if (!currentUseStateFn) {
throw new Error('`useState()` should be called inside a component');
}
return currentUseStateFn(initialState);
} | identifier_body |
index.ts | import {Component} from 'malevic';
import {getContext} from 'malevic/dom';
interface StateWrapper<T> {
state: T;
setState(newState: Partial<T>): void;
}
type UseStateFn<T> = (initialState: T) => StateWrapper<T>;
let currentUseStateFn: UseStateFn<any> = null;
export function useState<T extends {[prop: string... | currentUseStateFn = useState;
let result;
try {
result = type(props, ...children);
} finally {
currentUseStateFn = prevUseStateFn;
lock = false;
}
return result;
};
return Stateful;
} | random_line_split | |
index.ts | import {Component} from 'malevic';
import {getContext} from 'malevic/dom';
interface StateWrapper<T> {
state: T;
setState(newState: Partial<T>): void;
}
type UseStateFn<T> = (initialState: T) => StateWrapper<T>;
let currentUseStateFn: UseStateFn<any> = null;
export function | <T extends {[prop: string]: any}>(
initialState: T,
): StateWrapper<T> {
if (!currentUseStateFn) {
throw new Error('`useState()` should be called inside a component');
}
return currentUseStateFn(initialState);
}
export function withState<T extends Component>(type: T): T {
const Stateful: a... | useState | identifier_name |
struct-namespace.rs | // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
pub struct Struct2(pub u32);
}
fn main() {
let struct1 = Struct1 {
a: 0,
b: 1,
};
let struct2 = Struct2(2);
let mod1_struct1 = mod1::Struct1 {
a: 3,
b: 4,
};
let mod1_struct2 = mod1::Struct2(5);
zzz(); // #break
}
#[inline(never)]
fn zzz() {()} | pub b: u64,
} | random_line_split |
struct-namespace.rs | // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
pub a: u32,
pub b: u64,
}
pub struct Struct2(pub u32);
}
fn main() {
let struct1 = Struct1 {
a: 0,
b: 1,
};
let struct2 = Struct2(2);
let mod1_struct1 = mod1::Struct1 {
a: 3,
b: 4,
};
let mod1_struct2 = mod1::Struct2(5);
zzz()... | Struct1 | identifier_name |
Cert_5_6_09_NetworkDataForwarding.py | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | self.nodes[LEADER].add_prefix('2001:2:0:1::/64', 'paros', 'med')
self.nodes[LEADER].add_route('2001:2:0:2::/64', 'med')
self.nodes[LEADER].register_netdata()
time.sleep(10)
self.nodes[ROUTER2].add_prefix('2001:2:0:1::/64', 'paros', 'low')
self.nodes[ROUTER2].add_route('2... | self.nodes[LEADER].start()
self.nodes[LEADER].set_state('leader')
self.assertEqual(self.nodes[LEADER].get_state(), 'leader')
self.nodes[ROUTER1].start()
time.sleep(5)
self.assertEqual(self.nodes[ROUTER1].get_state(), 'router')
self.nodes[ROUTER2].start()
time.sl... | identifier_body |
Cert_5_6_09_NetworkDataForwarding.py | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... |
self.nodes[LEADER].set_panid(0xface)
self.nodes[LEADER].set_mode('rsdn')
self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64())
self.nodes[LEADER].add_whitelist(self.nodes[ROUTER2].get_addr64())
self.nodes[LEADER].enable_whitelist()
self.nodes[ROUTER1].set_... | self.nodes[i] = node.Node(i, (i in MTDS)) | conditional_block |
Cert_5_6_09_NetworkDataForwarding.py | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... | (unittest.TestCase):
def setUp(self):
self.nodes = {}
for i in range(1,6):
self.nodes[i] = node.Node(i, (i in MTDS))
self.nodes[LEADER].set_panid(0xface)
self.nodes[LEADER].set_mode('rsdn')
self.nodes[LEADER].add_whitelist(self.nodes[ROUTER1].get_addr64())
... | Cert_5_6_9_NetworkDataForwarding | identifier_name |
Cert_5_6_09_NetworkDataForwarding.py | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... |
self.nodes[ROUTER2].remove_prefix('2001:2:0:1::/64')
self.nodes[ROUTER2].add_prefix('2001:2:0:1::/64', 'paros', 'med')
self.nodes[ROUTER2].register_netdata()
time.sleep(10)
self.assertFalse(self.nodes[SED].ping('2007::1'))
if __name__ == '__main__':
unittest.main() | self.assertFalse(self.nodes[SED].ping('2007::1')) | random_line_split |
monch.rs | let value = String::from_utf8(value_bytes).ok().unwrap(); // do better
res.push((name, value));
}
Ok((res, bytes_len))
}
fn send_client_hello(sock: &mut Writer, max_length: i32) -> IoResult<()> {
try!(sock.write_i8(MESSAGE_TYPE_HELLO));
let attributes = vec![
(KEY_VERSION.to_string(), PROTOCOL_VERSION.to_str... | (sock: &mut Writer) -> IoResult<()> {
try!(sock.write_i8(MESSAGE_TYPE_HEARTBEAT));
try!(sock.write_be_i32(0));
try!(sock.flush());
Ok(())
}
#[derive(Debug)]
enum MyError {
Io(IoError),
Other(String)
}
impl FromError<IoError> for MyError {
fn from_error(err: IoError) -> MyError {
MyError::Io(err)
... | send_heartbeat | identifier_name |
monch.rs | let value = String::from_utf8(value_bytes).ok().unwrap(); // do better
res.push((name, value));
}
Ok((res, bytes_len))
}
fn send_client_hello(sock: &mut Writer, max_length: i32) -> IoResult<()> {
try!(sock.write_i8(MESSAGE_TYPE_HELLO));
let attributes = vec![
(KEY_VERSION.to_string(), PROTOCOL_VERSION.to_str... | else {
if body.len() as i32 == first_size.unwrap() {
same_size_count += 1;
}
}
if i % 1000 == 0 {
print!("\rCompleted {} requests.", i);
io::stdout().flush();
}
i += 1;
first = false;
},
other => return Err(MyError::Other(format!("Invalid message type. Expecting hear... | {
println!("First response attributes {:?}", attributes);
first_response = Some(body.clone());
first_size = Some(body.len() as i32)
} | conditional_block |
monch.rs | let value = String::from_utf8(value_bytes).ok().unwrap(); // do better
res.push((name, value));
}
Ok((res, bytes_len))
}
fn send_client_hello(sock: &mut Writer, max_length: i32) -> IoResult<()> {
try!(sock.write_i8(MESSAGE_TYPE_HELLO));
let attributes = vec![
(KEY_VERSION.to_string(), PROTOCOL_VERSION.to_str... |
fn connect(host: &str, port: u16, timeout: Duration) -> IoResult<TcpStream> {
//log("resolving %s..." % host)
//let address = socket.gethostbyname(host)
let sock = try!(TcpStream::connect_timeout((host, port), timeout));
Ok(sock)
}
fn parse_attributes(str: &Vec<String>) -> Result<Vec<(String, String)>, String> {... | {
let reference = try!(sock.read_be_u32());
let (attr, attr_len) = try!(recv_attributes(sock));
let remaining_length = length - 4 - attr_len;
let response = try!(sock.read_exact(remaining_length as usize));
let frame = ResponseData {
reference: reference as i32,
attributes: attr,
body: response
};
Ok(F... | identifier_body |
monch.rs | reference: i32,
attributes: Vec<(String, String)>,
body: Vec<u8>
}
fn recv_frame(sock: &mut Reader) -> Result<Frame, MyError> {
let message_type = try!(sock.read_byte()) as i8;
let length = try!(sock.read_be_i32());
match message_type {
MESSAGE_TYPE_HEARTBEAT => Ok(Frame::HeartBeat),
MESSAGE_TYPE_RESPONSE ... | println!("");
println!("Total time taken for tests: {:>7} ms", total_time);
println!("Connection time: {:>7} µs", connection_time); | random_line_split | |
types.ts | 1.166666, 1.428571]);
ss.harmonicMean([2, 3]).toFixed(2); // => '2.40'
ss.mean([0, 10]); // => 5
ss.median([10, 2, 5, 100, 2, 1]); // => 3.5
ss.medianSorted([10, 2, 5, 100, 2, 1]); // => 52.5
var bayes = new ss.BayesianClassifier();
bayes.train({ species: "Cat" }, "animal");
bayes.score({ species: "Cat" }); // => { a... | ss.chunk([1, 2, 3, 4, 5, 6], 2);
ss.ckmeans([-1, 2, -1, 2, 4, 5, 6, -1, 2, -1], 3);
ss.combinationsReplacement([1, 2], 2); // => [[1, 1], [1, 2], [2, 2]]
ss.combinations([1, 2, 3], 2); // => [[1,2], [1,3], [2,3]]
ss.equalIntervalBreaks([1, 2, 3, 4, 5, 6], 4); // => [1, 2.25, 3.5, 4.75, 6]
ss.errorFunction(1).toFixed(2)... | ss.chiSquaredDistributionTable[60][0.99]; | random_line_split |
types.ts | 1.166666, 1.428571]);
ss.harmonicMean([2, 3]).toFixed(2); // => '2.40'
ss.mean([0, 10]); // => 5
ss.median([10, 2, 5, 100, 2, 1]); // => 3.5
ss.medianSorted([10, 2, 5, 100, 2, 1]); // => 52.5
var bayes = new ss.BayesianClassifier();
bayes.train({ species: "Cat" }, "animal");
bayes.score({ species: "Cat" }); // => { an... |
p.predict([0, 0]); // 0
p.predict([0, 1]); // 0
p.predict([1, 0]); // 0
p.predict([1, 1]); // 1
ss.product([1, 2, 3, 4]); // => 24
ss.quantileSorted([3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20], 0.5); // => 9
ss.quantile([3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20], 0.5); // => 9
ss.quantile([3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20]... | {
p.train([1, 1], 1);
p.train([0, 1], 0);
p.train([1, 0], 0);
p.train([0, 0], 0);
} | conditional_block |
messages.js | 'use strict';
/**
* @ngdoc function
* @name saludWebApp.controller:AboutCtrl
* @description
* # AboutCtrl
* Controller of the saludWebApp
*/
angular.module('saludWebApp')
.controller('MessagesCtrl', function ($scope,Auth,Notifications,moment,global,Profile) {
Auth.isLogged(function(){
$scope.icon='f... | });
}); | random_line_split | |
__init__.py | # Copyright 2014, Rackspace, US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | from . import nova #flake8: noqa
from . import policy #flake8: noqa | from . import neutron #flake8: noqa | random_line_split |
relays.py | # -*- coding: utf-8 -*-
import logging
from flask import request
from flask import render_template
from relay import app
from relay.decorators import jsonify
from relay.decorators import session_required
from relay.decorators import sanitize_user
from relay.models.relays import add_relay_model
from relay.models.rel... |
elif request.method == 'POST':
success = queue_relay(
request.form['url'],
request.form['sender'],
request.form['recipients'],
)
return {'success': success}
@app.route('/a')
def test_relay_html():
relays = get_relays(None, 0)
return render_template('template.html', relays=relays)
... | offset = int(request.args.get('offset', 0))
return {'relays': get_relays(sent_relay_id, offset)} | conditional_block |
relays.py | # -*- coding: utf-8 -*-
import logging
from flask import request
from flask import render_template
from relay import app
from relay.decorators import jsonify
from relay.decorators import session_required
from relay.decorators import sanitize_user
from relay.models.relays import add_relay_model
from relay.models.rel... | (user_id=None, user=None):
offset = int(request.args.get('offset', 0))
limit = int(request.args.get('limit', 10))
sent_relays = []
sent_relay_items = get_sent_relays_for_user(user_id, offset=offset, limit=limit)
for sent_relay_item in sent_relay_items:
item_map = make_sent_relay_map(sent_relay_item)
... | get_relays_from_user | identifier_name |
relays.py | # -*- coding: utf-8 -*-
import logging
from flask import request
from flask import render_template
from relay import app
from relay.decorators import jsonify
from relay.decorators import session_required
from relay.decorators import sanitize_user
from relay.models.relays import add_relay_model
from relay.models.rel... |
@app.route('/relays/comment/delete', methods=['POST'])
@jsonify
@session_required
def remove_comment(user_id, user=None):
comment_id = long(request.form['comment_id'])
result = delete_comment(comment_id, user.key.id())
return {'success': result}
@app.route('/relays', methods=['GET', 'POST'])
@app.route('/rel... | like_id = long(request.form['like_id'])
result = delete_like(like_id, user.key.id())
return {'success': result} | identifier_body |
relays.py | # -*- coding: utf-8 -*-
import logging
from flask import request
from flask import render_template
from relay import app
from relay.decorators import jsonify
from relay.decorators import session_required
from relay.decorators import sanitize_user
from relay.models.relays import add_relay_model
from relay.models.rel... | @session_required
def get_relay_to_user(user_id=None, user=None, archived=False):
archived = bool(int(request.args.get('archived', 0)))
return _get_relay_to_user(user_id, user, archived)
def _get_relay_to_user(user_id=None, user=None, archived=False):
offset = int(request.args.get('offset', 0))
relays = get_re... | @jsonify
@sanitize_user | random_line_split |
wallet.py | .sync_all()
# node0 should end up with 100 btc in block rewards plus fees, but
# minus the 21 plus fees sent to node2
assert_equal(self.nodes[0].getbalance(), 100-21)
assert_equal(self.nodes[2].getbalance(), 21)
# Node0 should have two unspent outputs.
# Create a couple... |
# Have node 1 (miner) send the transactions
self.nodes[1].sendrawtransaction(txns_to_send[0]["hex"], True)
self.nodes[1].sendrawtransaction(txns_to_send[1]["hex"], True)
# Have node1 mine a block to confirm transactions:
self.nodes[1].generate(1)
self.sync_all()
... | inputs = []
outputs = {}
inputs.append({ "txid" : utxo["txid"], "vout" : utxo["vout"]})
outputs[self.nodes[2].getnewaddress("from1")] = utxo["amount"] - 3
raw_tx = self.nodes[0].createrawtransaction(inputs, outputs)
txns_to_send.append(self.nodes[0].signrawtra... | conditional_block |
wallet.py |
def setup_network(self, split=False):
self.nodes = start_nodes(3, self.options.tmpdir, self.extra_args[:3])
connect_nodes_bi(self.nodes,0,1)
connect_nodes_bi(self.nodes,1,2)
connect_nodes_bi(self.nodes,0,2)
self.is_network_split=False
self.sync_all()
def run_te... | super().__init__()
self.setup_clean_chain = True
self.num_nodes = 4
self.extra_args = [['-usehd={:d}'.format(i%2==0)] for i in range(4)] | identifier_body | |
wallet.py | (self):
# Check that there's no UTXO on none of the nodes
assert_equal(len(self.nodes[0].listunspent()), 0)
assert_equal(len(self.nodes[1].listunspent()), 0)
assert_equal(len(self.nodes[2].listunspent()), 0)
self.log.info("Mining blocks...")
self.nodes[0].generate(1)
... | run_test | identifier_name | |
wallet.py | .sync_all()
# node0 should end up with 100 btc in block rewards plus fees, but
# minus the 21 plus fees sent to node2
assert_equal(self.nodes[0].getbalance(), 100-21)
assert_equal(self.nodes[2].getbalance(), 21)
# Node0 should have two unspent outputs.
# Create a couple... | decRawTx = self.nodes[1].decoderawtransaction(rawTx)
signedRawTx = self.nodes[1].signrawtransaction(rawTx)
decRawTx = self.nodes[1].decoderawtransaction(signedRawTx['hex'])
zeroValueTxid= decRawTx['txid']
sendResp = self.nodes[1].sendrawtransaction(signedRawTx['hex'])
se... | usp = self.nodes[1].listunspent()
inputs = [{"txid":usp[0]['txid'], "vout":usp[0]['vout']}]
outputs = {self.nodes[1].getnewaddress(): 49.998, self.nodes[0].getnewaddress(): 11.11}
rawTx = self.nodes[1].createrawtransaction(inputs, outputs).replace("c0833842", "00000000") #replace 11.11 ... | random_line_split |
sort_transient_data.py | """ Module to correct pulsar and FRB DMs for the MW ISM """
from ne2001 import ne_io, density #ne2001 ism model
import pygedm #ymw ism model
import numpy as np
import pandas as pd
from astropy import units as u
from astropy.coordinates import SkyCoord, Galactic
import logging
logging.basicConfig(format='%(asctime)s -... | (transient_type,transient_data,ism_model,b_val,mc_deg=5,save_df=True):
"""
Find pulsar/FRB DMs corrected for by the MW ISM DM and remove observations in complex DM regions.
Returns array of DMs
FRB data is available as a csv in the FRBs/FRB/frb/data/FRBs repo (FRB catalogue [Petroff et al. 2017])
Pu... | find_delta_dm | identifier_name |
sort_transient_data.py | """ Module to correct pulsar and FRB DMs for the MW ISM """
from ne2001 import ne_io, density #ne2001 ism model
import pygedm #ymw ism model
import numpy as np
import pandas as pd
from astropy import units as u
from astropy.coordinates import SkyCoord, Galactic
import logging
logging.basicConfig(format='%(asctime)s -... | coords = SkyCoord(l=transcat_df['l'], b=transcat_df['b'], unit=(u.degree),frame=Galactic)
# Find transients in line of sight of MCs
logging.info('Removing transients near Magellanic clouds...')
# LMC
lmc_distance = 50*u.kpc
lmc_coord = SkyCoord('J052334.6-694522',unit=(u.hourangle, u.deg),d... | transcat_df['b'] = pd.DataFrame(c_icrs.galactic.b.value) | random_line_split |
sort_transient_data.py | """ Module to correct pulsar and FRB DMs for the MW ISM """
from ne2001 import ne_io, density #ne2001 ism model
import pygedm #ymw ism model
import numpy as np
import pandas as pd
from astropy import units as u
from astropy.coordinates import SkyCoord, Galactic
import logging
logging.basicConfig(format='%(asctime)s -... |
transcat_df['trans_ism'] = pd.DataFrame(trans_ism)
transcat_df['deltaDM'] = pd.DataFrame(transcat_df['dm']-transcat_df['trans_ism'])
if save_df==True:
transcat_df.to_csv('transient_data/'+transient_type+'cat_df_'+ism_model+'_'+str(int(b_val))+'.csv')
logging.info('Transient data saved to ... | trans_ism_ = ne.DM(transcat_df['l'].iloc[i], transcat_df['b'].iloc[i], 100.).value
trans_ism = np.append(trans_ism,trans_ism_) | conditional_block |
sort_transient_data.py | """ Module to correct pulsar and FRB DMs for the MW ISM """
from ne2001 import ne_io, density #ne2001 ism model
import pygedm #ymw ism model
import numpy as np
import pandas as pd
from astropy import units as u
from astropy.coordinates import SkyCoord, Galactic
import logging
logging.basicConfig(format='%(asctime)s -... |
Outputs:
"""
# Sort data and get coords
if transient_type=='frb':
transcat_df = pd.read_csv(transient_data, skiprows=1, usecols= [0,5,6,7], names=['Name','l','b','dm'])
transcat_df['dm'] = transcat_df['dm'].str.split('&').str[0].astype(float).values
coords = SkyCoord(l=tran... | """
Find pulsar/FRB DMs corrected for by the MW ISM DM and remove observations in complex DM regions.
Returns array of DMs
FRB data is available as a csv in the FRBs/FRB/frb/data/FRBs repo (FRB catalogue [Petroff et al. 2017])
Pulsar data is avaiable as a csv in the FRBs/pulsars/pulsars/data/atnf_cat re... | identifier_body |
build.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | () {
inner::main();
}
| main | identifier_name |
build.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | {
inner::main();
} | identifier_body | |
build.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | // 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 Parity. If not, see <http://www.gnu.org/licenses/>.
#[cfg(not(feature = "serde_macros"))]
mod inner {
extern crate se... | // but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
kdtu.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | self.state.config_recv(ep, buf, ord, msg_ord, 0);
self.write_ep_local(ep);
Ok(())
}
pub fn write_ep_remote(&mut self, vpe: &VPEDesc, ep: EpId, regs: &[Reg]) -> Result<(), Error> {
let eps = vpe.vpe().unwrap().eps_addr();
let addr = eps + ep * EPS_RCNT * util::size_of::<... | _size: usize) -> Result<(), Error> {
Err(Error::new(Code::NotSup))
}
pub fn recv_msgs(&mut self, ep: EpId, buf: goff, ord: i32, msg_ord: i32) -> Result<(), Error> { | random_line_split |
kdtu.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | () {
INST.set(Some(KDTU {
state: State::new(),
}));
}
pub fn get() -> &'static mut KDTU {
INST.get_mut().as_mut().unwrap()
}
pub fn write_ep_local(&mut self, ep: EpId) {
DTU::set_ep_regs(ep, self.state.get_ep(ep));
}
pub fn invalidate_ep_remote(&mut... | init | identifier_name |
kdtu.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... |
pub fn reset(&mut self, _vpe: &VPEDesc) -> Result<(), Error> {
// nothing to do
Ok(())
}
}
| {
let eps = vpe.vpe().unwrap().eps_addr();
let addr = eps + ep * EPS_RCNT * util::size_of::<Reg>();
let bytes = EPS_RCNT * util::size_of::<Reg>();
self.try_write_mem(vpe, addr as goff, regs.as_ptr() as *const u8, bytes)
} | identifier_body |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | 'wizard/hr_attendance_error_view.xml',
'res_config_view.xml',
],
'demo': ['hr_attendance_demo.xml'],
'test': [
'test/attendance_process.yml',
'test/hr_attendance_report.yml',
],
'installable': True,
'auto_install': False,
#web
"js": ["static/src/js/at... | 'hr_attendance_view.xml',
'hr_attendance_report.xml',
'wizard/hr_attendance_bymonth_view.xml',
'wizard/hr_attendance_byweek_view.xml', | random_line_split |
index.js | /* @flow */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
toggleCustomInlineStyle,
getSelectionCustomInlineStyle,
} from 'draftjs-utils';
import LayoutComponent from './Component';
export default class FontSize extends Component {
static propTypes = {
onChange: Prop... | (properties: Object): void {
if (properties.editorState &&
this.props.editorState !== properties.editorState) {
this.setState({
currentFontSize:
getSelectionCustomInlineStyle(properties.editorState, ['FONTSIZE']).FONTSIZE,
});
}
}
componentWillUnmount(): void {
const... | componentWillReceiveProps | identifier_name |
index.js | /* @flow */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
toggleCustomInlineStyle,
getSelectionCustomInlineStyle,
} from 'draftjs-utils';
import LayoutComponent from './Component';
export default class FontSize extends Component {
static propTypes = {
onChange: Prop... |
modalHandler.registerCallBack(this.expandCollapse);
}
componentWillReceiveProps(properties: Object): void {
if (properties.editorState &&
this.props.editorState !== properties.editorState) {
this.setState({
currentFontSize:
getSelectionCustomInlineStyle(properties.editorState... | {
this.setState({
currentFontSize:
getSelectionCustomInlineStyle(editorState, ['FONTSIZE']).FONTSIZE,
});
} | conditional_block |
index.js | /* @flow */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
toggleCustomInlineStyle,
getSelectionCustomInlineStyle,
} from 'draftjs-utils';
import LayoutComponent from './Component';
export default class FontSize extends Component {
static propTypes = {
onChange: Prop... | const newState = toggleCustomInlineStyle(
editorState,
'fontSize',
fontSize,
);
if (newState) {
onChange(newState);
}
};
render(): Object {
const { config, translations } = this.props;
const { expanded, currentFontSize } = this.state;
const FontSizeComponent = co... | random_line_split | |
index.js | /* @flow */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
toggleCustomInlineStyle,
getSelectionCustomInlineStyle,
} from 'draftjs-utils';
import LayoutComponent from './Component';
export default class FontSize extends Component {
static propTypes = {
onChange: Prop... |
onExpandEvent: Function = (): void => {
this.signalExpanded = !this.state.expanded;
};
expandCollapse: Function = (): void => {
this.setState({
expanded: this.signalExpanded,
});
this.signalExpanded = false;
}
doExpand: Function = (): void => {
this.setState({
expanded: tru... | {
const { modalHandler } = this.props;
modalHandler.deregisterCallBack(this.expandCollapse);
} | identifier_body |
timeranges.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::TimeRangesBinding;
use c... | else if new_range.is_before(&self.ranges[idx]) &&
(idx == 0 || self.ranges[idx - 1].is_before(&new_range))
{
// We are exactly after the current previous range and before the current
// range, while not overlapping with none of them.
// Or we ... | {
// The ranges are either overlapping or contiguous,
// we need to merge the new range with the existing one.
new_range.union(&self.ranges[idx]);
self.ranges.remove(idx);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.