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
mwaskom/seaborn
seaborn/tests/test_palettes.py
Python
bsd-3-clause
14,313
0.000279
import colorsys import numpy as np import matplotlib as mpl import pytest import numpy.testing as npt from .. import palettes, utils, rcmod from ..external import husl from ..colors import xkcd_rgb, crayons class TestColorPalettes: def test_current_palette(self): pal = palettes.color_palette(["red", "...
assert_array_equal(pal1, pal2) cmap1 = palettes.husl_palette(as_cmap=True) cmap2 = palettes.color_palette("husl", as_cmap=True) npt.assert_array_equal(cmap1([.2, .8]), cmap2([.2, .8])) def test_mpl_palette(self): pal1 = palettes.mpl_palette("Reds") pal2 = palettes.color_pa...
) npt.assert_array_equal(pal1, pal2) cmap1 = mpl.cm.get_cmap("Reds") cmap2 = palettes.mpl_palette("Reds", as_cmap=True) cmap3 = palettes.color_palette("Reds", as_cmap=True) npt.assert_array_equal(cmap1, cmap2) npt.assert_array_equal(cmap1, cmap3) def test_mpl_dark_p...
getting-things-gnome/gtg
GTG/plugins/unmaintained/geolocalized_tasks/geolocalized_tasks.py
Python
gpl-3.0
30,792
0
# Copyright (c) 2009 - Paulo Cabido <paulo.cabido@gmail.com> # # 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...
se
lf.on_contextmenu_tag_location, plugin_api) plugin_api.add_menu_tagpopup(self.context_item) # get the user settings from the config file self.config = plugin_api.get_config() if "geolocalized-tasks" in self.config.has_key: if "proximity_factor" in self.config["geolocalized-t...
UU-Hydro/PCR-GLOBWB_model
modflow/scripts/disclaimer.py
Python
gpl-3.0
2,094
0.011939
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging logger = logging.getLogger(__name__) def print_disclaimer(with_logger = False): # disclaimer message disclaimer_message = "\n" disclaimer_message ...
itz, Menno W. Straatsma, Niko Wanders, Dominik Wisser, " + "\n" disclaimer_message += " and Marc
F. P. Bierkens, " + "\n" disclaimer_message += " Faculty of Geosciences, Utrecht University, Utrecht, The Netherlands " + "\n" disclaimer_message += ...
dkong/tvshowlist
helloworld/tvdb_api/cache.py
Python
mit
7,334
0.003954
#!/usr/bin/env python #encoding:utf-8 #author:dbr/Ben #project:tvdb_api #repository:http://github.com/dbr/tvdb_api #license:Creative Commons GNU GPL v2 # (http://creativecommons.org/licenses/GPL/2.0/) """ urllib2 caching handler Modified from http://code.activestate.com/recipes/491261/ """ from __future__ import with_...
T request and the status code starts with 2 (200 OK etc) it caches it and returns a CachedResponse """ if (request.get_method() == "GET" and str(response.code).startswith("2") ): if 'x-local-cache' not in response.info(): # Response is not cached ...
request.get_full_url(), response ) else: set_cache_header = True #end if x-cache in response return CachedResponse( self.cache_location, request.get_full_url(), set_cache_header...
brk3/ekko
tools/generate_manifest.py
Python
apache-2.0
2,544
0.000393
#!/usr/bin/env python # Copyright 2016 Sam Yaple # # 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 a...
data.backupset_id, metadata.incremental, segment, 0, 0, os.urandom(20) ) def check_manifest(manifest_file): return os.path.isfile(manifest_file) def main(): args = parse_args() if check_manifest(args.manifest): print('manifest e
xists; exiting') return manifest = driver.DriverManager( namespace='ekko.manifest.drivers', name=args.driver, invoke_on_load=True, invoke_args=[args.manifest] ).driver size_of_disk = args.backupsize * 1024**3 # Convert GB to B incremental = 0 metadata = man...
reminisce/mxnet
tests/python/mkl/test_quantization_mkldnn.py
Python
apache-2.0
1,289
0.000776
# Licensed to the Apache Software Foundation (ASF) under one # or mor
e 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 use this file except in compliance # with the Li
cense. 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, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied....
google/ehr-predictions
ehr_prediction_modeling/mask_manager.py
Python
apache-2.0
15,792
0.003356
# coding=utf-8 # Copyright 2021 Google Health Research. # # 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 la...
NT_TRAIN_MASK: self._time_since_event_train_mask, mask_utils.SINCE_EVENT_EVAL_MASK: functools.partial( self._time_since_event_eval_mask, composite_mask_name), mask_utils.AT_DISCHARGE_MASK: self._at_discharge_mask, mask_utils.INTERVAL_MASK: ...
ND_OF_ADMISSION_MASK: self._end_of_admission_mask, mask_utils.IGNORE_MASK: self._ignore_mask, mask_utils.PADDED_EVENT_MASK: self._padded_event_mask, mask_utils.UNKNOWN_LOOKAHEAD_MASK: self._unknown_lookahead_mask, } if component_mask_name...
cute/pyjpegoptim
setup.py
Python
gpl-2.0
1,139
0.035996
from distutils.core import setup, Extension include_dirs = ['/usr/include', '/usr/local/include'] library_dirs = ['/usr/lib', '/usr/local/lib'] libraries = ['jpeg'] runtime_library_dirs = [] extra_objects = [] define_macros = [] setup(name = "pyjpegoptim", version = "0.1.1", author = "Guangming Li", ...
sources = ["src/jpegoptim.c"], include_dirs = include_dirs, library_dirs = library_dirs, runti
me_library_dirs = runtime_library_dirs, libraries = libraries, extra_objects = extra_objects, define_macros = define_macros )], )
pombredanne/MOG
nova/tests/virt/vmwareapi/test_vmwareapi_vm_util.py
Python
apache-2.0
14,359
0.000836
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # Copyright 2013 Canonical Corp. # 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 ...
DynamicProperty(name='foo', val='bar1'),
DynamicProperty(name='foo', val='bar2'), ]), ObjectContent(propSet=[ DynamicProperty( name='something', val=MoRef(value='thing'))]), ] for result in results_bad: bad_objects.add_object(result) prop = vm_util.property_from_property_set( ...
OpenMDM/OpenMDM
OpenMDM/settings.py
Python
apache-2.0
3,172
0.001261
""" Django settings for OpenMDM 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, ...) im...
GUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static file
s (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'src'), ) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) # plist group RETRIEVE_PLIST_FRO...
ester-project/ester
postprocessing/Roche.py
Python
gpl-3.0
361
0.027701
# We calculate the flatness with the Roche model # calculate omk knowing omc and vice-versa from numpy import * from scipy.optimize import root # we have to solve a cubic equation a-J2*a**3=1+J2+0.5*omk**2 def eps(omk): return omk**2
/(2+omk**2) def om_k(omc): khi=arcsin(omc) return sqrt(6*sin(khi/3)/om
c-2) omc=0.88 print 'omc=',omc,' omk=',om_k(omc)
lexrupy/gmate-editor
GMATE/files.py
Python
mit
2,328
0.005587
# -*- coding: utf-8 -*- # GMate - Plugin Based Programmer's Text Editor # Copyright © 2008 Alexandre da Silva / Carlos Antonio da Silva # # This file is part of Gmate. # # See LICENTE.TXT for licence information import os import gnomevfs from datetime import datetime def get_file_info(uri): """Return the File in...
visible directory.""" return is_dir(file_info) and not is_hidden(file_info) def is_visible_file(file_info): """Checks to see if the file is a visible file.""" return not is_dir(file_info) and not is_hidden(file_info) def get_user_home_uri(): """Gets a URI pointing to the user's home directory '~'."""...
type(uri) def get_path_from_uri(uri): return gnomevfs.get_local_path_from_uri(uri) def get_last_modification(uri): """Gigen a file uri return the last modification date""" file_info = get_file_info(uri) if file_info: return datetime.fromtimestamp(file_info.mtime)
lakiw/cripts
cripts/datasets/views.py
Python
mit
4,737
0.005911
import datetime import json import urllib from django.conf import settings from django.contrib.auth.decorators import user_passes_test from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import Requ...
CSV (yes if option is "csv") :type option: str :returns: :class:`django.http.HttpResponse` """ if option == "csv": return generate_dataset_csv(request) return generate_dataset_jtable(request, option) @user_passes_test(user_can_view_data) def upload_dataset(request): """ Add/Upl...
Django context which contains information about the session and key/value pairs for the Dataset request Returns: If the request is not a POST and not a Ajax call then: Returns a rendered HTML form for a bulk add of IPs If the request is a POST and a Ajax call then: ...
stampedeboss/lights
lights/cmdoptions.py
Python
cc0-1.0
3,918
0.026544
#!/usr/bin/env python # encoding: utf-8 ''' cmd_options -- Command Line Options Handler for JET MSS ''' import os import sys import logging from argparse import ArgumentParser from argparse import RawDescriptionHelpFormatter from os.path import dirname, expanduser, join, split, splitext, isabs from subprocess import ...
gfile', action='store', dest='logfile', default=log_file, help='Specify a custom logfile filename [default: %(default)s]') self.parser.add_argument("--Error-Log", dest="errorlog", action
="store_true", default=False, help="Create Seperate Log for Errors") self.parser.add_argument('--session_log', dest="session_log", action="store_false", default=True, help="paths to folder(s) with config file(s) ") self.parser.add_argument('pathname', m...
WorldViews/Spirals
YEI/examples/create_devices.py
Python
mit
3,574
0.010632
## Creating a serial port for the YEI 3-Space Sensor devices with Python 2.7, ## PySerial 2.6, and YEI 3-Space Python API import threespace_api as ts_api ## If the COM port is already known and the device type is known for the 3-Space ## Sensor device, we can just create the appropriate instance without doing a ## se...
ed via a serial connection. We can find out if there ## is any 3-Space Sensor devices by using the getSensorInfo function. However, ## we must send commands over the port which could make devices other than ## 3-Space Sensor devices act strangely. So, be sure to know what port your ## 3-Space Sensor device(s) are on wh...
pe, 3-Space ID, 3-Space Firmware Version String, ## 3-Space Hardware Version String, is in bootloader mode) for device_port in device_list: com_port, friendly_name, device_type = device_port if device_type == "USB": device = ts_api.TSUSBSensor(com_port=com_port) elif device_type == "DNG": d...
mattadri/delacook-homestead
weather/rainfall/raingauge.py
Python
mit
1,842
0.002714
from utilities import utilities import definitions import json from utilities import errors from utilities.result import Result from weather.configuration import rainfall as rainfall_config class RainfallData(object): def __init__(self, year): self.RAINFALL_DATA_PATH = rainfall_config.get_rainfall_data_...
tr(day).lstrip('0') month = str(month).
lstrip('0') if day in self.SOURCE_DATA['data'][month]['days']: self.SOURCE_DATA['data'][month]['days'][day] = quantity self.save() result.IS_SUCCESSFUL = True else: result.ERROR = errors.Errors().get_error('E0002', day=day, month=month) return ...
mcus/SickRage
sickbeard/metadata/helpers.py
Python
gpl-3.0
1,450
0.00069
# -*- coding: utf-8 -*- # Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either ...
ad if imgNum is not None: tempURL = url.split('-')[0] + "-" + str(imgNum) + ".jpg" else: tempURL = url lo
gging.debug("Fetching image from " + tempURL) image_data = helpers.getURL(tempURL, session=meta_session, needBytes=True) if image_data is None: logging.warning("There was an error trying to retrieve the image, aborting") return return image_data
googleapis/python-datacatalog
samples/generated_samples/datacatalog_v1_generated_policy_tag_manager_delete_policy_tag_async.py
Python
apache-2.0
1,449
0.00069
# -*- 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 agreed to in writing, software # distrib...
n 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. # # Generated code. DO NOT EDIT! # # Snippet for DeletePolicyTag # NOTE: This snippet has been automatically generated for...
wolvre/dreal
benchmarks/network/water/water-triple-ind.py
Python
gpl-2.0
6,830
0.013763
from gen import * ########## # shared # ########## flow_var[0] = """ (declare-fun tau () Real) (declare-fun x1 () Real) (declare-fun x2 () Real) (declare-fun x3 () Real) """ flow_dec[0] = """ (define-ode flow_1 ((= d/dt[x1] (/ (- 5 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5))) 2)) (= d/dt[x2] (...
] (/ (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5))) 3)) (= d/dt[tau] 1))) (define-ode flow_5 ((= d/dt[x1] (/ (* (* -0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5)) 2))
(= d/dt[x2] (/ (+ 3 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x1 0.5) (^ x2 0.5)))) 4)) (= d/dt[x3] (/ (+ 4 (* (* 0.5 (^ (* 2 9.80665) 0.5)) (- (^ x2 0.5) (^ x3 0.5)))) 3)) (= d/dt[tau] 1))) (define-ode flow_6 ((= d/dt[x1] (/ (* (* -0.5 (^ (* 2 9.80665) 0.5)) (^ x1 0.5)) 2)) ...
marl/jams
jams/display.py
Python
isc
6,670
0.0003
#!/usr/bin/env python r''' Display ------- .. autosummary:: :toctree: generated/ display display_multi ''' from collections import OrderedDict import json import re import six import numpy as np import matplotlib.pyplot as plt from matplotlib.offsetbox import AnchoredText import mir_eval.display fro...
kwargs.pop('ax', None) # If the annotation is empty, we need to c
onstruct a new axes ax = mir_eval.display.__get_axes(ax=ax)[0] times, values = annotation.to_interval_values() indices = np.unique([v['index'] for v in values]) for idx in indices: rows = [i for (i, v) in enumerate(values) if v['index'] == idx] freqs = np.asarray([values[r]['frequency...
kernc/orange3-text
orangecontrib/text/tests/test_corpus.py
Python
bsd-2-clause
782
0
import os import unittest from orangecontrib.text.corpus import Corpus DATASET_PATH = os.path.join(os.path.dirname(__file__), '..', '
datasets') class CorpusTests(unittest.TestCase): def test_corpus_from_file(self): c = Corpus.from_file(os.pa
th.join(DATASET_PATH, 'bookexcerpts.txt')) self.assertEqual(len(c), 140) self.assertEqual(len(c.domain), 0) self.assertEqual(len(c.domain.metas), 2) self.assertEqual(c.metas.shape, (140, 2)) def test_corpus_from_file_just_text(self): c = Corpus.from_file(os.path.join(DATASE...
velocyno/glances
glances/ports_list.py
Python
lgpl-3.0
5,667
0.003
# -*- coding: utf-8 -*- # # This file is part of Glances. # # Copyright (C) 2016 Nicolargo <nicolas@nicolargo.com> # # Glances is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
list =
[] if config is None: logger.debug("No configuration file available. Cannot load ports list.") elif not config.has_section(self._section): logger.debug("No [%s] section in the configuration file. Cannot load ports list." % self._section) else: logger.debug("S...
GenericMappingTools/gmt-python
pygmt/tests/test_helpers.py
Python
bsd-3-clause
3,568
0
""" Tests the helper functions/classes/etc used in wrapping GMT. """ import os import numpy as np import pytest from pygmt.exceptions import GMTInvalidInput from pygmt.helpers import ( GMTTempFile, args_in_kwargs, data_kind, kwargs_to_strings, unique_name, ) @pytest.mark.parametrize( "data,x,...
assert len(names) == len(set(names)) def test_kwargs_to_
strings_fails(): """ Make sure it fails for invalid conversion types. """ with pytest.raises(GMTInvalidInput): kwargs_to_strings(bla="blablabla") def test_gmttempfile(): """ Check that file is really created and deleted. """ with GMTTempFile() as tmpfile: assert os.path...
jrg365/gpytorch
test/examples/test_sgpr_regression.py
Python
mit
6,354
0.000944
#!/usr/bin/env python3 import os import random import unittest import warnings from math import exp, pi import gpytorch import torch from gpytorch.distributions import MultivariateNormal from gpytorch.kernels import InducingPointKernel, RBFKernel, ScaleKernel from gpytorch.likelihoods import GaussianLikelihood from g...
) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return Multivariat
eNormal(mean_x, covar_x) class TestSGPRRegression(unittest.TestCase): def setUp(self): if os.getenv("UNLOCK_SEED") is None or os.getenv("UNLOCK_SEED").lower() == "false": self.rng_state = torch.get_rng_state() torch.manual_seed(0) if torch.cuda.is_available(): ...
ChrisBuchholz/stonebear
stonebear/deploy.py
Python
gpl-3.0
245
0.004082
# -*- coding: utf-8 -*- from build import build from push import push from clean import clean def deploy(args, config):
''' convenience function that builds and pushes in one call ''' build(
args, config) push(args, config)
MartyParty21/AwakenDreamsClient
mcp/runtime/pylibs/normlines.py
Python
gpl-3.0
2,437
0
import sys import os import shutil import fnmatch import re from optparse import OptionParser def normaliselines(in_filename, out_filename=None): in_filename = os.path.normpath(in_filename) if out_filename is None: tmp_filename = in_filename + '.tmp' else: out_filename = os.pa...
if out_dirname is not None: dest_file = os.path.join(out_dirname, sub_dir, cur_file) else: dest_file = None
normaliselines(src_file, dest_file) def main(): usage = 'usage: %prog [options] src_file|src_dir [dest_file|dest_dir]' version = '%prog 6.0' parser = OptionParser(version=version, usage=usage) options, args = parser.parse_args() if len(args) == 1: in_name = args[0] out_na...
jmcnamara/XlsxWriter
xlsxwriter/test/comparison/test_set_column06.py
Python
bsd-2-clause
1,649
0
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier:
BSD-2-Clause # Copyright (c), 2013-2022, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(s...
def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'line'}) bold = workbook.add_format({'bold': 1}) italic = workbook.add_forma...
RossBarnie/rmt
web/client/HeartbeatClient.py
Python
gpl-2.0
1,171
0.002562
"""Heartbeat client, sends out an UDP packet periodically""" # Taken from http://code.activestate.com/recipes/52302-pyheartbeat-detecting-inactive-computers/ # Under PSF license import socket import time from ConfigParser import SafeConfigParser class config: def __init__(self): self.server_ip = "0.0.0...
cfg.server_ip, cfg.server_port) while True: cfg.refresh_config() hbSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) hbSocket.sendto('PyHB', (cfg.server_ip, cfg.server_port)) if __debug__: print 'Time: {}'.format(time.
ctime()) time.sleep(cfg.beat_period) if __name__ == "__main__": main()
jjgomera/pychemqt
lib/EoS/Cubic/RKTwu.py
Python
gpl-3.0
2,929
0
#!/usr/bin/python3 # -*- coding: utf-8 -*- r"""Pychemqt, Chemical Engineering Process simulator Copyright (C) 2009-2017, Juan José Gómez Romera <jjgomera@gmail.com> 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 Softwa...
}-\alpha^{(0)}\right)\\ \alpha^{(0)} = T_r^{-0.201158} \exp{0.141599\left(1-T_r^{2.29528} \right)}\\ \alpha^{(1)} = T_r^{-0.660145} \exp{0.500315\left(1-T_r^{2.63165
} \right)}\\ \end{array} """ __title__ = "Twu-Redlich-Kwong (1995)" __status__ = "RKTwu" __doi__ = { "autor": "Twu, C.H., Coon, J.E., Cunningham, J.R.", "title": "A New Generalized Alpha Function for a Cubic Equation of " "State Part 2. Redlich-Kwong equa...
nikesh-mahalka/cinder
cinder/tests/unit/api/contrib/test_volume_actions.py
Python
apache-2.0
41,283
0
# Copyright 2012 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.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
method = "POST" req.body = jsonutils.dumps(body) req.headers["content-type"] = "application/json" res = req.get_response(fakes.wsgi_app()) self.assertEqual(400, res.status_int) def test_initialize_connection_exception(self): with mock.patch.object(volume_api...
lize_connection') as init_conn: init_conn.side_effect = \ exception.VolumeBackendAPIException(data=None) body = {'os-initialize_connection': {'connector': 'fake'}} req = webob.Request.blank('/v2/fake/volumes/1/action') req.method = "POST" req.b...
ppizarror/TerminalDictionary
lib/mechanize/_msiecookiejar.py
Python
gpl-2.0
14,697
0.002177
"""Microsoft Internet Explorer cookie loading on Windows. Copyright 2002-2003 Johnny Lee <typo_pl@hotmail.com> (MSIE Perl code) Copyright 2002-2006 John J Lee <jjl@pobox.com> (The Python port) This code is free software; you can redistribute it and/or modify it under the terms of the BSD or ZPL 2.1 licenses (see the ...
ookie in cookie_data: flags = cookie["FLAGS"] secure = ((flags & 0x2000) != 0) filetime = (cookie["HIXP"] << 32) + cookie["LOXP"] expires = epoch_time_offset_from_win32_filetime(filetime) if expires < now: discard = True else:
discard = False domain = cookie["DOMAIN"] initial_dot = domain.startswith(".") if initial_dot: domain_specified = True else: # MSIE 5 does not record whether the domain cookie-attribute # was specified. ...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_11_01/operations/_express_route_circuit_connections_operations.py
Python
mit
24,012
0.005289
# 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 ...
parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_c...
raise HttpResponseError(response=response, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCircuits/{circuitName}/peerin...
letsmeet-click/letsmeet.click
letsmeet/letsmeet/context_processors.py
Python
mit
208
0
de
f environment(request): from django.conf import settings return { 'environment': getattr(settings, 'ENVIRONMENT', None), 'shackspace': getattr(setting
s, 'SHACKSPACE', None), }
pieterdp/doctoraat-ewout
prisoners/models/compare.py
Python
gpl-2.0
4,206
0.003091
import Levenshtein import re from prisoners import db from prisoners.models.original import Gedetineerde #prisonersmatch = db.Table('PrisonersMatch', # db.Column('master_id_ged', db.Integer, db.ForeignKey('PrisonersCompare.id_gedetineerde')), # db.Column('slave_id_ged...
def c_l_score(self): """ Compute the leve
nshtein distance between naamvoornaam and c_naamc_voornaam :return: """ master_naam = '{0}{1}'.format(self.Naam, self.Voornaam) master_c_naam = '{0}{1}'.format(self.c_naam, self.c_voornaam) non_alpha = re.compile('[^a-z]') # To lowercase master_naam.lower() ...
dajusc/trimesh
trimesh/graph.py
Python
mit
30,522
0
""" graph.py ------------- Deal with graph operations. Primarily deal with graphs in (n, 2) edge list form, and abstract the backend graph library being used. Currently uses networkx or scipy.sparse.csgraph backend. """ import numpy as np import collections from . import util from . import grouping from . import ex...
ate faces without exactly one unshared vertex per face it will be -1 """ # the non- shared vertex index is the same shape # as face_adjacency holding vertex indices vs face indices vid_unshared = np.zeros_like(mesh.face_adjacency, dtype=np.int64) - 1 # get the...
# faces from the current column of face adjacency faces = mesh.faces[fid] # should have one True per row of (3,) # index of vertex not included in shared edge unshared = np.logical_not(np.logical_or( faces == edges[:, 0].reshape((-1, 1)), faces == edges[:, ...
udacity/responsive-images
grading_scripts/2_5.py
Python
mit
1,377
0.008715
answer1 = widget_inputs["check1"] answer2 = widget_inputs["check2"] answer3 = widget_inputs["check3"] answer4 = widget_inputs["check4"] is_correct = False comments = [] def commentizer(new): if new not in comments: comments.append(new) if answer1 == True: is_correct = True els
e: is_correct = is_correct and False commentizer("Check the first answer. What would need to change if the resolutions are identical and the file sizes are different?") if answer2 == False: is_correct = is_correct and True else: is_correct = is_corr
ect and False commentizer("Check the second answer. Are the images the same size on the page? If so, the display resolutions are the same.") if answer3 == True: is_correct = is_correct and True else: is_correct = is_correct and False commentizer("Check the third answer. Do the original images have the ...
scribe777/collation_editor
python/collation/postprocessor.py
Python
gpl-3.0
24,405
0.008277
#-*- coding: utf-8 -*- """Algorithm for post-collate processing. """ from __future__ import print_function from functools import partial import copy import decimal import re import importlib from collation.regulariser import Regulariser import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwar...
sions = decisions self.display_settings_config = display_settings_config self.display_settings_config['configs'].sort(key=lambda k: k['execution_pos']) if local_python_functions: self.local_python_functions = local_python_functions module_name = local_python_functions['se...
et_rule_string']['class_name'] MyClass = getattr(importlib.import_module(module_name), class_name) self.set_rule_string_instance = MyClass() else: self.local_python_functions = None Regulariser.__init__(self, rule_conditions_config, local_python_functions) mod...
secnot/rectpack
tests/test_waste.py
Python
apache-2.0
2,165
0.002771
from unittest import TestCase import rectpack.waste as waste from rectpack.geometry import Rectangle class TestWaste(TestCase): def test_init(self): w = waste.WasteManager() def test_add_waste(self): w = waste.WasteManager() w.add_waste(30, 40, 50, 50) w.add_waste(5, 5, 20, 20...
ssertEqual(w.add_rect(30, 80), Rectangle(50, 40, 80, 30)) # Test rectangle rid w = waste.WasteManager(rot=True) w.add_waste(50, 40, 100, 40) rect = w.add_rect(30, 80, rid=23) self.assertEqual(rect.rid, 23) def test_iter(self): # Iterate through rectangles ...
0) w.add_waste(5, 5, 20, 20) w.add_waste(0, 100, 100, 100) w.add_rect(50, 50) for r in w: self.assertEqual(r, Rectangle(30, 40, 50, 50)) self.assertEqual(len(w), 1)
eric-stanley/robotframework
src/robot/parsing/htmlreader.py
Python
apache-2.0
6,458
0.001548
# Copyright 2008-2014 Nokia Solutions and Networks # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
if token.lower().startswith('charset='): return token[8:] def handle_pi(self, data): encoding = self._get_encoding_from_pi(data) if encoding:
self._encoding = encoding def _get_encoding_from_pi(self, data): data = data.strip() if not data.lower().startswith('xml '): return None if data.endswith('?'): data = data[:-1] for token in data.split(): if token.lower().startswith('encodin...
anhstudios/swganh
data/scripts/templates/object/mobile/shared_dressed_commoner_tatooine_trandoshan_female_01.py
Python
mit
478
0.046025
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPRO
PERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_comm
oner_tatooine_trandoshan_female_01.iff" result.attribute_template_id = 9 result.stfName("npc_name","trandoshan_base_female") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
AnasGhrab/scikit-learn
examples/decomposition/plot_pca_vs_fa_model_selection.py
Python
bsd-3-clause
4,467
0.001791
""" =============================================================== Model selection with Probabilistic PCA and Factor Analysis (FA) =============================================================== Probabilistic PCA and Factor Analysis are probabilistic models. The consequence is that the likelihood of new data can be u...
Wolf from sklearn.cross_validation import cross_val_score from sklearn.grid_search import GridSearchCV #######################################################
######################## # Create the data n_samples, n_features, rank = 1000, 50, 10 sigma = 1. rng = np.random.RandomState(42) U, _, _ = linalg.svd(rng.randn(n_features, n_features)) X = np.dot(rng.randn(n_samples, rank), U[:, :rank].T) # Adding homoscedastic noise X_homo = X + sigma * rng.randn(n_samples, n_featur...
itkach/mwscrape
mwscrape/scrape.py
Python
mpl-2.0
17,994
0.000889
# Copyright (C) 2013-2014 Igor Tkach # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # f
ile, You can obtain one at http://mozilla.org/MPL/2.0/. import argparse import fcntl import hashlib import os import random import socket import tempfile import time import traceback import urllib.parse from urllib.parse import urlparse from urllib.parse import urlunparse from collections import namedtuple from date...
time, timedelta from multiprocessing import RLock from multiprocessing.pool import ThreadPool from contextlib import contextmanager import couchdb import mwclient import mwclient.page import pylru import _thread def fix_server_url(general_siteinfo): """ Get server url from siteinfo's 'general' dict, add...
mrjacobagilbert/gnuradio
gr-channels/python/channels/impairments.py
Python
gpl-3.0
4,815
0.004777
#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Radio Impairments Model # Author: mettus # Generated: Thu Aug 1 12:46:10 2013 ################################################## from gnuradio import analog from gnuradio import blocks from gnuradio import g...
rt iqbal_gen from .distortion_2_gen import distortion_2_gen from .distortion_3_gen import distortion_3_gen class impairments(gr.hier_block2): def __init__(self, phase_noise_mag=0, magbal=0, phasebal=0, q_ofs=0, i_ofs=0, freq_offset=0, gamma=0, beta=0): gr.hier_block2.__init__( self,
"Radio Impairments Model", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.phase_noise...
blaulan/alfred-beancount
commandline.py
Python
mit
2,565
0.002339
# -*- coding: utf-8 -*- # @Author: Yue Wu <me@blaulan.com> # @Date: 2020-02-29 17:49:05 # @Last Modified By: Yue Wu <me@blaulan.com> # @Last Modified Time: 2020-03-02 22:06:26 from prompt_toolkit import PromptSession from prompt_toolkit.completion import Completer, Completion from prompt_toolkit.validation import ...
as ledger_file
: ledger_file.write(output['arg']+'\n\n') print(output['arg']) toolbar.clear_text() print('session ended!')
gimoh/ansible-modules-core
cloud/openstack/quantum_floating_ip.py
Python
gpl-3.0
10,210
0.007248
#!/usr/bin/python #coding: utf-8 -*- # (c) 2013, Benno Joy <benno@ansible.com> # # This module 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 ...
d'] fixed_ip_address =
ports['ports'][0]['fixed_ips'][0]['ip_address'] if not ports['ports']: return None, None return fixed_ip_address, port_id def _get_floating_ip(module, neutron, fixed_ip_address, network_name): kwargs = { 'fixed_ip_address': fixed_ip_address } try: ips = neutron.list_floa...
ygol/odoo
addons/mail/models/mail_render_mixin.py
Python
agpl-3.0
19,293
0.003473
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import babel import copy import datetime import dateutil.relativedelta as relativedelta import functools import logging import re from werkzeug import urls from odoo import _, api, fields, models, tools from odoo.excep...
n will be used. This should usually be a placeholder expression " "that provides the appropriate language, e.g. ${object.partner_id.lang}.") # expression builder model_object_field = fields.Many2one( 'ir.model.fields', string="Field", store=False, help="Select target field from the ...
\n" "If it is a relationship field you will be able to select " "a target field at the destination of the relationship.") sub_object = fields.Many2one( 'ir.model', 'Sub-model', readonly=True, store=False, help="When a relationship field is selected as first field, " ...
peterbe/bramble
bramble/base/api.py
Python
mpl-2.0
5,364
0.001305
import logging import anyjson as json from django.conf import settings as django_settings from django.http import HttpResponse, HttpResponseBadRequest from redis_utils import redis_client, RedisError log = logging.getLogger(__name__) def get_builds(request): ''' url handler that returns all known build uids...
content_type="application/json") redis_key = "change:%s" % (uid) try: r = redis_client('default') changeset_info = r.hgetall(redis_key) except RedisError as e: log.error('redis error: %s', e) changeset_info = {} return HttpResponse(json.serialize(changeset_info), ...
returns machine events and counts for how often they have occured event_type - restrict event types to one of `connect`, `disconnect`, 'build' """ if event_type not in ('connect', 'disconnect', 'build'): return HttpResponseBadRequest( json.serialize({'message': ...
YutingZhang/lmdis-rep
net_modules/distribution_utils.py
Python
apache-2.0
458
0
import tensorflow as tf import zutils.tf_m
ath_funcs as tmf # handle extended structure_param, pathc_feature_x, overall_features def reshape_extended_features(a, param_factor): if a is None: return None, None kept_sha
pe = tmf.get_shape(a)[:-1] + [tmf.get_shape(a)[-1] // param_factor] a = tf.reshape(a, kept_shape + [param_factor]) main_chooser = (slice(None, None),) * len(kept_shape) + (0,) b = a[main_chooser] return a, b
sztosz/neonet
DamageReports/views.py
Python
gpl-3.0
4,758
0.001892
#!/usr/bin/python # -*- coding: utf-8 -*- # # Created on 2013-10-11 # # @author: Bartosz Nowak sztosz@gmail.com # # This file is licensed GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 from __future__ import unicode_literals import unicodecsv from datetime import datetime, timedelta from pytz import timezone from...
select_related('commodity', 'detection_time', 'category', 'further_action', 'user').\ filter(date__range=(form.cleaned_data['date_from'], form.cleaned_data['date_to'])) writer = unicodecsv.writer(response, delimiter=b';') if not data: writer.writerow('Nie znaleziono żadnyc...
erial, report.detection_time.detection_time, report.category.category, report.comments, report.further_action.further_action, '', '', (report.user.first_name + ' ' + report.user.last_name) ] row = [element.strip(...
YeasterEgg/spotify_classify
mood/playlist_analyzer.py
Python
mit
1,640
0.026862
import pandas as pd import os import MySQLdb from sklearn.externals import joblib from sklearn.discriminant_analysis import LinearDiscriminantAnalysis import pdb ## PARSING METHODS def analyze_playlist(playlist, moods = ["happy", "sad"]): moods_tuple = tuple(sorted(moods)) filename = "_".join(mood for mood in mood...
"]["liveness"] parsed["valence"] = track["features"]["valence"] parsed["instrumentalness"] = track["
features"]["instrumentalness"] parsed["tempo"] = track["features"]["tempo"] parsed["speechiness"] = track["features"]["speechiness"] parsed["loudness"] = track["features"]["loudness"] return parsed ## ANALYSIS METHODS def load_model(filename): current_path = os.getcwd() file = os.p...
vicky2135/lucious
oscar/lib/python2.7/site-packages/phonenumbers/geodata/data11.py
Python
bsd-3-clause
914,640
0.021637
"""Per-prefix data, mapping each prefix to a dict of locale:name. Auto-generated file, do not edit by hand. """ from ..util import u # Copyright (C) 2011-2017 The Libphonenumber Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licens...
5f\u7701\u4f73\u6728\u65af\u5e02')}, '861361457':{'en': 'Da Hinggan Ling, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u5927\u5174\u5b89\u5cad\u5730\u533a')}, '861361456':{'en': 'Heihe, Heilongjiang', 'zh': u('\u9ed1\u9f99\u6c5f\u7701\u9ed1\u6cb3\u5e0
2')}, '861363024':{'en': 'YanAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u5ef6\u5b89\u5e02')}, '861363025':{'en': 'XiAn, Shaanxi', 'zh': u('\u9655\u897f\u7701\u897f\u5b89\u5e02')}, '861374730':{'en': 'Wuhai, Inner Mongolia', 'zh': u('\u5185\u8499\u53e4\u4e4c\u6d77\u5e02')}, '861374731':{'en': 'Wuhai, Inner Mongolia',...
root-mirror/root
bindings/pyroot/pythonizations/test/tcollection_listmethods.py
Python
lgpl-2.1
2,446
0.000818
import unittest import ROOT from libcppyy import SetOwnership class TCollectionListMethods(unittest.TestCase): """ Test for the Python-list-like methods added to TCollection (and subclasses): append, remove, extend, count """ num_elems = 3 # Helpers def create_tcollection(self): ...
itc1.Next(), itc2.Next()) def test_count(self): c = ROOT.TList() o1 = ROOT.TObject() o2 = ROOT.TObject() c.Add(
o1) c.Add(o2) c.Add(o1) self.assertEqual(c.count(o1), 2) self.assertEqual(c.count(o2), 1) if __name__ == '__main__': unittest.main()
axmachado/dia-group-resize
group_resize.py
Python
gpl-3.0
6,960
0.006753
# # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <axmachado@gmail.com> # # 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 Licen...
art(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'lar...
value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) ...
MarsZone/DreamLand
muddery/__init__.py
Python
bsd-3-clause
1,208
0.001656
""" Muddery text game creation system This is the main top-level API for Muddery. You can also explore the muddery library by accessing muddery.<subpackage> directly. For full functionality you need t
o explore this module via a django- aware shell. Go to your game directory and use the command 'muddery.py shell' to launch such a shell (using python or ipython depending on your install). See www.muddery.org for full documentation. """ from __future__ import print_function def _create_version(): """ Helpe...
STDOUT version = "Unknown" root = os.path.dirname(os.path.abspath(__file__)) try: with open(os.path.join(root, "VERSION.txt"), 'r') as f: version = f.read().strip() except IOError as err: print(err) return version __version__ = _create_version() del _create_version d...
SeyVu/subscription_renewal
nfl_ff_pred.py
Python
mit
8,303
0.004215
######################################################################################################### # Description: Function trying to predict fantasy points, yards and TDs for various players based on # their performance over past many years # ######################################################################...
columns=['name', 'year', 'team']).fit_transform(nfl_feat_space) logger.info(sf.Color.BOLD + sf.Color.GREEN + "Sample Data Post Label Encoding:" + sf.Color.END) logger.info(nfl_feat_space.head(3)) # Make NumPy Array x = nfl_feat_space.as_matrix().astype(np.float) # Handle Feature Scaling and Normal...
.info(sf.Color.BOLD + sf.Color.GREEN + "Sample Transformed Data:" + sf.Color.END) logger.info(x[0:3]) logger.info("Feature Space holds %d Observations and %d Features" % x.shape) return [x, y, nfl_df] #######################################################################################################...
antechrestos/cf-python-client
integration/v2/test_loggregator.py
Python
apache-2.0
457
0
import unittest import logging from config_test import build_clie
nt_from_configuration _logger = logging.getLogger(__name__) class TestLoggregator(unittest.TestCase): def test_recent(self): client = build_client_from_configuration() cpt = 0 for log_message in client.loggregator.get_
recent(client.log_app_guid): cpt += 1 _logger.debug("read %s", str(log_message)) _logger.debug("read %d", cpt)
dekom/threepress-bookworm-read-only
data/bin/convert.py
Python
bsd-3-clause
4,286
0.004445
#!/usr/bin/env python # -*- coding: utf-8 -*- from lxml import etree import os, sys, logging, subprocess from os.path import realpath, dirname import xapian sys.path.append('/home/liza/threepress') from threepress import settings db_dir = 'db/' main_db = 'threepress' logging.basicConfig(level=logging.WARNING) index...
text(para) # Add the document to the database. para_id = element.xpath('@xml:id')[0].replace('id', '') chapter_id = element.xpath('parent::tei:div[@type="chapter"]/@xml:id', namespaces={'tei':settings.TEI})[0] # Chapter ID is value 0 doc.add_value(settings.SEARCH_CHAPTER_ID...
ement.xpath('//tei:titleStmt/tei:title/text()', namespaces={'tei':settings.TEI})[0]) # Document ID is value 3 doc.add_value(settings.SEARCH_DOCUMENT_ID, id) # Create the document with the paragraph ID from the XML database.replace_document(int(para_id), doc) main_database.repla...
pfalcon/ScratchABit
plugins/cpu/x86_32_pymsasid.py
Python
gpl-3.0
816
0.001225
# ScratchABit - interactive disassembler # # Copyright (c) 2015-2018 Paul Sokolovsky # # 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 ...
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 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/>. import _x86_pymsasid def PROCESSOR_ENTRY(): return _x86_pymsasi...
wtaferner/odoo-addons
publisher_warranty_transparency/models/res_users.py
Python
agpl-3.0
941
0.003188
# -*- coding: utf-8 -*- from odoo import models, fields, api import logging _logger = logging.getLogger(__name__) class ResUsers(models.Model): _inherit = 'res.users' login_date = fields.Date( compute='_get_login_date', search='_search_login_date' ) @api.v7 def _get_login_date(...
self.pool.get('res.users')._get_login_date(self._cr, self._uid, self.ids, 'login_date', None, self._context) for user in self: user.login_date = res[user.id] @api.multi def _search_login_date(self, operator, value): users
= self.env['res.users.login'].search([('login_dt', operator, value)]) return [('id', 'in', users.ids)]
ambrosef/HLx_Examples
Acceleration/memcached/regressionSims/testgen/memtest_regressions.py
Python
bsd-3-clause
5,540
0.031588
#!/usr/bin/python import memlib ## EDIT HERE ################################################################### keySizes = [1,3,4,5,7,8,9,10,12,13,15,16,17,24,25,28,84,128] #valueSizes = [1,3,4,5,8,9,10,12,13,16,17,24,28,184,208,1024] valueSizes = [1,3,4,5,8,9,10,12,13,16,17,24,28,184,208, 256] seq1repeat = 5 key...
pen("
SEQ2_R12-pkt.in.hls.txt", "w") req.write( memlib.requests12Gbps_hls(SEQ2[0]) ) req.close() req = open("SEQ2_R1-pkt.in.hls.txt", "w") req.write( memlib.requests1Gbps_hls(SEQ2[0]) ) req.close() res = open("SEQ2-pkt.out.hls.txt", "w") res.write( memlib.responses_hls(SEQ2[1]) ) res.close() # SEQ3 req = open("SEQ3_R12-pkt....
Ubuntu-Solutions-Engineering/glance-simplestreams-sync-charm
hooks/charmhelpers/contrib/jujugui/utils.py
Python
agpl-3.0
20,533
0.000244
"""Juju GUI charm utilities.""" __all__ = [ 'AGENT', 'APACHE', 'API_PORT', 'CURRENT_DIR', 'HAPROXY', 'IMPROV', 'JUJU_DIR', 'JUJU_GUI_DIR', 'JUJU_GUI_SITE', 'JUJU_PEM', 'WEB_PORT', 'bzr_checkout', 'chain', 'cmd_log', 'fetch_api', 'fetch_gui', 'find_mis...
e', 'setup_gui', 'start_agent', 'start_gui', 'start_improv', 'write_apache_config', ] from contextlib import contextmanager import errno import json import os import logging import shutil from subprocess import CalledProcessError import tempfile from urlparse import urlparse import apt import temp...
n, script_name, search_file, su, ) from charmhelpers.core.host import ( service_start, ) from charmhelpers.core.hookenv import ( log, config, unit_get, ) AGENT = 'juju-api-agent' APACHE = 'apache2' IMPROV = 'juju-api-improv' HAPROXY = 'haproxy' API_PORT = 8080 WEB_PORT = 8000 CURRENT_DIR...
west-tandon/ReSearch
research/index/pruning.py
Python
mit
374
0.002674
from nltk.corpus import stopw
ords class BigUnicodePruner: def test(self, term): for ch in term:
if ord(ch) > 2048: return False return True class EnglishStopWordsPruner: def __init__(self): self.stopwords = set(stopwords.words('english')) def test(self, term): return term not in self.stopwords
wonder-sk/qgis-first-aid-plugin
handlers_qt.py
Python
gpl-2.0
453
0
from __future__ import absolute_import from qgis.PyQt.QtCore import * from .variablesview import custom_class_handlers, make_item def handle_QModelIndex(value, parent): make_item('valid', value.isValid(), parent) if value.isValid():
make_item('row', value.ro
w(), parent) make_item('column', value.column(), parent) make_item('parent', value.parent(), parent) custom_class_handlers[QModelIndex] = handle_QModelIndex
chinakr/jiaxiao
jiaxiao/home/url_dispatch.py
Python
gpl-2.0
613
0.006612
#-*- coding: utf-8 -*- """URL映射""" from django.views.generic.base import View from django.http import HttpResponse from django.shortcuts import render from jiaxiao.con
fig import site_name, channels, theme class URLDispatchView(View): """URL映射""" def get(self, request, page_name=''): """URL GET""" if page_name == '': page_name = 'index' template_name = '%s
/%s.html' % (theme, page_name) #return HttpResponse(page_name) return render(request, template_name, { 'site_name': site_name, 'channels': channels, })
robcarver17/pysystemtrade
sysinit/futures/roll_parameters_csv_mongo.py
Python
gpl-3.0
910
0.001099
""" Populate a mongo DB collection with roll data from a csv """ from sysdata.mongodb.mongo_roll_data import mongoRollParametersData from sysdata.csv.csv_roll_parameters import csvRollParametersData if __name__ == "__main__": input("Will overwrite existing data are you sure?! CTL-C to abort") # modify flags a...
ired data_out = mongoRollParametersData() data_in = csvRollParametersData() instrument_list = data_in.get_list_of_instruments() for instrument_code in instrument_list: instrument_object = data_in.get_roll_parameters(instrument_code) data_out.delete_roll_parameters(instrument_code, ar...
instrument_added = data_out.get_roll_parameters(instrument_code) print("Added %s: %s to %s" % (instrument_code, instrument_added, data_out))
crmccreary/openerp_server
openerp/addons/point_of_sale/report/account_statement.py
Python
agpl-3.0
1,923
0.0026
# -*- 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...
mport report_sxw class account_statement(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(account_statement, self).__init__(cr, uid, name, context=context) self.total = 0.0 self.localcontex
t.update({ 'time': time, 'get_total': self._get_total, 'get_data': self._get_data, }) def _get_data(self, statement): lines = [] for line in statement.line_ids: lines.append(line) return lines def _get_total(self, statement_line_...
mathjazz/pontoon
pontoon/sync/models.py
Python
bsd-3-clause
5,954
0.001176
import logging from django.urls import reverse from django.db import models from django.db.models import F, Max, Sum from django.utils import timezone from django.utils.functional import cached_property from pontoon.base.models import Project, ProjectLocale, Repository, TranslatedResource from pontoon.base.utils impo...
) repository = models.ForeignKey(Repository, models.CASCADE) start_time = models.DateTimeField(default=timezone.now) end_t
ime = models.DateTimeField(default=None, blank=True, null=True) @cached_property def finished(self): return self.end_time is not None def end(self): self.end_time = timezone.now() self.save(update_fields=["end_time"]) self.project_sync_log.sync_log.fix_stats()
raildo/python-keystoneclient
python-keystoneclient-0.4.1.7.gdca1d42/keystoneclient/base.py
Python
apache-2.0
15,511
0.00058
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 Jacob Kaplan-Moss # Copyright 2011 OpenStack Foundation # Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. ...
oked up in response dictionary, e.g., 'server' """ resp, body = self.client.get(url) return self.resource_class(self, body[response_key], loaded=True) def
_get_with_body(self, url, body, response_key): """Get an object from collection. :param url: a partial URL, e.g., '/servers' :param body: data that will be encoded as JSON and passed in GET request :param response_key: the key to be looked up in response dictionary, ...
thomasleese/gantt-charts
ganttcharts/web/routes/api.py
Python
mit
21,937
0.000729
""" Routes for the API. """ import datetime import dateutil.parser from cerberus import Validator import flask import sqlalchemy from ganttcharts.chart import Chart, InvalidGanttChart from ganttcharts.models import AccessLevel, Project, \ ProjectCalendarHoliday, ProjectEntry, ProjectEntryDependency, \ Projec...
r = get_
project_member_or_403(project) if flask.request.method == 'GET': if not account_member.access_level.can_view: raise errors.MissingPermission('can_view') return flask.jsonify(calendar=project.calendar.as_json()) elif flask.request.method == 'PATCH': if not account_member.acc...
prasadtalasila/MailingListParser
lib/input/imap/connection.py
Python
gpl-3.0
1,403
0.004277
import configparser import imaplib """ Gmail uses OAuth for authentications purposes. This means that a regular SSL connection request is refused by the mail server. So we have change the account settings to allow for access from less secure applications. """ def open_connection(verbose=False, config_file='./imap.co...
MAP connection to mail server. Takes as argument boolen value which is used to determine whether function works in verbose mode or not. :param verbose: Displays a detailed log if true. :param config_file: The file to be read by the configparser object.
""" # Reading from config file config = configparser.ConfigParser() config.read(config_file) # Creating connection to mail server using IMAP protocol hostname = config.get('server', 'hostname') if verbose: print('Connecting to ', hostname, ' ...') connection = imaplib.IMAP4_SSL(...
datasciencebr/serenata-de-amor
rosie/rosie/chamber_of_deputies/settings.py
Python
mit
876
0.001142
from rosie.chamber_of_deputies.classifiers import
ElectionExpensesClassifier from rosie.chamber_of_deputies.classifiers import IrregularCompaniesClassifier from rosie.chamber_of_deputies.classifiers import MealPriceOutlierClassifier from rosie.chamber_of_deputies.classifiers import MonthlySubquotaLimitClassifier from rosie.chamber_of_deputies.classifiers import Travel...
er, 'over_monthly_subquota_limit': MonthlySubquotaLimitClassifier, 'suspicious_traveled_speed_day': TraveledSpeedsClassifier, 'invalid_cnpj_cpf': InvalidCnpjCpfClassifier, 'election_expenses': ElectionExpensesClassifier, 'irregular_companies_classifier': IrregularCompaniesClassifier } UNIQUE_IDS = ...
vitlav/libnatspec
src/python/setup.py
Python
lgpl-2.1
546
0.086081
from distutils.core import setup, Extension m
odule1 = Extension('_natspec', define_macros = [('MAJOR_VERSION','0'), ('MINOR_VERSION','1')], include_dirs = ['../../include'], library_dirs = ['../../lib'], libraries = ['natspec'], sources = ['natspec_wrap.c']) setup (name='_natspec', version = '0.1.9', descript
ion = 'Python wrapper module for the LIBNATSPEC', author = 'Vitaly Lipatov', author_email = 'lav@etersoft.ru', long_description = ''' Wrapper for the Nation Specifity Library ''', ext_modules = [module1])
krishna11888/ai
third_party/gensim/gensim/test/test_hdpmodel.py
Python
gpl-2.0
2,047
0.00342
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Automated tests for checking transformation algorithms (the models package). """ import logging import unittest import os import o...
del self.model = self.class_(corpus, id2word=dictionary) def testShowTopics(self): topics = self.model.show_topics(formatted=False) for topic_no, topic in topics: self.assertTrue(isinstance(topic_no, int)) self.assertTrue(isinstance(topic, list))
for k, v in topic: self.assertTrue(isinstance(k, six.string_types)) self.assertTrue(isinstance(v, float)) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG) unittest.main()
pielgrzym/django-minishop
chartstats/chart.py
Python
gpl-3.0
4,294
0.015144
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response, get_object_or_404 from django.template.context import RequestContext from django.http import Http404, HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ import time, datetime, calendar import simplejson as json from char...
o be callable to be able to be invoked right within urls.py """ if request.method == 'GET': form = self.form() report_data = "" sql = "" else: form = self.form(request.POST) if form.is_valid(): params = {
'date_field': self.date_field, 'table': self.table, } # dynamically append all form field data do params for key in form.cleaned_data.keys(): params[key] = form.cleaned_data[key] report_data = self.fetch_data(params) flot_settings = self.flot_settings(...
xuru/pyvisdk
pyvisdk/do/event.py
Python
mit
1,384
0.010116
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def Event(vim, *args, **kwargs): '''This event is the base data object type from which al...
# do some validation checking... if (len(args) + len(kwargs)) < 4: raise IndexError('Expected at least 5 arguments got: %d' % len(args)) required = [ 'chainId', 'createdTime', 'key', 'userName' ] optional = [ 'changeTag', 'computeResource', 'datacenter', 'ds', 'dvs', 'fullFormattedMess...
value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj
eleonrk/SickRage
sickbeard/providers/btn.py
Python
gpl-3.0
12,849
0.002957
# coding=utf-8 # Author: Daniel Heimans # # URL: https://sickchill.github.io # # This file is part of SickChill. # # 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 version 3 of the License, o...
import jsonrpclib import six import sickbeard from sickbeard import classes, logger, scene_exceptions, tvcache from sickbeard.common import cpu_presets from sickbeard.helpers import sanitizeSceneName from sickchill.helper.common import episode_num from sickchill.helper.exceptions import AuthException, ex from sickch...
) self.supports_absolute_numbering = True self.api_key = None self.cache = BTNCache(self, min_time=15) # Only poll BTN every 15 minutes max self.urls = {'base_url': 'http://api.broadcasthe.net', 'website': 'http://broadcasthe.net/', } self.url = self.ur...
Trigition/Mimir
MimirInterface/MimirInterface/settings.py
Python
gpl-2.0
2,662
0
""" Django settings for MimirInterface project. Generated by 'django-admin startproject' using Django 1.8.6. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Bui...
django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'MimirInterface.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': '
django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs....
EricRho/home-assistant
homeassistant/components/device_tracker/actiontec.py
Python
mit
6,633
0.000151
""" homeassistant.components.device_tracker.actiontec ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Device tracker platform that supports scanning an Actiontec MI424WR (Verizon FIOS) router for device presence. This device tracker needs telnet to be enabled on the router. Configuration: To use the Action...
if not self.last_results: return None for client in self.last_results: if client.mac == device: return client.i
p return None @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): """ Ensures the information from the Actiontec MI424WR router is up to date. Returns boolean if scanning successful. """ _LOGGER.info("Scanning") if not self.success_init: re...
nasa-nccs-cds/CDAS2
python/test/helloServer.py
Python
gpl-2.0
466
0.002146
# # Hello
World server in Python # Binds REP socket to tcp://*:5555 # Expects b"Hello" from client, replies with b"World" # import time import zmq context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5555") while True: # Wait for next request from client message = socket.recv() p
rint("Received request: %s" % message) # Do some 'work' time.sleep(1) # Send reply back to client socket.send(b"World")
italoag/M101P
Week3/hw3-1/hw3.1.py
Python
mit
528
0
import pymongo connection = pymongo.Connection("mongodb://localhost", safe=True) db = connection.school students = db.students cursor = students.find({}, {'scores': 1}) for entry in cursor: _id = entry['_id'] scores = entry['scores'] hw_scores = [] for score in scores:
if score['type'] == 'homework': hw_scores.append(score['score']) hw_scores.sort() scores.remove({'type': 'homework', 'score': hw_scores[0]}) students.up
date({'_id': _id}, {'$set': {'scores': scores}})
druids/django-ats-sms-operator
ats_sms_operator/cores/views.py
Python
lgpl-3.0
1,841
0.003802
from __future__ import unicode_literals from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as _ from is_core.generic_views.form_views import AddModelFormView from ats_sms_operator.config import ATS_STATES, settings from ats_sms_operator.sender import send_multiple from ....
'error': _('Please correct the error below.') } def get_message_kwargs(self, objs): return {'recipients': ', '.join(force_text(obj.recipient) for obj in objs)}
def save_form(self, form, **kwargs): objs = form.save(commit=False) for obj in objs: obj.state = (ATS_STATES.DEBUG if settings.DEBUG and obj.recipient not in settings.WHITELIST else ATS_STATES.PROCESSING) obj.save() send_multiple(*objs) ...
AppliedAlgorithmsGroup/leon-lee
test/python/equal_tests.py
Python
mit
4,152
0.000482
from python.equal import Equal def count_steps_test(): equal_instance = Equal() array_a = [2, 2, 3, 7] array_b = [53, 361, 188, 665, 786, 898, 447, 562, 272, 123, 229, 629, 670, 848, 994, 54, 822, 46, 208, 17, 449, 302, 466, 832, 931, 778, 156, 39, 31, 777, 749, 436, 138, 289...
22, 942, 664, 36, 400, 857] array_c = [520, 862, 10, 956, 498, 956, 991, 542, 523, 664, 378, 194, 76, 90, 753, 868, 837, 830, 93
2, 814, 616, 78, 103, 882, 452, 397, 899, 488, 149, 108, 723, 22, 323, 733, 330, 821, 41, 322, 715, 917, 986, 93, 111, 63, 535, 864, 931, 372, 47, 215, 539, 15, 294, 642, 897, 98, 391, 796, 939, 540, 257, 662, 562, 580, 747, 893, 401, 789, 215, 468, 58, 553, 5...
PhilippMundhenk/IVNS
ECUSimulation/io_processing/result_interpreter/checkpoint_interpreter.py
Python
mit
29,278
0.012433
from io_processing.result_interpreter.abst_result_interpreter import AbstractInterpreter, \ InterpreterOptions from io_processing.surveillance_handler import CheckpointHandler from tools.general import RefList, General as G from enum import Enum import logging class CheckpointInterpreter(AbstractInterpreter): ...
bytes per category and ECU: \t" , self.timing.bytes_sent_per_category_and_ecu, "bytes")) txt_lines.
append(StringBeautifier().pretty_comp_cat("Received bytes per category and ECU: \t" , self.timing.bytes_received_per_category_and_ecu, "bytes")) txt_lines.append(StringBeautifier().pretty_comp_cat("Sent bytes per category and ECU [per cent]: \t" , self.timing.percent_bytes_sent_per_category_and_ecu, "%"...
ammannbros/garden-lighting
garden_lighting/light_control_dummy.py
Python
mit
457
0.004376
class LightControl: def __init__(self, max_
switch, logger, a_address, a_rst_pin, b_address, b_rst_pin): pass def run(self): pass def init(self): pass def can_switch(self, light): pass def update_switched(self, light): pass def schedule_switch(self, light, mode, time): pass def get_lig...
lights): pass
jrversteegh/softsailor
deps/scipy-0.10.0b2/scipy/signal/signaltools.py
Python
gpl-3.0
49,881
0.000421
# Author: Travis Oliphant # 1999 -- 2002 import sigtools from scipy import linalg from scipy.fftpack import fft, ifft, ifftshift, fft2, ifft2, fftn, \ ifftn, fftfreq from numpy import polyadd, polymul, polydiv, polysub, roots, \ poly, polyval, polyder, cast, asarray, isscalar, atleast_1d, \ on...
if product(s1, axis=0) > product(s2, axis=0): osize = s1 else: osize = s2 return _centered(ret, osize) elif mode == "valid": return _centered(ret, abs(s2 - s1) + 1) def convolve(in1, in2, mode='full'): """ Convolve two N-dimensional
arrays. Convolve in1 and in2 with output size determined by mode. Parameters ---------- in1: array first input. in2: array second input. Should have the same number of dimensions as in1. mode: str {'valid', 'same', 'full'} a string indicating the size of the output: ...
wfn/bridgedb
lib/bridgedb/Tests.py
Python
bsd-3-clause
30,756
0.005527
# BridgeDB by Nick Mathewson. # Copyright (c) 2007-2009, The Tor Project, Inc. # See LICENSE for licensing information from __future__ import print_function import doctest import os import random import sqlite3 import tempfile import unittest import warnings import time from datetime import datetime import bridgedb....
inally: b.or_addresses[address] = portlist try: portlist.add(b.or_addresses[address]
) except KeyError: pass finally: b.or_addresses[address] = portlist if transports: for i in xrange(0,8): b.transports.append(bridgedb.Bridges.PluggableTransport(b, random.choice(["obfs", "obfs2", "pt1"]), ra...
gordon-/yolo
learning/validators.py
Python
agpl-3.0
555
0
import re from django.core.exceptions import ValidationError def colorValidator(value): """ Validate
s if the given value is a string representing an hexadecimal color value (starts with a #, then RGB composants in hex). >>> colorValidator('#0a1b2C') >>> colorValidator('#AAAAAA') >>> colorValidator('ff00ff') ValidationError: ['ff00ff is not a valid hex color.'] """ exp = re.compile('^#[a...
not a valid hex color.'.format(value))
thedemz/python-gems
bitten.py
Python
mit
978
0.014315
import codecs unicode_string = "Hello Python 3 String" bytes_object = b
"Hello Python 3 Bytes" print(unicode_stri
ng, type(unicode_string)) print(bytes_object, type(bytes_object)) #decode to unicode_string ux = str(object=bytes_object, encoding="utf-8", errors="strict") print(ux, type(ux)) ux = bytes_object.decode(encoding="utf-8", errors="strict") print(ux, type(ux)) hex_bytes = codecs.encode(b"Binary Object", "hex_code...
Zbsiz/ZQ-home
python/test.py
Python
gpl-3.0
1,308
0.014526
word = 'a loooooooog word' num = 12 string = 'bang!' total = string * (len(word) - num) print(len(word)) print(total) phone_number = '1386-666-0006' hiding_number = phone_number.replace(phone_number[:9], '*') print(hiding_number) search = '168' num_a = '1386-168-0006' #print(search + ' is at ' + str(num_a.find(searc...
,sep='\n') def text_filter(word, censored_word = 'lame', changed_word = 'Awesome'): return word.replace(censored_word, changed_word) def text_create
(name, msg): desktop_path = './' full_path = desktop_path + name + '.txt' file = open(full_path, 'w') file.write(text_filter(msg)) file.close() print("done") text_create('nihao', 'lame\n')
Udzu/pudzu
dataviz/nobelslit.py
Python
mit
5,009
0.015572
import seaborn as sns from pudzu.charts import * from pudzu.sandbox.bamboo import * countries = pd.read_csv("datasets/countries.csv")[["country", "continent", "flag"]].split_columns('country', "|").explode('country').set_index('country') df = pd.read_csv("datasets/nobels.csv") df = df[df['category'] == "Litera...
egend], bg="white",
yalign=0, padding=5) title = Image.from_text("Geographic distribution of Literature Nobel laureates", arial(24, bold=True)).pad((0,4,0,8), "white") img = Image.from_column([title, chart], bg="white") img.place(Image.from_text("/u/Udzu", font("arial", 16), fg="black", bg="white", padding=5).pad((1,1,0,0), "black"), a...
hackshel/metaCollecter
src/metaManager/modules/cmdbServer.py
Python
bsd-3-clause
3,610
0.033408
# -*- coding: utf-8 -*- import httplib import pprint import json import sys import logging import datetime import os import os.path import codecs class cmdb( object ): def __init__( self, args , info=None ): self.res = {} self.result = {} self.info = info self.args = args ...
arning( loginfo ) if level == 'error' :logging.error( loginfo ) def dataFormat( self,data,cmdb_node ): rr = {} if cmdb_node != {}: rr['id'] = cmdb_node['.id'] rr['m
anifest'] = cmdb_node['.manifest'] rr['value'] = data else: rr['id'] = '' rr['manifest'] = '' rr['value'] = data return rr if __name__ == '__main__': import conf.cmdb_config as conf conditions = [ {'name':'rack','tag':'~','...
cemsbr/python-openflow
tests/v0x01/test_controller2switch/test_barrier_reply.py
Python
mit
562
0
"""Barrier reply message tests.""" from pyof.v0x01.controller2swit
ch.barrier_reply import BarrierReply from tests.test_struct import TestStruct class TestBarrierReply(TestStruct): """Barrier reply message tests (also those in :class:`.TestDump`).""" @classmethod def setUpClass(cls): """Configure raw file and its object in parent class (TestDump).""" sup...
) super().set_raw_dump_object(BarrierReply, xid=5) super().set_minimum_size(8)
googleapis/python-tasks
samples/generated_samples/cloudtasks_v2beta2_generated_cloud_tasks_renew_lease_async.py
Python
apache-2.0
1,455
0.000687
# -*- 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...
a2_generated_CloudTasks_RenewLease_async] from google.cloud import tasks_v2beta2 async def sample_renew_lease(): # Create a client client = tasks_v2beta2.CloudTasksAsyncCl
ient() # Initialize request argument(s) request = tasks_v2beta2.RenewLeaseRequest( name="name_value", ) # Make the request response = await client.renew_lease(request=request) # Handle the response print(response) # [END cloudtasks_v2beta2_generated_CloudTasks_RenewLease_async]
google/vizier
vizier/testing/test_studies.py
Python
apache-2.0
2,373
0.006321
"""Test study generator.""" from typing import Collection from vizier.pyvizier import pythia as vz def flat_space_with_all_types() -> vz.SearchSpace: """Search space with all parameter types.""" space = vz.SearchSpace() root = space.select_root() root.add_float_param('lineardouble', -1., 2.) root.add_floa...
urn [ vz.MetricInformation('gain', goal=vz.ObjectiveMetricGoal.MAXIMIZE), vz.MetricInformation('loss', goal=vz.ObjectiveMetricGoal.MINIMIZE), vz.MetricInformation( 'gt2', goal=vz.ObjectiveMetricGoal.MAXIMIZE, safety_threshold=2.0), vz.MetricInformation( 'lt2', goal=vz.Objecti...
ef metrics_all_constrained() -> Collection[vz.MetricInformation]: return [ vz.MetricInformation( 'auc', goal=vz.ObjectiveMetricGoal.MAXIMIZE, min_value=0.0, max_value=1.0), vz.MetricInformation( 'crossentropy', goal=vz.ObjectiveMetricGoal.MINIMIZE, min_val...
tech-blogging/sdataflow
sdataflow/callback/helper.py
Python
mit
417
0
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, print_function, unicode_literals) from sdataflow.shared import to_uni
code def create_data_wrapper(outcome_type_name): name = to_unicode(outcome_type_name) if name is None: raise RuntimeError
('create_data_wrapper') def wrapper(data): return (outcome_type_name, data) return wrapper
swappr-tanda-team/swappr
runserver.py
Python
mit
71
0
from swappr imp
ort app app.run(debug=True, host="0.0.0.0", port=90
00)
staranjeet/fjord
fjord/feedback/migrations/0003_delete_empty_desc_feedback.py
Python
bsd-3-clause
783
0
# -*- coding: utf-8 -*- """Deletes all feedback that have a description that's an empty string. """ from __future__ import unicode_literals import sys from django.db import models, migrations def delete_feedback(apps, schema_editor):
"""Delete all feedback with an empty description""" Response = apps.get_model('feedback', 'Response') qs = Response.objects.filter(description='') c
ount = qs.count() if count > 0: qs.delete() if 'test' not in sys.argv: print 'Deleted {0} responses'.format(count) def noop(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('feedback', '0002_make_products'), ] operations = [...
dvirtz/gmusicapi
gmusicapi/clients/musicmanager.py
Python
bsd-3-clause
24,772
0.002341
import os from socket import gethostname import time import urllib from uuid import getnode as getmac import webbrowser import httplib2 # included with oauth2client from oauth2client.client import OAuth2WebServerFlow, TokenRevokeError import oauth2client.file import gmusicapi from gmusicapi.clients.shared import _Ba...
is not None: if storage_filepath == OAUTH_FILEPATH: utils.make_sure_path_exists(os.pat
h.dirname(OAUTH_FILEPATH), 0o700) storage = oauth2client.file.Storage(storage_filepath) storage.put(credentials) return credentials def __init__(self, debug_logging=True, validate=True, verify_ssl=True): super(Musicmanager, self).__init__(self.__class__.__name__, ...
bluescarni/hyperion
docs/tutorials/scripts/flyaround_cube_animate.py
Python
bsd-2-clause
1,402
0
import os import numpy as np import matplotlib.pyplot as plt from hyperion.model import ModelOutput from hyperion.util.constants import pc # Create output directory if it does not already exist if not os.path.exists('frames'): os.mkdir('frames') # Open model m = ModelOu
tput('flyaround_cube.rtout') # Read image from model image = m.get_
image(distance=300 * pc, units='MJy/sr') # image.val is now an array with four dimensions (n_view, n_y, n_x, n_wav) for iview in range(image.val.shape[0]): # Open figure and create axes fig = plt.figure(figsize=(3, 3)) ax = fig.add_subplot(1, 1, 1) # This is the command to show the image. The parame...
LispyAriaro/instant-press
languages/pl.py
Python
gpl-2.0
9,384
0.022888
# coding: utf8 { '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyrażeniem postaci "pole1=\'nowawartość\'". Nie możesz uaktualnić lub usunąć wyników z JOIN:', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%...
hcesz usunąć ten obiekt?', 'Sure you want to delete this style?': 'Sure you want to delete this style?', 'Sure you want to delete this user?': 'Sure you want to delete this user?', 'Table name': 'Nazwa tabeli', 'Tags': 'Tags', 'The "query" is a condition like "db.table1.field1==\'value\'".
Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Zapytanie" jest warunkiem postaci "db.tabela1.pole1==\'wartość\'". Takie coś jak "db.tabela1.pole1==db.tabela2.pole2" oznacza SQL JOIN.', "The article id doesn't exist": "The article id doesn't exist", "The article id or page number doesn't...