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 |
|---|---|---|---|---|---|---|---|---|
acutesoftware/AIKIF | aikif/dataTools/cls_sql_code_generator.py | Python | gpl-3.0 | 14,592 | 0.008224 | # cls_sql_code_generator.py written by Duncan Murray June 2014
class SQLCodeGenerator(object):
""" generates SQL based on a table """
def __init__(self, fact_table):
self.fact_table = fact_table
self.sql_text = '' # for the main procedure
self.ddl_text = '' # for the create s... | ' + col + '\n'
return txt
def get_sql(self):
return self.sql_text
def save(self, fname):
try:
with open(fname, "w") as f:
f.write(self.sql_text)
except IOError:
print("Error - cant save file " + fname)
def save_ddl(self, ... | rite(self.ddl_text)
def save_undo(self, fname):
with open(fname, "w") as f:
f.write(self.undo_text)
def set_column_list(self, col_list):
"""
opens table or CSV file and collects column names, data samples
set_column_list(['yr', 'institution', 'gender',... |
cpicanco/abpmc-2016 | analysis/export.py | Python | gpl-3.0 | 997 | 0.021063 | import os
from categorization import relative_rate_left_right
from methods import get_data_path
from constants import INNER_PATHS
# assign the root data folder
data_path = get_data_path()
RED = 0
BLUE = 1
all_data = []
for ip in INNER_PATHS:
print(ip)
all_data.append(relative_rate_left_right(os.path.join(data_pa... | a:
try:
strings.append(repr(data[contingency][phase][cycle]))
except:
strings.append('nan')
return ','.join(strings)
print('Left-gaze proportion when left stimulus was red')
for cycle in range | (9):
print(line(0, RED, cycle))
for cycle in range(9):
print(line(1, RED, cycle))
for cycle in range(9):
print(line(2, RED, cycle))
print('Left-gaze proportion when left stimulus was blue')
for cycle in range(9):
print(line(0, BLUE, cycle))
for cycle in range(9):
print(line(1, BLUE, cycle))
for cycle in range... |
remybaranx/qtaste | tools/jython/lib/Lib/encodings/aliases.py | Python | gpl-3.0 | 2,790 | 0.002151 | """ Encoding Aliases Support
This module is used by the encodings package search function to
map encodings names to module names.
Note that the search function converts the encoding names to lower
case and replaces hyphens with underscores *before* performing the
lookup.
"""
aliases = {
# La... | 'ibm1140': 'cp1140',
# ISO
'8859': 'latin_1',
'iso8859': 'latin_1',
'iso8859_1': 'latin_1',
'iso_8859_1': 'latin_1',
'iso_8859_10': 'iso8859_10',
'iso_8859_13': 'iso8859_13',
'iso_8859_14': 'iso8859_14',
'iso_8859_15': 'iso8859_15',
'iso_8859_2': 'iso8859_2',
| 'iso_8859_3': 'iso8859_3',
'iso_8859_4': 'iso8859_4',
'iso_8859_5': 'iso8859_5',
'iso_8859_6': 'iso8859_6',
'iso_8859_7': 'iso8859_7',
'iso_8859_8': 'iso8859_8',
'iso_8859_9': 'iso8859_9',
# Mac
'maclatin2': 'mac_latin2',
'maccentraleurope': 'mac_latin2',
'maccyrillic': 'mac_cyr... |
georgejhunt/HaitiDictionary.activity | progresslistener.py | Python | gpl-2.0 | 3,788 | 0.000264 | # Copyright (C) 2006, Red Hat, Inc.
# Copyright (C) 2007, One Laptop Per Child
# Copyright (C) 2009, Tomeu Vizoso
#
# 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 Licens... | NOTIFY_STATE_NETWORK | \
interfaces.nsIWebProgress.NOTIFY_STATE_REQUEST | \
interfaces.nsIWebProgress.NOTIFY_LOCATION
browser.web_progress.addProgressListener(self._wrapped_self, mask)
def _reset_requests_count(self):
self._total_requests = 0
self._completed_r... | sChange(self, webProgress, request, curSelfProgress,
maxSelfProgress, curTotalProgress, maxTotalProgress):
pass
def onSecurityChange(self, webProgress, request, state):
pass
def onStateChange(self, webProgress, request, stateFlags, status):
if stateFlags & inte... |
bverhagen/openCV-sconsbuilder | opencvBuilder/__init__.py | Python | gpl-2.0 | 42 | 0.02381 | f | rom opencvBuilder impor | t exists,generate
|
odoousers2014/odoo_addons-2 | clv_tag/seq/__init__.py | Python | agpl-3.0 | 1,423 | 0.011947 | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | #
# This 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. ... | e GNU Affero General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
import clv_tag_seq
|
hyunoklee/turtlebot3_RBIZ | lane_filter/src/lane_filter_node.py | Python | gpl-2.0 | 6,754 | 0.042197 | #!/usr/bin/env python
import rospy
import numpy as np
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
from std_msgs.msg import Float32
from turtlebot3_auto_msgs.msg import SegmentList, Segment
from scipy.stats import multivariate_normal, entropy
from scipy.ndimage.filters import gaussian... | rating yellow disappear
self.yellow_x = beta*extend_x + (1 - beta)*self.yellow_x
self.yellow_y = beta*extend_y + (1 - beta)*se | lf.yellow_y
self.yellow_length = beta*extend_length + (1 - beta)*self.yellow_length
self.yellow_degree = beta*extend_degree + (1 - beta)*self.yellow_degree
self.yellow_time = cur_time
if (self.white_time - self.yellow_time)> 0.3 :
if 5500 < self.white_length and self.white_length ... |
ipython/ipywidgets | ipywidgets/widgets/tests/test_widget_selection.py | Python | bsd-3-clause | 2,058 | 0.00243 | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import inspect
import warnings
from unittest import TestCase
from traitlets import TraitError
from ipywidgets import Dropdown, SelectionSlider, Select
class TestDropdown(TestCase):
def test_construction(self):... | t_inde | x_trigger(self):
select = Select(options=[1, 2, 3])
observations = []
def f(change):
observations.append(change.new)
select.observe(f, 'index')
assert select.index == 0
select.options = [4, 5, 6]
assert select.index == 0
assert select.value == ... |
tadhg-ohiggins/regulations-site | regulations/tests/views_comment_tests.py | Python | cc0-1.0 | 2,705 | 0 | import json
import mock
from django.test import SimpleTestCase, override_settings
from regulations.views import comment
@override_settings(
ATTACHMENT_BUCKET='test-bucket',
ATTACHMENT_ACCESS_KEY_ID='test-access-key',
ATTACHMENT_SECRET_ACCESS_KEY='test-secret-key',
ATTACHMENT_MAX_SIZE=42,
)
class Tes... | ')
@mock.patch('regulations.tasks.get_random_string')
def test_get_url(self, get_random, mock_client, mock_time):
generate_presigned = mock_client.generate_presigned_url
generate_presigned.side_effect = ['first-url', 'second-url']
get_random.return_value = 'not-so-random'
mock_ti... | self.assertEqual(resp.status_code, 200)
body = json.loads(resp.content.decode())
generate_presigned.assert_any_call(
ClientMethod='put_object',
Params={
'ContentLength': 42,
'ContentType': 'application/octet-stream',
'Bucket': ... |
htcondor/htcondor | src/condor_tests/test_dagman_inline_submit.py | Python | apache-2.0 | 3,908 | 0.001024 | #!/usr/bin/env pytest
import logging
import textwrap
import htcondor
from ornithology import *
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
@standup
def condor(test_dir):
with Condor(
local_dir=test_dir / "condor",
config={"DAGMAN_USE_STRICT": "0"},
) as condor:
... | ent(
| """
JOB HelloInlineSubmit {{
executable = {}
arguments = 1
output = inline.out
MY.CustomAttribute = {}
}}
""".format(
path_to_sleep, custom_attribute_value,
)
)
sequence_number = 0
@action
def dag_dir(test_dir, dag_descript... |
a-parhom/edx-platform | common/djangoapps/student/views/management.py | Python | agpl-3.0 | 48,715 | 0.00273 | """
Student Views
"""
import datetime
import logging
import uuid
from collections import namedtuple
from bulk_email.models import Optout
from courseware.courses import get_courses, sort_by_announcement, sort_by_start_date
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.de... | IT_LOG = logging.getLogger("audit")
ReverifyInfo = namedtuple(
'ReverifyInfo',
'course_id course_name course_number date status display'
)
SETTING_CHANGE_INITIATED = 'edx.user.settings.change_initiated'
# Us | ed as the name of the user attribute for tracking affiliate registrations
REGISTRATION_AFFILIATE_ID = 'registration_affiliate_id'
REGISTRATION_UTM_PARAMETERS = {
'utm_source': 'registration_utm_source',
'utm_medium': 'registration_utm_medium',
'utm_campaign': 'registration_utm_campaign',
'utm_term': 're... |
crawfordsm/pyspectrograph | PySpectrograph/Spectrograph/Grating.py | Python | bsd-3-clause | 714 | 0 |
class Grating:
"""A class that describing gratings. Sigma should be in lines/mm and the
units of the dimensions should be mm.
"""
def __init__(self, name='', spacing=600, order=1, height=100, width=100,
thickness=100, blaze=0, type='transmission'):
# define the variables... | ame = name
self.type = type
# set the sign for the grating equation
self.sign = 1
if self.type | == 'transmission':
self.sign = -1
|
datamade/geomancer | geomancer/mancers/bea.py | Python | mit | 5,355 | 0.003922 | from urllib import urlencode
import json
import os
from geomancer.app_config import MANCER_KEYS
from geomancer.helpers import encoded_dict
from geomancer.mancers.geotype import State, StateFIPS
from geomancer.mancers.base import BaseMancer, MancerError
from string import punctuation
import re
from urlparse import urlpa... | elf, geo_ids=None, columns=None):
column_names = {
'GDP_SP': '2013 GDP (millions)',
'RGDP_SP': '2013 Real GDP (millions of chained 2009 dollars)',
'PCRGDP_SP': '201 | 3 Per Capita Real GDP (chained 2009 dollars)',
'TPI_SI': '2013 Total Personal Income (thousands of dollars)',
'PCPI_SI': '2013 Per Capita Personal Income (dollars)'
}
results = {'header':[]}
for col in columns:
url = self.base_url+'/?UserID=%s&method=GetData&dataset... |
AnsonT/pocket2quiver | pocket2quiver/quiver_export/quiver_exporter.py | Python | mit | 4,137 | 0.008702 | from __future__ import print_func | tion
import json
import uuid
from os import path, mkdir
from pathlib import Path
try:
from urllib.parse import urlparse
except ImportErr | or:
from urlparse import urlparse
from datetime import datetime
import html2text
import requests
import yaml
from .summarize_content import get_summary
# Download the images and generate UUIDs
def localize_images(resource_path, img_tags):
for img_tag in img_tags:
try:
url = img_tag['src']... |
YoeriDijkstra/iFlow | Examples/Tutorial/plotting/ws_Q_plot.py | Python | lgpl-3.0 | 3,083 | 0.004217 | """
ETMPlot
Date: 10-Jun-16
Authors: Y.M. Dijkstra
"""
from scipy.signal import argrelextrema
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import step as st
import nifty as ny
class ws_Q_plot:
# Variables
# Methods
def __init__(self, input):
self.input = input
... | f=0) + dc.v('c2', x=x, z=1, f=0)
maxc[i, j] = np.max(c)
try:
# loc = ny.toList(self.findETM(xdim, T, Tx))
loc = ny.toList(self.findETM(xdim, c))
ETMloc[i,j] = np.asarray(loc)
except:
print 'no etm'
plt.figure... | ))
log1 = 'True'
log2 = 'False'
if log1=='True':
v1 = np.log10(np.asarray(v1))
if log2=='True':
v2 = np.log10(np.asarray(v2))
x_up_round = np.ceil(max(xdim)/10000.)*10.
ETMloc[np.where(ETMloc>=x_up_round*1000.)] = x_up_round*1000.
levels =... |
ian1roberts/marcador_demo | mysite/marcador/models.py | Python | apache-2.0 | 1,623 | 0.000616 | # encoding: utf-8
from django.contrib.auth.models import User
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.timezone import now
@python_2_unicode_compatible
class Tag(models.Model):
name = models.CharField(max_length=50, unique=True)
class Meta:
... | eld('description', blank=True)
is_public = models.BooleanField('public', default=True)
date_created = models.DateTimeField('date created')
date_updated = model | s.DateTimeField('date updated')
owner = models.ForeignKey(User, verbose_name='owner',
related_name='bookmarks')
tags = models.ManyToManyField(Tag, blank=True)
objects = models.Manager()
public = PublicBookmarkManager()
class Meta:
verbose_name = 'bookmark'
verbose_name_plur... |
sergeLabo/pygame_server_gui | server_gui.py | Python | gpl-2.0 | 6,213 | 0.002417 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# server_gui.py
#############################################################################
# Copyright (C) Labomedia February 2015
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as ... | f.color, self.textpos)
self.fond.blit(self.title, self.textpos)
class Game:
def __init__(self):
self.screen = pygame.display.set_mode((640, 480))
self.level = 1
self.loop = True
# Définition de la police
self.big = pygame.font.SysFont('freesans', 48)
self.s... | = pygame.font.SysFont('freesans', 36)
self.create_fond()
self.create_button()
def update_textes(self):
self.textes = [ ["Buggy Server", ORANGE, self.big, 0, 50],
["Level", BLACK, self.small, 0, 150],
[str(self.level), BLACK, self.small, 0, 2... |
benob/chainer | tests/chainer_tests/functions_tests/loss_tests/test_huber_loss.py | Python | mit | 2,031 | 0 | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
class TestHuberLoss(unittest.TestCase):
def setUp(self):
self.shape = ... | etry(3)
def test_backward_gpu(self):
self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.t),
| cuda.to_gpu(self.gy))
testing.run_module(__name__, __file__)
|
pacificIT/mopidy | mopidy/local/storage.py | Python | apache-2.0 | 330 | 0 | from __futur | e__ import absolute_import, uni | code_literals
import logging
import os
logger = logging.getLogger(__name__)
def check_dirs_and_files(config):
if not os.path.isdir(config['local']['media_dir']):
logger.warning(
'Local media dir %s does not exist.' %
config['local']['media_dir'])
|
acutesoftware/AIKIF | scripts/res_core_data_mthd1.py | Python | gpl-3.0 | 961 | 0.011446 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# res_core_data_mthd1.py
import unittest
import sys
import os
root_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.sep + ".." + os.sep + | "aikif" )
sys.path.append(root_folder)
import core_data as mod_core
def get_method():
"""
returns a description in RST for the research paper
"""
txt = 'Method 1 - Ontological Mapping\n'
txt += '---------------------------------------\n\n'
txt += 'Using an ontology, map the columns in raw data... | ame, '\nMethod 1: running source data ' + dat + ' .... \n')
with open(dat, 'r') as f:
for line in f:
cols = parse_csv(line)
print(cols)
def append_rst(fname, txt):
with open(fname, 'a') as f:
f.write(txt)
def parse_csv(txt):
cols = txt.split(',')
... |
jhroot/elife-bot | provider/glencoe_check.py | Python | mit | 3,847 | 0.004939 | import sys, json
import requests
import re
from functional import seq
'''
glencoe_resp = {
"media1": {
"source_href": "https://static-movie-usa.glencoesoftware.com/source/10.7554/659/0f10378e095dde7aaf579af504c4bfdc6fb86550/elife-00569-media1.wmv",
"doi": "10.7554/eLife.00569.019",
"flv_hre... | c4bfdc6fb86550/elife-0056 | 9-media1.ogv",
"width": 640,
"href": "elife-00569-media1.wmv",
"webm_href": "https://static-movie-usa.glencoesoftware.com/webm/10.7554/659/0f10378e095dde7aaf579af504c4bfdc6fb86550/elife-00569-media1.webm",
"jpg_href": "https://static-movie-usa.glencoesoftware.com/jpg/10.7554/659/0f10378e... |
fdslight/fdslight | pywind/lib/netutils.py | Python | bsd-2-clause | 4,002 | 0.004357 | #!/usr/bin/env python3
import socket, struct
def hex_ifaddr(byte_s):
""" bytes硬件地址到16进制字符串
"""
seq = []
for n in byte_s:
t = hex(n)[2:]
if len(t) == 1:
t = "0%s" % t
seq.append(t)
return ":".join(seq)
def ifaddr_to_bytes(s):
seq = s.split(":")
result... | .inet_ntop(af, bytes(results))
def is_subnet(ip, prefix, subnet, is_ipv6=False):
return calc_subnet(ip, prefix, is_ipv6=is_ipv6) == subnet
def is_port_number(n):
"""检查是否是端口号
:param n:
:return:
"""
try:
v = int(n)
except ValueError:
return False
if v > 0xffff or v < 1... | sts_ipaddr) < 7: return False
seq = sts_ipaddr.split(".")
if len(seq) != 4: return False
for c in seq:
try:
v = int(c)
if v > 255: return False
except ValueError:
return False
''''''
try:
socket.inet_aton(sts_ipaddr)
except OSErro... |
graingert/sqlalchemy | examples/graphs/__init__.py | Python | mit | 378 | 0 | """An example of persistence for a directed graph structure. The
graph is stored as a collection of edges, each referencing both a
"lower" and an " | upper" node in a table of nodes. Basic persistence
and querying for lower- and upper- neighbors are illustrated::
n2 = Node(2)
n5 = Node(5)
n2.add_neighbor(n5)
print | (n2.higher_neighbors())
.. autosource::
"""
|
thaim/ansible | lib/ansible/modules/network/fortios/fortios_dnsfilter_profile.py | Python | mit | 18,043 | 0.001718 | #!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 3 of the Lic... | nse
# along with this program. If not, see <https://www.gnu.org/licenses/>.
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_dnsfilter_profile
short_description: Con... | This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
user to set and modify dnsfilter feature and profile category.
Examples include all parameters and values need to be adjusted to datasources before usage.
Tested with FOS v6.0.5
version_added: "2.8"
author:
- Migu... |
pombredanne/zero-install | tests/testifacecache.py | Python | lgpl-2.1 | 4,642 | 0.028221 | #!/usr/bin/env python
from basetest import BaseTest
import sys, tempfile, os, time
import unittest
import data
sys.path.insert(0, '..')
from zeroinstall.injector import model, gpg, trust
from zeroinstall.injector.namespaces import config_site
from zeroinstall.injector.iface_cache import PendingFeed
from zeroinstall.su... | eam.write(data.thomas_key)
stream.seek(0)
gpg.import_key(stream)
iface = iface_cache.get_interface('http://foo | ')
src = tempfile.TemporaryFile()
src.write(data.foo_signed_xml)
src.seek(0)
pending = PendingFeed(iface.uri, src)
assert iface_cache.update_feed_if_trusted(iface.uri, pending.sigs, pending.new_xml)
iface_cache.__init__()
feed = iface_cache.get_feed('http://foo')
assert feed.last_modified == 1154850229... |
dianamor8/waiter | waiter/apps/conexiones/views.py | Python | lgpl-3.0 | 1,781 | 0.02809 | # -*- coding: utf-8 -*-
from django.shortcuts import render
from waiter.apps.conexiones.models import Product_external_view
from waiter.settings import LOGIN_URL, LOGIN_REDIR | ECT_URL
from django.contrib.auth.decorators import login_required
from waiter.apps.conexiones.forms import addConexionDataBaseForm, TypeConexionForm, ConexionDBForm
import MySQLdb
# Create your views here.
@login_required(login_url=LOGIN_URL)
def view_configuration_productos(request):
productos = Product_external_vie... | e:
ctx = {'productos':productos, 'sidebar':'administracion'}
return render(request, 'home/panel_administracion/configurations.html', ctx)
@login_required(login_url=LOGIN_URL)
def view_configuration_products(request):
if request.method=='GET':
# ctx = {'holi':'holi'}
# bd = MySQLdb.connect("localhost","u... |
alshedivat/tensorflow | tensorflow/python/kernel_tests/logging_ops_test.py | Python | apache-2.0 | 14,951 | 0.011906 | # Copyright 2015 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... | nsor(1e-20)
x = ops.convert_to_tensor(0.0)
y = ops.convert_to_tensor(1.0)
z = ops.convert_to_tensor(2.0)
# assert(epsilon < y)
# z / y
with sess.graph.control_dependencies([
control_flow_ops.Assert(
math_ops.less(epsilon, y), ["Divide-by-zero"])
]):
... | ops.div(z, y)
self.assertAllEqual(2.0, out.eval())
# assert(epsilon < x)
# z / x
#
# This tests printing out multiple tensors
with sess.graph.control_dependencies([
control_flow_ops.Assert(
math_ops.less(epsilon, x), ["Divide-by-zero", "less than x"])
])... |
echenran/bg_daemon | setup.py | Python | gpl-2.0 | 1,862 | 0.001074 | #!/usr/bin/env python
import os
from setuptools import setup
from subprocess import call
from sys import platform, argv
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
SCRIPTS = ["src/bg_daemon/background_daemon.py"]
# only compile quack when none of these options are chosen... | 'src/bg_daemon/mac-update.sh'])],
long_description=read("README.md"),
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Topic :: Utilities",
"License :: ",
"Environment :: No Input/Output (Daemon)",
"Intended Audience :: End Users/Desktop",
... | install_requires=[
"imgurpython",
"requests",
"python-crontab",
"mock",
],
)
|
lreis2415/AutoFuzSlpPos | autofuzslppos/Config.py | Python | gpl-2.0 | 29,475 | 0.0038 | # -*- coding: utf-8 -*-
"""Configuration of pyAutoFuzSlpPos project.
@author: Liangjun Zhu
@changelog:
- 15-07-31 lj - initial implementation.
- 17-07-31 lj - reorganize as basic class, and incorporated with pygeoc.
"""
from __future__ import absolute_import, unicode_literals, division
import argpa... | enceparams: Automatically determine the parameters for fuzzy inference?
True is default, if false, the script will find these parameters
from the \*.ini configuration file, and/or the XXXInfConfig.dat
in 'Config' di... | formation to files. True is default.
selectedtopo: Topographic attributes used for AutoFuzSlpPos. The key is attribute name,
and value is full file path. See also topoparam.
extractrange: Extract value ranges for each topographic attributes of each slope positions.
... |
klahnakoski/JsonSchemaToMarkdown | vendor/mo_json/__init__.py | Python | mpl-2.0 | 13,209 | 0.002953 | # encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import
from __f... | ault(chr(i), u'\\u{0:04x}'.format(i))
ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
def replace(match):
return ESCAPE_DCT[match.group(0)]
| def float2json(value):
"""
CONVERT NUMBER TO JSON STRING, WITH BETTER CONTROL OVER ACCURACY
:param value: float, int, long, Decimal
:return: unicode
"""
if value == 0:
return u'0'
try:
sign = "-" if value < 0 else ""
value = abs(value)
sci = value.__format__("... |
bros-bioinfo/bros-bioinfo.github.io | COURS/M1/SEMESTRE2/ALGO/TD_Arbres.py | Python | mit | 817 | 0.001224 | from typing import *
class Sommet:
def __init__(self, pere, etiquette=None):
self.pere = pere
self.fils = []
self.label = etiquette
if pere:
pere | .fils.append(self)
class Arbre:
def __init__(self):
self.root = Sommet(None)
def fils(arbre: Arbre, sommet: Sommet) -> List[Sommet]:
return sommet.fils
def pere(arbre: Arbre, | sommet: Sommet) -> Sommet:
return sommet.pere
def racine(arbre: Arbre) -> Sommet:
return arbre.root
def etiquette(arbre: Arbre, sommet: Sommet):
return sommet.label
def taille_arbre(arbre: Arbre):
return rec_taille(arbre, racine(arbre))
def rec_taille(arbre: Arbre, sommet: Sommet) -> int:
t... |
FrodeSolheim/fs-uae-launcher | oyoyo/client.py | Python | gpl-2.0 | 10,090 | 0.000892 | # Copyright (c) 2008 Duncan Fordyce
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distri... | bargs.append(bytes(arg, encoding))
elif isinstance(arg, bytes):
bargs.append(arg)
elif type(arg).__name__ == 'unicode':
bargs.append(arg.encode(encoding))
else:
raise IRCClientError('Refusing to send one of the args from provided: %s'
... | rg) for arg in args]))
msg = bytes(" ", "ascii").join(bargs)
logging.info('---> send "%s"' % msg)
self.socket.send(msg + bytes("\r\n", "ascii"))
def connect(self):
""" initiates the connection to the server set in self.host:self.port
and returns a generator object.
... |
atareao/my-weather-indicator | src/comun.py | Python | mit | 7,329 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of my-weather-indicator
#
# Copyright (c) 2012 Lorenzo Carbonell Cerezo <a.k.a. atareao>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... | #####################
# check if | running from source
if is_package():
ROOTDIR = '/opt/extras.ubuntu.com/my-weather-indicator/share/'
LANGDIR = os.path.join(ROOTDIR, 'locale-langpack')
APPDIR = os.path.join(ROOTDIR, APP)
LOGOSDIR = os.path.join(APPDIR, 'logos')
ICONDIR = os.path.join(APPDIR, 'icons')
IMAGESDIR = os.path.join(APP... |
octobear2/ob2 | ob2/web/blueprints/onboarding/__init__.py | Python | bsd-2-clause | 10,932 | 0.002744 | import binascii
import logging
from flask import Blueprint, redirect, render_template, request, session, url_for
from functools import wraps
import ob2.config as config
from ob2.database import DbCursor
from ob2.database.helpers import (
get_photo,
get_user_by_id,
get_user_by_github,
get_user_by_studen... | )
if not photo:
return "onboarding.photo"
authenticate_as_user(user_id_)
return "dashboard.index"
def _get_next_step(current_step):
# I know this kind of logic requires O(2^N) different cases, but right now there's only 1 config
# option that affects this list (it's... | e student photos enable/disable), so it's simplest to
# express the 2 alternatives this way.
#
# When we add more features to the onboarding process, you can come up with a better,
# generalized way of determining the onboarding steps.
if config.student_photos_enabled:
steps = ["onboarding.s... |
c86j224s/snippet | Python_Asyncio_Cffi/sample_cli.py | Python | apache-2.0 | 1,254 | 0.030303 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio
from cffi import FFI
from pprint import pprint
ffi = FFI()
ffi.cdef('''
typedef struct {
int cmd;
int version;
} ProtoHelo;
''')
ffi.cdef('''
typedef struct {
int cmd;
int msgLe | n;
char msg[10];
} ProtoEcho;
''')
@asyncio.coroutine
def sample_cli(loop):
reader, writer = yield from asyncio.open_connection(
'127.0.0.1', 8888, loop=loop
)
print('Connected.')
helo = ffi.new('ProtoHelo[]', 1)
ffi.buffer(helo)[:] = yield from reader.read(ffi.sizeof(helo))
print(' | Received Helo: {}, {}'.format(
helo[0].cmd, helo[0].version
))
for i in range(0, 100+1):
sendMsg = 'msg_{}'.format(i)
sendEcho = ffi.new('ProtoEcho[]', [(i, len(sendMsg), sendMsg.encode('utf-8'))])
writer.write(bytes(ffi.buffer(sendEcho)))
yield from writer.drain()
recvEcho = ffi.new('ProtoEcho[]', 1)
... |
Asurada2015/TFAPI_translation | Training/Decaying the learning rate/tf_train_exponential_decay.py | Python | apache-2.0 | 1,500 | 0.003333 | """自适应学习率衰减
tf.train.exponential_decay(learning_rate, global_step, decay_steps, decay_rate, staircase=False, name=None)
退化学习率,衰减学习率,将指数衰减应用于学习速率。
计算公式:decayed_learning_rate = learning_rate *
decay_rate ^ (global_step / decay_steps)
"""
# 初始的学习速率是0.1,总的迭代次数是1000次,如果staircase=True,那就表明每decay_ste... | ant(0))
c = tf.train.expone | ntial_decay(learning_rate, global_, decay_steps, decay_rate, staircase=True)
d = tf.train.exponential_decay(learning_rate, global_, decay_steps, decay_rate, staircase=False)
T_C = []
F_D = []
with tf.Session() as sess:
for i in range(global_steps):
T_c = sess.run(c, feed_dict={global_: i})
T_C.app... |
yippeecw/sfa | sfa/generic/max.py | Python | mit | 553 | 0.019892 | # an example of how to plugin the max aggregate manager with the flavour model
# might need to be tested
#
from sfa.generic.pl import pl
class max (pl):
# the max flavour behaves like pl, except for
# the aggregate
def aggregate_manager_class (self) :
import sfa.managers.aggregate_manager_max |
return sf | a.managers.aggregate_manager_max.AggregateManagerMax
# I believe the component stuff is not implemented
def component_manager_class (self):
return None
def component_driver_class (self):
return None
|
lizardsystem/lizard-waterbalance | lizard_waterbalance/management/commands/jacktest.py | Python | gpl-3.0 | 2,276 | 0 | import datetime
import logging
from django.core.management.base import BaseCommand
from lizard_waterbalance.models import IncompleteData
from lizard_waterbalance.models import WaterbalanceConf
from lizard_waterbalance.models import WaterbalanceTimeserie
from lizard_wbcomputation.compute import WaterbalanceComputer2
#... | f.objects.get(
# slug=configuration_slug)
done_list = []
# Testing: update with dummy data. Comment out if you don't
# want your WaterbalanceConf's changed.
# for c in WaterbalanceConf.objects.all():
# if c.precipitation is None:
# c.precipitatio... | # c.evaporation = WaterbalanceTimeserie.objects.get(pk=22)
# if c.open_water is None:
# c.open_water = OpenWater.objects.get(pk=2)
# c.save()
# loop all configurations, try to calculate sluice errors.
for configuration in WaterbalanceConf.objects.all... |
rudaoshi/neural_machine | char_rnn/make_char_corpus.py | Python | gpl-3.0 | 520 | 0.003846 | __author__ = 'Sun'
from sandbox.dynamic_title.creator.char_corpus import CharacterCorpus
import cPic | kle
import click
@click.command()
@click.argument("text_file", type=click.File(mode='r', encoding='gb18030'))
@click.argument("char_cropus_fi | le", type=click.File(mode='wb'))
def make_char_corpus(text_file, char_cropus_file):
corpus = CharacterCorpus()
corpus.build(text_file)
cPickle.dump(corpus, char_cropus_file, protocol=cPickle.HIGHEST_PROTOCOL)
if __name__ == "__main__":
make_char_corpus() |
jonathanhogg/coderdojo-sequencer | light_controller/light_controller.py | Python | bsd-2-clause | 678 | 0.004425 |
import dmx
import socket
wash = dmx.EuroliteMovingHeadWash(base=1, color=(1, 1, 1), intensity=1)
controller = dmx.DMXController(debug=True, | fixtures=[wash], port='/dev/tty.usbmodem1421')
controller.enabled = True
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('localhost', 9000))
while True:
message = server.recv(1000)
command, argument = message.strip().split(' ', 1)
if command == 'color':
rgb = int(argument, ... | 6) / 255., ((rgb >> 8) & 0xff) / 255., (rgb & 0xff) / 255.
elif command == 'tilt':
wash.tilt = int(argument)
elif command == 'pan':
wash.pan = int(argument)
|
tootedom/moto | moto/cloudformation/models.py | Python | apache-2.0 | 6,905 | 0.001448 | from __future__ import unicode_literals
from datetime import datetime
import json
import boto.cloudformation
from moto.core import BaseBackend
from .parsing import ResourceMap, OutputMap
from .utils import generate_stack_id
from .exceptions import ValidationError
class FakeStack(object):
def __init__(self, stac... | ce_map = ResourceMap(self.stack_id, self.name, self.parameters, self.tags, self.region_name, self.template_dict)
resource_map.create()
return resource_map
def _create_output_map(self):
output_map = OutputMap(self.resource_map, self.template_dict)
output_map.create()
return o... | stack_id=self.stack_id,
stack_name=self.name,
logical_resource_id=self.name,
physical_resource_id=self.stack_id,
resource_type="AWS::CloudFormation::Stack",
resource_status=resource_status,
resource_status_reason=resource_status_reason,
... |
ajeygore/openstack-dashboard | django-openstack/django_openstack/dash/views/instances.py | Python | apache-2.0 | 9,109 | 0.001208 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Fourth Paradigm Development, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "Licen... | _openstack import utils
import openstack.compute.servers
import openstackx.api.exceptions as api_exceptions
LOG = logging.getLogger('django_openstack.dash')
class TerminateInstance(forms.SelfHandlingForm):
instance = forms.CharField(required=True)
def handle(self | , request, data):
instance_id = data['instance']
instance = api.server_get(request, instance_id)
try:
api.server_delete(request, instance)
except api_exceptions.ApiException, e:
LOG.error('ApiException while terminating instance "%s"' %
inst... |
wayetender/whip | benchmarks/parse_results/parse.py | Python | gpl-2.0 | 1,744 | 0.007454 | import os
f | = open('clientcalls')
f2 = open('times')
BUCKET=250
CASE=os.getenv('CASE')
sums = []
cnt = 0
tmp = 0
try:
for s in f:
parts = s.split(',')
if len(parts) != 2: continue
v_total = float(parts[1])
v_off = float(f2.next())
v = v_total - v_off
tmp += v
cnt += 1
... | = 0
except StopIteration:
pass
f.close()
f = open('/results/timing_%s.tsv' % CASE, 'w')
f.truncate()
i = 1
for p in sums:
f.write("%d\t%s\n" % (i * BUCKET, p))
i += 1
f.close()
f = open('bytes')
def conf_int_native(x, ci=0.95):
if len(x) == 0: return (0,0,0)
ci2 = (1-ci)*.5
low_idx = int(ci2*... |
lgarren/spack | var/spack/repos/builtin/packages/r-base64/package.py | Python | lgpl-2.1 | 1,717 | 0.000582 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | #########################################################################
from spack import *
class RBase64(RPackage):
"""Compatibility wrapper to replace the orp | haned package by Romain
Francois. New applications should use the 'openssl' or 'base64enc'
package instead."""
homepage = "https://cran.r-project.org/package=base64"
url = "https://cran.rstudio.com/src/contrib/base64_2.0.tar.gz"
list_url = homepage
version('2.0', 'f5a653842f75ad717e... |
henrysky/astroNN | astroNN/models/base_vae.py | Python | mit | 27,356 | 0.003765 | import json
import os
import time
from abc import ABC
import numpy as np
from tqdm import tqdm
from tensorflow import keras as tfk
from astroNN.config import MULTIPROCESS_FLAG
from astroNN.config import _astroNN_MODEL_NAME
from astroNN.datasets import H5Loader
from astroNN.models.base_master_nn import NeuralNetMaster
... | tric | s
self.keras_model.compile(loss=self.loss,
optimizer=self.optimizer,
metrics=self.metrics,
weighted_metrics=weighted_metrics,
loss_weights=loss_weights,
... |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247972723/_dbus_bindings/UInt64.py | Python | gpl-2.0 | 1,618 | 0.007417 | # encoding: utf-8
# module _dbus_bindings
# from /usr/lib/python2.7/dist-packages/_dbus_bindings.so
# by generator 1.135
"""
Low-level Python bindings for libdbus. Don't use this module directly -
the public API is provided by the `dbus`, `dbus.service`, `dbus.mainloop`
and `dbus.mainloop.glib` modules, with a lower-le... | riant_level`` must be non-negative; the default is 0.
:IVariables:
`variant_level` : int
Indicates how many nested Variant containers this object
is contained in: if a message's wire format has a variant containing a
variant containing a uint64, this is represented in Python by a
... | ed from __doc__
pass
@staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass
|
pinobatch/thwaite-nes | tools/zipup.py | Python | gpl-3.0 | 2,608 | 0.004218 | #!/usr/bin/env python3
import sys
import os
import argparse
import zipfile
import tarfile
def make_zipfile(outname, filenames, prefix):
with zipfile.ZipFile(outname, "w", zipfile.ZIP_DEFLATED) as z:
| for filename in filenames:
z.write(filename, prefix+filename)
def make_tarfile(outname, filenames, prefix, mode="w"):
with tarfile.open(outname, "w", zipfile.ZIP_DEFLATED) as z:
for filename in filenames:
z.add(filename, prefix+filename)
def make_tarfile_gz(outname, filenames,... | le(outname, filenames, prefix, mode="w:gz")
def make_tarfile_bz2(outname, filenames, foldername):
return make_tarfile(outname, filenames, prefix, mode="w:bz2")
def make_tarfile_xz(outname, filenames, foldername):
return make_tarfile(outname, filenames, prefix, mode="w:xz")
formathandlers = [
(".zip", mak... |
gimunu/mopidy-lcdplate | setup.py | Python | apache-2.0 | 1,406 | 0.000711 | from __future__ import unicode_literals
import re
from setuptools import find_packages, setup
def get_version(filename):
content = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content))
return metadata['version']
setup(
| name='Mopidy-Lcdplate',
version=get_version('mopidy_lcdplate/__init__.py'),
url='https://github.com/gimunu/mopidy-lcdplate',
license='Apache License, Version 2.0',
author='Umberto De Giovannini',
author_email='umberto.degiovannini@gmail.com',
description='Modipy extension for Adafruit lcd pl... | tests.*']),
zip_safe=False,
include_package_data=True,
install_requires=[
'setuptools',
'Mopidy >= 0.18',
'Pykka >= 1.1',
],
test_suite='nose.collector',
tests_require=[
'nose',
'mock >= 1.0',
],
entry_points={
'mopidy.ext': [
'... |
bjesus/wagtail | wagtail/wagtailimages/tests/test_admin_views.py | Python | bsd-3-clause | 25,034 | 0.002397 | from __future__ import unicode_literals
import json
from django.test import TestCase, override_settings
from django.utils.http import urlquote
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django.core.files.uploadedfile import SimpleUploadedFile
from django.templa... | limages:edit', args=(self.image.id,)), post_data)
def test_simple(self):
response = self.get()
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailimages/images/edit.html')
def test_edit(self):
| response = self.post({
'title': "Edited",
})
# Should redirect back to index
self.assertRedirects(response, reverse('wagtailimages:index'))
# Check that the image was edited
image = Image.objects.get(id=self.image.id)
self.assertEqual(image.title, "Edited"... |
wcannon/ranked-choice-voting | docopt_example.py | Python | gpl-3.0 | 1,073 | 0.003728 | #!/usr/bin/env python
"""Example of DocOpt
Usage:
docopt_example.py (-h | --help)
docopt | _example.py --version
docopt_example.py aws [--az=<az>] [--sg=<sg>] [--ssh_user=<sshuser>] [--ssh_key=<sshkey>] [--instance_type=<instance_type>] [--ami_id=<ami_id>] [--roles=<roles> ...]
docopt_example.py azure [--roles=<roles> ...]
docopt_example.py digitalocean [--roles=<roles> ...]
Options:
-h --help ... | fault: mvco-0]
--ssh_user=ssh_user SSH user account name [default: ubuntu]
--ssh_key=ssh_key SSH private key name [default: mvco-0]
--inst_type=intst_type AWS instance type [default: m1.small]
--ami_id=ami_id AWS ami id [default: ami-a73264ce]
--roles=csv of roles Roles to apply to new n... |
ludmilamarian/cds | cds/base/dojson/marc21/translations/default.py | Python | gpl-2.0 | 1,839 | 0 | # -*- | coding: | utf-8 -*-
#
# This file is part of CERN Document Server.
# Copyright (C) 2015 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 (at your option) any later... |
openstack/cloudbase-init | cloudbaseinit/metadata/services/base.py | Python | apache-2.0 | 8,089 | 0 | # Copyright 2012 Cloudbase Solutions Srl
#
# 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 l... | pdate_password(self):
"""The ability to update password of the metadata provider.
If :meth:`~can_update_password` is True, plugins can check
periodically (e.g. at every boot) if the password changed.
| :rtype: bool
.. notes:
The password will be updated only if the
:meth:`~is_password_changed` returns True.
"""
return False
def is_password_changed(self):
"""Check if the metadata provider has a new password for this instance
:rtype: bool
... |
msullivan/advent-of-code | 2021/20b.py | Python | mit | 1,368 | 0.010234 | #!/usr/bin/env python3
import sys
def vadd(v1, v2):
return tuple(x + y for x, y in zip(v1, v2))
ALL_DIRS = [(y, x) for x in [-1,0,1] for y in [-1,0,1]]
|
def get_index(default, m, pos):
l = "".join([m.get(vadd(pos, d), default) for d in ALL_DIRS])
l = l.replace(".", "0").replace("#", "1")
idx = int(l, 2)
return idx
def step(m, lookup, default):
nearby = {vadd(d, p) for p in m for d in ALL_DIRS}
return {
pos: lookup[get_index(default, m... | f draw(painted):
minx = min(x for x, y in painted)
miny = min(y for x, y in painted)
maxx = max(x for x, y in painted)
maxy = max(y for x, y in painted)
l = ""
for y in (list((range(miny, maxy+1)))):
for x in range(minx, maxx+1):
l += painted[x,y]
l += "\n"
print... |
zkmake520/SearchEngine | Indexer.py | Python | mit | 6,844 | 0.03872 | #! /usr/bin/env python
import os.path
import os
import argparse
import pickle
from util import *
from collections import defaultdict
import base64
import logging
import sys
import json
import shelve
#from FeatureExtraction import Tf_Idf
from LangProc import docTerms
# todo : remove this assumptions
# Indexer assumes th... | ]
minSize = sys.maxint
bestIndenticaltermSize = 0
for pos,term in enumerate(self.index.getDocumentOfId(id)):
if term in queryStr:
currentWindow[queryStr.index(term)] = pos
if -1 not in currentWindow:
start = min(currentWindow)
end = pos
indenticaltermSize = len(set(self.index.getDocumen... | > end-start+1) or (indenticaltermSize > bestIndenticaltermSize and minSize+2 >= end-start+1):
minWindow = currentWindow[:]
minSize = end-start + 1
bestIndenticaltermSize = indenticaltermSize
docLength = len(self.index.getDocumentOfId(id))
snippetsStart = max(min(minWindow)-10,0)
snippetsEnd =... |
rjschwei/azure-sdk-for-python | azure-mgmt-dns/azure/mgmt/dns/models/arecord.py | Python | mit | 833 | 0.0012 | # 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 ... | e incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Mode | l
class ARecord(Model):
"""An A record.
:param ipv4_address: The IPv4 address of this A record.
:type ipv4_address: str
"""
_attribute_map = {
'ipv4_address': {'key': 'ipv4Address', 'type': 'str'},
}
def __init__(self, ipv4_address=None):
self.ipv4_address = ipv4_addres... |
draekko/ADEL | _dumpFiles.py | Python | gpl-3.0 | 20,977 | 0.007341 | #!/usr/bin/python
#
# Copyright (C) 2012 Michael Spreitzenbarth, Sven Schmitt
#
# 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 3 of the License, or
# (at your option) any later v... | IPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
downloadsdb.wait()
_adel_log.log("downloads.db -> " + downloadsdb.communicate(0)[1].split("(")[1].split(")")[0] + " -> " + hashlib.sha256(backup_dir + "/downloads.db").hexdigest(), 3)
except:
_adel_log.log("dumpDBs: ----> downloads da... | tionary database ()
try:
userdb = subprocess.Popen(['adb', 'pull', '/data/data/com.android.providers.userdictionary/databases/user_dict.db', backup_dir], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
userdb.wait()
_adel_log.log("user_dict.db -> " + userdb.communicate... |
rwgdrummer/maskgen | maskgen/analytics/dctAnalytic.py | Python | bsd-3-clause | 17,525 | 0.01398 | # =============================================================================
# Authors: PAR Government
# Organization: DARPA
#
# Copyright (c) 2016 PAR Government
# All rights reserved.
#
#
# adapted from https://github.com/enmasse/jpeg_read
#==========================================================================... | f type == 0:
identifier = file.read (5)
Lp -= 5
version = file.read (2)
Lp -= 2
units = ord (file.read (1))
Lp -= 1
Xdensity = ord (file.read (1)) << 8
Xdensity |= ord (file.read (1))
Lp -= 2
Ydensity = ord (file.read (1)) << 8
Yden... | e):
""" Read a byte from file. """
return ord (file.read (1))
def readWord (file):
""" Read a 16 bit word from file. """
return ord (file.read (1)) << 8 | ord (file.read (1))
def restoreDC (data):
""" Restore the DC values. They are coded as the difference from the
previous DC value of ... |
TwilioDevEd/api-snippets | messaging/services/service-shortcode-add/service-shortcode-add.7.x.py | Python | mit | 567 | 0 | # Download the Python helper library from twilio.com/docs/python/install
import os
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
# To set up environmental variables, see http://twil.io/secure
account_si | d = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
short_code = client.messaging \
.services(sid="MG2172dd2db502e20dd981ef0d67850e1a") \
.short_codes \
.create(short_code_sid="SC3 | f94c94562ac88dccf16f8859a1a8b25")
print(short_code.sid)
|
jds2001/sos | sos/plugins/filesys.py | Python | gpl-2.0 | 2,190 | 0.000457 | # 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 op | tion) any later version.
# This 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 General Pu | blic License for more details.
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
cl... |
tdierks/project-euler | e32.py | Python | mit | 1,892 | 0.022727 | #!/usr/bin/pyt | hon |
import argparse
import sys
from itertools import *
import math
import operator
def euler32():
"""Find all unique products where A * B = C and the digits of A, B, and C cover 1...9
Return the sum of all such unique products C."""
# All such values have a one-digit A, a 4-digit B, and a 4-digit C or a two-... |
e0ne/cinder | cinder/backup/api.py | Python | apache-2.0 | 13,528 | 0.000074 | # Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# 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/LICEN... | ['status'] != "available":
msg = _('Volume to be backed up must be available')
raise exception.InvalidVolume(reason=msg)
volume_host = volume_utils.extract_host(volume['host'], 'host')
if not self._is_backup_service_enabled(volume, volume_host):
raise exception.Servic... | {'backups': 1,
'backup_gigabytes': volume['size']}
reservations = QUOTAS.reserve(context, **reserve_opts)
except exception.OverQuota as e:
overs = e.kwargs['overs']
usages = e.kwargs['usages']
quotas = e.kwargs['quotas']
de... |
williballenthin/EVTXtract | setup.py | Python | apache-2.0 | 943 | 0.011665 | #!/usr/bin/env python
import os
import setuptools
# this sets __version__
# # via: http://stackoverflow.com/a/7071358/87207
# # and: http://stackoverflow.com/a/2073599/87207
with open(os.path.join("evtxtract", "version.py"), "rb") as f:
exec(f.read())
setuptools.setup(name="evtxtract",
version=_ | _version__,
description="EVTXtract recovers and reconstructs fragments of EVTX log files from raw binary data, including unallocated space and memory images.",
author="Willi Ballenthin",
author_email="william.ballenthin@fireeye.com",
url="https://github.com/williballenthin/evt | xtract",
license="Apache 2.0 License",
packages=setuptools.find_packages(),
entry_points={
"console_scripts": [
"evtxtract=evtxtract.main:main",
]
},
install_requires=[
'six',
'lxml',
'pytest',
'python-evtx>=0.5.2',
... |
altg0x0/info_tasks | 18/k.py | Python | unlicense | 292 | 0 | n = int(input())
st = [(-1, -2)]
s = 0
for i, h in enumerate(map(int, inp | ut().split() + [' -1'])):
if h > st[-1][1]:
st.append((i, h))
else:
while st[-1][1] >= h:
r = st.pop()
s = max(s, (i - r[0]) | * r[1])
st.append((r[0], h))
print(s)
|
saltastro/polsalt | polsalt/oksmooth.py | Python | bsd-3-clause | 5,610 | 0.035116 |
"""
oksmooth
General purpose smoothing which properly uses pixel mask
"""
import os, sys, glob, shutil, inspect
import numpy as np
import pyfits
from scipy.interpolate import griddata
np.set_printoptions(threshold=np.nan)
# ---------------------------------------------------------------------------------
def box... | lock scaling to avoid triangularization failure
rfac,cfac = max(rblk,cblk)/rblk, max(rblk,cblk)/cblk
r0,c0 = (rows % rblk)/2,(cols % cblk)/2
arr_RCb = arr_rc[r0:(r0+rblk*rblks),c0:(c0+cblk*cblks)] \
.r | eshape(rblks,rblk,cblks,cblk).transpose(0,2,1,3).reshape(rblks,cblks,rblk*cblk)
ok_RCb = ok_rc[r0:(r0+rblk*rblks),c0:(c0+cblk*cblks)] \
.reshape(rblks,rblk,cblks,cblk).transpose(0,2,1,3).reshape(rblks,cblks,rblk*cblk)
r_RCb = rfac*((ok_rc*r_rc)[r0:(r0+rblk*rblks),c0:(c0+cblk*cblks)]) \
.re... |
sfu-natlang/glm-parser | src/learner/perceptron_base.py | Python | mit | 6,218 | 0.005307 | from weight.weight_vector import WeightVector
from data.data_pool import DataPool
import os
from learner import logger
__version__ = '1.0.0'
class PerceptronLearnerBase:
name = "PerceptronLearnerBase"
def __init__(self, w_vector=None):
self.w_vector = {}
if w_vector is None:
re... | ata_pool not of DataPool type")
if not isinstance(iterations, int):
raise ValueError("LEARNER [ERROR]: iterations not of int type")
i | f iterations < 1:
raise ValueError("LEARNER [ERROR]: iterations needs to be positive integer")
if d_filename is not None and not isinstance(d_filename, str):
raise ValueError("LEARNER [ERROR]: d_filename needs to be str or None")
if not isinstance(dump_freq, int):
rai... |
doublebits/osf.io | framework/auth/views.py | Python | apache-2.0 | 16,757 | 0.00179 | # -*- coding: utf-8 -*-
import datetime
import httplib as http
from flask import request
import markupsafe
from modularodm import Q
from modularodm.exceptions import NoResultsFound
from modularodm.exceptions import ValidationValueError
import framework.auth
from framework.auth import cas, campaigns
from framework i... | url') or web_url_for('goodbye', _absolute=True)
logout()
if 'reauth' in request.args:
cas_endpoint = cas.get_login_url(redirect_url)
else:
cas_endpoint = cas.get_logout_url(redirect_url)
resp = redirect(cas_endpoint)
resp.delete_cookie(settings.COOKIE_NAME, domain=settings.OSF_COOKIE... | if confirmation is
successful, otherwise shows an "Expired Link" error.
methods: GET
"""
user = User.load(kwargs['uid'])
is_merge = 'confirm_merge' in request.args
is_initial_confirmation = not user.date_confirmed
if user is None:
raise HTTPError(http.NOT_FOUND)
if auth and a... |
recklessromeo/otm-core | opentreemap/importer/models/trees.py | Python | agpl-3.0 | 15,243 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.core.exceptions import ValidationError
from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D
from djang... | ': fields.trees.SPECIES_OBJECT,
'date_planted': fields.trees.DATE_PLANTED,
# TODO: READONLY restore when implemented
# 'readonly': fields.trees.READ_ONLY
}
# plot that was created from this row
plot = models.ForeignKey(Plot, null=True, blank=True)
# The main import event
im... | def model_fields(self):
return fields.trees
def commit_row(self):
is_valid = self.validate_row()
if not is_valid:
return # not ready to commit
if self.status == TreeImportRow.SUCCESS:
return # nothing changed so no need to commit
# Get our da... |
laslabs/odoo-connector-carepoint | first_databank/__init__.py | Python | agpl-3.0 | 138 | 0 | # -*- coding: utf-8 -*-
# © 2015 LasLabs Inc.
# Licens | e AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.ht | ml).
from . import models
|
tmhorne/simplewiki | tests/tags.py | Python | gpl-2.0 | 11,780 | 0.026146 | # -*- coding: utf-8 -*-
# Copyright 2011 Jaap Karssenberg <jaap.karssenberg@gmail.com>
import tests
import gtk
import pango
from zim.index import Index, IndexPath, IndexTag
from zim.notebook import Path
from zim.gui.pageindex import FGCOLOR_COL, \
EMPTY_COL, NAME_COL, PATH_COL, STYLE_COL
# Explicitly don't import... |
path = path[:-1] + (path[-1]+1,) # inc | rease last member
else:
break
self.assertTrue(nitems > 10) # double check sanity of loop
# Check if all the signals go OK
treestore.disconnect_index()
del treestore
self.index.flush()
treestore = self.storeclass(self.index)
treeview = TagsPageTreeView(ui, treestore)
self.index.update(callba... |
Victor-Haefner/ontocad | src/selector.py | Python | gpl-3.0 | 1,989 | 0.047763 | #!/usr/bin/env python
import numpy
from numpy import *
from ocad_primitives import *
import layer
PI = 3.14159265359
class selector:
def __init__( self ):
self.selectionLasso = layer.layer("poly_lasso_selection")
self.selectionLasso.line_style = 1 #self.gtk.gdk.LINE_ON_OFF_DASH
self.selectionLasso.line_width =... | f):
self.closeLoop()
self.clear()
def appendToPolySelect(self, pos, im | gpos):
self.img_pnts.append(imgpos)
self.wrl_pnts.append(pos)
if self.lastPosition == None:#first point
self.firstPosition = pos[:]
self.lastPosition = pos[:]
if self.mode == "LASSO":
self.selectionLasso.clear()
self.selectionLasso.addPoint( pos[:] )
if self.mode == "PIN":
self.selectionPi... |
magic0704/oslo.db | oslo_db/tests/test_api.py | Python | apache-2.0 | 8,075 | 0 | # Copyright (c) 2013 Rackspace Hosting
# 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 req... | some_method()
def test_retry_wrapper_reaches_limit(self):
max | _retries = 10
@api.wrap_db_retry(max_retries=10, retry_on_request=True)
def some_method(res):
res['result'] += 1
raise exception.RetryRequest(ValueError())
res = {'result': 0}
self.assertRaises(ValueError, some_method, res)
self.assertEqual(max_retries +... |
msabramo/urllib3 | test/with_dummyserver/test_poolmanager.py | Python | mit | 6,688 | 0.002691 | import unittest
import json
from nose.plugins.skip import SkipTest
from dummyserver.server import HAS_IPV6
from dummyserver.testcase import (HTTPDummyServerTestCase,
IPv6HTTPDummyServerTestCase)
from urllib3.poolmanager import PoolManager
from urllib3.connectionpool import port_by_sch... | e, redirect=1))
self.fail("Failed to raise MaxRetryError exception, returned %r" % r.status)
except MaxRetryError:
pass
def test_raise_on_redirect(self):
http = PoolManager()
r = http.request('GET', '%s/redirect' % self.base_url,
fields={'ta... | al(r.status, 303)
def test_missing_port(self):
# Can a URL that lacks an explicit port like ':80' succeed, or
# will all such URLs fail with an error?
http = PoolManager()
# By globally adjusting `port_by_scheme` we pretend for a moment
# that HTTP's default port is not 80... |
anhstudios/swganh | data/scripts/templates/object/tangible/wearables/ithorian/shared_ith_shirt_s09.py | Python | mit | 464 | 0.047414 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE O | NLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Tangible()
result.template = "object/tangible/wearables/ithorian/shared_ith_shirt_s09.iff"
result.attribute_template_id = 11
result.stfName("wearables_name | ","ith_shirt_s09")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
tao12345666333/Talk-Is-Cheap | python/hayate/helpers/settings.py | Python | mit | 82 | 0 | # -*- coding:utf-8 -*-
# install | ed helper | list
INSTALLED_HELPERS = (
'dc',
)
|
RPGroup-PBoC/gist_pboc_2017 | code/gaussian_trap_stiffness.py | Python | mit | 3,972 | 0.003275 | # Import the necessary modules.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.optimize
import glob
import skimage.io
import skimage.morphology
import scipy.constants
# Define functions from Justin Bois
# Fit symmetric Gaussian to x, y, z data
def fit_gaussian(x, y, z):
"""
... | Return x-y position
ret | urn np.array([peak_i + i_subpix, peak_j + j_subpix])
# Load the images.
g = 'data/optical_tweezer/trapped_bead_5.2x_4_MMStack_Pos0.ome.tif'
im = skimage.io.imread(g)
# We will use the nine-point estimate (as is typically done)
selem = skimage.morphology.square(3)
# Loop through and find centers
centers = []
length... |
commonsense/conceptnet | maint/fix_concept_counts.py | Python | gpl-2.0 | 546 | 0.007326 | #!/usr/bin/env python
'''
Concepts keep track o | f their number of words. Or, they should.
'''
from csc.util.batch import queryset_foreach
from csc.conceptnet4.models import Concept
from django.db.models.query import Q
def fix_concept_counts():
def fix_concept(concept):
if concept.words: return
concept.words = len(concept.text.split())
c... |
fix_concept_counts()
|
HenriWahl/checkmk-agent-plugin-yum | lib/python3/cmk/base/cee/plugins/bakery/yum.py | Python | gpl-2.0 | 445 | 0.004494 | #!/usr/bin/env python3
# -*- encoding: utf-8; py-indent-offset: 4 -*-
from pathlib import Path
from typing import Any, Dict
from .bakery_api.v1 | import FileGenerator, OS, Plugin, register
def get_yum_files(conf: Dict[str, Any]) -> FileGenerator:
yield Plugin(base_os=OS.LINUX,
source=Path("yum"),
interval=conf.get("interval"))
register.bakery_plugin(
name="yum",
files_function=get_yum_fil | es,
)
|
PeterPetrik/QGIS | python/core/auto_additions/qgsannotationitemeditoperation.py | Python | gpl-2.0 | 921 | 0.004343 | # The following has been generated automatically from src/core/annotations/qgsan | notationitemeditoperation.h
# monkey patching scoped based enum
QgsAbstractAnnotationItemEditOperation.Type.MoveNode.__doc__ = "Move a node"
QgsAbstractAnnotationItemEditOperation.Type.DeleteNode.__doc__ = "Delete a node"
QgsAbstractAnnotationItemEditOperation.Type.AddNode.__doc__ = "Add a node"
QgsAbstractAnnotationIt... | .__doc__ = 'Operation type\n\n' + '* ``MoveNode``: ' + QgsAbstractAnnotationItemEditOperation.Type.MoveNode.__doc__ + '\n' + '* ``DeleteNode``: ' + QgsAbstractAnnotationItemEditOperation.Type.DeleteNode.__doc__ + '\n' + '* ``AddNode``: ' + QgsAbstractAnnotationItemEditOperation.Type.AddNode.__doc__ + '\n' + '* ``Transl... |
sunze/py_flask | venv/lib/python3.4/site-packages/celery/tests/utils/test_platforms.py | Python | mit | 23,623 | 0.000042 | from __future__ import absolute_import
import errno
import os
import sys
import signal
from celery import _find_option_with_arg
from celery import platforms
from celery.five import open_fqdn
from celery.platforms import (
get_fdmax,
ignore_errno,
set_process_title,
signals,
maybe_drop_privileges,
... | douts, mock_open, patch,
)
class test_find_option_with_arg(Case):
def test_long_opt(self):
self.assertEqual(
_find_op | tion_with_arg(['--foo=bar'], long_opts=['--foo']),
'bar'
)
def test_short_opt(self):
self.assertEqual(
_find_option_with_arg(['-f', 'bar'], short_opts=['-f']),
'bar'
)
class test_close_open_fds(Case):
def test_closes(self):
with patch('os.c... |
ratoaq2/Flexget | tests/test_sort_by.py | Python | mit | 2,714 | 0.004422 | from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase
class TestSortBy(FlexGetBase):
__yaml__ = """
tasks:
test1:
sort_by: title
mock:
- {title: 'B C D', url: 'http://localhost/1'}
- {title: 'A B C', ... | self.execute_task('test2')
assert self.task.entries[0]['title'] == 'B C D', 'Entries sorted alphabetically by title'
assert self.task.entries[1]['title'] == 'A P E', 'Entries sorted alphab | etically by title'
assert self.task.entries[2]['title'] == 'A B C', 'Entries sorted alphabetically by title'
def test_sort_by_reverse(self):
self.execute_task('test3')
assert self.task.entries[0]['title'] == 'A P E', 'Entries sorted alphabetically by title'
assert self.task.entries[... |
ntt-pf-lab/openstack-dashboard | django-openstack/django_openstack/api.py | Python | apache-2.0 | 32,907 | 0.001246 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... | _class__))
raise AttributeError(attr)
def __getitem__(self, item):
try:
return self.__getattr__(item)
except AttributeError, e:
# caller is expecting a KeyError
r | aise KeyError(e)
def get(self, item, default=None):
try:
return self.__getattr__(item)
except AttributeError:
return default
class Container(APIResourceWrapper):
"""Simple wrapper around cloudfiles.container.Container"""
_attrs = ['name']
class Console(APIResourc... |
jakesyl/fail2ban | fail2ban/tests/files/action.d/action_errors.py | Python | gpl-2.0 | 378 | 0.005291 |
from fail2ban.server.action import ActionBase
class TestAction(ActionBase):
def __init__(self, jail, name):
super(TestAction, self).__init__(jail, name)
def start(self):
raise Exception()
def stop(self):
raise Exception()
def ban(self | ):
raise Exception()
def unban(self):
raise Exception()
Action = TestActi | on
|
c0710204/mirrorsBistu | pypi/bandersnatch/lib/python2.7/site-packages/setuptools/ssl_support.py | Python | mit | 7,288 | 0.003019 | import sys, os, socket, atexit, re
import pkg_resources
from pkg_resources import ResolutionError, ExtractionError
from setuptools.compat import urllib2
try:
import ssl
except ImportError:
ssl = None
__all__ = [
'VerifyingHTTPSHandler', 'find_ca_bundle', 'is_available', 'cert_paths',
'opener_for'
]
c... | r("getaddrinfo returns an empty list")
try:
from ssl import Certific | ateError, match_hostname
except ImportError:
class CertificateError(ValueError):
pass
def _dnsname_to_pat(dn):
pats = []
for frag in dn.split(r'.'):
if frag == '*':
# When '*' is a fragment by itself, it matches a non-empty dotless
# fragment.... |
Innovailable/pypwrctrl | pypwrctrl/__init__.py | Python | gpl-3.0 | 61 | 0 | fro | m pypwrctrl.pypwrctrl import Plug, PlugDevice, PlugMa | ster
|
fernandog/Medusa | ext/sqlalchemy/dialects/mssql/__init__.py | Python | gpl-3.0 | 1,074 | 0 | # mssql/__init__.py
# Copyright (C) 2005-2018 the SQLAlchemy authors and contributors
# <see AUTHORS file> |
#
# This module is part of SQLAlchemy and is released under
# the MIT | License: http://www.opensource.org/licenses/mit-license.php
from . import base, pyodbc, adodbapi, pymssql, zxjdbc, mxodbc # noqa
from .base import \
INTEGER, BIGINT, SMALLINT, TINYINT, VARCHAR, NVARCHAR, CHAR, \
NCHAR, TEXT, NTEXT, DECIMAL, NUMERIC, FLOAT, DATETIME,\
DATETIME2, DATETIMEOFFSET, DATE, TIME... |
LoveBootCaptain/WeatherPi | WeatherPi.py | Python | mit | 1,346 | 0.000743 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from multiprocessing import Process
import os
from Modules.Update import Update
from Modules.UpdateLog import UpdateLog
from Modules.UpdateUnicorn import UniCorn, UpdateIcon
from Modules.init_unicorn import unicorn_init
from Modules.update_matrix import *
processes_bar = | []
def quit_all():
for thread in threads:
thread.cancel()
thread.join()
def main():
main_thread = threading.Timer(THREADING_TIMER, main)
main_thread.start()
| threads.append(main_thread)
try:
Update().update_json()
UpdateLog().create_log()
update_matrix()
p = Process(target=update_bargraph)
for process in processes_bar:
process.terminate()
p.start()
processes_bar.append(p)
UpdateIcon(... |
markboots/peg | celeryconfig.py | Python | gpl-3.0 | 349 | 0.008596 | ## Broker settings.
BROKER_URL = "amqp://guest:guest@localhost:5672//"
# List of modules to import when celery starts.
CELERY_IMPORTS = ("pegCelery", )
## Using amqp also to send task state and results.
CELERY_RESULT_BACKEND | = "amqp"
# Settings required for PHP AMQP extension
CELERY_RESULT_SERIALIZER = "jso | n"
CELERY_TASK_RESULT_EXPIRES = None
|
bow/crimson | crimson/star.py | Python | bsd-3-clause | 3,822 | 0.000785 | """Parser for STAR Log.final.out file"""
# (c) 2015-2021 Wibowo Arindrarto <contact@arindrarto.dev>
import os
from typing import Any, Callable, Dict, Optional, TextIO, Tuple, Union
import click
from .utils import convert, get_handle, get_linesep
__all__ = ["parse"]
def _pct_convert(raw_str: str) -> Union[str, int... | of splices: Annotated (sjdb)": ("nSplicesAnnotated", | convert),
"Number of splices: GT/AG": ("nSplicesGTAG", convert),
"Number of splices: GC/AG": ("nSplicesGCAG", convert),
"Number of splices: AT/AC": ("nSplicesATAC", convert),
"Number of splices: Non-canonical": ("nSplicesNonCanonical", convert),
"Mismatch rate per base, %": ("rateMismatchPerBase", _... |
arruda/pyfuzzy | doc/mypydoc.py | Python | lgpl-3.0 | 7,131 | 0.002524 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
"""\
# Modifies the pydoc contained in Python to use the member function filelink
# for filelink generation, so it can be later overridden.
# See also http://bugs.python.org/issue902061
"""
#
# Copyright (C) 2009 Rene Liebscher
#
# This program is free software; you... | for key, value in data:
contents.append(self.document(value, key))
result = result + self.bigsection(
'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
if hasattr(object, '__author__'):
contents = self.markup(str(object.__author__), self.preforma... | fffff', '#7799ee', contents)
if hasattr(object, '__credits__'):
contents = self.markup(str(object.__credits__), self.preformat)
result = result + self.bigsection(
'Credits', '#ffffff', '#7799ee', contents)
return result
# --------------------------------------- ... |
woutdenolf/spectrocrunch | spectrocrunch/patch/pint.py | Python | mit | 829 | 0 | # -*- coding: utf-8 -*-
from __futu | re__ import absolute_import
from pint import UnitRegistry, errors
from pint.quantity import _Quantity
from pint.unit import _Unit
from pint.measurement import _Measurement
ureg = UnitRegistry()
# Because of unpickling:
class Quantity(_Quantity):
_REGISTRY = ureg
force_ndarray = False
class Unit(_Unit):
... | se
ureg.Quantity = Quantity
ureg.Unit = Unit
ureg.Measurement = Measurement
ureg.define("classical_electron_radius = e^2/(4*pi*m_e*epsilon_0*c^2) = r_e")
ureg.define("percent = 1e-2*count = %")
ureg.define(u"permille = 1e-3*count = \u2030")
ureg.define("ppm = 1e-6*count")
ureg.define("ppb = 1e-9*count")
ureg.define... |
curtisblack/R2D2 | LiPo.py | Python | mit | 745 | 0 | class LiPo:
def __init__(self, voltage, current, cells, capacity):
self.voltage = voltage
self.current = current
self.cells = cells
self.capacity = capacity
def ChargePercen | tage(self):
v = self.voltage.GetVoltage() / self.cells
percent = 100 * (v - 3.7) / (4.2 - 3.7)
return max(0, min(100, int(percent)))
def | IsLowVoltage(self):
return self.voltage.GetVoltage() < 3.7 * self.cells
def IsCriticalVoltage(self):
return self.voltage.GetVoltage() < 3.3 * self.cells
def TimeRemaining(self):
p = self.ChargePercentage()
capacity = self.capacity * (p / 100.0)
A = self.current.GetCurr... |
annarev/tensorflow | tensorflow/compiler/mlir/tfr/define_op_template.py | Python | apache-2.0 | 2,013 | 0.003477 | # Copyright 2020 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... | AGS.output.endswith('.mlir')
generated_code = tfr_gen_from_module(sys.modules[__name_ | _], '_composite_')
dirname = os.path.dirname(FLAGS.output)
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(FLAGS.output, 'w') as f:
f.write(generated_code)
if __name__ == '__main__':
app.run(main=main)
|
klen/python-scss | scss/__init__.py | Python | lgpl-3.0 | 9,536 | 0.000419 | #!/usr/bin/env python
""" Python SCSS parser. """
import operator
from . import compat
VERSION_INFO = (0, 8, 73)
__project__ = "scss"
__version__ = "0.8.73"
__author__ = "Kirill Klenov <horneds@gmail.com>"
__license__ = "GNU LGPL"
CONV = {
'size': {
'em': 13.0,
'px': 1.0},
'length': {
... | 'table': 'table', 'list-item': 'li', 'table-row-group': 'tbody',
'table-header-group': 'thead', 'table-footer-group': 'tfoot', 'table-row':
'tr', 'table-cell': 'td, th', }
COLORS = {
'aliceblue': '#f0f8ff',
'antiquewhite': '#faebd7',
'aqua': '#00ffff' | ,
'aquamarine': '#7fffd4',
'azure': '#f0ffff',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'black': '#000000',
'blanchedalmond': '#ffebcd',
'blue': '#0000ff',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'burlywood': '#deb887',
'cadetblue': '#5f9ea0',
'chartreuse': '#7fff00'... |
prestontimmons/project-15053 | project_15053/urls.py | Python | mit | 1,935 | 0.002584 | from django.conf.urls import url
from django.shortcuts import render
from django.template.response import TemplateResponse
def syntax_error(request):
return TemplateResponse(
request, "syntax.html", {"coconuts": lambda: 42 / 0},
)
def template_strings(request):
return TemplateResponse(
r... | plate_name="jinja-syntax-error.html")),
url(r'^jinja-syntax-error2/$', render, dict(template_name="jinja-syntax-error2.html")),
url(r'^loop1/$', render, dict(template_name="loop1.html")),
url(r'^self/$', render, dict(template_name="self.html")),
url(r'^cached-extend/$', render, dict(template_name="c1.ht... | ax_error),
url(r'^syntax2/$', render, dict(template_name="syntax2.html")),
url(r'^unicode/$', unicode_error),
url(r'^tagparse/$', render, dict(template_name="bad-parse.html")),
url(r'^tagparsecached/$', render, dict(template_name="bad-parse-cached.html")),
url(r'^template-strings/$', template_string... |
largelymfs/w2vtools | build/scipy/setup.py | Python | mit | 7,514 | 0.005856 | #!/usr/bin/env python
"""SciPy: Scientific Library for Python
SciPy (pronounced "Sigh Pie") is open-source software for mathematics,
science, and engineering. The SciPy library
depends on NumPy, which provides convenient and fast N-dimensional
array manipulation. The SciPy library is built to work with NumPy
arrays, a... | os.path.join(cwd, 'tools', 'cythonize.py'),
'scipy'],
cwd=cwd)
if p != 0:
raise RuntimeError("Running cythonize failed!")
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
... | ,
delegate_options_to_subpackages=True,
quiet=True)
config.add_subpackage('scipy')
config.add_data_files(('scipy','*.txt'))
config.get_version('scipy/version.py')
return config
def setup_package():
# Rewrite the version file every time
write_ver... |
stephankramer/uptide | tests/test_tidal.py | Python | lgpl-3.0 | 1,855 | 0.000539 | import unittest
import uptide.tidal as ut
import datetime
import math
class TestTidal(unittest.TestCase):
"""Tests the uptide.tidal module (basic astronomical calculations)"""
def setUp(self):
# a random, insignificant date
self.date = datetime.datetime(1975, 10, 24, 1, 2, 3)
# I can s... | _omegas(self):
self.assertAlmostEqual(ut.omega['M2'], 0.0001405189)
# exactly twice a day:
self.assertAlmostEqual(ut.omega['S2'], 4*math.pi/864 | 00.)
self.assertAlmostEqual(ut.omega['SSA'], 3.9821275945895842e-07)
if __name__ == '__main__':
unittest.main()
|
yudingding6197/fin_script | gainian_bk_change.py | Python | gpl-2.0 | 3,018 | 0.045272 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import os
import datetime
import json
import getopt
import codecs
from internal.trade_date import *
from internal.url_dfcf.dc_hq_push import *
def cmp_gn_bk(cmpList, bk_id):
cmpLen = len(cmpList)
for idx in range(0, cmpLen):
if cmpList[idx]['f12']!=bk_id:
| continue
#print idx, cmpList[idx]
cmpList.pop(idx)
break
#print len(cmpList)
return
def check_quit_bk(trade_date):
cmp_date='2021-08-05'
cmp_fp='../data/entry/gainian/' + cmp_date[0:4] + '/gnbk_' + cmp_date + '.txt'
file = open(cmp_fp, 'r')
cmpObj = json.load(file)
file.close()
cur_fp='../data/entry/g... | ange(0, len(curObj['data']['diff'])):
#print idx, curObj['data']['diff'][idx]['f12']
cmp_gn_bk(cmpList, curObj['data']['diff'][idx]['f12'])
print "Left data", len(cmpList)
for i in range(0, len(cmpList)):
print cmpList[i]['f12'], cmpList[i]['f14']
#Quit 从概念板块中退出的BK
def handle_argument():
optlist, args = ge... |
AwesomeTurtle/personfinder | tests/server_test_cases/import_tests.py | Python | apache-2.0 | 11,780 | 0.001188 | #!/usr/bin/python2.7
# encoding: utf-8
# Copyright 2010 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 ... | form = doc.cssselect('form')[-1]
doc = self.s.submit(form, key='test_key', content=open(self.filename))
assert 'Note records Imported 1 of 1' in re.sub('\\s+', ' ', doc.text)
assert Note.all().count() == 1
note = Note.all().get()
assert | note.record_id == 'test.google.com/note1'
assert note.person_record_id == 'test.google.com/person1'
assert note.author_name == '_test_author_name'
assert note.source_date == datetime.datetime(2013, 2, 26, 9, 10, 0)
assert note.status == 'believed_alive'
assert Person.all().coun... |
ahmad88me/tada | tadacode/tadaa/urls.py | Python | mit | 1,340 | 0.002239 | from django.conf.urls import patterns, include, url
from django.contrib import admin
import views
urlpatterns = patterns('',
url(r'^add_model_abox', 'tadaa.views.add_model_abox'),
url(r'^add_model', 'tadaa.views.add_model'),
url(r'^list_models', 'tadaa.views.list_models', name='list_models'),
url(r'^ab... | _view()),
url(r'^view_classes_stat', views. | online_annotation_entity_stat),
url(r'^view_annotation_stat', views.online_annotation_annotation_stat),
url(r'^view_annotation', views.view_annotation),
url(r'^list_annotations', views.list_annotations),
url(r'^annotation_results', views.annotation_results),
url(r'^advanced_annotation', views.advanc... |
airbnb/airflow | airflow/providers/google/cloud/example_dags/example_cloud_memorystore.py | Python | apache-2.0 | 13,040 | 0.001687 | #
# 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... | ator,
)
from airflow.providers.google.cloud.operators.gcs import GCSBucketCreateAclEntryOperator
from airflow.utils import dates
GCP_PROJECT_ID = os.environ.get("GCP_PROJECT_ID", "example-project")
MEMORYSTORE_REDIS_INSTANCE_NAME = os.environ.get("GCP_MEMORYSTORE_INSTANCE_NAME", "test-memorystoreredis-")
MEMORYSTORE_... | memorystore-redis-2"
)
MEMORYSTORE_REDIS_INSTANCE_NAME_3 = os.environ.get(
"GCP_MEMORYSTORE_INSTANCE_NAME3", "test-memorystore-redis-3"
)
MEMORYSTORE_MEMCACHED_INSTANCE_NAME = os.environ.get(
"GCP_MEMORYSTORE_INSTANCE_NAME4", "test-memorystore-memcached-1"
)
EXPORT_GCS_URL = os.environ.get("GCP_MEMORYSTORE_EXP... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.