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 |
|---|---|---|---|---|
fig08_10.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
def main():
"""Main"""
# Objects of class Rational
rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Ration... | main() | conditional_block | |
fig08_10.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
| rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Rational(-7, 14) # -7/14 reduces to -1/2
# Printing objects of class Rational
print "Rational 1:", rational1
print "Rational 2:", rational2
print "Rational 3:", rational3
print
# Testing... | def main():
"""Main"""
# Objects of class Rational | random_line_split |
fig08_10.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
def main():
| rational1 += rational2 * rational3
print "\nrational1 after adding rational2 * rational3:", rational1
print
# Test comparison operators
print rational1, "<=", rational2, ":", rational1 <= rational2
print rational1, ">", rational3, ":", rational1 > rational3
print
# Test built-in functi... | """Main"""
# Objects of class Rational
rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Rational(-7, 14) # -7/14 reduces to -1/2
# Printing objects of class Rational
print "Rational 1:", rational1
print "Rational 2:", rational2
print "Rati... | identifier_body |
fig08_10.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
def | ():
"""Main"""
# Objects of class Rational
rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Rational(-7, 14) # -7/14 reduces to -1/2
# Printing objects of class Rational
print "Rational 1:", rational1
print "Rational 2:", rational2
pri... | main | identifier_name |
user.py | # coding: utf-8
from libs.redis_storage import db1
class User(object):
def __init__(self, **kwargs):
pk = kwargs.get('pk') or db1.incr('new_user_id')
kwargs['pk'] = pk
db1.hmset('user::{}'.format(pk), kwargs)
super(User, self).__setattr__('pk', pk)
super(User, self).__seta... |
def get_user_by_service(service, service_user_id):
user_pk = db1.get('{}_user_id::{}'.format(service, service_user_id))
if user_pk:
return User(pk=user_pk)
def add_service_to_user(service, service_user_id, user_pk):
db1.set('{}_user_id::{}'.format(service, service_user_id), user_pk)
user = ... | db1.hincrby(self.db_key, attr, by) | identifier_body |
user.py | # coding: utf-8
from libs.redis_storage import db1
class User(object):
def __init__(self, **kwargs):
pk = kwargs.get('pk') or db1.incr('new_user_id')
kwargs['pk'] = pk
db1.hmset('user::{}'.format(pk), kwargs)
super(User, self).__setattr__('pk', pk)
super(User, self).__seta... | return int(self.__info__.get('defeats', 0))
@property
def last_update(self):
return int(self.__info__.get('last_update', 0))
def __setattr__(self, attr, value):
self.__info__[attr] = value
db1.hset(self.db_key, attr, value)
def __getattr__(self, attr):
return s... | return int(self.__info__.get('wins', 0))
@property
def defeats(self): | random_line_split |
user.py | # coding: utf-8
from libs.redis_storage import db1
class User(object):
def __init__(self, **kwargs):
pk = kwargs.get('pk') or db1.incr('new_user_id')
kwargs['pk'] = pk
db1.hmset('user::{}'.format(pk), kwargs)
super(User, self).__setattr__('pk', pk)
super(User, self).__seta... | (service, service_user_id):
user_pk = db1.get('{}_user_id::{}'.format(service, service_user_id))
if user_pk:
return User(pk=user_pk)
def add_service_to_user(service, service_user_id, user_pk):
db1.set('{}_user_id::{}'.format(service, service_user_id), user_pk)
user = User(pk=user_pk)
setat... | get_user_by_service | identifier_name |
user.py | # coding: utf-8
from libs.redis_storage import db1
class User(object):
def __init__(self, **kwargs):
pk = kwargs.get('pk') or db1.incr('new_user_id')
kwargs['pk'] = pk
db1.hmset('user::{}'.format(pk), kwargs)
super(User, self).__setattr__('pk', pk)
super(User, self).__seta... |
@property
def short_info(self):
return {field: getattr(self, field) for field in [
'fio',
'sex',
'avatar',
'battles',
'wins',
'defeats',
'last_update'
]}
@property
def db_key(self):
return 'use... | self.__info__[k] = v.decode('utf-8') | conditional_block |
window.rs | /// Mutable reference to the scene associated with this window.
#[inline]
pub fn scene_mut<'a>(&'a mut self) -> &'a mut SceneNode {
&mut self.scene
}
// FIXME: give more options for the snap size and offset.
/// Read the pixels currently displayed to the screen.
///
/// # Argume... | verify!(gl::FrontFace(gl::CCW));
verify!(gl::Enable(gl::DEPTH_TEST)); | random_line_split | |
window.rs | .background.x = r;
self.background.y = g;
self.background.z = b;
}
// XXX: remove this (moved to the render_frame).
/// Adds a line to be drawn during the next frame.
#[inline]
pub fn draw_line(&mut self, a: &Pnt3<f32>, b: &Pnt3<f32>, color: &Pnt3<f32>) {
self.line_renderer.... |
/// Creates and adds a new object using the geometry registered as `geometry_name`.
pub fn add_geom_with_name(&mut self, geometry_name: &str, scale: Vec3<f32>) -> Option<SceneNode> {
self.scene.add_geom_with_name(geometry_name, scale)
}
/// Adds a cube to the scene. The cube is initially axis... | {
self.scene.add_trimesh(descr, scale)
} | identifier_body |
window.rs | self.background.x = r;
self.background.y = g;
self.background.z = b;
}
// XXX: remove this (moved to the render_frame).
/// Adds a line to be drawn during the next frame.
#[inline]
pub fn draw_line(&mut self, a: &Pnt3<f32>, b: &Pnt3<f32>, color: &Pnt3<f32>) {
self.line_rend... | (&mut self, r: GLfloat) -> SceneNode {
self.scene.add_sphere(r)
}
/// Adds a cone to the scene. The cone is initially centered at (0, 0, 0) and points toward the
/// positive `y` axis.
///
/// # Arguments
/// * `h` - the cone height
/// * `r` - the cone base radius
pub fn add_co... | add_sphere | identifier_name |
sb-1.3.0.js | .msg = {};
/**
* Name of app
* @type {String}
*/
this._name = name || "javascript client #";
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
/**
* Description of your app
* @type {String}
*/
this._description = descriptio... | {
self.connect();
console.log("[reconnect:Spacebrew] attempting to reconnect to spacebrew");
} | conditional_block | |
sb-1.3.0.js | type {String}
*/
this._name = name || "javascript client #";
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
/**
* Description of your app
* @type {String}
*/
this._description = description || "spacebrew javascript client";
i... | this.onClose(); | random_line_split | |
relative_paths.py | # All of the other examples directly embed the Javascript and CSS code for
# Bokeh's client-side runtime into the HTML. This leads to the HTML files
# being rather large. An alternative is to ask Bokeh to produce HTML that
# has a relative link to the Bokeh Javascript and CSS. This is easy to
# do; you just pass in ... | N = 100
x = np.linspace(0, 4*np.pi, N)
y = np.sin(x)
output_file("relative_paths.html", title="Relative path example", mode="relative")
scatter(x,y, color="#FF00FF", tools="pan,wheel_zoom,box_zoom,reset,previewsave")
show()
# By default, the URLs for the Javascript and CSS will be relative to
# the current director... | from bokeh.plotting import *
| random_line_split |
b-dummy.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:dummies/b-dummy/README.md]]
* @packageDocumentation
*/
import 'models/demo/pagination';
import { derive } from 'core/functools/trait';
imp... | }
get modules(): Modules {
return {
resizeWatcher: ResizeWatcher,
iObserveDOM,
htmlHelpers,
session,
browserHelpers,
cookie
};
}
get componentInstances(): Dictionary {
return {
bDummy,
bBottomSlide
};
}
override get baseMods(): CanUndef<Readonly<ModsNTable>> {
return {foo: 'ba... | random_line_split | |
b-dummy.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:dummies/b-dummy/README.md]]
* @packageDocumentation
*/
import 'models/demo/pagination';
import { derive } from 'core/functools/trait';
imp... |
get engines(): Engines {
return {
router: {
historyApiRouterEngine,
inMemoryRouterEngine
}
};
}
get modules(): Modules {
return {
resizeWatcher: ResizeWatcher,
iObserveDOM,
htmlHelpers,
session,
browserHelpers,
cookie
};
}
get componentInstances(): Dictionary {
return ... | {
return {
imageFactory: imageLoaderFactory,
image: ImageLoader,
inViewMutation,
inViewObserver,
updateOn
};
} | identifier_body |
b-dummy.ts | /*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
/**
* [[include:dummies/b-dummy/README.md]]
* @packageDocumentation
*/
import 'models/demo/pagination';
import { derive } from 'core/functools/trait';
imp... | (): CanUndef<Readonly<ModsNTable>> {
return {foo: 'bar'};
}
static override readonly daemons: typeof daemons = daemons;
setStage(value: string): void {
this.stage = value;
}
/** @see [[iObserveDOM.initDOMObservers]] */
@hook('mounted')
@wait('ready')
initDOMObservers(): void {
iObserveDOM.observe(this,... | baseMods | identifier_name |
response.tools.ts | import { ContentfulCommon } from 'ng2-contentful';
import { ContentfulNodePagesResponse } from './aliases.structures';
// this will be the part of ng2-contentful tools
/**
* Transforms response to usable form by resolving all includes objects
* @param response
* @param depth
* @returns {T[]}
*/
export function tr... |
}
for (let item of response.items) {
includes[item.sys.id] = item;
}
/**
* Replace `sys` reference with full contentful's object for one item
* @param item
* @returns {ContentfulCommon<any>}
*/
function extendObjectWithFields(item: ContentfulCommon<any>): ContentfulCommon<any> {
if (ite... | {
for (let item of response.includes[key]) {
includes[item.sys.id] = item;
}
} | conditional_block |
response.tools.ts | import { ContentfulCommon } from 'ng2-contentful';
import { ContentfulNodePagesResponse } from './aliases.structures';
// this will be the part of ng2-contentful tools
/**
* Transforms response to usable form by resolving all includes objects
* @param response
* @param depth | */
export function transformResponse<T extends ContentfulCommon<any>>(response: ContentfulNodePagesResponse, depth: number = 1): T[] {
let currentDepth = 0;
// collect all includes
let includes: any = {};
for (let key in response.includes) {
if (response.includes.hasOwnProperty(key)) {
for (let item... | * @returns {T[]} | random_line_split |
response.tools.ts | import { ContentfulCommon } from 'ng2-contentful';
import { ContentfulNodePagesResponse } from './aliases.structures';
// this will be the part of ng2-contentful tools
/**
* Transforms response to usable form by resolving all includes objects
* @param response
* @param depth
* @returns {T[]}
*/
export function tr... | * @returns {ContentfulCommon<any>}
*/
function extendObjectWithFields(item: ContentfulCommon<any>): ContentfulCommon<any> {
if (item.hasOwnProperty('sys') && includes.hasOwnProperty(item.sys.id)) {
item.fields = includes[item.sys.id].fields;
item.sys = includes[item.sys.id].sys;
}
return... | {
let currentDepth = 0;
// collect all includes
let includes: any = {};
for (let key in response.includes) {
if (response.includes.hasOwnProperty(key)) {
for (let item of response.includes[key]) {
includes[item.sys.id] = item;
}
}
}
for (let item of response.items) {
includ... | identifier_body |
response.tools.ts | import { ContentfulCommon } from 'ng2-contentful';
import { ContentfulNodePagesResponse } from './aliases.structures';
// this will be the part of ng2-contentful tools
/**
* Transforms response to usable form by resolving all includes objects
* @param response
* @param depth
* @returns {T[]}
*/
export function tr... | (item: ContentfulCommon<any>): ContentfulCommon<any> {
if (item.hasOwnProperty('sys') && includes.hasOwnProperty(item.sys.id)) {
item.fields = includes[item.sys.id].fields;
item.sys = includes[item.sys.id].sys;
}
return item;
}
/**
* Replace `sys` references with full contentful's object... | extendObjectWithFields | identifier_name |
post.js | import React, { PureComponent } from "react";
import { graphql } from 'gatsby'
import Link from "gatsby-link";
import path from "ramda/src/path";
import ScrollReveal from "scrollreveal";
import Layout from "../components/Layout";
import "prismjs/themes/prism.css";
import styles from "./post.module.scss";
const getPos... | ost = getPost(this.props);
const { next, prev } = getContext(this.props); // Not to be confused with react context...
return (
<Layout>
<header className="article-header">
<h1>{post.frontmatter.title}</h1>
</header>
<div
className="article-content"
da... | onst p | identifier_name |
post.js | import path from "ramda/src/path";
import ScrollReveal from "scrollreveal";
import Layout from "../components/Layout";
import "prismjs/themes/prism.css";
import styles from "./post.module.scss";
const getPost = path(["data", "markdownRemark"]);
const getContext = path(["pageContext"]);
const PostNav = ({ prev, next ... | import React, { PureComponent } from "react";
import { graphql } from 'gatsby'
import Link from "gatsby-link"; | random_line_split | |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
us... | <T: Timestamp, D: Data> {
buffer: PushBuffer<T, D, PushCounter<T, D, Tee<T, D>>>,
}
impl<T: Timestamp, D: Data> UnorderedHandle<T, D> {
fn new(pusher: PushCounter<T, D, Tee<T, D>>) -> UnorderedHandle<T, D> {
UnorderedHandle {
buffer: PushBuffer::new(pusher),
}
}
/// Allocat... | UnorderedHandle | identifier_name |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
us... |
fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<T as Timestamp>::Summary>>>,
Vec<CountMap<T>>) {
let mut internal = CountMap::new();
// augment the counts for each reserved capability.
for &(ref time, count) in self.internal.borrow().ite... | { 1 } | identifier_body |
unordered_input.rs | //! Create new `Streams` connected to external inputs.
use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;
use progress::frontier::Antichain;
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use timely_communication::Allocate;
use Data;
us... | }
impl<T: Timestamp, D: Data> Drop for UnorderedHandle<T, D> {
fn drop(&mut self) {
// TODO: explode if not all capabilities were given up?
}
} | /// Allocates a new automatically flushing session based on the supplied capability.
pub fn session<'b>(&'b mut self, cap: Capability<T>) -> AutoflushSession<'b, T, D, PushCounter<T, D, Tee<T, D>>> {
self.buffer.autoflush_session(cap)
} | random_line_split |
availability_set.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | :type sku: :class:`Sku <azure.mgmt.compute.models.Sku>`
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
'statuses': {'readonly': True},
}
_attribute_map = {
'id': {... | :vartype statuses: list of :class:`InstanceViewStatus
<azure.mgmt.compute.models.InstanceViewStatus>`
:param managed: If the availability set supports managed disks.
:type managed: bool
:param sku: Sku of the availability set | random_line_split |
availability_set.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | (self, location, tags=None, platform_update_domain_count=None, platform_fault_domain_count=None, virtual_machines=None, managed=None, sku=None):
super(AvailabilitySet, self).__init__(location=location, tags=tags)
self.platform_update_domain_count = platform_update_domain_count
self.platform_faul... | __init__ | identifier_name |
availability_set.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | super(AvailabilitySet, self).__init__(location=location, tags=tags)
self.platform_update_domain_count = platform_update_domain_count
self.platform_fault_domain_count = platform_fault_domain_count
self.virtual_machines = virtual_machines
self.statuses = None
self.managed = managed... | identifier_body | |
homepage.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... |
class TimeoutPage(Page):
def on_loaded(self):
pass
| cells = line.xpath('td')
snumber = cells[2].attrib['id'].replace('Contrat_', '')
slabel = cells[0].xpath('a')[0].text.replace('offre', '').strip()
d = unicode(cells[3].xpath('strong')[0].text.strip())
sdate = date(*reversed([int(x) for x in d.split("/")]))... | conditional_block |
homepage.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... | (Page):
def login(self, login, password):
self.browser.select_form('symConnexionForm')
self.browser["portlet_login_plein_page_3{pageFlow.mForm.login}"] = unicode(login)
self.browser["portlet_login_plein_page_3{pageFlow.mForm.password}"] = unicode(password)
self.browser.submit()
cl... | LoginPage | identifier_name |
homepage.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... |
class HomePage(Page):
def on_loaded(self):
pass
class AccountPage(Page):
def get_subscription_list(self):
table = self.document.xpath('//table[@id="ensemble_contrat_N0"]')[0]
if len(table) > 0:
# some clients may have subscriptions to gas and electricity,
#... | def login(self, login, password):
self.browser.select_form('symConnexionForm')
self.browser["portlet_login_plein_page_3{pageFlow.mForm.login}"] = unicode(login)
self.browser["portlet_login_plein_page_3{pageFlow.mForm.password}"] = unicode(password)
self.browser.submit() | identifier_body |
homepage.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Mathieu Jourdan
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... |
class TimeoutPage(Page):
def on_loaded(self):
pass | random_line_split | |
forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from taggit.forms import TagField
from places_core.forms import BootstrapBaseForm
from .models import Category, News
class NewsForm(forms.ModelForm, BootstrapBaseForm):
""" Edit/update/create blog entry. ""... |
model = News
exclude = ('edited', 'slug', 'creator',)
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control custom-wysiwyg'}),
'category': forms.Select(attrs={'class': 'form-control'}),
'location': forms.HiddenInput(),
'image': forms... | eta: | identifier_name |
forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from taggit.forms import TagField
from places_core.forms import BootstrapBaseForm
from .models import Category, News
class NewsForm(forms.ModelForm, BootstrapBaseForm):
""" Edit/update/create blog entry. ""... | odel = News
exclude = ('edited', 'slug', 'creator',)
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control custom-wysiwyg'}),
'category': forms.Select(attrs={'class': 'form-control'}),
'location': forms.HiddenInput(),
'image': forms.Clearable... | identifier_body | |
forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from taggit.forms import TagField
from places_core.forms import BootstrapBaseForm
from .models import Category, News
class NewsForm(forms.ModelForm, BootstrapBaseForm):
""" Edit/update/create blog entry. ""... | 'category': forms.Select(attrs={'class': 'form-control'}),
'location': forms.HiddenInput(),
'image': forms.ClearableFileInput(attrs={'class': 'civ-img-input', }),
} | exclude = ('edited', 'slug', 'creator',)
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control custom-wysiwyg'}), | random_line_split |
main.js | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import { sync } from 'vuex-router-sync'
import App from './views/App'
import router from './router'
import store from './store'
import Buefy from 'buefy'
impo... | store.commit('SET_USER', localUser)
store.commit('SET_IS_AUTHENTICATED', window.localStorage.getItem('isAuthenticated'))
}
} | if (window.localStorage) {
var localUserString = window.localStorage.getItem('user') || 'null'
var localUser = JSON.parse(localUserString)
if (localUser && store.state.user !== localUser) { | random_line_split |
main.js | // The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import { sync } from 'vuex-router-sync'
import App from './views/App'
import router from './router'
import store from './store'
import Buefy from 'buefy'
impo... |
}
| {
store.commit('SET_USER', localUser)
store.commit('SET_IS_AUTHENTICATED', window.localStorage.getItem('isAuthenticated'))
} | conditional_block |
saveMember.ts | import { FormValidationResult } from 'lc-form-validation';
import * as toastr from 'toastr';
import { actionTypes } from '../../../common/constants/actionTypes';
import { MemberEntity } from '../../../model';
import { memberAPI } from '../../../api/member';
import { memberFormValidation } from '../memberFormValidation'... |
dispatch(saveMemberActionCompleted(formValidationResult));
})
);
};
const saveMember = (member: MemberEntity) => {
trackPromise(
memberAPI.saveMember(member)
.then(() => {
toastr.success('Member saved.');
history.back();
})
.catch(toastr.error)
);
};
const ... | {
saveMember(member);
} | conditional_block |
saveMember.ts | import { FormValidationResult } from 'lc-form-validation';
import * as toastr from 'toastr';
import { actionTypes } from '../../../common/constants/actionTypes';
import { MemberEntity } from '../../../model';
import { memberAPI } from '../../../api/member';
import { memberFormValidation } from '../memberFormValidation'... | );
};
const saveMemberActionCompleted = (formValidationResult: FormValidationResult) => ({
type: actionTypes.SAVE_MEMBER,
payload: formValidationResult,
}); | })
.catch(toastr.error) | random_line_split |
cols_dimensionality.py | 'output dimensionalities for each column'
import csv
import sys
import re
import math
from collections import defaultdict
def get_words( text ):
text = text.replace( "'", "" )
text = re.sub( r'\W+', ' ', text )
text = text.lower()
text = text.split()
words = []
for w in text:
if w in words:
continue
wo... |
# print counts
for i in sorted( unique_values ):
l = len( unique_values[i] )
print "index: %s, count: %s" % ( i, l )
if l < 100:
pass
# print unique_values[i]
| for i in indexes2binarize:
value = line[i]
unique_values[i].add( value )
for i in indexes2tokenize:
words = get_words( line[i] )
unique_values[i].update( words )
n += 1
if n % 10000 == 0:
print n | conditional_block |
cols_dimensionality.py | 'output dimensionalities for each column'
import csv
import sys
import re
import math
from collections import defaultdict
def get_words( text ):
|
###
csv.field_size_limit( 1000000 )
input_file = sys.argv[1]
target_col = 'SalaryNormalized'
cols2tokenize = [ 'Title', 'FullDescription' ]
cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ]
cols2drop = [ 'SalaryRaw' ]
###
i_f = open( input_fi... | text = text.replace( "'", "" )
text = re.sub( r'\W+', ' ', text )
text = text.lower()
text = text.split()
words = []
for w in text:
if w in words:
continue
words.append( w )
return words | identifier_body |
cols_dimensionality.py | 'output dimensionalities for each column'
import csv
import sys
import re
import math
from collections import defaultdict
def get_words( text ):
text = text.replace( "'", "" )
text = re.sub( r'\W+', ' ', text )
text = text.lower()
text = text.split()
words = []
for w in text:
if w in words:
continue
wo... |
i_f = open( input_file )
reader = csv.reader( i_f )
headers = reader.next()
target_index = headers.index( target_col )
indexes2tokenize = map( lambda x: headers.index( x ), cols2tokenize )
indexes2binarize = map( lambda x: headers.index( x ), cols2binarize )
indexes2drop = map( lambda x: headers.index( x ), cols2dro... | cols2binarize = [ 'Loc1', 'Loc2', 'Loc3', 'Loc4', 'ContractType', 'ContractTime', 'Company', 'Category', 'SourceName' ]
cols2drop = [ 'SalaryRaw' ]
### | random_line_split |
cols_dimensionality.py | 'output dimensionalities for each column'
import csv
import sys
import re
import math
from collections import defaultdict
def | ( text ):
text = text.replace( "'", "" )
text = re.sub( r'\W+', ' ', text )
text = text.lower()
text = text.split()
words = []
for w in text:
if w in words:
continue
words.append( w )
return words
###
csv.field_size_limit( 1000000 )
input_file = sys.argv[1]
target_col = 'SalaryNormalized'
cols2token... | get_words | identifier_name |
search_indexes.py | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from haystack import indexes
from reviewboard.reviews.models import ReviewRequest
from reviewboard.search.indexes import BaseSearchIndex
class ReviewRequestIndex(BaseSearchIndex, indexes.Index... | (self, review_request):
"""Prepare the list of target users for the index.
If there aren't any target users, ``[0]`` will be returned. This
allows queries to be performed that check that there aren't any
users in the list, since we can't query against empty lists.
"""
re... | prepare_target_users | identifier_name |
search_indexes.py | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from haystack import indexes
from reviewboard.reviews.models import ReviewRequest
from reviewboard.search.indexes import BaseSearchIndex
class ReviewRequestIndex(BaseSearchIndex, indexes.Index... |
else:
return 0
def prepare_private_target_groups(self, review_request):
"""Prepare the list of invite-only target groups for the index.
If there aren't any invite-only groups associated, ``[0]`` will be
returned. This allows queries to be performed that check that none... | return review_request.repository_id | conditional_block |
search_indexes.py | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from haystack import indexes
from reviewboard.reviews.models import ReviewRequest
from reviewboard.search.indexes import BaseSearchIndex
class ReviewRequestIndex(BaseSearchIndex, indexes.Index... | 'target_people')
)
def prepare_file(self, obj):
return set([
(filediff.source_file, filediff.dest_file)
for diffset in obj.diffset_history.diffsets.all()
for filediff in diffset.files.all()
])
def prepare_private(self, r... | .prefetch_related('diffset_history__diffsets__files',
'target_groups', | random_line_split |
search_indexes.py | from __future__ import unicode_literals
from django.contrib.auth.models import AnonymousUser
from django.db.models import Q
from haystack import indexes
from reviewboard.reviews.models import ReviewRequest
from reviewboard.search.indexes import BaseSearchIndex
class ReviewRequestIndex(BaseSearchIndex, indexes.Index... | private = indexes.BooleanField()
private_repository_id = indexes.IntegerField()
private_target_groups = indexes.MultiValueField()
target_users = indexes.MultiValueField()
def get_model(self):
"""Returns the Django model for this index."""
return ReviewRequest
def get_updated_fi... | """A Haystack search index for Review Requests."""
model = ReviewRequest
local_site_attr = 'local_site_id'
# We shouldn't use 'id' as a field name because it's by default reserved
# for Haystack. Hiding it will cause duplicates when updating the index.
review_request_id = indexes.IntegerField(model... | identifier_body |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainE... |
pub fn dependencies(&self) -> &[Dependency] { self.manifest.dependencies() }
pub fn manifest(&self) -> &Manifest { &self.manifest }
pub fn manifest_path(&self) -> &Path { &self.manifest_path }
pub fn name(&self) -> &str { self.package_id().name() }
pub fn package_id(&self) -> &PackageId { self.man... | {
let path = manifest_path.parent().unwrap();
let source_id = try!(SourceId::for_path(path));
let (pkg, _) = try!(ops::read_package(&manifest_path, &source_id,
config));
Ok(pkg)
} | identifier_body |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainE... | }
impl<'cfg> PackageSet<'cfg> {
pub fn new(package_ids: &[PackageId],
sources: SourceMap<'cfg>) -> PackageSet<'cfg> {
PackageSet {
packages: package_ids.iter().map(|id| {
(id.clone(), LazyCell::new(None))
}).collect(),
sources: RefCell::new... | sources: RefCell<SourceMap<'cfg>>, | random_line_split |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainE... | {
// The package's manifest
manifest: Manifest,
// The root of the package
manifest_path: PathBuf,
}
#[derive(RustcEncodable)]
struct SerializedPackage<'a> {
name: &'a str,
version: &'a str,
id: &'a PackageId,
source: &'a SourceId,
dependencies: &'a [Dependency],
targets: &'a [... | Package | identifier_name |
package.rs | use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::fmt;
use std::hash;
use std::path::{Path, PathBuf};
use semver::Version;
use core::{Dependency, Manifest, PackageId, SourceId, Target, TargetKind};
use core::{Summary, Metadata, SourceMap};
use ops;
use util::{CargoResult, Config, LazyCell, ChainE... |
let mut sources = self.sources.borrow_mut();
let source = try!(sources.get_mut(id.source_id()).chain_error(|| {
internal(format!("couldn't find source for `{}`", id))
}));
let pkg = try!(source.download(id).chain_error(|| {
human("unable to get packages from sour... | {
return Ok(pkg)
} | conditional_block |
publisher.js | // Copyright (c) 2013, salesforce.com, inc.
// 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 condit... | elem.style.color = (bool) ? "green" : "red";
},
updateContent : function() {
if (!mobile) {
$$.byId('name').innerHTML = sr.context.user.firstName + " " + sr.context.user.lastName;
$$.byId('location').innerHTML = sr.context.environment.displayLocat... | canvasOptions : function(elem, option) {
var bool = Sfdc.canvas.indexOf(sr.context.application.options, option) == -1;
elem.innerHTML = (bool) ? "✓" : "✗"; | random_line_split |
publisher.js | // Copyright (c) 2013, salesforce.com, inc.
// 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 condit... |
},
onGetPayload : function() {
myPublisher.logEvent("getPayload");
var p = {};
if (postType === 'Text') {
// Example of a Text Post
p.feedItemType = "TextPost";
... | {
alert("Error: " + payload.errors.message);
} | conditional_block |
MathMenu.js | 7C wzory jako",
MathMLcode: "Kod MathML",
OriginalMathML: "Oryginalny MathML",
TeXCommands: "Polecenia TeX",
AsciiMathInput: "Wej\u015Bcie AsciiMathML",
Original: "Oryginalny formularz",
ErrorMessage: "Komunikat o b\u0142\u0119dzie",
Annotation: "Adn... | LatinModernWeb: "Latin Modern (www)",
NeoEulerWeb: "Neo Euler (www)",
CloseAboutDialog: "Zamknij okno o MathJax",
FastPreview: "Szybki podgl\u0105d strony", | random_line_split | |
master.py | #!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... | File(format("/home/{es_user}/elasticsearch.properties"), owner=params.es_user, group=params.es_group, content=params.es_load_config_file)
if not self.hdfs_path_exists("/user/" + params.es_user) :
self.create_es_hdfs_user()
if not self.hdfs_path_exists(params.es_hdfs_upload_dir) :
self.create_es_hdfs_... | geodeTarball.retrieve(params.es_jar_download_url, params.es_jar_path)
| random_line_split |
master.py | #!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... | (self, user):
import pwd
try:
pwd.getpwnam(user)
return True
except KeyError:
return False
def create_es_user(self):
import crypt
import params
Group(params.es_group)
User(params.es_user, gid=params.es_group, password=crypt.crypt(params.es_password, 'salt'), groups=[params.es_group]... | es_user_exists | identifier_name |
master.py | #!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
def install(self, env):
import params
env.set_params(params)
def configure(self, env):
import os
import params
import urllib
env.set_params(params)
if not self.es_user_exists(params.es_user):
self.create_es_user()
if not (os.path.exists(params.es_jar_path) and os.path.isfile(params.e... | import params
File(format("{es_user_file}"), owner=params.es_user, group=params.es_group, content=params.es_user)
File(format("{es_jar_path_file}"), owner=params.es_user, group=params.es_group, content=params.es_jar_path)
File(format("{es_hdfs_upload_dir_file}"), owner=params.es_user, group=params.es_group, co... | identifier_body |
master.py | #!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
if not self.hdfs_path_exists(params.es_hdfs_upload_dir) :
self.create_es_hdfs_upload_dir()
Execute(format('hadoop jar {es_jar_path} -download-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user... | self.create_es_hdfs_user() | conditional_block |
bdist_egg.py | .join(bdist_base, 'egg')
if self.plat_name is None:
self.plat_name = get_build_platform()
self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))
if self.egg_output is None:
# Compute filename of the output egg
basename = Distribution(
... | NATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())
def walk_egg(egg_dir): | random_line_split | |
bdist_egg.py | return safe
log.warn("zip_safe flag not set; analyzing archive contents...")
return analyze_egg(self.bdist_dir, self.stubs)
def gen_header(self):
epm = EntryPoint.parse_map(self.distribution.entry_points or '')
ep = epm.get('setuptools.installation', {}).get('eggsecutabl... | z = zipfile.ZipFile(zip_filename, mode, compression=compression)
for dirname, dirs, files in os.walk(base_dir):
visit(z, dirname, files)
z.close() | conditional_block | |
bdist_egg.py | self.ei_cmd = self.get_finalized_command("egg_info")
self.egg_info = ei_cmd.egg_info
if self.bdist_dir is None:
bdist_base = self.get_finalized_command('bdist').bdist_base
self.bdist_dir = os.path.join(bdist_base, 'egg')
if self.plat_name is None:
self.plat... | (self):
return [self.egg_output]
def call_command(self, cmdname, **kw):
"""Invoke reinitialized command `cmdname` with keyword args"""
for dirname in INSTALL_DIRECTORY_ATTRS:
kw.setdefault(dirname, self.bdist_dir)
kw.setdefault('skip_build', self.skip_build)
kw.s... | get_outputs | identifier_name |
bdist_egg.py | _directory(native_libs)
libs_file = open(native_libs, 'wt')
libs_file.write('\n'.join(all_outputs))
libs_file.write('\n')
libs_file.close()
elif os.path.isfile(native_libs):
log.info("removing %s" % native_libs)
if not self.... | if not sys.platform.startswith('java') and sys.platform != 'cli':
# CPython, PyPy, etc.
return True
log.warn("Unable to analyze compiled code on this platform.")
log.warn("Please ask the author to include a 'zip_safe'"
" setting (either True or False) in the package's setup.py") | identifier_body | |
convertToMappedObjectType.ts | /* @internal */
namespace ts.codefix {
const fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
const fixId = fixIdAddMissingTypeof;
const errorCodes = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
type FixableDeclara... |
function createTypeAliasFromInterface(declaration: FixableDeclaration, type: TypeNode): TypeAliasDeclaration {
return factory.createTypeAliasDeclaration(declaration.decorators, declaration.modifiers, declaration.name, declaration.typeParameters, type);
}
function doChange(changes: textChang... | {
const token = getTokenAtPosition(sourceFile, pos);
const indexSignature = cast(token.parent.parent, isIndexSignatureDeclaration);
if (isClassDeclaration(indexSignature.parent)) return undefined;
const container = isInterfaceDeclaration(indexSignature.parent) ? indexSignature.parent... | identifier_body |
convertToMappedObjectType.ts | /* @internal */
namespace ts.codefix {
const fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
const fixId = fixIdAddMissingTypeof;
const errorCodes = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
type FixableDeclara... | (sourceFile: SourceFile, pos: number): Info | undefined {
const token = getTokenAtPosition(sourceFile, pos);
const indexSignature = cast(token.parent.parent, isIndexSignatureDeclaration);
if (isClassDeclaration(indexSignature.parent)) return undefined;
const container = isInterfaceDe... | getInfo | identifier_name |
convertToMappedObjectType.ts | /* @internal */
| const fixId = fixIdAddMissingTypeof;
const errorCodes = [Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead.code];
type FixableDeclaration = InterfaceDeclaration | TypeAliasDeclaration;
registerCodeFix({
errorCodes,
g... | namespace ts.codefix {
const fixIdAddMissingTypeof = "fixConvertToMappedObjectType";
| random_line_split |
convert.py | # Copyright 2015 OpenStack Foundation
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | """Return task flow for converting images to different formats.
:param task_id: Task ID.
:param task_type: Type of the task.
:param image_repo: Image repository used.
"""
task_id = kwargs.get('task_id')
task_type = kwargs.get('task_type')
image_repo = kwargs.get('image_repo')
return lf... | identifier_body | |
convert.py | # Copyright 2015 OpenStack Foundation
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | "converted.")),
]
CONF = cfg.CONF
# NOTE(flaper87): Registering under the taskflow_executor section
# for now. It seems a waste to have a whole section dedicated to a
# single task with a single option.
CONF.register_opts(convert_task_opts, group='taskflow_executor')
class _Convert(task.Task):... | convert_task_opts = [
cfg.StrOpt('conversion_format',
default=None,
choices=('qcow2', 'raw', 'vmdk'),
help=_("The format to which images will be automatically " | random_line_split |
convert.py | # Copyright 2015 OpenStack Foundation
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | (self, task_id, task_type, image_repo):
self.task_id = task_id
self.task_type = task_type
self.image_repo = image_repo
super(_Convert, self).__init__(
name='%s-Convert-%s' % (task_type, task_id))
def execute(self, image_id, file_path):
# NOTE(flaper87): A format... | __init__ | identifier_name |
convert.py | # Copyright 2015 OpenStack Foundation
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
# TODO(flaper87): Check whether the image is in the desired
# format already. Probably using `qemu-img` just like the
# `Introspection` task.
dest_path = os.path.join(CONF.task.work_dir, "%s.converted" % image_id)
stdout, stderr = putils.trycmd('qemu-img', 'convert', '-O',
... | if not _Convert.conversion_missing_warned:
msg = (_LW('The conversion format is None, please add a value '
'for it in the config file for this task to '
'work: %s') %
self.task_id)
LOG.warn(msg)
... | conditional_block |
tasks.py | ')])
h = httplib2.Http()
creds.authorize(h)
service = build('analytics', 'v3', http=h)
domain = getattr(settings,
'GOOGLE_ANALYTICS_DOMAIN', None) or settings.DOMAIN
profile_id = get_profile_id(service, domain)
if profile_id is None:
log.critical('Failed to update gl... | index_theme_user_counts | identifier_name | |
tasks.py | collection_id=%s;" * len(data))
with connection.cursor() as cursor:
cursor.execute(
query,
list(itertools.chain.from_iterable(
[var['sum'], var['addon'], var['collection']]
for var in data)))
@task
def update_collections_total(data, **kw):
|
def get_profile_id(service, domain):
"""
Fetch the profile ID for the given domain.
"""
accounts = service.management().accounts().list().execute()
account_ids = [a['id'] for a in accounts.get('items', ())]
for account_id in account_ids:
webproperties = service.management().webpropert... | log.info("[%s] Updating collections' download totals." %
(len(data)))
for var in data:
(Collection.objects.filter(pk=var['collection_id'])
.update(downloads=var['sum'])) | identifier_body |
tasks.py | collection_id=%s;" * len(data))
with connection.cursor() as cursor:
cursor.execute(
query,
list(itertools.chain.from_iterable(
[var['sum'], var['addon'], var['collection']]
for var in data)))
@task
def update_collections_total(data, **kw):
log.... |
if name == domain:
return p['id']
@task
def update_google_analytics(date, **kw):
creds_data = getattr(settings, 'GOOGLE_ANALYTICS_CREDENTIALS', None)
if not creds_data:
log.critical('Failed to update global stats: '
'GOOGLE_ANALYTICS_CREDENTIAL... | if '://' in p['websiteUrl']:
name = p['websiteUrl'].partition('://')[-1]
else:
name = p['websiteUrl'] | random_line_split |
tasks.py | execute()
webproperty_ids = [p['id'] for p in webproperties.get('items', ())]
for webproperty_id in webproperty_ids:
profiles = service.management().profiles().list(
accountId=account_id,
webPropertyId=webproperty_id).execute()
for p in profiles.ge... | data.append(search.extract_download_count(dl)) | conditional_block | |
gcmservice.js | ZuYtOKLNSK98T9aFAiUpkLUukldgsYDPBvVcEWEabVnQeKyBGWWM-O7yrrufGe2N-40x4I07WLvveL8O3dzDAKKKM7";
// var apiKey = "AAAA7qUjTrg:APA91bFW2oVQ1mE9u2ANPjFy8IfkMWVGrHs0f1b1Umd_K1DDfng9h0e0hRQih8mLaXCPvu35xHBq9recmJ1EGJiCk7o2qwdN2n3FYPwHr21_p4iP2z1mgZGDdZo-uFLGrRxpqXM5L_tRvudTQJTxxH2IpQC0VquYPQ";
//iadapt
var apiKey = "AAAAjo8JD... | // // },
// data: {
// 'content-available': '1',
// 'priority': 1,
// 'title': 'Hellow world data',
// 'message': 'Notification Message for both IOS and Android',
// // 'icon': 'default',
// // 'sound': 'default',
// 'no... | random_line_split | |
selectplace.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2003-2006 Donald N. Allingham
# Copyright (C) 2009-2010 Gary Burton
# Copyright (C) 2010 Nick Hall
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
#... | (BaseSelector):
def _local_init(self):
"""
Perform local initialisation for this class
"""
self.width_key = 'interface.place-sel-width'
self.height_key = 'interface.place-sel-height'
def get_window_title(self):
return _("Select Place")
def get_model... | SelectPlace | identifier_name |
selectplace.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2003-2006 Donald N. Allingham
# Copyright (C) 2009-2010 Gary Burton
# Copyright (C) 2010 Nick Hall
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
#... | #
#-------------------------------------------------------------------------
class SelectPlace(BaseSelector):
def _local_init(self):
"""
Perform local initialisation for this class
"""
self.width_key = 'interface.place-sel-width'
self.height_key = 'interface.place-sel-height... | #
# SelectPlace | random_line_split |
selectplace.py | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2003-2006 Donald N. Allingham
# Copyright (C) 2009-2010 Gary Burton
# Copyright (C) 2010 Nick Hall
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
#... |
def get_column_titles(self):
return [
(_('Title'), 350, BaseSelector.TEXT, 0),
(_('ID'), 75, BaseSelector.TEXT, 1),
(_('Street'), 75, BaseSelector.TEXT, 2),
(_('Locality'), 75, BaseSelector.TEXT, 3),
(_('City'), 75, BaseSelector.TEX... | return PlaceListModel | identifier_body |
admin.py | # Amara, universalsubtitles.org
#
# Copyright (C) 2016 Participatory Culture Foundation
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... |
# Based on: http://www.djangosnippets.org/snippets/73/
#
# Modified by Sean Reifschneider to be smarter about surrounding page
# link context. For usage documentation see:
#
# http://www.tummy.com/Community/Articles/django-pagination/
from django.contrib import admin
from django.conf import settings
from open... | # along with this program. If not, see
# http://www.gnu.org/licenses/agpl-3.0.html. | random_line_split |
tr_global.js | var mdeps = require('../');
var test = require('tape');
var JSONStream = require('JSONStream');
var packer = require('browser-pack');
var concat = require('concat-stream');
var path = require('path');
test('global transforms', function (t) { |
var p = mdeps({
transform: [ 'tr-c', 'tr-d' ],
globalTransform: [
path.join(__dirname, '/files/tr_global/node_modules/tr-e'),
path.join(__dirname, '/files/tr_global/node_modules/tr-f')
],
transformKey: [ 'browserify', 'transform' ]
});
p.end(path.... | t.plan(1); | random_line_split |
music_hack.py | self.preload = preload
self.config = {}
self.tracks = self.parse_tracks(path)
self.conn = None
self.tracks_played = {scene:0 for scene in self.tracks}
self.poll_rate = self.config["poll_rate"]
self.current_scene = "SpaceCenter"
def can_connect(self):
... |
else:
result[k].append(os.path.join(v, f))
else:
logging.warning("{}: {} not found.".format(k, v))
logging.info("{}: {} tracks loaded".format(... | result[k].append(self.load_track(os.path.join(v, f))) | conditional_block |
music_hack.py | ()
self.preload = preload
self.config = {}
self.tracks = self.parse_tracks(path)
self.conn = None
self.tracks_played = {scene:0 for scene in self.tracks}
self.poll_rate = self.config["poll_rate"]
self.current_scene = "SpaceCenter"
def can_connect(self):
... |
def update_size(self):
if self.valid:
self.size_history.append(os.path.getsize(self.path))
def get_size(self):
return self | self.update_size()
lines = self.get_changed_lines()
if self.valid:
for line in lines:
if "Scene Change : From MAINMENU to SPACECENTER" in line:
return True
return False | identifier_body |
music_hack.py | ()
self.preload = preload
self.config = {}
self.tracks = self.parse_tracks(path)
self.conn = None
self.tracks_played = {scene:0 for scene in self.tracks}
self.poll_rate = self.config["poll_rate"]
self.current_scene = "SpaceCenter"
def can_connect(self):
... | result = self.tracks[scene][self.tracks_played[scene]]
self.tracks_played[scene] += 1
if not self.preload:
result = self.load_track(result)
return result
def play_next_track(self, scene):
while True:
next_track = self.select_track(s... | self.tracks[scene].append(last)
self.tracks_played[scene] = 0
| random_line_split |
music_hack.py | self.preload = preload
self.config = {}
self.tracks = self.parse_tracks(path)
self.conn = None
self.tracks_played = {scene:0 for scene in self.tracks}
self.poll_rate = self.config["poll_rate"]
self.current_scene = "SpaceCenter"
def can_connect(self):
... | (self):
gamelog = GameLog(self.config["gamelog"], self.config["poll_rate"])
gamelog.wait_for_game_start(self)
while True:
if self.can_connect() or gamelog.loaded_save():
self.player.stop()
logging.info("Save game loaded.")
ret... | wait_for_server | identifier_name |
resolver.ts | '@ember/-internals/container';
import { ENV } from '@ember/-internals/environment';
import { Factory, FactoryClass, LookupOptions, Owner } from '@ember/-internals/owner';
import { assert } from '@ember/debug';
import { _instrumentStart } from '@ember/instrumentation';
import { DEBUG } from '@glimmer/env';
import {
C... |
lookupComponent(name: string, owner: Owner): ResolvedComponentDefinition | null {
let pair = lookupComponentPair(owner, name);
if (pair === null) {
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
name !== 'text-area'
);
return null;
}
... | {
return BUILTIN_KEYWORD_MODIFIERS[name] ?? null;
} | identifier_body |
resolver.ts | from '@ember/-internals/container';
import { ENV } from '@ember/-internals/environment';
import { Factory, FactoryClass, LookupOptions, Owner } from '@ember/-internals/owner';
import { assert } from '@ember/debug';
import { _instrumentStart } from '@ember/instrumentation';
import { DEBUG } from '@glimmer/env';
import ... | (name: string, owner: Owner): ResolvedComponentDefinition | null {
let pair = lookupComponentPair(owner, name);
if (pair === null) {
assert(
'Could not find component `<TextArea />` (did you mean `<Textarea />`?)',
name !== 'text-area'
);
return null;
}
let template: ... | lookupComponent | identifier_name |
resolver.ts | from '@ember/-internals/container';
import { ENV } from '@ember/-internals/environment';
import { Factory, FactoryClass, LookupOptions, Owner } from '@ember/-internals/owner';
import { assert } from '@ember/debug';
import { _instrumentStart } from '@ember/instrumentation';
import { DEBUG } from '@glimmer/env';
import ... | layout: TemplateFactory;
};
function lookupComponentPair(
owner: Owner,
name: string,
options?: LookupOptions
): Option<LookupResult> {
let component = componentFor(name, owner, options);
if (component !== null && component.class !== undefined) {
let layout = getComponentTemplate(component.cla... | | {
component: null; | random_line_split |
resolver.ts | from '@ember/-internals/container';
import { ENV } from '@ember/-internals/environment';
import { Factory, FactoryClass, LookupOptions, Owner } from '@ember/-internals/owner';
import { assert } from '@ember/debug';
import { _instrumentStart } from '@ember/instrumentation';
import { DEBUG } from '@glimmer/env';
import ... | else {
key = pair.component;
}
let cachedComponentDefinition = this.componentDefinitionCache.get(key);
if (cachedComponentDefinition !== undefined) {
return cachedComponentDefinition;
}
if (template === null && pair.layout !== null) {
template = pair.layout(owner);
}
le... | {
key = template = pair.layout!(owner);
} | conditional_block |
plex.py | , please refer to the documentation at
https://home-assistant.io/components/media_player.plex/
"""
import os
import json
import logging
from datetime import timedelta
from urllib.parse import urlparse
from homeassistant.loader import get_component
import homeassistant.util as util
from homeassistant.components.media_p... |
@property
def media_series_title(self):
""" Series title of current playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.grandparentTitle
@property
def media_episode(self):
""" Episode of cu... | """ Season of curent playing media (TV Show only). """
from plexapi.video import Show
if isinstance(self.session, Show):
return self.session.seasons()[0].index | identifier_body |
plex.py | please refer to the documentation at
https://home-assistant.io/components/media_player.plex/
"""
import os
import json
import logging
from datetime import timedelta
from urllib.parse import urlparse
from homeassistant.loader import get_component
import homeassistant.util as util
from homeassistant.components.media_pl... | (self):
""" Duration of current playing media in seconds. """
if self.session is not None:
return self.session.duration
@property
def media_image_url(self):
""" Image url of current playing media. """
if self.session is not None:
return self.session.thumb... | media_duration | identifier_name |
plex.py | please refer to the documentation at
https://home-assistant.io/components/media_player.plex/
"""
import os
import json
import logging
from datetime import timedelta
from urllib.parse import urlparse
from homeassistant.loader import get_component
import homeassistant.util as util
from homeassistant.components.media_pl... |
else:
plex_clients[device.machineIdentifier].set_device(device)
if new_plex_clients:
add_devices_callback(new_plex_clients)
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update_sessions():
""" Updates the sessions objects. ""... | new_client = PlexClient(device, plex_sessions, update_devices,
update_sessions)
plex_clients[device.machineIdentifier] = new_client
new_plex_clients.append(new_client) | conditional_block |
plex.py | , please refer to the documentation at
https://home-assistant.io/components/media_player.plex/
"""
import os
import json
import logging
from datetime import timedelta
from urllib.parse import urlparse
from homeassistant.loader import get_component
import homeassistant.util as util
from homeassistant.components.media_p... | if config:
# We're writing configuration
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(config))
except IOError as error:
_LOGGER.error('Saving config file failed: %s', error)
return False
return True
else:
... | SUPPORT_PLEX = SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK
def config_from_file(filename, config=None):
''' Small configuration file management function''' | random_line_split |
ecdsa_test.py | #!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def test_sign_verify(self):
def do_test(secret_exponent, val_list):
public_point = public_pair_for_secret_exponent(generat... | unittest.main() | conditional_block | |
ecdsa_test.py | #!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def test_sign_verify(self):
def do_test(secret_exponent, val_list):
|
val_list = [100,20000,30000000,400000000000,50000000000000000,60000000000000000000000]
do_test(0x1111111111111111111111111111111111111111111111111111111111111111, val_list)
do_test(0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd, val_list)
do_test(0x47f7616ea6f9b923... | public_point = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)
for v in val_list:
signature = sign(generator_secp256k1, secret_exponent, v)
r = verify(generator_secp256k1, public_point, v, signature)
# Check that the 's' value is 'low', t... | identifier_body |
ecdsa_test.py | #!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def test_sign_verify(self):
def do_test(secret_exponent, val_list):
public_point = public_pair_for_secret_exponent(generat... | if __name__ == '__main__':
unittest.main() | random_line_split | |
ecdsa_test.py | #!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def | (self):
def do_test(secret_exponent, val_list):
public_point = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)
for v in val_list:
signature = sign(generator_secp256k1, secret_exponent, v)
r = verify(generator_secp256k1, public_point, ... | test_sign_verify | identifier_name |
6.py | # Nov 22, 2014
# This patch is to create all the prep/sample template files and link them in
# the database so they are present for download
from os.path import join
from time import strftime
from qiita_db.util import get_mountpoint
from qiita_db.sql_connection import SQLConnectionHandler
from qiita_db.metadata_templ... | for study_id in conn_handler.execute_fetchall(
"SELECT study_id FROM qiita.study"):
study_id = study_id[0]
if SampleTemplate.exists(study_id):
st = SampleTemplate(study_id)
fp = join(fp_base, '%d_%s.txt' % (study_id, strftime("%Y%m%d-%H%M%S")))
st.to_file(fp)
st.add_filep... |
_id, fp_base = get_mountpoint('templates')[0]
| random_line_split |
6.py | # Nov 22, 2014
# This patch is to create all the prep/sample template files and link them in
# the database so they are present for download
from os.path import join
from time import strftime
from qiita_db.util import get_mountpoint
from qiita_db.sql_connection import SQLConnectionHandler
from qiita_db.metadata_templ... | prep_template_id = prep_template_id[0]
pt = PrepTemplate(prep_template_id)
study_id = pt.study_id
fp = join(fp_base, '%d_prep_%d_%s.txt' % (pt.study_id, prep_template_id,
strftime("%Y%m%d-%H%M%S")))
pt.to_file(fp)
pt.add_filepath(fp) | conditional_block | |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a no... | // This test is half hearted as we can't test the interrupt
// case.
assert!(!ZSys::is_interrupted());
}
}
| interrupted() {
| identifier_name |
zsys.rs | //! Module: czmq-zsys
use {czmq_sys, RawInterface, Result};
use error::{Error, ErrorKind};
use std::{error, fmt, ptr};
use std::os::raw::c_void;
use std::sync::{Once, ONCE_INIT};
use zsock::ZSock;
static INIT_ZSYS: Once = ONCE_INIT;
pub struct ZSys;
impl ZSys {
// Each new ZSock calls zsys_init(), which is a no... | #[derive(Debug)]
pub enum ZSysError {
CreatePipe,
}
impl fmt::Display for ZSysError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ZSysError::CreatePipe => write!(f, "Could not create pipe"),
}
}
}
impl error::Error for ZSysError {
fn description(&se... | unsafe { czmq_sys::zsys_interrupted == 1 }
}
}
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.