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
liuyi1112/rst2pdf
rst2pdf/writer.py
Python
mit
860
0
# -*- coding: utf-8 -*- # See LICENSE.txt for licensing terms from StringIO import StringIO from docutils import writers from rst2pdf import createpdf class PdfWriter(writers.Writer): def __init__(self, builder): writers.Writer.__init__(self) self.builder = builder self.output = u'' ...
-8', 'ignore') def supports(self, format): """This writer supports all format-specific el
ements.""" return 1
qiuxs/ice-demos
python/Ice/properties/Client.py
Python
gpl-2.0
3,232
0.003403
#!/usr/bin/env python # ********************************************************************** # # Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. # # ********************************************************************** import sys, traceback, Ice slice_dir = Ice.getSliceDir() if not slice_dir: print(sy...
menu() c = None while c != 'x': try: sys.stdout.write("==> ") sys.st
dout.flush() c = sys.stdin.readline().strip() if c == "1" or c == "2": propsDict = c == "1" and batch1 or batch2 print("Sending:") for k, v in propsDict.items(): if k.startswith("Demo"): ...
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/testing/test_env.py
Python
mit
8,248
0.013337
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Sets environment variables needed to run a chromium unit test.""" import os import stat import subprocess import sys # This is...
stderr=sys.stdout) p2 = subprocess.
Popen( get_sanitizer_symbolize_command(executable_path=cmd[0]), env=env, stdin=p1.stdout) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. p1.wait() p2.wait() # Also feed the out-of-band JSON output to the symbolizer script. symbolize_snippets_in_json(cmd...
cycladesnz/chambersAndCreatures
src/item/suf_potions.py
Python
gpl-2.0
1,217
0.013969
import random from pdcglobal import * from effects import * def PotionOfKillbeePoison(item): item.full_name += ' of Killerbee-Poison' item.weaponinfotext = 'Dangerous Poison' def DrinkPotionOfKillbeePoison(self, actor): KillerbeePoisonEffect(actor,None) def PotionOfYumuraPoison(item): item.full_name ...
name += ' of Endurance' def DrinkPotionOfEndurance(self, actor): actor.cur_endurance += d(10) + d(10) def PotionOfMind(item): item.full_name += ' of Mind' def DrinkPotionOfMind(self, actor): actor.cur_mind += d(10) + d(10) def PotionOfSpellcaster(item):
item.full_name += ' of Spellcasters' def DrinkPotionOfSpellcaster(self, actor): actor.cur_endurance += d(10) + d(10) actor.cur_mind += d(10) + d(10) def PotionOfHealing(item): item.full_name += ' of Healing' def DrinkPotionOfHealing(self, actor): actor.cur_health += d(10)
osiloke/Flumotion-Transcoder
flumotion/transcoder/admin/adminconsts.py
Python
lgpl-2.1
5,673
0.000353
# vi:si:et:sw=4:sts=4:ts=4 # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L. # Copyright (C) 2010,2011 Flumotion Services, S.A. # All rights reserved. # # This file may be distributed and/or modified under the terms of # the GNU Lesser General Public License version 2.1...
MPLATE = "%(customerName)s/%(profileName)s transcoding %(trigger)s" DEFAULT_MAIL_BODY_TEMPLATE = """ Transcoding Report ================== Customer Name: %(customerName)s Profile Name: %(profileName)s -------------- File: '%(inputRelPath)s' Message: %(errorMessage)s """ # Default CustomerStore values DEFAULT...
oming" DEFAULT_OUTPUT_DIR = "/%s/files/outgoing" DEFAULT_FAILED_DIR = "/%s/files/failed" DEFAULT_DONE_DIR = "/%s/files/done" DEFAULT_LINK_DIR = "/%s/files/links" DEFAULT_CONFIG_DIR = "/%s/configs" DEFAULT_TEMPREP_DIR = "/%s/reports/pending" DEFAULT_FAILEDREP_DIR = "/%s/reports/failed" DEFAULT_DONEREP_DIR = "/%s/reports...
ryanss/holidays.py
test/countries/test_nicaragua.py
Python
mit
1,698
0
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holida
y as fast and flexible as possible. # # Authors: dr-prodigy <maurizio.montel@gmail.com> (c) 2017-2022 # ryanss <ryanssdev@icloud.com> (c) 2014-2017 # Website: https://github.com/dr-prodigy/python-holidays # License: MIT (see LICENSE file) import unittest from datetime import date import holidays class...
lf): self.ni_holidays = holidays.NI() def test_ni_holidays_2020(self): year = 2020 mn_holidays = holidays.NI(prov="MN") # New Year's Day self.assertIn(date(year, 1, 1), self.ni_holidays) # Maundy Thursday self.assertIn(date(year, 4, 9), self.ni_holidays) ...
Ictp/indico
indico/MaKaC/plugins/Collaboration/CERNMCU/options.py
Python
gpl-3.0
5,215
0.011697
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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; eith...
m Booking database.", "type": str, "defaultValue": "H323 IP", "editable": True, "visible": True}), ("extraMinutesBefore", {"description" : "Extra minutes allowed before Indico event s
tart time", "type": int, "defaultValue": 60} ), ("extraMinutesAfter", {"description" : "Extra minutes allowed after Indico event start time", "type": int, "defaultValue": 120} ), ("defaultMinutesBefor...
shlomozippel/ansible
plugins/callbacks/log_plays.py
Python
gpl-3.0
3,121
0.001922
# (C) 2012, Michael DeHaan, <michael.dehaan@gmail.com> # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
t, handler): pass def playbook_on_task_start(self, name, is_conditional): pass def playbook_on_vars_prompt(self, varname, private=True, prompt=None, encrypt=None, confirm=False
, salt_size=None, salt=None, default=None): pass def playbook_on_setup(self): pass def playbook_on_import_for_host(self, host, imported_file): log(host, 'IMPORTED', imported_file) def playbook_on_not_import_for_host(self, host, missing_file): log(host, 'NOTIMPORTED', missi...
edonyM/emthesis
code/num2iter.py
Python
mit
3,819
0.005237
#!/usr/bin/env python3 # -*- coding: utf-8 -*- r""" # .---. .----------- # / \ __ / ------ # / / \( )/ ----- (`-') _ _(`-') <-. (`-')_ # ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .-> # //// / // : : --- (,------...
y1 = np.linspace(38092, 40318,
100) y2 = np.linspace(507330, 800274, 100) y3_1 = np.linspace(2500737,3082897, 50) + 1000000 y3 = np.linspace(3082897, 2300181, 50) + 5000 y3_1 = list(y3_1) y3_1.extend(list(y3)) y3 = np.array(y3_1) y1 = [i+np.random.randint(50000, 100000) for i in y1] y2 = [i+np.random.randint(50000, 100000) for i in y2] y3 = [i+np.r...
vidartf/hyperspy
hyperspy/tests/signal/test_eds_tem.py
Python
gpl-3.0
12,087
0
# Copyright 2007-2016 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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 ...
rgy_axis.units = 'keV' energy_axis.name = "Energy" s.set_microscope_parameters(beam_energy=200, live_time=3.1, tilt_stage=0.0, azimuth_angle=None, elevation_angle=35, energy_resolution_MnKa=130) ...
.Acquisition_instrument.TEM.Detector.EDS.real_time = 2.5 s.metadata.Acquisition_instrument.TEM.beam_current = 0.05 elements = ['Al', 'Zn'] xray_lines = ['Al_Ka', 'Zn_Ka'] intensities = [300, 500] for i, xray_line in enumerate(xray_lines): gauss = Gaussian() ...
harryfb/DST5
ArcPy Code/Trees.py
Python
apache-2.0
760
0.015789
# import system modules import arcpy from
arcpy import env # Set environment settings env.workspace = "C:\Users\Ewan\Desktop\SFTPDST5\MapFiles" try: # Set the local variable in_Table = "Trees.csv" x_coords = "X"
y_coords = "Y" z_coords = "Z" out_Layer = "Trees_Layer" saved_Layer = "C:\Users\Ewan\Desktop\SFTPDST5\Mapfiles\Trees.lyr" # Set the spatial reference spRef = r"Coordinate Systems\Geographic Coordinate Systens\World\WGS 1984.prj" # Make the XY Event Layer arcpy.MakeXYEventLayer_...
sangwook236/sangwook-library
python/test/language_processing/synth90k_crnn.py
Python
gpl-2.0
29,148
0.020207
import abc import numpy as np import tensorflow as tf from swl.machine_learning.tensorflow_model import SimpleSequentialTensorFlowModel import swl.machine_learning.util as swl_ml_util #-------------------------------------------------------------------- class Synth90kCrnn(SimpleSequentialTensorFlowModel): def __init...
hape #conv5.shape.as_list() self._model_output_len = conv5_shape[1] #dense = tf.reshape(conv5, shape=conv5_shape[:2] + (-1,), name='reshape') #dense = tf.reshape(conv5, shape=conv5_shape[:2] + (conv5_shape[2] * conv5_shape[3]), name='reshape') outputs = tf.reshape(conv5, shape=(-1, conv5_shape[1], conv5_sh...
u, kernel_initializer=kernel_initializer, name='dense') def _create_recurrent_layer(self, inputs, input_len, kernel_initializer, is_training): num_hidden_units = 256 keep_prob = 1.0 #keep_prob = 0.5 with tf.variable_scope('rnn1', reuse=tf.AUTO_REUSE): cell_fw1 = self._create_unit_cell(num_hidden_units, ke...
Notgnoshi/clippy
clippy/clipboard.py
Python
mit
1,004
0.001992
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk class Clipboard(object): """A wrapper around GTK3's clipboard interface. Text only.""" def __init__(self): self._clipboard = Gtk.Clipboard.get(Gdk.
SELECTION_CLIPBOARD) self.text = None def __repr__(self): return str(self.text) def set(self, text): """ Set the contents of the clipboard. """ # -1 means figure out the length. self._clipboard.set_text(text, -1) self._clipboard.store() ...
""" return self._clipboard.wait_for_text() def hasUpdate(self): """ Check to see of the contents of the clipboard have changed since the last time this method was called. """ temp = self.get() if temp != self.text: self.text = temp ...
alikins/subscription-manager
src/subscription_manager/gui/networkConfig.py
Python
gpl-2.0
13,296
0.002332
# # Copyright (c) 2010 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy o...
# Update the proxy entry field to show we removed any scheme self.proxyEntry.set_text(proxy) try:
proxy_hostname, proxy_port = proxy.split(':') self.cfg.set("server", "proxy_hostname", proxy_hostname) self.cfg.set("server", "proxy_port", proxy_port) except ValueError: # no port? just write out the hostname and assume default ...
dknlght/dkodi
src/script.module.cryptopy/lib/crypto/hash/sha1Hash_test.py
Python
gpl-2.0
2,199
0.012278
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- """ sha1Hash_test.py Unit tests for sha1.py """ from crypto.hash.sha1Hash import SHA1 import unittest import stru
ct assert struct.calcsize('!IIIII') == 20, '5 integers should be 20 bytes' class SHA1_FIPS180_TestCases(unittest.TestCase): """
SHA-1 tests from FIPS180-1 Appendix A, B and C """ def testFIPS180_1_Appendix_A(self): """ APPENDIX A. A SAMPLE MESSAGE AND ITS MESSAGE DIGEST """ hashAlg = SHA1() message = 'abc' message_digest = 0xA9993E36L, 0x4706816AL, 0xBA3E2571L, 0x7850C26CL, 0x9CD0D89DL ...
sxjscience/tvm
python/tvm/relay/backend/vm.py
Python
apache-2.0
9,793
0.000715
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distribu
ted 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 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 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 ...
LeBarbouze/tunacell
tunacell/base/timeseries.py
Python
mit
8,945
0.000335
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ This module will define useful objects for conditional analysis """ import collections import numpy as np import pandas as pd from tunacell.base.datatools import Coordinates # define an object to handle heterogeneous types of time series class TimeSeries(object): ...
ames is not None: _arr = ts.view((float, len(ts.dtype.names))) _x_name, _y_name = ts.dtype.names[:2] # take only first 2 cols
else: _arr = ts _x_name, _y_name = 'x', 'y' _x = _arr[:, 0] _y = _arr[:, 1] self._timeseries = Coordinates(_x, _y, x_name=_x_name, y_name=_y_name) # ... list of couples elif isinstance(ts, coll...
dmpetrov/dataversioncontrol
dvc/updater.py
Python
apache-2.0
5,458
0
import logging import os import sys import time from typing import TYPE_CHECKING, Optional from packaging import version from dvc import __version__ from dvc.utils.pkg import PKG if TYPE_CHECKING: from dvc.ui import RichText logger = logging.getLogger(__name__) class Updater: URL = "https://updater.dvc.or...
except Exception as exc: # pylint: disable=broad-except msg = "'{}' i
s not a valid json: {}" logger.debug(msg.format(self.updater_file, exc)) self.fetch() return if version.parse(self.current) < version.parse(latest): self._notify(latest) def fetch(self, detach=True): from dvc.daemon import daemon ...
nirvn/QGIS
python/plugins/processing/algs/qgis/DensifyGeometriesInterval.py
Python
gpl-2.0
2,659
0.000752
# -*- coding: utf-8 -*- """ *************************************************************************** DensifyGeometriesInterval.py by Anita Graser, Dec 2012 based on DensifyGeometries.py --------------------- Date : October 2012 Copyright : (C) 2012 by Victor Olaya ...
************************************************** *
* * 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)...
zhouxiumin/projecteuler
python/euler65.py
Python
apache-2.0
329
0.097264
#coding=utf-8 def generatList(n)
: llist=[] for i in range(n): t=1 if i%3==1: t=2*(i/3+1) llist.append(t) return llist[::-1] def generatitem(n): fz=0 fm=1 llist=generatList(n) for i in llist: temp=fm fm=fz+i*fm
fz=temp return (fz+2*fm,fm) fz=[int(x) for x in list(str(generatitem(99)[0]))] print sum(fz)
realestate-com-au/dashmat
dashmat/option_spec/import_line.py
Python
mit
2,434
0.015612
from dashmat.option_spec.module_imports import module_import_spec from dashmat.formatter import MergedOptionStringFormatter from dashmat.core_modules.base import Module from dashmat.errors import UnknownModule from input_algorithms.spec_base import boolean, string_spec, formatted, listof, overridden, or_spec, set_opti...
ormatted = True , wrapper = listof , help = "The modules that are imported" ) import_from = dictobj.Field( string_spec , formatted = True , default = "main.jsx" , help = "The module in our import_path to import the imports from" ) def import_li...
e['import_path'] if isinstance(module_name, six.string_types): if module_name not in modules: raise UnknownModule(module=module_name, available=list(modules.keys())) module = modules[module_name] else: module = module_name if type(module) is ...
G4m4/chartreuse
scripts/freq_scale.py
Python
gpl-3.0
2,022
0.001978
#!/usr/bin/env python ''' @file freq_scale.py @brief Sandbox for various frequency scale generators @author gm @copyright gm 2014 This file is part of Chartreuse Chartreuse is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Fo...
umpy.ceil(low_edge * dft_bins_count / sampling_freq) high_edge_idx = dft_bins_count / 2 + 1 length = high_edge_idx - low_edge_idx + 1 gene
rator = LogFreqScale(length, dft_bins_count, sampling_freq) out_data = generator.data print(utilities.PrintMetadata(utilities.GetMetadata(out_data))) pylab.plot(out_data, label = "out") pylab.legend() pylab.show()
TouK/vumi
vumi/transports/cellulant/cellulant_sms.py
Python
bsd-3-clause
3,968
0.000756
# -*- test-case-name: vumi.transports.cellulant.tests.test_cellulant_sms -*- import json from urllib import urlencode from twisted.internet.defer import inlineCallbacks from vumi.utils import http_request_full from vumi import log from vumi.config import ConfigDict, ConfigText from vumi.transports.httprpc import Htt...
llulantSmsTransport, self).validate_config() @inlineCallbac
ks def handle_outbound_message(self, message): creds = self._credentials.get(message['from_addr'], {}) username = creds.get('username', '') password = creds.get('password', '') params = { 'username': username, 'password': password, 'source': messag...
mrev11/ccc3
jt/jtpython/jtlib/jtexec.py
Python
lgpl-2.1
653
0.027565
##! /usr/bin/env python # _*_ coding: latin-1 _*_ import jtutil import jtsocket import jtdom def jtexec(cmd): jtsocket.s
end("<jtexec>"+jtutil.cdataif(cmd)+"</jtexec>") # <exitvalue>value</exitvalue> # vagy # <execerror>error</execerror> while 1: rsp=jtsocket.recv() if rsp==None: return None dom=jtdom.do
mparse(rsp) node=jtdom.domfirst(dom) type=jtdom.domname(node) value=jtdom.domtext(node) if type=="execerror": raise jtutil.applicationerror, ("jtexec", "failed", value) elif type=="exitvalue": return value
lucasw/vimjay
scripts/dr_camera_info.py
Python
gpl-3.0
1,867
0.002142
#!/usr/bin/env python # Lucas Walter # Configure a CameraInfo from a dynamic reconfigure interface import rospy from dynamic_reconfigure.server import Server from sensor_msgs.msg import CameraInfo from vimjay.cfg import DrCameraInfoConfig class DrCameraInfo: def __init__(self): rospy.init_node('dr_camera...
K[0 * 3 + 2] = config['cx'] ci.K[1 * 3 + 1] = config['fy'] ci.K[1 * 3 + 2] = config['cy'] ci.K[2 * 3 + 2] = 1 ci.P[0 * 4 + 0] = conf
ig['fx'] ci.P[0 * 4 + 2] = config['cx'] ci.P[1 * 4 + 1] = config['fy'] ci.P[1 * 4 + 2] = config['cy'] ci.P[2 * 4 + 2] = 1 ci.R[0] = 1 ci.R[4] = 1 ci.R[8] = 1 self.camera_info = ci return config def update(self, event): self.camera_info...
s0hvaperuna/Not-a-bot
cogs/utils.py
Python
mit
28,689
0.002162
import inspect import logging import os import re import shlex import subprocess import sys import textwrap import time from datetime import datetime from email.utils import formatdate as format_rfc2822 from io import StringIO from urllib.parse import quote import aiohttp import discord import psutil import pytz from ...
rror from dateutil import parser from dateutil.tz import gettz from discord.ext.commands import (BucketType, Group, clean_content) from discord.ext.commands.errors import BadArgument from bot.bot import command, cooldown, bot_has_permissions from bot.converters import FuzzyRole, TzConverter, PossibleUser from cogs.cog...
zalgo import unzalgo, is_zalgo from utils.utilities import (random_color, get_avatar, split_string, get_emote_url, send_paged_message, format_timedelta, parse_timeout, DateAccuracy) try: from pip.commands import SearchCommand ex...
douban/code
vilya/models/ngit/repo.py
Python
bsd-3-clause
21,073
0.000238
# -*- coding: utf-8 -*- from __future__ import absolute_import import os import time import gzip import tempfile import ConfigParser from cStringIO import StringIO from datetime import datetime from ellen.repo import Jagare from ellen.utils import JagareError from vilya.libs.permdir import get_tmpdir from vilya.mode...
h['type'] == 'tree': path = Tree(self, path['entries']) elif path['type'] == 'blob': path = Blob(self, path) else: path = None return path def get_path(self, ref, path): _item = self.repo.show("%s:%s" % (ref, path)) if not _item: ...
'tree': item = Tree(self, _item['entries']) elif _item['type'] == 'blob': item = Blob(self, _item) else: item = None return item def get_last_update_timestamp(self): commit = self.get_last_commit('HEAD') if not commit: return 0...
philippks/OSMNames
tests/export_osmnames/test_export_housenumbers.py
Python
gpl-2.0
365
0.00274
import os from osmnames.export_osmnames.export_osmnames import export_housenumbers, create_views def test_tsv_get_created(session, tables): session.add( tables.osm_housenumber( osm_id=1, ) ) create_views()
export_housenumbers() assert os.path.exists('/tmp/osmnames/expo
rt/test_housenumbers.tsv')
sonali0901/zulip
zerver/webhooks/freshdesk/view.py
Python
apache-2.0
5,880
0.00102
"""Webhooks for external integrations.""" from __future__ import absolute_import from django.http import HttpRequest, HttpResponse from django.utils.translation import ugettext as _ from zerver.models import get_client, UserProfile from zerver.lib.actions import check_send_message from zerver.lib.response import json...
o_state))] def format_freshdesk_note_message(ticket, event_info): # type: (TicketDict, List[str]) -> str """There are public (visible to customers) and private note types.""" note_type = event_info[1] content = "%s <%s> added a %s note to [ticket #%s](%s)." % ( ticket.requester_nam
e, ticket.requester_email, note_type, ticket.id, ticket.url) return content def format_freshdesk_property_change_message(ticket, event_info): # type: (TicketDict, List[str]) -> str """Freshdesk will only tell us the first event to match our webhook configuration, so if we change multiple prop...
misterlihao/network-programming-project
synchronizationRole.py
Python
mit
3,395
0.010898
import socket import os import threading import time import zipfile import threading import myPacket as mp def getParentDirectory(path): path2 = path.split('/') temp='' for ph in path2: if(len(ph)>4 and (ph[len(ph)-4:] == '.txt')): break
temp = os.path.join(temp, ph) return temp def checkCharVersion(sock, myChadir, friChadir): text = str(getCharDataSize(myChadir)) print(text) mp.sendPacket(sock, text.encode('utf8')) data = mp.recvPacket(sock).decode('utf8') if cmpCharVersion(getCharDataSize(friChadir), int(data)): ...
rn False def cmpCharVersion(myDataSize = 0, hisDataSize = 0): if myDataSize == hisDataSize: return True return False def getCharDataSize(charDirectory): temp = 0 for dirPath, dirNames, fileNames in os.walk(charDirectory): for fileName in fileNames: file = os.path.join(dirP...
jejimenez/django
django/template/engine.py
Python
bsd-3-clause
10,778
0
import warnings from django.core.exceptions import ImproperlyConfigured from django.utils import lru_cache, six from django.utils.deprecation import RemovedInDjango110Warning from django.utils.functional import cached_property from django.utils.module_loading import import_string from .base import Context, Template f...
'django.template.loader_tags', ] def __init__(self, dirs=None, app_dirs=False, allowed_include_roots=None, context_processors=None, debug=False, loaders=None, string_if_invalid='', file_charset='utf-8', libraries=None, builtins=None): if dirs is...
allowed_include_roots = [] if context_processors is None: context_processors = [] if loaders is None: loaders = ['django.template.loaders.filesystem.Loader'] if app_dirs: loaders += ['django.template.loaders.app_directories.Loader'] else: ...
4k1/wufuzzer
src/util.py
Python
mit
2,921
0.008216
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ============================================================================== # MIT License # # Copyright (c) 2017-2019 4k1 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "S...
copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY...
gannicus-yu/pyutils
myutils/mailbase.py
Python
apache-2.0
4,008
0.000763
#!/usr/bin/env python # coding: utf-8 import email.utils import logging import os import smtplib import threading from email.mime.text import MIMEText from email.MIMEMultipart import MIMEMultipart logger = logging.getLogger("maillog") class MailBase(threading.Thread): mailServerPort = 25 def __init__(self,...
"""
self.BASICS = {} basic = ["TOLIST", "SERVER", "USERNAME", "PASSWORD", "PORT"] if isinstance(basic_info, dict): if "PORT" not in basic_info.keys(): basic_info["PORT"] = self.mailServerPort if len(basic_info.keys()) != len(basic): logger.err...
JacekKarnasiewicz/HomePage
apps/tree_traversal/apps.py
Python
mit
102
0
from django.apps import AppConfig class Tre
eTraversalConfig(AppConfig): name = 'tree_traver
sal'
magyarm/periphondemand-code
setup.py
Python
lgpl-2.1
3,545
0.010155
#! /usr/bin/python # -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # Name: setup.py # Purpose: # Author: Fabien Marteau <fabien.marteau@armadeus.com> # Created: 16/02/2009 #----------------------------------------------------------------------------- # Co...
ile = [] os.path.walk(os.path.join("src",directory),visit,libfile) new_libfile = [] for path_file in libf
ile: new_libfile.append('/'.join(path_file.split('/')[1:])) if (directory == "platforms"): print str(new_libfile) return new_libfile # Package files package_files_list = [] package_files_list.extend(getTree("library")) package_files_list.extend(getTree("platforms")) package_files_list.extend(ge...
face2wind/Elegance
tools/serialize_creator/cpp_creator.py
Python
lgpl-3.0
8,346
0.003834
#!/usr/bin/env python3 import os import sys import getopt import xml.dom.minidom class CppCreator(object): def __init__(self, file_name, xml_root, output_path): if not os.path.exists(output_path): print ("CppCreator create error") exit(1) self.xml_root = xml_r...
rialize(ByteArray &collector) const;\n" hpp_file_str += " virtual void Unserialize(ByteArray &collector);\n" hpp_file_str += " virtual const std::string GetTypeName() const { return \"" + class_name + "\"; }\n" hpp_file_str += "};\n\n" describe_class_name = "__" + clas...
ap()[\"" + class_name + "\"] = this; }\n virtual ~" + describe_class_name + "() {}\n") describe_hpp_str += "\nprotected:\n virtual SerializeBase * CreateSerialize() const { return new " + class_name + "(); }\n};\n\n" describe_cpp_str += (describe_class_name + " " + "for_describe_register_to_" ...
vgrem/SharePointOnline-REST-Python-Client
office365/sharepoint/content_type_collection.py
Python
mit
376
0.00266
from office365.runtime.client_object_collection import ClientObjectCollection from office365.sharepoint.content_type import ContentType class ContentTypeCollection(ClientObjectCollection): """Content Type resource collection""" def __init__(self, context, resource_path=None): super(ContentTypeCollecti...
)
badp/weather
weather/models.py
Python
bsd-2-clause
8,309
0.011674
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from collections import OrderedDict from datetime import date, timedelta import signals class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True) # Optional new fields...
= team.get_all_voters() predictors = team.get_all_predictors() votes = TodayVotes.objects.filter(user__in=voters) predictions = TodayVotes.objects.filter(user__in=predictors) if votes.count() < 3: print "Skipping %s, not enough votes" % team continue else: for vote...
es: Votes(team=team, vote=vote.vote, is_vote=True).save() for prediction in predictions: Votes(team=team, vote=vote.vote, is_prediction=True).save() # Send warnings team.check_for_warnings(send_signals=True) TodayVotes.objects.all().delete() def __unicode__(self): re...
paxswill/evesrp
src/evesrp/views/api.py
Python
bsd-2-clause
12,023
0.002578
from __future__ import absolute_import from flask import url_for, redirect, abort, request, Blueprint, current_app from flask_login import login_required, current_user import six from six.moves import filter, map from sqlalchemy.orm.exc import NoResultFound from itertools import chain from .. import ships, systems, db...
map(lambda p: p.division, filter(lambda p: p.permission == PermissionType.pay, group.permissions)) resp = { u'name': group.name, u'users': list(group.users), u'divisions': { u'submit': list(set(submit)), u'review': list(set(review)), ...
List all divisions. """ if not current_user.admin: abort(403) divisions = db.session.query(Division.id, Division.name) return jsonify(divisions=divisions) @api.route('/division/<int:division_id>/') @login_required def division_detail(division_id): """Get the details of a division. :pa...
codesy/codesy
auctions/migrations/0039_auto_20160909_1728.py
Python
agpl-3.0
573
0.001745
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-09-09 17:28 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auctions', '0038_offercredit'), ] operations = [ ...
rField( model_name='offercredit', name='offer', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCAD
E, related_name='offer_credit', to='auctions.Offer'), ), ]
kratorius/ads
python/interviewquestions/atoi.py
Python
mit
1,456
0.00206
""" Implement atoi() in Python (given a string, return a number). Assume all the strings are always valid. """ import unittest def atoi(string): l = len(string) t = 0 v = 10 ** (l - 1) for ch in string: t
+= v * int(ch) v /= 10 return t def atoi2(string): l, t = len(string), 0 for idx, ch in enumerate(string): t += int(ch) * (10 ** (l - idx - 1)) return t def atoi3(string): l = len(string) return sum([ int(ch) * (10 ** (l - idx - 1)) for idx, ch in enumerate(
string) ]) class AtoITest(unittest.TestCase): def test_atoi(self): self.assertEqual(12345, atoi("12345")) self.assertEqual(1234, atoi("1234")) self.assertEqual(123, atoi("123")) self.assertEqual(12, atoi("12")) self.assertEqual(1, atoi("1")) self.assertEqual(0, ...
PierreMarchand20/htool
interface/htool/multihmatrix.py
Python
mit
10,354
0.005698
#!/usr/bin/env python # coding: utf-8 import os,sys import ctypes import numpy as np from .hmatrix import _C_HMatrix, HMatrix class _C_MultiHMatrix(ctypes.Structure): """Holder for the raw data from the C++ code.""" pass class AbstractMultiHMatrix: """Common code for the two actual MultiHMatrix classes...
self.hmatrices = [] for l in range(0,self.size): c_data_hmatrix = self.lib.getHMatrix(self.c_data,l) self.hmatrices.append(HMatrix(c_data_hmatrix,**params)) self.params = params.copy() @classmethod def from_coefs(cls, getcoefs, nm, po
ints_target, points_source=None, **params): """Construct an instance of the class from a evaluation function. Parameters ---------- getcoefs: Callable A function evaluating an array of matrices at given coordinates. points_target: np.ndarray of shape (N, 3) ...
microcom/odoo-product-configurator
product_configurator_wizard/models/sale.py
Python
agpl-3.0
1,538
0.00065
# -*- coding: utf-8 -*- from ast import literal_eval from odoo import models, fields, api class SaleOrderLine(models.Model): _inherit = 'sale.order.line' config_ok = fields.Boolean( related='product_id.config_ok', string="Configurable", readonl
y=True ) @api.multi def reconfigure_product(self): """ Creates and launches a product configurator wizard with a linked template and variant in order to re-configure a existing product. It is esetially a shortcut to pre-fill configuration data of a variant""" cfg_steps = se...
ds active_step = str(cfg_steps[0].id) if cfg_steps else 'configure' product_modifiable = literal_eval(self.env['ir.config_parameter'].sudo().get_param( 'product_configurator.product_modifiable', default='False')) wizard_obj = self.env['product.configurator'] wizard = wizard_...
fidelram/deepTools
deeptools/plotCorrelation.py
Python
gpl-3.0
10,834
0.002861
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import argparse import numpy as np import matplotlib matplotlib.use('Agg') matplotlib.rcParams['pdf.fonttype'] = 42 matplotlib.rcParams['svg.fonttype'] = 'none' from deeptools import cm # noqa: F401 import matplotlib.pyplot as plt from deeptools.correlation im...
parser.add_argument_group('Required arguments') # define the arguments required.add_argument('--corData', '-in', metavar='FILE', help='Compressed matrix of values generated by multiBigwigSummary or multiBamSummary', required=True) ...
help="Correlation method.", choices=['spearman', 'pearson'], required=True) required.add_argument('--whatToPlot', '-p', help="Choose between a heatmap or pairwise scatter plots", choices...
open-synergy/opnsynid-partner-contact
partner_single_sale_risk_policy/models/res_partner.py
Python
agpl-3.0
2,591
0
# -*- coding: utf-8 -*- # Copyright 2016 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import models, fields, api from openerp.tools.translate import _ from openerp.exceptions import Warning as UserError class ResPartner(models.Model): _inherit = "r
es.partner" @api.multi def _compute_single_sale_policy(self): single_sale_order = 0.0 unset_single_sale_order = False criteria = [ ("user_ids.id", "in",
[self.env.user.id]), ] policy = self.env["partner.risk_limit_policy"].search( criteria, limit=1) if len(policy) == 1: single_sale_order = policy.single_sale_order_limit unset_single_sale_order = policy.unset_single_sale_order_limit for partner in sel...
pindanet/Raspberry
demoSenseHat.py
Python
gpl-3.0
2,108
0.005693
#!/usr/bin/python3 # x11vnc # SoftAP from sense_hat import SenseHat from time import sleep sense = SenseHat() sense.low_light = True led_loop = [4, 5, 6, 7, 15, 23, 31, 39, 47, 55, 63, 62, 61, 60, 59, 58, 57, 56, 48, 40, 32, 24, 16, 8, 0, 1, 2, 3] prev_x = 0 prev_y = 0 while True: sense.set_rotation(180) sen...
_y, 0, 0, 0) sense.set_pixel(x, y, 0, 255, 0) prev_x = x prev_y = y sleep(0.1) sense.set_pixel(5, 1, r, g, b) for offset in led_loop: y = offset // 8 # row x = offset % 8 # column if x != prev_x or y != prev_y: ...
sense.set_pixel(x, y, 0, 255, 0) prev_x = x prev_y = y sleep(0.1) t = sense.get_temperature() + 273.15 t = (t - 32)/1.8 p = sense.get_pressure() h = sense.get_humidity() t = round(t, 1) p = round(p, 1) h = round(h, 1) print("Deze Raspberry ...
koalalorenzo/python-digitalocean
digitalocean/__init__.py
Python
lgpl-3.0
1,128
0.001773
# -*- coding: utf-8 -*- """digitalocean API to manage droplets""" __version__ = "1.16.0" __author__ = "Lorenzo Setale ( http://who.is.lorenzo.setale.me/? )" __author_email__ = "lorenzo@setale.me" __license__ = "LGPL v3" __copyright__ = "Copyright (c) 2012-2020 Lorenzo Setale" from .Manager import Manager from .Drople...
LoadBalancer import StickySessions, ForwardingRule, HealthCheck from .Certificate import Certificate from .Snapshot i
mport Snapshot from .Project import Project from .Firewall import Firewall, InboundRule, OutboundRule, Destinations, Sources from .VPC import VPC
adundovi/CRPropa3-scripts
python_modules/network.py
Python
gpl-3.0
1,236
0.022654
import zmq from crpropa import Module class SendCandidateProperties( Module ): """ Sends candidate proporties given by the function ```extract_func( candidate )``` over the network to the server on ```ip_port``` """ def __init__( self, ip_port, extract_func ): Module.__init__( self...
self.extract_func = extract_func def beginRun( self ): context = zmq.Context() self.socket = context.socket( zmq.REQ )
self.socket.connect( self.ip_port ) def process(self, c): self.socket.send_pyobj( self.extract_func( c ) ) msg_in = self.socket.recv_pyobj() def endRun( self ): del self.socket class RecvCandidateProperties: """ Server side: receive data from the client module whi...
timpalpant/calibre
src/calibre/web/feeds/recipes/__init__.py
Python
gpl-3.0
1,816
0.010463
#!/usr/bin/env python2 __license__ = 'GPL v3' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' ''' Builtin recipes. ''' import re, time, io from calibre.web.feeds.news import (BasicNewsRecipe, CustomIndexRecipe, AutomaticNewsRecipe, CalibrePeriodical) from calibre.ebooks.BeautifulSoup import Beautif...
c src in namespace for x in namespace.itervalues(): if (isi
nstance(x, type) and issubclass(x, BasicNewsRecipe) and x not in basic_recipes): return x return None
olarcheveque/usinacv
usinacv/usinacv/settings/base.py
Python
mit
8,153
0.004661
"""Common settings and globals.""" from os.path import abspath, basename, dirname, join, normpath from sys import path try: from secret import * except: pass ########## PATH CONFIGURATION # Absolute filesystem path to the Django project directory: DJANGO_ROOT = dirname(dirname(abspath(__file__))) # Absolut...
e name: SITE_NAME = basename(DJANGO_ROOT) # Add our project to our pythonpath, this way we don't need to type our project # name in our dotted import paths: path.append(DJANGO_ROOT) # Add SITE_ROOT to lookup application (wsgi) path.append(SITE_ROOT) ########## END PATH CONFIGURATION ########## DEBUG CONFIGURATION # ...
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug TEMPLATE_DEBUG = DEBUG ########## END DEBUG CONFIGURATION ########## MANAGER CONFIGURATION # See: https://docs.djangoproject.com/en/dev/ref/settings/#admins ADMINS = ( ('olivier', 'olivier.larcheveque@gmail.com'), ) # See: https://docs.dja...
FRidh/Sea
Sea/model/couplings/Coupling2DCavities2D.py
Python
bsd-3-clause
1,049
0.010486
import numpy as np from Coupling import Coupling class Coupling2DCavities2D(Coupling): """ Coupling for cavity2D to cavity transmission. """ @property def impedance_from(self): """ Choses the right impedance of subsystem_from. Applies boundary conditions correction as w...
""" return self.subsystem_to.impedance @property def tau(self): """ Transmission coefficient. """ return np.zeros(self.frequency.amount) @property def clf(self): """ Coupling loss factor for transmission from a 2D cavity
to a cavity. .. math:: \\eta_{12} = \\frac{ \\tau_{12}}{4 \\pi} See BAC, equation 3.14 """ return self.tau / (4.0 * np.pi)
openqt/algorithms
projecteuler/pe157-solving-the-diophantine-equation-sup1supsubvaravarsubsup1supsubvarbvarsub-supvarpvarsupsub10supvarnvarsupsub.py
Python
gpl-3.0
823
0.009792
#!/usr/bin/
env python # coding=utf-8 """157. Solving the diophantine equation <sup>1</sup>/<sub><var>a<
/var></sub>+<sup>1</sup>/<sub><var>b</var></sub>= <sup><var>p</var></sup>/<sub>10<sup><var>n</var></sup></sub> https://projecteuler.net/problem=157 Consider the diophantine equation 1/a+1/b= p/10n with a, b, p, n positive integers and a ≤ b. For n=1 this equation has 20 solutions that are listed below: 1/1+1/1=20/1...
pivonroll/Qt_Creator
tests/system/suite_APTW/tst_APTW02/test.py
Python
gpl-3.0
1,630
0.00184
############################################################################ # # Copyright (C) 2016 The Qt Company Ltd. # Contact: https://www.qt.io/licensing/ # # This file is part of Qt Creator. # # Commercial License Usage # Licensees holding valid commercial Qt licenses may use this file in # accordance with the co...
cation build and run for release and debug option def main(): startApplication("qtcreator" + SettingsPath) if not startedWithoutPluginError(): return checkedTargets, projectName = createNewQtQuickApplication(tempD
ir(), "SampleApp") # run project for debug and release and verify results runVerify(checkedTargets) #close Qt Creator invokeMenuItem("File", "Exit")
dscho/hg
contrib/synthrepo.py
Python
gpl-2.0
18,180
0.000605
# synthrepo.py - repo synthesis # # Copyright 2012 Facebook # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. '''synthesize structurally interesting change history This extension is useful for creating a repository with properties ...
else: fp = open(output, 'w') # Always obtain file counts of each directory in the given roo
t directory. def onerror(e): ui.warn(_('error walking directory structure: %s\n') % e) dirs = {} rootprefixlen = len(root) for dirpath, dirnames, filenames in os.walk(root, onerror=onerror): dirpathfromroot = dirpath[rootprefixlen:] dirs[dirpathfromroot] = len(filenames) ...
216software/Profiles
communityprofiles/profiles/oldmigrations/0038_auto__add_precalculatedvalue.py
Python
mit
15,090
0.008217
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'PrecalculatedValue' db.create_table('profiles_precalculatedvalue', ( ('id', se...
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'Conten
tType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), ...
OpusVL/odoo_line_notes_field
line_notes_field/__init__.py
Python
agpl-3.0
25
0
import sale
s_order_n
otes
vaishalitekale/treeherder
treeherder/model/derived/jobs.py
Python
mpl-2.0
83,969
0.000488
import logging import time import zlib from collections import defaultdict from datetime import datetime from hashlib import sha1 from operator import itemgetter import simplejson as json from _mysql_exceptions import IntegrityError from django.conf import settings from django.core.cache import cache from django.core....
source.save() return cls(project=project) def execute(self, **kwargs): return utils.retry_execute(self.get_dhub(), logger, **kwargs) ################## # # Job schema data methods # ################## def get_job(self, id): """Return the job row for
this ``job_id``""" repl = [self.refdata_model.get_db_name()] data = self.execute( proc="jobs.selects.get_job", placeholders=[id], debug_show=self.DEBUG, replace=repl, ) return data def get_job_reference_data(self, signature): ...
xiaowing/tinysso
config.py
Python
apache-2.0
54
0
CSRF_ENABLED = True
SECRET_KEY = 'this-is-a-
secret'
jordanemedlock/psychtruths
temboo/core/Library/Yelp/__init__.py
Python
apache-2.0
1,354
0.005908
from temboo.Library.Yelp.SearchByAddress import SearchByAddress, SearchByAddressInputSet, SearchByAddressResultSet, SearchByAddressChoreographyExecution from temboo.Library.Yelp.SearchByBoundingBox import SearchByBoundingBox, SearchByBoundingBoxInputSet, SearchByBoundingBoxResultSet, SearchByBoundingBoxChoreographyExec...
SearchByNeighborhood import SearchByNeighborhood, SearchByNeighborhoodInputSet, SearchByNeighborhoodResultSet, SearchByNeighborhoodChoreographyExecution from temboo.Library.Yelp.SearchForBusiness import
SearchForBusiness, SearchForBusinessInputSet, SearchForBusinessResultSet, SearchForBusinessChoreographyExecution from temboo.Library.Yelp.SearchForBusinessesWithDeals import SearchForBusinessesWithDeals, SearchForBusinessesWithDealsInputSet, SearchForBusinessesWithDealsResultSet, SearchForBusinessesWithDealsChoreograph...
antoinecarme/sklearn2sql_heroku
tests/classification/FourClass_500/ws_FourClass_500_SGDClassifier_mysql_code_gen.py
Python
bsd-3-clause
141
0.014184
fr
om sklearn2sql_heroku.tests.classification import generic as class_gen class_gen.test_model("SGDClassifier" , "FourClass_500" , "mysql")
dwang159/iris-api
src/iris/role_lookup/__init__.py
Python
bsd-2-clause
863
0.001159
# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. # See LICENSE in the project root for license information. from iris.custom_import import import_custom_module import logging logger = logging.getLogger(__name__) class IrisRoleLookupException(Exception): pass d...
modules = config.get('role_lookups', []) # default to only support user and mailing_list. if not modules: modules = ['user', 'mailing_list'] imported_modules = [] for m in modules: try: imported_modules.append( import_custom_module('iris.role_lookup', m)...
ion('Failed to load role lookup module: %s', m) return imported_modules
SartoNess/BitcoinUnlimited
qa/rpc-tests/abandonconflict.py
Python
mit
7,686
0.008197
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Bitcoin Core developers # Copyright (c) 2015-2016 The Bitcoin Unlimited developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import Bit...
t(i for i, vout in enumerate(self.nodes[0].getrawtransaction(txA, 1)["vout"]) if vout["value"] == Decimal("10")) nB = next(i for i, vout in enumerate(self.nodes[
0].getrawtransaction(txB, 1)["vout"]) if vout["value"] == Decimal("10")) nC = next(i for i, vout in enumerate(self.nodes[0].getrawtransaction(txC, 1)["vout"]) if vout["value"] == Decimal("10")) inputs =[] # spend 10btc outputs from txA and txB inputs.append({"txid":txA, "vout":nA}) ...
ananswam/bioscrape
bioscrape/pid_interfaces.py
Python
mit
13,998
0.008573
from bioscrape.inference import DeterministicLikelihood as DLL from bioscrape.inference import StochasticTrajectoriesLikelihood as STLL from bioscrape.inference import StochasticTrajectories from bioscrape.inference import BulkData import warnings import numpy as np class PIDInterface(): ''' PID Interface : Pa...
lp += custom_fuction(key, value) else: raise ValueError('Prior type undefined.') return lp def uniform_prior(self, param_name, param_value): ''' Check if given param_value is valid according to the prior distribution. Returns np.Inf if the param_val...
rior_dict = self.prior if prior_dict is None: raise ValueError('No prior found') lower_bound = prior_dict[param_name][1] upper_bound = prior_dict[param_name][2] if param_value > upper_bound or param_value < lower_bound: return np.inf else: retu...
UKTradeInvestment/export-wins-data
wins/migrations/0018_merge.py
Python
gpl-3.0
324
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-08-03 13:45 from __future__ import unicode_literals from django.db import migrations class
Migration(migrations.Migration): dependencies = [ ('win
s', '0016_win_updated'), ('wins', '0017_auto_20160801_1230'), ] operations = [ ]
GeoMop/GeoMop
src/JobPanel/data/__init__.py
Python
gpl-3.0
131
0.007634
from
.states import (TaskStatus, MultijobActions, TASK_STATUS_PERMITTED_ACTIONS,
TASK_STATUS_STARTUP_ACTIONS)
antoinecarme/pyaf
tests/model_control/detailed/transf_Logit/model_control_one_enabled_Logit_ConstantTrend_Seasonal_Hour_ARX.py
Python
bsd-3-clause
156
0.051282
import tests.model_co
ntrol.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Logit'] , [
'ConstantTrend'] , ['Seasonal_Hour'] , ['ARX'] );
Azure/azure-sdk-for-python
sdk/sql/azure-mgmt-sqlvirtualmachine/azure/mgmt/sqlvirtualmachine/aio/_sql_virtual_machine_management_client.py
Python
mit
5,342
0.003931
# 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 ...
ID that identifies an Azure subscription. :type subscription_id: str :param base_url: Service URL. Default value is 'https://management.azure.com'. :type base_url: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. "...
subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, ...
ShawnHymel/TweetRace
pytest/wager_test_01.py
Python
mit
5,938
0.011115
import os import sys import pygame import signal import time import ConfigParser from twython import TwythonStreamer #----------------------------------------------------------------------------- # Import custom modules #----------------------------------------------------------------------------- # Add pyscope modul...
ms tf.start_track_streamer(BET_TERM) # Setup display pygame.init() #g_scope = pyscope.pyscope() fps_clock = pygame.time.Clock() pygame.mouse.set_visible(False) # Main game loop g_bet_loop = False while g_bet_loop: # H
andle game events for event in pygame.event.get(): # End game if quit event raises if event.type == pygame.QUIT: g_bet_loop = False # End game if 'q' or 'esc' key pressed elif event.type == pygame.KEYDOWN: if event.key == pygame.K...
moonbury/notebooks
github/Numpy/Chapter2/elementselection.py
Python
gpl-3.0
492
0.034553
from __future__ import print_function import numpy as np # Chapter 2 Beginning with NumPy fundamentals # # Demonstrates the selection # of ndarray elements. # # Run from the commandline with # # python elementselection.py a = np.array([[1,2],[3,4]]) print("In: a") print(a) #Ou
t: #array([[1, 2], # [3, 4]]) print("In: a[0,0]") print(a[0,0]) #Out: 1 print("In: a[0,1]") print(a[0,1]) #Out: 2 prin
t("In: a[1,0]") print(a[1,0]) #Out: 3 print("In: a[1,1]") print(a[1,1]) #Out: 4
algorhythms/LeetCode
146 LRU Cache py3.py
Python
mit
2,700
0
#!/usr/bin/python3 """ Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the ...
(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4 """ class Node: def __init__(self, key, val): self.k...
self.prev, self.next = None, None class LRUCache: def __init__(self, capacity: int): """ O(1) look up - Map O(1) update most recent vs. least recent - Linked List But Single linked list is not enough then Double Linked List Need dummy head and tail to avoid over comp...
googleapis/python-api-gateway
samples/generated_samples/apigateway_v1_generated_api_gateway_service_create_api_async.py
Python
apache-2.0
1,588
0.00063
# -*- 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...
"AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language govern
ing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for CreateApi # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute...
AklerQ/python_training
model/group.py
Python
apache-2.0
674
0.002967
from sys import maxsize class Group: def __init__(self, name=None, header=None, footer=None, id=None): self.name = name
self.header = header self.footer = footer self.id = id def __repr__(self): return "%s:%s:%s:%s" % (self.id, self.name, self.header, self.footer) def __eq__(self, other): return (self.id is None or other.id is None
or self.id == other.id) and (self.name == other.name or self.name is None) def id_or_max(self): if self.id: return int(self.id) else: return maxsize
IvIePhisto/ECoXiPy
ecoxipy/pyxom/__init__.py
Python
mit
21,834
0.001147
# -*- coding: utf-8 -*- u'''\ :mod:`ecoxipy.pyxom` - Pythonic XML Object Model (PyXOM) ======================================================== This module implements the *Pythonic XML Object Model* (PyXOM) for the representation of XML structures. To conveniently create PyXOM data structures use :mod:`ecoxipy.pyxom.o...
e" is not a valid XML name. >>> t = catch_not_well_formed(ProcessingInstruction, '1nvalid-xml-name') The value "1nvalid-xml-name" is not a valid XML processing instruction target. >>> t = catch_not_well_formed(ProcessingInstruction, 'target', 'invalid PI content ?>') The value "invalid PI content ?>" is not a valid
XML processing instruction content because it contains "?>". >>> t = catch_not_well_formed(Comment, 'invalid XML comment --') The value "invalid XML comment --" is not a valid XML comment because it contains "--". Navigation ^^^^^^^^^^ Use list semantics to retrieve child nodes and attribute access to retrieve node...
pozetroninc/micropython
tests/internal_bench/var-8-namedtuple-1st.py
Python
mit
190
0.010526
import bench from ucollections impor
t namedtuple T = namedtuple("Tup", ["num", "bar"]) def test(num): t = T(20000000, 0) i = 0 while i < t.num: i += 1 benc
h.run(test)
agustin380/school-registry
src/school_registry/wsgi.py
Python
gpl-3.0
407
0
""" WSGI config for school_registry 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.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "school_registry.settings") applica
tion = get_wsgi_application()
le9i0nx/ansible
lib/ansible/plugins/action/aireos.py
Python
gpl-3.0
3,433
0.001748
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible 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. # # Ansible is d...
lf, tmp=None, task_vars=None): if self._play_context.connection != 'local': return dict( failed=True, msg='invalid connection specified, expected connection=local, ' 'got %s' % self._play_context.connection ) provider = load_p...
ireos' pc.remote_addr = provider['host'] or self._play_context.remote_addr pc.port = int(provider['port'] or self._play_context.port or 22) pc.remote_user = provider['username'] or self._play_context.connection_user pc.password = provider['password'] or self._play_context.password ...
cmancone/mygrations
mygrate.py
Python
mit
795
0.003774
#!/usr/bin/env python3 import argparse from mygrations.mygrate import mygrate # argument parsing parser = argparse.ArgumentParser() parser.add_argument( 'command', nargs='?', default='version', choices=['version', 'apply', 'check', 'import', 'plan', 'plan_export'], help='Action to execute (default...
re errors/warnings and execute command anyway') parser.add_argument('-v', dest='v
ersion', action='store_true', help='Display version') args = parser.parse_args() # load up a mygrate object my = mygrate(args.command, vars(args)) # and execute my.execute()
dparks1134/UniteM
unitem/bin.py
Python
gpl-3.0
11,713
0.002134
############################################################################### # # # 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 ...
' '.join(bam_files)) run_cmd(cmd, program='jgi_summarize_bam_contig_depths') def check_on_path(self, options): """Check that all binning methods are on the system path.""" if options.mb2: self.logger.info('Checking MetaBAT v2 dependencies.') check_on_...
self.logger.info('Checking GroopM v2 dependencies.') check_on_path('groopm2') if options.max40 or options.max107: self.logger.info('Checking MaxBin dependencies.') check_on_path('run_MaxBin.pl') if (options.mb_verysensitive or options....
weixsong/algorithm
leetcode/123.py
Python
mit
1,949
0.00667
#!/usr/bin/env python """ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy ag...
profit = 0 for i in range(len(prices)): p1 = self.max_p(prices, 0, i) p2 = self.max_p(prices, i, len(prices) - 1) profit = max(profit, p1 + p2) return profit def max_p(self, prices, start, end): if start >= end: return 0 min_price...
rices[start] profit = 0 for i in range(start, end + 1): p = prices[i] profit = max(p - min_price, profit) min_price = min(min_price, p) return profit class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] ...
trailofbits/mcsema
tools/mcsema_disass/ida7/disass.py
Python
apache-2.0
2,610
0.015326
#!/usr/bin/env python # Copyright (c) 2017 Trail of Bits, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
ck try: from shlex import quote except: from pipes import quote def execute(args, command_args): """Execute IDA Pro as a subprocess, passing this file in as a batch-mode script for IDA to run. This forwards along arguments passed to `mcsema-disass` down into the IDA script. `command_args` contains unparsed ...
ida_dir = os.path.dirname(ida_disass_path) ida_get_cfg_path = os.path.join(ida_dir, "get_cfg.py") env = {} env["IDALOG"] = os.devnull env["TVHEADLESS"] = "1" env["HOME"] = os.path.expanduser('~') env["IDA_PATH"] = os.path.dirname(args.disassembler) env["PYTHONPATH"] = os.path.dirname(ida_dir) if "Sys...
bosswissam/shippo-python
shippo/api_requestor.py
Python
mit
7,865
0.000127
import calendar import datetime import platform import time import os import ssl import socket import urllib import urlparse import warnings import shippo from shippo import error, http_client, version, util, certificate_blacklist def _encode_datetime(dttime): if dttime.tzinfo and dttime.tzinfo.utcoffset(dttime)...
sinstance(value, list) or isinstance(value, tupl
e): for subvalue in value: yield ("%s[]" % (key,), util.utf8(subvalue)) elif isinstance(value, dict): subdict = dict(('%s[%s]' % (key, subkey), subvalue) for subkey, subvalue in value.iteritems()) for subkey, subvalue in _api_encode(...
kaiueo/octs
octs/teacher/views.py
Python
bsd-3-clause
34,607
0.014882
from flask import Blueprint, flash, redirect, render_template, request, url_for,send_from_directory, abort, make_response, send_file, session from octs.user.models import Course,Task, User, Message, Team,TeamUserRelation, File,Source,Term,TaskTeamRelation, Tag,UserScore from .forms import CourseForm,TaskForm, FileForm,...
ort db from flask_login import current_user from octs.extensions import data_uploader import time import os,zipfile from pypinyin import lazy_pinyin import xlwt blueprint = Blueprint('teacher', __name__, url_prefix='/teacher',static_folder='../static') @blueprint.route('/<teacherid>/course/') def course(teacherid): ...
html', list=courseList,term=term) @blueprint.route('/<courseid>/task/<taskid>') def task_detail(courseid,taskid): taskList = Task.query.filter_by(id=taskid).all() return render_template('teacher/taskdetail.html',list=taskList,courseid=courseid) @blueprint.route('/<teacherid>/course/edit/<id>',methods=['GET',...
oskgeek/xmccamp
xmccamp/xmccamp/urls.py
Python
mit
338
0.011834
fro
m django.conf.urls import patterns, include, url from django.conf import settings urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', \ {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}), url(r'', include('controller.urls')), url('^.*/$', 'controller.view...
ogin'), )
JesusAMR/ProgramasUNI
testing.py
Python
gpl-3.0
101
0.009901
#! /usr/bin/p
ython import re input = raw_input() result = re.findall(r"[0-9]",input) print(result)
KohlsTechnology/ansible
lib/ansible/module_utils/k8s/lookup.py
Python
gpl-3.0
7,677
0.001693
# # Copyright 2018 Red Hat | Ansible # # This file is part of Ansible # # Ansible 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. # # ...
e OpenShift Python client. Try `pip install openshift`" ) if not HAS_YAML: raise Exception( "Requires PyYAML. Try `pip install PyYAML`"
) self.kind = None self.name = None self.namespace = None self.api_version = None self.label_selector = None self.field_selector = None self.include_uninitialized = None self.resource_definition = None self.helper = None self.connection = ...
mckayward/floyd-cli
floyd/model/experiment_config.py
Python
apache-2.0
507
0
from marshmall
ow import Schema, fields, post_load from floyd.model.base import BaseModel class ExperimentConfigSchema(Schema): name = fields.Str() family_id = fields.Str() @post_load def make_access_token(self, data): return ExperimentConfig(**data) class ExperimentConfig(BaseModel): schema = Expe...
ema(strict=True) def __init__(self, name, family_id=None): self.name = name self.family_id = family_id
garrettcap/Bulletproof-Backup
gooey/mockapplications/mockapp.py
Python
gpl-2.0
2,121
0.016973
''' Created on Dec 21, 2013 @author: Chris ''' import sys import hashlib from time import time as _time from time import sleep as _sleep from argparse import ArgumentParser from gooey import Gooey @Gooey def main(): desc = "Mock application to test Gooey's functionality" file_help_msg = "Name o...
ositional my_cool_parser.add_argument("outfile", help="Name of the file where you'll save the output") # positional my_cool_parser.add_argument('-c
', '--countdown', default=10, type=int, help='sets the time to count down from') my_cool_parser.add_argument("-s", "--showtime", action="store_true", help="display the countdown timer") my_cool_parser.add_argument("-d", "--delay", action="store_true", help="Delay execution for a bit") my_cool_parser.add_argume...
sfiera/googletest
test/gtest_help_test.py
Python
bsd-3-clause
5,754
0.003823
#!/usr/bin/env python # # Copyright 2009, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condi
tions are # met: # # * Redistribut
ions of source code must retain the above copyright # 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 # d...
nesdis/djongo
tests/django_tests/tests/v22/tests/csrf_tests/csrf_token_error_handler_urls.py
Python
agpl-3.0
75
0
urlpatterns
= [] handler404 = 'csrf_te
sts.views.csrf_token_error_handler'
nishantsingla/optcoretech
docs/conf.py
Python
mit
7,786
0.007449
# -*- coding: utf-8 -*- # # Optcoretech documentation build configuration file, created by # sphinx-quickstart on Mon Sep 1 14:23:01 2014. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
# If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------
------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'optcoretech', u'Optcoretech Documentation', [u'Sheesh Mohsin'], 1) ] # If true, show URL addresses after external links. #man_show_urls = Fal...
CKPalk/MachineLearning
Assignment3/Naive_Bayes/nb.py
Python
mit
2,586
0.095514
import sys from csv_data import Data from csv_utilities import readIntegerCSV from csv_utilities import convertToZeroOne from statistics import mean from math import log def dotProduct( arr1, arr2 ): return sum( [ arr1[idx] * arr2[idx] for idx in range( len( arr1 ) ) ] ) # def dataSubsetWithY( data, y ): return [ r...
) # def rowPrediction( X, W, b ): return ( 1 if ( dotProduct( X, W ) + b >= 0 ) else 0 ) # def getResults( testing_d
ata, W, b ): return ( len( [ 1 for row in testing_data.rows if row.Y == rowPrediction( row.X, W, b ) ] ) / len( testing_data.rows ) ) # def printModel( model_stream, attrs, W, b ): model_stream.write( "{}\n".format( round( b, 4 ) ) ) for idx, attr in enumerate( attrs ): model_stream.write( "{:16}\t{}\n".format( at...
chr15m/Infinite8BitPlatformer
engine/Progress.py
Python
gpl-3.0
960
0.039583
import os from PodSix.Resource import * from PodSix.Concurrent import Concurrent class Progress(Concurrent): def __init__(self): Concurrent.__init__(self) self.sprite = Image(file=os.path.join("resources", "progress.png")) self.showing = False self.maximum = 1 self.value = 0 self.width = 142 self.heig...
elf.showing: gfx.screen.fill([80, 80, 80], special_flags=BLEND_SUB) gfx.BlitImage(self.sprite, center=[gfx.width / 2, gfx.height / 2]) g
fx.DrawRect((gfx.width / 2 - self.width / 2, gfx.height / 2 - self.height / 2, self.width * (1 - float(self.value) / self.maximum), self.height), [255, 0, 0], 0) def Show(self, maximum=None): if not maximum is None: self.maximum = maximum self.showing = True def Hide(self): if self.showing: self.showi...
lasercar/mcedit-filters
block_elevation_stats.py
Python
mit
1,764
0.036281
# Copyright (c) 2014 Lasercar7 (@lasercar) - MIT License # http://lasercar.github.io #TODO: dictionary that maps block ids (to be collected) with readable names stats = {} def logStat(block, elevation): if not block in stats: #initialize column stats[block] = map(lambda x: 0.0, range(256)) #add to stat stats[b...
ckAt(x, y, x) #calculate total blocks from scan radius, then conv
ert raw data to percentage options = {'Scan Radius': 100}#temp layerTotal = (float(options['Scan Radius']) * 2) **2 def percentFormat(): for block in stats: i = 0 for elevation in stats[block]: stats[block][i] = float(elevation)/layerTotal i += 1 percentFormat() #open csv file, convert stats to data, write...
kaedroho/django
django/db/backends/sqlite3/introspection.py
Python
bsd-3-clause
18,452
0.001734
import re from collections import namedtuple import sqlparse from django.db.backends.base.introspection import ( BaseDatabaseIntrospection, FieldInfo as BaseFieldInfo, TableInfo, ) from django.db.models import Index from django.utils.regex_helper import _lazy_re_compile FieldInfo = namedtuple('FieldInfo', BaseFi...
lean': 'BooleanField', 'smallint': 'SmallIntegerField', 'smallint unsigned': 'PositiveSmallIntegerField', 'smallinteger': 'SmallIntegerField', 'int': 'IntegerField', 'integer': 'IntegerField', 'bigint': 'BigIntegerField', 'integer unsigned': 'PositiveIntegerField'...
'real': 'FloatField', 'text': 'TextField', 'char': 'CharField', 'varchar': 'CharField', 'blob': 'BinaryField', 'date': 'DateField', 'datetime': 'DateTimeField', 'time': 'TimeField', } def __getitem__(self, key): key = key.lower().split('(', 1)[...
ImmobilienScout24/aws-monocyte
src/integrationtest/python/handler/iam_inline_policy_tests.py
Python
apache-2.0
4,364
0.000458
import json import logging import boto3 import unittest2 from mock import MagicMock from monocyte.handler import iam as iam_handler class IamInlinePolicyTests(unittest2.TestCase): def setUp(self): self.arn = '' logging.captureWarnings(True) self.iam_handler = iam_handler.InlinePolicy(Magi...
"Resource": "*" } ] } self._put_inline_role_policy(inline_policy) unwanted_resource = self.iam_handler.fetch_unwanted_resources() self.assertEqual([], self._uniq(unwanted_resource)) def test_wildcard_in_inline_policy_resource_and_action(s...
n": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "*" ], "Resource": "*" } ] } self._put_inline_role_policy(inline_policy) ...
EuroPython/epcon
tests/test_user_login_and_registration.py
Python
bsd-2-clause
8,704
0.00023
from pytest import mark from django.urls import reverse from email_template.models import Email from assopy.models import AssopyUser from conference.accounts import PRIVACY_POLICY_CHECKBOX, PRIVACY_POLICY_ERROR from conference.models import CaptchaQuestion from conference.users import RANDOM_USERNAME_LENGTH from te...
nce/base.html") user = AssopyUser.objects.get() assert user.name() == "Joe Doe" assert user.user.is_active is False # check if the random username was generated assert len(user.user.username) == RANDOM_USERNAME_LENGTH is_logged_in = client.login( email="joedoe@example.com", password="...
te_used(response, "conference/homepage/home_template.html") assert "Joe Doe" not in response.content.decode("utf-8") assert "Log out" not in response.content.decode("utf-8") # enable the user user.user.is_active = True user.user.save() is_logged_in = client.login( email="joedoe@example...
armikhael/software-center
softwarecenter/db/enquire.py
Python
gpl-3.0
13,223
0.002723
# Copyright (C) 2011 Canonical # # Authors: # Matthew McGowan # Michael Vogt # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License as published by the Free Software # Foundation; version 3. # # This program is distributed in the hope that it wi...
: q = xapian.Query(xapian.Query.OP_AND, xapia
n.Query("ATapplication"), q) LOG.debug("nearly completely filtered query: '%s'" % q) # filter out docs of pkgs of which there exists a doc of the app # FIXME: make this configurable again? enquire.set_query(xapian.Query(xapian.Query....
xZise/pywikibot-core
scripts/newitem.py
Python
mit
4,866
0.000822
#!/usr/bin/python # -*- coding: utf-8 -*- """ This script creates new items on Wikidata based on certain criteria. * When was the (Wikipedia) page created? * When was the last edit on the page? * Does the page contain interwiki's? This script understands various command-line arguments: -lastedit The minimum ...
'lastedit') self.pageAgeBefore = self.repo.getcurrenttime() - timedelta(days=self.pageAge) self.lastEditBefore = self.repo.getcurrenttime() - timedelta(days=self.lastEdit) self.treat_missing_item = True pywikibot.output('Page age is set to %s days so only pages created
' '\nbefore %s will be considered.' % (self.pageAge, self.pageAgeBefore.isoformat())) pywikibot.output('Last edit is set to %s days so only pages last edited' '\nbefore %s will be considered.' % (self.lastEdit, s...
diegordzr/YellowSpider
yellow/yellow/pipelines.py
Python
mit
1,714
0.021004
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json import pymongo from scrapy.settings import Settings from scrapy.exceptions import DropItem from scrapy import log fr...
ection_name].insert(di
ct(item)) #if('email' in item): self.db[self.collection_name].find_one_and_update( { 'key': item['key'] }, { '$set': dict(item) }, upsert=True) log.msg("Contact added to MongoDB database!", level=log.DEBUG, spider=spider) return item class DuplicatesPipeline(object): def __init__(self): ...
ajitghz582/PythonLearning
DAY_1_ASSIGNMENTS/1_name_phone_number.py
Python
mit
1,070
0.052336
student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name
\n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice =
= 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choi...