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 |
|---|---|---|---|---|
barb_demo.py | from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
# read in data.
file = open('fcover.dat','r')
ul=[];vl=[];pl=[]
nlons=73; nlats=73
dellat = 2.5; dellon = 5.
for line in file.readlines():
l = line.replace('\n','').split()
ul.append(float(l[0]))
vl.append(float(l[1]))... | # barbs point toward lower pressure (in both Hemisphere).
m = Basemap(width=10000000,height=10000000,lon_0=-90,lat_0=-45.,lat_ts=-45,
resolution='l',projection='stere')
x,y = m(lons,lats)
# transform from spherical to map projection coordinates (rotation
# and interpolation).
nxv = 25; nyv = 25
udat, vdat, ... | random_line_split | |
custom_stream.rs | use std::io::Result as IoResult;
use std::io::{Read, Write};
pub struct | <R, W> {
reader: R,
writer: W,
}
impl<R, W> CustomStream<R, W>
where
R: Read,
W: Write,
{
pub fn new(reader: R, writer: W) -> CustomStream<R, W> {
CustomStream { reader, writer }
}
}
impl<R, W> Read for CustomStream<R, W>
where
R: Read,
{
fn read(&mut self, buf: &mut [u8]) -> I... | CustomStream | identifier_name |
custom_stream.rs | use std::io::Result as IoResult;
use std::io::{Read, Write};
pub struct CustomStream<R, W> {
reader: R,
writer: W,
}
impl<R, W> CustomStream<R, W>
where
R: Read,
W: Write,
{
pub fn new(reader: R, writer: W) -> CustomStream<R, W> {
CustomStream { reader, writer }
}
}
impl<R, W> Read fo... | } | }
fn flush(&mut self) -> IoResult<()> {
self.writer.flush()
} | random_line_split |
Min.d.ts | import { SimpleRule } from './SimpleRule';
| import { Primitive } from './Primitive';
/**
* Use the [Min] rule to determine if the target value is equal to or greater than the minimum
* allowed value [comparison].
*/
export declare class Min extends SimpleRule {
target: Primitive;
comparison: Primitive;
prima: any;
/**
* The cons... | random_line_split | |
forms.py | """
Forms and validation code for user registration.
"""
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from registration.models import RegistrationProfile
# I put this on all required fields, because it's easier to pick up
# on them wit... | (self):
"""
Validate that the username is alphanumeric and is not already
in use.
"""
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise... | clean_username | identifier_name |
forms.py | """
Forms and validation code for user registration.
"""
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from registration.models import RegistrationProfile
# I put this on all required fields, because it's easier to pick up
# on them wit... |
class RegistrationFormNoFreeEmail(RegistrationForm):
"""
Subclass of ``RegistrationForm`` which disallows registration with
email addresses from popular free webmail services; moderately
useful for preventing automated spam registrations.
To change the list of banned domains, subclass this f... | """
Validate that the supplied email address is unique for the
site.
"""
if User.objects.filter(email__iexact=self.cleaned_data['email']):
raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))
return... | identifier_body |
forms.py | """
Forms and validation code for user registration.
"""
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from registration.models import RegistrationProfile
# I put this on all required fields, because it's easier to pick up
# on them wit... | Validates that the requested username is not already in use, and
requires the password to be entered twice to catch typos.
Subclasses should feel free to add any additional validation they
need, but should either preserve the base ``save()`` or implement
a ``save()`` which accepts the ``profile... | """
Form for registering a new user account.
| random_line_split |
forms.py | """
Forms and validation code for user registration.
"""
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from registration.models import RegistrationProfile
# I put this on all required fields, because it's easier to pick up
# on them wit... |
return self.cleaned_data
def save(self, request, profile_callback=None):
"""
Create the new ``User`` and ``RegistrationProfile``, and
returns the ``User``.
This is essentially a light wrapper around
``RegistrationProfile.objects.create_inactive_user()``... | if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_(u'You must type the same password each time')) | conditional_block |
es7_utils.py | import importlib
import inspect
from celery import task
from django.conf import settings
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk as es7_bulk
from elasticsearch.helpers.errors import BulkIndexError
from elasticsearch_dsl import Document, UpdateByQuery, analyzer, char_filter, token... | # we must use "true" instead of True to work around an elastic-dsl bug
expand="true",
lenient="true",
updateable="true",
)
def es_analyzer_for_locale(locale, search_analyzer=False):
"""Pick an appropriate analyzer for a given locale.
If no analyzer is defined for `locale` o... | return token_filter(
filter_name,
type="synonym_graph",
synonyms_path=f"synonyms/{synonym_file_name}.txt", | random_line_split |
es7_utils.py | import importlib
import inspect
from celery import task
from django.conf import settings
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk as es7_bulk
from elasticsearch.helpers.errors import BulkIndexError
from elasticsearch_dsl import Document, UpdateByQuery, analyzer, char_filter, token... | (locale, search_analyzer=False):
"""Pick an appropriate analyzer for a given locale.
If no analyzer is defined for `locale` or the locale analyzer uses a plugin
but using plugin is turned off from settings, return an analyzer named "default_sumo".
"""
name = ""
analyzer_config = config.ES_LOCAL... | es_analyzer_for_locale | identifier_name |
es7_utils.py | import importlib
import inspect
from celery import task
from django.conf import settings
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk as es7_bulk
from elasticsearch.helpers.errors import BulkIndexError
from elasticsearch_dsl import Document, UpdateByQuery, analyzer, char_filter, token... | es7_client(
timeout=timeout,
retry_on_timeout=True,
initial_backoff=timeout,
max_retries=settings.ES_BULK_MAX_RETRIES,
),
(doc.to_action(action=action, is_bulk=True, **kwargs) for doc in docs),
chunk_size=elastic_chunk_size,
raise_o... | """Bulk index ORM objects given a list of object ids and a document type name."""
doc_type = next(cls for cls in get_doc_types() if cls.__name__ == doc_type_name)
db_objects = doc_type.get_queryset().filter(pk__in=obj_ids)
# prepare the docs for indexing
docs = [doc_type.prepare(obj) for obj in db_obj... | identifier_body |
es7_utils.py | import importlib
import inspect
from celery import task
from django.conf import settings
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk as es7_bulk
from elasticsearch.helpers.errors import BulkIndexError
from elasticsearch_dsl import Document, UpdateByQuery, analyzer, char_filter, token... |
@task
def index_objects_bulk(
doc_type_name,
obj_ids,
timeout=settings.ES_BULK_DEFAULT_TIMEOUT,
elastic_chunk_size=settings.ES_DEFAULT_ELASTIC_CHUNK_SIZE,
):
"""Bulk index ORM objects given a list of object ids and a document type name."""
doc_type = next(cls for cls in get_doc_types() if cl... | doc_type.prepare(obj).to_action("index") | conditional_block |
AppContainer.js | 'use strict'
import React, {PropTypes} from 'react'
import {NavigationExperimental, View, StyleSheet} from 'react-native'
import { connect } from 'react-redux'
import First from './First'
import Second from './Second'
import { navigatePop } from '../actions'
const {
Transitioner: NavigationTransitioner,
Card: Navi... | // (Passing undefined causes the default interpolator to be used in NavigationCard.)
style={props.scene.route.key === 'Modal' ?
NavigationCard.CardStackStyleInterpolator.forVertical(props) :
undefined
}
onNavigateBack={backAction}
// By default a user can swipe bac... | {
let { navigationState, backAction } = this.props
return (
// Redux is handling the reduction of our state for us. We grab the navigationState
// we have in our Redux store and pass it directly to the <NavigationTransitioner />.
<NavigationTransitioner
navigationState={navigationState}
style={st... | identifier_body |
AppContainer.js | 'use strict'
import React, {PropTypes} from 'react'
import {NavigationExperimental, View, StyleSheet} from 'react-native'
import { connect } from 'react-redux'
import First from './First'
import Second from './Second'
import { navigatePop } from '../actions'
const {
Transitioner: NavigationTransitioner,
Card: Navi... | // By default a user can swipe back to pop from the stack. Disable this for modals.
// Just like for style interpolators, returning undefined lets NavigationCard override it.
panHandlers={props.scene.route.key === 'Modal' ? null : undefined }
renderScene={this._renderScene}
key={props... | NavigationCard.CardStackStyleInterpolator.forVertical(props) :
undefined
}
onNavigateBack={backAction} | random_line_split |
AppContainer.js | 'use strict'
import React, {PropTypes} from 'react'
import {NavigationExperimental, View, StyleSheet} from 'react-native'
import { connect } from 'react-redux'
import First from './First'
import Second from './Second'
import { navigatePop } from '../actions'
const {
Transitioner: NavigationTransitioner,
Card: Navi... | extends React.Component {
render() {
let { navigationState, backAction } = this.props
return (
// Redux is handling the reduction of our state for us. We grab the navigationState
// we have in our Redux store and pass it directly to the <NavigationTransitioner />.
<NavigationTransitioner
navigation... | AppContainer | identifier_name |
fixtures.py | tures ################
@pytest.fixture(scope='session')
def _django_db_setup(request,
_django_test_environment,
_django_cursor_wrapper):
"""Session-wide database setup, internal to pytest-django"""
skip_if_no_django()
from .compat import setup_databases, teardown_... | if 'south' not in settings.INSTALLED_APPS or get_django_version() > (1, 7):
return
from django.core import management
try:
# if `south` >= 0.7.1 we can use the test helper
from south.management.commands import patch_for_test_db_setup
except ImportError:
# if `south` < 0... | from django.conf import settings
# NOTE: Django 1.7 does not have `management._commands` anymore, which
# is used by South's `patch_for_test_db_setup` and the code below. | random_line_split |
fixtures.py | tures ################
@pytest.fixture(scope='session')
def _django_db_setup(request,
_django_test_environment,
_django_cursor_wrapper):
"""Session-wide database setup, internal to pytest-django"""
skip_if_no_django()
from .compat import setup_databases, teardown_... |
else:
# Django before 1.5 flushed the DB during setUp.
# Use pytest-django's old behavior with it.
def flushdb():
"""Flush the database and close database connections"""
# Django does this by default *before* each test
# inste... | from django.test import TransactionTestCase as django_case | conditional_block |
fixtures.py | ################
@pytest.fixture(scope='session')
def _django_db_setup(request,
_django_test_environment,
_django_cursor_wrapper):
"""Session-wide database setup, internal to pytest-django"""
skip_if_no_django()
from .compat import setup_databases, teardown_datab... |
class MonkeyPatchWrapper(object):
def __init__(self, monkeypatch, wrapped_object):
super(MonkeyPatchWrapper, self).__setattr__('monkeypatch', monkeypatch)
super(MonkeyPatchWrapper, self).__setattr__('wrapped_object',
wrapped_object)
def __g... | """RequestFactory instance"""
skip_if_no_django()
from django.test.client import RequestFactory
return RequestFactory() | identifier_body |
fixtures.py | ################
@pytest.fixture(scope='session')
def _django_db_setup(request,
_django_test_environment,
_django_cursor_wrapper):
"""Session-wide database setup, internal to pytest-django"""
skip_if_no_django()
from .compat import setup_databases, teardown_datab... | (self, attr):
self.monkeypatch.delattr(self.wrapped_object, attr)
@pytest.fixture()
def settings(monkeypatch):
"""A Django settings object which restores changes after the testrun"""
skip_if_no_django()
from django.conf import settings as django_settings
return MonkeyPatchWrapper(monkeypatch,... | __delattr__ | identifier_name |
computer_system_1_0_0_system_type.py | # coding: utf-8
"""
Copyright 2015 SmartBear Software
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 applica... |
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| """
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__ | identifier_body |
computer_system_1_0_0_system_type.py | # coding: utf-8
"""
Copyright 2015 SmartBear Software
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 applica... | """
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self ... |
def __repr__(self):
"""
For `print` and `pprint` | random_line_split |
computer_system_1_0_0_system_type.py | # coding: utf-8
"""
Copyright 2015 SmartBear Software
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 applica... |
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return sel... | result[attr] = value.to_dict() | conditional_block |
computer_system_1_0_0_system_type.py | # coding: utf-8
"""
Copyright 2015 SmartBear Software
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 applica... | (self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if ... | to_dict | identifier_name |
connectors_local.py | import time
from threading import Thread
import threading
from wtfj_ids import *
from wtfj_utils import *
class Printer:
''' Opens a new output window and prints messages sent to it '''
def __init__(self,header=''):
self._header = header
def send(self,string):
print(self._header+string)
class | :
''' Allows user to enter commands '''
def __init__(self,prompt='[$] '):
self._prompt = prompt
self._at = ''
def poll(self,wait_s=None,uid=None):
try:
prompt = str(self._at)+str(self._prompt)
msg = raw_input(prompt)
if msg == '':
self._at = ''
return []
if msg[0] == '@':
self._at = ms... | Console | identifier_name |
connectors_local.py | import time
from threading import Thread
import threading
from wtfj_ids import *
from wtfj_utils import *
class Printer:
''' Opens a new output window and prints messages sent to it '''
def __init__(self,header=''):
self._header = header
def send(self,string):
print(self._header+string)
class Console:
''' Al... |
else: assert uid in get_attr(Uid)
return self
def load(self,msg_array):
self._msgs += msg_array
return self
def set_period(self,period):
self._period = period
return self
def run(self):
t = threading.current_thread()
self._pid = str(t.ident)+' '+str(t.name)
while len(self.poll()) > 0: pass
... | assert uid[1:] in get_attr(Uid) | conditional_block |
connectors_local.py | import time
from threading import Thread
import threading
from wtfj_ids import *
from wtfj_utils import *
class Printer:
''' Opens a new output window and prints messages sent to it '''
def __init__(self,header=''):
self._header = header
def send(self,string):
print(self._header+string)
class Console:
''' Al... | time.sleep(period)
try:
msg = self._msgs[self._index]
print(self._pid+' SEND > '+msg)
self._index += 1
return [msg]
except IndexError:
return []
def subscribe(self,*uids):
for uid in uids:
if uid is not None:
if uid[0] is '@': assert uid[1:] in get_attr(Uid)
else: assert uid in get_a... | def poll(self,wait_s=None,uid=None):
period = self._period if wait_s is None else wait_s | random_line_split |
connectors_local.py | import time
from threading import Thread
import threading
from wtfj_ids import *
from wtfj_utils import *
class Printer:
''' Opens a new output window and prints messages sent to it '''
def __init__(self,header=''):
self._header = header
def send(self,string):
print(self._header+string)
class Console:
''' Al... |
def subscribe(self,*uids):
for uid in uids:
if uid is not None:
if uid[0] is '@': assert uid[1:] in get_attr(Uid)
else: assert uid in get_attr(Uid)
return self
def load(self,msg_array):
self._msgs += msg_array
return self
def set_period(self,period):
self._period = period
return self
def... | period = self._period if wait_s is None else wait_s
time.sleep(period)
try:
msg = self._msgs[self._index]
print(self._pid+' SEND > '+msg)
self._index += 1
return [msg]
except IndexError:
return [] | identifier_body |
utils.py | from __future__ import division
import datetime as dt
missing = object()
try:
import numpy as np
except ImportError:
np = None
def int_to_rgb(number):
"""Given an integer, return the rgb"""
number = int(number)
r = number % 256
g = (number // 256) % 256
b = (number // (256 * 256)) % 25... | self.f.write('\t' * self._indent)
self._freshline = False
if kwargs:
template = template.format(**kwargs)
self.f.write(template)
if template[-1] == '\n':
self._freshline = True
def write_label(self, label):
self._indent -= 1
se... | def write(self, template, **kwargs):
if self._freshline: | random_line_split |
utils.py | from __future__ import division
import datetime as dt
missing = object()
try:
import numpy as np
except ImportError:
np = None
def int_to_rgb(number):
"""Given an integer, return the rgb"""
number = int(number)
r = number % 256
g = (number // 256) % 256
b = (number // (256 * 256)) % 25... |
self.f.write(template)
if template[-1] == '\n':
self._freshline = True
def write_label(self, label):
self._indent -= 1
self.write(label + ':\n')
self._indent += 1
def writeln(self, template, **kwargs):
self.write(template + '\n', **kwargs)
| template = template.format(**kwargs) | conditional_block |
utils.py | from __future__ import division
import datetime as dt
missing = object()
try:
import numpy as np
except ImportError:
np = None
def int_to_rgb(number):
"""Given an integer, return the rgb"""
number = int(number)
r = number % 256
g = (number // 256) % 256
b = (number // (256 * 256)) % 25... |
def __exit__(self, exc_type, exc_val, exc_tb):
self.writer._indent -= 1
#self.writer.writeln(self.end)
def __init__(self, f):
self.f = f
self._indent = 0
self._freshline = True
def block(self, template, **kwargs):
return VBAWriter.Block(self, t... | self.writer.writeln(self.start)
self.writer._indent += 1 | identifier_body |
utils.py | from __future__ import division
import datetime as dt
missing = object()
try:
import numpy as np
except ImportError:
np = None
def int_to_rgb(number):
"""Given an integer, return the rgb"""
number = int(number)
r = number % 256
g = (number // 256) % 256
b = (number // (256 * 256)) % 25... | (self, template, **kwargs):
self.write(template + '\n', **kwargs)
| writeln | identifier_name |
plot_pca_vs_fa_model_selection.py | """
===============================================================
Model selection with Probabilistic PCA and Factor Analysis (FA)
===============================================================
Probabilistic PCA and Factor Analysis are probabilistic models.
The consequence is that the likelihood of new data can be u... |
def lw_score(X):
return np.mean(cross_val_score(LedoitWolf(), X))
for X, title in [(X_homo, 'Homoscedastic Noise'),
(X_hetero, 'Heteroscedastic Noise')]:
pca_scores, fa_scores = compute_scores(X)
n_components_pca = n_components[np.argmax(pca_scores)]
n_components_fa = n_components[... | shrinkages = np.logspace(-2, 0, 30)
cv = GridSearchCV(ShrunkCovariance(), {'shrinkage': shrinkages})
return np.mean(cross_val_score(cv.fit(X).best_estimator_, X)) | identifier_body |
plot_pca_vs_fa_model_selection.py | """
===============================================================
Model selection with Probabilistic PCA and Factor Analysis (FA)
===============================================================
Probabilistic PCA and Factor Analysis are probabilistic models.
The consequence is that the likelihood of new data can be u... |
# Adding heteroscedastic noise
sigmas = sigma * rng.rand(n_features) + sigma / 2.
X_hetero = X + rng.randn(n_samples, n_features) * sigmas
###############################################################################
# Fit the models
n_components = np.arange(0, n_features, 5) # options for n_components
def comp... |
# Adding homoscedastic noise
X_homo = X + sigma * rng.randn(n_samples, n_features) | random_line_split |
plot_pca_vs_fa_model_selection.py | """
===============================================================
Model selection with Probabilistic PCA and Factor Analysis (FA)
===============================================================
Probabilistic PCA and Factor Analysis are probabilistic models.
The consequence is that the likelihood of new data can be u... | (X):
pca = PCA()
fa = FactorAnalysis()
pca_scores, fa_scores = [], []
for n in n_components:
pca.n_components = n
fa.n_components = n
pca_scores.append(np.mean(cross_val_score(pca, X)))
fa_scores.append(np.mean(cross_val_score(fa, X)))
return pca_scores, fa_scores
... | compute_scores | identifier_name |
plot_pca_vs_fa_model_selection.py | """
===============================================================
Model selection with Probabilistic PCA and Factor Analysis (FA)
===============================================================
Probabilistic PCA and Factor Analysis are probabilistic models.
The consequence is that the likelihood of new data can be u... | plt.axvline(n_components_pca_mle, color='k',
label='PCA MLE: %d' % n_components_pca_mle, linestyle='--')
# compare with other covariance estimators
plt.axhline(shrunk_cov_score(X), color='violet',
label='Shrunk Covariance MLE', linestyle='-.')
plt.axhline(lw_score(X), co... | pca_scores, fa_scores = compute_scores(X)
n_components_pca = n_components[np.argmax(pca_scores)]
n_components_fa = n_components[np.argmax(fa_scores)]
pca = PCA(n_components='mle')
pca.fit(X)
n_components_pca_mle = pca.n_components_
print("best n_components by PCA CV = %d" % n_components_pca)
... | conditional_block |
api.py | /compute/"
# The API will return HTTP Bad Request if the ?changes-since
# parameter refers to a point in time more than POLL_LIMIT seconds ago.
POLL_LIMIT = 3600
# Astakos groups that have access to '/admin' views.
ADMIN_STATS_PERMITTED_GROUPS = ["admin-stats"]
# Enable/Disable the snapshots feature altogether at th... |
# The maximmum allowed metadata items for a Cyclades Virtual Machine
CYCLADES_VM_MAX_METADATA = 10
# Define cache for public stats
PUBLIC_STATS_CACHE = {
| random_line_split | |
mollom.flag.js | (function ($) {
/**
* Only show links to report comments after the comment has been moused over.
*/
Drupal.behaviors.mollomReportComment = {
showReportLink: function(e) {
$(this).find('.mollom-flag').show();
},
hideReportLink: function(e) {
if ($(this).find('.mollom-flag-reasons').length ==... | },
detach: function(context) {
if ($(context).hasClass('mollom-flag-container')) {
$(document).unbind('keydown',this.checkCloseDialog);
$(document).unbind('click',this.checkClickOutside);
}
}
};
/**
* Add a class to reported content to allow overriding the display with CSS.
*/
D... | $(document).bind('keydown',$.proxy(this.checkEscapeDialog,this));
$(document).bind('click',$.proxy(this.checkClickOutside,this));
}
| random_line_split |
mollom.flag.js | (function ($) {
/**
* Only show links to report comments after the comment has been moused over.
*/
Drupal.behaviors.mollomReportComment = {
showReportLink: function(e) {
$(this).find('.mollom-flag').show();
},
hideReportLink: function(e) {
if ($(this).find('.mollom-flag-reasons').length ==... |
},
detach: function(context) {
$(context).find('.comment:has(.mollom-flag)').unbind('mouseover',this.showReportLink);
$(context).find('.comment:has(.mollom-flag)').unbind('mouseout',this.hideReportLink);
}
};
/**
* Close a form to report comments as inappropriate if user clicks outside.
*/... | {
$(context).find('.comment:has(.mollom-flag)').bind('mouseover',this.showReportLink);
$(context).find('.comment:has(.mollom-flag)').bind('mouseout',this.hideReportLink);
$(context).find('.comment .mollom-flag').hide();
} | conditional_block |
UserAvatar.tsx | import {Avatar, AvatarPosition, AvatarSize, AvatarStatus, Box, Text, Tooltip} from '@sanity/ui'
import React, {useState} from 'react'
import type {User} from '@sanity/types'
import {useUserColor} from '../user-color'
import {useUser} from '../datastores/user/hooks'
type LegacyAvatarSize = 'small' | 'medium' | 'large'
... |
export function UserAvatar(props: Props) {
if (isLoaded(props)) {
if (props.withTooltip) {
return <TooltipUserAvatar {...props} />
}
return <StaticUserAvatar {...props} />
}
return <UserAvatarLoader {...props} />
}
function TooltipUserAvatar(props: LoadedUserProps) {
const {
user: {dis... | {
const namesArray = fullName.replace(symbols, '').split(whitespace)
if (namesArray.length === 1) {
return `${namesArray[0].charAt(0)}`.toUpperCase()
}
return `${namesArray[0].charAt(0)}${namesArray[namesArray.length - 1].charAt(0)}`
} | identifier_body |
UserAvatar.tsx | import {Avatar, AvatarPosition, AvatarSize, AvatarStatus, Box, Text, Tooltip} from '@sanity/ui'
import React, {useState} from 'react'
import type {User} from '@sanity/types'
import {useUserColor} from '../user-color'
import {useUser} from '../datastores/user/hooks'
type LegacyAvatarSize = 'small' | 'medium' | 'large'
... |
return `${namesArray[0].charAt(0)}${namesArray[namesArray.length - 1].charAt(0)}`
}
export function UserAvatar(props: Props) {
if (isLoaded(props)) {
if (props.withTooltip) {
return <TooltipUserAvatar {...props} />
}
return <StaticUserAvatar {...props} />
}
return <UserAvatarLoader {...pro... | {
return `${namesArray[0].charAt(0)}`.toUpperCase()
} | conditional_block |
UserAvatar.tsx | import {Avatar, AvatarPosition, AvatarSize, AvatarStatus, Box, Text, Tooltip} from '@sanity/ui'
import React, {useState} from 'react'
import type {User} from '@sanity/types'
import {useUserColor} from '../user-color'
import {useUser} from '../datastores/user/hooks'
type LegacyAvatarSize = 'small' | 'medium' | 'large'
... | const namesArray = fullName.replace(symbols, '').split(whitespace)
if (namesArray.length === 1) {
return `${namesArray[0].charAt(0)}`.toUpperCase()
}
return `${namesArray[0].charAt(0)}${namesArray[namesArray.length - 1].charAt(0)}`
}
export function UserAvatar(props: Props) {
if (isLoaded(props)) {
... | large: 2,
}
function nameToInitials(fullName: string) { | random_line_split |
UserAvatar.tsx | import {Avatar, AvatarPosition, AvatarSize, AvatarStatus, Box, Text, Tooltip} from '@sanity/ui'
import React, {useState} from 'react'
import type {User} from '@sanity/types'
import {useUserColor} from '../user-color'
import {useUser} from '../datastores/user/hooks'
type LegacyAvatarSize = 'small' | 'medium' | 'large'
... | (fullName: string) {
const namesArray = fullName.replace(symbols, '').split(whitespace)
if (namesArray.length === 1) {
return `${namesArray[0].charAt(0)}`.toUpperCase()
}
return `${namesArray[0].charAt(0)}${namesArray[namesArray.length - 1].charAt(0)}`
}
export function UserAvatar(props: Props) {
if (i... | nameToInitials | identifier_name |
styles_cssText.js | function loadText()
{
var txtLang = document.getElementsByName("txtLang");
txtLang[0].innerHTML = "CSS Text";
txtLang[1].innerHTML = "Klassnamn";
txtLang[2].innerHTML = "F\u00F6rhandsgranska";
txtLang[3].innerHTML = "Applicera p\u00E5";
var optLang = document.getElementsByName("... | ()
{
document.write("<title>Egen formatering</title>")
} | writeTitle | identifier_name |
styles_cssText.js | function loadText()
{
var txtLang = document.getElementsByName("txtLang");
txtLang[0].innerHTML = "CSS Text";
txtLang[1].innerHTML = "Klassnamn";
txtLang[2].innerHTML = "F\u00F6rhandsgranska";
txtLang[3].innerHTML = "Applicera p\u00E5";
var optLang = document.getElementsByName("... | {
switch(s)
{
case "You're selecting BODY element.":
return "Du har valt BODY taggen.";
case "Please select a text.":
return "V\u00E4nligen v\u00E4lj text.";
default:return "";
}
}
function writeTitle()
{
document.write("<ti... | document.getElementById("btnApply").value = "Verkst\u00E4ll";
document.getElementById("btnOk").value = " OK ";
}
function getText(s)
| random_line_split |
styles_cssText.js | function loadText()
{
var txtLang = document.getElementsByName("txtLang");
txtLang[0].innerHTML = "CSS Text";
txtLang[1].innerHTML = "Klassnamn";
txtLang[2].innerHTML = "F\u00F6rhandsgranska";
txtLang[3].innerHTML = "Applicera p\u00E5";
var optLang = document.getElementsByName("... | {
document.write("<title>Egen formatering</title>")
} | identifier_body | |
expander.rs | // Our use cases
use super::stream;
pub const WAVE_FORMAT_PCM: usize = 1;
#[derive(Default)]
pub struct WaveFormatEx {
pub format_tag: u16,
pub channels: u16,
pub samples_per_second: i32,
pub average_bytes_per_second: i32,
pub block_align: u16,
pub bits_per_sample: u16,
pub cb_size: u16,
}... | () -> SoundExpander {
let wave_format: WaveFormatEx = Default::default();
SoundExpander {
memb_20: 0,
memb_24: 0,
memb_28: 0,
memb_30: 0,
memb_34: 0,
memb_40: 0,
memb_48: 0,
memb_4C: 0,
memb_54: 0,
memb_58: 0,
memb_5C: 0,
memb_64: 0,
memb_68: 0,
memb_70: 0,
memb_7... | new | identifier_name |
expander.rs | // Our use cases
use super::stream;
pub const WAVE_FORMAT_PCM: usize = 1;
#[derive(Default)]
pub struct WaveFormatEx {
pub format_tag: u16,
pub channels: u16,
pub samples_per_second: i32,
pub average_bytes_per_second: i32,
pub block_align: u16,
pub bits_per_sample: u16,
pub cb_size: u16,
}... | }
} | some_var_6680EC: 0,
some_var_6680E8: 0,
previous: Box::new(SoundExpander::new()),
next: Box::new(SoundExpander::new()),
} | random_line_split |
LayerLoader.js | : constructor
* .. class:: LayerLoader
*
* A loader that will load all layers of a :class:`GeoExt.data.LayerStore`
* By default, only layers that have displayInLayerSwitcher set to true
* will be included. The childrens' iconCls defaults to
* "gx-tree-layer-icon".
*/
GeoExt.tree.LayerLoader... | this.addEvents(
/** api: events[beforeload]
* Triggered before loading children. Return false to avoid
* loading children.
*
* Listener arguments:
* * loader - :class:`GeoExt.tree.LayerLoader` this loader
* * node - ``Ex.tree.TreeNode`` the n... | Ext.apply(this, config); | random_line_split |
LayerLoader.js | : constructor
* .. class:: LayerLoader
*
* A loader that will load all layers of a :class:`GeoExt.data.LayerStore`
* By default, only layers that have displayInLayerSwitcher set to true
* will be included. The childrens' iconCls defaults to
* "gx-tree-layer-icon".
*/
GeoExt.tree.LayerLoader... |
this.store.each(function(record) {
this.addLayerNode(node, record);
}, this);
this.addStoreHandlers(node);
if(typeof callback == "function"){
callback();
}
this.fireEvent("load", this, node);
... | {
this.store = GeoExt.MapPanel.guess().layers;
} | conditional_block |
server.ts | import * as Koa from "koa";
import * as serve from "koa-static";
import * as bodyParser from "koa-bodyparser";
import * as compress from "koa-compress";
import * as https from "https";
import {Z_SYNC_FLUSH} from "zlib";
import {SERVER} from "./config/config";
import {routes, allowedMethods} from "./routes/index";
impo... | console.log("app listen on", this.server.address().address + ":" + this.server.address().port));
}
close() {
this.server.close(data => console.log("Server closed:", data));
}
} | this.app.use(allowedMethods());
this.app.use(redirect);
this.server = this.app.listen(SERVER.PORT, SERVER.HOST_NAME, () => | random_line_split |
server.ts | import * as Koa from "koa";
import * as serve from "koa-static";
import * as bodyParser from "koa-bodyparser";
import * as compress from "koa-compress";
import * as https from "https";
import {Z_SYNC_FLUSH} from "zlib";
import {SERVER} from "./config/config";
import {routes, allowedMethods} from "./routes/index";
impo... | {
app: Koa;
server: https.Server;
static bootstrap(): Server {
return new Server();
}
constructor() {
this.app = new Koa();
this.app.use(error);
this.app.use(log);
this.app.use(bodyParser());
this.app.use(compress({
filter: content_type... | Server | identifier_name |
record.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use api::{ApiMsg, FrameMsg, SceneMsg};
use bincode::serialize;
use byteorder::{LittleEndian, WriteBytesExt};
use s... |
fn write_length_and_data(&mut self, data: &[u8]) {
self.file.write_u32::<LittleEndian>(data.len() as u32).ok();
self.file.write(data).ok();
}
}
impl ApiRecordingReceiver for BinaryRecorder {
fn write_msg(&mut self, _: u32, msg: &ApiMsg) {
if should_record_msg(msg) {
le... | {
let mut file = File::create(dest).unwrap();
// write the header
let apimsg_type_id = unsafe {
assert!(mem::size_of::<TypeId>() == mem::size_of::<u64>());
mem::transmute::<TypeId, u64>(TypeId::of::<ApiMsg>())
};
file.write_u64::<LittleEndian>(WEBRENDER_R... | identifier_body |
record.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use api::{ApiMsg, FrameMsg, SceneMsg};
use bincode::serialize;
use byteorder::{LittleEndian, WriteBytesExt};
use s... | (&mut self, _: u32, msg: &ApiMsg) {
if should_record_msg(msg) {
let buf = serialize(msg).unwrap();
self.write_length_and_data(&buf);
}
}
fn write_payload(&mut self, _: u32, data: &[u8]) {
// signal payload with a 0 length
self.file.write_u32::<LittleEndia... | write_msg | identifier_name |
record.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use api::{ApiMsg, FrameMsg, SceneMsg};
use bincode::serialize;
use byteorder::{LittleEndian, WriteBytesExt};
use s... | SceneMsg::SetDisplayList { .. } |
SceneMsg::SetRootPipeline { .. } => return true,
_ => {}
}
}
for msg in &msgs.frame_ops {
match *msg {
FrameMsg::GetScrollNodeState(..) |
... | }
for msg in &msgs.scene_ops {
match *msg { | random_line_split |
gamepad.rs | //! Gamepad utility functions.
//!
//! This is going to be a bit of a work-in-progress as gamepad input
//! gets fleshed out. The `gilrs` crate needs help to add better
//! cross-platform support. Why not give it a hand?
//!
//! TODO: All of this.
use std::fmt;
use gilrs::{Event, Gamepad, Gilrs};
use crate::contex... | assert!(GilrsGamepadContext::new().is_ok());
}
} | mod tests {
use super::*;
#[test]
fn gilrs_init() { | random_line_split |
gamepad.rs | //! Gamepad utility functions.
//!
//! This is going to be a bit of a work-in-progress as gamepad input
//! gets fleshed out. The `gilrs` crate needs help to add better
//! cross-platform support. Why not give it a hand?
//!
//! TODO: All of this.
use std::fmt;
use gilrs::{Event, Gamepad, Gilrs};
use crate::contex... | () -> GameResult<Self> {
let gilrs = Gilrs::new()?;
Ok(GilrsGamepadContext { gilrs })
}
}
impl GamepadContext for GilrsGamepadContext {
fn next_event(&mut self) -> Option<Event> {
self.gilrs.next_event()
}
fn gamepad(&self, id: usize) -> Option<&Gamepad> {
self.gilrs.ge... | new | identifier_name |
a-dashboard_controller.js | 'use strict';
/* global angular */
(function() {
var aDashboard = angular.module('aDashboard');
aDashboard.controller('ADashboardController', function( $scope, $rootScope, tradelistFactory, $timeout) {
$scope.subState = $scope.$parent;
$scope.accountValue;
$scope.avgWin;
$scope.avgLoss;
$scope.avgTradeS... |
});
return {avg: (sum / count).toFixed(2), count: count};
};
function calculateAvgLoss( tradelist ){
var sum = 0;
var count = 0;
tradelist.forEach(function(entry) {
if( entry.tradeValue < 0 ){
++count
sum += Number(entry.tradeValue);
}
});
console.log('sum: ', sum);
... | {
++count;
sum += Number(entry.tradeValue);
} | conditional_block |
a-dashboard_controller.js | 'use strict';
/* global angular */
(function() {
var aDashboard = angular.module('aDashboard');
aDashboard.controller('ADashboardController', function( $scope, $rootScope, tradelistFactory, $timeout) {
$scope.subState = $scope.$parent;
$scope.accountValue;
$scope.avgWin;
$scope.avgLoss;
$scope.avgTradeS... | ;
function calculateAvgTradeSize( tradelist ){
var actionCount = 0;
var sum = 0;
tradelist.forEach(function(entry) {
var actions = entry.actions;
actions.forEach(function(action) {
if( action.price && action.quantity ){
++actionCount;
sum = sum + (Math.abs(action.price * action.quan... | {
var sum = 0;
var count = 0;
tradelist.forEach(function(entry) {
if( entry.tradeValue < 0 ){
++count
sum += Number(entry.tradeValue);
}
});
console.log('sum: ', sum);
return {avg: (sum / count).toFixed(2), count: count};
} | identifier_body |
a-dashboard_controller.js | 'use strict';
/* global angular */
(function() {
var aDashboard = angular.module('aDashboard');
aDashboard.controller('ADashboardController', function( $scope, $rootScope, tradelistFactory, $timeout) {
$scope.subState = $scope.$parent;
$scope.accountValue;
$scope.avgWin;
$scope.avgLoss;
$scope.avgTradeS... | ( tradelist ){
var actionCount = 0;
var sum = 0;
tradelist.forEach(function(entry) {
var actions = entry.actions;
actions.forEach(function(action) {
if( action.price && action.quantity ){
++actionCount;
sum = sum + (Math.abs(action.price * action.quantity));
}
});
});
if... | calculateAvgTradeSize | identifier_name |
a-dashboard_controller.js | 'use strict';
/* global angular */
| var aDashboard = angular.module('aDashboard');
aDashboard.controller('ADashboardController', function( $scope, $rootScope, tradelistFactory, $timeout) {
$scope.subState = $scope.$parent;
$scope.accountValue;
$scope.avgWin;
$scope.avgLoss;
$scope.avgTradeSize;
$scope.$on('tradeActionUpdated', function(e... | (function() { | random_line_split |
wrap-layout.d.ts | declare module "ui/layouts/wrap-layout" {
import layout = require("ui/layouts/layout-base");
import dependencyObservable = require("ui/core/dependency-observable");
/**
* WrapLayout position children in rows or columns depending on orientation property
* until space is filled and then wraps them ... | } | random_line_split | |
wrap-layout.d.ts | declare module "ui/layouts/wrap-layout" {
import layout = require("ui/layouts/layout-base");
import dependencyObservable = require("ui/core/dependency-observable");
/**
* WrapLayout position children in rows or columns depending on orientation property
* until space is filled and then wraps them ... | extends layout.LayoutBase {
/**
* Represents the observable property backing the orientation property of each WrapLayout instance.
*/
public static orientationProperty: dependencyObservable.Property;
/**
* Represents the observable property backing the itemWidth pro... | WrapLayout | identifier_name |
base_test.py | # Copyright (c) 2017 OpenStack Foundation
#
# 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 ... | (testtools.TestCase):
def setUp(self):
super(DataSourceBaseTestCase, self).setUp()
self.ds_base = DataSourceType()
def test_construct_url_no_placeholders(self):
base_url = "swift://container/input"
job_exec_id = uuidutils.generate_uuid()
url = self.ds_base.construct_url... | DataSourceBaseTestCase | identifier_name |
base_test.py | # Copyright (c) 2017 OpenStack Foundation
#
# 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 ... |
def test_construct_url_randstr_placeholder(self):
base_url = "swift://container/input.%RANDSTR(4)%.%RANDSTR(7)%.out"
job_exec_id = uuidutils.generate_uuid()
url = self.ds_base.construct_url(base_url, job_exec_id)
self.assertRegex(
url, "swift://container/input\.[a-z]{... | base_url = "swift://container/input.%JOB_EXEC_ID%.out"
job_exec_id = uuidutils.generate_uuid()
url = self.ds_base.construct_url(base_url, job_exec_id)
self.assertEqual(
"swift://container/input." + job_exec_id + ".out", url) | identifier_body |
base_test.py | # Copyright (c) 2017 OpenStack Foundation
#
# 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 ... |
def test_construct_url_job_exec_id_placeholder(self):
base_url = "swift://container/input.%JOB_EXEC_ID%.out"
job_exec_id = uuidutils.generate_uuid()
url = self.ds_base.construct_url(base_url, job_exec_id)
self.assertEqual(
"swift://container/input." + job_exec_id + ".o... | url = self.ds_base.construct_url(base_url, job_exec_id)
self.assertEqual(base_url, url) | random_line_split |
app.component.spec.ts | /**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at | * 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.
* =============================================================================
*/
import { TestBed } from '@angular/core/testing';
impo... | *
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
job_queue_manager.py | # Copyright (C) 2014 Statoil ASA, Norway.
#
# The file 'job_queue_manager.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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 vers... |
#################################################################
cwrapper = CWrapper(JOB_QUEUE_LIB)
cwrapper.registerObjectType("job_queue_manager", JobQueueManager)
JobQueueManager.cNamespace().alloc = cwrapper.prototype("c_void_p job_queue_manager_alloc( job_queue) ")
JobQueueM... | return JobQueueManager.cNamespace().job_complete( self , job_index ) | identifier_body |
job_queue_manager.py | # Copyright (C) 2014 Statoil ASA, Norway.
#
# The file 'job_queue_manager.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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 vers... | (self):
return JobQueueManager.cNamespace().is_running( self )
def free(self):
JobQueueManager.cNamespace().free(self)
def jobComplete(self , job_index):
return JobQueueManager.cNamespace().job_complete( self , job_index )
#######################################... | isRunning | identifier_name |
job_queue_manager.py | # Copyright (C) 2014 Statoil ASA, Norway.
#
# The file 'job_queue_manager.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT 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 vers... | def jobComplete(self , job_index):
return JobQueueManager.cNamespace().job_complete( self , job_index )
#################################################################
cwrapper = CWrapper(JOB_QUEUE_LIB)
cwrapper.registerObjectType("job_queue_manager", JobQueueManager)
JobQueueMan... | random_line_split | |
c_types.rs | #![allow(dead_code, non_camel_case_types)]
extern crate libc;
use self::libc::{
c_char,
c_int,
uid_t,
time_t
};
use self::libc::funcs::posix88::unistd::getgroups;
use std::vec::Vec;
use std::ptr::read;
use std::str::raw::from_c_str;
pub struct c_passwd {
pub pw_name: *c_char, /* user name... | pub struct utsname {
pub sysname: [c_char, ..256],
pub nodename: [c_char, ..256],
pub release: [c_char, ..256],
pub version: [c_char, ..256],
pub machine: [c_char, ..256]
}
#[cfg(target_os = "linux")]
pub struct utsname {
pub sysname: [c_char, ..65],
pub nodename: [c_char, ..65],
pub re... | random_line_split | |
c_types.rs | #![allow(dead_code, non_camel_case_types)]
extern crate libc;
use self::libc::{
c_char,
c_int,
uid_t,
time_t
};
use self::libc::funcs::posix88::unistd::getgroups;
use std::vec::Vec;
use std::ptr::read;
use std::str::raw::from_c_str;
pub struct c_passwd {
pub pw_name: *c_char, /* user name... | else {
ngroups = unsafe {
getgroups(NGROUPS, groups.as_mut_ptr() as *mut u32)
};
}
unsafe { groups.set_len(ngroups as uint) };
for &g in groups.iter() {
if nflag {
let group = unsafe { getgrgid(g as u32) };
if group.is_not_null() {
... | {
ngroups = NGROUPS;
unsafe {
getgrouplist(
possible_pw.unwrap().pw_name,
possible_pw.unwrap().pw_gid,
groups.as_ptr(),
&mut ngroups);
}
} | conditional_block |
c_types.rs | #![allow(dead_code, non_camel_case_types)]
extern crate libc;
use self::libc::{
c_char,
c_int,
uid_t,
time_t
};
use self::libc::funcs::posix88::unistd::getgroups;
use std::vec::Vec;
use std::ptr::read;
use std::str::raw::from_c_str;
pub struct c_passwd {
pub pw_name: *c_char, /* user name... | {
pub sysname: [c_char, ..256],
pub nodename: [c_char, ..256],
pub release: [c_char, ..256],
pub version: [c_char, ..256],
pub machine: [c_char, ..256]
}
#[cfg(target_os = "linux")]
pub struct utsname {
pub sysname: [c_char, ..65],
pub nodename: [c_char, ..65],
pub release: [c_char, ..... | utsname | identifier_name |
mqtt_sink.py | #
# Copyright (c) dushin.net All Rights Reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the foll... | #
# THIS SOFTWARE IS PROVIDED BY dushin.net ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL dushin.net BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLA... | random_line_split | |
mqtt_sink.py | #
# Copyright (c) dushin.net All Rights Reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the foll... |
def try_connect() :
if not self.connected :
try :
self.client.connect()
self.connected = True
except Exception as e :
print("Error connecting to MQTT Server: {}".format(e))
self.connected = False
| msg = ujson.dumps(message)
for i in range(1 + self.retries) :
try :
self.try_connect()
self.client.publish(self.topic, msgretain=self.retain, qos=self.qos)
return
except Exception as e :
print("Error publishing to MQTT Serve... | identifier_body |
mqtt_sink.py | #
# Copyright (c) dushin.net All Rights Reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the foll... |
def try_connect() :
if not self.connected :
try :
self.client.connect()
self.connected = True
except Exception as e :
print("Error connecting to MQTT Server: {}".format(e))
self.connected = False
| try :
self.try_connect()
self.client.publish(self.topic, msgretain=self.retain, qos=self.qos)
return
except Exception as e :
print("Error publishing to MQTT Server: {}".format(e))
self.connected = False | conditional_block |
mqtt_sink.py | #
# Copyright (c) dushin.net All Rights Reserved
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the foll... | (self, message) :
msg = ujson.dumps(message)
for i in range(1 + self.retries) :
try :
self.try_connect()
self.client.publish(self.topic, msgretain=self.retain, qos=self.qos)
return
except Exception as e :
print("Erro... | log | identifier_name |
transform.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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 a... |
// EXPORTS //
module.exports = transform; | }
}
return out;
} | random_line_split |
transform.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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 a... | ( files ) {
var match;
var name;
var out;
var i;
out = [];
for ( i = 0; i < files.length; i++ ) {
match = lastIndexOf( files[ i ], '@stdlib' );
if ( match >= 0 ) {
name = files[ i ].substring( match );
name = dirname( name );
out.push( convertPath( name, 'posix' ) );
}
}
return out;
}
// EXPOR... | transform | identifier_name |
transform.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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 a... |
}
return out;
}
// EXPORTS //
module.exports = transform;
| {
name = files[ i ].substring( match );
name = dirname( name );
out.push( convertPath( name, 'posix' ) );
} | conditional_block |
transform.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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 a... |
// EXPORTS //
module.exports = transform;
| {
var match;
var name;
var out;
var i;
out = [];
for ( i = 0; i < files.length; i++ ) {
match = lastIndexOf( files[ i ], '@stdlib' );
if ( match >= 0 ) {
name = files[ i ].substring( match );
name = dirname( name );
out.push( convertPath( name, 'posix' ) );
}
}
return out;
} | identifier_body |
ffi.rs | use std::fmt;
// this extern block links to the libm library
#[link(name = "m")]
extern {
// this is a foreign function
// that computes the square root of a single precision complex number
fn csqrtf(z: Complex) -> Complex;
}
fn main() {
// z = -1 + 0i
let z = Complex { re: -1., im: 0. };
// ... | {
re: f32,
im: f32,
}
impl fmt::Show for Complex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.im < 0. {
write!(f, "{}-{}i", self.re, -self.im)
} else {
write!(f, "{}+{}i", self.re, self.im)
}
}
}
| Complex | identifier_name |
ffi.rs | use std::fmt;
// this extern block links to the libm library
#[link(name = "m")]
extern {
// this is a foreign function
// that computes the square root of a single precision complex number
fn csqrtf(z: Complex) -> Complex;
}
fn main() {
// z = -1 + 0i
let z = Complex { re: -1., im: 0. };
// ... | write!(f, "{}-{}i", self.re, -self.im)
} else {
write!(f, "{}+{}i", self.re, self.im)
}
}
} | if self.im < 0. { | random_line_split |
ffi.rs | use std::fmt;
// this extern block links to the libm library
#[link(name = "m")]
extern {
// this is a foreign function
// that computes the square root of a single precision complex number
fn csqrtf(z: Complex) -> Complex;
}
fn main() {
// z = -1 + 0i
let z = Complex { re: -1., im: 0. };
// ... |
}
}
| {
write!(f, "{}+{}i", self.re, self.im)
} | conditional_block |
ffi.rs | use std::fmt;
// this extern block links to the libm library
#[link(name = "m")]
extern {
// this is a foreign function
// that computes the square root of a single precision complex number
fn csqrtf(z: Complex) -> Complex;
}
fn main() |
// Minimal implementation of single precision complex numbers
#[repr(C)]
struct Complex {
re: f32,
im: f32,
}
impl fmt::Show for Complex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.im < 0. {
write!(f, "{}-{}i", self.re, -self.im)
} else {
write... | {
// z = -1 + 0i
let z = Complex { re: -1., im: 0. };
// calling a foreign function is an unsafe operation
let z_sqrt = unsafe {
csqrtf(z)
};
println!("the square root of {} is {}", z, z_sqrt);
} | identifier_body |
setup.py | from setuptools import find_packages, setup
import os
name = 'presence_analyzer'
version = '0.2.2'
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(
name=name,
version=version,
description='Presence analyzer',
long_description=read('README.md'),
... | entry_points="""
[console_scripts]
flask-ctl = presence_analyzer.script:run
get_xml = presence_analyzer.script:get_xml
[paste.app_factory]
main = presence_analyzer.script:make_app
debug = presence_analyzer.script:make_debug
""",
) | random_line_split | |
setup.py | from setuptools import find_packages, setup
import os
name = 'presence_analyzer'
version = '0.2.2'
def | (*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(
name=name,
version=version,
description='Presence analyzer',
long_description=read('README.md'),
classifiers=[],
keywords='',
author='',
author_email='',
url='',
license='MIT',
packag... | read | identifier_name |
setup.py | from setuptools import find_packages, setup
import os
name = 'presence_analyzer'
version = '0.2.2'
def read(*rnames):
|
setup(
name=name,
version=version,
description='Presence analyzer',
long_description=read('README.md'),
classifiers=[],
keywords='',
author='',
author_email='',
url='',
license='MIT',
package_dir={'': 'src'},
packages=find_packages('src'),
include_package_data=True... | return open(os.path.join(os.path.dirname(__file__), *rnames)).read() | identifier_body |
index.js | var through = require('through2');
var cheerio = require('cheerio');
var gulp = require('gulp');
var url = require('url');
var path = require('path');
var fs = require('fs');
var typeMap = {
css: {
tag: 'link',
template: function(contents, el) {
var attribute = el.attr('media');
attribute = attri... | return el.attr('href');
}
},
js: {
tag: 'script',
template: function(contents) {
return '<script type="text/javascript">\n' + String(contents) + '\n</script>';
},
filter: function(el) {
return isLocal(el.attr('src'));
},
getSrc: function(el) {
return el.attr('src... | getSrc: function(el) { | random_line_split |
index.js | var through = require('through2');
var cheerio = require('cheerio');
var gulp = require('gulp');
var url = require('url');
var path = require('path');
var fs = require('fs');
var typeMap = {
css: {
tag: 'link',
template: function(contents, el) {
var attribute = el.attr('media');
attribute = attri... |
function inject($, process, base, cb, opts, relative, ignoredFiles) {
var items = [];
$(opts.tag).each(function(idx, el) {
el = $(el);
if(opts.filter(el)) {
items.push(el);
}
});
if(items.length) {
var done = after(items.length, cb);
items.forEach(function(el) {
var src = opt... | {
return through.obj(function(file, enc, cb) {
el.replaceWith(tmpl(file.contents, el));
this.push(file);
cb();
});
} | identifier_body |
index.js | var through = require('through2');
var cheerio = require('cheerio');
var gulp = require('gulp');
var url = require('url');
var path = require('path');
var fs = require('fs');
var typeMap = {
css: {
tag: 'link',
template: function(contents, el) {
var attribute = el.attr('media');
attribute = attri... | else {
done();
}
});
});
};
| {
inject($, opts[type], opts.base, done, typeMap[type], path.dirname(file.path), opts.ignore);
} | conditional_block |
index.js | var through = require('through2');
var cheerio = require('cheerio');
var gulp = require('gulp');
var url = require('url');
var path = require('path');
var fs = require('fs');
var typeMap = {
css: {
tag: 'link',
template: function(contents, el) {
var attribute = el.attr('media');
attribute = attri... | ($, process, base, cb, opts, relative, ignoredFiles) {
var items = [];
$(opts.tag).each(function(idx, el) {
el = $(el);
if(opts.filter(el)) {
items.push(el);
}
});
if(items.length) {
var done = after(items.length, cb);
items.forEach(function(el) {
var src = opts.getSrc(el) || '... | inject | identifier_name |
unicodeSymbols.js | // @flow
// This is an internal module, not part of the KaTeX distribution,
// whose purpose is to generate `unicodeSymbols` in Parser.js
// In this way, only this module, and not the distribution/browser,
// needs String's normalize function. As this file is not transpiled,
// Flow comment types syntax is used.
const ... | lt;
| ombined2;
}
}
}
}
module.exports = resu | conditional_block |
unicodeSymbols.js | // @flow
// This is an internal module, not part of the KaTeX distribution,
// whose purpose is to generate `unicodeSymbols` in Parser.js
// In this way, only this module, and not the distribution/browser,
// needs String's normalize function. As this file is not transpiled,
// Flow comment types syntax is used.
const ... | }
const combined2 = combined + accent2;
const normalized2 = combined2.normalize('NFC');
if (normalized2.length === 1) {
result[normalized2] = combined2;
}
}
}
}
module.exports = result; | if (accent === accent2) {
continue; | random_line_split |
db.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you ca... |
elif isinstance(val, unicode):
val = val.replace("'", "''")
else: # other type, we can str
val = unicode(str(val))
val = val.replace("'", "''")
return val
def create_insert_query(self, table, data):
"""Create a INSERT query in table with all dat... | val = val.decode('utf8', 'ignore').replace("'", "''") | conditional_block |
db.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you ca... | i = 0 # f or the ',' problem... look like C here...
for prop in data:
i += 1
val = data[prop]
# Boolean must be catch, because we want 0 or 1, not True or False
if isinstance(val, bool):
if val:
val = 1
... | props_str = u' ('
values_str = u' (' | random_line_split |
db.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you ca... | """Get all entry"""
return self.db_cursor.fetchall() | identifier_body | |
db.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you ca... | (self):
"""Just get an entry"""
return self.db_cursor.fetchone()
def fetchall(self):
"""Get all entry"""
return self.db_cursor.fetchall()
| fetchone | identifier_name |
core.js | = 'OPEN';
var toggler = doc.getElementById('tab-' + tabKey + '-imageToggle');
var toggleDiv = toggler.lastElementChild;
if (toggleDiv == null) {
toggler.value = 'Hide';
toggler.title = 'close';
toggler.alt = 'close';
} else {
var span = toggleDiv.firstElementChild;
... | {
if ((Math.abs(frameDocHeight - currentHeight)) > 59) {
routeLogFrame.style.height = (frameDocHeight + 30) + "px";
currentHeight = frameDocHeight;
}
} | conditional_block | |
core.js | 0, 0);
parent.window.scrollTo(0, 0);
}
function saveScrollPosition() {
if (document.forms[0].formKey) {
// KULRICE-8292: Timeout issues across servers (3535)
scrollPositionKey = document.forms[0].formKey.value % 20;
if (document.documentElement) {
x = Math.max(parent.docume... | {
var style_sheet = getStyleObject(showId);
if (style_sheet) {
changeObjectVisibility(showId, "block");
changeObjectVisibility(hideId, "none");
}
else {
alert("sorry, this only works in browsers that do Dynamic HTML");
}
} | identifier_body | |
core.js | ].id.substring(elements[x].id.length - 4, elements[x].id.length) === '-div') {
func(document, formId, elements[x].id.substring(4, elements[x].id.length - 4));
}
}
return false;
}
function showTab(doc, formId, tabKey) {
if (!doc.getElementById('tab-' + tabKey + '-div') || !doc.getElement... | return true;
}
//The following javascript is intended to resize the route log iframe
// to stay at an appropriate height based on the size of the documents
// contents contained in the iframe.
// NOTE: this will only work when the domain serving the content of kuali
// is the same as the domain serving th... | if (initiator == undefined || ( initiator.indexOf(buttonPrefix) != 0 && initiator.length > 0)) {
// disallow enter key from fields that dont match prefix.
return false;
}
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.