seq_id stringlengths 4 11 | text stringlengths 113 2.92M | repo_name stringlengths 4 125 ⌀ | sub_path stringlengths 3 214 | file_name stringlengths 3 160 | file_ext stringclasses 18
values | file_size_in_byte int64 113 2.92M | program_lang stringclasses 1
value | lang stringclasses 93
values | doc_type stringclasses 1
value | stars int64 0 179k ⌀ | dataset stringclasses 3
values | pt stringclasses 78
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
38031987622 | import csv
from ipaddress import ip_address
from .report import Host, Port
ALLOWED_COLUMNS = [
'ipv4',
'hostname',
'os_name',
'port',
'state',
'protocol',
'service',
'software_banner',
'version',
'cpe',
'other_info',
]
class CSVFileParser:
def load_hosts(self, fi... | delvelabs/batea | batea/core/csv_parser.py | csv_parser.py | py | 1,260 | python | en | code | 287 | github-code | 36 |
72724139624 | """
Faça um programa que leia nome e peso de várias pessoas,
guardando tudo em uma lista. No final, mostre:
A) Quantas pessoas foram cadastradas.
B) Uma listagem com as pessoas mais pesadas.
C) Uma listagem com as pessoas mais leves.
"""
lista = list()
dados = list()
tot = 0
mai = men = 0
while True:
dados.append(... | andersondev96/Curso-em-Video-Python | Ex084.py | Ex084.py | py | 989 | python | pt | code | 0 | github-code | 36 |
4778234359 | import os
import re
import glob
import datetime
from prettytable import PrettyTable
from matplotlib import pyplot as plt
NUM_MOST_RECENT_RUNS = 100
te_path = os.getenv("TE_PATH", "/opt/transformerengine")
mlm_log_dir = os.path.join(te_path, "ci_logs")
te_ci_log_dir = "/data/transformer_engine_ci_logs"
te_ci_plot_dir... | NVIDIA/TransformerEngine | tests/pytorch/distributed/print_logs.py | print_logs.py | py | 4,204 | python | en | code | 1,056 | github-code | 36 |
21173649855 | def RemoveDups(str):
l1={}
for i in str:
if i not in l1:
l1[i]=1
if i in l1:
continue
str=""
for x,y in l1.items():
str+=x
return str
str = "helllomanvvith"
print(RemoveDups(str))
| ManvithKumar/Py_codes | challenges/RemoveDups.py | RemoveDups.py | py | 261 | python | en | code | 0 | github-code | 36 |
16703859938 | # Copyright 2020 University of Basel, Center for medical Image Analysis and Navigation
#
# 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... | JuliaWolleb/DeScarGAN | main.py | main.py | py | 1,954 | python | en | code | 31 | github-code | 36 |
22984372414 | from .deltakere import Deltakere
from .lyd import Uro
import tkinter as Vindu
import random
import time
class Lek:
def __init__(self,
wait_time,
playlist,
directory,
music,
volume):
"""
Hovedklasse.
Para... | hallvardnmbu/PartyGame | src/norsk_personlig/lek.py | lek.py | py | 17,493 | python | no | code | 0 | github-code | 36 |
7450851742 | from django.conf import settings
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^user_profile/', include('user_profile.urls')),
url(r'^wd2csv/', include('wd2csv.urls')),
url(r'', include('homepage.urls')),
]
if setting... | Ash-Crow/ash-django | ash-django_app/urls.py | urls.py | py | 456 | python | en | code | 1 | github-code | 36 |
3110641490 | """
Creator:
Dhruuv Agarwal
Github: Dhr11
Reference used for iou calculation:
https://github.com/warmspringwinds/pytorch-segmentation-detection/blob/master/pytorch_segmentation_detection/metrics.py
"""
import numpy as np
from sklearn.metrics import confusion_matrix
class custom_conf_matrix():
def __init__(self, ... | Dhr11/Semantic_Segmentation | metrics.py | metrics.py | py | 1,203 | python | en | code | 2 | github-code | 36 |
1126909056 | import ply.yacc as yacc
from Parser.Lexer import Lexer
class Parser:
tokens = Lexer.tokens
def __init__(self):
self.input = None
self.symbolList = {'globalSymbol': {}, 'subFuncSymbol': {}, 'funcID': {}}
self.isInSubFunc = False
self.error = []
self.warning = []
... | wyjBot/Pascal_complier | Parser/Parser.py | Parser.py | py | 45,005 | python | en | code | 0 | github-code | 36 |
23559462035 | from pydicm import *
# import logging
# logging.basicConfig(level=0)
fn = "/tmp/input.dcm"
with open(fn, "rb") as f:
parser = Parser()
parser.set_input(f)
done = False
while not done:
ret = parser.next_event()
etype = ret
# print(etype)
if etype == Parser.EventType.ELE... | malaterre/pydicm | examples/dummy.py | dummy.py | py | 713 | python | en | code | 1 | github-code | 36 |
950439742 | pkgname = "gnome-settings-daemon"
pkgver = "45.0"
pkgrel = 0
build_style = "meson"
configure_args = ["-Dsystemd=false"]
hostmakedepends = [
"meson",
"pkgconf",
"glib-devel",
"xsltproc",
"docbook-xsl-nons",
"perl",
"gettext",
]
makedepends = [
"glib-devel",
"geocode-glib-devel",
"... | chimera-linux/cports | main/gnome-settings-daemon/template.py | template.py | py | 1,674 | python | en | code | 119 | github-code | 36 |
35076409139 | #!/bin/env python3.9
import sys
from base45 import b45decode
import zlib
from cbor2 import loads
from cose.messages import Sign1Message
from pyzbar.pyzbar import decode
from PIL import Image
import argparse
# Initialize components
CLI_PARSER = argparse.ArgumentParser()
def unpack_qr(qr_text):
compressed_bytes =... | ryanbnl/eu-dcc-diagnostics | print_payload_qr.py | print_payload_qr.py | py | 1,097 | python | en | code | 9 | github-code | 36 |
37711853411 | def openfile():
import json
f = open('bonus.txt', 'r')
val = json.load(f)
return val
def viewfile(content):
print(content)
def binarySearch(alist,item):
alist.sort()
first = 0
last = len(alist)-1
found = False
print(alist)
while first<=last and not found:
middle = (first+last)//2
if alist[middle] == i... | adnanhf/Basic-Programming-Algorithm | Modul-7-Sequential-and-Binary-Search/Bonus/module.py | module.py | py | 500 | python | en | code | 1 | github-code | 36 |
71916241705 | #!/usr/bin/env python
#mapper
import sys
import csv
reader = csv.reader(sys.stdin, delimiter='\t')
for line in reader:
if len(line) == 19:
if not line[0].isdigit(): # skip header
continue
node_id, title, tag_names, author_id, body, node_type, parent_id, abs_parent_id, added_at, scor... | yanyan2060/Udacity-Intro-to-Hadoop-and-MapReduce | Final_group.py | Final_group.py | py | 1,172 | python | en | code | 0 | github-code | 36 |
6435247522 | import sys
sys.setrecursionlimit(10**4)
def calcinterest(a,b,c):
bee = b
global count
interest = b * a
interest = round(interest*100) / 100
bee += interest
bee = round(bee*100) / 100
bee -= c
# print(addon)
# print(temp)
# print(count)
if count >= 1200:
return
e... | DongjiY/Kattis | src/creditcard.py | creditcard.py | py | 638 | python | en | code | 1 | github-code | 36 |
27545046731 | from tir import Webapp
import unittest
class OGAA580(unittest.TestCase):
@classmethod
def setUpClass(inst):
from datetime import datetime
DateSystem = datetime.today().strftime('%d/%m/%Y')
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGAADV',DateSystem,'T1','D MG ... | ccpn1988/TIR | Modules/SIGAAGR/OGAA580TestCase.py | OGAA580TestCase.py | py | 1,561 | python | en | code | 1 | github-code | 36 |
40082582688 | # import packages / libraries
import numpy
import torch
# import functions
from metrics import FOSC
class TemplatesHandler():
""" handles target updating and retrieving for the LOTS attack """
def __init__(self, template_size, num_classes, device):
self.templates = {i: [] for i in range(num_class... | michaelhodel/adversarial-training-with-lots | attacking.py | attacking.py | py | 8,200 | python | en | code | 0 | github-code | 36 |
39850416701 | import os
import sqlite3
import unittest
from fastapi.testclient import TestClient
from main import app, create_table, increment_count, DB_FILE
class FastAPITest(unittest.TestCase):
def setUp(self):
self.client = TestClient(app)
self.db_file = DB_FILE
create_table()
def tearDown(self... | jevillanueva/fastapi-jenkins | test.py | test.py | py | 1,527 | python | en | code | 0 | github-code | 36 |
7078700910 | import requests
from datetime import date, timedelta
import os
from twilio.rest import Client
STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"
STOCK_ENDPOINT_API = "https://www.alphavantage.co/support/#api-key"
NEWS_ENDPOINT_API = "https://newsapi.org/"
parameters = {
"function": "TIME_SERIES_DAILY",
"symbol"... | Omisw/Python_100_days | Day 36/main.py | main.py | py | 1,694 | python | en | code | 1 | github-code | 36 |
14381187351 | class Solution:
def selfDividingNumbers(self, left: int, right: int) -> List[int]:
def self_dividing(x: int) -> bool:
for i in str(x):
if i == '0':
return False
if x % int(i) != 0:
return False
return T... | jithindmathew/LeetCode | self-dividing-numbers.py | self-dividing-numbers.py | py | 474 | python | en | code | 0 | github-code | 36 |
2551686389 | #!/usr/bin/env python3
import sys
from ete3 import NCBITaxa
ncbi = NCBITaxa()
def get_desired_ranks(taxid):
desired_ranks = ['phylum', 'genus', 'species']
try:
lineage = ncbi.get_lineage(taxid)
except ValueError:
lineage = []
lineage2ranks = ncbi.get_rank(lineage)
ranks2lineage =... | waglecn/helD_search | scripts/tax_csv.py | tax_csv.py | py | 859 | python | en | code | 0 | github-code | 36 |
29112759837 | import uuid
from personal_okrs import db
from personal_okrs.data_model.objective import Objective
from personal_okrs.data_model.goal import Goal
# id = db.Column(db.String(255), primary_key=True)
# title = db.Column(db.String(512))
# description = db.Column(db.Text())
# type = db.Column(db.Enum(GoalTyp... | xonev/personal-okrs | personal_okrs/core/objective_repo.py | objective_repo.py | py | 1,304 | python | en | code | 0 | github-code | 36 |
33706303531 | import torch
import matplotlib.pyplot as plt
from pathlib import Path
import sys
sys.path.append("../")
import diffoptics as do
# initialization
# device = do.init()
device = torch.device('cpu')
# load target lens
lens = do.Lensgroup(device=device)
lens.load_file(Path('./lenses/Thorlabs/ACL5040U.txt'))
print(lens.su... | vccimaging/DiffOptics | examples/spherical_aberration.py | spherical_aberration.py | py | 1,719 | python | en | code | 96 | github-code | 36 |
38227695787 | from typing import (
List,
Tuple,
Dict,
Optional,
Callable,
)
import os
import sys
import unittest
from allennlp.data import Vocabulary
from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder
from allennlp.modules import TextFieldEmbedder, TokenEmbedder
from allennlp.data.token_i... | AkshatSh/DPD | tests/weak_supervision/cwr_func_test.py | cwr_func_test.py | py | 3,914 | python | en | code | 0 | github-code | 36 |
29937583846 | class Person:
name = "John"
country = "Norway"
setattr(Person, 'age', 40)
# The age property will now have the value: 40
x = getattr(Person, 'age')
print(x)
p = Person()
print(p.age)
| Alvanerle/PP2_Python | week/week 5/setattr.py | setattr.py | py | 195 | python | en | code | 0 | github-code | 36 |
17392602064 | import numpy as np
import matplotlib.pyplot as plt
class Model(object):
def __init__(self):
pass
def evaluate(self, loader):
raise NotImplementedError
def predict(self, data):
raise NotImplementedError
def train(self, train_loader, valid_loader=None, test_loader=None... | ekeilty17/Personal-Projects-In-Python | Machine_Learning/Models/model.py | model.py | py | 3,769 | python | en | code | 1 | github-code | 36 |
2884103209 | # coding:utf-8
from utils.util import get_code_token, get_requests, get_header ,form_post ,login ,json_post
#login('00852','20181205')
# rf_url = 'https://passport.lagou.com/grantServiceTicket/grant.html'
# get_header(rf_url)
cUserid = 80
def calling(cUserid):
calling_url = 'https://easy.lagou.com/phonecall/getVir... | Ariaxie-1985/aria | api_script/business/B_calling.py | B_calling.py | py | 688 | python | en | code | 0 | github-code | 36 |
25947081758 | # idea: problem is very similar to medium vertical traversal but the one thing
# we have to sort the nested array with row value
# the idea is to add row + val to nested array and sort them
# than loop throught and call sort for every nested array as well and
# add second value from this array to result
from collecti... | dzaytsev91/leetcode-algorithms | hard/987_vertical_order_traversal_of_a_binary_tree.py | 987_vertical_order_traversal_of_a_binary_tree.py | py | 1,160 | python | en | code | 2 | github-code | 36 |
7814996879 | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#Define some hyper-parameters
learning_rate = 0.01
epochs =1000
display_step = 100
# First generate some random (X, Y) points, in the plane
N = 100
xrange = 100
yrange = 10
db = 0.0
train_X1 = xrange ... | jojivk/Machine-Learning | Regression/multivariate.py | multivariate.py | py | 1,780 | python | en | code | 0 | github-code | 36 |
70580470825 | import cv2
import numpy as np
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
captura = cv2.VideoCapture(0)
captura.set(cv2.CAP_PROP_FPS,90)
captura.set(cv2.CAP_PROP_FRAME_WIDTH,320)
captura.set(cv2.CAP_PROP_FRAME_HEIGHT,240)
#La resolucion de la camara es 640x480 ------> Tamaño de la ventana openCv
... | jlukas1001/Seguidor-con-camara | seguidor2/seguidorVelocista/programaCamara.py | programaCamara.py | py | 3,765 | python | es | code | 0 | github-code | 36 |
2874693524 | import os
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.applications import VGG19
from tensorflow.keras.layers import MaxPooling2D
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
# Settings
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | CarlFredriksson/neural_style_transfer | neural_style_transfer.py | neural_style_transfer.py | py | 7,291 | python | en | code | 0 | github-code | 36 |
14791501184 | # -*- coding: utf-8 -*-
# 02/28/2022
import argparse
import os
import re
import json
import sys
import copy
from collections import OrderedDict
import opcodes_def
import cpx_opcode_def
def _read_json(filename=None):
json_object = None
crashfile = open(filename, 'r')
json_object = json.load(crashfile)
# ... | 0moyi0/onekeylog | onekeylog/converterranalyrpt.py | converterranalyrpt.py | py | 25,577 | python | en | code | 0 | github-code | 36 |
13989797888 | # this is editorial soln
from collections import deque
from sys import maxint
class Solution(object):
def bfs_search(self, matrix, queue, min_dist):
n, m = len(matrix), len(matrix[0])
while queue:
(x, y), d = queue.popleft()
for i, j in ((x - 1, y), (x + 1, y), (x, y - 1),... | dariomx/topcoder-srm | leetcode/zero-pass/google/01-matrix/Solution15.py | Solution15.py | py | 1,046 | python | en | code | 0 | github-code | 36 |
26870868112 | N = input()
miniL = maxiL = miniR = maxiR = 0
for i in range(3):
if N[i] == "*":
maxiL += 9
else:
miniL += int(N[i])
maxiL += int(N[i])
if N[i+3] == "*":
maxiR += 9
else:
miniR += int(N[i+3])
maxiR += int(N[i+3])
if maxiL < miniR or maxiR < miniL:
print("No")
else:
print("Yes")
| Maxim-2005/Olimp | Town-2022/5-Счастливый билетик.py | 5-Счастливый билетик.py | py | 300 | python | en | code | 3 | github-code | 36 |
37974609826 | import numpy as np
import matplotlib.pyplot as plt
import random
def random_angle():
return random.uniform(0, 2*np.pi)
def next_step(x_pos, y_pos):
angle = random_angle()
x_pos += np.cos(angle)
y_pos += np.sin(angle)
return (x_pos, y_pos)
colors = ['black', 'red', 'yellow', 'blue', 'orange', 'pur... | Fadikk367/WFiIS-VPython | LAB07/ZAD1B.py | ZAD1B.py | py | 877 | python | en | code | 0 | github-code | 36 |
4061239228 | #!/usr/bin/env python3
# coding=utf-8
"""
@athor:weifeng.guo
@data:2019/6/25 9:41
@filename:test_my_math
"""
import unittest
from chapter16 import my_math
class test_integer(unittest.TestCase):
def test_integers(self):
for x in range(-10, 10):
for y in range(-10, 10):
p = my... | guoweifeng216/python | python_basic/chapter16/test_my_math.py | test_my_math.py | py | 731 | python | en | code | 0 | github-code | 36 |
70230288424 | import graphene
class CreateAuctionInput(graphene.InputObjectType):
meme = graphene.List(graphene.NonNull(graphene.ID))
initial_price = graphene.Int(required = True)
limit = graphene.Int()
starts_at = graphene.DateTime(required = True)
ends_at = graphene.DateTime(required = True)
class Updat... | Bluefin-Tuna/meme-economy | ME/auction/GQL/inputs/auction.py | auction.py | py | 623 | python | en | code | 0 | github-code | 36 |
35566548820 | import torch
import json
import numpy as np
import torch.utils.data
class DataSet(torch.utils.data.Dataset):
def __init__(self, data_path: str, metadata_path: str, args):
with open(metadata_path, 'r') as j:
obj = json.load(j)
self.normalize = obj['normalized']
data_t... | kristofers-volkovs/Primed-UNet-LSTM | src/data_sets/data_rollout.py | data_rollout.py | py | 2,473 | python | en | code | 0 | github-code | 36 |
3853633003 | from Logger import Logger
from ConsoleLogger import ConsoleLogger
from HTTPRequest import HTTPRequest
from HTTPProxyRequest import HTTPProxyRequest
from ProxyManager import ProxyManager
import multiprocessing
import multiprocessing.managers
import json
import re
regex_email = '([A-Z0-9%+\-\._]+@[A-Z0-9\.\-_]+\.[A-Z0-9... | dsypniewski/allegro-profile-crawler | main.py | main.py | py | 8,550 | python | en | code | 0 | github-code | 36 |
44556329603 | #!/usr/bin/python3
import sys
import os.path
from parse_file import parse_file
def main():
file_name = ""
arg_num = len(sys.argv)
# check if too few arguments were supplied
if arg_num != 2:
print("Usage: factors <file>")
return 1
# check if file exists
if not os.path.isfile(... | patrickolumba/RSA-Factoring-Challenge | TASK-0-PYTHON/main.py | main.py | py | 535 | python | en | code | 0 | github-code | 36 |
72808863784 | from django.shortcuts import render,redirect
from django.http import JsonResponse
from rest_framework.decorators import api_view,permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly,IsAuthenticated
from .models import Advocate,Company
from .ser... | sakibsarker/REST_framework_Function-based | restwork/views.py | views.py | py | 3,777 | python | en | code | 0 | github-code | 36 |
28088792579 | import requests
from bs4 import BeautifulSoup
from .crawler import Crawler
from ..models.page import PageScraperModel
class SeedingCrawler(Crawler):
def __init__(self, base_url):
super().__init__(base_url + 'd/furniture/search/fua?')
self.stack = []
def scrape(self):
html = self.get... | philipk19238/klarity | api/app/scraper/crawlers/seeding_crawler.py | seeding_crawler.py | py | 1,372 | python | en | code | 1 | github-code | 36 |
42686015636 | #! /usr/bin/python
# -*- coding: utf-8 -*-
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__="andrew.tuley"
__date__ ="$24-Jul-2015 16:06:48$"
from Players import Player1,... | drewtuley/pythonplay | src/noughts_and_crosses/play.py | play.py | py | 2,393 | python | en | code | 0 | github-code | 36 |
33319839140 | from pygame import *
from meteor import Meteor
MOVE_SPEED = 3
WIDTH = 90
HEIGHT = 82
class SpaceShip(sprite.Sprite):
def __init__(self, x, y):
super(SpaceShip, self).__init__()
position = (x, y)
self.alive = True
self.image = Surface((WIDTH, HEIGHT), SRCALPHA)
self.image ... | MrRamka/FlyGame | space_ship.py | space_ship.py | py | 1,571 | python | en | code | 0 | github-code | 36 |
28564597089 | from functools import cache
import matplotlib.pyplot as plt
import numpy as np
from data import NICKEL_REGIMES, load_experiment_data
from experiment_setup import NI_FOIL
from intensity import output_intensity
from materials import Layer, Cell, KAPTON
def get_geometric_factor_ascan(plot=False):
# Limits determi... | ondraskacel/cellExperiments | geometry.py | geometry.py | py | 2,922 | python | en | code | 1 | github-code | 36 |
70669125543 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
# WDQ7005 - Data Mining
# Master of Data Science | University of Malaya
# Assignment Part A: Web Crawling of Real-time Data
# Group Members:
# Azwa Kamaruddin (WQD170089)
# Kok Hon Loong (WQD170086)
# In[1]:
import requests
import pandas as pd
import numpy as np
im... | hlkok/WQD7005DataMining-Assignments | Assignment-a-Web-Crawler_Final.py | Assignment-a-Web-Crawler_Final.py | py | 11,487 | python | en | code | 1 | github-code | 36 |
30800479288 | import time, datetime
from decoder import Decoder, InvalidGearException
import os, yaml, shutil, json
from gear import Gear, Substat
import unidecode
from PIL import Image
def show_img(path):
img = Image.open(path)
img.show()
de... | FrenchieTucker/RPGgearDetection | main_correcter.py | main_correcter.py | py | 4,475 | python | en | code | 0 | github-code | 36 |
1434884470 | import json
import sys
from btcc_trade_collector import bttc_trade_collector
from btcc_client import Market
from btcc_log import create_timed_rotating_log
from btcc_log import set_log_name_prefix
with open("./collector_config.json") as config_file:
config = json.load(config_file)
if (len(sys.argv) != 2):
pr... | UnluckyNinja/hwindCode | python/btctrade/run_collector.py | run_collector.py | py | 823 | python | en | code | 0 | github-code | 36 |
72809308264 | from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union
import attr
from ..models.extension_value_type import ExtensionValueType
from ..types import UNSET, Unset
if TYPE_CHECKING:
from ..models.reference import Reference
T = TypeVar("T", bound="Extension")
@attr.s(auto_attribs=True)
class Ext... | sdm4fzi/aas2openapi | ba-syx-submodel-repository-client/ba_syx_submodel_repository_client/models/extension.py | extension.py | py | 5,047 | python | en | code | 7 | github-code | 36 |
20070029006 | from itertools import compress
def bool_code(number):
b = list()
while number != 0:
if number % 2 == 1:
b.append(True)
else:
b.append(False)
number >>= 1
return b
def bit_not(n, num_bits):
return (1 << num_bits) - 1 - n
def translate_code(items, mask... | mghorbani2357/TT-Miner-Topology-Transaction-Miner-for-Mining-Closed-Itemset | utils/tools.py | tools.py | py | 897 | python | en | code | 1 | github-code | 36 |
22869103126 | __author__ = "Dev Churiwala"
"""
Simple model to predict the XOR/XNOR output of 2 bits based on third input
"""
import numpy as np
def sigmoid (x):
return (1/(1 + np.exp(-x)))
def sigmoid_derivative(x):
return (x * (1 - x))
#Input datasets
inputs = np.array([[1,1,0],[1,0,0],[0,1,0],[0,0,0],[1,1,1],[1,0,1... | DevChuriwala/SpikingNeuralNetwork | Neural Net for XOR-XNOR/2 Layer Model.py | 2 Layer Model.py | py | 1,936 | python | en | code | 0 | github-code | 36 |
15655149893 | import os
import pickle
import csv
import json
from copy import copy
import numpy as np
import datetime
from scipy.spatial.distance import jaccard, euclidean
def get_files(root_path):
dat_files = set()
for (root, dirs, files) in os.walk(root_path, topdown=True):
for file in files:
dat_files.add(root_... | ssikdar1/DeconstructingTheFilterBubble | replication_files/dump_to_dataset.py | dump_to_dataset.py | py | 7,917 | python | en | code | 5 | github-code | 36 |
27757909127 | # -*- coding: utf-8 -*-
import scrapy
'''以JSON格式导出爬取内容'''
class QuetosExtractSpider(scrapy.Spider):
name = 'quetos_extract'
def start_requests(self):
urls = [
'http://quotes.toscrape.com/page/1/',
'http://quotes.toscrape.com/page/2/',
]
for url in urls:
... | IceDerce/python-spider-practice | spider/scrapy_practice/scrapy_practice/spiders/quotes_extract.py | quotes_extract.py | py | 997 | python | en | code | 0 | github-code | 36 |
7396903634 | """
Based on:
https://devcenter.heroku.com/articles/getting-started-with-django
"""
from settings import *
import os
DEBUG = False
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default': dj_database_url.config() }
WSGI_APPLICATION = 'pdxtrees.wsgi_deploy.application'
SEC... | mattblair/pdx-trees-django | pdxtrees/settings_production.py | settings_production.py | py | 860 | python | en | code | 0 | github-code | 36 |
41761215227 | # coding:utf-8
from __future__ import unicode_literals
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
def clean_qq(self):
cleaned_data = self.cleaned_data['qq']
if not cleaned_data.isdigit():
raise forms.ValidationError('必须是数字!')
ret... | the5fire/django-practice-book | code/student_house/student_sys/student/forms.py | forms.py | py | 500 | python | en | code | 293 | github-code | 36 |
21194314439 | # 读取数据
import pandas as pd
def load_wingsize():
"""
:return: the wing span limitations for each gate
"""
data = pd.read_excel("./data/wingsizelimit.xls", sheet_name=None)
sheet_data = data['sheet1']
wingsize = {}
for i in sheet_data.index:
# print(sheet_data['gate'][i], end=' ')
... | VON0000/GAP | getdata.py | getdata.py | py | 3,327 | python | en | code | 0 | github-code | 36 |
20408748520 | """
This variables and constants are using in
the main file - main.py. Each section
is dived by following comment.
"""
from math import ceil
from pygame import init, display, FULLSCREEN
# display
init()
display_info = display.Info()
width = display_info.current_w
height = display_info.current_h
screen_mode = FULLSCR... | a1k0u/uni-projects | python/galton_board/config.py | config.py | py | 4,504 | python | en | code | 1 | github-code | 36 |
20024067664 | from PyQt5.QtWidgets import *
from controller_lsa_dummy.lsa_model import LsaModel
class LsaWidget(QFrame):
def __init__(self, parent: QWidget = None) -> None:
super().__init__(parent)
self.initUi()
def initUi(self):
self.tableView = QTableView()
self.setLayout(QVBoxLayout()... | like2000/PyQt5OfflineTemplate | controller_lsa_dummy/lsa_widget.py | lsa_widget.py | py | 1,078 | python | en | code | 0 | github-code | 36 |
25527382576 | import numpy as np
from matplotlib import pyplot as plt
from matplotlib import ticker
from PIL import Image
from statistics import mean
from collections import Counter
def threshold(imageArray):
balanceAr = []
newAr = imageArray
from statistics import mean
for eachRow in imageArray:
for eachPix... | MakGulati/OCR | OCR1/thres.py | thres.py | py | 2,809 | python | en | code | 0 | github-code | 36 |
74873112104 | import os
import sys
from .math.fibonacci import Fibonacci
def find_all():
print()
def check_all():
print()
class Abc:
prop: str
my_list = [
1, 2, 3,
4, 5, 6,
]
result = some_function_that_takes_arguments(
'a', 'b', 'c',
'd', 'e', 'f',
)
# Add 4 spaces (an extra level of indentati... | kasir-barati/my-python-journey | second_karma/pep.py | pep.py | py | 489 | python | en | code | 0 | github-code | 36 |
73980074024 | from random import choice, sample
from datetime import timedelta, date
cooking = []
washing = []
print("#+title: Rota")
print("#+options: h:2 num:nil toc:t")
print("\n")
def create_rota(d):
for i in range(0, 7):
avail_cook = ["Noam", "Laura", "Louis", "David", "Nat", "Störm"]
if(i==0):
... | locua/rota-generator | generate_rota.py | generate_rota.py | py | 1,500 | python | en | code | 0 | github-code | 36 |
12491747552 | from pathlib import Path
import pandas as pd
import numpy as np
ROOT_DIRECTORY = Path("/code_execution")
DATA_DIRECTORY = Path("/data")
QRY_VIDEOS_DIRECTORY = DATA_DIRECTORY / "query"
OUTPUT_FILE = ROOT_DIRECTORY / "subset_query_descriptors.npz"
QUERY_SUBSET_FILE = DATA_DIRECTORY / "query_subset.csv"
def generate_qu... | drivendataorg/meta-vsc-descriptor-runtime | submission_src/main.py | main.py | py | 1,151 | python | en | code | 6 | github-code | 36 |
2808406541 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
__version__ = "0.5.4"
__author__ = "Abien Fred Agarap"
from dataset.normalize_data import list_files
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import confusion_matrix
import tenso... | AFAgarap/gru-svm | utils/data.py | data.py | py | 3,939 | python | en | code | 136 | github-code | 36 |
25947079068 | from typing import List
class Solution:
def trap(self, height: List[int]) -> int:
if len(height) <= 2:
return 0
result = 0
left_max = height[0]
right_max = height[-1]
left = 1
right = len(height) - 1
while left <= right:
if height... | dzaytsev91/leetcode-algorithms | hard/42_trapping_rain_water.py | 42_trapping_rain_water.py | py | 699 | python | en | code | 2 | github-code | 36 |
74973219303 | import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import Acti... | Marwan8766/Scrapper | utils/scrappingLink.py | scrappingLink.py | py | 5,713 | python | en | code | 0 | github-code | 36 |
3881200220 | from typing import Tuple
import gym
from imitation.rewards.reward_nets import RewardNet
import numpy as np
import torch
from reward_preprocessing.env import maze, mountain_car # noqa: F401
class MazeRewardNet(RewardNet):
def __init__(self, size: int, maze_name: str = "EmptyMaze", **kwargs):
env = gym.m... | HumanCompatibleAI/reward-preprocessing | src/reward_preprocessing/models.py | models.py | py | 2,415 | python | en | code | 3 | github-code | 36 |
20816840348 | from __future__ import print_function
import copy
import warnings
import graphviz
import matplotlib.pyplot as plt
import numpy as np
from graph import feed_forward_layers, DrawNN
def plot_time(begin, end, filename, generation_time):
""" Plots the population's average and best fitness. """
if plt is None:
... | Dyend/NEAT-CAR-DRIVER | visualize.py | visualize.py | py | 10,018 | python | en | code | 0 | github-code | 36 |
25122731323 | #!/usr/bin/python3
def uppercase(str):
"""
a function that prints a string in uppercase followed by a new line
"""
out_str = ""
for s in str:
if ord(s) >= 97 and ord(s) < 123:
out_str += chr(ord(s) - 32)
else:
out_str += s
print(out_str.format())
| TanjereeN98/alx-higher_level_programming | 0x01-python-if_else_loops_functions/8-uppercase.py | 8-uppercase.py | py | 311 | python | en | code | 0 | github-code | 36 |
34682582382 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 11:49:53 2019
@ author: cacquist
@ date : 16 juli 2019
@ goal : built statistics of PBL observations and ICON LEM model outputs. The
code reads in the data from observations and model from the three different sites,
check if data are not there... | ClauClouds/PBL_paper_repo | PBLpaper_prepare_dataset_model_obs_stat.py | PBLpaper_prepare_dataset_model_obs_stat.py | py | 62,498 | python | en | code | 1 | github-code | 36 |
9194404834 | import os
import hydra
from pathlib import Path
from omegaconf import OmegaConf
import pytorch_lightning as pl
from pytorch_lightning.loggers import CSVLogger
from pytorch_lightning import Trainer
from dataloader import get_dataloader
from model.PlanT.lit_module import LitHFLM
@hydra.main(config_path=f"../config", ... | ge75her/Trajectory-Prediction-for-Utilizing-Geometric-Relationships | carla_agent_files/model/PlanT/lit_train.py | lit_train.py | py | 2,977 | python | en | code | 0 | github-code | 36 |
6642867036 | ##LC 1512. Number of Good Pairs
#Solution
class Solution(object):
def numIdenticalPairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ct = {}
for n in nums:
if n in ct:
ct[n] += 1
else:
ct[n] = 1
... | Caonisandaye/LeetCode | 1512.py | 1512.py | py | 582 | python | en | code | 1 | github-code | 36 |
30848251157 | from sys import argv
from .lox import Lox
def main(args):
print('running main')
if len(args) > 1:
print('Usage: pyLox [file]')
exit(64)
elif len(args) == 1:
Lox.run_file(args[0])
else:
Lox.run_prompt()
if __name__ == "__main__":
print('yes!')
main(argv[1:]) | g-areth/interpreters | py_interpreter/__main__.py | __main__.py | py | 315 | python | en | code | 0 | github-code | 36 |
28891606871 | """Tests for tool_utils.py."""
import sys
from pytype.platform_utils import path_utils
from pytype.tests import test_utils
from pytype.tools import tool_utils
import unittest
class TestSetupLoggingOrDie(unittest.TestCase):
"""Tests for tool_utils.setup_logging_or_die."""
def test_negative_verbosity(self):
... | google/pytype | pytype/tools/tool_utils_test.py | tool_utils_test.py | py | 1,346 | python | en | code | 4,405 | github-code | 36 |
20274778450 | import addonHandler
import api
import appModuleHandler
import bisect
import config
import controlTypes
import ctypes
import eventHandler
import globalPluginHandler
import gui
import json
import NVDAHelper
from NVDAObjects.behaviors import RowWithFakeNavigation, Dialog, Notification
from NVDAObjects.UIA import UIA
from ... | mltony/nvda-em-client | addon/appModules/mailclient.py | mailclient.py | py | 9,710 | python | en | code | 1 | github-code | 36 |
34526532786 | import requests
import pandas
from sqlalchemy import create_engine
import datetime as dt
engine = create_engine(
'mysql+pymysql://leiming:vg4wHTnJlbWK8SY@rm-2zeq92vooj5447mqzso.mysql.rds.aliyuncs.com:3306/cider')
# 判断订单是否为全部发货
url = 'https://erp.banmaerp.com/Order/Order/ListDataHandler'
headers = {
'content-ty... | yourant/ERPdata_Transfer | ERP_order_trans.py | ERP_order_trans.py | py | 8,230 | python | en | code | 0 | github-code | 36 |
34162635034 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger(None)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(
'%(asctime)s %(filename)s:%(lineno)s - %(funcName)20s() %(levelname)-8s %(message)s')
# StreamHandler
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)
... | daimrod/opinion-sentence-annotator | logger_config.py | logger_config.py | py | 485 | python | en | code | 0 | github-code | 36 |
475767730 | import re
from .string import String
from ..autodoc.schema import Array as AutoDocArray
from ..autodoc.schema import Object as AutoDocObject
from ..autodoc.schema import String as AutoDocString
from collections import OrderedDict
class BelongsTo(String):
"""
Controls a belongs to relationship.
This colum... | cmancone/clearskies | src/clearskies/column_types/belongs_to.py | belongs_to.py | py | 10,829 | python | en | code | 5 | github-code | 36 |
2720513480 | # Read text from a file, and count the occurence of words in that text
# Example:
# count_words("The cake is done. It is a big cake!")
# --> {"cake":2, "big":1, "is":2, "the":1, "a":1, "it":1}
# from tkinter import W
def read_file_content(filename):
# [assignment] Add your code here
# using the read()... | Ralatcode/Reading-Text-Files | main.py | main.py | py | 1,310 | python | en | code | 0 | github-code | 36 |
74021404262 | """django_demo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... | Abikwa/django_student_management | django_demo/urls.py | urls.py | py | 1,397 | python | en | code | 0 | github-code | 36 |
34622549711 | from pathlib import Path
from multiprocessing import Pool
from itertools import product
import click
import numpy as np
import pandas as pd
import SimpleITK as sitk
from tqdm import tqdm
from radiomics.featureextractor import RadiomicsFeatureExtractor
center = "mda_test"
project_dir = Path(__file__).resolve().parents... | voreille/hecktor | src/data/quality_control.py | quality_control.py | py | 5,658 | python | en | code | 65 | github-code | 36 |
70862760425 | from django.conf import settings
from simple_salesforce import Salesforce
import re
__author__ = 'eMaM'
E164_RE = re.compile('^\+\d{11}$')
class SalesForceClass():
def __init__(self):
self.sf = Salesforce(
username=settings.USERNAME,
password=settings.PASS,
security_... | eMaM1921990/Scrappers | travelmobApp/SalesForce.py | SalesForce.py | py | 3,066 | python | en | code | 0 | github-code | 36 |
38025192679 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
hall = 23
GPIO.setup(hall,GPIO.IN)
toggle = 1
state = 1
counter = 0
circ = 7 #circumference of tire
# this loop runs forever
while True:
if GPIO.input(hall) == 0:
toggle = 0
else:
toggle = 1
if state == 1 and toggle == 0... | Pvtw124/Bluetooth-Bike-IOT | hall.py | hall.py | py | 569 | python | en | code | 0 | github-code | 36 |
26097388362 | import fixtures
from authomatic.providers import oauth2
conf = fixtures.get_configuration('facebook')
LINK = 'https://www.facebook.com/' + conf.user_username_reverse
PICTURE = 'http://graph.facebook.com/{}/picture?type=large'\
.format(conf.user_username_reverse)
CONFIG = {
'class_': oauth2.Facebook,
'sc... | rnandan273/python | pyramid/authomatic-master/tests/functional_tests/expected_values/facebook.py | facebook.py | py | 1,299 | python | en | code | 0 | github-code | 36 |
36891691239 | # This file contains waf optimisations for Samba
# most of these optimisations are possible because of the restricted build environment
# that Samba has. For example, Samba doesn't attempt to cope with Win32 paths during the
# build, and Samba doesn't need build varients
# overall this makes some build tasks quite a ... | RMerl/asuswrt-merlin | release/src/router/samba-3.6.x/buildtools/wafsamba/samba_optimisation.py | samba_optimisation.py | py | 4,226 | python | en | code | 6,715 | github-code | 36 |
29605976878 | from types import LambdaType
from typing import Any, Dict, Type, Union, Callable, List, overload, TypeVar
from kink.errors.service_error import ServiceError
from kink.typing_support import is_optional, unpack_optional
_MISSING_SERVICE = object()
T = TypeVar("T")
class Container:
def __init__(self):
se... | kodemore/kink | kink/container.py | container.py | py | 3,509 | python | en | code | 266 | github-code | 36 |
74901383783 | import pickle
import socket
from _thread import *
from gameinfo import GameInfo
# server variables
PORT = int(input("What port should the server run on?"))
SERVER = socket.gethostbyname(socket.gethostname())
SERVERNAME = socket.gethostname()
# prints the values of the hosted server
print(f"The port of the server = ... | Teuntitaan1/MultiplayerGame | server.py | server.py | py | 1,679 | python | en | code | 0 | github-code | 36 |
37059824306 | import cv2
import streamlit as st
from streamlit_webrtc import webrtc_streamer
import av
st.title("QRコード読みとり")
FRAME_WINDOW = st.image([])
cap = cv2.VideoCapture(0)
detector = cv2.QRCodeDetector()
class VideoProcessor:
def recv(self, frame):
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
data = detect... | haru48/CameraTest | camera.py | camera.py | py | 712 | python | en | code | 0 | github-code | 36 |
8756340925 | # -*- coding: utf-8 -*-
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models, fields, api
class SaleQuoteLine(models.Model):
_inherit = 'sale.quote.line'
of_storage = fields.Boolean(string='Storage and withdrawal on demand of articles')
@api.onchange('product_id')
... | odof/openfire | of_partner_fuel_stock/models/of_sale_quote_template.py | of_sale_quote_template.py | py | 2,707 | python | en | code | 3 | github-code | 36 |
7777942198 | import os
import requests
import csv
import os
import json
import sys
import ast
import time
f = csv.writer(open('submissions.csv', 'a'))
uf= open('Tables/users.csv', 'r')
user_dict = set()
store_id = 0
authro = ''
worked = 0
zz = 0
for line in uf:
if zz != 0:
user_dict.add(line.split(',')[0])
zz... | H-KY/Codeforces | Dataset/rungetSubmissions.py | rungetSubmissions.py | py | 2,935 | python | en | code | 0 | github-code | 36 |
43438362913 | import numpy as np
import pandas as pd
import pytest
from datetime import datetime, timedelta
from metloom.variables import MesowestVariables, CdecStationVariables
from metloom.dataframe_utils import (
join_df, append_df, merge_df, resample_df, resample_whole_df
)
df1 = pd.DataFrame.from_records([{"foo": 12.0}, {... | M3Works/metloom | tests/test_dataframe_utils.py | test_dataframe_utils.py | py | 6,377 | python | en | code | 10 | github-code | 36 |
42578423711 | # WordNetのlemma.count()を用いて各word,synset,lemmaの頻度を算出してtextファイル化
import os
import sys
#WordNet
import nltk
from nltk.corpus import WordNetCorpusReader
from nltk.corpus import wordnet as wn
import codecs
import util
class ForwardWNGeneralityExtractor:
def __init__(self, folder, lang):
self.folder = folder
... | arairyoto/CrosslingualAutoExtend | Extractor/Frequency/ForwardWNGeneralityExtractor.py | ForwardWNGeneralityExtractor.py | py | 2,642 | python | en | code | 0 | github-code | 36 |
14950735831 | #!/usr/bin/python3.5
from random import randint
def drawCard(l):
r=randint(0,len(cards)-1)
l.append(cards[r])
del cards[r]
def cardsInHand(l):
arbList=[]
for i in range(len(l)):
x=str(l[i])
arbList.append(x)
c = ', '.join(arbList)
return c
def chkHand(l):
toplam=0
... | Tospaa/BlackJack-in-Python-3 | blackjack.py | blackjack.py | py | 2,619 | python | en | code | 1 | github-code | 36 |
41105772447 | """
satpy_overlay_plots.py
module implementing satpy based plots with OCO-2 data overlays.
intended to integrate with oco_vistool.py
"""
import os, glob, datetime, collections, itertools
import tempfile, shutil
import bz2
import numpy as np
from satpy import Scene
from satpy.writers import get_enhanced_image
impo... | hcronk/oco_vistool | satpy_overlay_plots.py | satpy_overlay_plots.py | py | 34,189 | python | en | code | 11 | github-code | 36 |
43301320924 | from rpython.jit.metainterp.history import ConstInt, ConstFloat, ConstPtr
from rpython.jit.metainterp.resoperation import rop, AbstractInputArg
from rpython.rlib.debug import (have_debug_prints, debug_start, debug_stop,
debug_print)
from rpython.rlib.objectmodel import we_are_translated, compute_unique_id
from rpyt... | mozillazg/pypy | rpython/jit/metainterp/logger.py | logger.py | py | 10,735 | python | en | code | 430 | github-code | 36 |
12444957695 | import os
import json
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.keras import layers
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.plot(history.hi... | happiness6533/AI-study-project | supervised_learning/natural_language_process/text_clustering/cnn_rnn.py | cnn_rnn.py | py | 6,131 | python | en | code | 0 | github-code | 36 |
12988569031 | class Buffer:
def __init__(self):
self.list = []
# конструктор без аргументов
def add(self, *args):
for arg in args:
self.list.append(arg)
while len(self.list) >= 5:
sum = 0
for i in range(5):
sum += self.list.pop(0)
... | ejina21/stepik_course | solutions_and_tests/6.py | 6.py | py | 972 | python | ru | code | 0 | github-code | 36 |
23617122121 | '''Created January 2016
ask if you want to check balance, withdraw, deposit
check balance; give balance
withdraw
ask how much
notify of fee
subtract from balance
deposit
ask how much
add to balance
'''
def ATM():
balance_total = 2000
while True:
command = input('Woul... | weberswords/reticent-pangolin | Python/ATM.py | ATM.py | py | 2,180 | python | en | code | 0 | github-code | 36 |
19474473863 | datbase_url = "https://handsin-bot-database.herokuapp.com/"
from pprint import pprint
import requests
import json
from pyinflect import getAllInflections, getInflection
import re
import random
import copy
from nltk.stem import PorterStemmer
from collections import OrderedDict
porter = PorterStemmer()
def isEntityUn... | Rodrigo010497/bot-test-strapi | queries.py | queries.py | py | 5,851 | python | en | code | 0 | github-code | 36 |
73424750504 | import json
import jwt
import socket
import struct
from nose.tools import ok_, eq_, assert_is_not_none
try:
from mock import Mock, patch
except ImportError:
from unittest.mock import Mock, patch
try:
from httplib import OK, FOUND, CREATED
except:
from http.client import OK, FOUND, CREATED
from uuid import uuid4... | belodetek/unzoner-api | src/tests/paypal_tests.py | paypal_tests.py | py | 20,462 | python | en | code | 3 | github-code | 36 |
17365968312 | import threading
import time
import urllib
import kolala
import kolala.framework.Chat as Chat
class ChatThread(threading.Thread):
def run(self):
self.stopping = False
while not kolala.globals.stopping and not self.stopping:
kolala.Client.getpage('newchatmessages.php?j=1')
... | mapledyne/kolala | kolala/actions/chat.py | chat.py | py | 944 | python | en | code | 1 | github-code | 36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.