seq_id
stringlengths
7
11
text
stringlengths
156
1.7M
repo_name
stringlengths
7
125
sub_path
stringlengths
4
132
file_name
stringlengths
4
77
file_ext
stringclasses
6 values
file_size_in_byte
int64
156
1.7M
program_lang
stringclasses
1 value
lang
stringclasses
38 values
doc_type
stringclasses
1 value
stars
int64
0
24.2k
dataset
stringclasses
1 value
pt
stringclasses
1 value
27063319487
from NETWORKS import * numAgentes = 100 interaction = 'Ising' topologia = 'Circular' iteracoes = numAgentes*10 gamma = np.linspace(0.0001,10,100) valoresFinais = np.zeros((np.size(gamma),1)) for i in range(0,np.size(gamma)): current = np.zeros((iteracoes, 1)) Grid = Network(numAgentes, interaction, topologia, ...
mconde94/Codigos-Tese
Behavioral Macroeconomic models/AntBasedModel.py
AntBasedModel.py
py
640
python
en
code
1
github-code
6
39824039269
import random import numpy as np from scipy.stats import entropy class CNF: def __init__(self, path=None, clauses=None): if path: with open(path, 'r') as cnf: formula = cnf.read() formula = formula.split('\n') start_index = 0 whil...
mosin26/master_thesis
cnf.py
cnf.py
py
5,685
python
en
code
0
github-code
6
43079348194
from typing import List class Solution: def factorial(self, n: int) -> int: fact = 1 for i in range(1, n+1): fact *= i return fact def combination(self, n: int, r: int) -> int: return self.factorial(n) // (self.factorial(n-r) * self.factorial(r)) def generate...
devKhush/DSALeetCodeProblems_Python
Pascal's Triangle/GeneratePascalTriangle.py
GeneratePascalTriangle.py
py
659
python
en
code
0
github-code
6
6193371438
#! /usr/bin/env python """ A very simple program to print the triplet primes less than n. Leon Hostetler, Jan. 26, 2017 USAGE: python primes_triplets.py """ from __future__ import division, print_function n = 1000 # Checks to see if a number is prime def is_prime(n): for i in range(2, n): ...
leonhostetler/sample-programs
python/prime_numbers/primes_triplets.py
primes_triplets.py
py
944
python
en
code
0
github-code
6
37198526566
# _*_ coding: utf-8 _*_ # @author: anniequ # @file: datapre.py # @time: 2020/11/12 11:07 # @Software: PyCharm import os from PIL import Image import matplotlib.pyplot as plt import numpy as np import torch import torchvision.transforms as tfs from torch.utils.data import DataLoader from torch import nn import torch.n...
Anniequ/FCNcopy
all.py
all.py
py
16,271
python
en
code
0
github-code
6
32108115946
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("orgs", "0014_auto_20150722_1419")] operations = [ migrations.CreateModel( name="Con...
rapidpro/ureport
ureport/contacts/migrations/0001_initial.py
0001_initial.py
py
990
python
en
code
23
github-code
6
29057620857
#!/usr/bin/python3 """ base module contains the Base class """ import json class Base: """ Base class: manage id attribute in all the subclass Attributes: __nb_objects - class attribute initialized with 0 __init__ - class constructor """ __nb_objects = 0 def __init__(self, i...
ZIHCO/alx-higher_level_programming
0x0C-python-almost_a_circle/models/base.py
base.py
py
3,809
python
en
code
0
github-code
6
43332148964
import logging import json import gzip import ipaddress import datetime from c99api import EndpointClient from typing import List, Dict, Optional from os.path import exists from pydantic import BaseModel logger = logging.getLogger() def enrich_object_c99(object, c99_key:str=""): c99 = EndpointClient c99.ke...
Magnus1990P/shodan_extractor
src/ShodanExtractor/common.py
common.py
py
7,089
python
en
code
0
github-code
6
22957669261
class Node: def __init__(self, value): self.value = value self.next = None def __str__(self): return str(self.value) class LinkedList: def __init__(self): self.First = None self.Size = 0 def append(self, value): myNode = Node(value) if self...
MarioAguilarReal/Python
Programación Estructurada/Listas Ligadas/LinkedList.py
LinkedList.py
py
4,106
python
en
code
0
github-code
6
39104149472
from django.urls import path from . import views app_name = 'orders' urlpatterns = [ path('checkout', views.checkout, name='checkout'), path('order_details', views.order_detail, name='order_details'), path('orders', views.orders, name='orders'), path('create_order/', views.create_order, name='create_o...
suveydacan/book_shopping_microservice
MyProject/orders/urls.py
urls.py
py
333
python
en
code
1
github-code
6
30763965983
# Obj: Data persistance # Opt1: External files # Opt2: DB # Procedure: # Create the external file. # Open the file # Manipulate the file # Close the file from io import open # First parameter file name, second parameter mode to open (read, write) textFile = open('file.txt', 'w') line = 'Great day to code Python \n...
Giorc93/PythonCourse
ExternalFiles/TextFiles/externalText.py
externalText.py
py
1,508
python
en
code
1
github-code
6
44098268965
import tensorflow as tf import numpy as np from typing import Union, Optional, Sequence from pathlib import Path from dui.datasets.hdf5datasetfactory import HDF5DatasetFactory from dui.utils.signal import compress_db from dui.layers.utils import get_channel_axis def create_image_dataset( path: Union[str, Pat...
dperdios/dui-ultrafast
dui/datasets/utils.py
utils.py
py
6,117
python
en
code
14
github-code
6
11004498308
class Solution: def findLongestChain(self, pairs: List[List[int]]) -> int: pairs.sort(key = lambda a:a[0]) dp = [1] * len(pairs) ans = 1 for i in range(len(pairs)): for j in range(i): if pairs[i][0] > pairs[j][1]: dp[i] = max(dp[j]+1, d...
xixihaha1995/CS61B_SP19_SP20
temp/toy/python/646. Maximum Length of Pair Chain.py
646. Maximum Length of Pair Chain.py
py
386
python
en
code
0
github-code
6
31653944297
#!/usr/bin/env python3 """ Using p022_names.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For examp...
ilee38/practice-python
coding_problems/project_e/22_names_scores.py
22_names_scores.py
py
1,010
python
en
code
0
github-code
6
72000467069
from __future__ import absolute_import from __future__ import division from __future__ import print_function import builtins import gc import os import time import numpy as np import torch from trident.backend.common import * from trident.backend.opencv_backend import image2array from trident.backend.pytorch_backend...
AllanYiin/trident
trident/models/pytorch_mtcnn.py
pytorch_mtcnn.py
py
28,973
python
en
code
74
github-code
6
2642867267
def findPeakElement(nums): if len(nums) == 1 or nums[0] > nums[1]: return 0 n = len(nums) if nums[n - 1] > nums[n - 2]: return n - 1 # 0th and n - 1 th index already checked start = 1 end = n - 1 while start <= end: mid = start + (end - start) // 2 if num...
ArunRawat404/DSA
Binary Seach/1. BS on 1D Arrays/13. Find Peak Element.py
13. Find Peak Element.py
py
633
python
en
code
0
github-code
6
40718345835
# Assignment - 20 Full Stack Web Development using Python MySirG #More on functions # 1. Write a python program to create a function that takes a list and returns a new list # with the original list's unique elements. def unique_list(l): x = [] for a in l: if a not in x: x.ap...
Bhawna011/Python_Assignments
Assignment_20_function(2).py
Assignment_20_function(2).py
py
3,338
python
en
code
0
github-code
6
12119046055
import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup try: from distutils.command.build_py import build_py_2to3 as build_py except ImportError: from distutils.command.build_py import build_py path, script = os.path.split(sys.argv[0]) os.chdir(os.p...
open-pay/openpay-python
setup.py
setup.py
py
1,312
python
en
code
19
github-code
6
11601984964
import sqlite3 """ Two functions to help the main.py functions to validate the reference variable. """ # Open the database and create a cursor conn = sqlite3.connect("candidate.db") c = conn.cursor() """ ************************** Args - ref - str Return - Bool A validation function that takes the reference as a...
JohnEHughes/arctic_shores_test_v1
validators.py
validators.py
py
1,584
python
en
code
0
github-code
6
4461070550
# Licensed under a MIT style license - see LICENSE.txt """MUSE-PHANGS check pipeline module """ __authors__ = "Eric Emsellem" __copyright__ = "(c) 2017, ESO + CRAL" __license__ = "MIT License" __contact__ = " <eric.emsellem@eso.org>" # This module will take a MusePipe object and do the plot check ups # Standard modu...
emsellem/pymusepipe
src/pymusepipe/check_pipe.py
check_pipe.py
py
4,869
python
en
code
7
github-code
6
36356263355
from PIL import ImageDraw from configs.cfgs import args def read_class_names(class_file_name): '''loads class name from a file''' names = {} with open(class_file_name, 'r') as data: for ID, name in enumerate(data): names[ID] = name.strip('\n') return names def draw_boxes(img, box...
alexchungio/RetinaNet-Pytorch
utils/tools.py
tools.py
py
1,245
python
en
code
0
github-code
6
2026787329
import csv import matplotlib.pyplot as plt Zb = [[], []] # with open('F:/zhengwangwork/test csv/4.csv','rb')as f: # reader=csv.reader(f) # for row in reader: # print(row[0]) file = open('../gold.csv', 'r', encoding='UTF-8') # 打开csv文件 reader = csv.reader(file) # 读取csv文件 data = list(reader) # 将csv数据转化...
Nienter/mypy
personal/gold.py
gold.py
py
775
python
zh
code
0
github-code
6
34730801336
import logging import json import os import requests logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(inputPayload, context): slack_link = os.environ['SLACK_URL'] try: url = inputPayload['issue']['html_url'] except Exception as e: logger.error(e) # retu...
ByteOfKathy/esep-webhooks
lambda_function.py
lambda_function.py
py
536
python
en
code
0
github-code
6
44343755795
import sys from itertools import combinations as comb sys.stdin = open('input/20529.txt') input = sys.stdin.readline def d(A, B): return sum([A[i] != B[i] for i in range(4)]) T = int(input()) for tc in range(T): N = int(input()) mbti = input().split() if len(mbti) > 32: print(0) else: ...
nayeonkinn/algorithm
baekjoon/[S1] 20529. 가장 가까운 세 사람의 심리적 거리.py
[S1] 20529. 가장 가까운 세 사람의 심리적 거리.py
py
493
python
en
code
0
github-code
6
29246617685
# from django.contrib import messages from json import loads, dumps from .models import Link from django.db.models import Sum from django.db import OperationalError from tenacity import (retry, stop_after_attempt, wait_fixed, retry_if_exception_type) import random import string import datetime fr...
RahulTandon1/cutshort
shortner/views.py
views.py
py
4,216
python
en
code
3
github-code
6
15183195346
#! usr/bin/env python # -*- coding : utf-8 -*- from skopt import gp_maximize import numpy as np from skopt.plots import plot_convergence np.random.seed(123) #%matplotlib inline import matplotlib.pyplot as plt noise_level = 0.1 def f(x, noise_level=noise_level): return np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)...
aggarwalpiush/Hyperparameter-Optimization-Tutorial
main.py
main.py
py
2,364
python
en
code
3
github-code
6
25231399833
#! /usr/bin/env python # encoding: utf-8 # vim: ai ts=4 sts=4 et sw=4 ## ## ## @author Nadia ## nadia@gmail.com/joel@gmail.com ## from coreapp.appmodel.models import CrecheParent, CrecheChild, PARENT_CHILD_RELATION from coreapp.service.base_service import BaseService from coreapp.service.child_service import ChildSe...
projet2019/Creche_Parentale
creche/coreapp/service/parent_service.py
parent_service.py
py
7,616
python
en
code
0
github-code
6
75127728507
# This script gets the data of a lineout for different components begin_file = 0 end_file = 20 file_step = 20 plt_prefix = "name_of_your_hdf5_files" path_to_hdf5_files = "path_to_hdf5s" # Choose components components = ["phi", "lapse", "chi"] # specify a begin and end point for the lineout, e.g. two (x,y) points if ...
GRChombo/Postprocessing_tools
VisItTools/LineoutTools/CurveLineout.py
CurveLineout.py
py
1,839
python
en
code
1
github-code
6
35509709603
def sum_even_odd_digits(number): ch = 0 nch = 0 position = 1 while number > 0: digit = number % 10 if position % 2 == 0: ch += digit else: nch += digit number //= 10 position += 1 return ch, nch number = int(input()) ch, nch = sum_e...
aas1565/Python
buns/mod2_1/task13_new.py
task13_new.py
py
417
python
en
code
0
github-code
6
2872283986
import requests import datetime as dt from twilio.rest import Client account_sid = 'Twilio_api_sid' auth_token = 'twilio_auth_token' STOCK = "TSLA" COMPANY_NAME = "Tesla Inc" stock_api_key = 'alpha_vantage_api_key' news_api_key = 'news_api_key' STOCK_ENDPOINT = "https://www.alphavantage.co/query" NEWS_ENDPOINT = "h...
mgardner1011/UdemyProjects
Stock_news_alert/main.py
main.py
py
2,383
python
en
code
0
github-code
6
42896269372
import jax import numpy as np import numpy.testing as npt import pytest from matplotlib import pyplot as plt from statsmodels.graphics.tsaplots import plot_acf from .common import GaussianDistribution, FlatPotential, FlatUnivariatePotential, GaussianDynamics, lgssm_data, \ GaussianObservationPotential from ..csmc ...
AdrienCorenflos/aux-ssm-samplers
aux_samplers/_primitives/test_csmc/test_csmc.py
test_csmc.py
py
3,688
python
en
code
7
github-code
6
25467673406
import tkinter as tk import message class Scribble: def on_pressed(self, event): self.sx = event.x self.sy = event.y self.canvas.create_oval(self.sx, self.sy, event.x, event.y, outline = self.color.get(), width = self.width.ge...
watachan7/Python_tkinter_painterz
src/Painter.py
Painter.py
py
2,232
python
en
code
0
github-code
6
27061966352
__all__ = [ "InvalidPaddingError", "find_potential_ecb", "pad_pkcs_7", "strip_pkcs_7", "detect_potential_repeating_ecb_blocks", "ecb_encrypt", "cbc_encrypt_prepadded", "ecb_decrypt", "cbc_encrypt", "cbc_decrypt", "ctr_transcrypt" ] # noinspection PyPackageRequirements # fals...
BrendanCoughlan/cryptopals
block_crypt.py
block_crypt.py
py
3,652
python
en
code
0
github-code
6
42965233010
# *args = parameter that will pack all arguments into a tuple. Useful for the function to be more flexible thing varying amount of arguments. # def add(num1, num2): # sum = num1 + num2 # return sum # print(add(1,2,3)) #no longer can use this if the parameter is more than 2 def add(*stuff): sum = 0 st...
Naqiu00/Python-beginner
args_parameter.py
args_parameter.py
py
437
python
en
code
0
github-code
6
33232976991
def find_empty_space(puzzle): # find an empty space and return -1 if it exists # this function will return row, col tuple for i in range(9): for j in range(9): if puzzle[i][j] == -1: return i, j # if there's no empty space return None, None def guess...
Nikhil-Pachpande/sudoku-solver
sudoku.py
sudoku.py
py
2,505
python
en
code
0
github-code
6
21845001985
math = int(input("Enter math rate: ")) physics = int(input("Enter physics rate: ")) geography = int(input("Enter geography rate: ")) history = int(input("Enter history rate: ")) geometry = int(input("Enter geometry rate: ")) result = math + physics + geography + history + geometry if result <= 40: print("Fail") e...
Areg14/DroneEduLab
Lesson5/Problem2.py
Problem2.py
py
550
python
en
code
0
github-code
6
70063592188
from pwn import * from LibcSearcher import * # p=remote('61.147.171.105',51339) p=process('./whoami') elf=ELF('./whoami') #libc=ELF('./libc-2.27.so') # libc=ELF('/usr/lib/x86_64-linux-gnu/libc.so.6') libc=ELF('/home/cutecabbage/glibc-all-in-one/libs/2.27-3ubuntu1_amd64/libc.so.6') rl = lambda a=False : p.recvline(a) r...
CookedMelon/mypwn
adworld/whoami/exp-bak.py
exp-bak.py
py
2,967
python
en
code
3
github-code
6
10423288883
from __future__ import annotations import pytest from PySide6.QtCore import Qt from randovania.game_description.db.configurable_node import ConfigurableNode from randovania.game_description.db.dock_node import DockNode from randovania.game_description.db.event_node import EventNode from randovania.game_description.db...
randovania/randovania
test/gui/dialog/test_node_details_popup.py
test_node_details_popup.py
py
4,199
python
en
code
165
github-code
6
23935769471
import numpy as np import scipy.sparse as sp import tensorflow as tf import gc import random from clac_metric import cv_model_evaluate from utils import * from model import GCNModel from opt import Optimizer def PredictScore(train_drug_dis_matrix, drug_matrix, dis_matrix, seed, epochs, emb_dim, dp, lr, adjdp): n...
storyandwine/LAGCN
code/main.py
main.py
py
5,019
python
en
code
45
github-code
6
72331827389
import csv class Node: def __init__(self, name): self.name = name self.links = [] self.visited = False class Link: def __init__(self, fromNode, toNode, cost): self.cost = cost self.nodes = [fromNode, toNode] class Graph: def __init__(self, fileName): se...
cdfmlr/Graph_Python
graph_class.py
graph_class.py
py
1,343
python
en
code
1
github-code
6
36010802868
# -*- coding: cp1252 -*- import arcpy #-------- Update les ID_Support pour que les valeurs puissent etre unique def update_IDSupport(in_table, sqlClause): fields=("ID_Support") workspace = 'F:/Douala/Data_gathering/Gathring.gdb' # Open an edit session and start an edit operation with ar...
Diffouo/Python-Data-Analysis
Update_IDSupport.py
Update_IDSupport.py
py
1,402
python
en
code
1
github-code
6
9470821711
#! /usr/bin/python3 import re total_c_in_C_count = 0 total_1_c_in_C_count = 0 total_c_in_gene = 0 total_1_c_in_gene = 0 total_c_in_intergenic = 0 total_c_in_exon = 0 total_c_in_intron = 0 total_c_in_UTR = 0 total_meth_count = 0 gene_meth_count = 0 intergenic_meth_count = 0 exon_meth_count = 0 intron_meth_count = 0 ...
MCH74/Mnat_Methylation
scripts/analyse_all_C_methcalls.py
analyse_all_C_methcalls.py
py
5,327
python
en
code
0
github-code
6
43085015911
import numpy as np class BrooksCorey(object): def __init__( self, lambd=0., alpha=0., sr=0.0, smoothing_interval=0. ): self._lambda = lambd self._alpha = alpha self._sr = sr self._pc0 = smoothing_interval self._factor = -2.0 - (0.5 + 2.0) * self._lambda; self._pc_bu...
amanzi/ats
tools/python_models/wrm_brookscorey.py
wrm_brookscorey.py
py
2,012
python
en
code
35
github-code
6
24860820161
# -*- coding: utf-8 -*- """ Mini project 1 Dennis Brown, COMP6636, 03 MAR 2021 """ import numpy as np import copy import matplotlib.pyplot as plt def libsvm_scale_import(filename): """ Read data from a libsvm .scale file """ datafile = open(filename, 'r') # First pass: get dimensions of data ...
dennisgbrown/classifiers-decision-trees-kNN-perceptron
MiniProj1.py
MiniProj1.py
py
15,120
python
en
code
0
github-code
6
41137173523
#to run, 'sudo python' then 'import gamepad' (this file), then 'gamepad.test()' #to install pygame: apt-get install python-pygame import pygame, time, serial, csv, motor_func, math pygame.init() j = pygame.joystick.Joystick(0) j.init() # This is for the output write (change it accordingly, i.e: /dev/ttyUSB0): #outpu...
rsx-utoronto/galaxy
ground_station/main_ui/joystick.py
joystick.py
py
1,815
python
en
code
1
github-code
6
2772802336
# Given a binary tree, flatten it to a linked list in-place. # For example, given the following tree: # 1 # / \ # 2 5 # / \ \ # 3 4 6 # The flattened tree should look like: # 1 # \ # 2 # \ # 3 # \ # 4 # \ # 5 # \ # 6 # Definition for a binary ...
queryor/algorithms
leetcode/114. Flatten Binary Tree to Linked List.py
114. Flatten Binary Tree to Linked List.py
py
1,688
python
en
code
0
github-code
6
777182916
import datetime import numpy as np import torch def get_gravity_constants(gravity_constant_name): if gravity_constant_name == 'wgs-72old': mu = 398600.79964 # in km3 / s2 radiusearthkm = 6378.135 # km xke = 0.0743669161 tumin = 1.0 / xke j2 = 0.001...
esa/dSGP4
dsgp4/util.py
util.py
py
14,817
python
en
code
1
github-code
6
45364274546
import pygame from Game.Scenes.Scene import * from Game.Shared import GameConstant from Game import Highscore class HighscoreScene(Scene): def __init__(self, game): super(HighscoreScene, self).__init__(game) self.__highScoreSprite = pygame.transform.scale(pygame.image.load(GameConstant....
grapeJUICE1/Grape-Bricks
Game/Scenes/HighScoreScene.py
HighScoreScene.py
py
1,256
python
en
code
7
github-code
6
5467682111
import time time_start = time.time() f = open('//Users/sanderlindberg/Documents/kodekalendere/knowit/2/world.txt').read().split("\n") def find_seq(elem): seqs = [] overflow_ind = 0 if elem[0] == " ": for i in range(len(elem)): if elem[i] == "#" or i == len(elem) -1: ove...
skanin/Julekalendere_2019
knowit/2/2.py
2.py
py
1,484
python
en
code
0
github-code
6
13043566776
from _datetime import datetime preparation_time = 30 donation_time = 30 class EventData(object): # @Nori # Definition explanation comes here... @staticmethod def get_event_date(): global ev_date isvaild = False while not isvaild: data = input("Enter your Event da...
Bandita69/TFF
Event.py
Event.py
py
4,417
python
en
code
1
github-code
6
29099358897
from extra_functions import rgb_to_hex, hex_to_rgb class Heatmap: def __init__(self): self.fact_cache = {} @staticmethod def _color_dict(gradient): """ Takes in a list of RGB sub-lists and returns dictionary of colors in RGB and hex form for use in a graphing function defi...
ZexiDilling/structure_search
heatmap.py
heatmap.py
py
8,347
python
en
code
0
github-code
6
17221793090
import json import aiohttp import discord import datetime from discord import Embed import plotly.express as px import pandas as pd import random with open("config.json", "r") as config: data = json.load(config) token = data["Token"] prefix = data["Prefix"] intents = discord.Intents.default() inten...
Eryck13/StockBot
main.py
main.py
py
8,237
python
en
code
0
github-code
6
70488529787
# accepted on codewars.com import sys deltas = [[-2, -1, 1, 2, 2, 1, -1, -2], [1, 2, 2, 1, -1, -2, -2, -1]] order = [4, 0, 5, 1, 6, 2, 7, 3] adjOnes = [[-1, 0, 1, 0], [0, 1, 0, -1]] flag: bool coordinates_of_knight: list[list[int]] def knights_tour(start: tuple[int, int], size: int): global flag, coordinates_of_...
LocusLontrime/Python
CodeWars_Rush/_4kyu/A_Knights_Tour_4kyu.py
A_Knights_Tour_4kyu.py
py
4,194
python
en
code
1
github-code
6
12229413948
import torch import torchvision import PIL import torch.nn.functional as F import numpy from matplotlib import cm #CAM def hook_store_A(module, input, output): module.A = output[0] def hook_store_dydA(module, grad_input, grad_output): module.dydA = grad_output[0] if __name__ == "__main__": mod...
pengxj/DeepLearningCourse
code/VisInput.py
VisInput.py
py
1,281
python
en
code
9
github-code
6
35227507194
# -*- coding: utf-8 -*- """ Created on Sat Feb 18 01:16:56 2017 @author: Leon """ from osgeo import gdal import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy import spatial import cv2 im = cv2.imread('fill.jpg') ntu = cv2.imread('DSCF2098_1471837627895.jpg') imgray = cv2.cvtColor(im,cv2.C...
LeonChen66/UAV-and-TrueOrtho
Building Roof Contour/RDP.py
RDP.py
py
1,318
python
en
code
8
github-code
6
31838419123
import numpy as np try: import cPickle as pickle except: import pickle from dataset.mnist import load_mnist from SGD.TwoLayerNet import TwoLayerNet (x_train, t_train), (x_test, t_test) = load_mnist\ (normalize=False,flatten=True,one_hot_label=True) train_loss = [] '''超参数''' iters_num = 1000 train_size = x_...
maplect/CNN-APP
SGD/Neuralnet_train.py
Neuralnet_train.py
py
1,093
python
en
code
2
github-code
6
22357678211
# -*- coding: utf-8 -*- from odoo import _, models, fields, api class SelectPurchaseOrder(models.TransientModel): _name = 'select.purchase.order' purchaseorder_ids = fields.Many2many('purchase.order', string='Purchase Order') @api.multi def select_purchaseorders(self): spp_id = ...
detian08/bsp_addons
account-payment-11.0/account_payment_spp/wizard/select_purchaseorder_wizard.py
select_purchaseorder_wizard.py
py
920
python
en
code
1
github-code
6
31449582311
import sys import time from multiprocessing import Process from scapy.all import * def arp_spoof(victim_ip, bystander_ip, attacker_mac): try: while True: send(ARP(op=2, pdst=victim_ip, psrc=bystander_ip, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=attacker_mac), verbose=0) send(ARP(op=2, pdst=...
emrberk/network-attacks
attacker/attacker.py
attacker.py
py
1,369
python
en
code
0
github-code
6
20210291556
import re txt = "The rain in Spain" x = re.search("^The.*Spain$", txt) if x: print("YES! We have a match!") else: print("No match") x = re.findall("ai", txt) print(x) x = re.split("\s", txt) print(x) txt = "The rain in Spain" x = re.split("\s", txt, 1) print(x) txt = "The rain in Spain" x = re.sub("\s", "9", txt)...
Nayassyl/22B050835
week5/w3schools/regex.py
regex.py
py
768
python
en
code
0
github-code
6
27630602762
#!/usr/bin/env python3 import string with open("game.py") as f: game_str = f.read() with open("style.css") as f: style_str = f.read() with open("index.html.template") as f: template_str = f.read() t = string.Template(template_str) out_str = t.substitute(python_code=game_str, style_sheet=style_str) with...
jthacker/memory_game
build.py
build.py
py
372
python
en
code
0
github-code
6
43001373047
__author__ = "Vikram Anand" __email__ = "vikram.anand@carenostics.com" __license__ = "Apache 2.0" __maintainer__ = "developer" __status__ = "Production" __version__ = "0.0.1" import os import logging from google.cloud import bigquery, storage logger = logging.getLogger('BigQuery') class BigQuery: """Class Bigquer...
RiptideStar/DataStack-main
hmhn/scripts/old-postgress/python-scripts/metrics/carenostics/big_query.py
big_query.py
py
814
python
en
code
0
github-code
6
35862756028
### VERI YAPILARI ## 1) Liste Olusturma; liste = ["a", 19.3, 30] liste_iki = [1, 2, 3, 4, 5] tum_liste = [liste, liste_iki] print(len(liste)) print(len(liste_iki)) print(liste[2]) print(liste_iki[3]) type(liste[2]) # Liste icindeki bir elemanin turu print(tum_liste) l...
Rumeysaislam/data-analysis-course
-4-Veri-Yapıları.py
-4-Veri-Yapıları.py
py
7,616
python
tr
code
0
github-code
6
27356830765
import random import os from helpers import * from keras.models import model_from_json # load json and create model json_file = open('saved_models/model.json', 'r') loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) # load weights into new model model.load_weights("saved...
pekkipo/Characters_recognition
predict_characters.py
predict_characters.py
py
1,793
python
en
code
1
github-code
6
26305089118
#!/usr/bin/python3 """Module containing the definition for a class of type square""" Rectangle = __import__('9-rectangle').Rectangle class Square(Rectangle): """Class representing a square""" def __init__(self, size): """method to be called on instantiation""" self.integer_validator("size", ...
AndyMSP/holbertonschool-higher_level_programming
0x0A-python-inheritance/10-square.py
10-square.py
py
390
python
en
code
0
github-code
6
16119657095
__author__ = 'burgosz' from django import template register = template.Library() from zabbix_reports.templatetags.zabbix_call import zbx_call from django.core.cache import cache @register.assignment_tag def zbx_service_container_get(): services = [] return services # Iterate over services and get the service...
burgosz/zabbix_reports
templatetags/zabbix_services.py
zabbix_services.py
py
1,574
python
en
code
5
github-code
6
8257193173
import logging from typing import Mapping from datetime import datetime import attr from .dixel import Dixel from ..utils import Pattern, DatetimeInterval, gateway from ..utils.dicom import DicomLevel # splunk-sdk is 2.7 only, so diana.utils.gateway provides a minimal query/put replacement # Suppress insecure warning...
derekmerck/DIANA
packages/diana/diana/apis/splunk.py
splunk.py
py
3,138
python
en
code
11
github-code
6
14153199843
from models import Pet,db,connect_db from app import app connect_db(app) db.drop_all() db.create_all() pet1 = Pet( name="Keeshond", species="dog", photo_url="http://cdn.akc.org/content/article-body-image/keeshond_dog_pictures.jpg", age=2, notes="I love thi...
nickchow2020/Adoption-Agency
seed.py
seed.py
py
1,193
python
en
code
0
github-code
6
35473650215
from tensorflow.keras.models import load_model from delta import calculate_gt from loss import detection_loss, ssd_loss import numpy as np import pickle from nms import non_maximum_suppression from utils import images_with_rectangles, plot_images, xywh2xyxy, draw_rectangles # load models model = load_model('../models/...
taila0/single-shot-multibox-detector
src/main_eval.py
main_eval.py
py
3,001
python
en
code
0
github-code
6
25755944520
import unittest from datetime import date, datetime from constants import ( STATUS_IN_PROGRESS, STATUS_COMPLETED, TASK_UPDATED, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, TASK1, TASK2, TASK3 ) from main import app, bd from models.task_model import Task from repository.task_reposi...
dan9Protasenia/task-management
tests/test_task_service.py
test_task_service.py
py
5,950
python
en
code
0
github-code
6
73871407226
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 27 20:09:14 2020 @author: scro3517 """ import torch import torch.nn as nn import torch.nn.functional as F c1 = 1 #b/c single time-series c2 = 4 #4 c3 = 16 #4 c4 = 32 #4 k=7 #kernel size s=3 #stride #num_classes = 3 class cnn_network_time(nn.Modu...
danikiyasseh/SoQal
prepare_network.py
prepare_network.py
py
3,891
python
en
code
4
github-code
6
41971622331
#!/usr/local/bin/python3 ''' Created on Mar 8, 2013 For interview test Consider a log file that showed important network events including packet drops. Log format is below: 2012-12-29 22:00 172.16.8.48 drops 24 packets 2012-12-29 22:01 172.16.8.48 buffer full 2012-12-29 22:02 172.16.8.45 drops 21 packets 2012-12-29 22...
rduvalwa5/TinkerGui
GUI_projects/Py2_Lessons/src/log_report.py
log_report.py
py
1,373
python
en
code
0
github-code
6
20399194189
with open('../src/mem.S', 'r') as f: lines = f.readlines() output = [] ignore = False for line in lines: if '# python start jacklight' in line: ignore = True elif '# python end jacklight' in line: ignore = False output.append(line) elif not ignore: output.append(line) ...
Qpicpicxxz/Venus-scheduler
task/rollback_mem.py
rollback_mem.py
py
382
python
en
code
1
github-code
6
40786176947
import pandas as file import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans from sklearn import cluster, datasets, metrics #分群 K-means model = KMeans(n_clusters = 16) data = file.read_csv("./data.csv") data.drop(['id'],axis=1) predict = model.fit(data).labels_ ans = [] for row in predi...
kiper00/DataMining
Hw2/Hw.py
Hw.py
py
694
python
en
code
0
github-code
6
9414662626
import socket ##required import argparse ##gets argument from command line import sys ##system calls import re ## parsing string BUFF_SIZE = 4096 TIMEOUT_SIZE = 2 neededInfo = { #contains everything that i need in my log 'url':None, 'sName':None, 'sIp':None, 'sPort':None, 'Path':...
kelly8282/python-stuff
kliu80MyCurl_2_1.py
kliu80MyCurl_2_1.py
py
6,029
python
en
code
0
github-code
6
26867008715
import numpy as np import pandas as pd def drop_first_rows(data): """ The first rows of many JOBNUMs, where many strings enter the machine and no ladders leave contain strange readings that are unrepresentative of the data as a whole. If called, this function will drop them. """ indices = dat...
Danavell/Dolle
pre_processing/aggregate_0102/aggregates.py
aggregates.py
py
3,892
python
en
code
0
github-code
6
22534790497
#Program for a Function that takes a list of words and returns the length of the longest one. def longest_word(list): #define a function which takes list as a parameter longest=0 for words in list: #l...
ABHISHEKSUBHASHSWAMI/String-Manipulation
str8.py
str8.py
py
704
python
en
code
1
github-code
6
42514144175
import math import nltk nltk.download('stopwords') import pandas as pd import re from copy import deepcopy from dictionary.models import Dialect from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from django.shortcuts import render, redirect class NaiveBayes: def split_reg(self, *args): sent...
eymkarla/thesisrepo
classifier/NB.py
NB.py
py
4,535
python
en
code
0
github-code
6
6017738646
import bisect l = [1, 2, 3, 4] # 先找索引 再插入 index = bisect.bisect_left(l, 5) l.insert(index, 5) print(l) # Output: [1, 2, 3, 4, 5] # 直接插入 bisect.insort_left(l, 6) print(l) # Output: [1, 2, 3, 4, 5,6] # 示例 查找分数等级 def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'): i = bisect.bisect(breakpoints, sco...
Yuelioi/Program-Learning
Python/Basic/标准库/07.数据类型/_bisect.py
_bisect.py
py
488
python
en
code
0
github-code
6
27055792799
"""empty message Revision ID: 22771e69d10c Revises: 8c7cbf0f76c6 Create Date: 2021-07-14 18:46:48.994109 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "22771e69d10c" down_revision = "8c7cbf0f76c6" branch_labels = None depends_on = None def upgrade(): op....
CodeForPoznan/codeforpoznan.pl_v3
backend/migrations/versions/22771e69d10c_.py
22771e69d10c_.py
py
2,028
python
en
code
8
github-code
6
42519865803
# The radical of n, rad(n), is the product of distinct prime factors of n. For # example, 504 = 2^3 x 3^2 x 7, so rad(504) = 2 x 3 x 7 = 42. # # We shall define the triplet of positive integers (a, b, c) to be an abc-hit if: # GCD(a, b) = GCD(a, c) = GCD(b, c) = 1 # a < b # a + b = c # rad(abc) < c # For exam...
jose-ramirez/project_euler
problems/p127.py
p127.py
py
2,025
python
en
code
0
github-code
6
19400321799
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None from common.linkedListCommon import * class Solution: def swapPairs(self, head: ListNode) -> ListNode: dummy = ListNode(0) dummy.next = head cur = dummy ...
Yigang0622/LeetCode
swapPairs.py
swapPairs.py
py
614
python
en
code
1
github-code
6
6433666492
import logging import requests import elasticsearch import datetime import os import re from .config import set_defaults from jinja2 import Template class ElasticTMDB(object): def load_config(self): set_defaults(self) # Set HTTP headers for TMDB requests self.headers = {} self.head...
shaunschembri/ElasticTMDB
elastictmdb/__init__.py
__init__.py
py
27,602
python
en
code
4
github-code
6
26126736743
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" # Imports import io from setuptools import setup, find_packages # Readme file with io.open('README.rst', encoding='utf-8') as readme_file: readme = readme_file.read() # ChangeLog file with io.open('HISTORY.rst', encoding='utf-8') as history_fil...
paip-web/pwbs
setup.py
setup.py
py
4,954
python
en
code
2
github-code
6
42793161783
import sys blastfile = open(sys.argv[1], 'r') earlyfasta = open(sys.argv[2], 'r') latefasta = open(sys.argv[3], 'r') earlycore = open(sys.argv[4], 'w') latecore = open(sys.argv[5], 'w') late = [] early = [] def get_next_fasta (fileObject): '''usage: for header, seq in get_next_fasta(fileObject): ''' head...
kdiverson/seqTools
getcoregenes.py
getcoregenes.py
py
1,209
python
en
code
3
github-code
6
71133520507
from Logic.Crud import * from Logic.Operatii import * import datetime def arata_meniu(): ''' :return: optiunile din meniu ''' print("1.Adaugare cheltuiala") print("2.Stergere cheltuiala") print("3.Modificare cheltuiala") print("4.Stergerea cheltuielilor pentru un nr de apartament") pr...
AP-MI-2021/lab-567-Pop-Sergiu-Adrian
lab5/Ui/Interfata.py
Interfata.py
py
5,122
python
es
code
0
github-code
6
30358044871
import wx from traitsui.wx.check_list_editor import CustomEditor from traitsui.testing.tester.command import MouseClick from traitsui.testing.tester.locator import Index from traitsui.testing.tester._ui_tester_registry._common_ui_targets import ( BaseSourceWithLocation, ) from traitsui.testing.tester._ui_tester_re...
enthought/traitsui
traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/check_list_editor.py
check_list_editor.py
py
2,444
python
en
code
290
github-code
6
5093704747
"""empty message Revision ID: b3ff59df2833 Revises: fee4d1b1d192 Create Date: 2022-04-08 07:33:52.082355 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'b3ff59df2833' down_revision = 'fee4d1b1d192' branch_labels = None depe...
sudiptob2/microserve-main
migrations/versions/b3ff59df2833_.py
b3ff59df2833_.py
py
934
python
en
code
1
github-code
6
20040106137
string = 'THis iS AN ExamPLe' command = 'CAPitalize' def string_op(string, command): command_list = ['upper','lower','capitalize'] command_low = command.lower() nw_str = [] if command_low not in command_list: nw_str = "Invalid command!" elif command_low == 'upper': nw_str = string.u...
mwboiss/DSI-Prep
inter_py/string_op.py
string_op.py
py
491
python
en
code
0
github-code
6
12769514952
import cv2 from cv2 import waitKey import torch import urllib.request import os import matplotlib.pyplot as plt print(torch.__version__) os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" # url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") # urllib.request.urlretrieve(url, filename) m...
JohnLee16/InfraredImage2Depth
src/midas_depth.py
midas_depth.py
py
1,628
python
en
code
0
github-code
6
23934349151
from pymongo import MongoClient import pprint import statistics client = MongoClient('mongodb://localhost:27017/') db = client.fantasypros def find(): players = db.playersbywk.distinct("name") for player in players: getstats(player) def getstats(player): points = [] player_position = '' ...
soboy2/pyrandom
fbstats.py
fbstats.py
py
1,583
python
en
code
0
github-code
6
20869059181
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.cm as cm import matplotlib import random vida=[] defesa=[] ataque=[] #Spearador de Dados def separador_atributos(arquivo): vida_max=0 vida_min=18 def_max=0 def_min=18 atk_...
Edumarek123/Machine_Learning
graficos/graficos_dispersao.py
graficos_dispersao.py
py
4,235
python
pt
code
0
github-code
6
8267902176
from __future__ import annotations import pickle import sys from collections import defaultdict from unittest.mock import Mock, patch import pytest from kombu import Connection, Consumer, Exchange, Producer, Queue from kombu.exceptions import MessageStateError from kombu.utils import json from kombu.utils.functional...
celery/kombu
t/unit/test_messaging.py
test_messaging.py
py
24,481
python
en
code
2,643
github-code
6
6824520762
import os from settings.common_settings import * DEBUG = True # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os...
Baronchibuikem/DhangoGraphenePratice
server/settings/production_settings.py
production_settings.py
py
618
python
en
code
0
github-code
6
34473798674
import numpy as np from scipy.optimize import curve_fit import sys def fit_DD(d, ik, imu, f, fit=None, p0=None, ilambda_max=None): """ Fit P_DD(k, mu, lambda) with an given function f(lambda, y0, ...) = PDD_0 + f(lambda) Args: d (dict): lambda data returned by load_lambda() ik (int): ...
junkoda/lambda
lib/lambdalib/lambda_fitting.py
lambda_fitting.py
py
8,421
python
en
code
0
github-code
6
659465820
import numpy as np from tqdm import tqdm from statistics import median class Filter : """ To add : - Filtre de Frost, Filtre de Gamma_MAP, Kuan - Autoencoder filtering ? """ #class specialized for filtering SAR images formated as (height, len, (HH,HV,VV)) def __init__(self...
ArnaudMi/Statistical-Learning-Methods-Contribution-for-the-description-of-SAR-targets
code/utils/filtre.py
filtre.py
py
4,147
python
en
code
0
github-code
6
1140042349
import compcore from joblib import Parallel, delayed import multiprocessing import numpy as np import scipy as sp import h5py import sys, csv, re, os, time, argparse, string, tempfile try: import lsalib except ImportError: from lsa import lsalib def main(): parser = argparse.ArgumentParser() arg_precision_...
foolstars/a_elsa
elsa/lsa/ppi.py
ppi.py
py
14,310
python
en
code
0
github-code
6
2856076738
import re, unittest from conans.model.settings import Settings from conans.model.conan_file import ConanFile from conans.client.generators.cmake import CMakeGenerator class CMakeGeneratorTest(unittest.TestCase): def extractMacro(self, name, text): pattern = ".*(macro\(%s\).*?endmacro\(\)).*" % name ...
AversivePlusPlus/AversivePlusPlus
tools/conan/conans/test/generators/cmake_test.py
cmake_test.py
py
1,364
python
en
code
31
github-code
6
23448338775
""" Created on Wed Apr 27 18:09:57 2022 @author: ljhs8 """ WIDTH = 750 HEIGHT = 600 GRID_SIZE= 9 GRID_WIDTH = 23 GRID_HEIGHT = 17 CELL_COUNT = GRID_HEIGHT*GRID_WIDTH MINESCOUNT = 45 WHITE = "#C1D4D7" GREY = "#ABB6B8"
Anonymousbowtie/Normal_minesweeper
settings.py
settings.py
py
240
python
en
code
0
github-code
6
3806456362
import pickle, custom_logger from cmd_parser import parser, createModelString, performSortingString from asyncio.log import logger from os.path import isfile from logging import INFO, DEBUG, WARN import utils import logging args = parser.parse_args() if args.debug: custom_logger.initialize_logger(logger_level=DE...
jmvaswani/picture-sorter
sorter.py
sorter.py
py
3,435
python
en
code
0
github-code
6
40732718573
n = int(input()) arr=[list(map(str, input().strip())) for i in range(n)] def check(x,y,n): color = arr[x][y] for i in range(x, x+n): for j in range(y, y+n): if color != arr[i][j]: print('(', end='') check(x, y, n//2) check(x, y+n//2, n//2) ...
seriokim/Coding-Study
백준 단계별로 풀어보기/분할정복/1992.py
1992.py
py
497
python
en
code
0
github-code
6