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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
7457839612 | import random
import numpy as np
import pandas as pd
from keras.layers import Input, Dense
from keras.models import Model
import tensorflow as tf
from shared_module import *
def input_encoding_model(encoded):
X_input = Input(encoded)
# X = Dense(2056, activation='sigmoid', name='fc0.0')(X_input)
X = D... | alechfho/dog_breed | triplet_encoding.py | triplet_encoding.py | py | 9,622 | python | en | code | 0 | github-code | 13 |
12001682700 | # -*- coding: utf-8 -*-
# Write : lgy
# Data : 2017-09-24
# function: Algorithm class NetWork for bp network
from Connections import Connections
from Layer import Layer
from Connection import Connection
class NetWork(object):
def __init__(self, layers):
"""
初始化一个全连接神经网络
:param layers: 二维数组,描述神经网络每层节点数
"""
... | liguoyu1/python | codeNLP/Algorithm/NeuralNetwork/Bp/NetWork.py | NetWork.py | py | 3,137 | python | en | code | 49 | github-code | 13 |
17589022332 | from pandas_datareader import data as wb
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from keras.layers import Dense, LSTM, SimpleRNN, Dropout, Flatten
import keras
from keras.models import Sequ... | aidingh/Project-Data-analytics-and-Finance | Project_Finance_and_Data_Analytics/Finance_Neural_Nets.py | Finance_Neural_Nets.py | py | 6,327 | python | en | code | 0 | github-code | 13 |
5945917046 | from flask import Flask, jsonify, make_response
from db import trade
app = Flask(__name__)
@app.route('/api/trade', methods=['GET'])
def get_trade():
trade_info = trade.read()
return jsonify({'result': trade_info})
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'result': Fal... | smartchris84/bitmexbot | rest/app.py | app.py | py | 384 | python | en | code | 0 | github-code | 13 |
32773464499 | import openpyxl
def writeExcel(file_name, file_name_database):
import_wb = openpyxl.load_workbook(file_name)
import_sheet = import_wb['Sheet1']
wb = openpyxl.load_workbook(file_name_database)
sheet = wb['Первый лист']
for i in range(2, import_sheet.max_row + 1):
im... | AlekseyNizhnikov/Home_Work_Python | Work_7/converter_excel.py | converter_excel.py | py | 1,579 | python | en | code | 0 | github-code | 13 |
72813985617 | from datetime import date
from six import iteritems
from seatsio.util import parse_date
class Chart:
def __init__(self, data):
self.id = data.get("id")
self.key = data.get("key")
self.status = data.get("status")
self.name = data.get("name")
self.published_version_thumbna... | seatsio/seatsio-python | seatsio/domain.py | domain.py | py | 14,699 | python | en | code | 8 | github-code | 13 |
71261645779 | from __future__ import print_function
import argparse
import os
import torch
import torch.nn as nn
from torch.autograd import Variable
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
import numpy as np
import math
from Preprocess_data import is_image_file, load_img, save_img, get_t... | dreamegg/2_Step_Inpainting | tools/make_pair.py | make_pair.py | py | 2,984 | python | en | code | 0 | github-code | 13 |
28396382662 | # cd Desktop\RETI NEURALI E ALG GENETICI\Cazzeggio\1) xor problem
import sys
sys.path.insert(1, '/Users/Sax/Desktop/RETI NEURALI E ALG GENETICI/Cazzeggio/toy_nn')
from nn import *
import random
if __name__ == '__main__':
training_data = [{
"inputs":[0,1], "targets":[1]
},
{... | simsax/Neural-Networks | 1) xor problem/main.py | main.py | py | 1,013 | python | en | code | 0 | github-code | 13 |
13169567638 | # linear sorting
# COUNTING Sort:
arr=[2,4,1,6,3,5,9,8,7]
low,high=int(input("enter the range a to b:").split())
extra=[0]*(high-low+1)
n=len(arr)
for i in arr:
extra[i]+=1
for i in range(1,len(extra)):
extra[i]+=extra[i-1]
| saketha55/Daily_Challenges | D6/Practice/counting srt.py | counting srt.py | py | 237 | python | en | code | 0 | github-code | 13 |
8191052915 | import os
from collections import defaultdict
from typing import Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
import pandas as pd
from d3l.indexing.lsh.lsh_index import LSHIndex
from d3l.indexing.similarity_indexes import NameIndex, SimilarityIndex
from d3l.input_output.dataloaders import DataLoad... | superctj/pylon | tabert_cl/d3l_extension.py | d3l_extension.py | py | 19,157 | python | en | code | 1 | github-code | 13 |
34779039 | import speech_recognition
recognizer = speech_recognition.Recognizer()
print("开始识别!")
has_next = True
while has_next:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio = recognizer.listen(mic)
text = recognize... | NormalLLer/Speech-Topic-Classification-on-ChatGPT | speech2text.py | speech2text.py | py | 619 | python | en | code | 0 | github-code | 13 |
39216713984 | import os
filePath = 'C:/Users/Administrator/Downloads/'
filenames=os.listdir(filePath)
# print(filenames)
for filename in filenames:
if(filename.endswith(".txt")):
file = open(r'C:/Users/Administrator/Downloads/'+filename, 'r',encoding="utf-8")
try:
string=file.read()
finally:
... | cerebrumWeaver/python-example | txt文字替换.py | txt文字替换.py | py | 1,821 | python | en | code | 0 | github-code | 13 |
41697851534 | """
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Author: @Andrew Auyeung andrew.k.auyeung@gmail.com
Location: Metis-Project-3/lib/
Dependencies: cleaning.py
Functions in this module are used to prepare cleaned data for classification.
Features are engineered to determine how they change in the leading rows.
"""
impo... | aauyeung19/rainOne | streamlit/feature_eng.py | feature_eng.py | py | 2,839 | python | en | code | 0 | github-code | 13 |
41904607526 | from fractions import Fraction
from random import choice
from random import seed
def random_bool(probability):
"""
get a random choice with desired probability.
Uses the python random choice function to
pick a bool out of a list.
To avoid to much memory usage because of
a long list, it is best... | alexander-n8hgeg5e/pylib | pylib/random.py | random.py | py | 1,368 | python | en | code | 0 | github-code | 13 |
18191316022 | """
Created by Jan Schiffeler on 18.10.20
jan.schiffeler[at]gmail.com
Changed by
MICROSERVICE for:
Finding gripping angles for a desired position
In:
Name | ID sender number: description, ...
frame | 1001 1: Cube frame
frame | 1001 2: Hand frame
Out:
Name | ID sender number: description, ...
frame | 100... | Platygator/visually-supervised-learning-for-robotic-manipulation | main/execution.py | execution.py | py | 4,674 | python | en | code | 1 | github-code | 13 |
3354822880 | from pathlib import Path
import pytest
from pydantic import Field, BaseModel
from wunderkafka.time import now
from wunderkafka.tests import TestProducer, TestHTTPClient
from wunderkafka.serdes.avro import AvroModelSerializer, ConfluentClouderaHeadersHandler
from wunderkafka.serdes.store import AvroModelRepo
from wund... | severstal-digital/wunderkafka | tests/integration/cloudera/test_serializing_avromodel.py | test_serializing_avromodel.py | py | 2,537 | python | en | code | 3 | github-code | 13 |
36093637435 | # Program to evaluate the sum of all the amicable numbers under 10,000
amicable_numbers = []
# Function getDivisors(num) finds the divisors of any inputted number and runs the getPossiblePair(divisors, checkNum) function on them
def getDivisors(num):
firstNum = num
set_of_divisors = []
for i in range(1,... | SuhaybDev/Project-Euler | 21_amicable_numbers.py | 21_amicable_numbers.py | py | 1,704 | python | en | code | 0 | github-code | 13 |
2954636855 | import urllib.request
import httplib2
import os
import pickle
import hashlib
from googleapiclient.discovery import build
def make_dir(path):
if not os.path.isdir(path):
os.mkdir(path)
def make_correspondence_table(correspondence_table, original_url, hashed_url):
correspondence_table[original_url] =... | dsonoda/ttango-engine | get_images/get_images.py | get_images.py | py | 2,968 | python | en | code | 0 | github-code | 13 |
20778541884 | # Python program to find the H.C.F of two input number
num1=input("enter first number:")
num2=input("second number:")
def calculateHCF(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller + 1):
if ((x % i == 0) and (y % i == 0)):
... | SShital/PythonAssignments | BasicAssignemnt/Ass22.py | Ass22.py | py | 431 | python | en | code | 0 | github-code | 13 |
478580730 | """
This file not meant to be modified to configure a local nor a production instance.
To configure the instance, please consider:
- editing a ".env" file at the root of the "oxe-api" directory
- passing the environment variables via "-e" flag if you use a docker container
"""
import os
from dotenv import load_... | CybersecurityLuxembourg/openxeco-eccc-middleware | oxe-api/config/config.py | config.py | py | 1,846 | python | en | code | 0 | github-code | 13 |
3614020518 | from pwn import *
from Crypto.Util.number import *
import json, codecs
d = {
"base64": b64d,
"hex": unhex,
"rot13": lambda s: codecs.encode(s, 'rot_13').encode(),
"bigint": lambda s: long_to_bytes(int(s, 0)),
"utf-8": bytes
}
def dec(o):
return d[o["type"]](o["encoded"])
i... | ThomasNJordan/CryptoHack | DataFormats/Conversion/better_remote.py | better_remote.py | py | 492 | python | en | code | 2 | github-code | 13 |
35373545869 | import numpy as np
import matplotlib.pylab as plt
from qampy import equalisation, signals, impairments, helpers
fb = 40.e9
os = 2
fs = os*fb
N = 2**18
theta = np.pi/2.35
M = 16
snr = 24
muCMA = 1e-3
muRDE = 0.5e-3
ntaps = 30
t_pmd = 50e-12
sig = signals.ResampledQAM(M, N, nmodes=2, fb=fb, fs=fs, resamplekwargs={"beta... | ChalmersPhotonicsLab/QAMpy | Scripts/mrde_equaliser.py | mrde_equaliser.py | py | 2,019 | python | en | code | 54 | github-code | 13 |
21271933714 | import mlflow
import os
mlflow.set_tracking_uri("http://127.0.0.1:5000")
if __name__ == "__main__":
# Start a new MLflow run
with mlflow.start_run():
mlflow.log_param("threshold", 5)
mlflow.log_metric("timestamp", 0.001)
# Ensure the artifact file exists before logging
file_pa... | jithsg/jupyter-notebook | test-mlflow.py | test-mlflow.py | py | 509 | python | en | code | 0 | github-code | 13 |
27543730676 | import numpy as np
import random
import sys
# calculate clusters for each data points
def nearestCluster(num, meanvalues):
dist = sys.maxsize
currCluster = -1
for i in range(len(meanvalues)):
if abs(num - meanvalues[i]) < dist:
dist = abs(num - meanvalues[i])
currCluster = i... | aditya9110/ScratchML | KMeans Clustering.py | KMeans Clustering.py | py | 1,698 | python | en | code | 1 | github-code | 13 |
10967867093 | """Functions to build a complex SQL Select statement to query variant.
In the most of cases, you will only use build_sql_query function.
Examples
conn = sqlite3.Connection("::memory::")
query = build_sql_query(fields, source, filters)
conn.execute(query)
Fields contains columns to select according sql t... | labsquare/cutevariant | cutevariant/core/querybuilder.py | querybuilder.py | py | 20,120 | python | en | code | 86 | github-code | 13 |
19394967475 | from configparser import ConfigParser
def config_reader(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db_conn_dict = {}
if parser.has_section(section):
p... | navodas/music-genre_classif | config.py | config.py | py | 620 | python | en | code | 0 | github-code | 13 |
14758730764 | DATETIME_FORMAT = '%Y%m%d%H%M%S'
class JOB:
FINISHED_SUCCESSFULLY = 0
FINISHED_WITH_WARNINGS = 1
FINISHED_WITH_ERRORS = 2
class DATETIME:
FORMAT = '%Y%m%d%H%M%S'
FORMAT_2 = '%Y-%m-%d %H:%M:%S'
PP_FORMAT = '%d/%m/%Y %H:%M:%S'
class ServiceDetails:
ROWS = [
['netflix', 'Netfl... | joshnic3/StreamGuide | src/Library/constants.py | constants.py | py | 904 | python | en | code | 0 | github-code | 13 |
35203599820 | import logging
import re
import urlparse
import sst.actions
from functools import wraps
logger = logging.getLogger('User test')
def log_action(log_func):
"""Decorator to log the call of an action method."""
def middle(f):
@wraps(f)
def inner(instance, *args, **kwargs):
class_... | miing/mci_migo_packages_u1-test-utils | u1testutils/sst/__init__.py | __init__.py | py | 5,281 | python | en | code | 0 | github-code | 13 |
31631005442 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import math
from glob import glob
import tGD_aux as aux
import tGD_fun as fun
import tGD_gene as drv
import tGD_plots as plot
from datetime import datetime
import MoNeT_MGDrivE as monet
import compress_pickle as pkl
(USR, DRV, AOI) = (sys.argv[1], sys.argv[2], sys... | Chipdelmal/MoNeT | DataAnalysis/tGDDecay/legacy/tGD_pstTracesOLD.py | tGD_pstTracesOLD.py | py | 4,106 | python | en | code | 7 | github-code | 13 |
42012874834 | import librosa
hop_length = 256
frame_length = 512
import librosa.display as disp
x, sr = librosa.load('audio/simple_loop.wav')
y = x
energy = np.array([sum((x[i:i+frame_length]**2)) for i in range(0,len(y),hop_length)])
energy_n = energy/energy.max()
frames = range(len(energy))
t = librosa.frames_to_time(frames,sr,ho... | wubinbai/2020 | Music/MIR/mir.py | mir.py | py | 2,268 | python | en | code | 0 | github-code | 13 |
36412528672 | # Import every library needed
#%%
import matplotlib
from LakesModeling_Subprogram import *
from geopy.distance import geodesic
from rasterio.plot import show
from matplotlib import gridspec
#%% md
# Init every parameter
#%%
# name of the lake to model
# available names : Amadeus, Austin, Barlee, Blanche, Carey, Carn... | LeoCkr/stage4A | LakesModelling_Notebook.py | LakesModelling_Notebook.py | py | 16,123 | python | en | code | 0 | github-code | 13 |
18415791141 | def even_odd(*args):
result = []
cmd = args[-1]
if cmd == 'even':
result = [i for i in args[:-1] if i % 2 == 0]
elif cmd == 'odd':
result = [i for i in args[:-1] if i % 2 != 0]
return result
print(even_odd(1, 2, 3, 4, 5, 6, "even"))
print(even_odd(1, 2, 3, 4, 5, 6, 7... | MiroVatov/Python-SoftUni | Python Advanced 2021/FUNCTIONS-ADVANCED/Exercise 08.py | Exercise 08.py | py | 341 | python | en | code | 0 | github-code | 13 |
15519037843 | import random
import sys
import os
pi_tuple = (3,1,4,1,5,9)
#Typecasting the tuple into a new list
new_list = list(pi_tuple)
#Typecasting a list into a tuple
new_tuple = tuple(new_list)
print(new_tuple)
print(new_list)
#legal, as we can append to list
new_list.append(19)
#Illegal operation: tuples are immutable
#... | Priyankasingtamkar/public | python/tuples.py | tuples.py | py | 364 | python | en | code | null | github-code | 13 |
72680646418 | import sublime, sublime_plugin
import os
from os.path import dirname
import sys
from subprocess import Popen, PIPE
import subprocess
import shlex
from sublime import Region, Phantom, PhantomSet
from os import path
from importlib import import_module
from time import time
import threading
from .Modules.ProcessManager i... | Jatana/FastOlympicCoding | test_edit.py | test_edit.py | py | 9,634 | python | en | code | 365 | github-code | 13 |
43230317536 | #!/usr/bin/env python
from os import path
import sys
# Directory containing this program.
PROGDIR = path.dirname(path.realpath(__file__))
# For click_common and common.
sys.path.insert(0, path.join(PROGDIR, ".."))
# For python_config.
sys.path.insert(0, path.join(PROGDIR, "..", "..", "etc"))
import click_common
impor... | mukerjee/etalon | experiments/buffers/optsys.py | optsys.py | py | 3,455 | python | en | code | 12 | github-code | 13 |
42987267960 | import os
# Helper functions
def getFiles(path, extension):
"""
Walks down all directories starting at *path* looking for files
ending with *extension*. Knows that UFOs are directories and stops
the walk for any found UFO.
"""
if not extension.startswith('.'):
extension = '.' + extens... | arrowtype/recursive | mastering/utils.py | utils.py | py | 15,682 | python | en | code | 2,922 | github-code | 13 |
71899352338 | from __future__ import unicode_literals
from __future__ import absolute_import
from collections import namedtuple
import logging
import re
from operator import attrgetter
import sys
import six
from docker.errors import APIError
from docker.utils import create_host_config
from .config import DOCKER_CONFIG_KEYS
from .c... | ianblenke/awsebcli | ebcli/bundled/_compose/service.py | service.py | py | 22,719 | python | en | code | 3 | github-code | 13 |
29294734871 | class Tournament:
def __init__(self, name, place, date, rounds, time, description):
self.name = name
self.place = place
self.date = date
self.rounds = rounds
self.round = []
self.player = []
self.time = time
self.description = description
#si ... | lbrrs/P4 | model/tournament.py | tournament.py | py | 372 | python | en | code | 0 | github-code | 13 |
33259270427 | """This spout connects to rabbitmq and gets messages off a queue.
It will map tuples to queues, and when told to ack a tuple, it will ack the
relevant message as well.
"""
import Queue
from streamparse import spout
import kombu
import genuid, settings
class GetDocumentsSpout(spout.Spout):
def initialize(self, ... | sujaymansingh/sparse_average | src/getdocuments.py | getdocuments.py | py | 1,962 | python | en | code | 1 | github-code | 13 |
10884921048 | import random
import time
import ujson
from machine import UART, Pin, SPI
from ili9341 import Display, color565
from xglcd_font import XglcdFont
BL = 13
DC = 8
RST = 12
MOSI = 11
SCK = 10
CS = 9
# font = None
display: Display = None
first_message = False
font_dict = {
'big': XglcdFont('fonts/Agency_FB21x40.c', 2... | mostaron/pc_monitor_board_pico | main.py | main.py | py | 4,304 | python | en | code | 0 | github-code | 13 |
29218352511 | # This example is provided for informational purposes only and has not been audited for security.
from pathlib import Path
from feature_gates import FeatureGates
FeatureGates.set_sourcemap_enabled(True)
from pyteal import * # noqa: E402
""" Template for layer 1 dutch auction (from Fabrice and Shai)
"""
tmpl_sta... | algorand/pyteal | examples/signature/dutch_auction.py | dutch_auction.py | py | 6,017 | python | en | code | 269 | github-code | 13 |
1456312341 | import RPi.GPIO as GPIO
import time
servo_pin = 18
rain_pin = 26
in1 = 24
in2 = 23
in3 = 5
in4 = 6
en1 = 25
en2 = 13
temp1=1
GPIO.setmode(GPIO.BCM)
GPIO.setup(rain_pin, GPIO.IN)
#server motor
GPIO.setup(servo_pin, GPIO.OUT)
pwm = GPIO.PWM(servo_pin, 50) # 50Hz
#mortor
GPIO.setmode(GPIO.BCM)
GPIO.setup(in1,GPIO.O... | ParkJunHyung17/team_A | CleenRobot.py | CleenRobot.py | py | 1,344 | python | en | code | 0 | github-code | 13 |
13812343138 | from utils.constants import (
HOG_HIST_NORMALIZATION_SIZE,
HOG_BLOCK_SIZE,
HOG_HISTOGRAM_BINS,
HOG_HISTOGRAM_RANGE,
HOG_KERNEL,
)
from utils.utils import magnitude, orientation, split_blocks, weighted_histogram
import numpy as np
def hog(img):
# calculate the magnitudes
magnitudes = magnit... | alexisbeaulieu97/PedestrianDetector | PedestrianDetector/utils/hog.py | hog.py | py | 1,558 | python | en | code | 0 | github-code | 13 |
27214175888 | from copy import deepcopy
from presidio_analyzer import AnalyzerEngine
# Set up the engine, loads the NLP module (spaCy model by default) and other PII recognizers
analyzer = AnalyzerEngine()
text = """
John, please get that article on www.linkedin.com to me by 5:00PM
on Jan 9th 2012. 4:00 would be ideal, actually. ... | mirfan899/PII_API | pa.py | pa.py | py | 1,145 | python | en | code | 0 | github-code | 13 |
11559333720 | from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
#@app.route("/")
#def hello():
# return "Hello, World!"
@app.route("/sms", methods=['POST'])
def sms_reply():
incoming_msg = request.form.get('Body').lower()
... | jerriebright/WaBot-For-Business | order.py | order.py | py | 1,475 | python | en | code | 0 | github-code | 13 |
377474470 | from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.core.validators import RegexValidator
from django.db import models
from django.contrib.auth import get_user_model
class UserManager(BaseUserManager):
"""
Manager to ... | mathuranish/Social-media-api | user/models.py | models.py | py | 3,348 | python | en | code | 1 | github-code | 13 |
21632339915 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
infile_1=open("../results/individual_energies_1.000000.txt").readlines()
infile_24=open("../results/individual_energies_2.400000.txt").readlines()
energies=[]
temp_1_dist=[]
temp_24_dist=[]
for line in infile_1[2:]:
energy,dist=line.split(",")
... | adrian2208/FYS3150_collab | Project4/python/plot_distribution.py | plot_distribution.py | py | 1,964 | python | en | code | 0 | github-code | 13 |
35521334467 | #coding=utf-8
from __future__ import division
import numpy as np
from scipy.spatial.distance import euclidean
from scipy.spatial.distance import euclidean
def costFunction(x_1,x_2,y,m1,m2,delta):
cost = 0
for i in range(len(x_1)):
d= delta[0]*euclidean(x_1[i],m1) - delta[1]*euclidean(x_2[i],m2)
... | lizaigaoge550/reduct_Dimension | updata_parameter.py | updata_parameter.py | py | 2,156 | python | en | code | 0 | github-code | 13 |
23034381452 | from typing import Any, Dict, List
from library.depends import tree
def order_levels(trees: List[Dict[str, Any]]) -> List[List[str]]:
"""
Given a collection of dependency trees,
walk down them and collect services at the same level
The collection returned are groups of services
that may be broug... | gastrodon/terraform-compose | library/depends/order.py | order.py | py | 914 | python | en | code | 3 | github-code | 13 |
74905213137 | print('Advent of Code 2017 - Day 11')
with open('day11.txt') as f:
path = f.read().split(',')
def no_of_steps(x, y):
y_prime = abs(y * 2)
x_prime = abs(x)
if x_prime >= y_prime:
return int(x_prime)
else:
return int(x_prime + ((y_prime - x_prime) / 2))
x = y = 0
furthest_step = 0
... | kdmontero/aoc | 2017/day11.py | day11.py | py | 780 | python | en | code | 0 | github-code | 13 |
39506577535 | #!/usr/bin/env python3
from multiprocessing import Pool
import os
import time, random
def my_fork():
print('process (%s) start...' % (os.getpid()))
pid = os.fork()
if pid == 0:
print('I am child process (%s) and my parent is (%s)' % (os.getpid(), os.getppid()))
else:
print('I (%s) just ... | zzucainiao/code-backup | learn_python/my_mulprocess.py | my_mulprocess.py | py | 907 | python | en | code | 0 | github-code | 13 |
31557466220 | import pygame.font
from pygame.sprite import Group
"""Pygame's Group class provides useful methods for adding, removing, and checking if a sprite exists in the group. In this code, the prep_ships() method creates a new Group object to store instances of the Ship class, representing the remaining ships in the game."""
... | wahabali790/Alien-Invasion | scoreboard.py | scoreboard.py | py | 4,482 | python | en | code | 0 | github-code | 13 |
41357125273 | """ Get ssh connexions for Buildbot master libvirt
watchdog script"""
import yaml
with open('../os_info.yaml', 'r') as f:
os_info = yaml.safe_load(f)
SSH_CONNECTIONS = 0
for os in os_info:
for arch in os_info[os]['arch']:
addInstall = True
if 'has_install' in os_info[os]:
addInstal... | MariaDB/buildbot | master-libvirt/get_ssh_cnx_num.py | get_ssh_cnx_num.py | py | 464 | python | en | code | 2 | github-code | 13 |
20408398074 | from time import time as get_current_time
from os import path, makedirs
from threading import Thread
from requests import Session
def convert_bytes(size: int) -> str:
"""
Convert bytes to human-readable format
:param size: bytes
"""
for s in ["bytes", "KB", "MB", "GB", "TB"]:
if size < 10... | DerSchinken/FontServer | src/FastDownload.py | FastDownload.py | py | 4,234 | python | en | code | 1 | github-code | 13 |
26710228794 | def long(n):
max=len(n[0])
for i in n:
if(len(i)>max):
max=len(i)
print('the length',max)
n=[]
m=int(input("enter the number of words: "))
for j in range(0,m):
i=input()
n.append(i)
long(n) | Ashwathy-rk/python | exp 30.py | exp 30.py | py | 240 | python | en | code | 0 | github-code | 13 |
27364477052 | import inspect
import torch
from torch import nn
import torch.distributed as dist
from ..schedule import create_schedule
from ..initialization import init_empty_weights
from ..pattern import call_module
from ..logger import get_logger
from .registry import register_schedule
@register_schedule()
def _apply_schedule(... | awslabs/slapo | slapo/model_schedule/t5.py | t5.py | py | 17,649 | python | en | code | 120 | github-code | 13 |
18995104263 | import pyfiglet as pf
from termcolor import colored
text1 = 'Ordinautz'
text2 = 'prepare to enter !orbit'
def ordinautz():
print(colored(pf.figlet_format(text1, font='slant'), 'yellow'))
print(pf.figlet_format(text2, font='slant'))
ordinautz() | kluless13/ordiquiz | ordinautz.py | ordinautz.py | py | 259 | python | en | code | 0 | github-code | 13 |
22737763029 | from django.shortcuts import render
from django.http import HttpResponse
from django.http import *
from . models import blooddata
from django.db.models import Q
from django.contrib import messages
from django.contrib import auth
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models impor... | ookapil/Blood-share | bloodshare/views.py | views.py | py | 1,644 | python | en | code | 0 | github-code | 13 |
4970415353 | MAX = 1001
parent = []
def makeSet():
global parent
parent = [i for i in range(MAX + 1)]
def findSet(u):
while u != parent[u]:
u = parent[u]
return u
def unionSet(u, v):
up = findSet(u)
vp = findSet(v)
parent[up] = vp
T = int(input())
t = input()
while T:
... | truclycs/code_for_fun | algorithms/python/python_blue/L18/_459_Graph_Connectivity.py | _459_Graph_Connectivity.py | py | 725 | python | en | code | 7 | github-code | 13 |
44890878848 | # advancedCalculator.py
# Author: Tinli Yarrington
# Date created: 3/21/15
# Dates edited: 3/23/15
# Purpose: to create a program that when user inputs certain function, program will calculate answer
# Notes:
# - add more shapes to calculate areas and volumes (maybe even be able to solve using integrals)
# ... | tyarrington/Calculator | advancedCalculator.py | advancedCalculator.py | py | 7,271 | python | en | code | 0 | github-code | 13 |
40206219640 | #!/usr/bin/env python
import rrdtool
'''
Given configuration
α : 0.1
β : 0.0035
γ : 0.1
period : 10
'''
ret = rrdtool.create("netP.rrd",
"--start",'N',
"--step",'300',
"DS:inoctets:COUNTER:600:U:U",
"DS:outoctets:COUNTER:600:U:U",... | PitCoder/NetworkMonitor | Service_Monitoring/Prediction/rrdPredict.py | rrdPredict.py | py | 1,349 | python | en | code | 2 | github-code | 13 |
33246231999 | #board =list(input())
board = [["X", ".", ".", "X"], [".", ".", ".", "X"], [".", ".", ".", "X"]]
def check(board):
if len(board) == 0:
return 0
result = 0
for i in range(len(board)):
for j in range(len(board[0])):
if (board[i][j] == '.'):
continue
if... | Narek-Papyan/ml | Practical_5/battleships-in-a-board.py | battleships-in-a-board.py | py | 527 | python | en | code | 0 | github-code | 13 |
12666421865 | class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
def Inbetween(self,middle_node,newdata):
if middle_node is None:
print("The mentioned node is absent")
return
... | lalithakre/Python- | insertionAtMiddleSingleLinkedList.py | insertionAtMiddleSingleLinkedList.py | py | 787 | python | en | code | 0 | github-code | 13 |
73257835218 | from django.urls import path
from . import views
app_name = 'menus'
urlpatterns = [
path('', views.ItemListView.as_view(), name='items'),
path('<int:pk>/', views.ItemUpdateView.as_view(), name='item_detail'),
path('create/', views.ItemCreateView.as_view(), name='create'),
] | flpn/muypicky | menus/urls.py | urls.py | py | 289 | python | en | code | 0 | github-code | 13 |
6795989238 | from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import AllowAny
from rest_framework.response import... | cesarparrado20/api-pairgame | src/users/views.py | views.py | py | 2,315 | python | en | code | 0 | github-code | 13 |
30568713682 | from typing import Optional
from fastapi import APIRouter, Depends
from fastapi.encoders import jsonable_encoder
from fastapi_pagination import Params
from fastapi_pagination.ext.sqlalchemy import paginate
from sqlalchemy.orm import Session
from app.models.movies import MovieBase
from db.database import get_db
from d... | SamMeown/billing_service | app/api/v1/server/movies.py | movies.py | py | 2,024 | python | en | code | 0 | github-code | 13 |
17113938846 | from django.urls import include, path
from . import views
app_name = 'parking'
urlpatterns = [
path('add/<zone>/<place_number>/<car_number>/', views.place_add, name='place-add'),
path('book/<slug:zone>/<int:place_number>/', views.add_booking, name='add-booking'),
path('zonemap/<int:zone_pk>/', views.get_z... | staplercut/parking | parking/urls.py | urls.py | py | 542 | python | en | code | 0 | github-code | 13 |
23602805352 | import numpy as np
import torch
from torch import nn
from utils.attentionTransfer_util.util import AverageMeter
from prefetch_generator import BackgroundGenerator
from utils.attentionTransfer_util.util import get_learning_rate, accuracy, record_epoch_learn_alpha, get_fc_name
from utils.attentionTransfer_util.regularize... | CN1Ember/feathernet_mine | data_clean/utils/attentionTransfer_util/framework.py | framework.py | py | 10,361 | python | en | code | 1 | github-code | 13 |
26621283749 |
# 이분탐색
import sys
input = sys.stdin.readline
n = int(input())
# 마을 번호만 담기
arr = []
# 마을정보
dic ={}
# 전체인구수
number_of_people = 0
for i in range(n):
# 마을별 사람 수 만큼, 채워 넣기
a,b = map(int, input().split())
# 딕셔너리로 처리
dic[a] = b
# 마을 번호 담기
arr.append(a)
# 전체 인구수 더하기
number_of_people += ... | isakchoe/TIL | algorithm /back_j/2141_우체국.py | 2141_우체국.py | py | 1,622 | python | ko | code | 0 | github-code | 13 |
72146493459 | import argparse
import numpy as np
from numpy import linalg as LA
from scipy.stats import norm
def calculate_cpma(sim_zscores, num_genes):
sim_pvalues = norm.cdf(sim_zscores)
likelihood = np.mean(np.negative(np.log(sim_pvalues)))
value = -2 * ((((likelihood - 1) * num_genes)/likelihood) - num_genes*np.log... | cynthiaewu/trans-eQTL | CPMA/misc/simulate_cpma.py | simulate_cpma.py | py | 2,514 | python | en | code | 3 | github-code | 13 |
43140399096 | import os
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from collections import defaultdict
from scipy.spatial.distance import cdist
def read_data():
data = pd.read_csv("./spotify-dataset/data.csv")
data['artists'] = data['artist... | mi-wit/tunecamp | backend/recomendation.py | recomendation.py | py | 3,729 | python | en | code | 0 | github-code | 13 |
38023136578 | #==============================================================
#
# Job options file for Geant4 Simulations
#
# CTB_G4Sim: CTB (2004) simulation production
#
__version__="$Revision: 1.12"
#==============================================================
#--- Detector flags -------------------------------------------
fro... | rushioda/PIXELVALID_athena | athena/Simulation/G4Sim/CTB_G4Sim/share/jobOptions.G4Ctb_SimExamples.py | jobOptions.G4Ctb_SimExamples.py | py | 4,841 | python | en | code | 1 | github-code | 13 |
1044556812 | import numpy as np
import cv2
import os
import tqdm
import argparse
from skimage.draw import polygon
import random
def random_flip_horizontal(img, box, p=0.5):
'''
对img和mask随机进行水平翻转。box为二维np.array。
https://blog.csdn.net/weixin_41735859/article/details/106468551
img[:,:,::-1] gbr-->bgr、img[:,::-1,:] 水平... | songjiahao-wq/untitled | youhua/数据增多/copy2.py | copy2.py | py | 10,164 | python | en | code | 1 | github-code | 13 |
12193904635 | #!/user/bin/env python3
#加载bcc的库
from bcc import BPF
#加载我们写的C源代码,之后被编译成BPF字节码
byte = BPF(src_file="HookOutput.c")
#将BPF程序挂载到内核探针kprobe,其中ip_local_out是iptablesOutput的系统调用
byte.attach_kprobe(event="ip_local_out",fn_name="hookOutput")
#读取内核调试文件 /sys/kernel/debug/tracing/trace_pipe
byte.trace_print()
| 564194070/ebpfDaliyDemo | 01-HookIptablesOutPut/LLVMGenerate.py | LLVMGenerate.py | py | 400 | python | zh | code | 0 | github-code | 13 |
32855375079 | import setuptools
#import pyGM
with open("readme.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name='pyGMs',
#name=pyGM.__title__,
#version=pyGM.__version__,
version='0.1.1',
author='Alexander Ihler',
author_email='ihler@ics.uci.edu',
description='... | ihler/pyGMs | setup.py | setup.py | py | 685 | python | en | code | 12 | github-code | 13 |
9535990857 | from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib import error
from urllib.request import Request
import random
import re
import sqlite3
import time
import numpy as np
headers = [{'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}, \
... | simonzhao88/personal-works | tongcheng/gethouseinfo.py | gethouseinfo.py | py | 2,414 | python | en | code | 1 | github-code | 13 |
18093456509 | from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.template.loader import render_to_string
import re
class BasicSpeedDial:
def __init__(self):
self.options = []
def add_option(
self,
name,
url,... | jts-bio/techn-i-cal | sch/components.py | components.py | py | 1,167 | python | en | code | 0 | github-code | 13 |
4060751398 | import numpy as np
from problems import zero_periodic
def F2(u, dt, dx, uold):
n = int(len(u) ** 0.5)
usqr = u ** 2
uoldsqr = uold ** 2
return u - uold + dt / (4 * dx) * (2 * usqr - np.roll(usqr, -n) - np.roll(usqr, -1)
+ 2 * uoldsqr - np.roll(uoldsqr, -n) - np.ro... | VilmerD/IterativeMethods | project/problems_2D.py | problems_2D.py | py | 526 | python | en | code | 0 | github-code | 13 |
36492556362 | # state values
modeOff = 0
modeHeat = 1
modeCool = 2
modeFan = 3
modeAuto = 4
inhibitDelay = 60
inhibitState = 1
inhibitWatchInterval = 1
defaultTemp = 72
from homealone import *
from homealone.resources.tempControl import *
# thermostat control for heating and cooling
class ThermostatControl(Control):
def __ini... | jbuehl/homealone | homealone/resources/thermostatControl.py | thermostatControl.py | py | 8,826 | python | en | code | 0 | github-code | 13 |
33679975749 | import aiopg.sa
from sqlalchemy import (
MetaData, Table, Column,
Integer, String
)
meta = MetaData()
users = Table(
'users', meta,
Column('id', Integer),
Column('creator', Integer),
Column('login', String(50))
)
units = Table(
'units', meta,
Column('id', Integer),
Column('creat... | MaksymMasalov/Aiohttp-task | app/db.py | db.py | py | 1,319 | python | en | code | 0 | github-code | 13 |
14957056494 | from BeautifulSoup import BeautifulSoup
import urllib2
import re
from urlparse import urlparse
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
firstLink = '... | ryankavanaugh/WebScraping-DataMining | WikipediaSearch.py | WikipediaSearch.py | py | 1,343 | python | en | code | 0 | github-code | 13 |
73292676816 | import collections
import logging
import yaml
from heat2arm.parser.common.resource import Resource
from heat2arm.parser.template import Template
from heat2arm.parser.testing.testutils import recursive_dict_search
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger("test_template")
# TemplateParsingTest... | cloudbase/heat2arm | heat2arm/parser/testing/template_testing.py | template_testing.py | py | 4,081 | python | en | code | 7 | github-code | 13 |
36262440312 | from chimerax.core.state import State
class DataFormat(State):
"""Keep tract of information about various data sources
..attribute:: name
Official name for format.
..attribute:: category
Type of data (STRUCTURE, SEQUENCE, etc.)
..attribute:: suffixes
Sequence of filename ex... | HamineOliveira/ChimeraX | src/bundles/data_formats/src/format.py | format.py | py | 2,404 | python | en | code | null | github-code | 13 |
4853943630 | import random
def create_show(fireworks, show_time):
fireworks.sort() #O(NlogN)
show = [] #O(1)
remaining_time = show_time #O(1)
while remaining_time > 0 and fireworks: #O(N)
# Select a random firework
firework = random.choice(fireworks)
if firework <= remaining_time: #O... | simachami/Week4-Day1 | fireworks_problem.py | fireworks_problem.py | py | 661 | python | en | code | 0 | github-code | 13 |
45754761676 | from selene import be, have
from selene.support.shared import browser
from summerpatio_web_autotests.data.contacts import Contact
from summerpatio_web_autotests.data.links import Link
from summerpatio_web_autotests.data.textings import Texting
from summerpatio_web_autotests.model.components.burger import Burger
from su... | aleksandrzavialov/summer_patio_web_autotests | summerpatio_web_autotests/model/pages/main_page.py | main_page.py | py | 2,327 | python | en | code | 0 | github-code | 13 |
16768537552 | """
@author: krakowiakpawel9@gmail.com
@site: e-smartdata.org
"""
import cv2
import numpy as np
original_img = cv2.imread(filename=r'C:\Users\User\PycharmProjects\computer-vision-course\01_basics\images\nerka 1.bmp')
img = original_img.copy()
# cv2.imshow(winname='logo', mat=img)
# cv2.waitKey(0)
# #informacja o pli... | sgol62/computer-vision-course | 01_basics/02_drawing.py | 02_drawing.py | py | 2,778 | python | en | code | 0 | github-code | 13 |
10353143017 | from random import randint
mylist = []
tally = 0
for i in range (0,1000):
diceroll = randint(1,6)
mylist.append(diceroll)
for i in range (0, len(mylist)):
tally += mylist[i]
average = tally/1000
print (average)
| JamesAUre/First-year-of-python | PythonSem1/BasicsDone/week3task5.py | week3task5.py | py | 228 | python | en | code | 0 | github-code | 13 |
38003827758 | # ------------------------------------------------------------
# RunJpsiExample.py
# J. Catmore (James.Catmore@cern.ch)
# Adapted by Cameron Cuthbert (17/07/2011)
# ------------------------------------------------------------
#-------------------------------------------------------------
# User analysis steerin... | rushioda/PIXELVALID_athena | athena/PhysicsAnalysis/JpsiUpsilonTools/share/RunJpsiEEExample.py | RunJpsiEEExample.py | py | 4,816 | python | en | code | 1 | github-code | 13 |
24884019883 | """
@author: Ludovic
"""
import os
import time
import sys
currentDir = os.getcwd()
Name = input("Creation's name : ")
try:
ImportedBot = open(os.path.expandvars(r'%LOCALAPPDATA%\RoboBuild\Saved\bots\.bot.' + Name + '/' + Name + '.schematic.json'),"r")
except:
print(Name + ".schematic.json not fou... | ludovicb1239/MainAssemblyTools | Creation_Hacker/Hacker.py | Hacker.py | py | 1,974 | python | en | code | 1 | github-code | 13 |
31010013370 | from tratamentoDeDados import *
from prettytable import PrettyTable
somaFinal = 0
cadastro = 0
tamanhoDoEstoque = 3
iD = 1
mercadorias = {1: "0"}
while (cadastro == 0):
control=[True]*4
loop = True
nomeDaMercadoria = input("Digite o nome da mercadoria: \n")
control[0],... | SamuelConcercio/AtividadeMercadorias | main.py | main.py | py | 2,377 | python | pt | code | 0 | github-code | 13 |
41874291409 | import json
from requests.models import Response
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
from pprint import pprint
from objdict import ObjDict
from collections import Counter
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id="7c5e565854fe420ba58b7ec434a105e1",
... | maximiliansteiger/spotify_playlist_analyzer_py | testing.py | testing.py | py | 2,061 | python | en | code | 0 | github-code | 13 |
32608814871 | import threading
import time
sem = threading.Semaphore(2)
threads = []
# sem.acquire()
# sem.release()
def fun1():
while True:
sem.acquire()
print("1 bohrain")
time.sleep(5)
sem.release()
print("1 release")
def fun2():
while True:
sem.acquire()
print("... | Amin-mashari/Task-Scheduling | semaphore/semTest.py | semTest.py | py | 691 | python | en | code | 0 | github-code | 13 |
32554947729 | """
-------------------------------------------------------
Lab 11, Task 12
Description:
Returns whether word is on the diagonal of a square matrix
of characters.
-------------------------------------------------------
Author: Mohammad El-Hassan
ID: 169067950
Email: elha7950@mylaurier.ca
__updated__ =... | mohammadelhsn/CP104 | elha7950_l11/src/t12.py | t12.py | py | 622 | python | en | code | 0 | github-code | 13 |
29354444992 | import argparse
import json
import os
from dotenv import load_dotenv
from google.cloud import dialogflow
def create_intent(project_id, display_name, training_phrases_parts, message_texts):
intents_client = dialogflow.IntentsClient()
parent = dialogflow.AgentsClient.agent_path(project_id)
training_phrase... | milov52/speach_bot | load_data.py | load_data.py | py | 1,626 | python | en | code | 1 | github-code | 13 |
74527387536 | import requests
import logging
import time
import pandas as pd
BASE_STREAM_API_URL = "http://localhost:8888/youtube_stream_api"
BASE_DEVICE_SCANNER_API_URL = "http://localhost:8887/device_scan_api"
WHITELISTED_DEVICES_CSV_PATH = "whitelisted_devices.csv"
WAIT_TIME_BETWEEN_SCANS_IN_MINUTES = 5
logger = logging.getLo... | gaborvecsei/YouTube-Live-Stream-Docker | master_app_image/code/start_app.py | start_app.py | py | 5,261 | python | en | code | 56 | github-code | 13 |
38945249942 | """
******************************************************************************************************
Project Introduction to Signal and Image Processing - Group Project: Where is Waldo?
Filename ColorMatching.py
Institution: University of Bern
Python Python 3.6
... | YvesJegge/IntroductionToSignalAndImageProcessingGroupProject | ColorMatching.py | ColorMatching.py | py | 8,235 | python | en | code | 0 | github-code | 13 |
44432134216 | #!/usr/bin/env python
# encoding: utf-8
from django.conf import settings
from django.contrib.sites.models import Site
def domain(request):
""" Add DOMAIN to context """
current_site = Site.objects.get_current()
domain = getattr(settings, 'DOMAIN', 'http://%s' % current_site.domain)
return {
... | krak3n/Facio-Default-Template | __PROJECT_NAME__/context_processors.py | context_processors.py | py | 375 | python | en | code | 2 | github-code | 13 |
20953547898 | import warnings
from typing import List, Optional, Tuple
import numpy as np
import torch
from skimage.feature import peak_local_max
def BCE_loss(input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
"""Simple BCE loss. Used to compute the BCE of the ground truth heatmaps as the BCELoss in Pytorch complains... | tlpss/keypoint-detection | keypoint_detection/utils/heatmap.py | heatmap.py | py | 9,967 | python | en | code | 30 | github-code | 13 |
4261223652 | #negative samples based on monolingual corpora
import numpy as np
import argparse
from sklearn.metrics.pairwise import cosine_similarity
parser = argparse.ArgumentParser()
parser.add_argument("--src-embedding", required=False, default="wmt20-sent.en-ps.ps.emb", help="file with the source side embeddings")
parser.add_... | Azax4/jhu-parallel-corpus-filtering | neg-samples/neg-pair-mono.py | neg-pair-mono.py | py | 2,096 | python | en | code | 0 | github-code | 13 |
41643419279 |
import pandas as pd
import numpy as np
from sklearn.externals import joblib
#import joblib
from fetchData import main
import os
FEATURES = ["Pregnancies", "Glucose", "BloodPressure", "SkinThickness",
"Insulin", "BMI", "DiabetesPedigreeFunction", "Age"]
data = main("?id", "=", ":1")
data = data[0]
columns ... | cnikoro/dms_with_semantic_technology | DiabetesDiagnosisProject/diagnose.py | diagnose.py | py | 586 | python | en | code | 0 | github-code | 13 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.