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 |
|---|---|---|---|---|---|---|---|---|
joyxu/kernelci-backend | app/urls.py | Python | agpl-3.0 | 3,196 | 0 | # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be usefu... | handlers.version.VersionHandler, name="version"
)
_REPORT_URL = tornado.web.url(
r"/report[s]?/?(?P<id>.*)",
handlers.report.ReportHandler,
name="response"
)
_UPLOAD_URL = tornado.web. | url(
r"/upload/?(?P<path>.*)",
handlers.upload.UploadHandler,
name="upload"
)
_SEND_URL = tornado.web.url(
r"/send/?",
handlers.send.SendHandler,
name="send"
)
_TEST_SUITE_URL = tornado.web.url(
r"/test[s]?/suite[s]?/?(?P<id>.*)",
handlers.test_suite.TestSuiteHandler,
name="test-suit... |
8none1/bravialib | bravialib.py | Python | gpl-3.0 | 24,487 | 0.009474 | #!/usr/bin/python
#
# bravialib - Will Cooke - Whizzy Labs - @8none1
# http://www.whizzy.org
# Copyright Will Cooke 2016. Released under the GPL.
#
#
# My attempt to talk to the Sony Bravia web API.
#
# This is designed to be used by a long running process
# So there is a potentially slow start-up time but then it ... | )
else:
r = requests.get(url, headers=headers, cookies=cookies, auth=auth, timeout=timeout)
return r
def do_POST(self, url=None, payload=None, headers=None, auth=None, cookies=None, timeout=None):
if url is None: return False
if type(payload) is dict: payload = json.dump... | if headers is None: headers = self._JSON_HEADER # If you don't want any extra headers pass in ""
if cookies is None and self.cookies is not None: cookies=self.cookies
if self.x_auth_psk is not None: headers['X-Auth-PSK']=self.x_auth_psk
if timeout is None: timeout = self._TIMEOUT
... |
OxPython/Python_lists_reverse | src/reverse_lists.py | Python | epl-1.0 | 594 | 0.013514 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Jul 1, 2014
@author: anroco
I have | a list in python and I want to invest the elements, ie the latter is the
first, how I can do?
Tengo una lista en python y quiero invertir los elementos de la lista, es
decir que el último sea el primero, ¿como puedo hacerlo?
'''
#create a list
lista = [9, 2, 5, 10 | , 9, 1, 3]
print (lista)
#reverses the order of the list
lista.reverse()
print (lista)
#create a list
lista = ['abc', 'a', 'bcd', 'c', 'bb', 'abcd']
print (lista)
#reverses the order of the list
lista.reverse()
print (lista)
|
skg-net/ansible | lib/ansible/module_utils/network/edgeos/edgeos.py | Python | gpl-3.0 | 4,592 | 0.002395 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of | the module, and may assign their own license
# to the complete work.
#
# (c) 2018 Red Hat Inc.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copy | right
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS ... |
jeromecc/doctoctocbot | src/community/migrations/0005_auto_20191010_0838.py | Python | mpl-2.0 | 1,298 | 0.003082 | # Generated by Django 2.2.6 on 2019-10-10 08:38
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('community', '0004_auto_20191010_0837'),
]
operations = [
migrations.CreateModel(
name='Cooperat... | on_delete=django.db.models.deletion.CASCADE, related_name='cooperation_from', to='community.Community')),
('to_community', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cooperation_to', to='community.Community')),
],
options={
'uniqu... | migrations.AddField(
model_name='community',
name='cooperation',
field=models.ManyToManyField(related_name='cooperating_with', through='community.Cooperation', to='community.Community'),
),
]
|
googleapis/python-analytics-admin | samples/properties_user_links_batch_get.py | Python | apache-2.0 | 2,230 | 0.000897 | #!/usr/bin/env python
# Copyright 2021 Google LLC All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | e running the sample.
property_user_link_id = "YOUR-ACCOUNT-USER-LINK-ID"
batch_get_property_user_link(property_id, property_user_link_id)
def batch_get_property_user_link(property_id, property_user_link_id):
"""Retrieves details for the Google Analytics 4 property user link using a
batch call."""
... | rent=f"properties/{property_id}",
names=[f"properties/{property_id}/userLinks/{property_user_link_id}"],
)
)
print("Result:")
for user_link in response.user_links:
print(user_link)
print()
# [END analyticsadmin_properties_user_links_batch_get]
if __name__ == "__main_... |
chrisullyott/udacity-conference-central | conference.py | Python | apache-2.0 | 35,954 | 0.005618 | #!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
# ! - - - LIBRARIES - - - - - - - - - ... | ID = endpoints.API_EXPLORER_CLIENT_ID
MEMCACHE_ANNOUNCEMENTS_KEY = "RECENT_ANNOUNCEMENTS"
MEMCACHE_FSPEAKER_PREFIX = "featured-speaker-"
ANNOUNCEMENT_TPL = ('Last chance to attend! The following conferences '
'are nearly sold out: %s')
CONF_DEFAULTS = {
"city": "Default City",
"maxAttendees... | "topics": [ "Default", "Topic" ],
}
SESS_DEFAULTS = {
"typeOfSession": "lecture",
"duration": 90 # (90 minutes)
}
OPERATORS = {
'EQ': '=',
'GT': '>',
'GTEQ': '>=',
'LT': '<',
'LTEQ': '<=',
'NE': '!='
}
FIELDS = {
'CITY': 'city',
'TOPIC': 'topics',
'MONTH': 'mo... |
snim2/rcsp | _pytest/assertion/__init__.py | Python | gpl-2.0 | 4,366 | 0.003894 | """
support for presenting detailed information in failing assertions.
"""
import py
import sys
import pytest
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--assert', action="store", dest="ass... | gic", help="DEPRECATED equivalent to --assert=plain")
class AssertionState:
"""State for the assertion plugin."""
def __init__(self, config, mode) | :
self.mode = mode
self.trace = config.trace.root.get("assertion")
def pytest_configure(config):
mode = config.getvalue("assertmode")
if config.getvalue("noassert") or config.getvalue("nomagic"):
mode = "plain"
if mode == "rewrite":
try:
import ast
except... |
emilgaripov/emilgaripov.github.io | code_examples/python_with/with_sqlite3_conn_contextmanager.py | Python | mit | 403 | 0.004963 | import contextlib
import sqlite3
@contextlib.contextmanager
def sqlite3_connection(db_name):
connection = sqlite3.connect(db_name)
yield connection
connection.close()
with sqlite3_connection('dhcp_snooping.db') as conn:
for row in conn.exec | ute('select * from dhcp'):
print(row)
try | :
conn.execute('select * from dhcp')
except sqlite3.ProgrammingError as e:
print(e)
|
Weihonghao/ECM | Vpy34/lib/python3.5/site-packages/theano/gpuarray/reduction.py | Python | agpl-3.0 | 6,187 | 0.003233 | from __future__ import print_function, absolute_import, division
import os
import theano
from theano.gof import Op, Apply
from theano.gof.type import Generic
from .basic_ops import (infer_context_name, as_gpuarray_variable)
from .type import GpuArrayType
try:
import pygpu
except ImportError as e:
pass
class... | %(fail)s
}
if (%(name)s_input_ndim == 0) {
/* GpuArray_maxandargmax can't handle a 0-d array
* because it expects that 1 <= redux_len <= input_ndim.
* As input_ndim == 0, then 1 <= redux_len <= 0 is false.
| * To handle this case we copy input to max and we set argmax to 0.
*/
if (GA_NO_ERROR != GpuArray_setarray(&%(max)s->ga, &%(X)s->ga)) {
PyErr_SetString(PyExc_RuntimeError, "GpuMaxAndArgmax: unable to copy input to max when input is a scalar.");
%(fail)s
... |
danforthcenter/plantcv | plantcv/plantcv/median_blur.py | Python | mit | 1,066 | 0.002814 | # Median blur device
import os
from plantcv.plantcv._debug import _debug
from plantcv.plantcv | import params
from plantcv.plantcv import fatal_error
from scipy.ndimage.filters import median_filter
def median_blur(gray_img, ksize):
"""
Applies a median blur filter (applies median value to central pixel within a kernel size).
I | nputs:
gray_img = Grayscale image data
ksize = kernel size => integer or tuple, ksize x ksize box if integer, (n, m) size box if tuple
Returns:
img_mblur = blurred image
:param gray_img: numpy.ndarray
:param ksize: int or tuple
:return img_mblur: numpy.ndarray
"""
# Make sure ksi... |
kevin-coder/tensorflow-fork | tensorflow/contrib/optimizer_v2/momentum.py | Python | apache-2.0 | 4,934 | 0.002027 | # 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... | .dtype.base_dtype),
grad.values,
grad.indices,
state.get_hyper("momentum", var.dtype.base_dtype),
use_locking=self._use_locking,
use_nesterov=self._use_nesterov).op
def _resource_apply_sparse(self, grad, var, indices, state):
mom = state.get_slot(var, "momentum")
retur... | ,
state.get_hyper("learning_rate", var.dtype.base_dtype),
grad,
indices,
state.get_hyper("momentum", var.dtype.base_dtype),
use_locking=self._use_locking,
use_nesterov=self._use_nesterov)
|
mic4ael/indico | indico/__init__.py | Python | mit | 329 | 0 | # This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# | Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.mimetypes import register_custom_mimetypes
__version__ = '2. | 3-dev'
register_custom_mimetypes()
|
waltervh/BornAgain-tutorial | old/bornagain-python/fitting/advanced-tutorial/step4_rectangular_detector.py | Python | gpl-3.0 | 5,388 | 0.001114 | """
Simulation with rectangular detector. Pilatus-1M detector is used as an example.
Results will be compared against simulation with spherical detector. Example demonstrates,
that intensity simulated with spherical detector gets more and more close to the intensity of
rectangular detector, with increase of detector di... | detector_distance = 500.0 # in mm
pilatus_pixel_size = 0.172 # in mm
pilatus_npx, pilatus_npy = 981, 1043 # number of pixels
def get_sample():
"""
Returns a sample with cylindrical particles on a substrate.
"""
# defining materials
m_ambience = ba.HomogeneousMaterial("Air", 0.0, 0.0)
m_subs... | cles
edge = 40*nm
ff = ba.FormFactorBox(edge, edge, edge)
cylinder = ba.Particle(m_particle, ff)
particle_layout = ba.ParticleLayout()
particle_layout.addParticle(cylinder, 1.0)
air_layer = ba.Layer(m_ambience)
air_layer.addLayout(particle_layout)
substrate_layer = ba.Layer(m_substrate)... |
alfakini/python-mercadobitcoin | tests/__init__.py | Python | mit | 466 | 0.004292 | import os
impo | rt inspect
import vcr
def build_path(function):
return os.path.join(os.path.dirname(inspect.getfile(function)),
'cassettes',
function.__module__.split('.')[1],
function.__name__ + '.yml')
vcr = vcr.config.VCR(
func_path_generator=build_path... | esponse=True,
record_mode='once'
)
|
pspacek/freeipa | ipatests/test_webui/test_range.py | Python | gpl-3.0 | 2,865 | 0.000698 | # Authors:
# Petr Vobornik <pvoborni@redhat.com>
#
# Copyright (C) 2013 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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 ... | webui.task_range import range_tasks
ENT | ITY = 'idrange'
PKEY = 'itest-range'
class test_range(range_tasks):
@screenshot
def test_crud(self):
"""
Basic CRUD: range
"""
self.init_app()
self.get_shifts()
self.basic_crud(ENTITY, self.get_data(PKEY))
@screenshot
def test_types(self):
"""
... |
jcmgray/quijy | quimb/tensor/tensor_approx_spectral.py | Python | mit | 1,751 | 0 | """Approximating spectral functions with tensor networks.
"""
import numpy as np
import random
import quimb as qu
from .tensor_gen import MPO_rand, MPO_zeros_like
def construct_lanczos_tridiag_MPO(A, K, v0=None, initial_bond_dim=None,
beta_tol=1e-6, max_bond=None, seed=False,
... | bond = 8
if v0 is None:
if seed:
# needs to be truly random so MPI processes don't overlap
qu.seed_rand(random.SystemRandom().randint(0, 2**32 - 1))
| V = MPO_rand(A.nsites, initial_bond_dim,
phys_dim=A.phys_dim(), dtype=A.dtype)
else: # normalize
V = v0 / (v0.H @ v0)**0.5
Vm1 = MPO_zeros_like(V)
alpha = np.zeros(K + 1)
beta = np.zeros(K + 2)
bsz = A.phys_dim()**A.nsites
beta[1] = bsz # == sqrt(prod(A.shape))
... |
guillaume-chevalier/HAR-stacked-residual-bidir-LSTMs | sliding_window.py | Python | apache-2.0 | 3,228 | 0.009603 | # From: https://github.com/sussexwearlab/DeepConvLSTM
# Which is from http://www.johnvinyard.com/blog/?p=268
import numpy as np
from numpy.lib.stride_tricks import as_strided as ast
def norm_shape(shape):
'''
Normalize numpy array shapes so they're always expressed as a tuple,
even for one-dimensional sha... | e):
raise ValueError(\
'ws cannot be larger than a in any dimension.\
a.shape was %s and ws was %s' % (str(a.shape),str(ws)))
# how many slices | will there be in each dimension?
newshape = norm_shape(((shape - ws) // ss) + 1)
# the shape of the strided array will be the number of slices in each dimension
# plus the shape of the window (tuple addition)
newshape += norm_shape(ws)
# the strides tuple will be the array's strides multiplied by s... |
he7d3r/revscoring | revscoring/languages/features/regex_matches/__init__.py | Python | mit | 560 | 0 | """
Implements a feature set based off of a set of regexes applied to strings.
.. autoclass:: revscoring.languages.features.RegexMatches
:members:
:member-order: bysource
Supporting classes
------------------
.. au | toclass:: revscoring.languages.features.regex_matches.Revision
:members:
:member-order: bysource
.. autoclass:: revscoring.languages.features.regex_matches.Diff
:members:
:member-order: bysource
"""
from .features import Diff, | Revision
from .regex_matches import RegexMatches
__all__ = [RegexMatches, Revision, Diff]
|
googleapis/python-game-servers | samples/generated_samples/gameservices_v1_generated_game_server_deployments_service_update_game_server_deployment_async.py | Python | apache-2.0 | 1,658 | 0.001809 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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... | ncClient()
# Initialize request argument(s)
request = gaming_v1.UpdateGameServerDeploymentRequest(
)
# Make the request
operation = client.update_game_server_deployment(request=request)
print("Waiting for operation to complete...")
response = await operation.result()
# Handle the re... | [END gameservices_v1_generated_GameServerDeploymentsService_UpdateGameServerDeployment_async]
|
Nitr4x/whichCDN | utils/loader.py | Python | mit | 828 | 0.003623 | #!/usr/bin/env python
import imp
import os
PluginFolder = "./plugins"
MainModule = "__init__"
def getPlugins():
"""
List | the plugins located in the plugins folder.
"""
plugins = []
pluginList = os.listdir(PluginFolder)
for pluginName in pluginList:
location = os.path.join(PluginFolder, pluginName)
if not os.path.isdir(location) or not MainModule + ".py" in os.listdir(location):
continue
... | ins
def loadPlugin(plugin):
"""
Loads the specified plugin.
Parameters
----------
plugin : Plugin
Plugin to load
Return
------
The plugin loaded
"""
return imp.load_module(MainModule, *plugin["info"])
|
dfalt974/SickRage | tests/sickchill_tests/show/show_tests.py | Python | gpl-3.0 | 4,719 | 0.002755 | # coding=utf-8
# This file is part of SickChill.
#
# URL: https://sickchill.github.io
# Git: https://github.com/SickChill/SickChill.git
#
# SickChill is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either vers... | show456 = TestTVShow(0, 456)
show789 = TestTVShow(0, 789)
shows = [show123, show456, show789]
shows_duplicate = shows + shows
test_cases = {
(False, None): None,
(False, ''): None,
(False, '123'): None,
(False, 123): None,
(F... | e, 12.3): None,
(True, 456): show456,
(True, 789): show789,
}
unicode_test_cases = {
(False, ''): None,
(False, '123'): None,
(True, ''): None,
(True, '123'): None,
}
for tests in test_cases, unicode_test_cases:
... |
OCA/social | mail_outbound_static/models/ir_mail_server.py | Python | agpl-3.0 | 1,677 | 0.001789 | # Copyright 2017 LasLabs Inc.
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class IrMailServer(models.Model):
_inherit = "ir.mail_server"
smtp_from = fields.Char(
string="Email From", help="Set this in order to email from a specific addres... | @api.model
def send_email(
self, message, mail_server_id=None, smtp_server=None, | *args, **kwargs
):
# Replicate logic from core to get mail server
mail_server = None
if mail_server_id:
mail_server = self.sudo().browse(mail_server_id)
elif not smtp_server:
mail_server = self.sudo().search([], order="sequence", limit=1)
if mail_se... |
TheAltcoinBoard/XAB-withoutSecp256k1 | share/seeds/generate-seeds.py | Python | mit | 4,318 | 0.007874 | #!/usr/bin/python
# Copyright (c) 2014 Wladmir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... | be pasted into `src/chainparamsseeds.h`.
'''
from __future__ import print_function, division
from base64 import b32decode
from binascii import a2b_hex
import sys, os
import re
# ipv4 in ipv6 pre | fix
pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff])
# tor-specific ipv6 prefix
pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43])
def name_to_ipv6(addr):
if len(addr)>6 and addr.endswith('.onion'):
vchAddr = b32decode(addr[0:-6], True)
if len(vchAddr) != 16-len(pchOnio... |
glenngillen/dotfiles | .vscode/extensions/ms-python.python-2021.5.842923320/pythonFiles/lib/jedilsp/pydantic/tools.py | Python | mit | 2,169 | 0.001383 | import json
from functools import lru_cache
from pathlib import Path
from typing import Any, Callable, Optional, Type, TypeVar, Union
from .parse import Protocol, load_file, load_str_bytes
from .types import StrBytes
from .typing import display_as_type
__all__ = ('parse_file_as', 'parse_obj_as', 'parse_raw_as')
Name... | ame: Optional[NameFactory] = None) -> Any:
from pydantic.main import create_model
if type_name is None:
type_name = _generate_parsing_type_name
if not isinstance(type_name, str):
type_name = type_name(type_)
return create_model(type_name, __root__=(type_, ...))
T = TypeVar('T')
def ... | ional[NameFactory] = None) -> T:
model_type = _get_parsing_type(type_, type_name=type_name) # type: ignore[arg-type]
return model_type(__root__=obj).__root__
def parse_file_as(
type_: Type[T],
path: Union[str, Path],
*,
content_type: str = None,
encoding: str = 'utf8',
proto: Protocol... |
makinacorpus/geonode | src/GeoNodePy/geonode/maps/utils.py | Python | gpl-3.0 | 23,695 | 0.007132 | from itertools import cycle, izip
import logging
import re
from django.db import transaction
from django.utils.translation import ugettext as _
from django.contrib.auth.models import User
from geonode.maps.models import Map, Layer, MapLayer, Contact, ContactRole, Role, get_csw
from geonode.maps.gs_helpers import fixup_... | files['sld'] = matches[0]
elif len(matches) > 1:
msg = ('Multiple style files for %s exist; they need to be '
'distinct by spelling and not just case.') % filename
raise GeoNodeException(msg)
return files
def get_valid_name(layer_name):
"""Create a brand new name
"... | (r"(^[^a-zA-Z\._]+)|([^a-zA-Z\._0-9]+)")
name = xml_unsafe.sub("_", layer_name)
proposed_name = name
count = 1
while Layer.objects.filter(name=proposed_name).count() > 0:
proposed_name = "%s_%d" % (name, count)
count = count + 1
logger.info("Requested name already used; adjusting... |
izrik/tudor | persistence/in_memory/layer.py | Python | gpl-2.0 | 24,126 | 0 |
from itertools import islice
from numbers import Number
import logging_util
from models.object_types import ObjectTypes
from persistence.in_memory.models.attachment import Attachment
from persistence.in_memory.models.note import Note
from persistence.in_memory.models.option import Option
from persistence.in_memory.mo... | = object()
TASK_ID = object()
ORDER_NUM = object()
DEADLINE = object()
def create_all(self):
pass
def create_task(self, summary, description='', is_done=False,
is_deleted=False, deadline=None,
expected_duration_minutes=None, expected_cost=None,
... | ary=summary, description=description, is_done=is_done,
is_deleted=is_deleted, deadline=deadline,
expected_duration_minutes=expected_duration_minutes,
expected_cost=expected_cost, is_public=is_public,
lazy=lazy)
def get_task(self, task_... |
koery/win-sublime | Data/Packages/Package Control/package_control/clients/readme_client.py | Python | mit | 2,452 | 0.002447 | import re
import os
import base64
try:
# Python 3
from urllib.parse import urlencode
except (ImportError):
# Python 2
from urllib import urlencode
from .json_api_client import JSONApiClient
from ..downloaders.downloader_exception import DownloaderException
# Used to map file extensions to formats
_r... | me?%s' % (user_repo, query_string)
try:
info = self.fetch_json(readme_json_url, prefer_cached=True)
contents = base64.b64decode(info['content'])
except (ValueError) as e:
pass
if not contents:
| contents = self.fetch(url)
basename, ext = os.path.splitext(url)
format = 'txt'
ext = ext.lower()
if ext in _readme_formats:
format = _readme_formats[ext]
try:
contents = contents.decode('utf-8')
except (UnicodeDecodeError) as e:
con... |
Kerbas-ad-astra/KerbalStuff | alembic/versions/1d46e8d4483_add_mod_versioning.py | Python | mit | 786 | 0.010178 | """Add mod versioning
Revision ID: 1d46e8d4483
Revises: 2650a2191fe
Create Date: 2014-06-10 01:29:49.567535
"""
# revision identifiers, used by Alembic.
revision = ' | 1d46e8d4483'
down_revision = '2650a2191fe'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('mod', 'ksp_version')
op.drop_column('mod', 'keywords')
### end Alembic commands ###
def downgrade():
### commands ... | ('mod', sa.Column('ksp_version', sa.VARCHAR(length=16), autoincrement=False, nullable=True))
### end Alembic commands ###
|
sealhuang/brainDecodingToolbox | braincode/util/colorwheel.py | Python | bsd-3-clause | 1,122 | 0.004456 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import numpy as np
import matplotlib as mpl
import m | atplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
display_axes = fig.add_axes([0.1, 0.1, 0.8, 0.8], projection='polar')
# This is a nasty hack - using | the hidden field to multiply the values
# such that 1 become 2*pi, this field is supposed to take values 1 or -1 only!!
display_axes._direction = 2*np.pi
norm = mpl.colors.Normalize(0.0, 2*np.pi)
# Plot the colorbar onto the polar axis
# note - use orientation horizontal so that the gradient goes around
# the wheel ra... |
ilstreltsov/django-db-mailer | demo/demo/views.py | Python | gpl-2.0 | 156 | 0.00641 | # -*- encoding: utf-8 -*-
| from django.shortcuts import render
def browser_notification(request):
return render(request, "browser_noitification.htm | l") |
msimacek/koschei | test/__init__.py | Python | gpl-2.0 | 1,083 | 0 | # Copyright (C) 2014-2016 Red Hat, 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 2 of the License, or
# (at your option) any later version.
#
# This program is distribute... | 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.
#
# Author: Michael Simacek <msimacek@redhat.com>
import os
from koschei.config... | e__))
load_config(['{0}/../config.cfg.template'.format(testdir),
'{0}/test_config.cfg'.format(testdir)],
ignore_env=True)
config = get_config(None)
|
gnu-sandhi/sandhi | modules/gr36/gr-blocks/python/qa_packed_to_unpacked.py | Python | gpl-3.0 | 10,891 | 0.006427 | #!/usr/bin/env python
#
# Copyright 2005,2007,2010,2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at ... | f.tb.run()
self.assertEqual(expected_results, dst.data())
def test_101 | a(self):
random.seed(0)
src_data = []
for i in xrange(100):
src_data.append((random.randint(-2**15,2**15-1)))
src_data = tuple(src_data)
expected_results = src_data
src = gr.vector_source_s(tuple(src_data), False)
op1 = blocks.packed_to_unpacked_ss(8, ... |
youprofit/webserver | admin/CTK/CTK/List.py | Python | gpl-2.0 | 3,058 | 0.006213 | # -*- coding: utf-8 -*-
#
# CTK: Cherokee Toolkit
#
# Authors:
# Alvaro Lopez Ortega <alvaro@alobbs.com>
#
# Copyright (C) 2010-2014 Alvaro Lopez Ortega
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the... | e 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 Widget import Widget
from Container import Container
from util import props_to_str
EN... | s>'
class ListEntry (Container):
def __init__ (self, _props={}, tag='li'):
Container.__init__ (self)
self.tag = tag
self.props = _props.copy()
def Render (self):
render = Container.Render (self)
if 'id' in self.props:
self.id = self.props['id']
p... |
hqro/Predictr | predictr.py | Python | mit | 5,103 | 0.006663 | from typing import Un | ion, Dict, List, Any
from flask_cors import CORS, cross_origin |
from flask import Flask, request
import json
import sys
import re
import os
app = Flask(__name__)
CORS(app)
def foreach(fn, elems: Any):
for elem in elems:
fn(elem)
def exists(item: Any):
return item
Ngram = int #Dict[str, Union[str, float, Dict[str, Union[str, float]]]]
class Markov():
""" ma... |
yeming233/rally | rally/plugins/openstack/context/nova/keypairs.py | Python | apache-2.0 | 2,640 | 0 | # Copyright 2014: Rackspace UK
# 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... | []),
superclass=self.__class__,
| task_id=self.get_owner_id())
|
israelem/aceptaelreto | codes/2017-10-09-modas.py | Python | mit | 790 | 0 | from statistics import mode
def moda(muestras):
frecuencias = {}
for muestra in muestras:
if muestra not in frecuencias.keys():
frecuencias[muestra] = 1
else:
frecuencias[muestra] += 1
valores = []
frecuencia_maxima = max(frecuencias.values())
for clave in f... | amano_muestra = int(input())
while tamano_muestra:
muestras = [int(x) for x in input().split(' ')]
# soluciones.append(moda(muestras))
soluciones.append(mode(muestras))
tamano_muestra = int(input())
for | solucion in soluciones:
print(solucion)
|
arpan-chavda/rh_app | libs/venus/tests/test_rlists.py | Python | gpl-3.0 | 1,477 | 0.006093 | #!/usr/bin/env python
import unittest, os, shutil
from planet import config, opml
from os.path import split
from glob import glob
from ConfigParser import ConfigParser
workdir = os.path.join('tests', 'work', 'config', 'cache')
class ReadingListTest(unittest.TestCase):
def setUp(self):
config.load('tests/... | name'])
feed2 = feeds['testfeed2.atom' | ]
self.assertEqual('two', config.feed_options(feed2)['name'])
# dictionaries
def test_cache(self):
cache = glob(os.path.join(workdir,'lists','*'))
self.assertEqual(1,len(cache))
parser = ConfigParser()
parser.read(cache[0])
feeds = [split(feed)[1] for feed in ... |
samitnuk/studentsdb | students/models/groups.py | Python | mit | 802 | 0 | from django.db import models
class Group(models.Mode | l):
"""Group Model"""
class Meta(object):
verbose_name = 'Група'
verbose_name_plural = 'Групи'
title = models.CharField(
max_length=256,
blank=False,
verbose_name='Назва')
leader = models.OneToOneField(
'S | tudent',
verbose_name='Староста',
blank=True,
null=True,
on_delete=models.SET_NULL)
notes = models.TextField(
blank=True,
verbose_name='Додаткові нотатки')
def __str__(self):
if self.leader:
return '%s (%s %s)' % (self.title, self.leader.firs... |
tkaitchuck/nupic | py/nupic/analysis/inspectors/network/__init__.py | Python | gpl-3.0 | 1,690 | 0.002367 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have purchased from
# Numenta, Inc. a separate commercial license for this software code, the
# following terms and conditions apply:
#
# This pro... | ------
"""
This file exports all NetworkInspectors.
"""
import os
import glob
import nupic
# Import Netwo | rkInspector and NetworkInspectorHandler
from nupic.analysis.inspectors.network.NetworkInspector import *
# Create networkInspectors as a list of all network inspector subclasses
files = [os.path.splitext(os.path.split(x)[1])[0] for x in
glob.glob(os.path.join(os.path.split(__file__)[0], '*.py'))]
files.r... |
tiagocoutinho/bliss | bliss/controllers/tango_fe.py | Python | lgpl-3.0 | 379 | 0.005277 | # -*- coding: utf-8 -*-
#
# This file is part of the bliss project |
#
# Copyright (c) 2016 Beamline Control Unit, ESRF
# Distributed under the GNU LGPLv3. See LICENSE for more info.
from bliss.controllers.tango_attr_as_counter import TangoAttrCounter
class tango_fe(TangoAttrCounter):
def __init__(self, name, config):
TangoAttrCounter.__init__(self, name, | config)
|
imh/gnss-analysis | gnss_analysis/abstract_analysis/report.py | Python | lgpl-3.0 | 1,655 | 0.00423 | #!/usr/bin/env python
# Copyright (C) 2015 Swift Navigation Inc.
# Contact: Ian Horn <ian@swiftnav.com>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WAR... | UENESS)
p | arents : set(Analysis)
A set of Analysis objects on which the Report depends.
dist_type : DistType
The type of distribution to plot the report as, when aggregated across runs.
"""
def __init__(self, key, parents, dist_type=ms.DistType.IGNORE):
self.key = key
self.parents = parents
self.dist_ty... |
evensource/fountain | gamesys.py | Python | mit | 1,427 | 0.012614 | # -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
import sys
class game:
def __init__(self, title, winSize = (800, 600), renderFps = 60, ogl = True, fs = True):
pygame.init()
self.calcClock = pygame.time.Clock()
self.renderClock = pygame.time.Clock()
pygame.disp... | on(title)
winState = DOUBLEBUF | HWSURFACE
if ogl == True:
winState |= OPENGL
if fs == True:
winState |= FULLSCREEN
self.winSurf= pygame.display.set_mode(winSize, winState)
self.rect = self.winSurf.get_rect()
self.winSize = self.rect.size
s... | Pos = (0, 0)
self.grabornot = True
#self.calcFps = calcFps
self.renderFps = renderFps
##pygame.key.set_repeat(1, 1)
def eventSolve(self):
self.mousePos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == QUIT:
pygame... |
galactics/beyond | beyond/io/ccsds/opm.py | Python | mit | 13,862 | 0.000794 | import numpy as np
import lxml.etree as ET
from ...dates import timedelta
from ...orbits import StateVector
from ...orbits.man import ImpulsiveMan, ContinuousMan
from ...utils import units
from ...frames.orient import G50, EME2000, GCRF, MOD, TEME, TOD, CIRF
from .cov import load_cov, dump_cov
from .commons import (
... | dsError(f"Missing mandatory parameter {e}")
orb = StateVector(
[x, y, z, vx, vy, vz], date, "cartesian", frame, name=name, cospar_id=cospar_id
)
if maneuvers:
for raw_man in maneuvers:
man = {}
man["date"] = parse_date(raw_man["MAN_EPOCH_IGNITION"].text, scale)
... | de_unit(raw_man, "MAN_DURATION", "s")
)
man["frame"] = (
raw_man["MAN_REF_FRAME"].text
if raw_man["MAN_REF_FRAME"].text != frame
else None
)
man["delta_mass"] = raw_man["MAN_DELTA_MASS"].text
man["comment"] = raw... |
mehulj94/BrainDamage | Breathe/hideme.py | Python | apache-2.0 | 582 | 0.005155 | import ctypes
FILE_ATTRIBUTE_HIDDEN = 0x02
def hideFiles(folderPath):
print '[*] Hiding files'
try:
ctypes.windll.kernel32.SetFileAttributesW.argtypes = (ctypes.c_wchar_p, ctypes.c_uint32)
ret = ctypes.windll.kernel32.SetFileAttributesW(folderPath.encode('string-escape'), FILE_ATTRIBUTE_HIDDEN)... | '[*] Folder is set to Hidden'
else: # return code of zero indicates failure, | raise Windows error
raise ctypes.WinError()
except Exception as e:
print '[*] Error in hiding files'
print e
|
51reboot/homework-arch-4 | 3/huangweiyi/download_2.py | Python | apache-2.0 | 2,457 | 0.004477 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
author: kakaxi
version: 0.2
create_time: 2015/05/14
"""
import requests
import threading
from threading import Lock
class FileMultiDownload(object):
""" file multi thread downlaod """
def __init__(self, url, filename=None, threadnum=None):
sel... | lf.getSplitRange()
thread_list = []
for i in range(0, self.threadnum):
t = threading.Thread(target=self.downSplitFile, args= | ranges[i])
t.start()
thread_list.append(t)
for t in thread_list:
t.join()
self.fd.close()
if __name__ == '__main__':
url = "http://dldir1.qq.com/qqfile/qq/QQ7.1/14522/QQ7.1.exe"
download = FileMultiDownload(url)
download.saveAllToFile()
|
umitproject/network-admin | gae_settings.py | Python | agpl-3.0 | 3,537 | 0.000283 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Adriano Monteiro Marques
#
# Author: Piotrek Wasilewski <wasilewski.piotrek@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Sof... | rch',
'djangoappengine' | ,
)
INSTALLED_APPS += GAE_APPS
AUTHENTICATION_BACKENDS = (
'permission_backend_nonrel.backends.NonrelPermissionBackend',
)
MIDDLEWARE_CLASSES += (
'autoload.middleware.AutoloadMiddleware',
)
TEST_RUNNER = 'djangotoolbox.test.CapturingTestSuiteRunner'
GAE_MAIL_ACCOUNT = 'your_email@example.com'
AUTOLOAD_SITE... |
lagopus/lagopus | test/integration_test/tools/lib/ofp/ofp_flow_mod.py | Python | apache-2.0 | 1,609 | 0.000622 | import os
import sys
import copy
import logging
from checker import *
from .ofp import register_ofp_creators
from .ofp import OfpBase
from .ofp_match import SCE_MATCH
from .ofp_match import OfpMatchCreator
from .ofp_instruction import SCE_INSTRUCTIONS
from .ofp_instruction import OfpInstructionCreator
# YAML:
# flow_... | dp, ofproto,
| ofp_parser,
params[SCE_MATCH])
kws[SCE_MATCH] = match
# instructions.
instructions = []
if SCE_INSTRUCTIONS in params:
instructions = OfpInstructionCreator.create(test_case_obj,
... |
ArchiFleKs/magnum | magnum/conductor/handlers/federation_conductor.py | Python | apache-2.0 | 1,155 | 0 | # 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
#
# Unl | ess required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from mag... | andler(object):
def __init__(self):
super(Handler, self).__init__()
def federation_create(self, context, federation, create_timeout):
raise NotImplementedError("This feature is not yet implemented.")
def federation_update(self, context, federation, rollback=False):
raise NotImplem... |
Abjad/abjad | abjad/__init__.py | Python | gpl-3.0 | 11,596 | 0.000086 | from quicktions import Fraction
from . import (
_update,
deprecated,
enumerate,
format,
get,
illustrators,
io,
iterate,
iterpitches,
lyconst,
lyenv,
makers,
mutate,
persist,
string,
wf,
)
from ._version import __version__, __version_info__
from .bind impo... | uration",
"Container",
"Context",
"ContextManager",
"Contrabass",
"ContrabassClarinet",
"ContrabassFlute",
"ContrabassSaxophone",
"Contrabassoon",
"CyclicTuple",
"Dow | n",
"DrumNoteHead",
"Duration",
"DurationSequenceTyping",
"DurationTyping",
"Dynamic",
"EnglishHorn",
"Exact",
"Expression",
"Fermata",
"FilesystemState",
"Flute",
"ForbidUpdate",
"Fraction",
"FrenchHorn",
"Glissando",
"Glockenspiel",
"Guitar",
"Ha... |
dtroyer/dwarf | tests/clients/test_nova.py | Python | apache-2.0 | 4,430 | 0.000451 | #!/usr/bin/env python
#
# Copyright (c) 2017 Hewlett Packard Enterprise, L.P.
# Copyright (c) 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apach... | virt.DOMAIN_STATE = libvirt.VIR_DOMAIN_RUNNING
libvirt.IP_ADDRESS = server1['ip']
time.sleep(3)
# Should show the IP and status 'active'
self.exec_verify(['nova', 'list'],
filename=cwd('nova_list'))
self.exec_verify | (['nova', 'show', server1['id']],
filename=cwd('nova_show'))
self.exec_verify(['nova', 'console-log', server1['id']],
stdout='Test server console log\n')
self.exec_verify(['nova', 'stop', server1['id']],
stdout='Request to stop... |
artzub/code_swarm-gource-my-conf | tools/codeswarm/lib/freebase/api/session.py | Python | gpl-3.0 | 17,231 | 0.003598 | # ========================================================================
# Copyright (c) 2007, Metaweb Technologies, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistribution... | IRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDI... | H DAMAGE.
# ========================================================================
#
# declarations for external metaweb api.
#
#
# from metaweb.api import HTTPMetawebSession
#
# mss = HTTPMetawebSession('sandbox.freebase.com')
# print mss.mqlread([dict(name=None, type='/type/type')])
#
#
#
__all__ = ['Me... |
msenin94/salt-mk-verificator | mk_verificator/tests/service_checker/test_services.py | Python | bsd-2-clause | 1,141 | 0 | import pytest
import json
from mk_verificator import utils
@pytest.mark.parametrize(
"group",
utils.get_groups(utils.get_configuration(__file__))
)
def test_check_services(local_salt_client, group):
config = utils.get_configuration(__file__)
output = local_salt_client.cmd(group, 'service.get_all', ex... | if srv in output[node]:
diff.append(srv)
row.append("{}: +".format(node))
else:
row.append("{}: No service".format(node))
if diff.count(diff[0]) < len(nodes):
row.sort()
row.insert(0, srv)
pkts_data.append(r... | or {0} group: {1}".format(
group, json.dumps(pkts_data, indent=4))
|
tisspage/ucar | api-server/api_v0/serializers/file.py | Python | mit | 653 | 0.027607 | #!/usr/bin/env python
# encoding: utf-8
"""
serializers.py
Created by Christophe VAN FRACKEM / Bastien ARNETTE on 2014/04/21/.
Copyright (c) 2014 Tiss'Page. MIT Licence.
UCAR serializers.
"""
__author__ = 'Christophe VAN FRACKEM <contact@tisspage.fr> / Bastien ARNETTE <bastien@rnette.fr>'
__ | version__= '0.0.1'
__copyright__ = '© 2014 Tiss\'Page for UCAR'
from rest_framework import serializers
from api_v0.models import File, Infos
class InfosSerializer(serializers.ModelSerializer):
cl | ass Meta:
model = Infos
class FileSerializer(serializers.ModelSerializer):
info = InfosSerializer(many=False)
class Meta:
model = File
|
elyezer/fake_pylarion | pylarion/work_item.py | Python | gpl-3.0 | 142 | 0 | class TestCase(object):
pass
class TestStep(object):
pass
class TestSteps(object):
pass
class Require | ment(object):
p | ass
|
Kjuly/iPokeMon-Server | test.py | Python | mit | 417 | 0.033573 | from bottle import Bottle, run
app = Bottle()
@app.route('/')
def index():
return 'PService Running'
#
# Start a s | erver instance
#
run(
app, # Run |app| Bottle() instance
host = '0.0.0.0',
port = 8080,
reloader = True, | # restarts the server every time edit a module file
debug = True # Comment out it before deploy
)
|
rananda/cfme_tests | cfme/containers/pod.py | Python | gpl-2.0 | 2,347 | 0.001278 | # -*- coding: utf-8 -*-
from functools import partial
from cfme.common import SummaryMixin, Taggable
from cfme.fixtures import pytest_selenium as sel
from cfme.web_ui import toolbar as tb, paginator, match_location,\
PagedTable, CheckboxTable
from cfme.containers.provider import details_page
from utils.appliance im... | heck_all())
@navigator.register(Pod, 'Details')
class Details(CFMENavigateStep):
prerequisite = NavigateToSibling('All')
def am_i_here(self):
return match_page(summary='{} (Summary)'.format(self.obj.name))
def step(self):
tb.select('List View')
sel.click(paged_tbl.find_row_by_cel... | lf.obj.name}))
|
dpnishant/appmon | appmon.py | Python | apache-2.0 | 14,441 | 0.005955 | #!/usr/bin/python
###
# Copyright (c) 2016 Nishant Das Patnaik.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | IE rendering engine or Chrome Frame,
and also to cache the rendered page for 10 minutes.
"""
r.headers["Cache-Cont | rol"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r
@app.route('/api/fetch', methods=['GET'])
def serve_json():
index = request.args.get('id')
if request.args.get('reportdb'):
... |
ClearCorp/knowledge | document_page/models/document_page.py | Python | agpl-3.0 | 4,535 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | )
def _get_page_index(self, page, link=True):
"""Return the index of a document."""
index = []
for subpage in page.child_ids:
index += ["<li>" + self._get_page_index(subpage) +
"</li>"]
| r = ''
if link:
r = '<a href="#id=%s">%s</a>' % (page.id, page.name)
if index:
r += "<ul>" + "".join(index) + "</ul>"
return r
def _get_display_content(self):
"""Return the content of a document."""
for page in self:
if page.type ... |
dpetzold/django-cacheops | cacheops/management/commands/cleanfilecache.py | Python | bsd-3-clause | 407 | 0.007371 | import os
from django.core.manag | ement.base import BaseCommand, CommandError
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from cacheops.simple import file_cache, FILE_CACHE_DIR
class Command(BaseCommand):
help = 'Clean filebased | cache'
def handle(self, **options):
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % FILE_CACHE_DIR)
|
iLoop2/ResInsight | ThirdParty/Ert/devel/python/python/ert/util/stat.py | Python | gpl-3.0 | 1,169 | 0.017964 | # Copyright (C) 2011 Statoil ASA, Norway.
#
# The file 'stat.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... | RPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.util import UTIL_LIB
from ert.cwrap import CWrapper, CWrapperNameSpace
def quantile( data, q ):
return cfunc.quantile(data, q)
def quantile_sorted( data, q ):
return cfunc.quantil... | )
cfunc.quantile = cwrapper.prototype("double statistics_empirical_quantile( double_vector , double )")
cfunc.quantile_sorted = cwrapper.prototype("double statistics_empirical_quantile( double_vector , double )")
|
spcs/synaps | synaps/monitor/__init__.py | Python | apache-2.0 | 11,730 | 0.010145 | # -*- coding:utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright (c) 2012 Samsung SDS Co., LTD
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0... | _periods = evaluation_periods
assert (len(metric_name) <= 255)
self.metric_name = metric_name
assert (len(namespace) <= 2 | 55)
self.namespace = namespace
assert (isinstance(period, int))
self.period = period
assert (statistic in self.STATISTICS)
self.statistic = statistic
self.threshold = threshold
self.unit = unit
self.alarm_arn = None
... |
claria/i3pystatus | setting_util.py | Python | mit | 2,881 | 0.003124 | #!/usr/bin/env python
import glob
import inspect
import os
import keyring
import getpass
import sys
import signal
from i3pystatus import Module, SettingsBase
from i3pystatu | s.core import ClassFinder
from collections import defaultdict, OrderedDict
def sign | al_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
def get_int_in_range(prompt, _range):
while True:
answer = input(prompt)
try:
n = int(answer.strip())
if n in _range:
return n
else:
print("Va... |
mattixpet/python-bach_machine | bach_version1.01/chord.py | Python | apache-2.0 | 623 | 0.046549 | # Chord object
#imports
from audio i | mport reprNotes;
#chord object, contains an array of notes
class chord:
def __init__(self, notes):
self.notes = notes;
def __repr__(self): #'tostr | ing method'
return reprNotes(self.notes)+'\n';
#function to get the notes, make sure to return a copy so the user cannot alter it
def getNotes(self):
return list(self.notes);
#basic set function
def setNotes(self,newNotes):
self.notes = list(newNotes); #make sure we don't just point to newNo... |
arthuralvim/django-gevsckio-example | gevsckio/wsgi.py | Python | mit | 391 | 0.002558 | """
WSGI config for gevsckio project.
It exposes the WSGI callable as a module-level variable named ``application``.
For | more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
i | mport os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gevsckio.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
Ingenico-ePayments/connect-sdk-python2 | ingenico/connect/sdk/domain/payment/definitions/g_pay_three_d_secure.py | Python | mit | 6,073 | 0.004611 | # -*- coding: utf-8 -*-
#
# This class was auto-generated from the API references found at
# https://epayments-api.developer-ingenico.com/s2sapi/v1/
#
from ingenico.connect.sdk.data_object import DataObject
from ingenico.connect.sdk.domain.payment.definitions.redirection_data import RedirectionData
class GPayThreeDSe... | return self.__exemption_request
@exemption_request.setter
def exemption_request(self, value):
self.__exemption_request = value
@property
def redirection_data(self):
"""
| Object containing browser specific redirection related data
Type: :class:`ingenico... |
return self.__redirection_data
@redirection_data.setter
def redirection_data(self, value):
self.__redirection_data = value
@property
def skip_authentication(self):
"""
* true = 3D Secure authentication will be skipped for this transaction. This setting should be used w... |
vstconsulting/polemarch | polemarch/main/repo/__init__.py | Python | agpl-3.0 | 69 | 0 | from .vcs import Git
fro | m . | tar import Tar
from .manual import Manual
|
naltimari/filebrowser | filebrowser/views.py | Python | bsd-3-clause | 18,909 | 0.005183 | # coding: utf-8
# general imports
import os, re
from time import gmtime, strftime
# django imports
from django.shortcuts import render_to_response, HttpResponse
from django.template import RequestContext as Context
from django.http import HttpResponseRedirect
from django.contrib.admin.views.decorators import staff_me... | if errno == 13:
form.errors['dir_name'] = forms.util.ErrorList([_('Permission denied.')])
else:
form.errors['dir_name'] = forms.util.ErrorList([_('Error creating folder.')])
else:
form = MakeDirForm(abs_path)
return r | ender_to_response('filebrowser/makedir.html', {
'form': form,
'query': query,
'title': _(u'New Folder'),
'settings_var': get_settings_var(),
'breadcrumbs': get_breadcrumbs(query, path),
'breadcrumbs_title': _(u'New Folder')
}, context_instance=Context(request))
mkdir ... |
LordDarkula/chess_py | chess_py/core/algebraic/__init__.py | Python | mit | 128 | 0 | from .location import Location, Direction
from .move import Move
| __all_ | _ = ['converter', 'Location', 'Move', 'notation_const']
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.2/django/contrib/sessions/backends/base.py | Python | bsd-3-clause | 9,240 | 0.000758 | import base64
import os
import random
import sys
import time
from datetime import datetime, timedelta
try:
import cPickle as pickle
except ImportError:
import pickle
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.utils.hashcompat import md5_constructor
# Us... | self._session_cache = {}
else:
| self._session_cache = self.load()
return self._session_cache
_session = property(_get_session)
def get_expiry_age(self):
"""Get the number of seconds until the session expires."""
expiry = self.get('_session_expiry')
if not expiry: # Checks both None and 0 cases
... |
chiara-paci/baskerville | baskervilleweb/bibliography/models.py | Python | gpl-3.0 | 75,809 | 0.020491 | # -*- coding: utf-8 -*-
from django.db import models
import django.template.defaultfilters
from django.db.models import Max
from django.utils.functional import cached_property
# Create your models here.
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.con... | self):
re | turn "; ".join([str(x) for x in self.begin_set.all()])
def ends(self):
return "; ".join([str(x) for x in self.end_set.all()])
def time_spans(self):
L=[str(x) for x in self.begin_set.all()]
L+=[str(x) for |
mlperf/training_results_v0.5 | v0.5.0/google/cloud_v3.8/ssd-tpuv3-8/code/ssd/model/tpu/models/official/squeezenet/squeezenet_main.py | Python | apache-2.0 | 4,590 | 0.003268 | # Copyright 2017 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... | u.TPUConfig(
iterations_per_loop=100,
num_shards=FLAGS.num_shards,
),
)
estimator = tf.contrib.tpu.TPUEstimator(
model_f | n=squeezenet_model.model_fn,
use_tpu=FLAGS.use_tpu,
config=run_config,
train_batch_size=FLAGS.batch_size,
eval_batch_size=FLAGS.batch_size,
params=dict(params, use_tpu=FLAGS.use_tpu),
)
num_evals = max(FLAGS.num_evals, 1)
examples_per_eval = training_examples // num_evals
for _ in... |
cseed/hail | hail/python/hail/experimental/vcf_combiner/sparse_mt_utils.py | Python | mit | 597 | 0 | import hail as hl
from hail.expr.expressions import expr_array, expr_call, expr_int32
from hail.typecheck import typecheck
@typecheck(lgt=expr_call, la=expr_array(expr_int32))
def lgt_to_gt(lgt, la):
"""Transform LGT into GT using local alleles array.
Parameters
----------
lgt : :class:`.CallExpressi... | ion assumes diploid genoty | pes.
"""
return hl.call(la[lgt[0]], la[lgt[1]], phased=lgt.phased)
|
kididcca/mqtt-mongo | assinante.py | Python | mit | 951 | 0.008421 | import time, os
import paho.mqtt.client as mqtt
from pymongo import MongoClient
cliente = MongoClient(os.getenv('MONGO_SERVER', 'nuvem.sj.ifsc.edu.br'))
db = cliente[os.getenv('DATABASE', 'estacao')]
def on_connect(client, userdata, flags, rc):
client.subscribe(os.getenv('TOPIC', 'estacao/#'))
def on_message(cl... | + ', valor: ' + valoratual + '\n')
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(os.getenv('MQTT_BROKER', 'nuvem.sj | .ifsc.edu.br'), 1883, 60)
client.loop_forever()
|
mathben/python_clang_parser | main.py | Python | gpl-3.0 | 12,033 | 0.004488 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os
from glob import glob
import argparse
import time
import datetime
from multiprocessing import Pool
# local import
from ast import ast
import result
AST_EXT_FILE = ".ast"
CSV_EXT_FILE = ".csv"
CPP_EXT_FILE = ("*.cc", "*.cpp")
# TODO support sigterm and close ... | anslation_unit_dir:
if not os.path.isdir(_parser.translation_unit_dir):
os.makedirs(_parser.translation_unit_dir)
# use ast file if translation_unit_dir not contain ast file
_parser.ast_file = glob(os.path.join(_parser.translation_unit_dir, "*" + AST_EXT_FILE))
else:
# ca... | include in _parser.include_clang.split(";")]
else:
_lst_include = []
# validate if all path exist
for include in _lst_include:
if not os.path.exists(include):
print("Warning, include '%s' not exist." % include)
# find include directory
if _parser.find_include:
key... |
Azure/azure-sdk-for-python | sdk/kubernetesconfiguration/azure-mgmt-kubernetesconfiguration/azure/mgmt/kubernetesconfiguration/v2021_03_01/models/__init__.py | Python | mit | 2,687 | 0.000744 | # 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 ... | els import ComplianceStatus # type: ignore
from ._models import ErrorDefinition # type: ignore
from ._models import ErrorResponse # type: ignore
from ._models import HelmOperatorProperties # type: ignore
from ._models import Pr | oxyResource # type: ignore
from ._models import Resource # type: ignore
from ._models import ResourceProviderOperation # type: ignore
from ._models import ResourceProviderOperationDisplay # type: ignore
from ._models import ResourceProviderOperationList # type: ignore
from ._models import Resul... |
sephiroth6/nodeshot | tests/ci/local_settings.example.py | Python | gpl-3.0 | 284 | 0 | DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NA | ME': 'nodeshot_ci',
'USER': 'custom_user',
'PASSWORD': 'custom_password',
'HOST': '127.0.0.1',
'PORT': '5432',
| }
}
DOMAIN = 'yourcustomhost.com'
|
sunlightlabs/foia-data | new/new-more/foia-master/contacts/tests/keywords_from_fr_tests.py | Python | gpl-3.0 | 2,306 | 0 | from mock import Mock
from unittest import TestCase
import keywords_from_fr as fr
class FRTests(TestCase):
"""Tests keywords_from_fr"""
def test_normalize_name(self):
for old, new in (
('United States African Development Foundation',
'AFRICAN DEVELOPMENT FOUNDATION'),
... | FAMILIES') | ,
('Export-Import Bank of the U.S.', 'EXPORTIMPORT BANK'),
('Department of the Army - Main Office', 'ARMY'),
('Centers for Disease Control', 'CENTER DISEASE CONTROL')
):
self.assertEqual(fr.normalize_name(old), new)
def test_fetch_page_dates(self):
""... |
Kalenai/url-shortener | manage.py | Python | mit | 672 | 0 | import click
import os
import unittest
from app import create_app, db
from app.models import UrlLink
app = create_app(os.getenv('APP_SETTINGS'))
@app.shell_context_processor
def ma | ke_shell_context():
return dict(app=app, db=db, UrlLink=UrlLink)
@app.cli.command()
def recreate_db():
click.echo('Recreating database...')
db.drop_all()
db.create_all()
db.session.commit()
click.echo('Finished reacreating database.')
@app.cli.command()
def test():
tests = unittest.TestL... | tests)
if result.wasSuccessful():
return 0
return 1
|
harisbal/pandas | asv_bench/benchmarks/stat_ops.py | Python | bsd-3-clause | 3,231 | 0 | import numpy as np
import pandas as pd
ops = ['mean', 'sum', 'median', 'std', 'skew', 'kurt', 'mad', 'prod', 'sem',
'var']
class FrameOps(object):
params = [ops, ['float', 'int'], [0, 1], [True, False]]
param_names = ['op', 'dtype', 'axis', 'use_bottleneck']
def setup(self, op, dtype, axis, use... | lf.data.rank(pct=pct)
def time_average_old(self, constructor, pct):
self.data.rank(pct=pct) / len(self.data)
class Correlation(object):
params = ['spearman', 'kendall', 'pearson']
param_names = ['method']
def setup(self, method):
self.df = pd.DataFrame(np.random.randn(1000, 30))
... | t setup # noqa: F401
|
abcdef123/stem | stem/util/system.py | Python | lgpl-3.0 | 19,948 | 0.021205 | """
Helper functions for working with the underlying system. These are mostly os
dependent, only working on linux, osx, and bsd. In almost all cases they're
best-effort, providing **None** if the lookup fails.
**Module Overview:**
::
is_windows - checks if we're running on windows
is_mac - checks if we're runnin... | commands...
#
# * They're not in the path so is_available() will fail.
# * subprocess.Popen() without the 'shell = True' argument will fail with...
# OSError: [Errno 2] No such file or directory
SHELL_COMMANDS = ['ulimit']
IS_RUNNING_PS_LINUX = "ps -A co command"
IS_RUNNING_PS_BSD = "ps -ao ucomm="
GET_... | %s"
GET_PID_BY_NAME_PS_BSD = "ps axc"
GET_PID_BY_NAME_LSOF = "lsof -tc %s"
GET_PID_BY_PORT_NETSTAT = "netstat -npltu"
GET_PID_BY_PORT_SOCKSTAT = "sockstat -4l -P tcp -p %s"
GET_PID_BY_PORT_LSOF = "lsof -wnP -iTCP -sTCP:LISTEN"
GET_PID_BY_FILE_LSOF = "lsof -tw %s"
GET_CWD_PWDX = "pwdx %s"
GET... |
meltwater/lighter | src/lighter/graphite.py | Python | mit | 2,361 | 0.001271 | import logging
import urllib2
import socket
import time
import re
import lighter.util as util
class Graphite(object):
def __init__(self, address, url, tags=[]):
"""
@param address hostname:port where the Graphite listens for the plaintext protocol, usually port 2003
@param url ... | b.com/gra | fana/grafana/issues/1474#issuecomment-105811191
self._call('/events/', {
'what': title,
'data': message,
'tags': ' '.join(self._mangle(tag) for tag in merged_tags),
'when': now
})
def _mangle(self, tag):
return re.sub('[\s,]', '_', tag.strip()... |
technologiescollege/Blockly-rduino-communication | scripts_XP/Lib/site-packages/idlexlib/extensions/_rmenu.py | Python | gpl-3.0 | 231 | 0.008658 | #
# The | patch applied in http://bugs.python.org/issue1207589
# changes the structure of rmenu_specs in EditorWindow.py. This breaks a lot of extensions.
# This file is a re | -factoring of rmenu code for other extensions to use.
#
|
Hydrosys4/Master | actuatordbmod.py | Python | gpl-3.0 | 9,532 | 0.053294 | # -*- coding: utf-8 -*-
"""
utility for the planning database
"""
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import logging
import string
from datetime import datetime,date,timedelta
import databasemod... | 0:
o | utputallsensordata.append(sensordata)
usedsensorlist.append(selsensor)
return outputallsensordata,usedsensorlist
# sensor data --------------------------------------------
def RemoveActuatorDataPeriod(removebeforedays, maxremovepersensor=300):
sensordata=[]
field=TIMEFIELD
startdate=datetime.now()
... |
albertoferna/compmech | compmech/conecyl/fsdt/setup_fsdt_donnell_bc2_linear.py | Python | bsd-3-clause | 496 | 0.024194 | from distutils.core import setup
from distutils.extension import Extension
| from Cython.Distutils import build_ext
ext_modules = [Extension('fsdt_donnell_bc2_linear',
['fsdt_donnell_bc2_linear.pyx'],
extra_compile_args=['/openmp',
'/O2', '/favor:INTEL64'],
extra_link_args=[],
)]
setup... | build_ext': build_ext},
ext_modules = ext_modules
)
|
silentsignal/wpc | windows-privesc-check.py | Python | gpl-2.0 | 119,299 | 0.026882 | from __future__ import unicode_literals
import glob
import datetime
import socket
import os, sys
import win32process
import re
import win32security, ntsecuritycon, win32api, win32con, win32file
import win32service
import pywintypes # doesn't play well with molebox pro - why did we need this anyway?
import win... | '937894': 'MS07_065 Microsoft Message Queueing Service DNS Name Path Overflow' | ,
'2592799': 'MS11-080: Vulnerability in ancillary function driver could allow elevation of privilege',
'2305420': 'MS10-092: Vulnerability in Task Scheduler could allow for elevation of privilege'
}
reg_paths = (
'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services',
'HKEY_CURRENT_USER\Softw... |
ZoranPavlovic/kombu | examples/simple_eventlet_receive.py | Python | bsd-3-clause | 1,188 | 0.000842 | """
Example that sends a single message and exits using the simple | interface.
You can use `simple_receive.py` (or `complete_receive.py`) to receive the
message sent.
"""
import eventlet
from kombu import Connection
eventlet.monkey_patch()
def wait_many(timeout=1):
#: Create connection
#: If hostname, userid, password and virtual_host is not specified
#: the values... | nterface of the Python Queue module.
#: First argument can either be a queue name or a kombu.Queue object.
#: If a name, then the queue will be declared with the name as the
#: queue name, exchange name and routing key.
with connection.SimpleQueue('kombu_demo') as queue:
whi... |
lalitkumarj/NEXT-psych | gui/base/controllers/new_experiment.py | Python | apache-2.0 | 3,408 | 0.008216 | from flask import Blueprint, render_template, flash, request, redirect, url_for, session
from flask.ext.login import login_user, logout_user, login_required
from wtforms import TextField, PasswordField, TextAreaField, RadioField, FieldList, IntegerField, FormField, StringField, validators
from wtforms.compat import wit... | base.forms import LoginForm, NewExperimentForm
from base.models import User
from base.current import *
from base.app_manager import app_manager
new_experiment = Blueprint('new_experiment', __name__)
@new_experiment.route('/')
@login_required
@project_required
def _new_experiment():
# check to se | e if targets have been uploaded
if len(current_project.target_sets) == 0:
return render_template('no_targets.html')
else:
# targets have been uploaded, show new experiment page
return render_template('new_experiment.html')
@new_experiment.route('/<app_id>',methods=["GET","POST"])
@login... |
awacha/cct | attic/gui/tools/maskeditor.py | Python | bsd-3-clause | 11,717 | 0.002902 | import datetime
import logging
import os
import numpy as np
from matplotlib.path import Path
from matplotlib.widgets import Cursor, EllipseSelector, LassoSelector, RectangleSelector
from sastool.io.credo_cct import Exposure
from scipy.io import loadmat, savemat
from ..core.exposureloader import ExposureLoader
from ..... | rder': 10},
button=[1, ],
interactive=False, lineprops={'zorder': 10})
else:
self._selector.set_active(False)
self._selector.set_visible(False)
self._selector = None
self... | n press and release events, with xdata and ydata
# carrying the two opposite corners of the bounding box of the rectangle. These
# are NOT the exact button presses and releases!
row = np.arange(self.mask.shape[0])[:, np.newaxis]
column = np.arange(self.mask.shape[1])[np.newaxis, :]
... |
codepaji2006/ethergeniee | main.py | Python | gpl-2.0 | 2,121 | 0.029703 |
#Distributed under GPLv2.0 license.
#Author: codepaji2006@github
#Repo: https://github.com/codepaji2006
#You may copy and distribute verbatim copies of the Program's source code as you
#receive it, in any medium, provided that you conspicuously and appropriately publish
#on each copy an appropriate copyright notice a... | print(f)
exit()
if out_dev is None:
print("error must specify interface.\n%s"%(usage_banner))
exit()
#check if config file exists or not
try:
conf_mode = os.stat(config_file).st_mode
except:
print("File %s not found"%(config_file))
exit()
#check if interface specified is correct or not
f = FlowConfi | gurations.FlowConfigurations(config_file)
final_frame=f.getFrame(0,56)# payload size
Linux.send_frame(out_dev,final_frame,len(final_frame))
|
exocad/exotrac | trac/mimeview/tests/pygments.py | Python | bsd-3-clause | 4,865 | 0.001439 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2013 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/Tra | cLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
from __future__ import absolute_import
import os
import unittest
from genshi.core import Stream, TEXT
from g... | view.api import Mimeview
if have_pygments:
from trac.mimeview.pygments import PygmentsRenderer
from trac.test import EnvironmentStub, Mock
from trac.web.chrome import Chrome, web_context
from trac.web.href import Href
class PygmentsRendererTestCase(unittest.TestCase):
def setUp(self):
self.env = Envi... |
coldfusion39/excel-press | excel_press.py | Python | mit | 9,911 | 0.024518 | #!/usr/bin/env python
# Copyright (c) 2015, Brandan [coldfusion]
#
# 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,... | d_end):
flag_byte_index = self.compressed_current
token_flags = 0
self.compressed_current = self.compressed_current + 1
for index in xrange(0, 8):
if ((self.decompressed_current < decompressed_end) and (self.compressed_current < compressed_end)):
token_flags = self.compress_token(compressed_end, decompr... | mpressed_end, decompressed_end, index, flags):
offset = 0
offset, length = self.matching(decompressed_end)
if offset:
if (self.compressed_current + 1) < compressed_end:
copy_token = self.pack_copy_token(offset, length)
struct.pack_into("<H", self.compressed_container, self.compressed_current, copy_tok... |
RamiOran/SeqCov | main.py | Python | mit | 3,137 | 0.023589 | # This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
from __future__ import division
"""
main.py -- main program of motif sequence coverage pipeline tool
example for running code: python main.py -jid tes... | fFile
#make a results directory to store job results
resultsDirName | = args.jid
os.makedirs(resultsDirName)
#make a file list to store all the files to be moved to the results folder
fileList = []
#copy the config file
cpConfFileName = args.jid + '_in_conf_file'
cpConfFile = open(cpConfFileName, 'wb')
with open(args.confFile, 'rb') as handler:
... |
sadanandb/pmt | src/tactic/utility/database.py | Python | epl-1.0 | 910 | 0.002198 | ############################################################
#
# Copyright (c) 2011, Southpaw Technology
# All Rights Reserved
#
# | PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
from pyasm.common import Config, Common
class DatabaseBackup(object):
def execute(my):
base_dir = "/tmp"
roo... | etime.now()
date = now.strftime("%Y%m%d_%H%M")
file_name = '%s_%s.sql' % (root, date)
path = "%s/%s" % (base_dir, file_name)
print "Backing up database to: [%s]" % path
import os
cmd = 'pg_dumpall -U postgres > %s' % path
os.system(cmd)
cmd = 'gzip -f /t... |
canhhs91/greenpointtrees | src/oscar/apps/customer/history.py | Python | mit | 1,949 | 0 | import json
from django.conf import settings
from oscar.core.loading import get_class, get_model
product_viewed = get_class('catalogue.signals', 'product_viewed')
Product = get_model('catalogue', 'Product')
def get(request):
"""
Return a list of recently viewed products
"""
ids = extract(request)
... | )
else:
# Badly written web crawlers send garbage in double quotes
if not isinstance(ids, list):
ids = []
return ids
def add(i | ds, new_id):
"""
Add a new product ID to the list of product IDs
"""
max_products = settings.OSCAR_RECENTLY_VIEWED_PRODUCTS
if new_id in ids:
ids.remove(new_id)
ids.append(new_id)
if (len(ids) > max_products):
ids = ids[len(ids) - max_products:]
return ids
def update(pr... |
OpenSight/StreamSwitch | controller/python/streamswitch/wsgiapp/daos/sender_conf_dao.py | Python | agpl-3.0 | 2,388 | 0.00335 | """
streamswitch.wsgiapp.daos.sender_conf_dao
~~~~~~~~~~~~~~~~~~~~~~~
This module implements the DAO for stream onfiguration's persistence
:copyright: (c) 2015 by OpenSight (www.opensight.cn).
:license: AGPLv3, see LICENSE for more details.
"""
from __future__ import unicode_literals, division
from ..models import... | _conf()
print("sender confs at begin:")
print(sender_conf_list)
sender_conf = SenderConf("test_type", "test_name", "test://test", stream_name="test_stream")
# sender_conf_dao.del_sender_conf("test_name")
sender_conf_dao.add_sender_conf(sender_conf)
sender_conf_list = sender | _conf_dao.get_all_sender_conf()
print("sender confs after add:")
print(sender_conf_list)
sender_conf_dao.del_sender_conf("test_name")
sender_conf_list = sender_conf_dao.get_all_sender_conf()
print("sender confs after del:")
print(sender_conf_list)
|
ju1ius/clisnips | clisnips/tui/models/snippets.py | Python | gpl-3.0 | 3,536 | 0.000283 | import enum
from contextlib import suppress
from typing import Tuple
import urwid
from clisnips.database.pager import Pager
from clisnips.database.search_pager import SearchPagerType, SearchSyntaxError
from clisnips.database.snippets_db import SnippetsDatabase
class SnippetsModel:
class Signals(enum.Enum):
... | return column, 'ASC' if order is Pager.SORT_ASC else 'DESC'
def set_sort_column(self, column, order='DESC'):
self._pager.set_sort_column(column, order)
def get(self, snippet_id):
return self._db.get(snippet_id)
def create(self, snippet):
rowid = self._db.insert(snippet)
... | ._emit(self.Signals.ROW_CREATED, snippet)
def update(self, snippet):
self._db.update(snippet)
self._emit(self.Signals.ROW_UPDATED, snippet['id'], snippet)
def delete(self, rowid):
self._db.delete(rowid)
with suppress(SearchSyntaxError):
self._pager.count()
s... |
gakhov/pdsa | setup.py | Python | mit | 5,837 | 0 | import os
from distutils.sysconfig import get_python_inc
from distutils.core import Extension, setup
try:
from Cython.Build import cythonize
except ImportError:
print("Please install cython and try again.")
raise SystemExit
PACKAGES = [
'pdsa',
'pdsa.cardinality',
'pdsa.frequency',
'pdsa.... | )
extensions.append(
Extension(
"pdsa.membership.counting_bloom_filter",
language='c++',
sources=['pdsa/membership/counting_bloom_filter.pyx'],
include_dirs=[
get_python_inc(plat_specific=True),
]
)
)
extensions.... | "pdsa.cardinality.linear_counter",
language='c++',
sources=['pdsa/cardinality/linear_counter.pyx'],
include_dirs=[
get_python_inc(plat_specific=True),
]
)
)
extensions.append(
Extension(
"pdsa.cardinality.pro... |
mdiener/grace | grace/doc.py | Python | gpl-3.0 | 2,343 | 0.005548 | from __future__ import absolute_import
from bu | iltins import object
from .error import CreateFolderError, FileNotWritableError, RemoveFolderError
import grace.py27.pyjsdoc
import os
from shutil import rmtree
class Doc(object):
def __init__(self, config):
self._cwd = os.getcwd()
| self._config = config
if 'doc_path' not in self._config:
self._doc_path = None
else:
self._doc_path = os.path.join(self._config['doc_path'], self._config['name'])
self._lib_path = os.path.join(self._cwd, 'src', 'lib')
def run(self, with_libs=False):
... |
bparzella/gemma | app/views/__init__.py | Python | lgpl-2.1 | 775 | 0.00129 | #####################################################################
# app/views/__init__.py
#
# (c) Copyright 2015, Benjamin Parzella. All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Le | sser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This software 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... | #########
from settings import DialogSettings |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.