branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/main | <file_sep>rule get_trna_miscrna:
output:
"results/bait/bait.fasta"
params:
trna = config.get("TRNA_FASTA"),
misc = config.get("MISC_RNA_FASTA"),
shell:
"wget -q -O - {params.trna} | zcat > {output} && "
"wget -q -O - {params.misc} | zcat >> {output}"
rule star_bait_index:
input:
fasta = rules.get_trna_miscrna.output
output:
directory("results/idx/bait")
threads:
12
params:
extra = "--genomeSAindexNbases 6"
log:
"results/logs/star_bait_index.log"
wrapper:
"https://github.com/snakemake/snakemake-wrappers/raw/0.72.0/bio/star/index"
rule star_genome_index:
input:
fasta = custom_genome('results/custom-genome/combined.fasta'),
gtf = custom_genome('results/custom-genome/combined.fixed.gtf')
output:
directory("results/idx/genome")
threads:
12
params:
extra = "--genomeSAindexNbases 12"
resources:
time=60,
mem=20000,
cpus=12
log:
"results/logs/star_genome_index.log"
wrapper:
"https://github.com/snakemake/snakemake-wrappers/raw/0.72.0/bio/star/index"
def get_fastqs(wc, r="r1"):
tmp = SUBSAMPLE_TABLE[SUBSAMPLE_TABLE['sample_name'] == wc.sample]
tmp2 = tmp[tmp['subsample_name'] == wc.subsample]
return [tmp2.get('fastq_'+r)[0]]
rule get_fqs:
output:
r1 = "results/fastq/{sample}/{subsample}_r1.fastq.gz",
r2 = "results/fastq/{sample}/{subsample}_r2.fastq.gz"
params:
r1 = lambda wc: get_fastqs(wc, "r1"),
r2 = lambda wc: get_fastqs(wc, "r2"),
shell:
"""
wget -O {output.r1} {params.r1} &&
wget -O {output.r2} {params.r2}
"""
rule trim_pe:
input:
r1 = rules.get_fqs.output.r1,
r2 = rules.get_fqs.output.r2
output:
r1 = "results/fastq/{sample}_{subsample}_r1.trimmed.fq.gz",
r2 = "results/fastq/{sample}_{subsample}_r2.trimmed.fq.gz",
html = "results/fastq/{sample}_{subsample}_fastp.html",
json = "results/fastq/{sample}_{subsample}_fastp.json"
threads:
12
resources:
time=60,
mem=20000,
cpus=12
conda:
"../envs/fastp.yaml"
singularity:
"docker://quay.io/biocontainers/fastp:0.20.0--hdbcaa40_0"
shell:
"fastp --in1 {input.r1} --in2 {input.r2} "
"--out1 {output.r1} --out2 {output.r2} "
"-j {output.json} -h {output.html} "
"-w {threads} -L -R {wildcards.sample}_fastp"
rule star_align_bait:
input:
fq1 = rules.trim_pe.output.r1,
# paired end reads needs to be ordered so each item in the two lists match
fq2 = rules.trim_pe.output.r2,
idx = rules.star_bait_index.output,
output:
# see STAR manual for additional output files
"results/aln/bait/{sample}/{subsample}/Aligned.out.bam",
r1 = "results/aln/bait/{sample}/{subsample}/Unmapped.out.mate1",
r2 = "results/aln/bait/{sample}/{subsample}/Unmapped.out.mate2",
log:
"results/logs/star/bait/{sample}/{subsample}.log"
params:
# path to STAR reference genome index
index="results/idx/bait",
# optional parameters
extra="--outReadsUnmapped Fastx --outSAMtype BAM Unsorted"
resources:
time=640,
mem=128000,
cpus=24
threads:
24
wrapper:
"https://github.com/snakemake/snakemake-wrappers/raw/0.72.0/bio/star/align"
rule star_align_genome:
input:
fq1 = rules.star_align_bait.output.r1,
# paired end reads needs to be ordered so each item in the two lists match
fq2 = rules.star_align_bait.output.r2,
idx = rules.star_genome_index.output,
vcf = te_variants('results/snps/snps.vcf'),
gtf = custom_genome('results/custom-genome/combined.fixed.gtf')
output:
# see STAR manual for additional output files
"results/aln/genome/{sample}/{subsample}/Aligned.out.bam"
log:
"results/logs/star/genome/{sample}/{subsample}.log"
resources:
time=720,
mem=64000,
cpus=24
params:
# path to STAR reference genome index
index="results/idx/genome",
# optional parameters
extra="--outSAMtype BAM Unsorted --outSAMmultNmax 1 --outSAMattributes NH HI AS nM vA vG --varVCFfile {v} --sjdbGTFfile {g}".format(g=custom_genome('results/custom-genome/combined.fixed.gtf'), v=te_variants('results/snps/snps.vcf'))
threads:
24
wrapper:
"https://github.com/snakemake/snakemake-wrappers/raw/0.72.0/bio/star/align"
rule sort_star:
input:
rules.star_align_genome.output
output:
"results/aln/sort/{sample}/{subsample}.bam"
threads: # Samtools takes additional threads through its option -@
8 # This value - 1 will be sent to -@.
params:
extra=""
resources:
time=240,
mem=24000,
cpus=8
wrapper:
"https://github.com/snakemake/snakemake-wrappers/raw/0.72.0/bio/samtools/sort"
rule filter_reads:
input:
rules.sort_star.output
output:
"results/aln/filt/{sample}/{subsample}.bam"
resources:
time=20,
mem=10000,
params:
"-O BAM -F 256"
wrapper:
"https://github.com/snakemake/snakemake-wrappers/raw/0.72.0/bio/samtools/view"
rule samtools_index:
input:
"{file}.bam"
output:
"{file}.bam.bai"
params:
"" # optional params string
wrapper:
"https://github.com/snakemake/snakemake-wrappers/raw/0.72.0/bio/samtools/index"
<file_sep>import sys
import peppy
from Bio import SeqIO
singularity: "docker://continuumio/miniconda3"
configfile: "config/config.yaml"
pepfile: "config/pep.yaml"
SAMPLES = [x.sample_name for x in pep.samples]
SUBSAMPLE_TABLE = pep.subsample_table
#SUBSAMPLE_NAMES = [expand("{s}-{ss}",s=x, ss=SUBSAMPLE_TABLE[SUBSAMPLE_TABLE['sample_name'] == x] for x in SAMPLES]
TES = [x.id.split("#")[0] for x in SeqIO.parse(config.get("TRANSPOSON_FASTA"), "fasta")]
MAIN_CONFIG = config.get("MAIN_CONFIG",'config/config.yaml')
subworkflow custom_genome:
workdir:
"../../gte21-custom-genome/"
snakefile:
"../../gte21-custom-genome/workflow/Snakefile"
#configfile:
# MAIN_CONFIG
subworkflow te_variants:
workdir:
"../../transposon-variants-hts/"
snakefile:
"../../transposon-variants-hts/workflow/Snakefile"
configfile:
MAIN_CONFIG
rule all:
input:
expand("results/aln/sex-te/{s}/{r}.{sex}.bam",s=SAMPLES,r=['rep1'],sex=['male','unknown']),
te_variants(expand('results/copies/{s}.csv',s=['w1118_male','w1118_female'])),
expand("results/depths/{s}-{r}-{t}-at-male-snps.csv.gz",s=['w1118_testes'],r=['rep1','rep2','rep3','rep4'],t=['depth','reads']),
expand("results/bigwigs/tes/{s}.{sub}.tes.strand-{t}.rpkm.bw",s=['w1118_testes'],sub=['rep1','rep2','rep3','rep4'],t=['forward','reverse'])
include: "../workflow/rules/align.smk"
include: "../workflow/rules/male-depths.smk"
include: "../workflow/rules/bigwigs.smk"
<file_sep>rule get_te_reads:
input:
rules.filter_reads.output
output:
tmp = temp("results/aln/tes/{sample}/{subsample}.tmp.bam"),
tmpbai = temp("results/aln/tes/{sample}/{subsample}.tmp.bam.bai"),
bam = "results/aln/tes/{sample}/{subsample}.tes.bam",
bai = "results/aln/tes/{sample}/{subsample}.tes.bam.bai",
params:
tes = TES
conda:
"../envs/samtools.yaml"
shell:
"""
cp {input} {output.tmp} && samtools index {output.tmp}
samtools view -b {output.tmp} {params.tes} > {output.bam} && \
samtools index {output.bam}
"""
rule get_male_specific_te_reads:
input:
rules.get_te_reads.output.bam
output:
sam = temp("results/aln/sex-te/{sample}/{subsample}.male.sam"),
bam = "results/aln/sex-te/{sample}/{subsample}.male.bam",
bai = "results/aln/sex-te/{sample}/{subsample}.male.bam.bai"
params:
tes = TES
conda:
"../envs/samtools.yaml"
shell:
"""
samtools view -H {input} > {output.sam} && \
samtools view {input} | grep "vA:B" | grep ",2[,\\s]" >> {output.sam} && \
samtools view -b {output.sam} > {output.bam} && \
samtools index {output.bam}
"""
rule get_non_male_te_reads:
input:
rules.get_te_reads.output.bam
output:
sam = temp("results/aln/sex-te/{sample}/{subsample}.unknown.sam"),
bam = "results/aln/sex-te/{sample}/{subsample}.unknown.bam",
bai = "results/aln/sex-te/{sample}/{subsample}.unknown.bam.bai"
params:
tes = TES
conda:
"../envs/samtools.yaml"
shell:
"""
samtools view -H {input} > {output.sam} && \
samtools view {input} | grep -v "vA:B:\\w+,2[,\\s]" | grep -v "c,2" >> {output.sam} && \
samtools view -b {output.sam} > {output.bam} && \
samtools index {output.bam}
"""
rule get_male_depth_per_snp:
input:
bam = rules.get_te_reads.output.bam,
vcf = te_variants('results/snps/snps.vcf'),
output:
csv = "results/depths/{sample}-{subsample}-depth-at-male-snps.csv.gz",
resources:
time=20,
mem=10000,
cpus=2
conda:
"../envs/bioc-general.yaml"
script:
'../scripts/depth-at-snps.R'
rule get_male_reads_per_snp:
input:
male = rules.get_male_specific_te_reads.output.bam,
unk = rules.get_non_male_te_reads.output.bam,
vcf = te_variants('results/snps/snps.vcf'),
output:
csv = "results/depths/{sample}-{subsample}-reads-at-male-snps.csv.gz",
resources:
time=20,
mem=10000,
cpus=2
conda:
"../envs/bioc-general.yaml"
script:
'../scripts/reads-at-snps.R'
<file_sep>rule bigwigs:
input:
bam = "results/aln/filt/{sample}/{subsample}.bam",
bai = "results/aln/filt/{sample}/{subsample}.bam.bai"
output:
"results/bigwigs/tes/{sample}.{subsample}.tes.strand-{strand}.rpkm.bw"
threads:
24
conda:
"../envs/deeptools.yaml"
resources:
time=60,
mem=20000,
cpus=24
shell:
"""
bamCoverage -b {input.bam} \
-o {output} -p {threads} -v --normalizeUsing RPKM \
--smoothLength 150 --filterRNAstrand {wildcards.strand}
"""
<file_sep>library(VariantAnnotation)
library(Rsamtools)
library(tidyverse)
bam <- snakemake@input[['bam']]
#bam <- "results/aln/tes/w1118_testes/rep1.tes.bam"
vcf <- snakemake@input[['vcf']]
#vcf <- "~/work/transposon-variants-hts/results/snps/snps.vcf"
sample_name <- snakemake@wildcards[['sample']]
# sample_name <- 'aa'
subsample_name <- snakemake@wildcards[['subsample']]
# subsample_name <- 'bb'
vr <- VariantAnnotation::readVcfAsVRanges(vcf)
gr <- vr %>% GRanges() %>% GenomicRanges::reduce()
allele.lookup <- vr %>% as.data.frame() %>% as_tibble() %>%
dplyr::select(seqnames, pos=start, ref, alt, specificity) %>%
filter(specificity == 'w1118_male')
pup <- PileupParam(max_depth = 10e6,
distinguish_nucleotides = T,
distinguish_strands = F,
min_minor_allele_depth = 0,
min_nucleotide_depth = 1)
scbp <- ScanBamParam(which = gr)
pileups.df <- pileup(bam, scanBamParam = scbp, pileupParam = pup) %>%
as_tibble(.) %>%
mutate(sample = sample_name) %>%
mutate(subsample = subsample_name)
pileups.df <- pileups.df %>%
left_join(allele.lookup, by=c('seqnames','pos')) %>%
mutate(sex = ifelse(nucleotide == alt, 'male','unknown')) %>%
#group_by(seqnames, pos, sex, sample, subsample) %>%
#summarise(depth = sum(`count`),.groups = 'drop') %>%
dplyr::select(sample, subsample, seqnames,pos, nucleotide, sex, count) %>%
arrange(seqnames, pos) %>%
distinct() # rm dups to joining with the allele lookup, which has multiple rows per position
write_csv(pileups.df, snakemake@output[['csv']])
<file_sep># transposon-variants-expression
<file_sep>library(VariantAnnotation)
library(Rsamtools)
library(tidyverse)
male <- snakemake@input[['male']] #male<- 'results/aln/sex-te/w1118_testes/rep1.male.bam'
unk <- snakemake@input[['unk']] # unk <- 'results/aln/sex-te/w1118_testes/rep1.unknown.bam'
vcf <- snakemake@input[['vcf']] #vcf <- "~/work/transposon-variants-hts/results/snps/snps.vcf"
sample_name <- snakemake@wildcards[['sample']]# sample_name <- 'aa'
subsample_name <- snakemake@wildcards[['subsample']]# subsample_name <- 'bb'
gr <-VariantAnnotation::readVcfAsVRanges(vcf) %>% GRanges()
pup <- PileupParam(max_depth = 10e6,
distinguish_nucleotides = F,
distinguish_strands = F,
min_minor_allele_depth = 0,
min_nucleotide_depth = 1)
scbp <- ScanBamParam(which = gr)
pileups.df <- list(male=male, unknown =unk) %>%
map(~pileup(., scanBamParam = scbp, pileupParam = pup)) %>%
map_df(as_tibble, .id = 'sex') %>%
mutate(sample = sample_name) %>%
mutate(subsample = subsample_name) %>%
dplyr::select(sample, subsample, sex, seqnames,pos,total.depth=count) %>%
arrange(seqnames, pos)
write_csv(pileups.df, snakemake@output[['csv']])
| e693276f3f67377de84fce6d9747ccd14aa26517 | [
"Markdown",
"Python",
"R"
]
| 7 | Python | Ellison-Lab/gte21-te-variant-expression | ed8dc2c222be34d20cd37a40ed0b902da426fcb2 | 39f57086af41bb39de65b1bd62dc4cbe86f4c644 |
refs/heads/master | <repo_name>wahajali/collector<file_sep>/lib/collector/handlers/dea.rb
module Collector
class Handler
class Dea < Handler
def additional_tags(context)
#NOTE remove stack since this is an array (causes problems with kairosDB)
{ #stack: context.varz["stacks"],
ip: context.varz["host"].split(":").first,
}
end
def process(context)
send_metric("can_stage", context.varz["can_stage"], context)
send_metric("reservable_stagers", context.varz["reservable_stagers"], context)
send_metric("available_memory_ratio", context.varz["available_memory_ratio"], context)
send_metric("available_disk_ratio", context.varz["available_disk_ratio"], context)
state_metrics, application_metrics = state_counts(context)
state_metrics.each do |state, count|
send_metric("dea_registry_#{state.downcase}", count, context)
end
application_metrics[:instances].each do |key, val|
["used_memory_in_bytes", "state_born_timestamp", "state_running_timestamp", "used_disk_in_bytes", "computed_pcpu"].each do |m|
#tags = { name: "#{val["application_name"]}/#{val["instance_index"]}", job: 'Application', index: val["instance_index"] }
tags = { name: "#{val["application_name"]}", job: 'Application', index: val["instance_index"] }
send_app_metric(m, val[m], context, tags)
end
end
metrics = registry_usage(context)
send_metric("dea_registry_mem_reserved", metrics[:mem], context)
send_metric("dea_registry_disk_reserved", metrics[:disk], context)
send_metric("total_warden_response_time_in_ms", context.varz["total_warden_response_time_in_ms"], context)
send_metric("warden_request_count", context.varz["warden_request_count"], context)
send_metric("warden_error_response_count", context.varz["warden_error_response_count"], context)
send_metric("warden_error_response_count", context.varz["warden_error_response_count"], context)
end
#Rewrote method from handler to change somethings specific to application data
# Sends the metric to the metric collector (historian)
#
# @param [String] name the metric name
# @param [String, Fixnum] value the metric value
#NOTE by default the metric name is set to the measuring value for kairos I change that inside the kairos class and swap it with the name tag
def send_app_metric(name, value, context, tags = {})
tags.merge!(deployment: Config.deployment_name)
tags.merge!(dea: "#{@job}/#{context.index}", dea_index: context.index)
@historian.send_data({
key: name,
timestamp: context.now,
value: value,
tags: tags
})
end
private
DEA_STATES = %W[
BORN STARTING RUNNING STOPPING STOPPED CRASHED RESUMING DELETED
].freeze
APPLICATION_METRICS = %W[
instance_index application_name used_memory_in_bytes used_disk_in_bytes computed_pcpu
].freeze
APPLICATION_METRICS_TIMESTAMPS = %W[state_running_timestamp state_born_timestamp].freeze
def state_counts(context)
metrics = DEA_STATES.each.with_object({}) { |s, h| h[s] = 0 }
applications = {}
applications[:instances] = {}
context.varz["instance_registry"].each do |_, instances|
instances.each do |k, instance|
metrics[instance["state"]] += 1
#TODO application host will always be the host ip of the DEA..?
#TODO each DEA can have more than one instance of each application (application name + index are unique)
app_data = APPLICATION_METRICS.each.with_object({}) do |key, h|
h[key] = instance[key]
end
app_data["computed_pcpu"] = app_data["computed_pcpu"] * 100 unless app_data["computed_pcpu"].nil?
tmp = APPLICATION_METRICS_TIMESTAMPS.each.with_object({}) do |key, h|
next if instance[key].nil?
h[key] = (instance[key] * 1000).truncate
end
app_data.merge! tmp
applications[:instances].update({ k => app_data })
end
end
Config.logger.info("collector.handler.dea.", { "application_count" => applications[:instances].size })
[metrics, applications]
end
RESERVING_STATES = %W[BORN STARTING RUNNING RESUMING].freeze
def registry_usage(context)
reserved_mem = reserved_disk = 0
context.varz["instance_registry"].each do |_, instances|
instances.each do |_, instance|
if RESERVING_STATES.include?(instance["state"])
reserved_mem += instance["limits"]["mem"]
reserved_disk += instance["limits"]["disk"]
end
end
end
{mem: reserved_mem, disk: reserved_disk}
end
register Components::DEA_COMPONENT
end
end
end
<file_sep>/lib/collector/historian/kairos.rb
module Collector
class Historian
class Kairos
include HTTParty
persistent_connection_adapter({ :idle_timeout => 30, :keep_alive => 30 })
def initialize(api_host, http_client, deployment_name)
@api_host = api_host
@http_client = http_client
@deployment_name = deployment_name
end
def send_data(data)
send_metrics(formatted_metric_for_data(data))
end
private
def formatted_metric_for_data(data)
data[:name] = "#{@deployment_name}/#{data[:tags][:name].gsub('.', '_')}"
data[:tags][:name] = data[:key]
data.delete :key
data
end
def send_metrics(data)
return if data[:value] == "default"
Config.logger.debug("Sending metrics to kairos: [#{data.inspect}]")
body = Yajl::Encoder.encode(data)
response = @http_client.post(@api_host, body: body, headers: {"Content-type" => "application/json"})
if response.success?
Config.logger.info("collector.emit-kairos.success", number_of_metrics: 1, lag_in_seconds: 0)
else
Config.logger.warn("collector.emit-kairos.fail", number_of_metrics: 1, lag_in_seconds: 0)
end
end
end
end
end
| d3e3bbaa69489e111620475e7cd73d0bd745d277 | [
"Ruby"
]
| 2 | Ruby | wahajali/collector | a2e8c4bafd8b902d2c8c03b1e350e15af28f2d15 | 0314d95da8f9054a3a5133ea222f7b09d5b3aa40 |
refs/heads/master | <repo_name>7818207/GeneticTrader<file_sep>/geneGrapher.py
# -*- coding: utf-8 -*-
def draw(gene,engine):
binDict = engine.binDict;
<file_sep>/OrderRunnerTest.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 25 18:18:34 2019
@author: james
"""
import OrderRunner as OR
import datadecoder as dd
dd = dd.DataDecoder()
oR = OR.orderRunner(dd)
time.sleep(1)
oR.run()
####!!!!!!!!!!!!!
####!!!Buy and sell has benn changed!!
####!!!!!!!!!!!!
#GBP757676
#GBP756929
#GBP758039
#GBP759545
#GBP759583
#GBP763600
#GBP750245
#USD 993208,11.MARCH 00:08
#USD993205, 11.MARCH 10:03
#USD993304
#USD993217 11.MARCH 13:42
#USD993085 11.MARCH 15:16
#USD993574 11.MARCH 17:13
#USD993580 11.MARCH 23:59
#USD993862 12.MARCH 13:54
#USD994066 12.MARCH 20:09
<file_sep>/beta_quickEngine.py
# -*- coding: utf-8 -*-
#quick version of dnaEngine, used in multiprocessing
import matplotlib.pyplot as plt
import bisect
from tqdm import tqdm
import numpy as np
import ast
import warnings
import pandas as pd
import re
#return a list containing bins, helper function for makeDf
def __init__(self):
self.df = pd.read_csv('df.csv')
self.column_index_value_dict,self.binDict = makeDf(self.df)
self.RbinDict = makeRDf(self.df)
def makeBin(data):
#bin of fixed size of 20
num_bins = 20
data = np.sort(data)
data_points_per_bin = len(data) // 20
bins = [data[_ * data_points_per_bin: (_+1)*data_points_per_bin] for _ in range(num_bins)]
binLevel = []
for l in bins:
binLevel.append(min(l))
binLevel.append(max(bins[-1]))
binLevel = np.array(binLevel)
binLevel.sort()
return binLevel
#result binDict
def makeRBin(data):
#bin of fixed size of 20
num_bins = 10
data = np.sort(data)
data_points_per_bin = len(data) // 10
bins = [data[_ * data_points_per_bin: (_+1)*data_points_per_bin] for _ in range(num_bins)]
binLevel = []
for l in bins:
binLevel.append(min(l))
binLevel.append(max(bins[-1]))
binLevel = np.array(binLevel)
binLevel.sort()
return binLevel
def makeRDf(df):
for i in range(20):
df['r%d'%(i+1)] = df['Close'].pct_change(i+1).shift(-(i+1))
binDict = {}
for i in range(1):
binDict[i+1] = makeRBin(df['r%d'%(i+1)][5:].tolist());
#Triming step ---Must go hand in hand
return binDict
#return a meta dictionary of type dictionary, the key is column name from dataframe, and value is array of corresponding values
#the returned value should be sorted in ascending order and their is a corresponding index list
def makeDf(df):
for i in range(20):
df['r%d'%(i+1)] = df['Close'].pct_change(i+1).shift(-(i+1))
for i in range(10):
#df['%dbHigh'%(i+1)] = df['High'].rolling(i+1).max()
#df['%dbLow'%(i+1)] = df['Low'].rolling(i+1).min()
#Calculate i bar spread
#df['%dSpread'%(i+1)] = df['%dbHigh'%(i+1)] - df['%dbLow'%(i+1)]
df['Close+%d'%(i+1)] = df['Close'].shift(i+1)
df['%dSpreadWPolarity'%(i+1)] = df['Close'] - df['Close+%d'%(i+1)]
binDict = {}
for i in range(10):
binDict[i+1] = makeBin(df['%dSpreadWPolarity'%(i+1)][5:].tolist());
#Triming step ---Must go hand in hand
df = df[10:]
column_index_value_dict = {}
for i in range(10):
index_value_list = []
df = df.sort_values('%dSpreadWPolarity'%(i+1))
value_list = df['%dSpreadWPolarity'%(i+1)].tolist()
index_list = df.index.tolist()
index_value_list.append(index_list)
index_value_list.append(value_list)
column_index_value_dict['%dSpreadWPolarity'%(i+1)] = index_value_list
return column_index_value_dict, binDict
def draw100dna(genes,binDict):
fig = plt.figure(figsize=(20,20))
fig.suptitle('price movement genes')
for i in range(100):
plt.subplot(10,10,i+1)
###need to be changed
gene = genes[i]
dictTuples = []
x = []
y = []
for i in range(5):
x.append(gene[2*i])
y.append(gene[2*i+1])
for i in range(len(x)):
dictTuples.append((x[i],[binDict[x[i]][y[i]-1],binDict[x[i]][y[i]]]))
currentLine = ([0,0],[0,0])
for i in range(len(dictTuples)):
x1 = currentLine[0][1]
x2 = dictTuples[i][0] + currentLine[0][1]
y1 = currentLine[1][1]
y2 = dictTuples[i][1][1] + currentLine[1][1]
plt.plot([x1,x2],[y1,y2],'--', color='g', lw= 0.8)
currentLine[0][0] = x1
currentLine[0][1] = x2
currentLine[1][0] = y1
currentLine[1][1] = y2
currentLine = ([0,0],[0,0])
for i in range(len(dictTuples)):
x1 = currentLine[0][1]
x2 = dictTuples[i][0] + currentLine[0][1]
y1 = currentLine[1][1]
y2 = dictTuples[i][1][0] + currentLine[1][1]
plt.plot([x1,x2],[y1,y2],'--', color='r', lw= 0.8)
currentLine[0][0] = x1
currentLine[0][1] = x2
currentLine[1][0] = y1
currentLine[1][1] = y2
plt.tight_layout()
time.sleep(1)
def valueMethod1(temporaldf,df):
factlist = []
factlist.append(len(temporaldf) / len(df) * 61714.3)
factlist.append(len(temporaldf))
for i in range(9):
try:
factlist.append(temporaldf['r%d'%(i+2)].mean())
factlist.append(sum(temporaldf['r%d'%(i+2)] > 0) / len(temporaldf))
factlist.append(sum(temporaldf['r%d'%(i+2)] < 0) / len(temporaldf))
except ZeroDivisionError:
pass
return factlist
def evaluategenes(genes,column_index_value_dict,binDict,df):
geneDict = {}
for gene in tqdm(genes):
geneDict[repr(gene)] = decode(gene,column_index_value_dict,binDict,df)
return geneDict
def decode(gene,column_index_value_dict,binDict,df):
lengthgene = []
bingene = []
for i in range(int(len(gene)/2)):
lengthgene.append(gene[2*i])
bingene.append(gene[2*i + 1])
interval = 0
list_of_index = set(column_index_value_dict['1SpreadWPolarity'][0])
for i in range(len(lengthgene) - 1):
list_of_index = np.array(list(list_of_index))+interval
lowBound = bisect.bisect_left(column_index_value_dict['%dSpreadWPolarity'%(lengthgene[i])][1],binDict[lengthgene[i]][bingene[i] - 1])
upBound = bisect.bisect_right(column_index_value_dict['%dSpreadWPolarity'%(lengthgene[i])][1],binDict[lengthgene[i]][bingene[i]])
list_of_index = set(column_index_value_dict['%dSpreadWPolarity'%(lengthgene[i])][0][lowBound:upBound]).intersection(list_of_index)
interval = lengthgene[i + 1]
return df.iloc[list(list_of_index)]
def appendrbin(tempdf,RbinDict):
tempdf['r20'] = tempdf['r20'] - tempdf['r19']
tempdf['r19'] = tempdf['r19'] - tempdf['r18']
tempdf['r18'] = tempdf['r18'] - tempdf['r17']
tempdf['r17'] = tempdf['r17'] - tempdf['r16']
tempdf['r16'] = tempdf['r16'] - tempdf['r15']
tempdf['r15'] = tempdf['r15'] - tempdf['r14']
tempdf['r14'] = tempdf['r14'] - tempdf['r13']
tempdf['r13'] = tempdf['r13'] - tempdf['r12']
tempdf['r12'] = tempdf['r12'] - tempdf['r11']
tempdf['r11'] = tempdf['r11'] - tempdf['r10']
tempdf['r10'] = tempdf['r10'] - tempdf['r9']
tempdf['r9'] = tempdf['r9'] - tempdf['r8']
tempdf['r8'] = tempdf['r8'] - tempdf['r7']
tempdf['r7'] = tempdf['r7'] - tempdf['r6']
tempdf['r6'] = tempdf['r6'] - tempdf['r5']
tempdf['r5'] = tempdf['r5'] - tempdf['r4']
tempdf['r4'] = tempdf['r4'] - tempdf['r3']
tempdf['r3'] = tempdf['r3'] - tempdf['r2']
tempdf['r2'] = tempdf['r2'] - tempdf['r1']
return tempdf
def pos_rate(ser):
return sum(ser > 0) / ser.count()
def get_strategy_bool(index,stop,limit,action,df):
end = False
indexer = index
terminal_index = len(df)
start_price = df.iloc[indexer].Close
while((not end) and (indexer < terminal_index-1)):
high = df.iloc[indexer].High
low = df.iloc[indexer].Low
if(action == 1):
if(high > start_price + limit):
return 1
elif(low < start_price - stop):
return -1
elif(action == -1):
if(high > start_price + stop):
return -1
elif(low < start_price - limit):
return 1
indexer+=1;
def get_monte_carlo_stra(gene,column_index_value_dict,binDict,df,RbinDict):
tempdf = decode(gene,column_index_value_dict,binDict,df)
tempdf = appendrbin(tempdf,RbinDict)
tempdf['l2s1bmean'] = 0
tempdf['l2s1bposrate'] = 0
tempdf['l2s1smean'] = 0
tempdf['l2s1sposrate'] = 0
tempdf['l4s2bmean'] = 0
tempdf['l4s2bposrate'] = 0
tempdf['l4s2smean'] = 0
tempdf['l4s2sposrate'] = 0
indexex = tempdf.index.tolist()
l2s1b = []
l2s1s = []
l4s2b = []
l4s2s = []
l8s3b = []
l8s3s = []
l9s3b = []
l9s3s = []
for i in indexex:
l2s1b.append(get_strategy_bool(i,0.0001,0.0002,1,df))
l2s1s.append(get_strategy_bool(i,0.0001,0.0002,-1,df))
l4s2b.append(get_strategy_bool(i,0.0002,0.0004,1,df))
l4s2s.append(get_strategy_bool(i,0.0002,0.0004,-1,df))
l8s3b.append(get_strategy_bool(i,0.0003,0.0008,1,df))
l8s3s.append(get_strategy_bool(i,0.0003,0.0008,-1,df))
l9s3b.append(get_strategy_bool(i,0.0003,0.0009,1,df))
l9s3s.append(get_strategy_bool(i,0.0003,0.0009,-1,df))
tempdf.loc[i]['l2s1bmean'] = np.mean(l2s1b)
tempdf.loc[i]['l2s1bposrate'] = sum(np.asarray(l2s1b) > 0) / len(l2s1b)
tempdf.loc[i]['l2s1smean'] = np.mean(l2s1s)
tempdf.loc[i]['l2s1sposrate'] = sum(np.asarray(l2s1s) > 0) / len(l2s1s)
tempdf.loc[i]['l4s2bmean'] = np.mean(l4s2b)
tempdf.loc[i]['l4s2bposrate'] = sum(np.asarray(l4s2b) > 0) / len(l4s2b)
tempdf.loc[i]['l4s2smean'] = np.mean(l4s2s)
tempdf.loc[i]['l4s2sposrate'] = sum(np.asarray(l4s2s) > 0) / len(l4s2s)
tempdf.loc[i]['l8s3bmean'] = np.mean(l8s3b)
tempdf.loc[i]['l8s3bposrate'] = sum(np.asarray(l8s3b) > 0) / len(l8s3b)
tempdf.loc[i]['l8s3smean'] = np.mean(l8s3s)
tempdf.loc[i]['l8s3sposrate'] = sum(np.asarray(l8s3s) > 0) / len(l8s3s)
tempdf.loc[i]['l9s3bmean'] = np.mean(l9s3b)
tempdf.loc[i]['l9s3bposrate'] = sum(np.asarray(l9s3b) > 0) / len(l9s3b)
tempdf.loc[i]['l9s3smean'] = np.mean(l9s3s)
tempdf.loc[i]['l9s3sposrate'] = sum(np.asarray(l9s3s) > 0) / len(l9s3s)
result = {'l2s1bmean':np.mean(l2s1b),'l2s1bposrate':sum(np.asarray(l2s1b) > 0) / len(l2s1b),'l2s1smean':np.mean(l2s1s)
,'l2s1sposrate':sum(np.asarray(l2s1s) > 0) / len(l2s1s),'l4s2bmean':np.mean(l4s2b),'l4s2bposrate':sum(np.asarray(l4s2b) > 0) / len(l4s2b),
'l4s2smean':np.mean(l4s2s),'l4s2sposrate':sum(np.asarray(l4s2s) > 0) / len(l4s2s),'l8s3bmean':np.mean(l8s3b),'l8s3bposrate':sum(np.asarray(l8s3b) > 0) / len(l8s3b),'l8s3smean':np.mean(l8s3s),'l8s3sposrate':sum(np.asarray(l8s3s) > 0) / len(l8s3s),'l9s3bmean':np.mean(l9s3b),'l9s3bposrate':sum(np.asarray(l9s3b) > 0) / len(l9s3b),'l9s3smean':np.mean(l9s3s),'l9s3sposrate':sum(np.asarray(l9s3s) > 0) / len(l9s3s)}
resultdf = pd.DataFrame(data=result,index=[0])
if(resultdf['l9s3sposrate'][0] > 0.7 and resultdf['l9s3smean'][0] > 0):
return 0.0009,0.0003,-1
elif(resultdf['l9s3bposrate'][0] > 0.7 and resultdf['l9s3bmean'][0] > 0):
return 0.0009,0.0003,1
elif(resultdf['l8s3bposrate'][0] > 0.7 and resultdf['l8s3bmean'][0] > 0):
return 0.0008,0.0003,1
elif(resultdf['l8s3sposrate'][0] > 0.7 and resultdf['l8s3smean'][0] > 0):
return 0.0008,0.0003,-1
elif(resultdf['l4s2bposrate'][0] > 0.7 and resultdf['l4s2bmean'][0] > 0):
return 0.0004,0.0002,1
elif(resultdf['l4s2sposrate'][0] > 0.7 and resultdf['l4s2smean'][0] > 0):
return 0.0004,0.0002,-1
elif(resultdf['l2s1bposrate'][0] > 0.7 and resultdf['l2s1bmean'][0] > 0):
return 0.0002,0.0001,1
elif(resultdf['l2s1sposrate'][0] > 0.7 and resultdf['l2s1smean'][0] > 0):
return 0.0002,0.0001,-1
return 0,0,0
def get_sharpe_stra(gene,column_index_value_dict,binDict,df,RbinDict):
tempdf = decode(gene,column_index_value_dict,binDict,df)
tempdf = appendrbin(tempdf,RbinDict)
binLists = []
for i in range(20):
dig = np.digitize(tempdf['r%d'%(i+1)], RbinDict[1])
binLists.append(dig)
binArray = np.array(binLists) - 5.5
arraydf = pd.DataFrame(binArray)
for i in range(14):
arraydf['mean%dposrate'%(i+6)] = arraydf.rolling(i+6).mean().apply(pos_rate,axis=1)
arraydf['mean%dposrate'%(i+6)] = arraydf['mean%dposrate'%(i+6)].shift(-(i+6))
arraydf['mean%d'%(i+6)] = arraydf.rolling(i+6).mean().mean(axis=1)
arraydf['mean%d'%(i+6)] = arraydf['mean%d'%(i+6)].shift(-(i+6))
arraydf['sharpe%d'%(i+6)] = (arraydf.rolling(i+6).mean() / arraydf.rolling(i+6).std()).mean(axis=1)
arraydf['sharpe%d'%(i+6)] = arraydf['sharpe%d'%(i+6)].shift(-(i+6))
arraydf['max'] = arraydf[['sharpe6','sharpe7','sharpe8','sharpe9','sharpe10','sharpe11','sharpe12','sharpe13','sharpe14','sharpe15','sharpe16','sharpe17','sharpe18','sharpe19']].idxmax(axis=1)
arraydf['min'] = arraydf[['sharpe6','sharpe7','sharpe8','sharpe9','sharpe10','sharpe11','sharpe12','sharpe13','sharpe14','sharpe15','sharpe16','sharpe17','sharpe18','sharpe19']].idxmin(axis=1)
maxname = arraydf.iloc[0]['max']
minname = arraydf.iloc[0]['min']
maxn = re.findall('\d+',arraydf.iloc[0]['max'])
minn = re.findall('\d+',arraydf.iloc[0]['min'])
maxint = int(maxn[0])
minint = int(minn[0])
if(arraydf.iloc[0][maxname] > 2.0):
return maxint
elif(arraydf.iloc[0][minname] < -2.0):
return -minint
else:
return 0
if __name__ == "__main__":
warnings.filterwarnings("ignore")
pd.options.mode.chained_assignment = None
filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
filedf.dropna(inplace=True)
genes = filedf.index.values.tolist()
new_genes = []
for x in genes:
new_genes.append(ast.literal_eval(x))
df = pd.read_csv('df.csv')
RbinDict = makeRDf(df)
bins = RbinDict[1]
column_index_value_dict,binDict = makeDf(df)
sharpedf = pd.DataFrame()
for gene in tqdm(new_genes):
tempdf = decode(gene,column_index_value_dict,binDict,df)
tempdf = appendrbin(tempdf,RbinDict)
binLists = []
for i in range(20):
dig = np.digitize(tempdf['r%d'%(i+1)], bins)
binLists.append(dig)
binArray = np.array(binLists) - 5.5
arraydf = pd.DataFrame(binArray)
for i in range(14):
arraydf['mean%dposrate'%(i+6)] = arraydf.rolling(i+6).mean().apply(pos_rate,axis=1)
arraydf['mean%dposrate'%(i+6)] = arraydf['mean%dposrate'%(i+6)].shift(-(i+6))
arraydf['mean%d'%(i+6)] = arraydf.rolling(i+6).mean().mean(axis=1)
arraydf['mean%d'%(i+6)] = arraydf['mean%d'%(i+6)].shift(-(i+6))
arraydf['sharpe%d'%(i+6)] = (arraydf.rolling(i+6).mean() / arraydf.rolling(i+6).std()).mean(axis=1)
arraydf['sharpe%d'%(i+6)] = arraydf['sharpe%d'%(i+6)].shift(-(i+6))
filedf.ix[gene.__repr__(),['sharpe6','sharpe7','sharpe8','sharpe9','sharpe10','sharpe11','sharpe12','sharpe13','sharpe14','sharpe15','sharpe16','sharpe17','sharpe18','sharpe19']] = arraydf[['sharpe6','sharpe7','sharpe8','sharpe9','sharpe10','sharpe11','sharpe12','sharpe13','sharpe14','sharpe15','sharpe16','sharpe17','sharpe18','sharpe19']].iloc[0]
<file_sep>/geneFun.py
# -*- coding: utf-8 -*-
from multiprocessing import Process, Manager
import dnaengine
import geneGenerator
engine = dnaengine.Engine()
generator = geneGenerator.geneGenerator(5,5)
genes = generator.generateMany(100)
engine.makeDf(df)
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
resultdict = {}
for i in range(500):
genes = generator.generateMany(100)
diction = engine.evaluategenes(genes)
resultdict = merge_two_dicts(resultdict,diction)
def evaluate(resultdict,genes):
resultdict = merge_two_dicts(resultdict, engine.evaluategenes(genes))
if __name__ == "__main__":
with Manager() as manager:
L = manager.dict() # <-- can be shared between processes.
processes = []
for i in tqdm(range(10)):
genes = generator.generateMany(100)
p = Process(target=evaluate, args=(L,genes)) # Passing the list
p.start()
processes.append(p)
for p in processes:
p.join()
print(L)<file_sep>/onda_fun.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 14 10:29:21 2019
@author: james
"""
import requests
#a5b72e26f74b956c0768edf23b8064e5-5ebe088b151f7beea5b258a086222662
auth_token='a5b72e26f74b956c0768edf23b8064e5-5ebe088b151f7beea5b258a086222662'
hed = {'Authorization': 'Bearer ' + auth_token}
url = 'https://api-fxtrade.oanda.com/v1/accounts'
response = requests.post(url, headers=hed)<file_sep>/beta_decoder.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 23:18:21 2019
@author: james
"""
import pandas as pd
import quickEngine as qe
import ast
import numpy as np
from operator import itemgetter
class BetaDecoder:
def __init__(self):
self.evaluation_method_5()
def evaluation_method_6(self):
self.filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
self.filedf['r7-r2'] = self.filedf['r7mean'] - self.filedf['r2mean']
self.filedf['r7-r2samesign'] = self.filedf['r2mean'] * self.filedf['r7-r2'] > 0
#for those that are of the same sign, take the highest
self.filedf.sort_values('r7-r2',inplace = True,ascending=False)
upper = self.filedf.head(int(len(self.filedf)*0.4))
upperdiffsign = upper[upper['r7-r2samesign'] == False]
uppersamesign = upper[upper['r7-r2samesign'] == True]
lower = self.filedf.tail(int(len(self.filedf)*0.4))
lowersamesign = lower[lower['r7-r2samesign'] == True]
lowerdiffsign = lower[lower['r7-r2samesign'] == False]
diffsigntemp = pd.concat([upperdiffsign,lowerdiffsign])
samesigntemp = pd.concat([uppersamesign,lowersamesign])
diffsigntemp['r7divr2'] = (diffsigntemp['r7-r2'])/ abs(diffsigntemp['r2mean'])
samesigntemp['r7divr2'] = (samesigntemp['r7-r2']) / samesigntemp['r2mean']
samesigntemp.sort_values('r7divr2',inplace = True,ascending=False)
diffsigntemp.sort_values('r7divr2',inplace = True,ascending=False)
#take 20% from them
samesigntemp = samesigntemp.head(int(len(samesigntemp)*0.2))
diffsigntemp = diffsigntemp.head(int(len(diffsigntemp)*0.2))
temp = pd.concat([samesigntemp,diffsigntemp])
temp['r7-r2viable'] = temp['r7-r2']*(temp['r7posrate']-temp['r7negrate'])
temp.sort_values('r7-r2viable',inplace = True,ascending=False)
temp = temp.head(int(len(temp) * 0.8))
self.usabledf = temp
genes = temp.index.tolist()
pool_genes = []
for x in genes:
pool_genes.append(ast.literal_eval(x))
self.genes = pool_genes
df = pd.read_csv('df.csv')
_, self.binDict = qe.makeDf(df)
self.inverseGenes()
def evaluation_method_5(self):
self.filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
self.filedf.dropna(inplace=True)
self.filedf = self.filedf[self.filedf['total_hits'] >= 20]
temp = self.filedf
self.usabledf = temp
genes = temp.index.tolist()
pool_genes = []
for x in genes:
pool_genes.append(ast.literal_eval(x))
self.genes = pool_genes
df = pd.read_csv('df.csv')
_, self.binDict = qe.makeDf(df)
self.inverseGenes()
def evaluation_method_4(self):
#First step is to get lowest 30% for all r1
self.filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
self.filedf.dropna(inplace=True)
#Calculate deal price,
self.filedf['r0mean'] = (self.filedf['r2mean'] - 0) * 0.3
self.filedf['r1mean'] = self.filedf['r0mean'] + (self.filedf['r2mean'] - self.filedf['r0mean'])/2
self.filedf['deal2'] = self.filedf['r2mean'] + (self.filedf['r3mean'] - self.filedf['r2mean']) * 0.3
self.filedf['deal3'] = self.filedf['r3mean'] + (self.filedf['r4mean'] - self.filedf['r3mean']) * 0.3
self.filedf['deal4'] = self.filedf['r4mean'] + (self.filedf['r5mean'] - self.filedf['r4mean']) * 0.3
self.filedf['deal5'] = self.filedf['r5mean'] + (self.filedf['r6mean'] - self.filedf['r5mean']) * 0.3
self.filedf['deal6'] = self.filedf['r6mean'] + (self.filedf['r7mean'] - self.filedf['r6mean']) * 0.3
self.filedf['deal7'] = self.filedf['r7mean'] + (self.filedf['r8mean'] - self.filedf['r7mean']) * 0.3
self.filedf['deal8'] = self.filedf['r8mean'] + (self.filedf['r9mean'] - self.filedf['r8mean']) * 0.3
self.filedf['deal9'] = self.filedf['r9mean'] + (self.filedf['r10mean'] - self.filedf['r9mean']) * 0.3
self.filedf['highest'] = self.filedf[['r0mean','r1mean','r2mean','r3mean','r4mean','r5mean','r6mean','r7mean','r8mean','r9mean']].max(axis=1)
self.filedf['lowest'] = self.filedf[['r0mean','r1mean','r2mean','r3mean','r4mean','r5mean','r6mean','r7mean','r8mean','r9mean']].min(axis=1)
self.filedf['profit'] = self.filedf['highest'] - self.filedf['lowest']
self.filedf['risk'] = self.filedf['profit'] / 2
self.filedf['maxname'] = self.filedf[['r0mean','r1mean','r2mean','r3mean','r4mean','r5mean','r6mean','r7mean','r8mean','r9mean']].idxmax(axis=1)
self.filedf['minname'] = self.filedf[['r0mean','r1mean','r2mean','r3mean','r4mean','r5mean','r6mean','r7mean','r8mean','r9mean']].idxmin(axis=1)
maxlist = list(map(itemgetter(1), self.filedf['maxname'].values))
self.filedf['maxtime'] = maxlist
self.filedf["maxtime"] = pd.to_numeric(self.filedf["maxtime"])
minlist = list(map(itemgetter(1), self.filedf['minname'].values))
self.filedf['mintime'] = minlist
self.filedf["mintime"] = pd.to_numeric(self.filedf["mintime"])
self.filedf['order_type'] = self.filedf['maxtime'] > self.filedf['mintime']
self.filedf['placetimebuy'] = self.filedf['mintime']*60
self.filedf['endtimebuy'] = self.filedf['maxtime']*60
self.filedf['placetimesell'] = self.filedf['maxtime']*60
self.filedf['endtimesell'] = self.filedf['mintime']*60
self.filedf.sort_values('profit',inplace = True,ascending=False)
self.filedf = self.filedf[self.filedf['total_hits'] >= 20]
self.filedf.sort_values('profit',inplace = True,ascending=False)
self.filedf = self.filedf.head(int(len(self.filedf)*0.5))
temp = self.filedf
self.usabledf = temp
genes = temp.index.tolist()
pool_genes = []
for x in genes:
pool_genes.append(ast.literal_eval(x))
self.genes = pool_genes
df = pd.read_csv('df.csv')
_, self.binDict = qe.makeDf(df)
self.inverseGenes()
def inverseGenes(self):
poolgenes = self.genes
inversedGenes = []
for gene in poolgenes:
newgene = []
newgene.append(gene[8])
newgene.append(gene[9])
newgene.append(gene[6])
newgene.append(gene[7])
newgene.append(gene[4])
newgene.append(gene[5])
newgene.append(gene[2])
newgene.append(gene[3])
newgene.append(gene[0])
newgene.append(gene[1])
inversedGenes.append(newgene)
self.inversedGenes = inversedGenes
self.genes = []
#Get raw data downloaded from ibkr,return 1 for buy order, 0 for sell order
def findMatch(self,df):
for i in range(20):
df['r%d'%(i+1)] = df['close'].pct_change(i+1).shift(-(i+1))
for i in range(10):
#df['%dbHigh'%(i+1)] = df['High'].rolling(i+1).max()
#df['%dbLow'%(i+1)] = df['Low'].rolling(i+1).min()
#Calculate i bar spread
#df['%dSpread'%(i+1)] = df['%dbHigh'%(i+1)] - df['%dbLow'%(i+1)]
df['Close+%d'%(i+1)] = df['close'].shift(i+1)
df['%dSpreadWPolarity'%(i+1)] = df['close'] - df['Close+%d'%(i+1)]
df['%dBin'%(i+1)] = np.digitize(df['%dSpreadWPolarity'%(i+1)],self.binDict[i+1])
df = df[10:]
df = df.iloc[::-1].reset_index(drop=True)
self.data = df
#finding match
self.bucket = []
self.genepool = []
for i in range(10):
self.bucket.append([i+1])
self.genepool.append(self.inversedGenes)
for i in range(9):
self.bucketcopy = self.bucket
self.genepoolcopy = self.genepool
self.bucket = []
self.genepool = []
for g,p in zip(self.bucketcopy,self.genepoolcopy):
self.evaluate(g,p)
self.reverseBucket()
return self.reversedBucket
def evaluate(self,g,p):
if(len(g) %2 != 0):
self.evaluate_odd(g,p)
else:
self.evaluate_even(g,p)
def evaluate_odd(self,genecopy,poolcopy):
tempgene = genecopy
index = 0
latest = tempgene[-1]
for i in range(len(tempgene) - 1):
if(i %2 == 0):
index += tempgene[i]
tempgene.append(self.data.iloc[index]['%dBin'%(latest)])
self.bucket.append(tempgene)
self.genepool.append(poolcopy)
def evaluate_even(self,genecopy,poolcopy):
tempgene = genecopy
pool = []
for ge in poolcopy:
flag = True
for i in range(len(tempgene)):
if(ge[i] != tempgene[i]):
flag = False
if flag:
pool.append(ge)
if ge[0:len(tempgene)+1] in self.bucket:
pass
else:
newgene = ge[0:len(tempgene)+1]
self.bucket.append(newgene)
self.genepool.append(pool)
def reverseBucket(self):
reversedBucket = []
for b in self.bucket:
buc = []
buc.append(b[8])
buc.append(b[9])
buc.append(b[6])
buc.append(b[7])
buc.append(b[4])
buc.append(b[5])
buc.append(b[2])
buc.append(b[3])
buc.append(b[0])
buc.append(b[1])
reversedBucket.append(repr(buc))
self.reversedBucket = reversedBucket<file_sep>/OrderRunner.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 25 18:08:05 2019
@author: james
"""
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
from ib.ext.EClientSocket import EClientSocket
import ib.ext.EWrapper # receiving msg
import ib.ext.EClientSocket # send msg
from ib.ext.ScannerSubscription import ScannerSubscription
from datetime import datetime
import time
import pandas as pd
import threading
import numpy as np
from IBWrapper import IBWrapper, contract
class orderRunner():
def __init__(self,datadecoder):
self.accountName = "asd781821"
self.callback = IBWrapper()
self.tws = EClientSocket(self.callback)
self.host = ""
self.port = 4003
self.clientId = 9
self.tws.eConnect(self.host, self.port, self.clientId)
self.dd = datadecoder
self.create = contract()
self.callback.initiate_variables()
self.callback.initiate_variables()
self.tws.reqAccountSummary(9,'All','TotalCashValue')
self.filedf =datadecoder.usabledf
self.datadecoder = datadecoder
def create_order(self,order_type, quantity, action):
"""Create an Order object (Market/Limit) to go long/short.
order_type - 'MKT', 'LMT' for Market or Limit orders
quantity - Integral number of assets to order
action - 'BUY' or 'SELL'"""
order = Order()
order.m_orderType = order_type
order.m_totalQuantity = quantity
order.m_action = action
return order
def buy(self,contract_Details):
self.tws.reqIds(-1)
oid = self.callback.next_ValidId
order = self.create_order('MKT', 300000, 'BUY')
self.tws.placeOrder(oid, contract_Details, order)
time.sleep(2)
print('|==========执行触发=================|')
print('|执行时期:%s|'%datetime.now())
print('|操作: BUY |')
print('|执行前总额:%s'%self.callback.account_Summary[-1][3])
print('|===================================|')
self.tws.reqIds(-1)
time.sleep(420)
oid = self.callback.next_ValidId
order = self.create_order('MKT', 300000, 'SELL')
self.tws.placeOrder(oid, contract_Details, order)
self.tws.reqIds(-1)
time.sleep(2)
print('|==========结束执行触发=============|')
print('|执行时期:%s|'%datetime.now())
print('|操作: BUY-FINISH |')
print('|执行后总额:%s |'%self.callback.account_Summary[-1][3])
print('|===================================|')
def sell(self,contract_Details):
self.tws.reqIds(-1)
oid = self.callback.next_ValidId
order = self.create_order('MKT', 300000, 'SELL')
self.tws.placeOrder(oid, contract_Details, order)
time.sleep(2)
print('|==========执行触发=================|')
print('|执行时期:%s|'%datetime.now())
print('|操作: SELL |')
print('|执行前总额:%s |'%self.callback.account_Summary[-1][3])
print('|===================================|')
self.tws.reqIds(-1)
time.sleep(420)
oid = self.callback.next_ValidId
order = self.create_order('MKT', 300000, 'BUY')
self.tws.placeOrder(oid, contract_Details, order)
print('sell order finished')
self.tws.reqIds(-1)
time.sleep(2)
print('|==========结束执行触发=============|')
print('|执行时期:%s|'%datetime.now())
print('|操作: SELL-FINISH |')
print('|执行后总额:%s |'%self.callback.account_Summary[-1][3])
print('|===================================|')
self.globalid = oid
def run(self):
tickerId = 9010
while(1):
contract_Details = self.create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
'''self.tws.reqCurrentTime()
time.sleep(1)
ts = self.callback.current_Time
data_endtime = datetime.utcfromtimestamp(ts).strftime('%Y%m%d %H:%M:%S')'''
tickerId += 1
self.tws.reqHistoricalData(tickerId = tickerId,
contract = contract_Details,
endDateTime = '',
durationStr="1 D",
barSizeSetting = "1 min",
whatToShow = "BID",
useRTH = 0,
formatDate = 1)
time.sleep(3)
data= pd.DataFrame(self.callback.historical_Data,
columns = ["reqId", "date", "open",
"high", "low", "close",
"volume", "count", "WAP",
"hasGaps"])[-500:-1]
self.dd.findMatch(data)
for b in self.dd.reversedBucket:
print('|=============================================|')
print('|检测到基因:%s|'%b)
print('|=============================================|')
if(self.filedf.index.contains(b)):
tempdf = self.filedf.loc[b]
if(tempdf['r7mean'] > 0):
threading.Thread(target=self.buy,args = [contract_Details]).start()
else:
threading.Thread(target=self.sell,args = [contract_Details]).start()
time.sleep(60)
def dc(self):
self.tws.eDisconnect()<file_sep>/datadecoder.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 20 15:13:59 2019
@author: james
"""
import pandas as pd
import quickEngine as qe
import ast
import numpy as np
class DataDecoder:
def __init__(self):
self.evaluation_method_4()
def evaluation_method_4(self):
#First step is to get lowest 30% for all r1
self.filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
self.filedf['r7-r2'] = self.filedf['r7mean'] - self.filedf['r2mean']
self.filedf['r7-r2samesign'] = self.filedf['r2mean'] * self.filedf['r7-r2'] > 0
#for those that are of the same sign, take the highest
self.filedf.sort_values('r7-r2',inplace = True,ascending=False)
upper = self.filedf.head(int(len(self.filedf)*0.4))
upperdiffsign = upper[upper['r7-r2samesign'] == False]
uppersamesign = upper[upper['r7-r2samesign'] == True]
lower = self.filedf.tail(int(len(self.filedf)*0.4))
lowersamesign = lower[lower['r7-r2samesign'] == True]
lowerdiffsign = lower[lower['r7-r2samesign'] == False]
diffsigntemp = pd.concat([upperdiffsign,lowerdiffsign])
samesigntemp = pd.concat([uppersamesign,lowersamesign])
diffsigntemp['r7divr2'] = (diffsigntemp['r7-r2'])/ abs(diffsigntemp['r2mean'])
samesigntemp['r7divr2'] = (samesigntemp['r7-r2']) / samesigntemp['r2mean']
samesigntemp.sort_values('r7divr2',inplace = True,ascending=False)
diffsigntemp.sort_values('r7divr2',inplace = True,ascending=False)
#take 20% from them
samesigntemp = samesigntemp.head(int(len(samesigntemp)*0.2))
diffsigntemp = diffsigntemp.head(int(len(diffsigntemp)*0.2))
temp = pd.concat([samesigntemp,diffsigntemp])
temp['r7-r2viable'] = temp['r7-r2']*(temp['r7posrate']-temp['r7negrate'])
temp.sort_values('r7-r2viable',inplace = True,ascending=False)
temp = temp.head(int(len(temp) * 0.3))
self.usabledf = temp
genes = temp.index.tolist()
pool_genes = []
for x in genes:
pool_genes.append(ast.literal_eval(x))
self.genes = pool_genes
df = pd.read_csv('df.csv')
_, self.binDict = qe.makeDf(df)
self.inverseGenes()
#Only aim for those strategy that has success rate of more than 80%, take r6 instead of r5
def evaluation_method_3(self):
self.filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
self.filedf.sort_values('r6posrate',inplace = True,ascending=False)
#take by posrate and negrate
upper = self.filedf[self.filedf['r6posrate'] >= 0.8]
upper = upper[upper['total_hits'] >= 10]
lower = self.filedf[self.filedf['r6negrate'] >= 0.8]
lower = lower[lower['total_hits'] >= 10]
temp = pd.concat([upper,lower])
#70% by viability
temp['r6difference'] = temp['r6posrate'] - temp['r6negrate']
temp['r6viable'] = temp['r6difference'] * temp['r6mean']
temp = temp[temp['r6viable'] > 0]
self.usabledf = temp
genes = temp.index.tolist()
pool_genes = []
for x in genes:
pool_genes.append(ast.literal_eval(x))
self.genes = pool_genes
df = pd.read_csv('df.csv')
_, self.binDict = qe.makeDf(df)
self.inverseGenes()
#1. rank by frequency, take 50%
def evaluation_method_2(self):
self.filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
self.filedf.sort_values('total_hits',inplace = True,ascending=False)
#take the upper 50%
temp = self.filedf.head(int(len(self.filedf)*0.5))
#take 50% by mean
temp.sort_values('r5mean',inplace = True,ascending=False)
how_many_to_take = int(len(self.filedf) * 0.25)
temp = pd.concat([temp.head(how_many_to_take),temp.tail(how_many_to_take)])
#70% by viability
temp['r5difference'] = temp['r5posrate'] - temp['r5negrate']
temp['r5viable'] = temp['r5difference'] * temp['r5mean']
temp.sort_values('r5viable',inplace = True,ascending=False)
temp = temp.head(int(len(temp) * 0.3))
self.usabledf = temp
genes = temp.index.tolist()
pool_genes = []
for x in genes:
pool_genes.append(ast.literal_eval(x))
self.genes = pool_genes
df = pd.read_csv('df.csv')
_, self.binDict = qe.makeDf(df)
self.inverseGenes()
#This is a expectation bound method
def evaluation_method_1(self):
self.filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
self.filedf.sort_values('r5mean',inplace = True,ascending=False)
#take highest and lowest 30% return
how_many_to_take = int(len(self.filedf)*0.3)
temp = pd.concat([self.filedf.head(how_many_to_take),self.filedf.tail(how_many_to_take)])
temp['r5difference'] = temp['r5posrate'] - temp['r5negrate']
temp['r5viable'] = temp['r5difference'] * temp['r5mean']
temp = temp[temp['r5viable'] > 0]
temp.sort_values('total_hits',inplace=True,ascending=False)
temp = temp.tail(int(len(temp)*0.8))
temp.sort_values('r5mean',inplace=True,ascending=False)
temp['r5meanabs'] = abs(temp['r5mean'])
temp.sort_values('r5meanabs',inplace=True,ascending=False)
temp = temp[temp['total_hits'] > 10]
self.usabledf = temp
genes = temp.index.tolist()
pool_genes = []
for x in genes:
pool_genes.append(ast.literal_eval(x))
self.genes = pool_genes
df = pd.read_csv('df.csv')
_, self.binDict = qe.makeDf(df)
self.inverseGenes()
def inverseGenes(self):
poolgenes = self.genes
inversedGenes = []
for gene in poolgenes:
newgene = []
newgene.append(gene[8])
newgene.append(gene[9])
newgene.append(gene[6])
newgene.append(gene[7])
newgene.append(gene[4])
newgene.append(gene[5])
newgene.append(gene[2])
newgene.append(gene[3])
newgene.append(gene[0])
newgene.append(gene[1])
inversedGenes.append(newgene)
self.inversedGenes = inversedGenes
self.genes = []
#Get raw data downloaded from ibkr,return 1 for buy order, 0 for sell order
def findMatch(self,df):
for i in range(20):
df['r%d'%(i+1)] = df['close'].pct_change(i+1).shift(-(i+1))
for i in range(10):
#df['%dbHigh'%(i+1)] = df['High'].rolling(i+1).max()
#df['%dbLow'%(i+1)] = df['Low'].rolling(i+1).min()
#Calculate i bar spread
#df['%dSpread'%(i+1)] = df['%dbHigh'%(i+1)] - df['%dbLow'%(i+1)]
df['Close+%d'%(i+1)] = df['close'].shift(i+1)
df['%dSpreadWPolarity'%(i+1)] = df['close'] - df['Close+%d'%(i+1)]
df['%dBin'%(i+1)] = np.digitize(df['%dSpreadWPolarity'%(i+1)],self.binDict[i+1])
df = df[10:]
df = df.iloc[::-1].reset_index(drop=True)
self.data = df
#finding match
self.bucket = []
self.genepool = []
for i in range(10):
self.bucket.append([i+1])
self.genepool.append(self.inversedGenes)
for i in range(9):
self.bucketcopy = self.bucket
self.genepoolcopy = self.genepool
self.bucket = []
self.genepool = []
for g,p in zip(self.bucketcopy,self.genepoolcopy):
self.evaluate(g,p)
self.reverseBucket()
return self.reversedBucket
def evaluate(self,g,p):
if(len(g) %2 != 0):
self.evaluate_odd(g,p)
else:
self.evaluate_even(g,p)
def evaluate_odd(self,genecopy,poolcopy):
tempgene = genecopy
index = 0
latest = tempgene[-1]
for i in range(len(tempgene) - 1):
if(i %2 == 0):
index += tempgene[i]
tempgene.append(self.data.iloc[index]['%dBin'%(latest)])
self.bucket.append(tempgene)
self.genepool.append(poolcopy)
def evaluate_even(self,genecopy,poolcopy):
tempgene = genecopy
pool = []
for ge in poolcopy:
flag = True
for i in range(len(tempgene)):
if(ge[i] != tempgene[i]):
flag = False
if flag:
pool.append(ge)
if ge[0:len(tempgene)+1] in self.bucket:
pass
else:
newgene = ge[0:len(tempgene)+1]
self.bucket.append(newgene)
self.genepool.append(pool)
def reverseBucket(self):
reversedBucket = []
for b in self.bucket:
buc = []
buc.append(b[8])
buc.append(b[9])
buc.append(b[6])
buc.append(b[7])
buc.append(b[4])
buc.append(b[5])
buc.append(b[2])
buc.append(b[3])
buc.append(b[0])
buc.append(b[1])
reversedBucket.append(repr(buc))
self.reversedBucket = reversedBucket
'''
#Pass in realtime data, genes, and binDict, return genes that are matched.
def findMatch(df,genes,binDict):
for i in range(20):
df['r%d'%(i+1)] = df['close'].pct_change(i+1).shift(-(i+1))
for i in range(10):
#df['%dbHigh'%(i+1)] = df['High'].rolling(i+1).max()
#df['%dbLow'%(i+1)] = df['Low'].rolling(i+1).min()
#Calculate i bar spread
#df['%dSpread'%(i+1)] = df['%dbHigh'%(i+1)] - df['%dbLow'%(i+1)]
df['Close+%d'%(i+1)] = df['close'].shift(i+1)
df['%dSpreadWPolarity'%(i+1)] = df['close'] - df['Close+%d'%(i+1)]
df['%dBin'%(i+1)] = np.digitize(df['%dSpreadWPolarity'%(i+1)],binDict[i+1])
df = df[10:]
'''
'''
geneLocators = []
for gene in dd.inversedGenes:
locators = []
locators.append(0)
locators.append(gene[0]+locators[0])
locators.append(locators[1]+gene[2])
locators.append(locators[2]+gene[4])
locators.append(locators[3]+gene[6])
geneLocators.append(locators)
binLocators = []
for gene in dd.inversedGenes:
locators = []
locators.append(gene[0])
locators.append(gene[2])
locators.append(gene[4])
locators.append(gene[6])
locators.append(gene[8])
binLocators.append(locators)
bins = []
for (gene,bind) in zip(geneLocators,binLocators):
bin = []
for (index, binl) in zip(gene, bind):
bin.append(data.iloc[index]['%dBin'%binl])
bins.append(bin)
search = []
global globalflag
globalflag = True
def match_search(li,pool_genes):
global globalflag
if globalflag == True:
if(len(li) == 10):
search.append(li)
print('10')
return
if(len(pool_genes) == 0):
search.append('x')
print('zero')
return
print('not 10 not zero')
gene = li
latest = li[-1]
if(len(li)%2 != 0):
print('old search')
index = 0
for i in range(len(li) - 1):
if(i %2 == 0):
index += li[i]
print('gene before %s'%gene)
gene.append(data.iloc[index]['%dBin'%(latest)])
print('gene after %s'%gene)
pool = []
for ge in pool_genes:
flag = True
for i in range(len(gene)):
if(ge[i] != gene[i]):
flag = False
if flag:
pool.append(ge)
print('pool length %d'%len(pool))
if(len(pool) == 0):
globalflag = False;
match_search(gene,pool)
print('even search %s'%gene)
pool = pool_genes
geneappendix = []
for ge in pool:
geneappendix.append(ge[len(gene)])
geneappendix = list(set(geneappendix))
for dix in geneappendix:
gene.append(dix)
print('new gene even search %s'%(gene))
match_search(gene,pool)
def match_search(li,pool_genes):
gene = li
latest = li[-1]
if(len(pool_genes) == 0):
return
if(len(gene) % 2 != 0):
index = 0
for i in range(len(li) - 1):
if(i %2 == 0):
index += li[i]
print('gene before %s'%gene)
gene.append(data.iloc[index]['%dBin'%(latest)])
print('gene after %s'%gene)
pool = []
for ge in pool_genes:
flag = True
for i in range(len(gene)):
if(ge[i] != gene[i]):
flag = False
if flag:
pool.append(ge)
match_search(gene,pool)
if(len(gene) == 10):
return li[-2:]
if(len(pool_genes) == 0):
return
pool = pool_genes
geneappendix = []
for ge in pool:
geneappendix.append(ge[len(gene)])
geneappendix = list(set(geneappendix))
for dix in geneappendix:
gene.append(dix)
print('new gene even search %s'%(gene))
match_search(gene,pool)
gene.append(gene)
if(len(gene) % 2 != 0):
index = 0
for i in range(len(gene) - 1):
if(i %2 == 0):
index += gene[i]
gene.append(data.iloc[index]['%dBin'%(latest)])
bucket.append(gene)
#Take gene, return next gene or list of next genes
bucket = []
def get_bucket_depth():
lengthlist = []
for b in bucket:
lengthlist.append(len(b))
return max(lengthlist)
def append_to_bucket(gene):
latest = gene[-1]
tempgene = gene
if(len(tempgene) % 2 != 0):
index = 0
for i in range(len(tempgene) - 1):
if(i %2 == 0):
index += tempgene[i]
tempgene.append(data.iloc[index]['%dBin'%(latest)])
bucket.append(tempgene)
return
if(len(tempgene) %2 == 0):
for ge in pool_genes:
flag = True
for i in range(len(tempgene)):
if(ge[i] != tempgene[i]):
flag = False
if flag:
bucket.append(ge[0:len(tempgene)+1])
def bucket_search():
global bucket
maxlength = get_bucket_depth()
list_of_max_length = []
for b in bucket:
if(len(b) == maxlength):
list_of_max_length.append(b)
for l in list_of_max_length:
append_to_bucket(l)
b_set = set(tuple(x) for x in bucket)
bucket = [ list(x) for x in b_set ]
return
bucket = []
for i in range(10):
bucket.append([i+1])
depth = 0
bucketdepth = get_bucket_depth()
while(depth != bucketdepth):
depth = get_bucket_depth()
bucket_search()
bucketdepth = get_bucket_depth()
for b in bucket:
if(len(b) == maxlength):
list_of_max_length.append(b)
'''
'''
bucketcopy = bucket
genepoolcopy = genepool
bucket = []
genepool = []
for g,p in zip(bucketcopy,genepoolcopy):
evaluate(g,p)
def evaluate(g,p):
if(len(g) %2 != 0):
evaluate_odd(g,p)
else:
evaluate_even(g,p)
def evaluate_odd(genecopy,poolcopy):
tempgene = genecopy
index = 0
latest = tempgene[-1]
for i in range(len(tempgene) - 1):
if(i %2 == 0):
index += tempgene[i]
tempgene.append(data.iloc[index]['%dBin'%(latest)])
bucket.append(tempgene)
genepool.append(poolcopy)
def evaluate_even(genecopy,poolcopy):
tempgene = genecopy
pool = []
for ge in poolcopy:
flag = True
for i in range(len(tempgene)):
if(ge[i] != tempgene[i]):
flag = False
if flag:
pool.append(ge)
if ge[0:len(tempgene)+1] in bucket:
pass
else:
newgene = ge[0:len(tempgene)+1]
bucket.append(newgene)
genepool.append(pool)
for i in range(10):
bucket.append([i+1])
genepool.append(pool_genes)
'''<file_sep>/apitest.py
# -*- coding: utf-8 -*-
def error_handler(msg):
"""Handles the capturing of error messages"""
print ("Server Error: %s" % msg)
def reply_handler(msg):
"""Handles of server replies"""
print ("Server Response: %s, %s" % (msg.typeName, msg))
def create_contract(symbol, sec_type, exch, prim_exch, curr):
"""Create a Contract object defining what will
be purchased, at which exchange and in which currency.
symbol - The ticker symbol for the contract
sec_type - The security type for the contract ('STK' is 'stock')
exch - The exchange to carry out the contract on
prim_exch - The primary exchange to carry out the contract on
curr - The currency in which to purchase the contract"""
contract = Contract()
contract.m_symbol = symbol
contract.m_secType = sec_type
contract.m_exchange = exch
contract.m_primaryExch = prim_exch
contract.m_currency = curr
return contract
def create_order(order_type, quantity, action):
"""Create an Order object (Market/Limit) to go long/short.
order_type - 'MKT', 'LMT' for Market or Limit orders
quantity - Integral number of assets to order
action - 'BUY' or 'SELL'"""
order = Order()
order.m_orderType = order_type
order.m_totalQuantity = quantity
order.m_action = action
return order
class TestWrapper(ib.ext.EWrapper):
pass
class TestClient(EClient):
def __init__(self, wrapper):
EClient.__init__(self, wrapper)
class TestApp(TestWrpper, TestClient):
def __init__(self):
TestWrapper.__init__(self)
TestClient.__init__(self, wrapper=self)
if __name__ == "__main__":
# Connect to the Trader Workstation (TWS) running on the
# usual port of 7496, with a clientId of 100
# (The clientId is chosen by us and we will need
# separate IDs for both the execution connection and
# market data connection)
conn = Connection.create(port=4002, clientId=100)
conn.connect()
# Assign the error handling function defined above
# to the TWS connection
conn.register(error_handler, 'Error')
# Assign all of the server reply messages to the
# reply_handler function defined above
conn.registerAll(reply_handler)
# Create an order ID which is 'global' for this session. This
# will need incrementing once new orders are submitted.
order_id = 1889
# Create a contract in GOOG stock via SMART order routing
contract = create_contract('EUR', 'CASH', 'IDEALPRO', 'IDEALPRO', 'USD')
# Go long 100 shares of Google
order = create_order('MKT', 100000, 'SELL')
# Use the connection to the send the order to IB
tws.placeOrder(order_id, contract, order)
# Disconnect from TWS
conn.disconnect()
from IBWrapper import IBWrapper, contract
accountName = "asd781820"
callback = IBWrapper()
tws = EClientSocket(callback)
host = ""
port = 4002
clientId = 8
tws.eConnect(host, port, clientId)
create = contract()
callback.initiate_variables()
tws.reqAccountUpdates(1,accountName)
acc = pd.DataFrame(callback.update_AccountValue,
columns= ['key','value','currency','accountName'])[:3]
accport = pd.DataFrame(callback.update_Portfolio,
columns=['Contract ID','Currency',
'Expiry','Include Expired',
'Local Symbol','Multiplier',
'Primary Exchange','Right',
'Security Type','Strike',
'Symbol','Trading Class',
'Position','Market Price','Market Value',
'Average Cost', 'Unrealised PnL', 'Realised PnL',
'Account Name'])[:3]
dat = pd.DataFrame(callback.position,
columns=['Account','Contract ID','Currency','Exchange','Expiry',
'Include Expired','Local Symbol','Multiplier','Right',
'Security Type','Strike','Symbol','Trading Class',
'Position','Average Cost'])
dat[dat["Account"] == accountName]
tws.reqIds(1)
order_id = callback.next_ValidId + 1
contract_info = create.create_contract("GOOG", "STK", "SMART", "USD")
order_info = create.create_order(accountName, "MKT", 250, "BUY")
tws.placeOrder(order_id, contract_info, order_info)
orders = pd.DataFrame(callback.order_Status,
columns = ['orderId', 'status', 'filled', 'remaining', 'avgFillPrice',
'permId', 'parentId', 'lastFillPrice', 'clientId', 'whyHeld'])
callback.open_Order[:1]
tws.cancelOrder(order_id)
contract_info = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
tickedId = 1002
tws.reqMktData(tickedId, contract_info, "", False)
tick_data = pd.DataFrame(callback.tick_Price,
columns = ['tickerId', 'field', 'price', 'canAutoExecute'])
tick_type = {0 : "BID SIZE",
1 : "BID PRICE",
2 : "ASK PRICE",
3 : "ASK SIZE",
4 : "LAST PRICE",
5 : "LAST SIZE",
6 : "HIGH",
7 : "LOW",
8 : "VOLUME",
9 : "CLOSE PRICE",
10 : "BID OPTION COMPUTATION",
11 : "ASK OPTION COMPUTATION",
12 : "LAST OPTION COMPUTATION",
13 : "MODEL OPTION COMPUTATION",
14 : "OPEN_TICK",
15 : "LOW 13 WEEK",
16 : "HIGH 13 WEEK",
17 : "LOW 26 WEEK",
18 : "HIGH 26 WEEK",
19 : "LOW 52 WEEK",
20 : "HIGH 52 WEEK",
21 : "AVG VOLUME",
22 : "OPEN INTEREST",
23 : "OPTION HISTORICAL VOL",
24 : "OPTION IMPLIED VOL",
27 : "OPTION CALL OPEN INTEREST",
28 : "OPTION PUT OPEN INTEREST",
29 : "OPTION CALL VOLUME"}
tick_data["Type"] = tick_data["field"].map(tick_type)
tick_data[-10:]
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
from ib.ext.EClientSocket import EClientSocket
import ib.ext.EWrapper # receiving msg
import ib.ext.EClientSocket # send msg
from ib.ext.ScannerSubscription import ScannerSubscription
from datetime import datetime
import time
import threading
import datadecoder
dd = datadecoder.DataDecoder()
import numpy as np
from IBWrapper import IBWrapper, contract
accountName = "asd781820"
callback = IBWrapper()
tws = EClientSocket(callback)
host = ""
port = 4002
clientId = 9
tws.eConnect(host, port, clientId)
create = contract()
callback.initiate_variables()
tws.reqAccountSummary(8,'All','TotalCashValue')
callback.accountSummary()
globalid = 138756199
def buy(globalid,contract_Details):
oid = globalid
order = create_order('MKT', 100000, 'BUY')
tws.placeOrder(oid, contract_Details, order)
time.sleep(2)
print('--------Account value before buy------')
print(callback.account_Summary[-1][3])
time.sleep(300)
oid += 1
order = create_order('MKT', 100000, 'SELL')
tws.placeOrder(oid, contract_Details, order)
print('buy order finished')
time.sleep(2)
print('-------Account value after buy--------')
print(callback.account_Summary[-1][3])
oid += 1
globalid = oid
def sell(globalid,contract_Details):
oid = globalid
order = create_order('MKT', 100000, 'SELL')
tws.placeOrder(oid, contract_Details, order)
time.sleep(2)
print('--------Account value before sell------')
print(callback.account_Summary[-1][3])
time.sleep(300)
oid += 1
order = create_order('MKT', 100000, 'BUY')
tws.placeOrder(oid, contract_Details, order)
print('sell order finished')
time.sleep(2)
print('-------Account value after sell--------')
print(callback.account_Summary[-1][3])
oid += 1
globalid = oid
while(1):
contract_Details = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
tws.reqCurrentTime()
time.sleep(1)
ts = callback.current_Time
data_endtime = datetime.utcfromtimestamp(ts).strftime('%Y%m%d %H:%M:%S')
tickerId = 9010
tws.reqHistoricalData(tickerId = tickerId,
contract = contract_Details,
endDateTime = data_endtime,
durationStr="1 D",
barSizeSetting = "1 min",
whatToShow = "BID",
useRTH = 0,
formatDate = 1)
time.sleep(3)
data= pd.DataFrame(callback.historical_Data,
columns = ["reqId", "date", "open",
"high", "low", "close",
"volume", "count", "WAP",
"hasGaps"])[-500:-1]
dd.findMatch(data)
for b in dd.reversedBucket:
print('b is %s'%b)
if(filedf.index.contains(b)):
tempdf = filedf.loc[b]
globalid += 2
print(tempdf)
if(tempdf['r5mean'] > 0):
threading.Thread(target=buy,args = [globalid,contract_Details]).start()
print('buy order executed')
else:
threading.Thread(target=sell,args = [globalid,contract_Details]).start()
print('sell order executed')
time.sleep(60)
contract_Details = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
tws.reqCurrentTime()
time.sleep(1)
ts = callback.current_Time
data_endtime = datetime.utcfromtimestamp(ts).strftime('%Y%m%d %H:%M:%S')
tickerId = 9009
tws.reqHistoricalData(tickerId = tickerId,
contract = contract_Details,
endDateTime = data_endtime,
durationStr="1 D",
barSizeSetting = "1 min",
whatToShow = "BID",
useRTH = 0,
formatDate = 1)
time.sleep(3)
data= pd.DataFrame(callback.historical_Data,
columns = ["reqId", "date", "open",
"high", "low", "close",
"volume", "count", "WAP",
"hasGaps"])[-500:-1]<file_sep>/README.md
# GeneticTrader
genetic algorithm for forex high frequency trading
# HowItWorks - General Ideas
Random hypothetical price movement is generated in the format [duration,pricechange(bin)] egg. [5,10,3,2] means for the past 5 days the price change falls in bin 10, and for 3 days ahead of the past 5 days, the price change falls in bin 2
Below is an example of what 100 randomly generated genes looks like:
============================Codes for drawing the below example===========
```python
import geneGenerator
import dnaengine
#Here 5 means totaly number of [duration, price_change] pairs, we give it 5 pairs
#10 means maximum lookback period for each block
#20 means bins for each lookback period
generator = geneGenerator.geneGenerator(5,10,20)
genes = generator.generateMany(100)
engine = dnaengine.Engine()
df = pd.read_csv('df.csv')
engine.makeDf(df)
engine.draw100Dna(genes)
```

# Monte-Carlo
Every hypothetical price movement is then tested for best stop-limit strategy using monte-carlo.
<file_sep>/quickEngineTest.py
# -*- coding: utf-8 -*-
import pandas as pd
import quickEngine
import numpy as np
import geneGenerator
from multiprocessing import Process, Manager, Pool
from concurrent.futures import ProcessPoolExecutor
import numpy as np
import time
import multiprocessing
import multiprocessing.pool
df = pd.read_csv('df.csv')
column_index_value_dict, binDict = quickEngine.makeDf(df)
generator = geneGenerator.geneGenerator(5,10,20)
'''
genes = generator.generateMany(100)
factsheetdict = evaluategenes(genes,column_index_value_dict)
factsheetdf = pd.DataFrame.from_dict(factsheetdict,orient='index',columns=['hits_per_day','total_hits','r2mean','r2posrate','r2negrate','r3mean','r3posrate','r3negrate','r4mean','r4posrate','r4negrate','r5mean','r5posrate','r5negrate','r6mean','r6posrate','r6negrate','r7mean','r7posrate','r7negrate','r8mean','r8posrate','r8negrate','r9mean','r9posrate','r9negrate','r10mean','r10posrate','r10negrate'])
genes = generator.generateMany(1000)
factsheetdict = evaluategenes(genes,column_index_value_dict)
factsheetdf = pd.DataFrame.from_dict(factsheetdict,orient='index',columns=['hits_per_day','total_hits','r2mean','r2posrate','r2negrate','r3mean','r3posrate','r3negrate','r4mean','r4posrate','r4negrate','r5mean','r5posrate','r5negrate','r6mean','r6posrate','r6negrate','r7mean','r7posrate','r7negrate','r8mean','r8posrate','r8negrate','r9mean','r9posrate','r9negrate','r10mean','r10posrate','r10negrate'])
factsheetdf.drop_duplicates(inplace = True)
'''
def evaluate200(i):
genes = generator.generateMany(200)
factsheetdict = quickEngine.evaluategenes(genes,column_index_value_dict,binDict,df)
mdict.update(factsheetdict)
'''if(i % 200 == 0):
factsheetdict = dict(mdict)
factsheetdf = pd.DataFrame.from_dict(factsheetdict,orient='index',columns=['hits_per_day','total_hits','r2mean','r2posrate','r2negrate','r3mean','r3posrate','r3negrate','r4mean','r4posrate','r4negrate','r5mean','r5posrate','r5negrate','r6mean','r6posrate','r6negrate','r7mean','r7posrate','r7negrate','r8mean','r8posrate','r8negrate','r9mean','r9posrate','r9negrate','r10mean','r10posrate','r10negrate'])
filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
finaldf = pd.concat([filedf,factsheetdf])
finaldf.drop_duplicates(inplace = True)
finaldf.to_csv('factsheetdf.csv')
m = Manager()
mdict = m.dict()'''
'''
for i in range(200):
evaluate200()
if __name__ == '__main__':
jobs = []
while(1):
for i in range(8):
p = Process(target=evaluate200)
jobs.append(p)
p.start()
time.sleep(500)'''
class NoDaemonProcess(multiprocessing.Process):
# make 'daemon' attribute always return False
def _get_daemon(self):
return False
def _set_daemon(self, value):
pass
daemon = property(_get_daemon, _set_daemon)
class MyPool(multiprocessing.pool.Pool):
Process = NoDaemonProcess
while(1):
m = Manager()
mdict = m.dict()
pool = MyPool(processes=6)
pool.map(evaluate200,[i for i in range(6)])
print('finished')
factsheetdict = dict(mdict)
factsheetdf = pd.DataFrame.from_dict(factsheetdict,orient='index',columns=['hits_per_day','total_hits','r2mean','r2posrate','r2negrate','r3mean','r3posrate','r3negrate','r4mean','r4posrate','r4negrate','r5mean','r5posrate','r5negrate','r6mean','r6posrate','r6negrate','r7mean','r7posrate','r7negrate','r8mean','r8posrate','r8negrate','r9mean','r9posrate','r9negrate','r10mean','r10posrate','r10negrate'])
filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
finaldf = pd.concat([filedf,factsheetdf])
finaldf.drop_duplicates(inplace = True)
finaldf.to_csv('factsheetdf.csv')
print('1')
pool.close()
pool.join()
print('2')
del factsheetdict
del factsheetdf
del finaldf
print('3')
time.sleep(30)<file_sep>/demoib.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 19 17:39:31 2019
@author: james
"""
import pandas as pd
import numpy as np
import datadecoder
#sorting filedf get usable df
#sorting priority.
#1. mean 0.6
#2. no.hits 0.8
#3. rate,difference 0.5
filedf = pd.read_csv('factsheetdf.csv',index_col='Unnamed: 0')
filedf.sort_values('r5mean',inplace = True,ascending=False)
#take highest and lowest 30% return
how_many_to_take = int(len(filedf)*0.3)
temp = pd.concat([filedf.head(how_many_to_take),filedf.tail(how_many_to_take)])
temp['r5difference'] = temp['r5posrate'] - temp['r5negrate']
temp['r5viable'] = temp['r5difference'] * temp['r5mean']
temp = temp[temp['r5viable'] > 0]
temp.sort_values('total_hits',inplace=True,ascending=False)
temp = temp.tail(int(len(temp)*0.8))
temp.sort_values('r5mean',inplace=True,ascending=False)
temp['r5meanabs'] = abs(temp['r5mean'])
temp.sort_values('r5meanabs',inplace=True,ascending=False)
temp = temp[temp['total_hits'] > 10]
genes = temp.index.tolist()
import ast
pool_genes = []
for x in genes:
pool_genes.append(ast.literal_eval(x))
#DATAFRAME RECEIVED AS data
def makedataDf(df):
for i in range(20):
df['r%d'%(i+1)] = df['close'].pct_change(i+1).shift(-(i+1))
for i in range(10):
#df['%dbHigh'%(i+1)] = df['High'].rolling(i+1).max()
#df['%dbLow'%(i+1)] = df['Low'].rolling(i+1).min()
#Calculate i bar spread
#df['%dSpread'%(i+1)] = df['%dbHigh'%(i+1)] - df['%dbLow'%(i+1)]
df['Close+%d'%(i+1)] = df['close'].shift(i+1)
df['%dSpreadWPolarity'%(i+1)] = df['close'] - df['Close+%d'%(i+1)]
df = df[10:]
#inverse data
df = df.iloc[::-1].reset_index(drop=True)
#inverse genes
inversedGenes = []
for gene in pool_genes:
newgene = []
newgene.append(gene[8])
newgene.append(gene[9])
newgene.append(gene[6])
newgene.append(gene[7])
newgene.append(gene[4])
newgene.append(gene[5])
newgene.append(gene[2])
newgene.append(gene[3])
newgene.append(gene[0])
newgene.append(gene[1])
inversedGenes.append(newgene)
<file_sep>/beta_test.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 00:59:32 2019
@author: james
"""
import orderRunnerBeta as ob
import beta_decoder as bdd
bd = bdd.BetaDecoder()
Orb = ob.orderRunnerBeta(bd)
time.sleep(1)
Orb.run()
#250411 15:33 13.March
#250409 17:13 13.March
#250214 19:23 13.March
#250276 20:08 13.March
#250345 22:23 13.March
#248281.80
#248840 23:50 17.March
#248305 14:12
#248,130 sharpe 1.0 with trailing stop 0.00008
#247,767 sharpe 1.6 with trailling stop 0.00010<file_sep>/dnaengine.py
# -*- coding: utf-8 -*-
import numpy as np
import collections
import matplotlib.pyplot as plt
from tqdm import tqdm
import numpy as np
class Engine:
def __init__(self):
pass
def makeDf(self,df):
#first run the return from 1-20
for i in range(20):
df['r%d'%(i+1)] = df['Close'].pct_change(i+1).shift(-(i+1))
#Make 5 spread of different bar-size
for i in range(10):
df['%dbHigh'%(i+1)] = df['High'].rolling(i+1).max()
df['%dbLow'%(i+1)] = df['Low'].rolling(i+1).min()
#Calculate i bar spread
df['%dSpread'%(i+1)] = df['%dbHigh'%(i+1)] - df['%dbLow'%(i+1)]
df['Close+%d'%(i+1)] = df['Close'].shift(i+1)
df['%dSpreadWPolarity'%(i+1)] = df['Close'] - df['Close+%d'%(i+1)]
self.df = df[10:]
#Make bin for those spreads
self.binDict = {}
#replace 0.1% extreme value with their 0.5% extreme value percentile.
for i in range(10):
self.binDict[i+1] = self.makeBin(df['%dSpreadWPolarity'%(i+1)][5:].tolist());
def makeBin(self,data):
#bin of fixed size of 20
num_bins = 20
data = np.sort(data)
data_points_per_bin = len(data) // 20
bins = [data[_ * data_points_per_bin: (_+1)*data_points_per_bin] for _ in range(num_bins)]
binLevel = []
for l in bins:
binLevel.append(min(l))
binLevel.append(max(bins[-1]))
binLevel = np.array(binLevel)
binLevel.sort()
return binLevel
def drawDna(self, gene):
###need to be changed
dictTuples = []
x = []
y = []
for i in range(5):
x.append(gene[2*i])
y.append(gene[2*i+1])
for i in range(len(x)):
dictTuples.append((x[i],[self.binDict[x[i]][y[i]-1],self.binDict[x[i]][y[i]]]))
currentLine = ([0,0],[0,0])
for i in range(len(dictTuples)):
x1 = currentLine[0][1]
x2 = dictTuples[i][0] + currentLine[0][1]
y1 = currentLine[1][1]
y2 = dictTuples[i][1][1] + currentLine[1][1]
plt.plot([x1,x2],[y1,y2],'--', color='g', lw= 0.8)
currentLine[0][0] = x1
currentLine[0][1] = x2
currentLine[1][0] = y1
currentLine[1][1] = y2
currentLine = ([0,0],[0,0])
for i in range(len(dictTuples)):
x1 = currentLine[0][1]
x2 = dictTuples[i][0] + currentLine[0][1]
y1 = currentLine[1][1]
y2 = dictTuples[i][1][0] + currentLine[1][1]
plt.plot([x1,x2],[y1,y2],'--', color='r', lw= 0.8)
currentLine[0][0] = x1
currentLine[0][1] = x2
currentLine[1][0] = y1
currentLine[1][1] = y2
def draw100Dna(self, genes):
fig = plt.figure(figsize=(20,20))
fig.suptitle('price movement genes')
for i in range(100):
plt.subplot(10,10,i+1)
###need to be changed
gene = genes[i]
dictTuples = []
x = []
y = []
#needed attention
for i in range(5):
x.append(gene[2*i])
y.append(gene[2*i+1])
for i in range(len(x)):
dictTuples.append((x[i],[self.binDict[x[i]][y[i]-1],self.binDict[x[i]][y[i]]]))
currentLine = ([0,0],[0,0])
for i in range(len(dictTuples)):
x1 = currentLine[0][1]
x2 = dictTuples[i][0] + currentLine[0][1]
y1 = currentLine[1][1]
y2 = dictTuples[i][1][1] + currentLine[1][1]
plt.plot([x1,x2],[y1,y2],'--', color='g', lw= 0.8)
currentLine[0][0] = x1
currentLine[0][1] = x2
currentLine[1][0] = y1
currentLine[1][1] = y2
currentLine = ([0,0],[0,0])
for i in range(len(dictTuples)):
x1 = currentLine[0][1]
x2 = dictTuples[i][0] + currentLine[0][1]
y1 = currentLine[1][1]
y2 = dictTuples[i][1][0] + currentLine[1][1]
plt.plot([x1,x2],[y1,y2],'--', color='r', lw= 0.8)
currentLine[0][0] = x1
currentLine[0][1] = x2
currentLine[1][0] = y1
currentLine[1][1] = y2
plt.tight_layout()
def decode(self,gene):
tempdf = self.df
lengthgene = []
bingene = []
for i in range(int(len(gene)/2)):
lengthgene.append(gene[2*i])
bingene.append(gene[2*i + 1])
interval = 0
temporaldf = tempdf
for i in range(len(lengthgene) - 1):
tempindex = temporaldf.index + interval
temporaldf = tempdf.loc[tempindex]
temporaldf = temporaldf[temporaldf['%dSpreadWPolarity'%(lengthgene[i])] < self.binDict[lengthgene[i]][bingene[i]]]
temporaldf = temporaldf[temporaldf['%dSpreadWPolarity'%(lengthgene[i])] >= self.binDict[lengthgene[i]][bingene[i] - 1]]
interval = lengthgene[i + 1]
return self.valueMethod1(temporaldf)
#Pure expected value method.
#meta 0 : mean
#meta 1: polarity
#meta 2: size
def valueMethod1(self, temporaldf):
meta = []
meta.append(temporaldf['r2'].mean())
meta.append(len(temporaldf['r2']) / len(self.df) * 86400.0)
meta.append(sum(temporaldf['r2'] > 0) / len(temporaldf))
meta.append(len(temporaldf))
return meta
def evaluategenes(self, genes):
geneDict = {}
for gene in tqdm(genes):
geneDict[repr(gene)] = self.decode(gene)
sorted(geneDict.values())
return geneDict
###Things to improve###
#1. Dynamic bin size, more bins around data points with more density#
<file_sep>/geneGenerator.py
# -*- coding: utf-8 -*-
from random import randint
class geneGenerator:
def __init__(self,maxBlocks,maxLookback,bins):
self.maxBlocks = maxBlocks
self.maxLookback = maxLookback
self.bins = bins
#Now only generating fixed length gene
def generateOne(self):
gene = []
for i in range(maxBlocks):
maxLookback = self.maxLookback
gene.append(randint(1,maxLookback))
gene.append(randint(1,self.bins))
return gene
def generateMany(self, no):
genes = []
for i in range(no):
gene = []
for i in range(self.maxBlocks):
gene.append(randint(1,self.maxLookback))
gene.append(randint(1,self.bins))
genes.append(gene)
return genes<file_sep>/MarkovInterpreter.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 11 22:35:15 2019
@author: james
"""
<file_sep>/orderRunnerBeta.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 25 18:08:05 2019
@author: james
"""
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message
from ib.ext.EClientSocket import EClientSocket
import ib.ext.EWrapper # receiving msg
import ib.ext.EClientSocket # send msg
from ib.ext.ScannerSubscription import ScannerSubscription
import beta_quickEngine as bqe
from datetime import datetime
import time
import pandas as pd
import threading
import numpy as np
import schedule
import ast
from IBWrapper import IBWrapper, contract
import beta_quickEngine as bqe
class orderRunnerBeta:
def __init__(self,datadecoder):
self.accountName = "asd781820"
self.callback = IBWrapper()
self.tws = EClientSocket(self.callback)
self.host = ""
self.port = 4002
self.clientId = 8
self.tws.eConnect(self.host, self.port, self.clientId)
self.dd = datadecoder
self.create = contract()
self.callback.initiate_variables()
self.callback.initiate_variables()
self.tws.reqAccountSummary(8,'All','TotalCashValue')
self.filedf =datadecoder.usabledf
self.datadecoder = datadecoder
contract_Details = self.create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
tickerId = 10000
self.tws.reqRealTimeBars(tickerId,contract_Details,5,"MIDPOINT",0)
self.tickerId = 9010
self.df = pd.read_csv('df.csv')
self.RbinDict = bqe.makeRDf(self.df)
self.column_index_value_dict,self.binDict = bqe.makeDf(self.df)
def create_trailing_order(self,action,quantity,trailingPercent = 0.006):
order = Order()
order.m_orderType = "TRAIL"
order.m_totalQuantity = quantity
order.m_trailingPercent = trailingPercent
order.m_action = action
return order
def create_order(self,order_type,quantity, action):
"""Create an Order object (Market/Limit) to go long/short.
order_type - 'MKT', 'LMT' for Market or Limit orders
quantity - Integral number of assets to order
action - 'BUY' or 'SELL'"""
order = Order()
order.m_orderType = order_type
order.m_totalQuantity = quantity
order.m_action = action
return order
def buy(self,contract_Details,limit,stop):
self.tws.reqIds(-1)
time.sleep(0.5)
oid = self.callback.next_ValidId
parent = Order()
parent.orderId = oid
parent.m_action = "BUY"
parent.m_orderType = "MKT"
parent.m_totalQuantity = 300000
parent.m_transmit = False
print('|==========执行触发=================|')
print('|执行时期:%s|'%datetime.now())
print('|操作: BUY |')
print('|执行前总额:%s'%self.callback.account_Summary[-1][3])
print('|===================================|')
self.tws.reqIds(-1)
takeProfit = Order()
takeProfit.orderId = parent.orderId + 1
takeProfit.m_action = "SELL"
takeProfit.m_orderType = "LMT"
takeProfit.m_totalQuantity = 300000
takeProfit.m_lmtPrice = limit
takeProfit.m_parentId = oid
takeProfit.m_transmit = False
stopLoss = Order()
stopLoss.orderId = parent.orderId + 2
stopLoss.m_action = "SELL"
stopLoss.m_orderType = "STP"
#Stop trigger price
stopLoss.m_auxPrice = stop
stopLoss.m_totalQuantity = 300000
stopLoss.m_parentId = oid
stopLoss.m_transmit = True
bracketOrder = [parent, takeProfit, stopLoss]
for o in bracketOrder:
self.tws.placeOrder(o.orderId, contract_Details, o)
self.tws.reqIds(-1)
time.sleep(1)
time.sleep(2)
def sell(self,contract_Details,limit,stop):
self.tws.reqIds(-1)
time.sleep(0.5)
oid = self.callback.next_ValidId
parent = Order()
parent.orderId = oid
parent.m_action = "SELL"
parent.m_orderType = "MKT"
parent.m_totalQuantity = 300000
parent.m_transmit = False
print('|==========执行触发=================|')
print('|执行时期:%s|'%datetime.now())
print('|操作: BUY |')
print('|执行前总额:%s'%self.callback.account_Summary[-1][3])
print('|===================================|')
self.tws.reqIds(-1)
takeProfit = Order()
takeProfit.orderId = parent.orderId + 1
takeProfit.m_action = "BUY"
takeProfit.m_orderType = "LMT"
takeProfit.m_totalQuantity = 300000
takeProfit.m_lmtPrice = limit
takeProfit.m_parentId = oid
takeProfit.m_transmit = False
stopLoss = Order()
stopLoss.orderId = parent.orderId + 2
stopLoss.m_action = "BUY"
stopLoss.m_orderType = "STP"
#Stop trigger price
stopLoss.m_auxPrice = stop
stopLoss.m_totalQuantity = 300000
stopLoss.m_parentId = oid
stopLoss.m_transmit = True
bracketOrder = [parent, takeProfit, stopLoss]
for o in bracketOrder:
self.tws.placeOrder(o.orderId, contract_Details, o)
self.tws.reqIds(-1)
time.sleep(1)
time.sleep(2)
def job(self):
contract_Details = self.create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
#self.tws.reqCurrentTime()
#time.sleep(1)
#ts = self.callback.current_Time
#data_endtime = datetime.utcfromtimestamp(ts).strftime('%Y%m%d %H:%M:%S')
self.tws.reqHistoricalData(tickerId = self.tickerId,
contract = contract_Details,
endDateTime = '',
durationStr="1 D",
barSizeSetting = "1 min",
whatToShow = "BID",
useRTH = 0,
formatDate = 1)
time.sleep(2)
data= pd.DataFrame(self.callback.historical_Data,
columns = ["reqId", "date", "open",
"high", "low", "close",
"volume", "count", "WAP",
"hasGaps"])[-500:-1]
self.dd.findMatch(data)
print(data)
print(datetime.now())
for b in self.dd.reversedBucket:
print('|=============================================|')
print('|检测到基因:%s|'%b)
print('|=============================================|')
if(self.filedf.index.contains(b)):
stra = bqe.get_sharpe_stra(b)
if(stra > 0):
threading.Thread(target=self.buy,args = [contract_Details,stra+1]).start()
elif(stra < 0):
threading.Thread(target=self.sell,args = [contract_Details,abs(stra-1)]).start()
self.tws.reqIds(-1)
print('|===================================|')
print('|总额:%s |'%self.callback.account_Summary[-1][3])
print('|===================================|')
def run(self):
print('|===========================================|')
print('|=======欢迎使用beta版本,祝您好运==========|')
print('|====新特性:1。止损定单 2。智能订单执行====|')
print('|===========================================|')
print('|===========================================|')
self.tickerId = 9010
while(1):
now = datetime.now()
if(now.second == 5):
contract_Details = self.create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
#self.tws.reqCurrentTime()
#time.sleep(1)
#ts = self.callback.current_Time
#data_endtime = datetime.utcfromtimestamp(ts).strftime('%Y%m%d %H:%M:%S')
self.tws.reqHistoricalData(tickerId = self.tickerId,
contract = contract_Details,
endDateTime = '',
durationStr="1 D",
barSizeSetting = "1 min",
whatToShow = "BID",
useRTH = 0,
formatDate = 1)
time.sleep(2)
data= pd.DataFrame(self.callback.historical_Data,
columns = ["reqId", "date", "open",
"high", "low", "close",
"volume", "count", "WAP",
"hasGaps"])[-500:-1]
self.dd.findMatch(data)
last_close = data.iloc[-1].close
for b in self.dd.reversedBucket:
if(self.filedf.index.contains(b)):
print('usable gene: %s'%b)
limit,stop,action = bqe.get_monte_carlo_stra(ast.literal_eval(b),self.column_index_value_dict,self.binDict,self.df,self.RbinDict)
if(action > 0):
limit_price = last_close + limit
stop_price = last_close - stop
threading.Thread(target=self.buy,args = [contract_Details,limit_price,stop_price]).start()
elif(action < 0):
limit_price = last_close - limit
stop_price = last_close + stop
threading.Thread(target=self.sell,args = [contract_Details,limit,stop]).start()
self.tws.reqIds(-1)
print('|===================================|')
print('|总额:%s |'%self.callback.account_Summary[-1][3])
print('|===================================|')
def dc(self):
self.tws.eDisconnect()<file_sep>/quickEngine.py
# -*- coding: utf-8 -*-
#quick version of dnaEngine, used in multiprocessing
import matplotlib.pyplot as plt
import bisect
from tqdm import tqdm
import numpy as np
#return a list containing bins, helper function for makeDf
def makeBin(data):
#bin of fixed size of 20
num_bins = 20
data = np.sort(data)
data_points_per_bin = len(data) // 20
bins = [data[_ * data_points_per_bin: (_+1)*data_points_per_bin] for _ in range(num_bins)]
binLevel = []
for l in bins:
binLevel.append(min(l))
binLevel.append(max(bins[-1]))
binLevel = np.array(binLevel)
binLevel.sort()
return binLevel
#return a meta dictionary of type dictionary, the key is column name from dataframe, and value is array of corresponding values
#the returned value should be sorted in ascending order and their is a corresponding index list
def makeDf(df):
for i in range(20):
df['r%d'%(i+1)] = df['Close'].pct_change(i+1).shift(-(i+1))
for i in range(10):
#df['%dbHigh'%(i+1)] = df['High'].rolling(i+1).max()
#df['%dbLow'%(i+1)] = df['Low'].rolling(i+1).min()
#Calculate i bar spread
#df['%dSpread'%(i+1)] = df['%dbHigh'%(i+1)] - df['%dbLow'%(i+1)]
df['Close+%d'%(i+1)] = df['Close'].shift(i+1)
df['%dSpreadWPolarity'%(i+1)] = df['Close'] - df['Close+%d'%(i+1)]
binDict = {}
for i in range(10):
binDict[i+1] = makeBin(df['%dSpreadWPolarity'%(i+1)][5:].tolist());
#Triming step ---Must go hand in hand
df = df[10:]
column_index_value_dict = {}
for i in range(10):
index_value_list = []
df = df.sort_values('%dSpreadWPolarity'%(i+1))
value_list = df['%dSpreadWPolarity'%(i+1)].tolist()
index_list = df.index.tolist()
index_value_list.append(index_list)
index_value_list.append(value_list)
column_index_value_dict['%dSpreadWPolarity'%(i+1)] = index_value_list
return column_index_value_dict, binDict
def draw100dna(genes,binDict):
fig = plt.figure(figsize=(20,20))
fig.suptitle('price movement genes')
for i in range(100):
plt.subplot(10,10,i+1)
###need to be changed
gene = genes[i]
dictTuples = []
x = []
y = []
for i in range(5):
x.append(gene[2*i])
y.append(gene[2*i+1])
for i in range(len(x)):
dictTuples.append((x[i],[binDict[x[i]][y[i]-1],binDict[x[i]][y[i]]]))
currentLine = ([0,0],[0,0])
for i in range(len(dictTuples)):
x1 = currentLine[0][1]
x2 = dictTuples[i][0] + currentLine[0][1]
y1 = currentLine[1][1]
y2 = dictTuples[i][1][1] + currentLine[1][1]
plt.plot([x1,x2],[y1,y2],'--', color='g', lw= 0.8)
currentLine[0][0] = x1
currentLine[0][1] = x2
currentLine[1][0] = y1
currentLine[1][1] = y2
currentLine = ([0,0],[0,0])
for i in range(len(dictTuples)):
x1 = currentLine[0][1]
x2 = dictTuples[i][0] + currentLine[0][1]
y1 = currentLine[1][1]
y2 = dictTuples[i][1][0] + currentLine[1][1]
plt.plot([x1,x2],[y1,y2],'--', color='r', lw= 0.8)
currentLine[0][0] = x1
currentLine[0][1] = x2
currentLine[1][0] = y1
currentLine[1][1] = y2
plt.tight_layout()
time.sleep(1)
def valueMethod1(temporaldf,df):
factlist = []
factlist.append(len(temporaldf) / len(df) * 61714.3)
factlist.append(len(temporaldf))
for i in range(9):
try:
factlist.append(temporaldf['r%d'%(i+2)].mean())
factlist.append(sum(temporaldf['r%d'%(i+2)] > 0) / len(temporaldf))
factlist.append(sum(temporaldf['r%d'%(i+2)] < 0) / len(temporaldf))
except ZeroDivisionError:
pass
return factlist
def evaluategenes(genes,column_index_value_dict,binDict,df):
geneDict = {}
for gene in tqdm(genes):
geneDict[repr(gene)] = decode(gene,column_index_value_dict,binDict,df)
return geneDict
def decode(gene,column_index_value_dict,binDict,df):
lengthgene = []
bingene = []
for i in range(int(len(gene)/2)):
lengthgene.append(gene[2*i])
bingene.append(gene[2*i + 1])
interval = 0
list_of_index = set(column_index_value_dict['1SpreadWPolarity'][0])
for i in range(len(lengthgene) - 1):
list_of_index = np.array(list(list_of_index))+interval
lowBound = bisect.bisect_left(column_index_value_dict['%dSpreadWPolarity'%(lengthgene[i])][1],binDict[lengthgene[i]][bingene[i] - 1])
upBound = bisect.bisect_right(column_index_value_dict['%dSpreadWPolarity'%(lengthgene[i])][1],binDict[lengthgene[i]][bingene[i]])
list_of_index = set(column_index_value_dict['%dSpreadWPolarity'%(lengthgene[i])][0][lowBound:upBound]).intersection(list_of_index)
interval = lengthgene[i + 1]
return valueMethod1(df.iloc[list(list_of_index)],df) | c4c251dc2e02e7e0b3094ac7a588b0de94dd97fd | [
"Markdown",
"Python"
]
| 18 | Python | 7818207/GeneticTrader | e2d426e1cf0f96c46338ba187d22d2c96273408e | 764d1dc1d8eb2a990b1c9568c3687f0e84120273 |
refs/heads/master | <file_sep># RustIntroWork
A repo for my HW and final project in PDX CS 410P Intro to Rust
<file_sep>// ALL CODE IN THIS DOCUMENT PROVIDED BY <NAME> FOR CS410P INTRO TO RUST COURSE - THANK YOU BART
//! Utility routines for toy RSA implementation.
//!
//! This code provides some functions useful for implementing
//! RSA with toy-sized (62-bit public) keys.
use std::convert::TryFrom;
#[cfg(test)]
// Largest prime less than 2**64.
// https://primes.utm.edu/lists/2small/0bit.html
const BIGM: u64 = u64::max_value() - 58;
/// Efficiently compute `x**y mod m`. Uses the standard
/// approach of repeated squaring with adjustments. `O(lg
/// y)` runtime.
///
/// # Panics
/// Will panic if `m` is 0.
pub fn modexp(x: u64, y: u64, m0: u64) -> u64 {
assert!(m0 > 0);
let m = m0 as u128;
let x = x as u128;
let y = y as u128;
if x == 0 {
return 0;
}
if y == 0 {
return 1 % m0;
}
let z = modexp(x as u64, (y / 2) as u64, m as u64) as u128;
let z = (z * z) % m;
let z = if y % 2 == 1 { (z * x) % m } else { z };
u64::try_from(z).unwrap()
}
#[test]
fn test_modexp() {
assert_eq!(0, modexp(BIGM - 2, BIGM - 1, 1));
assert_eq!(1, modexp(BIGM - 2, BIGM - 1, BIGM));
// https://practice.geeksforgeeks.org/problems/
// modular-exponentiation-for-large-numbers/0
let m = (u32::max_value() - 4) as u64;
assert_eq!(3976290898, modexp(m - 2, 65537, m));
assert_eq!(4, modexp(10, 9, 6));
assert_eq!(34, modexp(450, 768, 517));
}
/// Compute the greatest common divisor of two positive
/// numbers.
///
/// # Panics
/// Panic if either `n` or `m` is 0.
pub fn gcd(mut n: u64, mut m: u64) -> u64 {
assert!(n != 0 && m != 0);
while m != 0 {
if m < n {
std::mem::swap(&mut m, &mut n);
}
m %= n
}
n
}
#[test]
fn test_gcd() {
assert_eq!(1, gcd(100, 99));
assert_eq!(10, gcd(100, 110));
}
/// Compute the least common multiple of two positive
/// numbers.
pub fn lcm(n: u64, m: u64) -> u64 {
n * m / gcd(n, m)
}
#[test]
fn test_lcm() {
assert_eq!(180, lcm(36, 15));
}
/// Compute the modular inverse of `a` in the field mod `m`.
/// `m` must be greater than 0 and coprime with `a`.
// https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/
// XXX I'm working from pseudocode, so I'm not too interested
// in Clippy's naming critique.
#[allow(clippy::many_single_char_names)]
pub fn modinverse(a: u64, m: u64) -> u64 {
let mut a = a as i128;
let mut m = m as i128;
let m0 = m;
let mut y = 0;
let mut x = 1;
if m == 1 {
return 0;
}
while a > 1 {
// q is quotient.
let q = a / m;
let mut t = m;
// m is remainder now; process same as
// Euclid's Algorithm.
m = a % m;
a = t;
t = y;
// Update y and x.
y = x - q * y;
x = t;
}
// Make x positive.
if x < 0 {
x += m0;
}
// XXX This conversion should never fail, as `x` should
// always be positive and less than `m` at this point.
u64::try_from(x).unwrap()
}
#[test]
fn test_modinverse() {
let m0 = 0xffff_ffff_ffff_f000;
let mi = modinverse(m0, BIGM);
let m = modinverse(mi, BIGM);
assert_eq!(m0, m);
}
/// Produce a prime in the range `2**30`…`2**31` suitable
/// for use in RSA.
// Strategy: try random integers in-range forced to odd
// until one of them passes the `strong_check()` test.
pub fn rsa_prime() -> u32 {
use rand::Rng;
let mut rng = rand::thread_rng();
let max = u32::max_value();
let min = max / 2;
loop {
let p = rng.gen_range(min, max) | 1;
let bp = num_bigint::BigUint::from(p);
if glass_pumpkin::prime::strong_check(&bp) {
return p;
}
}
}<file_sep># <NAME>'s First Rust HW #
This rust program takes 3 arguments, and outputs the first raised to the second, modulo'd with the third.
I created this assignment from scratch with a few tips from the assignment description. I started with no understanding of Rust.
This assignment turned out very well because it was so simple. I believe that I have fully satisfied the requirements.
I tested my work by creating 3 example unit tests in rust which all pass correctly. I also manually tested by using incorrect (negative) values, strings, etc.
These would cause the program to fail if incorrect variables were passed in.<file_sep>#![allow(non_snake_case)]
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
//assert!(args.len() == 4, "You must enter 3 arguments on command line");
if args.len() != 4 {
error()
}
let x = args[1].parse::<u64>().unwrap();
let y = args[2].parse::<u64>().unwrap();
let m = args[3].parse::<u64>().unwrap();
//assert!(x >= 0, "X must be a positive number or 0");
//assert!(y >= 0, "Y must be a positive number or 0");
assert!(m >= 1, "Mod must be a positive number"); //Can't modulo with 0
//println!("x-y{} y-m{} m-x{}", x-y, y-m, m-x);
let fnoutput = modexp(x, y, m);
//println!("( {} ^ {} ) mod {} = {}", x, y, m, fnoutput);
println!("{}", fnoutput)
}
fn modexp(x: u64, y: u64, m: u64) -> u64 {
if x == 0 {
return 0;
}
if y == 0 {
return 1;
}
let mut z = modexp(x, y / 2, m);
z = (z * z) % m;
if y % 2 == 1 {
z = (z * x) % m;
}
z
}
//Error function from assignment description
fn error() -> ! {
eprintln!("modexp: usage: modexp <x> <y> <m> ex: (x^y)%m");
std::process::exit(1);
}
#[test]
fn assignment_supplied_example() {
assert!(modexp(2, 20, 17) == 16);
}
#[test]
fn another_example() {
assert!(modexp(5, 4, 3) == 1);
}
#[test]
fn last_test() {
assert!(modexp(12, 2, 44) == 12);
}
<file_sep>mod lib;
/// Fixed RSA encryption exponent.
pub const EXP: u64 = 65_537;
use std::convert::{TryInto};
/// Generate a pair of primes in the range `2**30..2**31`
/// suitable for RSA encryption with exponent
/// `EXP`. Warning: this routine has unbounded runtime; it
/// works by generate-and-test, generating pairs of primes
/// `p` `q` and testing that they satisfy `λ(pq) <= EXP` and
/// that `λ(pq)` has no common factors with `EXP`.
pub fn genkey() -> (u32, u32) {
let mut p = lib::rsa_prime() as u32;
let mut q = lib::rsa_prime() as u32;
while p == q || (EXP >= lib::lcm(p as u64 - 1, q as u64 - 1) && lib::gcd(EXP, lib::lcm(p as u64 - 1, q as u64 - 1)) != 1) {
p = lib::rsa_prime() as u32;
q = lib::rsa_prime() as u32;
}
println!("{} {}", p, q);
(p,q)
}
/// Encrypt the plaintext `msg` using the RSA public `key`
/// and return the ciphertext.
pub fn encrypt(key: u64, msg: u32) -> u64 {
let o = lib::modexp(msg as u64, EXP, key);
o
//let mut m = msg as u64;
//m = m.pow(EXP.try_into().unwrap()) % key;
//let o = u64::try_from(m).unwrap();
//m
}
/// Decrypt the cipertext `msg` using the RSA private `key`
/// and return the resulting plaintext.
pub fn decrypt(key: (u32, u32), msg: u64) -> u32 {
let l = lib::lcm((key.0 - 1) as u64, (key.1 - 1) as u64);
let d = lib::modinverse(EXP, l);
let m = lib::modexp(msg, d, key.0 as u64 * key.1 as u64);
let o: u32 = m.try_into().unwrap();
o
//let k = (key.0 * key.1) as u64;
//let d = 1 / (EXP % k);
//let o = msg.pow(d.try_into().unwrap()) % k;
//o as u32
}
fn main() {
let message: u32 = rand::random();
let (p, q) = genkey();
let key = p as u64 * q as u64;
let encrypted = encrypt(key, message);
let decrypted = decrypt((p, q), encrypted);
println!("Message before encryption: {}\nMessage after encryption: {}\nMessage after decryption:{}", message, encrypted, decrypted);
} | c95287e562e5d1e49264956530eafa3eaa685f4c | [
"Markdown",
"Rust"
]
| 5 | Markdown | jraypdx/RustIntroWork | 8e37f440dc1ed08b8b8cf035380e78cb957a29f7 | 78115d620fa7ee2b4d891c6dec71639ae2db546c |
refs/heads/main | <repo_name>YamileFernandez/Intro-component-with-sign-form<file_sep>/index.js
const formulario = document.getElementById('formulario');
const inputs = document.querySelectorAll('#formulario input');
const expresion = {
nombre : /^[a-zA-Z\s]{1,40}$/,
apellido : /^[a-zA-Z\s]{1,40}$/,
correo : /^[a-zA-Z0-9._]+@[a-zA-Z0-9]+\.[a-zA-Z]$/,
clave : /^.{4,16}$/
}
const validarformulario = (e) => {
switch (e.target.name) {
case "nombre":
if (expresion.nombre.test(e.target.value)){
document.getElementById('grupo__nombre').classList.remove('grupo__formulario-incorrecto');
document.getElementById('grupo__nombre').classList.add('grupo__formulario-correcto');
document.querySelector('#grupo__nombre .mensaje-error').classList.remove('mensaje-error-activo');
}else {
document.getElementById('grupo__nombre').classList.add('grupo__formulario-incorrecto');
document.getElementById('grupo__nombre').classList.remove('grupo__formulario-correcto');
document.querySelector('#grupo__nombre .mensaje-error').classList.add('mensaje-error-activo');
}
break;
case "apellido":
if (expresion.apellido.test(e.target.value)){
document.getElementById('grupo__apellido').classList.remove('grupo__formulario-incorrecto');
document.getElementById('grupo__apellido').classList.add('grupo__formulario-correcto');
document.querySelector('#grupo__apellido .mensaje-error').classList.remove('mensaje-error-activo');
}else {
document.getElementById('grupo__apellido').classList.add('grupo__formulario-incorrecto');
document.getElementById('grupo__apellido').classList.remove('grupo__formulario-correcto');
document.querySelector('#grupo__apellido .mensaje-error').classList.add('mensaje-error-activo');
}
break;
case "correo":
if (expresion.correo.test(e.target.value)){
document.getElementById('grupo__correo').classList.remove('grupo__formulario-incorrecto');
document.getElementById('grupo__correo').classList.add('grupo__formulario-correcto');
document.querySelector('#grupo__correo .mensaje-error').classList.remove('mensaje-error-activo');
}else {
document.getElementById('grupo__correo').classList.add('grupo__formulario-incorrecto');
document.getElementById('grupo__correo').classList.remove('grupo__formulario-correcto');
document.querySelector('#grupo__correo .mensaje-error').classList.add('mensaje-error-activo');
}
break;
case "clave":
if (expresion.clave.test(e.target.value)){
document.getElementById('grupo__clave').classList.remove('grupo__formulario-incorrecto');
document.getElementById('grupo__clave').classList.add('grupo__formulario-correcto');
document.querySelector('#grupo__clave .mensaje-error').classList.remove('mensaje-error-activo');
}else {
document.getElementById('grupo__clave').classList.add('grupo__formulario-incorrecto');
document.getElementById('grupo__clave').classList.remove('grupo__formulario-correcto');
document.querySelector('#grupo__clave .mensaje-error').classList.add('mensaje-error-activo');
}
break;
}
}
inputs.forEach((input) => {
input.addEventListener('keyup', validarformulario);
input.addEventListener('blur', validarformulario);
}); | 1146cc68e21ebb3ff0ff949d9017cc1f9a68a9d1 | [
"JavaScript"
]
| 1 | JavaScript | YamileFernandez/Intro-component-with-sign-form | 3a5053ac6ed3fd7dd7b40335ca9a3714ebf0e42e | ddae8b3dff15bf5252dd0b6a7238ee82d193b948 |
refs/heads/master | <repo_name>m2cci-maxime-mbogning/TP-programmation-en-C<file_sep>/les opérateurs/main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int les_operateurs = 5 ;
printf("le nombre d'operateur = %d\n", les_operateurs);
les_operateurs = 5;
printf("les operateurs = %d\n", les_operateurs);
printf("5+3= %d\n", 5+3);
printf("5-3= %d\n", 5-3);
printf("5*3= %d\n", 5*3);
printf("5/3= %d\n", 5/3);
printf("13%%7= %d\n", 13%7);
return 0;
}
<file_sep>/les consoles/main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int age_utilisateur= 0;
float taille_utilisateur =0.0;
printf("Quel age avez vous?\n Quel taille faites vous?\n");
scanf("%d %f", &age_utilisateur, &taille_utilisateur);
printf("J'ai %d ans et je mesure %f m\n", age_utilisateur, taille_utilisateur);
return 0;
}
<file_sep>/tp4_complement_variables/main.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
printf("TP4: Complements sur les variables\n");
//declaration des variables
int rayon_cercle = 0;
//lecture des informations
printf("Entrez le rayon du cercle : ");
scanf("%d", &rayon_cercle);
//affichage des variables
printf("Quel est le rayon du cercle ? %d\n", rayon_cercle);
printf("Ce cercle à pour diametre %d\n", rayon_cercle*2);
printf("Ce cercle à pour circonsference %f\n", (float)rayon_cercle*2*M_PI);
printf("Ce cercle à pour aire %f\n", (float)rayon_cercle*rayon_cercle*M_PI);
return 0;
}
<file_sep>/tp2_memoire_et_variable/main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("TP2: Memoire et Variables\n ");
int mediane = 4;
printf("la median est de %d et prend en mémoire %d octets\n", mediane, sizeof(int));
int long Max_poulet = 12;
printf("le nombre max de poulet est de %ld et prend en mémoire %d octets\n", Max_poulet, sizeof(long));
int short Min_poulet = 6;
printf("le nombre min de poulet est de %d et prend en mémoire %d octets\n", Min_poulet, sizeof(short));
float taille = 1.80;
printf("le taille moyenne des basketeur est de %f et prend en mémoire %d octets\n", taille, sizeof(float));
double taille_double = 13.9;
printf("le seuil double est de %f et prend en mémoire %d octets\n", taille_double, sizeof(double));
char nom = 'M';
printf("tous les noms commencant par %c et prend en mémoire %d octets\n", nom, sizeof(char));
return 0;
}
<file_sep>/boucle do while/main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int code_utilisateur = 1234;
do
{
printf("Code d'utilisateur : \n");
scanf("%d", &code_utilisateur);
}
while(code_utilisateur != 1234);
printf("OK");
return 0;
}
<file_sep>/Afficher le code ASCII/main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
// déclaration des variables
char lettre = ' ';
// lecture de la saisie
printf("Entrez une lettre: ");
scanf("%c", &lettre);
// Affichage des variable
printf("\t- %d en decimal \n", (int)lettre);
printf("\t- %x en hexacimal", (int)lettre);
return 0;
}
<file_sep>/tp3_operations_sur_variables/main.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("TP3: operations sur variables\n");
int taille_cote_carre = 0;
int perimetre_carre = 0;
int hauteur_rectangle = 0;
int largeur_rectangle = 0;
int perimetre_rectangle = 0;
int surface_rectangle = 0;
printf("Quel est la taille d un cote de carre ?\n" "Quel est la hauteur du rectangle ?\n" "Quel est la largeur du rectangle ?\n");
scanf("%d %d %d", &taille_cote_carre, &hauteur_rectangle, &largeur_rectangle);
printf("la taille d un cote de carre est de %d cm\n", taille_cote_carre);
printf("Ce carre a pour perimetre %d cm\n", 4*taille_cote_carre);
printf("Ce carre a pour surface %d cm2\n", taille_cote_carre*taille_cote_carre);
printf("la hauteur du rectangle est de %d cm\n", hauteur_rectangle);
printf("la largeur du rectangle est de %d cm\n", largeur_rectangle);
printf("Ce rectangle a pour perimetre %d cm\n", 2*hauteur_rectangle + 2*largeur_rectangle);
printf("Ce rectangle a pour surface %d cm2\n", hauteur_rectangle*largeur_rectangle);
return 0;
}
| 84ae4acc92dec8668cc0d304d0fab5bd83107c53 | [
"C"
]
| 7 | C | m2cci-maxime-mbogning/TP-programmation-en-C | 81adbc8bfb3380ea96b7146b326934ff855d337b | d12dee6d1bdfa330bb3ffd7bd12a027e8855dd39 |
refs/heads/main | <file_sep>package tn.formalab.ecommerce.models;
import javax.persistence.*;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue
public Integer id;
@Column(name = "name",nullable = false)
public String name;
@Column(name = "description",nullable = false)
public String description;
@Column(name = "imageUrl",nullable = false)
public String imageUrl;
@Column(name = "price",nullable = false)
public Double price;
//product 0..*----1 category
//ManyToOne ------- OneToMany
@ManyToOne
@JoinColumn(name = "idCategory")
public Category category;
}
<file_sep>package tn.formalab.ecommerce.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import tn.formalab.ecommerce.models.Category;
public interface CategoryRepository extends JpaRepository<Category, Integer> {
}
| e042123350da4bd9535a26fc643b5fcb9b142493 | [
"Java"
]
| 2 | Java | NasriHaithem/e-commerce-springboot-project | f9e6556e1012072ae21244a7a5a50a455633a400 | 80b5d63b4f2b7dbc37257da37bcd8d86a59c2b09 |
refs/heads/master | <repo_name>AtilaCosta87/JavaPOO<file_sep>/curso-javapoo/Exercicios Resolvidos/Aula12/src/aula12/Cachorro.java
/*
* 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.
*/
package aula12;
/**
*
* @author atila
*/
public class Cachorro extends Mamifero {
// Métodos
public void enterrarOsso() {
System.out.println("Enterrando osso");
}
public void abanarRabo() {
System.out.println("Abanando Rabo");
}
// Método Abstrato
@Override
public void emitirSom() {
System.out.println("Som de latido(Au!Au!Au!)");
}
}
<file_sep>/README.md
# Curso-JavaPOO-CursoEmVideo
Exercícios Resolvidos
| 91331d480a965410eeb53133ceb4fb905a668bb7 | [
"Markdown",
"Java"
]
| 2 | Java | AtilaCosta87/JavaPOO | 2fbe97ca13256c340ddec4bea0dc934aec085abe | 5eda8910b420c44ec1790ee126a86e09af0ce526 |
refs/heads/master | <file_sep>package com.capgemini.backgroundverification.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.capgemini.backgroundverification.entity.Logindata;
import com.capgemini.backgroundverification.entity.Verification;
import com.capgemini.backgroundverification.dao.LoginDaoImpl;
@Service
@Transactional
public class LoginServiceImpl implements LoginService
{
@Autowired
LoginDaoImpl dao;
@Override
public Logindata addUser(Logindata u) {
return dao.addUser(u);
}
@Override
public List<Logindata> getAllUsers()
{
return dao.getAllUsers();
}
@Override
public Logindata deleteUser(int userId)
{
return dao.deleteUser(userId);
}
@Override
public Logindata updateUser(Logindata u) {
return dao.updateUser(u);
}
@Override
public String loginUser(Logindata u)
{
return dao.loginUser(u);
}
@Override
public Verification addVer(Verification u) {
// TODO Auto-generated method stub
return dao.addVer(u);
}
}<file_sep>package com.capgemini.backgroundverification.dao;
import java.util.List;
import com.capgemini.backgroundverification.entity.Logindata;
import com.capgemini.backgroundverification.entity.Verification;
public interface LoginDao {
Logindata addUser(Logindata u);
List<Logindata> getAllUsers();
Logindata deleteUser(int userId);
Logindata updateUser(Logindata u);
String loginUser(Logindata u);
Verification addVer(Verification u);
}<file_sep>package com.capgemini.backgroundverification.service;
public class EmployeeServiceImpl {
}
| 6359145c9572362af5f2752fa035aa4f6abdf516 | [
"Java"
]
| 3 | Java | Deepesh412/AnuragBatch-3-BackGroundVerificationSystem | a4ca3251e60841079984c1751689b89f5b8de704 | 71ac37941d2349e762f050152266b0395a5c897f |
refs/heads/master | <file_sep># SatNDVI
Python code snippet to produce NDVI images from Red and NIR spectral channel images from satellites.
This small snippet will produce NDVI images with false-color palletes using NIR and R band images from satellite (Band 3 for R, Band 4 for NIR)
Prefferably use with cloudless, calibrated images that have had waterbody masks applied, or you can apply waterbody masks after NDVI processing.
NDVI is scaled on -1 to 1 scale, representing quality of vegetation. Tested with Himawari8 data.
Uses AstroPy and MatPlotLib
<file_sep>import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from astropy.nddata import NDDataArray
print("This programm will lead you through creating a NDVI map from images")
print("It works under assumption that you input two images into it: A Red band image and Near infrared image")
print("The images must be monochrome, cloudless and it would be best if they had a ocean mask applied.")
print("If they contain clouds/waterbodies, those will also be falsely ranged on scale.")
print("NIR is Band 4, R is Band 3 or broadband VIS")
pathNIR=input("Please input the path to near infrared image: ")
pathR=input("Please input the path to red image: ")
print("Please select a color pallete you want to use. Available palletes:")
print("Greens Greys hot seismic")
cmapN=input()
r=mpimg.imread(pathR)
nir=mpimg.imread(pathNIR)
numerator=NDDataArray.subtract(nir,r)
denominator=NDDataArray.add(nir,r)
NDVI=NDDataArray.divide(numerator,denominator)
plt.imshow(NDVI,cmap=cmapN)
plt.colorbar()
plt.show() | 524b14870f5438df041e325aef36839a6936f73e | [
"Markdown",
"Python"
]
| 2 | Markdown | AstroMasztalerz/SatNDVI | bd6d4c0893ed2efac2f046fb264a380e961b451b | 992922c9934d5171348d0546b21f6f7dd5933492 |
refs/heads/master | <repo_name>k1kiwi1/Bumper<file_sep>/bumper (1).cpp
#include "ros/ros.h"
#include <geometry_msgs/Twist.h>
#include <kobuki_msgs/BumperEvent.h>
#include <kobuki_msgs/CliffEvent.h>
geometry_msgs::Twist vmsg;
ros::Publisher cmd_vel_pub;
double bumper;
double state;
void publishVel(){
while(ros::ok()){
cmd_vel_pub.publish(vmsg);
ros::Duration(0.1).sleep();
ros::spinOnce();
}
}
void bumperCallback(const kobuki_msgs::BumperEvent::ConstPtr& msg){
bumper = msg->bumper;
state = msg->state;
ROS_INFO("bumper: %f, state: %f", bumper, state);
while(ros::ok()){
if(bumper == 1 && state == 1){
vmsg.linear.x = -0.17;
vmsg.angular.z = 2;
cmd_vel_pub.publish(vmsg);
ros::Duration(1).sleep();
ros::spinOnce();
ROS_INFO("Central bumper triggered");
}
else if(bumper == 0 && state == 1){
vmsg.linear.x = -0.13;
vmsg.angular.z = -2;
cmd_vel_pub.publish(vmsg);
ros::Duration(1).sleep();
ros::spinOnce();
ROS_INFO("Left bumper triggered");
}
else if(bumper == 2 && state == 1){
vmsg.linear.x = -0.13;
vmsg.angular.z = 2;
cmd_vel_pub.publish(vmsg);
ros::Duration(1).sleep();
ros::spinOnce();
ROS_INFO("Right bumper triggered");
}
vmsg.linear.x = 0.17;
vmsg.angular.z = 0.0;
cmd_vel_pub.publish(vmsg);
ros::Duration(0.01).sleep();
ros::spinOnce();
}
}
int main(int argc, char **argv) {
ros::init(argc, argv, "bumper");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/mobile_base/events/bumper", 1, bumperCallback);
cmd_vel_pub = n.advertise<geometry_msgs::Twist>("/cmd_vel_mux/input/navi", 1);
vmsg.linear.x = 0.17;
vmsg.angular.z = 0.0;
publishVel();
return 0;
}
| fa9a7c4f53bcd3e170003e481d7bc0cd196ce872 | [
"C++"
]
| 1 | C++ | k1kiwi1/Bumper | dfd802ab63691c594fa1e6e02cdbfa74f1a771f0 | cc9c8effb51d0f3ecc0fb53588954b8394c2f0a1 |
refs/heads/master | <repo_name>ZakeXu/fenci<file_sep>/fenci.py
import jieba
import json
def display():
src_path = "/home/users/xuzeke/src/baike_fenci/input/baikeSplitDatavr"
src_fid = open(src_path)
dst_path = "/home/users/xuzeke/src/baike_fenci/local/result.txt"
dst_fid = open(dst_path,'w')
lines = src_fid.readlines()
num = 1
for line in lines:
print num
num += 1
line = line.strip('\n')
data = line.split('\t')
word_list = []
for seg in data[5:7]:
try:
seg = eval('u'+stripTags(seg)) #去除html源码中的标签并说明格式为unicode编码
word_list.extend(list(jieba.cut(seg,cut_all=False)))
except Exception:
continue
fenci = {}
fenci['fenci'] = word_list
dst_fid.write(line+'\t'+json.dumps(fenci,ensure_ascii=False).encode('utf-8','ignore')+'\n')
def stripTags(s):
intag = [False]
def chk(c):
if intag[0]:
intag[0] = (c!='>')
return False
elif c=='<':
intag[0] = True
return False
return True
return ''.join(c for c in s if chk(c))
if __name__=="__main__":
display()
| d74f3bc1981d95830c1be49e026ee4c171e3360f | [
"Python"
]
| 1 | Python | ZakeXu/fenci | 6a9664b8ccaa2538f6f1898871a81ea3934d8275 | 3b1c9108cd753e6ca69cc1e46c29fe9266aabecc |
refs/heads/master | <repo_name>NidhiPankajShah/DataMininigAndRepresentationOfData<file_sep>/DataMiningon48States.py
import pandas as pd
import xlrd
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
country = pd.read_excel('C:\\Users\\Public\\dataset.xlsx')
df = country.head(48)
df = df.set_index(["Country"])
sd = df.reindex(columns=['Unemployment_rate_rural','Unemployment_rate_urban'])
print(sd)
sd.plot()
plt.show()
sd1 = df.reindex(columns=['Median_income_rural','median_income_urban'])
print(sd1)
sd1.plot()
plt.show()
| 25897fcc1b438a16d17e76d3e3c9a44d8dcd2be6 | [
"Python"
]
| 1 | Python | NidhiPankajShah/DataMininigAndRepresentationOfData | c584aa068c25164da64c7d5e393f38b6bf83460d | afd08271ccbab6836d386b0adc3c341e31b1c020 |
refs/heads/master | <file_sep>// todo: Could a constructor const or a class be helpful for organizing these?
const viewEmployees = () => {
return `SELECT e.id, CONCAT(e.first_name, ' ', e.last_name) AS 'Employee', d.name AS 'Department', r.title AS 'Title', r.salary AS 'Salary', CONCAT(m.first_name, ' ', m.last_name) AS 'Manager'
FROM employee e
LEFT JOIN employee m ON m.id = e.manager_id
LEFT JOIN Role r ON e.role_id = r.id
LEFT JOIN Department d ON d.id = r.department_id
ORDER BY e.id ASC;`;
};
const viewEmployeesByManager = () => {
return `SELECT IFNULL(CONCAT(m.first_name, ' ', m.last_name), '-self-') AS 'Manager', CONCAT(e.first_name, ' ', e.last_name) AS 'Employee', d.name, r.title, d.name, r.salary
FROM employee e
LEFT JOIN employee m ON m.id = e.manager_id
JOIN Role r ON e.role_id = r.id
JOIN Department d ON d.id = r.department_id
ORDER BY m.first_name ASC;`;
};
const viewEmployeesByDepartment = () => {
return `SELECT d.name AS 'Department', CONCAT(e.first_name, ' ', e.last_name) AS 'Employee', r.title, d.name, r.salary, CONCAT(m.first_name, ' ', m.last_name) AS 'Manager'
FROM employee e
LEFT JOIN employee m ON m.id = e.manager_id
JOIN Role r ON e.role_id = r.id
JOIN Department d ON d.id = r.department_id
ORDER BY d.name;`;
};
const viewDepartments = () => {
return `SELECT name AS 'Department Name'
FROM department
ORDER BY name ASC;`;
};
const viewRoles = () => {
return `SELECT title AS Role
FROM role
ORDER BY title ASC;`;
};
const viewDepartmentBudgets = () => {
return `not implemented`;
};
const addEmployee = (first, last, roleid, managerid) => {
return `INSERT INTO employee (first_name, last_name, role_id, manager_id)
VALUES ('${first}', '${last}', ${roleid}, ${managerid});`;
};
const addDepartment = (name) => {
return `INSERT INTO department (name) \
VALUES ('${name}');`;
};
const addRole = (title, salary, departmentid) => {
return `INSERT INTO role (title, salary, department_id)
VALUES ('${title}', '${salary}', '${departmentid}');`;
};
const updateEmployeeRole = (employeeid, roleid) => {
return `UPDATE employee e
SET
e.role_id = ${roleid}
WHERE
e.id = ${employeeid};`;
};
const updateEmployeeManager = (managerid, employeeid) => {
return `UPDATE employee e
SET
e.manager_id = ${managerid}
WHERE
e.id = ${employeeid};`;
};
const removeEmployee = (employeeid) => {
return `DELETE FROM employee where id = ${employeeid};`;
};
const removeDepartment = (removeDepartmentId) => {
return `DELETE FROM department where id = ${removeDepartmentId};`;
};
const removeRole = (removeRoleId) => {
return `DELETE FROM role where id = ${removeRoleId};`;
};
const utilGetEmployeeIdsNames = () => {
return `SELECT e.id, e.first_name, e.last_name
FROM employee e
ORDER BY e.first_name ASC;`;
};
const utilGetRoleIdsTitles = () => {
return `SELECT r.id, r.title
FROM role r
ORDER BY r.title ASC;`;
};
const utilGetDepartmentIdsNames = () => {
return `SELECT d.id, d.name
FROM department d
ORDER BY d.name ASC;
`;
};
exports.viewEmployees = viewEmployees;
exports.viewEmployeesByManager = viewEmployeesByManager;
exports.viewEmployeesByDepartment = viewEmployeesByDepartment;
exports.viewDepartments = viewDepartments;
exports.viewRoles = viewRoles;
exports.viewDepartmentBudgets = viewDepartmentBudgets;
exports.addEmployee = addEmployee;
exports.addDepartment = addDepartment;
exports.addRole = addRole;
exports.updateEmployeeRole = updateEmployeeRole;
exports.updateEmployeeManager = updateEmployeeManager;
exports.removeEmployee = removeEmployee;
exports.removeDepartment = removeDepartment;
exports.removeRole = removeRole;
exports.utilGetEmployeeIdsNames = utilGetEmployeeIdsNames;
exports.utilGetRoleIdsTitles = utilGetRoleIdsTitles;
exports.utilGetDepartmentIdsNames = utilGetDepartmentIdsNames;
<file_sep>// todo: move init functions to start? am i re-initializing after every action?
const mysql = require('mysql');
const inquirer = require('inquirer');
const sqlqueries = require('./sql');
const cTable = require('console.table');
const config = require('./config/dbpassword.config');
//#region banner
console.log(`,-----------------------------------------------------.
| |
| _____ _ |
| | ____|_ __ ___ _ __ | | ___ _ _ ___ ___ |
| | _| | '_ \` _ \\| '_ \\| |/ _ \\| | | |/ _ \\/ _ \\ |
| | |___| | | | | | |_) | | (_) | |_| | __/ __/ |
| |_____|_| |_| |_| .__/|_|\\___/ \\__, |\\___|\\___| |
| |_| |___/ |
| |
| __ __ |
| | \\/ | __ _ _ __ __ _ __ _ ___ _ __ |
| | |\\/| |/ _\` | '_ \\ / _\` |/ _\` |\/ _ \\ '__| |
| | | | | (_| | | | | (_| | (_| | __/ | |
| |_| |_|\\__,_|_| |_|\\__,_|\\__, |\\___|_| |
| |___/ |
| |
\`-----------------------------------------------------'
`);
//#endregion
//#region globals
let roleList;
let roleListObj;
let employeeList;
let employeeListObj;
let departmentList;
let departmentListObj;
function findRoleId(namedKey, objArray) {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].title === namedKey) {
return objArray[i];
}
}
}
function findEmployeeId(namedKey, objArray) {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].first_name + ' ' + objArray[i].last_name === namedKey.toString()) {
return objArray[i].id;
}
}
}
function findDepartmentId(namedKey, objArray) {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].name === namedKey) {
return objArray[i];
}
}
}
//#endregion
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: config.sqlPassword(),
database: "emsDB"
});
connection.connect(function (err) {
if (err) throw err;
// start();
init();
});
// todo: rename to populate lists? refresh lists?
// populate lists
function init() {
roleList = [];
roleListObj = {};
employeeList = [];
employeeListObj = {};
departmentList = [];
departmentListObj = {};
connection.query(sqlqueries.utilGetRoleIdsTitles(), function (err, results) {
if (err) throw err;
for (let i = 0; i < results.length; i++) {
roleList.push(results[i].title);
}
roleListObj = results;
});
connection.query(sqlqueries.utilGetEmployeeIdsNames(), function (err, results) {
if (err) throw err;
employeeList.push('None');
for (let i = 0; i < results.length; i++) {
employeeList.push(results[i].first_name + ' ' + results[i].last_name);
}
employeeListObj = results;
});
connection.query(sqlqueries.utilGetDepartmentIdsNames(), function (err, results) {
if (err) throw err;
for (let i = 0; i < results.length; i++) {
departmentList.push(results[i].name);
}
departmentListObj = results;
})
start();
}
function start() {
inquirer
.prompt({
name: "userAction",
type: "list",
message: "What would you like to do?",
choices: [
"View Employees", // required
"View Employees by Manager", // bonus
"View Employees by Department", // from demo app
"View Departments", // required
"View Roles", // required
"View Department Budgets", // bonus
new inquirer.Separator(),
"Add Employee", // required
"Add Department", // required
"Add Role", // required
new inquirer.Separator(),
"Update Employee Role", // required
"Update Employee Manager", // bonus
new inquirer.Separator(),
"Remove Employee", // bonus
"Remove Department", // bonus
"Remove Role", // bonus
new inquirer.Separator(),
"Exit",
new inquirer.Separator()
]
})
// todo: refactor function names to match ui
.then(function (answer) {
if (answer.userAction === "View Employees") {
viewEmployees();
}
else if (answer.userAction === "View Employees by Manager") {
viewEmployeesByManager();
}
else if (answer.userAction === "View Employees by Department") {
viewEmployeesByDepartment();
}
else if (answer.userAction === "View Departments") {
viewDepartments();
}
else if (answer.userAction === "View Roles") {
viewRoles();
}
else if (answer.userAction === "View Department Budgets") {
viewDepartmentBudgets();
}
else if (answer.userAction === "Add Employee") {
addEmployee();
}
else if (answer.userAction === "Add Department") {
addDepartment();
}
else if (answer.userAction === "Add Role") {
addRole();
}
else if (answer.userAction === "Update Employee Role") {
updateEmployeeRole();
}
else if (answer.userAction === "Update Employee Manager") {
updateEmployeeManager();
}
else if (answer.userAction === "Remove Employee") {
removeEmployee();
}
else if (answer.userAction === "Remove Department") {
removeDepartment();
}
else if (answer.userAction === "Remove Role") {
removeRole();
}
else {
connection.end();
}
});
}
function viewEmployees() {
connection.query(sqlqueries.viewEmployees(), function (err, results) {
if (err) throw err;
console.table(results);
start();
});
}
function viewEmployeesByManager() {
connection.query(sqlqueries.viewEmployeesByManager(), function (err, results) {
if (err) throw err;
console.table(results);
start();
});
}
function viewEmployeesByDepartment() {
connection.query(sqlqueries.viewEmployeesByDepartment(), function (err, results) {
if (err) throw err;
console.table(results);
start();
});
}
function viewDepartments() {
connection.query(sqlqueries.viewDepartments(), function (err, results) {
if (err) throw err;
console.table(results);
start();
})
}
function viewRoles() {
connection.query(sqlqueries.viewRoles(), function (err, results) {
if (err) throw err;
console.table(results);
start();
});
}
// todo: implement
function viewDepartmentBudgets() {
console.log('viewDepartmentBudgets() not implemented.');
start();
}
function addEmployee() {
inquirer.prompt([
{
message: "What is the employee's first name?",
name: "newFirstName",
validate: function validateFirstName(name) {
return name !== '';
},
type: "input",
},
{
message: "What is the employee's last name?",
name: "newLastName",
validate: function validateLastName(name) {
return name !== '';
},
type: "input"
},
{
message: "What is the employee's role?",
name: "newRole",
type: "list",
choices: function () {
var choiceArray = [];
for (var key in roleListObj) {
choiceArray.push(roleListObj[key].title);
}
return choiceArray;
}
},
{
message: "Who is the employee's manager?",
name: "newManager",
type: "list",
choices: employeeList
}
]).then(function (answer) {
var newRoleId = findRoleId(answer.newRole, roleListObj).id;
var newManagerId = (findEmployeeId(answer.newManager, employeeListObj)) ? findEmployeeId(answer.newManager, employeeListObj) : null;
connection.query(sqlqueries.addEmployee(answer.newFirstName, answer.newLastName, newRoleId, newManagerId), function (err, results) {
if (err) throw err;
console.log('Added ' + answer.newFirstName + ' ' + answer.newLastName + ' to the database.')
init();
});
});
}
function addDepartment() {
inquirer.prompt([
{
message: "What is the department name?",
name: "newDepartmentName",
validate: function validateFirstName(newDepartmentName) {
return newDepartmentName !== '';
},
type: "input",
}
]).then(function (answer) {
connection.query(sqlqueries.addDepartment(answer.newDepartmentName), function (err, results) {
if (err) throw err;
console.log(answer.newDepartmentName + ' added to the database.')
init();
});
});
}
function addRole() {
inquirer.prompt([
{
message: "What is the title?",
name: "newTitle",
validate: function validateFirstName(newTitle) {
return newTitle !== '';
},
type: "input",
},
{
message: "What is the salary?",
name: "newSalary",
validate: function validateLastName(newSalary) {
return newSalary !== '';
},
type: "input"
},
{
message: "Select a department:",
name: "newDepartment",
type: "list",
choices: function () {
var choiceArray = [];
for (var key in departmentListObj) {
choiceArray.push(departmentListObj[key].name);
}
return choiceArray;
}
}
]).then(function (answer) {
var newRoleId = findDepartmentId(answer.newDepartment, departmentListObj).id;
connection.query(sqlqueries.addRole(answer.newTitle, answer.newSalary, newRoleId, newRoleId), function (err, results) {
if (err) throw err;
console.log(answer.newTitle + ' added to the database.')
init();
});
});
}
function updateEmployeeRole() {
inquirer.prompt([
{
message: "Which employee do you want to update?",
name: "selectedEmployee",
type: "list",
choices: employeeList
},
{
message: "Select their new role.",
name: "selectedRole",
type: "list",
choices: roleList
}
]).then(function (answer) {
var employeeIdToUpdate = (findEmployeeId(answer.selectedEmployee, employeeListObj)) ? findEmployeeId(answer.selectedEmployee, employeeListObj) : null;
var newRoleId = findRoleId(answer.selectedRole, roleListObj).id;
connection.query(sqlqueries.updateEmployeeRole(employeeIdToUpdate, newRoleId), function (err, results) {
if (err) throw err;
console.log('The role for ' + answer.selectedEmployee + ' has been changed to ' + answer.selectedRole + '.');
init();
});
});
}
function updateEmployeeManager() {
inquirer.prompt([
{
message: "Which employee do you want to update?",
name: "selectedEmployee",
type: "list",
choices: employeeList
},
{
message: "Select their new manager.",
name: "selectedManager",
type: "list",
choices: employeeList
}
]).then(function (answer) {
var employeeIdToUpdate = (findEmployeeId(answer.selectedEmployee, employeeListObj)) ? findEmployeeId(answer.selectedEmployee, employeeListObj) : null;
if (answer.selectedManager === answer.selectedEmployee) {
newManagerId = null;
} else if (findEmployeeId(answer.selectedManager, employeeListObj)) {
newManagerId = findEmployeeId(answer.selectedManager, employeeListObj);
} else {
newManagerId = null;
}
connection.query(sqlqueries.updateEmployeeManager(newManagerId, employeeIdToUpdate), function (err, results) {
if (err) throw err;
console.log('The manager for ' + answer.selectedEmployee + ' has been changed to ' + answer.selectedManager + '.');
init();
});
});
}
function removeEmployee() {
inquirer.prompt({
message: "Which employee do you want to remove?",
name: "employeeName",
type: "list",
choices: employeeList
}).then(function (answer) {
if (answer.employeeName === 'None') {
start();
} else {
var employeeIdToRemove = (findEmployeeId(answer.employeeName, employeeListObj)) ? findEmployeeId(answer.employeeName, employeeListObj) : null;
connection.query(sqlqueries.removeEmployee(employeeIdToRemove), function (err, results) {
if (err) throw err;
console.log(answer.employeeName + ' removed from the database.')
init();
});
}
});
}
// todo: implement
function removeDepartment() {
inquirer.prompt([
{
message: "Which department do you want to remove?",
name: "removeDepartment",
type: "list",
choices: departmentList
}
]).then(function (answer) {
console.log(answer.removeDepartment);
var removeDepartmentId = findDepartmentId(answer.removeDepartment, departmentListObj).id;
console.log(removeDepartmentId);
connection.query(sqlqueries.removeDepartment(removeDepartmentId), function (err, results) {
if (err) throw err;
console.log(answer.removeDepartment + ' was removed from the database.')
init();
});
});
}
// todo: implement
function removeRole() {
inquirer.prompt([
{
message: "Which role do you want to remove?",
name: "removeRole",
type: "list",
choices: roleList
}
]).then(function (answer) {
console.log(answer.removeRole);
var removeRoleId = findRoleId(answer.removeRole, roleListObj).id;
console.log(removeRoleId);
connection.query(sqlqueries.removeRole(removeRoleId), function (err, results) {
if (err) throw err;
console.log(answer.removeRole + ' was removed from the database.')
init();
});
});
}
<file_sep># hw-12: MySQL Homework: Employee Tracker
Assignment: Architect and build a solution for managing a company's employees using node, inquirer, and MySQL.
To run: `npm start`
## Minimum Requirements
* [x] Functional application.
* [x] GitHub repository with a unique name and a README describing the project.
* The command-line application should allow users to:
* [x] Add employees, departments, roles
* [x] View employees, departments, roles
* [x] Update employee roles
## Bonus
* The command-line application should allow users to:
* [x] Update employee managers
* [x] View employees by manager
* [x] Delete departments, roles, and employees
* [ ] View the total utilized budget of a department -- ie the combined salaries of all employees in that department
## Submission on BCS
* [x] The URL of the GitHub repository
## ERR

<file_sep>-- ------------------------
-- POPULATE DB
-- ------------------------
USE emsDB;
INSERT INTO department (name) VALUES ('Sales');
INSERT INTO department (name) VALUES ('Engineering');
INSERT INTO department (name) VALUES ('Finance');
INSERT INTO department (name) VALUES ('Legal');
USE emsDB;
SELECT * FROM department;
USE emsDB;
INSERT INTO role (title, salary, department_id) VALUES ('Sales Lead', '100000', '1');
INSERT INTO role (title, salary, department_id) VALUES ('Salesperson', '80000', '1');
INSERT INTO role (title, salary, department_id) VALUES ('Lead Engineer', '150000', '2');
INSERT INTO role (title, salary, department_id) VALUES ('Software Engineer', '120000', '2');
INSERT INTO role (title, salary, department_id) VALUES ('Accountant', '125000', '3');
INSERT INTO role (title, salary, department_id) VALUES ('Legal Team Lead', '250000', '4');
INSERT INTO role (title, salary, department_id) VALUES ('Lawyer', '190000', '4');
USE emsDB;
SELECT * FROM role;
USE emsDB;
SELECT title
FROM role
ORDER BY department_id ASC, title ASC;
USE emsDB;
INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES ('Ashley', 'Rodriguez', 3, null);
INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES ('John', 'Doe', 1, 1);
INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES ('Mike', 'Chan', 2, 2);
INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES ('Kevin', 'Tupik', 4, 1);
INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES ('Malia', 'Brown', 5, null);
INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES ('Sarah', 'Lourd', 6, null);
INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES ('Tom', 'Allen', 7, 6);
INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES ('Christian', 'Eckenrode', 3, 3);
USE emsDB;
SELECT * FROM employee;
-- ------------------------
-- VIEW DATA
-- ------------------------
-- viewAllEmployees
USE emsDB;
SELECT e.id, CONCAT(e.first_name, ' ', e.last_name) AS 'Employee', d.name AS 'Department', r.title, r.salary, CONCAT(m.first_name, ' ', m.last_name) AS 'Manager'
FROM employee e
LEFT JOIN employee m ON m.id = e.manager_id
LEFT JOIN Role r ON e.role_id = r.id
LEFT JOIN Department d ON d.id = r.department_id
ORDER BY e.id ASC;
-- viewAllEmployeesByDepartment
USE emsDB;
SELECT d.name, CONCAT(e.first_name, ' ', e.last_name) AS 'Employee', r.title, d.name, r.salary, CONCAT(m.first_name, ' ', m.last_name) AS 'Manager'
FROM employee e
LEFT JOIN employee m ON m.id = e.manager_id
JOIN Role r ON e.role_id = r.id
JOIN Department d ON d.id = r.department_id
ORDER BY d.name ASC;
-- viewAllEmployeesByManager
USE emsDB;
SELECT IFNULL(CONCAT(m.first_name, ' ', m.last_name), '') AS 'Manager', CONCAT(e.first_name, ' ', e.last_name) AS 'Employee', d.name, r.title, d.name, r.salary
FROM employee e
LEFT JOIN employee m ON m.id = e.manager_id
JOIN Role r ON e.role_id = r.id
JOIN Department d ON d.id = r.department_id
ORDER BY m.first_name ASC;
-- viewDepartments
USE emsDB;
SELECT name AS 'Department Name'
FROM department
ORDER BY name ASC;
-- viewDepartmentBudgets
USE emsDB;
SELECT department_id, SUM(salary)
FROM role
GROUP BY department_id;
USE emsDB;
SELECT department_id, salary
FROM role;
USE emsDB;
SELECT e.id AS 'Employee ID', d.name AS 'Department', d.id AS 'Department ID', r.title AS 'Title', r.salary AS 'Salary'
FROM employee e
JOIN Role r ON e.role_id = r.id
JOIN Department d ON d.id = r.department_id
ORDER BY d.id ASC;
USE emsDB;
select role_id from employee;
USE emsDB;
SELECT d.name AS 'Department', CONCAT(e.first_name, ' ', e.last_name) AS 'Employee', r.title, r.salary, CONCAT(m.first_name, ' ', m.last_name) AS 'Manager'
FROM employee e
LEFT JOIN employee m ON m.id = e.manager_id
JOIN Role r ON e.role_id = r.id
JOIN Department d ON d.id = r.department_id
ORDER BY d.name ASC;
USE emsDB;
SELECT role_id, COUNT(role_id)
FROM employee
GROUP BY role_id
HAVING COUNT(role_id) > 0;
SELECT
email,
COUNT(email)
FROM
contacts
GROUP BY email
HAVING COUNT(email) > 1;
-- ------------------------
-- UPDATE QUERIES
-- ------------------------
USE emsDB;
UPDATE employee e
SET
e.role_id = ?
WHERE
e.id = ?;
USE emsdb; SELECT * FROM employee WHERE id = 12;
USE emsDB;
UPDATE employee e
SET
e.manager_id = ?
WHERE
e.id = ?;
USE emsdb; SELECT * FROM employee WHERE id = 12;
-- ------------------------
-- UTILITY QUERIES
-- ------------------------
-- queries for addEmployee()
USE emsDB;
SELECT e.id, e.first_name, e.last_name
FROM employee e
ORDER BY e.first_name ASC;
USE emsDB;
SELECT r.id, r.title
FROM role r
ORDER BY r.title ASC;
-- queries for addDepartment()
USE emsDB;
SELECT d.id, d.name
FROM department d
ORDER BY d.name ASC;
-- removeEmployee
USE emsDB;
-- DELETE FROM employee where id = ?;
-- updateEmployeeRole
-- updateEmployeeManager
-- viewAllRoles
-- addRole
-- removeRole
-- ------------------------
-- REMOVE QUERIES
-- ------------------------
-- queries for addEmployee()
USE emsDB;
-- USE emsDB;
-- DELETE FROM role where id = 3;
-- DELETE FROM role where id = 9;
use emsDB; select * from role;
use emsdb; select * from employee;
use emsdb; select * from department;
-- use emsDB; DELETE FROM role where id = 9;
-- use emsDB; DELETE FROM department where id = 6;
use emsDB; select * from role;
use emsdb; select * from employee;
use emsdb; select * from department;
-- ------------------------
-- SCRATCH
-- ------------------------
-- USE emsDB;
-- SELECT * FROM employee;
-- SELECT * FROM role;
-- SELECT * FROM department;
-- USE emsDB;SELECT r.title, d.name, r.salary FROM role AS r, department AS d WHERE r.department_id = d.id;
-- USE emsDB;SELECT e.first_name, e.last_name, r.title FROM employee AS e, role AS r WHERE e.role_id = r.id;
-- select everything but manager
-- USE emsDB;
-- SELECT CONCAT(e.first_name, ' ', e.last_name) AS 'Employee', r.title, d.name, r.salary
-- FROM role AS r, department AS d, employee AS e
-- WHERE r.department_id = d.id AND e.role_id = r.id;
-- select manager, employee
-- USE emsDB;
-- SELECT IFNULL(m.first_name, 'self') AS 'MANAGER', CONCAT(e.first_name, ' ', e.last_name) AS 'EMPLOYEE'
-- FROM employee e
-- LEFT JOIN employee m ON m.id = e.manager_id;
-- select depart info
-- USE emsDB;
-- SELECT role.department_id, department.name FROM role, department WHERE role.department_id = department.id;
-- ------------------------
-- RAW DATA FOR REFERENCE
-- ------------------------
-- beginning of überquery
-- SELECT e.first_name, e.last_name, r.title, d.name, r.salary, e.manager_id FROM employee as e, role as r, department as d WHERE
-- ALL EMPLOYEES >> this is the goal table output from console.table
-- 2 <NAME>, Sales Lead, Sales, 100000, <NAME>
-- 3 <NAME>, Salesperson, Sales, 80000, <NAME>
-- 1 <NAME>, Lead Engineer, Engineering, 150000, null
-- 4 <NAME>, Software Engineer, Engineering, 120000, <NAME>
-- 5 <NAME>, Accountant, Finance, 125000, null
-- 6 <NAME>, Legal Team Lead, Legal, 250000, null
-- 7 <NAME>, Lawyer, Legal, 190000, Sarah Lourd
-- 8 <NAME>, Lead Engineer, Engineering, 150000, <NAME>
-- DEPARTMENT
-- 1 Sales
-- 2 Engineering
-- 3 Finance
-- 4 Legal
-- ROLE
-- 1 Sales Lead
-- 2 Salesperson
-- 3 Lead Engineer
-- 4 Software Engineer
-- 5 Accountant
-- 6 Legal Team Lead
-- 7 Lawyer
-- EMPLOYEE
-- 1 <NAME>
-- 2 <NAME>
-- 3 <NAME>
-- 4 <NAME>
-- 5 <NAME>
-- 6 <NAME>
-- 7 <NAME>
-- 8 <NAME>
-- USE emsDB;
-- UPDATE role r
-- SET
-- r.title = 'Chief Data Scientist'
-- WHERE
-- r.id = 12;
-- USE emsdb; SELECT * FROM role;
USE emsdb;
SELECT r.id, r.title
FROM role r
ORDER BY r.title ASC; | 8ca1090b4d40cbe36ad863045aa7fb8ab2e4ea35 | [
"JavaScript",
"SQL",
"Markdown"
]
| 4 | JavaScript | kr4mpu5/hw-12 | 9dd9a45ac0aba6d5d49ad030425347e2071e49c3 | 4bbdd6126ded52e55d32d932f2367c3531fd5d51 |
refs/heads/master | <repo_name>abel-cabral/play-sbel<file_sep>/src/util/TimeConvert.java
package util;
import java.text.SimpleDateFormat;
public class TimeConvert {
public static String convertToMinute(double milliSeconds, String dateFormat) {
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
long aux = (long) milliSeconds;
return sdf.format(milliSeconds);
}
}
<file_sep>/src/gui/MainController.java
package gui;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon;
import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcons;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.util.Duration;
import util.SelectFile;
import util.TimeConvert;
import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;
public class MainController implements Initializable {
public static List<File> playList = new ArrayList<File>();
private int current = 0;
public File playing;
private boolean progressBarSystem = false; // Quanto true o usuario moveu a barra de tempo, caso contrário é o sistema atuando
Double timeMusic;
MediaPlayer mediaPlayer = null;
Media media = null;
@FXML
public Slider progressBar;
@FXML
Label timeScreen;
@FXML
Label musicName;
@FXML
MediaView mediaView;
@FXML
FontAwesomeIcon playPauseIcon;
@FXML
ImageView gifDancing;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
progressBar.setValue(0);
gifDancing.setVisible(false);
}
@FXML
private void openFile() {
playing = null;
List<File> aux = SelectFile.selectMusics();
if (aux == null) {
return;
}
Set<File> auxList = new HashSet<File>(); // Irá evitar repeticoes
auxList.addAll(aux);
// Add a playlist
playList = auxList.stream().collect(Collectors.toList());
playing = playList.get(current);
mediaPlayer = mediaPlayerFactory(playing, mediaPlayer);
playMusicButton();
}
private void timeLabel() {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Platform.runLater(() -> {
// Relogio decrementando
timeScreen.setText(TimeConvert.convertToMinute(mediaPlayer.getTotalDuration().toMillis() - mediaPlayer.getCurrentTime().toMillis(), "mm:ss"));
// Barra de progresso avançando
double auxPercent = (mediaPlayer.getCurrentTime().toMillis() / mediaPlayer.getTotalDuration().toMillis()) * 100;
progressBarSystem = true;
progressBar.setValue(auxPercent);
progressBarSystem = false;
}
);
if (mediaPlayer.getTotalDuration().toMillis() == mediaPlayer.getCurrentTime().toMillis() || mediaPlayer.getStatus() == Status.PAUSED || mediaPlayer.getStatus() == Status.STOPPED) {
timer.cancel();
}
}
}, 1000, 1000);
}
@FXML
public void nextMusic() {
if (playList.size() > current + 1) {
current += 1;
mediaPlayer.stop();
playing = playList.get(current);
mediaPlayer = mediaPlayerFactory(playing, mediaPlayer);
playMusicButton();
}
}
@FXML
public void previousMusic() {
if (current > 0) {
current -= 1;
mediaPlayer.stop();
playing = playList.get(current);
mediaPlayer = mediaPlayerFactory(playing, mediaPlayer);
playMusicButton();
} else {
mediaPlayer.seek(Duration.millis(1));
}
}
@FXML
public void playMusicButton() {
if (mediaPlayer != null) {
mediaPlayer.setOnReady(new Runnable() {
@Override
public void run() {
// Dados da Música Atual
timeMusic = mediaPlayer.getTotalDuration().toMillis();
timeScreen.setText(TimeConvert.convertToMinute(timeMusic, "mm:ss"));
musicName.setText(playing.getName().substring(0, playing.getName().lastIndexOf('.')).toUpperCase());
mediaPlayer.seek(Duration.millis(1)); // Corrige bug de leitura de mp3
// Posiciona a barra de progresso
mediaPlayer.play();
playPauseIcon.setIcon(FontAwesomeIcons.PAUSE);
gifDancing.setVisible(true);
// Barra de Progresso e Tempo de Execução
timeLabel();
}
});
if (mediaPlayer.getStatus() == Status.PAUSED || mediaPlayer.getStatus() == Status.STOPPED) {
mediaPlayer.play();
playPauseIcon.setIcon(FontAwesomeIcons.PAUSE);
gifDancing.setVisible(true);
timeLabel();
} else if (mediaPlayer.getStatus() == Status.PLAYING) {
playPauseIcon.setIcon(FontAwesomeIcons.PLAY_CIRCLE);
mediaPlayer.pause();
gifDancing.setVisible(false);
}
// Ao fim da musica avança para a proxima, se nao ultima permite ouvi-la novamente
mediaPlayer.setOnEndOfMedia(() -> {
if (current + 1 == playList.size()) {
mediaPlayer.seek(Duration.millis(1));
mediaPlayer.stop();
playPauseIcon.setIcon(FontAwesomeIcons.PLAY_CIRCLE);
}
nextMusic();
});
} else {
openFile();
}
}
private void beforePlayMusic() {
if (playList.isEmpty()) {
// Evita repeticoes
Set<File> auxList = new HashSet<File>(); // Irá evitar repeticoes
auxList.addAll(SelectFile.selectMusics());
// Add a playlist
playList = auxList.stream().collect(Collectors.toList());
if (playing == null) {
playing = playList.get(current);
}
}
}
@FXML
public void closeProgram() {
Platform.exit();
Platform.isImplicitExit();
System.exit(143);
}
@FXML
public void progressBarManager() {
if (mediaPlayer == null) {
return;
}
playMusicButton();
}
// UTILITARIOS
public MediaPlayer mediaPlayerFactory(File source, MediaPlayer now) {
if (now != null) {
now.stop();
}
// Instantiating MediaPlayer class
Media facMedia = new Media(new File("file:" + source.getPath().toString().replaceAll(" ", "%20")).getPath()); // Remove espaços que causam error ao ler path
MediaPlayer facMediaPlayer = new MediaPlayer(facMedia);
// Inicialização de componentes de tela
facMediaPlayer.setVolume(80);
facMediaPlayer.setAutoPlay(true);
// Subscrible para ouvir mudanças na barra de progresso
progressBar.setValue(0);
progressBar.setMax(100);
// Adding Listener to value property.
progressBar.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
if (progressBarSystem) {
return;
}
mediaPlayer.pause();
timeScreen.setText(TimeConvert.convertToMinute(timeMusic, "mm:ss"));
timeMusic = mediaPlayer.getTotalDuration().toMillis() - mediaPlayer.getCurrentTime().toMillis();
mediaPlayer.seek(mediaPlayer.getMedia().getDuration().multiply(progressBar.getValue() / 100));
}
});
return facMediaPlayer;
}
}
<file_sep>/src/util/Utils.java
package util;
public class Utils {
public static String rmExtension(String name) {
String[] auxName = name.split(".");
System.out.printf(auxName[0]);
return auxName[0];
}
}
| ec5b71167b442801be3512ab84c2c741be1c9888 | [
"Java"
]
| 3 | Java | abel-cabral/play-sbel | 5bf95d6b0875756ab0eb7e0d1025d3c7a33d33d9 | 2b9a8d356e58eb807147805db546d59c57349033 |
refs/heads/master | <file_sep>from keras.preprocessing.image import ImageDataGenerator
from keras.datasets import mnist,cifar10
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.callbacks import ModelCheckpoint, EarlyStopping
# 데이터 불러오기
(X_train, Y_train), (X_test, Y_test) = cifar10.load_data()
X_train = X_train[ :300]
X_test = X_test[ :300]
Y_train = Y_train[ :300]
Y_test = Y_test[ :300]
X_train = X_train.reshape(X_train.shape[0], 32, 32, 3).astype('float32') / 255 # MinMax Scaler
X_test = X_test.reshape(X_test.shape[0], 32, 32, 3).astype('float32') / 255
Y_train = np_utils.to_categorical(Y_train)
Y_test = np_utils.to_categorical(Y_test)
model = Sequential()
model.add(Conv2D(64, kernel_size=(3,3), input_shape=(32,32,3), activation='relu'))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.1))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(16, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.fit(X_train, Y_train, epochs=10,batch_size=30)
print("\n Test Accuracy: %.4f" % (model.evaluate(X_test, Y_test)[1]))<file_sep>from keras.preprocessing.image import ImageDataGenerator
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.callbacks import ModelCheckpoint, EarlyStopping
# 데이터 불러오기
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
X_train = X_train[ :300]
X_test = X_test[ :300]
Y_train = Y_train[ :300]
Y_test = Y_test[ :300]
| 88736acc56cae8275fd494c875906af4a84f0182 | [
"Python"
]
| 2 | Python | dkdldspd/AI_2 | de814336ad936101cb2376cb840a10bb0c8374a2 | 4c16eb68c3e7574ae7239cd40c38a86a72f58cec |
refs/heads/main | <file_sep># Generated by Django 3.1.7 on 2021-03-02 07:46
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='GoodsType',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('good_type_name', models.CharField(max_length=30, unique=True)),
],
options={
'verbose_name': '商品类型表',
'verbose_name_plural': '商品类型表',
'db_table': 'tb_goodstype',
},
),
migrations.CreateModel(
name='Goods',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('good_name', models.CharField(blank=True, max_length=50, unique=True)),
('good_pic', models.ImageField(blank=True, upload_to='static/goodspic')),
('good_count', models.IntegerField(blank=True)),
('good_desc', models.CharField(blank=True, max_length=500)),
('good_type', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='goods.goodstype')),
],
options={
'verbose_name': '商品信息表',
'verbose_name_plural': '商品信息表',
'db_table': 'tb_goods',
},
),
]
<file_sep>let vm = new Vue({
el:'#app',
delimiters:['[[',']]'],
data:{
username:'',
password:'',
error_username_code:false,
error_password_code:false,
error_username_message:'',
error_password_message:'',
},
methods:{
check_username() {
let re = /^[a-zA-Z0-9_-]{5,20}$/;
if(re.test(this.username)){
this.error_username_code=false;
}else {
this.error_username_message='请输入正确的用户名';
this.error_username_code=true;
}
},
check_password() {
let re = /^[a-zA-Z0-9]{8,20}$/;
if(re.test(this.password)){
this.error_password_code=false;
}else {
this.error_password_message='请按要求输入密码';
this.error_password_code=true;
}
},
check_submit(){
this.check_password();
this.check_username();
},
},
});<file_sep># coding=utf-8
# @Time:2021/3/2 14:21
# @Author:jia
# @File:urls.py
# @Software:PyCharm
from django.conf.urls import url
from goods import views
urlpatterns = [
url(r'^goodslist/$',views.GoodsListView.as_view(),name='goodslist'),
url(r'^addgoods/$',views.AddGoodsView.as_view(),name='addgoods'),
url(r'^addgoodstype/$',views.AddGoodstypeView.as_view(),name='addgoodstype'),
url(r'^goodstype/$',views.GoodstypelistView.as_view(),name='goodstype'),
url(r'^goodsinfo/(?P<goodsid>\d+)$',views.GoodsinfoView.as_view(),name='goodsinfo'),
url(r'^delgoods/(?P<goodsid>\d+)$',views.DeletegoodsView.as_view(),name='delgoods'),
url(r'^delgoodstype/(?P<typeid>\d+)$',views.DeletetypeView.as_view(),name='delgoodstype'),
url(r'^tj$',views.TjView.as_view(),name='tj'),
url(r'^search$',views.SearchView.as_view(),name='search'),
]<file_sep>from django.shortcuts import render, redirect
# Create your views here.
from django.urls import reverse
from django.views import View
from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
import re
from goods.models import Goods,GoodsType
from django.db import DatabaseError
from django.db.models import Count
class SearchView(View):
def get(self,request):
goods_list = []
goods = Goods.objects.all()
for good in goods:
goods_list.append(good.good_name)
content = {
'goods_list':goods_list,
}
return render(request,'search.html',context=content)
class TjView(View):
def get(self,request):
good_type_name = []
good_type_count = []
# goods = Goods.objects.annotate(c=Count('good_type')).values('good_type','c')
counts = Goods.objects.values('good_type').annotate(c=Count('good_type'))
count_list =[]
for count in counts:
name = GoodsType.objects.get(id=count['good_type']).good_type_name
total = Goods.objects.filter(good_type_id=count['good_type'])
goodscount = 0
for item in total:
goodscount += item.good_count
count_list.append(goodscount)
good_type_name.append(name)
good_type_count.append(count['c'])
content = {
'count_list':count_list,
'good_type_name':good_type_name,
'good_type_count':good_type_count,
}
# print(content)
# for good in goods:
# good.good_type.good_type_name
# print(c)
# goodstype = GoodsType.objects.order_by('id')
# goods = Goods.objects.get(id=1)
# type = goods.good_type.good_type_name
# type = GoodsType.objects.get(good_type_name='浴室柜')
# goods = type.goods_set.all()
# for good in goods:
# print(good.good_name)
# for type in goodstype:
# leixing = type.goodstype.good_type_name
# # good_type_name.append(type.good_type_id)
# print(goods)
return render(request,'tj.html',content)
class GoodstypelistView(LoginRequiredMixin,View):
def get(self,request):
goodstype = GoodsType.objects.order_by('id')
content={
'goodstype':goodstype,
}
return render(request,'goodstype.html',content)
def post(self,request):
typeid = request.POST.get('typeid')
typename = request.POST.get('typename')
goodstype = GoodsType.objects.get(id=typeid)
goodstype.good_type_name = typename
goodstype.save()
return redirect(reverse('goods:goodstype'))
class DeletetypeView(LoginRequiredMixin,View):
def get(self,request,typeid):
GoodsType.objects.get(id=typeid).delete()
return redirect(reverse('goods:goodstype'))
class AddGoodstypeView(LoginRequiredMixin,View):
def get(self,request):
return render(request,'addgoodstype.html')
def post(self,request):
goodstype = request.POST.get('goodstype')
if goodstype is None:
return http.HttpResponseForbidden('请输入类型')
if GoodsType.objects.filter(good_type_name=goodstype):
return http.HttpResponse('类型已经存在')
GoodsType.objects.create(good_type_name=goodstype)
return redirect(reverse('goods:addgoods'))
# return http.HttpResponse('添加成功')
class GoodsListView(LoginRequiredMixin,View):
def get(self,request):
return render(request,'index.html')
class AddGoodsView(LoginRequiredMixin,View):
def get(self,request):
goodstype = GoodsType.objects.all()
context = {
'goodstype':goodstype,
}
return render(request,'addgoods.html',context=context)
def post(self,request):
goodsname = request.POST.get('goodsname')
goodstype = request.POST.get('goodstype')
goodscount = int(request.POST.get('goodscount'))
goodsdesc = request.POST.get('goodsdesc')
if not all([goodsname,goodstype,goodscount]):
return http.HttpResponseForbidden('参数不全')
if not isinstance(goodscount,int):
return http.HttpResponseForbidden('数量必须为数字')
# 如果首次添加则创建,否则只累加数量
# print(Goods.objects.filter(good_name=goodsname))
if not Goods.objects.filter(good_name=goodsname):
goodtypes = GoodsType.objects.filter(good_type_name=goodstype).first()
Goods.objects.create(good_name=goodsname,good_count=goodscount,good_type=goodtypes,good_desc=goodsdesc)
else:
goods = Goods.objects.get(good_name=goodsname)
goods.good_count = goods.good_count + goodscount
goods.save()
return redirect('user:index')
# return http.HttpResponse('添加成功')
class GoodsinfoView(LoginRequiredMixin,View):
def get(self,request,goodsid):
goodsinfo = Goods.objects.filter(id=goodsid).first()
# type = goodsinfo.good_type.good_type_name
goodstype = GoodsType.objects.all()
content = {
'goodsinfo': goodsinfo,
'goodstype':goodstype,
}
return render(request,'goodsinfo.html',content)
def post(self,request,goodsid):
goodsname = request.POST.get('goodsname')
goodspic = request.FILES.get('goodspic')
goodstype = request.POST.get('goodstype')
goodscount = request.POST.get('goodscount')
goodsdesc = request.POST.get('goodsdesc')
if not all([goodsname,goodstype,goodscount,goodsdesc]):
return http.HttpResponseForbidden('参数不全')
goods = Goods.objects.get(id=goodsid)
goods.good_name = goodsname
goods.good_pic = goodspic
goods.good_type_id = goodstype
goods.good_count = goodscount
goods.good_desc = goodsdesc
goods.save()
# return render(request,'index.html')
# return http.HttpResponse('添加成功')
return redirect(reverse('user:index'))
class DeletegoodsView(View):
def get(self,request,goodsid):
Goods.objects.get(id=goodsid).delete()
return redirect(reverse('user:index'))
class GoodstypeView(LoginRequiredMixin,View):
def get(self,request):
goodstype = GoodsType.objects.all()
content = {
'goodstype':goodstype,
}
return render(request,'goodstype.html',content)
<file_sep>from django.db import models
# Create your models here.
from django.db.models import Model
class Goods(Model): # 商品信息表
good_name = models.CharField(max_length=50,unique=True,blank=True)
good_pic = models.ImageField(upload_to='pic/',blank=True)
good_type = models.ForeignKey('GoodsType',on_delete=models.SET_NULL,null=True)
good_count = models.IntegerField(blank=True)
good_desc = models.CharField(max_length=500,blank=True)
class Meta:
db_table = 'tb_goods'
verbose_name = "商品信息表"
verbose_name_plural = verbose_name
class GoodsType(Model):
good_type_name = models.CharField(max_length=30,unique=True,blank=False)
class Meta:
db_table = 'tb_goodstype'
verbose_name = '商品类型表'
verbose_name_plural = verbose_name
<file_sep>from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
mobile =models.CharField(max_length=11)
class Meta:
db_table = 'tb_users'
verbose_name = '用户管理'
verbose_name_plural = verbose_name
<file_sep># coding=utf-8
# @Time:2021/3/1 17:00
# @Author:jia
# @File:urls.py
# @Software:PyCharm
from django.conf.urls import url
from user import views
urlpatterns = [
url(r'^register/$',views.RegisterView.as_view(),name='register'),
# url(r'^image_codes/(?P<uuid>[\w-]+)/$',views.ImageCodeView.as_view()),
url(r'^index/$',views.IndexView.as_view(),name='index'),
url(r'^login/$',views.LoginView.as_view(),name='login'),
url(r'^test$',views.TestView.as_view()),
url(r'^logout$',views.LoginView.as_view(),name='logout'),
url(r'^$',views.LoginView.as_view()),
]
<file_sep>from django.shortcuts import render, redirect
# Create your views here.
from django.urls import reverse
from django.views import View
# from django_redis import get_redis_connection
from django import http
from django.db import DatabaseError
import re
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from user.models import User
from goods.models import Goods
from user.captcha.captcha import captcha
# class ImageCodeView(View):
# def get(self,request,uuid):
# text,image = captcha.generate_captcha()
# redis_con = get_redis_connection('verify_code')
# redis_con.setex('img_%s'%uuid,300,text)
# return http.HttpResponse(image,content_type='image/jpg')
class TestView(View):
def get(self,request):
return render(request,'test.html')
class LogoutView(View):
def get(self,request):
logout(request)
# request.delete_cookie()
return render(request,'login.html')
class LoginView(View):
def get(self,request):
return render(request,'login.html')
def post(self,request):
# 接收参数
username = request.POST.get('username')
password = request.POST.get('password')
password2 = request.POST.get('<PASSWORD>2')
# 校验参数
if not all([username,password,password2]):
return http.HttpResponseForbidden('参数不全')
if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
return http.HttpResponseForbidden('用户名不符合要求')
if not re.match(r'^[a-zA-Z0-9]{8,20}$',password):
return http.HttpResponseForbidden('密码不符合要求')
if password2 != password:
return http.HttpResponseForbidden('两次密码不一致')
# 验证登陆
user = authenticate(username=username,password=<PASSWORD>)
if user is None:
return render(request,'login.html',{'account_errmsg':'用户名或密码错误'})
login(request,user)
request.session.set_expiry(0)
# 登陆成功,跳转到首页
next = request.GET.get('next')
if next:
response = redirect(next)
else:
response = redirect(reverse('user:index'))
return response
class IndexView(LoginRequiredMixin,View):
def get(self,request):
# sort = request.GET.get('sort','id')
goods_list = []
page_num = request.GET.get('page_num',1)
goods = Goods.objects.order_by('id')
for good in goods:
goods_list.append(good.good_name)
count = goods.count()
paginator = Paginator(goods,10)
page_goods = paginator.page(page_num)
# total_page = paginator.num_pages
context = {
'goods_list':goods_list,
'count':count,
'page_goods':page_goods,
'page_num':page_num,
}
return render(request,'index.html',context)
class RegisterView(View):
def get(self,request):
return render(request,'register.html')
def post(self,request):
# 接收参数
username = request.POST.get('username')
password = request.POST.get('password')
password2 = request.POST.get('password2')
# 校验参数
if not all([username,password,password2]):
return http.HttpResponseForbidden('缺少必要参数')
if not re.match(r'[a-zA-Z0-9_-]{5,20}',username):
return http.HttpResponseForbidden('用户名格式错误')
if not re.match(r'[a-zA-Z0-9]{8,20}',password):
return http.HttpResponseForbidden('密码格式错误')
if password != password2:
return http.HttpResponseForbidden('两次密码不一致')
try:
user = User.objects.create_user(username=username,password=password)
except DatabaseError:
return render(request,'register.html',{"register_errmsg":"注册失败"})
login(request,user) # 注册成功,自动登陆,跳转到首页
request.session.set_expiry(0) #设置会话时间,浏览器关闭即失效
return render(request,'index.html')<file_sep>layui.config({
version: '1614920675134' //为了更新 js 缓存,可忽略
});
function jump(){
layer.msg('成功,正在跳转')
}
function add(){
$.post({
url: '',
data: '',
success:function (request){
if (request.requestcode == 200){
layui.use('layer',function (){
layer.msg('添加成功')
});
}
},
error:function (){
layui.use('layer',function (){
layer.msg('添加成功')
});
},
})
}
// layui.use([ 'layer'], function add(){
// $.ajax({
// type:'POST',
// dataType:'json',
// url:'/goodsinfo/1',
// data:$('#form1').serialize(),
// success:function (result){
// if (result.resultCode == 200){
// layer.msg('成功');
// };
// },
// error:function (){
// layer.msg('失败');
// }
//
// });
//
//
//
// }); | 978c0da68f9ea20ffcbb3fc367e7dd3e29f6c121 | [
"JavaScript",
"Python"
]
| 9 | Python | 569727863/huayi_stock | 6fa74fe1f127456a8af295a5b100d7c02b60f9f2 | a60fa26840d9e8f17383353b3f60c154b602c0ba |
refs/heads/master | <repo_name>NatalieAFoster/NFGlobal-Aerospace-Test<file_sep>/CCDefault.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
//CURRENCY CONVERTER USING JSON API
public class Rate
{
//read and write properties
public string to { get; set; } //paired dataset
public string from { get; set; }
public double rate { get; set; } // Time stamp and base are objects that could alo be extracted but not required for the programme
}
//This is a first attempt at using asp.Net, the comments will explain my logic for the code. However, even though the database it recognised in the system extraction to the currencies was not achieved
protected void Button1_Click(object sender, EventArgs e )// when conversion buttion is press the following should take place
{
double amount; // amount entered by the user
if (double.TryParse(Txt1.Text, out amount)) // amount entered in first text box converted to double output
{
WebClient web = new WebClient(); //webclient to download file
string url = string.Format("http://api.fixer.io/latest?from={0}&to={1}", DDLfrom.SelectedItem.Value, DDLto.SelectedItem.Value); //bind json database and set drop down list parameter
string rates = web.DownloadString(url); //extract rates
Rate rate = new JavaScriptSerializer().Deserialize<Rate>(rates); //deserialise JSON file
double exchange = amount * rate.rate; //calculation for currency conversion
string message = amount+ " " + DDLfrom.SelectedItem.Text + "\\n"; // show about enter with name of currency chosen
message += "The exchange rate for: " + DDLfrom.SelectedItem.Text + " to " + DDLto.SelectedItem.Text + " = " + exchange + "\\n"; // show exchange rate in message
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + message + "');", true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Invalid amount value.');", true);
}
}
protected void DDL3_SelectedIndexChanged(object sender, EventArgs e)
{
//STANDARD CURRENCY CONVERTER
}
protected void Button2_Click(object sender, EventArgs e)
{
int amount; // amount to be entered by the user
int.TryParse(Txt3.Text, out amount); //text box converted to interget input
double currency1 = double.Parse(DDL3.SelectedItem.Value); //currency variable to converted value from dropdown list
double currency2 = double.Parse(DDL4.SelectedItem.Value);
double conversion;
double con = amount * currency1;//conversion for first inout for first seleted currency
// if statements to produce error statement if the same currency is selected
if (DDL3.SelectedValue == "1.2329" && DDL4.SelectedValue == "1.2329")
{
Label4.Text = "INCORRECT SELECTION";
}
else if (DDL3.SelectedValue == "0.9326" && DDL4.SelectedValue == "0.9326")
{
Label4.Text = "INCORRECT SELECTION";
}
else if (DDL3.SelectedValue == "0.6432" && DDL4.SelectedValue == "0.6432")
{
Label4.Text = "INCORRECT SELECTION";
}
else if (DDL3.SelectedValue == "1" && DDL4.SelectedValue == "1")
{
Label4.Text = "INCORRECT SELECTION";
}
else if (DDL3.SelectedValue == "123.454" && DDL4.SelectedValue == "123.454")
{
Label4.Text = "INCORRECT SELECTION";
//Canadian Dollar Exhange
}
else if (DDL3.SelectedValue == "1.2329" && DDL4.SelectedValue == "0.9326") // when different selection are made from each comboBox a calculation for that currency will be performed
{
conversion = con * currency2; // currency is user input amount multiplied by the exchange rate
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " +conversion.ToString("N2"); // label 1 text, will display user input amount and name of current in comboBox 1 index selected as 0
}
else if (DDL3.SelectedValue == "1.2329" && DDL4.SelectedValue == "0.6432") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "1.2329" && DDL4.SelectedValue == "1") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "1.2329" && DDL4.SelectedValue == "123.454") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
//Swiss France Exchange
else if (DDL3.SelectedValue == "0.9326" && DDL4.SelectedValue == "1.2329") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "0.9326" && DDL4.SelectedValue == "0.6432") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "0.9326" && DDL4.SelectedValue == "1") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "0.9326" && DDL4.SelectedValue == "123.454") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
//Pound Sterling Exchange
else if (DDL3.SelectedValue == "0.6432" && DDL4.SelectedValue == "1.2329") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "0.6432" && DDL4.SelectedValue == "0.9326") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "0.6432" && DDL4.SelectedValue == "1") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "0.6432" && DDL4.SelectedValue == "123.454") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
//US Dollar
else if (DDL3.SelectedValue == "1" && DDL4.SelectedValue == "1.2329") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "1" && DDL4.SelectedValue == "0.9326") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "1" && DDL4.SelectedValue == "0.6432") {
conversion= con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "1" && DDL4.SelectedValue == "123.454") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
//Japanese Yen
else if (DDL3.SelectedValue == "123.454" && DDL4.SelectedValue == "1.2329") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "123.454" && DDL4.SelectedValue == "0.9326")
{
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "123.454" && DDL4.SelectedValue == "0.6432")
{
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
else if (DDL3.SelectedValue == "123.454" && DDL4.SelectedValue == "1") {
conversion = con * currency2;
Label4.Text = "The exchange rate is: " + DDL4.SelectedItem.Text + " " + conversion.ToString("N2");
}
}}
<file_sep>/README.md
# NFGlobal-Aerospace-Test
Currency Converter created in ASP.NET with C#
This file contains 2 converters
The first is a general currency converter
The second attempts to use JSON data to input the different currencies
| ecfc68e7dab024c4d529999b2246a60022832896 | [
"Markdown",
"C#"
]
| 2 | C# | NatalieAFoster/NFGlobal-Aerospace-Test | e7797c2da80424dc1b6a12c8d3ffceccd1e5d8e9 | 9ec235a8a028b3e91f93163901d08b975912017a |
refs/heads/master | <repo_name>focccus/shopping_list<file_sep>/README.md
# Shopping App
This is a simple shopping list app made in Flutter that syncs its content between multiple devices via Node.js and Websockets.
It also features an offline mode, caching data on device until connection retrieves.
Made with the Fluid UI Components for Flutter
## Deploy your own
You can deploy the nodejs server yourself. Just clone this repository, go into the `server` subfolder and run:
```
npm install
```
Start the server with
```
node server.js
```
<file_sep>/server/server.js
const fs = require("fs"),
url = require("url"),
path = require("path"),
express = require("express"),
cors = require("cors"),
Datastore = require("nedb"),
app = express(),
server = require("http").createServer(app),
io = require("socket.io")(server);
app.use(express.static("web"));
app.use(express.json());
app.use(cors());
app.get("/", (_, res) => {
res.sendFile(__dirname + "/web/index.html");
});
app.get("/app", (_, res) => {
res.sendFile(__dirname + "/download/Einkauf.apk");
});
var recipes = new Datastore({
filename: "data/recipes.db",
autoload: true,
});
app.post("/syncrecipes", async (req, res) => {
let time = parseInt(req.query.last) || 0;
console.log(req.body);
if (req.body && Array.isArray(req.body)) {
for (let recipe of req.body) {
if (recipe.id && recipe.name) {
recipe.synced = Date.now();
console.log(recipe);
recipes.update(
{ id: recipe.id },
{ $set: recipe },
{ upsert: true },
(err, num) => {
if (err) console.log(err);
}
);
}
}
}
recipes.find({ synced: { $gt: time } }, (err, items) => {
if (err) console.log(err);
res.send(items);
});
});
// socket io
var history = new Datastore({ filename: "data/history.db", autoload: true });
var items = new Datastore({ filename: "data/items.db", autoload: true });
var _sockets = new Set();
io.on("connection", (socket) => {
console.log(">>>>>>> new connection", socket.handshake.query.timestamp);
_sockets.add(socket);
socket.on("add", (data) => {
if (data.name) {
items.update(
{ name: data.name },
{ $set: { name: data.name }, $inc: { amount: data.amount || 1 } },
{ upsert: true, returnUpdatedDocs: true },
(err, num, doc) => {
console.log(doc);
_sockets.forEach((socket) => socket.emit("addItem", doc));
}
);
history.update(
{ name: data.name },
{ $set: { name: data.name }, $inc: { usage: 1 } },
{ upsert: true },
(err, num) => {
if (err) console.log(err);
}
);
}
});
socket.on("remove", (data) => {
if (data.id) {
items.remove({ _id: data.id }, (err, num) => {
console.log(num);
if (err) console.log(err);
else if (num > 0)
_sockets.forEach((socket) =>
socket.emit("removeItem", { id: data.id })
);
});
}
});
socket.on("items", (_) => {
items.find({}, (err, items) => socket.emit("items", items));
});
socket.on("history", (_) => {
history
.find({})
.sort({ usage: -1 })
.exec((err, history) => {
history = history.map((h) => h.name);
socket.emit("history", history);
});
});
socket.on("history_remove", (data) => {
if (data.name) {
history.remove({ name: data.name }, (err, num) => {
if (err) console.log(err);
else if (num > 0)
_sockets.forEach((socket) =>
socket.emit("history_remove", { name: data.name })
);
});
}
});
socket.on("disconnect", () => {
_sockets.delete(socket);
console.log(">>>>>>> disconnect", socket.handshake.query.timestamp);
console.log(">>>>>>> Total Sockets", _sockets.size);
});
});
server.listen(8090, "0.0.0.0");
console.log("Server started on 0.0.0.0:8090");
| 7ca591402aeefbe976e7742110bfe3a4301da962 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | focccus/shopping_list | f4e5355534cc4d41cc7e3cdd4d7b39afb434022d | 670d04a0a55c610848324ddb5b7450d16e2995c5 |
refs/heads/master | <file_sep>#ifndef JSON_PARSER_H_
#define JSON_PARSER_H_
#include <stddef.h>
struct json_value;
struct json_value* parse_json(const char* data, const size_t len);
#endif
<file_sep>int rest_server();
<file_sep>/* SPDX-License-Identifier: BSD-3-Clause */
/*
* Authors: <NAME> <<EMAIL>>
*
* Copyright (c) 2019, NEC Laboratories Europe GmbH, NEC Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* THIS HEADER MAY NOT BE EXTRACTED OR MODIFIED IN ANY WAY.
*/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <rest.h>
#include <uk/diagnostic.h>
#include <uk/json_ir.h>
#include "json_parser.h"
#define LISTEN_PORT 8123
static const char header[] = "HTTP/1.1 200 OK\r\n" \
"Content-type: application/json\r\n" \
"Connection: close\r\n" \
"\r\n" \
"";
#define BUFLEN 2048
static char recvbuf[BUFLEN];
static char sendbuf[BUFLEN];
int rest_server()
{
int rc = 0;
int srv, client;
ssize_t n;
struct sockaddr_in srv_addr;
srv = socket(AF_INET, SOCK_STREAM, 0);
if (srv < 0) {
fprintf(stderr, "Failed to create socket: %d\n", errno);
goto out;
}
srv_addr.sin_family = AF_INET;
srv_addr.sin_addr.s_addr = INADDR_ANY;
srv_addr.sin_port = htons(LISTEN_PORT);
rc = bind(srv, (struct sockaddr *) &srv_addr, sizeof(srv_addr));
if (rc < 0) {
fprintf(stderr, "Failed to bind socket: %d\n", errno);
goto out;
}
/* Accept one simultaneous connection */
rc = listen(srv, 1);
if (rc < 0) {
fprintf(stderr, "Failed to listen on socket: %d\n", errno);
goto out;
}
const size_t header_size = snprintf(&sendbuf[0], BUFLEN, "%s", &header[0]);
char* buff = &sendbuf[header_size];
const size_t buff_len = BUFLEN - header_size;
printf("Listening on port %d...\n", LISTEN_PORT);
while (1) {
client = accept(srv, NULL, 0);
if (client < 0) {
fprintf(stderr,
"Failed to accept incoming connection: %d\n",
errno);
goto out;
}
/* Receive some bytes (ignore errors) */
ssize_t bytes = read(client, recvbuf, BUFLEN);
if (bytes < 0) {
fprintf(stderr,
"Failed to read request: %d\n",
errno);
close(client);
continue;
}
/* skip lines until message body */
/* TODO: Use proper HTTP parsing once the parser library is implemented */
size_t offset = 0;
for (size_t i = 0; i < 7; i++) {
while (offset < (size_t) bytes && recvbuf[offset] != '\n') {
offset++;
}
offset++;
}
char* data = &recvbuf[offset];
size_t len = bytes - offset;
data[len] = '\0';
printf("message body:\n%s\n", data);
struct json_value* json = parse_json(data, len);
if (json->type != JSON_OBJECT) {
close(client);
free_json_value(json);
continue;
}
struct json_value* outputs = create_json_value(JSON_OBJECT);
for (struct json_object* obj = json->object; obj != NULL; obj = obj->next) {
printf("function name: %s\n", obj->key);
// TODO: use obj->value to pass parameters
struct json_value* result = NULL;
run_diag_function(obj->key, obj->value, &result);
json_object_insert(outputs, obj->key, result);
}
size_t size = to_json(buff, buff_len, outputs);
printf("result: %s\n", buff);
printf("size: %lu\n", size);
free_json_value(json);
free_json_value(outputs);
/* Send reply */
n = write(client, &sendbuf[0], header_size + size);
if (n < 0)
fprintf(stderr, "Failed to send a reply\n");
else
printf("Sent a reply\n");
/* Close connection */
close(client);
}
out:
return rc;
}
<file_sep>#include "json_parser.h"
#include <uk/json_ir.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
struct json_parser_state {
const char* data;
size_t len;
size_t pos;
bool error;
};
static struct json_value* parse_value(struct json_parser_state* state);
static char* parse_string(struct json_parser_state* state);
static bool check_end(struct json_parser_state* state) {
state->error = state->pos >= state->len;
return !state->error;
}
static bool expect_char(struct json_parser_state* state, char check) {
if (!check_end(state))
return false;
state->error = state->data[state->pos] != check;
if (!state->error)
state->pos++;
return !state->error;
}
static void parse_ws(struct json_parser_state* state) {
while (state->pos < state->len && isspace(state->data[state->pos])) {
state->pos++;
}
}
static struct json_value* parse_element(struct json_parser_state* state) {
parse_ws(state);
struct json_value* value = parse_value(state);
if (state->error) {
free_json_value(value);
return NULL;
}
parse_ws(state);
return value;
}
static struct json_object* parse_member(struct json_parser_state* state) {
parse_ws(state);
char* key = parse_string(state);
if (state->error) {
free(key);
return NULL;
}
parse_ws(state);
if (!expect_char(state, ':')) {
free(key);
return NULL;
}
struct json_value* value = parse_element(state);
if (state->error) {
free(key);
free_json_value(value);
return NULL;
}
struct json_object* object = malloc(sizeof(struct json_object));
object->key = key;
object->value = value;
object->next = NULL;
return object;
}
static struct json_object* parse_object(struct json_parser_state* state) {
if (!expect_char(state, '{')) {
return NULL;
}
parse_ws(state);
if (!check_end(state))
return NULL;
if (state->data[state->pos] == '}') {
// This is an empty object
state->pos++; // }
return NULL;
}
// Otherwise, we have a head member
struct json_object* head = parse_member(state);
if (state->error) {
free_json_object(head);
return NULL;
}
struct json_object* curr = head;
while(state->data[state->pos] != '}') {
if (!expect_char(state, ',')) {
free_json_object(head);
return NULL;
}
// get the next member, and append to the list
curr->next = parse_member(state);
if (state->error) {
free_json_object(head);
return NULL;
}
curr = curr->next;
}
if (!expect_char(state, '}')) {
free_json_object(head);
return NULL;
}
return head;
}
static struct json_array* parse_array(struct json_parser_state* state) {
if (!expect_char(state, '[')) {
return NULL;
}
parse_ws(state);
if (!check_end(state))
return NULL;
struct json_array* array = malloc(sizeof *array);
array->values = NULL;
array->size = 0;
if (state->data[state->pos] == ']') {
// This is an empty array
state->pos++; // }
return array;
}
// Otherwise, array is non-empty, initialize
size_t capacity = 16;
array->values = calloc(capacity, sizeof *array->values);
// get the first element
array->values[0] = parse_element(state);
array->size = 1;
if (state->error) {
free_json_array(array);
return NULL;
}
while(state->data[state->pos] != ']') {
if (!expect_char(state, ',')) {
free_json_array(array);
return NULL;
}
// get the next element
struct json_value* next = parse_element(state);
if (state->error) {
free_json_value(next);
free_json_array(array);
return NULL;
}
// reallocate if we need more space
if (array->size == capacity) {
capacity *= 2;
struct json_value** new_values = calloc(capacity, sizeof *new_values);
memcpy(new_values, array->values, array->size * sizeof *array->values);
free(array->values);
array->values = new_values;
}
array->values[array->size] = next;
array->size++;
}
if (!expect_char(state, ']')) {
free_json_array(array);
return NULL;
}
return array;
}
static char* parse_string(struct json_parser_state* state) {
if (!expect_char(state, '"'))
return NULL;
// first count the chars
size_t start_pos = state->pos;
size_t count;
for (count = 0;
state->pos < state->len && state->data[state->pos] != '"';
state->pos++, count++) {
if (state->data[state->pos] == '\\') {
// skip escaped chars
state->pos++;
}
}
if (!check_end(state)) {
return NULL;
}
// rewind to the start of the string
state->pos = start_pos;
char* string = malloc(sizeof(char) * (count + 1));
for (size_t str_pos = 0;
state->data[state->pos] != '"';
state->pos++, str_pos++) {
if (state->data[state->pos] == '\\') {
// TODO: Add proper escape character handling
// Just skip backslashes for now
state->pos++;
}
string[str_pos] = state->data[state->pos];
}
string[count] = '\0';
if (!expect_char(state, '"')) {
free(string);
return NULL;
}
return string;
}
static int64_t parse_int(struct json_parser_state* state) {
// TODO: Use stdlib to parse this?
if (!check_end(state))
return 0;
bool negative = state->data[state->pos] == '-';
if (negative)
state->pos++; // -
if (!check_end(state))
return 0;
if (!isdigit(state->data[state->pos])) {
state->error = true;
return 0;
}
int64_t num = 0;
for (; state->pos < state->len && isdigit(state->data[state->pos]); state->pos++) {
num *= 10;
num += state->data[state->pos] - '0';
}
if (negative)
num *= -1;
return num;
}
static struct json_value* parse_value(struct json_parser_state* state) {
if (!check_end(state))
return NULL;
struct json_value* value = create_json_value(JSON_ERROR);
char next_char = state->data[state->pos];
// object: '{'
// array: '['
// string: '"'
// true
// false
// null
// number: else
switch (next_char) {
case '{':
value->type = JSON_OBJECT;
value->object = parse_object(state);
break;
case '[':
value->type = JSON_ARRAY;
value->array = parse_array(state);
break;
case '"':
value->type = JSON_STRING;
value->string = parse_string(state);
break;
case 't':
value->type = JSON_TRUE;
state->pos += 4;
break;
case 'f':
value->type = JSON_FALSE;
state->pos += 5;
break;
case 'n':
value->type = JSON_NULL;
state->pos += 4;
break;
default:
value->type = JSON_INT;
value->integer = parse_int(state);
}
if (state->error) {
free_json_value(value);
return NULL;
}
return value;
}
struct json_value* parse_json(const char* data, const size_t len) {
struct json_parser_state state = {
.data = data,
.len = len,
.pos = 0,
.error = false,
};
struct json_value* result = parse_value(&state);
if (!state.error)
return result;
free_json_value(result);
return create_json_value(JSON_ERROR);
}
| 615e5e1578e4745481b2cd0bb289cd030f59e5cc | [
"C"
]
| 4 | C | robert-hrusecky/unikraft-ukdiagnostic-restapi | 848b9462645e4b38bbee0a0866d6adc3184813e8 | 882258d5fad1a655e6e809909226e5cc8ed0520e |
refs/heads/master | <file_sep>Recaptcha.configure do |config|
config.public_key = '<KEY>'
config.private_key = '<KEY>'
end<file_sep>class Project < ActiveRecord::Base
has_and_belongs_to_many :users
validates :name, :description, :target_area, presence: true
end
| 0d896734388ad1a6bc9d7d942c10361dc5c7e3a5 | [
"Ruby"
]
| 2 | Ruby | nadinelyab/ImpactWeb | b598a634d9246bf45f53810b8f22410285f1c94e | 651da12eded91dd299c0946fc1bb50d7df49c609 |
refs/heads/master | <repo_name>gugujiang-t/2020_project<file_sep>/app.py
# -*- coding = utf-8 -*-
# @Time = 2021/1/6 11:02
# @Author : <NAME>, <NAME>
# @File : main.py
# @Software : PyCharm
import sqlite3
import re
from flask import Flask, render_template
app = Flask(__name__)
# 数据库路径
dbpath = "cosmetics.db"
# 主页
@app.route('/')
def index():
return render_template("index.html")
# 主页
@app.route('/index.html')
def index_2():
return render_template("index.html")
# 分布_企业位置_Map
@app.route('/dist_loc')
def dist_loc():
# 连接数据库的操作
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
sql = """
select province as name,count(*) as value
from cosmetics
group by province
order by value ;
"""
dataList = cursor.execute(sql)
dataDict = []
dataJson = {}
for data in dataList:
tdict = {}
province = data[0]
if province != "黑龙江" and province != "内蒙古":
province = province[0:2]
tdict['name'] = province
tdict['value'] = data[1]
dataDict.append(tdict)
dataJson[province] = data[1]
print(dataDict) # 测试
# 关闭连接
cursor.close()
conn.close()
return render_template("maps/map1.html", dataDict=dataDict,dataJson=dataJson)
# 分布_产品项目类型在位置上_Map
@app.route('/dist_item')
def dist_item():
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
dataList = cursor.execute("select province, item from cosmetics order by province").fetchall()
curprovince = ""
itemDict = {} # {'广东':'护发清洁类','黑龙江':'发蜡类'}
tdict = {}
for i in range(len(dataList)):
data = dataList[i]
province = data[0]
if province != "黑龙江" and province != "内蒙古":
province = province[0:2]
if curprovince == "":
# 刚开始
curprovince = province
strItem = str(data[1]) # 一般液态单元(护发清洁类、护肤水类、啫喱类);膏霜乳液单元(护肤清洁类、护发类)‘
itemList = re.split('(|、|;|#|)', strItem)
# itemList = ['一般液态单元', '护发清洁类', '护肤水类', '啫喱类', '膏霜乳液单元', '护肤清洁类', '护发类', '']
for item in itemList:
# 是有效的可统计的类别
if item.find("类") != -1:
# eg. item = '护发清洁类' XX类
# 对当前省份继续统计
if curprovince == province and i != len(dataList) - 1:
# eg.tdict = {'护发清洁类':2,'啫喱类':3}
# 这一类第一次统计
if tdict.get(item, -1) == -1:
tdict[item] = 1
# 这一类之前有记录数字
else:
tdict[item] += 1
else:
# 新遍历到的省是另一个省了或是查询结果中最后的一个省,需要写入刚刚那个省的统计结果到字典
# dict进行降序排序 maxItem = '护发清洁类'
stupleList = sorted(tdict.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)
# eg.stupleList = [('护肤水类', 7), ('护肤清洁类', 6),...]
maxItem = stupleList[0][0]
if len(stupleList) > 1 and stupleList[0][1] == stupleList[1][1]: # 若有并列
maxItem += '、' + stupleList[1][0]
# 字典里加键值对 '广东':'护发清洁类'
itemDict[curprovince] = maxItem
# 重置curprovince和tdict
curprovince = province
tdict.clear()
# 数量随省分布的数据
sql = """
select province as name,count(*) as value
from cosmetics
group by province
order by value ;
"""
dataList = cursor.execute(sql)
dataList_ord = []
for data in dataList:
tdict = {}
province = data[0]
if province != "黑龙江" and province != "内蒙古":
province = province[0:2]
tdict['name'] = province
tdict['value'] = data[1]
dataList_ord.append(tdict)
cursor.close()
conn.close()
return render_template('maps/map2.html', dataList_ord=dataList_ord, itemDict=itemDict)
# 许可证_分发时间_Chart_Bar
@app.route('/cert_issue')
def cert_issue():
# 连接数据库的操作
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
dataList = cursor.execute("select substr(date,1,7) as month,count(*) from cosmetics group by substr(date,1,7)")
# [month, count]
# [2020-01, 10]
month = []
mcount = []
for data in dataList:
month.append(data[0])
mcount.append(data[1])
print(month[0]) # 测试
cursor.close()
conn.close()
return render_template("charts/charts.html", month=month, mcount=mcount)
# 许可证_有效时长_Chart_Pie
@app.route('/cert_life')
def cert_life():
# 连接数据库的操作
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
sql = """
select count(case when life >= 0 and life < 1 then 1 else null end) as '1年以内',
count(case when life >= 1 and life < 2 then 1 else null end) as '1~2年',
count(case when life >= 2 and life < 3 then 1 else null end) as '2~3年',
count(case when life >= 3 and life < 4 then 1 else null end) as '3~4年',
count(case when life >= 4 and life < 5 then 1 else null end) as '4~5年',
count(case when life = 5 then 1 else null end) as '5年'
from cosmetics;
"""
# ['1年以内',100]
dataList = cursor.execute(sql)
length = ["<1年","1~2年","2~3年","3~4年","4~5年","5年"]
lcount = []
for data in dataList:
for counts in data:
lcount.append(counts)
print(lcount[0]) # test
cursor.close()
conn.close()
return render_template("charts/charts_2.html", length=length, lcount=lcount)
# 源数据表打印_datatable
@app.route('/tables/datatables')
def table():
# 连接数据库的操作
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
dataList = list(cursor.execute("select name, num, province, office, date, life, item from cosmetics"))
#[{'name': '海南卓瑞生物医药有限公司', 'num': '琼妆20190009', 'province': '海南省', 'office': '海南省药品监督管理局',
# 'date': '2021-01-05', 'life': '1413', 'item': '一般液态单元(护肤水类)'}]
print(dataList[0]) #test
cursor.close()
conn.close()
return render_template("tables/datatables.html", dataList=dataList)
if __name__ == '__main__':
app.run()
<file_sep>/spider.py
#!/usr/bin/env python
# -*- coding = utf-8 -*-
# @Time : 2021/1/5 14:32
# @Author : <NAME>
# @File : dao.py
# @Software : PyCharm
import requests
import json
def getDataFromUrl(url):
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'
}
id_list = []
# 爬200页的数据
for page in range(1, 49):
data = {
'on': 'true',
'page': page,
'pageSize': '15',
'productName': '',
'conditionType': '1',
'applyname': '',
'applysn': '',
}
json_id = requests.post(url=url, data=data, headers=header).json()
print("page " + str(page) + " has successfully crawled")
for dic in json_id['list']:
id_list.append(dic['ID'])
data_list = []
post_url = 'http://scxk.nmpa.gov.cn:81/xk/itownet/portalAction.do?method=getXkzsById'
for id in id_list:
Data = {
'id': id
}
data_json = requests.post(url=post_url, headers=header, data=Data).json()
data_list.append(data_json)
fp = open('./data.json', 'w', encoding='utf-8')
json.dump(data_list, fp=fp, ensure_ascii=False)
print('spider succeed----------')
return data_list
<file_sep>/README.md
# 2020_project
## Python爬取化妆品许可证信息 使用flask框架可视化数据
##项目技术栈:`Flask框架、Echarts、爬虫、SQLite`
##环境:`Python3`
### 目录结构说明
├─static ----- 静态页面
├─templates ----- HTML页面
│ app.py ----- flask框架 文件
│ spider.py ----- 爬取数据 文件
│ dao.py ----- 数据库操作 文件
│ main.py ----- main入口 文件
│ cosmetic.db ----- 数据库
│ data.json ----- json格式保存的数据信息 文件
└─ README.md
### 步骤
- 运行main.py
- 爬取数据
- 在本地建立数据库并创建数据表
- 写入数据到数据库
- 运行app.py,使用flask在本地创建服务器
- 打开网页选择模块
- 查看可视化结果
### 页面展示


<file_sep>/dao.py
# -*- coding = utf-8 -*-
# @Time = 2021/1/5 20:07
# @Author : <NAME>, <NAME>
# @File : dao.py
# @Software : PyCharm
import sqlite3
import datetime
# 初始化 创建数据库
def init_db(dbpath):
conn = sqlite3.connect(dbpath)
print("Opened database successfully when initiating")
cursor = conn.cursor()
# 建表
# id, name, num(许可证编号),province, office, date, life,item(许可项目)
cursor.execute("drop table if exists cosmetics; --如果表存在则删除")
conn.commit()
sql = """
create table if not exists cosmetics
(
id varchar primary key,
name varchar,
num varchar,
province varchar,
office varchar,
date varchar,
life float,
item varchar
)
"""
cursor.execute(sql)
conn.commit()
conn.close()
print("Table created successfully")
def save2db(datalist, dbpath):
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
print("Opened database successfully when saving")
for data in datalist:
# data是一个字典
# 处理province 取发证机关前三个字
province = data['qfManagerName'][0:3]
# 处理life
date_begin = data['xkDateStr'] # 2021-01-06
date_end = data['xkDate']
date_begin = datetime.date(int(date_begin[:4]), int(date_begin[5:7]), int(date_begin[8:10]))
date_end = datetime.date(int(date_end[:4]), int(date_end[5:7]), int(date_end[8:10]))
life = ((date_end - date_begin).days) / 365.0
sql = """
insert into cosmetics(id,name,num,province,office,date,life,item)
values(%s,%s,%s,%s,%s,%s,%f,%s)
""" % ('"' + data['businessLicenseNumber'] + '"', '"' + data['epsName'] + '"', '"' + data['productSn'] + '"',
'"' + province + '"', '"' + data['qfManagerName'] + '"',
'"' + data['xkDateStr'] + '"', life, '"' + data['certStr'] + '"')
try:
cursor.execute(sql)
except:
exit(0)
conn.commit()
cursor.close()
conn.close()
print("Records created successfully")
<file_sep>/main.py
# -*- coding = utf-8 -*-
# @Time = 2021/1/7 20:06
# @Author : <NAME>
# @File : main.py
# @Software : PyCharm
import spider, dao
def main():
# 1. 爬取数据
url = "http://scxk.nmpa.gov.cn:81/xk/itownet/portalAction.do?method=getXkzsList"
data_list = spider.getDataFromUrl(url)
# 2.创建数据库和表
dbpath = "cosmetics.db" # 数据库路径
dao.init_db(dbpath)
# 3.往表里插入数据
dao.save2db(data_list, dbpath)
if __name__ == "__main__":
main()
| 8dab6748516380ba4c2c0d34b8a4dd019be0d7d9 | [
"Markdown",
"Python"
]
| 5 | Python | gugujiang-t/2020_project | e67f1d5dfdc377d91454eb270263fac44ed9da46 | 4dd4d647190c6da2e51796e185a1cd9bd62b26e5 |
refs/heads/master | <file_sep>## Put comments here that give an overall description of what your
## functions do
## Write a short comment describing this function
makeCacheMatrix <- function(x = matrix()) {
mi = NULL
getMatrix <- function() x
setMatrix <- function(matrix) {
mi <<- NULL;
x <<- matrix
}
getCachedInverse <- function() mi
setCachedInverse <- function(inv) mi <<- inv
list(getMatrix = getMatrix, setMatrix = setMatrix, getCachedInverse = getCachedInverse, setCachedInverse = setCachedInverse)
}
## Write a short comment describing this function
cacheSolve <- function(x, ...) {
cached <- x$getCachedInverse()
if (!is.null(cached)) {
message("Guys, we have a cache hit here! What a miracle!")
return(cached)
}
inv <- solve(x$getMatrix(), ...)
x$setCachedInverse(inv)
inv
}
| ba793b0b8a355bfcfff24f9c3092958c0fb50601 | [
"R"
]
| 1 | R | stropa/ProgrammingAssignment2 | d0afc59cb1a335ab95ae12f9d7386fc44628b789 | 668f19b6912f8556f949f7a33329a0f4bf1693ff |
refs/heads/master | <repo_name>Deena786/MVC4<file_sep>/eManager/eManager.Web/Scripts/jsHelpers.js
Bootstrap_alert = function () { }
/**
Bootstrap Alerts -
Function Name - showAlert()
Inputs - message, alerttype, targetId,
Examples - Bootstrap_alert.showAlert("Invalid login", "alert-error", "#alert-container", 3000)
Types of alerts - "alert-success", "alert-info", "alert-warning", "alert-danger"
Required - Bootstrap.css, Bootstrap.js
**/
Bootstrap_alert.showAlert = function (message, alerttype, targetId, timeout) {
$(targetId).html('<div id="bootstrap-alert" class="alert ' + alerttype + ' alert-dismissable fade in out"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><span>' + message + '</span></div>');
$("#bootstrap-alert").fadeOut(timeout);
}
<file_sep>/eManager/eManager.Web/Models/EditEmployeeViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace eManager.Web.Models
{
public class EditEmployeeViewModel
{
[HiddenInput(DisplayValue=false)]
public int Id { get; set; }
[HiddenInput(DisplayValue = false)]
public int DepartmentId { get; set; }
[Required(ErrorMessage="Name is required.")]
[StringLength(50, ErrorMessage="Name is too long. Max. 50 characters.")]
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime? HireDate { get; set; }
}
}<file_sep>/eManager/eManager.Domain/Employee.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace eManager.Domain
{
public class Employee
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
[Column(TypeName = "DateTime2")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public virtual DateTime? HireDate { get; set; }
public virtual Department Department { get; set; }
}
}
<file_sep>/eManager/eManager.Web/Controllers/DepartmentController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using eManager.Domain;
using eManager.Web.Infrastructure;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
namespace eManager.Web.Controllers
{
public class DepartmentController : Controller
{
private IDepartmentDataSource _db = new DepartmentDb();
public ActionResult Detail(int id)
{
var model = _db.Departments.Single(d => d.Id == id);
return View(model);
}
public ActionResult Department_Read (int id, [DataSourceRequest] DataSourceRequest request) {
var department = _db.Departments.Single(d => d.Id == id);
IQueryable<Employee> employees = department.Employees.AsQueryable();
// Deal with circular dependencies
employees = employees.Select(x => new Employee() {
Id = x.Id,
Name = x.Name,
HireDate = x.HireDate,
Department = null
});
DataSourceResult result = QueryableExtensions.ToDataSourceResult(employees, request);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
}
<file_sep>/eManager/eManager.Web/Controllers/EmployeeController.cs
using eManager.Domain;
using eManager.Web.Infrastructure;
using eManager.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace eManager.Web.Controllers
{
//[Authorize(Roles="Admin")]
public class EmployeeController : Controller
{
private IDepartmentDataSource _db = new DepartmentDb();
[HttpGet]
[Authorize(Roles="Admin")]
public ActionResult Create(int id)
{
var model = new CreateEmployeeViewModel();
model.DepartmentId = id;
model.HireDate = DateTime.Today;
if (Request.IsAjaxRequest()) return PartialView("_CreatePartial", model);
return View(model);
}
[HttpPost]
public ActionResult Create(CreateEmployeeViewModel viewModel)
{
if (ModelState.IsValid)
{
var department = _db.Departments.Single(d => d.Id == viewModel.DepartmentId);
var employee = new Employee();
employee.Name = viewModel.Name;
employee.HireDate = viewModel.HireDate;
department.Employees.Add(employee);
_db.Save();
if (Request.IsAjaxRequest()) return Json(JsonResponseFactory.SuccessResponse(), JsonRequestBehavior.DenyGet);
return RedirectToAction("detail", "department", new { id = viewModel.DepartmentId });
}
if (Request.IsAjaxRequest()) return Json(JsonResponseFactory.ErrorResponse("Please review your form."), JsonRequestBehavior.DenyGet);
return View(viewModel);
}
[HttpGet]
public ActionResult Detail(int id)
{
var Employee = _db.Employees.Single(e => e.Id == id);
if (Request.IsAjaxRequest()) return PartialView("_DetailPartial", Employee);
return View(Employee);
}
[HttpGet]
[Authorize(Roles="Admin")]
public PartialViewResult Edit(int id)
{
var Employee = _db.Employees.Single(e => e.Id == id);
var EmployeeEdit = new EditEmployeeViewModel();
EmployeeEdit.Id = Employee.Id;
EmployeeEdit.DepartmentId = Employee.Department.Id;
EmployeeEdit.Name = Employee.Name;
EmployeeEdit.HireDate = Employee.HireDate;
return PartialView("_EditEmployeePartial", EmployeeEdit);
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Edit(EditEmployeeViewModel employee)
{
ModelState.Clear();
if (ModelState.IsValid)
{
var EmployeeToUpdate = _db.Employees.Single(e => e.Id == employee.Id);
EmployeeToUpdate.Name = employee.Name;
_db.EntryChanged(EmployeeToUpdate);
_db.Save();
return Json(JsonResponseFactory.SuccessResponse(), JsonRequestBehavior.DenyGet);
}
return Json(JsonResponseFactory.ErrorResponse("Please review your form."), JsonRequestBehavior.DenyGet);
}
[HttpGet]
[Authorize(Roles="Admin")]
public ActionResult Delete(int id)
{
Employee employee = _db.Employees.Single(e => e.Id == id);
if (employee == null)
{
return HttpNotFound();
}
return View(employee);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Employee employee = _db.Employees.Single(e => e.Id == id);
var deptId = employee.Department.Id;
_db.RemoveEmployee(employee);
_db.Save();
return RedirectToAction("Detail", "Department", new { id = deptId});
}
}
}
<file_sep>/eManager/eManager.Web/Controllers/DataController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using eManager.Domain;
using eManager.Web.Infrastructure;
namespace eManager.Web.Controllers
{
public class DataController : Controller
{
private IDepartmentDataSource _db = new DepartmentDb();
public ActionResult Departments()
{
var allDepartments = _db.Departments;
return View(allDepartments);
}
}
}
| 902cbb6ef42bbe12cf42ee6c125f4d952fec5e6a | [
"JavaScript",
"C#"
]
| 6 | JavaScript | Deena786/MVC4 | e9e956cf3c53d46d5dfb1fa374d679da9a28108a | 5b96ad638ee253d49a2c394ff326bbd38746eea1 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bonus17
{
class Car
{
//create a class named Car to store the data about this car. This class should contain string make, model, int year, double price
private string make;
private string model;
private int year;
private double price;
public string Make //get set for each data piece
{
set { make = value; }
get { return make; }
}
public string Model
{
set { model = value; }
get { return model; }
}
public int Year
{
set { year = value; }
get { return year; }
}
public double Price
{
set { price = value; }
get { return price; }
}
//constructors
//default constructor
public Car() //base constructor?
{
make = "";
model = "";
year = 0;
price = 0;
}
//consturctor with values
public Car(string CarMake, string CarModel, int CarYear, double CarPrice)
{
make = CarMake; //calls Make from the array Car
model = CarModel;
year = CarYear;
price = CarPrice;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bonus17
{
class Program
{
static void Main(string[] args)
{
//create a class named CarApp that gets the user input, creates a car object, and displays the car information
Console.WriteLine("Welcome to the Grand Circus Motors admin console!");
int AmountofCars;
Console.WriteLine("How many cars are you entering:");
AmountofCars = int.Parse(Console.ReadLine());
//create an array to hold the objects
Car[] CarApp = new Car[AmountofCars];
for (int i = 0; i < CarApp.Length; i++)
{
CarApp[i] = new Car(); //create an object
}
//initialize
for (int i = 0; i < CarApp.Length; i++)
{
CarApp[i].Make = Console.ReadLine();
CarApp[i].Model = Console.ReadLine();
CarApp[i].Year = int.Parse(Console.ReadLine());
CarApp[i].Price = double.Parse(Console.ReadLine());
}
Console.WriteLine("Current Inventory:");
Console.WriteLine("Make".PadRight(10,' ') +"\t"+ "Model".PadRight(10, ' ') +"\t" + "Year".PadRight(10, ' ') + "\t" + "Price".PadRight(10, ' '));
foreach (Car Element in CarApp)
{
Console.WriteLine($"{Element.Make.PadRight(10, ' ')} \t{Element.Model.PadRight(10, ' ')} \t{Element.Year.ToString().PadRight(10, ' ')} \t${Element.Price.ToString("N2").PadRight(10, ' ')}");
}
}
public void ValidateMake(string Make)
{
bool check = false;
Console.WriteLine("Please enter the car's Make:");
Make = Console.ReadLine().ToLower(); //include lower and upper case
for (int i = 0; i < Make.Length; i++)
{
if (Make[i] >= 'a' && Make[i] <= 'z' || Make[i] == ' ') //checks for letters a-z and blank spaces
{
check = true;
}
else
{
check = false;
}
}
if (check == false)
{
Console.WriteLine("Enter a valid car Make:");
Make = Console.ReadLine();
}
}
public void ValidateModel(string Model)
{
bool check = false;
Console.WriteLine("Please enter the car Model:");
Model = Console.ReadLine().ToLower(); //check for capitalization
for (int i = 0; i < Model.Length; i++)
{
if (Model[i] >= 'a' && Model[i] <= 'z' || Model[i] == ' ') //checks that only letters a-z are covered for model input
{
check = true;
}
else
{
check = false;
}
}
if (check == false)
{
Console.WriteLine("Enter a valid car model:");
Model = Console.ReadLine();
}
}
public void ValidateYear(int Year)
{
bool check = false;
//drop down list?
Console.WriteLine("Please enter the car Year:");
Year = int.Parse(Console.ReadLine());
if (Year < 1900 && Year > 3000) //covers valid years where cars have been made
{
check = true;
}
else if (check == false)
{
Console.WriteLine("Enter a valid Year:");
Year = int.Parse(Console.ReadLine());
check = false;
}
}
public void ValidatePrice(double Price)
{
Console.WriteLine("Please enter the car Price:");
string input = Console.ReadLine(); //set the input as a string variable
double price; //double variable
if (!double.TryParse(input, out price)) //checks if input is a valid number
{
while (Price < 0) //catches if no number is entered
{
Console.WriteLine("Please enter a valid Price:"); //display message to user
double.TryParse(Console.ReadLine(), out price);
}
}
}
}
}
| 9cab1e92f7e494293d08748dcdf4aa453340fdc9 | [
"C#"
]
| 2 | C# | dowskee/Bonus17 | aab76eaa724f9d65a99b058c38546a2072068f3d | 51d0b84eee79f315bcf856dd0a547b7bc9b0ad40 |
refs/heads/master | <repo_name>jeremysklarsky/flatiron-resources-sinatra<file_sep>/app/models/resource_type.rb
class ResourceTool < ActiveRecord::Base
belongs_to :resource
belongs_to :tool
end<file_sep>/app/models/resource.rb
class Resource < ActiveRecord::Base
belongs_to :student
has_many :resource_subjects
has_many :subjects, through: :resource_subjects
has_many :resource_tools
has_many :tools, through: :resource_tools
def student_name=(name)
if name != ""
self.student = Student.find_or_create_by(:name => name)
end
end
def tool_name=(name)
if name != ""
self.tools << Tool.find_or_create_by(:name => name)
end
end
def subject_name=(name)
if name != ""
self.subjects << Subject.find_or_create_by(:name => name)
end
end
def add_karma
if self.karma == nil
self.karma = 1
else
self.karma += 1
end
self.save
end
end
<file_sep>/app/controllers/resources_controller.rb
class ResourcesController < ApplicationController
get '/cohorts/:id/resources' do
@cohort = Cohort.find(params[:id])
@resources = Resource.all
erb :'resources/index'
end
get '/cohorts/:id/resources/new' do
@cohort = Cohort.find(params[:id])
@students = @cohort.students
@tools = Tool.all
@subjects = Subject.all
erb :'resources/new'
end
get '/cohorts/:id/resources/:resource_id' do
@cohort = Cohort.find(params[:id])
@resource = Resource.find(params[:resource_id])
erb :'resources/show'
end
post '/cohorts/:id/resources' do
@resource = Resource.create(params[:resource])
@resource.save
redirect "/cohorts/#{params[:id]}/resources"
end
patch '/cohorts/:id/resources/:resource_id' do
@resource = Resource.find(params[:resource_id])
@resource.update(params[:resource])
@resource.save
redirect "/cohorts/#{params[:id]}/resources"
end
get '/cohorts/:id/resources/:resource_id/edit' do
@cohort = Cohort.find(params[:id])
@students = @cohort.students
@resource = Resource.find(params[:resource_id])
erb :'resources/edit'
end
post '/cohorts/:cohort_id/resources/:resource_id/karma' do
@resource = Resource.find(params[:resource_id])
@resource.add_karma
redirect back
end
delete '/cohorts/:id/resources/:resource_id' do
@resource = Resource.find(params[:resource_id])
@resource.destroy
redirect "/cohorts/#{params[:id]}/resources"
end
end<file_sep>/app/models/subject.rb
class Subject < ActiveRecord::Base
has_many :resource_subjects
has_many :resources, through: :resource_subjects
end<file_sep>/db/seeds.rb
ruby007 = Cohort.create(:name => "ruby007")
alex_test = Student.create(:name => "<NAME>", :cohort_name => "Ruby-007")
erb_sublime = Resource.create(:name => "ERB Sublime plugin", :link => "https://github.com/eddorre/SublimeERB", :student_name => "<NAME>", :description => "ERB Sublime thingy lets you make a shortcut to getting your ERB tags easily (i.e. <% %>)")
alex_test.save
erb_subj = Subject.create(:name => "ERB")
sinatra_subj = Subject.create(:name => "Sinatra")
env_setup_tool = Tool.create(:name => "Environment Setup")
sublime_tool = Tool.create(:name => "Sublime")
erb_sublime.tool_name = "Environment Setup"
erb_sublime.tool_name = "Sublime"
erb_sublime.subject_name = "ERB"
erb_sublime.subject_name = "Sinatra"
alex_test.save
erb_sublime.save
StudentNameScraper.new("Ruby-007").call<file_sep>/app/models/tool.rb
class Tool < ActiveRecord::Base
has_many :resource_tools
has_many :resources, through: :resource_tools
end<file_sep>/app/controllers/students_controller.rb
class StudentsController < ApplicationController
get '/cohorts/:cohort_id/students' do
@cohort = Cohort.find(params[:cohort_id])
@students = @cohort.students
erb :'students/index'
end
get '/cohorts/:cohort_id/students/:student_id' do
@cohort = Cohort.find(params[:cohort_id])
@student = Student.find(params[:student_id])
erb :'students/show'
end
end<file_sep>/app/controllers/cohorts_controller.rb
class CohortsController < ApplicationController
get '/cohorts' do
@cohorts = Cohort.all
erb :'cohorts/index'
end
get '/cohorts/new' do
erb :'cohorts/new'
end
post '/cohorts' do
Cohort.create(:name => params[:cohort][:name])
StudentNameScraper.new(params[:cohort][:name]).call
redirect '/cohorts'
end
end<file_sep>/lib/StudentNameScraper.rb
class StudentNameScraper
attr_accessor :cohort, :doc
def initialize(year)
@cohort = year
end
def slug
cohort.downcase.gsub("-", "").gsub(" ", "")
end
def get_info
html = open("http://#{self.slug}.students.flatironschool.com/")
@doc = Nokogiri::HTML(html)
doc.search("li.home-blog-post").collect do |student|
[student.search("div.blog-title a").text, student.search("img").attr("src").value, slug]
end
end
def call
get_info.each do |name|
build_students(*name)
end
end
def build_students(name, pic_link, cohort)
student = Student.create(name: name, pic_link: pic_link, cohort_name: cohort)
student.save
end
end<file_sep>/app/models/cohort.rb
class Cohort < ActiveRecord::Base
has_many :students
has_many :resources, through: :students
end<file_sep>/app/controllers/subjects_controller.rb
class SubjectsController < ApplicationController
get '/cohorts/:cohort_id/subjects' do
@cohort = Cohort.find(params[:cohort_id])
@subjects = Subject.all
erb :'/subjects/index'
end
get '/cohorts/:cohort_id/subjects/:subject_id' do
@cohort = Cohort.find(params[:cohort_id])
@subject = Subject.find(params[:subject_id])
erb :'/subjects/show'
end
end<file_sep>/app/models/student.rb
class Student < ActiveRecord::Base
belongs_to :cohort
has_many :resources
def cohort_name=(name)
self.cohort = Cohort.find_or_create_by(:name => name.downcase.gsub("-", "").gsub(" ", ""))
end
def total_karma
student_karma = self.resources.collect {|resource| resource.karma}
student_karma.inject(:+)
end
end<file_sep>/app/controllers/tools_controller.rb
class ToolsController < ApplicationController
get '/cohorts/:cohort_id/tools' do
@cohort = Cohort.find(params[:cohort_id])
erb :'/tools/index'
end
get '/cohorts/:cohort_id/tools/:tool_id' do
@cohort = Cohort.find(params[:cohort_id])
@tool = Tool.find(params[:tool_id])
erb :'/tools/show'
end
end<file_sep>/app/controllers/root_controller.rb
class RootController < ApplicationController
get '/' do
redirect '/cohorts'
end
end<file_sep>/README.md
# Flatiron Web Immersive Resources Catalog
This is a Sinatra powered web app to help Flatiron Students keep track of useful resources, shortcuts, and gems they come across during the course of the semester.
Students can add new resources and tag the entry by subject (ruby, sinatra, SQL, etc..) and type of tool it is (gem, useful link, shortcut, etc).
Give karma to people by upvoting resources you have enjoyed!
##TO DO
Slack notification integration
Sortable tables
<file_sep>/db/migrate/20150304154602_resource_subjects.rb
class ResourceSubjects < ActiveRecord::Migration
def change
create_table :resource_subjects do |t|
t.integer :resource_id
t.integer :subject_id
end
end
end
| b532dfc4cd204e4185a8ff865eaa3160f95c1d16 | [
"Markdown",
"Ruby"
]
| 16 | Ruby | jeremysklarsky/flatiron-resources-sinatra | 94dda92071b6853037cdc440f7d63fc4d225bd96 | 2ffeaed0450aa296dac2525b10522c053560abf2 |
refs/heads/master | <repo_name>NoyaKohavi/LINEAGE<file_sep>/build_test_database.py
''' lxml tutorial : https://lxml.de/tutorial.html '''
''' Elements carry attributes as a dict '''
from lxml import etree
# high-level structure
root = etree.Element('data')
archival_images = etree.SubElement(root,'archival_images')
fashion_images = etree.SubElement(root, 'fashion_images')
# populate:
# for item in folder add name to tag space and path to URL space, leave all other fields empty
import os
folder = '/Users/noyakohavi/Desktop/BROWN/test_set'
allfiles = os.listdir(folder)
for x in allfiles:
x = x.split('.')[0]
if 'f' in x:
etree.SubElement(fashion_images, x, url=folder+'/'+x, dom_color='', sec_color='')
if 'a' in x:
archival = etree.SubElement(archival_images, x, url=folder+'/'+x, dom_color='', sec_color='')
# pretty print database
print(etree.tostring(root, pretty_print=True))
# write database to file
with open('/Users/noyakohavi/Desktop/BROWN/test_database.xml','w') as f:
f.write(etree.tostring(root,pretty_print=True))
# find similar images by feature property :
same = []
not_same = []
for archival_images in root:
for image in archival_images:
if image.get('dom_color') == 'red': ### and image.get('sec_color') == 'green':# --> add multiple conditions
same.append(image.tag)
else:
not_same.append(image.tag)
print 'same', same
print 'not same', not_same
| 7106523a24303647b6e20c82cf13d1791ff10c29 | [
"Python"
]
| 1 | Python | NoyaKohavi/LINEAGE | 7ce1519bffcca319b5b37e905b5c22fd0796cc8f | f32e6764dfd42a87a06d096de2b208858076de0a |
refs/heads/master | <repo_name>t04glovern/eks-kubeflow-demo<file_sep>/eks-kubeflow-install.sh
# Change to what you set in Cognito
export COGNITO_AUTH_DOMAIN=kubeflow-devopstar
export AWS_REGION=us-west-2
export AWS_CLUSTER_NAME=eks-kubeflow
export AWS_COGNITO_STACK_NAME=eks-kubeflow-cognito
export COGNITO_USER_POOL=$(aws cloudformation describe-stacks --stack-name $AWS_COGNITO_STACK_NAME \
--region $AWS_REGION \
--query 'Stacks[0].Outputs[?OutputKey==`UserPool`].OutputValue' \
--output text)
export COGNITO_CLIENT_APP_ID=$(aws cloudformation describe-stacks --stack-name $AWS_COGNITO_STACK_NAME \
--region $AWS_REGION \
--query 'Stacks[0].Outputs[?OutputKey==`UserPoolClientId`].OutputValue' \
--output text)
AWS_CLUSTER_NODE_ROLE_LONG=$(aws eks describe-nodegroup --nodegroup-name nodegroup \
--region $AWS_REGION \
--cluster-name $AWS_CLUSTER_NAME \
--query 'nodegroup.nodeRole')
export AWS_CLUSTER_NODE_ROLE=$(echo $AWS_CLUSTER_NODE_ROLE_LONG | cut -b 33- | rev | cut -c 2- | rev)
export BASE_DIR=${PWD}
export KF_NAME=${AWS_CLUSTER_NAME}
export KF_DIR=${BASE_DIR}/${KF_NAME}
export CONFIG_URI="https://raw.githubusercontent.com/kubeflow/manifests/v1.0-branch/kfdef/kfctl_aws_cognito.v1.0.1.yaml"
export CONFIG_FILE=${KF_DIR}/kfctl_aws.yaml<file_sep>/README.md
# EKS Kubeflow Demo - Cognito Authorization
Checkout the [Blog post for this repository](https://devopstar.com/2020/03/31/kubeflow-on-eks-cognito-authentication)
| 4dd92fe9203ab5e1e06975057f6a3dbadf357bae | [
"Markdown",
"Shell"
]
| 2 | Shell | t04glovern/eks-kubeflow-demo | e174f09a45d765fcaa72c2d40e517cedb684fd24 | c2ba0db1a9e620450f564444a31222036d32bf42 |
refs/heads/master | <repo_name>kongxianglei0403/snaphelperdemo<file_sep>/app/src/main/java/com/example/myapplication/SnapHelperAdapter.kt
package com.example.myapplication
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
/**
*Create by 阿土 on ${date}
*/
class SnapHelperAdapter(val context: Context,val list: List<String>): RecyclerView.Adapter<SnapHelperAdapter.SnapHelperViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SnapHelperViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false)
return SnapHelperViewHolder(view)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: SnapHelperViewHolder, position: Int) {
holder.tv.text = list[position]
}
inner class SnapHelperViewHolder(view: View): RecyclerView.ViewHolder(view){
val tv = view.findViewById(R.id.tv) as TextView
}
}<file_sep>/app/src/main/java/com/example/myapplication/GallerySnapHelper.kt
package com.example.myapplication
import android.util.DisplayMetrics
import android.view.View
import androidx.recyclerview.widget.*
/**
*Create by 阿土 on ${date}
*/
class GallerySnapHelper: SnapHelper() {
private val INVALID_DISTANCE = 1f
private val MILLISECONDS_PER_INCH = 40f
private var mHorizontalHelper: OrientationHelper? = null
private var mRecyclerView: RecyclerView? = null
override fun attachToRecyclerView(recyclerView: RecyclerView?) {
mRecyclerView = recyclerView
super.attachToRecyclerView(recyclerView)
}
/**
* 该方法会计算第二个参数 对应的itemview当前的坐标到要对的view的坐标的距离
* 返回int[2] 对应x轴和y轴方向上的距离
*/
override fun calculateDistanceToFinalSnap(layoutManager: RecyclerView.LayoutManager, targetView: View): IntArray? {
val array = IntArray(2)
if (layoutManager.canScrollHorizontally()){
array[0] = distanceToStart(targetView,getHorizontalHelper(layoutManager))
}
return array
}
/**
* 该方法会根据触发fling操作的速率 (参数 velocityX 和velocityY) 确定recyclerview需要滚动到的位置
* 该位置上的itemview就是要对齐的项 该位置就是TargetSnapPosition 如果找不到就返回RecyclerView.NO_POSITION
*/
override fun findTargetSnapPosition(
layoutManager: RecyclerView.LayoutManager,
velocityX: Int,
velocityY: Int
): Int {
//因为layoutmanager很灵活 分为横向/纵向两种布局方式 每个布局上又有方向上的不同 正向/反向
//计算targetposition时都考虑进去了
//布局方向就通过RecyclerView.SmoothScroller.ScrollVectorProvider这个接口中的computeScrollVectorForPosition()方法来判断。
if (layoutManager !is RecyclerView.SmoothScroller.ScrollVectorProvider) {
return RecyclerView.NO_POSITION
}
val itemCount = layoutManager.itemCount
if (itemCount == 0){
return RecyclerView.NO_POSITION
}
val snapView = findSnapView(layoutManager)
if (null == snapView){
return RecyclerView.NO_POSITION
}
val snapPosition = layoutManager.getPosition(snapView)
if (snapPosition == RecyclerView.NO_POSITION){
return RecyclerView.NO_POSITION
}
val vectorProvider = layoutManager as RecyclerView.SmoothScroller.ScrollVectorProvider
val vectorEnd = vectorProvider.computeScrollVectorForPosition(itemCount - 1)
if (vectorEnd == null){
return RecyclerView.NO_POSITION
}
//手指松开屏幕 列表最多滑动一屏的item数
val deltaThreshold = layoutManager.width / getHorizontalHelper(layoutManager).getDecoratedMeasurement(snapView)
var deltaJump = 0
if (layoutManager.canScrollHorizontally()){
deltaJump = estimateNextPositionDiffForFling(layoutManager,getHorizontalHelper(layoutManager),velocityX,0)
if (deltaJump > deltaThreshold){
deltaJump = deltaThreshold
}
if (deltaJump < -deltaThreshold){
deltaJump = -deltaThreshold
}
if (vectorEnd.x < 0){
deltaJump = -deltaThreshold
}
}
else{
deltaJump = 0
}
if (deltaJump == 0){
return RecyclerView.NO_POSITION
}
var targetPostion = deltaJump + snapPosition
if (targetPostion < 0){
targetPostion = 0
}
if (targetPostion >= itemCount){
targetPostion = itemCount - 1
}
return targetPostion
}
/**
* 估算位置偏移量
*/
private fun estimateNextPositionDiffForFling(
layoutManager: RecyclerView.LayoutManager,
helper: OrientationHelper,
velocityX: Int,
velocityY: Int
): Int {
val distances = calculateScrollDistance(velocityX, velocityY)
val perChild = computeDistancePerChild(layoutManager, helper)
if (perChild <= 0){
return 0
}
val distance = distances[0]
if (distance > 0){
return Math.floor((distance / perChild).toDouble()).toInt()
}
else{
return Math.ceil((distance / perChild).toDouble()).toInt()
}
}
/**
* 计算每个itemview的长度
*/
private fun computeDistancePerChild(
layoutManager: RecyclerView.LayoutManager,
helper: OrientationHelper
): Float {
var minPosView: View? = null
var maxPosView: View? = null
var minPos = Int.MIN_VALUE
var maxPos = Int.MAX_VALUE
val childCount = layoutManager.childCount
if (childCount == 0){
return INVALID_DISTANCE
}
for(index in 0 until childCount){
val view = layoutManager.getChildAt(index)!!
val position = layoutManager.getPosition(view)
if (position == RecyclerView.NO_POSITION){
continue
}
if (position < minPos){
minPos = position
minPosView = view
}
if (position > maxPos){
maxPos = position
maxPosView = view
}
}
if (minPosView == null || maxPosView == null){
return INVALID_DISTANCE
}
//因为不确定起点和终点 所以取两个位置的最小值作为起点 最大值作为终点
val start = Math.min(helper.getDecoratedStart(minPosView), helper.getDecoratedStart(maxPosView))
val end = Math.max(helper.getDecoratedEnd(minPosView), helper.getDecoratedEnd(maxPosView))
val distance = end - start
if (distance == 0){
return INVALID_DISTANCE
}
// 总长度 / 总个数 = 每个item的长度
return 1f * distance / ((maxPos - minPos) + 1)
}
/**
* 找到当前layoutmanager上最接近对齐位置的那个view 就是snapview
* 如果返回null 就表示没有要对齐的view 不做滚动对齐处理
*/
override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? {
return findStartView(layoutManager,getHorizontalHelper(layoutManager))
}
private fun findStartView(layoutManager: RecyclerView.LayoutManager, helper: OrientationHelper): View? {
if (layoutManager is LinearLayoutManager){
val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
if (firstVisibleItemPosition == RecyclerView.NO_POSITION){
return null
}
val itemCount = layoutManager.itemCount
if (itemCount == 0)
return null
val lastCompletelyVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition()
//如果是最后一个 那就不做左对齐处理 不然的话会显示不全 返回null 表示不做对齐处理
if (lastCompletelyVisibleItemPosition == itemCount - 1){
return null
}
val firstView = layoutManager.findViewByPosition(firstVisibleItemPosition)
//如果第一个itemview被遮住的长度没有超过一半 就把itemview当成snapview
//否则把下一个itemview当成 snapview
if (helper.getDecoratedEnd(firstView) >= helper.getDecoratedMeasurement(firstView) / 2
&& helper.getDecoratedEnd(firstView) > 0){
return firstView
}
else{
return layoutManager.findViewByPosition(firstVisibleItemPosition + 1)
}
}
else{
return null
}
}
//左对齐
private fun distanceToStart(targetView: View, helper: OrientationHelper): Int {
return helper.getDecoratedStart(targetView) - helper.startAfterPadding
}
private fun getHorizontalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper {
return mHorizontalHelper?: OrientationHelper.createHorizontalHelper(layoutManager)
}
/**
* 该方法是为了设置
*/
override fun createScroller(layoutManager: RecyclerView.LayoutManager?): RecyclerView.SmoothScroller? {
return if (layoutManager !is RecyclerView.SmoothScroller.ScrollVectorProvider) {
null
} else object : LinearSmoothScroller(mRecyclerView?.context) {
override fun onTargetFound(
targetView: View,
state: RecyclerView.State,
action: RecyclerView.SmoothScroller.Action
) {
if (mRecyclerView == null) {
return
}
val snapDistances = calculateDistanceToFinalSnap(mRecyclerView!!.layoutManager!!, targetView)
val dx = snapDistances!![0]
val dy = snapDistances[1]
val time = calculateTimeForDeceleration(Math.max(Math.abs(dx), Math.abs(dy)))
if (time > 0) {
action.update(dx, dy, time, mDecelerateInterpolator)
}
}
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
return MILLISECONDS_PER_INCH / displayMetrics.densityDpi
}
}
}
}<file_sep>/app/src/main/java/com/example/myapplication/MainActivity.kt
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recycler.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
recycler.adapter = SnapHelperAdapter(this,initData())
GallerySnapHelper().attachToRecyclerView(recycler)
}
private fun initData(): List<String> {
val list = arrayListOf<String>()
(0 until 60).mapTo(list){ "$it=atu"}
return list
}
}
| 872e4720fc060ef841a6bffcafacd41481584eef | [
"Kotlin"
]
| 3 | Kotlin | kongxianglei0403/snaphelperdemo | 655021f3d0f92b106cad4b5403ae9c108380f0d5 | 72841487de7934af715721e63f7957c60588292b |
refs/heads/master | <repo_name>lin-lab/MetaSKAT<file_sep>/src/Interface_Meta.cpp
#include "RFunc.h"
#include "Meta.h"
/************************************************
************************************************/
extern "C" {
/* 1: little endian, 0: big endian (only little endian is valid)*/
void IsLittleEndian(int * re){
*re = endian();
}
/*************************************************************
MAT file for read
"MAT" and "MSSD" are the same
*************************************************************/
void META_MSSD_Read_Open_Init(int * pNumPop, int * err){
*err = Init_MatFile_Read(pNumPop[0]);
}
void META_MSSD_Read_Open(int * pidx, char ** pFileName, int * err){
*err = Open_NewMatFile_Read(pidx[0], pFileName[0]);
}
void META_MSSD_GetData(int * pidx, double * mat, double * pstart, int * pnmarker, int *err){
long start = (long)pstart[0];
*err =Mat_GetData(pidx[0], mat, start, pnmarker[0]);
}
void META_MSSD_Read_Close(int * pidx, int * err){
*err = Close_MatFile(pidx[0]);
}
/*************************************************************
MAT file for save
*************************************************************/
void META_MSSD_Write_Init(int * err){
*err = Mat_Init_Save();
}
void META_MSSD_Write_Open(char ** pFileName, int *err){
*err =Open_NewMatFile_Save(pFileName[0]);
}
void META_MSSD_Write(double * mat, int * psize, int *err){
*err = Mat_PutData(mat, psize[0]);
}
void META_MSSD_Check_Saved(int *err){
*err = Mat_Check_Saved();
}
void META_MSSD_Num_Sets(int * nsets, int *err){
*nsets = Mat_Num_Sets();
}
void META_MSSD_GetStart_Pos(double * pos, int * size, int *err){
*err = Mat_GetStart_Pos(pos, size);
}
void META_MSSD_Write_Close(int * err){
*err = Close_Write_MatFile();
}
/*************************************************************
Bed file for read
*************************************************************/
void META_BED_Init(char** pfilename, int* pNSample, int* pNSnp, int *err){
*err = Bed_Init(pfilename[0], pNSample[0], pNSnp[0]);
}
void META_BED_Read(int * pIdxs, unsigned char * Genotype, int * pnum, int *err){
*err = Bed_ReadData(pIdxs, pnum[0], Genotype);
}
void META_BED_Close(int *err){
*err = Bed_Close();
}
/*************************************************************
Dosage file for read
*************************************************************/
void META_Dosage_Init(char** pfilename, int* pNSample, int* pNSnp, int *err){
*err = Dosage_Init(pfilename[0], pNSample[0], pNSnp);
}
void META_Dosage_Read(int * pIdxs, float * Dosage, int * pnum, int *err){
*err = Dosage_ReadData(pIdxs, pnum[0], Dosage);
}
void META_Dosage_Close(int *err){
*err = Dosage_Close();
}
void META_Dosage_Info(char * pSNPID, char *pa1, char *pa2 , int *err){
*err = Dosage_Info(pSNPID, pa1, pa2);
}
} // extern "C"
<file_sep>/R/SSD.R
Print_Error_SSD<-function(code){
if(code == 0 ){
return(0);
} else if(code == 1){
stop("Error Can't open BIM file")
} else if(code == 2){
stop("Error Can't open FAM file")
} else if(code == 3){
stop("Error Can't open BED file")
} else if(code == 4){
stop("Error Can't open SETID file")
} else if(code == 5){
stop("Error Can't write SSD file")
} else if(code == 6){
stop("Error Can't read SSD file")
} else if(code == 7){
stop("Error Can't write INFO file")
} else if(code == 8){
stop("Error Can't read INFO file")
} else if(code == 9){
stop("Error Can't write INFO file")
} else if(code == 13){
stop("Error Wrong SNP or Individual sizes")
} else if(code == 14){
stop("Error SetID not found")
} else {
MSG<-sprintf("Error [%d]\n",code)
stop(MSG)
}
return(1)
}
Check_File_Exists<-function(FileName){
if(!file.exists(FileName)){
Msg<-sprintf("File %s does not exist\n",FileName)
stop(Msg)
}
}
MetaSKAT_Is_IsLittleEndian<-function(){
re<-0
temp<-.C("IsLittleEndian", as.integer(re))
re1<-temp[[1]]
if(re1 == 0){
stop("MSSD files can only be used on a little endian machine")
}
}
<file_sep>/README.md
# MetaSKAT
MetaSKAT is a R package for multiple marker meta-analysis. It can carry out meta-analysis of SKAT, SKAT-O and burden tests with individual level genotype data or gene level summary statistics.
## User Group
Please join the [SKAT/MetaSKAT Google Group](https://groups.google.com/forum/#!forum/skat_slee) to ask / discuss / comment about [SKAT](https://github.com/lin-lab/SKAT)/MetaSKAT.
## Download
We uploaded the package to CRAN. You can download the package, manual, and vignettes [here](https://cran.r-project.org/package=MetaSKAT).
## References
+ <NAME>, <NAME>, <NAME>, <NAME>, General Framework for Meta-analysis of Rare Variants in Sequencing Association Studies, In The *American Journal of Human Genetics*, Volume 93, Issue 1, 2013, Pages 42-53, ISSN 0002-9297, doi:[10.1016/j.ajhg.2013.05.010](https://doi.org/10.1016/j.ajhg.2013.05.010).
| 562aa184b7e6b8b566d4d9e1af8a8ccb128b0bc9 | [
"Markdown",
"R",
"C++"
]
| 3 | C++ | lin-lab/MetaSKAT | da7e0db47acd8f6fb67cd08648546bd7d2a474e0 | b90f6152346329dfe54b8bfdf24ef698d4a9ccff |
refs/heads/master | <repo_name>ashraf-git/JS_For_All<file_sep>/chapter_eight/return.js
function addAll(){
var sum = 0;
for(var i=0; i<arguments.length; i++){
sum+=arguments[i]
}
return sum
}
var result = addAll(1, 2, 3, 4)
console.log(result)
function person(name, email){
return{
name: name,
email: email
}
// console.log('something')
}
var p1 = person('aliahsraf', '<EMAIL>')
console.log(p1)<file_sep>/chapter_four/break.js
while(true){
var rend = Math.floor(Math.random() *10 + 1);
if(rend === 9){
console.log('you are wining 9')
break
}else{
console.log(' this is ' + rend)
}
}
for(var i = 3; i < 10; i++){
if(i%5 === 0){
break
}else{
console.log(i)
}
}<file_sep>/chapter_two/operator.js
// Arithmetic operators
// + - * / % ++ --
// var a = 11
// var b = 3
// console.log(a % b);
// Pre-increment - post increment
// console.log(a++)
// console.log(a)
// console.log(b--)
// console.log(b)
//assignment operators
// var a = 10;
// var b = 20;
// a += b
// console.log(a)
// a-=b
// console.log(a)
// a*=b
// console.log(a)
// a /= b
// console.log(a)
// a %= b
// console.log(a)
//comparison operators
// == != === !== > < >= <=
// var a = 20
// var b = 10
// console.log(a == b)// false
// console.log(a != b)// true
// console.log(a > b)// true
// console.log(a < b)// false
// b = 20
// console.log(a >= b)// true
// console.log(a <= b)// false/true
// var c = '50'
// var d = 50
// console.log(c === d)//false
// console.log(c !== d)//true
// Logical operators
// &&
// ||
// !
//Bitwise operators
// &
// |
// ~
// ^
// <<
// >>
// type of operator
console.log(typeof "ashraf")
console.log(typeof 52)<file_sep>/chapter_six/insertRemove.js
// Insert and Remove Elements
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
// Insert 10 to index 3
// arr[3] = 10
// arr.push(10)
// arr.unshift(10)
// arr.splice(3, 0, 23, 45)
// arr[3] = undefined
// arr.pop()
// arr.shift()
arr.splice(3, 1)
arr.splice(3, 1, 44)
console.log(arr)<file_sep>/chapter_seven/iterate.js
var obj = {
a: 34,
b: 63,
c: 98
}
// console.log('a' in obj)
// console.log('k' in obj)
for(var i in obj) {
console.log(i)
console.log(i + ':' + obj[i])
}<file_sep>/chapter_nine/pure.js
// what is Pure Function?
// It returns the same result if given the same arguments
// it doesn't cause any observable side effect
function sqr(n){
return n*n
}
console.log(sqr(3))
console.log(sqr(3))
console.log(sqr(3))
var n = 30
function change() {
n = 289
}
change()
console.log(n)
var point = {
x: 20,
y: 30
}
function printPiont(point) {
point.x = 100
point.y = 200
console.log(point)
}
printPiont(point)
console.log(point)
<file_sep>/chapter_three/if.js
var a = 30;
var b = 20;
if(a > b){
console.log("A is greater than B");
}
if(a < b){
console.log("B is greater than A");
}
var n = 50
if( n%2 == 0 ){
console.log(n + ' is even number');
}
if(n % 2 == 1) {
console.log(n + ' is odd number');
}<file_sep>/chapter_six/array.js
var arr = [1, 2, 3, 4, 5];
console.log(arr)
console.log(arr[3])
console.log(arr[4])
arr[5] = 6
console.log(arr[5])
console.log(arr)
console.log(arr[7])
arr[11] = 44
console.log(arr)
console.log(arr.length)
arr[2] =22
console.log(arr)
arr2 = Array(10,14,54,54,878,65)
console.log(arr2)
<file_sep>/chapter_two/statements.js
console.log('<NAME>')
var str = 'string'
var number = 3 + (43 * 4) * 5
var a = 34
var b = 44
var c = a >= b<file_sep>/chapter_nine/reduce.js
var arr = [52, 1, 2, 585, 3, 4, 5]
// var sum = arr.reduce(function(prev, curr){
// return prev + curr
// }, 100)
// console.log(sum)
// var max = arr.reduce(function(prev, curr){
// return Math.max(prev, curr)
// }, 0)
// console.log(max)
function myReduce(arr, cb, acc){
for(var i = 0; i < arr.length; i++) {
acc = cb(acc, arr[i])
}
return acc
}
var sum = myReduce(arr, function(prev, curr){
return prev + curr
},0)
console.log(sum)
var max = myReduce(arr, function(prev, curr){
return Math.max(prev, curr)
},0)
console.log(max)
var min = myReduce(arr, function(prev, curr){
return Math.min(prev, curr)
}, arr[0])
console.log(min)<file_sep>/chapter_nine/currying.js
function add(a, b, c){
return a + b + c;
}
var result1 = add(3, 5, 5)
console.log(result1)
function currying(a){
return function (b){
return function (c){
return a + b + c
}
}
}
var result =currying(3)(4)(5)
console.log(result)<file_sep>/chapter_nine/forEach.js
var arr = [1, 2, 3, 4, 5];
// var sum = 0;
// arr.forEach(function(value, index, arr){
// // console.log(value, index, arr)
// sum += value
// })
// console.log(sum)
function forBeach(arr, cb) {
var sum = 0;
for(var i = 0; i < arr.length; i++){
cb(arr[i], i , arr)
}
}
var sum = 0;
forBeach(arr, function(value, index, arr){
console.log(value, index, arr)
sum += value
})
console.log(sum)
forBeach(arr, function(value, index, arr){
arr[index] = value + 5
})
console.log(arr)<file_sep>/chapter_eight/function.js
// var date = new Date()
// date.getFullYear()
function functionName(){
console.log('I am a function')
}
function add(){
var a = 20;
var b = 48;
console.log(a+b)
}
function sub(){
var a = 40;
var b = 20;
console.log(a-b)
}
// functionName()
// functionName()
for(var i = 0; i < 10; i++){
functionName();
}
add();
sub();
console.log(add())<file_sep>/chapter_nine/firstclass.js
// First Class Function
function add(a, b) {
return a + b;
}
// 1. A Function can be stored in a variable
var sum = add
console.log(sum(2, 5))
console.log(typeof sum)
// 2. A function can be stored in a Array
var arr = []
arr.push(add)
console.log(arr)
console.log(arr[0](3, 5))
// 3. A function can be stored in a Object
var obj = {
sum: add
}
console.log(obj)
console.log(obj.sum(2, 8))
// 4. We can create function as needed
setTimeout(function() {
console.log('I have created...')
}, 1000)
// 5. We can pass a function as a arguments
// 6. We can return function from another function
<file_sep>/chapter_seven/methods.js
var obj = {
a: 434,
b: 878,
c: 349
};
console.log(Object.keys(obj));
console.log(Object.values(obj))
console.log(Object.entries(obj))
// var obj2 = obj
// obj2.a = 4354
// obj2.b = 87878
// console.log(obj)
// console.log(obj2)
var obj2 = Object.assign({}, obj);
obj2.a = 4
console.log(obj)
console.log(obj2)<file_sep>/chapter_six/traverse.js
// Travarse in javascript
var arr = [2, 54, 554, 54, 879, 556, 47, 54, 57];
// arr[0]
// arr[1]
// // arr[2]
// arr[arr.length-1]
// for(var i=0; i<arr.length; i++){
// // console.log(arr[i]);
// arr[i] = arr[i] + 2
// }
// console.log(arr[i])
// var sum = 0;
// for(var i=0; i<arr.length; i++){
// sum += arr[i]
// }
// console.log(sum)
// for (var i=0; i<arr.length; i++){
// if(arr[i]%2 === 0){
// console.log(arr[i])
// }
// }
var oddSum = 0;
for(var i=0; i<arr.length; i++){
if(arr[i]%2 ===1){
oddSum += arr[i]
}
}
console.log(oddSum)
var evenSum = 0;
for(var i=0; i<arr.length; i++){
if(arr[i]% 2 === 0){
evenSum += arr[i]
}
}
console.log(evenSum)
console.log(evenSum + oddSum)<file_sep>/chapter_two/datatypes.js
// primitive
// number
// String
// undefined
// null
// object
// object
// function
// array
// ****** number ******
// var n = 34;
// var f = 88.88;
// var nn = Number('53.67');
// console.log(nn);
// console.log(Number.parseInt(nn));
// console.log(Number.MAX_VALUE);
// console.log(Number.MIN_SAFE_INTEGER);
// console.log(1/0);
// console.log('Number' * 20);
// ****** String ******
// literal string
// var str = '123';
// var str2 = "String";
// var str5 = `String`;
// constructor string
// var str6 = String(3.54);
// var str3 = String("aliashraf");
// var str4 = String(25);
// console.log(str3, str5, str6)
// ****** Boolean ******
// var b1 = true;
// var b2 = false;
// var b3 = Boolean(true);
// var b4 = Boolean(false);
// console.log(b3, b4);
// ****** Null vs undefined ******
var abc
var xyz = null;
console.log(xyz);
console.log(abc);
var hex = 0xff
console.log(hex);
var oct = 0755;
console.log(oct);
<file_sep>/chapter_nine/return.js
function greet(msg) {
function greetings(name) {
return msg + ' ' + name
}
return greetings
}
var gm = greet('Good Morning')
// console.log(typeof gm)
var gn = greet('Good Night')
var hello = greet('Helloe')
var msg = gm('<NAME>')
console.log(msg)
console.log(gn('<NAME>'))
console.log(hello("Cats"))<file_sep>/chapter_four/forloop.js
// // for loops
// for(var i = 0; i < 500; i+=100) {
// console.log(i + 1 + ' <NAME>')
// }
// for (var i = 1; i <= 100; i++){
// console.log(i)
// }
// for(var i = 1; i <= 100; i+= 2){
// console.log(i)
// }
// for(var i = 1; i <= 100; i++){
// if(i%2 === 0){
// console.log(i)
// }
// }
// var sum = 0;
// for(var i = 1; i <=10; i++){
// console.log(sum + '+' + i +'='+ (sum + 1))
// sum += i
// }
// var sum = 0;
// for(var i =1; i <=10; i++){
// console.log(sum + '+' + i + '=' + (sum + i))
// sum += i
// }
// console.log('result = ' + sum)
var sum = 0;
for(var i =1; i <=10; i++){
console.log( sum + i)
sum += i
}
console.log('result = ' + sum)
<file_sep>/chapter_four/infinityloop.js
for(; ;){
var rend = Math.floor(Math.random() *10 + 1)
if(rend ===9 ){
console.log('your render is wining')
break
}else{
console.log('this is ' + rend)
}
}<file_sep>/chapter_two/variables.js
var name = '<NAME>'
var age = 33
console.log(name)
console.log(age)
console.log(name + ' knows Javascript');
console.log('His age is only '+ age)
console.log( name + ' is creating a course for all students')
console.log('But his age is only ' + age)
// const else = 'ashraf'
// console.logK(else)
/*
var mathNumber = 34
var accountNumverDetailsId = 102
var account_number_details_id
*/<file_sep>/chapter_two/math.js
console.log(Math.E)
console.log(Math.PI)
var n = 4.689
console.log(Math.abs(n))
console.log(Math.floor(n))
console.log(Math.ceil(n))
console.log(Math.round(n))
console.log(Math.max(400, 388, 533))
console.log(Math.min(400, 388, 533))
console.log(Math.pow(2, 3))
console.log(Math.pow(5, 4))
console.log(Math.sqrt(9))
console.log(Math.sqrt(64))
console.log(Math.round(Math.random() * 50 + 1))<file_sep>/chapter_two/hello.js
console.log('Hello World!');
console.log('Hello ashraf!');
console.log(34)
console.log(34.76)
console.log(9+9)
console.log('9'+9)
<file_sep>/chapter_three/logicalOperator.js
// && || !
// A && B
// true && true // true
// true && false // false
// false && true // false
// false && false // false
// true || true // true
// true || false // true
// false || true // true
// false || false // false
var a = 80;
var b = 50;
var c = 50;
var d = 60;
if(a > b && c > d) {
console.log("A is greater B and C is greater D")
}else{
console.log("At least one condition is false")
}
if(a > b || c > d) {
console.log("A is greater B or C is greater D")
}else{
console.log("Two condition is false")
}
var check = !!(a > b)
console.log(check)<file_sep>/chapter_five/string.js
// what is string value
// 'this is a string'
// "this is a string"
// var str = 'something'//string literal
// var str2 = String('something')//string constructor
// console.log(str, str2)
// var n = 10
// var str4 = n
// var str5 = n.toString()
// var str6 = n + ' '
// var str7 = String(n) //constructor
// console.log(n, str, str2, str4, str5, str6, str7)
//escape notation
// var str10 = " This \t is a 'string'\n"
// var str11 = 'This is \\a \'string\'\n'
// var str12 = 'This \\is\t a "string"'
// console.log(str10, str11, str12)
// carrige Return \r
// vertical tab \v
// backspace \b
// Form feed \f
// string comparison
// var x = 'abcS'
// var y = 'cdes'
// console.log(x<y)
// console.log('001' == 1)
// var a = "<NAME>"
// var b = "Khan"
// var c = a.concat(' ', b)
// console.log(c)
// var d = c.substr(11, 3)
// console.log(d)
// console.log(c.charAt(4))
// console.log(c.startsWith('Ali'))
// console.log(c.endsWith(' Khan34'))
// console.log(c.toUpperCase())
// console.log(c.toLowerCase())
// console.log(' Bangladesh '.trim())
// console.log(c.split(' '))
var str = 'Some '
// var str2 = str.charAt(12)
// console.log(str.charAt(12))
// console.log(typeof str2)
var length = 0
while(true) {
if(str.charAt(length)=== ''){
break
}else{
length++
}
}
console.log(length)
console.log(str.length)
console.log('alkhjas ashdkf '.length)
<file_sep>/chapter_eight/arguments.js
// function add(a, b) {
// var result = a + b
// console.log(result)
// }
// add(10, 20)
// add(3432, 4323)
// function sub(a, b) {
// var result = a - b
// console.log(result)
// }
// sub(29, 3)
// sub(74, 43)
// var arr1 = [1, 2, 3, 4, 5]
// var arr2 = [4, 5, 6, 4]
// var arr3 = [7, 8, 9, 10]
// var sum = 0
// for(var i = 0; i < arr1.length; i++){
// sum+= arr1[i]
// }
// console.log(sum)
// var sum2 = 0
// for(var i = 0; i < arr2.length; i++){
// sum2+= arr2[i]
// }
// console.log(sum2)
// var sum3 = 0
// for(var i = 0; i < arr3.length; i++){
// sum3+= arr3[i]
// }
// console.log(sum3)
// function sumOfArray(arr) {
// var sum = 0;
// for(var i = 0; i < arr.length; i++){
// sum+=arr[i]
// }
// console.log(sum)
// }
// sumOfArray(arr1)
// sumOfArray(arr2)
// sumOfArray(arr3)
function test(){
// console.log(arguments)
// console.log(typeof a)
for(var i = 0; i <arguments.length; i++){
console.log(arguments[i])
}
}
// test()
test(10, 20, 30)
function addAll(){
var sum = 0;
for(var i=0; i<arguments.length; i++){
sum+=arguments[i]
}
console.log(sum)
}
// addAll(2, 3, 4)
// addAll(34, 64, 65)
var a = addAll(2, 3, 4)
var b = addAll(34, 64, 65)
console.log(a, b)<file_sep>/chapter_nine/sort.js
var persons = [
{
name: 'zamal',
age: 36
},
{
name: 'Rana',
age: 35
},
{
name: 'Sabuj',
age: 98
},
{
name: 'Wahid',
age: 39
}
]
arr = [2, 5, 6, 4, 47, 8, 7, 4, 8, 21, 8, 9, 10, -6];
// arr.sort()
// persons.sort()
// console.log(persons)
arr.sort(function(a, b) {
if(a>b){
return 1
} else if (a<b){
return -1
}else{
return 0
}
})
console.log(arr)
persons.sort(function(a, b) {
if(a.age > b.age){
return 1
} else if(a.age < b.age){
return -1
} else{
return 0
}
})
console.log(persons)
var res1 = arr.every(function(value) {
return value === 0
})
console.log(res1)
var res2 = arr.every(function(value) {
return value >= 0
})
console.log(res2)
var res3 = arr.some(function(value) {
return value% 2 === 1
})
console.log(res3)
var res4 = arr.some(function(value){
return value >= 0
})
console.log(res4) | ac67a7c64ce45df9e0c6aee2a2ca3ac6c8cd5249 | [
"JavaScript"
]
| 27 | JavaScript | ashraf-git/JS_For_All | 41ca0a05fb17c16590a9d47a4542fad807cddfd1 | f252265d1ebe236c4a15df8f537fe80d2aaae9a2 |
refs/heads/master | <repo_name>angrypandahu/mojobs<file_sep>/grails-app/assets/stylesheets/workExperience/index.js
$(function () {
var $workExperienceId = $('#workExperienceId');
var $addWorkExperienceId = $('#addWorkExperienceId');
$addWorkExperienceId.click(function () {
var resumeId = $('#workExperienceResumeId').val();
$.get(
'/workExperience/create', {'resume.id': resumeId}, function (response, status, xhr) {
$workExperienceId.html(response);
$workExperienceId.removeClass('hidden');
}
)
});
$workExperienceId.addClass('hidden');
});
function editWorkExperience(id) {
$.get(
'/workExperience/edit', {id: id}, function (response, status, xhr) {
$('#workExperience-div-' + id).addClass('hidden');
$('#workExperience-edit-' + id).html(response).removeClass("hidden")
}
)
}
function deleteWorkExperience(id) {
$('#myModal').find('[name=id]').val(id)
}
function cancelWorkExperience(id) {
$('#workExperience-div-' + id).removeClass('hidden');
$('#workExperience-edit-' + id).addClass('hidden');
}
function cancelCreateWorkExperience() {
$('#workExperienceId').addClass('hidden');
}
function checkIsPresent(obj) {
$(obj).next().val(obj.checked)
}<file_sep>/grails-app/assets/javascripts/areaSelect.js
function loadCity(parentId) {
var city = $('select[name=city]');
if (parentId > 0) {
$.get('/addressDictionary/findAddressDicDataByParent?parent=' + parentId, function (dataResult) {
var cityHtml = "";
if (dataResult) {
for (var i = 0; i < dataResult.length; i++) {
var obj = dataResult[i];
cityHtml += "<option value='" + obj['id'] + "'>"
+ obj['name'] + "</option>";
}
}
city.html(cityHtml);
loadTown(dataResult[0].id)
})
}
}
function loadTown(parentId) {
var town = $('select[name=town]');
if (parentId > 0) {
$.get('/addressDictionary/findAddressDicDataByParent?parent=' + parentId, function (dataResult) {
var townHtml = "";
if (dataResult) {
for (var i = 0; i < dataResult.length; i++) {
var obj = dataResult[i];
townHtml += "<option value='" + obj['id'] + "'>"
+ obj['name'] + "</option>";
}
}
town.html(townHtml);
})
}
}<file_sep>/grails-app/assets/stylesheets/mojobs/js/bootstrap-select.js
// JS code for NewAdvance search new design logic
$(function(){
$(document).on('click', '.frmcheckwrap', function(){
$(this).toggleClass('active');
});
$('#opnadvance').click(function(){
$(this).remove();
$('.advancewrap').show();
$('.srch_wrap').css('padding-bottom','10px');
});
jQuery('.rgttablnk').click(function(){
var ele = jQuery(this);
if(ele.data('content') == 'topcomp')
{
jQuery('.rgttablnk').removeClass('active');
ele.addClass('active');
jQuery('#topcons').hide();
jQuery('#'+ele.data('content')).show();
}
else if (ele.data('content') == 'topcons')
{
jQuery('.rgttablnk').removeClass('active');
ele.addClass('active');
jQuery('#topcomp').hide();
jQuery('#'+ele.data('content')).show();
}
});
jQuery('.frmcheckwrap').click(function(){
if(!jQuery(this).hasClass('active')){
$("#ans").val(1);
} else {
$("#ans").val(0);
}
});
$(function(){
$("select[name='ind']").change(function(){
loadFA(this, document.myform.jbc, 0, '', 'Function');
$("select[name='jbc']").selectpicker('refresh', true);
loadRoles(document.myform.jbc,document.myform.jbr,0,'0','Role');
$("select[name='jbr']").selectpicker('refresh', true);
$("select[name='ind']").selectpicker('refresh', true);
});
$("select[name='jbc']").change(function() {
loadRoles(document.myform.jbc,document.myform.jbr,0,'0','Role');
$("select[name='jbr']").selectpicker('refresh', true);
$("select[name='jbc']").selectpicker('refresh', true);
});
$("select[name='jbr']").change(function() {
$("select[name='jbr']").selectpicker('refresh', true);
});
});
$('.viewall').click(function(){
$('.field_hide').show();
$('.viewall').hide();
$('.hideall').show();
$('.ind_mob').addClass('mob_show');
$('.func_mob').addClass('mob_show');
});
$('.hideall').click(function(){
$('.field_hide').hide();
$('.viewall').show();
$('.hideall').hide();
$('.ind_mob').removeClass('mob_show');
$('.func_mob').removeClass('mob_show');
});
$('#mn-loader').show();
setTimeout(function(){
$('#mn-loader').hide();
}, 3000);
$('.close_key').click(function(){
$('.choose').hide();
});
$('#fts_id,#lmy').click(function(){
jQuery('#workhist-ui-id-1,#workhist-ui-id-2').addClass('autocomplete_maindiv autocomplete_subdiv');
});
});
function getSalaryVal(counter,selMin,selMax) {
var salVal;
var salMaxVal = 0;
var salFinalval = 0;
var salValue;
var salMaxValue;
if(selMin){ selMin = selMin+'00000'; jQuery('input[name="mns"]').filter('[value='+selMin+']').attr('checked', true); }
if(selMax) { selMax = selMax+'000'; jQuery('input[name="mxs"]').filter('[value='+selMax+']').attr('checked', true); }
if(jQuery('input[name="mns"]').is(':checked')) {
salVal = salVal*1;
if(selMin){ salVal = selMin; }
else {
salValue = jQuery('input[name="mns"]:checked').val(); }
salVal = salValue;
}
if(jQuery('input[name="mxs"]').is(':checked')) {
if(selMax) { salMaxVal = selMax; }
else {
salMaxValue = jQuery('input[name="mxs"]:checked').val();
}
salMaxVal = salMaxValue*1;
if(salVal == undefined) {
salVal=0;
}
salVal = salVal+" - "+salMaxVal;
}
jQuery("#salary_"+counter).val(salVal);
if(salVal != null)
jQuery('#salary_'+counter+'_value').html(salVal);
}
function resetSalaryVal(counter) {
if(jQuery("input[type='radio'].from_min").is(':checked')) {
jQuery('input[name=mns]').attr('checked', false);
}
if(jQuery("input[type='radio'].from_max").is(':checked')) {
jQuery('input[name=mxs]').attr('checked', false);
}
jQuery('#salary_'+counter+'_value').html('Salary(in Lacs)');
jQuery("#salary_"+counter).val('');
}
/*search tips*/
var item = 0;
var slidetimeer ='';
function rotateslidemain(j){
var mrgn = j * 240;
$('.tipslidenavitem').removeClass('active');
$('.tipslidenavitem').eq(j).addClass('active');
if(Mons.LANG == 'ar'){
$('.tipslideinnr').animate({'margin-right': '-'+mrgn+'px'}, 500);
}else{
$('.tipslideinnr').animate({'margin-left': '-'+mrgn+'px'}, 500);
}
}
function rotateslide(){
console.log(item);
slidetimeer = setInterval(function(){
item++;
if(item > 2){
item = 0;
}
rotateslidemain(item);
}, 4500);
}
rotateslide();
$(function(){
$(document).on('click', '.tipslidenavitem', function(){
if(!$(this).hasClass('active')){
item = $(this).index();
clearInterval(slidetimeer);
rotateslidemain($(this).index());
rotateslide();
}
});
});
/*search tips*/
$( document ).ready(function() {
jQuery('#workhist-ui-id-1,#workhist-ui-id-2').addClass('autocomplete_maindiv autocomplete_subdiv');
if(typeof roleDataTargetVal !== 'undefined') {
$('#roleDataTarget').click();
}
if(typeof freshnessDataTargetVal !== 'undefined') {
$('#freshnessDataTarget').click();
}
if(typeof locationDataTargetVal !== 'undefined') {
$('#locationDataTarget').click();
}
if(typeof companyTypeDataTargetVal !== 'undefined') {
$('#companyTypeDataTarget').click();
}
if(typeof experienceDataTargetVal !== 'undefined') {
$('#experienceDataTarget').click();
}
if(typeof salaryDataTargetVal !== 'undefined') {
$('#salaryDataTarget').click();
}
if(typeof industrydataTargetVal !== 'undefined') {
$('#industrydataTarget').click();
}
if(typeof functionDataTargetVal !== 'undefined') {
$('#functionDataTarget').click();
}
});<file_sep>/settings.gradle
rootProject.name='mojobs'
<file_sep>/README.md
# mojobs
mojobs
grails 开发的招聘网站
前端使用bootstrap | 11e5e64382165621c4f7743c713a1efe5543d3df | [
"JavaScript",
"Markdown",
"Gradle"
]
| 5 | JavaScript | angrypandahu/mojobs | bcd8350c1f4126d1e768588d17e52180852fa139 | 6982ec1190496de9fa769fa91401445207080331 |
refs/heads/master | <repo_name>arhiordinator/java1<file_sep>/lesson1/task1/src/one/Robot.java
package one;
public class Robot {
String Run;
String Jump;
public static void main(String[] args) {
Robot Pavel = new Robot();
Pavel.Jump = "Прыгает";
Pavel.Run = "Бежит";
System.out.println(" Робот павел " + Pavel.Jump + " и ещё робот павел " + Pavel.Run);
}
}
<file_sep>/lesson1/task1/src/one/Cat.java
package one;
public class Cat {
String Run;
String Jump;
public static void main(String[] args) {
Cat Oreo = new Cat();
Oreo.Jump = "Прыгает";
Oreo.Run = "Бегает";
System.out.println("Кот " + Oreo.Run + " и ещё " + Oreo.Jump);
}
}
<file_sep>/lesson1/task1/src/one/People.java
package one;
public class People {
String Run;
String Jump;
public static void main(String[] args) {
People Leonid = new People();
Leonid.Jump ="Прыгать";
Leonid.Run = "Бегает";
System.out.println(" <NAME> " + Leonid.Run + " и ещё умеет " + Leonid.Jump);
}
}
<file_sep>/lesson1/tasl3/src/three/Main.java
package three;
public class Main {
public static void main(String[] args) {
obstacle obstacle1 = new obstacle("Стена",5);
obstacle obstacle2 = new obstacle("Дорожка",200);
// obstacle obstacle3 = new obstacle("Илья",202,3);
obstacle[] obstacles = new obstacle[2];
obstacle1.PutMeInArray(obstacles,0);
obstacle2.PutMeInArray(obstacles,1);
//Participant3.PutMeInArray(Participants,2);
Participant Participant1 = new Participant("Василий",220,10);
Participant Participant2 = new Participant("Петр",190,6);
Participant Participant3 = new Participant("Илья",202,3);
Participant[] Participants = new Participant[3];
Participant1.PutMeInArray(Participants,0);
Participant2.PutMeInArray(Participants,1);
Participant3.PutMeInArray(Participants,2);
for (int i = 0; i < Participants.length; i++) {
if (Participants[i].Jump < obstacles[0].parameter) {
System.out.println("Участник " + Participants[i].name + " не перепрыгнул");
continue;
}
if (Participants[i].Run < obstacles[1].parameter) {
System.out.println("Участник " + Participants[i].name + " не пробежал");
continue;
}
System.out.println("Участник " + Participants[i].name + " прошел все припятствия");
}
}
} | 28687f316f59621428c5f58d56d3753dd18956d7 | [
"Java"
]
| 4 | Java | arhiordinator/java1 | ca8da8376cc70c96c465e33e8452786031609b64 | 43788ed92ddd6bfce99986bde10ff2050d14ffde |
refs/heads/master | <file_sep>## Update
__(29/7/2020)__
- Rename `utils.py` to `local_utils.py` to avoid conflicit with default Python library `utils.py`.
- Replace error `index out of range` to `No License plate is founded!`.
- In case error `No License Plate is founded!` popped up, try to adjust Dmin from `get_plate()` function. Keep in mind that larger Dmin means more higly the plate information is lost.
## [Read the series on Medium](https://medium.com/@quangnhatnguyenle/detect-and-recognize-vehicles-license-plate-with-machine-learning-and-python-part-1-detection-795fda47e922)
- Part 1: [Detection License Plate with Wpod-Net](https://medium.com/@quangnhatnguyenle/detect-and-recognize-vehicles-license-plate-with-machine-learning-and-python-part-1-detection-795fda47e922)
- Part 2: [Plate character segmentation with OpenCV](https://medium.com/@quangnhatnguyenle/detect-and-recognize-vehicles-license-plate-with-machine-learning-and-python-part-2-plate-de644de9849f)
- Part 3: [Recognize plate license characters with OpenCV and Deep Learning](https://medium.com/@quangnhatnguyenle/detect-and-recognize-vehicles-license-plate-with-machine-learning-and-python-part-3-recognize-be2eca1a9f12)
## Tools and Libraries
- Python==3.6
- Keras==2.3.1
- Tensorflow==1.14.0
- Numpy==1.17.4
- Matplotlib==3.2.1
- OpenCV==4.1.0
- sklearn==0.21.3
# Detect and Recognize Vehicle’s License Plate with Machine Learning and Python
### [Part 1: Detection License Plate with Wpod-Net](https://medium.com/@quangnhatnguyenle/detect-and-recognize-vehicles-license-plate-with-machine-learning-and-python-part-1-detection-795fda47e922)
<p align="center"><img src="./figures/Part1_result.jpg" width=640></p><br>
### [Part 2: Plate character segmentation with OpenCV](https://medium.com/@quangnhatnguyenle/detect-and-recognize-vehicles-license-plate-with-machine-learning-and-python-part-2-plate-de644de9849f)
<p align="center"><img src="./figures/Part2_result.jpg" width=640></p><br>
### [Part 3: Recognize plate license characters with OpenCV and Deep Learning](https://medium.com/@quangnhatnguyenle/detect-and-recognize-vehicles-license-plate-with-machine-learning-and-python-part-3-recognize-be2eca1a9f12)
<p align="center"><img src="./figures/Part3_result.jpg" width=640></p><br>
#### ahah i have added a comment
## Credit
[sergiomsilva](https://github.com/sergiomsilva/alpr-unconstrained)
<file_sep>#include "CV_Replacement.h"
#include <vector>
#include <iostream>
//Rect boundingRect(std::vector<Coordinate> points);
Image::Image(){
}
//Constructor for loading in from a filepath. Intended for testing.
Image::Image(char* filepath){
//Code From:
//https://stackoverflow.com/questions/9296059/read-pixel-value-in-bmp-file/38440684
FILE* imageFile = fopen(filepath,"rb");
if(imageFile == NULL)
std::cout << "File opening error" << std::endl;
unsigned char info[54];
fread(info, sizeof(unsigned char), 54 , imageFile);
//Extract information from the header
int width = *(int*)&info[18];
int height = *(int*)&info[22];
//std::cout << std::endl;
//std::cout << " Width: " << width << std::endl;
//std::cout << "Height: " << height << std::endl;
int row_padded = (width*3+3)&(~3);
std::cout << "Row Padded: " << row_padded << std::endl;
unsigned char* data = new unsigned char[row_padded];
unsigned char tmp;
//Allocate the memory for the image
this->imageArray = (unsigned char***) malloc(width*sizeof(unsigned char**));
for(int i = 0; i < width; i++){
this->imageArray[i] = (unsigned char **) malloc(height*sizeof(unsigned char*));
for(int j = 0; j < height; j++){
this-> imageArray[i][j] = (unsigned char *) malloc(3*sizeof(unsigned char));//assumed depth
}
}
//std::cout << this->imageArray[27][2][4] << std::endl;
//*
//With the memory allocated, we fill it.
for(int i = 0; i < width; i++){
fread(data,sizeof(unsigned char), row_padded,imageFile);
for(int j = 0; j < height; j++){
//Converting BGR to RGB, will have to confirm if this is necessary later
imageArray[i][j][0] = data[j*3+2];
imageArray[i][j][1] = data[j*3+1];
imageArray[i][j][2] = data[j*3];
std::cout << "RGB: " << (int)data[j*3+2] << " " << (int)data[j*3+1] << " " << (int)data[j*3] << std::endl;
//std::cout << this->imageArray[i][j][0];
}
}
//*/
//Print out the data in a similar fashion.
/*
for(int i = 0; i < height; i++)
{
fread(data,sizeof(unsigned char), row_padded, imageFile);
for(int j = 0; j < width *3; j += 3){
//convert BGR to RGB
tmp = data[j];
data[j] = data[j+2];
data[j+2] = tmp;
std::cout << "R: "<< (int)data[j] << " G: " << (int)data[j+1]<< " B: " << (int)data[j+2]<< std::endl;
}
}
//*/
this->imageWidth = width;
this->imageHeight = height;
this->numChannels = 3;
fclose(imageFile);
return;
}
Image::Image(int width, int height, int channels){
}
Image::~Image(){
}
//Make the image grayscale. Will have to make a new bit of memory and free the previous array.
//0.299R, 0.587G,0.114B
void Image::cvtColor(){
int height = this->imageHeight;
int width = this->imageWidth;
std::cout << "RGBValues: " << (int)this->imageArray[0][0][0] << std::endl;
std::cout << "Height: " << height << "| Width: " << width << std::endl;
unsigned char ** grayArray = (unsigned char**) malloc(width*sizeof(unsigned char*));
for(int i = 0; i < width; i++){
grayArray[i] = (unsigned char *) malloc(height*sizeof(unsigned char));
}
for(int i = 0; i < width; i++){
for(int j = 0; j < height; j++){
int red = (int) this->imageArray[i][j][0];
int green = (int) this ->imageArray[i][j][1];
int blue = (int) this ->imageArray[i][j][2];
//std::cout << "Red: " << (int) red << " | Shifted: " << red*0.299 << std::endl;
int grayness = (red*0.299 + green*0.587 + blue*0.114);
std::cout << "Grayness: " << grayness << std::endl;
grayArray[i][j] = grayness;
}
}
//*
int threshold = 100;
std::cout << "----------------------------" << std::endl;
for(int i = 0; i < width; i++){
for(int j = 0; j < height; j++){
if(grayArray[j][i] > 200){
std::cout << "4";
}
else if(grayArray[j][i] > 150){
std::cout << "3";
}
else if(grayArray[j][i] > 100){
std::cout << "2";
}
else if(grayArray[j][i] > 50){
std::cout << "1";
}
else if(grayArray[j][i] > 10){
std::cout << "0";
}
else{
std::cout << " ";
}
}
std::cout << std::endl;
}
std::cout << "----------------------------" << std::endl;
//*/
}
//Draws a box over the image using the rectangle as the bounds. Destructive.
void Image::Rectangle(Rect bounds, int thickness){
}
//From a vector of coordinates returns a rectangle encompasing all of the points.
//Error will return a rectangle of all -1s.
Rect Image::BoundingRect(std::vector<Coordinate> points){
//IF VECTOR SIZE = 0 RETURN ERROR HERE
if(points.size() == 0){
std::cout << "No points in coordinate list. Error in 'boundingRect'" << std::endl;
Rect *errorRect = new Rect(-1,-1,-1,-1);
return(*errorRect);
}
//Set an initial value for our variables using the first given argument.
int maxX = points[0].x;
int maxY = points[0].y;
int minX = points[0].x;
int minY = points[0].y;
//Loop through starting with the second element to find more extreme maximums or minimums
int numberOfPoints = points.size();
//std::cout << "Number of points: " << numberOfPoints << std::endl;
//std::cout << "Vector: " << points[0].x << ", " << points[0].y << " | ";
for(int i = 1; i < numberOfPoints; i++){
std::cout << points[i].x << ", " << points[i].y << " | "; // << std::endl;
if(points[i].x > maxX){
maxX = points[i].x;
}
else if(points[i].x < minX){
minX = points[i].x;
}
if(points[i].y > maxY){
maxY = points[i].y;
}
else if(points[i].y < minY){
minY = points[i].y;
}
}
std::cout << std::endl;
//std::cout << "Maximums: " << maxX << " , " << maxY << std::endl;
//std::cout << "Minimums: " << minX << " , " << minY << std::endl;
Rect *boundingRect = new Rect(maxX,maxY,minX,minY);
return(*boundingRect);
}
//Takes an image, Creates new, slightly smaller memory for the return image.
//Performs the kernal convolution on each pixel and returns the new image.
Image Image::GaussianBlur(){
float blurKernal[7][7] = {
{0.00000067,0.00002292,0.00019117,0.00038771,0.00019117,0.00002292,0.00000067},
{0.00002292,0.00078633,0.00655965,0.01330373,0.00655965,0.00078633,0.00002292},
{0.00019117,0.00655965,0.05472157,0.11098164,0.05472157,0.00655965,0.00019117},
{0.00038771,0.01330373,0.11098164,0.22508352,0.11098164,0.01330373,0.00038771},
{0.00019117,0.00655965,0.05472157,0.11098164,0.05472157,0.00655965,0.00019117},
{0.00002292,0.00078633,0.00655965,0.01330373,0.00655965,0.00078633,0.00002292},
{0.00000067,0.00002292,0.00019117,0.00038771,0.00019117,0.00002292,0.00000067} };
//int originalX = this.imageWidth;
//int originalY = this.imageHeight;
}
<file_sep>""" https://docs.opencv.org/master/d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57
double cv::threshold ( InputArray src,
OutputArray dst,
double thresh,
double maxval,
int type
)
Python:
retval, dst = cv.threshold( src, thresh, maxval, type[, dst] )
#include <opencv2/imgproc.hpp>
Applies a fixed-level threshold to each array element.
The function applies fixed-level thresholding to a multiple-channel array. The function is typically used to get a bi-level (binary) image out of a grayscale image ( compare could be also used for this purpose) or for removing a noise, that is, filtering out pixels with too small or too large values. There are several types of thresholding supported by the function. They are determined by type parameter.
Also, the special values THRESH_OTSU or THRESH_TRIANGLE may be combined with one of the above values. In these cases, the function determines the optimal threshold value using the Otsu's or Triangle algorithm and uses it instead of the specified thresh.
Note
Currently, the Otsu's and Triangle methods are implemented only for 8-bit single-channel images.
Parameters
src input array (multiple-channel, 8-bit or 32-bit floating point).
dst output array of the same size and type and the same number of channels as src.
thresh threshold value.
maxval maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types.
type thresholding type (see ThresholdTypes).
Returns
the computed threshold value if Otsu's or Triangle methods used.
"""
<file_sep>#include "CV_Replacement.h"
Coordinate::Coordinate(int xCoordinate, int yCoordinate){
x = xCoordinate;
y = yCoordinate;
}
Coordinate::~Coordinate(){
}<file_sep>""" https://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#gaabe8c836e97159a9193fb0b11ac52cf1
void cv::GaussianBlur ( InputArray src,
OutputArray dst,
Size ksize,
double sigmaX,
double sigmaY = 0,
int borderType = BORDER_DEFAULT
)
Python:
dst = cv.GaussianBlur( src, ksize, sigmaX[, dst[, sigmaY[, borderType]]] )
#include <opencv2/imgproc.hpp>
Blurs an image using a Gaussian filter.
The function convolves the source image with the specified Gaussian kernel. In-place filtering is supported.
Parameters
src input image; the image can have any number of channels, which are processed independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
dst output image of the same size and type as src.
ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be positive and odd. Or, they can be zero's and then they are computed from sigma.
sigmaX Gaussian kernel standard deviation in X direction.
sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, respectively (see getGaussianKernel for details); to fully control the result regardless of possible future modifications of all this semantics, it is recommended to specify all of ksize, sigmaX, and sigmaY.
borderType pixel extrapolation method, see BorderTypes. BORDER_WRAP is not supported. """
<file_sep>""" https://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#ga67493776e3ad1a3df63883829375201f
void cv::morphologyEx ( InputArray src,
OutputArray dst,
int op,
InputArray kernel,
Point anchor = Point(-1,-1),
int iterations = 1,
int borderType = BORDER_CONSTANT,
const Scalar & borderValue = morphologyDefaultBorderValue()
)
Python:
dst = cv.morphologyEx( src, op, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]] )
#include <opencv2/imgproc.hpp>
Performs advanced morphological transformations.
The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as basic operations.
Any of the operations can be done in-place. In case of multi-channel images, each channel is processed independently.
Parameters
src Source image. The number of channels can be arbitrary. The depth should be one of CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
dst Destination image of the same size and type as source image.
op Type of a morphological operation, see MorphTypes
kernel Structuring element. It can be created using getStructuringElement.
anchor Anchor position with the kernel. Negative values mean that the anchor is at the kernel center.
iterations Number of times erosion and dilation are applied.
borderType Pixel extrapolation method, see BorderTypes. BORDER_WRAP is not supported.
borderValue Border value in case of a constant border. The default value has a special meaning.
"""
<file_sep>#include "CV_Replacement.h"
Rect::Rect(int xCoordinate1, int yCoordinate1, int xCoordinate2, int yCoordinate2){
x1 = xCoordinate1;
y1 = yCoordinate1;
x2 = xCoordinate2;
y2 = yCoordinate2;
}
Rect::Rect(Coordinate Coord1, Coordinate Coord2){
x1 = Coord1.x;
y1 = Coord1.y;
x2 = Coord2.x;
y2 = Coord2.y;
}
Rect::~Rect(){
}<file_sep>""" https://docs.opencv.org/master/d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0
void cv::findContours ( InputArray image,
OutputArrayOfArrays contours,
OutputArray hierarchy,
int mode,
int method,
Point offset = Point()
)
Python:
contours, hierarchy = cv.findContours( image, mode, method[, contours[, hierarchy[, offset]]] )
#include <opencv2/imgproc.hpp>
Finds contours in a binary image.
The function retrieves contours from the binary image using the algorithm [228] . The contours are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the OpenCV sample directory.
Note
Since opencv 3.2 source image is not modified by this function.
Parameters
image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero pixels remain 0's, so the image is treated as binary . You can use compare, inRange, threshold , adaptiveThreshold, Canny, and others to create a binary image out of a grayscale or color one. If mode equals to RETR_CCOMP or RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1).
contours Detected contours. Each contour is stored as a vector of points (e.g. std::vector<std::vector<cv::Point> >).
hierarchy Optional output vector (e.g. std::vector<cv::Vec4i>), containing information about the image topology. It has as many elements as the number of contours. For each i-th contour contours[i], the elements hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices in contours of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative.
mode Contour retrieval mode, see RetrievalModes
method Contour approximation method, see ContourApproximationModes
offset Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context.
"""
<file_sep>"""
https://docs.opencv.org/master/d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab
void cv::cvtColor ( InputArray src,
OutputArray dst,
int code,
int dstCn = 0
)
Python:
dst = cv.cvtColor( src, code[, dst[, dstCn]] )
#include <opencv2/imgproc.hpp>
Converts an image from one color space to another.
The function converts an input image from one color space to another. In case of a transformation to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.
The conventional ranges for R, G, and B channel values are:
0 to 255 for CV_8U images
0 to 65535 for CV_16U images
0 to 1 for CV_32F images
In case of linear transformations, the range does not matter. But in case of a non-linear transformation, an input RGB image should be normalized to the proper value range to get the correct results, for example, for RGB → L*u*v* transformation. For example, if you have a 32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will have the 0..255 value range instead of 0..1 assumed by the function. So, before calling cvtColor , you need first to scale the image down:
img *= 1./255;
cvtColor(img, img, COLOR_BGR2Luv);
If you use cvtColor with 8-bit images, the conversion will have some information lost. For many applications, this will not be noticeable but it is recommended to use 32-bit images in applications that need the full range of colors or that convert an image before an operation and then convert back.
If conversion adds the alpha channel, its value will set to the maximum of corresponding channel range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F.
Parameters
src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision floating-point.
dst output image of the same size and depth as src.
code color space conversion code (see ColorConversionCodes).
dstCn number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code.
"""<file_sep>""" https://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#gac342a1bb6eabf6f55c803b09268e36dc
Mat cv::getStructuringElement ( int shape,
Size ksize,
Point anchor = Point(-1,-1)
)
Python:
retval = cv.getStructuringElement( shape, ksize[, anchor] )
#include <opencv2/imgproc.hpp>
Returns a structuring element of the specified size and shape for morphological operations.
The function constructs and returns the structuring element that can be further passed to erode, dilate or morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as the structuring element.
Parameters
shape Element shape that could be one of MorphShapes
ksize Size of the structuring element.
anchor Anchor position within the element. The default value (−1,−1) means that the anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor position. In other cases the anchor just regulates how much the result of the morphological operation is shifted. """
<file_sep>#Python implementation of functions
#File created by <NAME> 1/30/2021
#Class: Capstone | On behalf of XMOS
#run with python3 <filename>.py
def test():
print("Test reached")
#This function finds the highest x and y values passed to it from a set.
import random
def FindBounds():
random.seed()
NumberOfPoints = 5
XLimit = 15
YLimit = 20
randomNumbers = [0,0]
lists = []
for i in range(5):
randomNumbers[0] = random.randint(0,XLimit)
randomNumbers[1] = random.randint(0,YLimit)
lists.append(randomNumbers[:])
print(lists)
print(lists[1][0])
maxX = lists[0][0]
maxY = lists[0][1]
minX = lists[0][0]
minY = lists[0][1]
for point in lists:
if point[0] > maxX:
maxX = point[0]
if point[0] < minX:
minX = point[0]
if point[1] > maxY:
maxY = point[1]
if point[1] < minY:
minY = point[1]
print("MaxX=" + str(maxX))
print("MaxY=" + str(maxY))
print("MinX=" + str(minX))
print("MinY=" + str(minY))
FindBounds()<file_sep>//C style main file
//File created by <NAME> 1/30/2021
//Class: Capstone | On behalf of XMOS
//To compile:
//clang++ main.cpp Coordinate.cpp Rect.cpp Image.cpp -I CV_Replacement.h -o main
//
#include "CV_Replacement.h"
#include <vector>
#include <iostream>
#include <time.h> //For seeding the random generator for testing
#include <string>
#include <fstream>
//#include <stdio.h>
void TestBoundingRect();
void TestImageConstructor();
void TestingBitmap();
Image TestingImageConstructor(char* filepath);
Image TestImgCVT(char* filepath);
int main(){
char* filepath = "./SampleImages/1.bmp";
//test();
//TestBoundingRect();
//TestingBitmap();
//TestingImageConstructor(filepath);
TestImgCVT(filepath);
return 0;
}
void TestBoundingRect(){
int desiredPoints = 5;
int XLimit = 15;
int YLimit = 20;
//Makes a coordinate
std::vector<Coordinate> points;
Coordinate *tempCoordinates = new Coordinate(0,0);
//Fills a vector with <desiredPoints> worth of randomized X and Y value pairs.
srand(time(0));
for(int i = 0; i < desiredPoints; i++){
//Generates between 0 and limit.
tempCoordinates->x = rand() % XLimit;
tempCoordinates->y = rand() % YLimit;
points.push_back(*tempCoordinates);
//std::cout << "Coordinate??? " + points[i].x + ", " + points[i].y << std::endl;
}
//Create a blank image for testing purposes
Image *testingImage = new Image();
//
Rect boundingRect = testingImage->BoundingRect(points);
std::cout << "Bounding Rect points: " << "MX: " << boundingRect.x1 << ", MY: " << boundingRect.y1 << ", mX: " << boundingRect.x2 << ", mY: " << boundingRect.y2 << std::endl;
return;
}
void TestImageConstructor(){
std::string readingpath = "../SampleImages/";
std::string filename = "2.jpg";
std::string fullInputPath = readingpath + filename;
std::string writingpath = "../OutputImages/";
std::string fullOutputPath = writingpath + filename;
//char filepath[100] = "../SampleImages/2.jpg";
}
//The purpose of this function is to test what happens when I read a bitmap image
void TestingBitmap(){
FILE* imageFile = fopen("./SampleImages/1.bmp","rb");
if(imageFile == NULL)
std::cout << "File opening error" << std::endl;
unsigned char info[54];
fread(info, sizeof(unsigned char), 54 , imageFile);
//Extract information from the header
int width = *(int*)&info[18];
int height = *(int*)&info[22];
std::cout << std::endl;
std::cout << " Width: " << width << std::endl;
std::cout << "Height: " << height << std::endl;
int row_padded = (width*3+3)&(~3);
unsigned char* data = new unsigned char[row_padded];
unsigned char tmp;
for(int i = 0; i < height; i++)
{
fread(data,sizeof(unsigned char), row_padded, imageFile);
for(int j = 0; j < width *3; j += 3){
//convert BGR to RGB
tmp = data[j];
data[j] = data[j+2];
data[j+2] = tmp;
std::cout << "R: "<< (int)data[j] << " G: " << (int)data[j+1]<< " B: " << (int)data[j+2]<< std::endl;
}
}
fclose(imageFile);
return;
}
Image TestingImageConstructor(char* filepath){
std::cout << "Reached TestingImageConstructor Function" << std::endl;
Image* ImageTest = new Image(filepath);
//ImageTest.printBinary;
std::cout << "Returned from ImageConstructor " << std::endl;
return *ImageTest;
}
Image TestImgCVT(char* filepath){
Image Image1 = TestingImageConstructor(filepath);
Image1.cvtColor();
return(Image1);
}<file_sep>""" https://docs.opencv.org/master/d6/d6e/group__imgproc__draw.html#ga07d2f74cadcf8e305e810ce8eed13bc9
void cv::rectangle ( InputOutputArray img,
Point pt1,
Point pt2,
const Scalar & color,
int thickness = 1,
int lineType = LINE_8,
int shift = 0
)
Python:
img = cv.rectangle( img, pt1, pt2, color[, thickness[, lineType[, shift]]] )
img = cv.rectangle( img, rec, color[, thickness[, lineType[, shift]]] )
#include <opencv2/imgproc.hpp>
Draws a simple, thick, or filled up-right rectangle.
The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners are pt1 and pt2.
Parameters
img Image.
pt1 Vertex of the rectangle.
pt2 Vertex of the rectangle opposite to pt1 .
color Rectangle color or brightness (grayscale image).
thickness Thickness of lines that make up the rectangle. Negative values, like FILLED, mean that the function has to draw a filled rectangle.
lineType Type of the line. See LineTypes
shift Number of fractional bits in the point coordinates.
"""
//Draws a rectangle on the image provided.
//Destructive to the image provided, recommended to clone / copy first.
void cv::rectangle()<file_sep>//Cstyle Header File
//File created by <NAME> 1/30/2021
//Class: Capstone | On behalf of XMOS
#pragma once
#ifndef CV_REPLACEMENT_H
#define CV_REPLACEMENT_H
//AFAIK includes should not be in header files, will move.
//#include <stdio.h>
#include <vector>
/////void cvtColor();
///Image GaussianBlur();
double threshold();
//Mat getStructuringElement();
void morphologyEx();
//rect boundingRect();
void findContours();
/////void rectangle();
//test();
class Coordinate{
public:
Coordinate(int xCoordinate, int yCooridnate);
~Coordinate();
int x;
int y;
};
class Rect{
public:
Rect(int xCoordinate1, int yCoordinate1, int xCoordinate2, int yCoordinate2);
Rect(Coordinate Coord1, Coordinate Coord2);
~Rect();
int x1;
int y1;
int x2;
int y2;
};
class Image
{
public:
Image();
Image(char* filepath);
Image(int width, int height, int channels);
~Image();
//make the image grayscale. Destructive.
void cvtColor();
//void Rectangle( InputOutputArray img, Point pt1, Point pt2, const Scalar & color, int thickness = 1, int lineType = LINE_8, int shift = 0 );
//Draws a rectangle on the image. Destructive.
void Rectangle(Rect bounds, int thickness);
//From a vector of coordinates returns a rectangle encompasing all of the points.
Rect BoundingRect(std::vector<Coordinate> CoordinateVector);
//Performs a hardcoded GaussianBlur on this image (assuming grayscale) and returns a new blurred image
//Currently implemented as a for loop, without utilizing the board's convolution, cuts off 3 pixels from each edge
Image GaussianBlur();
private:
unsigned int imageWidth;
unsigned int imageHeight;
unsigned int numChannels;
unsigned char *** imageArray;
};
#endif<file_sep>License plates collected by <NAME>
The image type is either .jpg or .png
Method of Collection:
Just Plates:
Searching around on google for images of just plates (centered).
Avoided any license plate labeled "product" by google
"Sample" license plates are avoided, Ex: ABC-123
Banned license plates are not, Ex: FARTBUS
Full Vehicle:
Searching car based subreddits for pictures of cars with licence plates.
Please forgive the r/shittycarmods, but im sure it will prove a challenge for the algorithm
FacingCamera: images of cars with a licence plate facing the camera (+/- ~10*)
Angled: images of cars with a licence plate at difficult angles (10*-60*)
Challenge: images of license plates that are partially obscured or low quality
These images should probably be considered testing images, they may confuse the training process.
Avoided any license plate labeled "product" by google
"Sample" license plates are avoided, Ex: ABC-123
Banned license plates are not, Ex: FARTBUS
Metadata:
Currently (9-29) images are sorted into the groups defined in the method of collection.
The image is of only one vehicle and the name of the image is the license plate (as I read it)
Note: any form of dot or dash towards the middle is treated as a -
Note: This does not include symbols that occour in a gap<file_sep>#Python implementation of functions
#File created by <NAME> 1/30/2021
#Class: Capstone | On behalf of XMOS
#https://docs.opencv.org/master/d3/dc0/group__imgproc__shape.html#ga103fcbda2f540f3ef1c042d6a9b35ac7
#boundingRect()
#Rect cv::boundingRect ( InputArray array )
#Python:
# retval = cv.boundingRect( array )
#
#include <opencv2/imgproc.hpp>
# Note #include "opencv2/imgproc/imgproc_c.h" also exists
# From this link https://docs.opencv.org/3.4/dd/d46/imgproc_8hpp.html
#
#Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image.
#
#The function calculates and returns the minimal up-right bounding rectangle for the specified point set or non-zero pixels of gray-scale image.
#
#Parameters
# array Input gray-scale image or 2D point set, stored in std::vector or Mat.
#X coordinates are the distance from the left
#Y coordinates are the distance from the top
//Input gray-scale image or 2D point set, stored in std::vector
Rect boundingRect(inputArray){
}
| 8f9b3d2db975a2a84a144e6b679f7b5252c5ee20 | [
"Markdown",
"Python",
"Text",
"C++"
]
| 16 | Markdown | kylenannig/Plate_detect_and_recognize | 015fd7c7f5f1d132d079e548d28355b3cc9eea18 | 69b4c70741318aa0b516b39c3c4cfd87634cb05f |
refs/heads/master | <file_sep>using PersonApplicationDll.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PersonApplicationDll.Managers
{
class PersonListManager : IManager<Person>
{
static PersonStatusListManager psm = new PersonStatusListManager();
private static int PersonId = 1;
static private readonly List<Person> Persons = new List<Person>();
public Person Create(Person person)
{
var pStatus = psm.Read(person.Status.Id);
person.Status = pStatus;
person.Id = PersonId++;
Persons.Add(person);
return person;
}
public bool Delete(int id)
{
return 1 == Persons.RemoveAll(x => x.Id == id);
}
public List<Person> Read()
{
return Persons;
}
public Person Read(int id)
{
return Persons.FirstOrDefault(x => x.Id == id);
}
public Person Update(Person p)
{
var personToEdit = Persons.FirstOrDefault(X => X.Id == p.Id);
if (personToEdit != null)
{
personToEdit.Name = p.Name;
personToEdit.Status = psm.Read(p.Status.Id); ;
}
return personToEdit;
}
}
}
<file_sep>using PersonApplicationDll.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PersonApplicationDll.Managers
{
class PersonStatusListManager : IManager<PersonStatus>
{
private static readonly List<PersonStatus> Statuses = new List<PersonStatus> { new PersonStatus { Id = 1, Name = "Away" },
new PersonStatus { Id = 2, Name = "Available" },
new PersonStatus { Id = 3, Name = "Busy" }
};
public PersonStatus Create(PersonStatus t)
{
throw new NotImplementedException();
}
public bool Delete(int id)
{
throw new NotImplementedException();
}
public List<PersonStatus> Read()
{
return Statuses;
}
public PersonStatus Read(int id)
{
return Statuses.FirstOrDefault(x => x.Id == id);
}
public PersonStatus Update(PersonStatus t)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PersonApplicationDll.Entities
{
public class EditPersonViewModel
{
public Person Person;
public List<PersonStatus> Statuses { get; set; }
}
}<file_sep>using PersonWebApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PersonApplicationDll.Entities;
using PersonApplicationDll;
using PersonApplicationDll.Managers;
namespace PersonWebApp.Controllers
{
public class PersonController : Controller
{
private IManager<Person> _pm = new DllFacade().GetPersonManager();
private IManager<PersonStatus> _psm = new DllFacade().GetPersonStatusManager();
// GET: Person
public ActionResult Index()
{
return View(_pm.Read());
}
public ActionResult Create()
{
return View(_psm.Read());
}
[HttpPost]
public ActionResult Create(Person person)
{
_pm.Create(person);
return RedirectToAction("Index");
}
public ActionResult Edit(int id)
{
var personToEdit = _pm.Read(id);
if (personToEdit == null) return RedirectToAction("Index");
var viewModel = new EditPersonViewModel
{
Person = personToEdit,
Statuses = _psm.Read()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Edit(Person p)
{
_pm.Update(p);
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
var personToDelete = _pm.Read(id);
if (personToDelete == null) return RedirectToAction("Index");
return View(personToDelete);
}
[HttpPost]
public ActionResult Delete(int? id)
{
if (id.HasValue)
{
_pm.Delete(id.Value);
}
return RedirectToAction("Index");
}
}
}<file_sep>using PersonApplicationDll.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PersonApplicationDll.Managers
{
public class DllFacade
{
public IManager<Person> GetPersonManager()
{
return new PersonListManager();
}
public IManager<PersonStatus> GetPersonStatusManager()
{
return new PersonStatusListManager();
}
}
}
| f0d418d68b4fce6c95e2116b92896345ab6e8209 | [
"C#"
]
| 5 | C# | mindess98/webapp00 | 6f633d34b122184aa431e10c3831d4e7154240c4 | e128e2d63d71c00ee23b857f974772284cf324bc |
refs/heads/master | <repo_name>psmari/encrypt-cesar<file_sep>/Tests/test_decrypt.py
import unittest
from Controller.decrypt import decrypt
class test_decrypt(unittest.TestCase):
def test_verificar_retorno_word(self):
# Arrange
input = "cnbcn"
key = 10
# Act
response = decrypt().decrypt(input,key)
# Assert
self.assertEqual("teste", response)
def test_verificar_retorno_text(self):
# Arrange
input = "cnbcjwmx nbyjlx"
key = 10
# Act
response = decrypt().decrypt(input,key)
# Assert
self.assertEqual("testando espaco", response)
if __name__ == '__main__':
unittest.main()
<file_sep>/main.py
from Controller.encrypt import encrypt
from Controller.decrypt import decrypt
from Controller.alphabet import alphabet
class main():
continuar = '1'
while(continuar == '1'):
inputData = input('Insira o texto: ')
key = input('Insira a chave: ')
num = input('Insira o número do alfabeto que deseja :\n1.Português/Inglês\n2.Russo\n')
a = alphabet.getAlphabet(num)
choice = input('Insira o número da ação que deseja que aconteça:\n1.Criptografar\n2.Descriptografar \n')
if int(choice) == 1:
res = encrypt().encrypt(inputData,int(key), a)
print(res)
elif int(choice) == 2:
res = decrypt().decrypt(inputData, int(key), a)
print(res)
continuar = input('Insira 0 para encerrar ou 1 para continuar...\n')
<file_sep>/Tests/test_validation.py
import unittest
from Controller.validation import validation
class test_validation(unittest.TestCase):
def test_key_invalid(self):
# Arrange
input = "cnbcn"
key = 30
# Act
response = validation().keyIsValid(int(key))
# Assert
self.assertEqual("A chave deve estar no intervalo da quantidade de letras do alfabeto.", response)
def test_key_valid(self):
# Arrange
input = "cnbcn"
key = 26
# Act
response = validation().keyIsValid(int(key))
# Assert
self.assertEqual("", response)
if __name__ = '__main__':
unittest.main()
<file_sep>/Controller/decrypt.py
class decrypt():
def decrypt(self,input, key, alphabet):
inputDecrypt = ""
for i in range(len(input)):
letter = input[i]
positionLetter = -1
# verificando se é um espaço
if letter != ' ':
# verificando posição da letra do input
for i in range(len(alphabet)):
if letter.lower() == alphabet[i]:
positionLetter = i
break
if(positionLetter == -1):
return "Verifique se a mensagem usa letras do alfabeto que você escolheu..."
# descriptografando
index = (positionLetter - key) % len(alphabet)
inputDecrypt += alphabet[index]
else:
inputDecrypt += ' '
return inputDecrypt<file_sep>/Tests/test_encrypt.py
import unittest
from Controller.encrypt import encrypt
from Controller.alphabet import alphabet
class test_encrypt(unittest.TestCase):
def test_verificar_retorno_word(self):
# Arrange
input = "teste"
key = 10
# Act
response = encrypt().encrypt(input, key)
# Assert
self.assertEqual("cnbcn", response)
def test_verificar_retorno_text(self):
# Arrange
input = "<NAME>"
key = 10
# Act
response = encrypt().encrypt(input, key)
# Assert
self.assertEqual("cnbcjwmx nbyjlx", response)
if __name__ == '__main__':
unittest.main()
<file_sep>/Controller/encrypt.py
class encrypt():
def encrypt(self, input, key, alphabet):
inputEncrypt = ""
for i in range(len(input)):
letter = input[i]
positionLetter = -1
# verificando se é um espaço
if letter != ' ':
# verificando posição da letra do input
for i in range(len(alphabet)):
if letter.lower() == alphabet[i]:
positionLetter = i
break
if(positionLetter == -1):
return "Verifique se a mensagem usa letras do alfabeto que você escolheu..."
# criptografando
index = (positionLetter+key) % len(alphabet)
inputEncrypt += alphabet[index]
else:
inputEncrypt += ' '
return inputEncrypt | d0a986c1c8bd718ed3ad697483194dabc0f8c884 | [
"Python"
]
| 6 | Python | psmari/encrypt-cesar | 8491056bb74ed7763f5ea72fd0951bf40c0649cd | d7cdd3d51c7567de4dd7308dff1a11c0fff25552 |
refs/heads/main | <repo_name>eaglepix/DeployNodeSQLMongo<file_sep>/src/config/strategies/local.strategy.js
const passport = require('passport');
const { Strategy } = require('passport-local');
const { mongoDBconnection } = require('../../../app');
const debug = require('debug')('app:local.strategy');
module.exports = function localStrategy() {
passport.use(new Strategy(
{
usernameField: 'username',
passwordField: '<PASSWORD>'
}, (username, password, done) => {
const dbName = 'libraryApp';
(async function mongo() {
const client = await mongoDBconnection();
const db = client.useDb(dbName);
const col = db.collection('users');
const user = await col.findOne({ username });
debug(user);
if (user === null) {
return done(null, false, { message: 'Incorrect username.' });
} else if (user.username == username && user.password === <PASSWORD>) {
return done(null, user, { message: 'Successfully logged in!' });
} else {
return done(null, false, { message: 'Incorrect password.' });
};
}());
}));
};
<file_sep>/src/controllers/bookController.js
const debug = require('debug')('app:bookController');
const numCustomer = 8; //MongoDB to extract number of books
const mongoose = require('mongoose');
const { mongoDBconnection } = require('../../app');
function getJSON(numCustomer) {
return new Promise(resolve => {
const request = require('request');
let url = `https://randomuser.me/api/?results=${numCustomer}`;
let options = { json: true };
var linkArray = [];
request(url, options, (error, res, body) => {
if (error) {
resolve(error)
};
if (!error && res.statusCode == 200) {
// do something with JSON, using the 'body' variable
for (let i = 0; i < numCustomer; i++) {
linkArray.push(body.results[i].picture.large);
console.log('from requestHTTP', linkArray[i]);
}
};
resolve(linkArray);
});
});
};
async function asyncCall(bookService, nav, req, res, option) {
// MongoDB Atlas connection
const dbName = 'libraryApp'; //libraryApp pydot16
if (option == 'getAll') {
console.log('calling randomuser photos');
const faceLinkArray = await getJSON(numCustomer);
console.log('randomuser successfully retrieved', faceLinkArray);
(async () => {
try {
const client = await mongoDBconnection();
const db = client.useDb(dbName);
const col = db.collection('books');
const books = await col.find().toArray();
let contactName = new Array();
let customerName = new Array();
let city = new Array();
let customerNumber = new Array();
for (let i = 0; i < books.length; i++) {
customerName.push(books[i].title);
contactName.push(books[i].author);
city.push(books[i].genre);
customerNumber.push(books[i]._id);
};
res.render('bookListView',
{
nav,
title: 'Mongo Books List',
length: books.length,
pageNum: 1,
customerName,
contactName,
city,
customerNumber,
picture: faceLinkArray,
link: '/MongoDB/'
});
}
catch (err) {
console.error(`Error operating the database. \n${err}`);
debug(err.stack);
};
})();
} else if (option == 'getById') {
const numCustomer = 1;
const faceLinkArray = await getJSON(numCustomer);
console.log('async', faceLinkArray);
debug(req.params);
const { id } = req.params;
(async () => {
try {
const client = await mongoDBconnection();
const db = client.useDb(dbName);
const col = db.collection('books');
const book = await col.findOne({ _id: new mongoose.Types.ObjectId(id) });
debug(book);
// API connect to openLibrary
const libraryAPI = await bookService.getBookById(book.title);
console.log('libraryAPI', libraryAPI);
let { title, author, genre, _id, } = book;
console.log('MongoDB Book details:', book, title, author, genre, _id);
res.render('bookView',
{
nav,
title: 'Individual Book Details',
customerName: title,
contactName: author,
database: 'MongoDB',
pageNum: '',
comm1: `Genre: ${genre}`,
comm2: `URL: ${libraryAPI.link}`,
comm3: `First Published Year: ${libraryAPI.first_publish_year}`,
detail_1: `Book ID: ${libraryAPI.OLID_ID}`,
detail_2: `Subject: ${libraryAPI.subject}`,
detail_3: `Description: ${libraryAPI.description}`,
picture: `http://covers.openlibrary.org/a/olid/${libraryAPI.authorpix}-L.jpg`,
// picture: `http://covers.openlibrary.org/b/olid/${book.desc.bookCover}-L.jpg`,
// picture: faceLinkArray[0],
});
}
catch (err) {
console.error(`Error operating the database. \n${err}`);
debug(err.stack);
};
})();
};
};
function bookController(bookService, nav) {
console.log('bookService', bookService);
function getIndex(req, res) {
asyncCall(bookService, nav, req, res, 'getAll');
}
function getById(req, res) {
asyncCall(bookService, nav, req, res, 'getById');
}
function middleware(req, res, next) {
if (req.user) {
next();
} else {
res.redirect('/');
}
}
return {
getIndex, getById, middleware
};
};
module.exports = {
'bookController': bookController,
// 'mongoURL': mongoURL,
// 'options': options
};<file_sep>/src/routes/mongoRoutes.js
const express = require('express');
const mongoRouter = express.Router();
const bookService = require('../services/openLibraryService');
const { bookController } = require('../controllers/bookController');
function router(nav) {
const { getIndex, getById, middleware } = bookController(bookService, nav);
mongoRouter.use(middleware);
mongoRouter.route('/')
.get(getIndex);
mongoRouter.route('/:id')
// .all((req,res,next) =>{}) to inject middleware if want
.get(getById);
return mongoRouter;
};
module.exports = router;
<file_sep>/Mongodb_startUp.md
To start up MongoDB local host: Need to open 2 cmd>
1) Start up mongod (local server) and assign the path:
"C:\Program Files\MongoDB\Server\4.4\bin\mongod.exe" --dbpath C:\Users\KL\Documents\MongoDBdata
2) Starting Mongo client from cmd>db
"C:\Program Files\MongoDB\Server\4.4\bin\mongo"
> show dbs
> use libraryApp
> db.books.find().pretty
> db.books.find()
3) Mongo CLI starting MongoDB Atlas
>mongo "mongodb+srv://pydot16.tafgx.mongodb.net/pydot16" --username eaglepix
<file_sep>/app.js
const express = require('express');
const chalk = require('chalk');
const debug = require('debug')('app');
const morgan = require('morgan');
const path = require('path');
const bodyParser = require('body-parser');
const passport = require('passport');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const app = express();
const port = process.env.PORT || 3000; // Boolean: if main port fails use backup port 3000
//Not recommended to do port this way: process.env.PORT doesn't check if the port is available
// cleardb MySQL server connection:
const mysql = require('mysql');
const pool = mysql.createPool(process.env.MYSQL_URL);
// To deploy the databases locally:
// const { cleardb } = require('C:/Users/kl/Documents/configVar.json');
// const pool = mysql.createPool({
// connectionLimit: 10,
// host: cleardb.host,
// port: 3306,
// user: cleardb.Username,
// password: <PASSWORD>,
// database: cleardb.database
// });
// connectionLimit: 10,
// host: 'localhost',
// port: 3306,
// user: 'root',
// password: <PASSWORD>,
// database: 'classicmodels'
// MongoDB Atlas connection variables
const mongoose = require('mongoose');
// Reading configVar.json
// const mgo = require('C:/Users/kl/Documents/configVar.json').mongoDB;
// const ID = mgo['ID2'];
// const pw = mgo['pw2'];
// const db = mgo['db1'];
// const mongoURL = mgo['url1'] + ID + ":" + pw + "@" + mgo['url2'] + db + mgo['url3'];
const mongoURL = process.env.MONGODB_URL;
const options = {
useNewUrlParser: true,
useUnifiedTopology: true
};
// 2 different ways of module exports:
module.exports = {
mongoDBconnection: (async () => {
var client = mongoose.connection;
console.log('Not connected=0 =>', mongoose.connection.readyState);
console.log('Connecting to Mongo Atlas Server ...');
await mongoose.connect(mongoURL, options);
console.log('Connected=1 =>', mongoose.connection.readyState);
console.log('Connected correctly to MongoDB server ');
client.on('error', console.error.bind(console, 'MongoDB Atlas connection error:'));
// console.log(client);
return client;
})
};
pool.getConnection((err, connection) => {
if (err) throw err => { debug(err) };
console.log(`connected as id ${connection.threadId}`);
console.log(`Mysql listening at port ${chalk.bgRed(connection.config.host, connection.config.port)}`);
module.exports.sqlConnection = connection;
});
// app.use(morgan('combined'));
app.use(morgan('tiny')); //spill out less info ... GET/304
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({ secret: 'library' }));
require('./src/config/passport.js')(app);
app.use(express.static(path.join(__dirname, '/public')));
app.use('/css', express.static(path.join(__dirname, 'node_modules/bootstrap/dist/css')));
app.use('/js', express.static(path.join(__dirname, 'node_modules/bootstrap/dist/js')));
app.use('/js', express.static(path.join(__dirname, 'node_modules/jquery/dist')));
app.set('views', './src/views');
app.set('view engine', 'ejs');
// app.set('view engine', 'pug');
const nav = [
{ link: '/books', title: 'SQL-Customers' },
{ link: '/MongoDB', title: 'MongoDB-Books' }
];
const bookRouter = require('./src/routes/bookRoutes')(nav);
const adminRouter = require('./src/routes/adminRoutes')(nav);
const mongoRouter = require('./src/routes/mongoRoutes')(nav);
const authRouter = require('./src/routes/authRoutes')(nav);
app.use('/books', bookRouter);
app.use('/admin', adminRouter);
app.use('/MongoDB', mongoRouter);
app.use('/auth', authRouter);
app.get('/', (req, res) => {
res.render('index',
{
nav: [{ link: '/books', title: 'SQL - Customer List' },
{ link: '/MongoDB', title: 'MongoDB - Books' },
{ link: '/admin', title: 'Admin: Add books to MongoDB' }],
title: 'Main Menu'
}); //for ejs
});
app.listen(port, function () {
debug(`listening at port ${chalk.green(port)}`);
});
<file_sep>/src/routes/bookRoutes.js
const express = require('express');
const bookRouter = express.Router();
const debug = require('debug')('app:bookRoutes');
const DB_connections = require('../../app');
const numCustomer = 10; //SQL to extract number of customers
var currPage;
function getJSON(numCustomer) {
return new Promise(resolve => {
const request = require('request');
let url = `https://randomuser.me/api/?results=${numCustomer}`;
let options = { json: true };
var linkArray = [];
request(url, options, (error, res, body) => {
if (error) {
resolve(error)
};
if (!error && res.statusCode == 200) {
// do something with JSON, using the 'body' variable
for (let i = 0; i < numCustomer; i++) {
linkArray.push(body.results[i].picture.large);
console.log('from requestHTTP', linkArray[i]);
}
};
resolve(linkArray);
});
});
};
async function asyncCall(nav, req, res, option, numCustomer) {
console.log('calling getJSON()');
if (option == 1) {
const faceLinkArray = await getJSON(numCustomer);
console.log('async', faceLinkArray);
let pgNum;
debug(req.params);
console.log('req.params', req.params);
if (Object.keys(req.params).length === 0) {
console.log('req.param is null');
pgNum = 1;
} else {
pgNum = req.params.pgNum;
console.log('pgNum', pgNum);
}
currPage = Number(pgNum);
console.log('currPage', currPage);
offsetNum = (currPage - 1) * numCustomer;
// example: query(sqlString, callback)
const sql = DB_connections.sqlConnection;
sql.query(`SELECT * from customers LIMIT ${numCustomer} OFFSET ${offsetNum}`, (err, result) => {
// connection.release(); // When done with the connection, release it.
debug(result);
let contactName = new Array();
let customerName = new Array();
let city = new Array();
let customerNumber = new Array();
for (let i = 0; i < result.length; i++) {
customerName.push(result[i].customerName);
contactName.push([result[i].contactFirstName, result[i].contactLastName].join(' '));
city.push(result[i].city);
customerNumber.push(result[i].customerNumber);
}
console.log(customerName, contactName, customerName, customerNumber);
res.render('bookListView',
{
nav,
title: 'SQL Customer List',
pageNum: currPage,
length: result.length,
customerName,
contactName,
city,
customerNumber,
picture: faceLinkArray,
link: '/books/indv/'
});
});
} else if (option == 2) {
const numCustomer = 1;
const faceLinkArray = await getJSON(numCustomer);
console.log('async', faceLinkArray);
console.log('currPage', currPage);
debug(req.params);
const { customerNumber } = req.params;
// const { id } = req.params;
// connection.input('customerNumber', customerNumber)
// .query(`SELECT * from customers WHERE customerNumber=@customerNumber}`, (err, result) => {
// example: query(sqlString, callback)
const sql = DB_connections.sqlConnection;
sql.query('SELECT * from customers WHERE customerNumber=?', [customerNumber], (err, result) => {
// getConnection().query(`SELECT * from customers WHERE customerNumber=${customerNumber}`, (err, result) => {
console.log('Result:', result[0]);
console.log(result[0].customerName);
let { customerName, city, country, customerNumber, phone, salesRepEmployeeNumber, creditLimit } = result[0];
let contactName = [result[0].contactFirstName, result[0].contactLastName].join(' ')
res.render('bookView',
{
nav,
database: 'books',
pageNum: currPage,
title: 'Individual Customer List',
customerName,
contactName,
comm1: `City: ${city}`,
comm2: `Country: ${country}`,
comm3: `Customer Number: ${customerNumber}`,
detail_1: `Phone: ${phone}`,
detail_2: `Sales Rep. Number: ${salesRepEmployeeNumber}`,
detail_3: `Credit Limit: ${creditLimit}`,
picture: faceLinkArray[0],
});
// res.send('hello single book');
});
};
};
function router(nav) {
let offsetNum;
bookRouter.use((req, res, next) => {
if (req.user) {
next();
} else {
res.redirect('/');
}
});
bookRouter.route('/').get((req, res) => {
asyncCall(nav, req, res, 1, numCustomer);
});
bookRouter.route('/indv/:customerNumber')
// .all((req,res,next) =>{}) to inject middleware if want
.get((req, res) => {
asyncCall(nav, req, res, 2, numCustomer);
});
bookRouter.route('/:pgNum')
// .all((req,res,next) =>{}) to inject middleware if want
.get((req, res) => {
asyncCall(nav, req, res, 1, numCustomer);
});
return bookRouter;
};
module.exports = router; | af8f8493224a0ccdee952b0f561c150882e087d7 | [
"JavaScript",
"Markdown"
]
| 6 | JavaScript | eaglepix/DeployNodeSQLMongo | d1ed1e22585fada69a129ce408baf6e03d43a31e | dc89304f0d236c035cff1c9e2fe0bca8930222c5 |
refs/heads/master | <file_sep>#include "network.h"
#include "random.h"
#include <algorithm>
#include <cmath>
Network::Network() {}
void Network::resize(const size_t& n){
values.resize(n);
RNG.normal(values);
}
bool Network::add_link(const size_t& a, const size_t& b){
if ((a == b) or (a >= values.size()) or (b >= values.size())) return false;
vector<size_t> neighborsA(neighbors(a));
vector<size_t> neighborsB(neighbors(b));
for(auto i : neighborsA){
if (i == b) return false;
}
for(auto i : neighborsB){
if (i == a) return false;
}
links.insert(std::pair<size_t, size_t > (a,b));
links.insert(std::pair<size_t, size_t > (b,a));
return true;
}
size_t Network::random_connect(const double& n){
RandomNumbers randomGenerator;
vector<int> numberOfConnections(values.size());
randomGenerator.poisson(numberOfConnections, n);
links.clear();
size_t result(0);
for(size_t i(0); i < values.size(); i++){
size_t nOC = numberOfConnections[i];
vector<int> randomConnection(values.size()); // va tester seulemtent values.size() valeurs, si pas trouvé de node libre parmis ces valeurs tant pis
for(size_t j(0); j<randomConnection.size() and degree(i) < nOC; j++){
randomGenerator.uniform_int(randomConnection, 0, values.size()-1);
if (degree(randomConnection[j]) < size_t (numberOfConnections[randomConnection[j]])){
if (add_link(i, randomConnection[j])) result++;
}
}
}
return result*2; //liens bidirectionnels dans le test
}
size_t Network::set_values(const std::vector<double>& newValues){
size_t result(0);
for( size_t i(0); i < newValues.size() and i < values.size(); i++){
values[i] = newValues[i];
result++;
}
return result;
}
size_t Network::size() const{
return values.size();
}
size_t Network::degree(const size_t &_n) const{
if (_n >= values.size()) throw out_of_range("In function degree: There's not " + to_string(_n) + " nodes");
return links.count(_n);
}
double Network::value(const size_t &_n) const{
if (_n >= values.size()) throw out_of_range("In function value: There's not " + to_string(_n) + " nodes");
return values[_n];
}
vector<double> Network::sorted_values() const{
vector<double> result(values);
sort(result.begin(), result.end());
reverse(result.begin(), result.end());
return result;
}
std::vector<size_t> Network::neighbors(const size_t& n) { // j'ai du enlever le const, marchait pas avec le equal_range
if (n >= values.size()) throw out_of_range("In function neighboors: There's not " + to_string(n) + " nodes");
vector<size_t> result;
std::pair<std::multimap<size_t, size_t>::iterator, std::multimap<size_t, size_t>::iterator> voisins;
voisins = links.equal_range(n);
for(std::multimap<size_t, size_t>::iterator i(voisins.first); i != voisins.second; i++ ){
result.push_back(i->second);
}
return result;
}
| c472ffe49780dee87ce7d16ee26ca065046ccc5d | [
"C++"
]
| 1 | C++ | AmauryMigeotte/Project2 | 19ceae1392f438e334fbc8b51b1201be02fa19fe | 8a7095e4cf59a28c37a36cc1aae73fb3be881b7e |
refs/heads/master | <repo_name>mduvarci12/onesignal-android-app<file_sep>/app/src/main/java/com/projectxr/mehmetd/personelynetim/models/sonMessage.java
package com.projectxr.mehmetd.personelynetim.models;
public class sonMessage {
private String Status;
public sonMessage(String status) {
Status = status;
}
public String getStatus() {
return Status;
}
}
<file_sep>/app/src/main/java/com/projectxr/mehmetd/personelynetim/models/BildirimResponse.java
package com.projectxr.mehmetd.personelynetim.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
public class BildirimResponse implements Serializable
{
@SerializedName("status")
@Expose
private String status;
@SerializedName("bildirimler")
@Expose
private List<Bildirimler> bildirimler = null;
private final static long serialVersionUID = 3548500618987725376L;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public BildirimResponse withStatus(String status) {
this.status = status;
return this;
}
public List<Bildirimler> getBildirimler() {
return bildirimler;
}
public void setBildirimler(List<Bildirimler> bildirimler) {
this.bildirimler = bildirimler;
}
public BildirimResponse withBildirimler(List<Bildirimler> bildirimler) {
this.bildirimler = bildirimler;
return this;
}
}<file_sep>/app/src/main/java/com/projectxr/mehmetd/personelynetim/ListItem.java
package com.projectxr.mehmetd.personelynetim;
public class ListItem {
private String productImage;
private String firmaName;
private String mekan_id;
public ListItem(String productImage, String firmaName, String mekan_id) {
this.productImage = productImage;
this.firmaName = firmaName;
this.mekan_id = mekan_id;
}
public String getProductImage() {
return productImage;
}
public String getFirmaName() {
return firmaName;
}
public String getMekan_id() {
return mekan_id;
}
}
<file_sep>/app/src/main/java/com/projectxr/mehmetd/personelynetim/models/LoginResponse.java
package com.projectxr.mehmetd.personelynetim.models;
public class LoginResponse {
private String status;
private String key;
public LoginResponse(String status, String key) {
this.status = status;
this.key = key;
}
public String getStatus() {
return status;
}
public String getKey() {
return key;
}
}
<file_sep>/app/src/main/java/com/projectxr/mehmetd/personelynetim/models/firma_id.java
package com.projectxr.mehmetd.personelynetim.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class firma_id {
@SerializedName("firma_id")
@Expose
private List<firma_id> firma_id = null;
public firma_id(List<com.projectxr.mehmetd.personelynetim.models.firma_id> firma_id) {
this.firma_id = firma_id;
}
public List<com.projectxr.mehmetd.personelynetim.models.firma_id> getFirma_id() {
return firma_id;
}
}
<file_sep>/app/src/main/java/com/projectxr/mehmetd/personelynetim/models/Item.java
package com.projectxr.mehmetd.personelynetim.models;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.projectxr.mehmetd.personelynetim.models.ItemResponse;
public class Item {
@SerializedName("status")
@Expose
private String status;
@SerializedName("firmalar")
@Expose
private List<ItemResponse> firmalar = null;
/**
* No args constructor for use in serialization
*
*/
public Item() {
}
/**
* @param status
* @param firmalar
*/
public Item(String status, List<ItemResponse> firmalar) {
super();
this.status = status;
this.firmalar = firmalar;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public List<ItemResponse> getFirmalar() {
return firmalar;
}
public void setFirmalar(List<ItemResponse> firmalar) {
this.firmalar = firmalar;
}
}
<file_sep>/app/src/main/java/com/projectxr/mehmetd/personelynetim/API/RetrofitService.java
package com.projectxr.mehmetd.personelynetim.API;
import com.projectxr.mehmetd.personelynetim.models.BildirimResponse;
import com.projectxr.mehmetd.personelynetim.models.FeedBackModel;
import com.projectxr.mehmetd.personelynetim.models.Item;
import com.projectxr.mehmetd.personelynetim.models.LoginResponse;
import com.projectxr.mehmetd.personelynetim.models.playerId;
import com.projectxr.mehmetd.personelynetim.models.sonMessage;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface RetrofitService {
@FormUrlEncoded
@POST("createuser")
Call<ResponseBody> createUser(
@Field("email") String email,
@Field("password") String password,
@Field("name") String name,
@Field("school") String school
);
@FormUrlEncoded
@POST("users/login")
Call<LoginResponse> userLogin(
@Field("username") String username,
@Field("password") String password
);
@FormUrlEncoded
@POST("users/set_player_id")
Call<playerId> setPlayerId(
@Field("user_key") String user_key,
@Field("player_id") String player_id
);
@FormUrlEncoded
@POST(RetrofitClient.BASE_URL + "firma/get_user_firma")
Call<Item> getFirma(
@Field("user_key") String user_key
);
@FormUrlEncoded
@POST("users/departmanlar")
Call<String> postDepartman(
@Field("firma_id") String firma_id);
@FormUrlEncoded
@POST("/bildirim")
Call<sonMessage> postMessage(
@Field("content") String context,
@Field("user_type") String user_type,
@Field("firma_id") String firma_id,
@Field("user_key") String user_key,
@Field("device_id") String deviceId
);
@FormUrlEncoded
@POST("/bildirimlerim")
Call<BildirimResponse> bildirimlerim(
@Field("player_id") String PlayerID
);
@FormUrlEncoded
@POST("/feedback")
Call<FeedBackModel> feedback(
@Field("bildirim_id") String bildirimID
);
}
<file_sep>/app/src/main/java/com/projectxr/mehmetd/personelynetim/DepartmanSec.java
package com.projectxr.mehmetd.personelynetim;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.projectxr.mehmetd.personelynetim.API.RetrofitClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.GET;
class Departman {
public String departmanTitle;
}
interface RetrofitService{
@GET("/users")
Call<ResponseBody> listRepos();//function to call api
}
public class DepartmanSec extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firma_sec);
final String mekanID = getIntent().getStringExtra("mekanID");
System.out.print(mekanID);
Call<String> call = RetrofitClient.getInstance().getApi().postDepartman(mekanID);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Log.e("departmanlar", response.body().toString());
String result = response.body().toString();
String asd = result.replace("[", "");
String dsa = asd.replace("]", "");
String das = dsa.replace("\"","");
final String[] strings = das.split(",");
// ADAPTERDE KULLANILACAK ARRAY strings
// Log.e("string arrayi0", strings[0]);
// Log.e("string arrayi1", strings[1]);
// Log.e("string arrayi2", strings[2]);
// Log.e("string arrayisize"," "+ strings.length);
ListView listView = findViewById(R.id.listview);
ArrayAdapter<String > adapter = new ArrayAdapter<>(getBaseContext(),android.R.layout.simple_list_item_1, strings);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// mekanID
Log.e("position",strings[position]);
Intent i = new Intent(DepartmanSec.this,SendActivity.class);
i.putExtra("mekanID", mekanID);
i.putExtra("user_type", strings[position]);
startActivity(i);
}
});
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("ASDASD" , "FAIL");
}
});
}
}
| d98bfbb33eb29fa94e0986f440d4b4616317934d | [
"Java"
]
| 8 | Java | mduvarci12/onesignal-android-app | bcc006b9375d98c59c5f2823302501aa3024abfe | 16991e42966594d9c1361f52780f2c12cdc072b9 |
refs/heads/master | <repo_name>Xizi0n/angular-template<file_sep>/angular-template/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { RouterModule, Routes } from '@angular/router';
// Material Component Imports
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatButtonModule} from '@angular/material/button';
import {MatSidenavModule} from '@angular/material/sidenav';
import {MatIconModule} from '@angular/material/icon';
import {MatCardModule} from '@angular/material/card';
import {MatMenuModule} from '@angular/material/menu';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {MatListModule} from '@angular/material/list';
import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { SidenavComponent } from './sidenav/sidenav.component';
import { ItemComponent } from './item/item.component';
import { RegistrationComponent } from './registration/registration.component';
import { LoginComponent } from './login/login.component';
import { WelcomeComponent } from './welcome/welcome.component';
import { CartComponent } from './cart/cart.component';
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'registration', component: RegistrationComponent },
{ path: '', component: WelcomeComponent},
{ path: 'cart', component: CartComponent}
];
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
SidenavComponent,
ItemComponent,
RegistrationComponent,
LoginComponent,
WelcomeComponent,
CartComponent
],
imports: [
BrowserModule,
RouterModule.forRoot( appRoutes, { enableTracing: true }),
BrowserAnimationsModule,
MatToolbarModule,
MatButtonModule,
MatSidenavModule,
MatIconModule,
MatCardModule,
MatMenuModule,
MatFormFieldModule,
MatInputModule,
MatListModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/angular-template/README.md
# AngularTemplate
## Előkészületek
### NodeJs telepítése
https://nodejs.org -ról letöltés és telepítés
Csekkolni hogy sikeres-e?
```
node -v
```
ha kiírja a verziószámot (jó esetben: v8.12.0)
```
npm -v
```
hakiír valami verziót akkor ez is jó
### Angular cli telepítése
Parancssorba:
```
npm install -g @angular/[email protected]
```
## Futtatás
Terminálba be cd-zel a projekt mappájába. Utána
```
npm install
```
Miután az lefut, jön az alábbi parancs:
```
ng serve
```
Ezután localhoston tudjátok elérni az appot
localhost:4200
<file_sep>/angular-template/src/app/welcome/welcome.component.html
<div >
<div class="container">
<img src="/assets/logo.png" alt="" class="logo">
<div class="miert">
<h4 class="center">Miért válassza Ön is az ElectricStuff csapatát?</h4>
<div class="row">
<div class="col-sm-3">
<mat-card>
<mat-card-header>
<mat-icon color="primary" style="text-align: center;">weekend</mat-icon>
</mat-card-header>
<mat-card-content>
<p>
Kényelmes rendelés
</p>
</mat-card-content>
</mat-card>
</div>
<div class="col-sm-3">
<mat-card>
<mat-card-header>
<mat-icon color="primary">local_shipping</mat-icon>
</mat-card-header>
<mat-card-content>
<p>
Gyors kiszállítás
</p>
</mat-card-content>
</mat-card>
</div>
<div class="col-sm-3">
<mat-card>
<mat-card-header>
<mat-icon color="primary">headset_mic</mat-icon>
</mat-card-header>
<mat-card-content>
<p>
Telefonos Segítség
</p>
</mat-card-content>
</mat-card>
</div>
<div class="col-sm-3">
<mat-card>
<mat-card-header>
<mat-icon color="primary">local_grocery_store</mat-icon>
</mat-card-header>
<mat-card-content>
<p>
Széles választék
</p>
</mat-card-content>
</mat-card>
</div>
</div>
</div>
</div>
</div> | b47807a4237cadfb08f2114d4bb9980e1e27988f | [
"Markdown",
"TypeScript",
"HTML"
]
| 3 | TypeScript | Xizi0n/angular-template | a76bfbc4890d6a7fac9749cdbc3200c2040dd383 | 8a17b99825342fd94ea58f619fc540af9231fc9f |
refs/heads/master | <repo_name>mvolkmann/angularjs-labs<file_sep>/collectbook/README.txt
To run the tests in this directory:
- open a new terminal
- cd to this directory
- node server.js
- open a new terminal
- cd to this directory
- protractor protractor-conf-js
or
grunt protractor
<file_sep>/collectbook/test/unit/dialog-directive-spec.js
'use strict';
/*global $: false, angular: false, beforeEach: false, describe: false, expect: false,
inject: false, it: false */
describe('cbDialog directive', function () {
beforeEach(module('cb-directives', 'features/directives/dialog.html'));
it('should work', inject(function ($compile, $rootScope, cbDialogSvc) {
var scope = $rootScope.$new();
// This is a place where the button functions can store data
// that will be accessible outside the dialog directive.
scope.data = {};
// This defines the buttons that will appear in the dialog footer
// and what will happen when they are pressed.
scope.btnMap = {
'OK': function () {
scope.data.ok = 'pressed OK';
},
'Cancel': function () {
scope.data.cancel = 'pressed Cancel';
}
};
// Create a dialog.
var html = '<cb-dialog id="myDialog" ' +
'title="Some Title" btn-map="btnMap" data="data">' +
'<h1>Content Header</h1>' +
'<p>content</p>' +
'</cb-dialog>';
var element = angular.element(html);
$compile(element)(scope);
scope.$digest();
// It should have the Twitter Bootstrap CSS class "modal".
expect(element.hasClass('modal')).toBe(true);
// Get a reference to the DOM element at the top of the dialog HTML.
var domEl = element[0];
// Test the content in the dialog body.
var body = domEl.querySelector('.modal-body');
var h1 = body.firstChild;
expect(h1.tagName).toBe('H1');
expect(h1.textContent).toBe('Content Header');
var p = body.lastChild;
expect(p.tagName).toBe('P');
expect(p.textContent).toBe('content');
// Test the buttons in the dialog footer.
// These values are set in the btnMap functions,
// but shouldn't be set yet.
expect(scope.data.ok).toBeUndefined();
expect(scope.data.cancel).toBeUndefined();
var okBtn = domEl.querySelector('#ok-btn');
expect(okBtn).not.toBeNull();
okBtn.click();
expect(scope.data.ok).toBe('pressed OK');
var cancelBtn = domEl.querySelector('#cancel-btn');
expect(cancelBtn).not.toBeNull();
cancelBtn.click();
expect(scope.data.cancel).toBe('pressed Cancel');
}));
});
<file_sep>/collectbook/features/filters/main.js
'use strict';
/*jshint esnext: true */
/*global angular: false */
var mod = angular.module('cb-filters', ['ngSanitize']);
// ES6 imports of files that add to this module.
import './obj-to-arr.js';
import './raw.js';
<file_sep>/collectbook/test/e2e/share.js
'use strict';
/*global beforeEach: false, browser: false, by: false, describe: false,
element: false, expect: false, it: false, protractor: false, xit: false */
var share = {
btnText: 'Foo Bar Baz',
fieldName: 'Email',
fieldType: 'email',
fieldPlaceholder: 'home email address',
ptor: null // set by share.before
};
share.before = function () {
browser.get('http://localhost:3000/');
share.ptor = protractor.getInstance();
};
function selectOption(selectElement, optionText) {
selectElement.findElements(by.tagName('option')).then(function (options) {
options.forEach(function (option) {
option.getText().then(function (text) {
if (text === optionText) option.click();
});
});
});
}
share.createTestBook = function () {
// Create a new book.
element(by.id('add-btn')).element(by.tagName('a')).click();
element(by.id('name')).sendKeys(share.btnText);
element(by.buttonText('Add')).click();
};
share.editTestBook = function () {
// Switch to the "edit" view for the new book.
var btn = element(by.buttonText(share.btnText));
var parent = btn.element(by.xpath('..'));
var icons = parent.element(by.className('icons'));
var editBtn = icons.element(by.className('glyphicon-wrench'));
editBtn.click();
// Add a field.
element(by.id('name')).sendKeys(share.fieldName);
selectOption(element(by.id('type')), share.fieldType);
var placeholder = element(by.id('placeholder'));
placeholder.clear();
placeholder.sendKeys(share.fieldPlaceholder);
element(by.id('required')).click();
element(by.buttonText('Add')).click();
};
share.deleteTestBook = function () {
var btn = element(by.buttonText(share.btnText));
var parent = btn.element(by.xpath('..'));
var icons = parent.element(by.className('icons'));
var deleteBtn = icons.element(by.className('glyphicon-remove'));
deleteBtn.click();
dismissAlert();
};
function dismissAlert() {
// Press "OK" button in alert.
share.ptor.switchTo().alert().accept();
}
module.exports = share;
<file_sep>/collectbook/features/models/item.js
'use strict';
/*jshint esnext: true */
class Item {
constructor() {
// Use the current timestamp as the unique id for this object.
this.id = Date.now();
// There are no other fixed properties for Item objects.
// They are dependent on the fields in the associated Book object.
}
}
export default Item;
<file_sep>/genlab.js
#!/usr/bin/env node
'use strict';
/*jshint esnext: true */
var child_process = require('child_process');
var fs = require('fs');
var newline = require('os').EOL; //'\n';
var rimraf = require('rimraf');
var onWindows = /^win/.test(process.platform);
function exit(msg) {
console.error(msg);
process.exit(1);
}
// Get the first command-line argument.
var filePath = process.argv[2];
if (!filePath) {
exit('usage: node genlab.js {lab-name}.txt');
}
// Read all the lines in the file.
var options = {encoding: 'utf8'};
var lines = fs.readFileSync(filePath, options).split(newline);
var lineIndex = 0;
function nextLine() {
return lines[lineIndex++];
}
// Get srcDir.
var line = nextLine();
console.log(line);
var match = line.match(/^srcDir (.+)$/);
if (!match) exit('first line must start with "srcDir"');
var srcDir = match[1];
// Get destDir.
line = nextLine();
match = line.match(/^destDir (.+)$/);
if (!match) {
throw 'second line must start with "destDir"';
}
var destDir = match[1];
// Get first file to process.
line = nextLine();
match = line.match(/^file (.+)$/);
if (!match) {
throw 'third line must start with "file"';
}
var firstFile = match[1];
// Remove destDir if it already exists.
console.log('removing', destDir, 'directory');
rimraf.sync(destDir);
// Copy srcDir to a new directory with the name of the lab.
console.log('copying', srcDir, 'directory to', destDir);
var cmd = onWindows ?
//'xcopy /e .\\' + srcDir + ' .\\' + destDir + '\\\\ /exclude:excludes.txt' :
'robocopy ' + srcDir + ' ' + destDir +
' /s /xd build node_modules > log:Nul' :
'rsync -a --exclude build --exclude node_modules ' + srcDir + '/ ' + destDir;
console.log('copy command is', cmd);
child_process.exec(cmd, function (err) {
if (err && !onWindows) exit(err);
processFile(firstFile);
});
/**
* Returns the index of the first line in an array of lines
* that matches a given regular expression.
* An optional startIndex for the search can be specified.
* Otherwise it starts at index 0.
*/
function findMatchingLine(lines, re, startIndex) {
re = new RegExp(re);
if (!startIndex) startIndex = 0;
var found = false, index;
for (index = startIndex; index < lines.length; index++) {
if (re.test(lines[index])) {
found = true;
break;
}
}
return found ? index : -1;
}
function processFile(filePath) {
console.log('modifying', filePath);
var path = destDir + '/' + filePath;
var oldLines = fs.readFileSync(path, options).split(newline);
processMods(filePath, oldLines);
// Write over old file.
fs.writeFile(path, oldLines.join(newline));
var line = nextLine();
if (!line) return; // end of file
var match = line.match(/^file (.+)$/);
if (!match) exit('expected file path but found', line);
processFile(match[1]);
}
function processMods(filePath, oldLines) {
var line = nextLine();
while (true) {
processMod(filePath, line, oldLines);
line = nextLine();
if (!line) break; // end of file
var match = line.match(/^file (.+)$/);
if (match) { // new file to process
lineIndex--; // back up one one
break;
}
}
}
function processMod(filePath, startRe, oldLines) {
var line = nextLine();
var length = parseInt(line, 10);
if (isNaN(length)) {
exit('invalid length after ' + startRe + ' for ' + filePath);
}
// Get lines up to the next empty line.
var newLines = [];
while (true) {
line = nextLine();
if (!line) break;
if (line === '\\n') line = '';
newLines.push(line);
}
// Find start of line range using startRe.
var startIndex = findMatchingLine(oldLines, startRe);
if (startIndex === -1) {
exit('no match found in ' + filePath + ' for ' + startRe);
}
//console.log('genLab2: re', startRe, 'matched at index', index);
var endIndex = startIndex + length - 1;
/*
console.log('replacing lines',
startIndex + 1, 'to', endIndex + 1,
'with\n' + newLines.join('\n') + '\n');
*/
var numLines = endIndex - startIndex + 1;
var args = [startIndex, numLines].concat(newLines);
oldLines.splice.apply(oldLines, args);
}
<file_sep>/README.md
angularjs-labs
==============
These are lab exercises for a course I teach on AngularJS.
For each lab,
1) generate a directory of files for lab n by
entering "node genlab.js labn.txt
2) cd to the labn directory
3) enter "npm install" to install all the Node.js dependencies
(proceed to the next step while this is running)
4) edit all the files containing "Lab:" comments
5) enter "grunt" to start the server
6) browse localhost:3000 to verify that the app works
<file_sep>/collectbook/test/unit/module-spec.js
'use strict';
/*global angular: false, describe: false, expect: false, it: false */
describe('KarmaDemo module', function () {
var module = angular.module('CollectBook');
it('should exist', function () {
expect(module).not.toBeNull();
});
it('should have correct dependencies', function () {
expect(module.requires.length).toBe(3);
expect(module.requires).toContain('cb-directives');
expect(module.requires).toContain('cb-filters');
expect(module.requires).toContain('ui.router');
});
});
<file_sep>/collectbook/test/unit/raw-filter-spec.js
'use strict';
/*global angular: false, beforeEach: false, describe: false, expect: false,
inject: false, it: false */
describe('objToArr filter', function () {
beforeEach(module('CollectBook'));
it('should provide SCE', inject(function (rawFilter) {
var html = '<div>playing card heart is &heart;</div>';
var actual = rawFilter(html);
expect(typeof actual).toBe('object');
var fn = actual.$$unwrapTrustedValue;
expect(typeof fn).toBe('function');
expect(fn()).toBe(html);
}));
});
<file_sep>/collectbook/test/unit/viewBookCtrl-spec.js
'use strict';
/*global angular: false, beforeEach: false, describe: false, expect: false,
inject: false, it: false */
describe('ViewBookCtrl controller', function () {
var scope;
beforeEach(function () {
module('CollectBook');
// Provide mock versions of "book" and "item" that are
// normally obtained from a resolve.
module(function ($provide) {
$provide.value('book', {data: {}});
$provide.value('items', {data: []});
});
// Create a scope for ViewBookCtrl.
inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
$controller('ViewBookCtrl', {$scope: scope});
});
});
it('should edit an item', function () {
// Test initial state.
expect(scope.editing).toBe(false);
// Test state after initiating editing of an item.
var item = 'any-value';
scope.editItem(item);
expect(scope.editing).toBe(true);
expect(scope.item).toBe(item);
// Test state after initiating editing of a different item.
item = 'different-value';
scope.editItem(item);
expect(scope.editing).toBe(true);
expect(scope.item).toBe(item);
});
it('should get field CSS class', function () {
expect(scope.getFieldClass({type: 'integer'})).toBe('right');
expect(scope.getFieldClass({type: 'anything-else'})).toBe('');
});
it('should get input CSS class', function () {
expect(scope.inputClass({type: 'boolean'})).toBe('');
expect(scope.inputClass({type: 'anything-else'})).toBe('form-control');
});
it('should get input type', function () {
expect(scope.inputType({type: 'boolean'})).toBe('checkbox');
expect(scope.inputType({type: 'integer'})).toBe('number');
expect(scope.inputType({type: 'anything-else'})).toBe('text');
});
it('should handle sorting', function () {
// Sort on a new field for the first time.
var field = {propertyName: 'some-prop-1'};
expect(scope.sortOn(field));
expect(scope.reverse).toBe(false);
expect(scope.sortKey).toBe(field.propertyName);
// Sort on the same field again.
expect(scope.sortOn(field));
expect(scope.reverse).toBe(true);
expect(scope.sortKey).toBe(field.propertyName);
// Sort on a different field.
field = {propertyName: 'some-prop-2'};
expect(scope.sortOn(field));
expect(scope.reverse).toBe(false);
expect(scope.sortKey).toBe(field.propertyName);
});
});
<file_sep>/collectbook/test/unit/routes-spec.js
'use strict';
/*global angular: false, beforeEach: false, describe: false, expect: false,
inject: false, it: false */
describe('ui-router', function () {
beforeEach(module('CollectBook'));
it('should have home route', inject(function ($rootScope, $state) {
var config = $state.get('home');
expect(config.name).toBe('home');
expect(config.url).toBe('/');
expect(config.views).toBeDefined();
expect(config.views.nav).toBeDefined();
}));
it('should have editBook route', inject(function ($rootScope, $state) {
var config = $state.get('editBook');
expect(config.name).toBe('editBook');
expect(config.url).toBe('/edit/:bookId');
var views = config.views;
expect(views).toBeDefined();
expect(views.nav).toBeDefined();
var content = views.content;
expect(content).toBeDefined();
expect(content.templateUrl).toBe('features/edit-book/edit-book.html');
expect(content.controller).toBe('EditBookCtrl');
var resolve = content.resolve;
expect(resolve).toBeDefined();
expect(resolve.book).toBeDefined();
}));
it('should have newBook route', inject(function ($rootScope, $state) {
var config = $state.get('newBook');
expect(config.name).toBe('newBook');
expect(config.url).toBe('/new');
var views = config.views;
expect(views).toBeDefined();
expect(views.nav).toBeDefined();
var content = views.content;
expect(content).toBeDefined();
expect(content.templateUrl).toBe('features/new-book/new-book.html');
expect(content.controller).toBe('NewBookCtrl');
}));
it('should have viewBook route', inject(function ($rootScope, $state) {
var config = $state.get('viewBook');
expect(config.name).toBe('viewBook');
expect(config.url).toBe('/view/:bookId');
var views = config.views;
expect(views).toBeDefined();
expect(views.nav).toBeDefined();
var content = views.content;
expect(content).toBeDefined();
expect(content.templateUrl).toBe('features/view-book/view-book.html');
expect(content.controller).toBe('ViewBookCtrl');
var resolve = content.resolve;
expect(resolve).toBeDefined();
expect(resolve.book).toBeDefined();
expect(resolve.items).toBeDefined();
}));
});
<file_sep>/collectbook/server.js
'use strict';
/*jshint esnext: true */
/*global Promise: false */
/**
* This is an HTTP server built in the Node.js Express module.
* It manages books and items in books.
* Each book is represented by a directory under the "data" directory
* and a JSON file inside that directory.
* Each item within a book is represented by a JSON file
* inside the directory of its book.
*/
// ES6 imports
import Book from './features/models/book.js';
import Field from './features/models/field.js';
// fs-promise wraps a subset of the functions in the Node.js fs module
// so they use ES6 promises.
import {exists, isDirectory, mkdir, readDir, readObject, rm, rmdir, writeObject}
from './features/share/fs-promise.js';
var express = require('express');
var path = require('path');
// __dirname refers to the build directory
// Get the path from which static files will be served.
var topPath = path.resolve(__dirname + '/..');
// Get the path from which data files that
// describe books and items will be read.
var dataPath = topPath + '/data/';
// Create and configure the Express app server.
var app = express();
// Automatically convert JSON request bodies to JavaScript objects.
app.use(express.bodyParser());
// Use request routing that will be configured later
// for requests that do not match static files.
// This is essential for implementing REST services.
app.use(app.router);
// Serve static files from a specified directory.
app.use(express.static(topPath));
// Initiates asynchronously deleting a book and
// returns a promise that is resolved when the operation completes.
function deleteBook(id) {
return rmdir(dataPath + id);
}
// Initiates asynchronously deleting an item within a given book and
// returns a promise that is resolved when the operation completes.
function deleteItem(bookId, itemId) {
var itemPath = getBookPath(bookId) + '/' + itemId + '.json';
return rm(itemPath);
}
// Initiates asynchronously getting a given book and
// returns a promise that is resolved when the operation completes.
function getBook(bookId) {
return new Promise((resolve, reject) => {
var dirPath = dataPath + bookId;
isDirectory(dirPath).then(
bool => {
if (!bool) return reject(dirPath + ' is not a directory');
readObject(dirPath + '/book.json').then(resolve, reject);
},
reject);
});
}
// Gets the file path for the JSON file that represents a given book.
function getBookPath(bookId) {
return dataPath + bookId;
}
// Initiates asynchronously getting an array containing
// an object for every book that holds only its id and name and
// returns a promise that is resolved when the operation completes.
function getBooks() {
// TODO: Is there a simpler way to write this?
return new Promise((resolve, reject) => {
readDir(dataPath).then(
filenames => {
var promises = filenames.map(filename => getBook(filename));
Promise.all(promises).then(
// Parens are needed around the object literal
// so the parser doesn't think that's a block.
books => resolve(books.map(
book => {
return {
id: book.id,
displayName: book.displayName //.toUpperCase()
};
})),
reject);
},
reject);
});
}
// Initiates asynchronously getting an item in a book and
// returns a promise that is resolved when the operation completes.
function getItem(bookId, fileName) {
var itemPath = getBookPath(bookId) + '/' + fileName;
return readObject(itemPath);
}
// Gets the file path for the JSON file that represents a given item.
function getItemPath(bookId, itemId) {
return getBookPath(bookId) + '/item/' + itemId + '.json';
}
// Initiates asynchronously getting every item in a given book and
// returns a promise that is resolved when the operation completes.
function getItems(bookId) {
return new Promise((resolve, reject) => {
readDir(getBookPath(bookId)).then(
filenames => {
filenames = filenames.filter(fn => fn !== 'book.json');
var promises = filenames.map(filename => getItem(bookId, filename));
Promise.all(promises).then(
results => {
var items = {};
results.forEach(item => items[item.id] = item);
resolve(items);
},
reject);
},
reject);
});
}
// Initiates asynchronously saving a book and
// returns a promise that is resolved when the operation completes.
function saveBook(book) {
var bookPath = getBookPath(book.id);
return mkdir(bookPath).then(
() => writeObject(book, bookPath + '/book.json')
);
}
// Initiates asynchronously saving an item within a book and
// returns a promise that is resolved when the operation completes.
function saveItem(bookId, item) {
var itemPath = getBookPath(bookId) + '/' + item.id + '.json';
return writeObject(item, itemPath);
}
// HTTP route to delete a book.
app['delete']('/collectbook/book/:bookId', (req, res) => {
var bookId = req.params.bookId;
deleteBook(bookId).then(
() => res.send(null, 200),
err => res.send(err, 500));
});
// HTTP route to delete an item.
app['delete']('/collectbook/book/:bookId/item/:itemId', (req, res) => {
var bookId = req.params.bookId;
var itemId = req.params.itemId;
deleteItem(bookId, itemId).then(
() => res.send(null, 200),
err => res.send(err, 500));
});
// HTTP route to retrieve all books as a JSON array where
// the values are objects with id and name properties.
app.get('/collectbook/book', (req, res) => {
getBooks().then(
books => res.send(books, 200),
err => res.send(err, 500));
});
// HTTP route to retrieve a specific Book object.
app.get('/collectbook/book/:bookId', (req, res) => {
var bookId = req.params.bookId;
getBook(bookId).then(
book => res.send(book, 200),
err => res.send(err, 500)
);
});
// HTTP route to retrieve all items in a given book as a JSON object where
// keys are ids and values are Item objects.
app.get('/collectbook/book/:bookId/item', (req, res) => {
var bookId = req.params.bookId;
// TODO: Verify that the book exists and return 404 if not.
getItems(bookId).then(
items => res.send(items, 200),
err => res.send(err, 500)
);
});
// HTTP route to update a book.
app.put('/collectbook/book/:bookId', (req, res) => {
var bookId = req.params.bookId;
// TODO: Verify that the book exists and return 404 if not.
var book = req.body;
if (book) saveBook(book);
res.send(null, book ? 200 : 404);
});
// HTTP route to update an item.
app.put('/collectbook/book/:bookId/item/:itemId', (req, res) => {
var bookId = req.params.bookId;
// TODO: Verify that the book exists and return 404 if not.
var itemId = req.params.itemId;
// TODO: Verify that the item exists and return 404 if not.
var item = req.item;
if (item) saveItem(bookId, item);
res.send(null, item ? 200 : 404);
});
// HTTP route to create a book and returns its URL.
app.post('/collectbook/book', (req, res) => {
var book = req.body;
saveBook(book);
res.send('/collectbook/book/' + book.id, 200);
});
// HTTP route to create an item and returns its URL.
app.post('/collectbook/book/:bookId/item', (req, res) => {
var bookId = req.params.bookId;
// TODO: Verify that the book exists and return 404 if not.
var item = req.body;
saveItem(bookId, item);
res.send(getItemPath(bookId, item.id), 200);
});
// HTTP route to retrieve all books as a JSON array where
// the values are objects with id and name properties.
app.get('/shutdown', (req, res) => {
res.send(null, 204);
server.close(() => process.exit());
// The server won't actually shutdown until all connections are destroyed.
sockets.forEach(socket => socket.destroy());
});
// Start the server listening on a given port
// and let the user know the port.
// Browse localhost:3000.
var PORT = 3000;
var server = app.listen(PORT, function () {
console.log('listening on port', PORT);
});
// Keep track of all connections so they can be destroyed
// if a request to shutdown this server is received.
var sockets = [];
server.on('connection', socket => sockets.push(socket));
<file_sep>/collectbook/test/e2e/new-book-spec.js
'use strict';
/*global beforeEach: false, browser: false, by: false, describe: false,
element: false, expect: false, it: false, protractor: false,
xdescribe: false */
var share = require('./share');
describe('new-book', function () {
beforeEach(share.before);
it('should create new book', function () {
share.createTestBook();
// Verify that a nav button was added for it.
var nav = element(by.id('nav'));
var btn = element(by.buttonText(share.btnText));
expect(btn.isPresent()).toBe(true);
share.deleteTestBook();
// Verify that the nav button is no longer present.
btn = element(by.buttonText(share.btnText));
expect(btn.isPresent()).toBe(false);
}, 3000); // three second timeout
});
<file_sep>/collectbook/features/share/fs-promise.js
'use strict';
/*jshint esnext: true */
/*global Promise: false */
/**
* This module wraps Node.js fs functions
* in new functions that return ES6 promises.
*/
var fs = require('fs');
var mkdirp = require('mkdirp');
var rimraf = require('rimraf');
/**
* Determines if a given path refers to an existing file or directory.
*/
export function exists(path) {
return new Promise(resolve => {
fs.exists(path, exists => resolve(exists));
});
}
/**
* Determines if a given path refers to a directory.
*/
export function isDirectory(path) {
return new Promise((resolve, reject) => {
fs.stat(path, (err, stat) => {
if (err) return reject(err);
resolve(stat.isDirectory());
});
});
}
/**
* Creates a directory.
*/
export function mkdir(path) {
return new Promise((resolve, reject) => {
mkdirp(path, err => {
if (err) return reject(err);
resolve();
});
});
}
/**
* Reads the content of a given directory.
*/
export function readDir(path) {
return new Promise((resolve, reject) => {
fs.readdir(path, (err, filenames) => {
if (err) {
if (err.code === 'ENOENT') {
resolve([]); // directory not found, so no contents
} else {
reject(err);
}
} else {
resolve(filenames);
}
});
});
}
/**
* Reads a text file and returns the content.
*/
export function readFile(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, {encoding: 'utf8'}, (err, content) => {
if (err) return reject(err);
resolve(content);
});
});
}
/**
* Reads a JSON file and returns a JavaScript value.
*/
export function readObject(filePath) {
return new Promise((resolve, reject) => {
readFile(filePath).then(
content => {
try {
resolve(JSON.parse(content));
} catch (e) {
reject(e);
}
},
reject);
});
}
/**
* Deletes a file.
*/
export function rm(filePath) {
return new Promise((resolve, reject) => {
fs.unlink(filePath, err => {
if (err) return reject(err);
resolve();
});
});
}
/**
* Deletes a directory, doing the equivalent of "rm -rf".
*/
export function rmdir(dirPath) {
return new Promise((resolve, reject) => {
rimraf(dirPath, err => {
if (err) return reject(err);
resolve();
});
});
}
/**
* Writes text to a file.
*/
export function writeFile(content, filePath) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, content, err => {
if (err) return reject(err);
resolve();
});
});
}
/**
* Writes a JavaScript value to a file.
*/
export function writeObject(obj, filePath) {
var text = JSON.stringify(obj, null, 2) + '\n'; // making it easier to debug
return writeFile(text, filePath);
}
<file_sep>/collectbook/features/models/field.js
'use strict';
/*jshint esnext: true */
import {camelCase} from '../share/string-util.js';
class Field {
constructor() {
var displayName;
Object.defineProperty(this, 'displayName', {
get: () => displayName,
set: value => {
displayName = value;
if (displayName) this.propertyName = camelCase(displayName);
},
enumerable: true
});
}
}
export default Field;
<file_sep>/collectbook/app.js
'use strict';
/*jshint esnext: true */
/*global $: false, angular: false */
// This is the starting JavaScript file for this web application.
// Create the main AngularJS module,
// specifying the modules on which it depends.
// This line must precede import of modules that use it.
var app = angular.module('CollectBook',
['cb-directives', 'cb-filters', 'ui.router']);
// These are ES6 imports of other JavaScript source files.
import './features/directives/main.js';
import './features/edit-book/edit-book.js';
import './features/filters/main.js';
import './features/nav/nav.js';
import './features/new-book/new-book.js';
import './features/view-book/view-book.js';
// This is the prefix for all REST URLs used by this app.
var URL_PREFIX = 'http://localhost:3000/collectbook/';
// Configure the initial ui-router state.
app.config(($stateProvider, $urlRouterProvider) => {
$urlRouterProvider.otherwise('/'); // default route URL
// Other states are defined in other source files.
$stateProvider.
state('home', {
url: '/',
views: {
nav: app.navConfig
// The home view doesn't display anything in the content area.
}
});
});
// Get the prefix for REST URLs related to books.
function getBookUrl(bookId) {
return URL_PREFIX + 'book/' + bookId;
}
// Get the prefix for REST URLs related to items in a book.
function getItemUrl(bookId, itemId) {
return URL_PREFIX + 'book/' + bookId + '/item/' + itemId;
}
// Display any uncaught exceptions in a modal dialog.
// Perhaps $injector must be used here instead of injecting cbDialogSvc
// to get around a timing issue with when cbDialogSvc is defined.
app.factory('$exceptionHandler', $injector => (exception, cause) => {
var cbDialogSvc = $injector.get('cbDialogSvc');
cbDialogSvc.showError('JavaScript Error', exception.message);
throw exception;
});
// Provide a service function that can be used anywhere in this app
// to display error messages from rejected promises in a modal dialog.
// This is used for REST calls.
app.factory('cbHandleErr', cbDialogSvc =>
err => cbDialogSvc.showError('Server Error', err.data)
);
// Provide service methods that perform CRUD operations
// on books and items in books.
app.factory('collectBookSvc', $http => {
var svc = {};
svc.addBook = book => $http.post(URL_PREFIX + 'book', book);
svc.addItem = (bookId, item) =>
$http.post(getBookUrl(bookId) + '/item', item);
svc.deleteBook = bookId => $http.delete(getBookUrl(bookId));
svc.deleteItem = (bookId, itemId) => $http.delete(getItemUrl(bookId, itemId));
svc.getBook = bookId => $http.get(getBookUrl(bookId));
svc.getBooks = () => $http.get(URL_PREFIX + 'book');
svc.getItems = bookId => $http.get(getBookUrl(bookId) + '/item');
svc.updateBook = book => $http.put(getBookUrl(book.id), book);
return svc;
});
// When an error occurs from an attempted ui-router state change,
// display it in a modal dialog.
app.controller('MainCtrl', ($scope, cbDialogSvc) => {
$scope.version = angular.version;
$scope.$root.$on('$stateChangeError',
(event, toState, toParams, fromState, fromParams, error) => {
cbDialogSvc.showError(
'Error changing state from "' + fromState.name +
'" to "' + toState.name + '"',
error.data);
});
});
<file_sep>/collectbook/Gruntfile.js
'use strict';
/*jshint esnext: true */
var http = require('http');
module.exports = function (grunt) {
grunt.initConfig({
clean: ['build'],
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: ['Gruntfile.js', '*.js', 'features/**/*.js']
},
csslint: {
strict: {
options: {
'box-model': false, // allows setting width/height with box properties
ids: false, // allows ids to be used in CSS selectors
'overqualified-elements': false // allows element name with class
},
src: ['build/styles/*.css']
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
less: {
all: {
files: [{
expand: true,
cwd: 'styles',
src: ['*.less'],
dest: 'build/styles',
ext: '.css'
}]
}
},
protractor: {
options: {
configFile: 'protractor.conf.js',
keepAlive: true,
noColor: false
},
all: {
}
},
touch: { // used to force livereload after server restart
/*
options: {
force: true,
mtime: true
},
*/
src: ['index.html'],
},
traceur: {
options: {
includeRuntime: true, // includes runtime code in generated file
traceurOptions: '--experimental --source-maps=file'
},
server: {
files: {
// Just need to transpile main file which imports others.
'build/server.js': ['server.js']
}
},
webapp: {
files: {
// Just need to transpile main file which imports others.
'build/app.js': ['app.js']
}
}
},
watch: {
app: {
options: { livereload: true },
files: ['build/app.js']
},
css: {
options: { livereload: true },
files: ['build/styles/*.css'],
// TODO: Why does livereload only work if "touch" is used?
tasks: ['csslint', 'touch']
},
less: {
files: ['styles/*.less'],
tasks: ['less']
},
html: {
options: { livereload: true },
files: ['index.html', 'features/**/*.html'],
tasks: []
},
js: {
files: ['Gruntfile.js', 'app.js', 'features/**/*.js'],
tasks: ['jshint', 'traceur:webapp']
},
server: {
files: ['server.js'],
tasks: ['jshint', 'traceur:server', 'restart', 'touch']
}
}
});
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.registerTask('restart', function () {
var done = this.async(); // This is an asynchronous Grunt task.
var req = http.get('http://localhost:3000/shutdown', function (res) {
// Give server time to shutdown.
setTimeout(function () {
grunt.task.run('server');
done();
}, 1000);
});
req.end();
});
grunt.registerTask('server', function () {
var options = {
cmd: 'node',
args: ['build/server.js'],
opts: {stdio: 'inherit'}
};
// Must give this a callback, but it doesn't need to do anything.
grunt.util.spawn(options, function () {});
});
grunt.registerTask('default',
['jshint', 'less', 'traceur', 'server', 'watch']);
};
<file_sep>/collectbook/features/nav/nav.js
'use strict';
/*jshint esnext: true */
/*global $: false, angular: false */
var app = angular.module('CollectBook');
app.navConfig = {
templateUrl: 'features/nav/nav.html',
controller: 'NavCtrl',
resolve: {
books: collectBookSvc => collectBookSvc.getBooks()
}
};
// Shim for Array findIndex method.
// Can't use arrow function because that
// doesn't give correct value for "this".
Array.prototype.findIndex = function (fn) {
for (var index = 0; index < this.length; index++) {
if (fn(this[index])) return index;
}
return -1;
};
app.controller('NavCtrl', ($scope, $state, books, collectBookSvc) => {
$scope.$parent.books = books.data;
$scope.deleteBook = (bookId, bookName) => {
var proceed = confirm(
'Are you sure you want to delete the book "' +
bookName + '" and all its data?');
if (proceed) {
collectBookSvc.deleteBook(bookId).then(
() => {
var books = $scope.$parent.books;
var index = books.findIndex(book => book.id === bookId);
books.splice(index, 1);
},
app.handleError);
}
};
// JSHint doesn't yet understand ES6 enhanced object literals.
$scope.editBook = bookId => $state.go('editBook', {bookId: bookId});
$scope.viewBook = bookId => $state.go('viewBook', {bookId: bookId});
});
<file_sep>/collectbook/features/directives/keys.js
/*global angular: false */
var mod = angular.module('cb-directives');
// Checks for lowercase and uppercase letters.
function isLetter(code) {
return code >= 65 && code <= 90;
}
// Checks for delete, tab, and arrow keys.
function isNavigation(event) {
var code = event.keyCode;
return !event.shiftKey &&
(code === 8 || code === 9 ||
(code >= 37 && code <= 40));
}
// Checks for 0 to 9 keys.
function isDigit(event) {
var code = event.keyCode;
return !event.shiftKey &&
((code >= 48 && code <= 57) ||
(code >= 96 && code <= 105)); // keypad
}
// Checks for characters allowed in JavaScript names.
function isIdentifier(event) {
var code = event.keyCode;
return code === 32 || // space
isLetter(code) ||
isDigit(event) ||
(code === 189 && event.shiftKey); // underscore
}
/**
* Restricts keys that can be pressed when an input has focus
* to digit and navigation keys.
* Example usage: <input type="number" cb-digits-only>
*/
mod.directive('cbDigitsOnly', () => ({
link: function (scope, element) {
element.on('keydown', function (event) {
var valid = isDigit(event) || isNavigation(event);
// In old versions of IE, event objects
// do not have the preventDefault method.
if (!valid && event.preventDefault) event.preventDefault();
return valid; // for IE8 and earlier
});
}
}));
/**
* Restricts keys that can be pressed when an input has focus
* to characters that are allowed in JavaScript identifiers,
* spaces, underscores, and navigation keys.
* Example usage: <input type="text" cb-identifier>
*/
mod.directive('cbIdentifier', () => ({
link: function (scope, element) {
element.on('keydown', function (event) {
var valid = isIdentifier(event) || isNavigation(event);
// In old versions of IE, event objects
// do not have the preventDefault method.
if (!valid && event.preventDefault) event.preventDefault();
return valid; // for IE8 and earlier
});
}
}));
<file_sep>/collectbook/test/unit/objToArr-filter-spec.js
'use strict';
/*global angular: false, beforeEach: false, describe: false, expect: false,
inject: false, it: false */
describe('objToArr filter', function () {
beforeEach(module('CollectBook'));
it('should create array from object', inject(function (objToArrFilter) {
var obj = {
foo: true,
bar: 3,
baz: 'text',
qux: ['a', 'b', 'c'],
sub: {alpha: 1, beta: 2}
};
var arr = objToArrFilter(obj);
var expected = [true, 3, 'text', ['a', 'b', 'c'], {alpha: 1, beta: 2}];
expect(arr).toEqual(expected);
}));
});
<file_sep>/collectbook/features/directives/color-picker.js
'use strict';
/*jshint esnext: true */
/*global angular: false, tinycolor: false */
var mod = angular.module('cb-directives');
/**
* Example usage:
* <div cb-color-picker color="scope-property"></div>
*/
mod.directive('cbColorPicker', () => ({
restrict: 'AE',
templateUrl: 'features/directives/color-picker.html',
replace: true,
scope: {
color: '='
},
//link: scope => { // TODO: Why doesn't using an arrow function work here?
link: function (scope) {
var dialog; // can't set now because template may not be loaded yet
// fontColor is being set in a watch to allow the color property
// to be modified from outside this directive.
scope.$watch('color', () => {
// Set fontColor to be the most readable color on top
// of the selected color between black and white.
// This uses a library at https://github.com/bgrins/TinyColor.
scope.fontColor = '#' +
tinycolor.mostReadable(scope.color, ['black', 'white']).toHex();
});
// These are the colors that will appear in the dialog,
// in the order in which they will appear.
scope.colors = [
['red', 'orange', 'yellow', 'green'],
['blue', 'purple', 'cyan', 'magenta'],
['pink', 'lightGreen', 'lightBlue', 'mediumPurple'],
['brown', 'white', 'gray', 'black']
];
// This is called when a color table cell is clicked.
scope.pick = color => {
scope.color = color;
dialog.modal('hide');
};
// This is called the color picker button is pressed.
// It shows the color picker dialog.
scope.show = () => {
if (!dialog) dialog = mod.byId('cbColorPickerDialog');
dialog.modal('show');
};
}
}));
<file_sep>/collectbook/features/share/string-util.js
'use strict';
/*jshint esnext: true */
// One or more spaces followed by a valid identifier character.
var camelRe = /[ ]+[a-zA-Z0-9-]/g;
/**
* Returns the camel-cased version of a given string.
*/
export function camelCase(str) {
return str.charAt(0).toLowerCase() +
str.substring(1).replace(camelRe, arg => arg.trim().toUpperCase());
}
<file_sep>/collectbook/features/edit-book/edit-book.js
'use strict';
/*jshint esnext: true */
/*global $: false, angular: false */
var app = angular.module('CollectBook');
import Field from '../models/field.js';
app.config(($stateProvider) => {
$stateProvider.
state('editBook', {
url: '/edit/:bookId',
views: {
nav: app.navConfig,
content: {
templateUrl: 'features/edit-book/edit-book.html',
controller: 'EditBookCtrl',
resolve: {
book: (collectBookSvc, $stateParams) => {
var bookId = $stateParams.bookId;
return collectBookSvc.getBook(bookId);
}
}
}
}
});
});
function getPlaceholder(type) {
return type === 'date' ? 'mm/dd/yyyy' :
type === 'email' ? '<EMAIL>' :
type === 'float' ? '3.14' :
type === 'integer' ? '42' :
type === 'price' ? '1.25' :
type === 'time' ? 'hh:mm' :
type === 'url' ? 'http://domain.tld/path' :
'';
}
app.controller('EditBookCtrl',
($scope, $stateParams, book, cbHandleErr, collectBookSvc) => {
$scope.book = book.data;
$scope.$watch('field.type', type => {
$scope.field.placeholder = getPlaceholder(type);
});
function resetInput() {
$scope.field = new Field();
$scope.field.type = 'text'; // default selected option
$('#name').focus(); // TODO: Do with native DOM?
}
resetInput();
function updateBook() {
collectBookSvc.updateBook($scope.book).then(
() => {},
cbHandleErr);
}
$scope.addField = () => {
$scope.book.fields.push($scope.field);
updateBook();
resetInput();
};
$scope.deleteField = (field) => {
var name = field.displayName;
$scope.book.fields = $scope.book.fields.filter(field => {
return field.displayName !== name;
});
updateBook();
};
});
<file_sep>/collectbook/test/unit/cbDialogSvc-spec.js
'use strict';
/*global angular: false, beforeEach: false, describe: false, expect: false,
inject: false, it: false */
describe('cbDialogSvc service', function () {
beforeEach(module('cb-directives'));
it('should set $rootScope properties',
inject(function ($rootScope, cbDialogSvc) {
var title = 'some title';
var msg = 'some message';
cbDialogSvc.showMessage(title, msg);
expect($rootScope.title).toBe(title);
expect($rootScope.message).toBe(msg);
}));
});
<file_sep>/collectbook/test/e2e/view-book-spec.js
'use strict';
/*global beforeEach: false, browser: false, by: false, describe: false,
element: false, expect: false, it: false, protractor: false, xit: false */
var share = require('./share');
describe('view-book', function () {
beforeEach(share.before);
it('should view book', function () {
share.createTestBook();
share.editTestBook();
// Switch to the "view" view for the new book.
var btn = element(by.buttonText(share.btnText));
btn.click();
// Expand to add items.
element(by.id('expand-form')).click();
// Enter a value in the first field.
var value = '<EMAIL>';
var field = element(by.className('form-control'));
field.clear();
field.sendKeys(value);
// Click "Update" button.
element(by.buttonText('Update')).click();
// Verify that the new item appears in the table.
var table = element(by.tagName('table'));
var trs = table.findElements(by.tagName('tr'));
trs.then(function (rows) {
// header row, filter row, and row for new field
expect(rows.length).toBe(3);
var tr = rows[2];
var tds = tr.findElements(by.tagName('td'));
tds.then(function (columns) {
expect(columns[0].getText()).toBe(value);
// Delete the item.
columns[1].click();
// Verify that the field was removed from the table.
trs = table.findElements(by.tagName('tr'));
trs.then(function (rows) {
expect(rows.length).toBe(2); // only header and filter rows
});
share.deleteTestBook();
});
});
}, 5000); // five second timeout
});
| c882f8aa550d3f9fbccadd0f59c077adad43c4c4 | [
"JavaScript",
"Text",
"Markdown"
]
| 25 | Text | mvolkmann/angularjs-labs | 5fb9ee4e0cfd7206b71da6dc06727c7ef7aad9c4 | da8b122014a39610def27fba1550385e75b65521 |
refs/heads/main | <file_sep># Assigment-4
Qalyn Calculator
<file_sep>const firstName = document.getElementById("firstname");
const startingBid = document.getElementById("startingbid");
const education = document.getElementById("education");
const networth = document.getElementById("networth");
const skills = document.getElementsByClassName("skills");
const age = document.getElementsByName("age");
const button = document.getElementById("submit");
const love_letter = document.getElementById("love_letter");
const calculate = () => {
let name = firstName.value;
let price = Number(startingBid.value);
let letter = love_letter.value;
if (name != "") {
price = getNewPrice(price, education);
if (name != "") {
price = getNewPrice(price, networth);}
let person = {
fullName: name,
finalPrice: price,
loveLetter: letter
}
document.getElementById("result").innerHTML = `The price for ${person.fullName} is ${person.finalPrice}. Your love letter is ${person.loveLetter}`;
}
else {
alert("Name and starting bid cannot be empty");
}
}
const getNewPrice = (price, criteria) => {
return price * Number(criteria.value);
}
document.getElementsByClassName("skills");
const getCheckboxValuesForLoop = (html_collection, price) => {
for (let i=0; i < html_collection.length; i++) {
if (html_collection[i].checked && Number.isInteger(Number(html_collection[i].value))) {
price = price + Number(html_collection[i].value)
}
else if (html_collection[i].checked && !Number.isInteger(html_collection[i].value)) {
price = price * Number(html_collection[i].value)
}
}
return price;
}
var xxx = document.getElementsByClassName("skills");
const getCheckboxValuesFilterReduce = (html_collection, price) => {
let list = Array.from(html_collection).filter(filteration)
let result = list.reduce(reducer, price)
return result;
}
const reducer = (price, xxx) => {
return xxx + Number(startingBid.value);
}
const filteration = (xxx) => {
return xxx.checked;
}
var score = document.getElementsByName("age");
const getRadioValue = (node_list, price) => {
node_list.forEach(score => {
if (score.checked) {
price = price * Number(score.value)
}
})
return price;
}
button.addEventListener("click", calculate)
| 66a4d6ce1f1d20155ed76caa6c29ce7af2d6b851 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | Tamirlan901/Assigment-4 | 8d98e19fca3197e78b306c4908c012207321a3c7 | ff8a025e5e7ab3fc12f46b886bdf9fe2a800e647 |
refs/heads/master | <file_sep>var express = require('express');
var router = express.Router();
var pool = require('../modules/pool.js');
//server connection to display tasks
router.get('/', function (req, res) {
pool.connect(function (errorConnectingToDatabase, client, done) {
if (errorConnectingToDatabase) {
console.log('Error connecting to database', errorConnectingToDatabase);
res.sendStatus(500);
} else {
client.query('Select * FROM todo ORDER by complete ASC;', function (errorMakingQuery, result) {
done();//putting the connection back in the pool
if (errorMakingQuery) {
console.log('there was an error Making the query(syntax error most likly):', errorMakingQuery);
res.sendStatus(500);
} else {
res.send(result.rows);
}//end of succesful connection else
})//end of client.query
}//end of 1st child else statement
})//end of pool.connect
})//end of router.get
//server connection to post a new task
router.post('/', function (req, res) {
pool.connect(function (errorConnectingToDatabase, client, done) {
if (errorConnectingToDatabase) {
console.log('Error connecting to database', errorConnectingToDatabase);
res.sendStatus(500);
} else {
client.query('INSERT INTO todo (task, complete) VALUES ($1, $2)',[req.body.task, req.body.complete ],
function (errorMakingQuery, result) {
done();//putting the connection back in the pool
if (errorMakingQuery) {
console.log('there was an error Making the query(syntax error most likly):', errorMakingQuery);
res.sendStatus(500);
} else {
res.send(result.rows);
}//end of succesful connection else
})//end of client.query
}//end of 1st child else statement
})//end of pool.connect
})//end of router.post
router.delete('/:id', function (req, res) {
var inputId = req.params.id;
console.log(inputId);
pool.connect(function (errorConnectingToDatabase, client, done) {
if (errorConnectingToDatabase) {
console.log('Error connecting to database', errorConnectingToDatabase);
res.sendStatus(500);
} else {
client.query("DELETE from todo where id = $1;",
[inputId],
function (errorMakingQuery, result) {
done();//putting the connection back in the pool
if (errorMakingQuery) {
console.log('there was an error Making the query(syntax error most likly):', errorMakingQuery);
res.sendStatus(500);
} else {
res.sendStatus(201);
}//end of succesful connection else
})//end of client.query
}//end of 1st child else statement
})//end of pool.connect
})//end of router.delete
router.put('/:id', function (req, res) {
var inputId = req.params.id;
console.log(req.body.done)
console.log('put was hit');
pool.connect(function (errorConnectingToDatabase, client, done) {
if (errorConnectingToDatabase) {
console.log('Error connecting to database', errorConnectingToDatabase);
res.sendStatus(500);
} else {
client.query("UPDATE todo SET complete='" + req.body.done + "' WHERE id = '" + inputId + "';",
function (errorMakingQuery, result) {
done();//putting the connection back in the pool
if (errorMakingQuery) {
console.log('there was an error Making the query(syntax error most likly):', errorMakingQuery);
res.sendStatus(500);
} else {
res.sendStatus(201);
}//end of succesful connection else
})//end of client.query
}//end of 1st child else statement
})//end of pool.connect
})//end of router.put
module.exports = router<file_sep>CREATE TABLE todo (
id serial primary key,
task VARCHAR(100),
complete Boolean
);
SELECT * FROM todo;
INSERT INTO todo (task, complete)
VALUES ('connect to database', 'false'),
('test pulling items from database(get)', 'false'),
('add items to database(post)','false'),
('remove items from database(delete)','false'),
('change class of items in database(put)', false);<file_sep>$(document).ready(function () {
getTasks()//calling the current tasks on document load.
//creates a new task on the button click
$('#createTask').on('click', function () {
console.log('button clicked, woot!!!');
var newTask = {
task: prompt("What is the plan?"),
complete: false
};
console.log(newTask.task);
$.ajax({
method: 'POST',
url: '/tasks',
data: newTask,
success: function (response) {
console.log('new task posted')
getTasks();
}//end of success
});//ajax
});//end of on click function
//marks a task as complete when complete? button is clicked
$('#toDo').on('click', '.complete', function () {
console.log('complete button was clicked, holla!!!');
var postId = $(this).parent().parent().data().id;
var itsDone = $(this).val();
console.log(itsDone);
console.log(postId);
if (itsDone === "true") {
itsDone = "false"
} else {
itsDone = "true"
};//end of if/else statement
//creating object for ajax send
var checkbox = {
done: itsDone
}
$.ajax({
method: 'PUT',
url: '/tasks/' + postId,
data: checkbox,
success: function (response) {
console.log('complete updated')
getTasks();
}//end of success
});//ajax
});//end of on click function
//removes a task completly when delete button is clicked
$('#toDo').on('click', '.delete', function () {
if (confirm("are you sure?")){
//console.log('delete button was clicked, woop woop!!!');
var deleteId = $(this).parent().parent().data().id;
console.log('deleteId =', deleteId);
$.ajax({
method: 'DELETE',
url: '/tasks/' + deleteId,
success: function (response) {
console.log(response)
console.log('task deleted');
getTasks();
}//end of success
});//ajax
}
});//end of on click function
});// end of document.ready
//function to retrieve tasks
function getTasks() {
emptyTasks();
$.ajax({
method: 'GET',
url: '/tasks',
success: function (response) {
console.log(response);
for (var i = 0; i < response.length; i++) {
var task = response[i];
$('#toDoItem').append('<tr data-id=' + task.id + ' class =' + task.complete + '>' +
'<td><button class="complete" value="' + task.complete + '">Done!</button></td>' +
'<td class="text">' + task.task + '</td>' +
'<td><button class="delete">Delete?</button>' +
'</td></tr>');
}//end of for loop
}//end of response
})//end of ajax
}//end of getTasks
//function to clear tasks.
function emptyTasks() {
$('#toDoItem').empty();
}//end of emptyTasks
| 87282d1997a39770ae0d2271b1ae71baa55ed275 | [
"JavaScript",
"SQL"
]
| 3 | JavaScript | AlexMJung/weekend-challenge-3 | 0e0130143be96c09a4ae38c1da9ba3de9c1bbcce | 9c17bbc6b5307028ea11df12054c58d26813e48a |
refs/heads/master | <repo_name>Mistive/OCR_Reader<file_sep>/featurematching.py
# match filter : https://nanamare.tistory.com/18
# matchTemplate 사용법 : https://webnautes.tistory.com/1004
#Feature Detection 알고리즘 설명 : https://laonple.blog.me/220906235537
#Featue Detection 함수 설명 : https://m.blog.naver.com/samsjang/220657746860
import numpy as np
import cv2 as cv
img1 = cv.imread('card_image/04261441301390_cardBox.png',cv.IMREAD_GRAYSCALE) # queryImage
img2 = cv.imread('alpabet/name.png',cv.IMREAD_GRAYSCALE) # trainImage
# Initiate SIFT detector
sift = cv.xfeatures2d.SIFT_create()
# find the keypoints and descriptors with SIFT
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
# BFMatcher with default params
bf = cv.BFMatcher()
matches = bf.knnMatch(des1,des2,k=2)
# Apply ratio test
good = []
for m,n in matches:
if m.distance < 0.75*n.distance:
good.append([m])
# cv.drawMatchesKnn expects list of lists as matches.
img3 = cv.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2)
cv.imshow("img3", img3)
cv.waitKey(0)
'''
import cv2
import numpy as np
import matplotlib.pyplot as plt
def getROI(source, sh, eh, sw, ew):
dest = source[sh:eh, sw, ew]
return dest
if __name__ == "__main__":
#image = cv2.imread('04261417320855_cardBox.png', cv2.IMREAD_COLOR)
img1 = cv2.imread('K.png', cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread('card.png', cv2.IMREAD_GRAYSCALE)
#img1 = cv2.resize(img1, None, fx=0.1, fy=0.1, interpolation=cv2.INTER_CUBIC)
#img2 = cv2.resize(img2, None, fx=0.7, fy=0.7, interpolation=cv2.INTER_CUBIC)
orb = cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1, None)
kp2, des2 = orb.detectAndCompute(img2, None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches = bf.match(des1, des2)
matches = sorted(matches, key=lambda x: x.distance)
img3 = cv2.drawMatches(img1, kp1, img2, kp2, matches[:10], None, flags=2)
#cv2.imshow("IMG1", img1)
#cv2.imshow("IMG2", img2)
cv2.imshow("Feature Matching", img3)
cv2.waitKey(0)
import numpy as np
import cv2
img1 =cv2.imread("card_image/04261441301390_cardBox.png",cv2.IMREAD_GRAYSCALE)
img2 =cv2.imread("alpabet/K.png",cv2.IMREAD_GRAYSCALE)
img1 = cv2.resize(img1, None, fx=0.1, fy=0.1, interpolation=cv2.INTER_CUBIC)
img2 = cv2.resize(img2, None, fx=0.7, fy=0.7, interpolation=cv2.INTER_CUBIC)
res = None
orb=cv2.ORB_create()
kp1, des1 = orb.detectAndCompute(img1,None)
kp2, des2 = orb.detectAndCompute(img2,None)
bf= cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
matches=bf.match(des1,des2)
matches = sorted(matches, key=lambda x:x.distance)
res=cv2.drawMatches(img1,kp1,img2,kp2,matches[:10],res,flags=0)
cv2.imshow("Feature Matching",res)
cv2.waitKey(0)
cv2.destroyAllWindows()
'''<file_sep>/matchTemplate.py
import cv2
import numpy as np
def getROI(source, sh, eh, sw, ew):
dest = source[sh:eh, sw, ew]
return dest
#match filter : https://nanamare.tistory.com/18
#matchTemplate 사용법 : https://webnautes.tistory.com/1004
if __name__ == "__main__":
#image = cv2.imread('04261417320855_cardBox.png', cv2.IMREAD_COLOR)
image = cv2.imread('card_image/04261441301390_cardBox.png', cv2.IMREAD_COLOR)
tmp = cv2.imread('alpabet/S2.png', cv2.IMREAD_COLOR)
h, w = tmp.shape[:2]
#h, w = 36, 25
result = cv2.matchTemplate(image, tmp, cv2.TM_CCORR)
cv2.imshow("result", result)
print(result)
#loc = np.where(result >= 0.9)
#for pt in zip(*loc[::-1]):
# cv2.rectangle(image, pt, (pt[0] +w, pt[1]+h), (255, 0, 0), 2)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
top_left = max_loc
#top_left = (91, 178)
bottom_right = (top_left[0] + w, top_left[1] + h)
cv2.rectangle(image,top_left,bottom_right,(0,0,255), 2)
cv2.imshow("image", image)
cv2.waitKey(0)
<file_sep>/ocrreader.py
import cv2
import os
from collections import namedtuple
Point = namedtuple("Point", ['x', 'y'])
Rect = namedtuple("Rectangle", ['p1', 'p2','cp', 'w', 'h','area'])
def getRectangle(cnt):
x, y, w, h = cv2.boundingRect(cnt)
cp = Point(x + int(w / 2), y + int(h / 2))
rect = Rect(Point(x, y), Point(x + w, y + h), cp, w, h, w * h)
return rect
if __name__ == "__main__":
img_color = cv2.imread('04261417320855_cardBox.png', cv2.IMREAD_COLOR)
img_Canny = cv2.Canny(img_color, 150, 200)
cv2.imshow('Canny1', img_Canny)
contours, hierachy = cv2.findContours(img_Canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_TC89_KCOS)
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
img_Morph = cv2.morphologyEx(img_Canny, cv2.MORPH_DILATE, kernel);
#cv2.imshow('Morph2', img_Morph)
img_Canny = cv2.Canny(img_Morph, 100, 200)
#cv2.imshow('Canny3', img_Canny)
img_Morph = cv2.morphologyEx(img_Canny, cv2.MORPH_DILATE, kernel);
#cv2.imshow('Morph4', img_Morph)
# img_Morph = cv2.morphologyEx(img_Morph, cv2.MORPH_CLOSE, kernel);
for cnt in contours:
area = cv2.contourArea(cnt)
x, y, w, h = cv2.boundingRect(cnt)
area = w * h
if area < 1000:
rect = getRectangle(cnt)
cv2.rectangle(img_color, rect.p1, rect.p2, (255,0,0), 2)
cv2.imshow('image', img_color)
cv2.waitKey(0)
<file_sep>/Note.md
## 개발 목적
* OCR 인식을 위한 딥러닝 회사의 아르바이트를 하는데 손목이 너무 아프다.
* 처음에는 마우스로 일일이 누르는게 귀찮아서 키보드를 이용해 마우스를 조정하여 좀 더 쉽게 노가다 하는 방법으로 하는데 그래도 손목이 너무 아프다
* 그래서 글자 영역을 인지해서 알아서 누를 수 있으면 쉽게 구현할 수 있지 않을까하는 마음에 짜본다.
## 어떻게 짤껀데?
* 일단 기존 이미지는 카드에 엠보싱이 적용된 형태이다.
1. 불러온다
2. 우리의 갓갓 Canny Edge
3. 모폴로지 연산을 이용하여 엣지를 좀 더 두텁게 만들어준다.
4. findContours 함수를 이용하여 각 윤곽선끼리 붙잡고
5. 문자로 추정되는 영역을 1차적으로 추출한다.
현재 가지고 있는 카드 이미지가 없어서 테스트를 해볼 수가 없는데 내일 알바 갔을 때 몰래 200장 정도 가져와야겠다.
단순히 Canny Edge 하면 엠보싱 처리된 이미지라 윤곽이 잘 잡힐 것 같지가 않다. Contrast Strech 기법 등을 이용해 영상 대비를 좀 더 늘려봐야겠다
## 2019.05.15
아르바이트를 쉽게 하기 위해 시작한 이 삽질... 단순히 Canny Edge를 해서 문제를 해결하기에는 한계가 너무 명확했다. 그래서 우리 갓갓 형님들이 짜놓으신 좋은 Matching 관련 알고리즘을 공부하고 예제를 실행해보려하는데...
Feature Matching 알고리즘인 SIFT 알고리즘이 저작권 문제(?)로 무료가 아니게 됬다는 충격적인 정보를 접하게 되었다... 그런데 opencv 홈페이지에는 왜 SIFT 예시가 나와있는건데???
하지만 갓갓 구글님께서는 모든 해결 방법이 있으시다....
**바로! 3.4.2.16 버전을 다운받는 것!!**
`pip install opencv-python==3.4.2.16`
`pip install opencv-contrib-python==3.4.2.16`
현재 **3.4.2.16 버전의 opencv**가 python2.7이랑 python3.7에서 동작하는 것을 확인했다. (후..... 개발환경 구성은 역시 삽질을 안할 수 없는건가...)
**matchTemplate() 함수를 이용한 matching 기법 -> 빛의 변화에 너무 약하다**
**Feature Matching 기법 -> 문자 특성상 특징이 너무 적어서 그런지 잘 매칭이 되는 것 같지 않다.**

## 참고문헌
[opencv 이미지 처리 관련 쩌는 블로그](https://m.blog.naver.com/samsjang/220657746860)
[opencv 공식 ](https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_matcher/py_matcher.html)
| 9e66c591f35ee9a472bd97375041635b4a5e0be3 | [
"Markdown",
"Python"
]
| 4 | Python | Mistive/OCR_Reader | 3c83851ada8c1bd7441997756e8b102dc41cea77 | 9951f00a534f0db96a155a73fd56e26955e2edab |
refs/heads/master | <repo_name>nextpay-ir/prestashop-1.7<file_sep>/nextpay/fa.php
<?php
/**
* Created by NextPay.ir
* author: Nextpay Company
* ID: @nextpay
* Date: 07/24/2017
* Time: 12:35 PM
* Website: NextPay.ir
* Email: <EMAIL>
* @copyright 2017
* @package NextPay_Gateway
* @version 1.0
*/
global $_MODULE;
$_MODULE = array();
$_MODULE['<{nextpay}default>nextpay_6f45efeb44e5d8cfe1e14ce4467f1f67'] = 'افزونه پرداخت نکست پی';
$_MODULE['<{nextpay}default>nextpay_909b1fcb6b37b6a330444235bfc2462c'] = ' پرداخت آنلاین با درگاه امن نکست پی ';
$_MODULE['<{nextpay}default>nextpay_69a1a3ad8dd5da6db3c4da838a0cf9c7'] = 'آیا برای پاک کردن اطلاعات مطمئن هستید؟';
$_MODULE['<{nextpay}default>nextpay_e2d93539acef2afbbadf8542351fb2b4'] = 'استفاده از ارز برای این ماژول غیر فعال هست.';
$_MODULE['<{nextpay}default>nextpay_6577035ab365dbb6b8f79829d4d29748'] = 'شما برای استفاده از درگاه امن نکست پی می بایست کلید مجوزدهی کد درگاه خود را در تنظیمات ماژول وارد کنید.';
$_MODULE['<{nextpay}default>nextpay_c888438d14855d7d96a2724ee9c306bd'] = 'تنظیمات دخیره شد.';
$_MODULE['<{nextpay}default>nextpay_b4740c9e4dd0751ea682fd81d627dee2'] = 'کلید مجوزدهی کد درگاه خود را وارد نمایید :';
$_MODULE['<{nextpay}default>nextpay_17857bb7e0e4a22fa99900af223a03f9'] = 'دخیره کن!';
$_MODULE['<{nextpay}default>nextpay_6585d9032a8dc4539e89237937549739'] = 'مشکلی وجود دارد!';
$_MODULE['<{nextpay}default>nextpay_2ea624d388b73c5ad7976bbb9d758a4f'] = 'در حال انتقال ...';
$_MODULE['<{nextpay}default>nextpay_payment_a9950f28d15992aed5045f5818cdb361'] = ' پرداخت آنلاین با درگاه امن نکست پی';
<file_sep>/nextpay/nextpay.php
<?php
/**
* Created by NextPay.ir
* author: <NAME>
* ID: @nextpay
* Date: 07/24/2017
* Time: 12:35 PM
* Website: NextPay.ir
* Email: <EMAIL>
* @copyright 2017
* @package NextPay_Gateway
* @version 1.0
*/
if (!defined('_PS_VERSION_'))
exit ;
class nextpay extends PaymentModule {
private $_html = '';
private $_postErrors = array();
public function __construct() {
$this->name = 'nextpay';
$this->tab = 'payments_gateways';
$this->version = '1.0';
$this->author = 'Nextpay Co.';
$this->currencies = true;
$this->currencies_mode = 'radio';
parent::__construct();
$this->displayName = $this->l('NextPay Payment Modlue');
$this->description = $this->l('Online Payment With NextPay');
$this->confirmUninstall = $this->l('Are you sure you want to delete your details?');
if (!sizeof(Currency::checkPaymentCurrencies($this->id)))
$this->warning = $this->l('No currency has been set for this module');
$config = Configuration::getMultiple(array('nextpay_API'));
if (!isset($config['nextpay_API']))
$this->warning = $this->l('You have to enter your nextpay merchant key to use nextpay for your online payments.');
}
public function install() {
if (!parent::install() || !Configuration::updateValue('nextpay_API', '') || !Configuration::updateValue('nextpay_LOGO', '') || !$this->registerHook('payment') || !$this->registerHook('paymentReturn'))
return false;
else
return true;
}
public function uninstall() {
if (!Configuration::deleteByName('nextpay_API') || !Configuration::deleteByName('nextpay_LOGO') || !parent::uninstall())
return false;
else
return true;
}
public function hash_key() {
$en = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$one = rand(1, 26);
$two = rand(1, 26);
$three = rand(1, 26);
return $hash = $en[$one] . rand(0, 9) . rand(0, 9) . $en[$two] . $en[$tree] . rand(0, 9) . rand(10, 99);
}
public function getContent() {
if (Tools::isSubmit('nextpay_setting')) {
Configuration::updateValue('nextpay_API', $_POST['nextpay_API']);
Configuration::updateValue('nextpay_LOGO', $_POST['zp_LOGO']);
$this->_html .= '<div class="conf confirm">' . $this->l('Settings updated') . '</div>';
}
$this->_generateForm();
return $this->_html;
}
private function _generateForm() {
$this->_html .= '<div align="center"><form action="' . $_SERVER['REQUEST_URI'] . '" method="post">';
$this->_html .= $this->l('Enter your API Key :') . '<br/><br/>';
$this->_html .= '<input type="text" name="nextpay_API" value="' . Configuration::get('nextpay_API') . '" ><br/><br/>';
$this->_html .= '<input type="submit" name="nextpay_setting"';
$this->_html .= 'value="' . $this->l('Save it!') . '" class="button" />';
$this->_html .= '</form><br/></div>';
}
public function do_payment($cart) {
error_reporting(E_ALL);
ini_set('display_errors', 1);
include_once("nextpay_payment.php");
$api_key = Configuration::get('nextpay_API');
$amount = floatval(number_format($cart ->getOrderTotal(true, 3), 2, '.', ''));
$callbackUrl = (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . __PS_BASE_URI__ . 'modules/nextpay/nextpay.php?do=call_back&id=' . $cart ->id . '&amount=' . $amount;
$order_id = $cart ->id;
$params = array(
'api_key' => $api_key,
'amount' => $amount,
'order_id' => $order_id,
'callback_uri' => $callbackUrl
);
$nxClass = new Nextpay_Payment($params);
$result = $nxClass->token();
$trans_id = $result->trans_id;
$code = intval($result->code);
if($code == -1){
echo $this->success($this->l('Redirecting...'));
$result = $nxClass->send($trans_id);
}
else{
echo $this->error($this->l('There is a problem.') . ' (' . $nxClass->code_error($code) . ')');
}
}
public function error($str) {
return '<div class="alert error">' . $str . '</div>';
}
public function success($str) {
echo '<div class="conf confirm">' . $str . '</div>';
}
public function hookPayment($params) {
global $smarty;
$smarty ->assign('nextpay_logo', Configuration::get('nextpay_LOGO'));
if ($this->active)
return $this->display(__FILE__, 'nextpay_payment.tpl');
}
public function hookPaymentReturn($params) {
if ($this->active)
return $this->display(__FILE__, 'nextpay_confirm.tpl');
}
}
// End of: nextpay.php
?>
<file_sep>/nextpay/nextpay_gateway.php
<?php
/**
* Created by NextPay.ir
* author: Nextpay Company
* ID: @nextpay
* Date: 07/24/2017
* Time: 12:35 PM
* Website: NextPay.ir
* Email: <EMAIL>
* @copyright 2017
* @package NextPay_Gateway
* @version 1.0
*/
@session_start();
if (isset($_GET['do'])) {
include (dirname(__FILE__) . '/../../config/config.inc.php');
include (dirname(__FILE__) . '/../../header.php');
include_once (dirname(__FILE__) . '/nextpay.php');
include_once (dirname(__FILE__) . '/nextpay_payment.php');
$nextpay = new nextpay;
if ($_GET['do'] == 'payment') {
$nextpay -> do_payment($cart);
} else {
if (isset($_GET['id']) && isset($_GET['amount']) && isset($_POST['trans_id']) && isset($_POST['order_id'])) {
$order_id = $_GET['id'];
$amount = $_GET['amount'];
$trans_id = $_POST['order_id'];
if (isset($_SESSION['order' . $orderId])) {
$api_key = Configuration::get('nextpay_API');
$params = array(
'api_key' => $api_key,
'amount' => $amount,
'order_id' => $order_id,
'trans_id' => $trans_id
);
$nxClass = new Nextpay_Payment();
$result = $nxClass->verify_request($params);
$code = intval($result);
if($code == 0){
$nextpay -> validateOrder($orderId, _PS_OS_PAYMENT_, $amount, $nextpay -> displayName, "سفارش تایید شده / کد رهگیری {$trans_id}", array(), $cookie -> id_currency);
$_SESSION['order' . $orderId] = '';
Tools::redirect('history.php');
}
else{
echo $nextpay -> error($nextpay -> l('There is a problem.') . ' (' . $result . ')<br/>' . $nxClass -> code_error($result) . ' : ' . $result);
$nxClass -> show_error($nxClass -> code_error($result));
}
} else {
echo $nextpay -> error($nextpay -> l('There is a problem.'));
}
} else {
echo $nextpay -> error($nextpay -> l('There is a problem.'));
}
}
include_once (dirname(__FILE__) . '/../../footer.php');
} else {
_403();
}
function _403() {
header('Status: 403 Forbidden');
header('HTTP/1.1 403 Forbidden');
exit();
}
<file_sep>/README.md
# prestashop-1.7
Nextpay Payment Gateway PrestaShop 1.7
<file_sep>/nextpay/index.php
<?php
/**
* Created by NextPay.ir
* author: Next<NAME>
* ID: @nextpay
* Date: 07/24/2017
* Time: 12:35 PM
* Website: NextPay.ir
* Email: <EMAIL>
* @copyright 2017
* @package NextPay_Gateway
* @version 1.0
*/
header('Status: 403 Forbidden');
header('HTTP/1.1 403 Forbidden');
exit();
?>
| 09b7cd34bbee0251658fa72e084133a36ac1f743 | [
"Markdown",
"PHP"
]
| 5 | PHP | nextpay-ir/prestashop-1.7 | fd9420cdb92b8e8c8ec80c90624b7f32d3437af6 | 0daac87dc709e3092e6ee5f908abff16a7c2fb1f |
refs/heads/master | <repo_name>Juyue/homework_fall2019<file_sep>/hw1/tmp_test.py
print('faslgdasogh')<file_sep>/hw1/cs285/scripts/run_many_experiments.py
import os
import time
from read_events_files import analyze_experiment_result
from run_hw1_behavior_cloning import BC_Trainer
print('hello')
def main(params):
##################################
### CREATE DIRECTORY FOR LOGGING
##################################
params['exp_name'] = 'l' + str(params['n_layers']) + 's' + str(params['size'])
logdir_prefix = 'bc_'
if params['do_dagger']:
logdir_prefix = 'dagger_'
assert params['n_iter'] > 1, ('DAGGER needs more than 1 iteration (n_iter>1) of training, to iteratively query the expert and train (after 1st warmstarting from behavior cloning).')
else:
params['n_iter'] ==1, ('Vanilla behavior cloning collects expert data just once (n_iter=1)')
## directory for logging
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../data')
if not (os.path.exists(data_path)):
os.makedirs(data_path)
logdir = logdir_prefix + params['exp_name'] + '_' + params['env_name'] + '_' + time.strftime("%d-%m-%Y_%H-%M-%S")
logdir = os.path.join(data_path, logdir)
params['logdir'] = logdir
if not(os.path.exists(logdir)):
os.makedirs(logdir)
trainer = BC_Trainer(params)
trainer.run_training_loop()
# analyze the result.
analyze_experiment_result(logdir)
# ROOT_PATH = "D:\\Documents\\JuyueFiles\\Learning\\DRL_Homework\\hw1\\"
ROOT_PATH = "/home/lc/jc/work/drl_cs285/hw/homework_fall2019/hw1/"
env_names = ['Ant-v2', 'Humanoid-v2', 'HalfCheetah-v2', 'Hopper-v2']
expert_policy_files = ['Ant.pkl', 'Humanoid.pkl', 'HalfCheetah.pkl', 'Hopper.pkl']
expert_data_files = ['Ant-v2', 'Humanoid-v2', 'HalfCheetah-v2', 'Hopper-v2']
do_daggers = [1, 0]
batch_size = 1000
ep_len = None
n_iter = 1000
# control the experiments you want to run.
for env_name, expert_policy_name, expert_data_name in zip(env_names[1:], expert_policy_files[1:], expert_data_files[1:]):
for do_dagger in do_daggers:
params = {}
params['expert_policy_file'] = os.path.join(ROOT_PATH, "cs285/policies/experts", expert_policy_name)
params['expert_data'] = os.path.join(ROOT_PATH, "cs285/expert_data/", 'expert_data_' + expert_data_name + '.pkl')
params['env_name'] = env_name
params['do_dagger'] = do_dagger
params['ep_len'] = ep_len
params['n_layers'] = 2
params['size'] = 64
params['num_agent_train_steps_per_iter'] = 1000
params['n_iter'] = n_iter
params['batch_size'] = batch_size
params['eval_batch_size'] = 200
params['train_batch_size'] = 100
params['learning_rate'] = 5e-3
params['video_log_freq'] = 1
params['scalar_log_freq'] = 1
params['use_gpu'] = 0
params['which_gpu'] = -1
params['max_replay_buffer_size'] = 1000000
params['seed'] = 1
main(params)
<file_sep>/hw1/cs285/scripts/read_events_files.py
import os
import tensorflow as tf
from matplotlib import pyplot as plt
def parse_filename(filepath):
fullfpath = os.path.split(filepath)[0].split(os.path.sep)
return fullfpath
def analyze_experiment_result(logdir):
for filename in os.listdir(logdir):
if filename.startswith('events.out.'):
filepath = os.path.join(logdir, filename)
break
output_result = collect_experiment_result(filepath)
plot_experiment_result(output_result)
fig_path = parse_filename(filepath)
plt.savefig(fig_path[-1])
def plot_experiment_result(output_result):
fig, ax = plt.subplots(3, 2)
max_step = len(output_result['loss'])
xaxis = list(range(max_step))
ax[0][0].plot(xaxis, output_result['train_mean'])
ax[0][0].title.set_text('return (train mean)')
ax[0][1].plot(xaxis, output_result['train_std'])
ax[0][1].title.set_text('return (train std)')
ax[1][0].plot(xaxis, output_result['eval_mean'])
ax[1][0].title.set_text('return (eval mean)')
ax[1][1].plot(xaxis, output_result['eval_std'])
ax[1][1].title.set_text('return (eval std)')
ax[2][0].plot(xaxis, output_result['loss'])
ax[2][0].title.set_text('loss')
def collect_experiment_result(filepath):
result = {'Train_AverageReturn': {}, 'Train_StdReturn':{}, 'Eval_AverageReturn':{}, 'Eval_StdReturn':{}, 'Train_Loss_mean':{}}
for summary in tf.train.summary_iterator(filepath):
for tag in result:
if summary.summary.value and summary.summary.value[0].tag == tag:
result[tag][summary.step] = summary.summary.value[0].simple_value
# turn it into a list.
max_step = max(result['Train_AverageReturn'].keys())
def dict2list(metrics, max_step):
return [result[metrics][i] for i in range(max_step + 1)]
eval_mean_return = dict2list('Eval_AverageReturn', max_step)
eval_std_return = dict2list('Eval_StdReturn', max_step)
train_mean_return = dict2list('Train_AverageReturn', max_step)
train_std_return = dict2list('Train_StdReturn', max_step)
loss_val = dict2list('Train_Loss_mean', max_step)
output_result = {'eval_mean': eval_mean_return,
'eval_std':eval_std_return,
'train_mean':train_mean_return,
'train_std':train_std_return,
'loss':loss_val}
return output_result
# filepath = os.path.join('D:\Documents\JuyueFiles\Learning\DRL_Homework\hw1\cs285\data\dagger_test_dagger_ant_Ant-v2_20-01-2020_14-58-21')
# analyze_experiment_result(filepath) | 77b026a3743a2687d130930515f3f142ae6c9650 | [
"Python"
]
| 3 | Python | Juyue/homework_fall2019 | aa9609339196e431285f303572ac12a25e47cd71 | e239fea60dda3a3a64136713c1113762d8f20c41 |
refs/heads/main | <file_sep># botst4rz
BOTANG NUR PRADANA HP WHATSAPP BOT
### Herramientas y materiales
Prepare las herramientas y los materiales.
`` golpe
> intención
> 2 teléfonos móviles (1 para ejecutar SC, 1 para escanear qr)
> Internet adecuado, si no tienes cupo, usa cupo del Ministerio de Educación y Cultura
> aplicación whatsapp
> aplicación termux
> café
''
### Cómo instalar
Antes de ejecutar el SC, instálelo primero.
`` golpe
> Si no tiene el APK de Termux, descárguelo de Playstore
> ingrese el termux apk y luego escriba a continuación!
> clon de git https://github.com/Bintang73/botst4rz.git
> cd botst4rz
> bash install.sh
> nodo index.js
> Solo escanea el qr bye
''
## Características
| st4rz BOT | Destacado |
| : -----------: | : --------------------------------: |
| ✅ | Creador de pegatinas |
| ✅ | Magernulis |
| ✅ | Pantun |
| ✅ | Descargador de Youtube |
| ✅ | Cotizaciones |
| ✅ | Anime |
| ✅ | Google Voice |
| ✅ | Corán |
| ✅ | Descargador de MP3 de Youtube |
| ✅ | Descargador de intagram |
| ✅ | Descargador de Twitter |
| ✅ | Descargador de Facebook |
| ✅ | Wikipedia |
| ✅ | Decir |
| ✅ | Info |
| ✅ | Donar
## Agradecimientos especiales a
* [`termux-whatsapp-bot`] (https://github.com/fdciabdul/termux-whatsapp-bot)
### Donar
* [`https://www.paypal.me/Kleber218)
<file_sep>const qrcode = require ("qrcode-terminal");
momento constante = require ("momento");
const cheerio = require ("cheerio");
const get = require ('obtuve')
const fs = require ("fs");
const dl = require ("./ lib / downloadImage.js");
const fetch = require ('búsqueda de nodo');
const urlencode = require ("urlencode");
const axios = require ("axios");
const imageToBase64 = require ('imagen a base64');
const menu = require ("./ lib / menu.js");
const donate = require ("./ lib / donate.js");
const info = require ("./ lib / info.js");
//
const BotName = 'El crack.r.informatico'; // El nombre el crack bot
const instagramlu = 'https://instagram.com/bintang_nur_pradana'; // Tu nombre de Instagram es chocolate
const whatsapplu = '0819-4698-3575'; // Número de Whatsapplu, estrangulamiento
const Kapanbotactive = '24 horas '; // ¿Cuándo estuvo activo tu bot?
const grupch1 = 'https://chat.whatsapp.com/FsAlnxqz6y2BhCQi5ayCLG'; // OFICIAL DEL GRUPO LU 1
const grupch2 = 'https://chat.whatsapp.com/KLW3UlFfeaH36Ucm5zRfCz'; // OFICIAL DEL GRUPO LU 2
//
constante
{
WAConexión,
Tipo de mensaje,
Presencia,
MessageOptions,
Tipo de Mimica,
WALocationMessage,
WA_MESSAGE_STUB_TYPES,
ReconectarMode,
ProxyAgent,
waChatKey,
} = require ("@ adiwajshing / baileys");
var hora = momento (). formato ("HH: mm");
función foreach (arr, func)
{
para (var i in arr)
{
func (i, arr [i]);
}
}
const conn = nueva conexión WAC ()
conn.on ('qr', qr =>
{
qrcode.generate (qr,
{
pequeño: cierto
});
console.log (`[$ {moment (). format (" HH: mm: ss ")}] Escanea tu código qr correctamente!`);
});
conn.on ('credenciales actualizadas', () =>
{
// guarda las credenciales cada vez que se actualizan
console.log (`credenciales actualizadas!`)
const authInfo = conn.base64EncodedAuthInfo () // obtenemos toda la información de autenticación que necesitamos para restaurar esta sesión
fs.writeFileSync ('./ session.json', JSON.stringify (authInfo, null, '\ t')) // guarda esta información en un archivo
})
fs.existsSync ('./ session.json') && conn.loadAuthInfo ('./ session.json')
// descomente la siguiente línea para hacer proxy de la conexión; algún proxy aleatorio del que salí: https://proxyscrape.com/free-proxy-list
//conn.connectOptions.agent = ProxyAgent ('http://192.168.3.11:8080')
conn.connect ();
conn.on ('user-present-update', json => console.log (`[$ (moment (). format (" HH: mm: ss ")}] => bot por @ bintang_nur_pradana`))
conn.on ('mensaje-estado-actualización', json =>
{
const participant = json.participant? '(' + json.participant + ')': '' // el participante existe cuando el mensaje es de un grupo
console.log (`[$ {momento (). formato (" HH: mm: ss ")}] => bot por @ bintang_nur_pradana`)
})
conn.on ('mensaje-nuevo', async (m) =>
{
const messageContent = m.message
texto constante = m.message.conversation
let id = m.key.remoteJid
const messageType = Object.keys (messageContent) [0] // el mensaje siempre contendrá una clave que indique qué tipo de mensaje
let imageMessage = m.message.imageMessage;
console.log (`[$ {moment (). format (" HH: mm: ss ")}] => Número: [$ {id.split (" @ s.whatsapp.net ") [0]}] = > $ {texto} `);
// Grupos
if (text.includes ("# Creategroup"))
{
var name = text.split ("# Creategroup") [1] .split ("- número") [0];
var nom = text.split ("- número") [1];
var numArray = nom.split (",");
para (var i = 0; i <numArray.length; i ++) {
numArray [i] = numArray [i] + "@ s.whatsapp.net";
}
var str = numArray.join ("");
console.log (str)
const group = await conn.groupCreate (nombre, cadena)
console.log ("grupo creado con id:" + group.gid)
conn.sendMessage (group.gid, "hola a todos", MessageType.extendedText) // saluda a todos en el grupo
}
// FF
if (text.includes ("# check")) {
var num = text.replace (/ # check /, "")
var idn = num.replace ("0", "+ 62");
console.log (id);
const gg = idn+'@s.whatsapp.net '
const existe = espera conn.isOnWhatsApp (gg)
console.log (existe);
conn.sendMessage (id, `$ {gg} $ {existe?" existe ":" no existe "} en WhatsApp`, MessageType.text)
}
if (text.includes ("# tts")) {
const text = text.replace (/ # tts /, "")
const gtts = (`https://rest.farzain.com/api/tts.php?id=$ {text} & apikey = <KEY>`)
conn.sendMessage (id, gtts, MessageType.text);
}
if (text.includes ("# say")) {
const text = text.replace (/ # say /, "")
conn.sendMessage (id, texto, MessageType.text)
}
if (text.includes ("# escribir")) {
const text = text.replace (/ # write /, "")
axios.get (`` https://st4rz.herokuapp.com/api/nulis?text=$ {text} `). then ((res) => {
let result = `` Descargue el resultado usted mismo, sí, el resultado está abajo, porque si lo envía directamente el resultado es borroso \ n \ n $ {res.data.result.data} `;
conn.sendMessage (id, resultado, MessageType.text);
})
}
if (text.includes ("# ytmp3")) {
const text = text.replace (/ # ytmp3 /, "")
axios.get (`` http://scrap.terhambar.com/yt?link=$ {text} `) .entonces ((res) => {
let result = `Descárguese usted mismo a través del enlace siguiente, me temo que el servidor no funciona xixi .. \ n \ nTamaño: $ {res.data.filesize} \ n \ nLink: $ {res.data.linkAudioOnly}`;
conn.sendMessage (id, resultado, MessageType.text);
})
}
if (text.includes ("# yt")) {
const text = text.replace (/ # yt /, "")
axios.get (`` http://scrap.terhambar.com/yt?link=$ {text} `) .entonces ((res) => {
let result = `Descárguese usted mismo a través del enlace de abajo, me temo que el servidor no funciona xixi .. \ n \ nTamaño: $ {res.data.filesize} \ n \ nLink: $ {res.data.linkVideo}`;
conn.sendMessage (id, resultado, MessageType.text);
})
}
if (text.includes ("# fb")) {
const text = text.replace (/ # fb /, "")
axios.get (`https://mhankbarbar.herokuapp.com/api/epbe?url=$ {text} & apiKey = <KEY>`) .entonces ((res) => {
let result = `` Descárguelo usted mismo a través del enlace de abajo, me temo que el servidor no funciona xixi .. \ n \ nTítulo: $ {res.data.title} \ n \ nSize: $ {res.data.filesize} \ n \ nEnlace: $ {res.data.result} `;
conn.sendMessage (id, resultado, MessageType.text);
})
}
if (text.includes ("# ig")) {
const text = text.replace (/ # ig /, "")
axios.get (`` https://st4rz.herokuapp.com/api/ig?url=$ {text} `). then ((res) => {
let result = `Descárguese usted mismo a través del enlace de abajo, me temo que el servidor no funciona xixi .. \ n \ nLink: $ {res.data.result}`;
conn.sendMessage (id, resultado, MessageType.text);
})
}
if (text.includes ("# twt")) {
const text = text.replace (/ # twt /, "")
axios.get (`https://mhankbarbar.herokuapp.com/api/twit?url=$ {text} & apiKey = <KEY>`). luego ((res) => {
let result = `` Descárguelo usted mismo a través del enlace de abajo, me temo que el servidor no funciona xixi .. \ n \ nTítulo: $ {res.data.title} \ n \ nSize: $ {res.data.filesize} \ n \ nEnlace: $ {res.data.result} `;
conn.sendMessage (id, resultado, MessageType.text);
})
}
if (text.includes ("# wiki")) {
const text = text.replace (/ # wiki /, "")
axios.get (`https://st4rz.herokuapp.com/api/wiki?q=$ {texto}`) .entonces ((res) => {
let result = `Según Wikipedia: \ n \ n $ {res.data.result}`;
conn.sendMessage (id, resultado, MessageType.text);
})
}
if (text == '#help') {
const corohelp = await get.get ('https://covid19.mathdro.id/api/countries/id') .json ()
var fecha = nueva fecha ();
var year = date.getFullYear ();
var mes = fecha.getMonth ();
var date = date.getDate ();
var day = date.getDay ();
var jam = date.getHours ();
var minutes = date.getMinutes ();
var segundos = date.getSeconds ();
cambiar (día) {
caso 0: días = "domingo"; descanso;
caso 1: día = "lunes"; descanso;
caso 2: día = "martes"; descanso;
caso 3: día = "miércoles"; descanso;
caso 4: día = "jueves"; descanso;
caso 5: días = "viernes"; descanso;
caso 6: día = "sábado"; descanso;
}
cambiar (mes) {
caso 0: mes = "enero"; descanso;
caso 1: mes = "febrero"; descanso;
caso 2: mes = "marzo"; descanso;
caso 3: mes = "abril"; descanso;
caso 4: mes = "mayo"; descanso;
caso 5: mes = "junio"; descanso;
caso 6: mes = "julio"; descanso;
caso 7: mes = "agosto"; descanso;
caso 8: mes = "septiembre"; descanso;
caso 9: mes = "octubre"; descanso;
caso 10: mes = "noviembre"; descanso;
caso 11: mes = "diciembre"; descanso;
}
var apareceDate = "FECHA:" + día + "," + fecha + "" + mes + "" + año;
var apareceTime = "HORA:" + hora + ":" + minuto + ":" + segundos;
conn.sendMessage (id, menu.menu (id, BotName, corohelp, showDate, showTime, Instagramlu, whatsapplu, whenbotactive, grupch1, grupch2), MessageType.text);
}
else if (text == '#quran') {
axios.get ('https://api.banghasan.com/quran/format/json/acak'). then ((res) => {
const sr = /((.*?))/gi;
const hs = res.data.acak.id.ayat;
const ket = `` $ {hs} `.replace (sr, '');
let result = `[$ {ket}] $ {res.data.acak.ar.text} \ n \ n $ {res.data.acak.id.text} (QS. $ {res.data.surat.name }, Párrafo $ {ket}) `;
conn.sendMessage (id, resultado, MessageType.text);
})
}
else if (text == 'assalamualaikum') {
conn.sendMessage (id, '3aalaikumsalam, ¿hay algo en lo que pueda ayudarlo? Si está confundido, escriba #help yes say ..', MessageType.text);
}
else if (texto == 'saludo') {
conn.sendMessage (id, 'Waalaikumsalam, ¿hay algo en lo que pueda ayudarlo? Si está confundido, escriba #help yes say ..', MessageType.text);
}
else if (text == 'asalamualaikum') {
conn.sendMessage (id, 'Waalaikumsalam, ¿hay algo en lo que pueda ayudarlo? Si está confundido, escriba #help yes say ..', MessageType.text);
}
else if (text == 'Assalamualaikum') {
conn.sendMessage (id, 'Waalaikumsalam, ¿hay algo en lo que pueda ayudarlo? Si está confundido, escriba #help yes say ..', MessageType.text);
}
else if (texto == 'p') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
más si (texto == 'P') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (texto == 'hola') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (texto == 'hola') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (text == 'woi') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
más si (texto == 'woy') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (texto == 'hola') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (text == 'gan') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (text == 'sis') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (texto == 'hermano') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (text == 'min') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (text == 'cariño') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (text == 'te amo') {
conn.sendMessage (id, 'también te quiero', MessageType.text);
}
else if (text == 'mas') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (texto == 'mba') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (text == 'bre') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
más si (texto == 'cuy') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
más si (texto == 'euy') {
conn.sendMessage (id, '¿Sí?, ¿puedo ayudarte? Si estás confundido, escribe #help yes say ..', MessageType.text);
}
else if (text == 'gracias') {
conn.sendMessage (id, 'De nada, que tenga un buen día :)', MessageType.text);
}
else if (text == 'Gracias') {
conn.sendMessage (id, 'De nada, que tenga un buen día :)', MessageType.text);
}
else if (text == 'gracias') {
conn.sendMessage (id, 'De nada, que tenga un buen día :)', MessageType.text);
}
else if (text == 'Gracias') {
conn.sendMessage (id, 'De nada, que tenga un buen día :)', MessageType.text);
}
else if (text == 'gracias') {
conn.sendMessage (id, 'De nada, que tenga un buen día :)', MessageType.text);
}
else if (text == 'Gracias') {
conn.sendMessage (id, 'De nada, que tenga un buen día :)', MessageType.text);
}
else if (text == 'gracias') {
conn.sendMessage (id, 'De nada, que tenga un buen día :)', MessageType.text);
}
else if (text == 'Gracias') {
conn.sendMessage (id, 'De nada, que tenga un buen día :)', MessageType.text);
}
else if (text == '#donate') {
const corohelp = await get.get ('https://covid19.mathdro.id/api/countries/id') .json ()
var fecha = nueva fecha ();
var year = date.getFullYear ();
var mes = fecha.getMonth ();
var date = date.getDate ();
var day = date.getDay ();
var jam = date.getHours ();
var minutes = date.getMinutes ();
var segundos = date.getSeconds ();
cambiar (día) {
caso 0: días = "domingo"; descanso;
caso 1: día = "lunes"; descanso;
caso 2: día = "martes"; descanso;
caso 3: día = "miércoles"; descanso;
caso 4: día = "jueves"; descanso;
caso 5: días = "viernes"; descanso;
caso 6: día = "sábado"; descanso;
}
cambiar (mes) {
caso 0: mes = "enero"; descanso;
caso 1: mes = "febrero"; descanso;
caso 2: mes = "marzo"; descanso;
caso 3: mes = "abril"; descanso;
caso 4: mes = "mayo"; descanso;
caso 5: mes = "junio"; descanso;
caso 6: mes = "julio"; descanso;
caso 7: mes = "agosto"; descanso;
caso 8: mes = "septiembre"; descanso;
caso 9: mes = "octubre"; descanso;
caso 10: mes = "noviembre"; descanso;
caso 11: mes = "diciembre"; descanso;
}
var apareceDate = "FECHA:" + día + "," + fecha + "" + mes + "" + año;
var apareceTime = "HORA:" + hora + ":" + minuto + ":" + segundos;
conn.sendMessage (id, donate.donate (id, BotName, corohelp, showDate, showTime, Instagramlu, whatsapplu, whenbotactive, grupch1, grupch2), MessageType.text);
}
else if (text == '# donación') {
const corohelp = await get.get ('https://covid19.mathdro.id/api/countries/id') .json ()
var fecha = nueva fecha ();
var year = date.getFullYear ();
var mes = fecha.getMonth ();
var date = date.getDate ();
var day = date.getDay ();
var jam = date.getHours ();
var minutes = date.getMinutes ();
var segundos = date.getSeconds ();
cambiar (día) {
caso 0: días = "domingo"; descanso;
caso 1: día = "lunes"; descanso;
caso 2: día = "martes"; descanso;
caso 3: día = "miércoles"; descanso;
caso 4: día = "jueves"; descanso;
caso 5: días = "viernes"; descanso;
caso 6: día = "sábado"; descanso;
}
cambiar (mes) {
caso 0: mes = "enero"; descanso;
caso 1: mes = "febrero"; descanso;
caso 2: mes = "marzo"; descanso;
caso 3: mes = "abril"; descanso;
caso 4: mes = "mayo"; descanso;
caso 5: mes = "junio"; descanso;
caso 6: mes = "julio"; descanso;
caso 7: mes = "agosto"; descanso;
caso 8: mes = "septiembre"; descanso;
caso 9: mes = "octubre"; descanso;
caso 10: mes = "noviembre"; descanso;
caso 11: mes = "diciembre"; descanso;
}
var apareceDate = "FECHA:" + día + "," + fecha + "" + mes + "" + año;
var apareceTime = "HORA:" + hora + ":" + minuto + ":" + segundos;
conn.sendMessage (id, donate.donate (id, BotName, corohelp, showDate, showTime, Instagramlu, whatsapplu, whenbotactive, grupch1, grupch2), MessageType.text);
}
else if (text == '#DONATE') {
const corohelp = await get.get ('https://covid19.mathdro.id/api/countries/id') .json ()
var fecha = nueva fecha ();
var year = date.getFullYear ();
var mes = fecha.getMonth ();
var date = date.getDate ();
var day = date.getDay ();
var jam = date.getHours ();
var minutes = date.getMinutes ();
var segundos = date.getSeconds ();
cambiar (día) {
caso 0: días = "domingo"; descanso;
caso 1: día = "lunes"; descanso;
caso 2: día = "martes"; descanso;
caso 3: día = "miércoles"; descanso;
caso 4: día = "jueves"; descanso;
caso 5: días = "viernes"; descanso;
caso 6: día = "sábado"; descanso;
}
cambiar (mes) {
caso 0: mes = "enero"; descanso;
caso 1: mes = "febrero"; descanso;
caso 2: mes = "marzo"; descanso;
caso 3: mes = "abril"; descanso;
caso 4: mes = "mayo"; descanso;
caso 5: mes = "junio"; descanso;
caso 6: mes = "julio"; descanso;
caso 7: mes = "agosto"; descanso;
caso 8: mes = "septiembre"; descanso;
caso 9: mes = "octubre"; descanso;
caso 10: mes = "noviembre"; descanso;
caso 11: mes = "diciembre"; descanso;
}
var apareceDate = "FECHA:" + día + "," + fecha + "" + mes + "" + año;
var apareceTime = "HORA:" + hora + ":" + minuto + ":" + segundos;
conn.sendMessage (id, donate.donate (id, BotName, corohelp, showDate, showTime, Instagramlu, whatsapplu, whenbotactive, grupch1, grupch2), MessageType.text);
}
else if (text == '#DONATE') {
const corohelp = await get.get ('https://covid19.mathdro.id/api/countries/id') .json ()
var fecha = nueva fecha ();
var year = date.getFullYear ();
var mes = fecha.getMonth ();
var date = date.getDate ();
var day = date.getDay ();
var jam = date.getHours ();
var minutes = date.getMinutes ();
var segundos = date.getSeconds ();
cambiar (día) {
caso 0: días = "domingo"; descanso;
caso 1: día = "lunes"; descanso;
caso 2: día = "martes"; descanso;
caso 3: día = "miércoles"; descanso;
caso 4: día = "jueves"; descanso;
caso 5: días = "viernes"; descanso;
caso 6: día = "sábado"; descanso;
}
cambiar (mes) {
caso 0: mes = "enero"; descanso;
caso 1: mes = "febrero"; descanso;
caso 2: mes = "marzo"; descanso;
caso 3: mes = "abril"; descanso;
caso 4: mes = "mayo"; descanso;
caso 5: mes = "junio"; descanso;
caso 6: mes = "julio"; descanso;
caso 7: mes = "agosto"; descanso;
caso 8: mes = "septiembre"; descanso;
caso 9: mes = "octubre"; descanso;
caso 10: mes = "noviembre"; descanso;
caso 11: mes = "diciembre"; descanso;
}
var apareceDate = "FECHA:" + día + "," + fecha + "" + mes + "" + año;
var apareceTime = "HORA:" + hora + ":" + minuto + ":" + segundos;
conn.sendMessage (id, donate.donate (id, BotName, corohelp, showDate, showTime, Instagramlu, whatsapplu, whenbotactive, grupch1, grupch2), MessageType.text);
}
else if (text == '#info') {
const corohelp = await get.get ('https://covid19.mathdro.id/api/countries/id') .json ()
var fecha = nueva fecha ();
var year = date.getFullYear ();
var mes = fecha.getMonth ();
var date = date.getDate ();
var day = date.getDay ();
var jam = date.getHours ();
var minutes = date.getMinutes ();
var segundos = date.getSeconds ();
cambiar (día) {
caso 0: días = "domingo"; descanso;
caso 1: día = "lunes"; descanso;
caso 2: día = "martes"; descanso;
caso 3: día = "miércoles"; descanso;
caso 4: día = "jueves"; descanso;
caso 5: días = "viernes"; descanso;
caso 6: día = "sábado"; descanso;
}
cambiar (mes) {
caso 0: mes = "enero"; descanso;
caso 1: mes = "febrero"; descanso;
caso 2: mes = "marzo"; descanso;
caso 3: mes = "abril"; descanso;
caso 4: mes = "mayo"; descanso;
caso 5: mes = "junio"; descanso;
caso 6: mes = "julio"; descanso;
caso 7: mes = "agosto"; descanso;
caso 8: mes = "septiembre"; descanso;
caso 9: mes = "octubre"; descanso;
caso 10: mes = "noviembre"; descanso;
caso 11: mes = "diciembre"; descanso;
}
var apareceDate = "FECHA:" + día + "," + fecha + "" + mes + "" + año;
var apareceTime = "HORA:" + hora + ":" + minuto + ":" + segundos;
conn.sendMessage (id, info.info (id, BotName, corohelp, showDate, showTime, Instagramlu, whatsapplu, whenbotactive, grupch1, grupch2), MessageType.text);
}
else if (text == '#ptl') {
conn.sendMessage (id, 'enviar #ptl niña / niño \ n \ nEjemplo: #ptl niña', MessageType.text);
}
if (messageType == 'imageMessage')
{
let caption = imageMessage.caption.toLocaleLowerCase ()
const buffer = await conn.downloadMediaMessage (m) // para descifrar y usar como búfer
if (título == '#sticker')
{
const sticker = await conn.downloadAndSaveMediaMessage (m) // para descifrar y guardar en el archivo
constante
{
ejecutivo
} = require ("child_process");
exec ('cwebp -q 50' + pegatina + '-o temp /' + jam + '.webp', (error, stdout, stderr) =>
{
let stick = fs.readFileSync ('temp /' + hour + '.webp')
conn.sendMessage (id, palo, MessageType.sticker)
});
}
}
si (messageType === MessageType.text)
{
let es = m.message.conversation.toLocaleLowerCase ()
si (es == '#pantun')
{
buscar ('https://raw.githubusercontent.com/pajaar/grabbed-results/master/pajaar-2020-pantun-pakboy.txt')
.entonces (res => res.text ())
.entonces (cuerpo =>
{
let tod = body.split ("\ n");
let pjr = tod [Math.floor (Math.random () * tod.length)];
let pantun = pjr.replace (/ pjrx-line / g, "\ n");
conn.sendMessage (id, pantun, MessageType.text)
});
}
}
/ * if (text.includes ("# yt"))
{
const url = text.replace (/ # yt /, "");
const exec = require ('child_process'). exec;
var videoid = url.match (/ (?: https ?: \ / {2})? (?: w {3} \.)? youtu (?: be)? \. (?: com | be) (? : \ / reloj \? v = | \ /) ([^ \ s &] +) /);
const ytdl = require ("ytdl-core")
si (videoid! = null)
{
console.log ("video id =", videoid [1]);
}
demás
{
conn.sendMessage (id, "gavalid", MessageType.text)
}
ytdl.getInfo (videoid [1]). luego (info =>
{
si (info.length_seconds> 1000)
{
conn.sendMessage (id, "el video es largo", MessageType.text)
}
demás
{
console.log (info.length_seconds)
función os_func ()
{
this.execCommand = función (cmd)
{
devolver nueva promesa ((resolver, rechazar) =>
{
exec (cmd, (error, stdout, stderr) =>
{
si (error)
{
rechazar (error);
regreso;
}
resolver (stdout)
});
})
}
}
var os = new os_func ();
os.execCommand ('ytdl' + url + '-q más alto -o mp4 /' + videoid [1] + '.mp4'). luego (res =>
{
const buffer = fs.readFileSync ("mp4 /" + videoid [1] + ". mp4")
conn.sendMessage (id, búfer, MessageType.video)
}). catch (err =>
{
console.log ("sistema operativo >>>", err);
})
}
});
} * /
/ * if (text.includes ("# nulis"))
{
constante
{
Aparecer
} = require ("child_process");
console.log ("escribiendo ...")
const text = text.replace (/ # write /, "")
const split = text.replace (/ (\ S + \ s *) {1,10} / g, "$ & \ n")
const FixedHeight = split.split ("\ n"). slice (0, 25) .join ("\\ n")
console.log (dividido)
spawn ("convertir", [
"./assets/paper.jpg",
"-fuente",
"Indie-Flower",
"-Talla",
"700 x 960",
"-punto",
"18",
"-interline-spacing",
"3",
"-anotar",
"+ 170 + 222",
FixedHeight,
"./assets/result.jpg"
])
.on ("error", () => console.log ("error"))
.on ("salir", () =>
{
const buffer = fs.readFileSync ("assets / result.jpg") // puede enviar mp3, mp4 y ogg, pero para archivos mp3, el tipo mime debe configurarse en ogg
conn.sendMessage (id, búfer, MessageType.image)
console.log ("hecho")
})
}
if (text.includes ("# comillas"))
{
var url = 'https://jagokata.com/kata-bijak/acak.html'
axios.get (url)
.entonces ((resultado) =>
{
let $ = cheerio.load (result.data);
var autor = $ ('a [clase = "auteurfbnaam"]'). contenido (). primer (). texto ();
var word = $ ('q [class = "fbquote"]'). contents (). first (). text ();
conn.sendMessage (
identificación,
'
_ $ {palabra} _
* ~ $ {autor} *
`, MessageType.text
);
});
} * /
if (text.includes ("# ptl chick"))
{
var items = ["ch<NAME>", "cewe cantik", "hijab cantik", "chica coreana"];
var cewe = items [Math.floor (Math.random () * items.length)];
var url = "https://api.fdci.se/rep.php?gambar=" + niña;
axios.get (url)
.entonces ((resultado) => {
var b = JSON.parse (JSON.stringify (result.data));
var chick = b [Math.floor (Math.random () * b.length)];
imageToBase64 (niña) // Ruta a la imagen
.luego (
(respuesta) => {
var buf = Buffer.from (respuesta, 'base64'); // Ta-da
conn.sendMessage (
identificación,
buf, MessageType.image)
}
)
.captura (
(error) => {
console.log (error); // Registra un error si hubo uno
}
)
});
}
if (text.includes ("# ptl guy"))
{
var items = ["chico guapo", "cogan", "chico coreano", "chico chino", "chico japonés"];
var cewe = items [Math.floor (Math.random () * items.length)];
var url = "https://api.fdci.se/rep.php?gambar=" + niña;
axios.get (url)
.entonces ((resultado) => {
var b = JSON.parse (JSON.stringify (result.data));
var chick = b [Math.floor (Math.random () * b.length)];
imageToBase64 (niña) // Ruta a la imagen
.luego (
(respuesta) => {
var buf = Buffer.from (respuesta, 'base64'); // Ta-da
conn.sendMessage (
identificación,
buf, MessageType.image)
}
)
.captura (
(error) => {
console.log (error); // Registra un error si hubo uno
}
)
});
}
if (text.includes ("# randomanime"))
{
var items = ["anime girl", "beautiful anime", "anime", "anime aesthetic"];
var cewe = items [Math.floor (Math.random () * items.length)];
var url = "https://api.fdci.se/rep.php?gambar=" + niña;
axios.get (url)
.entonces ((resultado) => {
var b = JSON.parse (JSON.stringify (result.data));
var chick = b [Math.floor (Math.random () * b.length)];
imageToBase64 (niña) // Ruta a la imagen
.luego (
(respuesta) => {
var buf = Buffer.from (respuesta, 'base64'); // Ta-da
conn.sendMessage (
identificación,
buf, MessageType.image)
}
)
.captura (
(error) => {
console.log (error); // Registra un error si hubo uno
}
)
});
}
/ * if (text.includes ("# scdl")) {
const fs = require ("fs");
const scdl = require ("./ lib / scdl");
scdl.setClientID ("iZIs9mchVcX5lhVRyQGGAYlNPVldzAoX");
scdl ("https://m.soundcloud.com/abdul-muttaqin-701361735/lucid-dreams-gustixa-ft-vict-molina")
.pipe (fs.createWriteStream ("mp3 / canción.mp3"));
}
else if (text.includes ("# tts")) {
var text = text.split ("# ttsid") [1];
var ruta = require ('ruta');
var text1 = text.slice (6);
texto1 = sonido;
var sound = text.replace (/ # ttsid / g, text1);
var filepath = 'mp3 / bacot.wav';
/ *
* guardar archivos de audio
* /
/*gtts.save(filepath, sound, function () {
console.log (`$ {filepath} MP3 GUARDADO!`)
});
aguardar nueva promesa (resolver => setTimeout (resolver, 500)); * /
/ * if (Suara.length> 200) {// verifica la longitud del texto, porque de lo contrario el traductor de Google me dará un archivo vacío
msg.reply ("Texto largo hermano!")
} demás {
const buffer = fs.readFileSync (ruta de archivo)
conn.sendMessage (id, búfer, MessageType.audio);
};
} * /
// fin del documento
}) | b8822db154ac92e6d23cb0ca6db175178e0772e3 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | crack-12/botst4rz-main. | bed4f8714475e984d2ecee856d627134bec8ec6c | 79b8e42edbc48ba75feaa6f07af5614679ef50b6 |
refs/heads/master | <file_sep>//
// CoreDataEngine.swift
// FoodApp
//
// Created by <NAME> on 16.09.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import Foundation
import CoreData
class CoreDataEngine {
static let sharedInstance : CoreDataEngine = {CoreDataEngine()}()
func addRestaurant(restaur : Resturant) {
let restaurant = RestaurantMO(context: CoreDataManager.sharedInstance.persistentContainer.viewContext)
restaurant.name = restaur.name
restaurant.location = restaur.location
restaurant.phone = restaur.phone
restaurant.isVisited = restaur.isVisited
restaurant.type = restaur.type
restaurant.raiting = restaur.raiting
restaurant.image = restaur.image
print("Save Data To Context ")
CoreDataManager.sharedInstance.saveContext()
// restaurant.name = restaurant.name
// restaurant.location = restaurant.location
// restaurant.phone = restaurant.phone
}
func fetchRestaurants() -> [RestaurantMO] {
let fetchRequest : NSFetchRequest<RestaurantMO> = RestaurantMO.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
// if let appDelegate = (UIApplication.shared.delegate as? AppDelegate) {
let context = CoreDataManager.sharedInstance.persistentContainer.viewContext
let fetchResultCOntroller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext : context, sectionNameKeyPath: nil, cacheName: nil)
do {
try fetchResultCOntroller.performFetch()
if let fetchedObjects = fetchResultCOntroller.fetchedObjects {
return fetchedObjects
}
} catch {
print(error)
}
return []
}}
<file_sep>//
// WebViewController.swift
// FoodApp
//
// Created by <NAME> on 02.05.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
if let url = URL(string: "http://www.appcoda.com/contact") {
let request = URLRequest(url: url)
webView.load(request)
}
}
override func loadView() {
webView = WKWebView()
view = webView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
<file_sep>//
// DataStore.swift
// FoodApp
//
// Created by <NAME> on 16.09.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import Foundation
class DataStore{
class var defaultLocalDB : CoreDataManager {
return CoreDataManager.sharedInstance
}
}
<file_sep>//
// KivaLoanTableViewController.swift
// KivaLoan
//
// Created by <NAME> on 24/03/2018.
//Copyright © 2018 DavydzikInc. All rights reserved.
import UIKit
import CoreData
class KivaLoanTableViewController: UITableViewController {
func updateTableViewContent(){
do {
try self.fetchResultController.performFetch()
} catch let error {
print(error)
}
let apiService = APIService()
apiService.getDataWith { (result) in
switch result{
case .Success(let data):
self.clearData()
self.saveInCoreData(loans: data)
case .Error(let error):
print(error)
}
}
}
// MARK: - ViewController Lifecycle methods
override func loadView() {
super.loadView()
UserDefaults.standard.set(false, forKey: "hasViewedWalkThrough")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 92.0
tableView.rowHeight = UITableViewAutomaticDimension
updateTableViewContent()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - CoreData operations
private lazy var fetchResultController: NSFetchedResultsController<NSFetchRequestResult> = {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: LoanMO.self))
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
let context = CoreDataManager.sharedInstance.persistentContainer.viewContext
let fetchResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fetchResultController.delegate = self
return fetchResultController
}()
private func createCoreDataEntityWith(loanDictionary : [String : AnyObject]) -> NSManagedObject?{
let loan = LoanMO(context: CoreDataManager.sharedInstance.persistentContainer.viewContext)
loan.name = loanDictionary["name"] as? String
let location = loanDictionary["location"] as? [String : AnyObject]
loan.country = location?["country"] as? String
loan.use = loanDictionary["use"] as? String
loan.loan_amount = (loanDictionary["loan_amount"] as? Int16)!
return loan
}
private func saveInCoreData(loans : [[String:AnyObject]]){
_ = loans.map({ self.createCoreDataEntityWith(loanDictionary: $0)})
do {
try CoreDataManager.sharedInstance.persistentContainer.viewContext.save()
} catch let error {
print(error)
}
CoreDataManager.sharedInstance.saveContext()
}
private func clearData() {
do {
let context = CoreDataManager.sharedInstance.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: LoanMO.self))
do {
let objects = try context.fetch(fetchRequest) as? [NSManagedObject]
_ = objects.map{$0.map{context.delete($0)}}
CoreDataManager.sharedInstance.saveContext()
} catch let error {
print("ERROR DELETING : \(error)")
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let fetchCount = fetchResultController.sections?.first?.numberOfObjects{
return fetchCount
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! KivaLoanTableViewCell
if let loan = self.fetchResultController.object(at: indexPath) as? LoanMO{
cell.nameLabel.text = loan.name
cell.countryLabel.text = loan.country
cell.useLabel.text = loan.use
cell.amountLabel.text = String(loan.loan_amount)
}
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowLoanDetail" {
if let indexPath = tableView.indexPathForSelectedRow{
let destinationController = segue.destination as! LoanDetailViewController
destinationController.loan = self.fetchResultController.object(at: indexPath) as? LoanMO
}
}
}
}
extension KivaLoanTableViewController : NSFetchedResultsControllerDelegate{
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
self.tableView.insertRows(at: [newIndexPath!], with: .automatic)
case .delete:
self.tableView.deleteRows(at: [indexPath!], with: .automatic)
default:
break
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.tableView.endUpdates()
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
}
<file_sep>//
// Restaurant.swift
// FoodApp
//
// Created by <NAME> on 14.04.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import Foundation
class Resturant {
var name : String?
var type :String?
var location :String?
var image = NSData()
var phone : String?
var raiting : String?
var isVisited = false
init(name: String, type: String , location : String ,phone: String, image : NSData, isVisited : Bool) {
self.name = name
self.type = type
self.location = location
self.image = image
self.isVisited = isVisited
self.phone = phone
}
}
<file_sep>//
// walkthroughPageViewController.swift
// FoodApp
//
// Created by <NAME> on 26.04.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import UIKit
class walkthroughPageViewController: UIPageViewController, UIPageViewControllerDataSource {
var pageHeadings = ["Personalize", "Locate", "Discover"]
var pageImages = ["foodpin-intro-1", "foodpin-intro-2", "foodpin-intro-3"]
var pageContent = ["Pin your favorite restaurants and create your own food guide",
"Search and locate your favourite restaurant on Maps",
"Find restaurants pinned by your friends and other foodies around the world"]
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
if let startingViewController = contentViewController(at: 0) {
setViewControllers([startingViewController], direction: .forward, animated: true, completion: nil)
}
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
var index = (viewController as! WalkThroughViewController).index
index -= 1
return contentViewController(at: index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
var index = (viewController as! WalkThroughViewController).index
index += 1
return contentViewController(at: index)
}
func contentViewController(at index: Int) -> WalkThroughViewController?{
if index<0 || index>=pageHeadings.count {
return nil
}
if let contentVC = storyboard?.instantiateViewController(withIdentifier: "WalkthroughContentViewController") as? WalkThroughViewController {
contentVC.heading = pageHeadings[index]
contentVC.content = pageContent [index]
contentVC.imageVIew = pageImages[index]
contentVC.index = index
return contentVC
}
return nil
}
func forward(index: Int) {
if let nextViewController = contentViewController(at: index + 1) {
setViewControllers([nextViewController], direction: .forward, animated: true, completion: nil)
}
}
}
<file_sep>//
// LoanDetailViewController.swift
// KivaLoan
//
// Created by <NAME> on 25/03/2018.
//Copyright © 2018 DavydzikInc. All rights reserved.
import UIKit
import MapKit
class LoanDetailViewController:UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet var tableView:UITableView!
var loan : LoanMO?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath) as! DetailLoanTableViewCell
switch indexPath.row {
case 0:
cell.fieldLabel.text = "Name"
cell.valueLabel.text = loan?.name
case 1:
cell.fieldLabel.text = "Country"
cell.valueLabel.text = loan?.country
case 2:
cell.fieldLabel.text = "Use"
cell.valueLabel.text = loan?.use
case 3:
cell.fieldLabel.text = "Amount"
cell.valueLabel.text = String(describing :(loan?.loan_amount)!)
default:
cell.fieldLabel.text = ""
cell.valueLabel.text = ""
}
cell.backgroundColor = UIColor.clear
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.2)
tableView.tableFooterView = UIView(frame: CGRect.zero)
tableView.separatorColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 0.8)
tableView.estimatedRowHeight = 92.0
tableView.rowHeight = UITableViewAutomaticDimension
createMapAnnotation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func createMapAnnotation() {
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString((loan?.country)!, completionHandler: {
placemarks, error in
if error != nil {
print(error as Any)
return
}
if let placemarks = placemarks {
let placemark = placemarks[0]
let annotation = MKPointAnnotation()
if let location = placemark.location {
annotation.coordinate = location.coordinate
self.mapView.addAnnotation(annotation)
let region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 800000, 3000)
self.mapView.setRegion(region, animated: false)
self.mapView.mapType = .standard
}
} })
}
}
<file_sep>//
// WalkThroughViewController.swift
// FoodApp
//
// Created by <NAME> on 26.04.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import UIKit
class WalkThroughViewController: UIViewController {
@IBOutlet var headingLabel : UILabel!
@IBOutlet var bodyLabel : UILabel!
@IBOutlet var imgView : UIImageView!
@IBOutlet var pageControl : UIPageControl!
@IBOutlet var nextButton : UIButton!
@IBAction func nextButtonTapped(sender: UIButton){
switch index {
case 0...1:
let parentVC = parent as? walkthroughPageViewController
parentVC?.forward(index: index)
case 2:
UserDefaults.standard.set(true, forKey: "hasViewedWalkThrough")
dismiss(animated: true, completion: nil)
default:
break
}
}
var index = 0
var heading = ""
var content = ""
var imageVIew = ""
override func viewDidLoad() {
super.viewDidLoad()
self.headingLabel.text = heading
self.bodyLabel.text = content
self.imgView.image = UIImage(named: imageVIew)
pageControl.currentPage = index
switch index {
case 0...1:
self.nextButton.setTitle("Next", for: .normal)
case 2:
self.nextButton.setTitle("Done", for: .normal)
default:
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
<file_sep># iOS-test-tasks
iOS test tasks in Swift
<file_sep>//
// DetailLoanTableViewCell.swift
// KivaLoan
//
// Created by <NAME> on 25/03/2018.
import UIKit
class DetailLoanTableViewCell: UITableViewCell {
@IBOutlet weak var valueLabel: UILabel!
@IBOutlet weak var fieldLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// KivaLoanTableViewCell.swift
// KivaLoan
//
// Created by <NAME> on 24/03/2018.
import UIKit
class KivaLoanTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel:UILabel!
@IBOutlet weak var countryLabel:UILabel!
@IBOutlet weak var useLabel:UILabel!
@IBOutlet weak var amountLabel:UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setContent(loan : LoanMO) {
DispatchQueue.main.async {
self.nameLabel.text = loan.name
self.countryLabel.text = loan.country
self.useLabel.text = loan.use
self.amountLabel.text = String(loan.loan_amount)
}
}
}
<file_sep>//
// ReviewViewController.swift
// FoodApp
//
// Created by <NAME> on 18.04.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import UIKit
class ReviewViewController: UIViewController {
@IBOutlet var backgroundImg: UIImageView?
@IBOutlet var containerView:UIView!
var restaurant:RestaurantMO?
override func viewDidLoad() {
super.viewDidLoad()
let blurEffect = UIBlurEffect(style: .dark)
let blurView = UIVisualEffectView(effect:blurEffect)
blurView.frame = view.bounds
backgroundImg?.addSubview(blurView)
let transform1 = CGAffineTransform(scaleX: 0 , y: 0)
let transform2 = CGAffineTransform.init(translationX: 0, y: -1000)
let transform3 = transform1.concatenating(transform2)
self.containerView.transform = transform3
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
UIView.animate(withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.2, options: .curveEaseInOut, animations: {
self.containerView.transform = CGAffineTransform.identity
}, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
<file_sep>//
// AddRestaurantControllerTableViewController.swift
// FoodApp
//
// Created by <NAME> on 19.04.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import CoreData
import UIKit
class AddRestaurantControllerTableViewController: UITableViewController , UIImagePickerControllerDelegate , UINavigationControllerDelegate{
var isVisited = true
var imageData : Data?
@IBOutlet var imageVIew : UIImageView!
@IBOutlet var nameTextField : UITextField!
@IBOutlet var typeTextField : UITextField!
@IBOutlet var locationTextField : UITextField!
@IBOutlet var noButton: UIButton!
@IBOutlet var yesButton: UIButton!
@IBOutlet var phoneTextField : UITextField!
var restaurant: RestaurantMO!
@IBAction func saveData(sender: AnyObject){
if self.nameTextField.text == "" || self.typeTextField.text == "" || self.locationTextField.text == "" || self.phoneTextField.text == "" {
let alertView = UIAlertController(title: "Please enter all fields", message: "Some fields are not write", preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alertView, animated: true, completion: nil)
}else{
if let image = imageVIew.image {
if let imageData = UIImagePNGRepresentation(image) {
self.imageData = imageData
}
}
restaurant = RestaurantMO(context: DataStore.defaultLocalDB.persistentContainer.viewContext )
restaurant.name = nameTextField.text
restaurant.location = locationTextField.text
restaurant.type = typeTextField.text
restaurant.isVisited = isVisited
restaurant.phone = phoneTextField.text
if let image = imageVIew.image {
if let imageData = UIImagePNGRepresentation(image) {
restaurant.image = NSData(data: imageData)
}
}
print("Save Data To Context ")
DataStore.defaultLocalDB.saveContext()
dismiss(animated: true, completion: nil)
}
}
@IBAction func changeBtnColor(sender:UIButton){
if sender == yesButton {
isVisited = true
yesButton.backgroundColor = UIColor(red: 218.0/255.0, green: 100.0/255.0, blue: 70.0/255.0, alpha: 1.0)
// Change the backgroundColor property of noButton to gray
noButton.backgroundColor = UIColor(red: 218.0/255.0, green: 223.0/255.0, blue: 225.0/255.0, alpha: 1.0)
}else{
isVisited = false
noButton.backgroundColor = UIColor(red: 218.0/255.0, green: 100.0/255.0, blue: 70.0/255.0, alpha: 1.0)
// Change the backgroundColor property of noButton to gray
yesButton.backgroundColor = UIColor(red: 218.0/255.0, green: 223.0/255.0, blue: 225.0/255.0, alpha: 1.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
}else{
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: - Table view data source
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
self.imageVIew.image = image
self.imageVIew.clipsToBounds = true
self.imageVIew.contentMode = .scaleAspectFill
}
let leadingConstraint = NSLayoutConstraint(item : self.imageVIew, attribute : NSLayoutAttribute.leading, relatedBy : NSLayoutRelation.equal, toItem : imageVIew.superview, attribute : NSLayoutAttribute.leading, multiplier: 1, constant : 0)
leadingConstraint.isActive = true
let trailingConstraint = NSLayoutConstraint(item : self.imageVIew, attribute : NSLayoutAttribute.trailing, relatedBy : NSLayoutRelation.equal, toItem : imageVIew.superview, attribute : NSLayoutAttribute.trailing, multiplier: 1, constant : 0)
trailingConstraint.isActive = true
let topConstraint = NSLayoutConstraint(item : self.imageVIew, attribute : NSLayoutAttribute.top, relatedBy : NSLayoutRelation.equal, toItem : imageVIew.superview, attribute : NSLayoutAttribute.top, multiplier: 1, constant : 0)
topConstraint.isActive = true
let bottomConstraint = NSLayoutConstraint(item : self.imageVIew, attribute : NSLayoutAttribute.bottom, relatedBy : NSLayoutRelation.equal, toItem : imageVIew.superview, attribute : NSLayoutAttribute.bottom, multiplier: 1, constant : 0)
bottomConstraint.isActive = true
dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// MapViewController.swift
// FoodApp
//
// Created by <NAME> on 18.04.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet var mapView: MKMapView!
var restaurant : RestaurantMO!
var locationManager = CLLocationManager()
var currentPlacemark : CLPlacemark?
override func viewDidLoad() {
super.viewDidLoad()
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(restaurant.location!, completionHandler:{ placemarks, error in
if error != nil{
print(error!)
return
}
self.mapView.delegate = self
if let placemarks = placemarks {
let placemark = placemarks[0]
self.currentPlacemark = placemark
let annotation = MKPointAnnotation()
annotation.title = self.restaurant.name
annotation.subtitle = self.restaurant.type
if let location = placemark.location{
annotation.coordinate = location.coordinate
//self.mapView.addAnnotation(annotation)
self.mapView.showAnnotations([annotation], animated: true)
self.mapView.selectAnnotation(annotation, animated: true)}
}
}
)
mapView.showsCompass = true
mapView.showsTraffic = true
mapView.showsScale = true
locationManager.requestWhenInUseAuthorization()
let status = CLLocationManager.authorizationStatus()
if status == CLAuthorizationStatus.authorizedWhenInUse {
mapView.showsUserLocation = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
public func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView?{
let reuseId = "myPin"
if annotation.isKind(of: MKUserLocation.self) {
return nil
}
var annotationView : MKPinAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
annotationView?.canShowCallout = true
}
let leftView = UIImageView(frame: CGRect(x:0, y:0, width: 53, height: 53))
leftView.image = UIImage(data: restaurant.image! as Data)
annotationView?.leftCalloutAccessoryView = leftView
return annotationView }
@IBAction func directionBtnTapped(_ sender: UIButton) {
guard let placemark = currentPlacemark else {
return
}
let directionRequest = MKDirectionsRequest()
directionRequest.source = MKMapItem.forCurrentLocation()
let destinationPlacemark = MKPlacemark(placemark: placemark)
directionRequest.destination = MKMapItem(placemark : destinationPlacemark)
directionRequest.transportType = MKDirectionsTransportType.automobile
let directions = MKDirections(request: directionRequest)
directions.calculate { (response, error) in
guard let routeResponse = response else {
if let error = error {
print(error)
}
return
}
let route = routeResponse.routes[0]
self.mapView.add(route.polyline, level: MKOverlayLevel.aboveRoads)
self.mapView.setRegion(MKCoordinateRegionForMapRect(route.polyline.boundingMapRect), animated: true)
}
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.lineWidth = 3.0
renderer.strokeColor = UIColor.red
return renderer
}
}
<file_sep>//
// LoanMO+CoreDataProperties.swift
// TestTask
//
// Created by <NAME> on 24/03/2018.
// Copyright © 2018 AppCoda. All rights reserved.
//
//
import Foundation
import CoreData
extension LoanMO {
@nonobjc public class func fetchRequest() -> NSFetchRequest<LoanMO> {
return NSFetchRequest<LoanMO>(entityName: "Loan")
}
@NSManaged public var name: String?
@NSManaged public var loan_amount: Int16
@NSManaged public var use: String?
@NSManaged public var country: String?
}
<file_sep>//
// RestaurantDetailViewController.swift
// FoodApp
//
// Created by <NAME> on 14.04.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import UIKit
import MapKit
class RestaurantDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var locationDetailLabel: UILabel!
@IBOutlet weak var typeDetailLabel: UILabel!
@IBOutlet weak var nameDetailLabel: UILabel!
@IBOutlet weak var restaurantImageView: UIImageView!
@IBOutlet var tableView: UITableView!
@IBOutlet var mapView: MKMapView!
@IBAction func ratingBtnTapped(segue: UIStoryboardSegue){
if let id = segue.identifier{
self.restaurant.isVisited = true
switch id {
case "great":
self.restaurant.raiting = "great"
case "good":
self.restaurant.raiting = "good"
case "dislike":
self.restaurant.raiting = "dislike"
default:
break
}
DataStore.defaultLocalDB.saveContext()
tableView.reloadData()
}
}
var restaurant:RestaurantMO!
@IBAction func close(segue: UIStoryboardSegue){
}
override func viewDidLoad() {
super.viewDidLoad()
self.restaurantImageView.image = UIImage(data: restaurant.image! as Data)
tableView.estimatedRowHeight = 36.0
tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.backgroundColor = UIColor(red: 240.0/255.0,green: 240.0/255.0,blue: 240.0/255.0, alpha: 0.2 )
title = self.restaurant.name
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(showMap))
mapView?.addGestureRecognizer(tapGestureRecognizer)
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(restaurant.location!, completionHandler:{ placemarks, error in
if error != nil{
print(error!)
return
}
if let placemarks = placemarks {
let placemark = placemarks[0]
let annotation = MKPointAnnotation()
if let location = placemark.location{
annotation.coordinate = location.coordinate
self.mapView.addAnnotation(annotation)
let region = MKCoordinateRegionMakeWithDistance(annotation.coordinate , 250, 250)
self.mapView.setRegion(region, animated: false)
}
}
}
)}
func showMap() {
self.performSegue(withIdentifier: "showMap", sender: self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
navigationController?.hidesBarsOnSwipe = false
navigationController?.setNavigationBarHidden(false, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "presentView"{
let destinationContrl = segue.destination as! ReviewViewController
destinationContrl.restaurant = restaurant
}else if segue.identifier == "showMap"{
let destinationContrl = segue.destination as! MapViewController
destinationContrl.restaurant = restaurant
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! RestaurantDetailTableViewCell
switch indexPath.row {
case 0:
cell.fieldLabel.text = NSLocalizedString("Name", comment: "Name Field")
cell.valueLabel.text = restaurant.name
case 1:
cell.fieldLabel.text = NSLocalizedString("Type", comment: "Type Field")
cell.valueLabel.text = restaurant.type
case 2:
cell.fieldLabel.text = NSLocalizedString("Location", comment: "Location/Adress Field")
cell.valueLabel.text = restaurant.location
case 3:
cell.fieldLabel.text = NSLocalizedString("Phone", comment: "Phone Field")
cell.valueLabel.text = restaurant.phone
case 4:
cell.fieldLabel.text = NSLocalizedString("Been there?", comment: "Been there? Field")
cell.valueLabel.text = restaurant.isVisited ?NSLocalizedString("Yes, i've been there before \(self.restaurant.raiting ?? "")", comment: "Yes, i've been there before") : NSLocalizedString("No", comment: "Yes, i've not been there before")
default:
cell.fieldLabel.text = ""
cell.valueLabel.text = ""
}
cell.backgroundColor = UIColor.clear
return cell
}
}
<file_sep>//
// AboutTableTableViewController.swift
// FoodApp
//
// Created by <NAME> on 02.05.17.
// Copyright © 2017 DavydzikInc. All rights reserved.
//
import UIKit
import SafariServices
class AboutTableTableViewController: UITableViewController {
var sectionTitles = ["Leave Feedback" , "Follow us" ]
var sectionContent = [["Rate us on AppStore", "Tell us your feedback"],["Twitter" , "Facebook" , "Pinterest"]]
var links = ["https://twitter.com/appcodamobile","https://facebook.com/appcodamobile", "https://pinterest.com/appcoda/"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionContent[section].count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = sectionContent[indexPath.section][indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0:
if indexPath.row == 0 {
if let url = URL(string:"http://www.apple.com/itunes/charts/paid-apps/") {
UIApplication.shared.open(url)
}}else if indexPath.row == 1 {
performSegue(withIdentifier: "showWebView", sender: self)
print("CLAC")
}
case 1:
if let url = URL(string: links[indexPath.row]) {
let safariVc = SFSafariViewController(url: url)
present(safariVc , animated: true, completion: nil)
}
default:
break
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
<file_sep>//
// APIService.swift
// KivaLoan
//
// Created by <NAME> on 24/03/2018.
//Copyright © 2018 DavydzikInc. All rights reserved.
import Foundation
class APIService : NSObject{
let kivaURL = "https://api.kivaws.org/v1/loans/newest.json"
func getDataWith(completion : @escaping(Result <[[String : AnyObject]]>) -> Void) {
guard let url = URL(string: kivaURL) else {return}
let request = URLRequest.init(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else {return completion(.Error(error!.localizedDescription))}
guard let data = data else{return completion(.Error(error?.localizedDescription ?? "No new data to show!"))}
do {
if let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : AnyObject]{
guard let jsonLoans = jsonResult["loans"] as? [[String : AnyObject]] else{
return completion(.Error(error?.localizedDescription ?? "There are no new Items to show"))
}
DispatchQueue.main.async {
completion(.Success(jsonLoans))
}
}
} catch let error {
completion(.Error(error.localizedDescription))
}
}
task.resume()
}
}
enum Result<T>{
case Success(T)
case Error(String)
}
| 1e811fb2f7c19ac613465c982ddbb59a798eb7c6 | [
"Swift",
"Markdown"
]
| 18 | Swift | daniildavydzik/iOS-test-tasks | a9b7bceb16ec8eed73419a15c5331aa75200c61f | c89939dd4cd19c757865d00736c9386597294d5f |
refs/heads/master | <file_sep>
#include "mbed.h"
#include "uLCD_4DGL.h"
uLCD_4DGL uLCD(D1, D0, D2); // serial tx, serial rx, reset pin;
PwmOut PWM1(D6);
AnalogIn Ain(A0);
int main()
{
uLCD.printf("\n106061255\n");
uLCD.line(30, 30, 40, 30, WHITE);
uLCD.line(40, 30, 40, 40, WHITE);
uLCD.line(40, 40, 30, 40, WHITE);
uLCD.line(30, 40, 30, 30, WHITE);
float i;
while(1){
for( i=0; i<1; i+=0.1 ){
PWM1.period(0.001);
PWM1 = Ain;
wait(0.1);
}
}
}
| cde7e6e6a27dcab9126155ddec4f188bb8c63336 | [
"C++"
]
| 1 | C++ | nicknike0616/exam01 | acadd740768de03b23cb9fac75f5eea81cbd62b1 | 6542b455a5130571447207883d0108fb21729076 |
refs/heads/master | <file_sep>import { RzdPage } from './app.po';
describe('rzd App', () => {
let page: RzdPage;
beforeEach(() => {
page = new RzdPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('Welcome to app!!');
});
});
<file_sep>import {Component, ContentChildren, Input, OnInit, QueryList} from '@angular/core';
import {TabComponent} from './tab/tab.component';
@Component({
selector: 'app-tab-group',
templateUrl: './tab-group.component.html',
styleUrls: ['./tab-group.component.css']
})
export class TabGroupComponent implements OnInit {
@ContentChildren(TabComponent)
tabs: QueryList<TabComponent>;
@Input() selectedIndex = 0;
@Input() switchNextTab: Function;
constructor() {
}
ngOnInit() {
}
selectTab(tab: TabComponent, index: number) {
if (!tab.disabled && this.selectedIndex != index) {
this.tabs.toArray().forEach((varTab) => {
varTab.active = false;
});
if (this.selectedIndex + 1 == index && this.switchNextTab) {
this.switchNextTab();
}
this.selectedIndex = index;
tab.active = true;
}
}
}
<file_sep>/**
* Extend all models from this base model in order to have ability to extends models centralized
*/
export class BaseModel {
id: string;
constructor() {
if (new.target === BaseModel) {
throw new Error(`You shouldn't instantiate a base class. Extend it instead`);
}
}
/*/!**
* Serialize a model
* @returns {string}
*!/
toJson() {
return JSON.stringify(this);
}*/
}
<file_sep>import {Component, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core';
import './rx-js.operators';
import {TabDto} from './models/dto/TabDto';
import {TabFacade} from './services/tab.facade';
import {ItemsComponent} from './items/items.component';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
tabs: TabDto[] = [];
@ViewChild('tabGroup') tabGroup;
@ViewChildren(ItemsComponent)
items: QueryList<ItemsComponent>;
constructor(private tabFacade: TabFacade) {
}
ngOnInit() {
this.tabFacade.getTabs().subscribe(
(tabDtos: TabDto[]) => {
if (tabDtos.length > 0) {
tabDtos[0].disabled = false;
tabDtos[0].active = true;
}
this.tabs = tabDtos;
});
}
switchNextTab = (): void => {
const item = this.items.find((it, i) => {
return i == this.tabGroup.selectedIndex
});
item.onSubmit(this.tabs[this.tabGroup.selectedIndex].id);
};
enableNextTab = (): void => {
if (this.tabs.length > this.tabGroup.selectedIndex + 1) {
this.tabs[this.tabGroup.selectedIndex + 1].disabled = false;
}
};
disableAllNextTabs = (): void => {
this.tabs.forEach(
(tab, index) => {
if (index > this.tabGroup.selectedIndex) {
tab.disabled = true;
}
}
)
}
}
<file_sep>import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {ValueTabService} from './value-tab.service';
@Injectable()
export class ValueTabFacade {
constructor(private valueTabService: ValueTabService) {
}
save(data): Observable<any> {
let observable: Observable<any>;
if (data.id) {
observable = this.valueTabService.update(data);
} else {
observable = this.valueTabService.create(data);
}
return observable;
}
}
<file_sep>import {Tab} from '../Tab';
export class TabDto extends Tab {
disabled = true;
active = false;
}
<file_sep>import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class ValueTabService {
private headers = new Headers({'Content-Type': 'application/json'});
private valueUrl = 'api/value';
constructor(private http: Http) {
}
create(data: any): Observable<any> {
return this.http
.post(this.valueUrl, JSON.stringify(data), {headers: this.headers})
.map((res) => {
return res.json().data;
})
.catch(this.handleError);
}
update(data: any): Observable<any> {
const url = `${this.valueUrl}/${data.id}`;
return this.http
.put(url, JSON.stringify(data), {headers: this.headers})
.map(() => data)
.catch(this.handleError);
}
private handleError(error: any): Observable<any> {
console.error('An error occurred', error);
return Observable.of(error.message || error);
}
}
<file_sep>import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {eValidatorTypes, ItemDto, ValidatorsItem, eType} from '../models/dto/ItemDto';
import {ItemFacade} from '../services/item.facade';
import {ValueTabFacade} from '../services/value-tab.facade';
@Component({
selector: 'app-items-component',
templateUrl: './items.component.html',
styleUrls: ['./items.component.css']
})
export class ItemsComponent implements OnInit {
static PATTERN_DATE = '(((19|20)([2468][048]|[13579][26]|0[48])|2000)[-]02[-]29|((19|20)[0-9]{2}[-](0[4678]|1[02])[-](0[1-9]|[12][0-9]|30)|(19|20)[0-9]{2}[-](0[1359]|11)[-](0[1-9]|[12][0-9]|3[01])|(19|20)[0-9]{2}[-]02[-](0[1-9]|1[0-9]|2[0-8])))';
get patternDate() {
return ItemsComponent.PATTERN_DATE
}
eType = eType;
@Input() tabId: string;
items: ItemDto[] = [];
tabForm: FormGroup;
formErrors: any = {};
@Input() enableNextTab: Function;
@Input() disableAllNextTabs: Function;
validationMessages = {
[eValidatorTypes[eValidatorTypes.required]]: 'Обязательное поле.',
[eValidatorTypes[eValidatorTypes.minlength]]: 'Значение должно быть не менее minlength символов.',
[eValidatorTypes[eValidatorTypes.maxlength]]: 'Значение не должно быть больше maxlength символов.',
[eValidatorTypes[eValidatorTypes.min]]: 'Значение должно быть не меньше min.',
[eValidatorTypes[eValidatorTypes.max]]: 'Значение не должно быть больше max.',
[eValidatorTypes[eValidatorTypes.pattern]]: 'Значение не соответствует указаннаму шаблону.',
};
constructor(private fb: FormBuilder,
private itemFacade: ItemFacade,
private valueTabFacade: ValueTabFacade) {
}
ngOnInit() {
this.itemFacade.getItems(this.tabId).subscribe(
(items) => {
this.items = items;
this.createFormControl();
}
);
}
createFormControl() {
const optionsFormGroup = {};
this.items.forEach((item) => {
this.formErrors[item.id] = '';
const validatorsForm: any[] = [];
item.validators.forEach(
(valid: ValidatorsItem) => {
switch (valid.type) {
case eValidatorTypes.required:
validatorsForm.push(Validators.required);
break;
case eValidatorTypes.requiredTrue:
validatorsForm.push(Validators.requiredTrue);
break;
case eValidatorTypes.max:
if (item.type == eType.number && +valid.value) {
validatorsForm.push(Validators.max(+valid.value));
}
if ((item.type == eType.text || item.type == eType.textarea) && +valid.value) {
validatorsForm.push(Validators.maxLength(+valid.value));
}
break;
case eValidatorTypes.maxlength:
validatorsForm.push(Validators.maxLength(+valid.value));
break;
case eValidatorTypes.min:
validatorsForm.push(Validators.min(+valid.value));
break;
case eValidatorTypes.minlength:
validatorsForm.push(Validators.minLength(+valid.value));
break;
case eValidatorTypes.pattern:
validatorsForm.push(Validators.pattern(valid.value));
break;
}
}
);
optionsFormGroup[item.id] = new FormControl('', validatorsForm);
});
this.tabForm = this.fb.group(optionsFormGroup);
this.tabForm.valueChanges.subscribe(
(data) => {
this.onValueChange(data);
});
this.onValueChange();
}
onValueChange(data?) {
if (!this.tabForm) {
return;
}
const form = this.tabForm;
for (const field in this.formErrors) {
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
for (const key in control.errors) {
let messErrors;
switch (key) {
case eValidatorTypes[eValidatorTypes.maxlength]:
case eValidatorTypes[eValidatorTypes.minlength]:
messErrors = this.validationMessages[key].replace(key, control.errors[key].requiredLength);
break;
case eValidatorTypes[eValidatorTypes.max]:
case eValidatorTypes[eValidatorTypes.min]:
messErrors = this.validationMessages[key].replace(key, control.errors[key][key]);
break;
default:
messErrors = this.validationMessages[key];
break;
}
this.formErrors[field] += messErrors ? messErrors : '' + '\n ';
}
}
}
if (form.dirty && form.valid) {
this.enableNextTab();
} else {
this.disableAllNextTabs();
}
}
onSubmit(id?) {
const data = {...this.tabForm.value};
if (id) {
data.id = id;
}
return this.valueTabFacade.save(data).subscribe(
(val) => {
console.log(val);
}
);
}
}
<file_sep>import {BaseModel} from './base-model';
export class Tab extends BaseModel {
title: string;
constructor(id, title) {
super();
this.id = id;
this.title = title;
}
}
<file_sep>import {InMemoryDbService} from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const tabs = [
{id: 1, title: 'Основные данные'},
{id: 2, title: 'Паспортные данные'},
{id: 3, title: 'Личные данные'},
{id: 4, title: 'Дополнительная инфомация'}
];
const items = [
{
id: '1_1', tabId: '1', lable: 'Имя', type: 'text',
validators: [{type: 'required'},
{type: 'pattern', value: '[а-яА-ЯёЁa-zA-Z]+$'}
]
},
{
id: '1_2', tabId: '1', lable: 'Фамилия', type: 'text',
validators: [{type: 'required'},
{type: 'pattern', value: '[а-яА-ЯёЁa-zA-Z]+$'}
]
},
{
id: '1_3', tabId: '1', lable: 'Отчество', type: 'text',
validators: [{type: 'pattern', value: '[а-яА-ЯёЁa-zA-Z]+$'}]
},
{
id: '1_4', tabId: '1', lable: 'Дата рождения', type: 'date',
validators: [{type: 'required'}]
},
{
id: '1_5', tabId: '1', lable: 'Адрес', type: 'textarea',
},
{
id: '1_6', tabId: '1', lable: 'Я даю согласие на обработку персональных данных', type: 'boolean',
validators: [{type: 'requiredTrue'}]
},
{
id: '2_1', tabId: '2', lable: 'Серия', type: 'text',
validators: [
{type: 'required'},
{type: 'pattern', value: '\\d{4}'}
]
},
{
id: '2_2', tabId: '2', lable: 'Номер', type: 'text',
validators: [
{type: 'required'},
{type: 'pattern', value: '\\d{6}'}
]
},
{
id: '2_3', tabId: '2', lable: 'Дата выдачи', type: 'date',
validators: [{type: 'required'}]
},
{
id: '2_4', tabId: '2', lable: 'Код подразделения', type: 'text',
validators: [
{type: 'required'},
{type: 'pattern', value: '\\d{6}'}
]
},
{
id: '2_5', tabId: '2', lable: 'Кем выдан', type: 'textarea',
validators: [
{type: 'required'}
]
},
{
id: '3_1', tabId: '3', lable: 'Номер телефона', type: 'text',
validators: [{type: 'pattern', value: '\\d{11}'}]
},
{
id: '3_2', tabId: '3', lable: 'email', type: 'text',
validators: [{type: 'pattern', value: '[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}'}]
},
{
id: '4_1', tabId: '4', lable: 'Дополнительная информация', type: 'textarea',
}
];
const value = [{id: 1}];
return {tabs, items, value};
}
}
<file_sep>import {Injectable} from '@angular/core';
import {ItemService} from './item.service';
import {Observable} from 'rxjs/Observable';
import {eType, eValidatorTypes, ItemDto} from '../models/dto/ItemDto';
import {Item} from '../models/Item';
@Injectable()
export class ItemFacade {
constructor(private itemService: ItemService) {
}
getItems(tabId: string): Observable<ItemDto[]> {
return this.itemService.getItems(tabId).map(
(items: Item[]) => {
const itemDtos = items.map((item) => {
let validators = null;
if (item.validators) {
validators = item.validators.map((val) => {
return {type: eValidatorTypes[val.type], value: val.value}
});
}
return new ItemDto(item.id, item.tabId, item.lable, eType[item.type], validators);
});
return itemDtos;
}
)
}
}
<file_sep>import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {TabService} from './tab.service';
import {Tab} from '../models/tab';
import {TabDto} from '../models/dto/TabDto';
@Injectable()
export class TabFacade {
constructor(private tabService: TabService) {
}
getTabs(): Observable<TabDto[]> {
return this.tabService.getTabs().map(
(tabs: Tab[]) => {
return tabs.map(tab => tab as TabDto);
}
)
}
}
<file_sep>import { Injectable } from '@angular/core';
import {Http, RequestOptions, Response, URLSearchParams} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import {Item} from '../models/Item';
@Injectable()
export class ItemService {
private itemsUrl = 'api/items';
constructor(private http: Http) { }
getItems(tabId: string): Observable<Item[]> {
const params: URLSearchParams = new URLSearchParams();
params.set('tabId', tabId);
const options: RequestOptions = new RequestOptions({params: params});
return this.http.get(this.itemsUrl, options).map(
(response: Response) => {
return response.json().data as Item[];
}
).catch(this.handleError);
}
private handleError(error: any): Observable<any> {
console.error('An error occurred', error);
return Observable.of(error.message || error);
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {TabGroupComponent} from './components/tabs/tab-group.component';
import { TabComponent } from './components/tabs/tab/tab.component';
import {InMemoryDataService} from './services/mock/in-memory-data.service';
import {InMemoryWebApiModule} from 'angular-in-memory-web-api';
import {TabService} from './services/tab.service';
import {HttpModule} from '@angular/http';
import {TabFacade} from './services/tab.facade';
import {ItemsComponent} from './items/items.component';
import {ReactiveFormsModule} from '@angular/forms';
import {ItemService} from './services/item.service';
import {ItemFacade} from './services/item.facade';
import {ValueTabFacade} from './services/value-tab.facade';
import {ValueTabService} from './services/value-tab.service';
@NgModule({
declarations: [
AppComponent,
TabGroupComponent,
TabComponent,
ItemsComponent
],
imports: [
BrowserModule,
HttpModule,
ReactiveFormsModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
],
providers: [
TabService,
TabFacade,
ItemService,
ItemFacade,
ValueTabService,
ValueTabFacade
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import {BaseModel} from '../base-model';
export interface ValidatorsItem {
type: eValidatorTypes,
value: string
}
export class ItemDto extends BaseModel {
tabId: string;
lable: string;
type: eType;
value: any;
validators: ValidatorsItem[] = [];
constructor(id: string, tabId: string, lable: string, type: eType, validators?: ValidatorsItem[]) {
super();
this.id = id;
this.tabId = tabId;
this.lable = lable;
this.type = type;
if (validators) {
this.validators = validators;
}
}
}
export enum eType {
number,
text,
textarea,
boolean,
date
}
export enum eValidatorTypes {
required,
min,
minlength,
max,
maxlength,
pattern,
requiredTrue
}
<file_sep>import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Tab} from '../models/Tab';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class TabService {
private tabsUrl = 'api/tabs';
constructor(private http: Http) { }
getTabs(): Observable<Tab[]> {
return this.http.get(this.tabsUrl).map(
(response: Response) => {
return response.json().data as Tab[];
}
).catch(this.handleError);
}
private handleError(error: any): Observable<any> {
console.error('An error occurred', error);
return Observable.of(error.message || error);
}
}
<file_sep>import {BaseModel} from './base-model';
export class Item extends BaseModel {
tabId: string;
lable: string;
type: string;
value: any;
validators: {type, value}[]
}
| a8083ef0ce28165178c99daf480a27e66b7eed8b | [
"TypeScript"
]
| 17 | TypeScript | RaskinaLubov/rzd | a76abc14a2c9acc0b77cb817ef5dcc0803e336da | f91650048267156e895d3bbfa381098a57b06a88 |
refs/heads/master | <repo_name>akuramshin/shopify-backend-challenge<file_sep>/tests/functional/test_search.py
"""
This file contains the functional tests for the 'search' blueprint.
These tests use GETs and POSTs to different URLs to check for the proper behavior.
"""
def test_text_search(test_client, init_database):
"""
GIVEN a testing client
WHEN the '/api/search-text' page is accessed with POST request
THEN check that we are shown correct search result
"""
search = dict(search='cat')
response = test_client.post('/api/search-text', data=search, follow_redirects=True)
assert response.status_code == 200
assert b'cat' in response.data
search = dict(search='duck')
response = test_client.post('/api/search-text', data=search, follow_redirects=True)
assert response.status_code == 200
assert b'No images found that match your search' in response.data
search = dict(search='all')
response = test_client.post('/api/search-text', data=search, follow_redirects=True)
assert response.status_code == 200
assert b'dog' in response.data
assert b'cat' in response.data
def test_image_search(test_client, init_database):
"""
GIVEN a testing client
WHEN the '/api/search-image' page is accessed with POST request
THEN check that we are shown correct search result
"""
files = dict(file=open('tests/functional/dog2.jpg', 'rb'))
response = test_client.post('/api/search-image', data=files, follow_redirects=True)
assert response.status_code == 200
assert b'dog' in response.data
files = dict(file=open('tests/functional/teddy.jpg', 'rb'))
response = test_client.post('/api/search-image', data=files, follow_redirects=True)
assert response.status_code == 200
assert b'No images found that match your search' in response.data
<file_sep>/README.md
# Smart Image Database
Image database that automatically labels uploaded images using a machine learning model for keyword image search.
## Get started
In order to run the API locally, you need the Python 3.x.x with the following dependencies installed:
* flask
* SQLAlchemy
* tensorflow
* OpenCV
* Keras
* imageAI
* pytest
You can use the package manager [pip](https://pip.pypa.io/en/stable/) to install the dependencies:
```bash
pip install Flask
pip install Flask-SQLAlchemy
pip install tensorflow
pip install opencv-python
pip install keras
pip install imageAI
pip install pytest
```
I was interested in implementing image search myself so I developed it from scratch. The library [**flask_image_search**](https://pypi.org/project/flask-image-search/) is an already made solution that works with flask. It is smarter to use already existing libraries if they match your use case.
## Usage
While in the main directory (`smart-image-search`), run the command `flask run` to start the flask application. It might take a bit for the application to start as it is creating the database and loading in the object detection model (ignore the warnings if you don't have a GPU set up on your machine).
Once the application is running, you can head over to the webpage [http://127.0.0.1:5000/](http://127.0.0.1:5000/).
There are two main functionalities: **upload** and **search**.
For [upload](http://127.0.0.1:5000/upload), you can drag and drop your image(s) into the drop-zone for them to be uploaded. The backend runs object detection to categorize each image with two tags (highest probability objects detected). The image files are saved in the file system along with a corresponding entry in the database.
For [search](http://12172.16.58.3:5000/search), there are two options, search using text or an image:
* Text search is looking for tag keywords such as "person" or "car". If you want to list all images, enter "all" into the text search.
* Image search looks for semantically similar images by comparing the query image tags with tags of images in the database.
For each image in the search result, its tags are listed and you can click on each image to get a closer look.
## Testing
I decided to use the `pytest` tool for testing. Pytest's fixtures make it easier to create multiple tests that require the same initial state.
I have split my tests into the unit and functional categories. Each test is accompanied by a description following the Given-When-Then style.
While in the main directory (`smart-image-search`), enter the command `python -m pytest` to run the tests.
## Security
Data submitted by users should never be trusted, so there are several checks we should perform.
1. A file with a virus or other malicious software might be uploaded where we expect an image.
2. directory traversal attacks via filenames.
3. A file size attack might cause our application to overload or fail.
Although I have included checks for (2) and (3) there are great security libraries like [**Werkzeug**](https://pypi.org/project/Werkzeug/) that can further check filenames. For (1) we can create a check that makes sure that the files we are receiving indeed image files via checking the file header.
## Further Improvement
Some things I would implement for a more polished version of this project.
* **Problem**: Currently files are saved on the server using the filename of the uploaded image. If an image is uploaded with the same filename as an existing image, it will not be saved.
* **Solution**: Ignore client-provided filenames and generate
our own filenames when saving images. This can be done if we
have some user system.
* Currently search via image works through image tags; semantic similarity. Another approach is to look at literal similarity by comparing pixel values
<file_sep>/tests/conftest.py
import pytest
from project import create_app, db
from project.models import Image
"""
This file contains the fixtures that define some initial testing state.
"""
@pytest.fixture(scope='module')
def new_image():
image = Image('dog.jpg', 'dog', 'cat')
return image
@pytest.fixture(scope='module')
def test_client():
app = create_app()
with app.test_client() as testing_client:
with app.app_context():
yield testing_client
@pytest.fixture(scope='module')
def init_database(test_client):
db.create_all()
image1 = Image('dog.jpg', 'dog', 'car')
image2 = Image('cat.jpg', 'cat', 'None')
db.session.add(image1)
db.session.add(image2)
db.session.commit()
yield
db.drop_all()
<file_sep>/tests/functional/test_upload.py
from project.models import Image
"""
This file contains the functional tests for the 'upload' blueprint.
These tests use GETs and POSTs to different URLs to check for the proper behavior.
"""
def test_home_page(test_client):
"""
GIVEN a testing client
WHEN the '/' (home) page is accessed with GET request
THEN check that we are directed to the upload page
"""
response = test_client.get('/')
assert response.status_code == 200
assert b"Upload Images" in response.data
def test_upload_image(test_client, init_database):
"""
GIVEN a testing client
WHEN the '/api/uploadImages' page recieves a POST request
THEN check that we recieve a valid response and the database is updated
"""
files = dict(file=open('tests/functional/dog2.jpg', 'rb'))
response = test_client.post('/api/uploadImages', data=files, follow_redirects=True)
assert response.status_code == 200
assert Image.query.filter(Image.file_name =='dog2.jpg').first() is not None
<file_sep>/tests/unit/test_models.py
from project.models import Image
"""
This file (models.py) contains the unit tests for the data models.
"""
def test_new_user(new_image):
"""
GIVEN a Image model
WHEN a new Image is uploaded
THEN check that the filename and the tag fields are defined correctly
"""
assert new_image.file_name == 'dog.jpg'
assert new_image.item_primary == 'dog'
assert new_image.item_secondary == 'cat'<file_sep>/project/models.py
from project import db
class Image(db.Model):
__tablename__ = 'images'
id = db.Column(db.Integer,primary_key=True)
file_name = db.Column(db.Text)
item_primary = db.Column(db.String(100))
item_secondary = db.Column(db.String(100))
def __init__(self, file_name, primary, secondary):
self.file_name = file_name
self.item_primary = primary
self.item_secondary = secondary
def add_image(file_name, primary, secondary):
image = Image(file_name, primary, secondary)
db.session.add(image)
db.session.commit()<file_sep>/project/shared/detector.py
from imageai.Detection import ObjectDetection
from imageai.Classification import ImageClassification
class Detector:
def __init__(self, model_path, speed):
self.detector = ObjectDetection()
self.detector.setModelTypeAsTinyYOLOv3()
self.detector.setModelPath(model_path)
self.detector.loadModel(detection_speed=speed)
# Run object detection and return the two tags with highest probability.
# In the case of no objects detected, tag="None"
def detect(self, input_path):
_, detection = self.detector.detectObjectsFromImage(input_image=input_path, output_type="array", minimum_percentage_probability=30)
detection = sorted(detection, key=lambda item: item["percentage_probability"], reverse=True)
objects = []
for eachItem in detection:
if eachItem["name"] not in objects:
objects.append(eachItem["name"])
if len(objects) == 2: break
while len(objects) != 2:
objects.append("None")
return objects
<file_sep>/project/shared/utils.py
from ..models import Image
from flask import current_app
import os
from project import dt
import ntpath
# Extract the filename in the case that the uploaded filename is in file path form (e.g. '/a/b/c/dog.jpg)
def get_filename(file):
return ntpath.basename(file.filename)
# Given search tags, query our database to see if any images match
def tag_search(primary, secondary=None):
images = None
if primary == "all":
images = Image.query.all()
elif primary == "None":
return images
else:
if secondary is None or secondary == "None":
images = Image.query.filter((Image.item_primary == primary) | (Image.item_secondary == primary)).all()
else:
images = Image.query.filter((Image.item_primary == primary) | (Image.item_secondary == primary) |
(Image.item_primary == secondary) | (Image.item_secondary == secondary)).all()
return images
def analyze_image(file):
filename = get_filename(file)
# Check filename extension to be valid
if filename != '':
extension = os.path.splitext(filename)[1]
if extension not in current_app.config['EXTENSIONS']:
return False
# Save the image to the file system and run object detection
file.save(os.path.join(current_app.config['UPLOAD_PATH'], filename))
objects = dt.detect(os.path.join(current_app.config['UPLOAD_PATH'], filename))
return [objects[0], objects[1]]<file_sep>/project/__init__.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from .shared.detector import Detector
db = SQLAlchemy()
dt = Detector(model_path="project/models/yolo-tiny.h5", speed="fastest")
# Application factory
def create_app():
app = Flask(__name__)
# Project configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///images.db'
app.config['EXTENSIONS'] = ['.jpg', '.png'] # Accepted image file extensions
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024 * 2 # Accept image files of max size 2 MB
app.config['UPLOAD_PATH'] = 'project/static/input' # Path to folder where images are saved
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
from project.Blueprints.search import search_blueprint
from project.Blueprints.upload import upload_blueprint
app.register_blueprint(upload_blueprint)
app.register_blueprint(search_blueprint)
return app
<file_sep>/project/Blueprints/search.py
from flask import render_template, request, Blueprint, redirect, url_for, abort
from ..shared.utils import tag_search, analyze_image
from ..models import Image
search_blueprint = Blueprint('search_blueprint', __name__, template_folder='templates')
@search_blueprint.route('/search')
def search():
return render_template('search.html')
# Check if the POSTed text query matches any of the images in our database
@search_blueprint.route('/api/search-text', methods=['POST'])
def api_search_text():
search = request.form['search'].lower()
images = tag_search(search)
if images:
return render_template('search.html', results=images)
else:
return redirect(url_for('search_blueprint.search'))
# Detect the tags of the query image and check if they match any of the images in our database
@search_blueprint.route('/api/search-image', methods=['POST'])
def api_search_image():
file = request.files['file']
tags = analyze_image(file)
if tags:
images = tag_search(tags[0], tags[1])
if images:
return render_template('search.html', results=images)
else:
return redirect(url_for('search_blueprint.search'))
# Given the unique id of the image in our database, display that image with full resolution
@search_blueprint.route('/view/<image_id>')
def view_image(image_id):
image = Image.query.filter(Image.id == image_id).first()
return render_template('view.html', image=image)
<file_sep>/app.py
from project import create_app, db
app = create_app()
with app.app_context():
db.create_all()
db.session.commit()<file_sep>/project/Blueprints/upload.py
from flask import render_template, request, Blueprint, redirect, url_for, abort
from ..shared.utils import analyze_image, get_filename
from ..models import Image, add_image
upload_blueprint = Blueprint('upload_blueprint', __name__, template_folder='templates')
@upload_blueprint.route('/')
@upload_blueprint.route('/upload')
def upload():
return render_template('upload.html')
# Given a POSTed image:
# 1. Check if the file is safe
# 2. Save the image in the file system
# 3. Add an entry into the database with the filename and tags
@upload_blueprint.route('/api/uploadImages', methods=['POST'])
def api_upload():
file = request.files['file']
filename = get_filename(file)
tags = analyze_image(file)
if not tags:
abort(400)
else:
add_image(filename, tags[0], tags[1])
return redirect(url_for('upload_blueprint.upload')) | 869d8fedb27aef777c1038221cfb2faac2fdc0bd | [
"Markdown",
"Python"
]
| 12 | Python | akuramshin/shopify-backend-challenge | d52bf1f61378048b31a978bd4d5dd808b25c288e | bcd48fc517549b4728021d8381a0c19001fa9de0 |
refs/heads/master | <file_sep>/*
* Copyright (c) 2019 <NAME>.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by arman on 10/10/2019.
*/
package com.adyen.checkout.example.data.api.model.paymentsRequest
import com.adyen.checkout.base.model.payments.Amount
@Suppress("MagicNumber")
data class PaymentMethodsRequest(
val merchantAccount: String,
val shopperReference: String,
// val additionalData: Any,
// val allowedPaymentMethods: ArrayList<String>,
val amount: Amount,
// val blockedPaymentMethods: ArrayList<String>,
val countryCode: String = "NL",
val shopperLocale: String = "en_US",
val channel: String = "android"
)
<file_sep>/*
* Copyright (c) 2019 <NAME>.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by arman on 10/10/2019.
*/
package com.adyen.checkout.example.service
import com.adyen.checkout.base.model.payments.Amount
import com.adyen.checkout.core.log.LogUtil
import com.adyen.checkout.core.log.Logger
import com.adyen.checkout.core.model.JsonUtils
import com.adyen.checkout.dropin.service.CallResult
import com.adyen.checkout.dropin.service.DropInService
import com.adyen.checkout.example.data.api.model.paymentsRequest.AdditionalData
import com.adyen.checkout.example.data.storage.KeyValueStorage
import com.adyen.checkout.example.repositories.paymentMethods.PaymentsRepository
import com.adyen.checkout.redirect.RedirectComponent
import com.google.gson.Gson
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.ResponseBody
import org.json.JSONObject
import org.koin.android.ext.android.inject
import retrofit2.Call
import java.io.IOException
/**
* This is just an example on how to make networkModule calls on the [DropInService].
* You should make the calls to your own servers and have additional data or processing if necessary.
*/
class ExampleDropInService : DropInService() {
companion object {
private val TAG = LogUtil.getTag()
private val CONTENT_TYPE: MediaType = "application/json".toMediaType()
}
private val paymentsRepository: PaymentsRepository by inject()
private val keyValueStorage: KeyValueStorage by inject()
override fun makePaymentsCall(paymentComponentData: JSONObject): CallResult {
Logger.d(TAG, "makePaymentsCall")
// Check out the documentation of this method on the parent DropInService class
val paymentRequest = createPaymentRequest(
paymentComponentData,
keyValueStorage.getShopperReference(),
keyValueStorage.getAmount(),
keyValueStorage.getMerchantAccount(),
RedirectComponent.getReturnUrl(applicationContext),
AdditionalData(
allow3DS2 = keyValueStorage.isThreeds2Enable().toString(),
executeThreeD = keyValueStorage.isExecuteThreeD().toString()
)
)
Logger.v(TAG, "paymentComponentData - ${JsonUtils.indent(paymentComponentData)}")
val requestBody = paymentRequest.toString().toRequestBody(CONTENT_TYPE)
val call = paymentsRepository.paymentsRequest(requestBody)
return handleResponse(call)
}
override fun makeDetailsCall(actionComponentData: JSONObject): CallResult {
Logger.d(TAG, "makeDetailsCall")
Logger.v(TAG, "payments/details/ - ${JsonUtils.indent(actionComponentData)}")
val requestBody = actionComponentData.toString().toRequestBody(CONTENT_TYPE)
val call = paymentsRepository.detailsRequest(requestBody)
return handleResponse(call)
}
@Suppress("NestedBlockDepth")
private fun handleResponse(call: Call<ResponseBody>): CallResult {
return try {
val response = call.execute()
val byteArray = response.errorBody()?.bytes()
if (byteArray != null) {
Logger.e(TAG, "errorBody - ${String(byteArray)}")
}
if (response.isSuccessful) {
val detailsResponse = JSONObject(response.body()?.string())
if (detailsResponse.has("action")) {
CallResult(CallResult.ResultType.ACTION, detailsResponse.get("action").toString())
} else {
Logger.d(TAG, "Final result - ${JsonUtils.indent(detailsResponse)}")
var content = "EMPTY"
if (detailsResponse.has("resultCode")) {
content = detailsResponse.get("resultCode").toString()
}
CallResult(CallResult.ResultType.FINISHED, content)
}
} else {
Logger.e(TAG, "FAILED - ${response.message()}")
CallResult(CallResult.ResultType.ERROR, "IOException")
}
} catch (e: IOException) {
Logger.e(TAG, "IOException", e)
CallResult(CallResult.ResultType.ERROR, "IOException")
}
}
@Suppress("LongParameterList")
private fun createPaymentRequest(
paymentComponentData: JSONObject,
shopperReference: String,
amount: Amount,
merchantAccount: String,
redirectUrl: String,
additionalData: AdditionalData
): JSONObject {
val request = JSONObject()
request.putOpt("paymentMethod", paymentComponentData.getJSONObject("paymentMethod"))
request.put("shopperReference", shopperReference)
request.put("storePaymentMethod", paymentComponentData.getBoolean("storePaymentMethod"))
request.put("amount", JSONObject(Gson().toJson(amount)))
request.put("merchantAccount", merchantAccount)
request.put("returnUrl", redirectUrl)
request.put("reference", "android-test-components")
request.put("channel", "android")
request.put("additionalData", JSONObject(Gson().toJson(additionalData)))
return request
}
}
| 06e32fe9ae759de644b6f4b4d71dd2ed35eeed03 | [
"Kotlin"
]
| 2 | Kotlin | JonSmart/adyen-android | b081948afc3175ebf8d1256c415ad67b4a300215 | 232b22b814959ffd41457eb570e3a5ac744a8a1a |
refs/heads/master | <file_sep>git status
git add .
git commit -m "remove container commands"
git push --force origin master
<file_sep># compose-build
Examples for "Managing Image with Docker Compose" Lesson
<file_sep>#! /bin/bash
# Create 'admin' User
echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', '<EMAIL>', 'admin')" | python manage.py shell
| c63abf31afd02a17b32bda04e9daa1fd7202ccb9 | [
"Markdown",
"Shell"
]
| 3 | Shell | datasciencedotuniversity/multi-container | fcc2e89475c4652deb4a9f2fce66a61ae63c7c12 | 88103204e303a83191566efc8750194ae5c99cf3 |
refs/heads/source | <repo_name>death-of-rats/death-of-rats.github.io<file_sep>/newpost.sh
#!/bin/bash
if [ -z ${1+"def"} ]; then
echo "Usage:"
echo "$0 <name of post file without extension>"
else
echo "creating post with title $1"
cd "${0%/*}"
cd posts
python3 -m nikola new_post -f markdown -s $1.md
fi
<file_sep>/code4posts/bootloader-read-disk-parameters/Makefile
all: os03.bin
os03.bin: os03.S
yasm -f bin -o os03.bin os03.S
run: os03.bin
qemu-system-i386 -drive format=raw,file=os03.bin
debug: os03.bin
qemu-system-i386 -S -gdb tcp::8000 -drive format=raw,file=os03.bin &
gdb \
-ix gdb_init_real_mode.txt \
-ex 'target remote localhost:8000' \
-ex 'break *0x7c00' \
-ex 'continue'
clean:
rm -rf os03.bin
<file_sep>/code4posts/format-string-attack/buggy.c
#include "stdio.h"
#include "string.h"
void win() {
printf("==============WIN===============\n");
printf(" OK, you win!\n");
printf("==============WIN===============\n");
}
int main() {
char name[512];
char msg[512];
char task[512];
int decision = 0;
strcpy(msg, "Welcome %s!...\n");
printf("Give me your name:\n");
scanf("%s", name);
printf(msg, name);
printf("Now tell me what to do:\n");
scanf("%s", task);
printf("OK! I am on it.\n -------ToDo-------\n");
printf(task);
printf("\n -------ToDo-------\n");
if(decision)
win();
return 0;
}<file_sep>/preview.sh
#!/bin/bash
python3 -m nikola auto -b
<file_sep>/code4posts/format-string-attack/buggy_exploit2.py
from binascii import hexlify
from pwn import *
p = process('./buggy')
gdb.attach(p)
print(p.readline())
name = 512*'A'+'__%p__'
p.sendline(name)
line = p.readline()
print(line)
address = line.split(b'__')[1]
print(f"address: {address}")
addr = int(address, 16)
addr += 0x610 + 0x8
winAddr = 0x76a
print(f"address for ret: {hex(addr)}")
payload = b'AAAAAAAA%136$lx%139$hhn=' + p64(addr)
print(hexlify(payload))
p.sendline(payload)
print(p.recv())
<file_sep>/code4posts/format-string-attack/buggy_exploit.py
from binascii import hexlify
from pwn import *
p = process('./buggy')
#gdb.attach(p)
print(p.readline())
name = 512*'A'+'__%p__'
p.sendline(name)
line = p.readline()
print(line)
address = line.split(b'__')[1]
print(f"address: {address}")
addr = int(address, 16)
addr -= 4
print(f"address of boolean: {hex(addr)}")
payload = b'AAAAAAAA-%138$n-' + p64(addr)
p.sendline(payload)
print(p.recv())
<file_sep>/code4posts/yasm-libc-echo/Makefile
all: prog
prog: asm01.o
ld -dynamic-linker /lib64/ld-linux-x86-64.so.2 -lc -o asm01 asm01.o
asm01.o: asm01.s
yasm -f elf64 -g dwarf2 asm01.s
clean:
rm -rf asm01.o
rm -rf asm01
<file_sep>/code4posts/format-string-attack/example.c
#include "stdio.h"
int main() {
int addr = 0x0806cd41;
char buf[10] = "DEADBEEF";
int wordCount;
printf("Starting at address %#010x we search for %s.%n\n",
addr, buf, &wordCount);
printf("That message contains %2$d chars, and address %1$#010x.\n",
addr, wordCount);
return 0;
} | 1057183e94b5ea7c06c9b46f220ead026840c807 | [
"C",
"Python",
"Makefile",
"Shell"
]
| 8 | Shell | death-of-rats/death-of-rats.github.io | 74d1d376ac152a5f52ff49c6c76a27128f1787b9 | 7df56c1a23a13b0d5a7364ded9c9db5b942eb3e2 |
refs/heads/master | <repo_name>KolobokLesnoi/NewsPaper<file_sep>/app/src/main/java/koloboklesnoi/newspaper/database/DatabaseManager.java
package koloboklesnoi.newspaper.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseManager extends SQLiteOpenHelper {
public static final String TABLE_NAME = "ARTICLES";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SECTION = "SECTION";
public static final String COLUMN_TITLE = "TITLE";
public static final String COLUMN_ABSTRACT = "ABSTRACT";
public static final String COLUMN_PHOTO = "PHOTO";
public static final String COLUMN_PUBLISH_DATE = "PUBLISH_DATE";
public static final String COLUMN_SOURCE = "SOURCE";
private static final int DATABASE_VERSION = 1;
public DatabaseManager(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "
+ "ARTICLES "
+ "(" + COLUMN_ID + " INTEGER, "
+ COLUMN_SECTION + " TEXT, "
+ COLUMN_TITLE + " TEXT, "
+ COLUMN_ABSTRACT + " TEXT, "
+ COLUMN_PHOTO + " TEXT, "
+ COLUMN_PUBLISH_DATE + " TEXT, "
+ COLUMN_SOURCE + " TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
<file_sep>/app/src/main/java/koloboklesnoi/newspaper/api/gson/converter/MediumGsonConverter.java
package koloboklesnoi.newspaper.api.gson.converter;
import com.google.gson.*;
import koloboklesnoi.newspaper.model.MediaMetadatum;
import koloboklesnoi.newspaper.model.Medium;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
public class MediumGsonConverter implements JsonDeserializer<Medium> {
@Override
public Medium deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Medium medium = new Medium();
JsonObject jsonObject = json.getAsJsonObject();
MediaMetadatum[] mediaMetadata = context
.deserialize(jsonObject.get("media-metadata"),MediaMetadatum[].class);
medium.setMediaMetadata(new ArrayList<MediaMetadatum>(Arrays.asList(mediaMetadata)));
return medium;
}
}
<file_sep>/app/src/main/java/koloboklesnoi/newspaper/model/Result.java
package koloboklesnoi.newspaper.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Result implements Parcelable{
@SerializedName("url")
@Expose
private String url;
@SerializedName("adx_keywords")
@Expose
private String adxKeywords;
@SerializedName("subsection")
@Expose
private String subsection;
@SerializedName("share_count")
@Expose
private long shareCount;
@SerializedName("count_type")
@Expose
private String countType;
@SerializedName("column")
@Expose
private String column;
@SerializedName("eta_id")
@Expose
private long etaId;
@SerializedName("section")
@Expose
private String section;
@SerializedName("id")
@Expose
private long id;
@SerializedName("asset_id")
@Expose
private long assetId;
@SerializedName("nytdsection")
@Expose
private String nytdsection;
@SerializedName("byline")
@Expose
private String byline;
@SerializedName("type")
@Expose
private String type;
@SerializedName("title")
@Expose
private String title;
@SerializedName("abstract")
@Expose
private String _abstract;
@SerializedName("published_date")
@Expose
private String publishedDate;
@SerializedName("source")
@Expose
private String source;
@SerializedName("updated")
@Expose
private String updated;
@SerializedName("des_facet")
@Expose
private List<String> desFacet = null;
@SerializedName("org_facet")
@Expose
private List<String> orgFacet = null;
@SerializedName("per_facet")
@Expose
private List<String> perFacet = null;
@SerializedName("geo_facet")
@Expose
private List<String> geoFacet = null;
@SerializedName("media")
@Expose
private List<Medium> media = null;
@SerializedName("uri")
@Expose
private String uri;
// Вспомогательные поля
private String photoURL = null;
private boolean favorites = false;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAdxKeywords() {
return adxKeywords;
}
public void setAdxKeywords(String adxKeywords) {
this.adxKeywords = adxKeywords;
}
public String getSubsection() {
return subsection;
}
public void setSubsection(String subsection) {
this.subsection = subsection;
}
public long getShareCount() {
return shareCount;
}
public void setShareCount(long shareCount) {
this.shareCount = shareCount;
}
public String getCountType() {
return countType;
}
public void setCountType(String countType) {
this.countType = countType;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
public long getEtaId() {
return etaId;
}
public void setEtaId(long etaId) {
this.etaId = etaId;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getAssetId() {
return assetId;
}
public void setAssetId(long assetId) {
this.assetId = assetId;
}
public String getNytdsection() {
return nytdsection;
}
public void setNytdsection(String nytdsection) {
this.nytdsection = nytdsection;
}
public String getByline() {
return byline;
}
public void setByline(String byline) {
this.byline = byline;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAbstract() {
return _abstract;
}
public void setAbstract(String _abstract) {
this._abstract = _abstract;
}
public String getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
public List<String> getDesFacet() {
return desFacet;
}
public void setDesFacet(List<String> desFacet) {
this.desFacet = desFacet;
}
public List<String> getOrgFacet() {
return orgFacet;
}
public void setOrgFacet(List<String> orgFacet) {
this.orgFacet = orgFacet;
}
public List<String> getPerFacet() {
return perFacet;
}
public void setPerFacet(List<String> perFacet) {
this.perFacet = perFacet;
}
public List<String> getGeoFacet() {
return geoFacet;
}
public void setGeoFacet(List<String> geoFacet) {
this.geoFacet = geoFacet;
}
public List<Medium> getMedia() {
return media;
}
public void setMedia(List<Medium> media) {
this.media = media;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getPhotoURL() {
return photoURL;
}
public void setPhotoURL(String photoURL) {
this.photoURL = photoURL;
}
public boolean isFavorites() {
return favorites;
}
public void setFavorites(boolean favorites) {
this.favorites = favorites;
}
/**
* Next methods are Parcelable interface.
**/
public Result(){}
protected Result(Parcel in) {
section = in.readString();
id = in.readLong();
title = in.readString();
_abstract = in.readString();
photoURL = in.readString();
publishedDate = in.readString();
source = in.readString();
favorites = in.readByte() != 0x00;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(section);
dest.writeLong(id);
dest.writeString(title);
dest.writeString(_abstract);
dest.writeString(photoURL);
dest.writeString(publishedDate);
dest.writeString(source);
dest.writeByte((byte) (favorites ? 0x01 : 0x00));
}
@SuppressWarnings("unused")
public static final Parcelable.Creator<Result> CREATOR = new Parcelable.Creator<Result>() {
@Override
public Result createFromParcel(Parcel in) {
return new Result(in);
}
@Override
public Result[] newArray(int size) {
return new Result[size];
}
};
}<file_sep>/app/src/main/java/koloboklesnoi/newspaper/api/gson/RtClient.java
package koloboklesnoi.newspaper.api.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import koloboklesnoi.newspaper.api.gson.converter.MediaMetadatumGsonConverter;
import koloboklesnoi.newspaper.api.gson.converter.MediumGsonConverter;
import koloboklesnoi.newspaper.api.MostPopular;
import koloboklesnoi.newspaper.api.gson.converter.ResultGsonConverter;
import koloboklesnoi.newspaper.model.MediaMetadatum;
import koloboklesnoi.newspaper.model.Medium;
import koloboklesnoi.newspaper.model.Result;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RtClient {
private static final String URL_ROOT = "https://api.nytimes.com/";
private static Retrofit getRetrofitInstance(){
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Result.class, new ResultGsonConverter());
gsonBuilder.registerTypeAdapter(Medium.class, new MediumGsonConverter());
gsonBuilder.registerTypeAdapter(MediaMetadatum.class, new MediaMetadatumGsonConverter());
Gson gson = gsonBuilder.create();
return new Retrofit.Builder()
.baseUrl(URL_ROOT)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
public static MostPopular getMostPopular(){
return getRetrofitInstance().create(MostPopular.class);
}
}
<file_sep>/app/src/main/java/koloboklesnoi/newspaper/adapter/ResultAdapter.java
package koloboklesnoi.newspaper.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import koloboklesnoi.newspaper.R;
import koloboklesnoi.newspaper.model.Result;
import java.util.List;
public class ResultAdapter extends ArrayAdapter<Result>{
List<Result> resultList;
Context context;
private LayoutInflater layoutInflater;
public ResultAdapter(Context context, List<Result> resultList){
super(context, 0, resultList);
this.resultList = resultList;
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
}
@Override
public Result getItem(int position) {
return super.getItem(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if(convertView == null){
View view = layoutInflater.inflate(R.layout.article_title_view, parent, false);
viewHolder = ViewHolder.create((LinearLayout) view);
view.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
Result result = getItem(position);
viewHolder.titleView.setText(result.getTitle());
return viewHolder.rootView;
}
private static class ViewHolder{
public final LinearLayout rootView;
public final TextView titleView;
public ViewHolder(LinearLayout rootView, TextView textView) {
this.rootView = rootView;
this.titleView = textView;
}
public static ViewHolder create(LinearLayout rootView){
TextView titleVIew = (TextView)rootView.findViewById(R.id.titleView);
return new ViewHolder(rootView,titleVIew);
}
}
public List<Result> getResultList() {
return resultList;
}
}
<file_sep>/app/src/main/java/koloboklesnoi/newspaper/api/gson/converter/MediaMetadatumGsonConverter.java
package koloboklesnoi.newspaper.api.gson.converter;
import com.google.gson.*;
import koloboklesnoi.newspaper.model.MediaMetadatum;
import java.lang.reflect.Type;
public class MediaMetadatumGsonConverter implements JsonDeserializer<MediaMetadatum> {
@Override
public MediaMetadatum deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
MediaMetadatum mediaMetadatum = new MediaMetadatum();
JsonObject jsonObject = json.getAsJsonObject();
mediaMetadatum.setUrl(jsonObject.get("url").getAsString());
return mediaMetadatum;
}
}
<file_sep>/app/src/main/java/koloboklesnoi/newspaper/MainActivity.java
package koloboklesnoi.newspaper;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.Toast;
import koloboklesnoi.newspaper.adapter.ResultAdapter;
import koloboklesnoi.newspaper.api.MostPopular;
import koloboklesnoi.newspaper.api.gson.RtClient;
import koloboklesnoi.newspaper.database.DatabaseManager;
import koloboklesnoi.newspaper.model.Article;
import koloboklesnoi.newspaper.model.Result;
import koloboklesnoi.newspaper.utility.InternetConnection;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private String apiKey = "<KEY>";
private TabHost tabHost;
private ListView emailedListView;
private ListView sharedListView;
private ListView viewedListView;
private ListView favoritesListView;
private List<Result> favoritesResultList;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
fillFavoritesResultList();
tabInitialize();
listViewInitialize();
resultListInitialize();
fillListsViewAndCheckOnFavorites(favoritesListView,favoritesResultList);
}
public void tabInitialize() {
tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("tag1");
tabSpec.setContent(R.id.tab1);
tabSpec.setIndicator("Most Emailed");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("tag2");
tabSpec.setContent(R.id.tab2);
tabSpec.setIndicator("Most Shared");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("tag3");
tabSpec.setContent(R.id.tab3);
tabSpec.setIndicator("Most Viewed");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("tag4");
tabSpec.setContent(R.id.tab4);
tabSpec.setIndicator("", ContextCompat.getDrawable(this,R.drawable.star_on));
tabHost.addTab(tabSpec);
tabHost.setCurrentTab(0);
}
private void fillFavoritesResultList(){
//Получение данных из базы
try {
DatabaseManager databaseManager = new DatabaseManager(this, "FAVORITES", null, 1);
DataBaseAsyncTask dataBaseAsyncTask = new DataBaseAsyncTask();
dataBaseAsyncTask.execute(databaseManager);
favoritesResultList = dataBaseAsyncTask.get();
}catch (Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
private void listViewInitialize(){
emailedListView = (ListView) findViewById(R.id.emailedListView);
sharedListView = (ListView) findViewById(R.id.sharedListView);
viewedListView = (ListView) findViewById(R.id.viewedListView);
favoritesListView = (ListView) findViewById(R.id.favoritesListView);
}
private void resultListInitialize(){
try {
// Если есть интернет - Получение Джейсона и заполнение списков
if (InternetConnection.checkConnection(this)) {
MostPopular api = RtClient.getMostPopular();
Call<Article> emailedCall = api.getEmailed(apiKey);
emailedCall.enqueue(new Callback<Article>() {
@Override
public void onResponse(Call<Article> call, Response<Article> response) {
fillListsViewAndCheckOnFavorites(emailedListView,response.body().getResults());
}
@Override
public void onFailure(Call<Article> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_LONG).show();
}
});
Call<Article> sharedCall = api.getShared(apiKey);
sharedCall.enqueue(new Callback<Article>() {
@Override
public void onResponse(Call<Article> call, Response<Article> response) {
fillListsViewAndCheckOnFavorites(sharedListView,response.body().getResults());
}
@Override
public void onFailure(Call<Article> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_LONG).show();
}
});
Call<Article> viewedCall = api.getViewed(apiKey);
viewedCall.enqueue(new Callback<Article>() {
@Override
public void onResponse(Call<Article> call, Response<Article> response) {
fillListsViewAndCheckOnFavorites(viewedListView,response.body().getResults());
}
@Override
public void onFailure(Call<Article> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_LONG).show();
}
});
} else {
Toast.makeText(this, "No internet", Toast.LENGTH_LONG).show();
}
}catch (Exception e){
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
}
}
private void fillListsViewAndCheckOnFavorites(ListView listView, List<Result> resultList){
checkOnFavorites(resultList, favoritesResultList);
setOnListViewOnItemClickListener(listView, resultList);
setAdapter(listView, resultList);
}
private void setAdapter(ListView listView, List<Result> resultList){
if(listView != null & resultList != null) {
ResultAdapter adapter = new ResultAdapter(this, resultList);
listView.setAdapter(adapter);
}
}
private void checkOnFavorites(List<Result> resultList, List<Result> favoritesList){
if(resultList != null & favoritesList != null) {
if (resultList.size() > 0) {
if(favoritesList.size() > 0){
for (Result result : resultList) {
for (Result favorites : favoritesList) {
if (result.getId() == favorites.getId()) {
result.setFavorites(true);
} else {
result.setFavorites(false);
}
}
}
}else {
for (Result result : resultList) {
result.setFavorites(false);
}
}
}
}
}
private void setOnListViewOnItemClickListener(ListView listView, final List<Result> resultList){
if(listView != null & resultList != null) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), ArticleActivity.class);
Result result = resultList.get((int) id);
if (result.getPhotoURL() == null) {
result.setPhotoURL(result.getMedia().get(0).getMediaMetadata().get(2).getUrl());
}
intent.putExtra("result", result);
startActivity(intent);
}
});
}
}
private class DataBaseAsyncTask extends AsyncTask<DatabaseManager,Void,List<Result>>{
@Override
protected List<Result> doInBackground(DatabaseManager... databaseManagers) {
List<Result> resultList = new ArrayList<>();
SQLiteDatabase database = databaseManagers[0].getReadableDatabase();
Cursor cursor = database.query(DatabaseManager.TABLE_NAME, null, null,
null, null, null, null);
if (cursor.moveToFirst()) {
int id = cursor.getColumnIndex(DatabaseManager.COLUMN_ID);
int section = cursor.getColumnIndex(DatabaseManager.COLUMN_SECTION);
int title = cursor.getColumnIndex(DatabaseManager.COLUMN_TITLE);
int abstract_ = cursor.getColumnIndex(DatabaseManager.COLUMN_ABSTRACT);
int photo = cursor.getColumnIndex(DatabaseManager.COLUMN_PHOTO);
int publish_date = cursor.getColumnIndex(DatabaseManager.COLUMN_PUBLISH_DATE);
int source = cursor.getColumnIndex(DatabaseManager.COLUMN_SOURCE);
do {
Result result = new Result();
result.setId(cursor.getLong(id));
result.setSection(cursor.getString(section));
result.setTitle(cursor.getString(title));
result.setAbstract(cursor.getString(abstract_));
result.setPhotoURL(cursor.getString(photo));
result.setPublishedDate(cursor.getString(publish_date));
result.setSource(cursor.getString(source));
// result.setFavorites(true);
resultList.add(result);
}while (cursor.moveToNext());
}
database.close();
return resultList;
}
}
@Override
protected void onRestart() {
super.onRestart();
fillFavoritesResultList();
fillListsViewAndCheckOnFavorites(favoritesListView,favoritesResultList);
ResultAdapter resultAdapter;
resultAdapter = (ResultAdapter) emailedListView.getAdapter();
fillListsViewAndCheckOnFavorites(emailedListView, resultAdapter.getResultList());
resultAdapter = (ResultAdapter) sharedListView.getAdapter();
fillListsViewAndCheckOnFavorites(sharedListView, resultAdapter.getResultList());
resultAdapter = (ResultAdapter) viewedListView.getAdapter();
fillListsViewAndCheckOnFavorites(viewedListView, resultAdapter.getResultList());
}
}
<file_sep>/app/src/main/java/koloboklesnoi/newspaper/api/MostPopular.java
package koloboklesnoi.newspaper.api;
import koloboklesnoi.newspaper.model.Article;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface MostPopular {
@GET("svc/mostpopular/v2/emailed/1.json")
Call<Article> getEmailed(@Query("api-key") String key);
@GET("svc/mostpopular/v2/shared/1/facebook.json")
Call<Article> getShared(@Query("api-key") String key);
@GET("svc/mostpopular/v2/viewed/1.json")
Call<Article> getViewed(@Query("api-key") String key);
}
| 737a67994e281bd6d6298046df0cd0836fe3f3a3 | [
"Java"
]
| 8 | Java | KolobokLesnoi/NewsPaper | 1bdc83efaf3e01b685429910ccbed0ccb4f7920a | c7e0b1a829606e01c889e8c9f1e661c342f6f497 |
refs/heads/master | <repo_name>hieubq90/VISCRegV1<file_sep>/verify_sig.py
#!/usr/bin/env python
# Make sure you have pysha3 installed
# pip install -U pysha3
import sha3, hashlib, sys
HASH_FUNCS = {
'SHA-256': lambda x: hashlib.sha256(x).hexdigest(),
'KECCAK-256': lambda x: sha3.keccak_256(x).hexdigest(),
}
def get_hashes(msg):
for h in ['SHA-256', 'KECCAK-256']:
msg_bytes = msg
if sys.version_info.major >= 3:
msg_bytes = msg.encode('utf-8')
out = '%s:%s' % (h, HASH_FUNCS[h](msg_bytes))
print(out)
if __name__ == '__main__':
if len(sys.argv) != 2:
raise Exception('Usage: %s <msg>' % sys.argv[0])
get_hashes('VISC:%s' % sys.argv[1]);
<file_sep>/reg/README.md
# Instruction
Create a PR and put file named `YOUR_GITHUB_ID.dat` with the following content:
```
SHA-256:(SHA-256(VISC:YOUR_GITHUB_ID_IN_LOWER_CASE))
KECCAK-256:(KECCAK-256(VISC:YOUR_GITHUB_ID_IN_LOWER_CASE))
```
For example my string is `VISC:vietlq` and my file `vietlq.dat` should look like this:
```
SHA-256:815f421ea518866d186845a4be3a46828ed21429a896654b36b7ddba1e464d04
KECCAK-256:47620e53f94f7d9f4560e4f89e25bb60513941f39fbc30d2494333431dc6c234
```
| 1dbf430bd7f9575d433969435630e15ddb3175e8 | [
"Markdown",
"Python"
]
| 2 | Python | hieubq90/VISCRegV1 | 33b9f0d555c52143a3812329227978a661b94e5e | 502b5d61b0998e27b32c529e5eba369cb2a473da |
refs/heads/master | <file_sep>class Substrings
def match(word)
word_frequency = Hash.new(0)
sentence = "super cat hair dog cattle catbird homework fan"
sentence.split.each do |dictionary|
word_frequency[/word/i.match(dictionary)] += 1
end
p word_frequency
#names = (regexp).names
#scan(regexp).collect do |match|
#Hash[names.zip(match)]
#{}/(cat)+/.match(word)[0]
end
end
<file_sep>require 'substrings'
require 'spec_helper'
describe Substrings do
let(:substrings) {Substrings.new}
it "can match one word exactly" do
expect(substrings.match("cat")).to eq "cat"
end
it "can match one word in a longer word" do
expect(substrings.match("catbird")).to eq "cat"
end
it "can match one word when it shows up twice" do
expect(substrings.match("cat cat")).to eq "cat cat"
end
end
<file_sep># substrings
# substrings
| ecb82a0d4dc0e999e65be140abf4a30bed0e371e | [
"Markdown",
"Ruby"
]
| 3 | Ruby | keflood/substrings | cb01a2b01074889a87faf89c3c62077ccded1cec | b95b1e367c03388a5991740cd1d0a4eed63dd0a9 |
refs/heads/master | <file_sep>package com.Interface;
public abstract class Vehicle implements Travel,Owner {
}class Car extends Vehicle {
@Override
public int getspeed() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getOwnerName() {
// TODO Auto-generated method stub
return null;
}
}class Cycle extends Vehicle {
@Override
public int getspeed(){
// TODO Auto-generated method stub
return 0;
}
@Override
public String getOwnerName() {
// TODO Auto-generated method stub
return null;
}
}class Bus extends Vehicle{
@Override
public int getspeed() {
return 0;
}
@Override
public String getOwnerName() {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>package com.Interface;
public abstract class Animal implements Travel,Owner {
}
class Dog extends Animal {
@Override
public int getspeed() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getOwnerName() {
// TODO Auto-generated method stub
return null;
}
class Cat extends Animal {
@Override
public int getspeed() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getOwnerName() {
// TODO Auto-generated method stub
return null;
}
}
class Rabbit extends Animal{
@Override
public int getspeed() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getOwnerName() {
// TODO Auto-generated method stub
return null;
}
}
}
<file_sep>
package com.basic;
public class conversion {
public static void main(String[]args) {
int i=0;
for(i=0;i<10;i++)
{
if(i == 3) {
continue;
}
System.out.println("for loop i =" +i);
if(i== 5)
{
break;
}
}
}
}
<file_sep>package com.Interface;
public class AcessModOne {
protected int count = 100;
}
| a1b0923254cfcd570767f0c1243b5b6900832886 | [
"Java"
]
| 4 | Java | soundharyas/javacorebasics | 8223d6a653e054b49c01e3fccba23cd0c5163115 | c984946c5acade5e6eb0f35d484b60fa05a309f6 |
refs/heads/master | <repo_name>ocfranz/todo-typescript<file_sep>/src/components/RangeTimerPicker/styles.ts
import styled from "styled-components";
const TimePickerStyled = styled.div`
display: flex;
`;
export { TimePickerStyled };
<file_sep>/src/components/Heading/styles.ts
import styled from "styled-components";
const HeadingStyled = styled.span<{ type: string }>`
font-weight: 700;
opacity : 0.7;
font-size: ${(props) => (props.type === "h1" ? "30px" : "24px")};
`;
const HeadingWrapper = styled.div`
margin: 20px 0px;
`;
export { HeadingStyled, HeadingWrapper };
<file_sep>/src/helpers/filterTasks.ts
import { getDateFromKeyword } from "./getDateFromKeyword";
const filterTasks = (tasks: any[], time: string) => {
const date = getDateFromKeyword(time);
const tasksFiltered = tasks.filter((item) => {
const splitedDate = item.date.split("/");
const taskDate = new Date(
`${splitedDate[2]}-${splitedDate[1]}-${splitedDate[0]}`
);
if (
date.getDate() === taskDate.getDate() &&
date.getMonth() === taskDate.getMonth() &&
date.getFullYear() === taskDate.getFullYear()
) {
return item;
}
});
return tasksFiltered
};
export { filterTasks };
<file_sep>/src/reducers/tasksReducer.ts
export interface Task {
id: number;
text: string;
isCompleted: boolean;
date: string;
estimated: number;
}
export interface TasksState {
tasks: Array<Task>;
}
const initialState = {
tasks: [],
};
type Action = {
type: "ADD_TASK" | "UPDATE_TASK";
payload: Task;
};
export const tasksReducer = (
state: TasksState = initialState,
action: Action
) => {
switch (action.type) {
case "ADD_TASK":
return { ...state, tasks: [...state.tasks, action.payload] };
case "UPDATE_TASK":
const tasks: Array<Task> = state.tasks.map((task) => {
if (task.id === action.payload.id) {
const updatedTask: Task = Object.assign(
{},
task,
action.payload
);
return updatedTask;
}
return task;
});
return { ...state, tasks: tasks };
default:
return state;
}
};
<file_sep>/src/components/TodoListItem/styles.ts
import styled from "styled-components";
const TodoListItemWrapper = styled.div<{ key: any }>`
width: 100%;
display: flex;
flex-direction: row;
align-items: center;
color: #686088;
font-weight: 500;
font-size: 18px;
margin: 15px 0px;
position: relative;
cursor: pointer;
`;
const CheckBox = styled.div`
border-radius: 50%;
width: 35px;
height: 35px;
margin-right: 10px;
cursor: pointer;
border-radius: 50%;
`;
const TodoTitleStyled = styled.div`
width: 60%;
display: flex;
align-items: center;
`;
const TodoDateStyled = styled.div`
width: 25%;
text-align: right;
opacity: 0.7;
font-size: 16px;
`;
const TodoEstimatedStyled = styled.div`
width: 15%;
text-align: right;
opacity: 0.7;
font-size: 16px;
`;
const ButtonControls = styled.div<{ visible: boolean }>`
margin-left: 10px;
width: 35px;
height: 35px;
display: ${(props) => (props.visible ? "block" : "none")};
`;
export {
TodoListItemWrapper,
CheckBox,
TodoTitleStyled,
TodoDateStyled,
TodoEstimatedStyled,
ButtonControls,
};
<file_sep>/src/components/IconButton/styles.ts
import styled from "styled-components";
const IconButtonStyled = styled.button`
padding: 0;
margin: 0px 10px 0px 0px;
border: none;
background-color: transparent;
cursor: pointer;
&:focus{
outline : none;
box-shadow : none;
}
`;
export { IconButtonStyled };
<file_sep>/src/components/TaskItemRow/styles.ts
import styled from "styled-components";
import { media } from "../../styles/Breakpoints";
const TaskItem = styled.div`
display: flex;
align-items: center;
padding: 10px 0px;
`;
const TaskItemTag = styled.div`
align-items: center;
display: flex;
width: 20%;
`;
const TaskItemName = styled.span`
font-size: 15px;
opacity: 0.8;
margin-left: 10px;
`;
const TaskItemAction = styled.div`
width: 80%;
`;
const TaskItemButton = styled.div`
text-align: left;
padding: 10px 0px 10px 10px;
cursor: pointer;
&:hover {
background-color: rgba(0, 0, 0, 0.3);
}
`;
const TimeInput = styled.input`
font-size: 16px;
border: none;
outline: none;
box-shadow: none;
background-color: transparent;
opacity: 0.8;
padding: 0;
&:focus {
outline: none;
box-shadow: none;
}
`;
export {
TaskItem,
TaskItemTag,
TaskItemAction,
TaskItemButton,
TaskItemName,
TimeInput,
};
<file_sep>/src/reducers/uiReducer.ts
export interface UiState {
showModalAdd: boolean;
showModalDate: boolean;
}
const initialStateUi = {
showModalAdd: false,
showModalDate: false,
};
type Action = {
type: "SHOW_MODAL_ADD" | "SHOW_MODAL_DATE";
payload: boolean;
};
export const uiReducer = (state: UiState = initialStateUi, action: Action) => {
switch (action.type) {
case "SHOW_MODAL_ADD":
return { ...state, showModalAdd: action.payload };
case "SHOW_MODAL_DATE":
return { ...state, showModalDate: action.payload };
default:
return state;
}
};
<file_sep>/src/components/SimpleGrid/styles.ts
import styled from "styled-components";
import { media } from "../../styles/Breakpoints";
const GridBasic= styled.div`
padding: 0px 20px;
@media ${media.sm} {
margin: 0px 150px;
}
@media ${media.md} {
margin: 0px 200px;
}
@media ${media.lg} {
margin: 0px 320px;
}
`;
const GridExtended = styled.div`
padding: 0px 10px;
@media ${media.sm} {
margin: 0px 100px;
}
@media ${media.md} {
margin: 0px 150px;
}
@media ${media.lg} {
margin: 0px 250px;
}
`;
export { GridBasic, GridExtended };
<file_sep>/src/helpers/getDateFromKeyword.ts
const getDateFromKeyword = (keyword: string) => {
const today = new Date();
switch (keyword) {
case "today":
return today;
case "tomorrow":
return new Date(
`${today.getFullYear()}-${today.getMonth()+1}-${
today.getDate() + 1
}`
);
default:
throw new Error("Keyword type error");
}
};
export { getDateFromKeyword };
<file_sep>/src/reducers/index.ts
import { combineReducers } from "redux";
import { tasksReducer } from "./tasksReducer";
import { uiReducer } from "./uiReducer";
export const rootReducer = combineReducers({ uiReducer, tasksReducer });
export type RootState = ReturnType<typeof rootReducer>;
<file_sep>/src/components/Button/style.ts
import styled from 'styled-components';
const ButtonStyled = styled.button`
` <file_sep>/src/modules/ModalDate/styles.ts
import styled from "styled-components";
const ModalDateStyled = styled.div<{ visible: boolean }>`
display: ${(props) => (props.visible ? "flex" : " none")};
position: absolute;
width: 250px;
height: 350px;
top: 25%;
z-index: 999;
background-color: #ffffff;
-webkit-box-shadow: 0px 0px 10px 0.5px rgba(196, 192, 196, 1);
-moz-box-shadow: 0px 0px 10px 0.5px rgba(196, 192, 196, 1);
box-shadow: 0px 0px 10px 0.5px rgba(196, 192, 196, 1);
flex-wrap: wrap;
`;
const ModalDateWrapper = styled.div`
padding: 10px 20px;
width: 100%;
`;
const DateInputWrapper = styled.div`
width: 100%;
display: flex;
`;
const DateInput = styled.input`
width: 100%;
padding: 2px 0px;
font-size: 18px;
border: 1px solid;
background: rgba(242, 241, 238, 0.6);
&:focus {
outline: none;
box-shadow: none;
}
`;
export { ModalDateStyled, ModalDateWrapper, DateInputWrapper, DateInput };
<file_sep>/src/modules/ModalAdd/styles.ts
import styled from "styled-components";
import { media } from "../../styles/Breakpoints";
const ModalWrapper = styled.div<{ visible: boolean }>`
display: ${(props) => (props.visible ? "flex" : "none")};
position: absolute;
top: 0;
left: 0;
width: 100%;
background: rgba(0, 0, 0, 0.3);
height: 100%;
align-items: center;
z-index: 99;
`;
const ModalDialog = styled.div`
width: 100%;
margin: 0;
padding: 0;
background-color: #ffffff;
@media ${media.md} {
max-width: 900px;
max-height: 400px;
margin: auto auto;
height: calc(100% - 144px);
}
`;
const ModalContent = styled.div`
overflow-y: auto;
height: 100%;
width: 100%;
`;
const ModalContainer = styled.div``;
const ModalHeader = styled.div`
padding: 10px 20px;
font-size: 15px;
display: flex;
justify-content: space-between;
align-items: center;
`;
const ModalFooter = styled.div`
text-align: center;
`;
const ModalBody = styled.div`
text-align: center;
padding: 20px 20px;
@media ${media.md} {
padding: 20px 100px;
}
`;
const TaskHeading = styled.div`
display: flex;
text-align: left;
flex-wrap: nowrap;
align-items: center;
`;
export {
ModalWrapper,
ModalDialog,
ModalContent,
ModalHeader,
ModalBody,
ModalFooter,
ModalContainer,
TaskHeading,
};
<file_sep>/src/components/EmptyDisplay/styles.ts
import styled from "styled-components";
const EmptyStyled = styled.div`
display: flex;
justify-content: center;
align-items: center;
padding: 25px 0px;
flex-direction: column;
background-color: rgba(255,255,255,0.5);
`;
const EmptyStrong = styled.span`
font-size: 18px;
font-weight: bold;
display: block;
opacity : 0.7;
`;
const EmptyMessage = styled.span`
display: block;
font-size: 15px;
opacity: 0.6;
margin-top: 5px;
`;
export { EmptyStyled, EmptyStrong, EmptyMessage };
<file_sep>/src/helpers/preventClickOutside.ts
const preventClickOutside = (ref : any,event : any)=>{
if (!ref.current.contains(event.target)) return true
return false
}
export {preventClickOutside};<file_sep>/src/styles/Breakpoints.ts
const media = {
xs: `(min-width: 480px)`,
sm: "(min-width: 768px)",
md: "(min-width: 992px)",
lg: "(min-width: 1200px)",
};
export { media};
<file_sep>/src/modules/Header/styles.ts
import styled from "styled-components";
const HeaderWrapper = styled.div`
display: flex;
height: 60px;
text-align: center;
justify-content: center;
align-items: center;
font-weight: 700;
font-size: 30px;
padding-top: 30px;
justify-content: space-between;
`;
const IconWrapper = styled.div`
padding-top: 2px;
`;
export { HeaderWrapper, IconWrapper };
<file_sep>/src/styles/GlobalStyles.ts
import { createGlobalStyle } from "styled-components";
const GlobalStyles = createGlobalStyle`
body, html{
border : 0;
margin :0;
padding: 0;
}
body{
height: 100%;
background: #FAF9FA;
color: #000000;
-webkit-transition: background-color 0.5s linear;
-moz-transition: background-color 0.5s linear;
-o-transition: background-color 0.5s linear;
transition: background-color 0.5s linear;
}
*{
font-family: 'DM Sans', sans-serif;
}
[contenteditable][placeholder]:empty:before {
content: attr(placeholder);
position: absolute;
color: rgba(55,53,47,0.4);
background-color: transparent;
}
`;
export default GlobalStyles;
<file_sep>/src/components/Calendar/styles.ts
import styled from "styled-components";
const CalendarWrapper = styled.div`
width: 100%;
`;
export { CalendarWrapper};
<file_sep>/src/components/Input/styles.ts
import styled from "styled-components";
const InputStyled = styled.input`
padding: 10px 20px;
height: 30px;
border-radius: 20px;
width: 25%;
text-align: center;
&:focus{
box-shadow: none;
outline: none;
}
`;
const InputWrapper = styled.div`
display: flex;
justify-content: center;
`;
export { InputStyled, InputWrapper };
<file_sep>/src/components/TodoListItem/CircleIcon.js
import React from "react";
const Circle = ({ size = 35, color = "#aca8b8" }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="#FFFFFF"
stroke={color}
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10"></circle>
</svg>
);
export default Circle;
| 90818832649388960e7cdb538c2a259d9cf1c24d | [
"JavaScript",
"TypeScript"
]
| 22 | TypeScript | ocfranz/todo-typescript | 4362e23f80cd909b5f2387def71187ce0fe7c5ba | 7db1db0fc1d983cd519892b7e418beb9698286cc |
refs/heads/main | <file_sep>import { _ } from 'lodash';
import { userId, password, getEditComment, userAgent } from '../../OFFAuth.js';
function _getBaseUrl(category) {
return category === 'Food' ? 'https://world.openfoodfacts.org' : 'https://world.openbeautyfacts.org';
}
export async function getProduct(ean, category) {
const url = `${_getBaseUrl(category)}/api/v0/product/${ean}.json`;
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
UserAgent: userAgent
}
});
const product = await response.json();
if (product.status === 0) {
return null;
}
return product;
} catch (error) {
console.error(error);
return null;
}
}
export async function uploadProductToOFF(args) {
const comment = await getEditComment();
const url = `${_getBaseUrl(args.category)}/cgi/product_jqm2.pl?code=${args.ean}&product_name=${encodeURIComponent(
args.name
)}&add_brands=${encodeURIComponent(args.brand)}&add_labels=${encodeURIComponent(
args.labels
)}&add_categories=${encodeURIComponent(args.categories)}&comment=${encodeURIComponent(
comment
)}&user_id=${userId}&password=${encodeURIComponent(password)}`;
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
UserAgent: userAgent
}
});
response.text().then(text => console.log('=> OFF response text:', _.truncate(text, { length: 100 })));
if (args.wholePicture) {
await _addPictureToProduct(
args.category,
args.ean,
args.wholePicture,
'front',
'imgupload_front',
'front_img.jpg'
);
}
if (args.ingredientsPicture) {
await _addPictureToProduct(
args.category,
args.ean,
args.ingredientsPicture,
'ingredients',
'imgupload_ingredients',
'ingredient_img.jpg'
);
}
if (args.nutritionPicture) {
await _addPictureToProduct(
args.category,
args.ean,
args.nutritionPicture,
'nutrition',
'imgupload_nutrition',
'nutrition_img.jpg'
);
}
} catch (error) {
console.error(error);
}
}
function _addPictureToProduct(category, code, picture, fieldValue, imgUpload, imgTitle) {
const url = `${_getBaseUrl(category)}/cgi/product_image_upload.pl`;
const formData = new FormData();
formData.append('code', code);
formData.append('imagefield', fieldValue);
formData.append(imgUpload, { uri: picture, type: 'image/jpg', name: imgTitle });
formData.append('user_id', userId);
formData.append('password', <PASSWORD>);
return fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
UserAgent: userAgent
},
body: formData
})
.then(response => response.text())
.then(text => console.log('uploaded picture: got response text: ', text))
.catch(error => console.error(error));
}
<file_sep># React native code to contribute products to Open Food Facts
Example code to add to a React native mobile application to contribute products to Open Food Facts.
Join the [Open Food Facts slack](https://openfoodfacts.slack.com) if you'd like to contribute or just reuse the code and need help.
## Contributors
- [EthicAdvisor](https://www.ethicadvisor.org) team
## Doc
See Open Food Facts wiki:
- https://en.wiki.openfoodfacts.org/API
## License
- The code is release under the APACHE 2.0 license (see LICENSE file).
## Credits
- Some icons are taken from [FlatIcon](www.flaticon.com)
## Third party applications
Feel free to open a PR to add your application in this list.
## Authors
<file_sep>import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Image, TextInput, Alert } from 'react-native';
import Accordion from 'react-native-collapsible/Accordion';
import { Icon } from 'react-native-elements';
import { getProduct, uploadProductToOFF } from '../API/Api';
import { getPicturePath, INGREDIENTS, NUTRITION, WHOLE } from './TakePictureScreen';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { logUserEventContributeOFF } from '../../helpers/Analytics';
export const FOOD = 'Food';
const ADD_PRODUCT = 'Ajouter le produit';
const EDIT_PRODUCT = 'Enregistrer';
export default class AddProductScreen extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: `Editer ou ajouter un produit`,
headerStyle: {
backgroundColor: '#38b3c5'
},
headerTintColor: 'white'
});
constructor(props) {
super(props);
this.state = {
activeSections: [],
textBrand: '',
textName: '',
textLabel: '',
textCategory: '',
alreadyExist: false,
existingName: '',
existingBrand: '',
existingLabels: '',
existingCategories: '',
status: ADD_PRODUCT
};
}
async componentDidMount() {
this.props.navigation.addListener('didFocus', () => {
// close section when getting back to this screen because section is not refreshed correctly when adding an image
this.setState({ activeSections: [] });
});
const offProduct = await getProduct(this.getEan(), this.getCategory());
if (offProduct !== null) {
if (!this.isEditMode()) {
Alert.alert(
'Edition',
`Le produit n'était pas encore présent dans la base EthicAdvisor mais existait déjà dans Open Food Facts. Vous pouvez compléter les infos et ajouter de nouvelles photos.`
);
}
const product = offProduct.product;
this.setState({
existingName: product.product_name,
textName: product.product_name,
existingLabels: product.labels,
existingCategories: product.categories,
existingBrand: product.brands,
alreadyExist: true,
status: EDIT_PRODUCT
});
}
}
_getStatus() {
if (this.state.alreadyExist) {
return EDIT_PRODUCT;
}
return ADD_PRODUCT;
}
_renderHeader = (section, index, isActive) => {
return (
<View style={styles.header}>
<Icon name={section.icon} />
<Text style={styles.headerText}>{section.title}</Text>
<View style={{ flex: 100, flexDirection: 'row', justifyContent: 'flex-end' }}>
<Icon name={isActive ? 'chevron-left' : 'chevron-right'} />
</View>
</View>
);
};
_renderBrands() {
if (this.state.existingBrand) {
return (
<Text style={[styles.textHeader, { marginTop: 5 }]}>
Les marques existantes sont : "{this.state.existingBrand}". Ajouter une autre marque :
</Text>
);
}
return <Text style={[styles.textHeader, { marginTop: 5 }]}>*Nom des marques :</Text>;
}
_renderName() {
if (this.state.existingName) {
return <Text style={styles.textHeader}>Renommer le produit :</Text>;
}
return <Text style={styles.textHeader}>*Nom du produit :</Text>;
}
_renderLabels() {
if (this.state.existingLabels) {
return (
<Text style={styles.textHeader}>
Les labels existants sont : "{this.state.existingLabels}". Ajouter d'autres labels (séparés par des
virgules) :
</Text>
);
}
return (
<Text style={[styles.textHeader, { marginTop: 5 }]}>Labels du produit (séparés par des virgules) :</Text>
);
}
_renderCategories() {
if (this.state.existingCategories) {
return (
<Text style={styles.textHeader}>
Les catégories existantes sont : "{this.state.existingCategories}". Ajouter d'autres catégories
(séparées par des virgules) :
</Text>
);
}
return (
<Text style={[styles.textHeader, { marginTop: 5 }]}>
Catégories du produit (séparées par des virgules) :
</Text>
);
}
_renderDescription() {
const exampleCategory = this.getCategory() === FOOD ? 'Plat cuisiné' : 'Corps';
return (
<View>
{this._renderBrands()}
<TextInput
placeholder="Par exemple : <NAME>, Léa Nature"
style={styles.textinputstyle}
onChangeText={textBrand => this.setState({ textBrand })}
value={this.state.textBrand}
/>
{this._renderName()}
<TextInput
placeholder="Par exemple : Haricots verts"
style={styles.textinputstyle}
onChangeText={textName => this.setState({ textName })}
value={this.state.textName}
/>
{this._renderLabels()}
<TextInput
placeholder="Par exemple : Bio"
style={styles.textinputstyle}
onChangeText={textLabel => this.setState({ textLabel })}
value={this.state.textLabel}
/>
{this._renderCategories()}
<TextInput
placeholder={`Par exemple : ${exampleCategory}`}
style={styles.textinputstyle}
onChangeText={textCategory => this.setState({ textCategory })}
value={this.state.textCategory}
/>
</View>
);
}
getCategory() {
return this.props.navigation.getParam('category');
}
isEditMode() {
return this.props.navigation.getParam('mode') === 'edit';
}
getEan() {
return this.props.navigation.getParam('ean');
}
getPicturePathParam(name) {
return this.props.navigation.getParam(getPicturePath(name));
}
_renderPictureSection(name) {
return (
<View>
<Text style={{ margin: 5 }}>
Appuyez sur la caméra pour prendre une photo, votre capture s'affichera ensuite à sa droite !
</Text>
<View style={styles.globalpicturestyle}>
<TouchableOpacity
onPress={() => {
this.props.navigation.navigate('TakePicture', { name: name });
}}
>
<Image
style={{ width: 70, height: 70, marginLeft: 30 }}
source={require('../assets/images/camera.png')}
/>
</TouchableOpacity>
{this._renderPicture(this.getPicturePathParam(name))}
</View>
</View>
);
}
_renderPicture(path) {
if (path) {
return <Image style={{ width: 130, height: 180, marginRight: '20%' }} source={{ uri: path }} />;
} else {
return <View />;
}
}
_updateSections = activeSections => {
this.setState({ activeSections: activeSections });
};
_verifyProduct() {
if (!this.state.textBrand && !this.state.existingBrand) {
return false;
}
if (!this.state.textName && !this.state.existingName) {
return false;
}
if (this.state.alreadyExist) {
this.getPicturePathParam(WHOLE);
}
return true;
}
async _validateProduct() {
if (!this._verifyProduct()) {
Alert.alert(
'Champ(s) vide(s) détecté(s)',
`Le nom, la marque du produit et les trois photos doivent être remplis.`
);
return;
}
this.setState({ status: 'Ajout en cours...' });
const args = {
ean: this.getEan(),
name: this.state.textName,
brand: this.state.textBrand,
wholePicture: this.getPicturePathParam(WHOLE),
ingredientsPicture: this.getPicturePathParam(INGREDIENTS),
labels: this.state.textLabel,
categories: this.state.textCategory,
category: this.getCategory()
};
if (this.getCategory() === FOOD) {
args.nutritionPicture = this.getPicturePathParam(NUTRITION);
}
try {
await uploadProductToOFF(args);
Alert.alert('Produit ajouté', `Ce produit a été ajouté avec succès, merci pour votre contribution !`);
await logUserEventContributeOFF(this.getEan(), this.isEditMode() ? 'edit' : 'add');
this.props.navigation.navigate('Scan');
} catch (error) {
Alert.alert('Un problème est survenu', `Ce produit n'a pas pu être ajouté, merci de réessayer.`);
this.setState({ status: this._getStatus() });
}
}
render() {
const sections = [
{
title: 'Description du produit',
icon: 'business',
content: this._renderDescription()
},
{
title: 'Ajouter une photo globale du produit',
icon: 'photo-camera',
content: this._renderPictureSection(WHOLE)
},
{
title: 'Ajouter une photo des ingrédients',
icon: 'room-service',
content: this._renderPictureSection(INGREDIENTS)
}
];
if (this.getCategory() === FOOD) {
sections.push({
title: 'Ajouter une photo des informations nutritionnelles',
icon: 'directions-run',
content: this._renderPictureSection(NUTRITION)
});
}
return (
<KeyboardAwareScrollView
style={{ flex: 1 }}
behavior="padding"
enabled
contentContainerStyle={{ flexGrow: 1 }}
enableOnAndroid={true}
>
<Accordion
sections={sections}
activeSections={this.state.activeSections}
renderHeader={this._renderHeader}
renderContent={section => section.content}
onChange={this._updateSections}
/>
<TouchableOpacity
style={styles.validatecontainer}
onPress={() => {
this._validateProduct();
}}
>
<Text style={{ color: 'white', fontSize: 18 }}>{this.state.status}</Text>
</TouchableOpacity>
</KeyboardAwareScrollView>
);
}
}
const styles = StyleSheet.create({
textHeader: {
margin: 3
},
textinputstyle: {
height: 50,
fontSize: 14,
marginLeft: 5,
marginRight: 5,
borderWidth: 1,
borderColor: '#38b3c5',
margin: 2
},
eanstyle: {
textAlign: 'center',
fontSize: 16,
marginBottom: 16,
marginTop: 16,
marginRight: 7,
marginLeft: 7
},
globalpicturestyle: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between'
},
validatecontainer: {
backgroundColor: '#38b3c5',
borderRadius: 7,
bottom: 20,
alignSelf: 'center',
width: 180,
height: 35,
alignItems: 'center',
justifyContent: 'center',
marginTop: 40
},
// accordion
header: {
backgroundColor: '#F5FCFF',
padding: 10,
flexDirection: 'row',
alignItems: 'center'
},
headerText: {
textAlign: 'center',
fontSize: 16,
fontWeight: '500',
paddingLeft: 15
},
sectionContent: {
padding: 15,
backgroundColor: '#fff'
},
sectionText: {
flexWrap: 'wrap',
flex: 1
}
});
| dda96346b13bb5af520dc171d3ed1c39d65cb485 | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | openfoodfacts/openfoodfacts-react-native | 22d7573779255d61259172d2f330406bc426f3dd | bfc5b89f6eebbc49dc95ae3209a486ad4365c0c6 |
refs/heads/master | <file_sep>#!/usr/bin/env bash
# fetching the value of "tpm_plugins" option
plugins_list=$(tmux show-option -gqv "@tpm_plugins")
# displaying variable content, line by line
for plugin in $plugins_list; do
echo $plugin
done
| 1d15f0bbeea5602fcaaf99912b67c948f551af8a | [
"Shell"
]
| 1 | Shell | Couto/tmux-example-plugin | 29a71f6749a5413f42445372052e612e937b23d6 | 94022cabe96b536ecee05f79e95150715781e39d |
refs/heads/master | <file_sep>import express from 'express';
const router = express.Router();
const jwt = require('jsonwebtoken');
import Usuario from '../models/usuario';
//Hash Contraseña
const bcrypt = require('bcrypt');
const saltRounds = 10;
router.post('/login', async (req,res) =>{
const body = req.body;
try {
//evaluarmos el email
const usuarioDB = await Usuario.findOne({email: body.email});
if(!usuarioDB){
return res.status(400).json({
mensaje: 'Usuario o contraseña inválidos'
});
}
//evaluamos la contraseña
if(!bcrypt.compareSync(body.contraseña, usuarioDB.contraseña)){
return res.status(400).json({
mensaje: 'Usuario o contraseña inválidos'
});
}
//generar token
const token = jwt.sign({
data: usuarioDB
}, 'the_BuyApp_secret', { expiresIn: 60 * 60 * 24 * 30 });
res.json({
usuarioDB,
token
})
} catch (error) {
return res.status(400).json({
mensaje: 'ERROR',
error
});
}
});
module.exports = router;<file_sep>const express = require('express');
const morgan = require('morgan');
const cors = require('cors');
const path = require('path');
const mongoose = require('mongoose');
const uri = 'mongodb://localhost:27017/BuyAppBD';
const options = {useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true};
const app = express();
//conexion a la BD
mongoose.connect(uri, options).then(
() => { console.log('Base de datos Conectada!'); },
err => { err }
);
//middleware
app.use(morgan('tiny'));
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended:true }));
//rutas
app.use(require('./routes/usuario'));
app.use(require('./routes/login'));
app.use(require('./routes/post_sugerencia'));
//middleware para vue.js del modo history
const history = require('connect-history-api-fallback');
app.use(history());
app.use(express.static(path.join(__dirname, 'public')));
//servidor
app.set('puerto', process.env.PORT || 3000);
app.listen(app.get('puerto'),()=>{
console.log('Escuchando el puerto:',app.get('puerto'))
})<file_sep>import express from 'express';
const router = express.Router();
import Usuario from '../models/usuario';
const {verificar_auth, verificar_admin} = require('../middleware/autenticacion');
//Hash Contraseña
const bcrypt = require('bcrypt');
const saltRounds = 10;
//para filtrar campos de PUT
const _ = require('underscore');
//agregar un nuevo Usuario
router.post('/new_usuario',async (req,res) =>{
const body = {
nombre: req.body.nombre,
nombre_usuario: req.body.nombre_usuario,
email: req.body.email,
role: req.body.role
}
body.contraseña = bcrypt.hashSync(req.body.contraseña, saltRounds);
try {
const usuarioDB = await Usuario.create(body);
return res.status(200).json(usuarioDB);
} catch (error) {
return res.status(500).json({
mensaje: 'ERROR No se puede agregar',
error
});
}
});
//buscar un usuario
router.get('/buscar_usuario/:id',verificar_auth, async(req,res) => {
const _id = req.params.id;
try {
const usuarioDB = await Usuario.findOne({_id});
res.json(usuarioDB);
} catch (error) {
return res.status(400).json({
mensaje: 'ERROR',
error
});
}
});
//Buscar todos los usuarios
router.get('/lista_usuarios', async (req,res) => {
try {
const usuarioDB=await Usuario.find();
res.json(usuarioDB);
} catch (error) {
return res.status(400).json({
mensaje: 'ERROR',
error
});
}
});
//eliminar usuario
router.delete('/del_usuario/:id', async(req,res) => {
const _id = req.params.id;
try {
const usuarioDB = await Usuario.findByIdAndDelete({_id});
if(!usuarioDB){
return res.status(400).json({
mensaje: 'ERROR',
error
});
}
res.json(usuarioDB);
} catch (error) {
return res.status(400).json({
mensaje: 'Ups 404 No existe :c',
error
});
}
});
//actualizar usuario para administradores
router.put('/act_usuario_admin/:id', [verificar_auth, verificar_admin], async(req,res) =>{
const _id =req.params.id;
const body = _.pick(req.body, ['email', 'contraseña', 'estado']);
if(body.contraseña){
body.contraseña = <PASSWORD>.hashSync(req.body.contraseña, saltRounds);
}
try {
const usuarioDB = await Usuario.findByIdAndUpdate(_id,body,{new: true, runValidators: true, context: 'query'});
return res.json(usuarioDB);
} catch (error) {
return res.status(400).json({
mensaje: 'Ocurrio un Error',
error
});
}
});
//actualizar usuario para usuarios normales
router.put('/act_usuario/:id', verificar_auth, async(req,res) =>{
const _id =req.params.id;
const body = _.pick(req.body, ['email', 'contraseña', 'estado','nombre','nombre_usuario']);
if(body.contraseña){
body.contraseña = <PASSWORD>.hashSync(req.body.contraseña, saltRounds);
}
try {
const usuarioDB = await Usuario.findByIdAndUpdate(_id,body,{new: true, runValidators: true, context: 'query'});
return res.json(usuarioDB);
} catch (error) {
return res.status(400).json({
mensaje: 'Ocurrio un Error',
error
});
}
});
module.exports = router;<file_sep>import express from 'express';
const router = express.Router();
//importamos el modelo de post_sugerencia
import Post_sugerencia from '../models/post_sugerencia'
import Usuario from '../models/usuario';
const {verificar_auth} = require('../middleware/autenticacion');
//agregar un post de sugerencia
router.post('/nueva_sugerencia', verificar_auth, async (req, res) => {
const body = req.body;
//agregar el id del usuario ya logueado
body.id_usuario = req.usuario._id;
body.nombre_usuario = req.usuario.nombre_usuario;
try {
const post_sugerenciaDB = await Post_sugerencia.create(body);
res.status(200).json(post_sugerenciaDB);
} catch (error) {
return res.status(500).json({
mensaje: 'Ocurrio un error',
error
});
}
});
// Get todas las sugerencias
router.get('/get_sugerencias', async (req, res) => {
try {
const post_sugerenciaDB = await Post_sugerencia.find();
res.json(post_sugerenciaDB);
} catch (error) {
return res.status(400).json({
mensaje: 'Ocurrio un error',
error
});
}
});
//Get de una sugerencia
router.get('/get_sugerencia/:id', async (req, res) => {
const _id = req.params.id;
try {
const post_sugerenciaDB = await Post_sugerencia.findById(_id);
res.json(post_sugerenciaDB);
} catch (error) {
return res.status(400).json({
mensaje: 'Ocurrio un error',
error
});
}
});
//actualizar sugerencia
router.put('/act_sugerencia/:id', verificar_auth, async (req, res) => {
const _id = req.params.id;
const body = req.body;
const post_sugerencia_checker=await Post_sugerencia.findById(_id);
//verificar si el usuario del post de sugerencia es el mismo que esta logueado
if(post_sugerencia_checker.id_usuario===req.usuario._id){
try {
const post_sugerenciaDB = await Post_sugerencia.findByIdAndUpdate(_id, body, {new: true});
res.json(post_sugerenciaDB);
} catch (error) {
return res.status(400).json({
mensaje: 'Ocurrio un error',
error
});
}
}else{
return res.status(400).json({
mensaje: 'Usuario no valido para esta accion',
});
}
});
module.exports = router;<file_sep>import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const post_sugerencia_schema = new Schema({
titulo: { type: String, required: [true, 'El titulo es requerido']},
descripcion: { type: String, required: [true, 'La descripción es requerida']},
fecha_creacion: { type:Date, default: Date.now},
estado: { type: Boolean, default: true},
id_usuario: String,
nombre_usuario: String
});
const Post_sugerencia = mongoose.model('Post_sugerencia', post_sugerencia_schema);
export default Post_sugerencia; | a9e1e65b47805ac2a9f0e0c86392096c4c049c89 | [
"JavaScript"
]
| 5 | JavaScript | silviobig96/BuyApp_Backend | 1d21d2ee7f38b6e0bc1f0e33158c57121165e0b5 | 758c0c1a13f8717b9b437dff061d32e539ce32af |
refs/heads/master | <file_sep># uplead-ci-airtable-translator
This script will read an exported UpLead csv of leads and grab all the relevant columns for the Customer Illuminated Airtable template.
## flags
```bash
$ ./translate_uplead_to_ci.py -h
usage: translate_uplead_to_ci.py [-h] -i INPUT -o OUTPUT [-r ROOT]
optional arguments:
-h, --help show this help message and exit
-i INPUT, --input INPUT
input filename
-o OUTPUT, --output OUTPUT
output filename
-r ROOT, --root ROOT root filepath to read / write the files from
```
It has a dependency on pandas, so feel free to pull the [docker image](https://hub.docker.com/u/10forward/uplead-ci-airtable) to run the script.
## docker usage
The docker image will look for the input file (`-i`) in the `/data/` directory in its container, so mount a folder with your exported leads to `/data`. The processed file (filename denoted by `-o`) will also be written into that mounted directory.
Usage:
```bash
$ ls
UpLead_05-09-2019.csv
$ docker pull 10forward/uplead-ci-airtable
$ docker run -v $(pwd):/data 10forward/uplead-ci-airtable -i UpLead_05-09-2019.csv -o airtable-ci.csv
exported translated file to /airtable-ci.csv
$ ls -l
airtable-ci.csv
UpLead_05-09-2019.csv
```
<file_sep>FROM python:3.7-slim
VOLUME /data
RUN pip install pandas
ADD translate_uplead_to_ci.py /translate_uplead_to_ci.py
RUN chmod +x /translate_uplead_to_ci.py
ENTRYPOINT ["/translate_uplead_to_ci.py"]<file_sep>#!/usr/bin/env python3
import os
import argparse
import pandas as pd
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', help="input filename", required=True)
parser.add_argument('-o', '--output', help="output filename", required=True)
parser.add_argument('-r', '--root', help="root filepath to read / write the files from", default="/data")
args = parser.parse_args()
uplead = pd.read_csv(os.path.join(args.root, args.input))
airtable = uplead[['LastName', 'FirstName', 'Email', 'CompanyName', 'Title', 'Website']].copy()
airtable = airtable.rename(index=str, columns={"LastName": "<NAME>", "FirstName": "<NAME>", "CompanyName": "Organization", "Title": "Job title"})
airtable.loc[:, "Contact stage"] = 'Contact not initiated'
airtable.loc[:, "QA'd"] = 'No'
airtable.loc[:, "QA'd by"] = None
airtable.loc[:, "Source of contact info"] = "UpLead"
airtable.loc[:, "Notes"] = None
path = os.path.join(args.root, args.output)
airtable.to_csv(path, index=False)
print("exported translated file to " + args.output)
| bd49caf0a9a34dfd75f58ebc33fdd43588d41974 | [
"Markdown",
"Python",
"Dockerfile"
]
| 3 | Markdown | tenforwardslash/uplead-ci-airtable-translator | 3b1b8aac0deeff99f229382f4ed43a96b865ef26 | 5372e7c00df7286b850038211c8f5b47acc4a97d |
refs/heads/master | <repo_name>qingw/dotfiles-2<file_sep>/README.md
# dotfiles
dotfiles
## macOS
```
defaults write -g KeyRepeat -int 1
defaults write -g InitialKeyRepeat -int 10
```
<file_sep>/script/setup
#!/bin/bash
bash "${HOME}"/.dotfiles/shell/script/setup
bash "${HOME}"/.dotfiles/lang/script/setup
bash "${HOME}"/.dotfiles/editor/script/setup
bash "${HOME}"/.dotfiles/tools/script/setup
<file_sep>/tools/script/bootstrap
#!/bin/bash
# nix https://nixos.org/nix/
curl https://nixos.org/nix/install | sh
nix-channel --add https://nixos.org/channels/nixpkgs-unstable
nix-channel --update
nix-env -iA nixpkgs.cachix
cachix use all-hies
<file_sep>/tools/env.zsh
alias ls="lsd --group-dirs first "
alias ll="ls -l"
alias ssh="TERM=xterm-256color ssh"
<file_sep>/tools/script/setup
#!/bin/bash
nix-env --install ripgrep
nix-env --install lsd
nix-env --install ghq
nix-env --install tig
nix-env --install peco
nix-env --install tokei
nix-env --install bat
nix-env --install ranger
nix-env --install alacritty
mkdir -p "${HOME}"/config/alacritty
ln -fs "${HOME}"/.dotfiles/tools/alacritty.yml "${HOME}"/.config/alacritty/alacritty.yml
cat >> "$HOME"/.gitconfig <<EOF
[ghq]
root = ${HOME}/src
EOF
<file_sep>/script/bootstrap
#!/bin/bash
bash "${HOME}"/.dotfiles/shell/script/bootstrap
bash "${HOME}"/.dotfiles/tools/script/bootstrap
bash "${HOME}"/.dotfiles/lang/script/bootstrap
<file_sep>/lang/script/setup
#!/bin/bash
# rust
rustup self update
rustup update
rustup install nightly
rustup component add rls
rustup component add rust-analysis
rustup component add rust-src
rustup component add rustfmt
rustup component add clippy
rustup completions zsh > ~/.zfunc/_rustup
cargo install racer
mkdir "${HOME}"/.zfunc
# script
nix-env --install ShellCheck
# haskell
nix-env --install stack
stack install apply-refact hlint stylish-haskell hasktags hoogle hindent
nix-env -iA selection --arg selector 'p: { inherit (p) ghc865; }' -f https://github.com/infinisil/all-hies/tarball/master
# ocaml
nix-env --install opam
opam init
opam config setup -a
opam install merlin utop ocp-indent
opam user-setup install
# c/c++
nix-env --install ccls
# jvm familiy
nix-env --install clojure
# go
nix-env --install go
nix-env --install delve
# javascript / web
nix-env --install nodejs
nix-env --install yarn
yarn global add typescript typescript-language-server
yarn global add prettier import-js
yarn global add vscode-html-languageserver-bin
yarn global add vscode-css-languageserver-bin
# elixir
nix-env --install elixir
# elm
nix-env --install elm
# python
nix-env --install python-2.7.16
nix-env --install python3-3.7.4
nix-env --install pipenv-2018.11.26
python3 -m ensurepip --default-pip --user
pip3 install --upgrade --user pip
pip3 install --user pynvim
pip3 install --user flake8
pip3 install --user yapf
pip3 install --user autoflake
pip3 install --user isort
pip3 install --user 'python-language-server[all]'
pip3 install --uesr 'ptvsd>=4.2'
pip3 install --user pyls-isort
pip3 install --user pyls-mypy
pip3 install --user importmagic
pip3 install --user epc
pip3 install --user black
pip3 install --user bashate
ln -fs "${HOME}"/.dotfiles/lang/mypy "${HOME}"/.config/mypy
ln -fs "${HOME}"/.dotfiles/lang/pylintrc "${HOME}"/.config/pylintrc
# ruby
nix-env --install ruby
mkdir -p "${HOME}"/bin/gem
gem install solargraph
gem install pry
gem install sqlint
# crystal
nix-env --install crystal
nix-env --install icr
# php
nix-env --install php-composer
yarn global add intelephense
# html / css
gem install specific_install
gem specific_install https://github.com/brigade/scss-lint.git
gem specific_install https://github.com/Sweetchuck/scss_lint_reporter_checkstyle.git
yarn global add vscode-css-languageserver-bin
<file_sep>/lang/script/update
#!/bin/bash
# rust
rustup self update
rustup update
rustup component add rls
rustup component add rust-analysis
rustup component add rust-src
rustup component add rustfmt
rustup component add clippy
rustup completions zsh > ~/.zfunc/_rustup
# Golang
go get -u github.com/cweill/gotests/...
go get -u github.com/davidrjenni/reftools/cmd/fillstruct
go get -u github.com/derekparker/delve/cmd/dlv
go get -u github.com/fatih/gomodifytags
go get -u github.com/golangci/golangci-lint/cmd/golangci-lint
go get -u github.com/haya14busa/gopkgs/cmd/gopkgs
go get -u github.com/josharian/impl
go get -u github.com/mdempsky/gocode
go get -u github.com/rogpeppe/godef
go get -u github.com/zmb3/gogetdoc
go get -u golang.org/x/tools/...
go get -u github.com/godoctor/godoctor
go install github.com/godoctor/godoctor
go get -u github.com/alecthomas/gometalinter
# python
pip3 install --user --upgrade pip
pip3 list --outdated | tail -n +3 | awk '{print $1}' | xargs pip3 install --user --upgrade
# ruby
gem update $(gem outdated | cut -d ' ' -f 1)
# node
yarn global upgrade
<file_sep>/editor/nvim/plugins.toml
[[plugins]]
repo = 'Shougo/dein.vim'
[[plugins]]
repo = 'w0rp/ale'
[[plugins]] # hybrid
repo = 'w0ng/vim-hybrid'
[[plugins]] # status-line
repo = 'itchyny/lightline.vim'
hook_add = '''
let g:lightline = {'colorscheme': 'wombat'}
'''
# ==============================================================================
# denite
# ==============================================================================
# ==============================================================================
# edit
# ==============================================================================
[[plugins]]
repo = 'tpope/vim-surround'
[[plugins]]
repo = 'Shougo/context_filetype.vim'
[[plugins]]
repo = 'Shougo/deoplete.nvim'
depends = 'context_filetype.vim'
on_i = 1
hook_source = '''
let g:deoplete#enable_at_startup = 1
'''
[[plugins]]
repo = 'Shougo/neosnippet.vim'
depends = ['context_filetype.vim']
on_event = 'InsertCharPre'
on_ft = 'snippet'
[[plugins]]
repo = 'Shougo/neosnippet-snippets'
[[plugins]]
repo = 'w0rp/ale'
[[plugins]]
repo = 'jiangmiao/auto-pairs'
# ==============================================================================
# colorscheme
# ==============================================================================
[[plugins]] # colorscheme
repo = 'jdkanani/vim-material-theme'
[[plugins]]
repo = 'jacoborus/tender'
# ==============================================================================
# languages
# ==============================================================================
[[plugins]]
repo = 'autozimu/LanguageClient-neovim'
depends = 'deoplete.nvim'
on_ft = ['rust', 'vue']
build = './install.sh'
rev = 'next'
hook_source = '''
set hidden
let g:LanguageClient_serverCommands = {
\ 'rust': ['rustup', 'run', 'nightly', 'rls'],
\ 'vue': ['vls'],
\ }
let g:LanguageClient_autoStart = 1
noremap <silent> H :call LanguageClient_textDocument_hover()<CR>
noremap <silent> Z :call LanguageClient_textDocument_definition()<CR>
noremap <silent> R :call LanguageClient_textDocument_rename()<CR>
noremap <silent> S :call LanugageClient_textDocument_documentSymbol()<CR>
'''
[[plugins]] # Toml
repo = 'cespare/vim-toml'
<file_sep>/editor/env.zsh
alias emacs="emacs -nw"
alias emacs-with-window="\emacs"
alias e="emacs"
alias ew="emacs-with-window"
alias vi="nvim -u NONE --noplugin"
alias vim="nvim"
alias spacemacs="rm ${HOME}/.emacs.d && ln -fs ${HOME}/.spacemacs.emacs.d ${HOME}/.emacs.d && emacs"
alias doomemacs="rm ${HOME}/.emacs.d && ln -fs ${HOME}/.doom.emacs.d ${HOME}/.emacs.d && emacs"
export PATH="$HOME/.doom.emacs.d/bin:$PATH"
<file_sep>/shell/script/setup
#!/bin/bash
nix-env --install zsh
nix-env --install tmux
ln -fs "${HOME}"/.dotfiles/shell/bash_profile "${HOME}"/.bash_profile
ln -fs "${HOME}"/.dotfiles/shell/bashrc "${HOME}"/.bashrc
ln -fs "${HOME}"/.dotfiles/shell/zshenv "${HOME}"/.zshenv
ln -fs "${HOME}"/.dotfiles/shell/zshrc "${HOME}"/.zshrc
ln -fs "${HOME}"/.dotfiles/shell/tmux.conf "${HOME}"/.tmux.conf
ln -fs "${HOME}"/.dotfiles/shell/nixpkgs "${HOME}"/.config/nixpkgs
source .zshrc
<file_sep>/editor/nvim/lazy.toml
[[plugins]] # Plugin to easily access Most Recently Used (MRU) files
repo = 'Shougo/neomru.vim'
on_source = 'denite.nvim'
on_path = '.*'
[[plugins]] # Yank
repo = 'Shougo/neoyank.vim'
on_source = 'denite.nvim'
on_event = 'TextYankPost'
# Lang
## Rust
[[plugins]]
repo = 'rust-lang/rust.vim'
on_ft = 'rust'
hook_source = '''
let g:rustfmt_autosave = 1
'''
## Go
[[plugins]]
repo = 'fatih/vim-go'
on_ft = 'go'
hook_source = '''
let g:go_fmt_command = "goimports"
let g:go_highlight_functions = 1
let g:go_highlight_methods = 1
let g:go_highlight_fields = 1
let g:go_highlight_types = 1
let g:go_highlight_operators = 1
let g:go_highlight_build_constraints = 1
'''
# [[plugins]]
# repo = 'godoctor/godoctor.vim'
[[plugins]]
repo = 'jodosha/vim-godebug'
<file_sep>/shell/zshenv
# zmodload zsh/zprof && zprof
. "${HOME}"/.nix-profile/etc/profile.d/nix.sh
autoload -Uz run-help
autoload -Uz add-zsh-hook
autoload -Uz colors && colors
autoload -Uz is-at-least
autoload -Uz vcs_info
fpath+="${HOME}"/.zfunc
autoload -Uz compinit && compinit -u
# 補完の大文字小文字区別
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
typeset -U path PATH
export LANGUAGE="en_US.UTF-8"
export LANG="${LANGUAGE}"
export LC_ALL="${LANGUAGE}"
export LC_CTYPE="${LANGUAGE}"
export EDITOR="nvim -u NONE --noplugin"
export CVSEDITOR="${EDITOR}"
export GIT_EDITOR="${EDITOR}"
export PAGER=less
export LESSCHARSET='utf-8'
export HISTFILE="${HOME}"/.zsh_history
export HISTSIZE=10000
export SAVEHIST=1000000
export LISTMAX=50
export XDG_CONFIG_HOME="${HOME}"/.config
source "${HOME}"/.dotfiles/tools/env.zsh
source "${HOME}"/.dotfiles/editor/env.zsh
source "${HOME}"/.dotfiles/lang/env.zsh
<file_sep>/lang/pylintrc
disable=
invalid-name
<file_sep>/script/update
#!/bin/bash
cd "${HOME}"/.dotfiles && git pull
bash "${HOME}"/.dotfiles/shell/script/update
bash "${HOME}"/.dotfiles/lang/script/update
bash "${HOME}"/.dotfiles/editor/script/update
bash "${HOME}"/.dotfiles/tools/script/update
<file_sep>/editor/script/setup
#!/bin/bash
nix-env --install emacs
nix-env --install neovim
# spacemacs
if [ ! -e "${HOME}"/.spacemacs.emacs.d ]; then
git clone https://github.com/syl20bnr/spacemacs ~/.spacemacs.emacs.d
(cd ~/.spacemacs.emacs.d && git checkout -b develop origin/develop)
fi
# doom emacs
if [ ! -e "${HOME}"/.doom.emacs.d ]; then
git clone https://github.com/hlissner/doom-emacs ~/.doom.emacs.d
ln -fs "${HOME}"/.doom.emacs.d "${HOME}"/.emacs.d
~/.emacs.d/bin/doom install
fi
# spacevim
if [ ! -e "${HOME}"/.dotfiles/editor/dein ]; then
mkdir -p "${HOME}"/.dotfiles/editor/dein
curl https://raw.githubusercontent.com/Shougo/dein.vim/master/bin/installer.sh > installer.sh
sh ./installer.sh "${HOME}"/.cache/dein
rm ./installer.sh
fi
curl -sLf https://spacevim.org/install.sh | bash
mkdir -p "${HOME}"/.config
ln -fs "${HOME}"/.dotfiles/editor/spacemacs "${HOME}"/.spacemacs
ln -fs "${HOME}"/.dotfiles/editor/doom "${HOME}"/.config/doom
ln -fs "${HOME}"/.dotfiles/editor/nvim "${HOME}"/.config/nvim
ln -fs "${HOME}"/.dotfiles/editor/spacevim "${HOME}"/.SpaceVim.d
ln -fs "${HOME}"/.dotfiles/editor/editorconfig "${HOME}"/.editorconfig
ln -fs "${HOME}"/.spacemacs.emacs.d "${HOME}"/.emacs.d
<file_sep>/editor/script/update
#!/bin/bash
cd "${HOME}"/.emacs.d && git pull
cd "${HOME}"/.SpaceVim && git pull
<file_sep>/lang/script/bootstrap
#!/bin/bash
if [ ! -e "${HOME}"/.cargo ]; then
curl https://sh.rustup.rs -sSf | sh
fi
<file_sep>/shell/zshrc
umask 022
limit coredumpsize 0
bindkey -d
bindkey -e
# prompt
export TERM='xterm-24bit'
PROMPT="%(?.%{${fg[cyan]}%}.%{${fg[red]}%})[%n@%m]%{$reset_color%}"
RPROMPT="%(?.%{${fg[cyan]}%}.%{${fg[red]}%})[%~]%{${reset_color}%}"
# git
setopt prompt_subst
zstyle ':vcs_info:git:*' check-for-changes true
zstyle ':vcs_info:git:*' stagedstr "%F{yellow}!"
zstyle ':vcs_info:git:*' unstagedstr "%F{red}+"
zstyle ':vcs_info:*' formats "%F{green}%c%u[%b]%f"
zstyle ':vcs_info:*' actionformats '[%b|%a]'
precmd () { vcs_info }
PROMPT=$PROMPT'${vcs_info_msg_0_} '
# peco
setopt hist_ignore_all_dups
function peco_select_history() {
local tac
if which tac > /dev/null; then
tac="tac"
else
tac="tail -r"
fi
BUFFER=$(fc -l -n 1 | eval $tac | peco --query "$LBUFFER")
CURSOR=$#BUFFER
zle clear-screen
}
zle -N peco_select_history
bindkey '^r' peco_select_history
function peco-src () {
local selected_dir=$(ghq list -p | peco --query "$LBUFFER")
if [ -n "$selected_dir" ]; then
BUFFER="cd ${selected_dir}"
zle accept-line
fi
zle clear-screen
}
zle -N peco-src
bindkey '^]' peco-src
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
[ -f ${HOME}/.dotfiles/private/.zshrc ] && source ${HOME}/.dotfiles/private/.zshrc
export PATH="$HOME/.cargo/bin:$HOME/.dotfiles/script:$HOME/.dotfiles/bin:/usr/local/bin:$PATH"
# zcompile
if [ $HOME/.dotfiles/shell/zshrc -nt ~/.zshrc.zwc ]; then
zcompile ~/.zshrc
fi
# if (which zprof > /dev/null 2>&1) ;then
# zprof
# fi
<file_sep>/editor/spacevim/init.toml
#=============================================================================
# dark_powered.toml --- dark powered configuration example for SpaceVim
# Copyright (c) 2016-2017 <NAME> & Contributors
# Author: <NAME> < wsdjeg at 163.com >
# URL: https://spacevim.org
# License: GPLv3
#=============================================================================
# All SpaceVim option below [option] section
[options]
# set spacevim theme. by default colorscheme layer is not loaded,
# if you want to use more colorscheme, please load the colorscheme
# layer
colorscheme = "one"
background = "dark"
# Disable guicolors in basic mode, many terminal do not support 24bit
# true colors
enable_guicolors = true
# Disable statusline separator, if you want to use other value, please
# install nerd fonts
statusline_separator = "nil"
statusline_inactive_separator = "nil"
buffer_index_type = 4
enable_tabline_filetype_icon = true
enable_statusline_display_mode = false
relativenumber = false
default_indent = 4
bootstrap_after = "init#after"
spacevim_autocomplete_method = 'coc'
# Enable autocomplete layer
[[layers]]
name = 'autocomplete'
auto-completion-return-key-behavior = "complete"
auto-completion-tab-key-behavior = "smart"
[[layers]]
name = 'denite'
[[layers]]
name = 'checkers'
enable_neomake = false
enable_ale = true
show_cursor_error = false
[[layers]]
name = 'debug'
[[layers]]
name = 'VersionControl'
[[layers]]
name = 'git'
[[layers]]
name = 'shell'
default_position = 'bottom'
default_height = 20
[[layers]]
name = 'colorscheme'
[[layers]]
name = 'lsp'
filetypes = [
'rust',
# 'haskell',
'go',
# 'kotlin',
'python',
'typescript',
'html'
]
[[layers]]
name = 'lang#rust'
[[layers]]
name = 'lang#haskell'
[[layers]]
name = 'lang#scheme'
[[layers]]
name = 'lang#lisp'
[[layers]]
name = 'lang#go'
[[layers]]
name = 'lang#c'
[[layers]]
name = 'lang#python'
format-on-save = 1
[[layers]]
name = 'lang#perl'
[[layers]]
name = 'lang#java'
[[layers]]
name = 'lang#kotlin'
[[layers]]
name = 'lang#scala'
[[layers]]
name = 'lang#clojure'
[[layers]]
name = 'lang#elm'
[[layers]]
name = 'lang#javascript'
[[layers]]
name = 'lang#typescript'
[[layers]]
name = 'lang#json'
[[layers]]
name = 'lang#html'
[[layers]]
name = 'lang#vue'
[[layers]]
name = 'lang#dockerfile'
<file_sep>/docker/Dockerfile
FROM ubuntu:18.04
RUN apt-get -y update
RUN apt-get -y upgrade
RUN apt-get install -y gcc gdb make git binutils libc6-dev
# man available
RUN sed -i 's@path-exclude=/usr/share/man/*@#path-exclude=/usr/share/man/*@' /etc/dpkg/dpkg.cfg.d/excludes
RUN apt-get install -y vim man manpages-dev manpages-posix
WORKDIR /mnt
<file_sep>/lang/env.zsh
export PATH="$HOME/.local/bin:$PATH"
# rust
source $HOME/.cargo/env
export RUST_SRC_PATH="$HOME/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/src"
# haskell
export PATH="$HOME/.cask/bin:$PATH"
# ocaml
eval $(opam env)
alias ocaml="rlwrap ocaml"
# go
export GOPATH="$HOME"
export GOBIN="$GOPATH/bin"
export PATH="$GOBIN:$PATH"
# ruby
export GEM_HOME="$HOME"/bin/gem
export PATH="$HOME/bin/gem/bin:$PATH"
# jvm family
# export SDKMAN_DIR=${HOME}/.sdkman
# source ${HOME}/.sdkman/bin/sdkman-init.sh
# node
export PATH="$HOME/.yarn/bin:$PATH"
# elm
export ELM_HOME=$HOME/node_modules/elm
<file_sep>/tools/script/update
#!/bin/bash
# (cd ${HOME}/.dotfiles/tools && cargo install --force --path .)
<file_sep>/shell/script/update
#!/bin/bash
nix-channel --update; nix-env -iA nixpkgs.nix
nix-channel --update nixpkgs
nix-env --upgrade '*'
| 61822225619e344a9460b098979ad82897008ef1 | [
"Markdown",
"TOML",
"INI",
"Dockerfile",
"Shell"
]
| 24 | Markdown | qingw/dotfiles-2 | e847031a003ef86f5128051eea1fd3ba1ad64350 | c192ee6aabc0b0036ec69ce2a33a8d8ce291fc9e |
refs/heads/master | <repo_name>helenmqin/NGordNet<file_sep>/TimeSeries.java
package ngordnet;
import java.util.Collection;
import java.util.NavigableSet;
import java.util.TreeMap;
import java.util.Set;
import java.util.ArrayList;
import java.util.HashSet;
public class TimeSeries<T extends Number> extends TreeMap<Integer, T> {
/** Constructs a new empty TimeSeries. */
public TimeSeries() {
super();
}
/** Returns the years in which this time series is valid. Doesn't really
* need to be a NavigableSet. This is a private method and you don't have
* to implement it if you don't want to. */
private NavigableSet<Integer> validYears(int startYear, int endYear) {
return null;
}
/** Creates a copy of TS, but only between STARTYEAR and ENDYEAR.
* inclusive of both end points. */
public TimeSeries(TimeSeries<T> ts, int startYear, int endYear) {
Set<Integer> boundyears = ts.keySet();
for (Integer y : boundyears) {
if (y >= startYear && y <= endYear) {
T data = ts.get(y);
this.put(y, data);
}
}
}
/** Creates a copy of TS. */
public TimeSeries(TimeSeries<T> ts) {
Set<Integer> boundyears = ts.keySet();
for (Integer y : boundyears) {
T data = ts.get(y);
this.put(y, data);
}
}
/** Returns the quotient of this time series divided by the relevant value in ts.
* If ts is missing a key in this time series, return an IllegalArgumentException. */
public TimeSeries<Double> dividedBy(TimeSeries<? extends Number> ts) {
TimeSeries<Double> totalquotient = new TimeSeries<Double>();
Collection<Integer> ts1 = ts.keySet();
Collection<Integer> ts2 = this.keySet();
if (!ts1.containsAll(ts2)) {
throw new IllegalArgumentException("Does not exist");
}
for (Integer y : ts2) {
double quotient = 0;
double top = this.get(y).doubleValue();
double bottom = ts.get(y).doubleValue();
quotient = top / bottom;
totalquotient.put(y, quotient);
}
return totalquotient;
}
/** Returns the sum of this time series with the given ts. The result is a
* a Double time series (for simplicity). */
public TimeSeries<Double> plus(TimeSeries<? extends Number> ts) {
TimeSeries<Double> total = new TimeSeries<Double>();
Collection<Integer> ts1 = ts.keySet();
Collection<Integer> ts2 = this.keySet();
Set<Integer> combine = new HashSet<Integer>();
combine.addAll(ts1);
combine.addAll(ts2);
for (Integer y : combine) {
double sum = 0;
if (ts.containsKey(y)) {
sum += ts.get(y).doubleValue();
}
if (this.containsKey(y)) {
sum += this.get(y).doubleValue();
}
total.put(y, sum);
}
return total;
}
/** Returns all years for this time series (in any order). */
public Collection<Number> years() {
Collection<Number> ret = new ArrayList<Number>();
Collection<Integer> year = this.keySet();
for (Integer y : year) {
ret.add(y);
}
return ret;
}
/** Returns all data for this time series (in any order). */
public Collection<Number> data() {
Collection<Number> ret = new ArrayList<Number>();
Collection<Integer> year = this.keySet();
for (Integer y : year) {
ret.add(this.get(y));
}
return ret;
}
}
<file_sep>/NgordnetUI.java
package ngordnet;
import edu.princeton.cs.introcs.StdIn;
import edu.princeton.cs.introcs.In;
import java.lang.IllegalArgumentException;
/** Provides a simple user interface for exploring WordNet and NGram data.
* @author <NAME>
*/
public class NgordnetUI {
public static void main(String[] args) {
In in = new In("./ngordnet/ngordnetui.config");
System.out.println("Reading ngordnetui.config...");
String wordFile = in.readString();
String countFile = in.readString();
String synsetFile = in.readString();
String hyponymFile = in.readString();
WordNet wn = new WordNet(synsetFile, hyponymFile);
NGramMap ngm = new NGramMap(wordFile, countFile);
int year;
int startDate = 1500;
int endDate = 2000;
String word;
System.out.println("\nBased on ngordnetui.config, using the following: "
+ wordFile + ", " + countFile + ", " + synsetFile +
", and " + hyponymFile + ".");
System.out.println("\nFor tips on implementing NgordnetUI, see ExampleUI.java.");
while (true) {
System.out.print("> ");
String line = StdIn.readLine();
String[] rawTokens = line.split(" ");
String command = rawTokens[0];
String[] tokens = new String[rawTokens.length - 1];
System.arraycopy(rawTokens, 1, tokens, 0, rawTokens.length - 1);
switch (command) {
case "quit":
return;
case "help":
In in2 = new In("help.txt");
String helpStr = in2.readAll();
System.out.println(helpStr);
break;
case "range":
startDate = Integer.parseInt(tokens[0]);
endDate = Integer.parseInt(tokens[1]);
System.out.println("Start date: " + startDate);
System.out.println("End date: " + endDate);
break;
case "count":
word = tokens[0];
year = Integer.parseInt(tokens[1]);
YearlyRecord yr = ngm.getRecord(year);
System.out.println("Word count for " + word + " in " + year
+ " : " + yr.count(word));
break;
case "hyponyms":
System.out.println(wn.hyponyms(tokens[0]));
break;
case "history":
Plotter.plotAllWords(ngm, tokens, startDate, endDate);
break;
case "hypohist":
Plotter.plotCategoryWeights(ngm, wn, tokens, startDate, endDate);
break;
case "wordlength":
WordLengthProcessor wlp = new WordLengthProcessor();
Plotter.plotProcessedHistory(ngm, startDate, endDate, wlp);
case "zipf year":
year = Integer.parseInt(tokens[0]);
Plotter.plotZipfsLaw(ngm, year);
break;
default:
System.out.println("Invalid command.");
break;
}
}
}
}
<file_sep>/README.md
# NGordNet
NGordnet is a google analytics inspired project and harnesses data processing ideas to model trends. Using the google word data base, NGordnet processes word usage throughout history to plot metrics that give insight to cultural and global phenomenons
| 4b5c1b2c1618dc52b5b1bc8f63c52e3186877aa1 | [
"Markdown",
"Java"
]
| 3 | Java | helenmqin/NGordNet | 8c2bf5c06fc94052bb77d42d2270a2f18cec0b5a | f0cca730427e39ca075a70721ec4218746490ebb |
refs/heads/master | <file_sep>'use strict';
function getYearOfBirth(age) {
if (age < 0) {
throw new Error('Age cannot be negative!');
}
return 2019 - age;
}
function createGreeting(name, age) {
if (!name || !age) {
throw new Error ('Arguments not valid!');
}
try {
let yearOfBirth = getYearOfBirth(age);
return `Hi, my name is ${name} and my age is ${age} and I was born in ${yearOfBirth}.`;
} catch (e) {
console.log(e.message);
}
}
const aSentence = createGreeting('Mike');
console.log(aSentence);
| 49e8fce36371fbe17fc775b1746ee5a897f27d10 | [
"JavaScript"
]
| 1 | JavaScript | RobWiggins/robert-michael-function-drills1 | 3aa947fdf13047c77005c7bf521dd0e5acdb3452 | 002caf60ed71f94db57e4ce3a14ddc8643a92a50 |
refs/heads/master | <file_sep>import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import AutoMinorLocator
plt.style.use('./style_config.mplstyle')
# График линейной зависимости по канонам ВТЭК
def vtek_linear_ploting(xmin, xmax, ymin, ymax,
title, xlabel, ylabel,
xdata, ydata, linedata,
imagename):
"""
xmin, xmax, ymin, ymax: Диапозоны графика
title, xlabel, ylabel: Заголовок и подписи осей
xdata, ydata: Экспериментальные точки
linedata: Данные линейной аппроксимации
imagename: Название сохраняемой картинки
"""
fig = plt.figure(figsize=[6.5,4.25], dpi=100)
ax = fig.gca()
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
ax.set_xscale("linear")
ax.set_yscale("linear")
ax.xaxis.set_minor_locator(AutoMinorLocator())
ax.yaxis.set_minor_locator(AutoMinorLocator())
ax.tick_params(direction="in", length=4, width=1.25)
ax.tick_params(which="minor", direction="in")
ax.grid(c='grey', ls='--', lw=1)
ax.spines["bottom"].set_linewidth(1.5)
ax.spines["right"].set_linewidth(1.5)
ax.spines["left"].set_linewidth(1.5)
ax.spines["top"].set_linewidth(1.5)
ax.set_title(title,
fontproperties=FontProperties(family='ubuntu', style='normal', weight='heavy', size=13),
pad=15)
ax.set_xlabel(xlabel, fontdict={'fontsize': 10}, labelpad=0)
ax.set_ylabel(ylabel, fontdict={'fontsize': 10}, labelpad=5)
ax.plot(xdata, ydata, 'ks', ms=7, label='Эксперимент')
ax.plot(xdata, linedata, '-b', lw=2.5, label='МНК')
ax.legend(loc='upper left')
fig.savefig(imagename, dpi=300)
fig.show() | c98c8af01f7e8dd2f5e1ce2d6c3c3f747645fc40 | [
"Python"
]
| 1 | Python | shampletov-no/plot-templates | 6fb896f91e9ef2d91e5383a2dc75a5b83898c8c4 | beb4385f54c67f7bca61403a86c303693f0ca247 |
refs/heads/master | <file_sep>IDIR=./include
PROJECTNAME=MACD
CC=clang++
CFLAGS=-I$(IDIR) -o$(PROJECTNAME) -g
<file_sep>#pragma once
#include<string>
#include<fstream>
#include<vector>
#include<memory>
class Data{
public:
enum TYPE {
INDEXDATA,
};
static std::unique_ptr<Data> make_data(Data::TYPE type);
virtual void setData(const std::string& line) = 0;
};
class IndexData : public Data{
public:
std::string date;
float opening;
float highest;
float lowest;
float closing;
void setData(const std::string& init_string);
};
class Dataset{
private:
std::vector<std::unique_ptr<Data>> data;
std::fstream fhandle;
public:
int loadCSV(const std::string& filename, Data::TYPE DATATYPE);
const std::vector<std::unique_ptr<Data>>& getData();
};
<file_sep>#include <sstream>
#include "../include/Dataset.h"
std::unique_ptr<Data> Data::make_data(Data::TYPE type){
switch(type){
case Data::INDEXDATA: return std::make_unique<IndexData>(); break;
}
}
void IndexData::setData(const std::string& init_string) {
std::istringstream iss(init_string);
iss >> date
>> opening
>> highest
>> lowest
>> closing;
}
int Dataset::loadCSV(const std::string& filename, Data::TYPE DATATYPE){
fhandle.open(filename);
for(std::string s; std::getline(fhandle, s); )
{
data.push_back(Data::make_data(DATATYPE));
data.back()->setData(s);
}
}
const std::vector<std::unique_ptr<Data>>& Dataset::getData() {
return data;
}
<file_sep>from datetime import timedelta, date
date = date.today() - timedelta(days=1000)
print(date)
| cc808107e4e6f7dac6c0ec96e39df2b37bc24e46 | [
"Python",
"Makefile",
"C++"
]
| 4 | Makefile | MaxchilKH/MAChillD | 19cb0ad944651e2016b97fefa3893cae2da917e4 | 241fd56986831d9e0cbc98d010f44629fd99069a |
refs/heads/master | <file_sep>import mintapi
import os
import json
import datetime
from pprint import pprint
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from database import db_session
app = Flask(__name__)
app.config.from_object(os.environ.get('APP_SETTINGS'))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
from models import Result
@app.route("/")
def hello():
return "Hello World!"
@app.route("/minty")
def minty():
# get my most recent result
result = Result.query.order_by(Result.created_date).first()
print(result.created_date - datetime.datetime.utcnow() )
if result and result.created_date - datetime.datetime.utcnow() < datetime.timedelta(83600):
# if the most recent result is within the last day, return it
transactions = result.transactions
budgets = result.budgets
return json.dumps({"transactions": transactions, "budget": budgets})
else:
# should be done in an RQ job
try:
mint = mintapi.Mint(os.environ.get('MINT_EMAIL'), os.environ.get('MINT_PASSWORD'))
except:
pass
budgets = mint.get_budgets()
transactions = json.loads(mint.get_transactions().to_json())
try:
result = Result(budgets=budgets, transactions=transactions)
db.session.add(result)
db.session.commit()
except:
pass
return json.dumps(budgets)
@app.route("/money")
def money():
return json.dumps({"transactions": [1, 2, 3]})
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
if __name__ == "__main__":
app.run()
<file_sep>import datetime
import os
from sqlalchemy.dialects.postgresql import JSON
from sqlalchemy import (DECIMAL, Boolean, Column, DateTime, Date, ForeignKey, Index,
Integer, MetaData, Table, Text, UniqueConstraint,
Float, CheckConstraint, event, BigInteger)
from database import Base
class Result(Base):
__tablename__ = 'results'
id = Column(Integer, primary_key=True)
created_date = Column(DateTime, default=datetime.datetime.utcnow)
budgets = Column(JSON)
transactions = Column(JSON)
def __repr__(self):
return '<id {}>'.format(self.id)
| a5ee63f3b5026790b176621a42e94e9e7c22dfa2 | [
"Python"
]
| 2 | Python | mweiss17/chrome_portal | 5120382a184df28a2fd5f541aea5ec61fd791a86 | 4f155116d17bb2f98f41bd7af1c29cbfc7c934a8 |
refs/heads/master | <repo_name>ptokmakov/Lab-2<file_sep>/Lab.c
#include <stdio.h>
#include <math.h>
int main()
{
float a,b,c,D;
float x1,x2,x;
printf ("Input A,B,C: \n");
printf("A=");
scanf("%f", &a);
printf("B=");
scanf("%f", &b);
printf("C=");
scanf("%f", &c);
D=b*b-4*a*c;
printf("D=%.3f \n", D);
if(D>0)
{
x1=(-b+sqrt(D))/(2*a);
x2=(-b-sqrt(D))/(2*a);
printf("x1=%.3f \n", x1);
printf("x2=%.3f \n", x2);
}
else if(D=0)
{
x=(-b)/(2*a);
printf("x=%.3f", x);
}
else if(D<0)
printf("NO SOLUTIONS");
return 0;
}
| 7ad93ac66ab3b0623d5311297203df2895f2a624 | [
"C"
]
| 1 | C | ptokmakov/Lab-2 | 97086b358965338aaa2ee6ad3d02453d2410fe4b | dbbc7b4ca8b6bdfb8899cd3cdc26235349475a6d |
refs/heads/master | <repo_name>juvenalfonseca/R<file_sep>/jbrasileiraoRBase/rotinas/config.R
source(pathSource('install.R'))
source(pathSource('library.R'))
source(pathSource('enum.R'))
source(pathSource('funcoes.R'))
<file_sep>/jbrasileiraoRBase/rotinas/enum.R
enum <- function(...) {
nms <- eval(substitute(alist(...)))
x <- as.list(setNames(as.character(nms), nms))
}
enumDataSets <-
enum("campeonato-brasileiro-pontos-corridos-2003-2020-jogos.csv",
"campeonato-brasileiro-pontos-corridos-2003-2020-periodo.csv")
<file_sep>/jbrasileiraoDplyr/rotinas/install.R
install.packages("dplyr")
install.packages("ggplot2")
install.packages("ggeasy")<file_sep>/jbrasileiraoRBase/rotinas/library.R
library(dplyr , quietly=TRUE)
library(ggplot2, quietly=TRUE)
library(ggeasy , quietly=TRUE)<file_sep>/jbrasileiraoDplyr/rotinas/run.R
### remove variáveis
rm(list=ls())
### instala e carrega biblioteca
install.packages("this.path")
library(this.path, quietly=TRUE)
### define path a partir da pasta raiz do projeto
THIS_DIR <- gsub("/rotinas", '', this.dir())
### cria função para retornar path do source
pathSource = function(script='') {
files <- list.files(THIS_DIR, full.names=TRUE, recursive=TRUE, all.files=TRUE, pattern="(*.R$|.env$|.csv)")
fs <- data.frame(dirname = dirname(files), basename = basename(files), path = files)
if (script != '') {
fs <- fs[fs$basename == script,]
}
return(as.character(fs$path))
}
### carrega configurações necessárias
source(pathSource('config.R'))
### carrega datasets
df.periodo <- read.csv2(file = pathSource(enumDataSets$`campeonato-brasileiro-pontos-corridos-2003-2020-periodo.csv`), sep = ";", header = TRUE, stringsAsFactors = FALSE)
df.jogos <- read.csv2(file = pathSource(enumDataSets$`campeonato-brasileiro-pontos-corridos-2003-2020-jogos.csv` ), sep = ";", header = TRUE, stringsAsFactors = FALSE)
### padroniza caixa dos nomes das variáveis
names.periodo <- colnames(df.periodo)
names.jogos <- colnames(df.jogos)
df.periodo <- df.periodo %>% rename_at(all_of(vars(names.periodo)), tolower)
df.jogos <- df.jogos %>% rename_at(all_of(vars(names.jogos )), tolower)
### captalizar strings
df.jogos <-
df.jogos %>%
mutate(dia = capwords(dia , TRUE),
mandante = capwords(mandante , TRUE),
visitante = capwords(visitante, TRUE),
vencedor = capwords(vencedor , TRUE),
arena = capwords(arena , TRUE))
### altera campos de datas de character para date
df.periodo <-
df.periodo %>%
mutate(inicio = as.Date(inicio, format = "%d/%m/%Y"),
fim = as.Date(fim , format = "%d/%m/%Y"))
df.jogos <-
df.jogos %>%
mutate(data = as.Date(data, format = "%d/%m/%Y") )
### junta os datasets e retorna apenas os registros corretos criados na junção (full join)
df <- merge(df.periodo, df.jogos) %>% filter(data >= inicio, data <= fim)
###### ANÁLISES ######
### GOLS POR EDIÇÃO
gols.edicao <-
df %>%
group_by(torneio) %>%
summarise(gols_mandante = sum(mandante.placar , na.rm = TRUE),
gols_visitantes = sum(visitante.placar, na.rm = TRUE),
gols_total = gols_mandante + gols_visitantes ) %>%
ungroup() %>%
mutate(gols_mandante_perc = (gols_mandante/gols_total )*100,
gols_visitantes_perc = (gols_visitantes/gols_total)*100)
### Melhores ataques por edição
gols.clubes.mandantes <-
df %>%
rename(clube=mandante) %>%
group_by(torneio, clube) %>%
summarise(gols_mandante = sum(mandante.placar , na.rm = TRUE), .groups="keep")
gols.clubes.visitantes <-
df %>%
rename(clube=visitante) %>%
group_by(torneio, clube) %>%
summarise(gols_visitante = sum(visitante.placar , na.rm = TRUE), .groups="keep")
gols.clubes <-
inner_join(gols.clubes.mandantes, gols.clubes.visitantes, by=c("torneio","clube")) %>%
mutate(gols_total = gols_mandante + gols_visitante )
gols.torneio.ataque <-
gols.clubes %>%
group_by(torneio) %>%
summarise(ataque_pior = min(gols_total),
ataque_melhor = max(gols_total)) %>%
ungroup()
gols.torneio.ataque.pior <-
inner_join(gols.torneio.ataque, gols.clubes, by="torneio") %>%
filter(ataque_pior == gols_total) %>%
select(torneio, clube, ataque_pior)
gols.torneio.ataque.melhor <-
inner_join(gols.torneio.ataque, gols.clubes, by="torneio") %>%
filter(ataque_melhor == gols_total) %>%
select(torneio, clube, ataque_melhor)
gols.ataques <- inner_join(gols.torneio.ataque.pior, gols.torneio.ataque.melhor, by="torneio", suffix=c("_pior","_melhor"))
#### RESULTADOS
# Gols por edição
gols.edicao
# Melhores e piores ataques
gols.ataques
# Maior pontuador de todas as edições
pontos.participantes <-
df %>%
select(torneio, mandante) %>%
group_by(torneio) %>%
summarise( times = n_distinct(mandante)) %>%
ungroup() %>%
mutate(pontos_max = (times - 1)*2*3)
pontos <-
df %>%
select(torneio, mandante, visitante, mandante.placar, visitante.placar) %>%
mutate(pontos_mandante = ifelse(mandante.placar > visitante.placar, 3, ifelse(mandante.placar < visitante.placar, 0, 1)),
pontos_visitante = ifelse(visitante.placar > mandante.placar , 3, ifelse(visitante.placar < mandante.placar, 0, 1)))
pontos.mandantes <-
pontos %>%
group_by(torneio, mandante) %>%
summarise(pontos_mandante = sum(pontos_mandante, na.rm=TRUE), .groups="keep") %>%
rename(clube=mandante)
pontos.visitante <-
pontos %>%
group_by(torneio, visitante) %>%
summarise(pontos_visitante = sum(pontos_visitante, na.rm=TRUE), .groups="keep" ) %>%
rename(clube=visitante)
pontos.total <-
inner_join(pontos.mandantes, pontos.visitante, by=c("torneio","clube")) %>%
mutate(pontos_total = pontos_mandante + pontos_visitante)
### maior pontuador de todas as edições
maior.pontuador <- pontos.total %>% filter(pontos_total == max(pontos.total$pontos_total))
### menor pontuador de todas as edições
menor.pontuador <- pontos.total %>% filter(pontos_total == min(pontos.total$pontos_total))
###
campeoes <-
pontos.total %>%
group_by(torneio) %>%
summarise(maior_ponto = max(pontos_total)) %>%
ungroup() %>%
inner_join(pontos.total, by=c("torneio")) %>%
filter( maior_ponto == pontos_total ) %>%
select(-maior_ponto) %>%
inner_join(pontos.participantes, by="torneio") %>%
mutate(aproveitamento = (pontos_total/pontos_max)*100 ) %>%
mutate(ano = gsub('[a-z|A-Z]','',torneio))
### Campeões ano a ano
campeoes %>% select(torneio, clube, pontos_mandante, pontos_visitante, pontos_total, aproveitamento)
### campeões com a maior e menor pontuação
campeoes.pontuacao <-
campeoes %>%
mutate(maior_ponto = max(pontos_total),
menor_ponto = min(pontos_total)) %>%
filter(pontos_total == maior_ponto | pontos_total == menor_ponto) %>%
mutate( observacao = ifelse(pontos_total == maior_ponto, 'Campeão com a maior pontuação', 'Campeão com a menor pontuação')) %>%
select(torneio, clube, pontos_total, observacao)
### campeões com o maior e menor aproveitamento
campeoes.aproveitamento <-
campeoes %>%
mutate(maior_aproveitamento = max(aproveitamento),
menor_aproveitamento = min(aproveitamento)) %>%
filter(aproveitamento == maior_aproveitamento | aproveitamento == menor_aproveitamento) %>%
mutate( observacao = ifelse(aproveitamento == maior_aproveitamento, 'Campeão com o melhor aproveitamento', 'Campeão com o menor aproveitamento')) %>%
select( torneio, clube, aproveitamento, observacao )
### gráfico de aproveitamento dos campeões
ggplot(campeoes, aes(x=ano, y=aproveitamento, fill=clube)) +
geom_bar(position='dodge', stat='identity') +
geom_text(aes(label=as.integer(aproveitamento)), position=position_dodge(width=0.9), vjust=-0.25) +
labs(title='Aproveitamento dos campeões do brasileirão de pontos corridos', x='Ano', y='Aproveitamento') +
guides(colour = "none") +
theme_light() +
ggeasy::easy_center_title()
<file_sep>/jbrasileiraoRBase/rotinas/run.R
### remove variáveis
rm(list=ls())
### instala e carrega biblioteca
install.packages("this.path")
library(this.path, quietly=TRUE)
### define path a partir da pasta raiz do projeto
THIS_DIR <- gsub("/rotinas", '', this.dir())
### cria função para retornar path do source
pathSource = function(script='') {
files <- list.files(THIS_DIR, full.names=TRUE, recursive=TRUE, all.files=TRUE, pattern="(*.R$|.env$|.csv)")
fs <- data.frame(dirname = dirname(files), basename = basename(files), path = files)
if (script != '') {
fs <- fs[fs$basename == script,]
}
return(as.character(fs$path))
}
### carrega configurações necessárias
source(pathSource('config.R'))
### carrega datasets
df.periodo <- read.csv2(file = pathSource(enumDataSets$`campeonato-brasileiro-pontos-corridos-2003-2020-periodo.csv`), sep = ";", header = TRUE, stringsAsFactors = FALSE)
df.jogos <- read.csv2(file = pathSource(enumDataSets$`campeonato-brasileiro-pontos-corridos-2003-2020-jogos.csv` ), sep = ";", header = TRUE, stringsAsFactors = FALSE)
### padroniza caixa dos nomes das variáveis
names.periodo <- colnames(df.periodo)
names.jogos <- colnames(df.jogos)
names(df.periodo) <- tolower(names.periodo)
names(df.jogos) <- tolower(names.jogos)
### altera campos de datas de character para date
df.periodo['inicio'] <- as.Date(df.periodo$inicio, format = "%d/%m/%Y")
df.periodo['fim' ] <- as.Date(df.periodo$fim , format = "%d/%m/%Y")
df.jogos['data'] <- as.Date(df.jogos$data , format = "%d/%m/%Y")
### captalizar strings
df.jogos['dia' ] <- capwords(df.jogos$dia , TRUE)
df.jogos['mandante' ] <- capwords(df.jogos$mandante , TRUE)
df.jogos['visitante'] <- capwords(df.jogos$visitante, TRUE)
df.jogos['vencedor' ] <- capwords(df.jogos$vencedor , TRUE)
df.jogos['arena' ] <- capwords(df.jogos$arena , TRUE)
### junta os datasets e retorna apenas os registros corretos criados na junção (full join)
df <- merge(df.periodo, df.jogos)
df <- df[df$data >= df$inicio & df$data <= df$fim, ]
###### ANÁLISES ######
### GOLS POR EDIÇÃO
gols_mandante <- aggregate(x=df$mandante.placar , by=list(df$torneio), FUN=sum)
gols_visitante <- aggregate(x=df$visitante.placar, by=list(df$torneio), FUN=sum)
names(gols_mandante) <- c('torneio', 'gols_mandante')
names(gols_visitante) <- c('torneio', 'gols_visitante')
gols.edicao <- merge(gols_mandante, gols_visitante, by="torneio")
gols.edicao['gols_total' ] <- gols.edicao$gols_mandante + gols.edicao$gols_visitante
gols.edicao['gols_mandante_perc' ] <- (gols.edicao$gols_mandante/gols.edicao$gols_total)*100
gols.edicao['gols_visitantes_perc'] <- (gols.edicao$gols_visitante/gols.edicao$gols_total)*100
gols.edicao
### MELHORES E PIORES ATAQUES POR EDIÇÃO
df['clube'] <- df$mandante
gols.clubes.mandantes <- aggregate(x=df$mandante.placar , by=list(df$torneio, df$clube), FUN=sum)
names(gols.clubes.mandantes) <- c('torneio', 'clube', 'gols_mandante')
df['clube'] <- df$visitante
gols.clubes.visitantes <- aggregate(x=df$visitante.placar , by=list(df$torneio, df$clube), FUN=sum)
names(gols.clubes.visitantes) <- c('torneio', 'clube', 'gols_visitante')
gols.clubes <- merge(gols.clubes.mandantes, gols.clubes.visitantes, by=c("torneio","clube"))
gols.clubes['gols_total'] <- gols.clubes$gols_mandante + gols.clubes$gols_visitante
ataque_pior <- aggregate(x=gols.clubes$gols_total, by=list(gols.clubes$torneio), FUN=min)
ataque_melhor <- aggregate(x=gols.clubes$gols_total, by=list(gols.clubes$torneio), FUN=max)
names(ataque_pior) <- c('torneio','ataque_pior')
names(ataque_melhor) <- c('torneio','ataque_melhor')
gols.torneio.ataque.pior <- merge(gols.clubes, ataque_pior, by.x=c("torneio",'gols_total'), by.y=c("torneio","ataque_pior"))[c('torneio','clube','gols_total')]
names(gols.torneio.ataque.pior)[names(gols.torneio.ataque.pior) == 'gols_total'] <- 'ataque_pior'
gols.torneio.ataque.melhor <- merge(ataque_melhor, gols.clubes, by.x=c("torneio","ataque_melhor"), by.y=c("torneio",'gols_total'))[c('torneio','clube','ataque_melhor')]
gols.ataques <- merge(gols.torneio.ataque.melhor, gols.torneio.ataque.pior, by="torneio", suffix=c("_melhor","_pior"))
gols.ataques
# MAIOR E MENOR PONTUADOR DE TODAS AS EDIÇÕES
pontos.participantes <- aggregate(x=df[, c('mandante')], by=list(df[, c('torneio')]), FUN=n_distinct)
names(pontos.participantes) <- c('torneio','times')
pontos.participantes['pontos_max'] <- (pontos.participantes$times - 1)*2*3
pontos <- df[, c('torneio', 'mandante', 'visitante', 'mandante.placar', 'visitante.placar')]
pontos['pontos_mandante' ] <- ifelse(pontos$mandante.placar > pontos$visitante.placar, 3, ifelse(pontos$mandante.placar < pontos$visitante.placar, 0, 1))
pontos['pontos_visitante'] <- ifelse(pontos$visitante.placar > pontos$mandante.placar , 3, ifelse(pontos$visitante.placar < pontos$mandante.placar, 0, 1))
pontos.mandantes <- aggregate(x=pontos$pontos_mandante, by=list(pontos$torneio, pontos$mandante), FUN=sum)
names(pontos.mandantes) <- c('torneio','clube','pontos_mandante')
pontos.visitante <- aggregate(x=pontos$pontos_visitante, by=list(pontos$torneio, pontos$visitante), FUN=sum)
names(pontos.visitante) <- c('torneio','clube','pontos_visitante')
pontos.total <- merge(pontos.mandantes, pontos.visitante, by=c("torneio","clube"))
pontos.total['pontos_total'] <- pontos.total$pontos_mandante + pontos.total$pontos_visitante
### maior pontuador de todas as edições
maior.pontuador <- pontos.total[pontos.total$pontos_total == max(pontos.total$pontos_total), ]
maior.pontuador
### menor pontuador de todas as edições
menor.pontuador <- pontos.total[pontos.total$pontos_total == min(pontos.total$pontos_total), ]
menor.pontuador
### CAMPEÕES
campeoes <- aggregate(x=pontos.total$pontos_total, by=list(pontos.total$torneio), FUN=max)
names(campeoes) <- c('torneio','maior_ponto')
campeoes <- merge(campeoes, pontos.total, by=c("torneio"))
campeoes <- campeoes[campeoes$maior_ponto == campeoes$pontos_total, ]
campeoes <- merge(campeoes, pontos.participantes, by=c("torneio"))
campeoes['aproveitamento'] <- (campeoes$pontos_total/campeoes$pontos_max)*100
campeoes['ano' ] <- gsub('[a-z|A-Z]','', campeoes$torneio)
### Campeões ano a ano
campeoes[, c('torneio', 'clube', 'pontos_mandante', 'pontos_visitante', 'pontos_total', 'aproveitamento')]
### campeões com a maior e menor pontuação
campeoes.pontuacao <- campeoes[, c('torneio', 'clube', 'pontos_total', 'aproveitamento')]
campeoes.pontuacao['maior_ponto'] <- max(campeoes.pontuacao$pontos_total)
campeoes.pontuacao['menor_ponto'] <- min(campeoes.pontuacao$pontos_total)
campeoes.pontuacao <- campeoes.pontuacao[campeoes.pontuacao$pontos_total == campeoes.pontuacao$maior_ponto | campeoes.pontuacao$pontos_total == campeoes.pontuacao$menor_ponto, ]
campeoes.pontuacao['observacao'] <- ifelse(campeoes.pontuacao$pontos_total == campeoes.pontuacao$maior_ponto, 'Campeão com a maior pontuação', 'Campeão com a menor pontuação')
campeoes.pontuacao <- campeoes.pontuacao[, c('torneio', 'clube', 'pontos_total', 'observacao')]
campeoes.pontuacao
### campeões com o maior e menor aproveitamento
campeoes.aproveitamento <- campeoes[, c('torneio', 'clube', 'pontos_total', 'aproveitamento')]
campeoes.aproveitamento['maior_aproveitamento'] <- max(campeoes.aproveitamento$aproveitamento)
campeoes.aproveitamento['menor_aproveitamento'] <- min(campeoes.aproveitamento$aproveitamento)
campeoes.aproveitamento <- campeoes.aproveitamento[campeoes.aproveitamento$aproveitamento == campeoes.aproveitamento$maior_aproveitamento | campeoes.aproveitamento$aproveitamento == campeoes.aproveitamento$menor_aproveitamento, ]
campeoes.aproveitamento['observacao'] <- ifelse(campeoes.aproveitamento$aproveitamento == campeoes.aproveitamento$maior_aproveitamento, 'Campeão com o melhor aproveitamento', 'Campeão com o menor aproveitamento')
campeoes.aproveitamento <- campeoes.aproveitamento[, c('torneio', 'clube', 'aproveitamento', 'observacao')]
campeoes.aproveitamento
### gráfico de aproveitamento dos campeões
ggplot(campeoes, aes(x=ano, y=aproveitamento, fill=clube)) +
geom_bar(position='dodge', stat='identity') +
geom_text(aes(label=as.integer(aproveitamento)), position=position_dodge(width=0.9), vjust=-0.25) +
labs(title='Aproveitamento dos campeões do brasileirão de pontos corridos', x='Ano', y='Aproveitamento') +
guides(colour = "none") +
theme_light() +
ggeasy::easy_center_title()
<file_sep>/README.md
# R
Repositório destinado para aplicações desenvolvidas em R.
| 49eb977dfad5f00bd05d8d3d12a9872cf6e433ce | [
"Markdown",
"R"
]
| 7 | R | juvenalfonseca/R | 6452b77bcb1b9bbcc1469fa6b429ae6452de9d5c | 3160d33a56582083cf7d28ee8e7592e0233b57c4 |
refs/heads/master | <repo_name>carrych/urij_bura_react<file_sep>/to-do-list/src/components/search-panel/search-panel.js
import React from "react";
import './search-panel.css';
const SearchPanel = () => {
return <input className="search-input" placeholder="search"/>;
};
export default SearchPanel;
| 2218b8cc7901d6baba7ad2012888d189bca6f0fe | [
"JavaScript"
]
| 1 | JavaScript | carrych/urij_bura_react | ff1e0d078fdf451679724340fb0bff4e80743b0d | 96d4e8f444b737764a61ce800e9e2e7d8f593d03 |
refs/heads/main | <repo_name>Rabee-Omran/Rest-Api-expenses-app-Django<file_sep>/userstats/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('expense_category_data/', views.ExpenseSummaryStats.as_view(), name="expense_category_data"),
path('income_source_data/', views.IncomeSourcesSummaryStats.as_view(), name="income_source_data"),
]
<file_sep>/requirements.txt
appdirs==1.4.3
asgiref==3.3.1
autopep8==1.5.5
CacheControl==0.12.6
certifi==2019.11.28
chardet==3.0.4
colorama==0.4.3
contextlib2==0.6.0
coreapi==2.3.3
coreschema==0.0.4
distlib==0.3.0
distro==1.4.0
Django==3.1.6
django-filter==2.4.0
djangorestframework==3.12.2
djangorestframework-simplejwt==4.6.0
drf-yasg==1.20.0
Faker==6.1.1
html5lib==1.0.1
idna==2.8
inflection==0.5.1
ipaddr==2.2.0
itypes==1.2.0
Jinja2==2.11.3
lockfile==0.12.2
Markdown==3.3.3
MarkupSafe==1.1.1
msgpack==0.6.2
packaging==20.3
pep517==0.8.2
pep8==1.7.1
progress==1.5
pycodestyle==2.6.0
PyJWT==2.0.1
pyparsing==2.4.6
python-dateutil==2.8.1
pytoml==0.1.21
pytz==2021.1
requests==2.22.0
retrying==1.3.3
ruamel.yaml==0.16.12
ruamel.yaml.clib==0.2.2
six==1.14.0
sqlparse==0.4.1
text-unidecode==1.3
toml==0.10.2
uritemplate==3.0.1
urllib3==1.25.8
webencodings==0.5.1
<file_sep>/README.md
# Rest-Api-expenses-app-Django
<file_sep>/utils/views.py
from django.http import JsonResponse
def error_404(request, exception):
message = ('the end point not found')
response = JsonResponse(data= {'message':message, 'status_code': 404})
response.status_code = 404
return response
def error_500(request):
message = ('An error occurred')
response = JsonResponse(data= {'message':message, 'status_code': 500})
response.status_code = 500
return response<file_sep>/authentication/urls.py
from django.urls import path
from .views import AuthUserAPIView, LoginAPIView, LogoutAPIView, PasswordTokenCheckAPI, RegisterView, RequestPasswordResetEmail, SetNewPasswordAPIView, VerifyEmail
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
path('register/', RegisterView.as_view(), name="register"),
path('login/', LoginAPIView.as_view(), name="login"),
path('logout/', LogoutAPIView.as_view(), name="logout"),
path('email-verify/', VerifyEmail.as_view(), name="email-verify"),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
path('user/', AuthUserAPIView.as_view(), name='user'),
path('request-reset-email/', RequestPasswordResetEmail.as_view(),
name="request-reset-email"),
path('password-reset/<uidb64>/<token>/',
PasswordTokenCheckAPI.as_view(), name='password-reset-confirm'),
path('password-reset-complete', SetNewPasswordAPIView.as_view(),
name='password-reset-complete')
]<file_sep>/userstats/views.py
from django.shortcuts import render
from rest_framework.views import APIView
import datetime
from expenses.models import Expense
from rest_framework import status, response
from income.models import Income
class ExpenseSummaryStats(APIView):
def get_category(self, expense):
return expense.category
def get_amount_for_category(self, expenses_list, category):
expenses = expenses_list.filter(category = category)
amount = 0
for expense in expenses:
amount += expense.amount
return {'amount' : str(amount)}
def get(self, request):
todays_date = datetime.date.today()
ayear_ago = todays_date - datetime.timedelta(days = 30*12)
expenses = Expense.objects.filter(owner = request.user, date__gte = ayear_ago, date__lte = todays_date)
final = {}
#set for remove duplicate -- map for loop and convert to list
categories = set(map(self.get_category , expenses))
for expense in expenses:
for category in categories:
final[category]= self.get_amount_for_category(expenses, category)
return response.Response({
'category_data': final
}, status = status.HTTP_200_OK)
###############################################################################
class IncomeSourcesSummaryStats(APIView):
def get_source(self, income):
return income.source
def get_amount_for_source(self, income_list, source):
incomes = income_list.filter(source = source)
amount = 0
for income in incomes:
amount += income.amount
return {'amount' : str(amount)}
def get(self, request):
todays_date = datetime.date.today()
ayear_ago = todays_date - datetime.timedelta(days = 30*12)
incomes = Income.objects.filter(owner = request.user, date__gte = ayear_ago, date__lte = todays_date)
final = {}
#set for remove duplicate -- map for loop and convert to list
sources = set(map(self.get_source , incomes))
for income in incomes:
for source in sources:
final[source]= self.get_amount_for_source(incomes, source)
return response.Response({
'income_data': final
}, status = status.HTTP_200_OK)
<file_sep>/utils/exception_handler.py
from rest_framework import response
from rest_framework.views import exception_handler
from authentication.views import AuthUserAPIView
def custom_exception_handler(exc, context):
handlers = {
'ValiddationError': _handle_generic_error,
'Http404': _handle_generic_error,
'PermissionDenied': _handle_generic_error,
'NotAuthenticated': _handle_authentication_error,
}
response = exception_handler(exc, context)
#add status code to response
if response is not None:
# import pdb ; pdb.set_trace()
##########################
#custom status code and message for custom view
if "AuthUserAPIView" in str(context['view']) and exc.status_code == 401:
response.status_code = 200
response.data = {'is logged in :' : False, 'status_code' : 200}
return response
#########################
response.data['status_code'] = response.status_code
#return exception class name
exception_class = exc.__class__.__name__
if exception_class in handlers:
return handlers[exception_class](exc, context, response)
return response
def _handle_authentication_error(exc, context, response):
response.data = {
'error': 'please login first. ',
'status_code' : response.status_code
}
return response
def _handle_generic_error(exc, context, response):
return response
| 05508104cf49cab283163e373711882beb9026aa | [
"Markdown",
"Python",
"Text"
]
| 7 | Python | Rabee-Omran/Rest-Api-expenses-app-Django | 0e73ebdf24494646e8ddb00696cd5a7367ca9ad2 | f3c595733361313d977448f4c8b4dae832e746b4 |
refs/heads/master | <repo_name>Zhaofan-Su/esg-demo<file_sep>/src/main/java/com/pwccn/esg/api/DataController.java
package com.pwccn.esg.api;
import com.pwccn.esg.dto.DataAnalysisDTO;
import com.pwccn.esg.model.CompanyEntity;
import com.pwccn.esg.model.IndicatorDataEntity;
import com.pwccn.esg.model.IndicatorEntity;
import com.pwccn.esg.repository.IndicatorDataRepository;
import com.pwccn.esg.repository.IndicatorRepository;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/api/data")
public class DataController {
@Autowired
private IndicatorRepository indicatorRepository;
@ApiOperation(value = "Analysis the data of the indicators")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The data analysis has been created."),
@ApiResponse(code = 204, message = "There is no data in the indicator."),
})
@PreAuthorize("hasRole('ROLE_ADMIN1')")
@GetMapping("/{indicatorName}")
public ResponseEntity<List<DataAnalysisDTO>> doAnalysis(@PathVariable String indicatorName) {
List<IndicatorEntity> indicatorEntities = indicatorRepository.findByName(indicatorName);
List<DataAnalysisDTO> results = new ArrayList<>();
for(IndicatorEntity indicatorEntity : indicatorEntities) {
if(!indicatorEntity.getIndicatorData().getStatus().equals("提交")) {
continue;
}
DataAnalysisDTO dataAnalysisDTO = new DataAnalysisDTO();
dataAnalysisDTO.setCompanyName(indicatorEntity.getCompany().getName());
dataAnalysisDTO.setUnit(indicatorEntity.getIndicatorData().getUnit());
String data = indicatorEntity.getIndicatorData().getSections();
double dataSum = 0.00;
String[] stringDatas = data.split(",");
for(int i = 0; i < stringDatas.length; i++) {
dataSum = dataSum + Double.parseDouble(stringDatas[i]);
}
dataAnalysisDTO.setData(new BigDecimal(dataSum).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
results.add(dataAnalysisDTO);
}
if(results.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(results, HttpStatus.OK);
}
}
<file_sep>/src/main/java/com/pwccn/esg/model/CompanyEntity.java
package com.pwccn.esg.model;
import com.pwccn.esg.dto.CompanyDTO;
import com.pwccn.esg.dto.UserDTO;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "company")
public class CompanyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String industry;
@OneToMany(mappedBy = "company", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<UserEntity> users;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "template_id")
private TemplateEntity templateEntity;
public CompanyEntity() {
}
public CompanyEntity(CompanyDTO companyDTO) {
setId(companyDTO.getId());
setName(companyDTO.getName());
setIndustry(companyDTO.getIndustry());
List<UserEntity> userEntities = new ArrayList<>();
for(UserDTO dto : companyDTO.getUsers()) {
userEntities.add(new UserEntity(dto));
}
setUsers(userEntities);
}
public void setTemplateEntity(TemplateEntity templateEntity) {
this.templateEntity = templateEntity;
}
public TemplateEntity getTemplateEntity() {
return templateEntity;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public List<UserEntity> getUsers() {
return users;
}
public void setUsers(List<UserEntity> users) {
this.users = users;
}
public void setIndustry(String industry) {
this.industry = industry;
}
public String getIndustry() {
return industry;
}
}
<file_sep>/src/main/resources/db/V2__DEV_DATA.sql
# ************************************************************
# Sequel Pro SQL dump
# Version 4541
#
# http://www.sequelpro.com/
# https://github.com/sequelpro/sequelpro
#
# Host: 127.0.0.1 (MySQL 5.7.21)
# Database: db_example
# Generation Time: 2018-11-04 13:03:35 +0000
# ************************************************************
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
# Dump of table indicator
# ------------------------------------------------------------
LOCK TABLES `indicator` WRITE;
/*!40000 ALTER TABLE `indicator` DISABLE KEYS */;
INSERT INTO `indicator` (`id`, `name`, `level`, `description`,`type`,`parent`,`company_id`,`data_id`,`module_id`)
VALUES
(1,'排放管理',1,'统计该公司有害化工产物的数据',NULL,NULL,1,NULL,1),
(2,'有害气体',2,NULL,NULL,1,1,NULL,NULL),
(3,'有害液体',2,NULL,NULL,1,1,NULL,NULL),
(4,'二氧化硫',3,'每月二氧化硫排放量','quantity',2,1,1,NULL),
(5,'排放管理',1,'统计该公司有害化工产物的数据',NULL,NULL,2,NULL,1),
(6,'有害气体',2,NULL,NULL,5,2,NULL,NULL),
(7,'有害液体',2,NULL,NULL,5,2,NULL,NULL),
(8,'二氧化硫',3,'每月二氧化硫排放量','quantity',6,2,2,NULL),
(9,'排放管理',1,'统计该公司有害化工产物的数据',NULL,NULL,3,NULL,1),
(10,'有害气体',2,NULL,NULL,9,3,NULL,NULL),
(11,'有害液体',2,NULL,NULL,9,3,NULL,NULL),
(12,'二氧化硫',3,'每月二氧化硫排放量','quantity',10,3,3,NULL),
(13,'含镉污水',3,'记录含镉污水具体情况','quality',3,1,4,NULL),
(14,'含铅污水',3,'记录污水含铅量具体情况','quality',7,2,5,NULL),
(15,'管培生管理',1,'统计公司管培生项目相关数据',NULL,NULL,4,NULL,2),
(16,'项目资金',2,NULL,NULL,15,4,NULL,NULL),
(17,'管培生评估',2,NULL,NULL,15,4,NULL,NULL),
(18,'每月开销',3,'一位管培生可用资金费用','quantity',16,4,6,NULL),
(19,'管培生管理',1,'统计公司管培生项目相关数据',NULL,NULL,5,NULL,2),
(20,'项目资金',2,NULL,NULL,19,5,NULL,NULL),
(21,'管培生评估',2,NULL,NULL,19,5,NULL,NULL),
(22,'每月开销',3,'一位管培生每月预估花费费用','quantity',20,5,7,NULL),
(23,'管培生管理',1,'统计公司管培生项目相关数据',NULL,NULL,6,NULL,2),
(24,'项目资金',2,NULL,NULL,23,6,NULL,NULL),
(25,'管培生评估',2,NULL,NULL,23,6,NULL,NULL),
(26,'每月开销',3,'一位管培生每月预估花费费用','quantity',20,6,8,NULL),
(27,'管培生综合素质评价',3,'记录公司对于每年管培生的评价','quality',17,4,9,NULL),
(28,'管培生综合素质评价',3,'记录公司对于每年管培生的看法评价','quality',21,5,10,NULL),
(29,'管培生综合素质评价',3,'公司对于每年管培生的评估记录','quality',25,6,11,NULL),
(30,'公司产品',1,'统计公司产品相关数据',NULL,NULL,7,NULL,3),
(31,'云产品',2,NULL,NULL,30,7,NULL,NULL),
(32,'SAP HANA',3,'SAP HANA相关评价','quality',31,7,12,NULL),
(33,'公司产品',1,'统计公司产品相关数据',NULL,NULL,8,NULL,3),
(34,'云产品',2,NULL,NULL,33,8,NULL,NULL),
(35,'阿里云',3,'阿里云相关评价','quality',34,8,13,NULL);
/*!40000 ALTER TABLE `indicator` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table indicator_data
# ------------------------------------------------------------
LOCK TABLES `indicator_data` WRITE;
/*!40000 ALTER TABLE `indicator_data` DISABLE KEYS */;
INSERT INTO `indicator_data` (`id`, `unit`, `context`, `sections`,`new_context`,`new_sections`,`status`)
VALUES
(1,'m^3',NULL,'10000,10000,20000,10000,20000,30000,20000,12000,15000,23000,18000,20000',NULL,NULL,'待审核'),
(2,'m^3',NULL,'15000,12000,19000,9000,21000,35000,15000,10000,12500,22500,17500,15000',NULL,NULL,'待审核'),
(3,'m^3',NULL,'9000,9500,18000,12000,22000,32000,21000,11500,15400,23400,17600,21000',NULL,NULL,'待审核'),
(4,NULL,'镉含量:0.004mg/L,符合标准',NULL,NULL,NULL,'待审核'),
(5,NULL,'铅含量:0.01mg/L',NULL,NULL,NULL,'待审核'),
(6,'$',NULL,'800,800,800,850,900,1000,1500,2000,2500,3000,4000,5000',NULL,NULL,'待审核'),
(7,'$',NULL,'750,750,750,750,800,900,1200,1500,2000,3000,4000,5000',NULL,NULL,'待审核'),
(8,'$',NULL,'750,750,750,750,800,950,1250,1550,2400,3200,4000,5500',NULL,NULL,'待审核'),
(9,NULL,'相较于2017年,2018年管培生业务能力普遍较高,经培训之后均有较大提升',NULL,NULL,NULL,'待审核'),
(10,NULL,'2018年管培生综合素质水平与往年没有过大差别,保持在平均水平',NULL,NULL,NULL,'通过'),
(11,NULL,'2018年管培生综合素质为历年最高,但培训之后仍有部分不合格',NULL,NULL,NULL,'待审核'),
(12,NULL,'软硬件结合体,提供高性能的数据查询功能',NULL,NULL,NULL,'提交'),
(13,NULL,'云翼计划助力学生未来反展',NULL,NULL,NULL,'提交');
/*!40000 ALTER TABLE `indicator_data` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table indicator_attribute
# ------------------------------------------------------------
# Dump of table module
# ------------------------------------------------------------
LOCK TABLES `module` WRITE;
/*!40000 ALTER TABLE `module` DISABLE KEYS */;
INSERT INTO `module` (`id`, `name`)
VALUES
(1,'环境管理'),
(2,'培训管理'),
(3,'产品管理'),
(4,'公益管理'),
(5,'员工管理'),
(6,'安全管理');
/*!40000 ALTER TABLE `module` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table template
# ------------------------------------------------------------
LOCK TABLES `template` WRITE;
/*!40000 ALTER TABLE `template` DISABLE KEYS */;
INSERT INTO `template` (`id`, `name`)
VALUES
(1,'巴斯夫综合数据'),
(2,'陶氏杜邦综合数据'),
(3,'中石化综合数据'),
(4,'联合健康保险综合数据'),
(5,'安盛集团综合数据'),
(6,'中国工商银行综合数据'),
(7,'SAP综合数据'),
(8,'阿里巴巴综合数据');
/*!40000 ALTER TABLE `template` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table template_has_module
# ------------------------------------------------------------
LOCK TABLES `template_has_module` WRITE;
/*!40000 ALTER TABLE `template_has_module` DISABLE KEYS */;
INSERT INTO `template_has_module` (`template_id`, `module_id`)
VALUES
(1,5),
(1,6),
(1,1),
(2,5),
(2,6),
(2,1),
(3,5),
(3,6),
(3,1),
(4,5),
(4,6),
(4,2),
(5,5),
(5,6),
(5,2),
(6,5),
(6,6),
(6,2),
(7,5),
(7,6),
(7,3),
(8,5),
(8,6),
(8,3);
/*!40000 ALTER TABLE `template_has_module` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table role
# ------------------------------------------------------------
LOCK TABLES `role` WRITE;
/*!40000 ALTER TABLE `role` DISABLE KEYS */;
INSERT INTO `role` (`id`, `name`)
VALUES
(1,'ROLE_ADMIN1'),
(2,'ROLE_ADMIN2'),
(3,'ROLE_AUDITOR'),
(4,'ROLE_OPERATOR');
/*!40000 ALTER TABLE `role` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table user
# ------------------------------------------------------------
LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` (`id`, `username`,`password`,`company_id`,`contactor`,`telephone`,`email`)
VALUES
(0,'ADMIN','$2a$10$qe.2q0.icyebaiqar.7TguXLnmgqpVwIFdb53WsNRXBfkpx1..rRC',0,'大牛','010-123456789','<EMAIL>'),
(1,'ADMIN_BSF','$2a$10$TIAgXdgLiNHH4VYqTQO8k.XNgZBPx3ev/7vzLwZ0TjpzhsXV4TtGq',1,'Lee','86-15503748989','<EMAIL>'),
(2,'ADMIN_TSDB','$2a$10$bIayB.iYYoRZH.VomCj3IOXlnn2mt6hhPp5.aBiMmltAU4BTpa8KG',2,'Brouce','987654321','<EMAIL>'),
(3,'ADMIN_ZSH','$2a$10$LwDI.mDz7SmtwnMuGV0j4uMo.RbDf8G9/oQIhcbMqC/SFdTGAxVVe',3,'王建国','989899988','<EMAIL>'),
(4,'ADMIN_LHJKBX','$2a$10$NPUT4ne7V.pH.G/W9LYVWOI4/3qUD/dJTX.UO0uWAzPxBAWwvONpi',4,'Merry','010-78698324','<EMAIL>'),
(5,'ADMIN_ASJT','$2a$10$AVLo/pEt01HGwq8Irzqqsev5XBePxBAwUbfWTNa0LM2DAGdTahNJ6',5,'苏晓','18717710887','<EMAIL>'),
(6,'ADMIN_ZGGSYH','$2a$10$Jz.1fk4NS8u48UWQW2JjveSx9nEhsNKSIxN1WK5f5G7R9j0zaYQTe',6,'岳小珏','15903748787','<EMAIL>'),
(7,'ADMIN_SAP','$2a$10$XDxB3TS.Kf1JIbaZU0ZQR.uUZkD3eWAiPcGPl0Kt5bQrHuTMZyjXq',7,'Celia','13479802342','<EMAIL>'),
(8,'ADMIN_ALBB','$2a$10$dFUUZgP2nFGQrOnHKSiQ1uQZiqCR61JUL1UyIR6yjRiPFuT5oEx4K',8,'马雲','999988887','<EMAIL>'),
(9,'ADMIN_IBM','$2a$10$FViaHxlE5n3xm6hNXQr7J.gJptPIPbvbLjyTT0co643d2cJsaGkA2',9,'Martin','010-2789874','<EMAIL>'),
(10,'ADMIN_UMG','$2a$10$zfqdmd928GDTWecM9CLxVuc1uzjjrPPiAP8zqAngYulMFJmTHdk0K',10,'Mr.R','9824332','<EMAIL>'),
(11,'BSF_AU','$2a$10$b3WvCVsixO/JC4XrBpFHeO9hnJ/ZADdkJVI.oD43hC0SZATRlkj.2',1,'张三','19842332448','<EMAIL>'),
(12,'BSF_OP','$2a$10$bCpTkXG7VEmLbS9qFg2jh.j7fKghFjorbXuIXVAsg50YkgL6J3kEq',1,'渡辺ゆり子','91323993','<EMAIL>');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table user_roles
# ------------------------------------------------------------
LOCK TABLES `user_roles` WRITE;
/*!40000 ALTER TABLE `user_roles` DISABLE KEYS */;
INSERT INTO `user_roles` (`user_id`, `role_id`)
VALUES
(0,1),
(1,2),
(2,2),
(3,2),
(4,2),
(5,2),
(6,2),
(7,2),
(8,2),
(9,2),
(10,2),
(11,3),
(12,4);
/*!40000 ALTER TABLE `user_roles` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table role
# ------------------------------------------------------------
LOCK TABLES `company` WRITE;
/*!40000 ALTER TABLE `company` DISABLE KEYS */;
INSERT INTO `company` (`id`, `name`,`template_id`,`industry`)
VALUES
(0,'PWC',null,null),
(1,'巴斯夫',1,'化工'),
(2,'陶氏杜邦',2,'化工'),
(3,'中石化',3,'化工'),
(4,'联合健康保险',4,'金融'),
(5,'安盛集团',5,'金融'),
(6,'中国工商银行',6,'金融'),
(7,'SAP',7,'互联网'),
(8,'阿里巴巴',8,'互联网'),
(9,'IBM',null,'互联网'),
(10,'Universal Music Group',null,'娱乐');
/*!40000 ALTER TABLE `company` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table role
# ------------------------------------------------------------
LOCK TABLES `domain` WRITE;
/*!40000 ALTER TABLE `domain` DISABLE KEYS */;
INSERT INTO `domain` (`id`, `name`)
VALUES
(1,'环境'),
(2,'社会'),
(3,'治理');
/*!40000 ALTER TABLE `domain` ENABLE KEYS */;
UNLOCK TABLES;
# Dump of table role
# ------------------------------------------------------------
LOCK TABLES `topic` WRITE;
/*!40000 ALTER TABLE `topic` DISABLE KEYS */;
INSERT INTO `topic` (`id`, `name`,`domain_id`)
VALUES
(1,'空气质量检测',1),
(2,'污水排放管理',1),
(3,'test1_E',1),
(4,'test2_E',1),
(5,'test3_E',1),
(6,'职员福利保障',2),
(7,'社会贡献度',2),
(8,'test1_S',2),
(9,'test2_S',2),
(10,'test3_S',2),
(11,'员工管理制度',3),
(12,'公司管理评估',3),
(13,'test1_G',3),
(14,'test2_G',3),
(15,'test3_G',3);
/*!40000 ALTER TABLE `topic` ENABLE KEYS */;
UNLOCK TABLES;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/src/main/java/com/pwccn/esg/dto/IndicatorDataDTO.java
package com.pwccn.esg.dto;
import com.pwccn.esg.model.IndicatorDataEntity;
import com.pwccn.esg.model.IndicatorEntity;
public class IndicatorDataDTO {
private Integer id;
private String unit;
private String sections;
private String newSections;
private String context;
private String newContext;
private String status;
public IndicatorDataDTO() {
}
public IndicatorDataDTO(IndicatorDataEntity data) {
setId(data.getId());
setContext(data.getContext());
setSections(data.getSections());
setUnit(data.getUnit());
setNewContext(data.getNewContext());
setNewSections(data.getNewSections());
setStatus(data.getStatus());
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setSections(String sections) {
this.sections = sections;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public String getSections() {
return sections;
}
public String getNewContext() {
return newContext;
}
public String getNewSections() {
return newSections;
}
public void setNewContext(String newContext) {
this.newContext = newContext;
}
public void setNewSections(String newSections) {
this.newSections = newSections;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
}
<file_sep>/src/main/java/com/pwccn/esg/repository/IndicatorRepository.java
package com.pwccn.esg.repository;
import com.pwccn.esg.model.CompanyEntity;
import com.pwccn.esg.model.IndicatorEntity;
import com.pwccn.esg.model.ModuleEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface IndicatorRepository extends JpaRepository<IndicatorEntity, Integer> {
List<IndicatorEntity> findByParentId(Integer parent);
List<IndicatorEntity> findByName(String name);
List<IndicatorEntity> findByLevel(Integer level);
List<IndicatorEntity> findByCompanyAndModule(CompanyEntity companyEntity, ModuleEntity moduleEntity);
}
<file_sep>/src/main/java/com/pwccn/esg/repository/TemplateRepository.java
package com.pwccn.esg.repository;
import com.pwccn.esg.model.TemplateEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TemplateRepository extends JpaRepository<TemplateEntity, Integer> {
TemplateEntity findByName(String name);
}
<file_sep>/README.md
# esg-demo
<file_sep>/src/main/java/com/pwccn/esg/dto/TemplateDTO.java
package com.pwccn.esg.dto;
import com.pwccn.esg.model.TemplateEntity;
public class TemplateDTO {
private Integer id;
private String name;
private String companyName;
private Integer companyId;
public TemplateDTO() {
}
public TemplateDTO(TemplateEntity template) {
setId(template.getId());
setName(template.getName());
setCompanyName(template.getCompanyEntity().getName());
setCompanyId(template.getCompanyEntity().getId());
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCompanyName() {
return companyName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCompanyId() {
return companyId;
}
public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}
}
<file_sep>/src/main/java/com/pwccn/esg/api/ModuleController.java
package com.pwccn.esg.api;
import com.pwccn.esg.dto.IndicatorDTO;
import com.pwccn.esg.dto.ModuleDTO;
import com.pwccn.esg.model.CompanyEntity;
import com.pwccn.esg.model.IndicatorEntity;
import com.pwccn.esg.model.ModuleEntity;
import com.pwccn.esg.repository.CompanyRepository;
import com.pwccn.esg.repository.IndicatorRepository;
import com.pwccn.esg.repository.ModuleRepository;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@RestController
@RequestMapping(path = "/api/modules")
public class ModuleController {
private ModuleRepository moduleRepository;
@Autowired
public ModuleController(ModuleRepository moduleRepository) {
this.moduleRepository = moduleRepository;
}
@ApiOperation(value = "Level 1 and level 2 admin get all modules.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "All the modules have been gotten."),
})
@GetMapping
@PreAuthorize("hasAnyRole('ROLE_ADMIN1','ROLE_ADMIN2')")
public ResponseEntity<List<ModuleDTO>> all() {
List<ModuleEntity> modules = moduleRepository.findAll();
List<ModuleDTO> moduleDTOs = new ArrayList<>();
for (ModuleEntity module : modules) {
moduleDTOs.add(new ModuleDTO(module));
}
return new ResponseEntity<>(moduleDTOs, HttpStatus.OK);
}
@ApiOperation(value = "Get all level-1 indicators of the company's module.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The company's module's level 1 indicators have been gotten."),
@ApiResponse(code = 404, message = "The module doesn't exit."),
})
@GetMapping(path = "/{Cid}/{Mid}/indicators")
public ResponseEntity<List<IndicatorDTO>> getAllIndicators(@PathVariable Integer Cid, @PathVariable Integer Mid ) {
Optional<ModuleEntity> module = moduleRepository.findById(Mid);
if (!module.isPresent()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Set<IndicatorEntity> indicators = module.get().getIndicators();
List<IndicatorDTO> indicatorDTOs = new ArrayList<>();
for (IndicatorEntity indicator : indicators) {
if(indicator.getCompany().getId() == Cid && indicator.getLevel() == 1) {
indicatorDTOs.add(new IndicatorDTO(indicator));
}
}
return new ResponseEntity<>(indicatorDTOs, HttpStatus.OK);
}
}
<file_sep>/src/main/java/com/pwccn/esg/repository/UserRepository.java
package com.pwccn.esg.repository;
import com.pwccn.esg.model.CompanyEntity;
import com.pwccn.esg.model.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<UserEntity, Integer> {
UserEntity findByUsername(String username);
UserEntity findByUsernameAndCompany(String username, CompanyEntity companyEntity);
UserEntity findByEmail(String email);
}
<file_sep>/src/main/java/com/pwccn/esg/api/SurveyController.java
package com.pwccn.esg.api;
import com.pwccn.esg.dto.CompanyDTO;
import com.pwccn.esg.model.CompanyEntity;
import com.pwccn.esg.model.DomainEntity;
import com.pwccn.esg.model.TopicEntity;
import com.pwccn.esg.repository.CompanyRepository;
import com.pwccn.esg.repository.DomainRepository;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping(path = "/api/survey")
@PreAuthorize("hasRole('ROLE_ADMIN1')")
public class SurveyController {
@Autowired
private CompanyRepository companyRepository;
@Autowired
private DomainRepository domainRepository;
@ApiOperation(value ="Get all the companies/stakeholders by industry.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Get all the companies successfully."),
@ApiResponse(code = 204, message = "No company exits."),
@ApiResponse(code = 404, message = "Not such an industry.")
})
@GetMapping(value = "/Stakeholders/{industry}")
public ResponseEntity<List<String>> getAllStakeholders(@PathVariable String industry){
if(!indudtries().contains(industry)) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
List<CompanyEntity> entities = companyRepository.findByIndustry(industry);
List<String> result = new ArrayList<>();
if(entities.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
for(CompanyEntity entity : entities) {
result.add(entity.getName());
}
return new ResponseEntity<>(result,HttpStatus.OK);
}
@ApiOperation(value = "Get all topics of a domain(环境/社会/治理).")
@ApiResponses({
@ApiResponse(code = 200, message = "All topics have been found successful."),
@ApiResponse(code = 204, message = "No topics for this domain."),
@ApiResponse(code = 404, message = "No such a domain.")
})
@GetMapping(value = "/topics/{domain}")
public ResponseEntity<List<String>> getTopics(@PathVariable String domain){
DomainEntity domainEntity = domainRepository.findByName(domain);
if(domainEntity!= null){
List<String> result = new ArrayList<>();
List<TopicEntity> topics = domainEntity.getTopics();
if(topics.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
for(TopicEntity topicEntity : topics) {
result.add(topicEntity.getName());
}
return new ResponseEntity<>(result, HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
@ApiOperation(value = "Get all industries.")
@ApiResponses({
@ApiResponse(code = 200, message = "Find all industries successfully."),
@ApiResponse(code = 204, message = "No industry exits.")
})
@GetMapping("/indutries")
public ResponseEntity<List<String>> getIndustries() {
List<String> result = indudtries();
if(result != null) {
return new ResponseEntity<>(result, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
private List<String> indudtries(){
List<String> result = new ArrayList<>();
List<CompanyEntity> companyEntities = companyRepository.findAll();
for(CompanyEntity companyEntity : companyEntities) {
if(!result.contains(companyEntity.getIndustry())) {
result.add(companyEntity.getIndustry());
}
}
return result;
}
}
<file_sep>/src/main/resources/db/V1__INIT_DB.sql
-- MySQL Script generated by MySQL Workbench
-- Mon Nov 5 00:55:35 2018
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema esg
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema esg
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS esg DEFAULT CHARACTER SET utf8 ;
USE esg ;
-- -----------------------------------------------------
-- Table `esg`.`template`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`template` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`module`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`module` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`indicator`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`indicator` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`level` INT NOT NULL,
`description` VARCHAR(255) NULL,
`type` VARCHAR(255) NULL,
`parent` INT NULL,
`company_id` INT NULL,
`data_id` INT NULL,
`module_id` INT NULL,
PRIMARY KEY (`id`),
INDEX `fk_indicator_parent_idx` (`parent` ASC),
CONSTRAINT `fk_indicator_parent`
FOREIGN KEY (`parent`)
REFERENCES esg.`indicator` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`indicator_data`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`indicator_data` (
`id` INT NOT NULL AUTO_INCREMENT,
`unit` VARCHAR(45) NULL,
`context` VARCHAR(255) NULL,
`sections` VARCHAR(255) NULL,
`new_context` VARCHAR(255) NULL,
`new_sections` VARCHAR(255) NULL,
`status` VARCHAR(255) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`template_has_module`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`template_has_module` (
`template_id` INT NOT NULL,
`module_id` INT NOT NULL,
PRIMARY KEY (`template_id`, `module_id`),
INDEX `fk_template_has_module_module1_idx` (`module_id` ASC),
INDEX `fk_template_has_module_template1_idx` (`template_id` ASC),
CONSTRAINT `fk_template_has_module_template1`
FOREIGN KEY (`template_id`)
REFERENCES esg.`template` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_template_has_module_module1`
FOREIGN KEY (`module_id`)
REFERENCES esg.`module` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`user` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL,
`password` VARCHAR(255) NOT NULL,
`company_id` INT,
`contactor` VARCHAR(255) NULL,
`telephone` VARCHAR(255) NULL,
`email` VARCHAR(255) NULL,
PRIMARY KEY (`id`),
INDEX `fk_user_company1`(`company_id`),
CONSTRAINT `fk_user_company1`
FOREIGN KEY (`company_id`)
REFERENCES esg.`company` (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`role`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`role` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`company`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`company` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`template_id` INT NULL,
`industry` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`user_roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`user_roles` (
`user_id` INT NOT NULL,
`role_id` INT NOT NULL,
PRIMARY KEY (`user_id`, `role_id`),
INDEX `fk_user_roles_user1_idx` (`user_id` ASC),
INDEX `fk_user_roles_role1_idx` (`role_id` ASC),
CONSTRAINT `fk_user_roles_role1`
FOREIGN KEY (`role_id`)
REFERENCES esg.`role` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_user_roles_user1`
FOREIGN KEY (`user_id`)
REFERENCES esg.`user` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`domain`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`domain` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `esg`.`topic`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS esg.`topic` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`domain_id` INT NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_topic_domain1`(`domain_id`),
CONSTRAINT `fk_topic_domain1`
FOREIGN KEY (`domain_id`)
REFERENCES esg.`domain` (`id`))
ENGINE = InnoDB;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
<file_sep>/src/main/java/com/pwccn/esg/api/MailController.java
package com.pwccn.esg.api;
import com.pwccn.esg.dto.UserDTO;
import com.pwccn.esg.mail.MailService;
import com.pwccn.esg.repository.UserRepository;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@Controller
@RequestMapping(path = "/api/mails")
public class MailController {
@Autowired
private MailService mailService;
@Autowired
private UserRepository userRepository;
private Map<String , String> userChek = new HashMap<>();
@ApiOperation("Users reset their password using email check code")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The check code has been sent"),
@ApiResponse(code = 404, message = "The email is not exit"),
})
@GetMapping("/getCheckCode/{email}")
public ResponseEntity<UserDTO> getCheckCode(@PathVariable String email) {
String checkCode = String.valueOf(new Random().nextInt(899999)+100000);
String message = "您的验证码为:" +checkCode;
if(userRepository.findByEmail(email) == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
userChek.put(userRepository.findByEmail(email).getUsername(), checkCode);
mailService.sendSimpleMail(email, "您正在使用验证码修改密码", message);
return new ResponseEntity<>(new UserDTO(userRepository.findByEmail(email)), HttpStatus.OK);
}
@ApiOperation("Check the check code.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The check code is right."),
@ApiResponse(code = 400, message = "The check code is wrong."),
})
@PostMapping("/checkCode/{checkCode}")
public ResponseEntity<UserDTO> checkCode(@RequestBody UserDTO userDTO, @PathVariable String checkCode) {
if(userChek.get(userDTO.getUsername()).equals(checkCode)) {
return new ResponseEntity<>(userDTO, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
}
| aefd23f8bb0e18423bfee060aa95fc6c6e462c36 | [
"Markdown",
"Java",
"SQL"
]
| 13 | Java | Zhaofan-Su/esg-demo | 29e65c815e286896b9e2a99ac3bbfdb37f97b70a | b1755e1dd25815857e05315880dfbe55cd1381a4 |
refs/heads/master | <repo_name>ericadcg/HangmanGame<file_sep>/Hangman/Letters.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace Hangman
{
class Letters
{
public char letter { get; set; }
public bool isGuessed { get; set; }
public Letters()
{
isGuessed = false;
}
}
}
<file_sep>/Hangman/Program.cs
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace Hangman
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Guess the Word! Please wait while the game is being set.\n");
Game hangmanGame = new Game();
//Initializes the game
while (true)
{
// display
hangmanGame.Display();
// update
hangmanGame.Update();
}
} //End of main
}
}
<file_sep>/Hangman/CurrentMatch.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace Hangman
{
class CurrentMatch
{
public GuessingWord CurrentWord { get; set; }
private List<Letters> AllLetters { get; set; }
public int Attempts { get; set; }
public List<char> WrongLetters {get; set;}
public bool IsMatchWon { get; set; }
public CurrentMatch(GuessingWord currentWord)
{
Attempts = 5;
IsMatchWon = false;
AllLetters = new List<Letters>();
WrongLetters = new List<char>();
this.CurrentWord = currentWord;
for(int i=0; i<currentWord.NumberOfLetters(); i++)
{
Letters aux = new Letters();
aux.letter = currentWord.Word[i];
AllLetters.Add(aux);
}
}
//Prints string to show player with guessed letters and _ (for missing letters)
public void PrintWord()
{
string toPrint = "";
foreach(Letters l in AllLetters)
{
if (l.isGuessed)
toPrint = toPrint + " " + l.letter;
else
toPrint = toPrint + " _";
}
Console.WriteLine(toPrint);
return;
}
//Checks if the letter is in the word
public bool checkLetterAtempt(char letter)
{
bool isCorrectGuess = false;
letter = char.ToLower(letter);
if(WrongLetters.Contains(letter))
{
Console.WriteLine("You have used this letter before. Try another one.");
return false;
}
foreach(Letters l in AllLetters)
{
if(letter == l.letter)
{
l.isGuessed = true;
isCorrectGuess = true;
}
}
if (!isCorrectGuess)
{
WrongLetters.Add(letter);
Attempts--;
}
return isCorrectGuess;
}
//Checks if the word has all letters guessed
public void checkWordGuessed()
{
bool isWordGuessed = true;
foreach (Letters l in AllLetters)
{
if (!l.isGuessed)
{
isWordGuessed = false;
}
}
IsMatchWon = isWordGuessed;
}
//Checks if the word guessing tentative is correct
public void checkWordAtempt(string word)
{
if(string.Equals(CurrentWord.Word, word.ToLower(), StringComparison.InvariantCultureIgnoreCase))
{
IsMatchWon = true;
}
else
{
Attempts--;
}
}
//Prints formated string with wrong letters
public void PrintWrongLetters()
{
if (WrongLetters.Any())
{
Console.WriteLine("Wrong guesses: " + string.Join(", ", WrongLetters));
}
}
}
}
<file_sep>/README.md
This is a console game where the player can choose the number of letters the word to guess will have or its category.
This was built using C#.<file_sep>/Hangman/GuessingWord.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
namespace Hangman
{
class GuessingWord
{
public string Category { get; set; }
public string Word { get; set; }
public GuessingWord(string category ,string word)
{
this.Category = category;
this.Word = word;
}
public int NumberOfLetters()
{
return this.Word.Length;
}
}
}
<file_sep>/Hangman/Game.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Hangman
{
class Game
{
//List of possible game states
internal enum States
{
Menu,
ChooseLetters,
ChooseCategory,
PlayGame
}
List<GuessingWord> AllWords { get; }
CurrentMatch currMatch = null;
//Defines game state variable. Start as Menu
private States gameState = States.Menu;
//Constructer gets words from file when game is inittialized
public Game()
{
AllWords = new List<GuessingWord>();
using StreamReader file = new StreamReader(@"AllWords.txt");
int count = 0;
string line;
while ((line = file.ReadLine()) != null)
{
count++;
string[] str = line.Split(" ");
GuessingWord aux = new GuessingWord(str[0], str[1]);
AllWords.Add(aux);
}
file.Close();
}
//Handles what to show at each phase of the game
public void Display()
{
switch (gameState)
{
case States.Menu:
ShowMenu();
break;
case States.ChooseLetters:
Console.WriteLine("Please insert the number of letters ("+ GetMinLengthWords()+ " to "+ GetMaxLengthWords()+ " ) the word to guess will have.");
break;
case States.ChooseCategory:
Console.WriteLine("Please enter one of the following categories to get a word to guess:");
ReturnAllCategories().ForEach(Console.WriteLine);
break;
case States.PlayGame:
Console.WriteLine("\nPlease enter a letter to guess if it belongs to the word.");
Console.WriteLine("You have " + currMatch.Attempts + " wrong attempts left.");
currMatch.PrintWrongLetters();
currMatch.PrintWord();
break;
default:
break;
}
}
//Handles game states
public void Update()
{
string auxInput;
try
{
auxInput = GetInput();
}
catch(ArgumentException a)
{
Console.WriteLine(a.Message);
return;
}
switch (gameState)
{
case States.Menu:
switch (auxInput)
{
case "1":
gameState = States.ChooseLetters;
break;
case "2":
gameState = States.ChooseCategory;
break;
case "3":
Environment.Exit(0);
break;
default:
break;
}
break;
case States.ChooseLetters:
int numberOfLetters = Int32.Parse(auxInput);
currMatch = new CurrentMatch(GetWordWithSize(numberOfLetters));
gameState = States.PlayGame ;
break;
case States.ChooseCategory:
currMatch = new CurrentMatch(GetWordFromCategory(auxInput));
gameState = States.PlayGame;
break;
case States.PlayGame:
char attempt = Char.Parse(auxInput);
currMatch.checkLetterAtempt(attempt);
currMatch.checkWordGuessed();
if (currMatch.IsMatchWon)
{
Console.WriteLine("----------- Congratulations! You've won!! ----------");
gameState = States.Menu;
}
else if (currMatch.Attempts < 1)
{
Console.WriteLine("----------- You've Lost... The word was " + currMatch.CurrentWord.Word + ". Better luck next time! -----------");
gameState = States.Menu;
}
break;
default:
break;
}
}
//Handles inputs and throw erros for each game phase
public string GetInput()
{
string auxInput = Console.ReadLine();
switch (gameState)
{
case States.Menu:
if (!Int32.TryParse(auxInput, out _))
throw new ArgumentException("Please input a digit.");
if (Int32.Parse(auxInput) < 1 || Int32.Parse(auxInput) > 3)
throw new ArgumentException("The number must be 1 or 2 or 3.");
break;
case States.ChooseLetters:
if (!Int32.TryParse(auxInput, out _))
throw new ArgumentException("Please input a valid number.");
int min = GetMinLengthWords();
int max = GetMaxLengthWords();
if (Int32.Parse(auxInput) < min || Int32.Parse(auxInput) > max)
throw new ArgumentException("Please input a number between " + min + " and " + max );
break;
case States.ChooseCategory:
auxInput = auxInput.ToLower();
if (!ReturnAllCategories().Contains(auxInput))
throw new ArgumentException("Please insert a valid category.");
break;
case States.PlayGame:
if (!char.TryParse(auxInput, out _))
throw new ArgumentException("Please input only one letter.");
break;
default:
break;
}
return auxInput;
}
//Return maximum size of letters in all words
public int GetMaxLengthWords()
{
int max;
max = AllWords.Select(w => w.NumberOfLetters()).Max();
return max;
}
//Return minimun size of letters in all words
public int GetMinLengthWords()
{
int min;
min = AllWords.Select(w => w.NumberOfLetters()).Min();
return min;
}
//Returns a word of a given size
public GuessingWord GetWordWithSize(int size)
{
List<GuessingWord> sizeList = new List<GuessingWord>();
foreach (GuessingWord w in AllWords)
{
if (w.NumberOfLetters() == size)
{
sizeList.Add(w);
}
}
var rand = new Random();
return sizeList[rand.Next(sizeList.Count)];
}
//Returns a word that belongs to a category
public GuessingWord GetWordFromCategory(string cat)
{
List<GuessingWord> catList = new List<GuessingWord>();
foreach (GuessingWord w in AllWords)
{
if (string.Equals(w.Category, cat))
{
catList.Add(w);
}
}
var rand = new Random();
return catList[rand.Next(catList.Count)];
}
//Returns list of all categoies
public List<string> ReturnAllCategories()
{
List<string> cat = new List<string>();
cat = AllWords.Select(w => w.Category).Distinct().ToList();
return cat;
}
static public void ShowMenu()
{
Console.WriteLine("Please enter a number to choose from the following options:\n");
Console.WriteLine(" 1 - Choose number of letters and play the game;\n 2 - Choose category and play the game\n 3 - Exit the game;");
}
}
}
| e31d134f8ab3028e4551b43fa4f10fc799a99347 | [
"Markdown",
"C#"
]
| 6 | C# | ericadcg/HangmanGame | 7dbb4bbc345945c4b0598a2f5d71552379e0bc06 | 4ec536bfe675564ec3b18f827311da5a23528c07 |
refs/heads/main | <repo_name>NKlug/thesis-mechanical-regression<file_sep>/python/geodesic_shooting/quadrants_dataset.py
import numpy as np
import tensorflow as tf
def sample_range(bottom_left_corner, top_right_corner, n):
"""
Samples the given box uniformly
:param n: number of sample points
:param bottom_left_corner: bottom left corner of the box
:param top_right_corner: top right corner of the box
:return: sampled points
"""
samples_x = tf.random.uniform((n, ), minval=bottom_left_corner[0], maxval=top_right_corner[0], dtype=tf.float64)
samples_y = tf.random.uniform((n, ), minval=bottom_left_corner[1], maxval=top_right_corner[1], dtype=tf.float64)
return tf.stack([samples_x, samples_y], axis=-1)
def generate_quadrants_dataset(seed=578, n=100):
"""
Create a dataset made of two classes in four quadrants.
:param n: number of points per spiral
:param phi: angular velocity
:param jitter: standard deviation of gaussian noise
:param coils: parameter to adjust number of coils
:param seed: seed for random sampling. The default of 578 was determined to maximize distances between nodes
:return: Training data and labels
"""
tf.random.set_seed(seed)
top_left_quadrant = sample_range(np.asarray([-9.5, 0.5]), np.asarray([-0.5, 9.5]), n // 2)
bottom_right_quadrant = sample_range(np.asarray([0.5, -9.5]), np.asarray([9.5, -0.5]), n // 2)
top_right_quadrant = sample_range(np.asarray([0.5, 0.5]), np.asarray([9.5, 9.5]), n // 2)
bottom_left_quadrant = sample_range(np.asarray([-9.5, -9.5]), np.asarray([-0.5, -0.5]), n // 2)
X = tf.concat([top_left_quadrant, bottom_right_quadrant, top_right_quadrant, bottom_left_quadrant], axis=0)
X = tf.reshape(X, (-1))
Y = tf.concat([tf.ones(n), -tf.ones(n)], axis=0)
X = tf.cast(X, tf.float64)
Y = tf.cast(Y, tf.float64)
return X, Y
<file_sep>/python/templates/default_template.slurm.txt
#!/bin/bash
#SBATCH --partition=gpu
#SBATCH --job-name={job_name}
#SBATCH --output=out/{job_name}.out
#SBATCH --error=out/{job_name}.err
#SBATCH --mail-type=BEGIN,END,FAIL
#SBATCH --mail-user={user_mail}
#SBATCH --nodes=1
#SBATCH --gres=gpu:1
#SBATCH --mem={mem}GB
PYTHON_PATH={script_dir}
{scripts}
<file_sep>/python/geodesic_shooting/shooting_function_V.py
import tensorflow as tf
from geodesic_shooting.leapfrog import explicit_leapfrog
def V(p0, X, Y, mu, leapfrog_step, Gamma, K, dq_h, dp_h, loss_fn, is_training=False, global_step=None):
"""
Function \mathfrak{V} in Equation (3.17) in [Owhadi2020]
:param loss_fn: loss function
:param global_step: global step for logging the loss. Only relevant if is_training is True.
:param is_training: if True, the loss will be logged to Tensorboard
:param p0: Initial momentum
:param X: Training data
:param Y: Training labels
:param mu: balance factor
:return: Value of V in (3.17)
"""
q, _ = explicit_leapfrog(dq_h, dp_h, X, p0, step=leapfrog_step)
v = tf.tensordot(p0, tf.linalg.matvec(Gamma(X, X), p0), axes=1)
deformation_loss = mu / 2 * v
regression_loss = loss_fn(q, Y, K)
loss = deformation_loss + regression_loss
if is_training:
if global_step is None:
raise Exception('Global step must not be None when training!')
tf.summary.scalar('loss/recovery', regression_loss, step=global_step.numpy())
tf.summary.scalar('loss/deformation', deformation_loss, step=global_step.numpy())
tf.summary.scalar('loss/total', loss, step=global_step.numpy())
return loss
<file_sep>/python/config/parse_config_json.py
import json
from config.training_parameters import TrainingParameters
def _get_or_raise(data, key):
result = data.get(key)
if result is None:
raise Exception("Key '{}' missing in data!".format(key))
return result
def _get_or_default(data, key, default):
return data.get(key, default)
def from_json(file_path):
with open(file_path) as json_file:
return json.load(json_file)
def get_params_from_config(file_path, user_dir_override=None):
data = from_json(file_path)
return TrainingParameters(**data, user_dir_override=user_dir_override)
<file_sep>/python/README.md
# Usage
If you want to run the code by yourself,
just install the required packages (they can be found in the requirements.txt).
Run `run.py` for minimizing (3.17) w.r.t p(0).
Checkpoints and logs are stored in `../training/`.
A command line interface is still missing but will eventually be added.<file_sep>/python/geodesic_shooting/losses.py
import tensorflow as tf
def optimal_recovery_loss(x, y, k, regularizer):
"""
Optimal recovery loss as in (2.15) in [Owhadi2020]
:param k: kernel
:param x: training data
:param y: training labels
:return: the loss
"""
# solve d = k(x, x) @ y rather than computing the inverse because of numerical stability
kernel_mat = k(x, x)
d = tf.linalg.solve(kernel_mat + regularizer * tf.eye(kernel_mat.shape[0], dtype=tf.float64), y[:, None])[:, 0]
return tf.tensordot(y, d, axes=1)
def ridge_regression_loss(x, y, k, regularizer):
"""
Ridge regression loss as in (2.21) in [Owhadi2020]
:param x: training data
:param y: training labels
:param k: kernel
:param regularizer: regularizing constant
:return: the loss
"""
# solve d = k(x, x) @ y rather than computing the inverse because of numerical stability
kernel_mat = k(x, x)
d = tf.linalg.solve(kernel_mat + regularizer * tf.eye(kernel_mat.shape[0], dtype=tf.float64), y[:, None])[:, 0]
return regularizer * tf.tensordot(y, d, axes=1)
<file_sep>/python/geodesic_shooting/kernels.py
import tensorflow as tf
def K(u, v, s, r):
"""
K: X x X -> L(Y, Y), which means R^2 x R^2 -> R.
In this implementation this is R^(nx2) x R^(nx2) -> R^(nxn), as in (2.15) a
"block operator matrix with entries K(u_i, v_j)" is required.
This function returns exactly this (nxn) matrix.
:param u:
:param v:
:return:
"""
# Reshape to (n, 2) from (2n)
u = tf.reshape(u, (u.shape[0] // 2, 2))
v = tf.reshape(v, (v.shape[0] // 2, 2))
# Calculate pairwise differences first
pw_difference = u[:, None, :] - v[None, :, :]
# Use scalar product instead of squared norm due to numerical instability when differentiating the square root
x = tf.einsum('ijk,ijk->ij', pw_difference, pw_difference) # Elementwise scalar product
return tf.exp(- x / (s**2)) + r
def Gamma(u, v, s, r):
"""
X x X -> L(X, X), which means R^2 x R^2 -> R^(2x2). In this implementation, this is
R^(2n) x R^(2n) -> R^(2n x 2n) (block operator matrix).
The blocks are: K(u_i, v_j) * I, where I is the 2x2 unit matrix.
:param u:
:param v:
:return:
"""
gaussian = K(u, v, s, r)
identity_op = tf.linalg.LinearOperatorIdentity(num_rows=2, dtype=tf.float64)
gaussian_op = tf.linalg.LinearOperatorFullMatrix(gaussian)
return tf.linalg.LinearOperatorKronecker([gaussian_op, identity_op]).to_dense()
<file_sep>/python/visualization.py
import matplotlib.animation as ani
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider
def create_result_slider(q, interval, n):
global is_manual
fig, ax = plt.subplots()
l1, = plt.plot([], [], '.')
l2, = plt.plot([], [], '.')
axamp = plt.axes([0.25, .03, 0.50, 0.02])
# Slider
samp = Slider(axamp, 'Step', valmin=0, valmax=q.shape[0] - 1, valstep=1, valinit=0)
# Animation controls
is_manual = False # True if user has taken control of the animation
def init_animation():
a = 1
x_max, x_min = np.max(q[:, :, 0]), np.min(q[:, :, 0])
y_max, y_min = np.max(q[:, :, 1]), np.min(q[:, :, 1])
ax.set_xlim(x_min - a, x_max + a)
ax.set_ylim(y_min - a, y_max + a)
return l1, l2
def update_slider(val):
global is_manual
is_manual = True
update(val)
def update(val):
# update curve
l1.set_data(q[val, :n, 0], q[val, :n, 1])
l2.set_data(q[val, n:, 0], q[val, n:, 1])
# redraw canvas while idle
fig.canvas.draw_idle()
def update_plot(num):
global is_manual
if is_manual:
return l1, l2 # don't change
samp.set_val(num % q.shape[0])
is_manual = False # the above line called update_slider, so we need to reset this
return l1, l2
def on_click(event):
# Check where the click happened
(xm, ym), (xM, yM) = samp.label.clipbox.get_points()
if xm < event.x < xM and ym < event.y < yM:
# Event happened within the slider, ignore since it is handled in update_slider
return
else:
# user clicked somewhere else on canvas = unpause
global is_manual
is_manual = False
# call update function on slider value change
samp.on_changed(update_slider)
fig.canvas.mpl_connect('button_press_event', on_click)
return ani.FuncAnimation(fig, update_plot, interval=interval, init_func=init_animation, frames=q.shape[0])
def create_result_animation(q, interval, n):
q = np.concatenate([q, q[::-1]], axis=0)
fig, ax = plt.subplots()
l1, = plt.plot([], [], '.')
l2, = plt.plot([], [], '.')
def update_animation(num, data, l1, l2):
l1.set_data(data[num, :n, 0], data[num, :n, 1])
l2.set_data(data[num, n:, 0], data[num, n:, 1])
return l1, l2
def init_animation():
a = 1
x_max, x_min = np.max(q[:, :, 0]), np.min(q[:, :, 0])
y_max, y_min = np.max(q[:, :, 1]), np.min(q[:, :, 1])
ax.set_xlim(x_min - a, x_max + a)
ax.set_ylim(y_min - a, y_max + a)
return l1, l2
return ani.FuncAnimation(fig, update_animation, frames=q.shape[0], fargs=(q, l1, l2), init_func=init_animation,
interval=interval, blit=True)
<file_sep>/README.md
# Mechanical Regression for Supervised Learning
This is the Bachelor's thesis I wrote for my B.Sc. degree in
Mathematics during the winter term 2020/21.
In the thesis, I examined mechanical regression which was proposed by <NAME>
in the paper "Do Ideas Have Shape? Plato's Theory of Forms as the Continuous Limit of
Artificial Neural Networks" [1].
Mechanical regression is a method for supervised learning that was derived from a
theoretical model of residual neural networks (ResNets).
This repository contains an implementation of the algorithm suggested in
section 3 in [1] (in the `python` folder) and also the LaTeX code for the thesis and
the figures.
The following are the abstracts in English and German.
## Abstract
Although neural networks have been used with extraordinary success for many years in machine learning, they are still not fully understood from a mathematical point of view.
In "Do Ideas Have Shape? Plato's Theory of Forms as the Continuous Limit of Neural Networks", <NAME> analyzes a subclass of neural networks which are called residual neural networks (ResNets) and shows their convergence towards a continuous mechanical system.
This system resembles algorithms from image registration and computational anatomy.
In this thesis, parts of Owhadi's results are presented and discussed.
It is shown that ResNets relate to a discretized stationary action principle which can be formulated as a discrete geodesic shooting problem.
Because of this connection to physics, these equivalent problems are summarized as _mechanical regression_.
All three discrete problems have continuous counterparts and converge towards them.
This convergence is in the sense that as the number of ResNet layers tends towards infinity or the step size towards zero, the minimal values converge and the adherence points of sequences of minimizers are solutions to the continuous problems.
From the continuous geodesic shooting problem, an algorithm for the supervised learning problem can be derived.
Parts of this algorithm are implemented and numerical experiments are conducted.
The results closely resemble those presented by Owhadi.
## Zusammenfassung
Obwohl neuronale Netze seit mehreren Jahren mit außergewöhnlichem Erfolg im maschinellen Lernen eingesetzt werden, sind sie aus mathematischer Perspektive immer noch nicht vollständig verstanden.
In "Do Ideas Have Shape? Plato's Theory of Forms as the Continuous Limit of Neural Networks" analysiert <NAME> eine Unterklasse neuronaler Netze, welche "Residual Neural Networks" (ResNets) genannt werden und zeigt, dass diese gegen ein stetiges mechanisches System konvergieren.
Dieses System ähnelt Algorithmen aus dem Bereich der Bilderfassung und rechenbasierter Anatomie.
In dieser Arbeit werden Teile von Owhadis Ergebnissen präsentiert und diskutiert.
Es wird gezeigt, dass ResNets in Zusammenhang zu einem diskreten Prinzip der stationären Wirkung stehen, welche als diskretes Geodesic-Shooting-Problem formuliert werden kann.
Aufgrund dieser Verbindung zur Physik werden diese äquivalenten Probleme als _Mechanische Regression_ zusammengefasst.
Alle drei diskreten Probleme haben stetige Gegenstücke und konvergieren gegen diese.
Diese Konvergenz ist folgendermaßen zu verstehen:
Strebt die Anzahl der ResNet-Schichten gegen unendlich beziehungsweise die Schrittweite gegen Null, konvergieren die minimalen Funktionswerte und die Berührpunkte von Folgen von Minimieren sind Lösungen der stetigen Probleme.
Aus der Formulierung als stetiges Geodesic-Shooting-Problem kann ein Algorithmus für das überwachte Lernen abgeleitet werden.
Teile dieses Algorithmus werden implementiert und numerische Experimente werden durchgeführt.
Die Ergebnisse sind denen, die von Owhadi berichtet wurden, sehr ähnlich.
## References
[1] <NAME>. Do Ideas Have Shape? Plato's Theory of Forms as the Continuous Limit of
Artificial Neural Networks. ArXiv, https://arxiv.org/abs/2008.03920.
<file_sep>/python/geodesic_shooting/swiss_roll_dataset.py
import numpy as np
import tensorflow as tf
@tf.function
def create_spiral(phi, jitter, coils, rotation, n=100):
"""
Samples equidistant points from a 2D spiral with gaussian noise
:param n: number of sample points
:param coils: parameter to adjust number of coils
:param phi: angular velocity
:param jitter: standard deviation of gaussian noise
:param rotation: rotation of the spiral
:return: the generated spiral
"""
# adjust start sample for arcsin (which is defined on [-1, 1])
roll = tf.range(coils ** 2, n + coils ** 2, dtype=tf.float64)
roll = tf.sqrt(roll)
angles = tf.cumsum(tf.asin(coils / roll)) + rotation
roll = tf.stack([-tf.cos(phi * angles) * roll + 0.5, tf.sin(phi * angles) * roll + 0.5], axis=-1)
roll += tf.random.normal(shape=roll.shape, mean=0, stddev=jitter, dtype=tf.float64)
return roll
def generate_swiss_roll(phi, jitter=0, coils=3, seed=0, n=100):
"""
Generates sampled points on a swissroll, i.e. two intertwined spirals
:param n: number of points per spiral
:param phi: angular velocity
:param jitter: standard deviation of gaussian noise
:param coils: parameter to adjust number of coils
:param seed: seed for random sampling
:return: the two spirals of the swissroll dataset
"""
tf.random.set_seed(seed)
roll_1 = create_spiral(phi, jitter, coils, 0, n=n)
roll_2 = create_spiral(phi, jitter, coils, np.pi, n=n)
return roll_1, roll_2
def generate_swiss_roll_dataset(phi, jitter=0, coils=3, seed=0, n=100):
"""
Create the swissroll dataset in Section 3.13.2 in [Owhadi2020]
:param n: number of points per spiral
:param phi: angular velocity
:param jitter: standard deviation of gaussian noise
:param coils: parameter to adjust number of coils
:param seed: seed for random sampling
:return: Training data and labels
"""
X = tf.concat(generate_swiss_roll(phi=phi, jitter=jitter, coils=coils, seed=seed, n=n), axis=0)
X = tf.reshape(X, (-1))
Y = tf.concat([tf.ones(n), -tf.ones(n)], axis=0)
X = tf.cast(X, tf.float64)
Y = tf.cast(Y, tf.float64)
return X, Y
<file_sep>/python/run.py
import argparse
from os import path, listdir
from pprint import pprint
import tensorflow as tf
from config.parse_config_json import get_params_from_config, from_json
from geodesic_shooting.model import Model
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='')
parser.add_argument('config', help=' location of the config for the current training.')
args = parser.parse_args()
# limit gpu memory allocation
gpus = tf.config.list_physical_devices('GPU')
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
print("Creating model from the following config:")
config_path = path.realpath(path.expanduser(args.config))
pprint(from_json(config_path))
params = get_params_from_config(config_path)
# check if there already exists an experiment with the same name
if path.exists(params.checkpoint_dir) and len(listdir(params.checkpoint_dir)) != 0:
print("There is already an experiment '{}' in '{}'! Aborting...".format(params['experiment'],
params.checkpoint_dir))
exit(1)
model = Model(checkpoint_interval=10, model_params=params)
# approximate the optimal initial momentum
model.train(steps=150000)
<file_sep>/python/requirements.txt
# This file may be used to create an environment using:
# $ conda create --name <env> --file <this file>
# platform: linux-64
_libgcc_mutex=0.1=main
_tflow_select=2.1.0=gpu
absl-py=0.11.0=py38h06a4308_0
aiohttp=3.6.3=py38h7b6447c_0
astroid=2.4.2=py38_0
astunparse=1.6.3=py_0
async-timeout=3.0.1=py38_0
attrs=20.3.0=pyhd3eb1b0_0
backcall=0.2.0=py_0
blas=1.0=mkl
blinker=1.4=py38_0
brotlipy=0.7.0=py38h27cfd23_1003
c-ares=1.17.1=h27cfd23_0
ca-certificates=2020.10.14=0
cachetools=4.1.1=py_0
certifi=2020.11.8=py38h06a4308_0
cffi=1.14.3=py38h261ae71_2
chardet=3.0.4=py38h06a4308_1003
click=7.1.2=py_0
cryptography=3.2.1=py38h3c74f83_1
cudatoolkit=10.1.243=h6bb024c_0
cudnn=7.6.5=cuda10.1_0
cupti=10.1.168=0
cycler=0.10.0=py38_0
cython=0.29.21=py38h2531618_0
dbus=1.13.18=hb2f20db_0
decorator=4.4.2=py_0
expat=2.2.10=he6710b0_2
fontconfig=2.13.0=h9420a91_0
freetype=2.10.4=h5ab3b9f_0
gast=0.3.3=py_0
glib=2.66.1=h92f7085_0
google-auth=1.23.0=pyhd3eb1b0_0
google-auth-oauthlib=0.4.2=pyhd3eb1b0_2
google-pasta=0.2.0=py_0
grpcio=1.31.0=py38hf8bcb03_0
gst-plugins-base=1.14.0=hbbd80ab_1
gstreamer=1.14.0=hb31296c_0
h5py=2.10.0=py38hd6299e0_1
hdf5=1.10.6=hb1b8bf9_0
icu=58.2=he6710b0_3
idna=2.10=py_0
importlib-metadata=2.0.0=py_1
intel-openmp=2020.2=254
ipython=7.19.0=py38hb070fc8_0
ipython_genutils=0.2.0=py38_0
isort=5.6.4=py_0
jedi=0.17.2=py38_0
jpeg=9b=h024ee3a_2
keras-preprocessing=1.1.0=py_1
kiwisolver=1.3.0=py38h2531618_0
lazy-object-proxy=1.4.3=py38h7b6447c_0
lcms2=2.11=h396b838_0
ld_impl_linux-64=2.33.1=h53a641e_7
libedit=3.1.20191231=h14c3975_1
libffi=3.3=he6710b0_2
libgcc-ng=9.1.0=hdf63c60_0
libgfortran-ng=7.3.0=hdf63c60_0
libpng=1.6.37=hbc83047_0
libprotobuf=3.13.0.1=hd408876_0
libstdcxx-ng=9.1.0=hdf63c60_0
libtiff=4.1.0=h2733197_1
libuuid=1.0.3=h1bed415_2
libxcb=1.14=h7b6447c_0
libxml2=2.9.10=hb55368b_3
lz4-c=1.9.2=heb0550a_3
markdown=3.3.3=py38h06a4308_0
matplotlib=3.3.2=0
matplotlib-base=3.3.2=py38h817c723_0
mccabe=0.6.1=py38_1
mkl=2020.2=256
mkl-service=2.3.0=py38he904b0f_0
mkl_fft=1.2.0=py38h23d657b_0
mkl_random=1.1.1=py38h0573a6f_0
multidict=4.7.6=py38h7b6447c_1
ncurses=6.2=he6710b0_1
numpy=1.19.2=py38h54aff64_0
numpy-base=1.19.2=py38hfa32c7d_0
oauthlib=3.1.0=py_0
olefile=0.46=py_0
openssl=1.1.1h=h7b6447c_0
opt_einsum=3.1.0=py_0
parso=0.7.0=py_0
pcre=8.44=he6710b0_0
pexpect=4.8.0=pyhd3eb1b0_3
pickleshare=0.7.5=py38_1000
pillow=8.0.1=py38he98fc37_0
pip=20.2.4=py38_0
prompt-toolkit=3.0.8=py_0
protobuf=3.13.0.1=py38he6710b0_1
ptyprocess=0.6.0=pyhd3eb1b0_2
pyasn1=0.4.8=py_0
pyasn1-modules=0.2.8=py_0
pycparser=2.20=py_2
pygments=2.7.2=pyhd3eb1b0_0
pyjwt=1.7.1=py38_0
pylint=2.6.0=py38_0
pyopenssl=19.1.0=pyhd3eb1b0_1
pyparsing=2.4.7=py_0
pyqt=5.9.2=py38h05f1152_4
pysocks=1.7.1=py38h06a4308_0
python=3.8.5=h7579374_1
python-dateutil=2.8.1=py_0
qt=5.9.7=h5867ecd_1
readline=8.0=h7b6447c_0
requests=2.24.0=py_0
requests-oauthlib=1.3.0=py_0
rsa=4.6=py_0
scipy=1.5.2=py38h0b6359f_0
setuptools=50.3.0=py38hb0f4dca_1
sip=4.19.13=py38he6710b0_0
six=1.15.0=py38h06a4308_0
sqlite=3.33.0=h62c20be_0
tensorboard=2.3.0=pyh4dce500_0
tensorboard-plugin-wit=1.6.0=py_0
tensorflow=2.2.0=gpu_py38hb782248_0
tensorflow-base=2.2.0=gpu_py38h83e3d50_0
tensorflow-estimator=2.2.0=pyh208ff02_0
tensorflow-gpu=2.2.0=h0d30ee6_0
termcolor=1.1.0=py38_1
tk=8.6.10=hbc83047_0
toml=0.10.1=py_0
tornado=6.0.4=py38h7b6447c_1
tqdm=4.51.0=pyhd3eb1b0_0
traitlets=5.0.5=py_0
urllib3=1.25.11=py_0
wcwidth=0.2.5=py_0
werkzeug=1.0.1=py_0
wheel=0.35.1=py_0
wrapt=1.11.2=py38h7b6447c_0
xz=5.2.5=h7b6447c_0
yarl=1.6.2=py38h7b6447c_0
zipp=3.4.0=pyhd3eb1b0_0
zlib=1.2.11=h7b6447c_3
zstd=1.4.5=h9ceee32_0
<file_sep>/python/geodesic_shooting/leapfrog.py
import numpy as np
from tqdm import tqdm
def _one_step(dq_h, dp_h, q, p, step):
"""
Performs one step of the Leapfrog scheme described in Equation (3.35) in
[Owhadi2020]
:param dq_h: partial derivative of the hamiltonian w.r.t q
:param dp_h: partial derivative of the hamiltonian w.r.t p
:param q: current value of the generalized coordinates q
:param p: current value of the generalized momenta p
:param step: step size
:return: the new q and p
"""
curr_p = p
curr_q = q
curr_p = curr_p - step / 2 * dq_h(curr_q, curr_p)
curr_q = curr_q + step * dp_h(curr_q, curr_p)
curr_p = curr_p - step / 2 * dq_h(curr_q, curr_p)
return curr_q, curr_p
def explicit_leapfrog(dq_h, dp_h, q0, p0, step, t_stop=1):
"""
Simulates the given Hamiltonian system with the leapfrog method as described in Equation (3.35) in
[Owhadi2020]. Returns the flows at time t_stop
:param t_stop: stop time
:param p0: initial momentum
:param q0: initial position
:param step: size of step
:param dq_h: partial derivative of Hamiltonian w.r.t q
:param dp_h: partial derivative of Hamiltonian w.r.t p
:return: flows q and p at time t_stop
"""
num_steps = int(1 / step * t_stop) + 1
curr_q = q0
curr_p = p0
for _ in tqdm(range(1, num_steps), disable=True):
curr_q, curr_p = _one_step(dq_h, dp_h, curr_q, curr_p, step)
return curr_q, curr_p
def simulate_flow(dq_h, dp_h, q0, p0, step, t_stop=1):
"""
Simulates the given Hamiltonian system with the leapfrog method as described in Equation (3.35) in
[Owhadi2020]. Returns the flows over time.
:param t_stop: stop time
:param p0: initial momentum
:param q0: initial position
:param step: size of step
:param dq_h: partial derivative of Hamiltonian w.r.t q
:param dp_h: partial derivative of Hamiltonian w.r.t p
:return: flows q and p
"""
num_steps = int(1 / step * t_stop) + 1
q = np.zeros((num_steps, *q0.shape))
p = np.zeros((num_steps, *p0.shape))
q[0] = q0.numpy()
p[0] = p0.numpy()
curr_q = q0
curr_p = p0
for i in tqdm(range(1, num_steps)):
curr_q, curr_p = _one_step(dq_h, dp_h, curr_q, curr_p, step)
p[i] = curr_p.numpy()
q[i] = curr_q.numpy()
return q, p
<file_sep>/python/geodesic_shooting/hamiltonians.py
import tensorflow as tf
def dq_h(q, p, Gamma):
"""
Partial derivative of the Hamiltonian in (1.13) in [Owhadi2020] w.r.t q
:param q: coordinates
:param p: momenta
:return: the partial derivative vector
"""
with tf.GradientTape() as t:
t.watch(q)
v = tf.linalg.matvec(Gamma(q, q), p)
h = 0.5 * tf.tensordot(p, v, axes=1)
return t.gradient(h, q)
def dp_h(q, p, Gamma):
"""
Partial derivative of the Hamiltonian in (1.13) in [Owhadi2020] w.r.t q
:param q: coordinates
:param p: momenta
:return: the partial derivative vector
"""
return tf.linalg.matvec(Gamma(q, q), p)
<file_sep>/python/evaluation/evaluate_multiple_experiments.py
import pickle as pkl
from glob import glob
from os import path
from config.parse_config_json import get_params_from_config
from evaluation.evaluator import Evaluator
from geodesic_shooting.model import Model
def evaluate_multiple_experiments(name_pattern, config_base_dir, user_dir_override):
for config_path in glob(path.join(config_base_dir, name_pattern)):
print('Evaluating experiment ', path.basename(config_path).replace('.json', ''))
params = get_params_from_config(config_path, user_dir_override)
model = Model(checkpoint_interval=10, model_params=params)
evaluator = Evaluator(model)
all_flows = evaluator.flows_over_epochs(every_nth=10)
result_path = path.join(user_dir_override, 'training', 'results',
path.basename(config_path).replace('.json', '.pkl'))
with open(result_path, 'wb') as f:
pkl.dump(all_flows, f)
if __name__ == '__main__':
name_pattern = '21_*/2021_02_23_*'
config_base_dir = '/home/nikolas/Projects/thesis-mechanical-regression/training/configs'
user_dir_override = '/home/nikolas/Projects/thesis-mechanical-regression'
evaluate_multiple_experiments(name_pattern, config_base_dir, user_dir_override)
<file_sep>/python/geodesic_shooting/model.py
import tensorflow as tf
from tqdm import tqdm
import geodesic_shooting.hamiltonians as ham
from geodesic_shooting import kernels
from geodesic_shooting.shooting_function_V import V
class Model(object):
def __init__(self, checkpoint_interval, model_params):
"""
A model of the mechanical regression problem proposed in [Owhadi2020].
:param checkpoint_interval: number of iterations after which to save the parameters
:param model_params: TrainingParameters object containing additional parameters
"""
self.checkpoint_interval = checkpoint_interval
self.X, self.Y = model_params.dataset
self.log_dir = model_params.log_dir
self.checkpoint_dir = model_params.checkpoint_dir
self.model_params = model_params
# Initialize variables
self.global_step = tf.Variable(0, name='global_step')
initial_p0 = tf.random.normal(shape=self.X.shape, dtype=tf.float64)
self.p0 = tf.Variable(initial_p0, trainable=True, dtype=tf.float64, name='p0')
self.trainable_variables = [self.p0]
# Define functions with respective hyper-parameters
self.K = lambda u, v: kernels.K(u, v, s=model_params.s, r=model_params.r)
self.Gamma = lambda u, v: kernels.Gamma(u, v, s=model_params.s, r=model_params.r)
self.dq_h = lambda q, p: ham.dq_h(q, p, self.Gamma)
self.dp_h = lambda q, p: ham.dp_h(q, p, self.Gamma)
self.regression_loss = lambda x, y, k: self.model_params.loss(x, y, k, regularizer=model_params.ls_regularizer)
self.loss = lambda: V(self.p0, self.X, self.Y, mu=model_params.mu,
leapfrog_step=model_params.h,
Gamma=self.Gamma,
K=self.K,
dq_h=self.dq_h,
dp_h=self.dp_h,
loss_fn=self.regression_loss,
is_training=True,
global_step=self.global_step)
self.optimizer = tf.optimizers.Adam()
# Take care of logging and saving
self.summary_writer = tf.summary.create_file_writer(self.log_dir)
self.checkpoint = tf.train.Checkpoint(optimizer=self.optimizer,
initial_momentum=self.p0,
global_step=self.global_step)
self.checkpoint_manager = tf.train.CheckpointManager(self.checkpoint, directory=self.checkpoint_dir,
checkpoint_interval=self.checkpoint_interval,
step_counter=self.global_step,
max_to_keep=None)
def restore(self, checkpoint=None):
"""
Restore the parameters at a checkpoint.
:param checkpoint: Checkpoint to restore. If None, the latest checkpoint is used.
"""
if checkpoint is None:
if self.checkpoint_manager.latest_checkpoint is None:
raise Exception('No checkpoint found in {}!'.format(self.checkpoint_manager.directory))
checkpoint = self.checkpoint_manager.latest_checkpoint
print('Restoring checkpoint {}.'.format(checkpoint))
self.checkpoint.restore(checkpoint).assert_existing_objects_matched()
def train(self, steps):
"""
Approximates the optimal initial momentum by minimizing (3.17) in [Owhadi2020]
w.r.t. p(0).
:param steps: number of steps to run on the optimizer
"""
for i in tqdm(range(steps)):
with self.summary_writer.as_default():
self.global_step.assign(i)
self.optimizer.minimize(self.loss, var_list=self.trainable_variables)
self.checkpoint_manager.save(check_interval=True)
<file_sep>/python/config/training_parameters.py
from os import path
from geodesic_shooting.losses import optimal_recovery_loss, ridge_regression_loss
from geodesic_shooting.quadrants_dataset import generate_quadrants_dataset
from geodesic_shooting.swiss_roll_dataset import generate_swiss_roll_dataset
losses = {
'optimal_recovery': optimal_recovery_loss,
'ridge_regression': ridge_regression_loss
}
class TrainingParameters(object):
def __init__(self, dataset, mu, h, s, r, ls_regularizer, checkpoint_base_dir, log_base_dir, name=None,
user_dir_override=None, loss=None,
*args, **kwargs):
"""
Hyper parameters for the model.
:param dataset: name of dataset
:param mu: balancing factor in the shooting function V
:param h: step width for the leapfrog integrator
:param s: standard deviation in gaussian kernel
:param r: nugget for gaussian kernel
"""
_datasets = {
'default_swiss_roll': generate_swiss_roll_dataset(1, jitter=0.1, coils=0.65, n=100),
'quadrants': generate_quadrants_dataset()
}
self.dataset = _datasets[dataset]
self.mu = mu
self.h = h
self.s = s
self.r = r
self.ls_regularizer = ls_regularizer
if loss is None:
loss = 'optimal_recovery'
self.loss = losses[loss]
if name is None:
raise Exception('Experiment name must not be None!')
self.experiment = name
if user_dir_override is not None:
checkpoint_base_dir = checkpoint_base_dir.replace('~', user_dir_override)
log_base_dir = log_base_dir.replace('~', user_dir_override)
self.checkpoint_dir = path.realpath(path.expanduser(path.join(checkpoint_base_dir, self.experiment)))
self.log_dir = path.realpath(path.expanduser(path.join(log_base_dir, self.experiment)))
<file_sep>/python/config/create_config.py
import argparse
import json
from datetime import datetime
from glob import glob
from itertools import product
from os import path
def create_slurm_jobs(local_config_dir, output_dir, user_mail, script_location, config_base_dir, job_name):
with open('templates/default_template.slurm.txt', 'r') as file:
template = file.read()
all_configs = glob(path.join(local_config_dir, '*.json'))
script_dir = path.dirname(script_location)
commands = []
for config in all_configs:
job_name = path.basename(config).replace('.json', '')
remote_config_path = path.join(config_base_dir, path.basename(config))
command = 'python3 ' + script_location + ' ' + remote_config_path + ' > out/' + job_name + '.out &\n'
commands.append(command)
commands.append('wait')
filled_template = template.format(mem=str(2 * len(all_configs)), job_name=job_name, user_mail=user_mail,
scripts=''.join(commands),
script_dir=script_dir)
with open(path.join(output_dir, job_name + '.slurm'), 'w') as out_file:
out_file.write(filled_template)
def create_configs(s, r, h, mu, ls_regularizer, loss, log_base_dir, checkpoint_base_dir, dataset):
for s1, r1, h1, mu1, ls_regularizer1, loss1, dataset1 in product(s, r, h, mu, ls_regularizer, loss, dataset):
name = "{}_s_{}_r_{}_h_{}_mu_{}_reg_{}".format(dataset1, s1, r1, h1, mu1, ls_regularizer1)
create_config(name, s=s1, r=r1, h=h1, mu=mu1, ls_reg=ls_regularizer1, loss=loss1, log_base_dir=log_base_dir,
checkpoint_base_dir=checkpoint_base_dir, dataset=dataset1)
def create_config(config_name, log_base_dir='', checkpoint_base_dir='', s=5, r=0.1, h=0, mu=0, ls_reg=1e-6,
loss='optimal_recovery', dataset='default_swiss_roll'):
config_name = datetime.now().strftime('%Y_%m_%d_') + str(config_name)
config = {
"name": config_name,
"log_base_dir": log_base_dir,
"checkpoint_base_dir": checkpoint_base_dir,
"dataset": dataset,
"s": s,
"r": r,
"h": h,
"mu": mu,
"ls_regularizer": ls_reg,
"loss": loss
}
with open(path.join('../training/configs', config_name + '.json'), 'w') as file:
json.dump(config, file)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='')
parser.add_argument('config_name', help=' name of the config to be created.')
args = parser.parse_args()
create_config(args.config_name)
<file_sep>/python/evaluation/evaluator.py
import re
from os import path, listdir
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from geodesic_shooting.leapfrog import simulate_flow
class Evaluator(object):
def __init__(self, model):
self.model = model
def all_checkpoints(self):
"""
Creates a list of the paths of all checkpoints available for the model
:return: A list of the paths of all checkpoints
"""
files = [f for f in listdir(self.model.checkpoint_dir) if path.isfile(path.join(self.model.checkpoint_dir, f))]
all_checkpoints = [re.findall(r'ckpt-\d+', f) for f in files if 'ckpt' in f]
all_checkpoints = [path.join(self.model.checkpoint_dir, c[0]) for c in all_checkpoints if len(c) > 0]
return sorted(set(all_checkpoints), key=lambda s: int(re.findall(r'\d+|$', path.basename(s))[0]))
def flows_over_epochs(self, every_nth=1):
"""
Calculates the flows q for each checkpoint available for the model
:param every_nth: only evaluate every n-th checkpoint
:return: dict of the flows and initial momenta for every n-th checkpoint
"""
all_flows = {}
for checkpoint in self.all_checkpoints()[::every_nth]:
self.model.restore(checkpoint)
q, _ = simulate_flow(self.model.dq_h, self.model.dp_h, self.model.X, self.model.p0,
step=self.model.model_params.h, t_stop=1)
q = q.reshape((-1, self.model.X.shape[0] // 2, 2))
all_flows[checkpoint] = {'flow': q, 'p0': self.model.p0}
return all_flows
def find_best_checkpoint(self, all_flows):
"""
Finds the checkpoint with the smallest overall loss
:param all_flows: flows for the checkpoints that should be checked
:return: path of the best checkpoint, value of smallest loss
"""
best_checkpoint = None
best_loss = np.infty
for checkpoint, data in tqdm(all_flows.items()):
flow = data['flow']
p0 = data['p0']
v = tf.tensordot(p0, tf.linalg.matvec(self.model.Gamma(self.model.X, self.model.X), p0),
axes=1)
deformation_loss = self.model.model_params.mu / 2 * v
loss = self.model.regression_loss(flow[-1].reshape(-1), self.model.Y, self.model.K) + deformation_loss
loss = loss.numpy()
if loss < best_loss:
best_loss = loss
best_checkpoint = checkpoint
return best_checkpoint, best_loss
| 16d050a22280f326fc7601d062c168030c95f9e3 | [
"Markdown",
"Python",
"Text",
"Shell"
]
| 19 | Python | NKlug/thesis-mechanical-regression | 1cf4b3177730191a806f37289367599b6c0523dd | 94d16f878ea895f23ecf4cc0f96fb8ba25845512 |
refs/heads/master | <file_sep>Gtvclass::Application.routes.draw do
resources :lessons
resources :flags
resources :flags
resources :answers
match '/flags', :to => 'flags#reset', :via => :delete
match '/answers', :to => 'answers#reset', :via => :delete
root :to => 'lessons#show'
end
<file_sep>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Base class for TV UI components.
*/
goog.provide('tv.ui.Component');
goog.require('goog.events');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.style');
goog.require('tv.ui');
goog.require('tv.ui.Document');
/**
* Constructs component.
* @constructor
* @extends {goog.events.EventTarget}
*/
tv.ui.Component = function() {
/**
* Facilitates listening for events: automatically binds 'this' to handlers
* and allows unlisten of all events at once.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
};
goog.inherits(tv.ui.Component, goog.events.EventTarget);
/**
* @type {string} Main CSS class that triggers decoration.
*/
tv.ui.Component.CLASS = 'tv-component';
tv.ui.registerDecorator(tv.ui.Component, tv.ui.Component.CLASS);
/**
* CSS classes that control and reflect look and feel of component.
* These classes are applied to root DOM element.
* @enum {string}
*/
tv.ui.Component.Class = {
/**
* Applied when component receives focus.
* @see tv.ui.Component.EventType#FOCUS
* @see tv.ui.Document#setFocusedComponent
*/
FOCUSED: 'tv-component-focused',
/**
* Applied when component is hidden.
* @see #isVisible
*/
HIDDEN: 'tv-component-hidden',
/**
* Applied when component cannot be selected.
* @see #isEnabled
*/
DISABLED: 'tv-component-disabled'
};
/**
* Event types dispatched by component.
*
* Note to subclass implementers: don't listen for events dispatched by self,
* override appropriate on...() methods to avoid race conditions with other
* event handlers on component state mutations. on...() methods are guaranteed
* to be called first.
*
* @enum {string}
*/
tv.ui.Component.EventType = {
/**
* Dispatched after component becomes focused in document.
* Focused component will receive key events.
* @see #onFocus
*/
FOCUS: goog.events.getUniqueId('focus'),
/**
* Dispatched before component stops being focused in document.
* @see #onBlur
*/
BLUR: goog.events.getUniqueId('blur'),
/**
* Dispatched when key is pressed while component or one of its children are
* focused.
* @see #onKey
*/
KEY: goog.events.getUniqueId('key')
};
/**
* Root DOM element of component.
* @type {Element}
* @private
*/
tv.ui.Component.prototype.element_;
/**
* Whether render was already scheduled.
* @type {boolean}
* @private
*/
tv.ui.Component.prototype.renderScheduled_;
/**
* @inheritDoc
*/
tv.ui.Component.prototype.disposeInternal = function() {
this.eventHandler_.dispose();
delete this.element_;
goog.base(this, 'disposeInternal');
};
/**
* @return {tv.ui.Container} Parent container.
*/
tv.ui.Component.prototype.getParent = function() {
return /** @type {tv.ui.Container} */(this.getParentEventTarget());
};
/**
* @param {tv.ui.Container} parent Sets parent container.
* @protected
*/
tv.ui.Component.prototype.setParent = function(parent) {
this.setParentEventTarget(parent);
};
/**
* @return {goog.events.EventHandler} Event handler.
* @protected
*/
tv.ui.Component.prototype.getEventHandler = function() {
return this.eventHandler_;
};
/**
* @return {Element} Root DOM element of component.
* @protected
*/
tv.ui.Component.prototype.getElement = function() {
return this.element_;
};
/**
* Decorates given DOM element and makes it root element for component.
* @param {Element} element DOM element to decorate.
*/
tv.ui.Component.prototype.decorate = function(element) {
goog.asserts.assert(
!this.element_, 'Component is already attached to DOM element.');
this.element_ = element;
goog.dom.classes.add(this.element_, this.getClass());
this.setVisible(!goog.dom.classes.has(
this.element_, tv.ui.Component.Class.HIDDEN));
this.eventHandler_.listen(
element,
goog.events.EventType.MOUSEDOWN,
this.onMouseDown);
this.eventHandler_.listen(
this, tv.ui.Component.EventType.FOCUS, this.onFocus);
this.eventHandler_.listen(
this, tv.ui.Component.EventType.BLUR, this.onBlur);
this.eventHandler_.listen(
this, tv.ui.Component.EventType.KEY, this.onKey);
};
/**
* @return {string} Main CSS class that triggers decoration.
*/
// TODO(maksym): Logic related to this method is dangerous, get rid of it.
tv.ui.Component.prototype.getClass = function() {
return tv.ui.Component.CLASS;
};
/**
* @return {tv.ui.Document} Document where component is located.
*/
tv.ui.Component.prototype.getDocument = function() {
return this.element_ ?
tv.ui.Document.getInstance(this.element_.ownerDocument) : null;
};
/**
* @return {boolean} Whether element is focused.
*/
tv.ui.Component.prototype.isFocused = function() {
return goog.dom.classes.has(this.element_, tv.ui.Component.Class.FOCUSED);
};
/**
* Called by tv.ui.Document when component gains focus.
* @suppress {underscore} Intended to be package-private method, thus shouldn't
* be called by anyone else but tv.ui.Document.
*/
tv.ui.Component.prototype.dispatchFocus_ = function() {
this.dispatchEvent(tv.ui.Component.EventType.FOCUS);
};
/**
* Handles focus event.
* @param {goog.events.Event} event Focus event.
* @protected
*/
tv.ui.Component.prototype.onFocus = function(event) {
// Add focused class to element.
goog.dom.classes.add(this.element_, tv.ui.Component.Class.FOCUSED);
event.stopPropagation();
};
/**
* Called by tv.ui.Document when component loses focus.
* @suppress {underscore} Intended to be package-private method, thus shouldn't
* be called by anyone else but tv.ui.Document.
*/
tv.ui.Component.prototype.dispatchBlur_ = function() {
this.dispatchEvent(tv.ui.Component.EventType.BLUR);
};
/**
* Handles blur event.
* @param {goog.events.Event} event Blur event.
* @protected
*/
tv.ui.Component.prototype.onBlur = function(event) {
// Remove focused class from element.
goog.dom.classes.remove(this.element_, tv.ui.Component.Class.FOCUSED);
event.stopPropagation();
};
/**
* Called by tv.ui.Document on focused component when document receives key
* event.
* @param {goog.events.KeyEvent} event Key event. Warning: method is
* destructive against event object.
* @suppress {underscore} Intended to be package-private method, thus shouldn't
* be called by anyone else but tv.ui.Document.
*/
tv.ui.Component.prototype.dispatchKey_ = function(event) {
event.type = tv.ui.Component.EventType.KEY;
event.target = this;
this.dispatchEvent(event);
};
/**
* Handles key event.
* To be used in subclasses.
* @param {goog.events.KeyEvent} Key event.
* @protected
*/
tv.ui.Component.prototype.onKey = goog.nullFunction;
/**
* Handles mouse down event.
* @param {goog.events.Event} event Mouse down event.
* @protected
*/
tv.ui.Component.prototype.onMouseDown = function(event) {
// Whether component and all its ancestors are enabled.
for (var component = this; component; component = component.getParent()) {
if (!component.isEnabled()) {
return;
}
}
// Request focus to component or in case of containers to one of its
// descendants.
var focusedComponent = this.getSelectedDescendantOrSelf();
if (!focusedComponent) {
return;
}
this.getDocument().setFocusedComponent(focusedComponent);
event.stopPropagation();
};
/**
* @return {tv.ui.Component} Self, or null if component cannot accept focus.
*/
tv.ui.Component.prototype.getSelectedDescendantOrSelf = function() {
return this.isEnabled() && this.isVisible() ? this : null;
};
/**
* Does nothing for non-container components.
* Used solely because of return value.
* @return {boolean} True if component can be selected.
* @protected
*/
tv.ui.Component.prototype.selectFirstChild = function() {
return this.isEnabled() && this.isVisible();
};
/**
* @return {boolean} Whether component is visible.
*/
tv.ui.Component.prototype.isVisible = function() {
return !goog.dom.classes.has(
this.element_, tv.ui.Component.Class.HIDDEN);
};
/**
* @param {boolean} visible Sets whether component is visible.
*/
tv.ui.Component.prototype.setVisible = function(visible) {
goog.dom.classes.enable(
this.element_, tv.ui.Component.Class.HIDDEN, !visible);
// As visibility affects whether component can be selected, we need to notify
// parent container.
var parent = this.getParent();
parent && parent.onChildVisibilityChange(this);
};
/**
* @return {boolean} Whether component can be selected.
*/
tv.ui.Component.prototype.isEnabled = function() {
return !goog.dom.classes.has(
this.element_, tv.ui.Component.Class.DISABLED);
};
/**
* Updates styles and layout according to state of component.
* Supposed to be used for computation-heavy updates that are too costly to
* call after every state mutation.
* @protected
*/
tv.ui.Component.prototype.render = function() {
this.renderScheduled_ = false;
};
/**
* Schedules eventual rendering of component.
* Render is performed only once, no matter how many times it was scheduled.
* @protected
*/
tv.ui.Component.prototype.scheduleRender = function() {
if (!this.renderScheduled_) {
this.renderScheduled_ = true;
tv.ui.scheduleRender(this);
}
};
<file_sep>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Single-line text input that is able to display hint when empty.
*/
goog.provide('tv.ui.Input');
goog.require('goog.dom');
goog.require('goog.dom.selection');
goog.require('goog.events.InputHandler');
goog.require('tv.ui');
goog.require('tv.ui.Component');
/**
* Constructs input.
* @constructor
* @extends {tv.ui.Component}
*/
tv.ui.Input = function() {
goog.base(this);
};
goog.inherits(tv.ui.Input, tv.ui.Component);
/**
* @type {string} Main CSS class that triggers decoration.
*/
tv.ui.Input.CLASS = 'tv-input';
tv.ui.registerDecorator(tv.ui.Input, tv.ui.Input.CLASS);
/**
* CSS classes that control and reflect look and feel of input.
* @enum {string}
*/
tv.ui.Input.Class = {
/**
* Applied to optional element which serves as hint.
* Hint is displayed when input contains no text, should be hidden by default.
* @see #HINT_SHOWN
*/
HINT: 'tv-input-hint',
/**
* Applied to hint element when it should be visible.
*/
HINT_SHOWN: 'tv-input-hint-shown'
};
/**
* @type {Element}
* @private
*/
tv.ui.Input.prototype.inputElement_;
/**
* @inheritDoc
*/
tv.ui.Input.prototype.disposeInternal = function() {
delete this.inputElement_;
goog.base(this, 'disposeInternal');
};
/**
* @inheritDoc
*/
tv.ui.Input.prototype.decorate = function(element) {
goog.base(this, 'decorate', element);
this.inputElement_ = element.tagName == 'INPUT' ?
element :
goog.dom.getElementsByTagNameAndClass('input', null, element)[0];
goog.asserts.assert(this.inputElement_, 'No input element found.');
this.hintElement_ = goog.dom.getElementByClass(
tv.ui.Input.Class.HINT, element);
this.updateHintVisibility_();
this.getEventHandler().listen(
this.inputElement_,
goog.events.InputHandler.EventType.INPUT,
this.onInput);
};
/**
* @return {Element} 'input' element.
*/
tv.ui.Input.prototype.getInputElement = function() {
return this.inputElement_;
};
/**
* @inheritDoc
*/
tv.ui.Input.prototype.getClass = function() {
return tv.ui.Input.CLASS;
};
/**
* Handles key event.
* Consumes navigation keys if cursor is not on the boundaries of input.
* @param {goog.events.KeyEvent} event Key event.
* @protected
*/
tv.ui.Input.prototype.onKey = function(event) {
if (event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
return;
}
var selectionPoints = goog.dom.selection.getEndPoints(this.inputElement_);
var hasSelection = selectionPoints[0] != selectionPoints[1];
switch (event.keyCode) {
case goog.events.KeyCodes.LEFT:
if (selectionPoints[0] != 0 || hasSelection) {
event.stopPropagation();
}
break;
case goog.events.KeyCodes.RIGHT:
if (selectionPoints[0] != this.inputElement_.value.length ||
hasSelection) {
event.stopPropagation();
}
break;
}
};
/**
* @inheritDoc
*/
tv.ui.Input.prototype.onFocus = function(event) {
goog.base(this, 'onFocus', event);
if (this.inputElement_.ownerDocument.activeElement != this.inputElement_) {
goog.Timer.callOnce(function() {
this.inputElement_.focus();
}, 0, this);
}
};
/**
* @inheritDoc
*/
tv.ui.Input.prototype.onBlur = function(event) {
goog.base(this, 'onBlur', event);
this.inputElement_.blur();
};
/**
* Handles input event.
* @param {goog.events.BrowserEvent} event Input event.
* @protected
*/
tv.ui.Input.prototype.onInput = function(event) {
this.updateHintVisibility_();
};
/**
* Shows or hides hint.
* @private
*/
tv.ui.Input.prototype.updateHintVisibility_ = function() {
if (this.hintElement_) {
goog.dom.classes.enable(
this.hintElement_,
tv.ui.Input.Class.HINT_SHOWN,
!this.inputElement_.value);
}
};
<file_sep>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A hyperlink.
*/
goog.provide('tv.ui.Link');
goog.require('tv.ui');
goog.require('tv.ui.Button');
/**
* Constructs button.
* @constructor
* @extends {tv.ui.Button}
*/
tv.ui.Link = function() {
goog.base(this);
};
goog.inherits(tv.ui.Link, tv.ui.Button);
/**
* @type {string} Main CSS class that triggers decoration.
*/
tv.ui.Link.CLASS = 'tv-link';
tv.ui.registerDecorator(tv.ui.Link, tv.ui.Link.CLASS);
/**
* @inheritDoc
*/
tv.ui.Link.prototype.getClass = function() {
return tv.ui.Link.CLASS;
};
/**
* Handles action event.
* Follows the hyperlink.
* @param {goog.events.Event} event Action event.
* @protected
*/
tv.ui.Link.prototype.onAction = function(event) {
this.navigate(this.getElement().getAttribute('href'));
};
/**
* Redirectes page to given location.
* @param {string} url URL to redirect browser.
* @private
*/
tv.ui.Link.prototype.navigate = function(url) {
window.location = url;
};
<file_sep>require "require/version"
module Require
# Your code goes here...
end
<file_sep>class AnswersController < ApplicationController
respond_to :json
def index
render json: Answer.all
end
def create
Answer.create params.slice(:value)
head :no_content
end
def reset
Answer.destroy_all
redirect_to :action => :index
end
end
<file_sep>class Flag < ActiveRecord::Base
end
<file_sep>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Component container that features highlighting and scrolling.
*/
goog.provide('tv.ui.Container');
goog.require('goog.dom');
goog.require('goog.dom.classes');
goog.require('goog.math.Coordinate');
goog.require('goog.style');
goog.require('tv.ui');
goog.require('tv.ui.Component');
/**
* Constructs container.
* @constructor
* @extends {tv.ui.Component}
*/
tv.ui.Container = function() {
goog.base(this);
/**
* @type {Array.<tv.ui.Component>}
* @private
*/
this.children_ = [];
};
goog.inherits(tv.ui.Container, tv.ui.Component);
/**
* @type {string} Main CSS class that triggers decoration.
*/
tv.ui.Container.CLASS = 'tv-container';
/**
* CSS classes that control and reflect look and feel of container.
* @enum {string}
*/
tv.ui.Container.Class = {
/**
* Applied to root element if container has horizontal orientation.
* In horizontal container elements span along x-axis.
* User can control selection by Left and Right keys.
* @see #isHorizontal
*/
HORIZONTAL: 'tv-container-horizontal',
/**
* Applied to root element if container has vertical orientation.
* In vertical container elements span along y-axis.
* User can control selection by Up and Down keys.
* @see #isVertical
*/
VERTICAL: 'tv-container-vertical',
/**
* Applied to root element if container has stack orientation.
* In stack container elements span along z-axis (only one element at the time
* is visible). User cannot control selection directly, an alternative way
* is usually provided by application developer, such as tab bar.
* @see #isStack
*/
STACK: 'tv-container-stack',
/**
* Applied to root element of currently selected child component.
* @see #getSelectedChild
*/
SELECTED_CHILD: 'tv-container-selected-child',
/**
* Denotes highlight element that will be positioned above currently selected
* child.
* @see #getHighlightElement
*/
HIGHLIGHT: 'tv-container-highlight',
/**
* Denotes highlight element that could be shared between different
* containers. Position and visibility of shared highlight is controlled
* by focused container. Shared highlight must be external element,
* set with setHighlightElement() method.
* @see #setHighlightElement
*/
SHARED_HIGHLIGHT: 'tv-container-shared-highlight',
/**
* Applied to highlight element when it's properly positioned.
* Useful for permanent and shared highlights. Since permanent highlight is
* always visible, this class helps to avoid appearance of misplaced highlight
* before decoration and after container becomes empty. Shared highlights
* could use this class to prevent animated transition between containers.
*/
HIGHLIGHT_POSITIONED: 'tv-container-highlight-positioned',
/**
* Applied to highlight element if one of container's descendants is focused.
* Could be used to control visibility of highlight.
*/
HIGHLIGHT_FOCUSED: 'tv-container-highlight-focused',
/**
* Denotes start slit element which is shown when there are child components
* before scrolling window.
*/
START_SLIT: 'tv-container-start-slit',
/**
* Applied to start slit element when there are child components before
* scrolling window.
* @see tv.ui.Container.Class#START_SLIT
*/
START_SLIT_SHOWN: 'tv-container-start-slit-shown',
/**
* Denotes end slit element which is shown when there are child components
* after scrolling window.
*/
END_SLIT: 'tv-container-end-slit',
/**
* Applied to end slit element when there are child components after
* scrolling window.
* @see tv.ui.Container.Class#END_SLIT
*/
END_SLIT_SHOWN: 'tv-container-end-slit-shown',
/**
* Applied to element that is parent to all scrollable child elements.
* Selected child will always be positioned at start of scrolling window.
*/
START_SCROLL: 'tv-container-start-scroll',
/**
* Applied to element that is parent to all scrollable child elements.
* Selected child will be positioned in the middle of scrolling window when
* it is possible.
*/
MIDDLE_SCROLL: 'tv-container-middle-scroll',
/**
* Applied to parent element of all mock children.
* Mock child is an element that has dimensions of typical child.
* It should be used when scroll element or child elements have animations.
*/
MOCK_SCROLL: 'tv-container-mock-scroll'
};
tv.ui.registerDecorator(
tv.ui.Container,
[
tv.ui.Container.CLASS,
tv.ui.Container.Class.HORIZONTAL,
tv.ui.Container.Class.VERTICAL
]);
/**
* Event types dispatched by container.
* @enum {string}
*/
tv.ui.Container.EventType = {
/**
* Dispatched after selected child has changed.
* @see #getSelectedChild
*/
SELECT_CHILD: goog.events.getUniqueId('select_child'),
/**
* Dispatched after position or visibility of highlight element has been
* changed.
* @see #getHighlightElement
*/
UPDATE_HIGHLIGHT: goog.events.getUniqueId('update_highlight')
};
// TODO(maksym): Comment member variables.
/**
* @type {Element}
* @private
*/
tv.ui.Container.prototype.scrollElement_;
/**
* @type {Element}
* @private
*/
tv.ui.Container.prototype.highlightElement_;
/**
* @type {Element}
* @private
*/
tv.ui.Container.prototype.startSlitElement_;
/**
* @type {Element}
* @private
*/
tv.ui.Container.prototype.endSlitElement_;
/**
* @type {Element}
* @private
*/
tv.ui.Container.prototype.mockScrollElement_;
/**
* @type {Element}
* @private
*/
tv.ui.Container.prototype.mockChildElement_;
/**
* @type {tv.ui.Component}
* @private
*/
tv.ui.Container.prototype.selectedChild_;
/**
* @type {boolean}
* @private
*/
tv.ui.Container.prototype.controllingSharedHighlight_;
/**
* @inheritDoc
*/
tv.ui.Container.prototype.disposeInternal = function() {
this.removeChildren();
delete this.scrollElement_;
delete this.highlightElement_;
delete this.startSlitElement_;
delete this.endSlitElement_;
delete this.mockScrollElement_;
delete this.mockChildElement_;
goog.base(this, 'disposeInternal');
};
/**
* @inheritDoc
*/
tv.ui.Container.prototype.decorate = function(element) {
goog.base(this, 'decorate', element);
for (var childNode = element.firstChild; childNode;
childNode = childNode.nextSibling) {
if (childNode.nodeType != goog.dom.NodeType.ELEMENT) {
continue;
}
var childElement = /** @type {Element} */(childNode);
if (goog.dom.classes.has(childElement, tv.ui.Container.Class.HIGHLIGHT)) {
this.setHighlightElement(childElement);
} else if (goog.dom.classes.has(
childElement, tv.ui.Container.Class.START_SLIT)) {
this.startSlitElement_ = childElement;
} else if (goog.dom.classes.has(
childElement, tv.ui.Container.Class.END_SLIT)) {
this.endSlitElement_ = childElement;
} else if (goog.dom.classes.has(
childElement, tv.ui.Container.Class.START_SCROLL)) {
this.scrollElement_ = childElement;
} else if (goog.dom.classes.has(
childElement, tv.ui.Container.Class.MIDDLE_SCROLL)) {
this.scrollElement_ = childElement;
} else if (goog.dom.classes.has(
childElement, tv.ui.Container.Class.MOCK_SCROLL)) {
this.mockScrollElement_ = childElement;
this.mockChildElement_ = /** @type {Element} */(
childElement.removeChild(childElement.firstChild));
}
}
};
/**
* @inheritDoc
*/
tv.ui.Container.prototype.getClass = function() {
return tv.ui.Container.CLASS;
};
/**
* Adds child component.
* @param {tv.ui.Component} child Child component.
*/
tv.ui.Container.prototype.addChild = function(child) {
this.children_.push(child);
child.setParent(this);
if (this.mockScrollElement_) {
var mockChildElement =
/** @type {Element} */(this.mockChildElement_.cloneNode(true));
goog.style.showElement(mockChildElement, child.isVisible());
this.mockScrollElement_.appendChild(mockChildElement);
}
if ((!this.selectedChild_ && child.getSelectedDescendantOrSelf()) ||
goog.dom.classes.has(
child.getElement(), tv.ui.Container.Class.SELECTED_CHILD)) {
this.setSelectedChild(child);
} else {
this.scheduleRender();
}
};
/**
* Removes all child components.
*/
tv.ui.Container.prototype.removeChildren = function() {
this.setSelectedChild(null);
if (this.mockScrollElement_) {
goog.dom.removeChildren(this.mockScrollElement_);
}
goog.array.forEach(this.children_, function(child) {
child.dispose();
});
this.children_ = [];
this.scheduleRender();
};
/**
* @return {Array.<tv.ui.Component>} List of children.
*/
tv.ui.Container.prototype.getChildren = function() {
return this.children_;
};
/**
* @return {boolean} Whether container has horizontal orientation.
*/
tv.ui.Container.prototype.isHorizontal = function() {
return goog.dom.classes.has(
this.getElement(), tv.ui.Container.Class.HORIZONTAL);
};
/**
* @return {boolean} Whether container has vertical orientation.
*/
tv.ui.Container.prototype.isVertical = function() {
return goog.dom.classes.has(
this.getElement(), tv.ui.Container.Class.VERTICAL);
};
/**
* @return {boolean} Whether container has stack orientation.
*/
tv.ui.Container.prototype.isStack = function() {
return goog.dom.classes.has(
this.getElement(), tv.ui.Container.Class.STACK);
};
/**
* @return {Element} Highlight element.
*/
tv.ui.Container.prototype.getHighlightElement = function() {
return this.highlightElement_;
};
/**
* Sets highlight element. This method is the only way to set external
* highlight element.
* @param {Element} highlightElement highlight element.
*/
tv.ui.Container.prototype.setHighlightElement = function(highlightElement) {
goog.asserts.assert(
!this.isStack(), 'Stack container doesn\'t support highlight.');
this.highlightElement_ = highlightElement;
};
/**
* @return {boolean} Whether container has shared highlight.
* @private
*/
tv.ui.Container.prototype.hasSharedHighlight_ = function() {
goog.asserts.assert(
this.highlightElement_, 'Container doesn\'t have highlight.');
return goog.dom.classes.has(
this.highlightElement_, tv.ui.Container.Class.SHARED_HIGHLIGHT);
};
/**
* @return {boolean} Whether this container is controlling position and
* visibility of highlight element.
* @private
*/
tv.ui.Container.prototype.isControllingHighlight_ = function() {
return this.controllingSharedHighlight_ || !this.hasSharedHighlight_();
};
/**
* @return {boolean} Whether policy is to keep selected child at start of
* scrolling window.
* @private
*/
tv.ui.Container.prototype.isStartScroll_ = function() {
goog.asserts.assert(
this.scrollElement_, 'Container doesn\'t have scroll.');
return goog.dom.classes.has(
this.scrollElement_, tv.ui.Container.Class.START_SCROLL);
};
/**
* Handles key event.
* Controls child component focus.
* @param {goog.events.KeyEvent} event Key event.
* @protected
*/
tv.ui.Container.prototype.onKey = function(event) {
if (this.isStack() ||
event.ctrlKey || event.altKey || event.shiftKey || event.metaKey) {
return;
}
var selectionChanged;
if (event.keyCode == this.getPreviousKey_()) {
selectionChanged = this.selectPreviousChild();
} else if (event.keyCode == this.getNextKey_()) {
selectionChanged = this.selectNextChild();
}
if (selectionChanged) {
event.stopPropagation();
event.preventDefault();
this.getDocument().setFocusedComponent(
this.selectedChild_.getSelectedDescendantOrSelf());
}
};
/**
* @return {number} Code for key that moves selection towards start of the
* container.
* @private
*/
tv.ui.Container.prototype.getPreviousKey_ = function() {
return this.isHorizontal() ?
goog.events.KeyCodes.LEFT : goog.events.KeyCodes.UP;
};
/**
* @return {number} Code for key that moves selection towards end of the
* container.
* @private
*/
tv.ui.Container.prototype.getNextKey_ = function() {
return this.isHorizontal() ?
goog.events.KeyCodes.RIGHT : goog.events.KeyCodes.DOWN;
};
/**
* Tries to select one of the child components starting from first one.
* Only components that can receive focus (or have children that can receive
* focus) are qualified.
* @return {boolean} Whether focusable child has been found.
* @protected
*/
tv.ui.Container.prototype.selectFirstChild = function() {
return goog.base(this, 'selectFirstChild') &&
goog.array.some(this.children_, function(child) {
if (child.selectFirstChild()) {
this.setSelectedChild(child);
return true;
}
return false;
}, this);
};
/**
* Tries to select one of the child components before currently selected one.
* Only components that can receive focus (or have children that can receive
* focus) are qualified.
* @return {boolean} Whether selection changed.
* @protected
*/
tv.ui.Container.prototype.selectPreviousChild = function() {
return this.changeSelectedChildIndexBy_(-1, 0);
};
/**
* Tries to select one of the child components after currently selected one.
* Only components that can receive focus (or have children that can receive
* focus) are qualified.
* @return {boolean} Whether selection changed.
* @protected
*/
tv.ui.Container.prototype.selectNextChild = function() {
return this.changeSelectedChildIndexBy_(1, this.children_.length - 1);
};
/**
* Tries to select one of the child components in given direction relatively to
* currently selected one.
* Only components that can receive focus (or have children that can receive
* focus) are qualified.
* @param {number} delta +/-1 for direction.
* @param {number} lastIndex Last child index.
* @return {boolean} Whether selection changed.
* @private
*/
tv.ui.Container.prototype.changeSelectedChildIndexBy_ = function(
delta, lastIndex) {
if (!this.selectedChild_) {
return false;
}
var selectedChildIndex =
goog.array.indexOf(this.children_, this.selectedChild_);
while (selectedChildIndex != lastIndex) {
selectedChildIndex += delta;
var selectedChild = this.children_[selectedChildIndex];
if (selectedChild.getSelectedDescendantOrSelf()) {
this.setSelectedChild(selectedChild);
return true;
}
}
return false;
};
/**
* @return {tv.ui.Component} Selected grand-...-grandchild, or null if no
* child is selected.
*/
tv.ui.Container.prototype.getSelectedDescendantOrSelf = function() {
return goog.base(this, 'getSelectedDescendantOrSelf') &&
this.selectedChild_ &&
this.selectedChild_.getSelectedDescendantOrSelf();
};
/**
* @return {tv.ui.Component} Currently selected child.
* Guaranteed to be focusable or have focusable child selected.
*/
tv.ui.Container.prototype.getSelectedChild = function() {
return this.selectedChild_;
};
/**
* @param {tv.ui.Component} selectedChild Sets currently selected child.
*/
tv.ui.Container.prototype.setSelectedChild = function(selectedChild) {
if (this.selectedChild_ == selectedChild) {
return;
}
if (this.selectedChild_) {
goog.dom.classes.remove(
this.selectedChild_.getElement(), tv.ui.Container.Class.SELECTED_CHILD);
}
this.selectedChild_ = selectedChild;
if (this.selectedChild_) {
goog.dom.classes.add(
this.selectedChild_.getElement(), tv.ui.Container.Class.SELECTED_CHILD);
this.scheduleRender();
}
var parent = this.getParent();
parent && parent.onChildSelectabilityChange(this);
this.dispatchEvent(tv.ui.Container.EventType.SELECT_CHILD);
};
/**
* @inheritDoc
*/
tv.ui.Container.prototype.render = function() {
goog.base(this, 'render');
if (!this.isStack()) {
this.scroll_();
this.updateHighlight_();
}
};
/**
* Scrolls children according to scrolling window policy.
* @private
*/
tv.ui.Container.prototype.scroll_ = function() {
// Do nothing if container is not scrollable.
if (!this.scrollElement_) {
return;
}
// No children or all children are non-focusable?
if (!this.selectedChild_) {
// Scroll to start.
this.setScrollElementPosition_(this.createCoordinate_(0));
// Hide slits.
this.startSlitElement_ && goog.dom.classes.remove(
this.startSlitElement_, tv.ui.Container.Class.START_SLIT_SHOWN);
this.endSlitElement_ && goog.dom.classes.remove(
this.endSlitElement_, tv.ui.Container.Class.END_SLIT_SHOWN);
return;
}
var selectedChildIndex =
goog.array.indexOf(this.children_, this.selectedChild_);
var selectedChildElement = this.getChildElement_(selectedChildIndex);
// Policy requires to keep selected child at start of scrolling window.
if (this.isStartScroll_()) {
this.setScrollElementPosition_(this.createCoordinate_(
-this.getOffsetCoordinate_(selectedChildElement)));
// TODO(maksym): Update slit visibility.
return;
}
// OK, hard part. Policy requires to position selected child in the middle of
// scrolling window.
var scrollWindowSize = this.getOffsetSize_(this.element_);
/**
* How much space is in scrolling window before selected element. We assume
* that selected element is positioned at most at the middle of scrolling
* window.
*/
var spaceBeforeSelectedSize = scrollWindowSize / 2;
var allChildrenSize = this.getScrollSize_(
this.mockScrollElement_ || this.scrollElement_);
var selectedChildCoordinate = this.getOffsetCoordinate_(
selectedChildElement);
// Can we fit selected and last element in half of scrolling window?
if (allChildrenSize - selectedChildCoordinate < spaceBeforeSelectedSize) {
// Yes, correct available space.
spaceBeforeSelectedSize =
scrollWindowSize - (allChildrenSize - selectedChildCoordinate);
}
// Try to fit in scrolling window as much fully visible elements to the left
// of selected element as possible.
//
// No, I'm not stupid. It's not possible to use division even if all elements
// have the same size. Webkit browsers have terrible rounding bug if page zoom
// isn't 100%. In short, if you place 2 elements of width 40 next to each
// other and measure total width by using offsetLeft (just an example, all
// measuring methods affected), it is very likely that it would be 79 or 81.
// Issue have cumulative effect, so it worsens with increasing number of
// elements.
var firstVisibleChildElement = selectedChildElement;
var startSlitShown = selectedChildIndex != 0;
for (var childIndex = selectedChildIndex - 1;
childIndex >= 0; childIndex--) {
if (!this.children_[childIndex].isVisible()) {
continue;
}
var childElement = this.getChildElement_(childIndex);
if (selectedChildCoordinate - this.getOffsetCoordinate_(childElement) >
spaceBeforeSelectedSize) {
break;
}
firstVisibleChildElement = childElement;
startSlitShown = childIndex != 0;
}
var firstVisibleChildCoordinate =
this.getOffsetCoordinate_(firstVisibleChildElement);
var endSlitShown =
(allChildrenSize - firstVisibleChildCoordinate) > scrollWindowSize;
// Scroll, finally!
this.setScrollElementPosition_(
this.createCoordinate_(-firstVisibleChildCoordinate));
// Show slits if necessary.
if (this.startSlitElement_) {
goog.dom.classes.enable(
this.startSlitElement_,
tv.ui.Container.Class.START_SLIT_SHOWN,
startSlitShown);
}
if (this.endSlitElement_) {
goog.dom.classes.enable(
this.endSlitElement_,
tv.ui.Container.Class.END_SLIT_SHOWN,
endSlitShown);
}
};
/**
* Returns child element used for measuring during scrolling.
* @param {number} childIndex Index of child.
* @return {Element} Either root element of child component or mock child
* element.
* @private
*/
tv.ui.Container.prototype.getChildElement_ = function(childIndex) {
return this.mockScrollElement_ ?
this.mockScrollElement_.childNodes[childIndex] :
this.children_[childIndex].getElement();
};
/**
* Sets position of real and mock scroll elements.
* @param {goog.math.Coordinate} scrollElementPosition Position to set.
* @private
*/
tv.ui.Container.prototype.setScrollElementPosition_ = function(
scrollElementPosition) {
goog.style.setPosition(this.scrollElement_, scrollElementPosition);
if (this.mockScrollElement_) {
goog.style.setPosition(this.mockScrollElement_, scrollElementPosition)
}
};
/**
* Moves highlight element at position of selected child.
* Does nothing if highlight is shared and container isn't in focus chain.
* @private
*/
tv.ui.Container.prototype.updateHighlight_ = function() {
if (!this.highlightElement_ || !this.isControllingHighlight_()) {
return;
}
if (this.selectedChild_) {
var selectedChildElement = this.getChildElement_(
goog.array.indexOf(this.children_, this.selectedChild_));
goog.style.setPosition(
this.highlightElement_,
goog.style.getRelativePosition(
selectedChildElement,
/** @type {Element} */(this.highlightElement_.parentNode)));
goog.dom.classes.add(
this.highlightElement_, tv.ui.Container.Class.HIGHLIGHT_POSITIONED);
} else {
goog.dom.classes.remove(
this.highlightElement_, tv.ui.Container.Class.HIGHLIGHT_POSITIONED);
}
this.dispatchEvent(tv.ui.Container.EventType.UPDATE_HIGHLIGHT);
};
/**
* Abstracts offset coordinate for horizontal and vertical container.
* @param {Element} element Element to measure.
* @return {number} Offset left or top, depending on container orientation.
* @private
*/
tv.ui.Container.prototype.getOffsetCoordinate_ = function(element) {
return this.isHorizontal() ? element.offsetLeft : element.offsetTop;
};
/**
* Abstracts offset size for horizontal and vertical container.
* @param {Element} element Element to measure.
* @return {number} Offset width or height, depending on container orientation.
* @private
*/
tv.ui.Container.prototype.getOffsetSize_ = function(element) {
return this.isHorizontal() ? element.offsetWidth : element.offsetHeight;
};
/**
* Abstracts scroll size for horizontal and vertical container.
* @param {Element} element Element to measure.
* @return {number} Scroll width or height, depending on container orientation.
* @private
*/
tv.ui.Container.prototype.getScrollSize_ = function(element) {
return this.isHorizontal() ? element.scrollWidth : element.scrollHeight;
};
/**
* Creates coordinate from given value.
* @param {number} value Coordinate value.
* @return {goog.math.Coordinate} 2-dimensional coordinate with one of
* dimensions set to given value, other one - to zero, depending on
* container orientation.
* @private
*/
tv.ui.Container.prototype.createCoordinate_ = function(value) {
return new goog.math.Coordinate(
this.isHorizontal() ? value : 0, this.isHorizontal() ? 0 : value);
};
/**
* Updates DOM styles.
* Called by child component to notify parent container that its visibility
* has changed.
* @param {tv.ui.Component} child Child component which visibility has changed.
*/
tv.ui.Container.prototype.onChildVisibilityChange = function(child) {
// Ensure consistent visibility of mock child.
if (this.mockScrollElement_) {
var childIndex = goog.array.indexOf(this.children_, child);
goog.style.showElement(
this.mockScrollElement_.childNodes[childIndex], child.isVisible());
}
this.onChildSelectabilityChange(child);
this.scheduleRender();
};
/**
* Updates selected child if necessary.
* Called by child component to notify parent container that one of conditions
* affecting selected child choice has changed.
* @param {tv.ui.Component} child Child component which property has changed.
* @protected
*/
tv.ui.Container.prototype.onChildSelectabilityChange = function(child) {
if (!this.selectedChild_ && child.getSelectedDescendantOrSelf()) {
// Child became selectable, set it as selected if container has none.
this.setSelectedChild(child);
} else if (this.selectedChild_ == child &&
!child.getSelectedDescendantOrSelf() &&
!this.selectNextChild() &&
!this.selectPreviousChild()) {
// Child stopped being selectable, no other selectable children found.
this.setSelectedChild(null);
}
};
/**
* Handles focus event.
* Enters mode when container is allowed to control external highlight and
* updates position and look of highlight element.
* @protected
*/
tv.ui.Container.prototype.onFocus = function(event) {
goog.base(this, 'onFocus', event);
if (this.highlightElement_) {
goog.dom.classes.add(
this.highlightElement_, tv.ui.Container.Class.HIGHLIGHT_FOCUSED);
if (this.hasSharedHighlight_()) {
this.controllingSharedHighlight_ = true;
// Overkill, we only need to position highlight element. We might have done
// it by calling updateHighlight_() method. However we can trigger
// unnecessary repaint in browser, so it's better this way.
this.scheduleRender();
}
}
};
/**
* Handles blur event.
* Exits mode when container is allowed to control external highlight and
* updates look of highlight element.
* @protected
*/
tv.ui.Container.prototype.onBlur = function(event) {
goog.base(this, 'onBlur', event);
if (this.highlightElement_) {
goog.dom.classes.remove(
this.highlightElement_, tv.ui.Container.Class.HIGHLIGHT_FOCUSED);
if (this.hasSharedHighlight_()) {
this.controllingSharedHighlight_ = false;
goog.dom.classes.remove(
this.highlightElement_, tv.ui.Container.Class.HIGHLIGHT_POSITIONED);
}
this.dispatchEvent(tv.ui.Container.EventType.UPDATE_HIGHLIGHT);
}
};
<file_sep>class FlagsController < ApplicationController
def index
respond_to do |format|
format.json { render json: Flag.all }
format.html do
@count = Flag.count
@red_count = Answer.where(value: 'red').count
@green_count = Answer.where(value: 'green').count
@blue_count = Answer.where(value: 'blue').count
@yellow_count = Answer.where(value: 'yellow').count
end
end
end
def new
@flag = Flag.new
end
def create
Flag.create
redirect_to :action => :new
end
def reset
Flag.destroy_all
redirect_to :action => :index
end
end
<file_sep>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Document controls focus and key event flow.
*/
goog.provide('tv.ui.Document');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventType');
goog.require('goog.events.KeyCodes');
goog.require('goog.events.KeyHandler');
/**
* Constructs document.
* Document should not be constructed directly but rather by means of
* tv.ui.Document.getInstance().
* @param {Document} document DOM document.
* @private
* @constructor
*/
tv.ui.Document = function(document) {
/**
* Facilitates listening for events: automatically binds 'this' to handlers
* and allows unlisten of all events at once.
* @type {goog.events.EventHandler}
* @private
*/
this.eventHandler_ = new goog.events.EventHandler(this);
this.eventHandler_.listen(
new goog.events.KeyHandler(document),
goog.events.KeyHandler.EventType.KEY,
this.onKey);
};
/**
* Component that is currently focused.
* @type {tv.ui.Component}
* @private
*/
tv.ui.Document.prototype.focusedComponent_;
/**
* Component that will eventually become focused.
* Used as one-element queue.
* @type {tv.ui.Component}
* @private
*/
tv.ui.Document.prototype.componentPendingFocus_;
/**
* Returns cached instance of document, which is created if necessary.
* @param {Document=} opt_document DOM document.
* @return {tv.ui.Document} Instance of document for given DOM document.
*/
tv.ui.Document.getInstance = function(opt_document) {
var document = opt_document || window.document;
if (!document.tvUiDocument_) {
document.tvUiDocument_ = new tv.ui.Document(document);
}
return document.tvUiDocument_;
};
/**
* Handles key event.
* Dispatches key event to currently focused component if any.
* @param {goog.events.KeyEvent} event Key event.
* @protected
*/
tv.ui.Document.prototype.onKey = function(event) {
this.focusedComponent_ && this.focusedComponent_.dispatchKey_(event);
};
/**
* @return {tv.ui.Component} Component that is currently focused.
*/
tv.ui.Document.prototype.getFocusedComponent = function() {
return this.focusedComponent_;
};
/**
* Sets focused component in document.
* Note that it is not guaranteed that component will be focused immediately
* after exiting this method or even at all.
* @param {tv.ui.Component} componentPendingFocus Component to focus.
*/
tv.ui.Document.prototype.setFocusedComponent = function(componentPendingFocus) {
// Detect recursive call from blur or focus handler.
var recursive = goog.isDef(this.componentPendingFocus_);
// Remember component to focus.
// If called recursively from handler, last call wins.
this.componentPendingFocus_ = componentPendingFocus;
// Request will proceed in loop below.
if (recursive) {
return;
}
while (true) {
componentPendingFocus = this.componentPendingFocus_;
if (this.focusedComponent_ == componentPendingFocus) {
delete this.componentPendingFocus_;
return;
}
// Find lowest common ancestor in component tree.
var blurCandidates = this.getAncestorsAndSelf_(this.focusedComponent_);
var focusCandidates = this.getAncestorsAndSelf_(componentPendingFocus);
var highestBlurIndex = blurCandidates.length - 1;
var highestFocusIndex = focusCandidates.length - 1;
if (highestBlurIndex > 0 && highestFocusIndex > 0) {
while (blurCandidates[highestBlurIndex] ==
focusCandidates[highestFocusIndex]) {
highestBlurIndex--;
highestFocusIndex--;
}
}
// Blur components up to the common ancestor.
for (var blurIndex = 0; blurIndex <= highestBlurIndex; blurIndex++) {
blurCandidates[blurIndex].dispatchBlur_();
}
this.focusedComponent_ = componentPendingFocus;
// Update selection chain.
var selectIndex = highestFocusIndex;
if (selectIndex + 1 == focusCandidates.length) {
selectIndex--;
}
for (; selectIndex >= 0; selectIndex--) {
focusCandidates[selectIndex + 1].setSelectedChild(
focusCandidates[selectIndex]);
}
// Focus components down from the common ancestor.
for (var focusedComponentIndex = highestFocusIndex;
focusedComponentIndex >= 0; focusedComponentIndex--) {
focusCandidates[focusedComponentIndex].dispatchFocus_();
}
}
};
/**
* @param {tv.ui.Component} self Component to start with.
* @return {Array.<tv.ui.Component>} All ancestors of the given component
* including itself.
* @private
*/
tv.ui.Document.prototype.getAncestorsAndSelf_ = function(self) {
var ancestors = [];
for (var ancestor = self; ancestor; ancestor = ancestor.getParent()) {
ancestors.push(ancestor);
}
return ancestors;
};
<file_sep>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Container that displays child components in tabs.
* Container consists of two child containers - tab bar and tab content, whose
* selections are synchronized.
*/
goog.provide('tv.ui.TabContainer');
goog.require('tv.ui.Container');
/**
* Constructs tab container.
* @constructor
* @extends {tv.ui.Container}
*/
tv.ui.TabContainer = function() {
goog.base(this);
};
goog.inherits(tv.ui.TabContainer, tv.ui.Container);
/**
* @type {string} Main CSS class that triggers decoration.
*/
tv.ui.TabContainer.CLASS = 'tv-tab-container';
tv.ui.registerDecorator(tv.ui.TabContainer, tv.ui.TabContainer.CLASS);
/**
* CSS classes that control look and feel of tab container.
* @enum {string}
*/
tv.ui.TabContainer.Class = {
/**
* Denotes element that serves at tab bar.
* This element should be decorated as tv.ui.Container.
* @see #getBarContainer
*/
BAR: 'tv-tab-container-bar',
/**
* Denotes element that serves at tab content.
* This element should be decorated as tv.ui.Container.
* @see #getContentContainer
*/
CONTENT: 'tv-tab-container-content',
/**
* Applied to tab content if it has to intercept focus from tab bar.
* This way tab bar is excluded from navigation but remains focusable.
*/
FOCUS_ATTRACTOR: 'tv-tab-container-focus-attractor'
};
/**
* @type {tv.ui.Container}
* @private
*/
tv.ui.TabContainer.prototype.barContainer_;
/**
* @type {tv.ui.Container}
* @private
*/
tv.ui.TabContainer.prototype.contentContainer_;
/**
* @return {tv.ui.Container} Bar container.
*/
tv.ui.TabContainer.prototype.getBarContainer = function() {
return this.barContainer_;
};
/**
* @return {tv.ui.Container} Content container.
*/
tv.ui.TabContainer.prototype.getContentContainer = function() {
return this.contentContainer_;
};
/**
* @return {boolean} Whether tab content container is focus attractor.
*/
tv.ui.TabContainer.prototype.hasFocusAttractor = function() {
return this.contentContainer_ && goog.dom.classes.has(
this.contentContainer_.getElement(),
tv.ui.TabContainer.Class.FOCUS_ATTRACTOR);
};
/**
* @inheritDoc
*/
tv.ui.TabContainer.prototype.getClass = function() {
return tv.ui.TabContainer.CLASS;
};
/**
* @inheritDoc
*/
tv.ui.TabContainer.prototype.addChild = function(child) {
goog.base(this, 'addChild', child);
if (goog.dom.classes.has(
child.getElement(), tv.ui.TabContainer.Class.BAR)) {
goog.asserts.assert(
child instanceof tv.ui.Container, 'Tab bar should be a container.');
this.barContainer_ = /** @type {tv.ui.Container} */(child);
this.getEventHandler().listen(
this.barContainer_,
tv.ui.Container.EventType.SELECT_CHILD,
this.onBarSelectChild);
this.getEventHandler().listen(
this.barContainer_,
tv.ui.Component.EventType.FOCUS,
this.onBarFocus);
} else if (goog.dom.classes.has(
child.getElement(), tv.ui.TabContainer.Class.CONTENT)) {
goog.asserts.assert(
child instanceof tv.ui.Container, 'Tab content should be a container.');
this.contentContainer_ = /** @type {tv.ui.Container} */(child);
this.getEventHandler().listen(
this.contentContainer_,
tv.ui.Container.EventType.SELECT_CHILD,
this.onContentSelectChild);
}
};
/**
* @inheritDoc
*/
tv.ui.TabContainer.prototype.selectPreviousChild = function() {
return !this.hasFocusAttractor() && goog.base(this, 'selectPreviousChild');
};
/**
* @inheritDoc
*/
tv.ui.TabContainer.prototype.selectNextChild = function() {
return !this.hasFocusAttractor() && goog.base(this, 'selectNextChild');
};
/**
* Handles child selection in bar container.
* @protected
*/
tv.ui.TabContainer.prototype.onBarSelectChild = function() {
if (this.contentContainer_) {
this.synchronizeSelectedChildren_(
this.barContainer_, this.contentContainer_);
}
};
/**
* Handles child selection in content container.
* @protected
*/
tv.ui.TabContainer.prototype.onContentSelectChild = function() {
if (this.barContainer_) {
this.synchronizeSelectedChildren_(
this.contentContainer_, this.barContainer_);
}
};
/**
* Sets selected child in destination container based on selected child in
* source container.
* @param {tv.ui.Container} sourceContainer Source container.
* @param {tv.ui.Container} destinationContainer Destination container.
* @private
*/
tv.ui.TabContainer.prototype.synchronizeSelectedChildren_ = function(
sourceContainer, destinationContainer) {
var selectedChildIndex = goog.array.indexOf(
sourceContainer.getChildren(),
sourceContainer.getSelectedChild());
destinationContainer.setSelectedChild(
destinationContainer.getChildren()[selectedChildIndex]);
};
/**
* Handles focus on bar container.
* @protected
*/
tv.ui.TabContainer.prototype.onBarFocus = function(event) {
if (this.hasFocusAttractor()) {
this.tryFocusSelectedDescendant(this.contentContainer_);
}
};
/**
* Focuses given component if it is able to receive focus.
* Does nothing otherwise.
* @param {goog.ui.Component} component Component to focus.
* @protected
*/
tv.ui.TabContainer.prototype.tryFocusSelectedDescendant = function(component) {
var selectedDescendant = component.getSelectedDescendantOrSelf();
if (selectedDescendant) {
this.getDocument().setFocusedComponent(selectedDescendant);
}
};
<file_sep>source 'https://rubygems.org'
gem 'rails', '3.2.11'
gem 'jquery-rails'
gem 'slim-rails'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'rails-backbone'
gem 'compass-rails'
gem 'zurb-foundation'
gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
group :development do
gem 'debugger'
gem 'sqlite3'
end
group :production do
gem 'pg'
end
<file_sep>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Core utilities for TV components.
*/
// TODO(maksym): Decide on decorate-only approach, replace decorate() with
// constructor and remove setters for final properties.
goog.provide('tv.ui');
goog.require('goog.array');
goog.require('goog.dom');
/**
* Map from CSS class to component constructor used to create components from
* DOM tree.
* @type {Object.<string, Function>}
* @private
*/
tv.ui.decoratorRegistry_ = {};
/**
* Registers decorator that will be used to create component from DOM element.
* @param {Function} decorator Component constructor.
* @param {string|Array.<string>} classNames CSS class or list of classes that
* will trigger component creation.
*/
tv.ui.registerDecorator = function(decorator, classNames) {
goog.array.forEach(
goog.isArray(classNames) ? classNames : [classNames],
function(className) {
tv.ui.decoratorRegistry_[className] = decorator;
});
};
/**
* Finds component constructor by matching it against one of the CSS classes.
* @param {Array.<string>} classNames List of CSS classes to look for into
* decorator registry. First matched class wins.
* @return {Function} Component constructor or null if registry doesn't contain
* match for any of CSS classes.
*/
tv.ui.findDecorator = function(classNames) {
for (var i = 0; i < classNames.length; i++) {
var decorator = tv.ui.decoratorRegistry_[classNames[i]];
if (decorator) {
return decorator;
}
}
return null;
};
/**
* Recursively creates components from DOM tree based on CSS classes, including
* root element. DOM elements that doesn't have appropriate decorators are
* omitted.
* @param {Element} element Root element for traversal.
* @param {Function} opt_handler Handler to be called for each decorated
* component.
* @param {tv.ui.Container} opt_parentContainer Root container for decorated
* components.
*/
tv.ui.decorate = function(element, opt_handler, opt_parentContainer) {
var component;
var decorator = tv.ui.findDecorator(goog.dom.classes.get(element));
if (decorator) {
component = new decorator();
component.decorate(element);
opt_parentContainer && opt_parentContainer.addChild(component);
}
tv.ui.decorateChildren(
element, opt_handler, component || opt_parentContainer);
if (component) {
opt_handler && opt_handler(component);
}
};
/**
* Recursively creates components from DOM tree based on CSS classes, excluding
* root element. DOM elements that doesn't have appropriate decorators are
* omitted. Usually used to update content of (already decorated) container.
* @param {Element} element Root element for traversal.
* @param {Function} opt_handler Handler to be called for each decorated
* component.
* @param {tv.ui.Container} opt_parentContainer Root container for decorated
* components.
*/
tv.ui.decorateChildren = function(element, opt_handler, opt_parentContainer) {
for (var childNode = element.firstChild; childNode;
childNode = childNode.nextSibling) {
if (childNode.nodeType == goog.dom.NodeType.ELEMENT) {
tv.ui.decorate(
/** @type {Element} */(childNode),
opt_handler,
opt_parentContainer);
}
}
};
/**
* Number of recursive calls to postponeRender() function.
* @type {number}
* @private
*/
tv.ui.postponeRenderCount_ = 0;
/**
* List of components requested rendering.
* @type {Array.<tv.ui.Component>}
* @private
*/
tv.ui.componentsScheduledRender_;
/**
* Postpones all rendering in components until given function exits.
* Allows to minimize number of layouts and style recalculations in browser.
* @param {Function} f Function to call, usually causing massive rendering.
* @param {Object} opt_context Context to call function in.
*/
tv.ui.postponeRender = function(f, opt_context) {
if (tv.ui.postponeRenderCount_++ == 0) {
tv.ui.componentsScheduledRender_ = [];
}
f.call(opt_context);
if (--tv.ui.postponeRenderCount_ == 0) {
goog.array.forEach(tv.ui.componentsScheduledRender_, function(component) {
component.render();
});
delete tv.ui.componentsScheduledRender_;
}
};
/**
* Schedules rendering of component if rendering is postponed and performes
* rendering immediately otherwise.
* @param {tv.ui.Component} component Component to render.
*/
tv.ui.scheduleRender = function(component) {
if (tv.ui.postponeRenderCount_ == 0) {
component.render();
} else {
tv.ui.componentsScheduledRender_.push(component);
}
};
<file_sep>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Menu with submenus.
* Based on tab container. Tab bar should consist of buttons which represent
* menu items, tab content - of containers which represent submenus. When button
* in tab bar is pressed, menu will focus appropriate container in tab content.
*/
goog.provide('tv.ui.Menu');
goog.require('tv.ui.Button');
goog.require('tv.ui.TabContainer');
/**
* Constructs menu.
* @constructor
* @extends {tv.ui.TabContainer}
*/
tv.ui.Menu = function() {
goog.base(this);
};
goog.inherits(tv.ui.Menu, tv.ui.TabContainer);
/**
* @type {string} Main CSS class that triggers decoration.
*/
tv.ui.Menu.CLASS = 'tv-menu';
tv.ui.registerDecorator(tv.ui.Menu, tv.ui.Menu.CLASS);
/**
* CSS classes that control look and feel of menu.
* @enum {string}
*/
tv.ui.Menu.Class = {
/**
* A button inside tab content which when pressed will bring focus back to
* corresponding menu item in tab bar.
*/
BACK_BUTTON: 'tv-menu-back-button'
};
/**
* @inheritDoc
*/
tv.ui.Menu.prototype.getClass = function() {
return tv.ui.Menu.CLASS;
};
/**
* @inheritDoc
*/
tv.ui.Menu.prototype.addChild = function(child) {
goog.base(this, 'addChild', child);
if (goog.dom.classes.has(
child.getElement(), tv.ui.TabContainer.Class.BAR)) {
this.getEventHandler().listen(
/** @type {tv.ui.Container} */(child),
tv.ui.Button.EventType.ACTION,
this.onBarAction);
} else if (goog.dom.classes.has(
child.getElement(), tv.ui.TabContainer.Class.CONTENT)) {
this.getEventHandler().listen(
/** @type {tv.ui.Container} */(child),
tv.ui.Button.EventType.ACTION,
this.onContentAction);
this.getEventHandler().listen(
/** @type {tv.ui.Container} */(child),
tv.ui.Component.EventType.KEY,
this.onContentKey);
}
};
/**
* @inheritDoc
*/
tv.ui.Menu.prototype.onBarSelectChild = function(event) {
goog.base(this, 'onBarSelectChild', event);
this.resetSubMenuSelection_();
};
/**
* @inheritDoc
*/
tv.ui.Menu.prototype.onBarFocus = function(event) {
this.resetSubMenuSelection_();
goog.base(this, 'onBarFocus', event);
};
/**
* Handles action event on tab bar.
* Focuses sub-menu that corresponds to selected menu item.
* @param {goog.events.Event} event Action event.
* @protected
*/
tv.ui.Menu.prototype.onBarAction = function(event) {
if (!goog.dom.classes.has(
event.target.getElement(), tv.ui.Menu.Class.BACK_BUTTON)) {
this.resetSubMenuSelection_();
this.tryFocusSelectedDescendant(this.getContentContainer());
event.stopPropagation();
}
};
/**
* Handles action event on tab content.
* Focuses menu item that corresponds to selected sub-menu if 'Back' button was
* pressed.
* @param {goog.events.Event} event Action event.
* @protected
*/
tv.ui.Menu.prototype.onContentAction = function(event) {
if (goog.dom.classes.has(
event.target.getElement(), tv.ui.Menu.Class.BACK_BUTTON)) {
this.tryFocusSelectedDescendant(this.getBarContainer());
event.stopPropagation();
}
};
/**
* Handles key event on tab content.
* Focuses menu item that corresponds to selected sub-menu if Esc is pressed.
* @param {goog.events.KeyEvent} event Key event.
* @protected
*/
tv.ui.Menu.prototype.onContentKey = function(event) {
if (event.keyCode == goog.events.KeyCodes.ESC) {
this.tryFocusSelectedDescendant(this.getBarContainer());
event.stopPropagation();
}
};
/**
* Selects first child in sub-menu.
* @private
*/
tv.ui.Menu.prototype.resetSubMenuSelection_ = function() {
if (this.getContentContainer()) {
var subMenu = this.getContentContainer().getSelectedChild();
if (subMenu instanceof tv.ui.Container) {
subMenu.selectFirstChild();
}
}
};
| 3e11bb9856e84721eeff13a14852c551d8d67699 | [
"JavaScript",
"Ruby"
]
| 14 | Ruby | bencallaway/gtv_classroom | 2cb21e00f254192cdce5c9e2402c8d293a58ecff | 72df23cc414ad25a368a17775e82d8bc822d8d20 |
refs/heads/master | <repo_name>toddarmstrong/factory-fable<file_sep>/gulpfiles/js/controllers/MainController.js
app.controller('MainController', ['$scope', '$interval', '$ngBootbox', 'Flash', function($scope, $interval, $ngBootbox, Flash) {
var startingStatus = {
currentMoney: 100,
moneyPerSec: 1,
availableEmployees: 10,
maxEmployees: 10
};
var startingStation = {
perSec: 0,
employees: 0,
speed: 1,
quality: 1
};
var startingProducts = {
productList: [
{id: 1, name: 'Product 01', amount: 0, value: 10},
{id: 2, name: 'Product 02', amount: 0, value: 20},
{id: 3, name: 'Product 03', amount: 0, value: 30}
],
stationOneSelected: {id: 1},
distributionSelected: {id: 1}
};
var startingDistribution = {
perSec: 0,
employees: 0,
speed: 1
};
// LOAD
if (simpleStorage.get("status")) {
$scope.status = simpleStorage.get("status");
} else {
$scope.status = startingStatus;
}
if (simpleStorage.get("products")) {
$scope.products = simpleStorage.get("products");
} else {
$scope.products = startingProducts;
}
if (simpleStorage.get("stationOne")) {
$scope.stationOne = simpleStorage.get("stationOne");
} else {
$scope.stationOne = startingStation;
}
if (simpleStorage.get("distribution")) {
$scope.distribution = simpleStorage.get("distribution");
} else {
$scope.distribution = startingStation;
}
// SAVE
$scope.saveGame = function(index) {
simpleStorage.set("status", $scope.status);
simpleStorage.set("products", $scope.products);
simpleStorage.set("stationOne", $scope.stationOne);
simpleStorage.set("distribution", $scope.distribution);
$ngBootbox.alert('Game successfully saved!');
//var message = 'Game saved!';
//Flash.create('success', message, 'status-message');
};
// RESET
$scope.resetGame = function(index) {
$ngBootbox.confirm('Are you sure you want to reset your game?')
.then(function() {
//for(var x in startingStatus) {
// $scope.status[x] = startingStatus[x];
//}
$scope.status = jQuery.extend(true, {}, startingStatus);
simpleStorage.set("status", $scope.status);
$scope.products = jQuery.extend(true, {}, startingProducts);
simpleStorage.set("products", $scope.products);
$scope.stationOne = jQuery.extend(true, {}, startingStation);
simpleStorage.set("stationOne", $scope.stationOne);
$scope.distribution = jQuery.extend(true, {}, startingDistribution);
simpleStorage.set("distribution", $scope.distribution);
}, function() {
//cancel reset
});
};
// LOGIC
$interval(function() {
$scope.status.currentMoney += $scope.status.moneyPerSec;
$scope.products.productList[($scope.products.stationOneSelected.id - 1)].amount += $scope.stationOne.perSec;
}, 1000);
$scope.increaseEmployee = function(station) {
if ($scope.status.availableEmployees > 0) {
station.employees += 1;
$scope.status.availableEmployees -= 1;
station.perSec = (station.employees * 1);
//$scope.status.moneyPerSec = ($scope.status.moneyPerSec + ($scope.distribution.perSec * $scope.products.productList[($scope.products.distributionSelected.id - 1)]));
} else {
$ngBootbox.alert('Not enough employees available!');
}
};
$scope.decreaseEmployee = function(station) {
if (station.employees > 0) {
station.employees -= 1;
$scope.status.availableEmployees += 1;
station.perSec = (station.employees * 1);
} else {
$ngBootbox.alert('There are no employees assigned to this station!');
}
}
}]);<file_sep>/gulpfile.js
var gulp = require('gulp'),
sass = require('gulp-sass'),
minify = require('gulp-minify-css'),
rename = require('gulp-rename'),
autoprefixer = require('gulp-autoprefixer'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
watch = require('gulp-watch');
// SASS //
gulp.task('sass', function() {
return gulp.src('gulpfiles/scss/style.scss')
.pipe(sass())
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('css'))
.pipe(sass())
.pipe(autoprefixer())
.pipe(minify({compatibility: 'ie8'}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('css'));
});
gulp.task('bootstrap', function() {
return gulp.src('node_modules/bootstrap/dist/css/bootstrap.css')
.pipe(rename('_bootstrap.scss'))
.pipe(gulp.dest('gulpfiles/scss/partials'))
});
// JS //
gulp.task('angular-js', function() {
var files = ['node_modules/angular/angular.js'];
return gulp.src(files)
.pipe(concat('plugins/angular.js'))
.pipe(gulp.dest('js'))
.pipe(rename('plugins/angular.min.js'))
.pipe(uglify())
.pipe(gulp.dest('js'));
});
gulp.task('app-js', function() {
var plugins = [
'node_modules/jquery/dist/jquery.js',
'node_modules/bootstrap/dist/js/bootstrap.js',
'node_modules/simplestorage.js/simpleStorage.js',
'node_modules/bootbox/bootbox.js',
'node_modules/ngbootbox/dist/ngBootbox.js',
'node_modules/angular-flash-alert/dist/angular-flash.js'
];
var app = ['gulpfiles/js/app.js'];
var controllers = ['gulpfiles/js/controllers/MainController.js'];
var directives = ['gulpfiles/js/directives/directives.js'];
var filters = ['gulpfiles/js/filters/filters.js'];
var files = plugins.concat(app, controllers, directives, filters);
return gulp.src(files)
.pipe(concat('app.js'))
.pipe(gulp.dest('js'))
.pipe(rename('app.min.js'))
.pipe(uglify())
.pipe(gulp.dest('js'));
});
// WATCH //
gulp.task('watch', function() {
gulp.watch('gulpfiles/js/**/**.js', ['app-js']);
gulp.watch('gulpfiles/scss/**/**.scss', ['sass']);
});
gulp.task('default', function () {
gulp.run('watch');
});<file_sep>/README.md
# factory-fable
An incremental web game in which you manage the production and distribution of goods.
<file_sep>/gulpfiles/js/filters/filters.js
app.filter('nospace', function () {
return function (value) {
return (!value) ? '' : value.replace(/ /g, '');
};
}); | c99237d62ed286dcd7b257f379cd6190cbbf3411 | [
"JavaScript",
"Markdown"
]
| 4 | JavaScript | toddarmstrong/factory-fable | 0a5bdbfbe3db0024926e825db744dba5275eb4d9 | 9d4ddfda028a8846ca2fc2071d5e16b19c3f1b3f |
refs/heads/master | <file_sep># hw4
CST 336 hw 4
<file_sep>const express = require("express");
const faker = require("faker");
const app = express();
app.engine('html', require('ejs').renderFile);
app.use(express.static("public"));
//Notes - Changed file names from .html to .ejs,
//added in span id tags in header.ejs to upkeep the distinction in the nav menu
//(title color change) to indicate to the user which page they are on
//(refer to the script tags in the non-partial views),
//and passed in new variable from route to view in render lines.
//The faker is in the header.ejs view as a random quote.
//routes
app.get("/", function(req, res) {
res.render("index.ejs", {"randomQuote":faker.hacker.phrase()});
});
app.get("/index", function(req, res) {
res.render("index.ejs", {"randomQuote":faker.hacker.phrase()});
});
app.get("/howitsused", function(req, res) {
res.render("howitsused.ejs", {"randomQuote":faker.hacker.phrase()});
});
app.get("/howitworks", function(req, res) {
res.render("howitworks.ejs", {"randomQuote":faker.hacker.phrase()});
});
app.get("/aihistory", function(req, res) {
res.render("aihistory.ejs", {"randomQuote":faker.hacker.phrase()});
});
//server listener
/*app.listen("8080", "127.0.0.1", function() {
console.log("Running Express Server...");
});*/
//accounts for publishing to Heroku
app.listen(process.env.PORT, process.env.IP, function() {
console.log("Running Express Server...");
});
| c7a0a0f8bbce272a70d195d1104290a9780369ee | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | dollybuzz/hw4 | 0064f0d82138202f7375b7365d66957bff93c943 | 51a87f9508c06caafa2b3b2db72b3a38104f2718 |
refs/heads/main | <repo_name>mibrahim09/clinic-managment-system<file_sep>/README.md
# clinic-managment-system
Clinic Management System
| 1f4f364ce027b903124965820bad56a5b5b115ad | [
"Markdown"
]
| 1 | Markdown | mibrahim09/clinic-managment-system | 076f6e073ffcf0079aff7aec0a94643076570acc | 3c81576597005f6c9adb95acb1c1ea05eb93aa2c |
refs/heads/master | <file_sep>#!/usr/bin/env ruby
if ARGV[0] && ARGV[0] == "-c"
odds = 98
else
odds = 88
end
(0..39).each do |i|
puts randn = rand(100)
if randn > odds
abort "Even tough you did everything right, your chain broke at #{i}."
end
end
puts "You successfully reached a 40 chain."
exit 0
<file_sep>#!/usr/bin/env ruby
# CONVERTER
# BY SHADYFENNEC <<EMAIL>>
# VER 0.3.2
# AUG 1 2016 12:00PM GMT+01:00
# PURPROSE : Encode any string to a user-specified base
### ARGV ###
ARGV << '--help' if ARGV.empty?
abort("Syntax error ! Please use --help if you need help") if ARGV[0] != '--help' and ARGV.length != 3
### END ARGV ###
### HELP ###
if ARGV[0] == "--help"
puts "Encode any string to a user-specified base"
puts "Syntax : number number_base output_base"
puts "number : the number to encode"
puts "number_base : the base of number. Example : for E21D41, specify 0123456789ABCDEF"
puts "output_base : the base to encode number with. Example : to binary, specify 01"
end
### END HELP ###
### INI ###
number = ARGV[0].to_s
number_a = number.split(//) # Transforms the string in array
number_alph = ARGV[1].to_s
number_alph_a = number_alph.split(//)
output_alph = ARGV[2].to_s
output_alph_a = output_alph.split(//)
number_base = number_alph.length
output_base = output_alph.length
def index_in_alph(str, alph, array) # Arranges in an array the decimal equivalent of a given character in an alphabet
for i in 1..str.length
array[i-1] = alph.index(str[i-1])
end
end
def convert_array_to_base(array, base) # Technically any base, but is used here in coordination with index_in_alph to transform the array in decimal
converted_number = 0
for i in 0..(array.length - 1)
converted_number += (base ** (array.length - 1 -i)) * array[i]
end
return converted_number
end
def convert_decimal_to_base(num, base, alph) # Converts any decimal number (base 10) in the user specified base
string, quotient = "", num
loop do
quotient, remainder = (quotient).divmod(base)
string.prepend(alph[remainder])
break if quotient.zero?
end
return string
end
### END INI ###
### ANALYSIS ###
# Check if alphabets are valid
abort("Argument error : a character appears more than once in number_base") if number_alph_a.uniq.length != number_alph_a.length && ARGV[0] != '--help'
abort("Argument error : a character appears more than once in output_base") if output_alph_a.uniq.length != output_alph_a.length && ARGV[0] != '--help'
# Check if number is coherent with number_alph
if ARGV[0] == '--help' # If put on the same line, the two conditions cause an error due to a nil value
abort()
else
abort("Coherence error : a character in number does not appear in number_base") if !((number_a - number_alph_a).empty?)
end
### END ANALYSIS ###
### PROCESSING ###
# Encode number to decimal
number_decimal = 0
number_decimal_a = []
index_in_alph(number, number_alph, number_decimal_a)
number_decimal = convert_array_to_base(number_decimal_a, number_base)
# Encode decimal to output_base
encoded_number = convert_decimal_to_base(number_decimal, output_base, output_alph)
### END PROCESSING ###
### OUTPUT ###
puts "Encoding #{number} (base #{number_base.to_s}) into base #{output_base.to_s}"
puts "Result : #{encoded_number.to_s}"
### END OUTPUT ###
<file_sep># If not running interactively, don't do anything
[ -z "$PS1" ] && return
# don't put duplicate lines in the history. See bash(1) for more options
# ... or force ignoredups and ignorespace
HISTCONTROL=ignoredups:ignorespace
# append to the history file, don't overwrite it
shopt -s histappend
# git completion
source ~/.git-completion.bash
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/home/sam/.local/bin
alias pwd_base='pwd | rev | cut -d"/" -f 1 | rev'
PROMPT_COMMAND='echo -ne "\033]0;$TERM: `pwd_base`\007"'
PS1='\[\e[1;38m\]\#`if [ $? = 0 ]; then echo "\[\e[1;32m\] ✔ "; else echo "\[\e[1;31m\] ✘ "; fi`\[\e[1;36m\]\u\[\e[0m\]@\h \[\e[1;33m\]\W \[\e[0m\]\$ '
alias ls='ls --color=auto'
alias ll='ls -alF'
alias la='ls -A'
| 1eefa727a512c32a6e76fd7b74f725afc305034a | [
"Ruby",
"Shell"
]
| 3 | Ruby | Siphonay/dotfiles_n_stuff | 8beaecca543c2e643d2da7cb70bc4bae76e062bd | 2946fb1432ed191cb6e690e80c7415fc66847ae5 |
refs/heads/master | <repo_name>Eroselyzong820/vueElementUIDemo<file_sep>/src/store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count: 0,
comfirmForm:'',
params:{
goodsList:[]
}
},
mutations: {
coundAdd(state) {
console.log(state);
state.count++;
},
transFromMute(state, params) {
state.params.goodsList = params;
}
},
actions: {
transFromAction(ctx, params) {
setTimeout(function () {
state.transformInfo = params;
} , 2000)
}
}
})
//mutations 追踪前后状态,但是异步会追踪不到
//actions :可以做异步 dispatch commit<file_sep>/src/router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import transPre from './views/transdemo1/transPre'
import transCom from './views/transdemo1/transCom'
import transRes from './views/transdemo1/transRes'
Vue.use(Router);
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
},
{
path: '/transPre',
name: 'transPre',
component: transPre
},
{
path: '/transCom',
name: 'transCom',
component: transCom
},
{
path: '/transRes',
name: 'transRes',
component: transRes
}
]
})
<file_sep>/src/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/ index.css'
import './registerServiceWorker'
import axios from 'axios'
require('./mock.js');
// import config from './config/config.js'
Vue.prototype.axios = axios;//axios不支持Vue.use()的声明方式,所以要用Vue的原型方式聲明
Vue.config.productionTip = false;
//引入ElementUI 组件引用到实例
Vue.use(ElementUI);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app');
/*var instance = axios.create({
// baseURL: '/api',
// timeout: 1000,
// headers: {'X-Custom-Header': 'foobar'}
host:'127.0.0.1',
port: 8080
});*/
| 173ee1d94c7c116799358fcdc4cbe19e949e134a | [
"JavaScript"
]
| 3 | JavaScript | Eroselyzong820/vueElementUIDemo | 58c926cb07b852d508b146989cb58c0efed440a6 | ba64b12fe4614b376946026e0531818566fba7b7 |
refs/heads/master | <repo_name>esteban-gs/ProjectOneMVC<file_sep>/ProjectOneMVC.Web/Services/ClassService.cs
using AutoMapper;
using ProjectOneMVC.Core.Entities;
using ProjectOneMVC.Data.Data.Repository;
using ProjectOneMVC.Web.ViewModels;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ProjectOneMVC.Web.Services
{
public class ClassService
{
private readonly ClassRepository classRepo;
private readonly UserClassRepository ucRepo;
private readonly IMapper _mapper;
public ClassService(ClassRepository classRepo,
UserClassRepository ucRepo,
IMapper mapper)
{
this.classRepo = classRepo;
this.ucRepo = ucRepo;
this._mapper = mapper;
}
/// <summary>
/// Gets all the records in class repo, takes a return type.
/// The type passed must be defined in the Automapper profiles:
/// From Class -> SomeClass
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>List of DB Class mapped to the type passed.</returns>
public List<T> GetAll<T>() where T : class
{
var dbClasses = classRepo.GetAll().Result;
return _mapper.Map<List<T>>(dbClasses);
}
/// <summary>
/// Gets all the records in class repo, takes a return type.
/// The type passed must be defined in the Automapper profiles:
/// From Class -> SomeClass
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>List of DB UserClass mapped to the type passed.</returns>
public List<T> GetAllForUser<T>(string userId) where T : class
{
List<Class> dbClasses = new List<Class>();
var userClasses = ucRepo.FindByCondition(uc => uc.SchoolUserId == userId).ToList();
foreach (var userClass in userClasses)
{
var enrolledClass = classRepo.Get(userClass.ClassId).Result;
dbClasses.Add(enrolledClass);
}
return _mapper.Map<List<T>>(dbClasses);
}
public async Task<ResultModel> AssignClassFor(string userId, List<EnrollViewModel> classes)
{
UserClass userClass = new UserClass();
var results = new ResultModel() { Success = false};
var recordsUpdated = 0;
foreach (var item in classes)
{
var ucExistsinDb = ucRepo.Exists(userId, item.Id).Result;
if (item.Selected && !ucExistsinDb)
{
userClass.ClassId = item.Id;
userClass.SchoolUserId = userId;
await ucRepo.Add(userClass);
recordsUpdated++;
}
}
results.Success = recordsUpdated > 0;
results.RecordsUpdated = recordsUpdated;
return results;
}
}
}
public struct ResultModel
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
public int RecordsUpdated { get; set; }
}<file_sep>/ProjectOneMVC.Web/Controllers/ClassesController.cs
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ProjectOneMVC.Data;
using ProjectOneMVC.Web.ViewModels;
namespace ProjectOneMVC.Web.Controllers
{
public class ClassesController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
public ClassesController(
ApplicationDbContext context,
IMapper mapper)
{
this._context = context;
this._mapper = mapper;
}
[Authorize(Roles = "Admin")]
// GET: ClassesController
public ActionResult Index()
{
var classes = _context.Classes.ToList();
var classesToRetrun = _mapper.Map<List<ClassViewModel>>(classes);
return View(classesToRetrun);
}
}
}
<file_sep>/ProjectOneMVC.Web/MapperProfiles/Profiles.cs
using AutoMapper;
using ProjectOneMVC.Core.Entities;
using ProjectOneMVC.Web.ViewModels;
namespace ProjectOneMVC.Web.MapperProfiles
{
public class Profiles : Profile
{
public Profiles()
{
//Classes List
CreateMap<Class, ClassViewModel>();
CreateMap<Class, EnrollViewModel>();
}
}
}
<file_sep>/ProjectOneMVC.Web/Controllers/HomeController.cs
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ProjectOneMVC.Web.DTO;
using ProjectOneMVC.Web.Services;
using ProjectOneMVC.Web.ViewModels;
namespace ProjectOneMVC.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ClassService _classService;
public HomeController(
ILogger<HomeController> logger,
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
ClassService classService
)
{
_logger = logger;
this._userManager = userManager;
this._signInManager = signInManager;
this._classService = classService;
}
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public IActionResult Index()
{
return View();
}
#region Identity
[HttpGet]
[AllowAnonymous]
public IActionResult Register(string returnUrl = null)
{
ReturnUrl = returnUrl;
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
public async Task<IActionResult> Register(RegisterInputModel inputModel, string returnUrl = null)
{
ReturnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var user = new IdentityUser { UserName = inputModel.Email, Email = inputModel.Email };
var result = await _userManager.CreateAsync(user, inputModel.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(ReturnUrl);
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
// If we got this far, something failed, redisplay form
return View();
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Login(string returnUrl = null)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
ModelState.AddModelError(string.Empty, ErrorMessage);
}
ReturnUrl = returnUrl ?? Url.Content("~/");
ViewData["ReturnUrl"] = ReturnUrl;
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
return View();
}
[HttpPost]
public async Task<IActionResult> Login(LoginInputModel loginInputModel, string returnUrl = null)
{
ReturnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(loginInputModel.Email, loginInputModel.Password, loginInputModel.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(ReturnUrl = ReturnUrl ?? Url.Content("~/"));
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View();
}
}
// If we got this far, something failed, redisplay form
return View();
}
public async Task<IActionResult> Logout(string returnUrl = null)
{
await _signInManager.SignOutAsync();
_logger.LogInformation("User logged out.");
if (returnUrl != null)
{
return LocalRedirect(returnUrl);
}
else
{
return View();
}
}
#endregion Identity
// GET: ClassesController
[Authorize(Roles = "Admin")]
[HttpGet]
public ActionResult ClassList()
{
var classViewModel = _classService.GetAll<ClassViewModel>();
return View(classViewModel);
}
[Authorize(Roles = "Admin")]
[HttpGet]
public IActionResult Enroll()
{
var classViewModel = _classService.GetAll<EnrollViewModel>();
return View(classViewModel);
}
[Authorize(Roles = "Admin")]
[HttpPost]
public async Task<IActionResult> Enroll(List<EnrollViewModel> inputModel)
{
var user = await _userManager.GetUserAsync(HttpContext.User);
var results = await _classService.AssignClassFor(user.Id, inputModel);
if (results.Success)
{
return RedirectToAction(nameof(StudentClasses), "Home");
}
// If we get this far, provice feedback
ViewData["Error"] = "Class already assigned!";
return View(_classService.GetAll<EnrollViewModel>());
}
// GET: ClassesController
[Authorize(Roles = "Admin")]
[HttpGet]
public async Task<ActionResult> StudentClasses()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
var classesToRetrun = _classService.GetAllForUser<ClassViewModel>(user.Id);
return View(classesToRetrun);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>/ProjectOneMVC.Data/Data/Repository/Repository.cs
using Microsoft.EntityFrameworkCore;
using ProjectOneMVC.Core.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace ProjectOneMVC.Data.Data.Repository
{
public abstract class Repository<TEntity, TContext> : IRepository<TEntity>
where TEntity : class, IEntity
where TContext : ApplicationDbContext
{
private readonly TContext context;
public Repository(TContext context)
{
this.context = context;
}
public async Task<TEntity> Add(TEntity entity)
{
context.Set<TEntity>().Add(entity);
await context.SaveChangesAsync();
return entity;
}
public async Task<TEntity> Delete(int id)
{
var entity = await context.Set<TEntity>().FindAsync(id);
if (entity == null)
{
return entity;
}
context.Set<TEntity>().Remove(entity);
await context.SaveChangesAsync();
return entity;
}
public async Task<TEntity> Get(int id)
{
return await context.Set<TEntity>().FindAsync(id);
}
public async Task<List<TEntity>> GetAll()
{
return await context.Set<TEntity>().ToListAsync();
}
public async Task<TEntity> Update(TEntity entity)
{
context.Entry(entity).State = EntityState.Modified;
await context.SaveChangesAsync();
return entity;
}
virtual public IQueryable<TEntity> FindByCondition(Expression<Func<TEntity, bool>> expression)
{
var entitiesQ = context.Set<TEntity>().Where(expression);
return entitiesQ;
}
public virtual IQueryable<TEntity> GetAllEagerly(Func<IQueryable<TEntity>, IQueryable<TEntity>> func)
{
var result = context.Set<TEntity>();
IQueryable<TEntity> resultWithEagerLoading = func(result);
return resultWithEagerLoading;
}
}
}
<file_sep>/ProjectOneMVC.Core/Entities/Class.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace ProjectOneMVC.Core.Entities
{
public class Class : BaseEntity
{
[Display(Name = "Class Name")]
[Required]
[MaxLength(250)]
public string Name { get; set; }
[Display(Name = "Class Description")]
[MaxLength(750)]
public string Description { get; set; }
public decimal Price { get; set; }
public List<UserClass> UserClass { get; set; }
}
}
<file_sep>/ProjectOneMVC.Core/Entities/SchoolUser.cs
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Text;
namespace ProjectOneMVC.Core.Entities
{
public class SchoolUser : BaseEntity
{
//public string UserId { get; set; }
//public IdentityUser User { get; set; }
public List<UserClass> UserClass { get; set; }
}
}
<file_sep>/ProjectOneMVC.Data/Data/Repository/UserClassRepository.cs
using Microsoft.EntityFrameworkCore;
using ProjectOneMVC.Core.Entities;
using System.Threading.Tasks;
namespace ProjectOneMVC.Data.Data.Repository
{
public class UserClassRepository : Repository<UserClass, ApplicationDbContext>
{
private readonly ApplicationDbContext _context;
public UserClassRepository(ApplicationDbContext context) : base(context)
{
this._context = context;
}
public async Task<bool> Exists(string userId, int classId)
{
var userClass = await _context
.UserClasses
.FirstOrDefaultAsync(uc => uc.ClassId == classId &&
uc.SchoolUserId == userId);
if (userClass != null)
return true;
return false;
}
}
}
<file_sep>/ProjectOneMVC.Web/Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using ProjectOneMVC.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using AutoMapper;
using Newtonsoft.Json;
using ProjectOneMVC.Core.Entities;
using ProjectOneMVC.Data.Data.Initialization;
using ProjectOneMVC.Data.Data.Repository;
using ProjectOneMVC.Web.Services;
namespace ProjectOneMVC
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>(options =>
options.SignIn.RequireConfirmedAccount = false
)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAutoMapper(typeof(Startup));
services.AddControllersWithViews();
services.AddRazorPages();
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Home/Login";
});
// Repositories
services.AddScoped<ClassRepository>();
services.AddScoped<UserClassRepository>();
// Service
services.AddScoped<ClassService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
CreateRoles(serviceProvider).Wait();
}
private async Task CreateRoles(IServiceProvider serviceProvider)
{
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
var context = serviceProvider.GetRequiredService<ApplicationDbContext>();
await context.Database.MigrateAsync();
IdentityResult roleResult;
//here in this line we are adding Admin Role
var roleCheck = await RoleManager.RoleExistsAsync("Admin");
if (!roleCheck)
{
//here in this line we are creating admin role and seed it to the database
roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
}
//here we are assigning the Admin role to the User that we have registered above
//Now, we are assinging admin role to this user below. When will we run this project then it will
//be assigned to that user.
IdentityUser user = await UserManager.FindByEmailAsync("<EMAIL>");
var userExists = user != null;
if (!userExists)
{
var newUser = new IdentityUser("<EMAIL>") { Email = "<EMAIL>" };
await UserManager.CreateAsync(newUser, "Secret123$");
IdentityUser createdUser = await UserManager.FindByEmailAsync("<EMAIL>");
await UserManager.AddToRoleAsync(createdUser, "Admin");
}
if (userExists && !await UserManager.IsInRoleAsync(user, "Admin"))
{
await UserManager.AddToRoleAsync(user, "Admin");
}
if (!context.Classes.Any())
{
var json = SeedData.ClassJson;
var classes = JsonConvert.DeserializeObject<List<Class>>(json);
foreach (var record in classes)
{
context.Classes.Add(record);
context.SaveChanges();
}
}
}
}
}
<file_sep>/ProjectOneMVC.Data/Data/ApplicationDbContext.cs
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using ProjectOneMVC.Core.Entities;
namespace ProjectOneMVC.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{ }
public DbSet<Class> Classes { get; set; }
public DbSet<UserClass> UserClasses { get; set; }
public DbSet<SchoolUser> SchoolUsers { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<UserClass>()
.HasKey(x => new { x.ClassId, x.SchoolUserId });
builder.Entity<Class>()
.Property(c => c.Price).HasColumnType("Money");
base.OnModelCreating(builder);
}
}
}
<file_sep>/ProjectOneMVC.Web/ViewModels/ClassViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace ProjectOneMVC.Web.ViewModels
{
public class ClassViewModel
{
[Display(Name = "Database ID")]
public int Id { get; set; }
[Display(Name = "Class Name")]
[Required]
[MaxLength(250)]
public string Name { get; set; }
[Display(Name = "Class Description")]
[MaxLength(750)]
public string Description { get; set; }
[DataType(DataType.Currency)]
public decimal Price { get; set; }
}
}
<file_sep>/ProjectOneMVC.Data/Data/Repository/ClassRepository.cs
using ProjectOneMVC.Core.Entities;
namespace ProjectOneMVC.Data.Data.Repository
{
public class ClassRepository : Repository<Class, ApplicationDbContext>
{
public ClassRepository(ApplicationDbContext context) : base(context)
{
}
}
}
<file_sep>/ProjectOneMVC.Data/Data/Initialization/SeedData.cs
namespace ProjectOneMVC.Data.Data.Initialization
{
public static class SeedData
{
public static string ClassJson
{
get => @"
[
{
'Name' : 'C#',
'Description' : 'Learn C#',
'Price' : 200.0000
},
{
'Name' : 'ASP.NET MVC',
'Description' : 'Learn how to create websites',
'Price' : 250.0000
},
{
'Name' : 'Android',
'Description' : 'Learn how to write Android applications',
'Price' : 500.0000
},
{
'Name' : 'Design Patterns',
'Description' : 'Learn how to write code better',
'Price' : 300.0000
}
]
";
}
}
}
<file_sep>/ProjectOneMVC.Core/Entities/UserClass.cs
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.Serialization;
using System.Text;
namespace ProjectOneMVC.Core.Entities
{
public class UserClass : IEntity
{
[ForeignKey("SchoolUser")]
public string SchoolUserId { get; set; }
[ForeignKey("Class")]
public int ClassId { get; set; }
public IdentityUser SchoolUser { get; set; }
public Class Class { get; set; }
[IgnoreDataMember]
public int Id { get; set; }
}
}
| 38e97255155dfaa9a348721a1d1da71645cb25b0 | [
"C#"
]
| 14 | C# | esteban-gs/ProjectOneMVC | d98fbb6059831519ce5928997f33a992448898d6 | d3661ec98561052209d5fe33cf97620a0f837bb0 |
refs/heads/master | <file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
try (
BufferedReader reader = new BufferedReader(
new InputStreamReader(Main.class.getResourceAsStream("people.txt")));
Stream<String> stream = reader.lines()
) {
stream.map(line -> {
String[] s = line.split(" ");
Person p = new Person(s[0].trim(), Integer.parseInt(s[1].trim()) );
list.add(p);
return p;
})
.forEach(System.out::println);
System.out.println(list.size());
}
catch (IOException e) {
e.printStackTrace();
}
Stream<Person> stream = list.stream();
Optional<Person> min = stream.filter(p -> p.getAge() >= 20).max(Comparator.comparing(Person::getAge));
System.out.println(min.get().getName());
}
}
| 3f37eeb94de9b4715fa92773f0432129f81005de | [
"Java"
]
| 1 | Java | mkarda/JavaTestsOnly | 14ea1b69991a087693794cab00b39e64b6fa5303 | 4bf214793b548f2e5e5b0084e4f41eb43cd52245 |
refs/heads/master | <repo_name>Taiki-jp/c_middle_level<file_sep>/chapter01/main.c
#include <stdlib.h>
int main()
{
init();
done();
exit (0);
} | 65ebf0c68915f5af5d396552241c869431fc4727 | [
"C"
]
| 1 | C | Taiki-jp/c_middle_level | 6b9146fd9e0eb96ef9d51ce0280d4069106692d8 | 465665221b396fe265f2117290af18cff0e9bcd5 |
refs/heads/master | <file_sep>filename = "housing.data"
file = open(filename, "r")
for line in file:
print (line)
filename = "housing.data"
file = open(filename, "r")
for x in file:
print(x.replace('\n','').split(" "))
<file_sep>import os
path = 'c:\\users\\lucia\\desktop'
files = []
dirs = os.listdir(path)
for file in dirs:
print(file, 'file')
for dir in dirs:
print(dir, 'directory') | f43f0e50c415374fb854f1681bb17b1063a6647c | [
"Python"
]
| 2 | Python | luciaachristina/python-homework | 02ded3685b8a712cf03a012175c5373c0dd0b215 | 521fd056f3ea0d87e4b38fbe87ce383516b647a2 |
refs/heads/master | <file_sep>// misc.c
#include "stdio.h"
#include "defs.h"
#ifdef WIN32
#include "windows.h"
#else
#include "sys/time.h"
#endif
inline int getTimeMs() {
#ifdef WIN32
return GetTickCount();
#else
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec*1000 + t.tv_usec/1000;
#endif
}
<file_sep>#ifndef PVTABLE_H_INCLUDED
#define PVTABLE_H_INCLUDED
#include "defs.h"
#include "fastrand.h"
#include "state.h"
int getPvLine(const int depth, State *pos);
void clearhashTable(HashTable *table);
void initHashTable(HashTable *table, const int mb);
int probeHashEntry(State *pos, MoveTuple *move, int alpha, int beta, int depth);
void storeHashEntry(State *pos, const MoveTuple move, const int depth);
MoveTuple probePvMove(const State *pos);
#endif // #ifndef PVTABLE_H_INCLUDED
<file_sep>#pragma GCC optimize("-O3")
#pragma GCC optimize("inline")
#pragma GCC optimize("omit-frame-pointer")
#pragma GCC optimize("unroll-loops")
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <fstream>
#include <string>
#include <ctime>
#include "defs.h"
#include "state.h"
#include "fastrand.h"
#include "hash.h"
#include "search.h"
//#include "pvtable.h"
#include "misc.h"
#include "test.h"
using namespace std;
int width;
int height;
int timebank;
int time_per_move;
int time_remaining;
int max_rounds;
int current_round;
int pathLen[HEIGHT + 2][WIDTH + 2][HEIGHT + 2][WIDTH + 2];
BugsList prevBugsList[1];
void getInfluenceValue(int x, int y, int (&path)[HEIGHT + 2][WIDTH + 2], State *state) {
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
path[i][j] = 0;
}
}
queue<Point> q;
q.push(Point(x, y));
path[x][y] = 1;
while(!q.empty()) {
Point top = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
Point cur = Point(top.first + dx[i], top.second + dy[i]);
if (state->map[cur.first][cur.second] != WALL
&& path[cur.first][cur.second] == 0) {
q.push(cur);
path[cur.first][cur.second] = path[top.first][top.second] + 1;
}
}
}
}
void initInfluenceTable(State *state) {
ofstream myfile;
myfile.open("lookup-table.txt");
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
for (int k = 0; k < HEIGHT + 2; k++) {
for (int t = 0; t < WIDTH + 2; t++) {
if (state->map[i][j] == WALL
|| state->map[k][t] == WALL) {
myfile << "0,";
continue;
}
if (i == k && j == t) {
myfile << "0,";
continue;
}
int pathFirst[HEIGHT + 2][WIDTH + 2];
int pathSecond[HEIGHT + 2][WIDTH + 2];
getInfluenceValue(i, j, pathFirst, state);
getInfluenceValue(k, t, pathSecond, state);
int sum = 0;
for (int f = 0; f < HEIGHT + 2; f++) {
for (int g = 0; g < WIDTH + 2; g++) {
if (pathFirst[f][g] < pathSecond[f][g]) {
sum++;
} else if (pathFirst[f][g] > pathSecond[f][g]) {
sum--;
}
}
}
printf("(%d %d) (%d %d) influence = %d\n\n", i, j, k, t, sum);
myfile << sum << ",";
}
}
}
}
myfile.close();
}
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
void getSpace(int x, int y, int (&path)[HEIGHT + 2][WIDTH + 2], State *state, int len) {
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
path[i][j] = 0;
}
}
queue<Point> q;
q.push(Point(x, y));
path[x][y] = 1;
while(!q.empty()) {
Point top = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
Point cur = Point(top.first + dx[i], top.second + dy[i]);
if (state->map[cur.first][cur.second] != WALL
&& path[cur.first][cur.second] == 0) {
q.push(cur);
if (path[top.first][top.second] + 1 > len) {
return;
}
path[cur.first][cur.second] = path[top.first][top.second] + 1;
}
}
}
}
/***************************************************************************/
/***************************************************************************/
/***************************************************************************/
int getDistance(int x, int y, int x1, int y1, int (&path)[HEIGHT + 2][WIDTH + 2], State *state) {
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
path[i][j] = 0;
}
}
queue<Point> q;
q.push(Point(x, y));
path[x][y] = 1;
while(!q.empty()) {
Point top = q.front();
q.pop();
if (top.first == x1 && top.second == y1) {
return path[top.first][top.second];
}
for (int i = 0; i < 4; i++) {
Point cur = Point(top.first + dx[i], top.second + dy[i]);
if (state->map[cur.first][cur.second] != WALL
&& path[cur.first][cur.second] == 0) {
q.push(cur);
path[cur.first][cur.second] = path[top.first][top.second] + 1;
}
}
}
ASSERT(false);
return 0;
}
void initDistanceTable(State *state) {
ofstream myfile;
myfile.open("dist-table.txt");
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
for (int k = 0; k < HEIGHT + 2; k++) {
for (int t = 0; t < WIDTH + 2; t++) {
if (state->map[i][j] == WALL
|| state->map[k][t] == WALL) {
myfile << "0,";
continue;
}
if (i == k && j == t) {
myfile << "0,";
continue;
}
int path[HEIGHT + 2][WIDTH + 2];
int dist = getDistance(i, j, k, t, path, state);
myfile << dist << ",";
}
}
}
}
myfile.close();
}
void process_next_command(State* state) {
string command;
cin >> command;
if (command == "settings") {
string type;
cin >> type;
if (type == "timebank") {
cin >> timebank;
} else if (type == "time_per_move") {
cin >> time_per_move;
} else if (type == "player_names") {
string names;
cin >> names;
// player names aren't very useful
} else if (type == "your_bot") {
cin >> state->myName;
} else if (type == "your_botid") {
cin >> state->myId;
} else if (type == "field_width") {
cin >> width;
} else if (type == "field_height") {
cin >> height;
} else if (type == "max_rounds") {
cin >> max_rounds;
}
} else if (command == "update") {
string player_name, type;
cin >> player_name >> type;
if (type == "round") {
cin >> state->round;
} else if (type == "field") {
string s;
cin >> s;
state->snippetsList->nSnippets = 0;
state->weaponsList->nSnippets = 0;
prevBugsList->nBugs = state->bugsList->nBugs;
for (int i = 0; i < prevBugsList->nBugs; i++) {
prevBugsList->bugs[i].x = state->bugsList->bugs[i].x;
prevBugsList->bugs[i].y = state->bugsList->bugs[i].y;
prevBugsList->bugs[i].prevX = state->bugsList->bugs[i].prevX;
prevBugsList->bugs[i].prevY = state->bugsList->bugs[i].prevY;
}
state->bugsList->nBugs = 0;
int n = s.length();
int i = 0;
for (int x = 1; x < HEIGHT + 1; x++) {
for (int y = 1; y < WIDTH + 1; y++) {
while (true) {
if (i == n || s[i] == ',') {
i++;
break;
}
char c = s[i++];
if (c == 'x') {
state->map[x][y] = WALL;
} else if (c == '.') {
state->map[x][y] = FREE_CELL;
} else if (c == 'E') {
if ((x == 8 && (y == 9 || y == 10 || y == 11 || y == 12))
|| (x == 7 && y == 10) || (x == 7 && y == 11)) {
state->map[x][y] = WALL;
} else {
state->map[x][y] = FREE_CELL;
}
int n = state->bugsList->nBugs;
state->bugsList->bugs[n].x = x;
state->bugsList->bugs[n].y = y;
state->bugsList->bugs[n].prevX = 0;
state->bugsList->bugs[n].prevY = 0;
state->bugsList->nBugs++;
} else if (c == 'W') {
state->map[x][y] = WEAPON;
int n = state->weaponsList->nSnippets++;
Snippet weapon;
weapon.x = x;
weapon.y = y;
weapon.visited = FALSE;
weapon.appearRound = state->round;
state->weaponsList->snippets[n] = weapon;
} else if (c == 'C') {
state->map[x][y] = SNIPPET;
int n = state->snippetsList->nSnippets++;
Snippet s;
s.x = x;
s.y = y;
s.visited = FALSE;
s.appearRound = state->round;
state->snippetsList->snippets[n] = s;
} else {
// played id
int id = c - '0';
if (id == PLAYER0) {
state->first->prevX = state->first->x;
state->first->prevY = state->first->y;
state->first->x = x;
state->first->y = y;
state->map[x][y] = FREE_CELL;
} else {
state->second->prevX = state->second->x;
state->second->prevY = state->second->y;
state->second->x = x;
state->second->y = y;
state->map[x][y] = FREE_CELL;
}
}
}
}
}
} else if (type == "snippets") {
double snippets;
cin >> snippets;
if (player_name == state->myName) {
if (state->myId == PLAYER0) {
state->first->snippets = snippets;
} else {
state->second->snippets = snippets;
}
} else {
if (state->myId == PLAYER0) {
state->second->snippets = snippets;
} else {
state->first->snippets = snippets;
}
}
} else if (type == "has_weapon") {
string value;
cin >> value;
if (player_name == state->myName) {
if (state->myId == PLAYER0) {
state->first->has_weapon = (value == "true");
} else {
state->second->has_weapon = (value == "true");
}
} else {
if (state->myId == PLAYER0) {
state->second->has_weapon = (value == "true");
} else {
state->first->has_weapon = (value == "true");
}
}
} else if (type == "is_paralyzed") {
string value;
cin >> value;
if (player_name == state->myName) {
if (state->myId == PLAYER0) {
state->first->is_paralyzed = (value == "true");
} else {
state->second->is_paralyzed = (value == "true");
}
} else {
if (state->myId == PLAYER0) {
state->second->is_paralyzed = (value == "true");
} else {
state->first->is_paralyzed = (value == "true");
}
}
}
} else if (command == "action") {
int iterations = 0;
// Fancy way to predict last bugs positions
while (!calculateBugsPrevPosition(state, prevBugsList, state->bugsList)) {
fprintf(stderr, "calculateBugsPrevPosition\n");
iterations++;
if(iterations > 5) {
fprintf(stderr, "ERROR\n");
break;
}
}
int playersSum = (int)(state->first->snippets + state->second->snippets);
if (state->snippetsEaten < playersSum) {
state->snippetsEaten = playersSum;
} else if (state->snippetsEaten > playersSum) {
if (state->snippetsEaten == playersSum + 3) {
state->snippetsEaten++;
} else if (state->snippetsEaten == playersSum + 7) {
state->snippetsEaten++;
} else if (state->snippetsEaten == playersSum + 6) {
state->snippetsEaten += 2;
}
}
string useless_move;
cin >> useless_move;
cin >> time_remaining;
SearchInfo info[1];
info->depth = MAX_SEARCH_DEPTH - 5;
info->timeset = true;
info->starttime = getTimeMs();
info->stoptime = info->starttime + 130;
info->debug = true;
state->first->centerBonus = 0;
state->second->centerBonus = 0;
if (info->debug) {
state->printMap();
cerr << "state eval = " << state->evaluate() << endl;
}
Move move = searchPosition(state, info, state->myId);
cout << output[move.direction] << endl;
}
}
/**************************************************************************/
/**************************************************************************/
/**************************************************************************/
int main() {
fast_srand((int)time(0));
State *state = new State();
//initHashKeys();
//initHashTable(state->hashTable, 128);
std::cerr << "init done" << std::endl;
//runTests();
while (true) {
process_next_command(state);
}
return 0;
}
<file_sep>#include "defs.h"
#include "fastrand.h"
#include "hash.h"
#include <iostream>
U64 pathHash[HEIGHT + 2][WIDTH + 2][2][MAX_ROUNDS];
U64 playerHash[HEIGHT + 2][WIDTH + 2][2];
U64 roundHash[MAX_ROUNDS];
U64 snippetHash[HEIGHT + 2][WIDTH + 2];
U64 weaponsHash[HEIGHT + 2][WIDTH + 2];
U64 bugsHash[HEIGHT + 2][WIDTH + 2];
void initHashKeys() {
fast_srand(42);
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
for (int k = 0; k < MAX_ROUNDS; k++) {
pathHash[i][j][0][k] = RAND_64;
pathHash[i][j][1][k] = RAND_64;
}
playerHash[i][j][0] = RAND_64;
playerHash[i][j][1] = RAND_64;
snippetHash[i][j] = RAND_64;
weaponsHash[i][j] = RAND_64;
bugsHash[i][j] = RAND_64;
}
}
for (int i = 0; i < MAX_ROUNDS; i++) {
roundHash[i] = RAND_64;
}
}
<file_sep>#ifndef STATE_H_INCLUDED
#define STATE_H_INCLUDED
#include "defs.h"
#include "fastrand.h"
#include "hash.h"
#include <string>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
class State {
public:
int map[HEIGHT + 2][WIDTH + 2];
Undo history[MAX_GAME_MOVES];
SnippetsList snippetsList[1];
SnippetsList weaponsList[1];
//HashTable hashTable[1];
//MoveTuple pvArray[MAX_SEARCH_DEPTH];
BugsList bugsList[1];
Player* first;
Player* second;
int round;
int snippetsEaten;
int collectedSnippets;
int hisPly;
int ply;
//U64 hashKey;
bool enemySpawned;
bool weaponSpawned;
string myName;
int myId;
State();
void printMap();
void getLegalMoves(MovesList* list, Player *player) const;
void getLegalMoves2(MovesList* list, Player *player) const;
void makeMove(Move &move, Player *player);
void takeMove(Player *player);
U64 positionKey() const;
double evaluate();
double evaluate2();
int distToNearestUnit(Player *player, int unitId) const;
int sumDistanceToSnippsAndWeapons();
int numbSnippetsCloserToPlayer();
int minDistToSnippets(int x, int y);
double nextDestinationValue(Player *p1, Player *p2);
// Engine
void makeEngineMove(Move &move, Player *player);
double getPChase();
int updateWinner();
inline void performBugMoves() {
ASSERT(this->bugsList->nBugs >= 0);
this->history[this->ply].bugs->nBugs = this->bugsList->nBugs;
for (int i = 0; i < this->bugsList->nBugs; i++) {
this->history[this->ply].bugs->bugs[i].prevX = this->bugsList->bugs[i].prevX;
this->history[this->ply].bugs->bugs[i].prevY = this->bugsList->bugs[i].prevY;
this->history[this->ply].bugs->bugs[i].x = this->bugsList->bugs[i].x;
this->history[this->ply].bugs->bugs[i].y = this->bugsList->bugs[i].y;
int prevX = this->bugsList->bugs[i].prevX;
int prevY = this->bugsList->bugs[i].prevY;
this->bugsList->bugs[i].prevX = this->bugsList->bugs[i].x;
this->bugsList->bugs[i].prevY = this->bugsList->bugs[i].y;
int x1[5];
int y1[5];
int n = 0;
int x = this->bugsList->bugs[i].x;
int y = this->bugsList->bugs[i].y;
// Check if there is mandatory move
for (int j = 0; j < 4; j++) {
if (this->map[x + dx[j]][y + dy[j]] != WALL
&& (x + dx[j] != prevX || y + dy[j] != prevY)) {
x1[n ] = dx[j];
y1[n++] = dy[j];
}
}
// Bug spawn
if (0 == n) {
ASSERT(8 == this->bugsList->bugs[i].x);
if (9 == this->bugsList->bugs[i].y) {
this->bugsList->bugs[i].y += 1;
} else if (12 == this->bugsList->bugs[i].y) {
this->bugsList->bugs[i].y -= 1;
} else {
this->bugsList->bugs[i].x -= 1;
}
// Mandotory direction found
} else if (1 == n) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
} else {
ASSERT(2 == n);
// Do chase
int firstDist = distances[first->x][first->y][x][y];
int secondDist = distances[second->x][second->y][x][y];
if ((x == first->x) && (y == first->y)) {
if ((x + x1[0] == first->prevX) && (y + y1[0] == first->prevY)) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].prevX][this->bugsList->bugs[i].prevY];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].x][this->bugsList->bugs[i].y];
continue;
} else if ((x + x1[1] == first->prevX) && (y + y1[1] == first->prevY)) {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].prevX][this->bugsList->bugs[i].prevY];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].x][this->bugsList->bugs[i].y];
continue;
}
}
if ((x == second->x) && (y == second->y)) {
if ((x + x1[0] == second->prevX) && (y + y1[0] == second->prevY)) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].prevX][this->bugsList->bugs[i].prevY];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].x][this->bugsList->bugs[i].y];
continue;
} else if ((x + x1[1] == second->prevX) && (y + y1[1] == second->prevY)) {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].prevX][this->bugsList->bugs[i].prevY];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].x][this->bugsList->bugs[i].y];
continue;
}
}
// Chase for nearest player
if (firstDist < secondDist) {
if (distances[first->x][first->y][x + x1[0]][y + y1[0]]
< distances[first->x][first->y][x + x1[1]][y + y1[1]]) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
} else {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
}
} else if (firstDist > secondDist){
if (distances[second->x][second->y][x + x1[0]][y + y1[0]]
< distances[second->x][second->y][x + x1[1]][y + y1[1]]) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
} else {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
}
// Chase for random player
} else {
if ((distances[first->x][first->y][x + x1[0]][y + y1[0]]
< distances[first->x][first->y][x + x1[1]][y + y1[1]])
|| (distances[second->x][second->y][x + x1[0]][y + y1[0]]
< distances[second->x][second->y][x + x1[1]][y + y1[1]])) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
} else {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
}
}
}
// Incrementally updating the hash
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].prevX]
// [this->bugsList->bugs[i].prevY];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].x]
// [this->bugsList->bugs[i].y];
ASSERT(this->bugsList->bugs[i].prevX > 0);
ASSERT(this->bugsList->bugs[i].prevY > 0);
ASSERT(this->bugsList->bugs[i].prevX != this->bugsList->bugs[i].x
|| this->bugsList->bugs[i].prevY != this->bugsList->bugs[i].y);
}
}
inline void performEngineBugMoves() {
ASSERT(this->bugsList->nBugs >= 0);
for (int i = 0; i < this->bugsList->nBugs; i++) {
int prevX = this->bugsList->bugs[i].prevX;
int prevY = this->bugsList->bugs[i].prevY;
this->bugsList->bugs[i].prevX = this->bugsList->bugs[i].x;
this->bugsList->bugs[i].prevY = this->bugsList->bugs[i].y;
int x1[5];
int y1[5];
int n = 0;
int x = this->bugsList->bugs[i].x;
int y = this->bugsList->bugs[i].y;
// Check if there is mandatory move
for (int j = 0; j < 4; j++) {
if (this->map[x + dx[j]][y + dy[j]] != WALL && (x + dx[j] != prevX
|| y + dy[j] != prevY)) {
x1[n ] = dx[j];
y1[n++] = dy[j];
}
}
// Bug spawn
if (0 == n) {
if (8 == this->bugsList->bugs[i].x) {
if (9 == this->bugsList->bugs[i].y) {
this->bugsList->bugs[i].y += 1;
} else if (12 == this->bugsList->bugs[i].y) {
this->bugsList->bugs[i].y -= 1;
} else {
this->bugsList->bugs[i].x -= 1;
}
}
// Mandotory direction found
} else if (1 == n) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
} else {
ASSERT(2 == n);
if (fastRandDouble() <= getPChase()) {
// Do chase
int firstDist = distances[first->x][first->y][x][y];
int secondDist = distances[second->x][second->y][x][y];
if ((x == first->x) && (y == first->y)) {
if ((x + x1[0] == first->prevX) && (y + y1[0] == first->prevY)) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].prevX][this->bugsList->bugs[i].prevY];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].x][this->bugsList->bugs[i].y];
continue;
} else if ((x + x1[1] == first->prevX) && (y + y1[1] == first->prevY)) {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].prevX][this->bugsList->bugs[i].prevY];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].x][this->bugsList->bugs[i].y];
continue;
}
}
if ((x == second->x) && (y == second->y)) {
if ((x + x1[0] == second->prevX) && (y + y1[0] == second->prevY)) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].prevX][this->bugsList->bugs[i].prevY];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].x][this->bugsList->bugs[i].y];
continue;
} else if ((x + x1[1] == second->prevX) && (y + y1[1] == second->prevY)) {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].prevX][this->bugsList->bugs[i].prevY];
//this->hashKey ^= bugsHash[this->bugsList->bugs[i].x][this->bugsList->bugs[i].y];
continue;
}
}
// Chase for nearest player
if (firstDist < secondDist) {
if (distances[first->x][first->y][x + x1[0]][y + y1[0]]
< distances[first->x][first->y][x + x1[1]][y + y1[1]]) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
} else {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
}
} else if (firstDist > secondDist){
if (distances[second->x][second->y][x + x1[0]][y + y1[0]]
< distances[second->x][second->y][x + x1[1]][y + y1[1]]) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
} else {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
}
// Chase for random player
} else {
if ((distances[first->x][first->y][x + x1[0]][y + y1[0]]
< distances[first->x][first->y][x + x1[1]][y + y1[1]])
|| (distances[second->x][second->y][x + x1[0]][y + y1[0]]
< distances[second->x][second->y][x + x1[1]][y + y1[1]])) {
this->bugsList->bugs[i].x += x1[0];
this->bugsList->bugs[i].y += y1[0];
} else {
this->bugsList->bugs[i].x += x1[1];
this->bugsList->bugs[i].y += y1[1];
}
}
// Do not chase
} else {
int r = fastrand() % n;
this->bugsList->bugs[i].x += x1[r];
this->bugsList->bugs[i].y += y1[r];
}
}
ASSERT(this->bugsList->bugs[i].prevX > 0);
ASSERT(this->bugsList->bugs[i].prevY > 0);
ASSERT(this->bugsList->bugs[i].prevX != this->bugsList->bugs[i].x
|| this->bugsList->bugs[i].prevY != this->bugsList->bugs[i].y);
}
}
inline void restoreBugs() {
ASSERT(this->bugsList->nBugs >= 0);
ASSERT(this->history[this->ply].bugs->nBugs >= 0);
this->bugsList->nBugs = this->history[this->ply].bugs->nBugs;
for (int i = 0; i < this->bugsList->nBugs; i++) {
this->bugsList->bugs[i].prevX = this->history[this->ply].bugs->bugs[i].prevX;
this->bugsList->bugs[i].prevY = this->history[this->ply].bugs->bugs[i].prevY;
this->bugsList->bugs[i].x = this->history[this->ply].bugs->bugs[i].x;
this->bugsList->bugs[i].y = this->history[this->ply].bugs->bugs[i].y;
}
}
inline void pickUpSnippets() {
ASSERT(ply <= MAX_SEARCH_DEPTH);
history[ply].snippetsList->nSnippets = 0;
if (first->x == second->x && first->y == second->y
&& map[first->x][first->y] == SNIPPET) {
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets ].x = first->x;
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets++].y = first->y;
first->snippets += 0.5 + ((MAX_ROUNDS - round) * 0.001);
second->snippets += 0.5 + ((MAX_ROUNDS - round) * 0.001);
map[first->x][first->y] = FREE_CELL;
//hashKey ^= snippetHash[first->x][first->y];
eraseFromSnippetsList(first->x, first->y);
} else {
if (map[first->x][first->y] == SNIPPET) {
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets].x = first->x;
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets++].y = first->y;
first->snippets += 1 + ((MAX_ROUNDS - round) * 0.001);
map[first->x][first->y] = FREE_CELL;
//hashKey ^= snippetHash[first->x][first->y];
eraseFromSnippetsList(first->x, first->y);
}
if (map[second->x][second->y] == SNIPPET) {
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets ].x = second->x;
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets++].y = second->y;
second->snippets += 1 + ((MAX_ROUNDS - round) * 0.001);
map[second->x][second->y] = FREE_CELL;
//hashKey ^= snippetHash[second->x][second->y];
eraseFromSnippetsList(second->x, second->y);
}
}
}
inline void pickUpSnippets2() {
ASSERT(ply <= MAX_SEARCH_DEPTH);
history[ply].snippetsList->nSnippets = 0;
if (first->x == second->x && first->y == second->y
&& map[first->x][first->y] == SNIPPET) {
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets ].x = first->x;
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets++].y = first->y;
first->snippets += 0.5;
second->snippets += 0.5;
map[first->x][first->y] = FREE_CELL;
//hashKey ^= snippetHash[first->x][first->y];
eraseFromSnippetsList(first->x, first->y);
} else {
if (map[first->x][first->y] == SNIPPET) {
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets].x = first->x;
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets++].y = first->y;
first->snippets += 1 + ((MAX_SEARCH_DEPTH - ply) * 0.2 / MAX_SEARCH_DEPTH);
map[first->x][first->y] = FREE_CELL;
//hashKey ^= snippetHash[first->x][first->y];
eraseFromSnippetsList(first->x, first->y);
}
if (map[second->x][second->y] == SNIPPET) {
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets ].x = second->x;
history[ply].snippetsList->snippets[history[ply].snippetsList->nSnippets++].y = second->y;
second->snippets += 1 + ((MAX_SEARCH_DEPTH - ply) * 0.2 / MAX_SEARCH_DEPTH);
map[second->x][second->y] = FREE_CELL;
//hashKey ^= snippetHash[second->x][second->y];
eraseFromSnippetsList(second->x, second->y);
}
}
}
inline void eraseFromSnippetsList(int x, int y) {
for (int i = 0; i < snippetsList->nSnippets; i++) {
if (snippetsList->snippets[i].x == x
&& snippetsList->snippets[i].y == y) {
snippetsList->snippets[i] = snippetsList->snippets[--snippetsList->nSnippets];
return;
}
}
ASSERT(false);
}
inline void eraseFromWeaponsList(int x, int y) {
for (int i = 0; i < weaponsList->nSnippets; i++) {
if (weaponsList->snippets[i].x == x
&& weaponsList->snippets[i].y == y) {
weaponsList->snippets[i] = weaponsList->snippets[--weaponsList->nSnippets];
return;
}
}
ASSERT(false);
}
inline void enginePickUpSnippets() {
ASSERT(ply <= MAX_SEARCH_DEPTH);
if (first->x == second->x && first->y == second->y
&& map[first->x][first->y] == SNIPPET) {
first->snippets += 0.5;
second->snippets += 0.5;
snippetsEaten++;
map[first->x][first->y] = FREE_CELL;
eraseFromSnippetsList(first->x, first->y);
} else {
if (map[first->x][first->y] == SNIPPET) {
first->snippets += 1;
snippetsEaten++;
map[first->x][first->y] = FREE_CELL;
eraseFromSnippetsList(first->x, first->y);
}
if (map[second->x][second->y] == SNIPPET) {
second->snippets += 1;
snippetsEaten++;
map[second->x][second->y] = FREE_CELL;
eraseFromSnippetsList(second->x, second->y);
}
}
}
inline void storePlayersState() {
history[ply].snippetsFirst = first->snippets;
history[ply].snippetsSecond = second->snippets;
history[ply].weaponFirst = first->has_weapon;
history[ply].weaponSecond = second->has_weapon;
history[ply].paralizeFirst = first->is_paralyzed;
history[ply].paralizeSecond = second->is_paralyzed;
history[ply].killedBugsFirst = first->killedBugs;
history[ply].killedBugsSecond = second->killedBugs;
if (first->is_paralyzed) {
first->is_paralyzed = false;
}
if (second->is_paralyzed) {
second->is_paralyzed = false;
}
}
inline void restorePlayersState() {
first->snippets = history[ply].snippetsFirst;
second->snippets = history[ply].snippetsSecond;
first->has_weapon = history[ply].weaponFirst;
second->has_weapon = history[ply].weaponSecond;
first->is_paralyzed = history[ply].paralizeFirst;
second->is_paralyzed = history[ply].paralizeSecond;
first->killedBugs = history[ply].killedBugsFirst;
second->killedBugs = history[ply].killedBugsSecond;
}
inline void restoreSnippets() {
ASSERT(history[ply].snippetsList->nSnippets >= 0);
for (int i = 0; i < history[ply].snippetsList->nSnippets; i++) {
ASSERT(history[ply].snippetsList->snippets[i].x > 0 && history[ply].snippetsList->snippets[i].x < HEIGHT + 1);
ASSERT(history[ply].snippetsList->snippets[i].y > 0 && history[ply].snippetsList->snippets[i].y < WIDTH + 1);
map[history[ply].snippetsList->snippets[i].x]
[history[ply].snippetsList->snippets[i].y] = SNIPPET;
history[ply].snippetsList->snippets[i].visited = false;
snippetsList->snippets[snippetsList->nSnippets++] =
history[ply].snippetsList->snippets[i];
}
}
inline void restoreWeapons() {
ASSERT(history[ply].weaponsList->nSnippets >= 0);
for (int i = 0; i < history[ply].weaponsList->nSnippets; i++) {
ASSERT(history[ply].weaponsList->snippets[i].x > 0 && history[ply].weaponsList->snippets[i].x < HEIGHT + 1);
ASSERT(history[ply].weaponsList->snippets[i].y > 0 && history[ply].weaponsList->snippets[i].y < WIDTH + 1);
map[history[ply].weaponsList->snippets[i].x]
[history[ply].weaponsList->snippets[i].y] = WEAPON;
history[ply].weaponsList->snippets[i].visited = false;
weaponsList->snippets[weaponsList->nSnippets++] =
history[ply].weaponsList->snippets[i];
}
}
inline void pickUpWeapons() {
history[ply].weaponsList->nSnippets = 0;
if (first->x == second->x && first->y == second->y
&& map[first->x][first->y] == WEAPON) {
// nothing to do
history[ply].weaponsList->snippets[history[ply].weaponsList->nSnippets ].x = first->x;
history[ply].weaponsList->snippets[history[ply].weaponsList->nSnippets++].y = first->y;
map[first->x][first->y] = FREE_CELL;
//hashKey ^= weaponsHash[first->x][first->y];
eraseFromWeaponsList(first->x, first->y);
} else {
if (map[first->x][first->y] == WEAPON) {
first->has_weapon = true;
map[first->x][first->y] = FREE_CELL;
history[ply].weaponsList->snippets[history[ply].weaponsList->nSnippets ].x = first->x;
history[ply].weaponsList->snippets[history[ply].weaponsList->nSnippets++].y = first->y;
//hashKey ^= weaponsHash[first->x][first->y];
eraseFromWeaponsList(first->x, first->y);
}
if (map[second->x][second->y] == WEAPON) {
second->has_weapon = true;
map[second->x][second->y] = FREE_CELL;
history[ply].weaponsList->snippets[history[ply].weaponsList->nSnippets ].x = second->x;
history[ply].weaponsList->snippets[history[ply].weaponsList->nSnippets++].y = second->y;
// hashKey ^= weaponsHash[second->x][second->y];
eraseFromWeaponsList(second->x, second->y);
}
}
}
inline void enginePickUpWeapons() {
if (first->x == second->x && first->y == second->y
&& map[first->x][first->y] == WEAPON) {
if ((rand() % 2) == 0) {
first->has_weapon = true;
} else {
second->has_weapon = true;
}
map[first->x][first->y] = FREE_CELL;
eraseFromWeaponsList(first->x, first->y);
} else {
if (map[first->x][first->y] == WEAPON) {
first->has_weapon = true;
map[first->x][first->y] = FREE_CELL;
eraseFromWeaponsList(first->x, first->y);
}
if (map[second->x][second->y] == WEAPON) {
second->has_weapon = true;
map[second->x][second->y] = FREE_CELL;
eraseFromWeaponsList(second->x, second->y);
}
}
}
inline void collideWithEnemies() {
int killed[10];
int nKilled = 0;
for (int i = 0; i < this->bugsList->nBugs; i++) {
int bugX = this->bugsList->bugs[i].x;
int bugY = this->bugsList->bugs[i].y;
int prevBugX = this->bugsList->bugs[i].prevX;
int prevBugY = this->bugsList->bugs[i].prevY;
if (prevBugX == first->x && prevBugY == first->y
&& bugX == first->prevX && bugY == first->prevY) {
hitByBug(first, i);
int add = TRUE;
for (int j = nKilled - 1; j >= 0; j--) {
if (i == killed[j]) {
add = FALSE;
break;
}
}
if (add == TRUE) {
killed[nKilled++] = i;
}
}
if (prevBugX == second->x && prevBugY == second->y
&& bugX == second->prevX && bugY == second->prevY) {
hitByBug(second, i);
int add = TRUE;
for (int j = nKilled - 1; j >= 0; j--) {
if (i == killed[j]) {
add = FALSE;
break;
}
}
if (add == TRUE) {
killed[nKilled++] = i;
}
}
}
killBugs(killed, nKilled);
// Collide by same position
nKilled = 0;
for (int i = 0; i < this->bugsList->nBugs; i++) {
int bugX = this->bugsList->bugs[i].x;
int bugY = this->bugsList->bugs[i].y;
if (bugX == first->x && bugY == first->y) {
hitByBug(first, i);
}
if (bugX == second->x && bugY == second->y) {
hitByBug(second, i);
}
}
killBugs(killed, nKilled);
}
inline void killBugs(int killed[10], int nKilled) {
for (int i = nKilled - 1; i >= 0; i--) {
for (int j = nKilled - 1; j >= 0; j--) {
if (killed[i] > killed[j]) {
int tmp = killed[i];
killed[i] = killed[j];
killed[j] = tmp;
}
}
}
ASSERT(nKilled <= this->bugsList->nBugs);
for (int i = nKilled - 1; i >= 0; i--) {
this->bugsList->bugs[killed[i]] = this->bugsList->bugs[--this->bugsList->nBugs];
}
}
inline void hitByBug(Player *player, int bugIndex) {
if (player->has_weapon) { // player kills enemy
player->killedBugs++;
player->has_weapon = false;
} else { // player loses snippets
player->snippets -= HIT_SNIPPETS_LOSS;
}
}
inline void spawnEnemy() {
int spawnX = 8;
int spawnY[] = {9, 10, 11, 12};
int r = fastrand() % 4;
int n = bugsList->nBugs++;
bugsList->bugs[n].x = spawnX;
bugsList->bugs[n].y = spawnY[r];
bugsList->bugs[n].prevX = 0;
bugsList->bugs[n].prevY = 0;
}
inline void spawnEnemySearch(int *y) {
int spawnX = 8;
int spawnY[] = {9, 10, 11, 12};
int r = fastrand() % 4;
int n = bugsList->nBugs++;
bugsList->bugs[n].x = spawnX;
bugsList->bugs[n].y = spawnY[r];
bugsList->bugs[n].prevX = 0;
bugsList->bugs[n].prevY = 0;
*y = spawnY[r];
}
inline void removeEnemySearch(int y) {
int x = 8;
for (int i = 0; i < bugsList->nBugs; i++) {
if (bugsList->bugs[i].x == x
&& bugsList->bugs[i].y == y) {
bugsList->bugs[i] = bugsList->bugs[--bugsList->nBugs];
return;
}
}
ASSERT(false);
}
inline void spawnSnippet() {
int x[300];
int y[300];
int n = 0;
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
if (map[i][j] == FREE_CELL) {
x[n ] = i;
y[n++] = j;
}
}
}
ASSERT(n <= 300);
int r = fastrand() % n;
map[x[r]][y[r]] = SNIPPET;
int k = snippetsList->nSnippets++;
Snippet snippet;
snippet.x = x[r];
snippet.y = y[r];
snippet.visited = false;
snippet.appearRound = round;
snippetsList->snippets[k] = snippet;
}
inline void spawnSnippetSearch(int *spawnX, int *spawnY) {
int x;
int y;
int n = 0;
int maxDist = 0;
int minDiff = INF;
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
if (map[i][j] == FREE_CELL) {
if (distances[i][j][first->x][first->y]
+ distances[i][j][second->x][second->y] > maxDist) {
x = i;
y = j;
maxDist = distances[i][j][first->x][first->y]
+ distances[i][j][second->x][second->y];
minDiff = abs(distances[i][j][first->x][first->y]
- distances[i][j][second->x][second->y]);
} else if (distances[i][j][first->x][first->y]
+ distances[i][j][second->x][second->y] == maxDist
&& abs(distances[i][j][first->x][first->y]
- distances[i][j][second->x][second->y])
< minDiff) {
x = i;
y = j;
maxDist = distances[i][j][first->x][first->y]
+ distances[i][j][second->x][second->y];
minDiff = abs(distances[i][j][first->x][first->y]
- distances[i][j][second->x][second->y]);
}
}
}
}
map[x][y] = SNIPPET;
int k = snippetsList->nSnippets++;
Snippet snippet;
snippet.x = x;
snippet.y = y;
snippet.visited = false;
snippet.appearRound = round;
snippetsList->snippets[k] = snippet;
*spawnX = x;
*spawnY = y;
}
inline void eraseSearchSnippet(int x, int y) {
map[x][y] = FREE_CELL;
for (int i = 0; i < snippetsList->nSnippets; i++) {
if (snippetsList->snippets[i].x == x
&& snippetsList->snippets[i].y == y) {
snippetsList->snippets[i] = snippetsList->snippets[--snippetsList->nSnippets];
return;
}
}
for (int i = 0; i < history[ply].snippetsList->nSnippets; i++) {
if (history[ply].snippetsList->snippets[i].x == x
&& history[ply].snippetsList->snippets[i].y == y) {
history[ply].snippetsList->snippets[i] =
history[ply].snippetsList->snippets[--history[ply].snippetsList->nSnippets];
return;
}
}
ASSERT(false);
}
inline void spawnWeapon() {
int x[300];
int y[300];
int n = 0;
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
if (map[i][j] == FREE_CELL) {
x[n ] = i;
y[n++] = j;
}
}
}
ASSERT(n <= 300);
int r = fastrand() % n;
map[x[r]][y[r]] = WEAPON;
int k = weaponsList->nSnippets++;
Snippet weapon;
weapon.x = x[r];
weapon.y = y[r];
weapon.visited = false;
weapon.appearRound = round;
weaponsList->snippets[k] = weapon;
}
inline void collideWithPlayers() {
// Collide by swap ans same pos
if ((first->x == second->x && first->y == second->y)
|| (first->x == second->prevX && first->y == second->prevY
&& second->x == first->prevX && second->y == first->prevY)) {
if (first->has_weapon && second->has_weapon) {
first->has_weapon = false;
second->has_weapon = false;
first->snippets -= HIT_SNIPPETS_LOSS;
second->snippets -= HIT_SNIPPETS_LOSS;
first->is_paralyzed = true;
second->is_paralyzed = true;
}
if (first->has_weapon) {
first->has_weapon = false;
first->killedBugs++;
second->snippets -= HIT_SNIPPETS_LOSS;
second->is_paralyzed = true;
}
if (second->has_weapon) {
second->has_weapon = false;
second->killedBugs++;
first->snippets -= HIT_SNIPPETS_LOSS;
first->is_paralyzed = true;
}
}
}
};
#endif // #ifndef STATE_H_INCLUDED
<file_sep>package info.stochastic;
import java.util.*;
class Player {
private static final int INF = Integer.MAX_VALUE / 3;
private static final int MAX_SAMPLES = 3;
private static final int MAX_MOLECULES = 10;
private static class Molecule {
String type;
int count;
public Molecule(String type, int count) {
this.type = type;
this.count = count;
}
@Override
public String toString() {
return "(" + type + "," + count + ")";
}
};
/**************************************************************/
/**************************************************************/
/********************** Storage class *************************/
private static class Storage {
private Molecule a = new Molecule("A", 0);
private Molecule b = new Molecule("B", 0);
private Molecule c = new Molecule("C", 0);
private Molecule d = new Molecule("D", 0);
private Molecule e = new Molecule("E", 0);
public Storage() {}
public Storage(int a, int b, int c, int d, int e) {
update(a, b, c, d, e);
}
public void update(int a, int b, int c, int d, int e) {
this.a.count = a;
this.b.count = b;
this.c.count = c;
this.d.count = d;
this.e.count = e;
}
public int getA() {return a.count;}
public int getB() {return b.count;}
public int getC() {return c.count;}
public int getD() {return d.count;}
public int getE() {return e.count;}
public Storage copy() {
return new Storage(a.count, b.count, c.count,
d.count, e.count);
}
public int moleculesCount() {
return a.count + b.count + c.count + d.count + e.count;
}
public Storage add(Storage storage) {
return new Storage(
a.count + storage.a.count,
b.count + storage.b.count,
c.count + storage.c.count,
d.count + storage.d.count,
e.count + storage.e.count
);
}
public Storage subtract(Storage storage) {
return new Storage(
a.count - storage.a.count,
b.count - storage.b.count,
c.count - storage.c.count,
d.count - storage.d.count,
e.count - storage.e.count
);
}
public Storage subtractOrZero(Storage storage) {
return new Storage(
Math.max(0, a.count - storage.a.count),
Math.max(0, b.count - storage.b.count),
Math.max(0, c.count - storage.c.count),
Math.max(0, d.count - storage.d.count),
Math.max(0, e.count - storage.e.count)
);
}
public void moleculeAdd(String molecule) {
switch(molecule) {
case "A" : a.count++; break;
case "B" : b.count++; break;
case "C" : c.count++; break;
case "D" : d.count++; break;
case "E" : e.count++; break;
default : break;
}
}
public void moleculeDel(String molecule) {
switch(molecule) {
case "A" : a.count--; break;
case "B" : b.count--; break;
case "C" : c.count--; break;
case "D" : d.count--; break;
case "E" : e.count--; break;
default : break;
}
}
@Override
public String toString() {
return "[count = " + moleculesCount() + "; " + a + ","
+ b + "," + c + "," + d + "," + e + "]";
}
public boolean moreOrEqual(Storage storage) {
return (a.count >= storage.a.count)
&& (b.count >= storage.b.count)
&& (c.count >= storage.c.count)
&& (d.count >= storage.d.count)
&& (e.count >= storage.e.count);
}
public String getNext(Storage storage) {
if (a.count < storage.a.count) {
return a.type;
} else if (b.count < storage.b.count) {
return b.type;
} else if (c.count < storage.c.count) {
return c.type;
} else if (d.count < storage.d.count) {
return d.type;
} else {
return e.type;
}
}
public String getMinExpertise() {
String result = "A";
int minCount = a.count;
if (b.count < minCount) {
minCount = b.count;
result = "B";
}
if (c.count < minCount) {
minCount = c.count;
result = "C";
}
if (d.count < minCount) {
minCount = d.count;
result = "D";
}
if (e.count < minCount) {
result = "E";
}
return result;
}
}
/**************************************************************/
/**************************************************************/
/********************** Sample class **************************/
private static class Sample {
public final int id;
public final int carriedBy;
public final int rank;
public final int health;
public final String expertiseGain;
private Storage cost = new Storage();
public Sample(int id, int carriedBy, int rank,
int health, String expertiseGain, Storage cost) {
this.id = id;
this.carriedBy = carriedBy;
this.rank = rank;
this.health = health;
this.expertiseGain = expertiseGain;
this.cost = cost;
}
public Storage getCost() {
return cost;
}
@Override
public String toString() {
return "(id:" + id + ", carriedBy:" + carriedBy + ", rank:"
+ rank + ", expertGain:" + expertiseGain + ", health:"
+ health + ", molecules:" + cost + ")";
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (!(obj instanceof Sample)) {
return false;
}
Sample object = (Sample)obj;
return id == object.id;
}
@Override
public int hashCode() {
return id;
}
}
/**************************************************************/
/**************************************************************/
/********************** Robot class ***************************/
private static class Robot {
private Storage molecules = new Storage();
private Storage expertise = new Storage();
private ArrayList<Sample> samples = new ArrayList<>();
private String target;
private int eta;
private int score;
private int deletedMolecules;
public void update(String target, int eta, int score,
Storage molecules, Storage expertise) {
this.target = target;
this.eta = eta;
this.score = score;
this.molecules = molecules;
this.expertise = expertise;
this.samples.clear();
this.deletedMolecules = 0;
}
public Storage getMolecules() {
return molecules;
}
public Storage getExpertise() {
return expertise;
}
public ArrayList<Sample> getSamples() {
return samples;
}
public String getTarget() {
return target;
}
public int getDeletedMolecules() {
return deletedMolecules;
}
public void addSample(Sample sample) {
samples.add(sample);
}
public boolean haveEnoughMolecules(Sample sample) {
return haveEnoughMolecules(sample, expertise);
}
public boolean haveEnoughMolecules(Sample sample, Storage newExpertise) {
return molecules.add(newExpertise).moreOrEqual(sample.getCost());
}
public String getNextMolecule(Sample sample) {
return molecules.add(expertise).getNext(sample.getCost());
}
public String getNextRandomMolecule(Storage available, Storage oppExpertise) {
String best = oppExpertise.getMinExpertise();
if (available.moreOrEqual(new Storage(1,0,0,0,0)) && "A".equals(best)) return "A";
if (available.moreOrEqual(new Storage(0,1,0,0,0)) && "B".equals(best)) return "B";
if (available.moreOrEqual(new Storage(0,0,1,0,0)) && "C".equals(best)) return "C";
if (available.moreOrEqual(new Storage(0,0,0,1,0)) && "D".equals(best)) return "D";
if (available.moreOrEqual(new Storage(0,0,0,0,1)) && "E".equals(best)) return "E";
if (available.moreOrEqual(new Storage(1,0,0,0,0))) return "A";
if (available.moreOrEqual(new Storage(0,1,0,0,0))) return "B";
if (available.moreOrEqual(new Storage(0,0,1,0,0))) return "C";
if (available.moreOrEqual(new Storage(0,0,0,1,0))) return "D";
if (available.moreOrEqual(new Storage(0,0,0,0,1))) return "E";
return "Err";
}
public String tryToHamperTheOpp(Robot opp, Storage available) {
String result = null;
int minToGet = INF;
for (Sample sample : opp.getSamples()) {
Storage availableCopy = available.copy();
Storage need = sample.getCost().subtractOrZero(opp.getExpertise())
.subtractOrZero(opp.getMolecules());
debug(sample + " need = " + need);
String curResult = null;
int curMin = INF;
if (availableCopy.moreOrEqual(need)) {
if (need.getA() > 0 && availableCopy.getA() - need.getA() < curMin) {
curResult = "A";
curMin = availableCopy.getA() - need.getA();
}
if (need.getB() > 0 && availableCopy.getB() - need.getB() < curMin) {
curResult = "B";
curMin = availableCopy.getB() - need.getB();
}
if (need.getC() > 0 && availableCopy.getC() - need.getC() < curMin) {
curResult = "C";
curMin = availableCopy.getC() - need.getC();
}
if (need.getD() > 0 && availableCopy.getD() - need.getD() < curMin) {
curResult = "D";
curMin = availableCopy.getD() - need.getD();
}
if (need.getE() > 0 && availableCopy.getE() - need.getE() < curMin) {
curResult = "E";
curMin = availableCopy.getE() - need.getE();
}
}
if (curMin < 3 && curMin < minToGet) {
minToGet = curMin;
result = curResult;
}
}
return result;
}
public Sample nextUndiagnosted() {
for (Sample sample : samples) {
if (sample.health == -1) {
return sample;
}
}
return null;
}
public boolean hasUndiagnosted() {
for (Sample sample : samples) {
if (sample.health == -1) {
return true;
}
}
return false;
}
public boolean canProduceAnySample(Storage molecules) {
for (Sample sample : samples) {
if (this.molecules
.add(molecules)
.add(expertise)
.moreOrEqual(sample.getCost())) {
return true;
}
}
return false;
}
public Sample cantProduceSample(Storage molecules) {
for (Sample sample : samples) {
if (!this.molecules
.add(molecules)
.add(expertise)
.moreOrEqual(sample.getCost())) {
return sample;
}
}
return null;
}
// NOTE: Time consuming method
public Sample nextSampleToProduce(Storage available) {
Sample sample = null;
int minValue = INF;
for (Sample curSample : samples) {
Storage newExpertise = expertise.copy();
ArrayList<Sample> newSamples = new ArrayList<>(samples);
newSamples.remove(curSample);
/*debug(
"***************** \n"
+ "expertise = " + expertise + "\n"
+ "curSample = " + curSample + "\n"
+ "available = " + available + "\n"
+ "canProduce = " + canProduceSample(available, curSample, expertise) + "\n"
+ "*****************"
); */
int value = 0;
if (canProduceSample(available, curSample, expertise)) {
newExpertise.moleculeAdd(curSample.expertiseGain);
int curSampleCost = curSample.getCost()
.subtractOrZero(newExpertise).moleculesCount();
value = nextSampleToProduce(newSamples, available, newExpertise, 0) + curSampleCost;
}
if (value > 0 && value < minValue) {
minValue = value;
sample = curSample;
}
}
return sample;
}
private int nextSampleToProduce(ArrayList<Sample> newSamples,
Storage available, Storage newExpertise, int skipped) {
if (newSamples.size() == 0) {
return skipped * 10;
}
int minValue = INF;
for (Sample curSample : newSamples) {
Storage curExpertise = newExpertise.copy();
ArrayList<Sample> nextSamples = new ArrayList<>(newSamples);
nextSamples.remove(curSample);
int value = 0;
if (canProduceSample(available, curSample, newExpertise)) {
curExpertise.moleculeAdd(curSample.expertiseGain);
int curSampleCost = curSample.getCost()
.subtractOrZero(curExpertise).moleculesCount();
value = nextSampleToProduce(nextSamples, available, curExpertise, skipped) + curSampleCost;
}
if (value > 0 && value < minValue) {
minValue = value;
}
}
return minValue == INF ? 0 : minValue;
}
// Returns list of Sample with the samples we can produce using molecules we have
public ArrayList<Sample> getSamplesWeCanProduce(ArrayList<Sample> newSamples,
ArrayList<Sample> toDelete, Storage newExpertise,
Storage myMolecules, int skipped) {
if (skipped + toDelete.size() == samples.size()) {
return toDelete;
}
int maxValue = 0;
ArrayList<Sample> result = null;
for (Sample curSample : newSamples) {
if (curSample.health == -1) {
continue;
}
Storage curExpertise = newExpertise.copy();
Storage newMolecules = myMolecules.copy();
ArrayList<Sample> nextSamples = new ArrayList<>(newSamples);
ArrayList<Sample> nextToDelete = new ArrayList<>(toDelete);
nextSamples.remove(curSample);
/*debug(
"***************** \n"
+ "myMolecules = " + myMolecules + "\n"
+ "curExpertise = " + curExpertise + "\n"
+ "Cost = " + curSample.getCost()
+ "*****************"
); */
if (newMolecules.add(curExpertise).moreOrEqual(curSample.getCost())) {
nextToDelete.add(curSample);
curExpertise.moleculeAdd(curSample.expertiseGain);
newMolecules = newMolecules.subtract(curSample.getCost().subtractOrZero(curExpertise));
nextToDelete = getSamplesWeCanProduce(nextSamples, nextToDelete,
curExpertise, newMolecules, skipped);
} else {
nextToDelete = getSamplesWeCanProduce(nextSamples, nextToDelete,
curExpertise, newMolecules, skipped + 1);
}
if (null != nextToDelete && nextToDelete.size() > maxValue) {
result = nextToDelete;
maxValue = nextToDelete.size();
}
}
return result;
}
public void deleteSamplesWeCanProduce(ArrayList<Sample> toDelete) {
if (null == toDelete) {
return;
}
for (Sample sample : toDelete) {
samples.remove(sample);
deletedMolecules += sample.getCost().subtractOrZero(expertise).moleculesCount();
molecules = molecules.subtract(sample.getCost().subtractOrZero(expertise));
expertise.moleculeAdd(sample.expertiseGain);
}
}
public boolean canProduceSample(Storage available, Sample sample) {
return canProduceSample(available, sample, expertise);
}
public boolean canProduceSample(Storage available, Sample sample, Storage newExpertise) {
return this.molecules
.add(available)
.add(newExpertise)
.moreOrEqual(sample.getCost());
}
@Override
public String toString() {
String samplesToString = "\n";
for (Sample sample : samples) {
samplesToString += "\t\t" + sample + "\n";
}
return "(target:" + target + ", samples:" + samples.size()
+ ", eta:" + eta + ", score:"
+ score + ", molecules:" + molecules
+ ", expertise:" + expertise + ")" + samplesToString;
}
}
/**************************************************************/
/**************************************************************/
/**************************************************************/
private interface IStrategy {
String makeMove();
}
private static class DecisionMaker {
private IStrategy strategy;
public DecisionMaker(IStrategy strategy) {
this.strategy = strategy;
}
public String getNextMove() {
return strategy.makeMove();
}
}
/**************************************************************/
/**************************************************************/
/**************************************************************/
/************** Strategy implementation below *****************/
private static class Strategy implements IStrategy {
Robot me;
Robot opp;
Storage available;
ArrayList<Sample> samples;
Strategy(Robot me, Robot opp,
Storage available, ArrayList<Sample> samples) {
this.me = me;
this.opp = opp;
this.available = available;
this.samples = samples;
}
private String hamper(String canHamper) {
if (null != canHamper && me.getMolecules().moleculesCount()
+ me.getDeletedMolecules() < MAX_MOLECULES) {
return "CONNECT " + canHamper;
}
return "GOTO LABORATORY";
}
@Override
public String makeMove() {
/****************************************/
/**************** START *****************/
/****************************************/
if ("START_POS".equals(me.getTarget())) {
return "GOTO SAMPLES";
}
/****************************************/
/*************** SAMPLES ****************/
/****************************************/
if ("SAMPLES".equals(me.getTarget())) {
if (me.getSamples().size() < MAX_SAMPLES) {
if (me.getExpertise().moleculesCount() < 12) {
return "CONNECT 1";
} else {
return "CONNECT 3";
}
}
return "GOTO DIAGNOSIS";
}
/****************************************/
/************** DIAGNOSIS ***************/
/****************************************/
if ("DIAGNOSIS".equals(me.getTarget())) {
ArrayList<Sample> toDelete = me.getSamplesWeCanProduce(
me.getSamples(),
new ArrayList<>(),
me.getExpertise(), me.getMolecules(), 0);
int canProduce = null == toDelete ? 0 : toDelete.size();
// Can produce without additional molecules
debug("canProduce = " + canProduce);
if (canProduce == 3) {
return "GOTO LABORATORY";
}
if (me.getSamples().size() > 0 && me.hasUndiagnosted()) {
Sample sample = me.nextUndiagnosted();
return "CONNECT " + sample.id;
} else {
if (me.getMolecules().moleculesCount() == MAX_MOLECULES) {
Sample badSample = me.cantProduceSample(available);
if (badSample != null) {
return "CONNECT " + badSample.id;
}
}
if (samples.size() > 0 && me.getSamples().size() < MAX_SAMPLES) {
Sample sample = samples.get(0);
if (me.canProduceSample(available, sample)) {
samples.remove(0);
return "CONNECT " + sample.id;
}
}
// Number of diagnosted samples
if (me.getSamples().size() > 0) {
return "GOTO MOLECULES";
} else {
return "GOTO SAMPLES";
}
}
}
/****************************************/
/************** MOLECULES ***************/
/****************************************/
if ("MOLECULES".equals(me.getTarget())) {
String canHamper = me.tryToHamperTheOpp(opp,available);
ArrayList<Sample> toDelete = me.getSamplesWeCanProduce(
me.getSamples(),
new ArrayList<>(),
me.getExpertise(), me.getMolecules(), 0);
me.deleteSamplesWeCanProduce(toDelete);
int canProduce = null == toDelete ? 0 : toDelete.size();
if (canProduce == 3 || (canProduce > 0 && me.getSamples().size() == 0)) {
return hamper(canHamper);
}
if (me.getSamples().size() > 0 && (me.canProduceAnySample(available) || canProduce > 0)) {
Sample sample = me.nextSampleToProduce(available);
if (null == sample
|| (!me.canProduceSample(available, sample, me.getExpertise()))) {
return hamper(canHamper);
}
if (!me.haveEnoughMolecules(sample)) {
if (me.getMolecules().moleculesCount() + me.getDeletedMolecules() < MAX_MOLECULES) {
return "CONNECT " + me.getNextMolecule(sample);
} else {
return canProduce > 0 ? "GOTO LABORATORY" : "GOTO DIAGNOSIS";
}
}
} else {
return "GOTO DIAGNOSIS";
}
return hamper(canHamper);
}
/****************************************/
/************** LABORATORY **************/
/****************************************/
if ("LABORATORY".equals(me.getTarget())) {
for (Sample sample : me.getSamples()) {
if (me.haveEnoughMolecules(sample)) {
return "CONNECT " + sample.id;
}
}
return me.getSamples().size() > 1 ? "GOTO MOLECULES" : "GOTO SAMPLES";
}
return "ERROR";
}
}
/**************************************************************/
/**************************************************************/
/**************************************************************/
private static void debugInput(Robot me, Robot opp,
Storage available, ArrayList<Sample> samples) {
System.err.println(available);
System.err.println(me);
System.err.println(opp);
for(Sample sample : samples) {
System.err.println(sample);
}
}
private static void debug(String msg) {
System.err.println(msg);
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
Robot player1 = new Robot();
Robot player2 = new Robot();
Storage available = new Storage(INF, INF, INF, INF, INF);
ArrayList<Sample> samples = new ArrayList<>();
Strategy strategy = new Strategy(player1, player2, available, samples);
DecisionMaker decisionMaker = new DecisionMaker(strategy);
int projectCount = in.nextInt();
for (int i = 0; i < projectCount; i++) {
Storage project = new Storage(in.nextInt(), in.nextInt(),
in.nextInt(), in.nextInt(), in.nextInt());
System.err.println(project);
}
// Game loop
while (true) {
player1.update(
in.next(), in.nextInt(), in.nextInt(),
new Storage(in.nextInt(), in.nextInt(),
in.nextInt(), in.nextInt(), in.nextInt()),
new Storage(in.nextInt(), in.nextInt(),
in.nextInt(), in.nextInt(), in.nextInt())
);
player2.update(
in.next(), in.nextInt(), in.nextInt(),
new Storage(in.nextInt(), in.nextInt(),
in.nextInt(), in.nextInt(), in.nextInt()),
new Storage(in.nextInt(), in.nextInt(),
in.nextInt(), in.nextInt(), in.nextInt())
);
available.update(in.nextInt(), in.nextInt(),
in.nextInt(), in.nextInt(), in.nextInt());
samples.clear();
int sampleCount = in.nextInt();
for (int i = 0; i < sampleCount; i++) {
int sampleId = in.nextInt();
int carriedBy = in.nextInt();
int rank = in.nextInt();
String expertiseGain = in.next();
int health = in.nextInt();
int costA = in.nextInt();
int costB = in.nextInt();
int costC = in.nextInt();
int costD = in.nextInt();
int costE = in.nextInt();
Sample sample = new Sample(sampleId, carriedBy, rank,
health, expertiseGain,
new Storage(costA, costB, costC, costD, costE)
);
if (sample.carriedBy == 0) {
player1.addSample(sample);
} else if (sample.carriedBy == 1) {
player2.addSample(sample);
} else {
samples.add(sample);
}
}
System.out.println(decisionMaker.getNextMove());
}
}
}<file_sep>#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
#include <iostream>
#include <string>
#include "defs.h"
#include "fastrand.h"
#include "state.h"
typedef struct {
int id;
int posRound;
Player first;
Player second;
SnippetsList snippetsList[1];
SnippetsList weaponsList[1];
BugsList bugsList[1];
Direction answer;
} TestCase;
inline bool calculateBugsPrevPosition(State *state, BugsList *prevList, BugsList *list) {
int done = 0;
for (int i = 0; i < list->nBugs; i++) {
int count = 0;
int index = 0;
for (int j = 0; j < prevList->nBugs; j++) {
int bugX = list->bugs[i].x;
int bugY = list->bugs[i].y;
int prevBugX = prevList->bugs[j].x;
int prevBugY = prevList->bugs[j].y;
for (int k = 0; k < 4; k++) {
if (bugX == prevBugX + dx[k] && bugY == prevBugY + dy[k]) {
if (1 == count && prevList->bugs[index].x == prevBugX
&& prevList->bugs[index].y == prevBugY) {
continue;
}
count++;
index = j;
}
}
}
// Bug found
if (1 == count) {
list->bugs[i].prevX = prevList->bugs[index].x;
list->bugs[i].prevY = prevList->bugs[index].y;
prevList->bugs[index] = prevList->bugs[--prevList->nBugs];
done++;
}
}
if ((prevList->nBugs > 0 && done == list->nBugs) || prevList->nBugs == 0) {
return true;
}
int count = 0;
bool visited[list->nBugs];
for (int j = 0; j < list->nBugs; j++) {
visited[j] = false;
}
for (int j = 0; j < list->nBugs; j++) {
for (int i = 0; i < prevList->nBugs; i++) {
int x1 = INF, y1 = INF;
int mandotory = 0;
for (int k = 0; k < 4; k++) {
if (state->map[prevList->bugs[i].x + dx[k]]
[prevList->bugs[i].y + dy[k]] != WALL
&& (prevList->bugs[i].x + dx[k] != prevList->bugs[i].prevX
|| prevList->bugs[i].y + dy[k] != prevList->bugs[i].prevY)) {
x1 = dx[k];
y1 = dy[k];
mandotory++;
}
}
if ((mandotory == 1) && (list->bugs[j].x == (prevList->bugs[i].x + x1))
&& (list->bugs[j].y == (prevList->bugs[i].y + y1)) && !visited[i]) {
list->bugs[j].prevX = prevList->bugs[i].x;
list->bugs[j].prevY = prevList->bugs[i].y;
count++;
visited[i] = true;
break;
}
}
}
return prevList->nBugs - count == 0 ? true : false;
}
Bug* bugFound(BugsList *list, int x, int y) {
for (int i = 0; i < list->nBugs; i++) {
int bugX = list->bugs[i].x;
int bugY = list->bugs[i].y;
for (int j = 0; j < 4; j++) {
if (bugX == x + dx[j] && bugY == y + dy[j]) {
return &list->bugs[i];
}
}
}
return NULL;
}
inline void updateField(State *state, string s) {
state->snippetsList->nSnippets = 0;
BugsList bugsList[1];
bugsList->nBugs = state->bugsList->nBugs;
for (int i = 0; i < bugsList->nBugs; i++) {
bugsList->bugs[i].x = state->bugsList->bugs[i].x;
bugsList->bugs[i].y = state->bugsList->bugs[i].y;
bugsList->bugs[i].prevX = state->bugsList->bugs[i].prevX;
bugsList->bugs[i].prevY = state->bugsList->bugs[i].prevY;
}
state->bugsList->nBugs = 0;
int n = s.length();
int i = 0;
for (int x = 1; x < HEIGHT + 1; x++) {
for (int y = 1; y < WIDTH + 1; y++) {
while (true) {
if (i == n || s[i] == ',') {
i++;
break;
}
char c = s[i++];
if (c == 'x') {
state->map[x][y] = WALL;
} else if (c == '.') {
state->map[x][y] = FREE_CELL;
} else if (c == 'E') {
if ((x == 8 && (y == 9 || y == 10 || y == 11 || y == 12))
|| (x == 7 && y == 10) || (x == 7 && y == 11)) {
state->map[x][y] = WALL;
} else {
state->map[x][y] = FREE_CELL;
}
int n = state->bugsList->nBugs;
state->bugsList->bugs[n].x = x;
state->bugsList->bugs[n].y = y;
Bug *bug = bugFound(bugsList, x, y);
if (NULL != bug) {
state->bugsList->bugs[n].prevX = bug->x;
state->bugsList->bugs[n].prevY = bug->y;
ASSERT(bug->x > 0 && bug->x < HEIGHT + 1);
ASSERT(bug->y > 0 && bug->y < WIDTH + 1);
} else {
state->bugsList->bugs[n].prevX = 0;
state->bugsList->bugs[n].prevY = 0;
}
state->bugsList->nBugs++;
} else if (c == 'W') {
state->map[x][y] = WEAPON;
} else if (c == 'C') {
state->map[x][y] = SNIPPET;
int n = state->snippetsList->nSnippets++;
Snippet s;
s.x = x;
s.y = y;
s.visited = false;
s.appearRound = state->round;
state->snippetsList->snippets[n] = s;
} else {
// played id
int id = c - '0';
if (id == PLAYER0) {
state->first->x = x;
state->first->y = y;
state->first->prevX = 0;
state->first->prevY = 0;
state->map[x][y] = FREE_CELL;
} else {
state->second->x = x;
state->second->y = y;
state->second->prevX = 0;
state->second->prevY = 0;
state->map[x][y] = FREE_CELL;
}
}
}
}
}
}
inline bool checkTestCase(TestCase test) {
printf("Start test number %d...\n", test.id);
State *state = new State();
//initHashTable(state->hashTable, 128);
updateField(state, ".,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,x,x,x,x,x,.,x,x,x,x,x,x,.,x,x,x,x,x,.,.,x,.,.,.,.,.,x,x,x,x,x,x,.,.,.,.,.,x,.,.,x,.,x,x,x,.,.,.,x,x,.,.,.,x,x,x,.,x,.,.,.,.,.,.,x,x,x,.,x,x,.,x,x,x,.,.,.,.,.,.,x,x,x,.,x,.,.,.,.,.,.,.,.,x,.,x,x,x,.,.,.,.,x,.,x,.,x,x,x,x,x,x,.,x,.,x,.,.,.,x,x,0,x,.,.,.,x,x,x,x,x,x,.,.,.,x,1,x,x,.,.,.,x,x,x,.,x,x,x,x,x,x,.,x,x,x,.,.,.,.,x,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,x,.,.,x,x,x,.,x,x,x,x,x,x,x,x,x,x,.,x,x,x,.,.,x,x,x,.,.,.,.,.,.,.,.,.,.,.,.,x,x,x,.,.,x,x,x,.,x,x,x,.,x,x,.,x,x,x,.,x,x,x,.,.,.,.,.,.,.,.,.,.,x,x,.,.,.,.,.,.,.,.,.");
state->myId = 0;
state->round = test.posRound;
state->first->x = test.first.x;
state->first->y = test.first.y;
state->first->prevX = test.first.prevX;
state->first->prevY = test.first.prevY;
state->first->snippets = test.first.snippets;
state->first->has_weapon = test.first.has_weapon;
state->second->x = test.second.x;
state->second->y = test.second.y;
state->second->prevX = test.second.prevX;
state->second->prevY = test.second.prevY;
state->second->snippets = test.second.snippets;
state->second->has_weapon = test.second.has_weapon;
for (int i = 0; i < test.snippetsList->nSnippets; i++) {
Snippet s = test.snippetsList->snippets[i];
state->map[s.x][s.y] = SNIPPET;
int n = state->snippetsList->nSnippets++;
s.visited = false;
state->snippetsList->snippets[n] = s;
}
for (int i = 0; i < test.weaponsList->nSnippets; i++) {
Snippet s = test.weaponsList->snippets[i];
state->map[s.x][s.y] = WEAPON;
int n = state->weaponsList->nSnippets++;
s.visited = false;
state->weaponsList->snippets[n] = s;
}
for (int i = 0; i < test.bugsList->nBugs; i++) {
Bug bug = test.bugsList->bugs[i];
int n = state->bugsList->nBugs++;
state->bugsList->bugs[n] = bug;
}
SearchInfo info[1];
info->timeset = false;
info->debug = false;
info->depth = 8;
Move move0 = searchPosition(state, info, 0);
if(move0.direction == test.answer) {
printf("Test number %d passed\n", test.id);
} else {
printf("ERROR: Test number %d failed! Expected %s Given %s\n",
test.id, output[test.answer].c_str(), output[move0.direction].c_str());
state->printMap();
}
}
TestCase bugPrediction(int id) {
TestCase test;
test.id = id;
test.posRound = 37;
test.answer = LEFT;
test.first.x = 10;
test.first.y = 14;
test.first.prevX = 10;
test.first.prevY = 15;
test.first.snippets = 3;
test.first.has_weapon = false;
test.second.x = 7;
test.second.y = 14;
test.second.prevX = 6;
test.second.prevY = 14;
test.second.snippets = 2;
test.second.has_weapon = false;
test.bugsList->nBugs = 1;
test.bugsList->bugs[0].x = 6;
test.bugsList->bugs[0].y = 13;
test.bugsList->bugs[0].prevX = 6;
test.bugsList->bugs[0].prevY = 12;
test.weaponsList->nSnippets = 0;
test.snippetsList->nSnippets = 1;
test.snippetsList->snippets[0].x = 6;
test.snippetsList->snippets[0].y = 11;
return test;
}
TestCase doNotGoForHopelessSnip(int id) {
TestCase test;
test.id = id;
test.posRound = 90;
test.answer = LEFT;
test.first.x = 12;
test.first.y = 13;
test.first.prevX = 12;
test.first.prevY = 12;
test.first.snippets = 7;
test.first.has_weapon = true;
test.second.x = 8;
test.second.y = 18;
test.second.prevX = 7;
test.second.prevY = 18;
test.second.snippets = 4;
test.second.has_weapon = false;
test.bugsList->nBugs = 2;
test.bugsList->bugs[0].x = 7;
test.bugsList->bugs[0].y = 19;
test.bugsList->bugs[0].prevX = 7;
test.bugsList->bugs[0].prevY = 20;
test.bugsList->bugs[1].x = 7;
test.bugsList->bugs[1].y = 17;
test.bugsList->bugs[1].prevX = 6;
test.bugsList->bugs[1].prevY = 17;
test.weaponsList->nSnippets = 0;
test.snippetsList->nSnippets = 2;
test.snippetsList->snippets[0].x = 8;
test.snippetsList->snippets[0].y = 16;
test.snippetsList->snippets[1].x = 14;
test.snippetsList->snippets[1].y = 4;
return test;
}
inline void runTests() {
checkTestCase(bugPrediction(0));
checkTestCase(doNotGoForHopelessSnip(1));
}
#endif //#ifndef TEST_H_INCLUDED
<file_sep>#ifndef HASH_H_INCLUDED
#define HASH_H_INCLUDED
#include "defs.h"
#include "fastrand.h"
extern U64 pathHash[HEIGHT + 2][WIDTH + 2][2][MAX_ROUNDS];
extern U64 playerHash[HEIGHT + 2][WIDTH + 2][2];
extern U64 roundHash[MAX_ROUNDS];
extern U64 snippetHash[HEIGHT + 2][WIDTH + 2];
extern U64 weaponsHash[HEIGHT + 2][WIDTH + 2];
extern U64 bugsHash[HEIGHT + 2][WIDTH + 2];
void initHashKeys();
#endif //#ifndef HASH_H_INCLUDED
<file_sep>
<h2> Artificial Intelligence competitions code examples: </h2>
<ul>
<li> 1st place in HackMan competition by Booking.com </li>
<li> About 50th place in WonderWoman competition by codingame.com </li>
<li> Simple AI (about 250th place) for Code4Life competition by codingame.com </li>
</ul><file_sep>#include "defs.h"
#include "state.h"
#include "hash.h"
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
State::State() {
this->first = new Player();
this->second = new Player();
this->first->x = 0;
this->first->y = 0;
this->first->prevX = 0;
this->first->prevY = 0;
this->second->x = 0;
this->second->y = 0;
this->second->prevX = 0;
this->second->prevY = 0;
this->first->id = 0;
this->second->id = 1;
this->first->killedBugs = 0;
this->second->killedBugs = 0;
this->round = 0;
this->snippetsEaten = 0;
this->collectedSnippets = 0;
this->snippetsList->nSnippets = 0;
this->bugsList->nBugs = 0;
this->first->is_paralyzed = false;
this->second->is_paralyzed = false;
this->first->has_weapon = false;
this->second->has_weapon = false;
this->first->snippets = 0;
this->second->snippets = 0;
this->first->centerBonus = 0;
this->second->centerBonus = 0;
this->first->space = 0;
this->second->space = 0;
this->history[ply].weaponsList->nSnippets = 0;
this->history[ply].snippetsList->nSnippets = 0;
this->history[ply].bugs->nBugs = 0;
this->hisPly = 0;
this->ply = 0;
this->enemySpawned = false;
this->weaponSpawned = false;
for (int i = 0; i < HEIGHT + 2; i++){
this->map[i][0] = WALL;
this->map[i][WIDTH + 1] = WALL;
}
for (int i = 0; i < WIDTH + 2; i++){
this->map[0][i] = WALL;
this->map[HEIGHT + 1][i] = WALL;
}
}
void State::printMap() {
cerr << endl;
cerr << "influence = " << (influence[first->x][first->y][second->x][second->y] / 20.0) << endl;
cerr << "snippets eaten = " << snippetsEaten << endl;
cerr << "pos round = " << this->round << endl;
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
bool bug = false;
for (int k = 0; k < bugsList->nBugs; k++) {
if (i == bugsList->bugs[k].x && j == bugsList->bugs[k].y) {
cerr << "B ";
bug = true;
}
}
if (bug) {
continue;
}
if (i == this->first->x && j == this->first->y) {
cerr << "0 ";
} else if (i == this->second->x && j == this->second->y) {
cerr << "1 ";
} else if (WALL == this->map[i][j]) {
cerr << "# ";
} else if (FREE_CELL == this->map[i][j]) {
cerr << " ";
} else {
cerr << this->map[i][j] << " ";
}
}
cerr << endl;
}
}
void State::getLegalMoves(MovesList* list, Player *player) const {
list->nMoves = 0;
//list->moves[list->nMoves ].direction = PASS;
//list->moves[list->nMoves++].score = 0;
if (this->map[player->x + 1][player->y] != WALL) {
list->moves[list->nMoves ].direction = DOWN;
list->moves[list->nMoves++].score = 0;
}
if (this->map[player->x - 1][player->y] != WALL) {
list->moves[list->nMoves ].direction = UP;
list->moves[list->nMoves++].score = 0;
}
if (this->map[player->x][player->y + 1] != WALL) {
list->moves[list->nMoves ].direction = RIGHT;
list->moves[list->nMoves++].score = 0;
}
if (this->map[player->x][player->y - 1] != WALL) {
list->moves[list->nMoves ].direction = LEFT;
list->moves[list->nMoves++].score = 0;
}
ASSERT(list->nMoves > 0 && list->nMoves <= 5);
}
void State::makeEngineMove(Move &move, Player *player) {
ASSERT(move.direction >= 0 && move.direction <= 4);
ASSERT(player->x > 0 && player->x < HEIGHT + 1);
ASSERT(player->y > 0 && player->y < WIDTH + 1);
player->prevX = player->x;
player->prevY = player->y;
player->x += dx[move.direction];
player->y += dy[move.direction];
ASSERT(player->x > 0 && player->x < HEIGHT + 1);
ASSERT(player->y > 0 && player->y < WIDTH + 1);
}
double State::getPChase() {
double pChase = 0.2 + ((round - 1) * 0.004);
if (pChase > 1.0) return 1.0;
if (pChase < 0.0) return 0.0;
return pChase;
}
int State::updateWinner() {
if (first->snippets < 0 && second->snippets < 0) {
return 3;
} else if (first->snippets < 0) {
return 1;
} else if (second->snippets < 0) {
return 0;
}
if (round >= 200) {
if (first->snippets == second->snippets) {
return 3;
} else if (first->snippets > second->snippets) {
return 0;
} else if (first->snippets < second->snippets) {
return 1;
}
ASSERT(false);
}
return -1;
}
void State::makeMove(Move &move, Player *player) {
ASSERT(move.direction >= 0 && move.direction <= 4);
ASSERT(player->x > 0 && player->x < HEIGHT + 1);
ASSERT(player->y > 0 && player->y < WIDTH + 1);
//this->history[this->ply].hashKey = this->hashKey;
this->history[this->ply].move = move;
this->history[this->ply].prevX = player->prevX;
this->history[this->ply].prevY = player->prevY;
//this->hashKey ^= playerHash[player->x][player->y][player->id];
player->prevX = player->x;
player->prevY = player->y;
if (!player->is_paralyzed) {
player->x += dx[move.direction];
player->y += dy[move.direction];
}
ASSERT(player->x > 0 && player->x < HEIGHT + 1);
ASSERT(player->y > 0 && player->y < WIDTH + 1);
player->centerBonus += centerBonus[player->x][player->y];
player->space += space[player->x][player->y];
//this->hashKey ^= playerHash[player->x][player->y][player->id];
this->ply++;
}
void State::takeMove(Player *player) {
ASSERT(player->x > 0 && player->x < HEIGHT + 1);
ASSERT(player->y > 0 && player->y < WIDTH + 1);
ASSERT(this->round >= 0);
this->ply--;
player->centerBonus -= centerBonus[player->x][player->y];
player->space -= space[player->x][player->y];
player->prevX = this->history[this->ply].prevX;
player->prevY = this->history[this->ply].prevY;
//this->hashKey = this->history[this->ply].hashKey;
Move move = this->history[this->ply].move;
ASSERT(move.direction >= 0 && move.direction <= 4);
if (!player->is_paralyzed) {
player->x -= dx[move.direction];
player->y -= dy[move.direction];
}
}
U64 State::positionKey() const {
U64 key = 0;
key ^= playerHash[this->first->x][this->first->y][this->first->id];
key ^= playerHash[this->second->x][this->second->y][this->second->id];
key ^= roundHash[this->round];
for (int i = 0; i < this->snippetsList->nSnippets; i++) {
key ^= snippetHash[this->snippetsList->snippets[i].x]
[this->snippetsList->snippets[i].y];
}
for (int i = 0; i < this->bugsList->nBugs; i++) {
key ^= bugsHash[this->bugsList->bugs[i].x]
[this->bugsList->bugs[i].y];
}
for (int i = 0; i < this->weaponsList->nSnippets; i++) {
key ^= weaponsHash[this->weaponsList->snippets[i].x]
[this->weaponsList->snippets[i].y];
}
return key;
}
int State::distToNearestUnit(Player *player, int unitId) const {
int path[HEIGHT + 2][WIDTH + 2];
for (int i = 0; i < HEIGHT + 2; i++) {
for (int j = 0; j < WIDTH + 2; j++) {
path[i][j] = 0;
}
}
queue<Point> q;
q.push(Point(player->x, player->y));
path[player->x][player->y] = 1;
while(!q.empty()) {
Point top = q.front();
q.pop();
if (this->map[top.first][top.second] == unitId) {
return path[top.first][top.second];
}
for (int i = 0; i < 4; i++) {
Point cur = Point(top.first + dx[i], top.second + dy[i]);
if (this->map[cur.first][cur.second] != WALL
&& path[cur.first][cur.second] == 0) {
q.push(cur);
path[cur.first][cur.second] = path[top.first][top.second] + 1;
}
}
}
return 0;
}
int State::minDistToSnippets(int x, int y) {
int minValue = INF;
for (int i = snippetsList->nSnippets - 1; i >= 0 ; i--) {
if (snippetsList->snippets[i].visited) {
continue;
}
snippetsList->snippets[i].visited = TRUE;
int value = distances[x][y][snippetsList->snippets[i].x]
[snippetsList->snippets[i].y]
+ minDistToSnippets(snippetsList->snippets[i].x,
snippetsList->snippets[i].y);
snippetsList->snippets[i].visited = FALSE;
if (value < minValue) {
minValue = value;
}
}
return minValue == INF ? 0 : minValue;
}
int State::sumDistanceToSnippsAndWeapons() {
int sum = 0;
for (int i = 0; i < snippetsList->nSnippets; i++) {
sum += distances[first->x][first->y][snippetsList->snippets[i].x]
[snippetsList->snippets[i].y];
sum -= distances[second->x][second->y][snippetsList->snippets[i].x]
[snippetsList->snippets[i].y];
}
for (int i = 0; i < weaponsList->nSnippets; i++) {
sum += distances[first->x][first->y][weaponsList->snippets[i].x]
[weaponsList->snippets[i].y];
sum -= distances[second->x][second->y][weaponsList->snippets[i].x]
[weaponsList->snippets[i].y];
}
return sum;
}
int State::numbSnippetsCloserToPlayer() {
int sum = 0;
for (int i = 0; i < snippetsList->nSnippets; i++) {
if (distances[first->x][first->y][snippetsList->snippets[i].x]
[snippetsList->snippets[i].y]
< distances[second->x][second->y][snippetsList->snippets[i].x]
[snippetsList->snippets[i].y]) {
sum++;
}
if (distances[first->x][first->y][snippetsList->snippets[i].x]
[snippetsList->snippets[i].y]
> distances[second->x][second->y][snippetsList->snippets[i].x]
[snippetsList->snippets[i].y]) {
sum--;
}
}
return sum;
}
double State::nextDestinationValue(Player *p1, Player *p2) {
int nSnippets = snippetsList->nSnippets;
// Go to the best position relative to the opponent
if (0 == nSnippets) {
return min(distances[p1->x][p1->y][9][7],
distances[p1->x][p1->y][9][14]);
} else if (1 == nSnippets) {
Snippet snip1 = snippetsList->snippets[0];
if (distances[p1->x][p1->y][snip1.x][snip1.y]
< distances[p2->x][p2->y][snip1.x][snip1.y]) {
return distances[p1->x][p1->y][snip1.x][snip1.y];
}
} else if (2 == nSnippets) {
Snippet snip1 = snippetsList->snippets[0];
Snippet snip2 = snippetsList->snippets[1];
// We are closer to both snipps
if ((distances[p1->x][p1->y][snip1.x][snip1.y]
< distances[p2->x][p2->y][snip1.x][snip1.y])
&& (distances[p1->x][p1->y][snip2.x][snip2.y]
< distances[p2->x][p2->y][snip2.x][snip2.y])) {
// Try to pick both
if ((distances[p1->x][p1->y][snip1.x][snip1.y]
+ distances[snip2.x][snip2.y][snip1.x][snip1.y])
< distances[p2->x][p2->y][snip2.x][snip2.y]) {
// Go to the snip1 and then to the snip2
return distances[p1->x][p1->y][snip1.x][snip1.y]
+ distances[p1->x][p1->y][snip2.x][snip2.y] * 0.2;
}
if ((distances[p1->x][p1->y][snip2.x][snip2.y]
+ distances[snip2.x][snip2.y][snip1.x][snip1.y])
< distances[p2->x][p2->y][snip1.x][snip1.y]) {
// Go to the snip2 ant then to the snip1
return distances[p1->x][p1->y][snip2.x][snip2.y]
+ distances[p1->x][p1->y][snip1.x][snip1.y] * 0.2;
}
// Cant pick both, try to pick best
if (distances[p1->x][p1->y][snip1.x][snip1.y]
< distances[p1->x][p1->y][snip2.x][snip2.y]) {
// Go to the snip1
int center = min(distances[snip1.x][snip1.y][9][7],
distances[snip1.x][snip1.y][9][14]);
return distances[p1->x][p1->y][snip1.x][snip1.y] + center * 0.2;
} else {
// Go to the snip2
int center = min(distances[snip2.x][snip2.y][9][7],
distances[snip2.x][snip2.y][9][14]);
return distances[p1->x][p1->y][snip2.x][snip2.y] + center * 0.2;
}
}
if (distances[p1->x][p1->y][snip1.x][snip1.y]
< distances[p2->x][p2->y][snip1.x][snip1.y]) {
// Go to the snip1
int center = min(distances[snip1.x][snip1.y][9][7],
distances[snip1.x][snip1.y][9][14]);
return distances[p1->x][p1->y][snip1.x][snip1.y] + center * 0.2;
} else {
// Go to the snip2
int center = min(distances[snip2.x][snip2.y][9][7],
distances[snip2.x][snip2.y][9][14]);
return distances[p1->x][p1->y][snip2.x][snip2.y] + center * 0.2;
}
}
return 0;
}
double State::evaluate() {
double eval = 0;
/*
1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0
1 .,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,4,.,.,.,
2 .,0,0,0,0,0,.,0,0,0,0,0,0,.,0,0,0,0,0,.,
3 .,0,.,.,.,.,.,0,0,0,0,0,0,.,.,.,.,.,0,.,
4 .,0,.,0,0,0,.,.,.,0,0,.,.,.,0,0,0,.,0,.,
5 .,.,.,.,.,0,0,0,.,0,0,.,0,0,0,.,.,.,.,.,
6 .,0,0,0,.,0,.,.,.,.,.,.,.,.,0,.,0,0,0,.,
7 .,.,.,0,.,0,.,0,0,0,0,0,0,.,0,.,0,.,.,.,
8 0,0,.,0,.,.,.,0,0,0,0,0,0,.,.,.,0,.,0,0,
9 .,.,.,0,0,0,.,0,0,0,0,0,0,.,0,0,0,.,4,.,
10 .,0,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,.,0,.,
11 .,0,0,0,.,0,0,0,0,0,0,0,0,0,0,.,0,0,0,.,
12 .,0,0,0,.,.,.,.,.,.,.,.,.,.,.,.,0,0,0,.,
13 .,0,0,0,.,0,0,0,.,0,0,.,0,0,0,.,0,0,0,.,
14 .,.,.,.,.,.,.,.,.,0,0,.,.,.,.,.,.,.,.,.
*/
/*
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 15 15 15 17 19 21 23 21 20 19 19 20 21 23 21 19 17 15 15 15 0
0 17 0 0 0 0 0 23 0 0 0 0 0 0 23 0 0 0 0 0 17 0
0 19 0 21 21 21 22 24 0 0 0 0 0 0 24 22 21 21 21 0 19 0
0 21 0 22 0 0 0 23 22 22 0 0 22 22 23 0 0 0 22 0 21 0
0 23 23 23 21 20 0 0 0 23 0 0 23 0 0 0 20 21 23 23 23 0
0 22 0 0 0 19 0 24 24 25 23 23 25 24 24 0 19 0 0 0 22 0
0 21 20 20 0 19 0 25 0 0 0 0 0 0 25 0 19 0 20 20 21 0
0 0 0 21 0 20 23 27 0 0 0 0 0 0 27 23 20 0 21 0 0 0
0 18 20 24 0 0 0 28 0 0 0 0 0 0 28 0 0 0 24 20 18 0
0 16 0 26 30 34 32 30 25 22 20 20 22 25 30 32 34 30 26 0 16 0
0 15 0 0 0 33 0 0 0 0 0 0 0 0 0 0 33 0 0 0 15 0
0 14 0 0 0 31 27 25 24 23 23 23 23 24 25 27 31 0 0 0 14 0
0 14 0 0 0 27 0 0 0 21 0 0 21 0 0 0 27 0 0 0 14 0
0 15 17 19 22 24 22 20 19 19 0 0 19 19 20 22 24 22 19 17 15 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 */
int firstMinDist = INF;
int secondMinDist = INF;
int nearSnippets = 0;
for (int i = 0; i < snippetsList->nSnippets; i++) {
int x = snippetsList->snippets[i].x;
int y = snippetsList->snippets[i].y;
if (distances[x][y][first->x][first->y] < firstMinDist) {
firstMinDist = distances[x][y][first->x][first->y];
}
if (distances[x][y][second->x][second->y] < secondMinDist) {
secondMinDist = distances[x][y][second->x][second->y];
}
}
int numBugsChasing = 0;
for (int i = 0; i < bugsList->nBugs; i++) {
int x = bugsList->bugs[i].x;
int y = bugsList->bugs[i].y;
if (distances[x][y][first->x][first->y] < distances[x][y][second->x][second->y]) {
numBugsChasing--;
}
if (distances[x][y][first->x][first->y] > distances[x][y][second->x][second->y]) {
numBugsChasing++;
}
}
// Influence table
eval += (numBugsChasing * 8) * (0.2 + (round * 0.004));
eval += influence[first->x][first->y][second->x][second->y] / 30.0;
eval += (first->space - second->space) / (105.0);
eval += (first->centerBonus - second->centerBonus) / 40.0;
// For first
eval += 150.0 * first->snippets;
eval += 100.0 * first->killedBugs;
eval += -4.0 * firstMinDist;
eval += -0.4 * nextDestinationValue(first, second);
if (snippetsList->nSnippets < 6) {
eval += -minDistToSnippets(first->x, first->y);
}
if (first->has_weapon) {
eval += 105.0;
}
// For second
eval -= 150.0 * second->snippets;
eval -= 100.0 * second->killedBugs;
eval -= -4.0 * secondMinDist;
eval -= -0.4 * nextDestinationValue(second, first);
if (snippetsList->nSnippets < 6) {
eval -= -minDistToSnippets(second->x, second->y);
}
if (second->has_weapon) {
eval -= 105.0;
}
return eval;
}
<file_sep>#pragma GCC optimize("-O3")
#pragma GCC optimize("inline")
#pragma GCC optimize("omit-frame-pointer")
#pragma GCC optimize("unroll-loops")
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <queue>
// Iterative deepeing will stop by time limit or not
#define SEARCH_USE_TIME
// Use hash table to speed up search
#define SEARCH_USE_HASH_TABLE
// Use aspiration window
//#define SEARCH_USE_ASPIRATION_WINDOW
// For assert
//#define DEBUG
// For slow assert
//#define FULL_DEBUG
#define PRODUCTION
int const MAX_SIZE = 9;
int const FIRST = 0;
int const SECOND = 1;
int const PLAYERS = 2;
int const SEARCH_TIME_CHECK_RATE = 31;
int const MAX_SEARCH_DEPTH = 4;
int const MAX_MOVES = 256;
int const TIME_FOR_MOVE_MS = 200;
int const HASH_TABLE_MEMORY_MB = 128;
int const INF = 30000000;
int const WIN_SCORE = 300000;
int const WALL = -1;
int const FREE = 0;
int const TOP = 3;
int const FOR_ONE = 1;
int const FOR_BOTH = 2;
int const DIRECTIONS = 8;
int const dx[] = {1, 1, 1, -1, -1, -1, 0, 0};
int const dy[] = {1, 0, -1, 1, 0, -1, 1, -1};
int const dirX[8][3] = {{1, 1, 0}, {1, 1, 1}, { 1, 1, 0}, {-1, 0, -1},
{-1, -1, -1}, {-1, -1, 0}, {0, 1, -1}, { 0, -1, 1}};
int const dirY[8][3] = {{1, 0, 1}, {0, 1, -1}, {-1, 0, -1}, { 1, 1, 0},
{ 0, -1, 1}, {-1, 0, -1}, {1, 1, 1}, {-1, -1, -1}};
std::string const out[] = {"SE", "E", "NE", "SW", "W", "NW", "S", "N"};
std::string const outType[] = {"MOVE&BUILD", "PUSH&BUILD"};
typedef unsigned long long U64;
typedef std::pair<int,int> Point;
enum {FALSE = 0, TRUE = 1};
enum {HFNONE, HFALPHA, HFBETA, HFEXACT};
enum {MOVE_BUILD = 0, PUSH_BUILD = 1};
using namespace std;
map<string, Point> dir;
map<string, string> dirOut;
U64 zorbistHashMap[MAX_SIZE + 2][MAX_SIZE + 2][6];
U64 zorbistHashPlayer[MAX_SIZE + 2][MAX_SIZE + 2][2][2];
U64 zorbistHashTurn;
static unsigned int g_seed;
inline void fast_srand(int seed) {
//Seed the generator
g_seed = seed;
}
inline int fastrand() {
//fastrand routine returns one integer, similar output value range as C lib.
g_seed = (214013*g_seed+2531011);
return (g_seed>>16)&0x7FFF;
}
inline int fastRandInt(int maxSize) {
return fastrand() % maxSize;
}
inline int fastRandInt(int a, int b) {
return(a + fastRandInt(b - a));
}
inline double fastRandDouble() {
return static_cast<double>(fastrand()) / 0x7FFF;
}
inline double fastRandDouble(double a, double b) {
return a + (static_cast<double>(fastrand()) / 0x7FFF)*(b-a);
}
#define RAND_64 ((unsigned long long)fastrand() | \
(unsigned long long)fastrand() << 15 | \
(unsigned long long)fastrand() << 30 | \
(unsigned long long)fastrand() << 45 | \
((unsigned long long)fastrand() & 0xf) << 60 )
#ifdef WIN32
#include "windows.h"
#else
#include "sys/time.h"
#endif
inline int getTimeMs() {
#ifdef WIN32
return GetTickCount();
#else
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_sec*1000 + t.tv_usec/1000;
#endif
}
#ifndef DEBUG
#define ASSERT(n)
#else
#define ASSERT(n) \
if(!(n)) { \
printf("%s - Failed",#n); \
printf("On %s ",__DATE__); \
printf("At %s ",__TIME__); \
printf("In File %s ",__FILE__); \
printf("At Line %d\n",__LINE__); \
exit(1);}
#endif
#ifndef FULL_DEBUG
#define SLOW_ASSERT(n)
#else
#define SLOW_ASSERT(n) \
if(!(n)) { \
printf("%s - Failed",#n); \
printf("On %s ",__DATE__); \
printf("At %s ",__TIME__); \
printf("In File %s ",__FILE__); \
printf("At Line %d\n",__LINE__); \
exit(1);}
#endif
#ifndef PRODUCTION
#include <Windows.h>
inline void setColor(int text, int background) {
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, (WORD)((background << 4) | text));
}
#else
inline void setColor(int text, int background) {
}
#endif
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
class Player {
public:
int x;
int y;
int proven;
Player() {
x = 0;
y = 0;
proven = 0;
}
Player(int x, int y) {
this->x = x;
this->y = y;
proven = 0;
}
};
class Move {
public:
int score;
int x1;
int y1;
int x2;
int y2;
int type;
int playerId;
string toString() {
return "Error";
}
string dir1() {
if (x1 == 1 && y1 == 1) return "SE";
if (x1 == 0 && y1 == 1) return "E";
if (x1 == -1 && y1 == 1) return "NE";
if (x1 == 1 && y1 == -1) return "SW";
if (x1 == 0 && y1 == -1) return "W";
if (x1 == -1 && y1 == -1) return "NW";
if (x1 == 1 && y1 == 0) return "S";
if (x1 == -1 && y1 == 0) return "N";
return "ERROR";
}
string dir2() {
if (x2 == 1 && y2 == 1) return "SE";
if (x2 == 0 && y2 == 1) return "E";
if (x2 == -1 && y2 == 1) return "NE";
if (x2 == 1 && y2 == -1) return "SW";
if (x2 == 0 && y2 == -1) return "W";
if (x2 == -1 && y2 == -1) return "NW";
if (x2 == 1 && y2 == 0) return "S";
if (x2 == -1 && y2 == 0) return "N";
return "ERROR";
}
};
class MovesList {
public:
Move moves[MAX_MOVES];
int count;
MovesList() {
this->count = 0;
}
};
class Settings {
public:
int depth;
int nodes;
int stopped;
int debug;
int timeset;
int stoptime;
int nullCut;
Settings() {
depth = MAX_SEARCH_DEPTH;
nodes = 0;
stopped = 0;
debug = 0;
timeset = 0;
stoptime = 0;
nullCut = 0;
}
void refresh() {
stopped = FALSE;
nodes = 0;
}
};
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
class HashEntry {
public:
U64 stateKey;
Move move;
int score;
int depth;
int flags;
};
class HashTable {
private:
HashEntry *hashEntry;
int numEntries;
int newWrite;
int overWrite;
int hit;
public:
int cut;
HashTable(const int mb) {
initHashTable(mb);
};
void clearHashTable() {
for (HashEntry *e = this->hashEntry; e < this->hashEntry + this->numEntries; e++) {
e->stateKey = 0ULL;
Move nomove;
e->move = nomove;
e->depth = 0;
e->score = 0;
e->flags = 0;
}
this->newWrite = 0;
};
void initHashTable(const int mb) {
int hashSize = 0x100000 * mb;
this->numEntries = hashSize / sizeof(HashEntry);
this->numEntries -= 2;
if (this->hashEntry != NULL) {
free(this->hashEntry);
}
this->hashEntry = (HashEntry*) malloc(this->numEntries * sizeof(HashEntry));
if (this->hashEntry == NULL) {
initHashTable(mb / 2);
} else {
clearHashTable();
}
};
int probeHashEntry(Move *move, U64 stateHash, int ply, int *score, int alpha, int beta, int depth) {
int index = stateHash % ((U64)this->numEntries);
ASSERT(index >= 0 && index <= this->numEntries - 1);
ASSERT(depth >= 1 && depth <= MAX_SEARCH_DEPTH * 2);
ASSERT(alpha < beta);
ASSERT(alpha >= -INF && alpha <= INF);
ASSERT(beta >= -INF && beta <= INF);
ASSERT(ply >= 0 && ply <= MAX_SEARCH_DEPTH * 2);
if (this->hashEntry[index].stateKey == stateHash) {
*move = this->hashEntry[index].move;
if (this->hashEntry[index].depth >= depth) {
this->hit++;
ASSERT(this->hashEntry[index].depth >=1
&& this->hashEntry[index].depth <= MAX_SEARCH_DEPTH * 2);
ASSERT(this->hashEntry[index].flags >= HFALPHA
&& this->hashEntry[index].flags <= HFEXACT);
*score = this->hashEntry[index].score;
if (*score > WIN_SCORE) {
*score -= ply;
} else if (*score < -WIN_SCORE) {
*score += ply;
}
switch(this->hashEntry[index].flags) {
ASSERT(*score >= -INF && *score <= INF);
case HFALPHA:
if (*score <= alpha) {
*score = alpha;
return TRUE;
}
break;
case HFBETA:
if(*score >= beta) {
*score = beta;
return TRUE;
}
break;
case HFEXACT:
return TRUE;
break;
default: ASSERT(FALSE); break;
}
}
}
return FALSE;
};
void storeHashEntry(const Move move, const U64 stateHash, const int ply,
int score, const int flags, const int depth) {
int index = stateHash % ((U64)this->numEntries);
ASSERT(index >= 0 && index <= this->numEntries - 1);
ASSERT(depth >= 1 && depth <= MAX_SEARCH_DEPTH * 2);
ASSERT(flags >= HFALPHA && flags <= HFEXACT);
ASSERT(score >= -INF && score <= INF);
ASSERT(ply >= 0 && ply <= MAX_SEARCH_DEPTH * 2);
if (0 == this->hashEntry[index].stateKey) {
this->newWrite++;
} else {
this->overWrite++;
}
if (score > WIN_SCORE) {
score += ply;
} else if (score < -WIN_SCORE) {
score -= ply;
}
this->hashEntry[index].move = move;
this->hashEntry[index].stateKey = stateHash;
this->hashEntry[index].flags = flags;
this->hashEntry[index].score = score;
this->hashEntry[index].depth = depth;
};
Move getBestMove(const U64 stateHash) {
int index = stateHash % ((U64) this->numEntries);
ASSERT(index >= 0 && index <= this->numEntries - 1);
if(this->hashEntry[index].stateKey == stateHash) {
return this->hashEntry[index].move;
}
Move nomove;
nomove.x1 = 0;
nomove.y1 = 0;
return nomove;
}
};
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
class State {
public:
int **map;
int firstScore;
int secondScore;
Player *first[PLAYERS];
Player *second[PLAYERS];
int version;
int oppSetByGuess;
int playerToMove;
int ply;
int gameRound;
int myId;
int size;
U64 hashKey;
HashTable* hashTable;
State(int size) {
this->size = size;
playerToMove = FIRST;
ply = 0;
gameRound = 0;
oppSetByGuess = -1;
firstScore = 0;
secondScore = 0;
hashTable = new HashTable(HASH_TABLE_MEMORY_MB);
map = new int*[size + 2];
for (int i = 0; i < size + 2; i++) {
map[i] = new int[size + 2];
}
for (int i = 0; i < size + 2; i++) {
for (int j = 0; j < size + 2; j++) {
map[i][j] = WALL;
}
}
initHash();
}
void getLegalMoves(MovesList *list) {
Player **current = playerToMove == FIRST ? first : second;
Player **opp = playerToMove == FIRST ? second : first;
list->count = 0;
for (int i = 0; i < PLAYERS; i++) {
int x = current[i]->x;
int y = current[i]->y;
// Seems the player in the shadow
if (x == 0 || y == 0) {
continue;
}
int level = map[x][y];
ASSERT(level >= 0 && level <= 3)
// MOVE && BUILD
for (int j = 0; j < DIRECTIONS; j++) {
Move move;
move.playerId = i;
if (map[x + dx[j]][y + dy[j]] == WALL) continue;
if (x + dx[j] == second[0]->x && y + dy[j] == second[0]->y) continue;
if (x + dx[j] == second[1]->x && y + dy[j] == second[1]->y) continue;
if (x + dx[j] == first[0]->x && y + dy[j] == first[0]->y) continue;
if (x + dx[j] == first[1]->x && y + dy[j] == first[1]->y) continue;
if (map[x + dx[j]][y + dy[j]] - 1 <= level) {
move.type = MOVE_BUILD;
move.x1 = dx[j];
move.y1 = dy[j];
current[i]->x += dx[j];
current[i]->y += dy[j];
int nx = x + dx[j];
int ny = y + dy[j];
// BUILD
for (int k = 0; k < DIRECTIONS; k++) {
if (map[nx + dx[k]][ny + dy[k]] == WALL) continue;
if (nx + dx[k] == second[0]->x && ny + dy[k] == second[0]->y) continue;
if (nx + dx[k] == second[1]->x && ny + dy[k] == second[1]->y) continue;
if (nx + dx[k] == first[0]->x && ny + dy[k] == first[0]->y) continue;
if (nx + dx[k] == first[1]->x && ny + dy[k] == first[1]->y) continue;
move.x2 = dx[k];
move.y2 = dy[k];
move.score = map[nx][ny]
+ (map[nx + dx[k]][ny + dy[k]] + 1) % 4;
list->moves[list->count++] = move;
}
current[i]->x -= dx[j];
current[i]->y -= dy[j];
}
}
// PUSH & BUILD
for (int j = 0; j < DIRECTIONS; j++) {
Move move;
move.playerId = i;
if (map[x + dx[j]][y + dy[j]] == WALL) continue;
if ((opp[0]->x != x + dx[j] || opp[0]->y != y + dy[j])
&& (opp[1]->x != x + dx[j] || opp[1]->y != y + dy[j])) {
continue;
}
move.type = PUSH_BUILD;
move.x1 = dx[j];
move.y1 = dy[j];
int tx = x + dx[j];
int ty = y + dy[j];
// BUILD
for (int k = 0; k < 3; k++) {
if (map[tx + dirX[j][k]][ty + dirY[j][k]] == WALL) continue;
if (tx + dirX[j][k] == second[0]->x && ty + dirY[j][k] == second[0]->y) continue;
if (tx + dirX[j][k] == second[1]->x && ty + dirY[j][k] == second[1]->y) continue;
if (tx + dirX[j][k] == first[0]->x && ty + dirY[j][k] == first[0]->y) continue;
if (tx + dirX[j][k] == first[1]->x && ty + dirY[j][k] == first[1]->y) continue;
if (map[tx + dirX[j][k]][ty + dirY[j][k]] - 1 <= map[tx][ty]) {
move.x2 = dirX[j][k];
move.y2 = dirY[j][k];
move.score = (map[tx][ty] * map[tx][ty])
- map[tx + dirX[j][k]][ty + dirY[j][k]];
list->moves[list->count++] = move;
}
}
}
}
return;
};
int activityValue(Player *player) const {
int activity = 0;
for (int i = 0; i < DIRECTIONS; i++) {
if (WALL == map[player->x + dx[i]][player->y + dy[i]]) {
continue;
}
if (map[player->x + dx[i]][player->y + dy[i]] - 1
> map[player->x][player->y]) {
continue;
}
for (int j = 0; j < DIRECTIONS; j++) {
if (WALL == map[player->x + dx[i] + dx[j]]
[player->y + dy[i] + dy[j]]) {
continue;
}
if (map[player->x + dx[i] + dx[j]]
[player->y + dy[i] + dy[j]] - 1
> map[player->x + dx[i]][player->y + dy[i]]) {
continue;
}
activity++;
}
activity += map[player->x + dx[i]][player->y + dy[i]];
}
activity += map[player->x][player->y] * 2;
return activity;
}
int getDistances() const {
int tempMap[MAX_SIZE][MAX_SIZE];
memset(tempMap, FREE, sizeof(tempMap[0][0]) * MAX_SIZE * MAX_SIZE);
queue<Point> q;
q.push(Point(first[0]->x, first[0]->y));
q.push(Point(first[1]->x, first[1]->y));
tempMap[first[0]->x][first[0]->y] = 1;
tempMap[first[1]->x][first[1]->y] = 1;
int ans = 0;
while (!q.empty()) {
Point top = q.front();
q.pop();
for (int i = 0; i < DIRECTIONS; i++) {
Point cur = Point(top.first + dx[i], top.second + dy[i]);
if (map[cur.first][cur.second] != WALL
&& tempMap[cur.first][cur.second] == FREE
&& (map[top.first][top.second] >= map[cur.first][cur.second] - 1)
&& !(cur.first == second[0]->x && cur.second == second[0]->y)
&& !(cur.first == second[1]->x && cur.second == second[1]->y)) {
q.push(cur);
tempMap[cur.first][cur.second] = 1 + tempMap[top.first][top.second];
ans++;
}
}
}
return ans;
}
int getDistancesOpp() const {
int tempMap[MAX_SIZE][MAX_SIZE];
memset(tempMap, FREE, sizeof(tempMap[0][0]) * MAX_SIZE * MAX_SIZE);
queue<Point> q;
if (second[0]->x != 0) {
q.push(Point(second[0]->x, second[0]->y));
tempMap[second[0]->x][second[0]->y] = 1;
}
if (second[1]->x != 0) {
q.push(Point(second[1]->x, second[1]->y));
tempMap[second[1]->x][second[1]->y] = 1;
}
int ans = 0;
while (!q.empty()) {
Point top = q.front();
q.pop();
for (int i = 0; i < DIRECTIONS; i++) {
Point cur = Point(top.first + dx[i], top.second + dy[i]);
if (map[cur.first][cur.second] != WALL
&& tempMap[cur.first][cur.second] == FREE
&& (map[top.first][top.second] >= map[cur.first][cur.second] - 1)
&& !(cur.first == first[0]->x && cur.second == first[0]->y)
&& !(cur.first == first[1]->x && cur.second == first[1]->y)) {
q.push(cur);
tempMap[cur.first][cur.second] = 1 + tempMap[top.first][top.second];
ans++;
}
}
}
return ans;
}
int evaluate(int mode) const {
int score = 0;
int firstActivity1 = activityValue(first[0]);
int firstActivity2 = activityValue(first[1]);
int secondActivity1 = 0;
int secondActivity2 = 0;
if (second[0]->x != 0) {
secondActivity1 = activityValue(second[0]);
}
if (second[1]->x != 0) {
secondActivity2 = activityValue(second[1]);
}
score += firstActivity1 + firstActivity2;
score -= secondActivity1 + secondActivity2;
score += firstScore * 2;
score -= secondScore * 2;
score += getDistances() * 10 - getDistancesOpp() * 10;
if (FOR_ONE == mode) {
return score;
} else {
return playerToMove == FIRST ? score : -score;
}
}
void initHash() {
zorbistHashTurn = RAND_64;
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
for (int k = 0; k < 5; k++) {
zorbistHashMap[i][j][k] = RAND_64;
}
zorbistHashPlayer[i][j][0][0] = RAND_64;
zorbistHashPlayer[i][j][0][1] = RAND_64;
zorbistHashPlayer[i][j][1][0] = RAND_64;
zorbistHashPlayer[i][j][1][1] = RAND_64;
}
}
}
U64 hash() const {
U64 hash = 213;
hash ^= firstScore;
hash ^= secondScore;
if (playerToMove == FIRST) {
hash ^= zorbistHashTurn;
}
if (first[0]->x > 0) {
hash ^= zorbistHashPlayer[first[0]->x][first[0]->y][0][0];
}
if (first[1]->x > 0) {
hash ^= zorbistHashPlayer[first[1]->x][first[1]->y][0][1];
}
if (second[0]->x > 0) {
hash ^= zorbistHashPlayer[second[0]->x][second[0]->y][1][0];
}
if (second[1]->x > 0) {
hash ^= zorbistHashPlayer[second[1]->x][second[1]->y][1][1];
}
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
hash ^= zorbistHashMap[i][j][map[i][j] + 1];
}
}
return hash;
}
void makeMove(Move move, int mode) {
Player **current = playerToMove == FIRST ? first : second;
Player **opp = playerToMove == FIRST ? second : first;
Player *player = current[move.playerId];
ASSERT(player->x >= 1 && player->y >= 1 && player->x <= size && player->y <= size);
ASSERT(player->x + move.x1 >= 1 && player->y + move.y1 >= 1);
ASSERT(player->x + move.x1 <= size && player->y + move.y1 <= size);
ASSERT(map[player->x + move.x1 + move.x2][player->y + move.y1 + move.y2] != WALL);
if (MOVE_BUILD == move.type) {
// Update player hash
hashKey ^= zorbistHashPlayer[player->x][player->y][playerToMove][move.playerId];
player->x += move.x1;
player->y += move.y1;
hashKey ^= zorbistHashPlayer[player->x][player->y][playerToMove][move.playerId];
// Update map hashKey
hashKey ^= zorbistHashMap[player->x + move.x2][player->y + move.y2]
[map[player->x + move.x2][player->y + move.y2] + 1];
map[player->x + move.x2][player->y + move.y2]++;
if (4 == map[player->x + move.x2][player->y + move.y2]) {
map[player->x + move.x2][player->y + move.y2] = WALL;
}
hashKey ^= zorbistHashMap[player->x + move.x2][player->y + move.y2]
[map[player->x + move.x2][player->y + move.y2] + 1];
if (TOP == map[player->x][player->y]) {
if (FIRST == playerToMove) {
hashKey ^= firstScore;
firstScore++;
hashKey ^= firstScore;
} else {
hashKey ^= secondScore;
secondScore++;
hashKey ^= secondScore;
}
}
} else {
ASSERT(opp[0]->x == player->x + move.x1 && opp[0]->y == player->y + move.y1
|| opp[1]->x == player->x + move.x1 && opp[1]->y == player->y + move.y1);
int index = (opp[1]->x == player->x + move.x1
&& opp[1]->y == player->y + move.y1);
ASSERT(index == 0 || index == 1);
ASSERT(opp[index]->x == player->x + move.x1 && opp[index]->y == player->y + move.y1)
hashKey ^= zorbistHashMap[opp[index]->x][opp[index]->y]
[map[opp[index]->x][opp[index]->y] + 1];
map[opp[index]->x][opp[index]->y]++;
if (4 == map[opp[index]->x][opp[index]->y]) {
map[opp[index]->x][opp[index]->y] = WALL;
}
hashKey ^= zorbistHashMap[opp[index]->x][opp[index]->y]
[map[opp[index]->x][opp[index]->y] + 1];
hashKey ^= zorbistHashPlayer[opp[index]->x][opp[index]->y][playerToMove ^ 1][index];
opp[index]->x += move.x2;
opp[index]->y += move.y2;
hashKey ^= zorbistHashPlayer[opp[index]->x][opp[index]->y][playerToMove ^ 1][index];
}
if (FOR_BOTH == mode) {
playerToMove ^= 1;
hashKey ^= zorbistHashTurn;
}
SLOW_ASSERT(hashKey == hash());
return;
}
void takeMove(Move move, int mode) {
if (FOR_BOTH == mode) {
playerToMove ^= 1;
hashKey ^= zorbistHashTurn;
}
Player **current = playerToMove == FIRST ? first : second;
Player **opp = playerToMove == FIRST ? second : first;
Player *player = current[move.playerId];
ASSERT(player->x >= 1 && player->y >= 1 && player->x <= size && player->y <= size);
if (MOVE_BUILD == move.type) {
if (TOP == map[player->x][player->y]) {
if (FIRST == playerToMove) {
hashKey ^= firstScore;
firstScore--;
hashKey ^= firstScore;
} else {
hashKey ^= secondScore;
secondScore--;
hashKey ^= secondScore;
}
}
ASSERT(player->x - move.x1 >= 1 && player->y - move.y1 >= 1);
ASSERT(player->x - move.x1 <= size && player->y - move.y1 <= size);
hashKey ^= zorbistHashMap[player->x + move.x2][player->y + move.y2]
[map[player->x + move.x2][player->y + move.y2] + 1];
if (WALL == map[player->x + move.x2][player->y + move.y2]) {
map[player->x + move.x2][player->y + move.y2] = 4;
}
map[player->x + move.x2][player->y + move.y2]--;
hashKey ^= zorbistHashMap[player->x + move.x2][player->y + move.y2]
[map[player->x + move.x2][player->y + move.y2] + 1];
hashKey ^= zorbistHashPlayer[player->x][player->y][playerToMove][move.playerId];
player->x -= move.x1;
player->y -= move.y1;
hashKey ^= zorbistHashPlayer[player->x][player->y][playerToMove][move.playerId];
} else {
int index = (opp[1]->x == player->x + move.x1 + move.x2
&& opp[1]->y == player->y + move.y1 + move.y2);
hashKey ^= zorbistHashPlayer[opp[index]->x][opp[index]->y][playerToMove ^ 1][index];
opp[index]->x -= move.x2;
opp[index]->y -= move.y2;
hashKey ^= zorbistHashPlayer[opp[index]->x][opp[index]->y][playerToMove ^ 1][index];
ASSERT(index == 0 || index == 1);
ASSERT(opp[index]->x == player->x + move.x1
&& opp[index]->y == player->y + move.y1)
hashKey ^= zorbistHashMap[opp[index]->x][opp[index]->y]
[map[opp[index]->x][opp[index]->y] + 1];
if (WALL == map[opp[index]->x][opp[index]->y]) {
map[opp[index]->x][opp[index]->y] = 4;
}
map[opp[index]->x][opp[index]->y]--;
hashKey ^= zorbistHashMap[opp[index]->x][opp[index]->y]
[map[opp[index]->x][opp[index]->y] + 1];
ASSERT(opp[0]->x == player->x + move.x1 && opp[0]->y == player->y + move.y1
|| opp[1]->x == player->x + move.x1 && opp[1]->y == player->y + move.y1);
}
SLOW_ASSERT(hashKey == hash());
return;
}
int oppIsVisible() {
return second[0]->x != 0 || second[1]->x != 0;
}
void setValue(int i, int j, int value) {
map[i][j] = value;
}
void predictOppPosition(int (&prevMap)[MAX_SIZE][MAX_SIZE],
Player tFirst[2], Player tSecond[2]) {
// Nothing to do, can see both
if (second[0]->proven && second[1]->proven) {
return;
}
// If it was PUSH from opp
if (tFirst[0].x != first[0]->x || tFirst[0].y != first[0]->y
|| tFirst[1].x != first[1]->x || tFirst[1].y != first[1]->y) {
int px = (tFirst[0].x - first[0]->x) + (tFirst[1].x - first[1]->x);
int py = (tFirst[0].y - first[0]->y) + (tFirst[1].y - first[1]->y);
int d = 0;
for (int i = 0; i < DIRECTIONS; i++) {
if (dx[i] == px && dy[i] == py) {
d = i;
break;
}
}
// Check if someone has been staying from the prev turn
int second1 = abs(tSecond[0].x + tSecond[0].y) > 0;
int second2 = abs(tSecond[1].x + tSecond[1].y) > 0;
int x1 = 0;
int y1 = 0;
if (tFirst[0].x != first[0]->x || tFirst[0].y - first[0]->y) {
x1 = tFirst[0].x;
y1 = tFirst[0].y;
} else {
x1 = tFirst[1].x;
y1 = tFirst[1].y;
}
if (tSecond[0].x == x1 && tSecond[0].y == y1) {
second1 = FALSE;
}
if (tSecond[1].x == x1 && tSecond[1].y == y1) {
second2 = FALSE;
}
// If we see prev pos than there is can't be enemy
for (int i = 0; i < DIRECTIONS; i++) {
if (tSecond[0].x + dx[i] == first[0]->x
&& tSecond[0].y + dy[i] == first[0]->y) {
second1 = FALSE;
}
if (tSecond[0].x + dx[i] == first[1]->x
&& tSecond[0].y + dy[i] == first[1]->y) {
second1 = FALSE;
}
if (tSecond[1].x + dx[i] == first[0]->x
&& tSecond[1].y + dy[i] == first[0]->y) {
second2 = FALSE;
}
if (tSecond[1].x + dx[i] == first[1]->x
&& tSecond[1].y + dy[i] == first[1]->y) {
second2 = FALSE;
}
}
for (int i = 0; i < DIRECTIONS; i++) {
if (WALL == map[x1 + dx[i]][y1 + dy[i]]) {
continue;
}
if (x1 + dx[i] == tSecond[0].x && y1 + dy[i] == tSecond[0].y) {
second1 = FALSE;
}
if (x1 + dx[i] == tSecond[1].x && y1 + dy[i] == tSecond[1].y) {
second2 = FALSE;
}
for (int j = 0; j < DIRECTIONS; j++) {
int nx = x1 + dx[i] + dx[j];
int ny = x1 + dy[i] + dy[j];
if (WALL == map[nx][ny]) {
continue;
}
if (nx == tSecond[0].x && ny == tSecond[0].y) {
second1 = FALSE;
}
if (nx == tSecond[1].x && ny == tSecond[1].y) {
second2 = FALSE;
}
}
}
if (TRUE == second1) {
// Skip if already here
if (!(second[0]->x == tSecond[0].x && second[0]->y == tSecond[0].y
|| second[1]->x == tSecond[0].x && second[1]->y == tSecond[0].y)) {
if (!second[0]->proven) {
second[0]->x = tSecond[0].x;
second[0]->y = tSecond[0].y;
} else {
second[1]->x = tSecond[0].x;
second[1]->y = tSecond[0].y;
}
}
} else if (TRUE == second2) {
// Skip if already here
if (!(second[0]->x == tSecond[1].x && second[0]->y == tSecond[1].y
|| second[1]->x == tSecond[1].x && second[1]->y == tSecond[1].y)) {
if (!second[0]->proven) {
second[0]->x = tSecond[1].x;
second[0]->y = tSecond[1].y;
} else {
second[1]->x = tSecond[1].x;
second[1]->y = tSecond[1].y;
}
}
}
for (int i = 0; i < 3; i++) {
int x = tFirst[0].x != first[0]->x
? tFirst[0].x + dirX[d][i]
: tFirst[1].x + dirX[d][i];
int y = tFirst[0].y != first[0]->y
? tFirst[0].y + dirY[d][i]
: tFirst[1].y + dirY[d][i];
if (WALL == map[x][y]) {
continue;
}
if (abs(first[0]->x - x) <= 1 && abs(first[0]->y - y) <= 1) {
continue;
}
if (abs(first[1]->x - x) <= 1 && abs(first[1]->y - y) <= 1) {
continue;
}
if (!second[0]->proven) {
second[0]->x = x;
second[0]->y = y;
} else {
second[1]->x = x;
second[1]->y = y;
}
break;
}
// It was MOVE & BUILD or unsuccessful PUSH
} else {
int x = 0;
int y = 0;
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
if (map[i][j] != prevMap[i][j]) {
x = i;
y = j;
break;
}
}
}
if (x + y == 0) {
fprintf(stderr, "*** something went wrong! ****\n");
return;
}
// Check if someone has been staying from the prev turn
int second1 = abs(tSecond[0].x + tSecond[0].y) > 0;
int second2 = abs(tSecond[1].x + tSecond[1].y) > 0;
if (tSecond[0].x == x && tSecond[0].y == y) {
second1 = FALSE;
}
if (tSecond[1].x == x && tSecond[1].y == y) {
second2 = FALSE;
}
// If we see prev pos than there is can't be enemy
for (int i = 0; i < DIRECTIONS; i++) {
if (tSecond[0].x + dx[i] == first[0]->x
&& tSecond[0].y + dy[i] == first[0]->y) {
second1 = FALSE;
}
if (tSecond[0].x + dx[i] == first[1]->x
&& tSecond[0].y + dy[i] == first[1]->y) {
second1 = FALSE;
}
if (tSecond[1].x + dx[i] == first[0]->x
&& tSecond[1].y + dy[i] == first[0]->y) {
second2 = FALSE;
}
if (tSecond[1].x + dx[i] == first[1]->x
&& tSecond[1].y + dy[i] == first[1]->y) {
second2 = FALSE;
}
}
for (int i = 0; i < DIRECTIONS; i++) {
if (WALL == map[x + dx[i]][y + dy[i]]) {
continue;
}
if (x + dx[i] == tSecond[0].x && y + dy[i] == tSecond[0].y) {
second1 = FALSE;
}
if (x + dx[i] == tSecond[1].x && y + dy[i] == tSecond[1].y) {
second2 = FALSE;
}
for (int j = 0; j < DIRECTIONS; j++) {
int nx = x + dx[i] + dx[j];
int ny = y + dy[i] + dy[j];
if (WALL == map[nx][ny]) {
continue;
}
if (nx == tSecond[0].x && ny == tSecond[0].y) {
second1 = FALSE;
}
if (nx == tSecond[1].x && ny == tSecond[1].y) {
second2 = FALSE;
}
}
}
if (TRUE == second1) {
// Skip if already here
if (!(second[0]->x == tSecond[0].x && second[0]->y == tSecond[0].y
|| second[1]->x == tSecond[0].x && second[1]->y == tSecond[0].y)) {
if (!second[0]->proven) {
second[0]->x = tSecond[0].x;
second[0]->y = tSecond[0].y;
} else {
second[1]->x = tSecond[0].x;
second[1]->y = tSecond[0].y;
}
}
} else if (TRUE == second2) {
// Skip if already here
if (!(second[0]->x == tSecond[1].x && second[0]->y == tSecond[1].y
|| second[1]->x == tSecond[1].x && second[1]->y == tSecond[1].y)) {
if (!second[0]->proven) {
second[0]->x = tSecond[1].x;
second[0]->y = tSecond[1].y;
} else {
second[1]->x = tSecond[1].x;
second[1]->y = tSecond[1].y;
}
}
}
int minDist = INF;
int minDir = -1;
for (int k = 0; k < DIRECTIONS; k++) {
if (WALL != map[x + dx[k]][y + dy[k]]
&& !(first[0]->x == x + dx[k] && first[0]->y == y + dy[k])
&& !(first[1]->x == x + dx[k] && first[1]->y == y + dy[k])
&& ((abs(first[0]->x - (x + dx[k])) > 1)
|| (abs(first[0]->y - (y + dy[k])) > 1))
&& ((abs(first[1]->x - (x + dx[k])) > 1)
|| (abs(first[1]->y - (y + dy[k])) > 1))) {
if (minDist > abs(first[0]->x - (x + dx[k]))
+ abs(first[0]->y - (y + dy[k]))) {
minDist = abs(first[0]->x - (x + dx[k]))
+ abs(first[0]->y - (y + dy[k]));
minDir = k;
}
if (minDist > abs(first[1]->x - (x + dx[k]))
+ abs(first[1]->y - (y + dy[k]))) {
minDist = abs(first[1]->x - (x + dx[k]))
+ abs(first[1]->y - (y + dy[k]));
minDir = k;
}
}
}
if (minDist < INF && 0 == second[0]->x) {
fprintf(stderr, "guess opp is here %d %d\n", x + dx[minDir], y + dy[minDir]);
second[0]->x = x + dx[minDir];
second[0]->y = y + dy[minDir];
} else if (minDist < INF && 0 == second[1]->x) {
fprintf(stderr, "guess opp is here %d %d\n", x + dx[minDir], y + dy[minDir]);
second[1]->x = x + dx[minDir];
second[1]->y = y + dy[minDir];
}
}
}
void setPlayer(int x, int y, int teamId, int playerId) {
ASSERT(teamId == FIRST || teamId == SECOND);
ASSERT(playerId == FIRST || playerId == SECOND);
if (teamId == FIRST) {
first[playerId] = new Player(x, y);
} else {
second[playerId] = new Player(x, y);
if (x + y != 0) {
second[playerId]->proven = TRUE;
}
}
}
int isTerminal() const {
return 0;
}
void print() const {
cerr << "hash(inc) = " << hashKey << endl;
cerr << "hash = " << hash() << endl;
cerr << first[0]->y - 1 << " " << first[0]->x - 1 << endl;
cerr << first[1]->y - 1 << " " << first[1]->x - 1 << endl;
cerr << second[0]->y - 1 << " " << second[0]->x - 1 << endl;
cerr << second[1]->y - 1 << " " << second[1]->x - 1 << endl;
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
if (map[i][j] == WALL) {
cerr << "#";
} else{
cerr << map[i][j];
}
}
cerr << "\n";
}
cerr << "\n\n";
}
};
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
inline void checkUp(Settings *settings) {
if (settings->timeset && getTimeMs() > settings->stoptime) {
settings->stopped = TRUE;
}
}
inline void pickNextMove(int index, MovesList *list) {
Move temp;
int bestScore = 0;
int bestNum = index;
for (int i = index; i < list->count; i++) {
if (list->moves[i].score > bestScore) {
bestScore = list->moves[i].score;
bestNum = i;
}
}
ASSERT(index >= 0 && index < list->count);
ASSERT(bestNum >= 0 && bestNum < list->count);
ASSERT(bestNum >= index);
temp = list->moves[index];
list->moves[index] = list->moves[bestNum];
list->moves[bestNum] = temp;
}
int alphaBeta(int alpha, int beta, int depth, State *state,
Settings *settings, int nullMovePruning/*, PVLine *pvLine*/) {
ASSERT(beta > alpha);
ASSERT(depth >= 0);
settings->nodes++;
if (depth <= 0 || state->isTerminal()) {
return state->evaluate(FOR_BOTH);
}
#ifdef SEARCH_USE_TIME
if ((settings->nodes & SEARCH_TIME_CHECK_RATE) == 0) {
checkUp(settings);
}
#endif
int score = -INF;
Move pvMove;
pvMove.x1 = 0;
pvMove.y1 = 0;
#ifdef SEARCH_USE_HASH_TABLE
if (state->hashTable->probeHashEntry(&pvMove, state->hashKey,
state->ply, &score, alpha, beta, depth)) {
state->hashTable->cut++;
return score;
}
#endif
MovesList list[1];
state->getLegalMoves(list);
if (0 == list->count) {
return state->playerToMove == FIRST ? -WIN_SCORE : WIN_SCORE;
}
int oldAlpha = alpha;
Move bestMove;
bestMove.x1 = 0;
bestMove.y1 = 0;
bestMove.x2 = 0;
bestMove.y2 = 0;
int bestScore = -INF;
#ifdef SEARCH_USE_HASH_TABLE
if (0 != pvMove.x1 + pvMove.y1) {
for (int i = 0; i < list->count; i++) {
if (list->moves[i].x1 == pvMove.x1 && list->moves[i].y1 == pvMove.y1
&& list->moves[i].x2 == pvMove.x2 && list->moves[i].y2 == pvMove.y2
&& list->moves[i].playerId == pvMove.playerId
&& list->moves[i].type == pvMove.type) {
list->moves[i].score = 200000;
break;
}
}
}
#endif
/*PVLine line;*/
for(int currentMove = 0; currentMove < list->count; currentMove++) {
// Shift next best move to currentMove position in list
pickNextMove(currentMove, list);
state->ply++;
state->makeMove(list->moves[currentMove], FOR_BOTH);
score = -alphaBeta(-beta, -alpha, depth - 1, state, settings, TRUE/*, &line*/);
state->takeMove(list->moves[currentMove], FOR_BOTH);
state->ply--;
#ifdef SEARCH_USE_TIME
if (settings->stopped) {
return 0;
}
#endif
if (score > bestScore) {
bestScore = score;
bestMove = list->moves[currentMove];
bestMove.score = score;
if (score > alpha) {
if (score >= beta) {
#ifdef SEARCH_USE_HASH_TABLE
state->hashTable->storeHashEntry(bestMove, state->hashKey,
state->ply, beta, HFBETA, depth);
#endif
return beta;
}
//pvLine->moves[0] = list->moves[currentMove];
//memcpy(pvLine->moves + 1, line.moves, line.length * sizeof(Move));
//pvLine->length = line.length + 1;
alpha = score;
}
}
}
ASSERT(alpha >= oldAlpha);
#ifdef SEARCH_USE_HASH_TABLE
if (alpha != oldAlpha) {
state->hashTable->storeHashEntry(bestMove, state->hashKey,
state->ply, bestScore, HFEXACT, depth);
} else {
state->hashTable->storeHashEntry(bestMove, state->hashKey,
state->ply, alpha, HFALPHA, depth);
}
#endif
return alpha;
}
Move searchPositionIterative(State *state, Settings *settings) {
Move bestMove;
int bestScore = -INF;
int delta = -INF;
int alpha = -INF;
int beta = INF;
int start = getTimeMs();
/*PVLine line;*/
// Iterative deepening
for (int currentDepth = 1; currentDepth <= settings->depth; currentDepth++) {
settings->nodes = 0;
#ifdef SEARCH_USE_ASPIRATION_WINDOW
if (currentDepth > 1) {
delta = 35;
Move move = state->hashTable->getBestMove(state->hashKey);
alpha = std::max(move.score - delta, -INF);
beta = std::min(move.score + delta, INF);
}
while (true) {
bestScore = alphaBeta(alpha, beta, currentDepth, state, settings, TRUE/*, &line*/);
#ifdef SEARCH_USE_TIME
if (settings->stopped) {
break;
}
#endif
// In case of failing low/high increase aspiration window and
// re-search, otherwise exit the loop.
if (bestScore <= alpha) {
beta = (alpha + beta) / 2;
alpha = std::max(bestScore - delta, -INF);
} else if (bestScore >= beta) {
alpha = (alpha + beta) / 2;
beta = std::min(bestScore + delta, INF);
} else {
break;
}
fprintf(stderr, "aspiration failed\n");
delta += delta / 4 + 5;
ASSERT(alpha >= -INF && beta <= INF);
}
#endif
#ifndef SEARCH_USE_ASPIRATION_WINDOW
bestScore = alphaBeta(alpha, beta, currentDepth, state, settings, TRUE/*, &line*/);
#endif
#ifdef SEARCH_USE_TIME
if (settings->stopped) {
break;
}
#endif
bestMove = state->hashTable->getBestMove(state->hashKey);
fprintf(stderr, "Search depth : %d nodes : %d time : %f\n",
currentDepth, settings->nodes, (getTimeMs() - start) / 1000.0);
fprintf(stderr, "best move = (%d %d) score = %d\n", bestMove.x1, bestMove.y1, bestMove.score);
//bestMove = line.moves[0];
}
return bestMove;
}
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
int calculateValue(State *state, int depth) {
if (0 == depth) {
return state->evaluate(FOR_ONE);
}
MovesList list[1];
state->getLegalMoves(list);
int bestValue = -INF;
for (int i = 0; i < list->count; i++) {
state->makeMove(list->moves[i], FOR_ONE);
int value = calculateValue(state, depth - 1);
state->takeMove(list->moves[i], FOR_ONE);
bestValue = max(bestValue, value);
}
return bestValue;
}
Move getBestMove(State *state, int depth, Settings *settings) {
MovesList list[1];
state->getLegalMoves(list);
Move bestMove;
int bestValue = -INF;
for (int i = 0; i < list->count; i++) {
state->makeMove(list->moves[i], FOR_ONE);
int value = calculateValue(state, depth) + list->moves[i].score;
state->takeMove(list->moves[i], FOR_ONE);
checkUp(settings);
if (settings->stopped) {
return bestMove;
}
cerr << outType[list->moves[i].type]
<< " " << list->moves[i].playerId
<< " " << dirOut[list->moves[i].dir1()].c_str()
<< " " << dirOut[list->moves[i].dir2()].c_str()
<< " value = " << value << endl;
if (value > bestValue) {
bestValue = value;
bestMove = list->moves[i];
}
}
return bestMove;
}
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
/*******************************************************************************************/
int main() {
int mapSize;
cin >> mapSize; cin.ignore();
int unitsPerPlayer;
cin >> unitsPerPlayer; cin.ignore();
dir["SE"] = Point(1,1);
dir["E"] = Point(0,1);
dir["NE"] = Point(-1,1);
dir["SW"] = Point(1,-1);
dir["W"] = Point(0,-1);
dir["NW"] = Point(-1,-1);
dir["S"] = Point(1,0);
dir["N"] = Point(-1,0);
dirOut["SE"] = "RD";
dirOut["E"] = "R";
dirOut["NE"] = "RU";
dirOut["SW"] = "LD";
dirOut["W"] = "L";
dirOut["NW"] = "LU";
dirOut["S"] = "D";
dirOut["N"] = "U";
State *state = new State(mapSize);
Move move;
// game loop
while (1) {
// Copy state's map
Player tFirst[2];
Player tSecond[2];
int tMap[MAX_SIZE][MAX_SIZE];
if (state->gameRound) {
tFirst[0].x = state->first[0]->x;
tFirst[0].y = state->first[0]->y;
tFirst[1].x = state->first[1]->x;
tFirst[1].y = state->first[1]->y;
tSecond[0].x = state->second[0]->x;
tSecond[0].y = state->second[0]->y;
tSecond[1].x = state->second[1]->x;
tSecond[1].y = state->second[1]->y;
for (int i = 0; i <= mapSize + 1; i++) {
for (int j = 0; j <= mapSize + 1; j++) {
tMap[i][j] = state->map[i][j];
}
}
}
for (int i = 0; i < mapSize; i++) {
string row;
cin >> row; cin.ignore();
for (int j = 0; j < row.length(); j++) {
if (row[j] == '.') {
state->setValue(i + 1, j + 1, WALL);
} else {
if (row[j] - '0' == 4) {
state->setValue(i + 1, j + 1, WALL);
} else {
state->setValue(i + 1, j + 1, row[j] - '0');
}
}
}
}
int x, y;
// First player (me)
cin >> y >> x; cin.ignore();
state->setPlayer(x + 1, y + 1, 0, 0);
cin >> y >> x; cin.ignore();
state->setPlayer(x + 1, y + 1, 0, 1);
// Second player (opp)
cin >> y >> x; cin.ignore();
state->setPlayer(x + 1, y + 1, 1, 0);
cin >> y >> x; cin.ignore();
state->setPlayer(x + 1, y + 1, 1, 1);
int legalActions;
cin >> legalActions; cin.ignore();
state->print();
if (state->gameRound > 0) {
state->predictOppPosition(tMap, tFirst, tSecond);
}
state->hashKey = state->hash();
string type[200];
int ids[200];
string dir1[200];
string dir2[200];
int value[200];
for (int i = 0; i < legalActions; i++) {
string atype;
int id;
string d1;
string d2;
cin >> atype >> id >> d1 >> d2; cin.ignore();
Player *me = state->first[id];
me->x += dir[d1].first;
me->y += dir[d1].second;
type[i] = atype;
ids[i] = id;
dir1[i] = d1;
dir2[i] = d2;
if (atype == "PUSH&BUILD") {
value[i] = (state->map[me->x][me->y] * state->map[me->x][me->y])
- state->map[me->x + dir[d2].first][me->y + dir[d2].second];
} else {
value[i] = (state->map[me->x][me->y] % 4) +
((state->map[me->x + dir[d2].first]
[me->y + dir[d2].second] + 1) % 4);
}
me->x -= dir[d1].first;
me->y -= dir[d1].second;
}
int maxValue = value[0];
int maxIndex = 0;
for (int i = 0; i < legalActions; i++) {
if (value[i] > maxValue) {
maxValue = value[i];
maxIndex = i;
}
}
cerr << "best " << dirOut[dir1[maxIndex]] << " " << dirOut[dir2[maxIndex]] << endl;
if (legalActions == 0) {
continue;
}
Settings *settings = new Settings();
settings->timeset = TRUE;
settings->stoptime = getTimeMs() + 35;
if (state->oppIsVisible()) {
move = searchPositionIterative(state, settings);
} else {
move = getBestMove(state, 2, settings);
}
state->makeMove(move, FOR_ONE);
state->gameRound++;
cout << outType[move.type]
<< " " << move.playerId
<< " " << move.dir1()
<< " " << move.dir2() << endl;
}
}
<file_sep>#include "stdio.h"
#include "defs.h"
#include "state.h"
#include "pvtable.h"
#include <iostream>
#include <cstdlib>
using namespace std;
int getPvLine(const int depth, State *state) {
ASSERT(depth < MAX_SEARCH_DEPTH && depth >= 1);
MoveTuple move = probePvMove(state);
int count = 0;
while (move.firstDirection != NO_MOVE && count < depth) {
ASSERT(count < MAX_SEARCH_DEPTH);
state->pvArray[count++] = move;
Move firstMove, secondMove;
firstMove.direction = move.firstDirection;
secondMove.direction = move.firstDirection;
// Move players
state->makeMove(firstMove, state->first);
state->makeMove(secondMove, state->second);
state->storePlayersState();
// Move bugs
state->performBugMoves();
// Calculate changes due to collisions
state->pickUpSnippets();
state->pickUpWeapons();
state->collideWithEnemies();
state->collideWithPlayers();
state->round++;
state->hashKey ^= roundHash[state->round - 1];
state->hashKey ^= roundHash[state->round];
move = probePvMove(state);
}
while (state->ply > 0) {
state->round--;
state->restoreBugs();
state->restoreWeapons();
state->restoreSnippets();
state->restorePlayersState();
state->takeMove(state->second);
state->takeMove(state->first);
}
return count;
}
void clearhashTable(HashTable *table) {
HashEntry *tableEntry;
for (tableEntry = table->pTable; tableEntry < table->pTable + table->numEntries; tableEntry++) {
tableEntry->posKey = 0ULL;
MoveTuple nomove;
nomove.firstDirection = NO_MOVE;
nomove.secondDirection = NO_MOVE;
nomove.score = 0;
tableEntry->move = nomove;
tableEntry->depth = 0;
tableEntry->score = 0;
tableEntry->flags = 0;
}
table->newWrite = 0;
}
void initHashTable(HashTable *table, const int MB) {
int hashSize = 0x100000 * MB;
table->numEntries = hashSize / sizeof(HashEntry);
table->numEntries -= 2;
if (table->pTable != NULL) {
free(table->pTable);
}
table->pTable = (HashEntry *) malloc(table->numEntries * sizeof(HashEntry));
if (table->pTable == NULL) {
fprintf(stderr, "HashTable allocation failed, trying %dmb...\n",MB/2);
initHashTable(table, MB / 2);
} else {
clearhashTable(table);
}
}
int probeHashEntry(State *pos, MoveTuple *move, int alpha, int beta, int depth) {
int index = (pos->hashKey ^ pos->pathDependentKey) % pos->hashTable->numEntries;
ASSERT(index >= 0 && index <= pos->hashTable->numEntries - 1);
ASSERT(depth>=1 && depth<MAX_SEARCH_DEPTH);
ASSERT(alpha<beta);
ASSERT(alpha>=-INF && alpha<=INF);
ASSERT(beta>=-INF && beta<=INF);
ASSERT(pos->ply>=0 && pos->ply<MAX_SEARCH_DEPTH);
if (pos->hashTable->pTable[index].posKey == (pos->hashKey ^ pos->pathDependentKey)) {
*move = pos->hashTable->pTable[index].move;
if (pos->hashTable->pTable[index].depth >= depth){
pos->hashTable->hit++;
ASSERT(pos->hashTable->pTable[index].depth>=1&&pos->hashTable->pTable[index].depth<MAX_SEARCH_DEPTH);
return TRUE;
}
}
return FALSE;
}
void storeHashEntry(State *pos, const MoveTuple move, const int depth) {
int index = (pos->hashKey ^ pos->pathDependentKey) % pos->hashTable->numEntries;
ASSERT(index >= 0 && index <= pos->hashTable->numEntries - 1);
ASSERT(depth >= 1 && depth < MAX_SEARCH_DEPTH);
ASSERT(pos->ply >= 0 && pos->ply < MAX_SEARCH_DEPTH);
if (pos->hashTable->pTable[index].posKey == 0) {
pos->hashTable->newWrite++;
} else {
pos->hashTable->overWrite++;
}
pos->hashTable->pTable[index].move = move;
pos->hashTable->pTable[index].posKey = (pos->hashKey ^ pos->pathDependentKey);
pos->hashTable->pTable[index].score = move.score;
pos->hashTable->pTable[index].depth = depth;
}
MoveTuple probePvMove(const State *pos) {
int index = (pos->hashKey ^ pos->pathDependentKey) % pos->hashTable->numEntries;
ASSERT(index >= 0 && index <= pos->hashTable->numEntries - 1);
if (pos->hashTable->pTable[index].posKey == (pos->hashKey ^ pos->pathDependentKey)) {
return pos->hashTable->pTable[index].move;
}
MoveTuple nomove;
nomove.firstDirection = NO_MOVE;
nomove.secondDirection = NO_MOVE;
nomove.score = 0;
return nomove;
}
<file_sep>#ifndef FASTRAND_H_INCLUDED
#define FASTRAND_H_INCLUDED
static unsigned int g_seed;
inline void fast_srand(int seed) {
//Seed the generator
g_seed = seed;
}
inline int fastrand() {
//fastrand routine returns one integer, similar output value range as C lib.
g_seed = (214013*g_seed+2531011);
return (g_seed>>16)&0x7FFF;
}
inline int fastRandInt(int maxSize) {
return fastrand() % maxSize;
}
inline int fastRandInt(int a, int b) {
return(a + fastRandInt(b - a));
}
inline double fastRandDouble() {
return static_cast<double>(fastrand()) / 0x7FFF;
}
inline double fastRandDouble(double a, double b) {
return a + (static_cast<double>(fastrand()) / 0x7FFF)*(b-a);
}
#define RAND_64 ((unsigned long long)fastrand() | \
(unsigned long long)fastrand() << 15 | \
(unsigned long long)fastrand() << 30 | \
(unsigned long long)fastrand() << 45 | \
((unsigned long long)fastrand() & 0xf) << 60 )
#endif // #ifndef FASTRAND_H_INCLUDED
<file_sep>#include "defs.h"
#include "state.h"
//#include "pvtable.h"
#include "misc.h"
#include <string>
#include <iostream>
#include <cmath>
int rootDepth;
static double AlphaBeta(int alpha, int beta, int depth, State *state, SearchInfo *info);
static void checkUp(SearchInfo *info) {
// Check if time is up
if(info->timeset == TRUE && getTimeMs() > info->stoptime) {
info->stopped = TRUE;
}
}
static void clearForSearch(State *state, SearchInfo *info) {
int index = 0;
int index2 = 0;
state->ply = 0;
info->stopped = 0;
info->nodes = 0;
info->fh = 0;
info->fhf = 0;
}
static int chooseRow(double scores[MAX_MOVES][MAX_MOVES], int rowMoves, int colMoves) {
int rowIndex = -1;
double rowScore = -INF;
for(int i = 0; i < rowMoves; i++) {
double rowMin = INF;
for(int j = 0; j < colMoves; j++) {
if (scores[i][j] < rowMin) {
rowMin = scores[i][j];
}
}
if (rowMin > rowScore) {
rowScore = rowMin;
rowIndex = i;
}
ASSERT(rowMin != INF);
}
ASSERT(rowIndex >= 0);
return rowIndex;
}
static int chooseCol(double scores[MAX_MOVES][MAX_MOVES], int rowMoves, int colMoves) {
int colIndex = -1;
double colScore = INF;
for(int j = 0; j < colMoves; j++) {
double colMax = -INF;
for(int i = 0; i < rowMoves; i++) {
if (scores[i][j] > colMax) {
colMax = scores[i][j];
}
}
if (colMax < colScore) {
colScore = colMax;
colIndex = j;
}
ASSERT(colMax != INF);
}
ASSERT(colIndex >= 0);
return colIndex;
}
static MoveTuple minimax(int alpha, int beta, int depth, State *state, SearchInfo *info) {
MovesList listFirst[1];
MovesList listSecond[1];
state->getLegalMoves(listFirst, state->first);
state->getLegalMoves(listSecond, state->second);
double scores[MAX_MOVES][MAX_MOVES];
int rowMoves = listFirst->nMoves;
int colMoves = listSecond->nMoves;
MoveTuple answer;
info->nodes++;
//if(probeHashEntry(state, &answer, alpha, beta, depth) == TRUE) {
// state->hashTable->cut++;
// return answer;
//}
for(int i = 0; i < rowMoves; i++) {
for(int j = 0; j < colMoves; j++) {
//U64 stateHashKey = state->hashKey;
// Move players
state->makeMove(listFirst->moves[i], state->first);
state->makeMove(listSecond->moves[j], state->second);
state->storePlayersState();
// Move bugs
state->performBugMoves();
// Calculate changes due to collisions
state->pickUpSnippets();
state->pickUpWeapons();
state->collideWithEnemies();
state->collideWithPlayers();
state->round++;
//state->hashKey ^= roundHash[state->round - 1];
//state->hashKey ^= roundHash[state->round];
// Recursive call
scores[i][j] = AlphaBeta(-beta, -alpha, depth - 1, state, info);
state->round--;
state->restoreBugs();
state->restoreWeapons();
state->restoreSnippets();
state->restorePlayersState();
state->takeMove(state->second);
state->takeMove(state->first);
//state->hashKey = stateHashKey;
}
}
int row = chooseRow(scores, rowMoves, colMoves);
int col = chooseCol(scores, rowMoves, colMoves);
if(info->stopped == TRUE) {
answer.firstDirection = NO_MOVE;
answer.secondDirection = NO_MOVE;
answer.score = 0;
} else {
answer.firstDirection = listFirst->moves[row].direction;
answer.secondDirection = listSecond->moves[col].direction;
answer.score = scores[row][col];
//storeHashEntry(state, answer, depth);
}
return answer;
}
static double AlphaBeta(int alpha, int beta, int depth, State *state, SearchInfo *info) {
ASSERT(beta > alpha);
ASSERT(depth >= 0);
// TERMINAL STATE
// Check for 200 rounds
if (depth <= 0 || state->ply >= MAX_SEARCH_DEPTH || state->round >= 201) {
return state->evaluate();
}
MovesList listFirst[1];
MovesList listSecond[1];
state->getLegalMoves(listFirst, state->first);
state->getLegalMoves(listSecond, state->second);
if ((info->nodes & 15) == 0) {
checkUp(info);
}
info->nodes++;
MoveTuple answer;
//if(probeHashEntry(state, &answer, alpha, beta, depth) == TRUE) {
// state->hashTable->cut++;
// return answer.score;
//}
double scores[MAX_MOVES][MAX_MOVES];
int rowMoves = listFirst->nMoves;
int colMoves = listSecond->nMoves;
for(int i = 0; i < rowMoves; i++) {
for(int j = 0; j < colMoves; j++) {
//U64 stateHashKey = state->hashKey;
// Move players
state->makeMove(listFirst->moves[i], state->first);
state->makeMove(listSecond->moves[j], state->second);
state->storePlayersState();
// Move bugs
state->performBugMoves();
// Calculate changes due to collisions
state->pickUpSnippets();
state->pickUpWeapons();
state->collideWithEnemies();
state->collideWithPlayers();
if (state->snippetsEaten % ENEMY_APPEAR_RATE != 0) {
state->enemySpawned = false;
}
state->round++;
//state->hashKey ^= roundHash[state->round - 1];
//state->hashKey ^= roundHash[state->round];
// Recursive call
scores[i][j] = AlphaBeta(-beta, -alpha, depth - 1, state, info);
state->round--;
state->restoreBugs();
state->restoreWeapons();
state->restoreSnippets();
state->restorePlayersState();
state->takeMove(state->second);
state->takeMove(state->first);
//state->hashKey = stateHashKey;
if(info->stopped == TRUE) {
return 0;
}
}
}
int row = chooseRow(scores, rowMoves, colMoves);
int col = chooseCol(scores, rowMoves, colMoves);
answer.firstDirection = listFirst->moves[row].direction;
answer.secondDirection = listSecond->moves[col].direction;
answer.score = scores[row][col];
//storeHashEntry(state, answer, depth);
return scores[row][col];
}
Move searchPosition(State *state, SearchInfo *info, int playerId) {
MoveTuple bestMove;
int pvMoves = 0;
clearForSearch(state, info);
// Iterative deepening
for(int currentDepth = 1; currentDepth <= info->depth; currentDepth++) {
MoveTuple currentBest = minimax(-INF, INF, currentDepth, state, info);
if (currentBest.firstDirection != NO_MOVE) {
if (info->debug == TRUE) {
fprintf(stderr, "first = %s second = %s\n",
output[currentBest.firstDirection].c_str(),
output[currentBest.secondDirection].c_str()
);
}
bestMove = currentBest;
}
if(info->stopped == TRUE) {
break;
}
//pvMoves = getPvLine(currentDepth, state);
//bestMove = state->pvArray[0];
if (info->debug == TRUE) {
fprintf(stderr,"score:%f depth:%d nodes:%ld time:%d(ms) \n",
bestMove.score, currentDepth, info->nodes, getTimeMs() - info->starttime);
}
}
Move move;
move.direction = PLAYER0 == playerId ?
bestMove.firstDirection :
bestMove.secondDirection;
move.score = bestMove.score;
return move;
}
<file_sep>#ifndef SEARCH_H_INCLUDED
#define SEARCH_H_INCLUDED
#include "defs.h"
#include "state.h"
Move searchPosition(State *state, SearchInfo *info, int playerId);
#endif //#ifndef SEARCH_H_INCLUDED
| 204eb0cc61975a1fa56f14f837cadc9e4f1805fd | [
"Java",
"C",
"C++",
"Markdown"
]
| 15 | C | subtleB/AI-Competitions | 866132794c938641cf535b71c2c91b1810a542f3 | cae920489c09476af9edd0c275b0fd745160b079 |
refs/heads/master | <repo_name>ali-of-cia/Etch-E-Sketch<file_sep>/script.js
$(document).ready(function() {
/* Create the Grid */
var grid = 64;
createGrid(grid);
makePretty();
/* Create a new sketch */
$('#sketch').click(function(){
$('.square').remove();
grid = parseInt(prompt('What size grid? Choose 100-1.'));
if (grid > 100) {
grid = 100
} else if (grid < 1) {
grid = 1;
}
createGrid(grid);
makePretty();
});
});
function makePretty(){
$('.square').mouseenter(function() {
$(this).addClass('tracer');
$(this).mouseleave(function() {
$(this).fadeTo('slow', 0.5);
});
});
}
function createGrid(numBoxes) {
for (var i = 0; i < (numBoxes * numBoxes); i++) {
$('<div/>', {
'class' : 'square',
}).appendTo('#grid');
}
/* Grid will be 600 pixels */
var squareSize = 600 / numBoxes;
$('.square').css({
'height': squareSize,
'width' : squareSize
});
}
<file_sep>/README.md
# Etch-E-Sketch
Ethh-E-Sketch made using jquery.
| 799d7465174f9cb47d09b9a26a5250ae36aa7873 | [
"JavaScript",
"Markdown"
]
| 2 | JavaScript | ali-of-cia/Etch-E-Sketch | 77482e6130c02fee802ba96cfe1c9b1dd5562a49 | e1bd7b1dd502de4dab3a3fb45ffee1b25bca886d |
refs/heads/master | <repo_name>jeffschwartz/express-modularized-middleware-routing<file_sep>/routes/main.js
/**
* Created with JetBrains WebStorm.
* User: jeffrey
* Date: 8/25/12
* Time: 3:55 PM
* To change this template use File | Settings | File Templates.
*/
var app = require("../app").app;
var exposeDb = require("../middleware/exposedb").exposeDb;
app.get('/', exposeDb, function(req, res){
var mongoDb = req.mongoDb;
var expose = "";
if(mongoDb){
expose = "index route has access to mongo";
}else{
expose = "index route doesn't have access to mongo";
}
res.render('index', { title: 'Express', expose: expose });
});<file_sep>/README.md
express-modularized-middleware-routing
======================================
Shows how to take advantage of Node's modular system to structure your
application. Implements route specific middleware as an example.
<file_sep>/middleware/exposedb.js
/**
* Created with JetBrains WebStorm.
* User: jeffrey
* Date: 8/25/12
* Time: 5:28 PM
* To change this template use File | Settings | File Templates.
*/
var db = require("../app").db;
// route specific middleware - will expose the database to route
exports.exposeDb = function(req, resp, next){
req.mongoDb = db;
next();
};
| 327b2ee297a28d33e4655d85f13dc3884f810d1a | [
"JavaScript",
"Markdown"
]
| 3 | JavaScript | jeffschwartz/express-modularized-middleware-routing | 70d96cb0b570782f810dc38a6a1194b15d04dffb | 6710dd7dc6b406add6017df6d76faf05c574ce41 |
refs/heads/main | <repo_name>EvanXwang/Line_bot<file_sep>/Nodejs_line_bot/01_basic_line_bot/app.js
// 引用linebot SDK
var linebot = require('linebot');
// 用於辨識Line Channel的資訊
var bot = linebot({
channelId: '替換成你的CHANNEL_ID',
channelSecret: '替換成你的CHANNEL_SECRET',
channelAccessToken: '替換成你的CHANNEL_ACCESS_TOKEN'
});
// 當有人傳送訊息給Bot時
// 處理「 訊息 」事件
bot.on('message', function (event) {
// event.message.text是使用者傳給bot的訊息
// 使用event.reply(要回傳的訊息)方法可將訊息回傳給使用者
event.reply(event.message.text).then(function (data) {
// 處理回覆成功的程式碼
}).catch(function (error) {
// 處理回覆失敗的程式碼
});
});
// Bot所監聽的webhook路徑與port
bot.listen('/linewebhook', 3000, function () {
console.log('[BOT已準備就緒]');
});<file_sep>/Nodejs_line_bot/01_basic_line_bot/README.md
# node.js line_bot basic Echo Bot
### 執行步驟
1. npm install linebot --save
2. node app.js
3. ngrok http 3000
### line developers設定
1. Webhook URL 需加入 > ngrok產生https網址/linewebhook<file_sep>/Nodejs_line_bot/03_echo/app.js
const express = require('express');
const botRouter = require('./lib/myLine/botRouter');
require('dotenv').config();
var app = express();
const port = process.env.PORT || 3000;
app.use(botRouter);
app.listen(port, () => {
console.log(`listening on ${port}`);
});
module.exports = app;<file_sep>/Nodejs_line_bot/03_echo/lib/myLine/bot.js
const line = require('@line/bot-sdk');
require('dotenv').config();
// create LINE SDK config from env variables
const config = {
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.CHANNEL_SECRET,
};
const client = new line.Client(config);
const middleware = line.middleware(config);
module.exports = {
middleware : middleware,
lineClient : client
};<file_sep>/Nodejs_line_bot/03_echo/lib/myLine/botRouter.js
const express = require('express');
const router = express.Router();
const middleware = require('./bot').middleware;
const eventHandler = require('./eventHandler');
router.post('/callback', middleware, (req, res) => {
Promise
.all(req.body.events.map(eventHandler))
.then((result) => res.json(result))
.catch((err) => {
console.error(err);
res.status(500).end();
});
});
module.exports = router; | f28cfce8d8c3f006f3abd6a4e702e0a1a49e3fd0 | [
"JavaScript",
"Markdown"
]
| 5 | JavaScript | EvanXwang/Line_bot | 5b1cb7790b21592940a60c4bda5ff8a24c1302bd | 2aa59cb8ebbc625ea8fd742105d210adfc64c4db |
refs/heads/main | <repo_name>NotXia/pathfinding<file_sep>/js/algorithms/a_star.js
import { adjacent_nodes_s, adjacent_nodes_d, draw_path } from '../finder.js'
async function a_star_d(grid) {
await a_star(grid, adjacent_nodes_d, chebyshev_distance);
}
async function a_star_s(grid) {
await a_star(grid, adjacent_nodes_s, manhattan_distance);
}
function manhattan_distance(node_coord, end_coord) {
let dist_x = Math.abs(node_coord.getX() - end_coord.getX());
let dist_y = Math.abs(node_coord.getY() - end_coord.getY());
return (dist_x + dist_y);
}
function chebyshev_distance(node_coord, end_coord) {
let dist_x = Math.abs(node_coord.getX() - end_coord.getX());
let dist_y = Math.abs(node_coord.getY() - end_coord.getY());
return Math.max(dist_x, dist_y);
}
async function a_star(grid, adjacent_nodes_function, heuristic) {
var start_coord = grid.getStart();
var end_coord = grid.getEnd();
grid.setCurrentMode(VISITED_TILE);
var cost_to = {};
var best_node_to = {};
var to_visit = [];
for (let x = 0; x < grid.getColumns(); x++) {
for (let y = 0; y < grid.getRows(); y++) {
best_node_to[new Coord(x, y).toString()] = undefined;
cost_to[new Coord(x, y).toString()] = Infinity;
}
}
cost_to[start_coord.toString()] = 0;
best_node_to[start_coord.toString()] = start_coord;
to_visit.push([start_coord, Number(heuristic(start_coord, end_coord))]);
while (to_visit.length > 0) {
let curr_coord = to_visit.shift()[0];
if (curr_coord.equals(end_coord)) {
break;
}
if (!curr_coord.equals(start_coord) && !curr_coord.equals(end_coord)) {
grid.draw(curr_coord);
}
await new Promise(r => setTimeout(r, ANIMATION_SPEED));
adjacent_nodes_function(grid, curr_coord).forEach(near_node => {
if (Number(cost_to[curr_coord.toString()]) + Number(grid.getCostAt(near_node)) < cost_to[near_node.toString()]) {
cost_to[near_node.toString()] = Number(cost_to[curr_coord.toString()]) + Number(grid.getCostAt(near_node));
best_node_to[near_node.toString()] = curr_coord;
to_visit.push([near_node, Number(cost_to[near_node.toString()] + heuristic(near_node, end_coord)) ]);
to_visit.sort(function (a, b) {
return a[1] - b[1];
});
}
});
}
var final_path = [];
var node = end_coord;
if (best_node_to[node.toString()] !== undefined) {
final_path.push(end_coord);
while (!node.equals(start_coord)) {
node = best_node_to[node.toString()];
final_path.push(node);
}
}
await draw_path(grid, final_path.reverse());
}
export { a_star_d, a_star_s };<file_sep>/js/algorithms/bfs.js
import { adjacent_nodes_s, adjacent_nodes_d, draw_path } from '../finder.js'
async function bfs_d(grid) {
await bfs(grid, adjacent_nodes_d);
}
async function bfs_s(grid) {
await bfs(grid, adjacent_nodes_s);
}
async function bfs(grid, adjacent_nodes_function) {
var start_coord = grid.getStart();
var end_coord = grid.getEnd();
grid.setCurrentMode(VISITED_TILE);
var to_visit = [];
var visited = [];
var final_path = [];
to_visit.push([start_coord, []]);
visited[start_coord.toString()] = true;
while (to_visit.length > 0) {
let curr_coord = to_visit.shift();
if (curr_coord[0].equals(end_coord)) {
final_path = curr_coord[1];
final_path.push(end_coord);
break;
}
if (!curr_coord[0].equals(start_coord)) {
grid.draw(curr_coord[0]);
await new Promise(r => setTimeout(r, ANIMATION_SPEED));
}
adjacent_nodes_function(grid, curr_coord[0]).forEach(near_node => {
if (visited[near_node.toString()] === undefined) {
let path = curr_coord[1].slice();
path.push(curr_coord[0]);
to_visit.push([near_node, path]);
visited[near_node.toString()] = true;
}
});
}
await draw_path(grid, final_path);
}
export { bfs_d, bfs_s };
<file_sep>/js/grid.js
const WALL_TILE = 0;
const ROAD_TILE = 1;
const START_TILE = 2;
const END_TILE = 3;
const VISITED_TILE = 4;
const PATH_TILE = 5;
const COST_TILE = 6;
const NORTH = 0;
const SOUTH = 1;
const EAST = 2;
const WEST = 3;
const NORTH_EAST = 4;
const NORTH_WEST = 5;
const SOUTH_EAST = 6;
const SOUTH_WEST = 7;
const DEFAULT_COST = 1;
class Coord {
constructor(x, y) {
this.x = x;
this.y = y;
}
getX() {
return this.x;
}
getY() {
return this.y;
}
equals(coord) {
if (coord === undefined) {
return false;
}
else {
return this.x == coord.getX() && this.y == coord.getY();
}
}
toString() {
return "(" + this.x + ";" + this.y + ")";
}
}
class Grid {
constructor(container_id, columns, rows, cost_input_id) {
this.container_id = container_id;
this.columns = columns;
this.rows = rows;
this.cost_input = cost_input_id
this.show_cost = true;
this.drawing = false;
this.curr_mode = WALL_TILE;
// Initializes all the tiles
this.matrix = [];
for (let x = 0; x < columns; x++) {
this.matrix[x] = [];
for (let y = 0; y < rows; y++) {
this.matrix[x][y] = { type: ROAD_TILE, cost: DEFAULT_COST };
}
}
this.render();
}
getColumns() {
return this.columns;
}
getRows() {
return this.rows;
}
getMatrix() {
return this.matrix;
}
/* Gets the Coord object of the starting point */
getStart() {
for (let i = 0; i < this.columns; i++) {
for (let j = 0; j < this.rows; j++) {
if (this.matrix[i][j].type == START_TILE) {
return new Coord(i, j)
}
}
}
return undefined;
}
/* Gets the Coord object of the ending point */
getEnd() {
for (let i = 0; i < this.columns; i++) {
for (let j = 0; j < this.rows; j++) {
if (this.matrix[i][j].type == END_TILE) {
return new Coord(i, j)
}
}
}
return undefined;
}
/* Returns an identifier for the tile at the given coordinate */
getSquareId(coord) {
return this.container_id + "-" + coord.getX() + "-" + coord.getY();
}
getCostAt(coord) {
return this.matrix[coord.getX()][coord.getY()].cost;
}
/* Displays the grid */
render() {
// Generation the grid container
var grid = document.createElement("div");
grid.className = "grid-container";
grid.id = this.container_id + "grid-container";
// Generation of all the squares
for (let y = 0; y < this.rows; y++) {
for (let x = 0; x < this.columns; x++) {
var square = document.createElement("div");
square.className = "square tile" + this.matrix[x][y].type;
square.id = this.getSquareId(new Coord(x, y));
let grid_class = this;
let coord = new Coord(x, y)
square.addEventListener("mouseover", function () {
if (grid_class.drawing) {
grid_class.draw(coord);
}
}, false);
square.addEventListener("mousedown", function (event) {
event.preventDefault();
grid_class.drawing = true;
grid_class.draw(coord);
}, false);
square.addEventListener("mouseup", function () {
grid_class.drawing = false;
}, false);
/* For mobile */
square.addEventListener("touchstart", function () {
grid_class.drawing = true;
grid_class.draw(coord);
}, false);
square.addEventListener("touchend", function () {
grid_class.drawing = false;
}, false);
grid.appendChild(square);
}
}
/* For mobile */
let grid_class = this;
grid.addEventListener("touchmove", function (event) {
event.preventDefault();
if (grid_class.drawing) {
let coord_parts = document.elementFromPoint(event.touches[0].pageX, event.touches[0].pageY).id.split("-");
grid_class.draw(new Coord(coord_parts[1], coord_parts[2]));
}
}, false);
document.getElementById(this.container_id).innerHTML = "";
document.getElementById(this.container_id).appendChild(grid);
this.scale();
/* Showing cost for each tile (if needed) */
for (let y = 0; y < this.rows; y++) {
for (let x = 0; x < this.columns; x++) {
this.showCostAt(new Coord(x, y));
}
}
}
/* Scales the grid */
scale() {
var container = document.getElementById(this.container_id);
var grid = document.getElementById(this.container_id + "grid-container");
var square_size = Math.min(container.clientWidth / this.columns, container.clientHeight / this.rows);
grid.style.width = (square_size * this.columns) + "px";
grid.style.height = (square_size * this.rows) + "px";
grid.style.gridTemplateColumns = (square_size + "px ").repeat(this.columns);
grid.style.gridTemplateRows = (square_size + "px ").repeat(this.rows);
}
/* Resizes the grid and renders it */
resize(new_columns, new_rows) {
if (new_columns > this.columns) {
for (let i = 0; i < (new_columns - this.columns); i++) {
var new_row = [];
for (let j = 0; j < new_rows; j++) {
new_row.push({ type: ROAD_TILE, cost: 1 });
}
this.matrix.push(new_row);
}
}
else if (new_columns < this.columns) {
for (let i = 0; i < (this.columns - new_columns); i++) {
this.matrix.pop();
}
}
this.columns = new_columns;
if (new_rows > this.rows) {
for (let i = 0; i < this.columns; i++) {
for (let j = 0; j < (new_rows - this.rows); j++) {
this.matrix[i][this.rows + j] = { type: ROAD_TILE, cost: 1 };
}
}
}
else if (new_rows < this.rows) {
for (let i = 0; i < this.columns; i++) {
for (let j = 0; j < (this.rows - new_rows); j++) {
this.matrix[i].pop();
}
}
}
this.rows = new_rows;
this.render();
}
/* Removes from the matrix all the visited node and the final path of the previous search */
reset() {
for (let i = 0; i < this.columns; i++) {
for (let j = 0; j < this.rows; j++) {
if (this.matrix[i][j].type == VISITED_TILE || this.matrix[i][j].type == PATH_TILE) {
this.matrix[i][j].type = ROAD_TILE;
}
}
}
this.render();
}
/* Shows the weight of each node */
showCost() {
this.show_cost = true;
for (let y = 0; y < this.rows; y++) {
for (let x = 0; x < this.columns; x++) {
this.showCostAt(new Coord(x, y));
}
}
}
/* Hides the weight of each node */
hideCost() {
this.show_cost = false;
for (let y = 0; y < this.rows; y++) {
for (let x = 0; x < this.columns; x++) {
var square = document.getElementById(this.getSquareId(new Coord(x, y)));
square.innerHTML = "";
}
}
}
/* Displays the weight of the square at the given coordinate */
showCostAt(coord) {
var square = document.getElementById(this.getSquareId(coord));
if (this.show_cost) {
if (([WALL_TILE, START_TILE, END_TILE]).includes(this.matrix[coord.getX()][coord.getY()].type)) {
square.innerHTML = "";
}
else {
square.innerHTML = this.getCostAt(coord);
}
}
else {
square.innerHTML = "";
}
}
setCurrentMode(mode) {
this.curr_mode = mode;
}
/* Handles the type change of the given coordinate */
draw(coord) {
switch (this.curr_mode) {
case WALL_TILE:
this.setWall(coord);
break;
case ROAD_TILE:
this.setRoad(coord);
break;
case START_TILE:
this.setStart(coord);
break;
case END_TILE:
this.setEnd(coord);
break;
case VISITED_TILE:
this.setVisited(coord);
break;
case PATH_TILE:
this.setPath(coord);
break;
case COST_TILE:
this.setCost(coord, document.getElementById(this.cost_input).value);
break;
}
}
/* Changes the type of the tile at the given coordinate */
setAt(coord, type) {
var square = document.getElementById(this.getSquareId(coord));
square.classList.remove(
"tile0", "tile1", "tile2", "tile3", "tile4", "tile5",
"direction0", "direction1", "direction2", "direction3", "direction4", "direction5", "direction6", "direction7"
);
square.classList.add("tile" + type);
this.matrix[coord.getX()][coord.getY()].type = type;
this.showCostAt(coord);
}
setWall(coord) {
this.setCost(coord, DEFAULT_COST);
this.setAt(coord, WALL_TILE);
}
setRoad(coord) {
this.setAt(coord, ROAD_TILE);
}
setStart(coord) {
var start_coord = this.getStart();
if (start_coord !== undefined) {
this.setAt(start_coord, ROAD_TILE);
}
this.setCost(coord, DEFAULT_COST);
this.setAt(coord, START_TILE);
}
setEnd(coord) {
var end_coord = this.getEnd();
if (end_coord !== undefined) {
this.setAt(end_coord, ROAD_TILE);
}
this.setCost(coord, DEFAULT_COST);
this.setAt(coord, END_TILE);
}
setVisited(coord) {
this.setAt(coord, VISITED_TILE);
}
setPath(coord) {
this.setAt(coord, PATH_TILE);
}
setCost(coord, cost) {
if (!([WALL_TILE, START_TILE, END_TILE]).includes(this.matrix[coord.getX()][coord.getY()].type)) {
if (cost >= 0) {
this.matrix[coord.getX()][coord.getY()].cost = cost;
}
else {
this.matrix[coord.getX()][coord.getY()].cost = DEFAULT_COST;
}
this.showCostAt(coord);
}
}
setDirection(coord, direction) {
var square = document.getElementById(this.getSquareId(coord));
square.classList.add("direction" + direction);
}
/* Locks the grid, preventing any action */
lock() {
document.getElementById(this.container_id).classList.add("lock");
}
/* Unloocks the grid */
unlock() {
document.getElementById(this.container_id).classList.remove("lock");
}
/* Checks if the start and the end nodes are set */
isValid() {
return (this.getStart() !== undefined) && (this.getEnd() !== undefined);
}
}
<file_sep>/js/algorithms/dijkstra.js
import { adjacent_nodes_s, adjacent_nodes_d, draw_path } from '../finder.js'
async function dijkstra_d(grid) {
await dijkstra(grid, adjacent_nodes_d);
}
async function dijkstra_s(grid) {
await dijkstra(grid, adjacent_nodes_s);
}
async function dijkstra(grid, adjacent_nodes_function) {
var start_coord = grid.getStart();
var end_coord = grid.getEnd();
grid.setCurrentMode(VISITED_TILE);
var cost_to = {};
var best_node_to = {};
var to_visit = [];
for (let x=0; x<grid.getColumns(); x++) {
for (let y=0; y<grid.getRows(); y++) {
best_node_to[new Coord(x, y).toString()] = undefined;
cost_to[new Coord(x, y).toString()] = Infinity;
}
}
cost_to[start_coord.toString()] = 0;
best_node_to[start_coord.toString()] = start_coord;
to_visit.push([start_coord, 0]);
while (to_visit.length > 0) {
let curr_coord = to_visit.shift()[0];
if (curr_coord.equals(end_coord)) {
break;
}
if (!curr_coord.equals(start_coord) && !curr_coord.equals(end_coord)) {
grid.draw(curr_coord);
}
await new Promise(r => setTimeout(r, ANIMATION_SPEED));
adjacent_nodes_function(grid, curr_coord).forEach(near_node => {
if (Number(cost_to[curr_coord.toString()]) + Number(grid.getCostAt(near_node)) < cost_to[near_node.toString()]) {
cost_to[near_node.toString()] = Number(cost_to[curr_coord.toString()]) + Number(grid.getCostAt(near_node));
best_node_to[near_node.toString()] = curr_coord;
to_visit.push([near_node, cost_to[near_node.toString()]]);
to_visit.sort(function(a, b) {
return a[1] - b[1];
});
}
});
}
var final_path = [];
var node = end_coord;
if (best_node_to[node.toString()] !== undefined) {
final_path.push(end_coord);
while (!node.equals(start_coord)) {
node = best_node_to[node.toString()];
final_path.push(node);
}
}
await draw_path(grid, final_path.reverse());
}
export { dijkstra_d, dijkstra_s };
<file_sep>/README.md
# Pathfinding
## Introduction
A simple pathfinding visualizer with the following algorithms:
- Breadth First Search
- Depth First Search
- Dijkstra
- A*
## Demo
https://notxia.github.io/pathfinding-visualizer/
| 6f305fc206fc5fa2ac1458546ee0599f49adda2b | [
"JavaScript",
"Markdown"
]
| 5 | JavaScript | NotXia/pathfinding | 0d22d5bee07f1c2484360a3a7f52dc313ef7f064 | 56be677137710c268a89474686d6d1c914145b6c |
refs/heads/master | <repo_name>kushal90/Demo_Html<file_sep>/js/script.js
let skills = ["Javascript", "Node.js", "BrowserSync", "npm"];
let skillPosition = -1;
function writeText() {
if (skillPosition === skills.length-1)
skillPosition = 0;
else
skillPosition += 1;
if (skillPosition === 0)
document.getElementsByClassName("c-main-text-dynamic-text")[0].innerHTML = skills[skillPosition];
document.getElementsByClassName("c-main-text-dynamic-text")[0].innerHTML = skills[skillPosition];
}
// Animating the burger and opening the navigation menu on small screen devices.
let burger = document.getElementsByClassName("c-navigation-burger")[0];
burger.addEventListener("click", () =>
{
burger.classList.toggle("c-navigation-burger__clicked");
document.getElementsByClassName("c-all-content-links")[0].classList.toggle("c-all-content-links__active");
});
// To position profile pic in the centre.
function positionProfilePic() {
let w = window.innerWidth;
let h = window.innerHeight;
let profilePic = document.getElementsByClassName("c-profile-pic-and-icons-profile-pic")[0];
let marginLeft = (w-profilePic.width)
- (w-profilePic.width-document.getElementsByClassName("c-profile-pic-and-icons-social-icons-link-github")[0].width) + profilePic.width*4/100;
profilePic.setAttribute("style", `margin-left: ${marginLeft}px`);
}
let interval = setInterval(writeText, 1000);
positionProfilePic(); | 5a500776484f2678d99078ecb5bc9d2e364b0986 | [
"JavaScript"
]
| 1 | JavaScript | kushal90/Demo_Html | e5669894a22fb20c00fe4eaaa7879264577ed6c7 | 3e31538b198e9796a17028278b547d40accf27ac |
refs/heads/master | <file_sep>document.write('<div class="header">'+
'<div class="bg">透明背景层</div>'+
'<h1 class="logo">'+
'<a href="#">VIBE UI</a>'+
'</h1>'+
'<span class="menuCtrl" id="menuCtrl">菜单</span>'+
'<div class="menuContainer" id="menuContainer">'+
'<ul class="menu">'+
'<li><a href="index.html" data-page-name="index">首页</a></li>'+
'<li><a href="feature.html" data-page-name="feature">功能</a></li>'+
'<li><a href="download.html" data-page-name="download">下载</a></li>'+
'<li><a href="http://bbs.lenovo.com/vibeui/">论坛</a></li>'+
'<li><a href="http://www.lenovo.com">联想官网</a></li>'+
'</ul>'+
'<div class="codeImages">'+
'<div class="info">'+
'扫码关注<br>VIBE UI'+
'</div>'+
'<div class="cols col2 images">'+
'<div class="col weiXin">'+
'微信'+
'</div>'+
'<div class="col weiBo">'+
'微博'+
'</div>'+
'</div>'+
'</div>'+
'</div>'+
'</div>'); | 439ee413766d3204747dda1440ad6a198131c8a2 | [
"JavaScript"
]
| 1 | JavaScript | zyhndesign/lianxiang | 366e50fb735ea6f279f72f7193e60aa14e71107e | 3bd21c4f3d89611a6478c9e87698af7bf1ceffee |
refs/heads/master | <repo_name>kanglewu/acm_test<file_sep>/src/com/poj/Main2752.java
package com.poj;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
/**
* 2752 KMP
*
* @author wuyq101
* @version 1.0
*/
public class Main2752 {
private static char[] s = new char[400000];
private static int N;
private static int[] t = new int[400001];
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
String w = cin.next();
N = w.length();
w.getChars(0, N, s, 0);
if (N == 1) {
System.out.println(1);
continue;
}
kmp_table();
solve();
}
}
private static void solve() {
Set<Integer> set = new TreeSet<Integer>();
int i = N;
while (t[i] > 0) {
set.add(t[i]);
i = t[i];
}
set.add(N);
StringBuilder sb = new StringBuilder();
for (int j : set) {
sb.append(j).append(' ');
}
System.out.println(sb.substring(0, sb.length() - 1));
}
private static void kmp_table() {
t[0] = -1;
t[1] = 0;
// the current position we are computing in T
int pos = 2;
// the zero-based index in W of the next character of the current candidate substring
int cnd = 0;
int ls = s.length;
while (pos <= ls) {
// first case: the substring continues
if (s[pos - 1] == s[cnd]) {
cnd = cnd + 1;
t[pos] = cnd;
pos = pos + 1;
} else if (cnd > 0) {
cnd = t[cnd];
} else {
t[pos] = 0;
pos = pos + 1;
}
}
}
}
| 6927b2757688e6773781c2f3f00a53f40646340d | [
"Java"
]
| 1 | Java | kanglewu/acm_test | 227b8a34b4c141d1d9f43296c2a0415f8755b7fb | 5cdcade0432318d3a9e9b3f351e105b7b411afcd |
refs/heads/master | <file_sep>def loadingManager():
path, mode, content = "dziennik.txt", "r", []
f = open(path, mode, encoding = "utf-8-sig")
content = f.readlines()
content = list(map(lambda s: int(s.strip()), content))
return content
def ex1And3(content):
start, cnt, amm, best, bestArr = content[0], 0, 0, 0,[]
message = ["<NAME> {} pozytywnych serii treningowych", "Najdłuższa seria trwała {} dni"]
for i in range(len(content)):
if cnt > 3:
cnt, amm = 0, amm+1
cur = content[i]
if not i == 0 and content[i-1] > cur:
bestArr.append(best)
best = 0
continue
cnt += 1
best += 1
print((message[0]).format(amm))
print((message[1]).format(max(bestArr)))
def ex2(content):
m1, m2, m1i, m2i = max(content), min(content), content.index(max(content)), content.index(min(content))
print(("Max: {} (dzień {})\nMin: {} (dzień {})").format(m1,m1i,m2,m2i))
content = loadingManager()
ex1And3(content)
ex2(content)
<file_sep>global directions
global N,E,S,W
global board
N,E,S,W = 'N', 'E', 'S', 'W'
directions = { N: -19, E: 1, S: 19, W: -1}
def fileManager(path, mode = "r", content = ""):
f = open(path, mode, encoding = 'utf-8-sig')
if mode == "r":
content = f.readlines()
content = [content.split() for content in content]
return content
else:
f.writelines(content)
f.close()
return None
board = fileManager("plansza.txt")
def isOutOfBounds(player):
vertical, horizontal, p = 0, 0, None
for i in range(len(player)):
currentPlayer = player[i] ##wtf Python
## print(currentPlayer)
for j in range(len(currentPlayer)):
p = currentPlayer[j]
## ugly, but works
if p == 'N':
vertical += directions[N]
if p == 'S':
vertical += directions[S]
if p == 'E':
horizontal += directions[E]
if p == 'W':
horizontal += directions[W]
if vertical < 0 or vertical > 20:
return True
if horizontal < 0 or horizontal > 20:
return True
else:
return False
def isScore(vertical, horizontal):
tile = board[vertical][horizontal]
if tile != 0:
return tile
else:
return None
def isMax(player):
biggest, index = 0, 0
toReturn = [index, biggest]
score = 3 ##everyone starts on field with 3 points
##if it looks stupid but works, it ain't stupid!
for i in range(len(player)):
vertical, horizontal = 0, 0
unpacked = player[i]
for j in range(len(unpacked)):
p = unpacked[j]
if p == 'N':
vertical += directions[W]
if p == 'S':
vertical += directions[E]
if p == 'E':
horizontal += directions[E]
if p == 'W':
horizontal += directions[W]
if not isScore(vertical, horizontal) is None:
score += int(isScore(vertical, horizontal))
if score > biggest:
print(score)
biggest = score
toReturn = [index, biggest]
print(toReturn)
return toReturn
def disAndMax():
players = fileManager("robot.txt")
player, disqualified, remaining = None, 0, [] ##remaining = list of remaining players indexes
##check for disqualified players
for i in range(len(players)):
player = players[i]
#print(player)
if isOutOfBounds(player):
disqualified += 1
else:
remaining.append(i)
string = "Liczba graczy zdyskwalifokowanych: " + str(disqualified)
return string
## ##check which remaining player has the biggest score
## biggestPlayerScore, biggestPlayerScoreIndex = 0, 0
## for i in range(len(remaining)):
##
## player = players[remaining[i]]
## arr = isMax(player)
## playerIndex, playerScore = arr[0], arr[1
## ]
## if playerScore > biggestPlayerScore:
## biggestPlayerScore = playerScore
## playerIndex = biggestPlayerScoreIndex
## print(biggestPlayerScore, biggestPlayerScoreIndex)
##
## #print(disqualified)
fileManager("zadanie4.txt",mode = "w+", content = disAndMax())
| 7fee5dad7436877ff9d192b8323831207c70fdde | [
"Python"
]
| 2 | Python | syrekable/MaturaInfa | 3aab3efa5301fa5cc8f7c8ee0d0fb92bcdb4caec | 5389e99c67bad60e19cafc049fa4c4bdb75fba8b |
refs/heads/master | <repo_name>msGenDev/SpeedReaderForWear<file_sep>/wear/src/main/java/net/austinhughes/speedreaderforwear/MainActivityWear.java
/*
(C) 2015 - <NAME>, <NAME>, <NAME>
Last Modified: 2015-01-01
*/
package net.austinhughes.speedreaderforwear;
// Imports
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.wearable.view.WatchViewStub;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.data.FreezableUtils;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataEvent;
import com.google.android.gms.wearable.DataEventBuffer;
import com.google.android.gms.wearable.DataMapItem;
import com.google.android.gms.wearable.Wearable;
import java.util.List;
/*
Main class for wearable side application
*/
public class MainActivityWear extends Activity implements ConnectionCallbacks, DataApi.DataListener, OnConnectionFailedListener
{
// private class variables
private TextView mTextView;
private GoogleApiClient mGoogleApiClient;
private Handler mHandler;
private static final String TAG = "DataListenerService";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.activity_main_activity_wear);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener()
{
@Override
public void onLayoutInflated(WatchViewStub stub)
{
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
Log.d("Wearable DataListenerService", "onCreate");
}
@Override
protected void onResume()
{
super.onResume();
mGoogleApiClient.connect();
}
@Override
protected void onPause()
{
super.onPause();
Wearable.DataApi.removeListener(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
@Override
public void onConnected(Bundle connectionHint)
{
Log.d(TAG, "onConnected(): connected to Google API client");
Wearable.DataApi.addListener(mGoogleApiClient, this);
}
@Override
public void onConnectionSuspended(int cause)
{
Log.d(TAG, "onConnectionSuspended(): Connection to Google API client was suspended");
}
@Override
public void onConnectionFailed(ConnectionResult result)
{
Log.e(TAG, "onConnectionFailed(): Failed to connect with result: " + result);
}
@Override
public void onDataChanged(DataEventBuffer dataEvents)
{
Log.d("Wearable DataListenerService", "onDataChanged" + dataEvents);
final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
dataEvents.close();
for (DataEvent event : events)
{
if (event.getType() == DataEvent.TYPE_CHANGED)
{
DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
final String text = dataMapItem.getDataMap().get("editTextValue");
Log.d("DataItem", text);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
mTextView.setText(text);
}
});
}
}
}
}
| acebc395996799297240e19d1028fb6b9f0f26eb | [
"Java"
]
| 1 | Java | msGenDev/SpeedReaderForWear | 864ffb6c9ff95401f132287b6c6d83425cbe565a | c16f9296cc94c52a75c234d84e8486c963ef3054 |
refs/heads/master | <repo_name>RetzKu/SDL_Test<file_sep>/SDL/Game.cpp
#include "Game.h"
mouse_Pos* Mouse = new mouse_Pos(0,0);
MainGame::MainGame()
{
_window = nullptr;
_gameState = GameState::PLAY;
}
MainGame::~MainGame()
{
}
void MainGame::run()
{
initSystems();
gameLoop();
SDL_DestroyWindow(_window);
delete Mouse;
}
void MainGame::processInput()
{
SDL_Event evnt;
while (SDL_PollEvent(&evnt))
{
switch (evnt.type)
{
case SDL_QUIT:
_gameState = GameState::EXIT;
break;
case SDL_MOUSEMOTION:
Mouse->Get_M_Location(evnt.motion.x, evnt.motion.y);
Mouse->Box(250, 270, 100, 100);
break;
case SDL_TEXTINPUT:
c = *evnt.text.text;
std::cout << c;
stream.push_back(c);
std::cout << stream;
stream.clear();
SDL_StopTextInput();
break;
}
}
}
void MainGame::gameLoop()
{
while (_gameState != GameState::EXIT)
{
processInput();
}
}
void MainGame::initSystems()
{
SDL_Init(SDL_INIT_EVERYTHING);
SDL_CreateWindow("Beli", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _screenWidth, _screenHeight, SDL_WINDOW_OPENGL);
}
<file_sep>/SDL/Game.h
#pragma once
#include <GL\glew.h>
#include <SDL\SDL.h>
#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include "Input_Manager.h"
enum class GameState{PLAY, EXIT};
class MainGame
{
public:
MainGame();
~MainGame();
void run();
private:
void processInput();
void gameLoop();
void initSystems();
SDL_Window* _window;
int _screenWidth = 480;
int _screenHeight = 360;
GameState _gameState;
char c;
bool Typing;
std::string stream;
};
| a6d56302eba13f089490efa9b93cfa021115d757 | [
"C++"
]
| 2 | C++ | RetzKu/SDL_Test | abab5c6abcc621604d414eb4081a6a7c59876bde | cd8d74b84e7b2fbc82df82792b0d5c7652bba027 |
refs/heads/master | <file_sep><?php
header("access-control-allow-origin: *");
include_once 'api/api.php';
global $conn, $api;
session_start();
//addUser($conn, new User("admin", "<EMAIL>", "<PASSWORD>"));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Blank Pay | Access Easy loans</title>
<!-- Bootstrap Core CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<!-- Custom Fonts -->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">
<!-- Plugin CSS -->
<link rel="stylesheet" href="css/animate.min.css" type="text/css">
<!-- Custom CSS -->
<link rel="stylesheet" href="css/custom.css" type="text/css">
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top">
<nav id="mainNav" class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand page-scroll" href="/hacklab">Blank</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<?php if(isset($_SESSION['login_user'])){
$user = getUserWithID($conn, isset($_SESSION['login_user']));
?>
<li>
<a class="page-scroll">Welcome, <?php echo $user->getUsername(); ?></a>
</li>
<li>
<a class="page-scroll" href="auth/logout.php">Logout</a>
</li>
<?php } else { ?>
<li>
<a class="page-scroll" href="login.php">Sign In/Up</a>
</li>
<?php } ?>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav><file_sep><?php
header("access-control-allow-origin: *");
include_once '../api/api.php';
global $conn, $api;
session_start();
if(isset($_POST['loan-submit'])){
if (empty($_POST['amount'])) {
$error = "You must enter and amount!";
}
else{
$user_id = $_SESSION['login_user'];
$sdate = date("Y-m-d H:i:s");
$amount = $_POST['amount'];
$conn = openConnection();
$user = getUserWithId($conn, $user_id);
$loanID = addLoan($conn, new Loan($sdate, $user_id, $amount, Loan::REQUESTED));
if(!empty($loanID)){
header("location: ../dashboard.php"); // Redirecting To Other Page
}
}
}
?>
<file_sep><?php
include('header.php');
?>
<div class="dashboard container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li><a href="dashboard.php">Overview <span class="sr-only">(current)</span></a></li>
<li class="active"><a href="#">Make a Payment</a></li>
<li><a href="loan.php">Apply for a Loan</a></li>
<!-- <li><a href="#">Loan</a></li> -->
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1 class="page-header">Transaction</h1>
<div class="row placeholders">
<div class="col-xs-6 col-sm-6 amount">
<span class="text-muted">You currently owe:</span>
<h1>GH₵ <?php echo number_format($user->getBalance(), 2, '.', '');?></h1>
</div>
<!-- <div class="col-xs-6 col-sm-6 amount">
<span class="text-muted">Your slidepay balance:</span>
<h1>GH₵ <?php echo number_format($user->getBalance(), 2, '.', '');;?></h1>
</div> -->
</div>
<br>
<h2 class="sub-header">Make the payment:</h2>
<br>
<div class="table-responsive">
<form id="login-form" action="api/payments.php" method="post" role="form" style="display: block;">
<div class="col-xs-2 col-sm-2">
<h1>GH₵</h1>
</div>
<div class="form-group col-xs-6 col-sm-6 paybox ">
<input type="text" name="amount" id="amount" tabindex="1" class="form-control" placeholder=" 0.00" value="">
</div>
<div class="form-group col-xs-4 col-sm-4 paybtn">
<input type="submit" name="login-submit" id="transaction-submit" tabindex="4" class="form-control btn btn-login" value="Pay Now">
</div>
<input type="hidden" name="user_id" id="user_id" value="<?php echo $_SESSION["login_user"]?>">
</form>
</div>
</div>
</div>
</div>
<?php
include('footer.php');
?>
</body>
</html>
<file_sep><?php
header("access-control-allow-origin: *");
include_once 'api/api.php';
global $conn, $api;
session_start();
if(isset($_POST['register'])){
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is empty";
}
else{
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$conn-> OpenConnection();
$user = getUserWithUsername($conn, $username);
if($user == 'not found'){
retrun "User not found";
}else{
$checkPass = $user->getPassword();
if($checkPass !== $password){
return "Incorrect Password";
}else{
$_SESSION['user']=$user->getID();
header("location: dashboard.php"); // Redirecting To Other Page
}
}
}
}
?><file_sep>slydepay.api_version=1.4
slydepay.merchant_key=1459496944466
slydepay.merchant_email=<EMAIL><file_sep><?php
function userGetter($conn, $condition){
try
{
$conn = OpenConnection();
if(empty($condition)) {
$sql = "SELECT id, username, email, password, balance FROM Users";
}
else{
$sql = "SELECT id, username, email, password, balance FROM Users WHERE ".$condition;
}
foreach ($conn->query($sql) as $row) {
$user = new User($row["username"], $row["email"], $row["password"]);
$user->setBalance($row["balance"]);
$user->setId($row["id"]);
$users[] = $user;
}
$conn = null;
if (!empty($users)) {
return $users;
}else{
return null;
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
function getUserWithID($conn, $id){
$cond = "id = \"$id\"";
$user = userGetter($conn, $cond);
if (empty($user)){
return "not found";
}
return $user[0];
}
function getUserWithUsername($conn, $username){
$cond = "username = \"$username\"";
$users = userGetter($conn, $cond);
if (empty($users)){
return "not found";
}
return $users[0];
}
function addUser($conn, $user){
try{
$username = $user->getUsername();
$email = $user->getEmail();
$password = $user->getPassword();
$sql = "INSERT INTO Users (username, email, password)
VALUES ('$username','$email','$password')";
$conn = OpenConnection();
$conn->exec($sql);
$new_id = $conn->lastInsertId();
$conn = null;
if (empty($new_id)){
return null;
}else{
return $new_id;
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
function updateUser($conn, $user){
try{
$id = $user->getId();
$username = $user->getUsername();
$email = $user->getEmail();
$password = $user-><PASSWORD>();
$balance = $user->getBalance();
$sql = "UPDATE Users
SET username = '$username', email = '$email', password = <PASSWORD>', balance = '$balance'
WHERE id = \"$id\"";
$conn = OpenConnection();
$conn->exec($sql);
$new_id = $conn->lastInsertId();
$conn = null;
if (empty($new_id)){
return null;
}else{
return $new_id;
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
function editUserBalance($conn, $userId, $amount){
$user = getUserWithID($conn, $userId);
$newbal = $user->getBalance() + $amount;
$user->setBalance($newbal);
$user->setId($userId);
updateUser($conn, $user);
}
function transactionGetter($conn, $condition){
try {
$conn = OpenConnection();
if (empty($condition)) {
$sql = "SELECT id, tdate, amount, user_id FROM Transactions";
} else {
$sql = "SELECT id, tdate, amount, user_id FROM Transactions WHERE $condition";
}
foreach($conn->query($sql) as $row) {
$transaction = new transaction($row["tdate"], $row["user_id"], $row["amount"]);
$transaction->setId($row["id"]);
$transactions[] = $transaction;
}
$conn = null;
if (!empty($transactions)) {
return $transactions;
} else {
return null;
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
function getTransactionWithID($conn, $id){
$cond = "id = \"$id\"";
$transactions = transactionGetter($conn, $cond);
if (empty($transactions)){
return null;
}else{
return $transactions[0];
}
}
function getTransactions($conn){
$transactions = transactionGetter($conn, null);
if (empty($transactions)){
return "No transactions available";
}
return $transactions;
}
function getUserTransactions($conn, $user_id){
$cond = "user_id = \"$user_id\"";
$transactions = transactionGetter($conn, $cond);
if (empty($transactions)){
return null;
}else{
return $transactions;
}
}
function addTransaction($conn, $transaction){
$user_id = $transaction->getUserID();
$tdate = $transaction->getTDate();
$amount = $transaction->getAmount();
try {
$sql = "INSERT INTO transactions (tdate, amount, user_id)
VALUES ('$tdate','$amount','$user_id')";
//Insert query
$conn = OpenConnection();
$conn->exec($sql);
$new_id = $conn->lastInsertId();
$conn = null;
if (empty($new_id)){
return null;
}else{
editUserBalance($conn, $user_id, $amount);
return $new_id;
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
function loanGetter($conn, $condition){
try {
$conn = OpenConnection();
if (empty($condition)) {
$sql = "SELECT id, sdate, amount, user_id, status FROM loans";
} else {
$sql = "SELECT id, sdate, amount, user_id, status FROM loans WHERE $condition";
}
foreach($conn->query($sql) as $row) {
$loan = new loan($row["sdate"], $row["user_id"], $row["amount"], $row["status"]);
$loan->setId($row["id"]);
$loans[] = $loan;
}
$conn = null;
if (!empty($loans)) {
return $loans;
} else {
return null;
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
function getloanWithID($conn, $id){
$cond = "id = \"$id\"";
$loans = loanGetter($conn, $cond);
if (empty($loans)){
return null;
}else{
return $loans[0];
}
}
function getloans($conn){
$loans = loanGetter($conn, null);
if (empty($loans)){
return "No loans available";
}
return $loans;
}
function getUserloans($conn, $user_id){
$cond = "user_id = \"$user_id\"";
$loans = loanGetter($conn, $cond);
if (empty($loans)){
return null;
}else{
return $loans;
}
}
function addloan($conn, $loan){
$user_id = $loan->getUserID();
$sdate = $loan->getSDate();
$amount = $loan->getAmount();
$status = $loan->getStatus();
try {
$sql = "INSERT INTO loans (sdate, amount, user_id, status)
VALUES ('$sdate','$amount','$user_id', '$status')";
//Insert query
$conn = OpenConnection();
$conn->exec($sql);
$new_id = $conn->lastInsertId();
$conn = null;
if (empty($new_id)){
return null;
}else{
return $new_id;
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}
//Encode result in json format
function sanitizeResult($result, $code = 200) {
if (count($result) > 0) {
sendResponse($code, json_encode($result));
return true;
} else {
sendResponse($code, json_encode("ERROR"));
return true;
}
}
function GeSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {
if (PHP_VERSION < 6) {
$theValue_ = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
switch ($theType) {
case "text":
$theValue_ = ($theValue != "") ? $theValue : "NULL";
break;
case "long":
case "int":
$theValue_ = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue_ = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue_ = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue_ = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue_;
}<file_sep>HackLab KNUST 2016
Project by
<NAME>
<NAME>- Ansah<file_sep><?php
require_once 'config.php';
require_once 'definition.php';
//require_once 'PDOCommonUtil.php';
//require_once 'DBMethods.php';
require_once 'DB.php';
require_once 'Model/User.php';
require_once 'Model/Transaction.php';
require_once 'Model/Loans.php';
<file_sep><?php
define("SET_FEEDBACK_MSG", "");
define("API_CALL", "API");
define("DB_METHODS", "DB_METHODS");<file_sep><?php
class User {
public $id;
public $username;
public $password;
public $balance;
public function newUser($id, $username, $email, $password) {
$this->id = $id;
$this->username = $username;
$this->email = $email;
$this->password = $<PASSWORD>;
$this->balance = 0;
}
public function __construct($username, $email, $password){
$this->username = $username;
$this->email = $email;
$this->password = $<PASSWORD>;
$this->balance = 0;
}
function __toString()
{
return "UserId: ".$this->getId().
" Username: ".$this->getUsername().
" Email: ".$this->getEmail().
" Password: ".$<PASSWORD>().
" Balance: ".$this->getBalance().
"<br>";
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getUsername()
{
return $this->username;
}
/**
* @param mixed $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* @param mixed $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* @return mixed
*/
public function getpassword()
{
return $this->password;
}
/**
* @param mixed $password
*/
public function setpassword($password)
{
$this->password = $password;
}
/**
* @return mixed
*/
public function getBalance()
{
return $this->balance;
}
/**
* @param mixed $password
*/
public function setBalance($balance)
{
$this->balance = $balance;
}
}
<file_sep><?php
include('header.php');
?>
<div class="dashboard container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li class="active"><a href="#">Overview <span class="sr-only">(current)</span></a></li>
<li><a href="transaction.php">Make a Payment</a></li>
<li><a href="loan.php">Apply for a Loan</a></li>
<!-- <li><a href="#">Loan</a></li> -->
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1 class="page-header">Dashboard</h1>
<div class="row placeholders">
<div class="col-xs-6 col-sm-6 amount">
<span class="text-muted">You currently owe:</span>
<h1>GH₵ <?php echo number_format($user->getBalance(), 2, '.', '');?></h1>
</div>
<div class="col-xs-3 col-sm-3 dashbtn">
<a href="transaction.php" role="button" class="btn btn-primary">Pay Money</a>
</div>
<div class="col-xs-3 col-sm-3 dashbtn">
<a href="loan.php" role="button" class="btn btn-primary">Apply for Loan</a>
</div>
</div>
<h2 class="sub-header">Recent Transactions</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Date</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php
$trans = getUserTransactions($conn, $user->getId());
foreach($trans as $t){
?>
<tr>
<td><?php echo $t->getId();?></td>
<td><?php echo $t->getTDate();?></td>
<td><?php echo $t->getAmount();?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<h2 class="sub-header">Recent Loans</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>Id</th>
<th>Date Submitted</th>
<th>Amount</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$loans = getUserLoans($conn, $user->getId());
foreach($loans as $l){
?>
<tr>
<td><?php echo $l->getId();?></td>
<td><?php echo $l->getSDate();?></td>
<td><?php echo $l->getAmount();?></td>
<td><?php echo $l->getStatus();?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<?php
include('footer.php');
?>
</body>
</html>
<file_sep><?php
class Loan{
public $id;
public $sdate;
public $user_id;
public $amount;
public $status;
const REQUESTED = 'REQUESTED';
const READ = 'READ';
const APPROVED = 'APPROVED';
const DISBERSED = 'DISBERSED';
const DEFAULTED = 'DEFAULTED';
public function newLoan($id, $sdate, $user_id, $amount) {
$this->id = $id;
$this->user_id = $user_id;
$this->sdate = $sdate;
$this->amount = $amount;
$this->status = Loan::REQUESTED;
}
public function __construct($sdate, $user_id, $amount, $status) {
$this->user_id = $user_id;
$this->sdate = $sdate;
$this->amount = $amount;
$this->status = $status;
}
function __toString(){
return "loanID: ".$this->getId()." UserID: ".$this->user_id()." Date: ".$this->getsDate()." Amount: ".$this->getLocation()."<br>";
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getSDate()
{
return $this->sdate;
}
/**
* @param mixed $sdate
*/
public function setSDate($sdate)
{
$this->sdate = $sdate;
}
/**
* @return mixed
*/
public function getUserID()
{
return $this->user_id;
}
/**
* @param mixed $user_id
*/
public function setUserID($user_id)
{
$this->user_id = $user_id;
}
/**
* @return mixed
*/
public function getAmount()
{
return $this->amount;
}
/**
* @param mixed $amount
*/
public function setAmount($amount)
{
$this->amount = $amount;
}
/**
* @return mixed
*/
public function getStatus()
{
return $this->status;
}
/**
* @param mixed $status
*/
public function setStatusRequested()
{
$this->status = Loan::REQUESTED;
}
/**
* @param mixed $status
*/
public function setStatusRead()
{
$this->status = Loan::READ;
}
/**
* @param mixed $status
*/
public function setStatusApproved()
{
$this->status = Loan::APPROVED;
}
/**
* @param mixed $status
*/
public function setStatusDisbersed()
{
$this->status = Loan::DISBERSED;
}
/**
* @param mixed $status
*/
public function setStatusDefaulted()
{
$this->status = Loan::DEFAULTED;
}
}
<file_sep><?php
class Transaction {
public $id;
public $tdate;
public $user_id;
public $amount;
public function newTransaction($id, $tdate, $user_id, $amount) {
$this->id = $id;
$this->user_id = $user_id;
$this->tdate = $tdate;
$this->amount = $amount;
}
public function __construct($tdate, $user_id, $amount) {
$this->user_id = $user_id;
$this->tdate = $tdate;
$this->amount = $amount;
}
function __toString(){
return "TransactionID: ".$this->getId().
" UserID: ".$this->getUserID().
" Date: ".$this->getTDate().
" Amount: ".$this->getAmount().
"<br>";
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getTDate()
{
return $this->tdate;
}
/**
* @param mixed $tdate
*/
public function setTDate($tdate)
{
$this->tdate = $tdate;
}
/**
* @return mixed
*/
public function getUserID()
{
return $this->user_id;
}
/**
* @param mixed $user_id
*/
public function setUserID($user_id)
{
$this->user_id = $user_id;
}
/**
* @return mixed
*/
public function getAmount()
{
return $this->amount;
}
/**
* @param mixed $amount
*/
public function setAmount($amount)
{
$this->amount = $amount;
}
}
<file_sep><?php
include_once 'controller.php';
error_reporting(E_ALL);
class api {
public $conn;
// Constructor - open DB connection
function __construct() {
global $conn;
$this->conn = $conn;
}
// Destructor - close DB connection
function __destruct() {
$this->conn = null;
}
// API interface
function api($action = null, $msg = null) {
if ((isset($action) && isset($msg)) || isset($action)) {
//NQAssertSession();
switch ($action) {
case API_CALL:
echo "This is a test api call<br/>";
break;
case DB_METHODS:
break;
//Aux command calls
case SET_FEEDBACK_MSG:
setFeedbackMessage($msg);
break;
default : sanitizeResult('Invalid Action', 400);
break;
}
} else {
sanitizeResult('Invalid Request', 400);
echo "Bad Call. Boohoo";
}
}
}<file_sep><?php
header("access-control-allow-origin: *");
include_once '../api/api.php';
global $conn, $api;
session_start();
include_once 'Integrator.class.php';
$paylive="https://test.slydepay.com/payLIVE/detailsnew.aspx?pay_token=";
$ns="http://www.i-walletlive.com/payLIVE";
$wsdl="https://test.slydepay.com/webservices/paymentservice.asmx?wsdl";
$settings = parse_ini_file("slydepay.ini");
$api_version=$settings["slydepay.api_version"];
$merchant_email=$settings["slydepay.merchant_email"];
$merchant_secret_key=$settings["slydepay.merchant_key"];
$service_type="C2B";
$integration_mode=true;
$slyde = new SlydepayConnector($ns, $wsdl, $api_version, $merchant_email, $merchant_secret_key, $service_type, $integration_mode);
if(isset($_GET['status']) && isset($_GET['transac_id']) && $_GET['status'] === 0 ){
$slyde->ConfirmTransaction($_GET['pay_token'], $_GET['$transac_id']);
$transaction = new Transaction(date("Y-m-d H:i:s"),$_SESSION["user_id"],$_SESSION["amount"]);
addTransaction($conn, $transaction);
unset($_SESSION['amount']);
header("Location: ../transactions.php");
} else{
echo "error!";
}
$order_id= GUID();
//me:
$transaction = new Transaction(date("Y-m-d H:i:s"),$_POST["user_id"],$_POST["amount"]);
$_SESSION['current_amount'] = $_POST["amount"];
$order_items[0] = $slyde->buildOrderItem($transaction->getId(), $transaction->getUserId(), $transaction->getId(), $transaction->getAmount(), 1, $transaction->getAmount());
$response = $slyde->ProcessPaymentOrder($order_id, $transaction->getAmount(), 0, 0, $transaction->getAmount(), "", "", $order_items);
// var_dump($response);
// var_dump($response->ProcessPaymentOrderResult);
$redirect = $paylive.$response->ProcessPaymentOrderResult;
header("Location: $redirect");
function GUID()
{
if (function_exists('com_create_guid') === true)
{
return trim(com_create_guid(), '{}');
}
return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}
?>
<file_sep><?php
define("HOST", "localhost");
define("USER", "root");
define("PORT", "3306");
define("PASSWORD", "");
define("DATABASE", "hacklab");
define("SECURE", FALSE);
define("BASE_DIR", "");
define("BASE_URL", "");
?><file_sep><?php
include('header.php');
?>
<div class="dashboard container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li><a href="dashboard.php">Overview <span class="sr-only">(current)</span></a></li>
<li><a href="transactions.php">Make a Payment</a></li>
<li class="active"><a href="loan.php">Apply for a Loan</a></li>
<!-- <li><a href="#">Loan</a></li> -->
</ul>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1 class="page-header">Transaction</h1>
<div class="row placeholders">
<div class="col-xs-6 col-sm-6 amount">
<span class="text-muted">You currently owe:</span>
<h1>GH₵ <?php echo number_format($user->getBalance(), 2, '.', '');?></h1>
</div>
<!-- <div class="col-xs-6 col-sm-6 amount">
<span class="text-muted">Your slidepay balance:</span>
<h1>GH₵ <?php echo $user->getBalance();?></h1>
</div> -->
</div>
<br>
<h2 class="sub-header">Apply for a Loan:</h2>
<br>
<div class="table-responsive">
<form id="login-form" action="api/loans.php" method="post" role="form" style="display: block;">
<div class="form-group">
<input type="text" name="name" id="name" tabindex="1" class="form-control" placeholder="NAME" value="">
</div>
<div class="form-group">
<input type="text" name="name" id="name" tabindex="2" class="form-control" placeholder="NAME OF COMPANY">
</div>
<div class="form-group">
<input type="text" name="telephonenumber" id="telephonenumber" tabindex="3" class="form-control" placeholder="TELEPHONE NUMBER">
</div>
<div class="form-group">
<input type="text" name="address" id="homeaddress" tabindex="4" class="form-control" placeholder="HOME ADDRESS" value="">
</div>
<div class="form-group">
<input type="text" name="email" id="email" tabindex="5" class="form-control" placeholder="EMAIL" value="">
</div>
<div class="form-group">
<input type="text" names="collateral" id="collateral" tabindex="6" class="form-control" placeholder="COLLATERAL" value="">
</div>
<div class="form-group">
<input type="text" name="occupation" id="occupation" tabindex="7" class="form-control" placeholder="OCCUPATION" value="">
</div>
<div class="form-group">
<input type="text" name="amount" id="amount" tabindex="8" class="form-control" placeholder="AMOUNT" value="">
</div>
<div class="form-group">
<input type="text" name="mode of payment" id="mode of payment" tabindex="9" class="form-control" placeholder="MODE OF PAYMENT" value="">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="loan-submit" id="loan-submit" tabindex="10" class="form-control btn btn-login" value="Submit Application">
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<?php
include('footer.php');
?>
</body>
</html>
<file_sep><?php
include('header.php');
?>
<header>
<div class="header-content">
<div class="header-content-inner">
<h1 id="title">BLANK PAY</h1>
<h2>Easy, Reliable, Faster</h2>
<hr>
<p>Start using BLANK PAY and gain easy access to otherwise hard-to-get banking services; claim and pay off loans with ease and speed!</p>
<a href="#about" class="btn btn-primary btn-xl page-scroll">Find Out More</a>
</div>
</div>
</header>
<section class="bg-primary" id="about">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<h2 class="section-heading">We've got what you need!</h2>
<hr class="light">
<p class="text-faded">This micro-finance site helps you to get loans with just a click, free to register online, and easy to use. No strings attached!</p>
<?php if(isset($_SESSION['login_user'])){?>
<a href="dashboard.php" class="btn btn-default btn-xl">Go to your Dashboard!</a>
<?php } else { ?>
<a href="login.php" class="btn btn-default btn-xl">Get Started!</a>
<?php } ?>
</div>
</div>
</div>
</section>
<section id="services">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">At Your Service</h2>
<hr class="primary">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-money wow bounceIn text-primary"></i>
<h3>AMOUNT PAID</h3>
<p class="text-muted">Amount paid shows the amounts you can deposit and also receive as loan</p>
</div>
</div>
<div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-shekel wow bounceIn text-primary" data-wow-delay=".1s"></i>
<h3>MODE OF PAYMENTS</h3>
<p class="text-muted">You can use this theme to make the payments</p>
</div>
</div>
<div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-star-half wow bounceIn text-primary" data-wow-delay=".2s"></i>
<h3>UP TO DATE</h3>
<p class="text-muted">We update fresh on transactions made.</p>
</div>
</div>
<div class="col-lg-3 col-md-6 text-center">
<div class="service-box">
<i class="fa fa-4x fa-thumbs-up wow bounceIn text-primary" data-wow-delay=".3s"></i>
<h3>SUGGESTIONS</h3>
<p class="text-muted">To tell us new ideas and experences using the services</p>
</div>
</div>
</div>
</div>
</section>
<section class="no-padding" id="portfolio">
<div class="container-fluid">
<div class="row no-gutter">
<div class="col-lg-4 col-sm-6">
<a href="#" class="portfolio-box">
<img src="img/portfolio/1.jpg" class="img-responsive" alt="">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<div class="project-category text-faded">
Category
</div>
<div class="project-name">
Project Name
</div>
</div>
</div>
</a>
</div>
<div class="col-lg-4 col-sm-6">
<a href="#" class="portfolio-box">
<img src="img/portfolio/2.jpg" class="img-responsive" alt="">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<div class="project-category text-faded">
Category
</div>
<div class="project-name">
Project Name
</div>
</div>
</div>
</a>
</div>
<div class="col-lg-4 col-sm-6">
<a href="#" class="portfolio-box">
<img src="img/portfolio/3.jpg" class="img-responsive" alt="">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<div class="project-category text-faded">
Category
</div>
<div class="project-name">
Project Name
</div>
</div>
</div>
</a>
</div>
<div class="col-lg-4 col-sm-6">
<a href="#" class="portfolio-box">
<img src="img/portfolio/4.jpg" class="img-responsive" alt="">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<div class="project-category text-faded">
Category
</div>
<div class="project-name">
Project Name
</div>
</div>
</div>
</a>
</div>
<div class="col-lg-4 col-sm-6">
<a href="#" class="portfolio-box">
<img src="img/portfolio/5.jpg" class="img-responsive" alt="">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<div class="project-category text-faded">
Category
</div>
<div class="project-name">
Project Name
</div>
</div>
</div>
</a>
</div>
<div class="col-lg-4 col-sm-6">
<a href="#" class="portfolio-box">
<img src="img/portfolio/6.jpg" class="img-responsive" alt="">
<div class="portfolio-box-caption">
<div class="portfolio-box-caption-content">
<div class="project-category text-faded">
Category
</div>
<div class="project-name">
Project Name
</div>
</div>
</div>
</a>
</div>
</div>
</div>
</section>
<aside class="bg-dark">
<div class="container text-center">
<div class="call-to-action">
<h2>Free Download at blankpay!</h2>
<a href="#" class="btn btn-default btn-xl wow tada">Download Now!</a>
</div>
</div>
</aside>
<section id="contact">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<h2 class="section-heading">Let's Get In Touch!</h2>
<hr class="primary">
<p>Ready to start your next work with us? That's great! Give us a call or send us an email and we will get back to you as soon as possible!</p>
</div>
<div class="col-lg-4 col-lg-offset-2 text-center">
<i class="fa fa-phone fa-3x wow bounceIn"></i>
<p>123-456-6789</p>
</div>
<div class="col-lg-4 text-center">
<i class="fa fa-envelope-o fa-3x wow bounceIn" data-wow-delay=".1s"></i>
<p><a href="mailto:<EMAIL>"><EMAIL></a></p>
</div>
</div>
</div>
</section>
<?php
include('footer.php');
?>
</body>
</html>
| 7890affe38553bd2890a188e129fd5300604159f | [
"Markdown",
"PHP",
"INI"
]
| 18 | PHP | jyoansah/hacklab | 3471de9bef386e52ba90070641a16369455732dd | a0e17dab71877e92029cada9f7384c993fe7ace6 |
refs/heads/master | <file_sep># getbyreferenceid-reactjs-client
1) Cretaed the project in visual studio code by install npm, yarn first then visual studio code
main files are
a) Create react applicaation.Command is (create in any folder)
npx create-react-app
Above commnad also creates project strure and also add dependencies
a) index.html b) index.js c) get.js
d) After adding these files in visual studio code , add axios dependency by
yarn add axios
e) Start yarn by calling.. yarn start
f) React application opens ....url is ...http://localhost:3000/
2) Also add @CrossOrigin( origins = "*" ) on every controller method in BricksCustomerController java class
3) Not able to add complete dependencies as project size is large.
<file_sep>import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class Get extends Component {
constructor(props){
super(props);
this.state = {product:{}};
}
onIdChange = (e)=>{
this.setState({id:e.target.value});
}
getProduct(){
const axios = require('axios');
axios.get("http://localhost:8080/BrickOrderingApplication/customer-orders/"+this.state.id)
.then(res=>{
console.log(res);
this.setState({product:res.data});
})
}
render() {
return (
<div>
Enter ReferenceId ID:<input onChange={this.onIdChange}/>
<button onClick={this.getProduct.bind(this)}>Get Order Details</button>
<br/>
CustomerId: {this.state.product.cutomerId}
<br/>
Order ReferenceId: {this.state.product.orderReferenceId}
<br/>
NumberofBricks: {this.state.product.numberofBricks}
</div>
);
}
}
export default Get;
| c23aaa9e08a6362ae355e6fc8496ed6ddc510697 | [
"Markdown",
"JavaScript"
]
| 2 | Markdown | santoshr1239/getbyreferenceid-reactjs-client | 2877a504c44d2dc429e8c91a9ed6a8edde759132 | de700e44f86cf7ccd5106606b4f1d51deaf647f5 |
refs/heads/main | <repo_name>Gvenkatesh27/new-project<file_sep>/Assignment/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<?php ?>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form class="myform" action="./server.php" method="POST">
<h2><b>ADD NEW EMPLOYEE</b></h2>
<input type="text" name="id" class="id form-control" placeholder="id">
<input type="text" name="name" class="name form-control" placeholder="name">
<input type="text" name="fathername" class="fathername form-control" placeholder="fathername">
<input type="text" name="emailid" class="emailid form-control" placeholder="emailid">
<input type="text" name="phonenumber" class="phonenumber form-control" placeholder="phonenumber">
<input type="text" name="address" class="address form-control" placeholder="address">
<input type="submit" value="create new" name="submit" class="btn btn-primary login_btn" id="myloginbtn">
</form>
</div>
</div>
</div>
</body>
</html>
<file_sep>/sample-reg/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php ?>
<body class ="back-image">
<div>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form class="myform" action="./server.php" method="POST">
<h2><b>login form</b></h2>
<input type="text" name="email" class="email form-control" placeholder="email">
<input type="text" name="password" class="password form-control" placeholder="<PASSWORD>">
<input type="text" name="address" class="address form-control" placeholder="address">
<input type="text" name="mobile" class="mobile form-control" placeholder="mobile">
<input type="submit" value="login" name="submit" class="btn btn-primary login-btn" id="mylogin btn">
</form>
</div>
</div>
</div>
</div>
</body>
</html><file_sep>/Assignment/details.php
<?php
include_once('fetch.php');
$user_id = $_GET['id'];
if($user_id != NULL){
$detail_query = mysqli_query($con,"DETAILS FROM store WHERE id=$user_id");
if($detail_query){
header("location: fetch.php");
}
else{
echo "DETAILS FOUND";
}
}
?><file_sep>/Assignment/server.php
<?php
if(isset($_POST['submit'])){
inserData();
}
function inserData(){
include_once('db_config.php');
$id= $_POST['id'];
$name = $_POST['name'];
$fathername = $_POST['fathername'];
$emailid = $_POST['emailid'];
$phonenumber = $_POST['phonenumber'];
$address = $_POST['address'];
$ins_query = mysqli_query($con, "INSERT INTO store (id,name,fathername,emailid,phonenumber,address) VALUES ('$id','$name','$fathername','$emailid','$phonenumber','$address')");
if($ins_query){
header("location: fetch.php");
}
}
?>
<file_sep>/Assignment/fetch.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h2><b>LIST OF ALL EMPLOYEE</b></h2>
<?php
include_once('db_config.php');
$fetch_query = mysqli_query($con,"select * from store");
$query_rows = mysqli_num_rows($fetch_query);
if($query_rows > 0){
echo "<table class='table table-bordered'><tr><th>id</th><th>name</th><th>fathername</th><th>emailid</th><th>phonenumber</th><th>address</th></tr>";
while($row = mysqli_fetch_array($fetch_query)){
echo "<tr><td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['fathername']."</td>";
echo "<td>".$row['emailid']."</td>";
echo "<td>".$row['phonenumber']."</td>";
echo "<td>".$row['address']."</td>";
echo "<td> <a href='./delete.php?id=".$row['id']."'><button class='btn btn-danger'>Delete</button></a> <a href='./edit.php?id=".$row['id']."'> <button class='btn btn-success'>Edit</button></a> <a href='./details.php?id=".$row['id']."'> <button class='btn btn-success'>details</button></a></td></tr>";
}
echo "</table>";
}else{
echo "No Data found";
}
?>
</body>
</html><file_sep>/Demo/index.php
<?php
include_once("navbar.php");
include_once("footer.php");
?>
<html>
<head>
<title>venky</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h3>Welcome To Huddlerise </h3>
<p class="classss">Freshers Program Training in Bangalore <br>Getting a placement is not a easy for all kind of students</p>
<div class="classs" >Read More</div>
<h3 class="demos">Welcome To Huddlerise </h3>
<p class="demo">Freshers Program Training in Bangalore <br>Getting a placement is not a easy for all kind of students</p>
<div class="dem" >Read More</div>
<h3 class="demoss">Welcome To Huddlerise </h3>
<p class="de">Freshers Program Training in Bangalore <br>Getting a placement is not a easy for all kind of students</p>
<div class="d" >Read More</div>
<h4 class="links">sidbar links </h4>
<p class="link"> link1<br> link2<br> link3<br> link4<br>
</body>
</html>
<file_sep>/sample-reg/server.php
<?php
// Database connection
if(isset($_POST['submit'])){
inserData();
}
function inserData(){
include_once('db_config.php');
$email= $_POST['email'];
$password= $_POST['password'];
$address = $_POST['address'];
$mobile = $_POST['mobile'];
$insert_query = mysqli_query($con,"INSERT INTO users (email,password,address,mobile) values('$email','$password','$address','$mobile')");
if($insert_query){
header("location: fetch.php");
}
}
?>
<file_sep>/practice/index.php
<?php
include_once("navbar.php");
include_once("footer.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body class="demo">
<div class="demosss">
<h1 style="color:white">providing you business solutions</h1>
<p style="color:white">Lorem ipsum dolor sit amet consectetur adipisicing elit. Amet voluptates</br> reiciendis consequuntur, magnam, vitae doloribus officia non dignissimos neque</br> in incidunt nihils qui! Perferendis consequuntur delectus dolor, iusto autem minima.</p>
<div class="images">
<img src="img_chania.jpg" alt="Flowers in Chania" width="160" height="180"/>
</div>
</div>
</body>
</html> <file_sep>/Assignment/edit_data.php
<?php
if(isset($_POST['submit'])){
inserData();
}
function inserData(){
$edit_id = $_GET['id'];
include_once('db_config.php');
$id= $_POST['id'];
$name = $_POST['name'];
$fathername = $_POST['fathername'];
$emailid = $_POST['emailid'];
$phonenumber = $_POST['phonenumber'];
$address = $_POST['address'];
$ins_query = mysqli_query($con, "UPDATE store
SET id = '$id',name = '$name', fathername= '$fathername',emailid = '$emailid', phonenumber= '$Phonenumber',address= '$address'
WHERE id = $edit_id");
if($ins_query){
header("location: fetch.php");
}
}
?>
| 2b268bfcb89076ae7fd45fe0a2973be69fb8c0f2 | [
"PHP"
]
| 9 | PHP | Gvenkatesh27/new-project | ade8f754e373ca175a55f91ee10468fbc7c22f1b | e1c4b0eae0882451a518592c9e3dba5b5a534bd1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.