repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
vnsofthe/odoo-dev | addons/rhwl_hr/__init__.py | Python | agpl-3.0 | 55 | 0 | import rhwl_hr
import rhwl_holidays
imp | ort con | trollers
|
mnrozhkov/candybot | twitter_stream.py | Python | gpl-2.0 | 1,522 | 0.027595 | #!/usr/bin/python
# Import the necessary package to process data in JSON format
try:
import json
except ImportError:
import simplejson as json
# Import the necessary methods from "twitter" library
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
# from twython import Twython
from secret import ... | T, CONSUMER_KEY, CO | NSUMER_SECRET)
# Initiate the connection to Twitter Streaming API
twitter_stream = TwitterStream(auth=oauth)
def listenTwitter(track, code):
"""
Listen Twitter for mention of keywords stated in 'track' and 'code'.
Use Twitter stream API
Params:
track: message to track in Tweets
code: uni... |
daniellima/othello | main.py | Python | mit | 204 | 0.014706 | from controllers.board_controller import BoardController
from mo | dels.move import Move
from models.board import Board
controller = BoardController()
controller. | init_game() |
bowenliu16/deepchem | examples/benchmark.py | Python | gpl-3.0 | 23,002 | 0.012086 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 18 15:53:27 2016
@author: Michael Wu
Benchmark test:
Giving classification performances of:
Random forest(rf), MultitaskDNN(tf),
RobustMultitaskDNN(tf_robust),
Logistic regression(logreg),
Graph convolution(graphconv) ... | alid_score = benchmark_regression(
train_dataset, valid_dataset, tasks,
transformers, hp, n_features,
model=model)
time_finish_fitting = time.time()
with open(os.path.join(out_path, 'results.csv'),'a') as f:
writer = csv.writer(f)
if mode == 'classification... | _score'], 'valid', i,
valid_score[i]['mean-roc_auc_score'],
'time_for_running',
time_finish_fitting-time_start_fitting]
writer.writerow(output_line)
else:
for i in train_score:
output_line = [count, dataset, st... |
dnr2/fml-twitter | tweets.py | Python | mit | 1,301 | 0.017679 | #gets COUNT tweets from user's timeline
import os
import tweepy
import cPickle as pickle
from config i | mport Config
#constants
COUNT = 200
#tweepy configuration
keys = file('config.cfg')
cfg = Config(keys)
consumer_key= cfg.consumer_key
consumer_secret= cfg.consumer_secret
access_token= cfg.access_token
access_token_secret= cfg.access_token_secret
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_a... | isVerified):
if isVerified:
file_name = './verified/'+username+'/'+username+'_tweets.pickle'
else:
file_name = './unverified/'+username+'/'+username+'_tweets.pickle'
#save tweets
with open(file_name, 'wb') as f:
pickler = pickle.Pickler(f, -1)
tweet_count = 0
for tweet in tweepy.Cursor(api... |
alflanagan/css_compare | doc/conf.py | Python | agpl-3.0 | 9,525 | 0.005879 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# CSS Compare documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 6 06:29:25 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
... | being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file | named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'L... |
melund/python-prompt-toolkit | examples/switch-between-vi-emacs.py | Python | bsd-3-clause | 1,411 | 0.000709 | #!/usr/bin/env python
"""
Example that displays how to switch between Emacs and Vi input mode.
"""
from prompt_toolkit import prompt
from prompt_toolkit.enums import EditingMode
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
from prompt_toolkit.styles import style... | dd an additional key binding for | toggling this flag.
@manager.registry.add_binding(Keys.F4)
def _(event):
" Toggle between Emacs and Vi mode. "
if event.cli.editing_mode == EditingMode.VI:
event.cli.editing_mode = EditingMode.EMACS
else:
event.cli.editing_mode = EditingMode.VI
# Add a bottom... |
wilvk/ansible | lib/ansible/modules/network/aci/aci_taboo_contract.py | Python | gpl-3.0 | 4,522 | 0.002211 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
... | mat(tenant),
module_object=tenant,
),
subclass_1=dict(
aci_class='vzTaboo',
aci_rn='taboo-{0}'.format(taboo_contract),
filter_target='eq(vzTaboo.name, "{0}")'.format(tab | oo_contract),
module_object=taboo_contract,
),
)
aci.get_existing()
if state == 'present':
# Filter out module parameters with null values
aci.payload(
aci_class='vzTaboo',
class_config=dict(
name=taboo_contract,
d... |
VolpeUSDOT/CV-PEP | lambda/cvp-qc/bucket_handler_lambda/bucket_event_lambda_handler.py | Python | mit | 9,274 | 0.003882 | import os
import boto3
import json
import urllib.parse
from elasticsearch import ElasticsearchException
from botocore.exceptions import ClientError
from common.elasticsearch_client import *
from common.constants import *
from common.logger_utility import *
class HandleBucketEvent:
def _fetchS3DetailsFromEvent(se... | onstants.DEFAULT_INDEX_ID, doc_type=bucket_name, body=json.dumps(metadata))
except ElasticsearchException as e:
LoggerUtility.logError(e)
LoggerUtility.logError("Could not index in Elasticsearch")
raise e
def _publishCustomMetricsToCloudwatch(self, bucket_name, metadata)... | on["SUBMISSIONS_BUCKET_NAME"] and metadata["Dataset"] == "waze":
cloudwatch_client = boto3.client('cloudwatch')
cloudwatch_client.put_metric_data(
Namespace='dot-sdc-waze-submissions-bucket-metric',
MetricData=[
{
... |
Thraxis/pymedusa | sickbeard/providers/thepiratebay.py | Python | gpl-3.0 | 7,881 | 0.00368 | # coding=utf-8
# Author: Dustyn Gibson <miigotu@gmail.com>
#
# This file is part of Medusa.
#
# Medusa is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any... | title = result.find(class_='detName')
title = title.get_text(strip=True) if title else None
download_url = result.find(title='Download this torrent using magnet')
download_url = download_url['href'] + self._custom_trac... | ne
if download_url and 'magnet:?' not in download_url:
logger.log('Invalid ThePirateBay proxy please try another one', logger.DEBUG)
continue
if not all([title, download_url]):
... |
kmad1729/python_notes | metaprogramming/practice_code/metatype_demo.py | Python | unlicense | 583 | 0.010292 | from cls_method_decorators import debugmethods
class metatype(type):
def __new__(cls, cls_name, bases, cls_dict):
clsobj = super().__new__(cls, cls_name, bases, cl | s_dict)
clsobj = debugmethods(clsobj)
return clsobj
class Animal(metaclass = metatype):
def __init__(self, name):
self.name = name
def greet(self):
print("hi, my name is ", self.name)
class Dog(Animal):
def greet(self):
print("Woof!, my name is", self.name)
clas... | self.name)
|
inclement/kivy | kivy/uix/behaviors/button.py | Python | mit | 6,290 | 0 | '''
Button Behavior
===============
The :class:`~kivy.uix.behaviors.button.ButtonBehavior`
`mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides
:class:`~kivy.uix.button.Button` behavior. You can combine this class with
other widgets, such as an :class:`~kivy.uix.image.Image`, to provide
alternative buttons th... | ase`
| Fired when the button is released (i.e. the touch/click that
pressed the button goes away).
'''
state = OptionProperty('normal', options=('normal', 'down'))
'''The state of the button, must be one of 'normal' or 'down'.
The state is 'down' only when the button is currently touched/... |
santisiri/popego | envs/ALPHA-POPEGO/lib/python2.5/site-packages/twisted/words/test/test_jabbercomponent.py | Python | bsd-3-clause | 4,313 | 0.002319 | # Copyright (c) 2001-2005 Twisted Matrix Laboratories.
# See LICENSE for details.
import sys, os, sha
from twisted.trial import unittest
from twisted.words.protocols.jabber.component import ConnectComponentAuthenticator, ComponentInitiatingInitializer
from twisted.words.protocols import jabber
from twisted.words.pro... | xs.connectionMade()
xs.dataReceived("<stream:stream xmlns='jabber:component:accept' xmlns:stream='http://etherx.jabber.org/streams' from='cjid' id='12345'>")
# Calculate what we expect the handshake value to be
hv = sha.new("%s%s" % ("12345", "secret")).hexdigest()
self.assertEquals(... | erServiceHarness(jabber.component.Service):
def __init__(self):
self.componentConnectedFlag = False
self.componentDisconnectedFlag = False
self.transportConnectedFlag = False
def componentConnected(self, xmlstream):
self.componentConnectedFlag = True
def componentDi... |
jaggu303619/asylum | openerp/addons/crm/report/__init__.py | Python | agpl-3.0 | 1,107 | 0.00271 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004 | -2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# T | his program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General ... |
anderasberger/pydnsmap | pydnsmap/util.py | Python | bsd-3-clause | 18,175 | 0.010344 | # Copyright (c) 2014, FTW Forschungszentrum Telekommunikation Wien
# 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... | suffix='.'.join(sdomain[-levels:])
d[suffix]+=1
domainCounts=d.items()
_,counts=zip(*domainCounts)
domainCounts.sort(key=lambda x:x[1])
return (domainCounts[-1][0], domainCounts[-1][1]/float(sum(counts)))
def splitOnCondition(seq, condition):
"""
Splits a list ... | y>. Returns the <x> elements as tuple of two lists.
"""
l1,l2 = itertools.tee((condition(item),item) for item in seq)
return ([i[0] for p, i in l1 if p], [i[0] for p, i in l2 if not p])
def minmax(data):
"""
Computes the minimum and maximum values in one-pass using only
1.5*len(data) comparison... |
lingtools/lingtools | extract_elp_prons.py | Python | apache-2.0 | 4,566 | 0 | #!/usr/bin/env python
"""
Extract pronunciations from the ELP items.
Outputs a CSV with the orthographic and phonological form on each
line. The phonological form is stripped of syllabification and stress
markers.
"""
# Copyright 2013 Constantine Lignos
#
# Licensed under the Apache License, Version 2.0 (the "Licens... | pen(output_path, 'wb') as output_file:
elp = ELP(input_path)
# Sort by lowercase version of entry
words = sorted(elp.keys(), key=lambda s: s.lower())
count = 0
for word in words:
entry = elp[word]
# Extract orthography and pron
pron = entry.p... | not None and nsyll != target_sylls:
continue
# Skip non-monomorphs if specified
if mono_only and not entry.monomorph:
continue
# Skip NULL prons, get the length if there is a pron.
if pron == NULL:
continue
els... |
ankitjavalkar/algosutra | yaksh_video_replacer/replacer.py | Python | gpl-2.0 | 2,250 | 0.005333 | from bs4 import BeautifulSoup
import os
PATH = '/home/arj/arj_projects/imp_dump/kv_advanced/course_material/Advanced_Python_Course_(KV_October_2019)'
VID_DIR = 'advanced_videos'
LESSON_VID_MAP = {
# 'AD_-_Decorators_2': '29B_Decorators.webm',
# 'AD_-_Introduction': '01_Introduction.webm',
# 'AD_-_Exercise1' | : '04_Exercise_1.webm',
# 'AD_-_Exercise5': '08_Exercise_5.webm',
}
def dir_walk(path):
""" Use to walk through all objects in a directory."""
for f in os.listdir(path):
yield os.path.join(path, f)
def walker(path):
flist = []
reslist | = _walker(path, flist)
return reslist
def _walker(dirpath, flist):
for f in os.listdir(dirpath):
fpath = os.path.join(dirpath, f)
if os.path.isfile(fpath):
flist.append(fpath)
else:
_walker(fpath, flist)
return flist
def get_soup(filepath):
with open(fil... |
IfcOpenShell/IfcOpenShell | src/blenderbim/blenderbim/bim/module/style/prop.py | Python | lgpl-3.0 | 1,292 | 0 | # BlenderBIM Add-on - OpenBIM Blender Add-on
# Copyright (C) 2020, 2021 Dion Moult <dion@thinkmoult.com>
#
# This file is part of BlenderBIM Add-on.
#
# BlenderBIM Add-on 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 Fo... | rt StrProperty, Attribute
from bpy.types import PropertyGroup
from bpy.props import (
PointerProperty,
StringProperty,
EnumProperty,
BoolProperty,
IntProperty,
FloatProperty,
FloatVectorProperty,
CollectionProperty,
)
class BIMStyleProperties(PropertyGroup):
attributes: Coll | ectionProperty(name="Attributes", type=Attribute)
is_editing: BoolProperty(name="Is Editing")
|
tbtimes/checkup-survey | editorial_board/dbtemplates/south_migrations/0002_auto__del_unique_template_name.py | Python | mit | 1,636 | 0.006724 | # encoding: utf-8
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'Template', fields ['name']
db.delete_unique('django_template', ['name'])
def backwards(self, orm):
# Adding uniqu... | models.fields.CharField', [], {'max_length': '100'}),
'sites': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['sites.Site']", 'symmetrical': 'False'})
},
'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
... | .models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
}
}
complete_apps = ['dbtemplates']
|
dpapathanasiou/recipebook | sites/wsonoma.py | Python | mit | 2,219 | 0.001803 | #!/usr/bin/env python
"""
wsonoma.py
This module inherits from RecipeParser, and provides an implementation
for parsing recipes from the williams-sonoma.com site.
"""
from urllib.parse import urlsplit
from parser import RecipeParser
class WilliamsSonoma(RecipeParser):
def getTitle(self):
"""The title... | tiveTab=recipes&words=winter_weeknight_dinners
has a collection of individual recipe links, and this method will find them.
"""
data = []
for link in self.tree.xpath('//ul[@class="recipe-list"]/li/a'):
if 'href' in list(link.keys()):
href = urlsplit(link.get(... | m_src=RECIPESEARCH' == href.query:
data.append(href.scheme + '://' + href.netloc + href.path)
return data
|
DigitalSlideArchive/HistomicsTK | histomicstk/utils/hessian.py | Python | apache-2.0 | 1,287 | 0 | import numpy as np
def hessian(im_input, sigma):
"""
Calculates hessian of image I convolved with a gaussian kernel with
covariance C = [Sigma^2 0; 0 Sigma^2].
Parameters
----------
im_input : array_like
M x N grayscale image.
sigma : double
standard deviation of | gaussian kernel.
Returns
-------
im_hess : array_like
M x N x 4 hessian matrix - im_hess[:,:,0] = dxx,
im_hess[:,:,1] = im_hess[:,:,2] = dxy, im_hess[:,:,3] = dyy.
"""
from scipy.ndimage.filters import convolve
# generate kernel domain
h, k = round(3 * sigma), round(3 * si... | y**2) / (2 * sigma ** 2))
gxy = 1./(2 * np.pi * sigma ** 6) * np.multiply(x, y) * \
np.exp(-(x**2+y**2) / (2 * sigma ** 2))
gyy = np.transpose(gxx)
# convolve
dxx = convolve(im_input, gxx, mode='constant')
dxy = convolve(im_input, gxy, mode='constant')
dyy = convolve(im_input, gyy, mode... |
foosel/OctoPrint | tests/settings/__init__.py | Python | agpl-3.0 | 394 | 0.007653 | # -*- coding: utf-8 -*-
from __future__ import | absolute_import, division, print_function, unicode_literals
"""
Unit tests for ``octoprint.settings``.
"""
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/a | gpl.html'
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
gislab-npo/gislab-web | server/webgis/map/views.py | Python | gpl-2.0 | 9,021 | 0.002439 | import os
import re
import json
import urllib.parse
import urllib.request
import contextlib
import hashlib
from lxml import etree
from django.conf import settings
from django.http import HttpResponse, JsonResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.vary import va... | t_data = get_project(request)
return JsonResponse(project_data, status=project_data['status'])
except InvalidProjectException:
raise Http404
project_name_pattern = re.compile('(.+)_(\d{10})')
def parse_project_name(name):
match = project_name_pattern.match(name)
if match:
return ma... | ')
def ows(request):
params = {key.upper(): request.GET[key] for key in request.GET.keys()}
ows_project = clean_project_name(params.get('MAP'))
project, timestamp = parse_project_name(ows_project)
project_hash = hashlib.md5(project.encode('utf-8')).hexdigest()
pi = get_project_info(project_hash, ti... |
BeyondSkyCoder/BeyondCoder | leetcode/python/bulls_and_cows.py | Python | apache-2.0 | 1,021 | 0.002938 | __author__ = 'BeyondSky'
from collections import defaultdict
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
bulls = cows = 0
digits = defaultdict(int)
# first pass: count bulls and non... | ls += 1
else:
# not match, increase number of non-matching digits
digits[secret[index]] += 1
# second pass: count number of cows
for index in range(len(secret)):
if secret[index] != guess[index]:
# decrease number of non-matching d... | ndex]] > 0:
cows += 1
digits[guess[index]] -= 1
return str(bulls) + 'A' + str(cows) + 'B' |
khalim19/gimp-plugin-export-layers | export_layers/pygimplib/gui/itembox.py | Python | gpl-3.0 | 18,637 | 0.014863 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2019 khalim19
#
# 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 applicab... | lf._drag_and_drop_context.setup_drag(
item.item_widget,
self._get_drag_data,
self._on_drag_data_received,
[item],
[item],
self)
def _get_drag_data(self, dragged_item):
return str(self._items.index(dragged_item))
def _on_drag_data_received(self, dragged_item_index_str, d... | f _on_item_widget_key_press_event(self, widget, event, item):
if event.state & gtk.gdk.MOD1_MASK: # Alt key
key_name = gtk.gdk.keyval_name(event.keyval)
if key_name in ["Up", "KP_Up"]:
self.reorder_item(
item, self._get_item_position(item) - 1)
elif key_name in ["Down", "KP_D... |
diegojromerolopez/djanban | src/djanban/apps/reports/migrations/0011_auto_20170211_1640.py | Python | mit | 573 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.1 | 0 on 2017-02-11 15:40
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('reports', '0010_auto_20170211_0306'),
]
operations = [
migrations.RemoveField(
model_name='listreport',
name='... | ',
),
]
|
jhao104/proxy_pool | test.py | Python | mit | 770 | 0.003916 | # -*- coding: utf-8 -*-
"""
-------------------------------------------- | -----
File Name: test.py
Des | cription :
Author : JHao
date: 2017/3/7
-------------------------------------------------
Change Activity:
2017/3/7:
-------------------------------------------------
"""
__author__ = 'JHao'
from test import testProxyValidator
from test import testConfigHandler
from test i... |
niphlod/pydal | tests/_helpers.py | Python | bsd-3-clause | 758 | 0.001319 | from ._compat import unittest
from ._adapt import DEFAULT_URI
from pydal import DAL
class DALtest(unittest.TestCase):
| def __init__(self, *args, **kwargs):
super(DALtest, self).__init__(*args, **kwargs)
self._connections = []
def connect(self, *args, **kwargs):
if not args:
kwargs.setdefault('uri', DEFAULT_URI)
kwargs.setdefault('check_reserved', ['all'])
ret = DAL(*args, **kwarg... | for table in reversed(tablist):
db[table].drop()
db.close()
self._connections = []
|
PetePriority/home-assistant | homeassistant/components/satel_integra/__init__.py | Python | apache-2.0 | 5,379 | 0 | """
Support for Satel Integra devices.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/satel_integra/
"""
import asyncio
import logging
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.const import (
STATE_ALARM... | hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _close())
_LOGGER | .debug("Arm home config: %s, mode: %s ",
conf,
conf.get(CONF_ARM_HOME_MODE))
task_control_panel = hass.async_create_task(
async_load_platform(hass, 'alarm_control_panel', DOMAIN, conf, config))
task_zones = hass.async_create_task(
async_load_platform(hass, '... |
smarkets/pyunimate | unimate.py | Python | mit | 1,311 | 0.00382 | # coding=utf-8
from __future__ import unicode_literals
"""
Utility library for interacting with unimate
"""
import socket
import types
class Client(object):
"""
Unimate client
" | ""
def __init__(self, server, port):
if not isinstance(server, types.StringTypes):
raise TypeError("server must be a string")
if not isinstance(port, (int, long)):
raise TypeError("port must be an integer")
self._server = server
self._port = port
def send... | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self._server, self._port))
if isinstance(message, str):
message = message.decode('utf-8')
if room is None:
msg = "broadcast %s\r\n" % message
else:
if isinstance(room, str... |
supergis/git_notebook | other/schedule.py | Python | gpl-3.0 | 515 | 0 | # -*- coding: utf- | 8 -*-
# Use this file to easily define all of your cron jobs.
#
# It's helpful to understand cron before proceeding.
# http://en.wikipedia.org/wiki/Cron
#
# Learn more: http://github.com/fengsp/plan
from plan import Plan
cron = Plan()
# register one command, script or module
# cron.command('command', every='1.day')... | __":
cron.run()
|
blckshrk/Weboob | modules/poivy/browser.py | Python | agpl-3.0 | 2,888 | 0.001385 | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Fourcot Florent
#
# 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 o... | l,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licen... | tPassword, BrowserBanned
from .pages import HomePage, LoginPage, HistoryPage, BillsPage, ErrorPage
__all__ = ['PoivyBrowser']
class PoivyBrowser(BaseBrowser):
DOMAIN = 'www.poivy.com'
PROTOCOL = 'https'
ENCODING = None # refer to the HTML encoding
PAGES = {'.*login': LoginPage,
... |
talha131/pelican | pelican/tools/pelican_import.py | Python | agpl-3.0 | 37,631 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
import os
import re
import subprocess
import sys
import time
from collections import defaultdict
from html import unescape
from urllib.error import URLError
from urllib.parse import quote, urlparse, urlsplit, urlunsplit
from urllib.request im... | or, categories,
tags, status, kind, 'wp-html')
def blogger2fields(xml):
"""Opens a blogger XML file, and yield Pelican fields"""
soup = xml_to_soup(xml)
entries = soup.feed.findAll('entry')
for entry in entries:
raw_kind = entry.find(
'category', {'scheme': 'htt... | elif raw_kind == 'http://schemas.google.com/blogger/2008/kind#comment':
kind = 'comment'
elif raw_kind == 'http://schemas.google.com/blogger/2008/kind#page':
kind = 'page'
else:
continue
try:
assert kind != 'comment'
filename = e... |
adaur/SickRage | sickbeard/providers/thepiratebay.py | Python | gpl-3.0 | 6,703 | 0.003431 | # coding=utf-8
# Author: Dustyn Gibson <miigotu@gmail.com>
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of ... | NU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SickRage. If not, see <http://www.gnu.org/licenses/>.
import re
import posixpath # Must use posixpath
from urllib import urlencode
from sickbeard import logger
from sickbeard import tvcache
f... | sickrage.helper.common import try_int, convert_size
from sickrage.providers.torrent.TorrentProvider import TorrentProvider
class ThePirateBayProvider(TorrentProvider): # pylint: disable=too-many-instance-attributes
def __init__(self):
TorrentProvider.__init__(self, "ThePirateBay")
self.public =... |
MiniSEC/GRR_clone | lib/flows/general/services_test.py | Python | apache-2.0 | 1,398 | 0.003577 | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Tests for grr.lib.flows.general.services."""
from grr.lib import aff4
from grr.lib import rdfvalue
from grr.lib import test_lib
class ServicesTest(test_lib.FlowTestsBaseclass):
def testEnumerateRunningServices(self):
| class ClientMock(object):
def EnumerateRunningServices(self, _):
service = rdfvalue.Service(label="org.openbsd.ssh-agent",
args="/usr/bin/ssh-agent -l")
service.osx_launchd.sessiontype = "Aqua"
service.osx_launchd.lastexitstatus = 0
service.osx_... | for _ in test_lib.TestFlowHelper(
"EnumerateRunningServices", ClientMock(), client_id=self.client_id,
token=self.token):
pass
# Check the output file is created
fd = aff4.FACTORY.Open(rdfvalue.RDFURN(self.client_id)
.Add("analysis/Services"),
... |
franek/weboob | modules/societegenerale/backend.py | Python | agpl-3.0 | 2,388 | 0.000839 | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Jocelyn Jaubert
#
# 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 yo... | raleBackend']
class SocieteGeneraleBackend(BaseBackend, ICapBank):
NAME = 'societegenerale'
MAINTAINER = u'Jocelyn Jaubert'
EMAIL = 'joce | lyn.jaubert@gmail.com'
VERSION = '0.f'
LICENSE = 'AGPLv3+'
DESCRIPTION = u'Société Générale French bank website'
CONFIG = BackendConfig(ValueBackendPassword('login', label='Account ID', masked=False),
ValueBackendPassword('password', label='Password'))
BROWSER = Soc... |
masfaraud/volmdlr | scripts/faces/planar.py | Python | gpl-3.0 | 1,693 | 0.002363 |
import volmdlr
import volmdlr.edges
import volmdlr.wires
import volmdlr.faces
p1 = volmdlr.Point3D(0.15, 0.48, 0.5)
p2 = volmdlr.Point3D(0.15, 0.1, 0.5)
p1s = volmdlr.Point2D(0, 0)
p2s = volmdlr.Point2D(0.1, 0)
p3s = volmdlr.Point2D(0.2, 0.1)
p4s = volmdlr.Point2D(-0.01, 0.05)
surface2d = volmdlr.faces.Surface2D(vol... | , color='r')
plane_inter_1 = plane.linesegment_intersections(l1)
if plane_inter_1:
plane_inter_1[0].plot(ax=ax, color='b')
plane_inter_2 = plane.linesegment_int | ersections(l2)
if plane_inter_2:
plane_inter_2[0].plot(ax=ax, color='g')
plane_inter_1_2d = plane.point3d_to_2d(plane_inter_1[0])
plane_inter_2_2d = plane.point3d_to_2d(plane_inter_2[0])
ax2 = face.surface2d.plot()
plane_inter_1_2d.plot(ax=ax2, color='b')
plane_inter_2_2d.plot(ax=ax2, color='g')
assert surface2d... |
yannrouillard/weboob | modules/bp/pages/accountlist.py | Python | agpl-3.0 | 3,140 | 0.000637 | # -*- coding: utf-8 -*-
# Copyright(C) 2010-2011 Nicolas Duhamel
#
# 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 y... | a.coming = Decimal('0.0')
a.coming += account.balance
else:
account._card_links = []
self.accounts[account.id] = account
def get_account(self, id):
try:
return self.accounts[id]
except KeyError:
raise ... | NotFound('Unable to find account: %s' % id)
|
Endika/manufacture | mrp_production_real_cost/__init__.py | Python | agpl-3.0 | 165 | 0 | # -*- coding: utf-8 -*-
# © 2014-20 | 15 Avanzosc
# © 2014-2015 Pedro M. Baeza
# License AGPL-3 - See http://www.gn | u.org/licenses/agpl-3.0.html
from . import models
|
insomnia-lab/calibre | src/calibre/devices/kobo/bookmark.py | Python | gpl-3.0 | 4,557 | 0.007022 | # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2011, Timothy Legge <timlegge@gmail.com> and Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
from contextlib import closing
class Bookmark(): # {{{
'''
A simple class fetching boo... | tartOffset = 0
e_type = 'Bookmark'
text = row[9]
# highli | ght is text with no annotation
elif text is not None and (annotation is None or annotation == ""):
e_type = 'Highlight'
elif text and annotation:
e_type = 'Annotation'
else:
e_type = 'Unknown annotation type'
... |
thiagopena/djangoSIGE | djangosige/apps/estoque/forms/local.py | Python | mit | 461 | 0 | # -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from djang | osige.apps.estoque.models import LocalEstoque
class LocalEstoqueForm(forms.ModelForm):
class Meta | :
model = LocalEstoque
fields = ('descricao',)
widgets = {
'descricao': forms.TextInput(attrs={'class': 'form-control'}),
}
labels = {
'descricao': _('Descrição'),
}
|
ueshin/apache-spark | python/pyspark/pandas/tests/test_window.py | Python | apache-2.0 | 13,671 | 0.003292 | #
# 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"); you may not us... | :
getattr(psdf.a.expanding(1), name) # Series
deprecated_properties = [
name
for (name, type_) in missing_properties
if type_.fget.__name__ == "deprecated_property"
]
for name in deprecated_properties:
wi | th self.assertRaisesRegex(
PandasNotImplementedError, "property.*Expanding.*{}.*is deprecated".format(name)
):
getattr(psdf.expanding(1), name) # Frame
with self.assertRaisesRegex(
PandasNotImplementedError, "property.*Expanding.*{}.*is deprecated... |
CongBao/mrsys.online | sub_mrsys/schedule/apps.py | Python | apache-2.0 | 156 | 0 | # -*- | coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class ScheduleConfig(AppConfig):
name = 'sched | ule'
|
rickiepark/openbidder | protobuf/protobuf-2.6.1/python/stubout.py | Python | mit | 4,934 | 0.004662 | #!/usr/bin/python2.4
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | ethod is smart and works
at the module, class, and instance level while preserving proper
inheritance. It will not stub out C types however unless that has been
explicitly allowed by the type.
This method supports the case where attr_name is a staticmethod or a
classmethod of obj.
... | obj is an instance, then it is its class that will actually be
stubbed. Note that the method Set() does not do that: if obj is
an instance, it (and not its class) will be stubbed.
- The stubbing is using the builtin getattr and setattr. So, the __get__
and __set__ will be called when stubb... |
Maelstroms38/ecommerce | src/ecommerce/settings/local.py | Python | mit | 7,411 | 0.003778 | """
Django settings for ecommerce project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build path... | ango.contrib.auth.context_processors.auth',
'django.contrib.messages.cont | ext_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ecommerce.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),... |
ferdas/ws-rpc | websocket.py | Python | gpl-3.0 | 8,711 | 0.011365 | # versione 0.5
import socket
import threading
import hashlib
import base64
import json
class BadWSRequest(Exception):
pass
class BadWSFrame(Exception):
pass
class BadCmdCall(Exception):
pass
class BadCmdParam(Exception):
pass
class Client(threading.Thread):
_MAGIC_STRING = '258EAFA5-E914-47... | gth: ' + str(length))
#Read the mask applied to data
maskKey = self.socket.recv(4)
#valutare di bufferizzare per rendere il thread piu' parsionioso
rcvBuffer = self.socket.recv(length)
message = b''
for i in range(length):
#Unmask the original messag... | ge)
if opcode == self._OPCODE_TEXT:
return json.loads( message.decode('utf-8') )
elif opcode == self._OPCODE_CLOSE:
return None
else:
raise BadWSFrame('Unknown OpCode')
def _sndResponse(self, data):
data = json.dumps(data).encode('utf-8'... |
lukemetz/MLFun | DistCifar10/model.py | Python | mit | 1,811 | 0.008283 | import theano.tensor as T
import numpy as np
from cuboid.bricks import Flattener, FilterPool, Dropout, BatchNormalization
from cuboid.bricks import Convolutional, LeakyRectifier, BrickSequence
from blocks.bricks.conv import MaxPooling
from blocks.bricks import Linear, Softmax
from blocks.initialization import Isotrop... | bias=True)
class ModelHelper():
def __init__(self, config):
self.X = T.tensor4("features")
c = config
seq = BrickSequence(input_dim = (3, 32, 32), bricks=[
conv3(c['n_l1']),
conv3(c['n_l2']),
max_pool(),
conv3(c['n_l3']),
conv3(c[... | ax()
])
seq.initialize()
self.pred = seq.apply(self.X)
self.Y = T.imatrix("targets")
self.cost = CategoricalCrossEntropy().apply(self.Y.flatten(), self.pred)
self.cost.name = "cost"
self.accur = 1.0 - MisclassificationRate().apply(self.Y.flatten(), self.pr... |
krintoxi/NoobSec-Toolkit | NoobSecToolkit /tools/inject/lib/core/optiondict.py | Python | gpl-2.0 | 13,002 | 0.000154 | #!/usr/bin/env python
"""
Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
optDict = {
# Format:
# Family: { "parameter name": "parameter datatype" },
# Or:
# Family: { "parameter name"... | "url": "string",
| "logFile": "string",
"bulkFile": "string",
"requestFile": "string",
"sessionFile": "string",
"googleDork": "string",
... |
haypo/trollius | tests/test_subprocess.py | Python | apache-2.0 | 18,416 | 0.000163 | from trollius import subprocess
from trollius import test_utils
import trollius as asyncio
import os
import signal
import sys
import warnings
from trollius import BrokenPipeError, ConnectionResetError, ProcessLookupError
from trollius import From, Return
from trollius import base_subprocess
from trollius import test_su... | p.run_until_complete(waiter)
self.assertEqual(transport.get_returncode(), 6)
self.assertTrue(protocol.connection_made.called)
self.assertTrue(protocol.process_exited.called)
self.assertTrue(protocol.connection_lost.called)
self.assertE | qual(protocol.connection_lost.call_args[0], (None,))
self.assertFalse(transport._closed)
self.assertIsNone(transport._loop)
self.assertIsNone(transport._proc)
self.assertIsNone(transport._protocol)
# methods must raise ProcessLookupError if the process exited
self.asser... |
ghchinoy/tensorflow | tensorflow/python/distribute/multi_worker_util_test.py | Python | apache-2.0 | 8,226 | 0.004012 | # Copyright 2018 The TensorFlow Authors. 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 required by applica... | r_spec = {
"chief": ["127.0.0.1:1234"],
"worker": ["127.0.0.1:8964", "127.0.0.1:2333"],
"ps": ["127.0.0.1:1926", "127.0.0.1:3141"]
}
self.assertTrue(multi_worker_util.is_chief(cluster_spec, "chief", 0))
self.assertFalse(multi_wo | rker_util.is_chief(cluster_spec, "worker", 0))
def testClusterWithoutChief(self):
cluster_spec = {"worker": ["127.0.0.1:8964", "127.0.0.1:2333"]}
self.assertTrue(multi_worker_util.is_chief(cluster_spec, "worker", 0))
self.assertFalse(multi_worker_util.is_chief(cluster_spec, "worker", 1))
with self.a... |
tocisz/oraschemadoc | oraschemadoc/dot.py | Python | gpl-2.0 | 6,714 | 0.003724 | """ Oriented graph aka ERD painter """
# Copyright (C) Petr Vanek <petr@yarpen.cz> , 2005
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option... | ot(fname) == 0:
return mainName+'.png'
return None
def fileGraphDict(self, all={}):
"""! \brief Make wide graph for the whole schema.
It's used at the index page."""
allNodes = all.keys()
for i in all.keys():
if type(i) != types.ListType:
... | :
s += self.makeKeyNode(i)
for i in all.keys():
s += self.graphList(i, all[i])
s = self.graphTemplate % ('ERD of the schema', s)
fname = os.path.join(self.outPath, 'main')
f = file(fname + '.dot', 'w')
f.write(s)
f.close()
if self.callDot(f... |
OpenSoccerManager/opensoccermanager | uigtk/continuedialog.py | Python | gpl-3.0 | 1,783 | 0 | #!/usr/bin/env python3
# This file is part of OpenSoccerManager.
#
# OpenSoccerManager is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later ver... | True
else:
self.destroy()
data.window.mainscreen.information.update_date()
state | = False
return state
def show(self):
self.show_all()
GObject.timeout_add(10, self.on_timeout_event)
|
pseudonym117/Riot-Watcher | tests/integration/riot/test_AccountApi.py | Python | mit | 1,465 | 0.001365 | import pytest
@pytest.fixture(params=["EUROPE", "ASIA", "AMERICAS"])
def region(request):
return request.param
@pytest.fixture(params=["pseudonym", "Tuxedo"])
def game_name(request):
return request.param
@pytest.fixture(params=["sudo", "riot"])
def t | ag_line(request):
return request.param
@pytest.fixture(params=["val", "lor"])
def game(request):
return request.param
@pytest.mark.riot
@pytest.mark.integration
class TestAccountApi:
def test_by_puuid(self, riot_context, region, puuid):
actual_response = riot_context.watcher.account.by_pu | uid(region, puuid)
riot_context.verify_api_call(
region, f"/riot/account/v1/accounts/by-puuid/{puuid}", {}, actual_response
)
def test_by_riot_id(self, riot_context, region, game_name, tag_line):
actual_response = riot_context.watcher.account.by_riot_id(
region, gam... |
cheenwe/cheenwe.github.io | study/python/8_get_web_page.py | Python | mit | 220 | 0.022727 | import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind | ((host, port))
s.listen(5)
while True:
| c, addr = s.accept()
print "Get coonect from", addr
c.send('Thanks your coonecting')
c.close() |
caiobrentano/swift_undelete | setup.py | Python | apache-2.0 | 1,663 | 0.000601 | #!/usr/bin/python
# Copyright (c) 2014 SwiftStack, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | or ag | reed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup, find_package... |
hanuprateek/django-jsonfield | setup.py | Python | mit | 1,596 | 0.001253 | from distutils.core import Command
from setuptools import setup
class TestCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
from django.conf import settings
settings.configure(
DATABASES... | ng_description=open("README.rst").read(),
install_requires=['Django >= 1.4.3'],
tests_require=['Django >= 1.4.3'],
cmdclass={'test': TestCommand},
classifiers=[
'Environment :: Web Environment',
'Intended | Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Prog... |
ecreall/deform_treepy | deform_treepy/utilities/tree_utility.py | Python | agpl-3.0 | 11,176 | 0.000358 | # -*- coding: utf-8 -*-
"""Tree utilities
"""
class TranslationKind(object):
in_ = 'in'
out_ = 'out'
def _normalize_branche(branche, node_mapping):
new_branches = []
if node_mapping:
node_id = node_mapping.get('node_id')
parts = node_id.split('/')
aliases = node_mapping.get('... | = list(branches)
for branche in branches:
branch_result = normalize_branche(branche, mapping)
if branch_result:
result.extend(branch_result)
result.extend(normaliz | e_branches_out(branch_result, mapping))
return list(set(result))
def normalize_branches_out(branches, mapping):
new_branches = list(branches)
for node_mapping in mapping:
node_id = node_mapping.get('node_id')
parts = node_id.split('/')
aliases = node_mapping.get('aliases')
... |
ratschlab/ASP | examples/undocumented/python_modular/classifier_knn_modular.py | Python | gpl-2.0 | 1,033 | 0.03969 | from tools.load import LoadMatrix
lm=LoadMatrix()
traindat = lm.load_numbers('../data/fm_train_real.dat')
testdat = lm.load_numbers('../data/fm_test_real.dat')
label_traindat = lm.load_labels('../data/label_train_multiclass.dat')
parameter_list = [[traindat,testdat,label_traindat,3],[traindat,testdat,label_traindat,3]... | at,label_train_multiclass=label_traindat, k=3 ):
from shogun.Features import RealFeatures, MulticlassLabels
from shogun.Classifier import KNN
from shogun.Distance import EuclidianDistance
feats_train=RealFeatures(fm_train_real)
feats_test=RealFeatures(fm_test_real)
dista | nce=EuclidianDistance(feats_train, feats_train)
labels=MulticlassLabels(label_train_multiclass)
knn=KNN(k, distance, labels)
knn_train = knn.train()
output=knn.apply(feats_test).get_labels()
multiple_k=knn.classify_for_multiple_k()
return knn,knn_train,output,multiple_k
if __name__=='__main__':
print('KNN')
... |
lord63/getname | getname/__init__.py | Python | mit | 385 | 0 | #! | /usr/bin/env python
# -*- coding: utf-8 -*-
"""
getname
~~~~~~~
Get popular cat/dog/superhero/supervillain names.
:copyright: (c) 2015 by lord63.
:license: MIT, see LICENSE for more details.
"""
from getname.main import random_name
__title__ = "getname"
__version__ = '0.1.1'
__author__ = "lord6... | 15 lord63"
|
eScatter/cstool | cstool/parse_input.py | Python | apache-2.0 | 7,511 | 0.001333 | """
Parses input files of the Cross-section tool, and generates valid input files
from (modified) settings in Python.
"""
from collections import OrderedDict
from ruamel import yaml
from cslib import (
units)
from cslib.settings import (
Type, Model, ModelType, Settings, each_value_conforms,
check_settin... | quantity(description, uni | t_str, default=None):
return Type(description, default=default,
check=has_units(unit_str),
generator=lambda v: '{:~P}'.format(v),
parser=units.parse_expression)
def maybe_quantity(description, unit_str, default=None):
return Type(description, default=default,
... |
csxeba/ReSkiv | brainforge/costs/__init__.py | Python | gpl-3.0 | 22 | 0 | f | rom ._costs import *
| |
liuxue1990/python-ll1-parser-generator | yaml_generator.py | Python | gpl-3.0 | 1,932 | 0.036232 | from ll1_symbols import *
YAML_OUTPUT = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s
table: %s" | ""
YAML_OUTPUT_NO_TABLE = """terminals: %s
non-terminals: %s
eof-marker: %s
error-marker: %s
start-symbol: %s
productions: %s"""
class YamlGenerator(object):
"""docstring for yaml_generator"""
def __init__(self, grammar):
self.grammar = grammar
def print_yaml(self, ll1_table = None):
def convert_list_str(a_li... | ct.items()])
def convert_dict_dict_str(a_dict):
return "\n %s" % ("\n ".join(["%s: %s" % (key, convert_dict_str(value))
for key, value in a_dict.items()]))
def convert_dict_list_str(a_dict):
return "{%s}" % (", \n ".join(["%s: %s" % (key, convert_list_str(value))
for key, value in a_dict.items()... |
lafranceinsoumise/api-django | agir/donations/migrations/0007_auto_20190114_1514.py | Python | agpl-3.0 | 681 | 0 | # Generated by Django 2.1.5 on 2019-01-14 14:14
| from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [("donations", "0006_document_deleted")]
operations = [
migrations.AlterField(
model_name="spendingrequest",
name="created",
field=models.Da... | ld(
model_name="spendingrequest",
name="modified",
field=models.DateTimeField(auto_now=True, verbose_name="modified"),
),
]
|
Adrianzatreanu/coala-decorators | coala_decorators/decorators.py | Python | mit | 11,053 | 0.00009 | import inspect
from functools import total_ordering
def yield_once(iterator):
"""
Decorator to make an iterator yield each result only once.
:param iterator: Any iterator
:return: An iterator that yields every result only once at most.
"""
def yield_once_generator(*args, **kwargs):
... | given member names. All ordering except equality functions will
raise a TypeError when a comparison with an unrelated class is attempted.
(Comparisons with child classes will thus work fine with the capabilities
of the base class as python will choose the base classes comparison
operator in that case.)... | low. I.e. if the first member is equal the second will be
taken for comparison and so on. If a member is None it is
considered smaller than any other value except None.
"""
def decorator(cls):
def lt(self, other):
if not isinstance(other, c... |
imthomasking/MATLAB-files | Python/Project.Euler/Answers.Python/48.py | Python | mit | 391 | 0.048593 | # problem 48
# Project Euler
__author__ = 'Libao Jin'
__date__ = 'July 18, 2015'
def lastTenDigits(number):
string = str(number)
lastTen = int | (string[-10:])
return lastTen
def amazingSum(n):
s = 0
while n >= 1:
s += n ** n
n -= 1
return s
def selfPowers(n):
s = amazingSum(n)
l = lastTenDigits(s)
return (l, s)
def solution():
| ls = selfPowers(1000)
print(ls)
solution()
|
andreimuntean/LinearRegression | LinearRegression/datahelpers.py | Python | mit | 1,252 | 0.0088 | #!/usr/bin/python3
"""datahelpers.py: Provides functions for handling data."""
__author__ = 'Andrei Muntean'
__license__ = 'MIT License'
import numpy as np
def shuffle_data(x, y):
random_indexes = np.random.permutation(x.shape[0])
shuffled_x = np.empty_like(x)
shuffled_y = np.empty_like(y)
for in... | x] = y[random_index]
return x, y
def split_data(x, y, threshold = 0.7, shuffle = True):
"""Generates training and tests sets from the specified data."""
if shuffle:
x, y = shuffle_data(x, y)
pivot_index = round(threshold * x.shape[0])
training_data = {
'x': x[0 : pivot_ind... | ]
}
return training_data, test_data
def read_data(path):
"""Reads csv-formatted data from the specified path."""
data = np.loadtxt(path, delimiter = ',')
# Gets the dependent variables. They're stored in the first column.
y = data[:, 0]
# Gets the independent variables.
x = data[:,... |
anushbmx/kitsune | kitsune/users/api.py | Python | bsd-3-clause | 16,254 | 0.000984 | import random
import re
from datetime import datetime, timedelta
from string import letters
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ValidationError
from djan... | ils import num_answers, num_solutions, num_questions
from kitsune.sumo import email_utils
from kitsune.sumo.api_utils import DateTimeUTCField, GenericAPIException, PermissionMod
from kitsune.sumo.decorators import json_view
from kitsune.users.templatetags.jinja_helpers import profile_avatar
from kitsune.users.model | s import Profile, RegistrationProfile, Setting
def display_name_or_none(user):
try:
return user.profile.name
except (Profile.DoesNotExist, AttributeError):
return None
class TimezoneField(serializers.Field):
def to_representation(self, obj):
return force_text(obj)
def to_int... |
rbeardow/boki | boki/user.py | Python | mit | 1,427 | 0.004905 | from pushyou import db
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(255), unique=True)
status = db.Column(db.SmallInteger)
account_type = db.Column(db.SmallInteger) # Staff,Client,
email = db.Column(db.String(... | iness_name = db.Column(db.String(255))
business_abn = db.Column(db.String(255))
contact_name = db.Column(db.String(255))
contact_phone = db.Column(db.String(255))
address_line1 = db.Column(db.String(255))
address_line2 = db.Column(db.String(255))
address_suburb = db.Column(db.String(255))
ad... | ? Gold?
max_sites = db.Column(db.SmallInteger)
max_active_promo = db.Column(db.SmallInteger)
max_promo_per_site = db.Column(db.SmallInteger)
create_date = db.Column(db.Date)
update_date = db.Column(db.Date)
last_login_date = db.Column(db.Date)
last_login_ip = db.Column(db.Date)
loca... |
defivelo/db | apps/challenge/views/settings.py | Python | agpl-3.0 | 3,051 | 0.000657 | # defivelo-intranet -- Outil métier pour la gestion du Défi Vélo
# Copyright (C) 2020 Didier 'OdyX' Raboud <didier.raboud@liip.ch>
#
# 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... | ryset().filter(year=self.year, canton__in=self.cantons)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# Add our menu_category context
context["menu_category"] = "settings"
context["year"] = self.year
return context
def get_form_kwarg... | form_kwargs = super().get_form_kwargs()
form_kwargs["year"] = self.year
form_kwargs["cantons"] = self.cantons
return form_kwargs
def get_success_url(self):
return reverse_lazy(
"annualstatesettings-list", kwargs={"year": self.object.year}
)
class AnnualState... |
democrats/new-channel-bot | tests/test_new_channel_bot.py | Python | mit | 4,261 | 0 | """ Tests for new channel bot """
import datetime
import time
import unittest
import mock
import new_channel_bot
def _make_fake_api(channels, posts):
"""
Construct a fake slack API
Args: channels (dict): List of channels to mock in.
posts (array): Collection of all calls to the postMessage api.... | "
posts = [ | ]
channels = {
'channels': [
{
'name': u'\U0001f604',
'id': '1',
'created': time.time(),
'purpose': {'value': u'something\U0001f604'},
}
]
}
api.side_effect = ... |
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/aio/operations/_sync_groups_operations.py | Python | mit | 47,878 | 0.004511 | # 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 may ... | cation_name=location_name,
subscription_id=self._config.subscription_id,
template | _url=next_link,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("Syn... |
bptripp/grasp-convnet | py/cninit.py | Python | mit | 7,083 | 0.009318 | __author__ = 'bptripp'
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Flatten
from keras.... | ,2)
plt.hist(sigmoid_inputs[Y_train>.5])
plt.show()
def get_inputs(model, X_train, layer):
if layer == 0:
return X_train
else:
partial_model = Sequential(layers=model.layers[:layer])
partial_model.compile('sgd', 'mse')
return partial_model.p | redict(X_train)
if __name__ == '__main__':
# check_sigmoid()
# check_get_prototypes()
# check_discriminant()
import cPickle
f = file('../data/bowl-test.pkl', 'rb')
# f = file('../data/depths/24_bowl-29-Feb-2016-15-01-53.pkl', 'rb')
d, bd, l = cPickle.load(f)
f.close()
d = d - np.... |
guorendong/iridium-browser-ubuntu | tools/telemetry/telemetry/util/find_dependencies.py | Python | bsd-3-clause | 9,310 | 0.009774 | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import fnmatch
import imp
import logging
import modulefinder
import optparse
import os
import sys
import zipfile
from telemetry import benchmark
from teleme... | path, path.GetChromiumSrcDir()):
continue
yield module_path
def FindPageSetDependencies(base_dir):
logging.info('Finding page sets in %s' % base_dir)
# Add base_dir to path so our imports relative to base_dir will work.
sys.path.append(base_dir)
tests = discover.DiscoverClasses(base_dir, base_dir,... | index_by_class_name=True)
for test_class in tests.itervalues():
test_obj = test_class()
# Ensure the test's default options are set if needed.
parser = optparse.OptionParser()
test_obj.AddCommandLineArgs(parser, None)
options = optparse.Values()
for k, v in parser.get_defaul... |
shashi792/courtlistener | alert/alerts/forms.py | Python | agpl-3.0 | 1,815 | 0 | from django.conf import settings
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from django.forms.widgets import HiddenInput, TextInput, Select, CheckboxInput
from alert.userHandling.models import Alert
class CreateAlertForm(ModelForm):
def __init__(self, *args, **kwargs):
... | }
),
'name': TextInput(
attrs={
'class': 'form-control',
'tabindex': '251'
}
),
| 'rate': Select(
attrs={
'class': 'form-control',
'tabindex': '252',
}
),
'always_send_email': CheckboxInput(
attrs={
'tabindex': '253',
}
),
}
|
ukanga/SickRage | sickbeard/providers/hdbits.py | Python | gpl-3.0 | 6,545 | 0.00275 | # coding=utf-8
#
# URL: https://sickrage.github.io
#
# This file is part of SickRage.
#
# SickRage is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any lat... | else:
post_data['tvdb'] = {
'id': show.indexerid,
'season': episode.scene_season,
'episode': episode.scene_episode
}
if season:
if show. | air_by_date or show.sports:
post_data['tvdb'] = {
'id': show.indexerid,
'season': str(season.airdate)[:7],
}
elif show.anime:
post_data['tvdb'] = {
'id': show.indexerid,
'season': ... |
Hybrid-Cloud/cinder | cinder/volume/drivers/fujitsu/eternus_dx_fc.py | Python | apache-2.0 | 8,064 | 0 | # Copyright (c) 2015 FUJITSU LIMITED
# Copyright (c) 2012 EMC Corporation.
# Copyright (c) 2012 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 Licen... | "Allow connection to connector and retu | rn connection info."""
LOG.debug('initialize_connection, volume id: %(vid)s, '
'wwpns: %(wwpns)s, enter method.',
{'vid': volume['id'], 'wwpns': connector['wwpns']})
info = self.common.initialize_connection(volume, connector)
data = info['data']
init... |
agusmakmun/Some-Examples-of-Simple-Python-Script | list/katakan.py | Python | agpl-3.0 | 984 | 0.01626 | """
4
2 belas
seratus 4 puluh 0
9 ribu seratus 2 puluh 1
2 puluh 1 ribu 3 puluh 0
9 ratus 5 ribu 0
8 puluh 2 juta 8 ratus 8 belas ribu seratus 8 puluh 8
3 ratus 1 juta 4 puluh 8 ribu 5 ratus 8 puluh 8
"""
def kata(n):
angka = range(11)
temp = ""
if n < 12:
temp += str(angka[n])
elif n < 20:
... | :
temp += str(kata(n/10)) + " puluh "+ str(kata(n%10))
elif n < 200:
temp += "seratus "+ str(kata(n-100))
elif n < 1000:
temp += str(kata(n/100))+ " ratus " + str(kata(n%100))
elif n < 2000:
temp += "seribu "+str(kata(n-1000))
elif n < 1000000:
temp += str(kata(... | temp += str(kata(n/1000000)) +" juta " + str(kata(n%1000000))
return temp
print kata(4)
print kata(12)
print kata(140)
print kata(9121)
print kata(21030)
print kata(905000)
print kata(82818188)
print kata(301048588)
|
CERNDocumentServer/invenio | modules/bibsort/lib/bibsort_daemon.py | Python | gpl-2.0 | 15,964 | 0.003257 | # -*- mode: python; coding: utf-8; -*-
#
# This file is part of Invenio.
# Copyright (C) 2010, 2011, 2012 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or... | g.set(section, "definition", item[2])
config.set(section, "washer", item[3])
output_file_name = CFG_ETCDIR + '/bibsort/bibsort_db_dump_%s.cfg' % \
strftime("%d%m%Y%H%M%S", time.localtime())
write_message('Opening the output file %s' %output_file_name)
try:
... | le)
output_file.close()
except Error, err:
write_message('Can not operate on the configuration file %s [%s].' \
%(output_file_name, err), stream=sys.stderr)
return False
write_message('Configuration data dumped to file.')
else:
wr... |
gileno/djangoecommerce | checkout/migrations/0003_order_orderitem.py | Python | cc0-1.0 | 2,362 | 0.004671 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-31 17:48
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class M | igration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('checkout', '0002_auto_20160724_1533') | ,
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('status', models.IntegerField(blank=True, choices=[(0, 'Aguardando Pagamento'), (... |
idkwim/pysmt | pysmt/solvers/pico.py | Python | apache-2.0 | 4,835 | 0.001861 | #
# This file is part of pySMT.
#
# Copyright 2014 Andrea Micheli and Marco Gario
#
# 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
... | cnf_assertion(cnf)
def _add_c | nf_assertion(self, cnf):
for clause in cnf:
for lit in clause:
v = self._get_pico_lit(lit)
picosat.picosat_add(self.pico, v)
picosat.picosat_add(self.pico, 0)
@clear_pending_pop
@catch_conversion_error
def solve(self, assumptions=None):
... |
Azure/WALinuxAgent | azurelinuxagent/pa/deprovision/default.py | Python | apache-2.0 | 10,146 | 0.001774 | # Microsoft Azure Linux Agent
#
# Copyright 2018 Microsoft Corporation
#
# 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 b... | n import version
from azurelinuxagent.common.exception import ProtocolError
from azurelinuxagent.common.osutil import get_osutil
from azurelinuxagent.common.persist_firewall_rules import PersistFirewallRulesHandler
from azurelinuxagent.common.protocol.util import get_protocol_util
from azurelinuxagent.ga.exthandlers im... | read_input(message):
if sys.version_info[0] >= 3:
return input(message)
else:
# This is not defined in python3, and the linter will thus
# throw an undefined-variable<E0602> error on this line.
# Suppress it here.
return raw_input(message) # pylint: disable=E0602
cla... |
jrosebr1/imutils | demos/sorting_contours.py | Python | mit | 1,343 | 0.008935 | # author: Adrian Rosebrock
# website: http://www.pyimagesearch.com
# USAGE
# BE SURE TO INSTALL 'imutils' PRIOR TO EXECUTING THIS COMMAND
# python sorting_contours.py
# import the necessary packages
from imutils import contours
import imutils
import cv2
# load the shapes image clone it, convert it to grayscale,... | (i, c) in enumerate(cnts):
sort | edImage = contours.label_contour(clone, c, i, color=(240, 0, 159))
# show the sorted contour image
cv2.imshow(method, sortedImage)
# wait for a keypress
cv2.waitKey(0)
|
uogbuji/Library.Link | pylib/util.py | Python | apache-2.0 | 17,711 | 0.005533 | '''
'''
import re
import http
import logging
import urllib
import urllib.request
from itertools import *
import collections.abc
from versa.driver import memory
from versa import I, VERSA_BASEIRI, ORIGIN, RELATIONSHIP, TARGET, ATTRIBUTES
from versa.reader import rdfalite
from versa.reader.rdfalite import RDF_NS, SCHEM... | ort util as versautil
from bibframe import BFZ, BL
from bibframe.zextra import LL
from rdflib import URIRef, Literal
from rdflib import BNode
from amara3 import iri
from amara3.uxml import tree
from amara3.uxml import xmliter
from amara3.uxml.treeutil import *
from amara3.uxml import html5
RDFTYPE = 'http://www.w3.... | ype'
SCHEMAORG = 'http://schema.org/'
def load_rdfa_page(site, max_retries=1):
'''
Helper to load RDFa page as text, plus load a Versa model with the metadata
Returns a versa memory model and the raw site text, except in eror case where it returns None and the error
'''
retry_count = 0
wh... |
Taapat/enigma2-openpli-fulan | lib/python/Plugins/SystemPlugins/SoftwareManager/plugin.py | Python | gpl-2.0 | 81,511 | 0.028143 | import os
import time
import cPickle
from Plugins.Plugin import PluginDescriptor
from Screens.Console import Console
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.Ipkg import Ipkg
from Screens.... | PicLoad, eRCInput, getPrevAsciiCode, eEnv
from twisted.web import client
from ImageWizard import ImageWizard
from BackupRestore import BackupSelection, RestoreMenu, BackupScreen, Res | toreScreen, getBackupPath, getBackupFilename
from SoftwareTools import iSoftwareTools
config.plugins.configurationbackup = ConfigSubsection()
config.plugins.configurationbackup.backuplocation = ConfigText(default = '/media/hdd/', visible_width = 50, fixed_size = False)
config.plugins.configurationbackup.backupdirs = C... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractWwwTccedwardsCom.py | Python | bsd-3-clause | 548 | 0.034672 |
def extractWwwTccedwardsCom(item):
'''
Parser for 'www.tccedwards.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Lo... | e in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWit | hType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
gileno/djangoecommerce | catalog/apps.py | Python | cc0-1.0 | 272 | 0 | # coding=ut | f-8
from django.apps import AppConfig
from watson import search as watson
class CatalogConfig(AppConfig):
name = 'catalog'
verbose_name = 'Catálogo'
def ready(self):
Product = self.get_model('Product')
watson.regi | ster(Product)
|
boh1996/LectioAPI | importers/importGroupMembers.py | Python | mit | 3,867 | 0.041376 | import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'scrapers'))
sys.path.append("..")
from datetime import datetime
from pymongo import MongoClient
from database import *
import error
import sync
import group_members as groupMembersApi
def importGroupMembers ( school_id, branch_id, team_eleme... | _cards" : contextCards,
"school_id" : str(school_id),
"branch_id" : str(branch_id)
}
if "field_of_study" in row:
# Add Field of Study Sybc
element["field_of_study"] = {
"name" : row["field_of_study"]["name"],
| "field_of_study_id" : row["field_of_study"]["field_of_study_id"]
}
if "picture_id" in row:
# Launch Fetch Picture Task
element["picture_id"] = row["picture_id"]
else:
unique = {
"teacher_id" : row["person_id"]
}
contextCards = []
contextCards.append(row["con... |
Nexolight/wtstamp | src/utils.py | Python | gpl-2.0 | 17,014 | 0.020336 | from datetime import datetime
from src import yamlsettings as settings
from models.models import Workday
from calendar import monthrange
import time
from math import ceil,floor
class Utils:
WEEKDAYS=["monday","tuesday","wednesday","thursday", "friday", "saturday", "sunday"]
MONTHS=["january","february","m... | stamp":<utc_seconds>}...
]
'''
iterts = datetime.strptime(str(dS.day)+"."+str(dS.month)+"."+str(dS.year), "%d.%m.%Y").timestamp()
| iterdate=datetime.fromtimestamp(iterts).date()
dates=[{"date":iterdate,"timestamp":iterts}]
while True:
iterts=iterts+86400
iterdate=datetime.fromtimestamp(iterts).date()
dates.append({"date":iterdate, "timestamp":iterts})
if(iterdate == dE):
... |
imcleod/anaconda-ec2 | ozutil.py | Python | lgpl-2.1 | 22,263 | 0.001887 | # Copyright (C) 2010,2011,2012 Chris Lalancette <clalance@redhat.com>
# Copyright (C) 2012,2013 Chris Lalancette <clalancette@gmail.com>
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation;... | rror
if line[current] != ' ' and line[current] != '\t':
return None, None
current += 1
# if the whitespace is not immediately followed by another space or a *,
# it is an error
if line[current] != ' ' and line[current] != '*':
return None, None
if line[current] == '*':
... |
filename = line[current:-1]
else:
filename = line[current:]
if escaped_filename:
# FIXME: a \0 is not allowed in the sum file format, but
# string_escape allows it. We'd probably have to implement our
# own codec to fix this
filename = filename.decode('string_e... |
rohitranjan1991/home-assistant | tests/components/tibber/test_statistics.py | Python | mit | 2,649 | 0.00151 | """Test adding external statistics from Tibber."""
from unittest.mock import AsyncMock
from homeassistant.components.recorder.statistics import statistics_during_period
from homeassistant.components.tibber.sensor import TibberDataCoordinator
from homeassistant.util import dt as dt_util
from .test_common import CONSUM... | dt_util.parse_datetime(CONSUMPTION_DATA_1[0]["from"]),
None,
[statistic_id],
"hour",
True,
)
assert len(stats) == 1
assert len(stats[statistic_id]) == 3
_sum = 0
for k, stat in enumerate(stats[statistic_id]):
assert stat["start"] == dt_util.parse_date... | in"] is None
assert stat["max"] is None
assert stat["last_reset"] is None
_sum += CONSUMPTION_DATA_1[k]["consumption"]
assert stat["sum"] == _sum
# Validate cost
statistic_id = "tibber:energy_totalcost_home_id"
stats = await hass.async_add_executor_job(
statistics_... |
sciyoshi/gini | frontend/src/gbuilder/Core/globals.py | Python | mit | 1,542 | 0.029183 | """ Various global variables """
import os
PROG_NAME = "gBuilder"
PROG_VERSION = "2.0.0"
environ = {"os":"Windows",
"path":os.environ["GINI_HOME"]+"/",
"remotepath":"./",
"images":os.environ["GINI_HOME"]+"/share/gbuilder/images/",
"config":os.environ["GINI_HOME"]+"/etc/",
... | 240)",
"background":environ["images"] + "background.jpg",
"windowTheme":environ["images"] + "background2.jpg",
"baseTheme":environ["images"] + "background3.jpg",
"autorouting":True, "autogen":True, "autocompile":True,
"graphing":True, "username":"",
"ser... | ":None,
"canvas":None,
"tab":None,
"popup":None,
"log":None,
"tm":None,
"properties":None,
"interfaces":None,
"routes":None,
"drop":None,
"client":None}
defaultOptions =... |
izapolsk/integration_tests | cfme/tests/automate/test_vmware_methods.py | Python | gpl-2.0 | 4,838 | 0.00186 | """This module contains tests that exercise the canned VMware Automate stuff."""
from textwrap import dedent
import fauxfactory
import pytest
from widgetastic.widget import View
from widgetastic_patternfly import Dropdown
from cfme import test_requirements
from cfme.common import BaseLoggedInPage
from cfme.infrastruc... | _to(domain=domain)
return domain.namespaces.instantiate(name='System').classes.ins | tantiate(name='Request')
@pytest.fixture(scope="module")
def testing_group(appliance):
group_desc = fauxfactory.gen_alphanumeric()
group = appliance.collections.button_groups.create(
text=group_desc,
hover=group_desc,
type=appliance.collections.button_groups.VM_INSTANCE
)
yield... |
kevinlee9/cnn-text-classification-tf | load.py | Python | apache-2.0 | 1,773 | 0.003384 | # -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
# Parameters
# ==================================================
# Data Parameters
# t | f.flags.DEFINE_string("positive_data_file", "./data/rt-polarit | ydata/rt-polarity.pos", "Data source for the positive data.")
# tf.flags.DEFINE_string("negative_data_file", "./data/rt-polaritydata/rt-polarity.neg", "Data source for the positive data.")
# Eval Parameters
# tf.flags.DEFINE_integer("batch_size", 64, "Batch Size (default: 64)")
tf.flags.DEFINE_string("checkpoint_dir",... |
nickyc4/coolq-telegram-bot | plugins/qq_namelist.py | Python | gpl-3.0 | 1,401 | 0.012274 | from bot_constant import FORWARD_LIST
import global_vars
from utils import send_both_side
from command import command_listener
import telegram
import logging
logger = logging.getLogger("CTBPlugin." + __name__)
logger. | debug(__name__ + " loading")
global_vars.create_variable('group_members', [[]] * len(FORWARD_LIST))
def reload_all_qq_namelist():
for i in range(len(FORWARD_LIST)):
global_vars.group_members[i] = global_vars.qq_bot.get_group_member_list(group_id=FORWARD_LIST[i]['QQ'])
@command_listener('update namelist... | , 'name', description='update namelist for current group')
def update_namelist(forward_index: int,
tg_group_id: int=None,
tg_user: telegram.User=None,
tg_message_id: int=None,
tg_reply_to: telegram.Message=None,
qq_group... |
its-dirg/Flask-pyoidc | setup.py | Python | apache-2.0 | 704 | 0 | from setuptools import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='Flask-pyoidc',
version='3.9.0',
packages=['flask_pyoidc'],
package | _dir={'': 'src'},
url='https://github.com/zamzterz/flask-pyoidc',
license='Apache 2.0',
author='Samuel Gulliksson',
author_email='samuel.gulliksson@gmail.com',
description='Flask extension for OpenID Connect authentication.',
install_requires=[
'oic>=1.2.1',
'Flask',
'req... | package_data={'flask_pyoidc': ['parse_fragment.html']},
long_description=long_description,
long_description_content_type='text/markdown',
)
|
google/grr | grr/core/grr_response_core/lib/rdfvalues/chipsec_types.py | Python | apache-2.0 | 1,216 | 0.010691 | #!/usr/bin/env python
"""RDFValues used to communicate with Chipsec."""
from grr_response_core.lib import rdfvalue
from grr_response_core.lib.rdfvalues import paths as rdf_paths
from grr_response_core.lib.rdfvalues import structs as rdf_structs
from grr_response_proto import chipsec_pb2
class DumpFlashImageRequest... | sh image (BIOS)."""
protobuf = chipsec_pb2.DumpFlashImageRequest
class DumpFlashImageResponse(rdf_structs.RDFProtoStruct):
"""A response from Chipsec to dump the flash image (BIOS)."""
protobuf = chipsec_pb2.DumpFlashImageResponse
rdf_deps = [
rdf_paths.PathSpec,
]
class ACPITableData(rdf_structs.RD... | s.RDFProtoStruct):
"""A request to Chipsec to dump an ACPI table."""
protobuf = chipsec_pb2.DumpACPITableRequest
class DumpACPITableResponse(rdf_structs.RDFProtoStruct):
"""A response from Chipsec to dump an ACPI table."""
protobuf = chipsec_pb2.DumpACPITableResponse
rdf_deps = [
ACPITableData,
]
|
appium/python-client | test/unit/webdriver/device/remote_fs_test.py | Python | apache-2.0 | 3,434 | 0.000874 | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You ma | y obtain a copy of the License at
#
# | http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing perm... |
dmarx/praw | praw/errors.py | Python | gpl-3.0 | 14,656 | 0.000068 | # This file is part of PRAW.
#
# PRAW is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# PRAW is distributed in the hope that it will ... | sociate with the
exception. Default: `function` requires the OAuth2 scope `scope`
"""
if not message:
message = '`{0}` requires the OAuth | 2 scope `{1}`'.format(function,
scope)
super(OAuthScopeRequired, self).__init__(message)
self.scope = scope
class LoginRequired(ClientException):
"""Indicates that a logged in session is required.
This exception is raised on... |
AlbertoPeon/invenio | modules/bibupload/lib/batchuploader_engine.py | Python | gpl-2.0 | 28,252 | 0.004071 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2010, 2011, 2012, 2013 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or ... | ec bibupload for the given file.
Finally, write upload history.
@return: tuple (error code, message)
error code: code that indicates if an error ocurred
message: message describing the error
"""
# start output:
req.content_type = "text/html"
req.send_http_header()
error_code... | le:
if filetype != 'marcxml':
metafile = _transform_input_to_marcxml(file_input=metafile)
user_info = collect_user_info(req)
tempfile.tempdir = CFG_TMPSHAREDDIR
filename = tempfile.mktemp(prefix="batchupload_" + \
user_info['nickname'] + "_" + time.strftime("%Y%m%d%H%M%S",
time.... |
UManPychron/pychron | alembic_dvc/versions/45f4b2dbc41a_update_sample_prep_s.py | Python | apache-2.0 | 607 | 0.003295 | """update sample prep steps
Revision ID: 45f4b2dbc41a
Revises: d1653e552ab
Create Date: 2018-07-18 10:01:26.668385
"""
# revision identifiers, used by Alembic.
revision = '45f4b2dbc41a'
down_revision = | 'd1653e552ab'
import sqlalchemy as sa
from alembic import op
def upgrade():
for step in ('mount', 'gold_table', 'us_wand', 'eds', 'cl', 'bse', 'se'):
op.add_column('SamplePrepStepTbl',
sa.Column(step, sa.String(140)))
def downgrade():
for step in ('mount', 'gold_table', 'us_w... | tep)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.