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 |
|---|---|---|---|---|---|---|---|---|
globz-eu/infrastructure | chef-repo/cookbooks/chef_server/files/chef_server_scripts/tests/helpers.py | Python | gpl-3.0 | 1,116 | 0.000896 | import os
import shutil
import stat
from tests.conf_tests import TEST_DIR
def make_test_dir():
os.makedirs(TEST_DIR, exist_ok=True)
def remove_test_dir():
for test_path in [TEST_DIR]:
if os.path.isdir(test_path):
try:
shutil.rmtree(test_path)
except Permission... | try:
shutil.rmtree(test_path)
except PermissionError:
for root, dirs, files in o | s.walk(test_path):
for name in dirs:
os.chmod(os.path.join(root, name), stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
shutil.rmtree(test_path)
else:
pass
class Alternate:
"""
returns elements in ret_list in sequence each... |
airbnb/superset | tests/queries/saved_queries/api_tests.py | Python | apache-2.0 | 22,536 | 0.000932 | # 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 u... | "order_direction": "asc",
}
uri = f"api/v1/saved_query/?q={prison.dumps(query_string)}"
rv = self.get_assert_metric(uri, "get_list")
assert rv.status_code == 200
@pytest.mark.usefixtures("create_saved_queries")
def test_get_list_filter_saved_query(self):
"""
... | all_queries = (
db.session.query(SavedQuery).filter(SavedQuery.label.ilike("%2%")).all()
)
self.login(username="admin")
query_string = {
"filters": [{"col": "label", "opr": "ct", "value": "2"}],
}
uri = f"api/v1/saved_query/?q={prison.dumps(query_string... |
cortesi/mitmproxy | mitmproxy/platform/pf.py | Python | mit | 1,021 | 0.004897 | import re
import sys
def lookup(address, port, s):
"""
Parse the pfctl state output s, to look up the destination host
matching the client (address, port).
Returns an (address, port) tuple, or None.
"""
# We may get an ipv4-mapped ip | v6 address here, e.g. ::ffff:127.0.0.1.
# Those still appear as "127.0.0.1" in the table, so we need to strip the prefix.
address = re.sub("^::ffff:(?=\d+.\d+.\d+.\d+$)", "", address)
s = s.decode()
spec = "%s:%s" % (address, port)
for i in s.split("\n"):
if "ESTABLISHED:ESTABLISHED" in i an... | s = i.split()
if len(s) > 4:
if sys.platform.startswith("freebsd"):
# strip parentheses for FreeBSD pfctl
s = s[3][1:-1].split(":")
else:
s = s[4].split(":")
if len(s) == 2:
... |
OCA/l10n-italy | l10n_it_vat_statement_split_payment/tests/test_vat_statement_split.py | Python | agpl-3.0 | 10,516 | 0.000856 | # Copyright 2015 Agile Business Group <http://www.agilebg.com>
# Copyright 2021 Lorenzo Battistini @ TAKOBI
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from datetime import datetime
from dateutil.rrule import MONTHLY
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
... | cls.a_recv = cls.account_model.create(
dict(
code="cust_acc",
name="customer account",
user_type_id=account_user_type.id,
| reconcile=True,
)
)
cls.a_sale = cls.env["account.account"].search(
[
(
"user_type_id",
"=",
cls.env.ref("account.data_account_type_revenue").id,
)
],
... |
simark/simulavr | regress/test_opcodes/test_RETI.py | Python | gpl-2.0 | 3,053 | 0.022601 | #! /usr/bin/env python
###############################################################################
#
# simulavr - A simulator for the Atmel AVR family of microcontrollers.
# Copyright (C) 2001, 2002 Theodore A. Roth
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of th... | is loaded from the stack and set the global interrupt flag
syntax: RETI
opcode is '1001 0101 0001 1000'
"""
def setup(self):
# set the pc to a different position
self.setup_regs[Reg.PC] = self.old_pc * 2
# put the value on the stack
self.setup_ | word_to_stack(self.new_pc)
# zero the SREG
self.setup_regs[Reg.SREG] = 0
return 0x9518
def analyze_results(self):
self.is_pc_checked = 1
self.reg_changed.extend( [ Reg.SP, Reg.SREG ] )
# check that SP changed correctly
expect = self.setup_regs[Reg.SP] + 2
got = self.anal_regs[Reg.SP]
if got ... |
micumatei/asciipic | asciipic/tasks/base.py | Python | mit | 2,066 | 0 | """Base class for Tasks."""
import abc
from oslo_log import log as logging
import six
import rq
from rq import Queue
f | rom asciipic.common import exception
from asciipic import config as asciipic_config
fro | m asciipic.common import tools
CONFIG = asciipic_config.CONFIG
LOG = logging.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta)
class BaseTask(object):
"""Base class for Tasks."""
@abc.abstractmethod
def _on_task_done(self, result):
"""What to execute after successfully finished processing a t... |
Diralf/evolution | app/entity/human/human.py | Python | mit | 295 | 0 | from app.entity.human.human_data impo | rt *
from core.entity.entity import *
class Human(Entity):
def __init__(self, human_data=None):
# type: (HumanData) -> None
Entity.__init__(self)
self.data = human_data or HumanData()
def update(self, delta):
pass
| |
kishori82/MetaPathways_Python.3.0 | libs/python_scripts/MetaPathways_rpkm.py | Python | mit | 16,444 | 0.024933 | #!/usr/bin/python
"""This script run the pathologic """
try:
import copy, optparse, sys, re, csv, traceback
from os import path, _exit, rename
import logging.handlers
from glob import glob
import multiprocessing
from libs.python_modules.utils.errorcodes import *
from libs.python_modules.utils.sy... | es abcd:
1. abcd.fastq : this means non-paired reads
| 2. abcd.b1.fastq : means only unpaired read from batch b1
3. abcd_1.fastq and abcd_2.fastq: this means paired reads for sample
4. abcd_1.fastq or abcd_2.fastq: this means only one end of a paired read
5. abcd_1.b2.fastq and abcd_2.b2.fastq: this m... |
niksolaz/TvApp | remembermyseries/settings.py | Python | mit | 2,156 | 0 | """
Django settings for remembermyseries project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR... | D_PROTO', 'https')
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.cont | rib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tvapp',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.Cs... |
angelapper/edx-platform | lms/djangoapps/lms_xblock/field_data.py | Python | agpl-3.0 | 1,403 | 0.001426 | """
:class:`~xblock.field_data.FieldData` subclasses used by the LMS
"""
from xblock.field_data import ReadOnlyF | ieldData, SplitFieldData
from xblock.fields import Scope
class LmsFieldData(SplitFieldData):
"""
A :class:`~xblock.field_data.FieldData` that
reads all UserScope.ONE and UserScope.ALL fields from `student_data`
and all UserScope.NONE fields from `authored_data`. It also prevents
writing to `author... | ed_data, LmsFieldData):
authored_data = authored_data._authored_data # pylint: disable=protected-access
else:
authored_data = ReadOnlyFieldData(authored_data)
self._authored_data = authored_data
self._student_data = student_data
super(LmsFieldData, self).__init... |
dcramer/sentry-old | tests/__init__.py | Python | bsd-3-clause | 1,088 | 0.003676 | import functools
import unittest2
from sentry import app
from sentry.db import get_backend
de | f with_settings(**settings):
def wrapped(func):
@functools.wraps(func)
def _wrapp | ed(*args, **kwargs):
defaults = {}
for k, v in settings.iteritems():
defaults[k] = app.config.get(k)
app.config[k] = v
try:
return func(*args, **kwargs)
finally:
for k, v in defaults.iteritems():
... |
ricardovandervlag/Project-2.1---Python | window.py | Python | gpl-3.0 | 947 | 0.004224 | """
hierin heb ik een poging gedaan om een klasse voor knoppen te maken (het is overigens niet echt gelukt)
"""
from tkinter import *
class Knoppen:
def bericht(self):
print("werkt dit?")
def tweede(self):
print("test")
def __init__(self, master):
beeld = Frame(master)
... | dow, width=300, heig | ht=250)
frame.bind("<Button-1>", leftClick)
frame.bind("<Button-2>", middleClick)
frame.bind("<Button-3>", rightClick)
frame.pack()
window.mainloop() |
tuxfux-hlp-notes/python-batches | archieves/batch-65/second.py | Python | gpl-3.0 | 171 | 0.011696 | #!/usr/bin/python
name = raw_input | ("please enter your name:")
address = raw_input("please enter your address:")
print "my | name is {} and i live in {}".format(name,address) |
urlist/urlist | motherbrain/tests/monitor.py | Python | gpl-3.0 | 3,107 | 0 | import unittest
import time
from motherbrain.workers.monitor import MBObjectMonitor, MBMonitorMixin
class TestMBObjectMonitor(unittest.TestCase):
def test_track(self):
mon = MBObjectMonitor()
mon.track('foo-event')
mon.track('bar-event')
mon.track('foo-event')
foo_count ... | self.mon = FakeObject()
def test_track(self):
mon | = self.mon
mon.track('foo-event')
mon.track('bar-event')
mon.track('foo-event')
foo_count = mon.events.get('foo-event').get('count')
bar_count = mon.events.get('bar-event').get('count')
self.assertEqual(foo_count, 2)
self.assertEqual(bar_count, 1)
def tes... |
leppa/home-assistant | homeassistant/components/geo_rss_events/sensor.py | Python | apache-2.0 | 5,338 | 0.001124 | """
Generic GeoRSS events service.
Retrieves current events (typically incidents or alerts) in GeoRSS format, and
shows information on events filtered by distance to the HA instance's location
and grouped by category.
For more details about this platform, please refer to the documentation at
https://home-assistant.io... | US,
CONF_UNIT_O | F_MEASUREMENT,
CONF_URL,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
ATTR_CATEGORY = "category"
ATTR_DISTANCE = "distance"
ATTR_TITLE = "title"
CONF_CATEGORIES = "categories"
DEFAULT_ICON = "mdi:alert"
DEFAULT_NAME ... |
asedunov/intellij-community | python/testData/override/circle_after.py | Python | apache-2.0 | 171 | 0.02924 | class Spam(Eggs):
def spam_methods(self):
pass
class Eggs(Spam):
def spam_methods(self):
super(Eggs, self).spam_methods()
def my_methods(sel | f):
pass
| |
pbmanis/acq4 | acq4/analysis/modules/STDPAnalyzer/STDPPlotsTemplate.py | Python | mit | 3,796 | 0.003952 | # -*- coding: utf-8 -*-
from __future__ import print_function
# F | orm implementation generated from reading ui file 'acq4/analysis/modules/STDPAnalyzer/STDPPlotsTemplate.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
de... | return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text,... |
WarwickAnimeSoc/aniMango | polls/migrations/0001_initial.py | Python | mit | 883 | 0.003398 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2018-08-08 19:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Option... | fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text=b'Enter name of poll', max_length=30)), |
],
),
]
|
hbp-unibi/SNABSuite | plot/histogram.py | Python | gpl-3.0 | 2,636 | 0.003035 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SNABSuite -- Spiking Neural Architecture Benchmark Suite
# Copyright (C) 2017 Christoph Jenzen
#
# 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 F... | rgument("-s", type=str, help="Name of the simulator", default="")
parser.add_argument("-t", type=str, help="Title of the plot", default="")
parser.add_argument("-b", help="Number of bins", default='auto')
parser.add_argument("-n", help="Normed histogram",
default=False, action="store_true")
args = ... | arse_args()
import numpy as np
import matplotlib.pyplot as plt
import os
from dim_labels import *
def histogram_plot(data, xlabel, title="", bins='auto', normed=False):
fig = plt.figure()
if bins != "auto":
plt.hist(data, bins=int(bins), density=normed, color='black',
histtype="bar", rw... |
garywu/pypedream | pypedream/__init__.py | Python | bsd-3-clause | 1,083 | 0.003693 | """
A framework for data processing and data preparation DAG (directed acyclic graph) pipelines.
The examples in the documentation assume
>>> from __future__ import print_function
if running pre Py3K, as well as
>>> from dagpype import *
"""
import types
from . import _cor | e
from . import _src
from . import _filt
from . import _ | snk
from . import _subgroup_filt
try:
from ._core import *
from ._src import *
from ._filt import *
from ._snk import *
from ._subgroup_filt import *
from ._csv_utils import *
except ValueError:
from _core import *
from _src import *
from _filt import *
from _snk import *
f... |
xyuanmu/XX-Net | python3.8.2/Lib/ctypes/test/test_funcptr.py | Python | bsd-2-clause | 4,026 | 0.003974 | import unittest
from ctypes import *
try:
WINFUNCTYPE
except NameError:
# fake to enable this test on Linux
WINFUNCTYPE = CFUNCTYPE
import _ctypes_test
lib = CDLL(_ctypes_test.__file__)
class CFuncPtrTestCase(unittest.TestCase):
def test_basic(self):
X = WINFUNCTYPE(c_int, c_int, c_int)
... | self.assertRaises(TypeError, c, 1, 2, 3)
self.assertEqual(c(1, 2, 3, 4, 5, 6), 3)
if not WINFUNCTYPE is CFUNCTYPE:
self.assertRaises(T | ypeError, s, 1, 2, 3)
def test_structures(self):
WNDPROC = WINFUNCTYPE(c_long, c_int, c_int, c_int, c_int)
def wndproc(hwnd, msg, wParam, lParam):
return hwnd + msg + wParam + lParam
HINSTANCE = c_int
HICON = c_int
HCURSOR = c_int
LPCTSTR = c_char_p
... |
ArcherSys/ArcherSys | Lib/test/test_pty.py | Python | mit | 33,998 | 0.003 | <<<<<<< HEAD
<<<<<<< HEAD
from test.support import verbose, run_unittest, import_module, reap_children
#Skip these tests if either fcntl or termios is not available
fcntl = import_module('fcntl')
import_module('termios')
import errno
import pty
import os
import sys
import select
import signal
import socket
import uni... | os._exit(4)
else:
debug("Waiting for child (%d) to finish." % pid)
# In verbose mode, we have to consume the debug output from the
# child or the child will block, causing this test to hang in the
# parent's | waitpid() call. The child blocks after a
# platform-dependent amount of data is written to its fd. On
# Linux 2.6, it's 4000 bytes and the child won't block, but on OS
# X even the small writes in the child above will block it. Also
# on Linux, the read() will raise a... |
charanpald/wallhack | wallhack/clusterexp/BoundExp2.py | Python | gpl-3.0 | 2,119 | 0.007079 | from cvxopt import matrix, solvers
from apgl.data.Standardiser import Standardiser
import numpy
"""
Let's test the massively complicated bound on the clustering error
"""
numpy.set_printoptions(suppress=True, linewidth=150)
numC1Examples = 50
numC2Examples = 50
d = 3
numpy.random.seed(21)
center1 = numpy.array([-1... | numpy.array([muC2]), 0, 0]
P = numpy.r_[P1, P2, P3, P4]
R1 = numpy.c_[0, 0.5 * numpy.array([f])]
R2 = numpy.c_[0.5 * numpy.array([f]).T, zero3]
R = numpy.r_[R1, R2]
S1 = numpy.r_[numpy.c_[-q, -0.5 *numpy.array([g])], numpy.c_[-0.5*numpy.array([g]).T, P]]
S2 = numpy.r_[numpy.c_[-1, numpy.array([zero4])], numpy.c_[nu... | y.c_[-1, -0.5 * numpy.array([h])], -0.5 * numpy.c_[numpy.array([h]).T, zero3]]
print(S1)
cvxc = matrix(R.flatten())
cvxG = [matrix(S1.flatten()).T]
#cvxG += [matrix(S2.flatten()).T]
#cvxG += [matrix(S3.flatten()).T]
#cvxG += [matrix(S4.flatten()).T]
cvxh = [matrix([0.0])]
#cvxh += [matrix([0.0])]
#cvxh += [matrix([... |
BostonA/SpudnikPi | Server.py | Python | apache-2.0 | 564 | 0.030142 | #import RPi.GPIO as GPIO
import time
def ToString (List): # Coverts List to String
return ''.join(List)
def Setup ():
def Wait ():
| reading_file=open('DataStore.txt', 'r')
lines=reading_file.readlines()
#print lines
GoodLine = lines[len(lines) - 1] #GoodLine is the last line of the file!
if len(lines) > len(oldLinesGood): # If there are more lines i | n the new one one was added. So then that line should be read
return True
else:
return False
OldGood = GoodLine # Resets Vars For comparison
oldLinesGood = lines
|
Yarrick13/hwasp | tests/asp/AllAnswerSets/tight/bug.learning.03.asp.test.py | Python | apache-2.0 | 599 | 0 | input = """
1 2 2 1 3 4
1 3 2 1 2 4
1 4 0 0
1 5 2 1 6 7
1 6 2 1 5 7
1 7 0 0
1 8 2 1 9 10
1 9 2 1 8 10
1 10 0 0
1 11 2 1 12 13
1 12 2 1 11 13
1 13 0 0
1 14 1 0 2
1 15 1 0 5
1 16 1 0 8
1 17 1 0 11
1 1 | 8 1 0 2
1 19 1 0 5
1 20 1 0 2
1 21 1 0 5
1 22 1 0 8
1 23 1 0 11
1 21 2 1 19 20
1 24 1 1 18
1 23 1 0 8
1 25 1 1 18
1 26 1 0 22
1 1 2 0 14 16
1 1 2 0 17 15
1 1 1 1 23
1 1 1 1 21
0
23 n
12 n_d
18 i
22 m
2 a
8 c
11 d
3 n_a
17 h
21 l
26 r
25 q
9 n_c
5 b
24 p
16 g
20 | k
15 f
14 e
19 j
6 n_b
0
B+
0
B-
1
0
1
"""
output = """
{a, n_b, n_c, d, e, h, i, k, l, n}
{n_a, b, c, n_d, f, g, j, l, m, n, p, q, r}
"""
|
amites/nedcompost_wordpress | fabsettings.py | Python | gpl-2.0 | 1,613 | 0.0031 | from os import path
try:
from lib.settings_build import Configure
except ImportError:
import sys
| from os.path import expanduser, join
sys.path.append(join(expanduser("~"), 'workspace/automation/launchy'))
from lib.settings_build import Configure
class | Default(Configure):
def __init__(self):
self.beta = False
self.local = False
self.project = 'nedcompost'
self.php = True
self.database_name = self.project
self.database_user = self.project
self.path_project_root = path.join('/mnt', self.pr... |
Kefkius/electrum-frc | gui/qt/history_widget.py | Python | gpl-3.0 | 765 | 0.001307 | from PyQt4.QtGui import *
from electrum_frc.i18n import _
class HistoryWidget(QTreeWidget):
def __init__(self, parent=No | ne):
QTreeWidget.__init__(self, parent)
self.setColumnCount(2)
self.setHeaderLabels([_("Amount"), _("To / From"), _("When")])
self.setIndentation(0)
def empty(self):
self.clear()
d | ef append(self, address, amount, date):
if address is None:
address = _("Unknown")
if amount is None:
amount = _("Unknown")
if date is None:
date = _("Unknown")
item = QTreeWidgetItem([amount, address, date])
if float(amount) < 0:
i... |
orlade/microsimmer | unit_tests/test_host/test_implant/TestWorker.py | Python | mit | 994 | 0.003018 | from unit_tests.util import *
from unit_tests.AmqpTestCase import AmqpTestCase
from host.implant.Worker import Worker
class TestWorker(AmqpTestCase):
"""
Tests the functionality of the Worker class to process AMQP messages.
"""
def __init__(self):
self.worker = None
def setup(self):
... | EUE: 0, TEST_RESULT_QUEUE: 0})
# def test_work(self):
# """
# Tests that a Worker can process a message and produce a result.
# """
# publish_message('Foo')
# publish_message('Bar')
# self.worker | .work()
# assert_queue_size({TEST_REQUEST_QUEUE: 0, TEST_RESULT_QUEUE: 2}) |
GeassDB/xunlei-lixian | lixian_plugins/commands/get_torrent.py | Python | mit | 1,302 | 0.025346 |
from lixian_plugins.api import command
from lixian_cli_parser import command_line_parser, command_line_option
from lixian_cli_parser import with_parser
from lixian_cli import parse_login
from lixian_commands.util import create_client
@command(name='get-torrent', usage='get .torrent by task id or info hash')
@command... | h(id)
elif re.match(r'\d+$', id):
import lixian_query
task = lixian_query.get_task_by_id(client, id)
id = task['bt_hash']
id = id.lower()
torrent = client.get_torrent_file_by_info_hash(id)
else:
raise NotImplementedError()
if args.rename:
import lixian_hash_bt
from lixian_encoding import d... | utf-8')).encode(default_encoding)
import re
name = re.sub(r'[\\/:*?"<>|]', '-', name)
else:
name = id
path = name + '.torrent'
print path
with open(path, 'wb') as output:
output.write(torrent)
|
KBIAnews/Podcasts | django-project/shows/admin.py | Python | mit | 719 | 0.008345 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admi | n
from .models import Show, Episode, Category, ShowCategory
# Create custom admins with inlines for categories
class ShowCategoryInline(admin.TabularInline):
model = Category.shows.through
class EpisodeInline(admin.TabularInline):
model = Episode
class ShowAdmin(admin.ModelAdmin):
inlines = [
| ShowCategoryInline,
EpisodeInline,
]
class CategoryAdmin(admin.ModelAdmin):
inlines = [
ShowCategoryInline,
]
exclude = ('shows',)
# Register your models here.
admin.site.register(Show, ShowAdmin)
admin.site.register(Episode)
admin.site.register(Category, CategoryAdmin) |
irvingprog/pilas | pilas/pilasversion.py | Python | lgpl-3.0 | 1,208 | 0.000835 | # -*- encoding: utf-8 -*-
# pilas engine - a video game framework.
#
# copyright 2010 - hugo ruscitti
# license: lgplv3 (see http://www.gnu.org/licenses/lgpl.html)
#
# website - http://www.pilas-engine.com.ar
'''
pilas.pilasverion
=================
Definición de la version actual de pilas y funciones para compararla... | - **0** si ``v0`` == ``v1``.
- **1** si ``v0`` > ``v1``.
:param v0: primer versión a comparar.
:type v0: str
:param v1: segunda versión a comparar.
| :type v1: str
"""
v0 = v0.split(".")
v1 = v1.split(".")
return -1 if v0 < v1 else 0 if v0 == 1 else 1
|
renoirb/browsercompat | webplatformcompat/urls.py | Python | mpl-2.0 | 1,187 | 0 | from django.conf.urls import include, patterns, url
from django.views.generic.base import RedirectView
from mdn.urls import mdn_urlpatterns
from webplatformcompat.routers import router
from .views import RequestView, ViewFeature
webplatformcompat_urlpatterns = patterns(
'',
url(r'^$', RequestView.as_view(
... | r'^about/', RequestView.as_view(
template_name='webplatformcompat/about.jinja2'),
name='about'),
url(r'^browse/', RequestView.as_view(
template_name='webplatformcompat/browse.jinja2'),
name='browse'),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_frame... | r$', RedirectView.as_view(
url='/importer/', permanent=False)),
url(r'^importer/', include(mdn_urlpatterns)),
url(r'^view_feature/(?P<feature_id>\d+)(.html)?$', ViewFeature.as_view(
template_name='webplatformcompat/feature.js.jinja2'),
name='view_feature'),
)
|
tiexinliu/odoo_addons | smile_module_record/__init__.py | Python | agpl-3.0 | 1,003 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014 Smile (<http://www.smile.fr>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Aff... | ublic License for more details.
#
# You shoul | d have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import models
import wizard
|
BlackHole/enigma2-1 | lib/python/Tools/HardwareInfo.py | Python | gpl-2.0 | 1,714 | 0.032089 | from boxbranding import getBoxType, getBrandOEM
from Components.About import about
class HardwareInfo:
device_name = None
device_version = None
def __init__(self):
if HardwareInfo.device_name is not None:
# print "using cached result"
return
HardwareInfo.device_name = "unknown"
try:
file = open("/pr... | detection to work properly"
print "----------------"
print "fallback to detect hardware via /proc/cpuinfo!!"
try:
rd = open("/proc/cpuinfo", "r").read()
if "Brcm4380 V4.2" in rd:
HardwareInfo.device_name = "dm8000"
print "dm8000 detected!"
elif "Brcm7401 V0.0" in rd:
HardwareInfo.de... | 00"
print "dm800 detected!"
elif "MIPS 4KEc V4.8" in rd:
HardwareInfo.device_name = "dm7025"
print "dm7025 detected!"
except:
pass
def get_device_name(self):
return HardwareInfo.device_name
def get_device_version(self):
return HardwareInfo.device_version
def has_hdmi(self):
return ... |
antoinecarme/sklearn2sql_heroku | tests/classification/digits/ws_digits_DummyClassifier_sqlite_code_gen.py | Python | bsd-3-clause | 137 | 0.014599 | from sklearn2sql_heroku.tests.classification im | port generic as class_gen
class_gen.test_model("DummyClassifier" , "di | gits" , "sqlite")
|
zhangxu273/JRQ-Order-Collector | JRQ Order Collector/Logger.py | Python | gpl-3.0 | 584 | 0.035959 | # coding=utf-8
import lo | gging
import datetime
import os
filename = datetime.datetime.now().strftime("%Y-%m-%d")
path = './{0}.log'.format(filename)
logger = logging.getLogger("loggingmodule.NomalLogger")
formatter = logging.Formatter("[%(levelname)s][%(funcName)s][%(asctime)s]%(message)s")
handler = logging.FileHandler(path)
handler.s... | logger.info(str)
def Error(str):
print(str)
logger.error(str)
|
jackton1/django_google_app | map_app/forms.py | Python | gpl-3.0 | 4,132 | 0 | from __future__ import absolute_import, unicode_literals
import logging
from django import forms
from django.contrib import messages
from django.http import Http404
from django.utils.encoding import smart_str
from easy_maps.models import Address
from . import lib
log = logging.getLogger(__name__)
class AddressFor... | ance:
part = "Successfully added a new "
message_ = "%s %s: %s" % (
part,
instance.__class__.__name__,
instance.address
)
if added_to_fusion_table:
... | on table: %s"
f_message_ = f_part % (
instance.__class__.__name__,
instance.address
)
log.info(f_message_)
messages.success(request, message_)
log.info(... |
GbalsaC/bitnamiP | venv/src/edx-milestones/milestones/management/commands/tests/__init__.py | Python | agpl-3.0 | 75 | 0 | """
Milestones management commands tests package initializati | on mod | ule
"""
|
thenetcircle/dino | dino/rest/resources/joins.py | Python | apache-2.0 | 2,089 | 0.000479 | import logging
from datetime import datetime
from flask import request
from dino import environ
from dino.exceptions import NoSuchRoomException
from dino.rest.resources.base import BaseResource
from dino.utils import b64d
from dino.utils.decorators import timeit
logger = logging.getLogger(__name__)
class JoinsInRo... | = self.validate_json(self.request, silent=False)
if not is_valid:
logger.error('invalid json: %s' % msg)
return dict()
logger.debug('GET request: %s | ' % str(json))
if 'room_ids' not in json and 'room_names' not in json:
return dict()
output = dict()
if 'room_ids' in json:
for room_id in json['room_ids']:
output[room_id] = self.do_get_with_params(room_id=room_id)
if 'room_names' in json:
... |
volpino/Yeps-EURAC | tools/sr_mapping/bowtie_wrapper_code.py | Python | mit | 507 | 0.005917 | import os
def exec_before_job(ap | p, inp_data, out_data, param_dict, tool):
try:
refFile = param_dict['refGenomeSource']['indices'].value
except:
try:
refFile = param_dict['refGenomeSource']['ownFile'].dbkey
except:
out_data['output'].set_dbkey('?')
| return
dbkey = os.path.split(refFile)[1].split('.')[0]
# deal with the one odd case
if dbkey.find('chrM') >= 0:
dbkey = 'equCab2'
out_data['output'].set_dbkey(dbkey)
|
macosforge/ccs-calendarserver | txweb2/dav/test/test_acl.py | Python | apache-2.0 | 15,068 | 0.001394 | ##
# Copyright (c) 2005-2017 Apple Inc. All rights reserved.
#
# 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, mod... | oing
# less so that they don't need a fres | h copy of this state.
if hasattr(self, "_docroot"):
rmdir(self._docroot)
del self._docroot
def test_COPY_MOVE_source(self):
"""
Verify source access controls during COPY and MOVE.
"""
def work():
dst_path = os.path.join(self.docroot, "copy... |
Aravinthu/odoo | odoo/tools/mail.py | Python | agpl-3.0 | 22,248 | 0.003731 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import collections
import logging
from lxml.html import clean
import random
import re
import socket
import threading
import time
from email.header import decode_header
from email.utils import getaddresses, formataddr
fr... | res_id', 'data-member_id', 'data-view-id'
])
class _Cleaner(clean.Cleaner):
_style_re = re.compile('''([\w-]+)\s*:\s*((?:[^;"']|"[^"]*"|'[^']*')+)''')
_style_whitelist = [
'font-size', 'font-family', 'font-weight', 'background-color', 'color', 'text-align',
'li | ne-height', 'letter-spacing', 'text-transform', 'text-decoration',
'padding', 'padding-top', 'padding-left', 'padding-bottom', 'padding-right',
'margin', 'margin-top', 'margin-left', 'margin-bottom', 'margin-right'
# box model
'border', 'border-color', 'border-radius', 'border-style', 'h... |
Archman/pandora | python/scripts/plotaw.py | Python | gpl-2.0 | 420 | 0.038095 | #!/usr/bin/env python
"""
plot magnetic lattice
"""
import matplotlib.pylab as plt
import numpy as np
f12 = 'AWDall. | lat'
data12 = | np.loadtxt(f12)
plt.plot(data12[:,0], data12[:,1], 'r-',
data12[:,0], data12[:,2], 'b-',
linewidth=2)
plt.xlim([110,240])
plt.ylim([1.5,1.53])
plt.legend([r'$a_u$',r'$a_d$'],1)
plt.xlabel(r'$z\,\mathrm{[m]}$',fontsize=18)
plt.ylabel(r'undulator parameter',fontsize=18)
plt.show()
|
gion86/awlsim | awlsim/core/labels.py | Python | gpl-2.0 | 2,248 | 0.024466 | # -*- coding: utf-8 -*-
#
# AWL simulator - labels
#
# Copyright 2012-2014 Michael Buesch <[email protected]>
#
# 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) 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 Public License fo | r 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 __future__ import division, absolute_import, print_function, unicode_literals
from a... |
sbarakat/graph-partitioning | graph_partitioning/scotch_partitioner.py | Python | mit | 10,772 | 0.003992 | import os
import sys
import numpy as np
import networkx as nx
import graph_partitioning.partitioners.utils as putils
import graph_partitioning.partitioners.scotch.scotch as scotch
import graph_partitioning.partitioners.scotch.scotch_data as sdata
class ScotchPartitioner():
def __init__(self, lib_path, virtualNo... | # set the node weight
G.node[node_indeces[node]]['weight'] = graph.node[node]['weight']
except Exception as err:
pass
# STEP 2: add virtual nodes, if enabled and required
# if there are edgeless nodes, then we need virtu | al nodes - this may actually not be needed
requires_virtual = self._requiresVirtualNodes(graph)
virtual_nodes = []
if requires_virtual:
# add virtual nodes to the new graph G
virtual_nodes = self._createVirtualNodes(G, num_partitions)
# STEP 3: add edges & weight... |
skawouter/piwall-ffmpeg-scenegenerator | vatypes.py | Python | gpl-3.0 | 1,444 | 0.004848 | class VideoFile(object):
def __init__(self, filename, position='random', vtype='file', startat=0):
self.filename = filename
self.position = str(position)
self.vtype = vtype
self.startat = startat
def get_input_line(self):
if self.vtype == 'file':
if self.star... | self.vtype == 'testimage':
return ' -f lavfi -i testsrc '
if self.vtype == 'black':
return ' -f lavfi -i color=black'
if self.vtype =='concat':
return ' -i "concat:' + self.filename+ '" '
def __repr__(self):
return '[{0}:: {1}]'.format(self.filename, se... | def get_input_line(self):
if self.vtype == 'file':
return ' -i {0}'.format(self.filename)
if self.vtype == 'noise':
return ' -ar 48000 -ac 2 -f s16le -i /dev/urandom '
if self.vtype == 'silence':
return ' -f lavfi -i aevalsrc=0 '
|
sryno/rynosm | topology_script/makeITP.py | Python | gpl-3.0 | 47,357 | 0.004392 | from __future__ import print_function
import argparse
import sys
from scipy import *
from scipy.sparse import *
__author__ = 'Sean M. Ryno'
__copyright__ = 'Copyright 2017, Sean M. Ryno'
__credits__ = 'Sean M. Ryno'
__license__ = 'GPL v3.0'
__version__ = '0.1'
__maintainer__ = 'Sean M. Ryno'
__email__ = ... | um, x, y, z = [], [], [], [], [], [], []
for line in fin:
if len(line.split()) > 3:
resNum.append(int(line[0:5].strip()))
name.append(line[5:10].strip())
atomType.append(line[10:15].strip())
atomNum.append(int(line[15:20].strip()))
x.append(... | .strip()))
z.append(float(line[36:44].strip()))
# elements.append(line[52:].strip())
return resNum, name, atomType, atomNum, x, y, z
def parseFF(itpFile):
itp = {}
fin = open(itpFile, 'r')
for line in fin:
if 'atomtypes' in line:
pass
e... |
riftadi/smallcorptools | sct_initdb.py | Python | mit | 11,668 | 0.02194 | #!/usr/bin/python
# by: Mohammad Riftadi <[email protected]>
# Testing Database instance for CPE Manager
from pymongo import MongoClient
import hashlib
client = MongoClient('mongodb://localhost:27017/')
dbh = client.jawdat_internal
#drop if collections exists
dbh.drop_collection("resetpass")
#drop if collections e... | "external",
"supervisor" : "[email protected]",
},
{
"username" : "[email protected]",
"secret" : has | hlib.md5("J@wdat12345").hexdigest(),
"first_login" : True,
"jawdat_id" : "023",
"roles" : ["staff"],
"fullname" : "Panji Harimurti",
"position" : "Tax and Accounting Staff",
"division" : "finance",
"supervisor" : "[email protected]",
},
{... |
hyperwd/hwcram | crontab/cron.py | Python | mit | 1,727 | 0.012739 | import os
import sys
import django
import datetime
from api.ecs_api import EcsApi
import log.log as log
from multiprocessing import Pool
from time import sleep
import subprocess
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,BASE_DIR)
os.environ.setdefault("DJANGO_SETTINGS_MOD... | e:
log.logging.error(e)
log.logging.error("Failed to update_token")
def cron_nginx():
retcode_nginx = subprocess.call("netstat -lnpt|grep nginx|grep -v grep",shell=True)
if retcode_nginx == 1:
subprocess.call("/usr/sbin/nginx",shell=True)
def cron_uwsgi():
retcode_uwsgi = sub | process.call("netstat -lnpt|grep uwsgi|grep -v grep",shell=True)
if retcode_uwsgi == 1:
subprocess.call("/usr/bin/uwsgi --ini /opt/hwcram/hwcram_uwsgi.ini -d /var/log/hwcram/uwsgi.log",shell=True)
def cron_celery():
retcode_celery = subprocess.call("ps -ef|grep '/usr/local/python3/bin/python3.6 -m cele... |
internetarchive/ias3 | s3path.py | Python | lgpl-2.1 | 1,384 | 0.000723 | """
Internet archive S3 web connector.
Copyright 2008-2010 Internet Archive.
Parts of this are derived from:
Python WebDAV Server.
Copyright (C) 1999 Christian Scholz ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GN... | .]+\.s3dns\.us\.archive\.org(:\d+)?$',
)
self.port = 82
self.pbconfig = self.petabox + "/etc/petabox-sw-config-u | s.xml"
|
chrismattmann/NLTKRest | nltkrest/nltkrest/server.py | Python | apache-2.0 | 4,079 | 0.006129 | #!/usr/bin/env python
# encoding: utf-8
#
# 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, Versi... | 8881.
-u, --units Enable parser to extract measurements from text
"""
Verbose = 0
Port = 8881 #default port
Units = 0
def echo2(*s): sys.stderr.write('server.py [NLTK]: ' + ' '.join(map(str, s)) + '\n')
app = Flask(__name__)
@app.route('/')
def status():
msg = '''
<html><hea | d><title>NLTK REST Server</title></head><body><h3>NLTK REST server</h3>
<p>This app exposes the Python <a href="http://nltk.org/">Natural Language Toolkit (NLTK)</a>
as a REST server.</p>
<h2>Status: Running</h2>
<p>More apps from the <a href="//irds.usc.edu/">USC Information Retrieval & Dat... |
hoangt/gem5v | src/mem/AddrMapper.py | Python | bsd-3-clause | 3,454 | 0.00029 | # Copyright (c) 2012 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality ... | # These two vectors should be the exact same length and each range
# should be the exact same size. Each range | in original_ranges is
# mapped to the corresponding element in the remapped_ranges. Note
# that the same range can occur multiple times in the remapped
# ranges for address aliasing.
original_ranges = VectorParam.AddrRange(
"Ranges of memory that should me remapped")
remapped_ranges = Vector... |
beaker-project/beaker-core-tasks | virt/install/py3/zrhel5_write_consolelogs.py | Python | gpl-2.0 | 18,072 | 0.005035 | #!/usr/bin/python3 -u
#
#
#
#################################################################################
# Start off by implementing a general purpose event loop for anyones use
#################################################################################
import sys
import atexit
import getopt
import os
impor... | self.cb = cb
self.opaque = opaque
def get_id(self):
return self.handle
def get_fd(self):
return self.fd
def get_events(self):
return self.events
def set_events(self, events):
self.events = events
def dispatch(sel... | s contains the data we need to track for a
# single periodic timer
class virEventLoopPureTimer:
def __init__(self, timer, interval, cb, opaque):
self.timer = timer
self.interval = interval
self.cb = cb
self.opaque = opaque
self.lastfired = 0
... |
Traviskn/django_starter_template | {{cookiecutter.project_name}}/{{cookiecutter.project_name}}/views.py | Python | mit | 101 | 0 | from django.shortcuts import render
def home(requ | est):
return r | ender(request, 'home.html', {})
|
daltonmenezes/learning-C | src/Python/format/thousands_separator.py | Python | mit | 72 | 0 | #!/usr/bin/env python
print " For | mated number:", "{:,}".for | mat(102403)
|
valmynd/MediaFetcher | src/plugins/youtube_dl/youtube_dl/extractor/charlierose.py | Python | gpl-3.0 | 1,554 | 0.027027 | from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import remove_end
class CharlieRoseIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?charlierose\.com/(?:video|episode)(?:s|/player)/(?P<id>\d+)'
_TESTS = [{
'url': 'https://charlierose.com/videos/27996',
'md5': 'fda41d49... | },
},
}, {
'url': 'https://charlierose.com/videos/27996',
'only_matching': True,
}, {
'u | rl': 'https://charlierose.com/episodes/30887?autoplay=true',
'only_matching': True,
}]
_PLAYER_BASE = 'https://charlierose.com/video/player/%s'
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(self._PLAYER_BASE % video_id, video_id)
title = remove_end(self._og_... |
newmediamedicine/indivo_server_1_0 | indivo/tests/integration/test_modules/messaging.py | Python | gpl-3.0 | 2,631 | 0.022045 | import data
PRD = 'prd'
from utils import *
def test_messaging(IndivoClient):
try:
BODY = 'body'
SUBJECT = 'subject'
MSG_ID = 'message_id'
SEVERITY = 'severity'
admin_client = IndivoClient(data.machine_app_email, data.machine_app_secret)
admin_client.set_app_id(data.app_email)
ac... | admin_client.set_record_owner(data=account_id)
admin_client.setup_app(record_id=record_id, app_id=data.app_email)
admin_client.message_record(data={SUBJECT : data.message01[SUBJECT],
BODY : data.message01[BODY],
| SEVERITY: data.message01[SEVERITY]},
message_id = data.message01[MSG_ID])
admin_client.message_account(account_id = account_id,
data= { SUBJECT : data.message02[SUBJECT],
BODY : ... |
facebookexperimental/eden | eden/hg-server/edenscm/mercurial/transaction.py | Python | gpl-2.0 | 25,993 | 0.000846 | # Portions Copyright (c) Facebook, Inc. and its affiliates.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2.
# transaction.py - simple journaling scheme for mercurial
#
# This transaction scheme is intended to gracefully handle program
# errors and int... | 't referenced in the changelog.
#
# Copyright 2005, 2006 Matt Mackall <[email protected]>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
from __future__ import absolute_import
import errno
import functools
from . import encoding,... | ld only be executed after the
# finalizers are done, since they rely on the output of the finalizers (like
# the changelog having been written).
postfinalizegenerators = {"bookmarks", "dirstate"}
gengroupall = "all"
gengroupprefinalize = "prefinalize"
gengrouppostfinalize = "postfinalize"
def active(func):
def _... |
skylifewww/pangolin-fog | product/migrations/0029_auto_20170213_1741.py | Python | mit | 681 | 0.001468 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-02-13 17:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations. | Migration):
dependencies = [
('product', '0028_product_related_title'),
]
operations = [
migrations.RemoveField(
model_name='menuitemproduct',
name='category',
),
migrations.AddField(
model_name='menuitemproduct',
name='catego... | lated_name='menuitem', related_query_name='menuit', to='product.Category', verbose_name='Category'),
),
]
|
samuelleeuwenburg/Samplate | event/models.py | Python | mit | 1,665 | 0.001201 | from __future__ import unicode_literals
from django.db import models
from django.core.paginator import Paginator, PageNotAnInteger
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailimages.edit_... | _length=250, blank=True)
intro = models.CharField(max_length=250, blank=True)
body = RichTextField(blank=True)
main_image = model | s.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
search_fields = Page.search_fields + (
index.SearchField('intro'),
index.SearchField('body'),
)
content_panels = Page.content_panels + [
... |
tperrier/mwachx | contacts/models/visit.py | Python | apache-2.0 | 9,392 | 0.012777 | #!/usr/bin/python
#Django Imports
from django.db import models
from django.db.models import Q
from django.conf import settings
#Python Imports
import datetime
#Local Imports
from utils.models import TimeStampedModel,ForUserQuerySet
import utils
class ScheduleQuerySet(ForUserQuerySet):
def pending(self,**kwargs... | condition = self.get_condition('attend')
message = self.participant.send_automated_message(send=send,send_base='visit',
condition=condition,exact=True)
def send_missed_visit_reminder(self,send=True,extra_kwargs=None):
today = utils.today()
schedu | led_date = self.scheduled
if self.no_sms or scheduled_date > today or self.status != 'pending':
# Don't send if scheduled date in the future or visit is not pending
return
if send is True and self.missed_sms_count < 2:
self.missed_sms_count += 1
self.miss... |
jamslevy/gsoc | tests/svn_helper_test.py | Python | apache-2.0 | 2,452 | 0.006933 | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | lient=self.client))
def testLsDirs(self):
"""Test if lsDirs() cont | ains only dir entries, using the SoC SVN repo.
"""
self.assert_(
'tests/' in svn_helper.lsDirs(
'http://soc.googlecode.com/svn/trunk', client=self.client))
self.assert_(
'svn_helper_test.py' not in svn_helper.lsDirs(
'http://soc.googlecode.com/svn/trunk... |
MichaelMGonzalez/MagneticFieldLocalization | Arduino/Odometer/Data/Plotter.py | Python | gpl-3.0 | 370 | 0.024324 | import csv
imp | ort sys
import numpy as np
import matplotlib.pyplot as plt
if len( sys.argv ) == 1:
print "Please enter the csv file you want to plot!"
sys.exit(0)
points = []
with open( sys.argv[1] ) as csvfile:
reader = csv.reader(csvfile)
points = [ int(c[1]) for c in reader]
print points
xs = range( len( points ... | show()
|
luoguizhou/gooderp_addons | report_docx/report/ir_report.py | Python | agpl-3.0 | 941 | 0.001064 | # -*- coding: utf-8 -*-
# © 2016 Elico Corp (www.elico-corp.com).
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from odoo import api, models
import re | port_docx
class IrActionReportDocx(models.Model):
_inherit = 'ir.actions.report.xml'
# @api.model
# def _check_selection_field_value(self, field, value):
# if field == 'report_type' and value == 'docx':
# return
#
# return super(IrActionReportDocx, self)._check_selection_f... | SELECT * FROM ir_act_report_xml WHERE report_name=%s", (name,))
r = self._cr.dictfetchone()
if r:
if r['report_type'] == 'docx':
return report_docx.ReportDocx('report.' + r['report_name'], r['model'], register=False)
return super(IrActionReportDocx, self)._lookup_rep... |
jeffery9/mixprint_addons | jasper_reports/JasperReports/RecordDataGenerator.py | Python | agpl-3.0 | 5,047 | 0.009709 | ##############################################################################
#
# Copyright (c) 2009 Albert Cervera i Areny <[email protected]>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting f... | r='"' )
header = {}
for field in fieldNames + ['']:
header[ field ] = field
writer.writerow( header )
error_reported_fields = []
for record in self.records:
row = {}
for field in record:
if fi... | OUND IN REPORT." % field
error_reported_fields.append( field )
continue
value = record.get(field, False)
if value==0.0:
value = 0.0
elif value == False:
value ... |
tao12345666333/app-turbo | demos/helloworld/store/actions.py | Python | apache-2.0 | 322 | 0.006211 | fr | om turbo.flux import Mutation, register, dispatch, register_dispatch
import mutation_types
@register_dispatch('user', mutation_types.INCREASE)
def increase(rank):
pass
def decrease(rank):
return dispatch('user', mutation_types.DECREASE, rank)
| @register_dispatch('metric', 'inc_qps')
def inc_qps():
pass |
shellphish/rex | rex/exploit/cgc/cgc_type1_exploit.py | Python | bsd-2-clause | 3,456 | 0.002025 | from .cgc_exploit import CGCExploit
from .c_templates import c_template_type1
import logging
l = logging.getLogger("rex.exploit.cgc.cgc_type1_exploit")
class CGCType1Exploit(CGCExploit):
'''
A CGC exploit object, offers more flexibility than an Exploit object for
the sake of the game. This should repres... | ([x.start for x in self._sorted_stdin_int_infos])
fmt_args["payload_int_bases"] = self._make_c_int_arr([x.base for x in self._sorted_stdin_int_infos])
fmt_args["payload_int_expected_lens"] = self._make_c_int_arr([x.size for x in self._sorted_stdin_int_infos])
fmt_args["recv_int_start_locations"]... | "] = self._make_c_int_arr([x.base for x in self._sorted_stdout_int_infos])
fmt_args["recv_int_expected_lens"] = self._make_c_int_arr([x.size for x in self._sorted_stdout_int_infos])
fmt_args["num_payload_ints"] = str(len(self._sorted_stdin_int_infos))
fmt_args["num_recv_ints"] = str(len(self._so... |
linyaoli/acm | others/hard/next_permutation.py | Python | gpl-2.0 | 1,207 | 0.006628 | """
6 8 7 4 3 2
1. from right to left, find the first element which violates the increasing order, marked as N.
2. from right to left, find the first element which is larger that N, marked as M.
3. swap N and M.
> 7 8 6 4 3 2
4. reverse all digits on the right of M.
> 7 2 3 4 6 8
"""
class Solution:
... | = len(num) - 1
while idx > 0:
if num[idx - 1] < num[idx]:
break
idx -= 1
# ..., find the 1st num which is larger than num[idx]
pn = len(num) - 1
if idx > 0:
idx -= 1
while pn >= 0 and num[pn] <= num[idx]:
... | ts on the right of idx .
r_num = num[idx:]
r_num.reverse()
return num[:idx] + r_num
sol = Solution()
print sol.nextPermutation([1,3,2])
|
OpenSPA/dvbapp | lib/python/Components/Lcd.py | Python | gpl-2.0 | 18,578 | 0.032189 | from boxbranding import getBoxType
from twisted.internet import threads
from enigma import eDBoxLCD, eTimer
from config import config, ConfigSubsection, ConfigSelection, ConfigSlider, ConfigYesNo, ConfigNothing
from Components.SystemInfo import SystemInfo
from Tools.Directories import fileExists
import usb
def IconC... | value = 63
eDBoxLCD.getInstance().setLCDContrast(value)
def setInverted(self, value):
if value:
value = 255
eDBoxLCD.getInstance().setInverted(value)
def setFlipped(self, value):
eDBoxLCD.getInstance().setFlipped(value)
def | setScreenShot(self, value):
eDBoxLCD.getInstance().setDump(value)
def isOled(self):
return eDBoxLCD.getInstance().isOled()
def setMode(self, value):
if fileExists("/proc/stb/lcd/show_symbols"):
print 'setLCDMode',value
f = open("/proc/stb/lcd/show_symbols", "w")
f.write(value)
f.close()
def setP... |
balopat/pyquil | pyquil/tests/test_quil.py | Python | apache-2.0 | 11,288 | 0.001772 | #!/usr/bin/python
##############################################################################
# Copyright 2016-2017 Rigetti Computing
#
# 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 ... | RE(0, Addr(1)))
assert p.out() == 'ME | ASURE 0 [1]\n' * 2
def test_construction_syntax():
p = Program().inst(X(0), Y(1), Z(0)).measure(0, 1)
assert p.out() == 'X 0\nY 1\nZ 0\nMEASURE 0 [1]\n'
p = Program().inst(X(0)).inst(Y(1)).measure(0, 1).inst(MEASURE(1, 2))
assert p.out() == 'X 0\nY 1\nMEASURE 0 [1]\nMEASURE 1 [2]\n'
p = Program().... |
arnef/airpi | server/server.py | Python | mit | 1,658 | 0.018094 | #!flask/bin/python
from flask import Flask, request
from flask_cors import cross_origin
import os
from subprocess import Popen, PIPE
app = Flask(__name__)
def play_video(url):
os.system('killall omxplayer.bin')
os.system('mkfifo /tmp/omx')
os.system('omxplayer -b "' + url + '" < /tmp/omx &')
os.system('echo ... | video ' + url)
@app.route('/', methods=['POST'])
@cross_origin()
def index():
if 'url' in request.json:
play_video(request.json['url'])
return 'default'
@app.route('/ping', methods=['GET'])
@cross_origin()
def ping():
return 'ok'
@app.route('/playing', methods=['GET'])
@cross_origin()
def playing():
p =... | id is not '':
return '{playing: true}'
else:
return '{playing: false}'
@app.route('/cmd', methods=['POST'])
@cross_origin()
def cmd():
if 'cmd' in request.json:
cmd = request.json['cmd']
if cmd == 'stop':
os.system('killall omxplayer.bin')
if cmd == '-30s':
os.system("echo -... |
SDM-OS/playlist | cherrymusicserver/sqlitecache.py | Python | gpl-3.0 | 32,587 | 0.00356 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# CherryMusic - a standalone music server
# Copyright (c) 2012 Tom Wallroth & Tilman Boerner
#
# Project page:
# http://fomori.org/cherrymusic/
# Sources on github:
# http://github.com/devsnd/cherrymusic/
#
# CherryMusic is based on
# jPlayer (GPL/MIT license) http://w... | der GNU GPL version 3 (or later)
#
# 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 version.
#
# This program is distributed in th... | e the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
#python 2.6+ backward compability
from __future__ import unicode_literals
import os
import re
import sqlite3
import sys
im... |
washort/zamboni | mkt/tvplace/tests/test_views.py | Python | bsd-3-clause | 2,926 | 0 | import json
from django.core.urlresolvers import reverse
from nose.tools import eq_, ok_
import mkt
from mkt.api.tests import BaseAPI
from mkt.api.tests.test_oauth import RestOAuth
from mkt.site.fixtures import fixture
from mkt.site.tests import ESTestCase, app_factory
from mkt.tvplace.serializers import (TVAppSeria... | ail, self).setUp()
Webapp.objects.get(pk=337141).addondevicetype_set.create(
device_type | =5)
self.url = reverse('tv-app-detail', kwargs={'pk': 337141})
def test_get(self):
res = self.client.get(self.url)
data = json.loads(res.content)
eq_(data['id'], 337141)
def test_get_slug(self):
Webapp.objects.get(pk=337141).update(app_slug='foo')
res = self.cli... |
jpopelka/fabric8-analytics-worker | f8a_worker/workers/dependency_parser.py | Python | gpl-3.0 | 16,342 | 0.002509 | """Output: List of direct and indirect dependencies."""
import re
import anymarkup
import itertools
from pathlib import Path
from tempfile import TemporaryDirectory
from f8a_worker.base import BaseTask
from f8a_worker.errors import TaskError
from f8a_worker.process import Git
from f8a_worker.utils import TimedCommand... | ndencies()
else:
return None
@staticmethod
def get_maven_dependencies(user_flow):
"""Get direct and indirect dependencies from pom.xml by using maven dependency tree plugin.
:return: set of direct and indirect dependencies
"""
output_file = P... | esolve(output_file)
cmd = ["mvn", "org.apache.maven.plugins:maven-dependency-plugin:3.0.2:tree",
"-DoutputType=dot",
"-DoutputFile={filename}".format(filename=output_file),
"-DappendOutput=true"]
GithubDependencyTreeTask.run_timed_command(cmd, output_file)
... |
mfassler/jaivis | jv/xmlReader.py | Python | gpl-2.0 | 41,125 | 0.009532 |
# Copyright 2009, Mark Fassler
# 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, version 2 of the License.
import logging
import vtk
from jv.jvPaths import *
import xml.etree.ElementTree as ET
... | def Texture(self, currentElement):
self.logger. | debug(' inside a <Texture> element: "%s"' % currentElement.get('name'))
texture = vtk.vtkTexture()
# Datatype(s) I need for input: ImageReader
ImageReaderNode = ''
for childElement in currentElement.getchildren():
if childElement.tag in vtkTypes['ImageReader']:
... |
bnzk/djangocms-misc | djangocms_misc/basic/middleware/redirect_subpage.py | Python | mit | 1,271 | 0.001574 | from django.shortcuts import redirect
class RedirectFirstSubpageMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the... | hild":
if getattr(request.current_page, 'get_child_pages', None):
subpages = request.current_page.get_child_pages()
else:
| subpages = request.current_page.children.all()
if len(subpages):
return redirect(subpages[0].get_absolute_url(), permanent=True)
return None
|
adfernandes/mbed | storage/filesystem/littlefsv2/littlefs/scripts/readblock.py | Python | apache-2.0 | 858 | 0.006993 | #!/usr/bin/env python3
import subprocess as sp
def main(args):
with open(args.disk, 'rb') as f:
f.seek(args.block * args.block_size)
block = (f.read(args.block_size)
.ljust(args.block_size, b'\xff'))
# what did you expect?
print("%-8s %-s" % ('off', 'data'))
return sp.run... | , '-g1', '-'], input=block).returncode
if __name__ == "__main__":
import argparse
import sys
parser = argparse.ArgumentParser(
description="Hex dump a specific block in a disk.")
parser.add_a | rgument('disk',
help="File representing the block device.")
parser.add_argument('block_size', type=lambda x: int(x, 0),
help="Size of a block in bytes.")
parser.add_argument('block', type=lambda x: int(x, 0),
help="Address of block to dump.")
sys.exit(main(parser.parse_args()))
|
ESOedX/edx-platform | openedx/core/djangoapps/content/course_overviews/admin.py | Python | agpl-3.0 | 2,543 | 0.001573 | """
Django admin page for CourseOverviews, t | he basic metadata about a course that
is used in user dashboard queries and other places where you need info like
name, and start dates, but don't actually need to crawl into course content.
"""
from __future__ import absolute_import
from config_models.admin import ConfigurationModelAdmin
from django.contrib import ad... | Simple, read-only list/search view of Course Overviews.
"""
list_display = [
'id',
'display_name',
'version',
'enrollment_start',
'enrollment_end',
'created',
'modified',
]
search_fields = ['id', 'display_name']
class CourseOverviewImageConfigA... |
tturpen/django-csaesrapp | apps/models.py | Python | bsd-2-clause | 30 | 0.033333 | " | ""Placeholder for testing. | """ |
atlarge-research/opendc-web-server | opendc/api/v1/specifications/cpus/id/endpoint.py | Python | mit | 747 | 0 | from opendc.models.cpu import CPU
from opendc.util import exceptions
from opendc.util.rest import Response
def GET(request):
"""Get the specs of a CPU."""
# Make sure required parameters are there
try:
request.check_required_parameters(
path={
| 'id': 'int'
}
)
except exceptions.ParameterError as e:
return Response(400, e.message)
# Instantiate a CPU and make sure it exists
cpu = CPU.from_primary_key((request.params_path['id'],))
if not cpu.exists():
return Response(404, '{} not found.'.format(... | rmat(cpu),
cpu.to_JSON()
)
|
town-hall-pinball/project-omega | pin/lib/dmd.py | Python | mit | 6,277 | 0.000637 | # Copyright (c) 2014 - 2016 townhallpinball.org
#
# 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, p... | ublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHE... |
MPIB/Lagerregal | devicedata/providers/opsi.py | Python | bsd-3-clause | 6,368 | 0.003612 | from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import gettext_lazy as _
from devicedata.providers.base_provider import BaseDeviceInfo
from devicedata.providers.base_provider import BaseProvider
from devicedata.providers.base_provider import DeviceIn... | ["ipAddress"]))
else:
formatted_controllers.append(
"{0} <span class='text-warning'>{1}<span>".format(controller["description"],
controller["ipAd | dress"]))
self.formatted_entries.append(FormattedDeviceInfoEntry(_("Network"), "<br />".join(formatted_controllers)))
def format_graphics(self):
entries = self.find_entries("VIDEO_CONTROLLER")
if len(entries) > 0:
self.formatted_entries.append(FormattedDeviceInfoEntry(_("Graphic... |
idekerlab/graph-services | services/ig_community/service/test/myservice.py | Python | mit | 1,621 | 0.001851 | import cxmate
import logging
import seaborn as sns
from Adapter import IgraphAdapter
from handlers import CommunityDetectionHandlers
logging.basicConfig(level=logging.DEBUG)
# Label for CXmate output
OUTPUT_LABEL = 'out_net'
# Community detection algorithm name
ALGORITHM_TYPE = 'type'
# Palette name
PALETTE_NAME =... | CI service for detecting communities in the given network data
| """
def __init__(self):
self.__handlers = CommunityDetectionHandlers()
def process(self, params, input_stream):
logging.debug(params)
algorithm_type = params[ALGORITHM_TYPE]
del params[ALGORITHM_TYPE]
palette = params[PALETTE_NAME]
del params[PALETTE_NAME]
... |
jameswilddev/WalkingSimulator | tools/blenderMSG.py | Python | mit | 2,526 | 0.013856 | bl_info = {
"name": "MSG",
"author": "jameswilddev",
"version": (0, 0, 0),
"blender": (2, 7, 0),
"location": "File > Export > MasSplat Geometry (.msg)",
"description": "Export triangles as MasSplat Geometry (.msg)",
"category": "Import-Export"
}
import bpy, struct, math, random
class ExportMSG(bpy.types... | invoke(self, context, event):
wm = context.window_manager
self.properties.filepath = ""
wm.fileselect_add(self)
return {"RUNNING_MODAL"}
def menu_func(self, context):
self.layout. | operator(ExportMSG.bl_idname, text="MasSplat Geometry (.msg)")
def register():
bpy.utils.register_class(ExportMSG)
bpy.types.INFO_MT_file_export.append(menu_func)
def unregister():
bpy.utils.unregister_class(ExportMSG)
bpy.types.INFO_MT_file_export.remove(menu_func)
if __name__ == "__main__":
register() |
chipaca/snapcraft | tests/spread/plugins/v1/python/snaps/python-pbr/python3/setup.py | Python | gpl-3.0 | 77 | 0 | from setuptools i | mport setup
setup(setup_requires=["p | br>=2.0.0"], pbr=True)
|
mancoast/cado-nfs | scripts/opal-test/report.py | Python | lgpl-2.1 | 8,520 | 0.003756 | #!/usr/bin/env python3
import sys
import re
from math import log, sqrt
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
RE_FP = r"[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?"
CAP_FP = "(%s)" % RE_FP
REGEXES = {"cap_fp" : CAP_FP}
PATTERN_SIEVE_SQ = re.compile(r"# Sieving... | 1.5
>>> n.add(2,3)
>>> n.get_value()
4.0
>>> x = n.interpolate_for_value(3.); 1.6457 < x < 1.6458
True
>>> 2.9999 < n.interpolate_at_coord(x) < 3.0001
True
"""
def __init__(self):
# At index 0, the most recent value | ,coordinate pair.
# At index 1, the value,coordinate pair before that.
self.lastvalue = [None, None]
self.lastcoord = [None, None]
self.sum = 0
def trapez_area(self):
""" Return area of the trapezoidal defined by the last two pairs of coordinates """
return (self.last... |
klausman/scion | python/topology/utils.py | Python | apache-2.0 | 2,247 | 0 | # Copyright 2018 ETH Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | buted 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 Lice | nse.
# Stdlib
import os
# External packages
import yaml
# SCION
from lib.util import write_file
from topology.common import ArgsBase
DOCKER_TESTER_CONF = 'testers-dc.yml'
class TesterGenArgs(ArgsBase):
pass
class TesterGenerator(object):
def __init__(self, args):
"""
:param TesterGenArgs a... |
luckyz/raspberry | dht11/dht11_examples/dht_log.py | Python | gpl-3.0 | 1,700 | 0.017647 | #!/usr/bin/python
# Internet de las Cosas - http://internetdelascosas.cl
#
# Descripcion : Programa que permite obtener la lectura de un sensor DHT11
# Lenguaje : Python
# Autor : Jose Zorrilla <[email protected]>
# Dependencias : Libreria de Adafruit https://github.com/adafruit/Adafruit_Python_DHT
# Web ... | de el sensor
humedad, temperatura = Adafruit_DHT.read_retry(sensor, pin)
# Si o | btiene una lectura del sensor la registra en el archivo log
if humedad is not None and temperatura is not None:
write_log("DHT Sensor - Temperatura: %s" % str(temperatura))
write_log("DHT Sensor - Humedad: %s" % str(humedad))
else:
write_log('Error al obtener la lectura del sensor')
# Duerme 10 segundo... |
harinarayan/litmus | rip/migrations/0005_auto_20141218_1306.py | Python | gpl-2.0 | 769 | 0.0013 | # -*- coding: u | tf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('rip', '0004_auto_20141218_1303'),
]
operations = [
migrations.AlterField(
... | 13, 6, 32, 429034, tzinfo=utc), max_length=10000),
preserve_default=False,
),
migrations.AlterField(
model_name='testcase',
name='input',
field=models.CharField(max_length=400000, null=True),
preserve_default=True,
),
]
|
galaxyfeeder/CodeSubmission | main/admin.py | Python | mit | 1,131 | 0.007958 | """
Copyright (c) 2016 Gabriel Esteban
Permis | sion 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, distribute, sublicense, | and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of
the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY O... |
Backfeed/backfeed-protocol | backfeed_protocol/models/__init__.py | Python | gpl-3.0 | 850 | 0.001176 | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
DBSession = scoped_session(sessionmaker())
Base = declarative_base()
def initialize_sql(engine):
from user import User # NOQA
from contract import Contract # NOQA
from evaluation import Eval... | **kw):
# DBSession.begin(subtransactions=True)
try:
ret = fn(*args, **kw)
DBSession.commit()
return ret
except:
DBS | ession.rollback()
raise
return go
|
vcelis/cs253 | lesson5/homework1/blog.py | Python | mit | 438 | 0.004566 | """
Udacity CS253 - Lesson 5 - Homework 1
"""
import webapp2, handlers
app = webapp2.WSGIApplication([
('/', handlers.Ho | mePage),
('/newpost', handlers.NewPostPage),
('/signup', handlers.SignupPage),
('/login', handlers.LoginPage),
('/logout', handlers.LogoutPage),
('/welcome', handlers.WelcomePage),
('/ | .json', handlers.JsonPage),
(r'/(\d+)\.json', handlers.JsonPage),
(r'/(\d+)', handlers.HomePage)
], debug=True) |
yarocoder/radwatch-analysis | Gamma_Reference.py | Python | mit | 4,730 | 0 | from utils import peak_measurement, background_subtract
from utils import absolute_efficiency, isotope_activity
import SPEFile
class ReferenceBase(object):
"""
Generates a reference object that contains a reference mass and
concentrations. Mass is in kg and concentrations are in percent for
K-40 and p... | gy in isotope.list_sig_g_e:
reference_peak = peak_measurement(reference, energy)
| background_peak = peak_measurement(background, energy)
reference_area = background_subtract(reference_peak,
background_peak,
reference.livetime,
background.live... |
Azure/azure-sdk-for-python | sdk/machinelearning/azure-mgmt-machinelearningservices/azure/mgmt/machinelearningservices/operations/_workspace_connections_operations.py | Python | mit | 16,366 | 0.004827 | # 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 ... | on
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.WorkspaceConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.... | ent_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.create.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", se |
tskisner/pytoast | src/python/tod/sim_det_noise.py | Python | bsd-2-clause | 6,740 | 0.000445 | # Copyright (c) 2015-2018 by the parties listed in the AUTHORS file.
# All rights reserved. Use of this source code is governed by
# a BSD-style license that can be found in the LICENSE file.
"""
sim_det_noise.py implements the noise simulation operator, OpSimNoise.
"""
import numpy as np
from ..op import Operator... | ng
super(). | __init__()
self._out = out
self._oversample = 2
self._realization = realization
self._component = component
self._noisekey = noise
self._rate = rate
self._altfft = altFFT
def exec(self, data):
"""
Generate noise timestreams.
This ite... |
LLNL/spack | var/spack/repos/builtin/packages/samrai/package.py | Python | lgpl-2.1 | 4,890 | 0.004499 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Samrai(AutotoolsPackage):
"""SAMRAI (Structured Adaptive Mesh Refinement Application Infra... | silo+mpi', when='+silo')
# don't build SAMRAI 3+ with tools with gcc
patch('no-tool-build.patch', when='@3.0.0:%gcc')
# 2.4.4 needs a lot of patches to fix ADL and performance problems
patch('https://github.com/IBAMR/IBAMR/releases/download/v0.3. | 0/ibamr-samrai-fixes.patch',
sha256='1d088b6cca41377747fa0ae8970440c20cb68988bbc34f9032d5a4e6aceede47',
when='@2.4.4')
def configure_args(self):
options = []
options.extend([
'--with-CXX=%s' % self.spec['mpi'].mpicxx,
'--with-CC=%s' % self.spec['mpi'].mp... |
sharadagarwal/autorest | AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/operations/header_operations.py | Python | mit | 5,835 | 0.001714 | # 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 ... | arameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.post(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if respo... | )
if raw:
client_raw_response = ClientRawResponse(None, response)
client_raw_response.add_headers({
'foo-request-id': 'str',
})
return client_raw_response
def custom_named_request_id_param_grouping(
self, header_custom_named_reque... |
anhstudios/swganh | data/scripts/templates/object/mobile/shared_dressed_fs_village_whip.py | Python | mit | 448 | 0.046875 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_fs_village_whip.iff"
result.attribute_template_id = 9
... | npc_name","human_base_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return | result |
VirusTotal/msticpy | msticpy/sectools/__init__.py | Python | mit | 788 | 0 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license informati | on.
# --------------------------------------------------------------------------
"""MSTIC Security Tools."""
# flake8: noqa: F403
# pylint: disable=W0401
from .iocextract import IoCExtract
from .geoip import GeoLiteLookup, IPStackLookup, geo_distance
from .tilookup import TILookup
from .vtlookup import VTL | ookup
from . import base64unpack as base64
from . import process_tree_utils as ptree
from .._version import VERSION
try:
from IPython import get_ipython
from . import sectools_magics
except ImportError as err:
pass
__version__ = VERSION
|
borg-project/borg | borg/unix/__init__.py | Python | mit | 68 | 0.014706 | from . import accounting
from | . import proc
from . import session | s
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.