index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
5,000
7130a382784955780a3f258c81ce05c61915af56
import numpy as np def get_mask(mask): r = mask[:, :, 0] g = mask[:, :, 1] return r // (r.max() or 1) * -1 + g // (g.max() or 1) def calculate_brightness(image): weights = np.array([0.299, 0.587, 0.114]) brightness_matrix = (image*weights).sum(axis=2) return brightness_matrix def calculate...
5,001
e204cbbf36ac180eba0e95916345088c77bca7c0
#!/usr/bin/python import wx class test(wx.Frame): def __init__(self,parent,id): wx.Frame.__init__(self,parent,id,"TestFrame",size=(500,500)) if __name__ == '__main__': app = wx.PySimpleApp() frame = test(parent=None,id=-1,) frame.show() app.mainloop()
5,002
2bc3b0df720788e43da3d9c28adb22b3b1be8c58
import logging from django.contrib.auth.models import User import json from django.http import HttpResponse from enumfields.fields import EnumFieldMixin from Api.models import Status logger = logging.getLogger() logger.setLevel(logging.INFO) def check_cookie(request): # Post.objects.all().delete() result = ...
5,003
13e2f474294edb7c78bd81456097d1389e6a0f1b
from .isearch import ISearcher __all__ = ['ISearcher']
5,004
d960d3d1680f825f0f68fc6d66f491bbbba805ce
# Kipland Melton import psutil import math def convert_size(size_bytes): if size_bytes == 0: return "0B" size_name = ("%", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return "%s %s" % (s, siz...
5,005
b7606befe123c4fb6840a1bc62e43e6721edfcc3
import boto3 import json region = 'us-east-2' ec2 = boto3.resource('ec2',region) ImageId = 'ami-07efac79022b86107' KeyName = 'aws_keypair' InstanceType = 't2.micro' #IamInstanceProfile = instances = ec2.create_instances( ImageId =ImageId, MinCount = 1, MaxCount = 5, KeyName = KeyName, InstanceTyp...
5,006
d90a4b00d97cecf3612915a72e48a363c5dcc97b
#!/usr/bin/python3 """Locked class module""" class LockedClass: """test class with locked dynamic attruibute creation """ __slots__ = 'first_name'
5,007
b1c8aceab44574d0f53d30969861be028c920ef2
# Create your views here. # -*- coding: utf-8 -*- from json import dumps from django.shortcuts import render_to_response from django.http import Http404, HttpResponseRedirect, HttpResponse from django.template import RequestContext from django.conf import settings from utils import Utils, MERCS, ENTITY, PARTS, ARMY, D...
5,008
fb2ef5a90b6e2582450726905868dd1b78e36166
# 2019/10/08 2019๋…„10์›”8์ผ ss = input('๋‚ ์งœ: ๋…„/์›”/์ผ ์ž…๋ ฅ-> ') sslist = ss.split('/') print(sslist) print('์ž…๋ ฅํ•˜์‹  ๋‚ ์งœ์˜ 10๋…„ ํ›„ -> ', end='') year = int(sslist[0]) + 10 print(str(year) + "๋…„", end='') print(sslist[1] + "์›”", end='') print(sslist[2] + "์ผ")
5,009
14f3c941856ddf6bd7b3e046f21072f0b5f7b036
class Solution: def minimumDeletions(self, nums: List[int]) -> int: n = len(nums) a = nums.index(min(nums)) b = nums.index(max(nums)) if a > b: a, b = b, a return min(a + 1 + n - b, b + 1, n - a)
5,010
394f835064d070a30040b6f01b25b6f0e005827d
""" Created on Fri Jan 07 20:53:58 2022 @author: Ankit Bharti """ from unittest import TestCase, main from cuboid_volume import * class TestCuboid(TestCase): def test_volume(self): self.assertAlmostEqual(cuboid_volume(2), 8) self.assertAlmostEqual(cuboid_volume(1), 1) self.assertAlmostE...
5,011
4bd6a7c7fc6a788b2cb010f6513872bd3e0d396c
import os import random readpath = './DBLP/' writepath = './DBLP/' dataname = 'dblp.txt' labelname = 'node2label.txt' testsetname = writepath + 'dblp_testset.txt' def run(save_rate): rdataname = readpath + dataname rlabelname = readpath + labelname wdataname = writepath + dataname wlabelname = writepath + labelna...
5,012
26ef7de89e2e38c419310cc66a33d5dc0575fc0d
# Generates an infinite series of odd numbers def odds(): n = 1 while True: yield n n += 2 def pi_series(): odd_nums = odds() approximation = 0 while True: approximation += (4 / next(odd_nums)) yield approximation approxim...
5,013
d386047c087155b1809d47349339eb6882cf8e26
import stock as stk import portfolio as portf import plot import sys import cmd import os import decision as des class CLI(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.prompt = '$> ' self.stk_data_coll = stk.StockDataCollection() self.add_to_plot_lst = [] ...
5,014
706f8d83bc9b4fab6f6d365c047c33913daece61
"""This module runs cdb on a process and !exploitable on any exceptions. """ import ctypes import logging import os from pprint import pformat from subprocess import Popen from threading import Timer import time from certfuzz.debuggers.debugger_base import Debugger as DebuggerBase from certfuzz.debuggers.ou...
5,015
15e1ce95398ff155fe594c3b39936d82d71ab9e2
import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func, inspect from flask import Flask, jsonify, render_template, redirect from flask_pymongo import PyMongo from config import mongo_password, mongo_username, sql_username, sql_pass...
5,016
ba09dbe3fbca51ece8a7d482324a2dec32e7dc8a
import librosa import librosa.display import matplotlib.pyplot as plt import os import numpy as np import time import multiprocessing as mp from tempfile import TemporaryFile class DataSet(): def __init__(self,training_folder): self.training_folder = training_folder print("load Data") def load...
5,017
52dc8a4f9165a88dddc1da16e0adb045c4d851ed
import json from typing import TYPE_CHECKING import pytest from eth_utils import is_checksum_address from rotkehlchen.globaldb.handler import GlobalDBHandler from rotkehlchen.types import ChainID if TYPE_CHECKING: from rotkehlchen.chain.ethereum.node_inquirer import EthereumInquirer def test_evm_contracts_data...
5,018
fe45fc6cd16be37b320844c5a8b43a964c016dd1
# -*- coding: utf-8 -*- from Clases import Lugar from Clases import Evento import Dialogos import Funciones puntuacion_necesaria = 10 hp_inicial = 5 eventos = [ Evento("dormir", 2, False, -3, 4, Dialogos.descripciones_eventos[0], Dialogos.descripciones_triunfos[0], Dialogos.descripciones...
5,019
4620b52a43f2469ff0350d8ef6548de3a7fe1b55
# -*- snakemake -*- # # CENTIPEDE: Transcription factor footprinting and binding site prediction # install.packages("CENTIPEDE", repos="http://R-Forge.R-project.org") # # http://centipede.uchicago.edu/ # include: '../ngs.settings.smk' config_default = { 'bio.ngs.motif.centipede' : { 'options' : '', ...
5,020
cdc9bc97332a3914415b16f00bc098acc7a02863
L = "chaine de caractere" print("parcours par รฉlรฉment") for e in L : print("caractere : *"+e+"*")
5,021
69511933697905fb4f365c895264596f19dc1d8d
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 26 18:39:26 2020 @author: Fanny Fredriksson and Karen Marie Sandรธ Ambrosen """ import numpy as np import matplotlib.pyplot as plt import pandas as pd from tqdm import tqdm #count ffor loops import math from sklearn.model_selection import GridSearch...
5,022
7d8c2aa5674704d4443034c29bbdc715da9fd567
""" db.้›†ๅˆ.update() """ """ ๅฎžไพ‹ ่ขซๆ›ฟๆขไบ† > db.test1000.update({'name':'dapeng'},{'name':'ๅคง้น'}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.test1000.find() { "_id" : ObjectId("5c35549d7ad0cf935d3c150d"), "name" : "ๅคง้น" } { "_id" : ObjectId("5c3554f37ad0cf935d3c150e"), "nInserted" : 1 } { "_id" : Obj...
5,023
c0c0ed31a09f2b49448bc1f3519aa61daaba20af
import sys input = sys.stdin.readline from collections import deque size, num = map(int,input().split()) position = list(map(int,input().split())) cnt =0 nums = [] for k in range(1,size+1) : nums.append(k) size = deque(nums) position = deque(position) while position != deque([]) : if position[0]==1: si...
5,024
351421ef6a40e3a4bd4549a1851fbf4bed9ddf30
ghj=input("enter your first name:") print("Welcome to my Quiz:\nIf you go wrong once you lose but if you give all the answers correct then you win but no CHEATING.") print("Q1:-Who is the president of India?") winlist=("ramnath govind","multiple choice question","multiple choice questions","mumbai") enter=input("en...
5,025
deff4eb3ae933a99036f39213ceaf2144b682904
from __future__ import print_function import re import sys from pyspark import SparkContext # define a regular expression for delimiters NON_WORDS_DELIMITER = re.compile(r'[^\w\d]+') def main(): if len(sys.argv) < 2: print('''Usage: pyspark q2.py <file> e.g. pyspark q2.py file:///home/cloudera/test...
5,026
2b9dfd0cfd62276330f1a4f983f318076f329437
def domain_name(url): while "https://" in url or "http://" in url or "www." in url: url = url.replace("https://", ' ') if "https://" in url else url.replace("http://", ' ') if "http://" in url else url.replace("www.", ' ') url = list(url) for i in range(len(url)): if url[i] == ".": ...
5,027
bf3b529f8f06619c94d2dfca283df086466af4ea
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-26 16:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20170308_1949'), ] operations = [ migrations.AlterField( ...
5,028
9bc15f063adc7d2a5ea81d090736ab6ce66a03d4
from django.db import models from django.utils.safestring import mark_safe from ondoc.authentication.models import TimeStampedModel, CreatedByModel, Image import datetime from django.contrib.contenttypes.models import ContentType from django.urls import reverse from ondoc.doctor.models import Doctor, PracticeSpecializ...
5,029
cc160b1b0478446ba0daec4a0fe9e63453df3d96
N = int(input()) A_list = list(map(int,input().split())) B_list = list(map(int,input().split())) C_list = list(map(int,input().split())) ans = 0 for i in range(N): ans += B_list[A_list[i]-1] if i < N-1: if A_list[i]+1==A_list[i+1]: ans += C_list[A_list[i]-1] print(ans)
5,030
4c1fea4dcf143ec976d3956039616963760d5af6
# add some description here import glob import matplotlib.pyplot as plt import numpy as np import pandas as pd import xarray as xr import pandas as pd import os import pickle from scipy.interpolate import griddata from mpl_toolkits.basemap import Basemap from mpl_toolkits.axes_grid1 import make_axes_locatable from mat...
5,031
6025b8d4015572ea1a760c1b4bc7200a1019c802
from can.interfaces.ics_neovi.neovi_bus import NeoViBus
5,032
0ff8743e54509a76e9a7add4be9da279bdee82a6
class Solution: def calculate(self, s: str) -> int: nums = [] ops = [] def cal(): a = nums.pop() b = nums.pop() c = ops.pop() if c == '+': nums.append(b + a) elif c == '-': nums.append(b - a) ...
5,033
d50618f7784e69b46cb665ec1a9c56f7a2867785
#n-repeated element class Solution: def repeatedNTimes(self, A): freq = {} for i in A: if i in freq.keys(): freq[i] += 1 else: freq[i] = 1 key = list(freq.keys()) val = list(freq.values()) m = max(val) return key...
5,034
a8f200e0ae1252df4ad6560e5756347cd0e4c8ba
""" Client component of the Quartjes connector. Use the ClientConnector to create a connection to the Quartjes server. Usage ----- Create an instance of this object with the host and port to connect to. Call the start() method to establish the connection. Now the database and the stock_exchange variable can be used to...
5,035
fe01b78d29dc456f7a537dd5639bc658fc184e36
from collections import defaultdict, namedtuple from color import RGB, clamp import math import controls_model as controls from eyes import Eye, MutableEye from geom import ALL #from icicles.ice_geom import ALL def load_geometry(mapfile): """ Load sheep neighbor geometry Returns a map { panel: [(edge-ne...
5,036
beb536b6d8883daaa7e41da03145dd98aa223cbf
from room import Room from player import Player from item import Item # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons"), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""...
5,037
222a02f97df5ded6fea49e9eb201ed784a2a2423
# # # ## from __future__ import print_function, unicode_literals import inspect import os import pprint as pp import time from time import gmtime, strftime import subprocess from local import * from slurm import * class Job_status( object ): """ Enumerate class for job statuses, this is done differently in pyt...
5,038
0cef70b8d661fe01ef4a1eda83a21e1186419a0d
# coding: utf-8 """ Created on Mon Oct 29 12:57:40 2018 @authors Jzhu, Lrasmy , Xin128 @ DeguiZhi Lab - UTHealth SBMI Last updated Feb 20 2020 """ #general utilities from __future__ import print_function, division from tabulate import tabulate import numpy as np import random import matplotlib.pyplot as plt try: ...
5,039
c2e9a93861080be616b6d833a9343f1a2f018a0b
def presses(phrase): keyboard = [ '1', 'ABC2', 'DEF3', 'GHI4', 'JKL5', 'MNO6', 'PQRS7', 'TUV8', 'WXYZ9', '*', ' 0', '#' ] amount = 0 for lttr in phrase.upper(): for key in keyboard: try: ...
5,040
866ec11f6fe13fb2283709128376080afc7493bf
from datetime import datetime import httplib2 from apiclient.discovery import build from flask_login import UserMixin from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from oauth2client.client import OAuth2Credentials from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.types import...
5,041
1c668cf6f145b85a09b248fefda46e928de64e41
from django.shortcuts import render from rest_framework import status, viewsets , response from . import models from . import serializers # Create your views here. class TodoViewset(viewsets.ModelViewSet): queryset = models.Todo.objects.all() serializer_class = serializers.TodoSerializer
5,042
d7ff5bf5d8f397500fcac30b73f469316c908f15
def divisible_by(numbers, divisor): res = [] for e in numbers: if e % divisor == 0: res.append(e) return res
5,043
67385d6d58cc79037660be546d41ea9ba1f790fa
from datetime import date def solution(mon: int, day: int) -> str: return date(2016, mon, day).strftime("%a").upper()
5,044
f1ca3d7ff7efcf500f1a16e415b13c47fd08688d
# 30_Days_Of_Code # Day 2 # Boolean print(True) print(False)
5,045
6d0b9523668bd0b302fdbc196d3d7ff25be10b23
def clear_firefox_driver_session(firefox_driver): firefox_driver.delete_all_cookies() # Note this only works if the browser is set to a location. firefox_driver.execute_script('window.localStorage.clear();') firefox_driver.execute_script('window.sessionStorage.clear();') class LocationNotSet(Exception...
5,046
d36552cc589b03008dc9edab8d7e4a003e26bd21
from __future__ import print_function import tensorflow as tf # from keras.callbacks import ModelCheckpoint from data import load_train_data from utils import * import os create_paths() log_file = open(global_path + "logs/log_file.txt", 'a') X_train, y_train = load_train_data() labeled_index = np.arange(0, nb_labeled...
5,047
e1a2b33a1ec7aca21a157895d8c7c5b5f29ff49c
#!/usr/bin/python3 """ Requests username and tasks from JSON Placeholder based on userid (which is sys.argv[1]) """ import json import requests import sys if __name__ == "__main__": url = "https://jsonplaceholder.typicode.com" if len(sys.argv) > 1: user_id = sys.argv[1] name = requests.get("{}...
5,048
de819a72ab659b50620fad2296027cb9f4d3e4c0
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os import platform import subprocess # try to import json module, if got an error use simplejson instead of json. try: import json except ImportError: import simplejson as json # if your server uses fqdn, you can suppress the domain, just change the bellow...
5,049
8d4ffed90e103e61a85a54d6163770966fb2e5c9
#!/usr/bin/env python3 """Test telegram_menu package."""
5,050
1a730f4a5fa2be434af41a3e320cab8338d93644
def describe(): desc = """ Problem : Given a string, find the length of the longest substring in it with no more than K distinct characters. For example : Input: String="araaci", K=2 Output: 4 Explanation: The longest substring with no more than '2' distinct characters is "araa", where the distinct char...
5,051
7455eb670c2c019b8d066fcc6f2878a2136b7fd0
__author__ = "Prikly Grayp" __license__ = "MIT" __version__ = "1.0.0" __email__ = "priklygrayp@gmail.com" __status__ = "Development" from contextlib import closing class RefrigeratorRaider: '''Raid a refrigerator''' def open(self): print('Open fridge door.') def take(self, food): print('...
5,052
9cc6700ab14bed9d69d90c1540f6d42186033a19
from typing import List def sift_up(heap: List, pos: int = None): if pos is None: pos = len(heap) - 1 current, parent = pos, (pos - 1) // 2 while current > 0: if heap[current] > heap[parent]: heap[current], heap[parent] = heap[parent], heap[current] else: b...
5,053
3a878c91218dfbf23477ae5b7561e9eecfcd1350
""" Created on Dec 1, 2014 @author: Ira Fich """ import random from igfig.containers import WeightedList class Replacer(): """ A class that replaces itself with a subclass of itself when you instantiate it """ subclass_weight = 0 def __new__(cls, *args, **kwargs): subs = WeightedList(cls.__subclasses__(),...
5,054
25a159ca2abf0176135086324ab355d6f5d9fe9e
#!/bin/python3 import sys from collections import deque def connectedCell(matrix,n,m): # Complete this function visit = [] for j in range(n): a = [] for i in range(m): a.append(True) visit.append(a) #print(visit) path = 0 for i in range(n): for j in ...
5,055
1b741b34649193b64479724670244d258cfbbdfc
import RPi.GPIO as GPIO import numpy as np import array import time import json import LED_GPIO as led import BUTTON_GPIO as btn import parseJson as gjs rndBtnState = False interval = .1 rndbtn = gjs.getJsonRnd() gpioValues = gjs.getJsonData() strArray = gpioValues[0] btnArray = gpioValues[1] ledArray = gpioValue...
5,056
44dee207ffa4f78293484126234a3b606e79915b
#!/usr/bin/env python3 # Written by jack @ nyi # Licensed under FreeBSD's 3 clause BSD license. see LICENSE '''This class calls the system's "ping" command and stores the results''' class sys_ping: '''this class is a python wrapper for UNIX system ping command, subclass ping does the work, last stores data from t...
5,057
e3071643548bb3a4e8d0a5710820ad39b8a6b04b
#!/usr/bin/env python # -*- coding: utf-8 -*- """Script to view and manage OPenn repositories. Use this script to list and update OPenn primary repositories, to view repository details, and to list documents in each repository. """ import os import sys import argparse import logging sys.path.insert(0, os.path.abspa...
5,058
2fc2fd6631cee5f3737dadaac1a115c045af0986
# Libraries from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.orm import relationship # Taskobra from taskobra.orm.base import ORMBase from taskobra.orm.relationships import SystemComponent class System(ORMBase): __tablename__ ...
5,059
ac8c8dc4bcccef7942dd48d54902e13e811f950c
#!/usr/bin/env python # coding: utf-8 from unittest import TestCase from optimoida.logging import ( SUCCESS, FAILURE, logger) class LoggerTestCase(TestCase): def test_flag_value(self): self.assertEqual(SUCCESS, "\x1b[34mSUCCESS\x1b[0m") self.assertEqual(FAILURE, "\x1b[31mFAILURE\x1b[0m") ...
5,060
416f4c6bbd2f2b9562ab2d1477df4ebc45070d8d
#!/usr/bin/env python3 import argparse import boutvecma import easyvvuq as uq import chaospy import os import numpy as np import time from dask.distributed import Client from dask_jobqueue import SLURMCluster import matplotlib.pyplot as plt if __name__ == "__main__": parser = argparse.ArgumentParser(description...
5,061
1a9cad6e49e5ed2bb7781f9fec930d48ec048b3b
#!/usr/bin/env python # coding: utf-8 # MIT Licensed # http://opensource.org/licenses/MIT led_dir = "/sys/class/gpio/gpio40/" led_pin = led_dir + "value" led_mode = led_dir + "direction" with open(led_mode, "wb") as f: f.write("out") with open(led_pin, "wb") as f: f.write(__import__("sys").argv[1]) """ Contrib...
5,062
70c20b38edb01552a8c7531b3e87a9302ffaf6c5
# -*- coding: utf-8 -*- """Module providing views for asset storage folder""" from Products.Five.browser import BrowserView from plone import api from plone.app.contenttypes.interfaces import IImage class AssetRepositoryView(BrowserView): """ Folderish content page default view """ def contained_items(self, u...
5,063
28077af0759e062078f7b9d1f7bbbb93c62835cb
version = (2, 5, 8) version_string = ".".join(str(v) for v in version) release_date = "2015.12.27"
5,064
ec19567b49f686f613308d79e439f6ff9053fa40
import sys import os import logging import sh from ..util.path import SmartTempDir, replace_path logger = logging.getLogger('pyrsss.gps.teqc') def rinex_info(rinex_fname, nav_fname, work_path=None): """ Query RINEX file *rinex_fname* and RINEX nav file *nav_fname* for usef...
5,065
ecd5097d9d497b62b89217ee3c46506f21fc15d2
from web3 import Web3, HTTPProvider, IPCProvider from tcmb.tcmb_parser import TCMB_Processor from ecb.ecb_parser import ECB_Processor from web3.contract import ConciseContract from web3.middleware import geth_poa_middleware import json import time tcmb_currencies = ["TRY", "USD", "AUD", "DKK", "EUR", "GBP", "CHF", "SE...
5,066
d9cdcf64042c3c6c4b45ec0e3334ba756dd43fcd
# -*- coding: utf-8 -*- """ Created on Mon May 2 17:24:00 2016 @author: pasca """ # -*- coding: utf-8 -*- import os.path as op from nipype.utils.filemanip import split_filename as split_f from nipype.interfaces.base import BaseInterface, BaseInterfaceInputSpec from nipype.interfaces.base import traits, File, Trait...
5,067
4a8d203872a1e86c54142dea6cd04c1cac6bcfb2
# coding: utf-8 # In[1]: import numpy as np import pandas as pd from sklearn.svm import SVR # In[2]: from sklearn.preprocessing import StandardScaler # In[3]: #import matplotlib.pyplot as plt # %matplotlib inline # In[90]: aapl = pd.read_csv('return_fcast.csv') # In[79]: y = aapl['return'] # In[80]: ...
5,068
2a09711e3e487c5d7790af592ff2eb03bb53cff2
def inplace_quick_sort(S, start, end): if start > end: return pivot = S[end] left = start right = end - 1 while left <= right: while left <= right and S[left] < pivot: left += 1 while left <= right and pivot < S[right]: right -= 1 ...
5,069
046db03b146ce0182ba7889908f536a09de051d5
from HDPython import * import HDPython.examples as ahe from enum import Enum, auto class counter_state(Enum): idle = auto() running = auto() done = auto() class Counter_cl(v_class_master): def __init__(self): super().__init__() self.counter = v_variable(v_slv(32)) self.cou...
5,070
628fdf848079d0ecf5bf4f5bd46e07ad6cd10358
from threading import Thread import time def sleeping(): time.sleep(5) print('Ended') Thread(target=sleeping, daemon=True).start() print('Hello world') time.sleep(5.5)
5,071
454f885e2254295ce6508e70c0348f5cbe855520
from handler.auth import provider_required from handler.provider import ProviderBaseHandler from forms.provider import ProviderAddressForm, ProviderVanityURLForm import logging from data import db from util import saved_message class ProviderEditAddressHandler(ProviderBaseHandler): @provider_required def get(s...
5,072
2dc4a4ae8e02e823073b1a9711dbd864a54bab43
class Account: '''์€ํ–‰๊ณ„์ขŒ๋ฅผ ํ‘œํ˜„ํ•˜๋Š” ํด๋ž˜์Šค''' def __init__(self,name,account): self.name = name self._balance = amount def __str__(self): return '์˜ˆ๊ธˆ์ฃผ {}, ์ž”๊ณ  {}'.format(slef.name, self._balance) def _info(self): print('\t')
5,073
abf25cf3d4435754b916fa06e5e887b1e3589a1c
from django import forms from crawlr.models import Route, Category, UserProfile from django.contrib.auth.models import User class CategoryForm(forms.ModelForm): name = forms.CharField(max_length=128, help_text = "Please enter the category name.") views = forms.IntegerField(widget=for...
5,074
c2c1194ed23adda015b23897888d1a4cc11423d5
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2014 Thibaut Lapierre <git@epheo.eu>. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # ...
5,075
fc8976141a19afd099f92cbbdb578e9c620cb745
array = [1, 7, 3, 8, 9, 2, 4] index = 0 while (index < len(array)): count = 0 while(count <= len(array)-2): if(count == len(array)-1): break if (array[count] > array[count+1]): sift = array[count] array[count] = array[count+1] array[count+1] = sift...
5,076
e7295336a168aa2361a9090e79465eab5f564599
__author__ = 'sushil' from .utilities import decompose_date from .DateConverter import _bs_to_ad, _ad_to_bs def convert_to_ad(bs_date): date_components = decompose_date(bs_date) year, month, day = date_components ad_year, ad_month, ad_day = _bs_to_ad(year, month, day) formatted_date = "{}-{:02}-{:02}"...
5,077
839b3ebffebce95de25f75edc67a647bd1318268
#!/usr/bin/env python from __future__ import division from __future__ import print_function import numpy as np from mpi4py import MPI from parutils import pprint comm = MPI.COMM_WORLD pprint("-"*78) pprint(" Running on %d cores" % comm.size) pprint("-"*78) comm.Barrier() # Prepare a vector of N=5 elements to be ...
5,078
f1b36e3ce3189c8dca2e41664ac1a6d632d23f79
import ssl import sys import psycopg2 #conectarte python con postresql import paho.mqtt.client #pip install paho-mqtt import json conn = psycopg2.connect(host = 'raja.db.elephantsql.com', user= 'oyoqynnr', password ='myHVlpJkEO21o29GKYSvMCGI3g4y05bh', dbname= 'oyoqynnr') def on_connect(client, userdata, flags, r...
5,079
1db397df2d030b2f622e701c46c15d653cb79e55
from ParseTree import ParseTree from Node import Node from NodeInfo import NodeInfo from TreeAdjustor import TreeAdjustor from model.SchemaGraph import SchemaGraph class TreeAdjustorTest: schema = None def __init__(self): return def getAdjustedTreesTest(self): T = ParseTree() ...
5,080
513aff6cf29bbce55e2382943767a9a21df2e98e
#-*-coding:utf-8-*- from Classify import get_train_data import sys ''' ่Žทๅ–่ฎญ็ปƒ้›†ๆ•ฐๆฎ ''' get_train_data(sys.argv[1], sys.argv[2])
5,081
dd7896e3beb5e33282b38efe0a4fc650e629b185
from gym_mag.envs.mag_control_env import MagControlEnv
5,082
d86fe165e378e56650e3b76bf3d0f72e2a50a023
import requests rsp = requests.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s'%('wx27c0e6ef6a7f0716','6e29e232daf462652f66ee8acc11838b')) print(rsp.text)
5,083
e8e78610df4461a96f7d9858870de0e3482801fd
#!/usr/bin/env python import argparse import requests import sys import os import xml.dom.minidom __author__ = 'Tighe Schlottog || tschlottog@paloaltonetworks.com' ''' wf.py is a script to interact with the WildFire API to upload files or pull back reports on specific hashes. You need to have the argparse a...
5,084
7de3c0ab2e7c8ac00d37f1dfb5948027cfa7806c
######################################################### # Author: Todd A. Reisel # Date: 2/24/2003 # Class: StaticTemplateList ######################################################### from BaseClasses.TemplateList import *; class StaticTemplateList(TemplateList): def __init__(self, viewMode = None): Te...
5,085
f178ae70ce54244624c2254d0d6256b83144db33
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg # Define a function to compute color histogram features # Pass the color_space flag as 3-letter all caps string # like 'HSV' or 'LUV' etc. # KEEP IN MIND IF YOU DECIDE TO USE THIS FUNCTION LATER # IN YOUR PROJECT THAT IF ...
5,086
6ce50552571594c7be77ac0bf3b5274f2f39e545
class Circle(): def __init__(self, radius, color="white"): self.radius = radius self.color = color c1 = Circle(10, "black") print("ๅŠๅพ„:{}, ่‰ฒ: {}".format(c1.radius, c1.color))
5,087
4122da21abab462a28c925c1afa5792ec729a75a
import re print("Welcome to the Python Calculator") print("To stop calculator type: quit") previous = 0 run = True def perform_math(): '''(numbers) -> numbers accepts numbers from the user and performs continuous mathematical equations on them. precondition input must be numbers and m...
5,088
305554fc86ddc116677b6d95db7d94d9f2213c41
from .line_detection_research import score_pixel_v3p2
5,089
3bb25cedc29f9063046329db1c00e7d9e10ce1cc
#!/usr/bin/env python # -*- coding: UTF-8 -*- from multiprocess.managers import BaseManager from linphonebase import LinphoneBase class MyManager(BaseManager): pass MyManager.register('LinphoneBase', LinphoneBase) manager = MyManager() manager.start() linphoneBase = manager.LinphoneBase()
5,090
5aaac757b766b0143ca3ea54d8fc4b8936160ec7
from django.urls import path from . import views # url configuration for view.index function app_name = 'movies' urlpatterns = [ path('', views.index, name='index'), # represents a root of this app path('<int:movie_id>', views.detail, name='detail') ]
5,091
a7de079866d7ac80260b438043cf0403f598cebc
''' Write the necessary code to display the area and perimeter of a rectangle that has a width of 2.4 and a height of 6.4. ''' x, y = 2.4, 6.4 perimeter = (x*2)+(y*2) area = x*y print("Perimeter is "+str(perimeter) + ", Area is " + str(area))
5,092
4ad3390f8f2c92f35acde507be7a7b713af997f2
from odoo import models, fields, api class Aceptar_letras_wizard(models.TransientModel): _name = 'aceptar_letras_wizard' _description = "Aceptar letras" def _get_letras(self): if self.env.context and self.env.context.get('active_ids'): return self.env.context.get('active_ids') ...
5,093
68bcb76a9c736e21cc1f54c6343c72b11e575b5d
import time import torch from torch.utils.data import DataLoader from nn_model import NNModel def train(dataset: 'Dataset', epochs: int=10): loader = DataLoader(dataset, batch_size=2, shuffle=True) model = NNModel(n_input=2, n_output=3) # model.to(device='cpu') optimizer = torch.optim.Adam(model.p...
5,094
be867d600f5f267986368f5573006f63004dbf9e
seq = input('write a sequence of numbers: ') print(seq.split(',')) print(tuple(seq.split(',')))
5,095
c9f4ae94dc901d34a3c0fb4371c8d35a7fe94507
"""Exercise 7.2. Encapsulate this loop in a function called square_root that takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.""" def my_square_root(a,x) : e = 0.0001 while True : y=(x+a/x)/2 if abs(y-x) < e : return y ...
5,096
fed94e0affa1fe6c705577a63fabee839aa9f05c
# Generated by Django 2.0.1 on 2018-05-01 11:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rover', '0002_auto_20180501_1431'), ] operations = [ migrations.CreateModel( name='RoverPage', fields=[ ...
5,097
eb99def75404bc3b674bcb633714009149f2d50d
# Named Entity Recognition on Medical Data (BIO Tagging) # Bio-Word2Vec Embeddings Source and Reference: https://github.com/ncbi-nlp/BioWordVec import os import re import torch import pickle from torch import nn from torch import optim import torch.nn.functional as F import numpy as np import random from DNC.dnc imp...
5,098
94cbd9554e3326897147dc417d9fc8f91974786a
#!/bin/env python3 """ https://www.hackerrank.com/challenges/triangle-quest-2 INPUT: integer N where 0 < N < 10 OUTPUT: print palindromic triangle of size N e.g.for N=5 1 121 12321 1234321 123454321 """ for i in range(1, int(input()) + 1): j = 1 while j < i: print(j,end='') j += 1 w...
5,099
849db3a92e0544661dd465b3e7f6949f8de5633b
from PyQt5.QtWidgets import * from select_substituents_table import * from save_selection_dialog import * class SelectSubsDialog(QDialog): def __init__(self, r_group): super().__init__() self.r_group = r_group self.substituents = None self.new_set_saved = False self.setWi...