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/master | <repo_name>benmelnick/youtube-to-spotify<file_sep>/create_playlist.py
from secrets import SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET
from constants import PLAYLIST_NAME, YOUTUBE_API_URL, YOUTUBE_URL, IGNORE
import os
import youtube_dl
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import sys
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
class CreatePlaylist:
def __init__(self):
self.youtube_client = self.get_youtube_client()
self.spotify_client = self.get_spotify_client()
self.all_liked_songs = {}
self.user_id = self.get_user_id()
self.playlist_id = self.get_playlist()
self.cache = self.init_cache()
"""
Step 1: log into youtube
"""
def get_youtube_client(self):
try:
print("Initializing YouTube client...")
# disable OAuthlib's HTTPS verification when running locally
# DO NOT leave this enabled in production
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
api_service_name = "youtube"
api_version = "v3"
client_secrets_file = "client_secret.json"
# get credentials and create an API client
scopes = [YOUTUBE_API_URL]
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes)
credentials = flow.run_console()
youtube_client = googleapiclient.discovery.build(api_service_name, api_version, credentials=credentials)
print("YouTube client initialized")
return youtube_client
except:
sys.exit("Error initializing YouTube client")
def get_spotify_client(self):
try:
print("Initializing Spotify client...")
scope = "playlist-modify-public"
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=SPOTIFY_CLIENT_ID, client_secret=SPOTIFY_CLIENT_SECRET,
redirect_uri="http://localhost:8080/callback", scope=scope))
print("Spotify client initialized")
return sp
except Exception as e:
print(e)
print("Error initializing Spotify client")
"""
Step 2: get liked videos
places all of the important info into a dictionary
"""
def get_liked_videos(self):
request = self.youtube_client.videos().list(
part="snippet,contentDetails,statistics",
myRating="like"
)
response = request.execute()
# collect each video and get the important info
for item in response["items"]:
video_title = item["snippet"]["title"]
print(f"Found liked video {video_title}")
youtube_url = YOUTUBE_URL.format(item["id"])
# use youtube_dl to collect song name and artist name
# given the video URL, return the song name and artist - use this info to query spotify
video = youtube_dl.YoutubeDL({}).extract_info(item["id"], download=False)
song_name = video["track"]
artist = video["artist"]
# only query spotify for the song name if youtube-dl could actually find it
if song_name is not None:
spotify_uri = self.get_spotify_uri(song_name, artist)
else:
# youtube-dl seems to only be working if the video is published with only the song name in the title
# if youtube-dl didn't work, we know that the artist name is very likely in the title
# need to filter the title to separate the two search parameters (song name and artist)
print(f"youtube-dl could not find song name for video {video_title}")
filtered_title = self.filter_title(video_title)
spotify_uri = self.get_spotify_uri(filtered_title["track"], filtered_title["artist"])
self.all_liked_songs[video_title] = {
"youtube_url": youtube_url,
"song_name": song_name,
"artist": artist,
# fetch the spotify link at the same time as the liked youtube video
"spotify_uri": spotify_uri["uri"],
"existsInPlaylist": spotify_uri["existsInCache"]
}
def filter_title(self, video_title):
# todo: this method assume that the format is (artist) - (song name) - need to try the other way around
print(f"Filtering {video_title}...")
for ch in IGNORE:
if ch in video_title:
video_title = video_title.replace(ch, '')
artist = (video_title.rsplit("-")[0]).strip()
track = (video_title[len(artist) + 2:]).strip()
return {"artist": artist, "track": track}
def get_user_id(self):
return self.spotify_client.current_user()["id"]
"""
Step 3: create a new playlist in spotify
calls spotify api to create playlist
"""
def get_playlist(self):
print(f"Fetching playlists for user {self.user_id}")
# check to make sure the playlist already exists
playlists = self.spotify_client.current_user_playlists()
for playlist in playlists["items"]:
if playlist["name"] == PLAYLIST_NAME:
print(f"Playlist {PLAYLIST_NAME} already exists")
playlist_id = playlist["id"]
return playlist_id
new_playlist = self.spotify_client.user_playlist_create(self.user_id, PLAYLIST_NAME,
description="My liked YouTube videos")
playlist_id = new_playlist["id"]
print(f"Created new playlist {playlist_id}")
return playlist_id
def init_cache(self):
print("Populating cache...")
cache = {}
playlist_items = self.spotify_client.playlist_items(self.playlist_id)
count = 0
for item in playlist_items["items"]:
uri = item["track"]["uri"]
song_name = item["track"]["name"]
cache[song_name] = uri
count += 1
print(f"Brought {count} song uri's into cache")
return cache
"""
Step 4: search for the song in spotify
"""
def get_spotify_uri(self, song_name, artist):
# check the cache
for key in self.cache:
if key.lower() in song_name.lower():
print(f"Found {song_name} in cache")
return {"uri": self.cache[key], "existsInCache": True}
print(f"Searching Spotify for {song_name} by {artist}")
search_query = "artist:{} track:{}".format(artist, song_name)
search_result = self.spotify_client.search(search_query, limit=1, type='track', market=None)
if search_result["tracks"]["total"] == 0:
print(f"No Spotify results for song {song_name} by artist {artist}")
uri = 0
else:
# return the URI
print(f"Successfully found Spotify results for {song_name} by {artist}")
uri = search_result["tracks"]["items"][-1]["uri"]
actual_song_name = search_result["tracks"]["items"][-1]["name"]
self.cache[actual_song_name] = uri
return {"uri": uri, "existsInCache": False}
"""
checks in the playlist to see if the song has been avoided - avoids duplicates
"""
def song_does_not_exist(self, song_uri):
# check the cache to see if song already exists in the playlist
if song_uri in self.cache:
return False
else:
# cache miss - add to the cache
self.cache[song_uri] = 1
return True
"""
the main body of the code - calls all of the above methods in a single workflow
"""
def add_song_to_playlist(self):
# grab all of the information for songs
self.get_liked_videos()
# collect spotify uri of each song in liked videos
uris = []
for song, info in self.all_liked_songs.items():
song_uri = info["spotify_uri"]
if (song_uri is not 0) and (not info["existsInPlaylist"]):
# add the uri's for songs that did not already exist
uris.append(song_uri)
if len(uris) == 0:
print("No songs to add")
return
# add songs to playlist
print(f"Adding {len(uris)} songs to playlist...")
print(uris)
response = self.spotify_client.playlist_add_items(self.playlist_id, uris)
print(f"Successfully added {len(uris)} songs to playlist")
print(response)
def run(cp):
cp.add_song_to_playlist()
# main code
if __name__ == "__main__":
create_playlist = CreatePlaylist()
create_playlist.add_song_to_playlist()
# schedule.every(1).minutes.do(run, create_playlist)
#
# while True:
# schedule.run_pending()
# time.sleep(1)
<file_sep>/README.md
# youtube-to-spotify<file_sep>/constants.py
# URLs
SPOTIFY_API_URL = "https://api.spotify.com/v1"
YOUTUBE_API_URL = "https://www.googleapis.com/auth/youtube.readonly"
YOUTUBE_URL = "https://www.youtube.com/watch?v={}"
# Playlist information
PLAYLIST_NAME = "YouTube Likes"
# Words to delete from the fetched title name from Youtube
IGNORE = ['(', '[', ' x', ')', ']', '&', 'lyrics', 'lyric',
'video', '/', ' proximity', ' ft', '.', ' edit', ' feat', ' vs', ',',
'Official', 'Music', 'Video']
| fb8bf004d3c600ac5539dbf90ad1dccc261784b0 | [
"Markdown",
"Python"
] | 3 | Python | benmelnick/youtube-to-spotify | 5808cfdf5ff458336d0a47bb484d63ec75e4c6c9 | 3b609640f82ffcb9bddd5a5864f6f62ab20cf90c |
refs/heads/master | <file_sep>.PHONY: test test-sanity test-general test-skydns test-monitord test-graphite \
test-riemann
test: test-sanity test-general test-skydns test-monitord test-graphite \
test-riemann
test-sanity:
../script/run-test.sh success.test.service
../script/run-test.sh success.test.service success
! ../script/run-test.sh success.test.service failure
! ../script/run-test.sh success.test.service timeout
! ../script/run-test.sh failure.test.service
! ../script/run-test.sh failure.test.service success
../script/run-test.sh failure.test.service failure
! ../script/run-test.sh failure.test.service timeout
! ../script/run-test.sh timeout.test.service
! ../script/run-test.sh timeout.test.service success
! ../script/run-test.sh timeout.test.service failure
../script/run-test.sh timeout.test.service timeout
test-general: test-sanity
../script/run-test.sh hosts-file.test.service
test-skydns: test-sanity
../script/run-test.sh skydns-running.test.service
../script/run-test.sh skydns-resolvconf.test.service
../script/run-test.sh skydns-external.test.service
../script/run-test.sh skydns-wildcards.test.service
test-monitord:
@# test-sanity test-skydns
../script/run-test.sh monitord-running.test.service
../script/run-test.sh monitord-to-riemann.test.service
../script/run-test.sh monitord-available.test.service
test-graphite:
@# test-sanity test-skydns
fleetctl destroy ../services/graphite.service
fleetctl start ../services/graphite.service
../script/run-test.sh graphite-running.test.service
../script/run-test.sh graphite-available.test.service
../script/run-test.sh grafana-available.test.service
test-riemann:
@# test-monitord
fleetctl destroy ../services/riemann.service
fleetctl start ../services/riemann.service
../script/run-test.sh riemann-running.test.service
../script/run-test.sh riemann-available.test.service
<file_sep>NINSTANCES=3
FLEETCTL_TUNNEL=172.17.8.101
FLEETCTL_HOST_FILE=~/.fleetctl/known_hosts
.PHONY: all run config stop clean test
all: run
# Need inject the new user-data on every up
run: config user-data
vagrant up --provision
ssh-add ~/.vagrant.d/insecure_private_key
for i in $$(seq 1 ${NINSTANCES}); do \
prefix=`echo ${FLEETCTL_TUNNEL} | sed 's/.$$//'`; \
ssh -A -o StrictHostKeyChecking=no \
-o UserKnownHostsFile=${FLEETCTL_HOST_FILE} \
core@$${prefix}$${i} true; \
done
sleep 5s # Wait until the cluster is up
fleetctl --tunnel=${FLEETCTL_TUNNEL} --strict-host-key-checking=false \
--known-hosts-file=${FLEETCTL_HOST_FILE} list-machines
@echo -e '\n\nUse the following fleetctl settings:'
@cat .config.sh
stop:
vagrant halt
rm discovery-url
clean:
vagrant destroy -f
rm -f user-data discovery-url config.rb ${FLEETCTL_HOST_FILE} .config.sh
config: .config.sh
# If config changes, destroy the cluster
.config.sh: config.rb
vagrant destroy -f
rm -f ${FLEETCTL_HOST_FILE}
echo > $@
echo 'export FLEETCTL_TUNNEL=${FLEETCTL_TUNNEL}' >> $@
echo 'export FLEETCTL_HOST_FILE=${FLEETCTL_HOST_FILE}' >> $@
discovery-url:
curl -s https://discovery.etcd.io/new > $@ || \
{ rm $@ && false; }
user-data: user-data.sample discovery-url
sed $< >$@ \
-e 's!^\([ ]*\)#\(discovery:\).*$$!\1\2 '$$(cat discovery-url)'!'
config.rb:
echo > $@
echo '$$num_instances=${NINSTANCES}' >> $@
echo '$$update_channel="alpha"' >> $@
echo '$$enable_serial_logging=false' >> $@
echo '$$vb_gui=false' >> $@
echo '$$vb_memory=512' >> $@
echo '$$vb_cpus=1' >> $@
test:
make -C . clean
make -C . run NINSTANCES=1
make -C test test
<file_sep>#!/bin/bash
CANONICAL_PATH=`readlink -f "$0"`
PROG_NAME=`basename "$CANONICAL_PATH"`
SCRIPT_DIR=`dirname "$CANONICAL_PATH"`
export PATH="$SCRIPT_DIR:$PATH"
unit_path="$1"
unit_name=`basename "$unit_path"`
expected_result="${2:-success}"
if [ $# -lt 1 -o "$unit_path" == "-h" -o "$unit_path" == "--help" ]; then
cat >&2 <<EOF
Usage: $PROG_NAME <test unit> [<expected result>]
where expected result values are: success, failure, timeout (default: success)
EOF
exit 1
fi
fleetctl start "$unit_path"
res=`fleet-wait.sh "$unit_name"`
if [ "$res" != "$expected_result" ]; then
echo " : got = $res, expected = $expected_result"
fleetctl journal --lines 50 "$unit_name" | sed 's/^/ : /'
fi
fleetctl destroy "$unit_name"
echo ' '
test "$res" == "$expected_result"
<file_sep>#!/bin/sh
PROG_PATH=`readlink -f "$0"`
ROOT_PATH=`dirname "${PROG_PATH}/.."`
if [ $# -le 1 ]; then
prog=`filename "$PROG_PATH"`
echo "Usage: $prog <units to undeploy>" >&2
exit 1
fi
shift
. "${ROOT_PATH}/.config"
FLEETCTL_TUNNEL=${FLEETCTL_TUNNEL:-172.17.8.101}
FLEETCTL_HOST_FILE="${FLEETCTL_HOST_FILE:-~/.fleetctl/known_hosts}"
fleetctl --tunnel=${FLEETCTL_TUNNEL} --strict-host-key-checking=false \
--known-hosts-file=${FLEETCTL_HOST_FILE} destroy "$@"
fleetctl --tunnel=${FLEETCTL_TUNNEL} --strict-host-key-checking=false \
--known-hosts-file=${FLEETCTL_HOST_FILE} list-units
<file_sep>#!/bin/sh
CANONICAL_PATH=`readlink -f "$0"`
PROG_NAME=`basename "$CANONICAL_PATH"`
SCRIPT_DIR=`dirname "$CANONICAL_PATH"`
get_status() {
# Remove color escape codes, then do the manipulation
fleetctl status "$1" | \
sed 's,\x1B\[[0-9;]*[a-zA-Z],,g' | \
sed -n 's/^ *Active: \([a-zA-Z0-9]*\) (\([^)]*\)).*$/\1\n\2/p'
}
is_done() {
get_status "$1" | head -n 1 | grep -qwEe 'inactive|failed'
}
debug() {
echo "[D] $@" >&2
}
unit="$1"
if [ $# -lt 1 -o "$unit" == "-h" -o "$unit" == "--help" ]; then
echo "Usage: $PROG_NAME <test unit>" >&2
exit 1
fi
if ! get_status "$unit" | grep -q . ; then
echo "Error: unknown unit '$unit'" >&2
exit 1
fi
until is_done "$unit"; do
debug `get_status "$unit"` "... waiting 5 seconds..."
sleep 5;
done
debug `get_status "$unit"`
get_status "$unit" | tail -n +2 | \
awk '/\<dead\>/ { print "success"; exit 0; }
/\<timeout\>/ { print "timeout"; exit 0; }
/\<exit-code\>/ { print "failure"; exit 0; }
{ exit 1; }
'
| 0922ca84e4955faf726e5a20364e4c1ed14a41f1 | [
"Makefile",
"Shell"
] | 5 | Makefile | PlanitarInc/coreos-cluster | 35a42c6c74fa44a4fdf3fd706663ebc322e0a03b | a69d71b699ba079c46ecd1913a05a18b3566fe34 |
refs/heads/master | <file_sep>// var csv = require('ya-csv');
//
// //load csv file
// var loadCsv = function() {
// var reader = csv.createCsvFileReader('Liste', {
// 'separator': ',',
// 'quote': '"',
// 'escape': '"',
// 'comment': '',
// });
//
// var allEntries = new Array();
//
// reader.setColumnNames([ 'PPN', 'Exemplar-Datensatznr', 'Signatur', 'Barcode', 'Sigel' ]);
//
// reader.addListener('data', function(data) {
// //this gets called on every row load
// allEntries.push(data);
// });
//
// reader.addListener('end', function(data) {
// //this gets called when it's finished loading the entire file
// return allEntries;
// });
// };
//
// var myUsers = loadCsv();
| 8c5ba42e55f6c9aadda48528eb8f492952fdff0f | [
"JavaScript"
] | 1 | JavaScript | TimoFesseler/datenanalyseJS | c70717d94b69e3dd58c0e3425477a7d1df0fc5a2 | df18ba59102d358a9c747dad212d928524adc3d5 |
refs/heads/main | <file_sep>from flask import Flask, request
from flask_restful import Api, Resource, reqparse
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
import datetime
app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
# Base AudioModel
class AudioModel(db.Model):
__abstract__ = True
name = db.Column(db.String(100), nullable=False)
duration = db.Column(db.Integer, nullable=False)
uploaded_time = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now())
class SongModel(AudioModel):
__tablename__ = 'songmodel'
id = db.Column(db.Integer, primary_key=True)
class PodcastModel(AudioModel):
__tablename__ = 'podcastmodel'
id = db.Column(db.Integer, primary_key=True)
host = db.Column(db.String(100), nullable=False)
class AudioBookModel(AudioModel):
__tablename__ = 'audiobookmodel'
id = db.Column(db.Integer, primary_key=True)
author = db.Column(db.String(100), nullable=False)
narrator = db.Column(db.String(100), nullable=False )
# db.drop_all()
# db.create_all()
# Get Put Patch Delete endpoints for the requested audiofiletype
class AudioFile(Resource):
def get(self,audioFileType,audioFileId):
try:
if audioFileType == "Podcast":
res = PodcastModel.query.filter_by(id=audioFileId).first()
return {"name":res.name,"duration":res.duration,"host":res.host,"uploaded_time":str(res.uploaded_time)}
elif audioFileType == "Audiobook":
res = AudioBookModel.query.filter_by(id=audioFileId).first()
return {"title":res.name,"duration":res.duration,"narrator":res.narrator,"author":res.author,"uploaded_time":str(res.uploaded_time)}
elif audioFileType == "Song":
res = SongModel.query.filter_by(id=audioFileId).first()
return {"name":res.name,"duration":res.duration,"uploaded_time":str(res.uploaded_time)}
else:
return {"message":f"{audioFileType} is not a valid audioFileType.."}, 400
except AttributeError:
return {"message":f"{audioFileType} with ID-{audioFileId} doesn't exists.."}, 400
def put(self,audioFileType,audioFileId):
try:
if audioFileType == "Song":
args = ("name","duration")
req = request.form
if req:
if len(req)==len(args):
for key in req:
if key not in args:
return {"message":f"{key} key in the request body is incorrect.."}, 400
name = req['name']
if not len(name)<101:
return {"message":"Please provide proper name within 100 characters.."}, 400
try:
duration = int(req['duration'])
except:
return {"message":"Type of duration is not int.."}, 400
uploaded_time = datetime.datetime.now()
else:
return {"message":"Entered Request body is incorrect.."}, 400
song = SongModel(id=audioFileId,
name = name,
duration = duration,
uploaded_time = uploaded_time
)
db.session.add(song)
elif audioFileType == "Podcast":
args = ("name","duration","host")
req = request.form
if req:
if len(req)==len(args):
for key in req:
if key not in args:
return {"message":f"{key} key in the request body is incorrect.."}, 400
name = req['name']
if not len(name)<101:
return {"message":"Please provide proper name within 100 characters.."}, 400
try:
duration = int(req['duration'])
except:
return {"message":"Type of duration is not int.."}, 400
host = req['host']
if not len(host)<101:
return {"message":"Please provide proper host within 100 characters.."}, 400
uploaded_time = datetime.datetime.now()
else:
return {"message":"Entered Request body is incorrect.."}, 400
podcast = PodcastModel(id=audioFileId,
name = name,
duration = duration,
host = host,
uploaded_time = uploaded_time
)
db.session.add(podcast)
elif audioFileType == "Audiobook":
args = ("title","duration","author","narrator")
req = request.form
if req:
if len(req)==len(args):
for key in req:
if key not in args:
return {"message":f"{key} key in the request body is incorrect.."}, 400
name = req['title']
if not len(name)<101:
return {"message":"Please provide proper title within 100 characters.."}, 400
try:
duration = int(req['duration'])
except:
return {"message":"Type of duration is not int.."}, 400
author = req['author']
if not len(author)<101:
return {"message":"Please provide proper author name within 100 characters.."}, 400
narrator = req['narrator']
if not len(narrator)<101:
return {"message":"Please provide proper narrator name within 100 characters.."}, 400
uploaded_time = datetime.datetime.now()
else:
return {"message":"Entered Request body is incorrect.."}, 400
audiobook = AudioBookModel(id=audioFileId,
name=name,
duration=duration,
uploaded_time=uploaded_time,
author=author,
narrator=narrator
)
db.session.add(audiobook)
else:
return {"message":f"{audioFileType} is not Valid.."}, 400
db.session.commit()
return {"message":"success"}
except IntegrityError:
db.session.rollback()
return {"message":f"{audioFileType} of ID {audioFileId} has already existed"}, 400
except Exception as e:
return {"message":"Please check the Payload"}, 400
def patch(self,audioFileType,audioFileId):
if audioFileType in ("Song","Podcast","Audiobook"):
try:
if audioFileType == "Song":
args = ("name","duration")
req = request.form
if req:
for key in req:
if key not in args:
return {"message":f"{key} key in the request body is incorrect.."}, 400
song = SongModel.query.filter_by(id=audioFileId).first()
if 'name' in req:
if len(req["name"])>100:
return {"message":"Name is more than 100 characters"}, 400
else:
song.name = req["name"]
if 'duration' in req:
try:
song.duration = int(req["duration"])
except:
return {"message":"Type of duration is not int.."}, 400
db.session.commit()
elif audioFileType == "Podcast":
args = ("name", "duration", "host")
req = request.form
if req:
for key in req:
if key not in args:
return {"message":f"{key} key in the request body is incorrect.."}, 400
podcast = PodcastModel.query.filter_by(id=audioFileId).first()
if 'name' in req:
if len(req["name"])>100:
return {"message":"Name is more than 100 characters"}, 400
else:
podcast.name = req["name"]
if 'duration' in req:
try:
podcast.duration = int(req["duration"])
except:
return {"message":"Type of duration is not int.."}, 400
if 'host' in req:
if len(req["host"])>100:
return {"message":"Host is more than 100 characters"}, 400
else:
podcast.host = req["host"]
db.session.commit()
elif audioFileType == "Audiobook":
args = ("title", "duration", "narrator", "author")
req = request.form
if req:
for key in req:
if key not in args:
return {"message":f"{key} key in the request body is incorrect.."}, 400
audiobook = AudioBookModel.query.filter_by(id=audioFileId).first()
if 'title' in req:
if len(req["title"])>100:
return {"message":"Title is more than 100 characters"}, 400
else:
audiobook.name = req["title"]
if 'duration' in req:
try:
audiobook.duration = int(req["duration"])
except:
return {"message":"Type of duration is not int.."}, 400
if 'narrator' in req:
if len(req["narrator"])>100:
return {"message":"Narrator is more than 100 characters"}, 400
else:
audiobook.narrator = req["narrator"]
if 'author' in req:
if len(req["author"])>100:
return {"message":"Author is more than 100 characters"}, 400
else:
audiobook.author = req["author"]
db.session.commit()
return {"message":"Success"}
except AttributeError:
return {"message":f"{audioFileType} with ID-{audioFileId} doesn't exists.."}, 400
else:
return {"message":f"{audioFileType} is not valid.."}, 400
def delete(self,audioFileType,audioFileId):
if audioFileType in ("Song","Podcast","Audiobook"):
try:
if audioFileType == "Song":
song = SongModel.query.filter_by(id=audioFileId).first()
db.session.delete(song)
if audioFileType == "Podcast":
podcast = PodcastModel.query.filter_by(id=audioFileId).first()
db.session.delete(podcast)
if audioFileType == "Audiobook":
audiobook = AudioBookModel.query.filter_by(id=audioFileId).first()
db.session.delete(audiobook)
db.session.commit()
return {"message":"success"}
except AttributeError:
return {"message":f"{audioFileType} with ID-{audioFileId} doesn't exists.."}, 400
else:
return {"message":f"{audioFileType} is not valid.."}, 400
# Route to get the data of all the audiofiles of the requested type
class GetAudioFiles(Resource):
def get(self,audioFileType):
if audioFileType in ("Song","Podcast","Audiobook"):
data = {}
if audioFileType == "Song":
songs = SongModel.query.all()
for song in songs:
song_data = {"name":song.name,"duration":song.duration,"uploaded_time":str(song.uploaded_time)}
data[f'{song.id}'] = song_data
return {"Songs":data}
if audioFileType == "Audiobook":
audiobooks = AudioBookModel.query.all()
for audiobook in audiobooks:
audiobook_data = {"title":audiobook.name,"duration":audiobook.duration,"author":audiobook.author,
"narrator":audiobook.narrator,"uploaded_time":str(audiobook.uploaded_time)}
data[f'{audiobook.id}'] = audiobook_data
return {"Audiobooks":data}
if audioFileType == "Podcast":
podcasts = PodcastModel.query.all()
for podcast in podcasts:
podcast_data = {"name":podcast.name,"duration":podcast.duration,"host":podcast.host,
"uploaded_time":str(podcast.uploaded_time)}
data[f'{podcast.id}'] = podcast_data
return {"Podcasts":data}
else:
return {"message":f"{audioFileType} is not valid.."}, 400
# Adding routes
api.add_resource(AudioFile,"/<string:audioFileType>/<int:audioFileId>")
api.add_resource(GetAudioFiles,"/<string:audioFileType>")
if __name__ == "__main__":
app.run(debug=True)<file_sep># audio_api
Flask Audio File Web API for an audiofile server.
Run pip install -r requirements.txt
Use Endpoints like Song or Podcast or Audiobook.
Run python3 main.py to initialise the audio file server.
Run python3 test.py in another terminal to connect to the server.
<file_sep>import requests
BASE = "http://127.0.0.1:5000/"
response = requests.put(BASE + "Song/111112", {"name":"xyz", "duration":111})
# response = requests.put(BASE + "Podcast/11111", {"name":"xyz", "duration":111, "host":"pqr"})
# response = requests.put(BASE + "Audiobook/11111", {"title":"xyz", "duration":111, "author":"abc", "narrator":"pqr"})
response = requests.patch(BASE + "Song/111112", {"title":"xyz", "duration":111, "author":"abc", "narrator":"pqr"})
# response = requests.patch(BASE + "Podcast/11111", {"title":"xyz", "duration":111, "author":"abc", "narrator":"pqr"})
# response = requests.patch(BASE + "Audiobook/11111", {"title":"xyz", "duration":111, "author":"abc", "narrator":"pqr"})
response = requests.get(BASE + "Song/111112")
# response = requests.get(BASE + "Podcast/11111")
# response = requests.get(BASE + "Audiobook/11111")
response = requests.get(BASE + "Song")
# response = requests.get(BASE + "Podcast")
# response = requests.get(BASE + "Audiobook")
print(response.json())
print(response.status_code)
response = requests.delete(BASE + "Song/111112")
# response = requests.delete(BASE + "Podcast/1111")
# response = requests.delete(BASE + "Audiobook/1111") | ebeb322888c119760e11b399d7617e40cbfa58ce | [
"Markdown",
"Python"
] | 3 | Python | sagarnimma/audio_api | 0e0327152732ebfa66f6b428c490aeaa52aa1b7d | a287efe2c1776a64e39720b348aa995fae03baa8 |
refs/heads/master | <file_sep>'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Metadata.
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> Brightcove;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n',
// Task configuration.
clean: {
files: ['build', 'dist', 'tmp']
},
concat: {
options: {
banner: '<%= banner %>',
stripBanners: true
},
dist: {
nonull: true,
src: ['src/videojs-share.js'],
dest: 'dist/videojs.share.js'
}
},
uglify: {
options: {
banner: '<%= banner %>'
},
dist: {
src: '<%= concat.dist.dest %>',
dest: 'dist/videojs.share.min.js'
}
},
qunit: {
files: ['test/**/*.html', '!test/perf.html', '!test/muxer/**']
},
jshint: {
gruntfile: {
options: {
jshintrc: '.jshintrc'
},
src: 'Gruntfile.js'
},
src: {
options: {
jshintrc: 'src/.jshintrc'
},
src: ['src/**/*.js']
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/**/*.js',
'!test/tsSegment.js',
'!test/fixtures/*.js',
'!test/manifest/**',
'!test/muxer/**']
}
},
connect: {
dev: {
options: {
port: 9999,
keepalive: true
}
}
},
open : {
dev : {
path: 'http://127.0.0.1:<%= connect.dev.options.port %>/example.html',
app: 'Google Chrome'
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
src: {
files: '<%= jshint.src.src %>',
tasks: ['jshint:src', 'qunit']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'qunit']
}
},
mxmlc: {
options: {
// http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_16.html
metadata: {
// `-title "Adobe Flex Application"`
title: 'VideoJS SWF',
// `-description "http://www.adobe.com/flex"`
description: 'http://www.videojs.com',
// `-publisher "The Publisher"`
publisher: 'Brightcove, Inc.',
// `-creator "The Author"`
creator: 'Brightcove, Inc.',
// `-language=EN`
// `-language+=klingon`
language: 'EN',
// `-localized-title "The Color" en-us -localized-title "The Colour" en-ca`
localizedTitle: null,
// `-localized-description "Standardized Color" en-us -localized-description "Standardised Colour" en-ca`
localizedDescription: null,
// `-contributor "Contributor #1" -contributor "Contributor #2"`
contributor: null,
// `-date "Mar 10, 2013"`
date: null
},
// http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_18.html
application: {
// `-default-size 240 240`
layoutSize: {
width: 640,
height: 360
},
// `-default-frame-rate=24`
frameRate: 30,
// `-default-background-color=0x869CA7`
backgroundColor: 0x000000,
// `-default-script-limits 1000 60`
scriptLimits: {
maxRecursionDepth: 1000,
maxExecutionTime: 60
}
},
// http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_19.html
// `-library-path+=libraryPath1 -library-path+=libraryPath2`
libraries: ['libs/*.*'],
// http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_14.html
// http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_17.html
// http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_20.html
// http://livedocs.adobe.com/flex/3/html/help.html?content=compilers_21.html
compiler: {
// `-accessible=false`
'accessible': false,
// `-actionscript-file-encoding=UTF-8`
'actionscriptFileEncoding': null,
// `-allow-source-path-overlap=false`
'allowSourcePathOverlap': false,
// `-as3=true`
'as3': true,
// `-benchmark=true`
'benchmark': true,
// `-context-root context-path`
'contextRoot': null,
// `-debug=false`
'debug': false,
// `-defaults-css-files filePath1 ...`
'defaultsCssFiles': [],
// `-defaults-css-url http://example.com/main.css`
'defaultsCssUrl': null,
// `-define=CONFIG::debugging,true -define=CONFIG::release,false`
// `-define+=CONFIG::bool2,false -define+=CONFIG::and1,"CONFIG::bool2 && false"
// `-define+=NAMES::Company,"'Adobe Systems'"`
'defines': {},
// `-es=true -as3=false`
'es': false,
// `-externs className1 ...`
'externs': [],
// `-external-library-path+=pathElement`
'externalLibraries': [],
'fonts': {
// `-fonts.advanced-anti-aliasing=false`
advancedAntiAliasing: false,
// `-fonts.languages.language-range "Alpha and Plus" "U+0041-U+007F,U+002B"`
// USAGE:
// ```
// languages: [{
// lang: 'Alpha and Plus',
// range: ['U+0041-U+007F', 'U+002B']
// }]
// ```
languages: [],
// `-fonts.local-fonts-snapsnot filePath`
localFontsSnapshot: null,
// `-fonts.managers flash.fonts.JREFontManager flash.fonts.BatikFontManager flash.fonts.AFEFontManager`
// NOTE: FontManager preference is in REVERSE order (prefers LAST array item).
// For more info, see http://livedocs.adobe.com/flex/3/html/help.html?content=fonts_06.html
managers: []
},
// `-incremental=false`
'incremental': false
}
},
videojs_swf: {
files: {
'src/swf/clipboard.swf': ['src/swf/ClipboardAPI.as']
}
}
},
concurrent: {
dev: {
tasks: ['connect', 'open', 'watch'],
options: {
logConcurrentOutput: true
}
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-open');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-shell');
grunt.registerMultiTask('mxmlc', 'Compiling SWF', function () {
// Merge task-specific and/or target-specific options with these defaults.
var childProcess = require('child_process');
var flexSdk = require('flex-sdk');
var async = require('async');
var pkg = grunt.file.readJSON('package.json');
var
options = this.options,
done = this.async(),
maxConcurrency = 1,
q,
workerFn;
workerFn = function(f, callback) {
// Concat specified files.
var srcList = f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.error('Source file "' + filepath + '" not found.');
return false;
}
else {
return true;
}
});
var cmdLineOpts = [];
if (f.dest) {
cmdLineOpts.push('-output');
cmdLineOpts.push(f.dest);
}
cmdLineOpts.push('-define=CONFIG::version, "' + pkg.version + '"');
cmdLineOpts.push('--');
cmdLineOpts.push.apply(cmdLineOpts, srcList);
grunt.verbose.writeln('package version: ' + pkg.version);
grunt.verbose.writeln('mxmlc path: ' + flexSdk.bin.mxmlc);
grunt.verbose.writeln('options: ' + JSON.stringify(cmdLineOpts));
// Compile!
childProcess.execFile(flexSdk.bin.mxmlc, cmdLineOpts, function(err, stdout, stderr) {
if (!err) {
grunt.log.writeln('File "' + f.dest + '" created.');
}
else {
grunt.log.error(err.toString());
grunt.verbose.writeln('stdout: ' + stdout);
grunt.verbose.writeln('stderr: ' + stderr);
if (options.force === true) {
grunt.log.warn('Should have failed but will continue because this task had the `force` option set to `true`.');
}
else {
grunt.fail.warn('FAILED');
}
}
callback(err);
});
};
q = async.queue(workerFn, maxConcurrency);
q.drain = done;
q.push(this.files);
});
// Launch a Development Environment
grunt.registerTask('dev', 'Launching Dev Environment', 'concurrent:dev');
// Default task.
grunt.registerTask('default',
['clean',
'jshint',
'manifests-to-js',
'qunit',
'concat',
'uglify']);
};
<file_sep>/* Share Control Bar Button
================================================================================ */
videojs.ShareButton = videojs.Component.extend({
init: function(player, options) {
videojs.Component.call(this, player, options);
this.createEl('div');
this.closeButton = new videojs.Component(player);
this.closeButton.createEl('i');
this.addClass('vjs-share-control fa fa-share fa-2x white');
this.addChild(this.closeButton);
this.on('click', this.onClick);
}
});
videojs.ShareButton.prototype.onClick = function() {
player.trigger('showshareoverlay');
};
<file_sep># VideoJS Share Screen Plugin
A video.js plugin that allows a configurable share screen during playback.
## Getting Started
On your web page:
```html
<script src="video.js"></script>
<script src="src/js/videojs-share.js"></script>
<script src="src/js/ui/share-overlay.js"></script>
<script src="src/js/ui/share-control-bar-button.js"></script>
<script>
var player = videojs('video');
// See Plugin code for model schema
var optionalShareObject = {};
player.share(optionalShareObject);
player.play();
</script>
```
### Documentation
This is a demo repo for Brightcove consideration. Please see the example.html. If
using the Connect server grunt task, it should open at the following url:
http://localhost:9999/example.html
Some notes are as follows;
1. This plugin requires a compiled SWF for the clipboard functionality. This
works across desktop but mobile will still need some workaround. Clipboard API
in browsers not universally supported yet.
2. To test the clipboard API, click on either the direct link or embed code then
paste elsewhere.
3. The plugin has the following grunt commands;
#### Build SWF
```bash
grunt mxmlc
```
#### Start Development Server
```bash
grunt connect
```
#### Build Distribution package
```bash
grunt dist
```
### Events
#### showshareoverlay
Fired from player to show the share overlay screen.
#### hideshareoverlay
Fired from player to hide the share overlay screen.
<file_sep>/* Share Overlay
================================================================================ */
videojs.ShareOverlay = videojs.Component.extend({
init: function(player, options) {
videojs.Component.call(this, player, options);
this.createEl();
this.hide();
this.setDetails(player.share);
player.on('showshareoverlay', this.onShowShareOverlay);
player.on('hideshareoverlay', this.onHideShareOverlay);
}
});
var createShareOverlayContainer = function() {
return "<div class=\"vjs-share-options-container\">" +
"<div class=\"vjs-share-options-container-asset-title\">Share Video:<\/div>" +
"<div class=\"vjs-share-options-container-social-container\">" +
"<div class=\"vjs-share-options-container-section-title\">Share via:<\/div>" +
"<div class=\"vjs-share-options-container-social-icon-container\">" +
"<span class=\"fa-stack fa-lg\">" +
"<i class=\"fa fa-square fa-2x vjs-share-options-container-social-icon-fb\"><\/i>" +
"<i class=\"fa fa-facebook fa-stack-1x vjs-share-options-container-social-icon\"><\/i>" +
"<\/span>" +
"<span class=\"fa-stack fa-lg\">" +
"<i class=\"fa fa-square fa-2x vjs-share-options-container-social-icon-gp\"><\/i>" +
"<i class=\"fa fa-google-plus fa-stack-1x vjs-share-options-container-social-icon\"><\/i>" +
"<\/span>" +
"<span class=\"fa-stack fa-lg\">" +
"<i class=\"fa fa-square fa-2x vjs-share-options-container-social-icon-tw\"><\/i>" +
"<i class=\"fa fa-twitter fa-stack-1x vjs-share-options-container-social-icon\"><\/i>" +
"<\/span>" +
"<span class=\"fa-stack fa-lg\">" +
"<i class=\"fa fa-square fa-2x vjs-share-options-container-social-icon-tu\"><\/i>" +
"<i class=\"fa fa-tumblr fa-stack-1x vjs-share-options-container-social-icon\"><\/i>" +
"<\/span>" +
"<span class=\"fa-stack fa-lg\">" +
"<i class=\"fa fa-square fa-2x vjs-share-options-container-social-icon-pt\"><\/i>" +
"<i class=\"fa fa-pinterest fa-stack-1x vjs-share-options-container-social-icon\"><\/i>" +
"<\/span>" +
"<span class=\"fa-stack fa-lg\">" +
"<i class=\"fa fa-square fa-2x vjs-share-options-container-social-icon-in\"><\/i>" +
"<i class=\"fa fa-linkedin fa-stack-1x vjs-share-options-container-social-icon\"><\/i>" +
"<\/span>" +
"<\/div>" +
"<br style=\"clear: both\">" +
"<div class=\"vjs-share-options-input-row\">" +
"<div class=\"vjs-share-options-direct-link-container\">" +
"<div class=\"vjs-share-options-container-section-title\">Direct Link:<\/div>" +
"<div class=\"vjs-share-options-direct-link-input\">Direct Link<\/div>" +
"<div class=\"vjs-share-clipboard-container-direct-link\"></div>" +
"<\/div>" +
"<div class=\"vjs-share-options-start-time-container\">" +
"<div class=\"vjs-share-options-container-section-title\">Start Time:<\/div>" +
"<div class=\"vjs-share-options-start-time-input\">00:00<\/div>" +
"<\/div>" +
"<div class=\"vjs-share-options-input-row\">" +
"<div class=\"vjs-share-options-embed-container\">" +
"<div class=\"vjs-share-options-container-section-title\">Embed Code:<\/div>" +
"<div class=\"vjs-share-options-embed-input\">Embed Code Here<\/div>" +
"<div class=\"vjs-share-clipboard-container-embed-code\"></div>" +
"<\/div><\/div><\/div><\/div><\/div>";
};
var createClipboardSWF = function (url, className, elementId, playerId) {
var div = document.createElement('div'),
params =
'<param name="flashvars" value="playerId=' + playerId + '">' +
'<param name="wmode" value="transparent">' +
'<param name="AllowScriptAccess" value="always">',
id = elementId,
object;
// create a cross-browser friendly SWF embed
div.innerHTML =
'<!--[if !IE]>-->' +
'<object width="100%" height="100%" type="application/x-shockwave-flash">' +
'<param name="movie" value="'+ url +'">' + params +
'</object>' +
'<!--<![endif]-->';
object = div.querySelector('object');
// build an embed for IE<10
if (!object) {
div.innerHTML =
'<object width="100%" height="100%" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">' +
'<param name="movie" value="'+ url +'">' + params +
'</object>';
}
object.id = id;
object.name = id;
object.className = className;
return object.outerHTML;
};
var createLinkIcon = function (object) {
return "<a target=\"_blank\" href=\""+ object.url.toLowerCase() +"\">" +
"<span class=\"fa-stack fa-lg\">" +
"<i class=\"fa fa-square fa-2x "+ object.backgroundClass + "\"><\/i>" +
"<i class=\"fa fa-"+object.name.toLowerCase()+" fa-stack-1x vjs-share-options-container-social-icon\"><\/i>" +
"<\/span></a>";
};
videojs.ShareOverlay.prototype.createEl = function() {
this.el().innerHTML = createShareOverlayContainer();
this.addClass('vjs-share-overlay');
this.closeButton = new videojs.Component(player);
this.closeButton.createEl();
this.closeButton.addClass('fa fa-times fa-2x vjs-share-options-container-close-icon white');
this.closeButton.on('click', this.onCloseButtonClick);
this.addChild(this.closeButton);
this.overlayContainer = this.el().children[0];
this.titleElement = this.overlayContainer.querySelector('.vjs-share-options-container-asset-title');
this.timeElement = this.overlayContainer.querySelector('.vjs-share-options-start-time-input');
this.linkElement = this.overlayContainer.querySelector('.vjs-share-options-direct-link-input');
this.linkElement.addEventListener('click', this.onDirectLinkClick);
this.embedCodeElement = this.overlayContainer.querySelector('.vjs-share-options-embed-input');
this.embedCodeElement.addEventListener('click', this.onEmbedCodeClick);
this.directLinkSWFContainer = this.overlayContainer.querySelector('.vjs-share-clipboard-container-direct-link');
this.directLinkSWFContainer.innerHTML = createClipboardSWF(videojs.share.swf, 'vjs-clipboard-swf-direct-link', 'vjs-share-clipboard-api-direct-link', player.el().id);
this.embedCodeSWFContainer = this.overlayContainer.querySelector('.vjs-share-clipboard-container-embed-code');
this.embedCodeSWFContainer.innerHTML = createClipboardSWF(videojs.share.swf, 'vjs-clipboard-swf-embed-code', 'vjs-share-clipboard-api-embed-code', player.el().id);
this.socialIconContainer = this.overlayContainer.querySelector('.vjs-share-options-container-social-icon-container');
videojs.share.clipboardAPI = {};
videojs.share.clipboardAPI.directLink = this.directLinkSWFContainer.querySelector('.vjs-clipboard-swf-direct-link');
videojs.share.clipboardAPI.embedCode = this.embedCodeSWFContainer.querySelector('.vjs-clipboard-swf-embed-code');
return this.el();
};
videojs.ShareOverlay.prototype.setDetails = function(details) {
if(!details) {
details = videojs.share.defaults;
}
this.title(details.title);
this.directLink(details.directLink);
this.embedCode(details.embedCode);
this.startTime(player.currentTime());
this.socialIconContainer.innerHTML = "";
for (i in details.networks) {
this.socialIconContainer.innerHTML += createLinkIcon(details.networks[i]);
}
};
videojs.ShareOverlay.prototype.title = function(title) {
if(title) {
this.titleElement.innerHTML = "Share Video: " + title;
}
return this.titleElement.innerHTML.substr(13);
};
videojs.ShareOverlay.prototype.directLink = function(url) {
if(url) {
this.linkElement.innerHTML = (url.length > 55) ? url.substr(0,55) + '...' : url;
setTimeout(function() {
try {
videojs.share.clipboardAPI.directLink.copy(url);
} catch (error) {
}
}, 500);
}
return this.linkElement.innerHTML;
};
videojs.ShareOverlay.prototype.startTime = function(time) {
if(time) {
this.timeElement.innerHTML = this.formatTime(time);
}
return this.timeElement.innerHTML;
};
videojs.ShareOverlay.prototype.embedCode = function(code) {
if(code) {
this.embedCodeElement.innerHTML = (code.length > 85) ? code.substr(0,85) + '...' : code;
setTimeout(function() {
try {
videojs.share.clipboardAPI.embedCode.copy(code);
} catch (error) {
}
}, 500);
}
return this.embedCodeElement.innerHTML;
};
/**
* Event handler for player.on('showshareoverlay')
*/
videojs.ShareOverlay.prototype.onShowShareOverlay = function() {
this.share.paused = this.paused();
this.pause();
this.children.shareOverlay.setDetails(this.share);
this.children.shareOverlay.show();
};
/**
* Event handler for player.on('hideshareoverlay');
*/
videojs.ShareOverlay.prototype.onHideShareOverlay = function() {
this.children.shareOverlay.hide();
if(!this.share.paused) {
this.play();
}
};
/**
* Event handler for close button click
*/
videojs.ShareOverlay.prototype.onCloseButtonClick = function() {
player.trigger('hideshareoverlay');
};
/**
* Format seconds as a time string, H:MM:SS or M:SS
* Supplying a guide (in seconds) will force a number of leading zeros
* to cover the length of the guide
* @param {Number} seconds Number of seconds to be turned into a string
* @param {Number} guide Number (in seconds) to model the string after
* @return {String} Time formatted as H:MM:SS or M:SS
* @private
*/
videojs.ShareOverlay.prototype.formatTime = function(seconds, guide) {
// Default to using seconds as guide
guide = guide || seconds;
var s = Math.floor(seconds % 60),
m = Math.floor(seconds / 60 % 60),
h = Math.floor(seconds / 3600),
gm = Math.floor(guide / 60 % 60),
gh = Math.floor(guide / 3600);
// handle invalid times
if (isNaN(seconds) || seconds === Infinity) {
// '-' is false for all relational operators (e.g. <, >=) so this setting
// will add the minimum number of fields specified by the guide
h = m = s = '-';
}
// Check if we need to show hours
h = (h > 0 || gh > 0) ? h + ':' : '';
// If hours are showing, we may need to add a leading zero.
// Always show at least one digit of minutes.
m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':';
// Check if leading zero is need for seconds
s = (s < 10) ? '0' + s : s;
return h + m + s;
}; | 5b70e222ee36326728a30882d3d1a7a8c485d74b | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | dmlap/videojs-share | 0e6a0f78a200331f1fcdad224596b2448bb0763e | c393de8643fa8dac12552793e2ea91e458b5de65 |
refs/heads/main | <repo_name>moneymouse/backable<file_sep>/app/src/components/Svg/types.ts
import { SVGAttributes } from "react";
import { SpaceProps } from "styled-system";
export interface SvgProps extends SVGAttributes<HTMLOrSVGElement>, SpaceProps {}
export type IconComponentType = {
iconName: string;
isActive?: boolean;
height?: string;
width?: string;
activeColor?: string;
} & SvgProps;<file_sep>/README.md
# Backable
<p align="center"><img src="./assets/readme-header.png" alt="Verge Source Code"></p>
<p>
<img src="https://img.shields.io/badge/license-MIT-blue.svg">
</p>
**Backable Address contract on Testnet**: `0x98d9d37089E93592ca583f42672b0155EE9D8465`
## What is Backable?
Backable is the first decentralized and collateralized stablecoin protocol with a value pegged to the US dollar on the Nervos network.
`1 BCUSD = 1 USD`.
Backable will bring stability to payments with cryptocurrencies to merchants and users who want to use them in their frequent payments and thanks to Nervos it will be part of the universal passport to blockchain.
Backable will open up new opportunities with a barrier-free and soon a more stable economy.
## Why Nervos?
Nervos breaks with several of the current problems of Bitcoin and Ethereum, mainly with the problem of the blockchain trilemma.
- Read about the Blockchain Trilemma [here](https://coinmarketcap.com/alexandria/glossary/blockchain-trilemma).
Nervos is the only blockchain that truly seeks interoperability, this allows Backable to not only reach Nervos users but also Ethereum users and soon other blockchains.
## Why Backable?
Cryptocurrencies are growing at an accelerated rate, even the country of El Salvador in Latin America allowed the use of Bitcoin as a legal means of payment, but this will bring a lot of conflict for certain types of payment such as micropayments and payments that require speed, confirmation almost instantaneous and price stability in the face of fluctuations.
That is why Backable was born to provide a stable currency (for the moment pegged to the USD nothing else), fast payments and allowing micropayments as well.
Backable will not only be a protocol to allow a decentralized collateralized stablecoin, but it also hopes to become a whole monetary ecosystem for the new interoperable web 3.0.
## What role does NATOR play within Backable?
Technology projects, and especially the most innovative ones, may fail in the future due to lack of good government or just someone to govern them. So it is crucial to ensure the project in the long term and that it is better managed by your own community.
That is why the governance token, `NATOR`, was created, which will have a voting weight at the project level and will allow users who so decide to become a Backable governor.
Among the options that can be voted on are:
- Smart contracts and protocol updates
- Policies
- Reward percentage
- Percentage of the fund for contributors
- Partnerships
At the beginning of Backable's development, voting will be off-chain through a web platform, but as the project evolves it will become a chain.
## NATOR's Tokenomics
**Market Cap**: `10,000,000 NATOR`

## Build Frontend
```
$cd app
```
```
$npm install
```
```
$npm run build
```
or dev
```
$npm run start
```
| bcf7cee6c00d017a3478ec7b7552c571747babdf | [
"Markdown",
"TypeScript"
] | 2 | TypeScript | moneymouse/backable | 15aa8564222bd5008b4250e51a966e56a9063fe1 | cb15add18f38c3acc14b0edfe50dd673c9854fa9 |
refs/heads/master | <repo_name>gitachyut/ns-reporting<file_sep>/export-comments.js
const request = require('request');
const APITOKEN = '7e2d8c0eaccd1e81d8b1ee121ee3031ce9e83bf32897ae995c420d737e4024c0';
const initiateCommentsDownloader = (url, media, type = null) => new Promise((resolve, reject) => {
let options;
if(media === 'twitter'){
options = {
url: `https://exportcomments.com/api/v2/export?url=${url}&replies=true&nested=true&twitterType=Tweets`,
method: 'PUT',
headers: {
'X-AUTH-TOKEN': <PASSWORD>
}
};
}else{
options = {
url: `https://exportcomments.com/api/v2/export?url=${url}&replies=true&nested=true`,
method: 'PUT',
headers: {
'X-AUTH-TOKEN': <PASSWORD>
}
};
}
request(options, function(err, res, body) {
if(err){
console.log(err);
reject(err);
}else{
let json = JSON.parse(body);
console.log(json)
resolve(json);
}
});
})
const checkStatus = (id) => new Promise((resolve, reject) => {
const options = {
url: `https://exportcomments.com/api/v2/export?guid=${id}`,
method: 'GET',
headers: {
'X-AUTH-TOKEN': <PASSWORD>
}
};
request(options, function(err, res, body) {
if(err){
console.log("error:", err);
reject(err);
}else{
let json = JSON.parse(body);
resolve(json);
}
});
})
// https://www.facebook.com/ulive.sg/posts/10158686643617177
// initiateCommentsDownloader('https://www.facebook.com/ulive.sg/posts/10158686643617177')
// .then(res => console.log(res))
// .catch(err => console.log(err))
module.exports = {
initiateCommentsDownloader,
checkStatus
}<file_sep>/unused/excel.js
const ExcelJS = require('exceljs');
const loadXLS = async () => {
const wb = new ExcelJS.Workbook();
const excelFile = await wb.xlsx.readFile('./comments.xlsx');
let ws = excelFile.getWorksheet('ExportComments.com');
// console.log(ws.getSheetValues())
let data = ws.getSheetValues();
data.map(r => {
return [r[3],r[2],r[3]]
})
data.shift();
data.shift();
data = data.map((r,i)=>{
if(i === 0){
// return [
// 'Item',
// 'Hot Links',
// r[4]
// ]
return [
'Post Link',
r[2],
''
]
}
// if(i === 1){
// return [
// 'Sequence',
// 'Date',
// 'Comment'
// ]
// }
if( i > 1){
if(r[2]){
let t = r[2].replace('-', '.')
return [
parseFloat(t), r[5], r[7]
]
}else{
if(r[1])
return [
r[1], r[5], r[7]
]
}
}
})
console.log(data);
}
loadXLS()<file_sep>/unused/downloder.js
const got = require("got");
const { createWriteStream } = require("fs");
const url = "https://exportcomments.com/exports/comments5fda343de89a5-4834360433301753.xlsx";
const fileName = "./downloads/omments5fda343de89a5-4834360433301753.xlsx";
const downloadStream = got.stream(url);
const fileWriterStream = createWriteStream(fileName);
downloadStream
.on("downloadProgress", ({ transferred, total, percent }) => {
const percentage = Math.round(percent * 100);
console.error(`progress: ${transferred}/${total} (${percentage}%)`);
})
.on("error", (error) => {
console.error(`Download failed: ${error.message}`);
});
fileWriterStream
.on("error", (error) => {
console.error(`Could not write file to system: ${error.message}`);
})
.on("finish", () => {
console.log(`File downloaded to ${fileName}`);
});
downloadStream.pipe(fileWriterStream);<file_sep>/app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { startDownload } = require('./download');
const app = new express();
// Response body parser
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
// Cors setup
app.use(cors())
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
next();
});
app.post('/comment-scrap', (req,res)=>{
const {
url,
sheetName,
spreadsheetId,
workSheetName
} = req.body;
const sheetMeta = {
spreadsheetId: spreadsheetId,
workSheetName: workSheetName || null
}
// console.log(url, sheetName, sheetMeta)
startDownload(url, sheetName, sheetMeta)
.then(( res) => {
res.json({
done: true
});
})
.catch(err => res.json({
fail: true
}))
})
module.exports = app;
| bb7e03f5c6e80f1fff95a4a68d8031f84ecd1f6c | [
"JavaScript"
] | 4 | JavaScript | gitachyut/ns-reporting | 841551651b91de4052d3507c5dd37d6eb04276fe | 4c02419df33446d24f15d03b507fc98977b089dd |
refs/heads/master | <repo_name>africanrt/action-scheduler-high-volume<file_sep>/action-scheduler-high-volume.php
<?php
/**
* Plugin Name: Action Scheduler High Volume
* Plugin URI: https://github.com/prospress/action-scheduler-high-volume
* Description: Increase Action Scheduler batch size, concurrency and timeout period to process large queues of actions more quickly on servers with more server resources.
* Author: Prospress Inc.
* Author URI: http://prospress.com/
* Version: 1.1.0
*
* Copyright 2018 Prospress, Inc. (email : <EMAIL>)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author <NAME>
* @since 1.0
*/
/**
* Action scheduler claims a batch of actions to process in each request. It keeps the batch
* fairly small (by default, 25) in order to prevent errors, like memory exhaustion.
*
* This method increases it so that more actions are processed in each queue, which speeds up the
* overall queue processing time due to latency in requests and the minimum 1 minute between each
* queue being processed.
*
* For more details, see: https://actionscheduler.org/perf/#increasing-batch-size
*/
function ashp_increase_queue_batch_size( $batch_size ) {
return $batch_size * 4;
}
add_filter( 'action_scheduler_queue_runner_batch_size', 'ashp_increase_queue_batch_size' );
/**
* Action scheduler processes queues of actions in parallel to speed up the processing of large numbers
* If each queue takes a long time, this will result in multiple PHP processes being used to process actions,
* which can prevent PHP processes being available to serve requests from visitors. This is why it defaults to
* only 5. However, on high volume sites, this can be increased to speed up the processing time for actions.
*
* This method hextuples the default so that more queues can be processed concurrently. Use with caution as doing
* this can take down your site completely depending on your PHP configuration.
*
* For more details, see: https://actionscheduler.org/perf/#increasing-concurrent-batches
*/
function ashp_increase_concurrent_batches( $concurrent_batches ) {
return $concurrent_batches * 2;
}
add_filter( 'action_scheduler_queue_runner_concurrent_batches', 'ashp_increase_concurrent_batches' );
/**
* Action scheduler reset actions claimed for more than 5 minutes. Because we're increasing the batch size, we
* also want to increase the amount of time given to queues before reseting claimed actions.
*/
function ashp_increase_timeout( $timeout ) {
return $timeout * 3;
}
add_filter( 'action_scheduler_timeout_period', 'ashp_increase_timeout' );
add_filter( 'action_scheduler_failure_period', 'ashp_increase_timeout' );
/**
* Action scheduler initiates one queue runner every time the 'action_scheduler_run_queue' action is triggered.
*
* Because this action is only triggered at most once every minute, that means it would take 30 minutes to spin
* up 30 queues. To handle high volume sites with powerful servers, we want to initiate additional queue runners
* whenever the 'action_scheduler_run_queue' is run, so we'll kick off secure requests to our server to do that.
*/
function ashp_request_additional_runners() {
// allow self-signed SSL certificates
add_filter( 'https_local_ssl_verify', '__return_false', 100 );
for ( $i = 0; $i < 5; $i++ ) {
$response = wp_remote_post( admin_url( 'admin-ajax.php' ), array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => false,
'headers' => array(),
'body' => array(
'action' => 'ashp_create_additional_runners',
'instance' => $i,
'ashp_nonce' => wp_create_nonce( 'ashp_additional_runner_' . $i ),
),
'cookies' => array(),
) );
}
}
add_action( 'action_scheduler_run_queue', 'ashp_request_additional_runners', 0 );
/**
* Handle requests initiated by ashp_request_additional_runners() and start a queue runner if the request is valid.
*/
function ashp_create_additional_runners() {
if ( isset( $_POST['ashp_nonce'] ) && isset( $_POST['instance'] ) && wp_verify_nonce( $_POST['ashp_nonce'], 'ashp_additional_runner_' . $_POST['instance'] ) ) {
ActionScheduler_QueueRunner::instance()->run();
}
wp_die();
}
add_action( 'wp_ajax_nopriv_ashp_create_additional_runners', 'ashp_create_additional_runners', 0 );
/**
* Action Scheduler provides a default maximum of 30 seconds in which to process actions. Increase this to 120
* seconds for hosts like Pantheon which support such a long time limit, or if you know your PHP and Apache, Nginx
* or other web server configs support a longer time limit.
*
* Note, WP Engine only supports a maximum of 60 seconds - if using WP Engine, this will need to be decreased to 60.
*/
function ashp_increase_time_limit() {
return 120;
}
add_filter( 'action_scheduler_queue_runner_time_limit', 'ashp_increase_time_limit' );
<file_sep>/README.md
> **Note:** With the major improvements added to Action Scheduler 3.0, most notably the migration to custom tables for storing actions and loopback requests to chain the processing of actions, the tweaks available in this plugin should be required far less often than with earlier versions of Action Scheduler.
> The code here remains mostly to demonstrate how to tweak some of the configuration that influences throughput.
### Action Scheduler High Volume
Increase the processing thresholds for Action Scheduler to process large queues of actions more quickly. Handy for high volume websites with more server resources.
This plugin will change the Action Scheduler:
* [Time Limit](https://actionscheduler.org/perf/#increasing-time-limit): to process queues for up to 120 seconds, instead of the default limit of 30 seconds*.
* [Batch Size](https://actionscheduler.org/perf/#increasing-batch-size): to process batches of 100 actions and reduce time taken to claim additional actions.
* [Concurrency](https://actionscheduler.org/perf/#increasing-concurrent-batches): to allow 10 concurrent queues to process actions, up from 5.
* [Runner Initialization Rate](https://actionscheduler.org/perf/#increasing-initialisation-rate-of-runners): to start 5 queues every time WP Cron triggers Action Scheduler (scheduled to be every minute) instead of one queue.
For more details on these changes, refer to the [Action Scheduler Performance Tuning guide](https://actionscheduler.org/perf/).
> <sup>*</sup> WP Engine only supports a maximum of 60 seconds per request - if using WP Engine, the time limit set by this plugin in the `ashp_increase_time_limit()` function will need to be decreased from 120 to 60.
| 10c033a501fedaa71d034d739267e0e8c812c7da | [
"Markdown",
"PHP"
] | 2 | PHP | africanrt/action-scheduler-high-volume | f77478766c7df0ef4cfef55a4d8d4bb46abff7e3 | 7c8bfff85ec0a6d63534784fd335ecdcd9edb7e5 |
refs/heads/main | <repo_name>tgc77/django-blog<file_sep>/comentarios/admin.py
from django.contrib import admin
from .models import Comentario
class ComentarioAdmin(admin.ModelAdmin):
list_display = ('id', 'nome', 'email', 'post', 'data_criacao', 'publicado')
list_editable = ('publicado',)
list_display_links = ('id', 'nome', 'email')
admin.site.register(Comentario, ComentarioAdmin)
<file_sep>/posts/templatetags/pfilters.py
from django import template
register = template.Library()
@register.filter
def plural_comentarios(num_coment: int) -> str:
if num_coment > 1:
return f"{num_coment} Comentarios"
else:
return f"{num_coment} Comentario"
<file_sep>/comentarios/forms.py
from typing import Any, Dict
from django.forms import ModelForm
from .models import Comentario
class FormComentario(ModelForm):
def clean(self) -> Dict[str, Any]:
data = self.cleaned_data
# nome = data.get('nome')
# email = data.get('email')
conteudo = data.get('conteudo')
# if nome == 'Tiago':
# self.add_error('nome', 'Esse usuario nao pode cementar!')
if any(palavrao in conteudo for palavrao in ['shit', 'merda', 'cacete']):
self.add_error('conteudo', 'Conteudo invalido!')
return data
class Meta:
model = Comentario
fields = ('nome', 'email', 'conteudo')
<file_sep>/comentarios/migrations/0001_initial.py
# Generated by Django 3.1.5 on 2021-04-19 22:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Comentario',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=120)),
('email', models.EmailField(max_length=254)),
('conteudo', models.TextField()),
('data_criacao', models.DateTimeField(default=django.utils.timezone.now)),
('publicado', models.BooleanField(default=False)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='posts.post')),
('usuario', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>/posts/models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse
from categorias.models import Categoria
class Post(models.Model):
titulo_post = models.CharField(max_length=255, verbose_name='Titulo')
autor_post = models.ForeignKey(
User, on_delete=models.DO_NOTHING, verbose_name='Autor')
data_post = models.DateTimeField(default=timezone.now, verbose_name='Data')
conteudo_post = models.TextField(verbose_name='Conteudo')
excerto_post = models.TextField(verbose_name='Excerto')
categoria_post = models.ForeignKey(
Categoria, on_delete=models.DO_NOTHING,
blank=True, null=True, verbose_name='Categoria')
imagem_post = models.ImageField(
upload_to='post_img/%Y/%m/%d', blank=True, null=True, verbose_name='Imagem')
publicado_post = models.BooleanField(
default=False, verbose_name='Publicado')
def __str__(self) -> str:
return self.titulo_post
# def get_absolute_url(self):
# return reverse("post_detalhes", kwargs={"pk": self.id})
<file_sep>/comentarios/models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from posts.models import Post
class Comentario(models.Model):
nome = models.CharField(max_length=120)
email = models.EmailField()
conteudo = models.TextField()
post = models.ForeignKey(Post, on_delete=models.CASCADE)
usuario = models.ForeignKey(
User, on_delete=models.DO_NOTHING, blank=True, null=True)
data_criacao = models.DateTimeField(default=timezone.now)
publicado = models.BooleanField(default=False)
def __str__(self) -> str:
return self.nome
<file_sep>/requirements.txt
asgiref==3.3.1
autopep8==1.5.4
Django==3.1.5
django-summernote==0.8.11.6
gunicorn==20.0.4
Pillow==8.1.0
pycodestyle==2.6.0
pytz==2020.5
sqlparse==0.4.1
toml==0.10.2
psycopg2
<file_sep>/README.md
# django-blog
A blog built in Django
| 4db32defb02f36e2969bc18c8a652afa4a2a4f07 | [
"Markdown",
"Python",
"Text"
] | 8 | Python | tgc77/django-blog | 0dadf81c02b7b7cb8b1a11621c7d1ab7e9de96c0 | 53c9e0e904032b38da00dee7ef8975826a186191 |
refs/heads/master | <file_sep>// 导入mysql扩展
const mysql = require("mysql");
// 设置mysql连接的属性
let connect = mysql.createConnection({
host:"localhost",
user:"root",
password:"<PASSWORD>",
database:"blog",
});
// mysql连接
connect.connect();
module.exports = connect;<file_sep>// 导入express
let express = require("express");
// 实例化路由类
let router = express.Router();
// 导入文件处理模块
const fs = require("fs");
const crypto = require('crypto');
// 导入数据库相关模块
const mysql = require("../config/db.js");
const multer = require("multer");
const upload = multer({dest:"tmp/"});
const uploads = require("../common/uploads.js");
// 导入moment模块
const moment = require("moment");
const page = require("../common/page.js");
// 前台首页
router.get('/',function(req,res,next){
// 读取网站配置相关数据'
let webConfigData = fs.readFileSync(__dirname+"/../config/webConfig.json");
let webConfig = JSON.parse(webConfigData.toString());
let p = req.query.p ? req.query.p :1;
let size = 5;
// 读取分类信息
mysql.query("select * from newstype order by sort desc",function(err,data){
// 判断是否失败
if (err) {
return "";
}else{
// 读取轮播图信息
mysql.query("select * from banner order by sort desc",function(err,data2){
if (err) {
return "";
}else{
// 查询最新发布的文章
mysql.query("select news.*,newstype.name tname from news,newstype where news.cid = newstype.id order by news.id desc",function(err,data3){
if (err) {
return "";
}else{
data3.forEach(item=>{
item.time = moment(item.time*1000).format("YYYY-MM-DD HH:mm:ss");
})
// 热门文章
mysql.query("select * from news order by num desc limit 5",function(err,data4){
if (err) {
return "";
}else{
data4.forEach(item=>{
item.time = moment(item.time*1000).format("YYYY-MM-DD");
})
// 加载首页
res.render("home/index.html",{
webConfig:webConfig,
typeData:data,
sliderData:data2,
newsData:data3,
hotData:data4,
user:req.session.YzmMessageUsername
});
}
});
}
});
}
});
}
});
});
// 前台分类页
router.get('/list',function(req,res,next){
let id = req.query.id;
// 读取网站配置相关数据'
let webConfigData = fs.readFileSync(__dirname+"/../config/webConfig.json");
let webConfig = JSON.parse(webConfigData.toString());
// 读取分类数据
mysql.query("select * from newstype order by sort desc",function(err,data){
if (err) {
return "";
}else{
// 获取当前分类信息
let typeInfo = "";
data.forEach(item=>{
if (item.id == id) {
typeInfo=item;
};
});
// 查询分类对应的新闻信息
mysql.query("select * from news where cid = ? order by id desc",[id],function(err,data2){
if (err) {
return "";
}else{
data2.forEach(item=>{
item.time = moment(item.time*1000).format("YYYY-MM-DD");
});
// 分类下的热们新闻
mysql.query("select * from news where cid = ? order by num desc",[id],function(err,data3){
if (err) {
return "";
}else{
data3.forEach(item=>{
item.time = moment(item.time*1000).format("YYYY-MM-DD");
});
// 加载首页
res.render("home/list.html",{
webConfig:webConfig,
typeData:data,
typeInfo:typeInfo,
newsData:data2,
hotData:data3
});
}
});
}
});
}
});
});
// 前台新闻详情页
router.get('/news',function(req,res,next){
let id = req.query.id;
// 读取网站配置相关数据'
let webConfigData = fs.readFileSync(__dirname+"/../config/webConfig.json");
let webConfig = JSON.parse(webConfigData.toString());
// 加载分类数据
mysql.query("select * from newstype order by sort desc",function(err,data){
if (err) {
return "";
}else{
//加载对应文章数据
mysql.query("select news.*,newstype.name from news,newstype where news.cid = newstype.id and news.id = "+id,function(err,data2){
if(err){
return "";
}
else{
data2.forEach(item=>{
item.time = moment(item.time*1000).format("YYYY-MM-DD HH:mm:ss");
});
mysql.query("select * from comment where news_id= "+id,function(err,data3){
if(err){
return "";
}
else{
data3.forEach(item=>{
item.time = moment(item.time*1000).format("YYYY-MM-DD HH:mm:ss");
});
res.render("home/news.html",{
webConfig:webConfig,
typeData:data,
newsData:data2[0],
commentData:data3,
user:req.session.YzmMessageUsername
});
}
})
}
})
}
})
});
// 前台登录页面
router.get('/login',function(req,res,next){
res.render("home/login.html");
});
//denglupanding
router.post('/login',function(req,res,next){
//接受数据
let {username,password} = req.body;
if(username){
if(password){
// 密码加密
let md5 = crypto.createHash('md5');
password = md5.update(password).digest('hex');
// 判断数据库中是否存在该用户
mysql.query("select * from user where username = ? and password = ? and status = 0",[username,password],function(err,data){
if (err) {
return ""
}else{
if (data.length) {
req.session.YzmMessageIsAdmin = true;
req.session.YzmMessageUsername = data[0].username;
res.send("<script>alert('登录成功');location.href='/'</script>");
}else{
res.send("<script>alert('登录失败');location.href='/'</script>");
}
}
});
}
else{
res.send("<script>alert('请输入密码');location.href='login'</script>");
}
}
else{
res.send("<script>alert('请输入用户名');location.href='login'</script>");
}
});
// 前台注册页面
router.get('/reg',function(req,res,next){
res.render("home/reg.html");
});
//注册提交页面
router.post('/check',function(req,res,next){
let {username,password,repassword} = req.body;
if(username){
if(password){
if(password == repassword){
mysql.query("select * from user where username = ?",[username],function(err,data){
if(err){
return "";
}
else{
// 判断该用户名是否注册
if (data.length==0) {
// 没有注册,我们需要插入数据
// 当前时间戳
let time = Math.round((new Date().getTime())/1000);
// 密码加密
let md5 = crypto.createHash('md5');
password = md5.update(password).digest('hex');
mysql.query("insert into user(username,password,status,time) value(?,?,?,?)",[username,password,0,time],function(err,data){
// 判断
if (err) {
return "";
}else{
// 判断是否执行成
if (data.affectedRows==1) {
res.send("<script>alert('注册成功');location.href='login'</script>");
}else{
res.send("<script>alert('注册失败');history.go(-1)</script>");
}
}
})
}else{
res.send("<script>alert('该账户名已经注册,请直接登录');location.href='login'</script>");
}
}
})
}
else{
res.send("<script>alert('两次密码不一致');location.href='reg'</script>");
}
}
else{
res.send("<script>alert('请输入密码');location.href='reg'</script>");
}
}
else{
res.send("<script>alert('请输入用户名');location.href='reg'</script>");
}
});
//发表文章
router.get('/article',function(req,res,next){
// 读取网站配置相关数据'
let webConfigData = fs.readFileSync(__dirname+"/../config/webConfig.json");
let webConfig = JSON.parse(webConfigData.toString());
//读取轮播图
mysql.query("select * from newstype order by sort desc",function(err,data){
// 判断是否失败
if (err) {
return "";
}else{
// 读取轮播图信息
mysql.query("select * from banner order by sort desc",function(err,data2){
if (err) {
return "";
}else{
// 热门文章
mysql.query("select * from news order by num desc limit 5",function(err,data4){
if (err) {
return "";
}else{
data4.forEach(item=>{
item.time = moment(item.time*1000).format("YYYY-MM-DD");
})
// 加载首页
res.render("home/article.html",{
webConfig:webConfig,
typeData:data,
sliderData:data2,
hotData:data4,
user:req.session.YzmMessageUsername
});
}
});
}
})
}
})
});
router.post('/article',upload.single("img"),function(req,res,next){
// 接受文件上传资源
let imgRes = req.file;
// 接受表单上传内容
let {title,keywords,description,info,author,cid,text} = req.body;
let num = 0;
let time = Math.round((new Date().getTime())/1000);
// 进行图片上传
let img = uploads(imgRes,"news");
// 进行数据插入
mysql.query("insert into news(cid,title,keywords,description,img,time,num,info,author,text) value(?,?,?,?,?,?,?,?,?,?)",[cid,title,keywords,description,img,time,num,info,author,text],function(err,data){
if (err) {
return "";
}else{
if (data.affectedRows==1) {
res.send("<script>alert('添加成功');location.href='/'</script>");
}else{
res.send("<script>alert('添加失败');history.go(-1);</script>");
}
}
});
})
router.get('/author',function(req,res,next){
res.send('作者首页')
})
router.post('/news',function(req,res,next){
if(req.session.YzmMessageUsername == null){
res.send("<script>alert('请登录后评论');location.href='/login'</script>");
}
else{
let{user_name,news_id,author_name,comment} = req.body;
let time = Math.round((new Date().getTime())/1000);
let status = 0;
mysql.query("insert into comment(user_name,news_id,text,time,status,author_name) value(?,?,?,?,?,?)",[user_name,news_id,comment,time,status,author_name],function(err,data){
if(err){
return "";
}
else{
if (data.affectedRows==1) {
res.send("<script>alert('评论成功');history.go(-1);</script>");
}else{
res.send("<script>alert('评论失败');history.go(-1);</script>");
}
}
})
}
})
//退出系统
router.get('/logout',function(req,res,next){
req.session.YzmMessageUsername = null;
res.send("<script>alert('退出成功');location.href='/'</script>");
});
function checkLogin(req, res, next) {
if (req.session.YzmMessageUsername == null) {
res.send("<script>alert('1');location.href='/'</script>");
res.redirect('/login');
}
else{
res.send("<script>alert('2');</script>");
}
next();
}
// function checkNotLogin(req, res, next) {
// if (req.session.YzmMessageUsername) {
// res.send("<script>alert('已登录');location.href='/'</script>");
// }
// next();
// }
module.exports = router;
<file_sep> // 导入express
const express = require("express");
// 实例化router
const router = express.Router();
// 导入数据库相关内容
const mysql = require("../../config/db.js");
// 分类查看页面
router.get("/",function(req,res,next){
// 从数据库中查询相关数据
mysql.query("select * from newstype order by sort desc",function(err,data){
if (err) {
return "";
}else{
// 加载页面
res.render("admin/type/index.html",{data:data});
}
});
});
// 分类的添加页面
router.get("/add",function(req,res,next){
// 加载添加页面
res.render("admin/type/add.html");
});
// 分类的添加操作
router.post("/add",function(req,res,next){
// 接收参数
let {name,keywords,description,sort} = req.body;
// 将数据插入到数据库中
mysql.query("insert into newstype(name,keywords,description,sort) value(?,?,?,?)",[name,keywords,description,sort],function(err,data){
// 判断是否错误
if (err) {
return "";
}else{
// 判断是否执行成功
if (data.affectedRows==1) {
res.send("<script>alert('添加成功');location.href='/admin/type'</script>");
}else{
res.send("<script>alert('添加失败');history.go(-1)</script>");
}
}
})
});
// 分类的修改页面
// 修改页面
router.get("/edit",function(req,res,next){
// 获取用户需要修改的数据
let id = req.query.id;
// 从数据库中查询相关数据
mysql.query("select * from newstype order by sort desc",function(err,data){
if (err) {
return "";
}else{
// 查询修改文章对应数据
mysql.query("select * from newstype where id = "+id,function(err,data2){
if (err) {
return "";
}else{
// 加载修改页面
res.render("admin/type/edit.html",{data:data,newData:data2[0]});
}
});
}
});
});
router.post("/edit",function(req,res,next){
//接受表单数据
let{id,name,keywords,description,sort} = req.body;
mysql.query("update newstype set name= ? , keywords=? , description=? , sort=? where id = ?",[name,keywords,description,sort,id],function(err,data){
if (err) {
return "";
}else{
// 判断影响行数
if (data.affectedRows==1) {
res.send("<script>alert('修改成功');location.href='/admin/type';</script>");
}else{
res.send("<script>alert('修改失败');history.go(-1);</script>");
}
}
});
});
// 无刷新删除数据
router.get("/ajax_del",function(req,res,next){
// 接受到删除的数据
let {id} = req.query;
// 删除数据
mysql.query("delete from newstype where id = "+id,function(err,data){
if (err) {
return "";
}else{
if (data.affectedRows==1) {
res.send("1");
}else{
res.send("0");
}
}
});
});
// 无刷新的修改排序
router.get("/ajax_sort",function(req,res,next){
// 接受数据
let {id,sort} = req.query;
// 数据的修改
mysql.query("update newstype set sort = ? where id = ?",[sort,id],function(err,data){
// 判断是否执行成功
if (err) {
return "";
}else{
if (data.affectedRows==1) {
res.send("1");
}else{
res.send("0");
}
}
});
});
module.exports = router;
| b313fd9bc2bc327de4d1e1298c479de4277b6eda | [
"JavaScript"
] | 3 | JavaScript | CHLMangguo/blog | b5d3f703981be0e8ff3356452a975e12ceed3098 | b3e882828522143e7cea9b6d7682198edba602d8 |
refs/heads/master | <repo_name>WGDetecive/WebLab1<file_sep>/src/by/bsu/aviacompany/entity/dao/AirportDao.java
package by.bsu.aviacompany.entity.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import by.bsu.aviacompany.entity.model.Airport;
public class AirportDao extends AbstractDao<Airport> {
@Override
public String getInsertQuery() {
return Query.AIRPORT_INSERT;
}
@Override
public void insertCustomData(PreparedStatement statement, Airport entity)
throws SQLException {
statement.setString(2, entity.getName());
}
@Override
public String getSelectAllQuery() {
return Query.AIRPORT_SELECT_ALL;
}
@Override
public Airport getEntity(ResultSet rs) throws SQLException {
Airport airport = new Airport();
airport.setId((UUID) rs.getObject(1));
airport.setName(rs.getString(2));
return airport;
}
@Override
public String getFindByIdQuery() {
return Query.AIRPORT_FIND_BY_ID;
}
}
<file_sep>/src/database.properties
url=jdbc:postgresql://localhost:5432/postgres
driver=org.postgresql.Driver
user=postgres
password=<PASSWORD><file_sep>/src/by/bsu/aviacompany/entity/model/AbstractEntity.java
package by.bsu.aviacompany.entity.model;
import java.util.UUID;
public abstract class AbstractEntity {
protected UUID id;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String toString() {
return this.getClass().getSimpleName(); // id.toString();
}
}
<file_sep>/src/by/bsu/aviacompany/main/Main.java
package by.bsu.aviacompany.main;
import java.util.List;
import java.util.Scanner;
import by.bsu.aviacompany.entity.model.Airport;
import by.bsu.aviacompany.entity.model.Flight;
import by.bsu.aviacompany.entity.model.Team;
import by.bsu.aviacompany.enums.FlightStatus;
import by.bsu.aviacompany.util.DBUtils;
public class Main {
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
mainScreen();
}
private static void mainScreen() {
System.out.println("1) List of flights\n2) Canceled flights\n0) Exit");
int i = Integer.parseInt(scanner.nextLine());
if (i == 1)
listOfFlightsScreen();
else if (i == 2)
canceledFlightsScreen();
else
return;
}
private static void canceledFlightsScreen() {
System.out.println("List of canceled flights:");
List<Flight> flights = DBUtils.selectCanceledFlights();
System.out.println(flights);
int i = 0;
for (Flight flight : flights) {
i++;
StringBuilder sb = new StringBuilder();
sb.append(i + ") Flight number: ").append(flight.getNumber())
.append("\n").append("From ").append(flight.getFrom())
.append(" at ").append(flight.getFromDate()).append("\n")
.append("To ").append(flight.getTo()).append(" at ")
.append(flight.getToDate()).append("\n")
.append(flight.getPlane().toString()).append("\n")
.append("Flight status: ").append(flight.getStatus());
System.out.println(sb.toString());
}
System.out.println("0) Back");
int selected = Integer.parseInt(scanner.nextLine());
if (selected == 0)
mainScreen();
else
flightInformationScreen(flights.get(selected - 1));
}
public static void listOfFlightsScreen() {
System.out.println("List of flights:");
List<Flight> flights = DBUtils.getAllFlights();
int i = 0;
for (Flight flight : flights) {
i++;
System.out.println(i + ") " + flight.getNumber() + " "
+ flight.getFrom().getName() + "-"
+ flight.getTo().getName());
}
System.out.println("0) Back");
int selected = Integer.parseInt(scanner.nextLine());
if (selected == 0)
mainScreen();
else
flightInformationScreen(flights.get(selected - 1));
}
private static void flightInformationScreen(Flight flight) {
StringBuilder sb = new StringBuilder();
sb.append("Flight number: ").append(flight.getNumber()).append("\n")
.append("From ").append(flight.getFrom()).append(" at ")
.append(flight.getFromDate()).append("\n").append("To ")
.append(flight.getTo()).append(" at ")
.append(flight.getToDate()).append("\n")
.append(flight.getPlane().toString()).append("\n")
.append("Flight status: ").append(flight.getStatus());
System.out.println(sb.toString());
System.out
.println("\n1) Team information\n2) Change flight status\n3) Change destination airport\n0) Back");
int i = Integer.parseInt(scanner.nextLine());
if (i == 0)
mainScreen();
else if (i == 1)
teamInformationScreen(flight.getTeam());
else if (i == 2)
changeFlightStatusScreen(flight);
else if (i == 3)
changeDestinationAirportScreen(flight);
}
private static void changeDestinationAirportScreen(Flight flight) {
System.out.println("Current destination airport: " + flight.getTo());
List<Airport> list = DBUtils.getAllAirports();
int i = 0;
for (Airport airport : list) {
System.out.println(++i + ") " + airport);
}
System.out.println("0) Back");
i = Integer.parseInt(scanner.nextLine());
if (i != 0 && i <= list.size())
DBUtils.changeFlightTo(flight, list.get(i - 1));
flight = DBUtils.getFlightById(flight.getId());
flightInformationScreen(flight);
}
private static void changeFlightStatusScreen(Flight flight) {
System.out.println("Current status: " + flight.getStatus() + "\n1) "
+ FlightStatus.RELEVANT + "\n2) " + FlightStatus.POSTPONED
+ "\n3) " + FlightStatus.CANCELED + "\n0) Back");
FlightStatus newStatus = null;
int i = Integer.parseInt(scanner.nextLine());
if (i == 1)
newStatus = FlightStatus.RELEVANT;
else if (i == 2)
newStatus = FlightStatus.POSTPONED;
else if (i == 3)
newStatus = FlightStatus.CANCELED;
if (newStatus != null)
DBUtils.changeFlightStatus(flight, newStatus);
flight = DBUtils.getFlightById(flight.getId());
flightInformationScreen(flight);
}
private static void teamInformationScreen(Team team) {
System.out.println(team.toString());
System.out.println("\n0) Back to list");
Integer.parseInt(scanner.nextLine());
listOfFlightsScreen();
}
}
| 2df613c3c4ad1834cdb156ca9c7d651498892b67 | [
"Java",
"INI"
] | 4 | Java | WGDetecive/WebLab1 | f25335376667d480ee91ad28e13f1ed1a606ee9d | 39721454eada3c4f8c4f87e672c49fcc8d1279b4 |
refs/heads/master | <repo_name>WarrenGreen/Chord<file_sep>/Chord/src/com/green/chord/Node.java
package com.green.chord;
import com.sun.istack.internal.logging.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
/**
* @author wsgreen
* @ip IP Address of node
* @port Port of node
* @Id SHA-1 hash of (ip, port)
* @leader first node in the ring
* @fingerCount number of finger table entries to store. Default is 10 unless specified. Maximum is 265 with SHA-1.
* @ringIp an ip of a node in the desired ring
* @ringPort an ip corresponding to the ringIp
*/
public class Node {
private static final Logger LOGGER = Logger.getLogger(Node.class);
private static final String FIND = "find";
private static final String INSERT = "insert";
private static final String HELP = "Please enter a valid command.";
//Potentially convert these to generic Param type inside map as parameters grow
private String ip = null;
private int port = -1;
private String id;
private boolean leader;
private int fingerCount = 256;
private String ringIp;
private int ringPort;
private ServerSocket serverSocket = null;
private AtomicBoolean running = new AtomicBoolean(true);
private Finger[] fingerTable;
private Finger predecessor;
public Node(String configFile) {
readConfig(configFile);
fingerTable = new Finger[fingerCount];
LOGGER.info(String.format("%s: init", this.id));
if(leader)
initRing();
else {
fingerTable[0] = null;
joinRing();
}
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Server socket failure.");
System.exit(1);
}
Thread listener = new Thread(getListener());
listener.start();
Thread stabilizer = new Thread(getStabilizer());
stabilizer.start();
Thread client = new Thread(getClient());
client.start();
}
private String findSuccessor(String id) {
LOGGER.log(Level.INFO, String.format("%s: find %s", this.id, id));
if( fingerTable[0] != null &&
this.id.compareTo(fingerTable[0].getId()) ==0 ||
((id.compareTo(this.id) > 0) && (id.compareTo(fingerTable[0].getId()) <= 0)) ||
((id.compareTo(this.id) > 0) && (id.compareTo(fingerTable[0].getId()) > 0) && this.id.compareTo(fingerTable[0].getId()) >= 0) ){
return fingerTable[0].toString();
} else {
String n0 = closestPrecedingNode(id);
Message m = Message.sendWithResponse(n0, new Message(ip + ":" + port, id, Message.FIND_SUCCESSOR, ""));
return m.getValue();
}
}
private String closestPrecedingNode(String id) {
for(int i=fingerTable.length-1;i>=0;i++) {
String finger = fingerTable[i].getId();
if((finger.compareTo(this.id) > 0) && (finger.compareTo(id) < 0)) { // finger[i] in (n, id)
return fingerTable[i].toString();
}
}
return this.toString();
}
private void initRing() {
for(int i=0;i<fingerTable.length;i++) {
fingerTable[i] = new Finger(ip, port, id);
}
predecessor = null;
}
private void joinRing() {
Message m = Message.sendWithResponse(ringIp+":"+ringPort, new Message(ip + ":" + port, id, Message.FIND_SUCCESSOR, ""));
fingerTable[0] = new Finger(m.getValue());
for(int i=1;i<fingerTable.length;i++) {
fingerTable[i] = new Finger(findSuccessor(fingerTable[i-1].getId()));
}
predecessor = null;
}
private void readConfig(String configFile) {
List<String> configParams = null;
try {
configParams = Files.readAllLines(Paths.get(configFile));
} catch (IOException e) {
System.err.println("Config file was not found or was unable to be read.");
System.exit(1);
}
for(String param: configParams) {
int colon = param.indexOf(':');
String title = param.substring(0, colon).trim();
String value = param.substring(colon+1).trim();
switch (title) {
case Params.IP_ADDRESS:
ip = value;
break;
case Params.PORT:
port = Integer.valueOf(value);
break;
case Params.LEADER:
leader = Boolean.valueOf(value);
break;
case Params.RING_IP:
ringIp = value;
break;
case Params.RING_PORT:
ringPort = Integer.valueOf(value);
break;
case Params.FINGER_TABLE_LENGTH:
fingerCount = Integer.valueOf(value);
}
}
assert(ip != null);
assert(port > 0);
id = Params.toSHA1(ip, port);
}
private Runnable getListener() {
return () -> {
Socket clientSocket = null;
BufferedReader in = null;
PrintWriter out = null;
Message msg = null;
while(running.get()) {
try {
clientSocket = serverSocket.accept();
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
msg = new Message(in.readLine());
LOGGER.info(String.format("%s: receive %s", this.id, msg.getFromIp()));
switch (msg.getType()) {
case Message.FIND_SUCCESSOR:
Message resp = null;
if(msg.getRegardingId().compareTo(this.id)==0 ) {
resp = new Message(ip + ":" + port, msg.getRegardingId(),
Message.RET_SUCCESSOR, this.id);
} else {
resp = new Message(ip + ":" + port, msg.getRegardingId(),
Message.RET_SUCCESSOR, findSuccessor(msg.getRegardingId()));
}
out.println(resp.toString());
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
private Runnable getStabilizer() {
//TODO
return null;
}
private Runnable getClient() {
return () -> {
Scanner in = new Scanner(System.in);
String input = null;
while( (input = in.nextLine()).compareToIgnoreCase("end") != 0) {
switch (input) {
default:
System.out.println(Node.HELP);
}
}
running.set(false);
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
};
}
@Override
public String toString() {
return ip+":"+port;
}
}
| 14052dae6627169604e50369840623fd5819e184 | [
"Java"
] | 1 | Java | WarrenGreen/Chord | b60fbccbce7b6da6fd5ce08b8245721581e4354c | eec7e064979b9a3b0c4a8756c1d755227acd2318 |
refs/heads/master | <file_sep>[tox]
envlist = py27, py27-configparser, py35, py36, py37, py38, pypy, pypy3
[testenv]
passenv = HOME
deps=
pytest>=3.4.0
mock
testfixtures
commands=
py.test -r a [] tests
[testenv:py27-configparser]
basepython= python2.7
deps=
pytest
mock
configparser
testfixtures
[pytest]
minversion= 2.0
norecursedirs= .git .hg .tox build dist tmp*
python_files = test*.py
<file_sep>import codecs
import platform
import sys
IS_PY2 = sys.version_info[0] == 2
IS_PY3 = sys.version_info[0] == 3
IS_WINDOWS = platform.system() == "Windows"
def _command_args(args):
if IS_WINDOWS and IS_PY2:
return [a.encode("utf-8") for a in args]
return args
if IS_PY2:
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
from StringIO import StringIO # noqa # pylint: disable=import-error
from ConfigParser import ( # noqa
RawConfigParser,
SafeConfigParser as ConfigParser,
NoOptionError,
)
elif IS_PY3:
from io import StringIO # noqa # pylint: disable=import-error
# On Py2, "SafeConfigParser" is the same as "ConfigParser" on Py3
from configparser import ( # noqa
RawConfigParser,
ConfigParser,
NoOptionError,
)
<file_sep>__version__ = "0.5.12-dev"
__license__ = "MIT"
__title__ = "bumpversion"
<file_sep>class IncompleteVersionRepresentationException(Exception):
def __init__(self, message):
self.message = message
class MissingValueForSerializationException(Exception):
def __init__(self, message):
self.message = message
class WorkingDirectoryIsDirtyException(Exception):
def __init__(self, message):
self.message = message
class MercurialDoesNotSupportSignedTagsException(Exception):
def __init__(self, message):
self.message = message
<file_sep>import io
import os
from setuptools import setup
description = 'Version-bump your software with a single command!'
# Import the README and use it as the long-description.
# This requires 'README.md' to be present in MANIFEST.in.
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = '\n' + f.read()
setup(
name='bump2version',
version='0.5.12-dev',
url='https://github.com/c4urself/bump2version',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
packages=['bumpversion'],
description=description,
long_description=long_description,
long_description_content_type='text/markdown',
entry_points={
'console_scripts': [
'bumpversion = bumpversion.cli:main',
'bump2version = bumpversion.cli:main',
]
},
python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: PyPy',
],
)
| e5afcfa081d95f95d173470c90f40db2431619a0 | [
"Python",
"INI"
] | 5 | INI | yakky/bump2version | 527ca7af0f8cdc80fee7cbb0392855ee2561958a | 833c13cf75176c0790e2479d71586d526bbf040e |
refs/heads/master | <repo_name>bojianyin/mpro<file_sep>/public/sectionList.js
import React,{Component} from "react";
import {FlatList, SectionList as List, View, Text, StyleSheet,ActivityIndicator} from 'react-native';
import PropTypes from "prop-types";
import {gfont, gh, gw} from './screenUtil';
class Sectionlist extends Component {
constructor(props){
super(props);
}
static propTypes = {
numColumns: PropTypes.number,
data:PropTypes.array,
itempad:PropTypes.number,
itemmar:PropTypes.number,
sticky:PropTypes.boolean,
renderItemc:PropTypes.element,
isload:PropTypes.boolean,
isempty:PropTypes.boolean,
};
static defaultProps = {
numColumns: 1,
sticky:true,
itempad:0,
itemmar:0,
isload:true,
isempty:false,
};
//底部组件
_footerRender = () => {
//未加载
if(this.props.status==0){
return (
<View style={styles.moreTips}>
<Text style={styles.Tips}>上拉加载更多</Text>
</View>
);
//正在加载
}else if(this.props.status==1){
return (
<View style={styles.moreTips}>
<ActivityIndicator color="#FFB624"/>
<Text style={styles.Tips}>正在加载中...</Text>
</View>
);
}else if(this.props.status==2){
return (
<View style={styles.moreTips}>
<Text style={styles.Tips}>没有更多数据了</Text>
</View>
);
}else{
return null;
}
};
_renderItem = ({ section,index,item }) => {
const { numColumns } = this.props;
if (index % numColumns !== 0) return null;
const items = [];
for (let i = index; i < index + numColumns; i++) {
if (i >= section.data.length) {
break;
}
items.push(this.props.renderItemc(section,index,i,item));
}
return <View
style={{
flexDirection: "row",justifyContent: "space-between",paddingLeft:this.props.itempad,paddingRight:this.props.itempad,marginBottom:this.props.itemmar
}}
>
{items}
</View>;
};
render() {
return (
<List
{...this.props}
sections={this.props.data}
// style={styles.container}
renderItem={this._renderItem}
keyExtractor={(item, index) => item.toString()+index.toString()}
showsVerticalScrollIndicator = {false}
extraData={this.state} //保证组件刷新
stickySectionHeadersEnabled={this.props.sticky}
onEndReachedThreshold = {0.03}
onEndReached = {this.props.isload?this.props.loadMore:null}
ListFooterComponent = {this.props.isempty?null:this._footerRender}
/>
);
}
}
const styles = StyleSheet.create({
moreTips:{
height:gh(100),
flexDirection:"row",
justifyContent:"center",
alignItems:"center"
},
Tips:{
fontSize:gfont(26),
marginLeft:gw(10),
color:"#999"
}
});
export default Sectionlist;
<file_sep>/page/stack/Webcom.js
import React, {Component} from "react";
import {StyleSheet, View, Text} from "react-native";
import Common from "../../public/common";
import { WebView } from 'react-native-webview';
export default class Webcom extends Common {
constructor(props) {
super(props);
}
render() {
return (
<View style={{flex:1}}>
<View style={{flex:1}}>
<WebView source={{uri:"static.bundle/index.html"}}
originWhitelist={['*']}
/>
</View>
</View>
);
}
}
<file_sep>/page/login.js
import React, {Component} from "react";
import {StyleSheet, View, Text,TextInput,TouchableOpacity} from "react-native";
import {gh,gw,gfont} from "../public/screenUtil";
export default class Login extends Component {
constructor(props) {
super(props);
this.state={
name:"",
pass:"",
}
}
render() {
return (
<View style={{flex:1,backgroundColor:"#fff",alignItems:"center"}}>
<View style={{width:gw(680),marginTop:gh(500)}}>
<TextInput
placeholder={"请输入账户名"}
value={this.state.name}
onChangeText={name=>this.setState({name})}
style={style.inp}
/>
<TextInput
placeholder={"请输入密码"}
value={this.state.pass}
onChangeText={pass=>this.setState({pass})}
style={style.inp}
/>
<TouchableOpacity style={{borderRadius:5,width:gw(680),height: gh(80),justifyContent: "center",alignItems:"center",backgroundColor:"#0495ea",marginTop:gh(50)}} onPress={()=>{
this.props.navigation.navigate("Home");
}}>
<Text style={{fontSize:gfont(30),color:"#fff"}}>登录</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const style=StyleSheet.create({
inp:{
height:gh(80),
justifyContent:"center",
fontSize:gfont(28),
borderBottomWidth:1,
borderBottomColor:"#eee",
paddingBottom:gh(10),
marginTop:gh(20)
}
})
<file_sep>/App.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React, {Fragment} from 'react';
import {} from 'react-native';
import Path from "./page/path";
import NavigationService from "./public/NavigationService";
import {NavigationContainer} from "@react-navigation/native";
import {createStackNavigator,} from "@react-navigation/stack";
const Stack=createStackNavigator();
const App = () => {
return (
<NavigationContainer ref={navigatorRef => {
NavigationService.setTopLevelNavigator(navigatorRef);
}}>
<Path params={Stack}/>
</NavigationContainer>
);
};
export default App;
<file_sep>/page/path.js
import 'react-native-gesture-handler';
import React from "react";
import {Text,Image,TouchableOpacity,View} from "react-native";
import { createStackNavigator,CardStyleInterpolators } from '@react-navigation/stack';
import { createDrawerNavigator,DrawerContentScrollView,
DrawerItemList,DrawerItem } from '@react-navigation/drawer';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import Home from "./home";
import Login from "./login";
import Charts from "./Charts";
import Command from "./Command";
import Setting from "./setting";
import Newstack from "./stack/newstack";
import Webcom from "./stack/Webcom";
import {gfont, gh, gw} from "../public/screenUtil";
import NavigationService from "../public/NavigationService";
const Drawer = createDrawerNavigator();
function CustomDrawerContent(props) {
return (
<DrawerContentScrollView {...props}>
<View style={{flex:1,justifyContent:"center",alignItems:"center",marginBottom:gh(50)}}>
<Image
source={{uri:"https://profile.csdnimg.cn/A/B/2/2_qq_37399372"}}
resizeMode={"contain"}
style={{width:gw(150),height:gw(150),borderRadius:100}}
/>
<Text style={{marginTop:gh(20),fontSize:gfont(30),}}>xiaobo</Text>
</View>
<DrawerItemList {...props} />
</DrawerContentScrollView>
);
}
//抽屉堆栈
function MyDrawer() {
return (
<Drawer.Navigator initialRouteName="Dashboard" drawerType={"back"}
drawerContent={CustomDrawerContent}
drawerStyle={{
backgroundColor: '#fff',
width: gw(500),
}}
>
<Drawer.Screen
name="Dashboard"
component={Home}
options={{ drawerLabel: 'Dashboard' }}
/>
<Drawer.Screen
name="Charts"
component={Charts}
options={{ drawerLabel: 'Charts' }}
/>
<Drawer.Screen
name="Command"
component={Command}
options={{ drawerLabel: 'Command' }}
/>
<Drawer.Screen
name="Setting"
component={Setting}
options={{ drawerLabel: 'Setting' }}
/>
</Drawer.Navigator>
);
}
//导航堆栈
export default function App({params}) {
const Stack=params;
return (
<SafeAreaProvider>
<Stack.Navigator
initialRouteName="Login"
mode="card"
screenOptions={{
mode: "card",
gestureEnabled: false,
cardShadowEnabled: false,
headerMode: "screen",
title: "defaultTitle",
gestureResponseDistance: "horizontal",
gestureDirection: "horizontal",
cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
headerShown: true,
}}
>
<Stack.Screen name="Home" component={MyDrawer} options={{
title:"首页",
headerLeft: (props) => <TouchableOpacity onPress={()=>{
NavigationService.toggle();
}}>
<Image source={require("../resource/menu.png")} style={{marginLeft:gw(20),width:gw(50),height:gw(50)}} resizeMode={"contain"}/>
</TouchableOpacity>,
}}
/>
<Stack.Screen name="Login" component={Login} options={{
headerShown:false
}} />
<Stack.Screen name="Newstack" component={Newstack} options={{
title:"新页面"
}} />
<Stack.Screen name="Webcom" component={Webcom} options={{
title:"打开 webpage"
}} />
</Stack.Navigator>
</SafeAreaProvider>
);
}
<file_sep>/page/home.js
import React, {Component} from "react";
import {StyleSheet, View, Text,Button} from "react-native";
import {HeaderBackButton} from "@react-navigation/stack";
import {NavigationContext} from "@react-navigation/native";
export default class Home extends Component {
constructor(props) {
super(props);
}
static contextType = NavigationContext;
render() {
return (
<View style={{flex:1}}>
<Button title={"hello world!"} onPress={()=>this.props.navigation.navigate("Newstack")}/>
<Button title={"hello world!"} onPress={()=>this.props.navigation.navigate("Newstack")}/>
<Button title={"打开网页"} onPress={()=>this.props.navigation.navigate("Webcom")} />
</View>
);
}
}
<file_sep>/public/Shake.js
// 防抖函数:调用后在一定的时间内函数不执行,过了限时执行,在限时内再次调用会重新开启定时器
export function debounce(func, delay) {
let inDebounce;
return function () {
const context = this;
const args = arguments;
clearTimeout(inDebounce); // 定时器用来执行函数
inDebounce = setTimeout(() => func.apply(context, args), delay);
};
}
// 截流函数:调用后在限时内执行一次,限时内再次调用,函数执行判断条件为关闭状态,函数不执行,函数执行后判断条件打开
export function throttle (fun, delay = 500) {
let prev = new Date();
return function (args) {
let now = new Date();
let that = this;
if (now - prev > delay) {
fun.call(that, args);
prev = now
}
}
}<file_sep>/public/DateFormat.js
/**
* Descrip:
* Author: Administrator
* Time: 2018/8/20
* Version:
*/
export default class DateFormat{
static currDateFormat(num,time=false){
let date = time?new Date(time):new Date();
let seperator1 = "-";
let seperator2 = ":";
let seperator3 = ".";
let seperator4 = "/";
let month = date.getMonth() + 1;
let strDate = date.getDate();
let strHours=date.getHours();
let strMinutes=date.getMinutes();
let miao=date.getSeconds();
if (month <= 9) {
month = "0" + month;
}
if (strDate <= 9) {
strDate = "0" + strDate;
}
if (strHours <= 9) {
strHours = "0" + strHours;
}
if (strMinutes <= 9) {
strMinutes = "0" + strMinutes;
}
if(miao<=9){
miao="0"+miao;
}
let currentdate1 = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + strHours + seperator2 + strMinutes
+ seperator2 + miao;
let currentdate2 = date.getFullYear() + seperator1 + month + seperator1 + strDate;
let currentdate3 = date.getFullYear() + seperator3 + month + seperator3 + strDate;
let currentdate4 = date.getFullYear() + seperator3 + month + seperator3 + strDate+" "+ strHours + seperator2 + strMinutes+seperator2 + miao;
let currentdate5 = month + seperator4 + strDate+" "+ strHours + seperator2 + strMinutes;
let currentdate6 = strMinutes+seperator2 + miao;
let currentdate7=miao;
let currentdate8 = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + miao;
if(num == 1){
return currentdate1;
}else if(num==2){
return currentdate2;
}else if(num==3){
return currentdate3;
}else if(num==4){
return currentdate4;
}else if(num==5){
return currentdate5;
}else if(num==6){
return currentdate6;
}else if(num==7){
return currentdate7;
}else if(num==8){
return currentdate8;
}
}
}
<file_sep>/README.md
# mpro
test project
react-native 项目中webview添加纯前端项目
<file_sep>/page/stack/newstack.js
import React, {Component} from "react";
import {StyleSheet, View, Text} from "react-native";
export default class Newstack extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={{flex:1}}>
<Text>this is new stack!</Text>
</View>
);
}
}
<file_sep>/public/header.js
import React,{Component} from "react"
import {
Text, View, StyleSheet, Image, StatusBar,TouchableOpacity,Platform
} from "react-native"
import image from "../image/"
import {gw,gh,gfont} from "./screenUtil"
import PropTypes from 'prop-types'
import {isIPhoneXFooter,isIphoneX} from './Phonex';
export default class Header extends Component{
constructor(prop){
super(prop);
}
static propTypes={
barStyle:PropTypes.string,
name:PropTypes.string,
push:PropTypes.func,
isback:PropTypes.bool,
headerback:PropTypes.string,
url:PropTypes.any,
txtcolor:PropTypes.string,
txtpress:PropTypes.func,
txtname:PropTypes.string,
righttype:PropTypes.bool,
them:PropTypes.string
};
static defaultProps={
isback:true,
barStyle:"dark-content",
headerback:"#ED4040",
headertype:"pic",
txtcolor:"#fff",
txtname:"添加优惠券",
righttype:false,
them:"#000"
}
render(){
return (
<View style={{zIndex:1}}>
<StatusBar
translucent={true}
animated={true}
backgroundColor={"transparent"}
barStyle={this.props.barStyle}
/>
<View style={{height:StatusBar.currentHeight||(isIphoneX()?44:20),backgroundColor:this.props.headerback }} />
<View style={[style.con,{
backgroundColor:this.props.headerback,
}]}>
{this.props.isback?
<TouchableOpacity style={style.left} onPress={()=>{
if(this.props.gobackcall){
this.props.gobackcall();
return ;
}
this.props.nav.goBack();
}}>
<View>
<Image source={image.Home.back} style={{marginLeft:gw(24),tintColor: this.props.them}}/>
</View>
</TouchableOpacity>
:
null
}
<View style={style.center}>
<Text style={{fontSize:gfont(35),color:this.props.them}}>{this.props.name}</Text>
</View>
{this.props.righttype==true?
<TouchableOpacity style={style.shouhoubtn} onPress={this.props.push}>
<View>
<Image source={this.props.url} resizeMode={"contain"}/>
</View>
</TouchableOpacity>
:
null
}
{this.props.headertype=="pic"?
<TouchableOpacity style={style.right} onPress={this.props.push}>
<View>
<Image source={this.props.url} resizeMode={"contain"}/>
</View>
</TouchableOpacity>
:
<TouchableOpacity style={style.right2} onPress={this.props.txtpress}>
<Text style={[style.righttext,{color:this.props.txtcolor}]}>{this.props.txtname}</Text>
</TouchableOpacity>}
</View>
</View>
);
}
}
const style=StyleSheet.create({
con:{height:gh(100), justifyContent:"center"},
center:{alignItems:"center"},
left:{position:"absolute", left:0, zIndex:2, height:"100%", justifyContent:"center", width:gw(104),},
right:{position:"absolute",right:0,alignItems:"center",zIndex:2, height:gh(100), justifyContent:"center", width:gw(100),},
right2:{position:"absolute", right:gw(20), zIndex:2, height:gh(100), justifyContent:"center", alignItems:"center",minWidth:gw(100)},
righttext:{ fontSize: gfont(28)},
shouhoubtn:{position:"absolute",right:gh(130),height:gh(100),width:gw(100),alignItems:"flex-end",justifyContent:"center"},
})
<file_sep>/public/fetchUtil.js
/**
* fetch 网络请求的header,可自定义header 内容
* @type {{Accept: string, Content-Type: string, accessToken: *}}
*/
import {Toast,Loading} from "./loading"
import NetInfo from "@react-native-community/netinfo"
import {Alert} from "react-native";
import CONF from "../conf/"
import User from "../conf/user";
const Ip=CONF['FETCH_IP'];
// const Ip="http://192.168.1.200:9000";
global.imgurl=CONF['IMAGE_IP'];
// const Ip="http://172.16.58.3:8083";
let header = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
};
let header2 = {
'Accept': 'application/json',
'Content-Type': 'application/json',
};
//
// let header1 = {
// 'Accept': 'application/json',
// 'Content-Type': 'multipart/form-data',
// };
/**支持上传的图片格式*/
const extgroup=["jpg","JPG","png","PNG","gif","GIF","jpeg"];
/**
* GET 请求时,拼接请求URL
* @param url 请求URL
* @param params 请求参数
* @returns {*}
*/
const handleUrl = url => params => {
if (params) {
let paramsArray = []
Object.keys(params).forEach(key => paramsArray.push(key + '=' + encodeURIComponent(params[key])))
if (url.search(/\?/) === -1) {
typeof (params) === 'object' ? url += '?' + paramsArray.join('&') : url
} else {
url += '&' + paramsArray.join('&')
}
}
return url
}
const handleUrl2 = url => params => {
if (params) {
let paramsArray = []
Object.keys(params).forEach(key => paramsArray.push(key + '=' + encodeURIComponent(params[key])))
return paramsArray.join('&')
}
}
/**
* fetch 网络请求超时处理
* @param original_promise 原始的fetch
* @param timeout 超时时间 30s
* @returns {Promise.<*>}
*/
const timeoutFetch = (original_fetch, timeout = 20000) => {
// global.timeoutBlock = () => {}
let timeoutBlock;
let timeout_promise = new Promise((resolve, reject) => {
timeoutBlock = (type) => {
// 请求超时处理
// if(type=='notauto')
// reject('请求取消');
// else
reject('请求超时');
}
})
// Promise.race(iterable)方法返回一个promise
// 这个promise在iterable中的任意一个promise被解决或拒绝后,立刻以相同的解决值被解决或以相同的拒绝原因被拒绝。
let abortable_promise = Promise.race([
original_fetch,
timeout_promise
])
setTimeout(() => {
timeoutBlock()
}, timeout)
return abortable_promise
}
/**
* 网络请求工具类
*/
export default class HttpUtils {
constructor(){
this.current=0;
this.picgroup=[];
}
static timer=null;
/**
* 基于fetch 封装的GET 网络请求
* @param method
* @param url 请求URL
* @param params 请求参数
* @param host
* @param head
* @returns {Promise}
*/
static request = async (method,url, params = {},host=Ip,head=1) => {
// console.log(host,"debugger --- into ....");
let Interinfo=await NetInfo.fetch();
if(!Interinfo.isConnected)
{
Toast.show("您当前没有网络,请检查网络连接后重试!");
Loading.hide();
throw "not found network";
}
let result;
if(method=="get"||method=="GET"){
result = timeoutFetch(
fetch(handleUrl(host + '' + url)(params), {
method: 'GET',
headers: head===1?header:header2
})
)
}else if(method=="post"||method=="POST"){
result = timeoutFetch(
fetch(host + '' + url, {
method: 'POST',
headers:head===1?header:header2,
body: head===1?handleUrl2(url)(params):JSON.stringify(params)
})
)
}else{
result = timeoutFetch(
fetch(host + '' + url, {
method: method,
headers:head===1?header:header2,
body:head===1?handleUrl2(url)(params):JSON.stringify(params)
})
)
}
return new Promise((resolve, reject)=>{
result
.then(response => {
if (response.ok) {
// console.log(host,"debugger --- http ok 200 into ....");
return response.text()
} else {
// console.log(host,"debugger --- http ok ??error? into ....");
if(__DEV__) alert('服务器繁忙,请稍后再试;\r\nCode:' + response.status)
}
})
.then(response => {
// console.log("网络请求log"+host,response);
console.log(host,"debugger网络请求LOG"+response);
try{
response=JSON.parse(response);
if(host===CONF.msc){
if(response.result!==1){
if(response.result===9){
Toast.show("登陆重联中...");
//登陆过期
HttpUtils.login(method,url,params)
.then((res)=>{
resolve(res);
})
.catch((e)=>{
console.log(e);
Toast.show("登陆重联失败!");
reject("重联失败");
})
}else{
console.error(response.message);
Toast.show(response.message||"网络开小差了,请刷新后重试");
resolve(response);
}
}else{
resolve(response);
}
}else{
resolve(response);
}
}catch (e) {
console.error("json解析错误,请检查");
console.log(response);
Toast.show("服务器发生错误!");
reject("error");
}
})
.catch(error => {
Loading.hide();
if(error=="请求超时"||error=="请求取消"){
Toast.show(error);
}else{
Toast.show("服务器连接异常!");
}
if(__DEV__) console.error(error);
reject(error);
})
.done()
})
}
/*上传步骤
*
* resKey<Array> eg:["result"<状态码key>,"callbackname"<返回图片list key>]
* */
CommonUpload(h,uploadurl,fileDetail,upload_files,resKey){
return new Promise((resolve, reject)=>{
//有文件
if(fileDetail.length>0){
//content 读取缓存token 2 .3 同下面方法
this._fetch(h,uploadurl,fileDetail,this.current,resKey,upload_files,(R)=>{
this.current=0;//清空变量值
Loading.hide();
this.picgroup=[];
resolve(R);
},()=>{
this.current=0;//清空变量值
Loading.hide();
this.picgroup=[];
Toast.showLong("不支持的文件类型");
reject("不支持的文件类型");
return ;
})
}else{
//没有文件
Loading.hide();
this.picgroup=[];
resolve("no file");
return ;
}
});
}
/*上传过程*/
_fetch(h,uploadurl,fileDetail,currentindex,resKey,upload_files,fn,rejectcallback){
this.current=currentindex;
let extary=fileDetail[this.current]["name"].split(".");
if(extgroup.indexOf(extary[extary.length-1])===-1){
rejectcallback();
return ;
}
Loading.show((this.current+1)+"/"+upload_files.length);
fetch(h+''+uploadurl,{
method: 'POST',
// headers: header1,
body: upload_files[this.current],
})
.then((response)=>response.text())
.then((responseText)=>{
// console.log('段继龙'+responseText);
let res=JSON.parse(responseText);
if(res[resKey[0]]===1){
//成功
this.current++;
if(this.current<upload_files.length){
//延时回调
HttpUtils.timer=setTimeout(()=>{
HttpUtils.timer&&clearTimeout(HttpUtils.timer);
Loading.hide();
this.picgroup.push(res[resKey[1]]);
this._fetch(h,uploadurl,fileDetail,this.current,resKey,upload_files,fn,rejectcallback)
},1000);
}else{
HttpUtils.timer=setTimeout(()=>{
HttpUtils.timer&&clearTimeout(HttpUtils.timer);
this.picgroup.push(res[resKey[1]]);
fn(this.picgroup);
},1000);
}
}else{
Loading.hide();
this.current=0;//清空变量值
Toast.show(res.message);
return ;
}
})
.catch((error)=>{
if(__DEV__) console.error(error);
this.current=0;
Loading.hide();
})
}
static login(m,u,p){
return new Promise((resolve, reject)=>{
let U=User.useraccount.split("#");
let params={
"username":U[0],
"passwd":U[1],
"password":U[1],
};
HttpUtils.request("post","/api/mobile/member/staticPwd-login.do",params,CONF.msc)
.then((e)=>{
if(e.result===1){
//重复登陆ok
Toast.show("已连接");
//延迟处理服务器频繁请求
setTimeout(async ()=>{
let res=await HttpUtils.request(m,u,p,CONF.msc); //发起重新请求
resolve(res);
},500);
// Alert.alert(
// '提示',
// '已成功连接到服务,点击重试重新获取.',
// [
// {text: '重试', onPress: async () => {
// let res=await HttpUtils.request(m,u,p,CONF.msc); //发起重新请求
// resolve(res);
// }},
// ],
// { cancelable: false }
// )
}else{
reject("err");
}
})
.catch((e)=>{
reject(e.toString());
})
});
}
}
<file_sep>/public/NavigationService.js
// NavigationService.js
import { StackActions } from '@react-navigation/native';
import {NavigationActions} from "@react-navigation/compat";
import {DrawerActions} from "@react-navigation/native";
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
function toggle() {
_navigator.dispatch(
DrawerActions.toggleDrawer()
);
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator,
toggle
};
<file_sep>/page/setting.js
import React, {Component} from "react";
import {StyleSheet, View, Text,TouchableOpacity,Image} from "react-native";
import {gfont, gh, gw} from "../public/screenUtil";
import NavigationService from "../public/NavigationService";
import {NavigationActions} from "@react-navigation/compat";
export default class Setting extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={{flex:1}}>
<TouchableOpacity
style={{flexDirection: 'row', paddingLeft: gw(28), height: gh(116), alignItems: 'center',backgroundColor:"#fff"}}
onPress={() => this.props.navigation.navigate('Newstack')}
>
<Image source={require("../resource/setting.png")} resizeMode={'contain'} style={{marginRight: gw(28)}}/>
<Text>Login</Text>
</TouchableOpacity>
<TouchableOpacity
style={{flexDirection: 'row', paddingLeft: gw(28), height: gh(116), alignItems: 'center',backgroundColor:"#fff"}}
onPress={() => this.props.navigation.navigate('Newstack')}
>
<Image source={require("../resource/setting.png")} resizeMode={'contain'} style={{marginRight: gw(28)}}/>
<Text>Register</Text>
</TouchableOpacity>
<TouchableOpacity
style={{flexDirection: 'row', paddingLeft: gw(28), height: gh(116), alignItems: 'center',backgroundColor:"#fff"}}
onPress={() => this.props.navigation.navigate('Newstack')}
>
<Image source={require("../resource/setting.png")} resizeMode={'contain'} style={{marginRight: gw(28)}}/>
<Text>Forgot Password</Text>
</TouchableOpacity>
<TouchableOpacity
style={{flexDirection: 'row', paddingLeft: gw(28), height: gh(116), alignItems: 'center',backgroundColor:"#fff"}}
onPress={() => this.props.navigation.navigate('Newstack')}
>
<Image source={require("../resource/setting.png")} resizeMode={'contain'} style={{marginRight: gw(28)}}/>
<Text>404 page</Text>
</TouchableOpacity>
<TouchableOpacity
style={{flexDirection: 'row', paddingLeft: gw(28), height: gh(116), alignItems: 'center',backgroundColor:"#fff"}}
onPress={() => {
NavigationService.navigate("Newstack")
}}
>
<Image source={require("../resource/setting.png")} resizeMode={'contain'} style={{marginRight: gw(28)}}/>
<Text>Blank page</Text>
</TouchableOpacity>
</View>
);
}
}
<file_sep>/public/common.js
import React from 'react';
import {Platform,BackHandler,NativeModules} from "react-native";
import { NavigationContext,useNavigation } from '@react-navigation/native';
export default class Common extends React.Component {
constructor(props) {
super(props);
}
}
| e3ae8b5e4b1faabff8545a6b9513d9949f85aaa9 | [
"JavaScript",
"Markdown"
] | 15 | JavaScript | bojianyin/mpro | 6ef5f8687266db272e4624cc48682155a470bf27 | f8f890a6963d21a658eb463a79d5e0c3ea5271e4 |
refs/heads/master | <repo_name>hejazifar/Pre_Project<file_sep>/tcp.cpp
#include "tcp.hpp"
#include <arpa/inet.h>
#include <iostream>
#include <netdb.h>
#include <string.h>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
// create the server, if successful, return the clientsocket otherwise return a
// digit other than 0 based on the case
int tcp::tcp_server_init(int port, string ipaddress) {
// Create a socket
int listening = socket(AF_INET, SOCK_STREAM, 0);
if (listening == -1) {
cerr << "Can't create a socket" << endl;
return -1;
}
// Bind the socket to IP / port
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipaddress.c_str(), &hint.sin_addr); // 127.0.0.1
if (bind(listening, (sockaddr *)&hint, sizeof(hint)) == -1) {
cerr << "Can't bind to IP/port" << endl;
return -2;
}
// Mark the socket for listening in
if (listen(listening, SOMAXCONN) == -1) {
cerr << "Can't listen!";
return -3;
}
// Accept a call
sockaddr_in client;
socklen_t clientSize = sizeof(client);
char host[NI_MAXHOST];
char svc[NI_MAXSERV];
int clientSocket = accept(listening, (sockaddr *)&client, &clientSize);
if (clientSocket == -1) {
cerr << "Problem with client connection";
return -4;
}
// Close the listening socket
close(listening);
memset(host, 0, NI_MAXHOST);
memset(svc, 0, NI_MAXSERV);
int result = getnameinfo((sockaddr *)&client, sizeof(client), host,
NI_MAXHOST, svc, NI_MAXSERV, 0);
if (result) {
cout << host << " connected on " << svc << endl;
} else {
inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
cout << host << "connected on" << ntohs(client.sin_port) << endl;
}
return clientSocket;
}
int tcp::tcp_client_init(int port, string ipaddress) {
// Create a socket
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
return 1;
}
// Creat a hint structure for the server we're connection with
sockaddr_in hint; // A.B.C.D type of address
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipaddress.c_str(),
&hint.sin_addr); // convert ipaddress to a binary format and save it
// hint.sin.addrr
// Connect to the server on the socket
int connectResult = connect(sock, (sockaddr *)&hint, sizeof(hint));
if (connectResult == -1) {
return -1;
}
return sock;
}
// send the message, if successful return 0 otherwise return -1
int tcp::tcp_send(int sock, char *message, int size) {
int sendRes = send(sock, message, size, 0);
if (sendRes == -1) {
cout << "Could not send the message! \r\n";
return -1;
}
return 0;
}
// receive the message and return the data as a char array
char *tcp::tcp_receive(int sock, char *receivedData, int size) {
int bytesRecv = recv(sock, receivedData, size, 0);
if (bytesRecv == -1) {
cerr << "There was a connection issue" << endl;
}
if (bytesRecv == 0) {
cout << "The client disconnected" << endl;
}
// Display the message
cout << "Recieved: " << receivedData << endl;
return receivedData;
}
// close the socket
void tcp::tcp_close_socket(int sock) { close(sock); }<file_sep>/Hello_world/CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
set(CMAKE_SYSTEM_NAME Generic)
set(CMAKE_SYSTEM_VERSION 1)
project(first_hello_world C CXX ASM)
set(CMAKE_CXX_STANDARD 11)
######## CHIP CONFIGURATION ##########
set(ROOT_PROJ ${CMAKE_CURRENT_SOURCE_DIR})
set(CPU "cortex-m4")
set(ARCH_NAME "arm")
set(ARCH_VER "v7e-m") ## TO BE CHECKED
set(FAMILY "stm32f3")
set(CHIP "STM32F301x6")
set(ARCH "${ARCH_NAME}${ARCH_VER}")
######################################
# MCU Config
set(FPU "-mfpu=fpv4-sp-d16")
set(FLOAT-ABI "-mfloat-abi=hard")
# Toolchain path
set(TOOLCHAIN_PATH "/home/mehdi/ARMToolChain/gcc-arm-none-eabi-9-2019-q4-major-x86_64-linux/gcc-arm-none-eabi-9-2019-q4-major/bin")
# Specify C, C++ and ASM compilers
SET(CMAKE_C_COMPILER ${TOOLCHAIN_PATH}/arm-none-eabi-gcc)
SET(CMAKE_CXX_COMPILER ${TOOLCHAIN_PATH}/arm-none-eabi-g++)
set(CMAKE_ASM_COMPILER ${TOOLCHAIN_PATH}/arm-none-eabi-as)
set(AR ${TOOLCHAIN_PATH}/arm-none-eabi-ar)
set(OBJCOPY ${TOOLCHAIN_PATH}/arm-none-eabi-objcopy)
set(OBJDUMP ${TOOLCHAIN_PATH}/arm-none-eabi-objdump)
set(SIZE ${TOOLCHAIN_PATH}/arm-none-eabi-size)
set(GDB ${TOOLCHAIN_PATH}/arm-none-eabi-gdb)
set(SIZE ${TOOLCHAIN_PATH}/arm-none-eabi-size)
# Definitions passed at compile time (#defines)
add_definitions(-DFAMILY=${FAMILY})
add_definitions(-DCHIP=${CHIP})
add_definitions(-D${CHIP})
add_definitions(-DUSE_FULL_LL_DRIVER)
add_definitions(-USE_HAL_DRIVER)
add_definitions(-DHSE_VALUE=8000000)
add_definitions(-DHSE_STARTUP_TIMEOUT=100)
add_definitions(-DLSE_STARTUP_TIMEOUT=5000)
add_definitions(-DLSE_VALUE=32768)
add_definitions(-DHSI_VALUE=8000000)
add_definitions(-DLSI_VALUE=40000)
add_definitions(-DDD_VALUE=3300)
add_definitions(-DPREFETCH_ENABLE=1)
# Compilation flags
add_compile_options(-mcpu=${CPU})
add_compile_options(-march=${ARCH})
add_compile_options(-mthumb)
add_compile_options(${FPU})
add_compile_options(${FLOAT_ABI})
add_compile_options(-Og)
add_compile_options(-Wall)
add_compile_options(-fdata-sections)
add_compile_options(-ffunction-sections)
# Only for debugging
add_compile_options(-g -gdwarf-2)
# Linker script path
file(GLOB_RECURSE LINKER_SCRIPT ${ROOT_PROJ}/*.ld)
# Variables initialized first time
SET(CMAKE_CXX_FLAGS_INIT "-std=c++11")
SET(CMAKE_C_FLAGS_INIT "-std=gnu99")
################################## Source code ###############################################################
file(GLOB SOURCES "helloWorld.cpp")
################################## Source code END ###########################################################
set(EXE_NAME "${PROJECT_NAME}_${CHIP}")
add_executable(${EXE_NAME}.elf "${SOURCES}" "${LINKER_SCRIPT}")
set(CMAKE_EXE_LINKER_FLAGS "-mcpu=${CPU} -mthumb ${FPU} ${FLOAT_ABI} --specs=nano.specs -T${LINKER_SCRIPT} -Wl,-Map=${PROJECT_BINARY_DIR}/${PROJECT_NAME}.map,--cref -Wl,--gc-sections")
# Libs and external dependencies
target_link_libraries(${EXE_NAME}.elf -lc -lm -lnosys)
# Outputs
set(ELF_FILE ${PROJECT_BINARY_DIR}/${EXE_NAME}.elf)
set(HEX_FILE ${PROJECT_BINARY_DIR}/${EXE_NAME}.hex)
set(BIN_FILE ${PROJECT_BINARY_DIR}/${EXE_NAME}.bin)
add_custom_command(TARGET "${EXE_NAME}.elf" POST_BUILD
# Build .hex and .bin files
COMMAND ${OBJCOPY} -Obinary ${ELF_FILE} ${BIN_FILE}
COMMAND ${OBJCOPY} -Oihex ${ELF_FILE} ${HEX_FILE}
COMMENT "Building ${PROJECT_NAME}.bin and ${PROJECT_NAME}.hex"
# Copy files to a custom build directory
COMMAND ${CMAKE_COMMAND} -E copy ${ELF_FILE} "${ROOT_PROJ}/builds/${CHIP}/${EXE_NAME}.elf"
COMMAND ${CMAKE_COMMAND} -E copy ${HEX_FILE} "${ROOT_PROJ}/builds/${CHIP}/${EXE_NAME}.hex"
COMMAND ${CMAKE_COMMAND} -E copy ${BIN_FILE} "${ROOT_PROJ}/builds/${CHIP}/${EXE_NAME}.bin"
# Display sizes
COMMAND ${SIZE} --format=berkeley ${EXE_NAME}.elf ${EXE_NAME}.hex
COMMENT "Invoking: Cross ARM GNU Print Size"
)
#add_custom_target(UPLOAD
# ${GDB} -iex "target remote tcp:127.0.0.1:3333"
# -iex "monitor program ${EXE_NAME}.elf"
# -iex "monitor reset init"
# -iex "disconnect" -iex "quit ")
<file_sep>/slave.cpp
#include "tcp.hpp"
#include <iostream>
using namespace std;
string message;
int calculate(string message);
int main() {
int serverSock = 0;
serverSock = tcp::tcp_client_init();
// receiving data
char *recieveData;
recieveData = new char[12];
recieveData = tcp::tcp_receive(serverSock, recieveData, 12);
message = string(recieveData);
// parsing data and calculating
message = to_string(calculate(message));
// sending back the result
char *sendData;
sendData = new char[12];
message.copy(sendData, message.size());
tcp::tcp_send(serverSock, sendData, 12);
tcp::tcp_close_socket(serverSock);
return 0;
}
int calculate(string message) {
int num1 = stoi(message.substr(0, message.find("+")));
int num2 = stoi(message.substr(message.find("+") + 1,
message.find("=") - message.find("+") - 1));
return num1 + num2;
}<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.17)
project(Pre_Project VERSION 1.0)
set(CMAKE_CXX_STANDARD_11 11)
set(CMAKE_CXX_STANDARD_REQUIRED true)
project("Pre_Project")
add_executable("${PROJECT_NAME}" Arm_Master.cxx Arm_Slave.cxx)
<file_sep>/tcp.hpp
#ifndef TCP_HPP_INCLUDED
#define TCP_HPP_INCLUDED
#include <string>
namespace tcp{
int tcp_server_init(int port = 8080, std::string ipaddress = "0.0.0.0");
int tcp_client_init(int port = 8080, std::string ipaddress = "127.0.0.1");
int tcp_send(int sock, char * message, int size);
char * tcp_receive(int sock, char * recieveData, int size);
void tcp_close_socket(int sock);
}
#endif<file_sep>/master.cpp
#include "tcp.hpp"
#include <iostream>
using namespace std;
using namespace tcp;
int main() {
int clientSock = 0;
clientSock = tcp_server_init();
char *sendData;
sendData = new char[12];
string message = "2+3= ";
message.copy(sendData, message.size());
tcp::tcp_send(clientSock, sendData, 12);
char *recieveData;
recieveData = new char[12];
recieveData = tcp_receive(clientSock, recieveData, 12);
cout << recieveData << endl;
tcp_send(clientSock, sendData, 12);
tcp_close_socket(clientSock);
} | 5244badcf8e7e08d32e3e6553bc5ef2709702192 | [
"CMake",
"C++"
] | 6 | C++ | hejazifar/Pre_Project | 2db38513aedd13edc8d5244125beb2bdcdf54c58 | fe81d8923dc7a5b6baa970806ef6ef62b8bcf721 |
refs/heads/master | <repo_name>Nishant-l/route_planner<file_sep>/src/route_planner.cpp
#include "route_planner.h"
#include <algorithm>
RoutePlanner::RoutePlanner(RouteModel &model, float start_x, float start_y, float end_x, float end_y): m_Model(model) {
// Convert inputs to percentage:
start_x *= 0.01;
start_y *= 0.01;
end_x *= 0.01;
end_y *= 0.01;
// Store the nodes you find in the RoutePlanner's start_node and end_node attributes.
start_node =& m_Model.FindClosestNode(start_x,start_y);
end_node=& m_Model.FindClosestNode(end_x,end_y);
//m_Model.FindClosestNode()
}
float RoutePlanner::CalculateHValue(RouteModel::Node const *node) {
//RouteModel::Node obj;
//return(obj.distance(node));
return(node->distance(*end_node));
}
void RoutePlanner::AddNeighbors(RouteModel::Node *current_node) {
// RouteModel::Node obj;
//obj.neighbors.push_back(current_node);
current_node->FindNeighbors();
for(auto i:current_node->neighbors)
{
i->parent=current_node;
i->h_value=CalculateHValue(i);
i->g_value=current_node->g_value+current_node->distance(*i);
open_list.push_back(i);
i->visited=true;
}
}
}
RouteModel::Node* RoutePlanner::NextNode() {
// sorting custom objects
// I sorted descending here so the smallest node is at the back of the vector
std::sort(open_list.begin(), open_list.end(), [](const auto &lhs, const auto &rhs) {
return (lhs->g_value + lhs->h_value) > (rhs->g_value + rhs->h_value);
});
RouteModel::Node *next_node = open_list[open_list.size() - 1];
open_list.pop_back();
return next_node;
}
std::vector<RouteModel::Node> RoutePlanner::ConstructFinalPath(RouteModel::Node *current_node) {
// Create path_found vector
distance = 0.0f;
std::vector<RouteModel::Node> path_found;
// std::vector<RouteModel::Node> path_found1;
RouteModel::Node *temp_node=current_node;
//for(int tt=0;ni!=)
// TODO: Implement your solution here.
while(temp_node->parent != nullptr)
{
path_found.push_back(*temp_node);
distance=distance+(temp_node->distance(* temp_node->parent));
temp_node=temp_node->parent;
}
path_found.push_back(*temp_node);
reverse(path_found.begin(),path_found.end());
distance *= m_Model.MetricScale(); // Multiply the distance by the scale of the map to get meters.
return path_found;
}
void RoutePlanner::AStarSearch() {
start_node->visited=true;
open_list.push_back(start_node);
RouteModel::Node *current_node = nullptr;
while(!open_list.empty())
{
// AddNeighbors(current_node);
current_node=NextNode();
if(current_node->distance(*end_node)==0)
{
m_Model.path=ConstructFinalPath(current_node);
return;
}
AddNeighbors(current_node);
}
} | c313f24c93e120b03ba14ac6afa78df00243b7f4 | [
"C++"
] | 1 | C++ | Nishant-l/route_planner | 67f653c558a2855791884dd3349b04c84ea95449 | d217d2530fe34dfcc05c4047f28a93be4875a347 |
refs/heads/master | <repo_name>Franziac/Easy-Python-Coder<file_sep>/README.md
# Easy-Python-Coder
I know it's messy but feel free to contribute
This program is made for beginners to start learning python by first just clicking some buttons
<file_sep>/Easy Python Coder v1.3.py
from os import path
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
import os
icon_path = os.path.dirname(os.path.realpath(__file__))
root.iconbitmap(icon_path + r"\icon\favicon.ico")
root.title("Easy Python Coder")
root.configure(bg="#404142")
frame4=tk.Frame(root,bg="#404142")
frame=tk.Frame(root,bg="#404142")
frame5=tk.Frame(root,bg="#404142")
frame6=tk.Frame(root,bg="#404142")
frame8=tk.Frame(root,bg="#404142")
frame2=tk.Frame(root,bg="#404142")
frame7=tk.Frame(root,bg="#404142")
frame3=tk.Frame(root,bg="#404142")
building_frame=tk.Frame(root,bg="#404142")
frame9=tk.Frame(root,bg="#404142")
frame10=tk.Frame(root,bg="#404142")
frame11=tk.Frame(root,bg="#404142")
def_buttons_frame=tk.Frame(root,bg="#404142")
def_print_text_frame=tk.Frame(root,bg="#404142")
def_print_buttons_frame=tk.Frame(root,bg="#404142")
def_print_advanced_text_frame=tk.Frame(root,bg="#404142")
def_print_advanced_buttons_frame=tk.Frame(root,bg="#404142")
def_input_text_frame=tk.Frame(root,bg="#404142")
def_input_buttons_frame=tk.Frame(root,bg="#404142")
def_var_text_frame=tk.Frame(root,bg="#404142")
def_var_buttons_frame=tk.Frame(root,bg="#404142")
def_if_text_frame=tk.Frame(root,bg="#404142")
def_if_buttons_frame=tk.Frame(root,bg="#404142")
if_buttons_frame=tk.Frame(root,bg="#404142")
if_print_text_frame=tk.Frame(root,bg="#404142")
if_print_buttons_frame=tk.Frame(root,bg="#404142")
if_print_advanced_text_frame=tk.Frame(root,bg="#404142")
if_print_advanced_buttons_frame=tk.Frame(root,bg="#404142")
if_input_text_frame=tk.Frame(root,bg="#404142")
if_input_buttons_frame=tk.Frame(root,bg="#404142")
if_var_text_frame=tk.Frame(root,bg="#404142")
if_var_buttons_frame=tk.Frame(root,bg="#404142")
def_if_print_text_frame=tk.Frame(root,bg="#404142")
def_if_print_buttons_frame=tk.Frame(root,bg="#404142")
def_if_print_advanced_text_frame=tk.Frame(root,bg="#404142")
def_if_print_advanced_buttons_frame=tk.Frame(root,bg="#404142")
def_if_input_text_frame=tk.Frame(root,bg="#404142")
def_if_input_buttons_frame=tk.Frame(root,bg="#404142")
def_if_var_text_frame=tk.Frame(root,bg="#404142")
def_if_var_buttons_frame=tk.Frame(root,bg="#404142")
grid_frame2=tk.Frame(root,bg="#404142")
#def_input_commands=""
text=""
def_var_input=tk.Entry(root,bg="#404142")
def_print_input=tk.Entry(root,bg="#404142")
def_input_input=tk.Entry(root,bg="#404142")
def_input_input2=tk.Entry(root,bg="#404142")
def_input_input3=tk.Entry(root,bg="#404142")
if_var_input=tk.Entry(root,bg="#404142")
if_print_input=tk.Entry(root,bg="#404142")
if_input_input=tk.Entry(root,bg="#404142")
if_input_input2=tk.Entry(root,bg="#404142")
if_input_input3=tk.Entry(root,bg="#404142")
if_input_name=tk.Entry(root,bg="#404142")
if_input_commands=tk.Entry(root,bg="#404142")
def_if_input_name=tk.Entry(root,bg="#404142")
def_if_input_commands=tk.Entry(root,bg="#404142")
def_if_var_input=tk.Entry(root,bg="#404142")
def_if_print_input=tk.Entry(root)
#cancel_button,add_button,build="","",""
#Add and Cancel---------------------------------------------------------------------------------------------------------------
def add(button):
if(button=="print"):
global text
text="print('{}')".format(print_input.get())+"\n"
print_text.grid_forget()
print_cancel_button.grid_forget()
print_add_button.grid_forget()
print_input.grid_forget()
print_advanced_button.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
textbox.insert(tk.INSERT,text)
if(button=="input"):
#global input_input
if(input_input3.get()=="str"):
text="{} = input('{}')".format(input_input.get(),input_input2.get())+"\n"
elif(input_input3.get()=="int"):
text="{} = int(input('{}'))".format(input_input.get(),input_input2.get())+"\n"
elif(input_input3.get()=="float"):
text="{} = float(input('{}'))".format(input_input.get(),input_input2.get())+"\n"
##Lisää else
input_text.grid_forget()
input_type.grid_forget()
input_name.grid_forget()
input_cancel_button.grid_forget()
input_add_button.grid_forget()
input_input.grid_forget()
input_input2.grid_forget()
input_input3.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
textbox.insert(tk.INSERT,text)
if(button=="var"):
text="{} \n".format(var_input.get())
var_text.grid_forget()
var_cancel_button.grid_forget()
var_add_button.grid_forget()
var_input.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
textbox.insert(tk.INSERT,text)
if(button=="def"):
end=False
i=0
while(end==False):
i+=1
def_input_commands.insert('{}.0'.format(i),"\t")
if(i > 20):
end=True
text="def {} (): \n{}\n#You can call the function with {}()".format(def_input_name.get(),def_input_commands.get("1.0",tk.END),def_input_name.get())
def_text_name.grid_forget()
def_text_commands.grid_forget()
def_cancel_button.grid_forget()
def_add_button.grid_forget()
def_input_name.grid_forget()
def_input_commands.grid_forget()
def_print_button.grid_forget()
def_input_button.grid_forget()
def_var_button.grid_forget()
def_if_button.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
if_button.pack(fill=tk.X)
textbox.insert(tk.INSERT,text)
if(button=="if"):
end=False
i=0
while(end==False):
i+=1
if_input_commands.insert('{}.0'.format(i),"\t")
if(i > 20):
end=True
text="if ({}): \n{}\n".format(if_input_name.get(),if_input_commands.get("1.0",tk.END))
if_text_name.grid_forget()
if_text_commands.grid_forget()
if_cancel_button.grid_forget()
if_add_button.grid_forget()
if_input_name.grid_forget()
if_input_commands.grid_forget()
if_print_button.grid_forget()
if_input_button.grid_forget()
if_var_button.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
if_button.pack(fill=tk.X)
textbox.insert(tk.INSERT,text)
frame3.tkraise()
frame7.tkraise()
frame2.tkraise()
def cancel(button):
global def_var_input,def_print_input, if_var_input,if_print_input, if_input_name,if_input_commands,def_if_input_name,def_if_input_commands
if(button=="print"):
#global print_cancel_button,print_add_button
print_text.grid_forget()
print_cancel_button.grid_forget()
print_add_button.grid_forget()
print_advanced_button.grid_forget()
print_input.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
if_button.pack(fill=tk.X)
elif(button=="input"):
#global input_cancel_button,add_button
input_text.grid_forget()
input_name.grid_forget()
input_type.grid_forget()
input_cancel_button.grid_forget()
input_add_button.grid_forget()
input_input.grid_forget()
input_input2.grid_forget()
input_input3.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
if_button.pack(fill=tk.X)
elif(button=="var"):
var_text.grid_forget()
var_cancel_button.grid_forget()
var_add_button.grid_forget()
var_input.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
if_button.pack(fill=tk.X)
elif(button=="def"):
def_text_name.grid_forget()
def_text_commands.grid_forget()
def_cancel_button.grid_forget()
def_add_button.grid_forget()
def_input_name.grid_forget()
def_input_commands.grid_forget()
def_print_button.grid_forget()
def_input_button.grid_forget()
def_var_button.grid_forget()
def_if_button.grid_forget()
def_print_text.grid_forget()
def_print_cancel_button.grid_forget()
def_print_add_button.grid_forget()
def_print_input.grid_forget()
def_print_advanced_button.grid_forget()
def_input_text.grid_forget()
def_input_text_name.grid_forget()
def_input_type.grid_forget()
def_input_cancel_button.grid_forget()
def_input_add_button.grid_forget()
def_input_input.grid_forget()
def_input_input2.grid_forget()
def_input_input3.grid_forget()
def_var_text.grid_forget()
def_var_cancel_button.grid_forget()
def_var_add_button.grid_forget()
def_var_input.grid_forget()
if_text_name.grid_forget()
if_text_commands.grid_forget()
if_cancel_button.grid_forget()
if_add_button.grid_forget()
def_if_text_name.grid_forget()
def_if_text_commands.grid_forget()
def_if_print_button.grid_forget()
def_if_input_button.grid_forget()
def_if_var_button.grid_forget()
def_if_cancel_button.grid_forget()
def_if_add_button.grid_forget()
def_if_input_name.grid_forget()
def_if_input_commands.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
if_button.pack(fill=tk.X)
elif(button=="if"):
if_text_name.grid_forget()
if_text_commands.grid_forget()
if_cancel_button.grid_forget()
if_add_button.grid_forget()
if_input_name.grid_forget()
if_input_commands.grid_forget()
if_print_button.grid_forget()
if_input_button.grid_forget()
if_var_button.grid_forget()
if_print_text.grid_forget()
if_print_cancel_button.grid_forget()
if_print_add_button.grid_forget()
if_print_input.grid_forget()
if_print_advanced_button.grid_forget()
if_input_text.grid_forget()
if_input_text_name.grid_forget()
if_input_type.grid_forget()
if_input_cancel_button.grid_forget()
if_input_add_button.grid_forget()
if_input_input.grid_forget()
if_input_input2.grid_forget()
if_input_input3.grid_forget()
if_var_text.grid_forget()
if_var_cancel_button.grid_forget()
if_var_add_button.grid_forget()
if_var_input.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
if_button.pack(fill=tk.X)
frame3.tkraise()
frame7.tkraise()
frame2.tkraise()
frame5.tkraise()
def advanced(button):
if(button=="print"):
global print_advanced_input, print_advanced_input2
print_text.grid_forget()
print_cancel_button.grid_forget()
print_add_button.grid_forget()
print_advanced_button.grid_forget()
print_input.grid_forget()
print_advanced_input=tk.Entry(frame8)
print_advanced_input2=tk.Entry(frame8)
print_advanced_text.grid()
print_advanced_input.grid()
print_advanced_variables.grid(row=2)
print_advanced_input2.grid()
print_advanced_add_button.grid(row=0,column=1)
print_advanced_cancel_button.grid(row=0,column=0)
frame11.tkraise()
frame8.tkraise()
def advanced_add(button):
if(button=="print"):
global text
text="print('{}'.format({}))".format(print_advanced_input.get(),print_advanced_input2.get())+"\n"
print_text.grid_forget()
print_advanced_cancel_button.grid_forget()
print_advanced_add_button.grid_forget()
print_advanced_input.grid_forget()
print_advanced_input2.grid_forget()
print_advanced_text.grid_forget()
print_advanced_variables.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
textbox.insert(tk.INSERT,text)
frame11.tkraise()
frame4.tkraise()
frame3.tkraise()
frame7.tkraise()
frame2.tkraise()
frame5.tkraise()
def advanced_cancel(button):
if(button=="print"):
print_text.grid_forget()
print_advanced_cancel_button.grid_forget()
print_advanced_add_button.grid_forget()
print_advanced_input.grid_forget()
print_advanced_input2.grid_forget()
print_advanced_text.grid_forget()
print_advanced_variables.grid_forget()
print_button.pack(fill=tk.X)
input_button.pack(fill=tk.X)
var_button.pack(fill=tk.X)
def_button.pack(fill=tk.X)
frame3.tkraise()
frame7.tkraise()
frame2.tkraise()
frame5.tkraise()
frame4.tkraise()
#print----------------------------------------------------------------------------------------------
def cmd_print():
global print_input
print_button.pack_forget()
input_button.pack_forget()
var_button.pack_forget()
def_button.pack_forget()
if_button.pack_forget()
print_text.grid()
print_input=tk.Entry(frame7)
print_input.grid(row=4)
print_cancel_button.grid(row=5,column=0)
print_add_button.grid(row=5,column=1)
print_advanced_button.grid(row=5,column=2)
frame3.tkraise()
frame7.tkraise()
#----------------------------------------------------------------------------------------------
#input----------------------------------------------------------------------------------------------
def cmd_input():
global input_input,input_input2,input_input3
print_button.pack_forget()
input_button.pack_forget()
var_button.pack_forget()
def_button.pack_forget()
if_button.pack_forget()
input_input=tk.Entry(grid_frame2)
input_input2=tk.Entry(grid_frame2)
input_input3=tk.Entry(grid_frame2)
input_name.grid()
input_input.grid()
input_text.grid()
input_input2.grid()
input_type.grid()
input_input3.grid()
input_cancel_button.grid(row=6)
input_add_button.grid(row=6,column=1)
grid_frame2.tkraise()
frame5.tkraise()
#var-------------------------------------------------------------------------------------------------------------
def cmd_var():
global var_input
print_button.pack_forget()
input_button.pack_forget()
var_button.pack_forget()
def_button.pack_forget()
if_button.pack_forget()
var_input=tk.Entry(frame9)
var_text.grid()
var_input.grid()
var_cancel_button.grid(row=5)
var_add_button.grid(row=5,column=1)
frame9.tkraise()
frame10.tkraise()
#def----------------------------------------------------------------------------------------------------------
def cmd_def():
global def_input_name, def_input_commands
print_button.pack_forget()
input_button.pack_forget()
var_button.pack_forget()
def_button.pack_forget()
if_button.pack_forget()
def_input_name=tk.Entry(frame9,bg="#727272",fg="white",bd=0)
def_input_commands=tk.Text(frame9,width=50, height=10,bg="#727272",fg="white",bd=0)
def_text_name.grid()
def_input_name.grid()
def_text_commands.grid()
def_input_commands.grid()
def_cancel_button.grid(row=5)
def_add_button.grid(row=5,column=1)
def_print_button.grid(row=5,column=2)
def_input_button.grid(row=5,column=3)
def_var_button.grid(row=5,column=4)
def_if_button.grid(row=5,column=5)
frame9.tkraise()
def_buttons_frame.tkraise()
def def_print():
global def_print_input
def_print_button.grid_forget()
def_input_button.grid_forget()
def_var_button.grid_forget()
def_if_button.grid_forget()
def_print_text.grid()
def_print_input=tk.Entry(def_print_text_frame)
def_print_input.grid(row=4)
def_print_cancel_button.grid(row=5,column=0)
def_print_add_button.grid(row=5,column=1)
def_print_advanced_button.grid(row=5,column=2)
def_print_text_frame.tkraise()
def_print_buttons_frame.tkraise()
def def_input():
global def_input_input,def_input_input2,def_input_input3
def_print_button.grid_forget()
def_input_button.grid_forget()
def_var_button.grid_forget()
def_if_button.grid_forget()
def_input_input=tk.Entry(def_input_text_frame)
def_input_input2=tk.Entry(def_input_text_frame)
def_input_input3=tk.Entry(def_input_text_frame)
def_input_text_name.grid()
def_input_input.grid()
def_input_text.grid()
def_input_input2.grid()
def_input_type.grid()
def_input_input3.grid()
def_input_cancel_button.grid(row=6)
def_input_add_button.grid(row=6,column=1)
def_input_text_frame.tkraise()
def_input_buttons_frame.tkraise()
def def_var():
global def_var_input
def_print_button.grid_forget()
def_input_button.grid_forget()
def_var_button.grid_forget()
def_if_button.grid_forget()
def_var_input=tk.Entry(def_var_text_frame)
def_var_text.grid()
def_var_input.grid()
def_var_cancel_button.grid(row=5)
def_var_add_button.grid(row=5,column=1)
def_var_text_frame.tkraise()
def_var_buttons_frame.tkraise()
def def_if():
global def_if_input_name, def_if_input_commands
def_print_button.grid_forget()
def_input_button.grid_forget()
def_var_button.grid_forget()
def_if_button.grid_forget()
def_if_input_name=tk.Entry(def_if_text_frame,bg="#727272",fg="white",bd=0)
def_if_input_commands=tk.Text(def_if_text_frame,width=50, height=10,bg="#727272",fg="white",bd=0)
def_if_text_name.grid()
def_if_input_name.grid()
def_if_text_commands.grid()
def_if_input_commands.grid()
def_if_cancel_button.grid(row=1)
def_if_add_button.grid(row=1,column=1)
def_if_print_button.grid(row=1,column=2)
def_if_input_button.grid(row=1,column=3)
def_if_var_button.grid(row=1,column=4)
def def_if_print():
global def_if_print_input
def_if_print_button.grid_forget()
def_if_input_button.grid_forget()
def_if_var_button.grid_forget()
def_if_print_text.grid()
def_if_print_input=tk.Entry(def_if_print_text_frame)
def_if_print_input.grid(row=4)
def_if_print_cancel_button.grid(row=5,column=0)
def_if_print_add_button.grid(row=5,column=1)
def_if_print_advanced_button.grid(row=5,column=2)
def_if_print_text_frame.tkraise()
def_if_print_buttons_frame.tkraise()
def def_if_input():
global def_if_input_input,def_if_input_input2,def_if_input_input3
def_if_print_button.grid_forget()
def_if_input_button.grid_forget()
def_if_var_button.grid_forget()
def_if_input_input=tk.Entry(def_if_input_text_frame)
def_if_input_input2=tk.Entry(def_if_input_text_frame)
def_if_input_input3=tk.Entry(def_if_input_text_frame)
def_if_input_text_name.grid()
def_if_input_input.grid()
def_if_input_text.grid()
def_if_input_input2.grid()
def_if_input_type.grid()
def_if_input_input3.grid()
def_if_input_cancel_button.grid(row=6)
def_if_input_add_button.grid(row=6,column=1)
def_if_input_text_frame.tkraise()
def_if_input_buttons_frame.tkraise()
def def_if_var():
global def_if_var_input
def_if_print_button.grid_forget()
def_if_input_button.grid_forget()
def_if_var_button.grid_forget()
def_if_var_input=tk.Entry(def_if_var_text_frame)
def_if_var_text.grid()
def_if_var_input.grid()
def_if_var_cancel_button.grid(row=5)
def_if_var_add_button.grid(row=5,column=1)
def_if_var_text_frame.tkraise()
def_if_var_buttons_frame.tkraise()
def show_buttons():
def_print_button.grid(row=5,column=2)
def_input_button.grid(row=5,column=3)
def_var_button.grid(row=5,column=4)
def_if_button.grid(row=5,column=5)
def if_show_buttons():
def_if_print_button.grid(row=1,column=2)
def_if_input_button.grid(row=1,column=3)
def_if_var_button.grid(row=1,column=4)
def def_add(button):
if(button=="print"):
global text,def_input_commands
text="print('{}')\n".format(def_print_input.get())
def_print_text.grid_forget()
def_print_cancel_button.grid_forget()
def_print_add_button.grid_forget()
def_print_input.grid_forget()
def_print_advanced_button.grid_forget()
show_buttons()
def_input_commands.insert(tk.INSERT,text)
frame4.tkraise()
if(button=="input"):
#global input_input
if(def_input_input3.get()=="str"):
text="{} = input('{}')\n".format(def_input_input.get(),def_input_input2.get())
elif(def_input_input3.get()=="int"):
text="{} = int(input('{}'))\n".format(def_input_input.get(),def_input_input2.get())
elif(def_input_input3.get()=="float"):
text="{} = float(input('{}'))\n".format(def_input_input.get(),def_input_input2.get())
def_input_text.grid_forget()
def_input_type.grid_forget()
def_input_text_name.grid_forget()
def_input_cancel_button.grid_forget()
def_input_add_button.grid_forget()
def_input_input.grid_forget()
def_input_input2.grid_forget()
def_input_input3.grid_forget()
show_buttons()
def_input_commands.insert(tk.INSERT,text)
if(button=="var"):
text="{} \n".format(def_var_input.get())
def_var_text.grid_forget()
def_var_cancel_button.grid_forget()
def_var_add_button.grid_forget()
def_var_input.grid_forget()
show_buttons()
def_input_commands.insert(tk.INSERT,text)
if(button=="if"):
end=False
i=0
while(end==False):
i+=1
def_if_input_commands.insert('{}.0'.format(i),"\t")
if(i > 20):
end=True
text="if ({}): \n{}\n".format(def_if_input_name.get(),def_if_input_commands.get("1.0",tk.END))
def_if_text_name.grid_forget()
def_if_text_commands.grid_forget()
def_if_cancel_button.grid_forget()
def_if_add_button.grid_forget()
def_if_input_name.grid_forget()
def_if_input_commands.grid_forget()
def_if_print_button.grid_forget()
def_if_input_button.grid_forget()
def_if_var_button.grid_forget()
show_buttons()
def_input_commands.insert(tk.INSERT,text)
if(button=="if print"):
text="print('{}')\n".format(def_if_print_input.get())
def_if_print_text.grid_forget()
def_if_print_cancel_button.grid_forget()
def_if_print_add_button.grid_forget()
def_if_print_input.grid_forget()
def_if_print_advanced_button.grid_forget()
if_show_buttons()
#if_var_button.grid(row=5,column=5)
def_if_input_commands.insert(tk.INSERT,text)
frame4.tkraise()
if(button == "if input"):
if(def_if_input_input3.get()=="str"):
text="{} = input('{}')\n".format(def_if_input_input.get(),def_if_input_input2.get())
elif(def_if_input_input3.get()=="int"):
text="{} = int(input('{}'))\n".format(def_if_input_input.get(),def_if_input_input2.get())
elif(def_if_input_input3.get()=="float"):
text="{} = float(input('{}'))\n".format(def_if_input_input.get(),def_if_input_input2.get())
def_if_input_text.grid_forget()
def_if_input_type.grid_forget()
def_if_input_text_name.grid_forget()
def_if_input_cancel_button.grid_forget()
def_if_input_add_button.grid_forget()
def_if_input_input.grid_forget()
def_if_input_input2.grid_forget()
def_if_input_input3.grid_forget()
if_show_buttons()
def_if_input_commands.insert(tk.INSERT,text)
frame4.tkraise()
if(button=="if var"):
text="{}\n".format(def_if_var_input.get())
def_if_var_text.grid_forget()
def_if_var_cancel_button.grid_forget()
def_if_var_add_button.grid_forget()
def_if_var_input.grid_forget()
if_show_buttons()
def_if_input_commands.insert(tk.INSERT,text)
frame4.tkraise()
def def_cancel(button):
if(button=="print"):
global def_if_print_input
def_print_text.grid_forget()
def_print_cancel_button.grid_forget()
def_print_add_button.grid_forget()
def_print_advanced_button.grid_forget()
def_print_input.grid_forget()
show_buttons()
frame4.tkraise()
elif(button=="input"):
#global input_cancel_button,add_button
def_input_text.grid_forget()
def_input_text_name.grid_forget()
def_input_type.grid_forget()
def_input_cancel_button.grid_forget()
def_input_add_button.grid_forget()
def_input_input.grid_forget()
def_input_input2.grid_forget()
def_input_input3.grid_forget()
show_buttons()
#if_var_button.grid(row=5,column=5)
elif(button=="var"):
def_var_text.grid_forget()
def_var_cancel_button.grid_forget()
def_var_add_button.grid_forget()
def_var_input.grid_forget()
show_buttons()
# if_var_button.grid(row=5,column=5)
elif(button=="if"):
def_if_text_name.grid_forget()
def_if_text_commands.grid_forget()
def_if_print_button.grid_forget()
def_if_input_button.grid_forget()
def_if_var_button.grid_forget()
def_if_cancel_button.grid_forget()
def_if_add_button.grid_forget()
def_if_input_name.grid_forget()
def_if_input_commands.grid_forget()
def_if_print_text.grid_forget()
def_if_print_cancel_button.grid_forget()
def_if_print_add_button.grid_forget()
def_if_print_input.grid_forget()
def_if_print_advanced_button.grid_forget()
def_if_input_text.grid_forget()
def_if_input_type.grid_forget()
def_if_input_text_name.grid_forget()
def_if_input_cancel_button.grid_forget()
def_if_input_add_button.grid_forget()
def_if_input_input.grid_forget()
def_if_input_input2.grid_forget()
def_if_input_input3.grid_forget()
def_if_var_text.grid_forget()
def_if_var_cancel_button.grid_forget()
def_if_var_add_button.grid_forget()
def_if_var_input.grid_forget()
show_buttons()
#if_var_button.grid(row=5,column=5)
elif(button=="if print"):
def_if_print_text.grid_forget()
def_if_print_cancel_button.grid_forget()
def_if_print_add_button.grid_forget()
def_if_print_input.grid_forget()
def_if_print_advanced_button.grid_forget()
if_show_buttons()
elif(button=="if input"):
def_if_input_text.grid_forget()
def_if_input_type.grid_forget()
def_if_input_text_name.grid_forget()
def_if_input_cancel_button.grid_forget()
def_if_input_add_button.grid_forget()
def_if_input_input.grid_forget()
def_if_input_input2.grid_forget()
def_if_input_input3.grid_forget()
if_show_buttons()
elif(button =="if var"):
def_if_var_text.grid_forget()
def_if_var_cancel_button.grid_forget()
def_if_var_add_button.grid_forget()
def_if_var_input.grid_forget()
if_show_buttons()
def def_advanced(button):
if(button=="print"):
global def_print_advanced_input, def_print_advanced_input2
def_print_text.grid_forget()
def_print_cancel_button.grid_forget()
def_print_add_button.grid_forget()
def_print_advanced_button.grid_forget()
def_print_input.grid_forget()
def_print_advanced_input=tk.Entry(def_print_advanced_text_frame)
def_print_advanced_input2=tk.Entry(def_print_advanced_text_frame)
def_print_advanced_text.grid()
def_print_advanced_input.grid()
def_print_advanced_variables.grid(row=2)
def_print_advanced_input2.grid()
def_print_advanced_add_button.grid(row=0,column=1)
def_print_advanced_cancel_button.grid(row=0,column=0)
def_print_advanced_buttons_frame.tkraise()
def_print_advanced_text_frame.tkraise()
def def_advanced_add(button):
if(button=="print"):
global text
text="print('{}'.format({}))".format(def_print_advanced_input.get(),def_print_advanced_input2.get())+"\n"
def_print_text.grid_forget()
def_print_advanced_cancel_button.grid_forget()
def_print_advanced_add_button.grid_forget()
def_print_advanced_input.grid_forget()
def_print_advanced_input2.grid_forget()
def_print_advanced_text.grid_forget()
def_print_advanced_variables.grid_forget()
def_print_button.grid(row=5,column=2)
def_input_button.grid(row=5,column=3)
def_var_button.grid(row=5,column=4)
def_input_commands.insert(tk.INSERT,text)
frame11.tkraise()
frame4.tkraise()
def def_advanced_cancel(button):
if(button=="print"):
def_print_text.grid_forget()
def_print_advanced_cancel_button.grid_forget()
def_print_advanced_add_button.grid_forget()
def_print_advanced_input.grid_forget()
def_print_advanced_input2.grid_forget()
def_print_advanced_text.grid_forget()
def_print_advanced_variables.grid_forget()
def_print_button.grid(row=5,column=2)
def_input_button.grid(row=5,column=3)
def_var_button.grid(row=5,column=4)
frame11.tkraise()
frame4.tkraise()
def def_if_advanced(button):
if(button=="print"):
global def_if_print_advanced_input, def_if_print_advanced_input2
def_if_print_text.grid_forget()
def_if_print_cancel_button.grid_forget()
def_if_print_add_button.grid_forget()
def_if_print_advanced_button.grid_forget()
def_if_print_input.grid_forget()
def_if_print_advanced_input=tk.Entry(def_if_print_advanced_text_frame)
def_if_print_advanced_input2=tk.Entry(def_if_print_advanced_text_frame)
def_if_print_advanced_text.grid()
def_if_print_advanced_input.grid()
def_if_print_advanced_variables.grid(row=2)
def_if_print_advanced_input2.grid()
def_if_print_advanced_add_button.grid(row=0,column=1)
def_if_print_advanced_cancel_button.grid(row=0,column=0)
def_if_print_advanced_buttons_frame.tkraise()
def_if_print_advanced_text_frame.tkraise()
def def_if_advanced_add(button):
if(button=="print"):
global text
text="print('{}'.format({}))".format(def_if_print_advanced_input.get(),def_if_print_advanced_input2.get())+"\n"
def_if_print_text.grid_forget()
def_if_print_advanced_cancel_button.grid_forget()
def_if_print_advanced_add_button.grid_forget()
def_if_print_advanced_input.grid_forget()
def_if_print_advanced_input2.grid_forget()
def_if_print_advanced_text.grid_forget()
def_if_print_advanced_variables.grid_forget()
if_show_buttons()
def_if_input_commands.insert(tk.INSERT,text)
def_if_print_advanced_text_frame.tkraise()
def_if_print_advanced_buttons_frame.tkraise()
def def_if_advanced_cancel(button):
if(button=="print"):
def_if_print_text.grid_forget()
def_if_print_advanced_cancel_button.grid_forget()
def_if_print_advanced_add_button.grid_forget()
def_if_print_advanced_input.grid_forget()
def_if_print_advanced_input2.grid_forget()
def_if_print_advanced_text.grid_forget()
def_if_print_advanced_variables.grid_forget()
if_show_buttons()
def_if_print_advanced_buttons_frame.tkraise()
def_if_print_advanced_text_frame.tkraise()
#If------------------------------------------------------------------------------------------------------
def cmd_if():
global if_input_name, if_input_commands
print_button.pack_forget()
input_button.pack_forget()
var_button.pack_forget()
def_button.pack_forget()
if_button.pack_forget()
if_input_name=tk.Entry(frame9,bg="#727272",fg="white",bd=0)
if_input_commands=tk.Text(frame9,width=50, height=10,bg="#727272",fg="white",bd=0)
if_text_name.grid()
if_input_name.grid()
if_text_commands.grid()
if_input_commands.grid()
if_cancel_button.grid(row=5)
if_add_button.grid(row=5,column=1)
if_print_button.grid(row=5,column=2)
if_input_button.grid(row=5,column=3)
if_var_button.grid(row=5,column=4)
frame9.tkraise()
if_buttons_frame.tkraise()
def if_print():
global if_print_input
if_print_button.grid_forget()
if_input_button.grid_forget()
if_var_button.grid_forget()
if_print_text.grid()
if_print_input=tk.Entry(if_print_text_frame)
if_print_input.grid(row=4)
if_print_cancel_button.grid(row=5,column=0)
if_print_add_button.grid(row=5,column=1)
if_print_advanced_button.grid(row=5,column=2)
if_print_text_frame.tkraise()
if_print_buttons_frame.tkraise()
def if_input():
global if_input_input,if_input_input2,if_input_input3
if_print_button.grid_forget()
if_input_button.grid_forget()
if_var_button.grid_forget()
if_input_input=tk.Entry(if_input_text_frame)
if_input_input2=tk.Entry(if_input_text_frame)
if_input_input3=tk.Entry(if_input_text_frame)
if_input_text_name.grid()
if_input_input.grid()
if_input_text.grid()
if_input_input2.grid()
if_input_type.grid()
if_input_input3.grid()
if_input_cancel_button.grid(row=6)
if_input_add_button.grid(row=6,column=1)
if_input_text_frame.tkraise()
if_input_buttons_frame.tkraise()
def if_var():
global if_var_input
if_print_button.grid_forget()
if_input_button.grid_forget()
if_var_button.grid_forget()
if_var_input=tk.Entry(if_var_text_frame)
if_var_text.grid()
if_var_input.grid()
if_var_cancel_button.grid(row=5)
if_var_add_button.grid(row=5,column=1)
if_var_text_frame.tkraise()
if_var_buttons_frame.tkraise()
def if_add(button):
if(button=="print"):
global text,if_input_commands
text="print('{}')\n".format(if_print_input.get())
if_print_text.grid_forget()
if_print_cancel_button.grid_forget()
if_print_add_button.grid_forget()
if_print_input.grid_forget()
if_print_advanced_button.grid_forget()
if_print_button.grid(row=5,column=2)
if_input_button.grid(row=5,column=3)
if_var_button.grid(row=5,column=4)
if_input_commands.insert(tk.INSERT,text)
frame4.tkraise()
if(button=="input"):
#global input_input
if(if_input_input3.get()=="str"):
text="{} = input('{}')\n".format(if_input_input.get(),if_input_input2.get())+"\n"
elif(if_input_input3.get()=="int"):
text="{} = int(input('{}'))\n".format(if_input_input.get(),if_input_input2.get())+"\n"
elif(if_input_input3.get()=="float"):
text="{} = float(input('{}'))\n".format(if_input_input.get(),if_input_input2.get())+"\n"
if_input_text.grid_forget()
if_input_type.grid_forget()
if_input_text_name.grid_forget()
if_input_cancel_button.grid_forget()
if_input_add_button.grid_forget()
if_input_input.grid_forget()
if_input_input2.grid_forget()
if_input_input3.grid_forget()
if_print_button.grid(row=5,column=2)
if_input_button.grid(row=5,column=3)
if_var_button.grid(row=5,column=4)
if_input_commands.insert(tk.INSERT,text)
if(button=="var"):
text="{} \n".format(if_var_input.get())
if_var_text.grid_forget()
if_var_cancel_button.grid_forget()
if_var_add_button.grid_forget()
if_var_input.grid_forget()
if_print_button.grid(row=5,column=2)
if_input_button.grid(row=5,column=3)
if_var_button.grid(row=5,column=4)
if_input_commands.insert(tk.INSERT,text)
def if_cancel(button):
if(button=="print"):
#global print_cancel_button,print_add_button
if_print_text.grid_forget()
if_print_cancel_button.grid_forget()
if_print_add_button.grid_forget()
if_print_advanced_button.grid_forget()
if_print_input.grid_forget()
if_print_button.grid(row=5,column=2)
if_input_button.grid(row=5,column=3)
if_var_button.grid(row=5,column=4)
frame4.tkraise()
elif(button=="input"):
#global input_cancel_button,add_button
if_input_text.grid_forget()
if_input_text_name.grid_forget()
if_input_type.grid_forget()
if_input_cancel_button.grid_forget()
if_input_add_button.grid_forget()
if_input_input.grid_forget()
if_input_input2.grid_forget()
if_input_input3.grid_forget()
if_print_button.grid(row=5,column=2)
if_input_button.grid(row=5,column=3)
if_var_button.grid(row=5,column=4)
elif(button=="var"):
if_var_text.grid_forget()
if_var_cancel_button.grid_forget()
if_var_add_button.grid_forget()
if_var_input.grid_forget()
if_print_button.grid(row=5,column=2)
if_input_button.grid(row=5,column=3)
if_var_button.grid(row=5,column=4)
def if_advanced(button):
if(button=="print"):
global if_print_advanced_input, if_print_advanced_input2
if_print_text.grid_forget()
if_print_cancel_button.grid_forget()
if_print_add_button.grid_forget()
if_print_advanced_button.grid_forget()
if_print_input.grid_forget()
if_print_advanced_input=tk.Entry(if_print_advanced_text_frame)
if_print_advanced_input2=tk.Entry(if_print_advanced_text_frame)
if_print_advanced_text.grid()
if_print_advanced_input.grid()
if_print_advanced_variables.grid(row=2)
if_print_advanced_input2.grid()
if_print_advanced_add_button.grid(row=0,column=1)
if_print_advanced_cancel_button.grid(row=0,column=0)
if_print_advanced_buttons_frame.tkraise()
if_print_advanced_text_frame.tkraise()
def if_advanced_add(button):
if(button=="print"):
global text
text="print('{}'.format({}))".format(if_print_advanced_input.get(),if_print_advanced_input2.get())+"\n"
if_print_text.grid_forget()
if_print_advanced_cancel_button.grid_forget()
if_print_advanced_add_button.grid_forget()
if_print_advanced_input.grid_forget()
if_print_advanced_input2.grid_forget()
if_print_advanced_text.grid_forget()
if_print_advanced_variables.grid_forget()
if_print_button.grid(row=5,column=2)
if_input_button.grid(row=5,column=3)
if_var_button.grid(row=5,column=4)
if_input_commands.insert(tk.INSERT,text)
frame11.tkraise()
frame4.tkraise()
def if_advanced_cancel(button):
if(button=="print"):
if_print_text.grid_forget()
if_print_advanced_cancel_button.grid_forget()
if_print_advanced_add_button.grid_forget()
if_print_advanced_input.grid_forget()
if_print_advanced_input2.grid_forget()
if_print_advanced_text.grid_forget()
if_print_advanced_variables.grid_forget()
if_print_button.grid(row=5,column=2)
if_input_button.grid(row=5,column=3)
if_var_button.grid(row=5,column=4)
frame11.tkraise()
frame4.tkraise()
#Build---------------------------------------------------------------------------------------------------
def file(text):
destination=filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("Python","*.py"),("All Files","*.*")))
if(destination !=""):
createFile(destination,text)
def createFile(dest,text):
global build
if not(path.isfile(dest)):
f = open(dest+".py",'w')
f.write(textbox.get("1.0", tk.END))
f.close()
building_frame.tkraise()
build.grid(row=10,column=1)
root.after(1000,close_building)
def close_building():
build.grid_forget()
frame4.tkraise()
frame2.tkraise()
frame.tkraise()
frame6.tkraise()
build = tk.Label(building_frame,text='Building was successful',width=30,height=3,font='Arial 18',bg="green")
#Frame 1--------------------------------------------------------------------------------------------
title = tk.Label(frame,text='Easy Python Coder',font='Arial 18',bg="#404142",fg="#efa207")
title.grid(row=0,column=0)
#Buttons--------------------------------------------------------------------------------------------
border_width=0.5
print_button = tk.Button(frame2,text="Print", command=cmd_print,bg="#727272",fg="#efa207",relief="solid",bd=border_width)
print_button.pack(fill=tk.X)
print_text = tk.Label(frame7,text='What to print?',bg="#404142",fg="#efa207")
print_cancel_button = tk.Button(frame3,text="Cancel", command=lambda: cancel("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
print_add_button = tk.Button(frame3,text="Add", command = lambda: add("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
print_advanced_button = tk.Button(frame3,text="Advanced", command = lambda: advanced("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
print_advanced_text = tk.Label(frame8,text='What to print(mark places for variables with {}',bg="#404142",fg="#efa207")
print_advanced_variables = tk.Label(frame8,text='What variables do you want them to represent?',bg="#404142",fg="#efa207")
print_advanced_cancel_button = tk.Button(frame11,text="Cancel", command=lambda: advanced_cancel("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
print_advanced_add_button = tk.Button(frame11,text="Add", command = lambda: advanced_add("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
input_button = tk.Button(frame2,text="Input", command=cmd_input,bg="#727272",fg="#efa207",relief="solid",bd=border_width)
input_button.pack(fill=tk.X)
input_text = tk.Label(grid_frame2,text='What do you want it to ask?',bg="#404142",fg="#efa207")
input_name = tk.Label(grid_frame2,text='What is the name of the input?',bg="#404142",fg="#efa207")
input_type = tk.Label(grid_frame2,text='What type is the input(int,float or str)',bg="#404142",fg="#efa207")
input_cancel_button = tk.Button(frame5,text="Cancel", command=lambda: cancel("input"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
input_add_button = tk.Button(frame5,text="Add", command = lambda: add("input"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
var_button = tk.Button(frame2,text="Variable", command=cmd_var,bg="#727272",fg="#efa207",relief="solid",bd=border_width)
var_button.pack(fill=tk.X)
var_text = tk.Label(frame9,text='Variable name and value',bg="#404142",fg="#efa207")
var_cancel_button = tk.Button(frame10,text="Cancel", command=lambda: cancel("var"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
var_add_button = tk.Button(frame10,text="Add", command = lambda: add("var"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_button = tk.Button(frame2,text="Function", command=cmd_def,bg="#727272",fg="#efa207",relief="solid",bd=border_width)
def_button.pack(fill=tk.X)
def_text_name = tk.Label(frame9,text='Function name',bg="#404142",fg="#efa207")
def_text_commands = tk.Label(frame9,text='Commands inside the function',bg="#404142",fg="#efa207")
def_cancel_button = tk.Button(def_buttons_frame,text="Cancel", command=lambda: cancel("def"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_add_button = tk.Button(def_buttons_frame,text="Add", command = lambda: add("def"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_print_button = tk.Button(def_buttons_frame,text="Print", command = def_print,bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_input_button = tk.Button(def_buttons_frame,text="Input", command = def_input,bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_var_button = tk.Button(def_buttons_frame,text="Variable", command = def_var,bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_button = tk.Button(def_buttons_frame,text="If", command = def_if,bg="#727272",relief="solid",bd=border_width,fg="#efa207",padx=10)
def_print_text = tk.Label(def_print_text_frame,text='What to print?',bg="#404142",fg="#efa207")
def_print_cancel_button = tk.Button(def_print_buttons_frame,text="Cancel", command=lambda: def_cancel("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_print_add_button = tk.Button(def_print_buttons_frame,text="Add", command = lambda: def_add("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_print_advanced_button = tk.Button(def_print_buttons_frame,text="Advanced", command = lambda: def_advanced("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_print_advanced_text = tk.Label(def_print_advanced_text_frame,text='What to print(mark places for variables with {}',bg="#404142",fg="#efa207")
def_print_advanced_variables = tk.Label(def_print_advanced_text_frame,text='What variables do you want them to represent?',bg="#404142",fg="#efa207")
def_print_advanced_cancel_button = tk.Button(def_print_advanced_buttons_frame,text="Cancel", command=lambda: def_advanced_cancel("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_print_advanced_add_button = tk.Button(def_print_advanced_buttons_frame,text="Add", command = lambda: def_advanced_add("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_input_text = tk.Label(def_input_text_frame,text='What do you want it to ask?',bg="#404142",fg="#efa207")
def_input_text_name = tk.Label(def_input_text_frame,text='What is the name of the input?',bg="#404142",fg="#efa207")
def_input_type = tk.Label(def_input_text_frame,text='What type is the input(int,float or str)',bg="#404142",fg="#efa207")
def_input_cancel_button = tk.Button(def_input_buttons_frame,text="Cancel", command=lambda:def_cancel("input"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_input_add_button = tk.Button(def_input_buttons_frame,text="Add", command =lambda: def_add("input"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_var_text = tk.Label(def_var_text_frame,text='Variable name and value',bg="#404142",fg="#efa207")
def_var_cancel_button = tk.Button(def_var_buttons_frame,text="Cancel", command=lambda: def_cancel("var"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_var_add_button = tk.Button(def_var_buttons_frame,text="Add", command = lambda: def_add("var"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_text_name = tk.Label(def_if_text_frame,text='If what',bg="#404142",fg="#efa207")
def_if_text_commands = tk.Label(def_if_text_frame,text='Then do',bg="#404142",fg="#efa207")
def_if_cancel_button = tk.Button(def_if_buttons_frame,text="Cancel", command=lambda: def_cancel("if"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_add_button = tk.Button(def_if_buttons_frame,text="Add", command = lambda: def_add("if"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_print_button = tk.Button(def_if_buttons_frame,text="Print", command = def_if_print,bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_input_button = tk.Button(def_if_buttons_frame,text="Input", command = def_if_input,bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_var_button = tk.Button(def_if_buttons_frame,text="Variable", command = def_if_var,bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_print_text = tk.Label(def_if_print_text_frame,text='What to print?',bg="#404142",fg="#efa207")
def_if_print_cancel_button = tk.Button(def_if_print_buttons_frame,text="Cancel", command=lambda: def_cancel("if print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_print_add_button = tk.Button(def_if_print_buttons_frame,text="Add", command = lambda: def_add("if print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_print_advanced_button = tk.Button(def_if_print_buttons_frame,text="Advanced", command = lambda: def_if_advanced("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_print_advanced_text = tk.Label(def_if_print_advanced_text_frame,text='What to print(mark places for variables with {}',bg="#404142",fg="#efa207")
def_if_print_advanced_variables = tk.Label(def_if_print_advanced_text_frame,text='What variables do you want them to represent?',bg="#404142",fg="#efa207")
def_if_print_advanced_cancel_button = tk.Button(def_if_print_advanced_buttons_frame,text="Cancel", command=lambda: def_if_advanced_cancel("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_print_advanced_add_button = tk.Button(def_if_print_advanced_buttons_frame,text="Add", command = lambda: def_if_advanced_add("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_input_text = tk.Label(def_if_input_text_frame,text='What do you want it to ask?',bg="#404142",fg="#efa207")
def_if_input_text_name = tk.Label(def_if_input_text_frame,text='What is the name of the input?',bg="#404142",fg="#efa207")
def_if_input_type = tk.Label(def_if_input_text_frame,text='What type is the input(int,float or str)',bg="#404142",fg="#efa207")
def_if_input_cancel_button = tk.Button(def_if_input_buttons_frame,text="Cancel", command=lambda:def_cancel("if input"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_input_add_button = tk.Button(def_if_input_buttons_frame,text="Add", command =lambda: def_add("if input"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_var_text = tk.Label(def_if_var_text_frame,text='Variable name and value',bg="#404142",fg="#efa207")
def_if_var_cancel_button = tk.Button(def_if_var_buttons_frame,text="Cancel", command=lambda: def_cancel("if var"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
def_if_var_add_button = tk.Button(def_if_var_buttons_frame,text="Add", command = lambda: def_add("if var"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_button = tk.Button(frame2,text="If", command=cmd_if,bg="#727272",fg="#efa207",relief="solid",bd=border_width)
if_button.pack(fill=tk.X)
if_text_name = tk.Label(frame9,text='If what',bg="#404142",fg="#efa207")
if_text_commands = tk.Label(frame9,text='Then do',bg="#404142",fg="#efa207")
if_cancel_button = tk.Button(if_buttons_frame,text="Cancel", command=lambda: cancel("if"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_add_button = tk.Button(if_buttons_frame,text="Add", command = lambda: add("if"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_print_button = tk.Button(if_buttons_frame,text="Print", command = if_print,bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_input_button = tk.Button(if_buttons_frame,text="Input", command = if_input,bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_var_button = tk.Button(if_buttons_frame,text="Variable", command = if_var,bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_print_text = tk.Label(if_print_text_frame,text='What to print?',bg="#404142",fg="#efa207")
if_print_cancel_button = tk.Button(if_print_buttons_frame,text="Cancel", command=lambda: if_cancel("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_print_add_button = tk.Button(if_print_buttons_frame,text="Add", command = lambda: if_add("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_print_advanced_button = tk.Button(if_print_buttons_frame,text="Advanced", command = lambda: if_advanced("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_print_advanced_text = tk.Label(if_print_advanced_text_frame,text='What to print(mark places for variables with {}',bg="#404142",fg="#efa207")
if_print_advanced_variables = tk.Label(if_print_advanced_text_frame,text='What variables do you want them to represent?',bg="#404142",fg="#efa207")
if_print_advanced_cancel_button = tk.Button(if_print_advanced_buttons_frame,text="Cancel", command=lambda: if_advanced_cancel("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_print_advanced_add_button = tk.Button(if_print_advanced_buttons_frame,text="Add", command = lambda: if_advanced_add("print"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_input_text = tk.Label(if_input_text_frame,text='What do you want it to ask?',bg="#404142",fg="#efa207")
if_input_text_name = tk.Label(if_input_text_frame,text='What is the name of the input?',bg="#404142",fg="#efa207")
if_input_type = tk.Label(if_input_text_frame,text='What type is the input(int,float or str)',bg="#404142",fg="#efa207")
if_input_cancel_button = tk.Button(if_input_buttons_frame,text="Cancel", command=lambda:if_cancel("input"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_input_add_button = tk.Button(if_input_buttons_frame,text="Add", command =lambda: if_add("input"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_var_text = tk.Label(if_var_text_frame,text='Variable name and value',bg="#404142",fg="#efa207")
if_var_cancel_button = tk.Button(if_var_buttons_frame,text="Cancel", command=lambda: if_cancel("var"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
if_var_add_button = tk.Button(if_var_buttons_frame,text="Add", command = lambda: if_add("var"),bg="#727272",relief="solid",bd=border_width,fg="#efa207")
#TextBox----------------------------------------------------------------------------------------------------
textbox=tk.Text(frame4,height=42,bg="#727272",fg="white",border=0)
textbox.pack(fill=tk.BOTH)
#Top Menu-----------------------------------------------------------------------------------------------------------
menu = tk.Menu(root)
root.config(menu=menu)
build_menu=tk.Menu(menu)
build_menu.add_command(label='Build',command=lambda: file(text))
menu.add_cascade(label="Build",menu=build_menu)
#Project Name------------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------------------------
frame.place(relx=0.5,rely=0, anchor=tk.N)
frame2.place(x=5,y= 100,anchor=tk.W)
grid_frame2.place(x=30,y= 100,anchor=tk.W)
frame3.place(x=43,y=105)
frame4.place(relx=0.95,y=35, anchor= tk.NE)
frame5.place(x=90,y=180,anchor=tk.W)
frame6.place(relx=0.80,y=20, anchor=tk.E)
frame7.place(x=55,y=80, anchor=tk.W)
frame8.place(x=55,y=60,anchor=tk.W)
building_frame.place(relx=0.5,rely=0.5,anchor=tk.CENTER)
frame9.place(x=55,y=80)
frame10.place(x=80,y=125)
frame11.place(x=135,y=100)
def_buttons_frame.place(x=55,y=310)
def_print_text_frame.place(x=700,y=90)
def_print_buttons_frame.place(x=690,y=135)
def_print_advanced_text_frame.place(x=600,y=90)
def_print_advanced_buttons_frame.place(x=690,y=175)
def_input_text_frame.place(x=700,y=80)
def_input_buttons_frame.place(x=760,y=205)
def_var_text_frame.place(x=700,y=120)
def_var_buttons_frame.place(x=725,y=165)
def_if_text_frame.place(x=50, y= 380)
def_if_buttons_frame.place(x=50,y=610)
if_buttons_frame.place(x=55,y=310)
if_print_text_frame.place(x=700,y=90)
if_print_buttons_frame.place(x=690,y=135)
if_print_advanced_text_frame.place(x=600,y=90)
if_print_advanced_buttons_frame.place(x=690,y=175)
if_input_text_frame.place(x=700,y=80)
if_input_buttons_frame.place(x=760,y=205)
if_var_text_frame.place(x=700,y=120)
if_var_buttons_frame.place(x=725,y=165)
def_if_print_text_frame.place(x=700,y=290)
def_if_print_buttons_frame.place(x=690,y=335)
def_if_print_advanced_text_frame.place(x=600,y=290)
def_if_print_advanced_buttons_frame.place(x=690,y=375)
def_if_input_text_frame.place(x=700,y=280)
def_if_input_buttons_frame.place(x=760,y=405)
def_if_var_text_frame.place(x=700,y=320)
def_if_var_buttons_frame.place(x=725,y=365)
root.state("zoomed")
#root.attributes("-fullscreen",True)
#root.resizable(False,False)
root.minsize(1280,720)
root.mainloop()
input()
| 8fd9c38c70ba2eb82ad928920a3e2f9784acd9bf | [
"Markdown",
"Python"
] | 2 | Markdown | Franziac/Easy-Python-Coder | 43bb69fded964045841806e9a65bd2354c0b3f2d | b3188a8f10113928af5559f4bbc49ef89b146fe5 |
refs/heads/master | <file_sep># HomeControl
A simple framework for adding room features control (like light, temperature, music etc).
Additional features may be implemented in `feature` package as a stand-alone mini-modules.
#Installation guide
1. Download project zip and import it to your Android Studio (use default Gradle Wrapper.).
2. The project requires build tools version 24.0.2 - Android Studio should prompt you to update it automatically.
3. Remember to download all necessary Android SDK's and build tools from your [Android Studio SDK manager](https://developer.android.com/studio/intro/update.html).
4. In order to run your project, you need an Android phone connected via usb, or Android Emulator ([Here is how to setup emulator](https://developer.android.com/studio/run/managing-avds.html))
5. Compile and run your project.
<file_sep>package com.paweldylag.homecontrol.presenter;
/**
* @author <NAME> (<EMAIL>)
*/
public interface RoomPresenter {
void loadRoomData();
}
<file_sep>package com.paweldylag.homecontrol.view.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;
import com.paweldylag.homecontrol.model.Room;
import com.paweldylag.homecontrol.view.RoomFragment;
import java.util.LinkedList;
import java.util.List;
/**
* @author <NAME> (<EMAIL>)
*/
public class RoomPagerAdapter extends FragmentPagerAdapter {
private static final String TAG = RoomPagerAdapter.class.getSimpleName();
private List<Room> mRooms;
public RoomPagerAdapter(FragmentManager fm) {
super(fm);
mRooms = new LinkedList<>();
}
@Override
public Fragment getItem(int position) {
return RoomFragment.build(mRooms.get(position));
}
@Override
public int getCount() {
return mRooms.size();
}
@Override
public CharSequence getPageTitle(int position) {
return mRooms.get(position).name;
}
public int getRoomIndex(Room room) {
int index = mRooms.indexOf(room);
if (index >= 0) {
return index;
} else {
Log.d(TAG, "Unable to find room with name " + room.name + " and id " + room.id);
return 0;
}
}
public void setRooms(List<Room> rooms) {
this.mRooms = rooms;
notifyDataSetChanged();
}
}
<file_sep>package com.paweldylag.homecontrol.view;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.paweldylag.homecontrol.R;
import com.paweldylag.homecontrol.app.App;
import com.paweldylag.homecontrol.app.exception.LoginException;
import com.paweldylag.homecontrol.presenter.LoginPresenter;
import com.paweldylag.homecontrol.presenter.LoginPresenterImpl;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements LoginView {
private LoginPresenter mLoginPresenter;
// UI references.
private AutoCompleteTextView mLoginView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mLoginView = (AutoCompleteTextView) findViewById(R.id.email);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
mLoginPresenter = new LoginPresenterImpl(this, App.getServiceProvider().getAccountRepository());
}
private void attemptLogin() {
mLoginView.setError(null);
mPasswordView.setError(null);
String login = mLoginView.getText().toString();
String password = mPasswordView.getText().toString();
mLoginPresenter.attemptLogin(login, password);
}
@Override
public void showEmptyLogin() {
mLoginView.requestFocus();
mLoginView.setError("Login must not be empty.");
}
@Override
public void showEmptyPassword() {
mPasswordView.requestFocus();
mPasswordView.setError("Password must not be empty.");
}
@Override
public void showWrongPassword() {
mPasswordView.requestFocus();
mPasswordView.setError("Password is wrong.");
}
@Override
public void proceedWithLogin() {
Intent intent = new Intent(this, RoomListActivity.class);
startActivity(intent);
finish();
}
@Override
public void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public void showError(LoginException e) {
Toast.makeText(this, "Error! Code: " + e.getCode(), Toast.LENGTH_SHORT).show();
}
}
<file_sep>package com.paweldylag.homecontrol.feature;
import com.paweldylag.homecontrol.feature.light.LightFeatureView;
import com.paweldylag.homecontrol.feature.music.MusicFeatureView;
import com.paweldylag.homecontrol.feature.temperature.TemperatureFeatureView;
import com.paweldylag.homecontrol.model.Feature;
import com.paweldylag.homecontrol.model.Room;
/**
* @author <NAME> (<EMAIL>)
*/
public class FeatureBundleFactory {
public FeatureBundleFactory() {
}
public FeatureBundle getFeatureBundle(Feature feature, Room room) {
switch(feature.type){
case LIGHT:
return new FeatureBundle(feature, new LightFeatureView(room));
case TEMPERATURE:
return new FeatureBundle(feature, new TemperatureFeatureView(room));
case MUSIC:
return new FeatureBundle(feature, new MusicFeatureView(room));
default:
return null;
}
}
}
<file_sep>package com.paweldylag.homecontrol.view;
import com.paweldylag.homecontrol.app.exception.HomeControlException;
import com.paweldylag.homecontrol.feature.FeatureBundle;
import com.paweldylag.homecontrol.model.Feature;
import java.util.List;
/**
* @author <NAME> (<EMAIL>)
*/
public interface RoomView {
void showFeatures(List<FeatureBundle> features);
void showError(HomeControlException e);
}
<file_sep>package com.paweldylag.homecontrol.feature.light;
import android.os.Build;
import com.paweldylag.homecontrol.BuildConfig;
import com.paweldylag.homecontrol.model.Room;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.assertj.core.api.Java6Assertions.assertThat;
/**
* @author <NAME> (<EMAIL>)
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class LightFeaturePresenterTest {
// ===========================================================
// TESTS
// ===========================================================
@Test
public void changes_brightness_properly() {
// given
LightFeaturePresenter presenter = new LightFeaturePresenter(new Room(0, "a"));
int level = 10;
// when
presenter.onBrightnessChanged(level);
// then
assertThat(presenter.currentBrightness()).isEqualTo(level);
}
@Test
public void changes_light_temperature_properly() {
// given
LightFeaturePresenter presenter = new LightFeaturePresenter(new Room(0, "a"));
int level = 10;
// when
presenter.onTemperatureChanged(level);
// then
assertThat(presenter.currentTemperature()).isEqualTo(level);
}
// ===========================================================
// METHODS AND SUPPORT CLASSES
// ===========================================================
}<file_sep>package com.paweldylag.homecontrol.app.exception;
/**
* @author <NAME> (<EMAIL>)
*/
public class LoginException extends HomeControlException {
public static final int ERROR_EMPTY_LOGIN = 0;
public static final int ERROR_EMPTY_PASSWORD = 1;
public static final int ERROR_WRONG_PASSWORD = 2;
public LoginException(int errorCode, String msg) {
super(errorCode, msg);
}
}
<file_sep>package com.paweldylag.homecontrol.app;
import android.app.Application;
import android.content.Context;
import com.paweldylag.homecontrol.app.service.DefaultServiceProvider;
import com.paweldylag.homecontrol.app.service.ServiceProvider;
/**
* @author <NAME> (<EMAIL>)
*/
public class App extends Application {
private static ServiceProvider serviceProvider = new DefaultServiceProvider();
public static ServiceProvider getServiceProvider() {
return serviceProvider;
}
}
<file_sep>package com.paweldylag.homecontrol.app.service;
import com.paweldylag.homecontrol.app.exception.LoginException;
/**
* @author <NAME> (<EMAIL>)
*/
public interface AccountRepository {
interface LoginCallback {
void onSuccess();
void onError(LoginException e);
}
void login(String login, String password, LoginCallback callback);
}
<file_sep>package com.paweldylag.homecontrol.view.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import com.paweldylag.homecontrol.feature.FeatureBundle;
import java.util.List;
/**
* @author <NAME> (<EMAIL>)
*/
public class FeaturesRecyclerAdapter extends RecyclerView.Adapter<FeatureViewHolder> {
private List<FeatureBundle> mFeatureBundles;
@Override
public FeatureViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
for (FeatureBundle f : mFeatureBundles) {
if(f.getViewHolderType() == viewType) {
return f.createViewHolder(parent);
}
}
return new FeatureViewHolder(parent);
}
@Override
public void onBindViewHolder(FeatureViewHolder holder, int position) {
if (mFeatureBundles != null) {
mFeatureBundles.get(position).bindViewHolder(holder);
}
}
@Override
public int getItemCount() {
if (mFeatureBundles != null) {
return mFeatureBundles.size();
} else return 0;
}
@Override
public int getItemViewType(int position) {
if (mFeatureBundles != null) {
return mFeatureBundles.get(position).getViewHolderType();
} else return 0;
}
public void setFeatureBundles(List<FeatureBundle> featureBundles) {
this.mFeatureBundles = featureBundles;
this.notifyDataSetChanged();
}
}
<file_sep>package com.paweldylag.homecontrol.presenter;
import android.os.Build;
import com.paweldylag.homecontrol.BuildConfig;
import com.paweldylag.homecontrol.app.exception.LoginException;
import com.paweldylag.homecontrol.app.service.AccountRepository;
import com.paweldylag.homecontrol.view.LoginView;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author <NAME> (<EMAIL>)
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
public class LoginPresenterImplTest {
// ===========================================================
// TESTS
// ===========================================================
@Test
public void shows_info_when_wrong_password() {
// given
LoginView view = mock(LoginView.class);
LoginPresenter presenter = new LoginPresenterImpl(view, new DummyAccountRepository());
String login = "wrong";
String password = "<PASSWORD>";
// when
presenter.attemptLogin(login, password);
// then
verify(view).showWrongPassword();
}
@Test
public void shows_info_when_empty_login() {
// given
LoginView view = mock(LoginView.class);
LoginPresenter presenter = new LoginPresenterImpl(view, new DummyAccountRepository());
String login = "";
String password = "<PASSWORD>";
// when
presenter.attemptLogin(login, password);
// then
verify(view).showEmptyLogin();
}
@Test
public void shows_info_when_empty_password() {
// given
LoginView view = mock(LoginView.class);
LoginPresenter presenter = new LoginPresenterImpl(view, new DummyAccountRepository());
String login = "login";
String password = "";
// when
presenter.attemptLogin(login, password);
// then
verify(view).showEmptyPassword();
}
@Test
public void proceed_with_login_when_data_valid() {
// given
LoginView view = mock(LoginView.class);
LoginPresenter presenter = new LoginPresenterImpl(view, new DummyAccountRepository());
String login = "login";
String password = "<PASSWORD>";
// when
presenter.attemptLogin(login, password);
// then
verify(view).proceedWithLogin();
}
// ===========================================================
// METHODS AND SUPPORT CLASSES
// ===========================================================
public static class DummyAccountRepository implements AccountRepository {
private final String login = "login";
private final String password = "<PASSWORD>";
@Override
public void login(String login, String password, LoginCallback callback) {
if (login == null || login.isEmpty()) {
callback.onError(new LoginException(LoginException.ERROR_EMPTY_LOGIN, ""));
} else {
if (login.equals(this.login) && password.equals(this.password)) {
callback.onSuccess();
} else {
callback.onError(new LoginException(LoginException.ERROR_WRONG_PASSWORD, ""));
}
}
}
}
}<file_sep>package com.paweldylag.homecontrol.app.service;
import com.paweldylag.homecontrol.app.exception.HomeControlException;
import com.paweldylag.homecontrol.model.Feature;
import com.paweldylag.homecontrol.model.Room;
import java.util.List;
/**
* @author <NAME> (<EMAIL>)
*/
public interface RoomRepository {
interface RoomCallback {
void onSuccess(List<Room> rooms);
void onError(HomeControlException e);
}
interface FeatureCallback {
void onSuccess(List<Feature> rooms);
void onError(HomeControlException e);
}
interface LoadCallback {
void onSuccess();
void onError(HomeControlException e);
}
/**
* Returns all rooms in repository.
* @param callback
*/
void getRooms(RoomCallback callback);
/**
* Returns all available features in given room
* @param room
*/
void getFeaturesForRoom(Room room, FeatureCallback callback);
/**
* Used for async loading of data from server. Does not return list of rooms.
* See {@link RoomRepository#getRooms(RoomCallback)}
* @param callback
*/
void loadData(LoadCallback callback);
}
<file_sep>package com.paweldylag.homecontrol.app.service;
import com.paweldylag.homecontrol.app.exception.LoginException;
/**
* @author <NAME> (<EMAIL>)
*/
public class OfflineAccountRepository implements AccountRepository {
private static OfflineAccountRepository INSTANCE;
private final String login = "admin";
private final String password = "<PASSWORD>";
public static OfflineAccountRepository getInstance() {
if (INSTANCE == null) {
INSTANCE = new OfflineAccountRepository();
}
return INSTANCE;
}
@Override
public void login(String login, String password, AccountRepository.LoginCallback callback) {
if (login == null || login.isEmpty()) {
callback.onError(new LoginException(LoginException.ERROR_EMPTY_LOGIN, ""));
} else {
if (login.equals(this.login) && password.equals(this.password)) {
callback.onSuccess();
} else {
callback.onError(new LoginException(LoginException.ERROR_WRONG_PASSWORD, ""));
}
}
}
}
<file_sep>package com.paweldylag.homecontrol.view.adapter;
import android.view.ViewGroup;
/**
* @author <NAME> (<EMAIL>)
*/
public class FeatureViewHolderFactory {
public FeatureViewHolder createView(ViewGroup parent, int viewType) {
return null;
}
}
<file_sep>package com.paweldylag.homecontrol.presenter;
import com.paweldylag.homecontrol.model.Room;
/**
* @author <NAME> (<EMAIL>)
*/
public interface RoomListPresenter {
void loadRooms();
void onRoomSelected(Room room);
}
<file_sep>package com.paweldylag.homecontrol.app.service;
/**
* @author <NAME> (<EMAIL>)
*/
public class DummyServiceProvider implements ServiceProvider {
@Override
public RoomRepository getRoomRepository() {
return null;
}
@Override
public AccountRepository getAccountRepository() {
return null;
}
}
<file_sep>package com.paweldylag.homecontrol.app.service;
import com.paweldylag.homecontrol.app.exception.HomeControlException;
import com.paweldylag.homecontrol.model.Feature;
import com.paweldylag.homecontrol.model.FeatureType;
import com.paweldylag.homecontrol.model.Room;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/**
* @author <NAME> (<EMAIL>)
*/
public class OfflineRoomRepository implements RoomRepository {
private static OfflineRoomRepository INSTANCE;
private List<Room> rooms;
private HashMap<Room, List<Feature>> features;
public static OfflineRoomRepository getInstance() {
if (INSTANCE == null) {
INSTANCE = new OfflineRoomRepository();
}
return INSTANCE;
}
protected OfflineRoomRepository() {
rooms = new ArrayList<>();
rooms.add(new Room(0, "Bathroom"));
rooms.add(new Room(1, "Kitchen"));
rooms.add(new Room(2, "Living room"));
List<Feature> kitchenFeatures = new LinkedList<>();
kitchenFeatures.add(new Feature(0, "Light", FeatureType.LIGHT));
List<Feature> bathroomFeatures = new LinkedList<>();
bathroomFeatures.add(new Feature(2, "Light", FeatureType.LIGHT));
bathroomFeatures.add(new Feature(3, "Music", FeatureType.MUSIC));
List<Feature> livingRoomFeatures = new LinkedList<>();
livingRoomFeatures.add(new Feature(5, "Light", FeatureType.LIGHT));
livingRoomFeatures.add(new Feature(6, "Temperature", FeatureType.TEMPERATURE));
features = new HashMap<>();
features.put(rooms.get(0), bathroomFeatures);
features.put(rooms.get(1), kitchenFeatures);
features.put(rooms.get(2), livingRoomFeatures);
}
@Override
public void getRooms(RoomCallback callback) {
callback.onSuccess(new ArrayList<>(rooms));
}
@Override
public void getFeaturesForRoom(Room room, FeatureCallback callback) {
if (rooms.contains(room)){
callback.onSuccess(features.get(room));
} else{
callback.onError(new HomeControlException(0, "No features for given room."));
}
}
@Override
public void loadData(LoadCallback callback) {
callback.onSuccess();
}
}
<file_sep>package com.paweldylag.homecontrol.presenter;
import com.paweldylag.homecontrol.app.exception.HomeControlException;
import com.paweldylag.homecontrol.app.exception.LoginException;
/**
* @author <NAME> (<EMAIL>)
*/
public interface LoginPresenter {
void attemptLogin(String login, String password);
}
| 563bbacf0fb37f716436997a3ef1f8c1f0c31530 | [
"Markdown",
"Java"
] | 19 | Markdown | pawelDylag/HomeControl | 898d6cb81b27ed28620b0a165acc18039f0b7829 | 56a08772e15e64214abc6a915a3d95c3e01ff004 |
refs/heads/master | <file_sep>/*
Langton's Ant
Here are the rules:
At a white square, turn 90° right, flip the color of the square, move forward one unit
At a black square, turn 90° left, flip the color of the square, move forward one unit
We are going to have the following represent the colors:
W: White
B: Black
AU/AR/AD/AL: Red (Ant) + Direction
And we are going to have each cell be either:
["W", "AD"] if the ant is present or
["W", "N"] if not, where N is a string that doesn't have A in it
*/
// Import all required libraries and headers
// This allows use of libraries, which the libraries can be called to help create the application and not recreate code that is already made
#include "langtons_ant_config.h"
#include <QApplication>
#include <QtWidgets>
#include <QMainWindow>
#include <QPixmap>
#include <QPainter>
#include <QColor>
#include <array>
#include <vector>
#include <string>
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
string direction;
// Initializing window variables
vector<vector<vector<string> > > grid;
int height = 128;
int width = 128;
int depth = 2;
// Conditions for when ant reaches a white or black square
// If statement when ant reaches a colour, simple conditions for changing the color
string invert_color(string color){
if (color == "W"){
return "B";
}else{
return "W";
}
}
// Function for ant turning right
// Function provides a number of conditions when string "direction" reaches a condition
// Function is written as is because ant needs conditions stated at top in order to turn
// When ant reaches white square, the ant checks the direction it is facing, turns 90° right and returns a string its "new direction"
char turn_right(string direction){
if (direction == "U"){
return 'R';
}else if(direction == "R"){
return 'D';
}else if(direction == "D"){
return 'L';
}else{
return 'U';
}
}
// Function for ant turning left
// Function provides a number of conditions when string "direction" reaches a condition
// Function is written as is because ant needs conditions stated at top in order to turn
// When ant reaches black square, the ant checks the direction it is facing, turns 90° left and returns a string its "new direction"
char turn_left(string direction){
if (direction == "U"){
return 'L';
}else if(direction == "R"){
return 'U';
}else if(direction == "D"){
return 'R';
}else{
return 'D';
}
}
// Function which allows the ant to move forward
// The ant's position is tracked on a 2D board consisting of x and y coordinates which are created by a multidimensional array, the function needs to iterate through the array and check conditions for the ant to move
// The function starts with iterations through the x dimension of the matrix and y dimension of matrix, then checks if "A" is not the greatest value
// Afterso, the function will check conditionals and move accordingly to the ant's rules of movement, where the code will set a previous position of the matrix as the new position
// After which it will return the new matrix with the update position
vector<vector<vector<string>>> move_ant_forward(vector<vector<vector<string>>> matrix){
for(int x=0;x<matrix.size();x++){
for(int y=0;y<matrix[x].size();y++){
if (matrix[x][y][1].find("A") != string::npos){
//Get ant's direction
direction = matrix[x][y][1].back();
if (direction == "U"){
matrix[x-1][y][1] = matrix[x][y][1];
}else if(direction == "R"){
matrix[x][y+1][1] = matrix[x][y][1];
}else if(direction == "D"){
matrix[x+1][y][1] = matrix[x][y][1];
}else{
matrix[x][y-1][1] = matrix[x][y][1];
}
matrix[x][y][1] = "";
return matrix;
}
}
}
}
// This function gets the current ant position and turns the ant
// The function like the move_ant_forward function needs to iterate through the array and check the conditions in which the ant will turn
// This function uses the matrix array to track the ants position, it will find the ants position , then checks if "A" is not the greatest value
// Afterso, the function will check conditionals and turn accordingly to the ant's rules of turning, whether it will turn left or right
// After that, the code will invert the color of the square and then call the move_ant_forward function to move the ant forward after its turn
// In which the it will return the new matrix with an updated position
vector<vector<vector<string>>> update_pixmap(vector<vector<vector<string>>> matrix){
//Get current ant pos
for(int x=0;x<matrix.size();x++){
for(int y=0;y<matrix[x].size();y++){
if (matrix[x][y][1].find("A") != string::npos){
//Get ant's direction
direction = matrix[x][y][1].back();
if (matrix[x][y][0] == "W"){
matrix[x][y][1].back() = turn_right(direction);
}else{
matrix[x][y][1].back() = turn_left(direction);
}
matrix[x][y][0] = invert_color(matrix[x][y][0]);
matrix = move_ant_forward(matrix);
return matrix;
}
}
}
}
// The main function where all the interface setup happens in order to display Langton's Ant
int main(int argc, char **argv){
QApplication app (argc, argv);
//Set up sizes. (heightxwidth)
grid.resize(height);
for (int i = 0; i < height; ++i) {
grid[i].resize(width);
for (int j = 0; j < width; ++j){
grid[i][j].resize(depth);
}
}
//Fill with white cells
for (int x=0;x<grid.size();x++){
for (int y=0;y<grid[x].size();y++){
grid[x][y][0] = "W";
grid[x][y][1] = "W";
}
}
grid[128/2][128/2][1] = "AL";//Initial placement of ant
// These objects are creating instances from the libraries, all of these are graphic related instances
// These include the windows, its labels, and the pixels they will use
// Libraries and these instances are used because the library is available for usage, coding these from scratch would be redundant and extremely inefficient
QMainWindow *window = new QMainWindow;
QWidget *widget = new QWidget;
QHBoxLayout *layout = new QHBoxLayout(widget);
QLabel *label = new QLabel();
QFont *font = new QFont("Courier");
QPixmap *pix = new QPixmap(500,500);
// Create painter object and fill the whole map white
// A rule with Langton's ant is that the ant's starting map must be blank, henceforth these are created to make the map white (blank)
pix->fill(Qt::white);
QPainter *painter = new QPainter(pix);
window->setWindowTitle("Langton's Ant");
window->resize(500,500);
window->setCentralWidget(widget);
layout->addWidget(label);
window->show();
// Reiterations through the grid in order to color the grid when there is a possible change in the grid because of the ant movement
// Conditionals are set, these check if the grid is white or black, in which the brush will change to the opposite color to color the grid when the ant moves
while (true){
for(int x=0;x<grid.size();x++){
for(int y=0;y<grid[x].size();y++){
//draw square of appropriate color
if (grid[x][y][1].find("A") != string::npos){
painter->setBrush(QColor(255,0,0,255));
}else if (grid[x][y][0] == "W"){
painter->setBrush(QColor(255,255,255,255));
}else if(grid[x][y][0] == "B"){
painter->setBrush(QColor(0,0,0,255));
}
painter->drawRect(y*4,x*4,4,4);
}
}
label->setPixmap(*pix);
qApp->processEvents();
grid = update_pixmap(grid);
//this_thread::sleep_for(chrono::seconds(1));
}
}
| d858b2824ba0ba490269742eba48df07314194f8 | [
"C++"
] | 1 | C++ | TrongPTran/3I03-Code-Doc-Assignment | 3707cb7ab04f2541ea99fac14d112847a7b320ad | 6d2a2e40e7946ff2403fc9ff7d9630bfb01d33a3 |
refs/heads/main | <repo_name>yuyuyu-bot/thread_pool<file_sep>/utilities/stop_watch.hpp
#ifndef __STOP_WATCH_HPP__
#define __STOP_WATCH_HPP__
#include <chrono>
#include <stack>
namespace time_unit {
using milliseconds = std::chrono::milliseconds;
using microseconds = std::chrono::microseconds;
}
template <typename DurationUnit = time_unit::microseconds>
class stop_watch {
public:
using milliseconds = std::chrono::milliseconds;
using microseconds = std::chrono::microseconds;
using time_point = std::chrono::high_resolution_clock::time_point;
void tick() {
time_points_.push(get());
}
std::uint64_t tock() {
const auto finish = get();
const auto start = time_points_.top();
time_points_.pop();
return duration_cast(start, finish);
}
private:
time_point get() {
return std::chrono::high_resolution_clock::now();
}
auto duration_cast(const time_point& start, const time_point& finish) {
return std::chrono::duration_cast<DurationUnit>(finish - start).count();
}
std::stack<time_point> time_points_;
};
#endif // !__STOP_WATCH_HPP__<file_sep>/core/thread_pool.hpp
#ifndef __THREAD_POOL_HPP__
#define __THREAD_POOL_HPP__
#include <cstdint>
#include <functional>
#include <atomic>
#include <cassert>
#include "locked_queue.hpp"
template <class OutputType>
class thread_pool {
public:
thread_pool(int thread_count, std::size_t queue_capacity, bool need_output = true)
: is_termination_requested_(false)
, task_queue_(queue_capacity)
, output_queue_(queue_capacity)
, need_output_(need_output){
for (int i = 0; i < thread_count; i++) {
threads_.emplace_back(std::thread(main_));
}
}
~thread_pool() {
is_termination_requested_.store(true);
condition_.notify_all();
for (auto& thread : threads_) {
thread.join();
}
}
bool add(const std::function<OutputType()>& func) {
task_queue_.enqueue(func);
condition_.notify_all();
return true;
}
bool add(std::function<OutputType()>&& func) {
task_queue_.enqueue(std::move(func));
condition_.notify_all();
return true;
}
bool try_pull(OutputType& ret) {
assert(need_output_);
return output_queue_.try_dequeue(ret);
}
OutputType pull() {
assert(need_output_);
OutputType ret;
output_queue_.dequeue(ret);
return ret;
}
private:
std::function<void()> main_ = [this]() {
while (true) {
std::function<OutputType()> func;
{
std::unique_lock<std::mutex> lock(mutex_);
while (task_queue_.empty()) {
if (is_termination_requested_.load()) {
return;
}
condition_.wait(lock, [&]() { return !task_queue_.empty() || is_termination_requested_.load(); });
}
const auto dequeue_result = task_queue_.dequeue(func);
assert(dequeue_result);
}
if (need_output_) output_queue_.enqueue(func());
else func();
}
};
bool need_output_;
std::atomic<bool> is_termination_requested_;
locked_queue<std::function<OutputType()>> task_queue_;
locked_queue<OutputType> output_queue_;
std::mutex mutex_;
std::condition_variable condition_;
std::vector<std::thread> threads_;
};
#endif // !__THREAD_POOL_HPP__<file_sep>/test/main.cpp
#include "test_class.hpp"
int main(int argc, char** argv)
{
test_class test;
int counter = 0;
while (std::getchar()) {
test.execute();
counter++;
std::cout << counter << std::endl;
}
return 0;
}<file_sep>/core/locked_queue.hpp
#ifndef __LOCKED_QUEUE_HPP__
#define __LOCKED_QUEUE_HPP__
#include <cstdint>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <atomic>
template <class T, class UnderlyingContainer = std::deque<T>>
class locked_queue {
public:
typedef T value_type;
typedef std::queue<T, UnderlyingContainer> container;
locked_queue() : capacity_(std::numeric_limits<std::size_t>::max()) {}
locked_queue(std::size_t capacity) : capacity_(capacity) {}
void enqueue(T val) {
std::unique_lock<std::mutex> lock(mutex_);
condition_enqueue.wait(lock, [&] { return queue_.size() < capacity_; });
queue_.push(std::move(val));
condition_dequeue.notify_one();
}
bool try_dequeue(T& ret) {
std::unique_lock<std::mutex> lock(mutex_);
if (!queue_.empty()) {
ret = std::move(queue_.front());
queue_.pop();
condition_enqueue.notify_one();
return true;
}
else {
return false;
}
}
bool dequeue(T& ret) {
std::unique_lock<std::mutex> lock(mutex_);
condition_dequeue.wait(lock, [this] { return !queue_.empty(); });
ret = std::move(queue_.front());
queue_.pop();
condition_enqueue.notify_one();
return true;
}
bool empty() {
std::unique_lock<std::mutex> lock(mutex_);
const auto ret = queue_.empty();
return ret;
}
private:
std::size_t capacity_;
container queue_;
std::mutex mutex_;
std::condition_variable condition_enqueue;
std::condition_variable condition_dequeue;
};
#endif // !__LOCKED_QUEUE_HPP__<file_sep>/test/test_class.hpp
#ifndef __TEST_CLASS_HPP__
#define __TEST_CLASS_HPP__
#include <iostream>
#include "../core/thread_pool.hpp"
#include "../utilities/stop_watch.hpp"
#define CALL_NOTICE() (std::cout << __FUNCTION__ << " called at thread " << std::this_thread::get_id() << std::endl)
class test_class {
public:
test_class() : producer(1, 10, true), consumer(2, 10, false) {
}
void execute() {
CALL_NOTICE();
producer.add(std::bind(&test_class::runner, this));
consumer.add(std::bind(&test_class::getter, this));
}
int runner() {
return test_func(1, 2, 100);
}
int getter() {
auto out = producer.pull();
std::printf("out = %d\n", out);
return 0;
}
private:
int test_func(int a, int b, int sleep_time) {
std::this_thread::sleep_for(std::chrono::milliseconds(sleep_time));
return a + b;
}
thread_pool<int> producer;
thread_pool<int> consumer;
};
#endif // !__TEST_CLASS_HPP__ | a6d9d2826b873151aa7d6d7d18f0cb5321108ecd | [
"C++"
] | 5 | C++ | yuyuyu-bot/thread_pool | 7dce92c949a0d4d742bcfde75adbcc37c0d34d47 | a76b2e92c7fe3376149c7d4ff9b57c0f3b9e656b |
refs/heads/main | <file_sep># Babel Setup for Es6
View Sample Project https://babel-sample.herokuapp.com<file_sep>const app = require('express')();
app.get('/', (req, res) => {
res.send('Hi');
})
const PORT = process.env.PORT || 4000;
app.listen(PORT); | 0a0121e185dd1a0d4d1d0d64a0bb16ff22990764 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | littlepotato123/Babel-Setup | 8f053de89ffb202d5d5eb030837a5d875d85e3a1 | 2b78902a74898d43b94e1073317bce4607fe313d |
refs/heads/master | <file_sep>require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'sqlite3'
def init_db
@db = SQLite3::Database.new 'leprosorium.db'
@db.results_as_hash = true
end
before do
init_db
end
configure do
init_db
@db.execute 'create table if not exists posts
(id integer primary key autoincrement,
created_date date,
content text)'
@db.execute 'create table if not exists comments
(id integer primary key autoincrement,
created_date date,
content text,
post_id integer)'
end
get '/' do
@results = @db.execute 'select * from posts order by id desc'
erb :index
end
get '/newpost' do
erb :newpost
end
post '/newpost' do
@content = params[:content]
if @content.length <= 0
@error = 'Type some text'
erb :newpost
else @db.execute 'insert into posts (content, created_date) values(?,datetime())',[@content]
redirect to '/'
end
end
get '/details/:post_id' do
post_id = params[:post_id]
result = @db.execute 'select * from posts where id = ?',[post_id]
@row = result[0]
@comments = @db.execute 'select * from comments where post_id = ? order by id', [post_id]
erb :details
end
post '/details/:post_id' do
post_id = params[:post_id]
content = params[:content]
if content.length < 1
result = @db.execute 'select * from posts where id = ?',[post_id]
@row = result[0]
@comments = @db.execute 'select * from comments where post_id = ? order by id', [post_id]
@error = 'Type some text'
erb :details
else @db.execute 'insert into comments
(
content,
created_date,
post_id
)
values
(
?,
datetime(),
?
)',[content , post_id]
redirect to ('/details/'+ post_id)
end
end | c17b9741766d1fa71e797045b8e1310930a7bc4e | [
"Ruby"
] | 1 | Ruby | windmaiden/leprosorium | 014e0e58b3f553b6282a4459be92e0bf0668b9ca | 5f03ec614febd1128c9b73c175f52321e24b3b85 |
refs/heads/master | <repo_name>mvdvnk/itmo-design-2021-mat-cal<file_sep>/src/src/Gauss.java
package src;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.io.File;
import java.io.FileNotFoundException;
public class Gauss {
public double[][] matrixData;
private double precision;
private int n;
public void init(String filename) throws FileNotFoundException {
int countOfNumbersAfterZero;
double[][] matrix;
File file = new File(filename); //файл
try (Scanner scan = new Scanner(file)) { //сканнер
n = scan.nextInt();
countOfNumbersAfterZero = scan.nextInt();
precision = Math.pow(10, -(countOfNumbersAfterZero + 1)); //лучше с файла
matrixData = new double[n][];
for (int i = 0; i < n; i++) { //читаем матрицу
matrixData[i] = new double[n + 1];
for (int j = 0; j < n + 1; j++) {
matrixData[i][j] = scan.nextDouble();
}
}
}
}
public double[] backtrace() { // обратная подстановка
//matrixData.length - количество строчек. У нас ещё есть дополнительный столбец
//под номером как раз matrixData.length - столбец свободного члена
double[] answerData = new double[matrixData.length];
for (int k = answerData.length - 1; k >= 0; k--) {
for (int j = k + 1; j < answerData.length; j++) // все найд. ответы умножаем на соответствующие
// коэффициенты в текущем уравнении и вычитаем из b
matrixData[k][matrixData.length] -= answerData[j] * matrixData[k][j];
answerData[k] = matrixData[k][matrixData.length] / matrixData[k][k];
}
return answerData;
}
protected int checkZeroSolutions() {
int len = matrixData.length;
if (isZero(matrixData[len - 1][len - 1]) && !isZero(matrixData[len - 1][len]))//строка с которой работаю и с какими отрабатываю
return 2;
return 0;
}
// 1 2 3 3 |1
// 1 5 4 5 |2
// 1 0 0 5 |3
// 0 0 0 0 |0 <- проверка последних двух нулей
private int checkInftySolutions() {
int len = matrixData.length;
if (isZero(matrixData[len - 1][len - 1]) && isZero(matrixData[len - 1][len]))
return 3; // infty solutions
return 0;
}
public int triangularForm() { // приведение к треугольному виду
for (int i = 0; i < matrixData.length; i++) { // первый цикл
// zerocoeff - второй цикл
if (!zeroCoeff(i)) { // если функция вернула true, то найден ненулевой, идем дальше. Иначе приведение
// невозможно
return 1;
}
eliminateDiagonal(i); // исключаем диаг. коэфф,
}
return 0;
}
private void eliminateDiagonal(int diagonalIndex) { // зануляем весь столбец под ненулевым элементом.
for (int k = diagonalIndex + 1; k < matrixData.length; k++) { // Исключаем коэффициент в k-м уравнении, начиная
// со следующего
coeffCount(matrixData, diagonalIndex, k);
matrixData[k][diagonalIndex] = 0;
}
}
private void coeffCount(double matrixData[][], int diagonalIndex, int k) {
double m = matrixData[k][diagonalIndex] / matrixData[diagonalIndex][diagonalIndex];
for (int j = diagonalIndex + 1; j < matrixData.length; j++) {
matrixData[k][j] -= matrixData[diagonalIndex][j] * m;
}
}
private boolean zeroCoeff(int diagonalIndex) { // ищем первую строчку, в которой коэфф. не равен 0, меняем местами,
// увеличиваем кол-во перестановок (a11 !=0)
for (int numberToSwap = diagonalIndex; numberToSwap < matrixData.length; numberToSwap++) {
if (!isZero(matrixData[numberToSwap][diagonalIndex])) { //!! не сравн. с 0 (точность - из файла/константа)
swapEquations(numberToSwap, diagonalIndex);
return true;
}
// System.out.println(matrixData[equationNumberToSwap][indexOfDiagonalCoef]);
}
return false; // столбец нулей, приведение невозможно
}
private void swapEquations(int numberToSwap, int diagonalIndex) { // меняем местами уравнения
double[] temp = matrixData[numberToSwap];
matrixData[numberToSwap] = matrixData[diagonalIndex];
matrixData[diagonalIndex] = temp;
}
public boolean isZero(double value) { //сравнение с
return Math.abs(value) <= this.precision;
}
public double[][] getMatrixData() {
return matrixData;
}
public int getN() {
return n;
}
public int solve() {
int result = 0;
if (triangularForm() == 1) // матрица вырождена
result = 1;
else
if(checkZeroSolutions() == 2)
result = 2;
else if(checkInftySolutions() == 3)
result = 3;
return result;
}
} | 24522b5f3f434dac5d0b674d4dfffc097b3311eb | [
"Java"
] | 1 | Java | mvdvnk/itmo-design-2021-mat-cal | 0e1da0008e71b2761c6959c1450222934abbbda6 | 947323d29fe3848cdb3ab00af60dd5673371cf0f |
refs/heads/master | <repo_name>ValeriyWorld/calculator<file_sep>/calculator.py
from tkinter import *
from tkinter import messagebox as mb
def onclick_input(number):
length = len(entry.get())
entry.insert(length, number)
def onclick_symbol(symbol):
if entry.get() and entry.get()[-1] not in '+-*/':
onclick_input(symbol)
def equal(*args):
expression = entry.get()
key_tracker = True
if expression:
for i in expression:
if i not in '0123456789+-*/.':
key_tracker = False
break
if key_tracker:
if expression[-1] in '+-*/.':
mb.showerror('Error', 'An expression can\'t end with symbol!')
else:
try:
answer = eval(expression)
entry.delete(0, END)
entry.insert(0, answer)
except SyntaxError:
mb.showerror('Error', 'Syntax error!')
except ZeroDivisionError:
mb.showerror('Error', 'Zero division is not allowed!')
else:
mb.showerror('Error', 'You typed unallowed symbols!')
def clear_all():
entry.delete(0, END)
def backspace():
length = len(entry.get())
entry.delete(length-1)
root = Tk()
root.title('Calculator')
root.resizable(False, False)
entry = Entry(root, width=34, bd=2, font='24')
entry.grid(row=0, column=0, columnspan=5, padx=5, pady=10)
button0 = Button(
root, text="0", width=13, height=3, font='24',
command = lambda: onclick_input(0)
)
button1 = Button(
root, text="1", width=6, height=3, font='24',
command = lambda: onclick_input(1)
)
button2 = Button(
root, text="2", width=6, height=3, font='24',
command = lambda: onclick_input(2)
)
button3 = Button(
root, text="3", width=6, height=3, font='24',
command = lambda: onclick_input(3)
)
button4 = Button(
root, text="4", width=6, height=3, font='24',
command = lambda: onclick_input(4)
)
button5 = Button(
root, text="5", width=6, height=3, font='24',
command = lambda: onclick_input(5)
)
button6 = Button(
root, text="6", width=6, height=3, font='24',
command = lambda: onclick_input(6)
)
button7 = Button(
root, text="7", width=6, height=3, font='24',
command = lambda: onclick_input(7)
)
button8 = Button(
root, text="8", width=6, height=3, font='24',
command = lambda: onclick_input(8)
)
button9 = Button(
root, text="9", width=6, height=3, font='24',
command = lambda: onclick_input(9)
)
button_eq = Button(
root, text="=", width=6, height=3, font='24',
bg='#49a2e6', fg='#fff',
activebackground='#49a2e6', activeforeground='#fff',
command = equal
)
button_clear = Button(
root, text="C", width=6, height=3, font='24',
bg='#f05959', fg='#fff',
activebackground='#f05959', activeforeground='#fff',
command = clear_all
)
button_backspace = Button(
root, text="<=", width=6, height=3, font='24',
bg='#f05959', fg='#fff',
activebackground='#f05959', activeforeground='#fff',
command = backspace
)
button_plus = Button(
root, text="+", width=6, height=3, font='24',
bg='#828385', fg='#fff',
activebackground='#828385', activeforeground='#fff',
command = lambda: onclick_symbol('+')
)
button_minus = Button(
root, text="-", width=6, height=3, font='24',
bg='#828385', fg='#fff',
activebackground='#828385', activeforeground='#fff',
command = lambda: onclick_symbol('-')
)
button_multiply = Button(
root, text="x", width=6, height=3, font='24',
bg='#828385', fg='#fff',
activebackground='#828385', activeforeground='#fff',
command = lambda: onclick_symbol('*')
)
button_divide = Button(
root, text="/", width=6, height=3, font='24',
bg='#828385', fg='#fff',
activebackground='#828385', activeforeground='#fff',
command = lambda: onclick_symbol('/')
)
button_empt = Button(
root, text='', width=13, height=3, font='24',
bg='#828385', fg='#fff',
activebackground='#828385', activeforeground='#fff',
state=DISABLED
)
button0.grid(row=4, column=0, columnspan=2)
button1.grid(row=3, column=0)
button2.grid(row=3, column=1)
button3.grid(row=3, column=2)
button4.grid(row=2, column=0)
button5.grid(row=2, column=1)
button6.grid(row=2, column=2)
button7.grid(row=1, column=0)
button8.grid(row=1, column=1)
button9.grid(row=1, column=2)
button_backspace.grid(row=1, column=3)
button_clear.grid(row=1, column=4)
button_plus.grid(row=2, column=3)
button_minus.grid(row=2, column=4)
button_multiply.grid(row=3, column=3)
button_divide.grid(row=3, column=4)
button_eq.grid(row=4, column=2)
button_empt.grid(row=4, column=3, columnspan=2)
root.bind('<Return>', equal)
root.mainloop()
<file_sep>/README.md
# calculator
just a simple calculator with Python + Tkinter
| 759cc0eea7d98c4a3e043f30bb41266ad35c3107 | [
"Markdown",
"Python"
] | 2 | Python | ValeriyWorld/calculator | e9b2457122719023e361ed657908d3e779f73d9c | 592ffa94255ebb972f524ed476f47764d61c69cc |
refs/heads/main | <repo_name>ManhattanDoctor/ts-core-two-fa-totp<file_sep>/README.md
# ts-core-tw-fa-totp
Classes for TOTP 2FA
<file_sep>/src/TotpProvider.ts
import { ITwoFaProvider, ITwoFaValidateDetails } from '@ts-core/two-fa-backend/provider';
import { ILogger, LoggerWrapper } from '@ts-core/common/logger';
import { TwoFaOwnerUid } from '@ts-core/two-fa';
import * as speakeasy from 'speakeasy';
import * as _ from 'lodash';
export class TotpProvider extends LoggerWrapper implements ITwoFaProvider<ITotpCreateDetails> {
// --------------------------------------------------------------------------
//
// Constructor
//
// --------------------------------------------------------------------------
constructor(logger: ILogger, protected options: ITotpOptions) {
super(logger);
}
// --------------------------------------------------------------------------
//
// Public Methods
//
// --------------------------------------------------------------------------
public async create(ownerUid: TwoFaOwnerUid): Promise<ITotpCreateDetails> {
let secret = speakeasy.generateSecret({ name: this.options.name, length: this.options.length }).base32;
return { secret };
}
public async validate(token: string, details: ITotpCreateDetails): Promise<ITwoFaValidateDetails> {
if (_.isEmpty(token)) {
return { isValid: false };
}
token = token.replace(/[^0-9]/gi, '');
let delta = speakeasy.totp.verifyDelta({ token, secret: details.secret, window: this.options.window, encoding: 'base32' });
return { isValid: !_.isNil(delta) };
}
// --------------------------------------------------------------------------
//
// Public Properties
//
// --------------------------------------------------------------------------
public get type(): string {
return 'totp';
}
}
export interface ITotpOptions {
name: string;
length: number;
window: number;
}
export interface ITotpCreateDetails {
secret: string;
}
<file_sep>/src/index.ts
export * from './TotpProvider';
| a8a9094b04ce2d2efe48184e5375f68c7fd21094 | [
"Markdown",
"TypeScript"
] | 3 | Markdown | ManhattanDoctor/ts-core-two-fa-totp | 229047ffacb5fb661e467263f7e0830a6e54ad77 | 474a862b4e925b68fd1de9badceb29f291ce003a |
refs/heads/master | <file_sep># BibleSearch
An efficient algorithm for searching Bible text.
In `legacy/`, there is an older Python-based legacy version.
It was designed for server usage and is fairly slow due to
being written in Python.
<file_sep>t ?= web
dir ?= ../
default:
$(CC) -I$(dir) $(dir)/biblec/biblec.c bsearch.c test.c -o test.out
./test.out
rm -rf *.out
# make setup f=kjv
setup:
-cd biblec; mkdir bibles
cd biblec/bibles; wget http://api.heb12.com/translations/biblec/$(t).i
cd biblec/bibles; wget http://api.heb12.com/translations/biblec/$(t).t
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <biblec/biblec.h>
#include "bsearch.h"
struct BiblecTranslation translation;
int main() {
int tryFile = biblec_parse(
&translation,
"/home/daniel/.local/share/heb12/web.i"
);
if (tryFile) {
return -1;
}
clock_t start = clock();
char mySearch[][BSEARCH_MAX_WORD] = {
"for",
"god",
"loved",
"world",
};
int *hits = malloc(BSEARCH_MAX_HITS * sizeof(int));
int c = bsearch_open(mySearch,
sizeof(mySearch) / sizeof(mySearch[0]), hits, &translation);
if (c == -1) {
puts("Err");
return 1;
}
char buffer[1024];
for (int i = 0; i < c; i++) {
bsearch_getVerse(buffer, hits[i], &translation);
printf("%d\t%s\n", hits[i], buffer);
}
free(hits);
double elapsed = (double)(clock() - start) / CLOCKS_PER_SEC;
printf("Done in %f seconds.\n", elapsed);
return 0;
}
<file_sep>// TODO:
// error system
// bsearch? biblesearch?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <biblec/biblec.h>
#include "bsearch.h"
// Get verse from line number in BibleC file
int bsearch_getVerse(char buffer[], int line, struct BiblecTranslation *translation) {
int result = 0;
// Locate book
int book = 0;
while (translation->books[book].start <= line) {
book++;
// Assume overflow means last book
if (book > MAX_BOOKS - 1) {
break;
}
}
book--;
result = translation->books[book].start;
// Get right under last chapter
int chapter = 0;
while (result <= line) {
if (chapter > translation->books[book].length) {
return -2;
}
result += translation->books[book].chapters[chapter];
chapter++;
}
result -= translation->books[book].chapters[chapter - 1];
line -= result;
// (verses start at zero)
//line++;
// TODO: return as a structure instead of a
// possible useless string
sprintf(buffer, "%s %d %d", translation->books[book].name, chapter, line);
return 0;
}
int getHits(int hits[], char string[], struct BiblecTranslation *translation) {
int hit = 0;
int line = 0;
FILE *verseFile = fopen(translation->location, "r");
if (verseFile == NULL) {
free(hits);
return -1;
}
char word[BSEARCH_MAX_WORD];
char buffer[VERSE_LENGTH];
while (fgets(buffer, VERSE_LENGTH, verseFile) != NULL) {
int wc = 0;
for (int c = 0; buffer[c] != '\0'; c++) {
// Make sure this is an alphabetical character
if (buffer[c] >= 'a' && buffer[c] <= 'z') {
word[wc] = buffer[c];
wc++;
} else if (buffer[c] >= 'A' && buffer[c] <= 'Z') {
// Make character lowercase
word[wc] = buffer[c] + ('a' - 'A');
wc++;
} else if (buffer[c] == ' ' || buffer[c] == '\n') {
// Quit if no useful data was read
if (wc <= BSEARCH_MIN_WORD) {
word[wc] = '\0';
wc = 0;
continue;
}
// Reset once we encounter new line
word[wc] = '\0';
wc = 0;
// Check current search word after parsing
// current word from file
if (!strcmp(string, word)) {
hits[hit] = line;
hit++;
if (hit > BSEARCH_MAX_HITS) {
free(hits);
fclose(verseFile);
return -1;
}
// Break loop since new
// matches are unecessary
break;
}
}
}
line++;
}
fclose(verseFile);
return hit;
}
int bsearch_open(char mySearch[][BSEARCH_MAX_WORD], int length,
int hits[BSEARCH_MAX_HITS], struct BiblecTranslation *translation) {
int hiti = 0;
char buffer[6000];
char word[64];
int line = 0;
FILE *verseFile = fopen(translation->location, "r");
if (verseFile == NULL) {
return -1;
}
while (fgets(buffer, VERSE_LENGTH, verseFile) != NULL) {
int match[1024] = {0};
int wc = 0;
int wordi = 0;
for (int c = 0; buffer[c] != '\0'; c++) {
// Make sure this is an alphabetical character
if (buffer[c] >= 'a' && buffer[c] <= 'z') {
word[wc] = buffer[c];
wc++;
} else if (buffer[c] >= 'A' && buffer[c] <= 'Z') {
// Make character lowercase
word[wc] = buffer[c] + ('a' - 'A');
wc++;
} else if (buffer[c] == ' ' || buffer[c] == '\n') {
// Quit if no useful data was read
if (wc <= BSEARCH_MIN_WORD) {
word[wc] = '\0';
wc = 0;
continue;
}
// Reset once we encounter new line
word[wc] = '\0';
wc = 0;
for (int i = 0; i < length; i++) {
if (!strcmp(mySearch[i], word)) {
match[i]++;
break;
}
}
wordi++;
}
}
line++;
int fullMatch = 1;
for (int i = 0; i < length; i++) {
if (!match[i]) {
fullMatch = 0;
}
}
if (fullMatch) {
hits[hiti] = line;
hiti++;
}
}
fclose(verseFile);
return hiti;
}
<file_sep>#ifndef BIBLESEARCH_H
#define BIBLESEARCH_H
#define BSEARCH_MAX_HITS 100000
#define BSEARCH_MAX_WORD 128
#define BSEARCH_MIN_WORD 2
int bsearch_getVerse(char buffer[], int line,
struct BiblecTranslation *translation);
int bsearch_open(char mySearch[][BSEARCH_MAX_WORD], int length,
int hits[BSEARCH_MAX_HITS], struct BiblecTranslation *translation);
#endif
| f6dbe8ab5834a1cfb43d572f2c62fe1de7a5d474 | [
"Markdown",
"C",
"Makefile"
] | 5 | Markdown | heb12/biblesearch | 4fe38ae545a15be6673e9821f550817b1e988a68 | dcc5182a7339533b8681bd397f9abbbd9adc8919 |
refs/heads/master | <repo_name>BoiseCodeWorks/fall20-apod-fireside<file_sep>/app/Controllers/ApodController.js
import apodService from "../Services/ApodService.js"
import { ProxyState } from "../AppState.js";
function _drawApod() {
let apod = ProxyState.apod
console.log(apod)
if (apod.includes("youtube")) {
document.getElementById("apod-vid").innerHTML = `<div class="col-12 text-center"><iframe src="${apod}" width="500" height="500"></iframe></div> `
document.getElementById("bg-img").style.backgroundImage = ``
} else {
document.getElementById("bg-img").style.backgroundImage = `url(${apod})`
document.getElementById("apod-vid").innerHTML = ``
}
}
export default class ApodController {
constructor() {
this.getApod()
ProxyState.on("apod", _drawApod)
}
getApod() {
try {
apodService.getApod()
} catch (error) {
console.error(error);
}
}
search(event) {
try {
event.preventDefault();
let form = event.target
let date = form.date.value
apodService.search(date)
form.reset()
} catch (error) {
console.error(error);
}
}
}<file_sep>/app/Services/ApodService.js
import { api } from "./AxiosService.js"
import { ProxyState } from "../AppState.js";
class ApodService {
constructor() {
}
async getApod() {
let res = await api.get("apod?api_key=<KEY>")
ProxyState.apod = res.data.url
}
async search(date) {
let res = await api.get("apod?api_key=<KEY>&date=" + date)
// console.log(res)
ProxyState.apod = res.data.url
}
}
const APODSERVICE = new ApodService()
export default APODSERVICE<file_sep>/app/Services/AxiosService.js
// @ts-ignore
export const api = axios.create({
baseURL: "https://api.nasa.gov/planetary",
timeout: 3000
}) | 038a34eddadd0dc7a695c2a3b2187f8b350795e0 | [
"JavaScript"
] | 3 | JavaScript | BoiseCodeWorks/fall20-apod-fireside | d52ac020d49eceb38def153bc97b50030ed0beb0 | 017ae047c921435e98ca113ca007e3518f9ce567 |
refs/heads/master | <repo_name>mohammadEslamiyeh/reza_sadeghi_text<file_sep>/app/src/main/java/com/elevenprin/www/rezasadeghinew/Favorites_sh.java
package com.elevenprin.www.rezasadeghinew;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by NP on 4/29/2016.
*/
public class Favorites_sh extends AppCompatActivity {
public static SharedPreferences shared_fav;
public static SharedPreferences.Editor editor_fav;
public ImageView iv_favorites;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.three_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.show1_toolbar);
setSupportActionBar(toolbar);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.show1_fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
shared_fav = getSharedPreferences("Favorites", MODE_PRIVATE);
editor_fav = shared_fav.edit();
Bundle extras = getIntent().getExtras();
if (extras != null) {
final String fave = extras.getString("key_number");
Boolean b2 = shared_fav.getBoolean(fave, false);
if (b2) {
editor_fav.putBoolean(fave, false);
editor_fav.apply();
fab.setImageResource(R.drawable.favorite_not_selected);
// show message
String message = getResources().getString(R.string.favorites_removed);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
editor_fav.putBoolean(fave, true);
editor_fav.apply();
fab.setImageResource(R.drawable.favorite_selected);
// show message
String message = getResources().getString(R.string.favorites_added);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
}
});
///////////////////////////////////////////////////////////////////////////////////////
Bundle extras = getIntent().getExtras();
if (extras != null) {
final String fave = extras.getString("key_number");
int resId = getResources().getIdentifier(fave, "string", getPackageName());
String song = getResources().getString(resId);
TextView tv = (TextView) findViewById(R.id.show_textview);
tv.setText(song);
shared_fav = getSharedPreferences("Favorites", MODE_PRIVATE);
editor_fav = shared_fav.edit();
///////////////////////////////////////////////text size
int size =shared_fav.getInt("size",10);
tv.setTextSize(size);
boolean chbt = shared_fav.getBoolean("chk", true);
if (chbt)
getWindow()
.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// safhe
//////////////////////////////////////////////////////////////
final Boolean b1 = shared_fav.getBoolean(fave, false);
if (b1) {
fab.setImageResource(R.drawable.favorite_selected);
} else {
fab.setImageResource(R.drawable.favorite_not_selected);
}
//iv_favorites = (ImageView) findViewById(R.id.imageView1);
//final int subject_number_int = Integer.parseInt(this_subject);
//*
//final String this_subject_2 = "album_2_" + String.valueOf(my_key_number);
/* iv_favorites.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
*/
}
}
}
<file_sep>/app/src/main/java/com/elevenprin/www/rezasadeghinew/Album_17_show.java
package com.elevenprin.www.rezasadeghinew;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by NP on 4/7/2016.
*/
public class Album_17_show extends AppCompatActivity {
public static SharedPreferences shared_3;
public SharedPreferences.Editor editor_3;
Globals0 global = new Globals0();
public ImageView iv_favorites_3;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.three_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.show1_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.show1_fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
shared_3 = getSharedPreferences("Favorites", MODE_PRIVATE);
editor_3 = shared_3.edit();
Bundle extras = getIntent().getExtras();
if (extras != null) {
final String my_key_number = extras.getString("key_number");
final String this_subject_3 = "album_17_" + my_key_number;
Boolean b2 = shared_3.getBoolean(this_subject_3, false);
if (b2) {
editor_3.putBoolean(this_subject_3, false);
editor_3.apply();
fab.setImageResource(R.drawable.favorite_not_selected);
// show message
String message = getResources().getString(R.string.favorites_removed);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
editor_3.putBoolean(this_subject_3, true);
editor_3.apply();
fab.setImageResource(R.drawable.favorite_selected);
// show message
String message = getResources().getString(R.string.favorites_added);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
}
});
///////////////////////////////////////////////////////////////////////////////////////////////////
Bundle extras = getIntent().getExtras();
if (extras != null) {
String my_key_number = extras.getString("key_number");
String this_subject = "album_17_" + my_key_number;
int resId = getResources().getIdentifier(this_subject, "string", getPackageName());
String song = getResources().getString(resId);
TextView tv3 = (TextView) findViewById(R.id.textview11);
Bundle extras2 = getIntent().getExtras();
if(extras2 != null)
{
String list = extras2.getString("list");
int resID_2 = getResources().getIdentifier(list,"string",getPackageName());
String list_song = getResources().getString(resID_2);
tv3.setText(list_song);
}
TextView tv = (TextView) findViewById(R.id.show_textview);
tv.setText(song);
shared_3 = getSharedPreferences("Favorites", MODE_PRIVATE);
editor_3 = shared_3.edit();
///////////////////////////////////////////////text size
int size =shared_3.getInt("size",10);
tv.setTextSize(size);
boolean chbt = shared_3.getBoolean("chk", true);
if (chbt)
getWindow()
.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// safhe
//////////////////////////////////////////////////////////////
final String this_subject_3 = "album_17_" + my_key_number;
final Boolean b1 = shared_3.getBoolean(this_subject, false);
if (b1) {
fab.setImageResource(R.drawable.favorite_selected);
} else {
fab.setImageResource(R.drawable.favorite_not_selected);
}
//
/// ////////////////////////////////////////////////////////////////////////////////////////////
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.meu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemFavorites:
startActivity(new Intent(Album_17_show.this, favorites_show.class));
return true;
default:
return true;
}
}
}
<file_sep>/app/src/main/java/com/elevenprin/www/rezasadeghinew/Album_10.java
package com.elevenprin.www.rezasadeghinew;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
/**
* Created by NP on 4/6/2016.
*/
public class Album_10 extends ListActivity {
public Globals0 global = new Globals0();
private int song_number = global.album_10_song_number;
private String[] Album_10_song = new String[song_number];
private ListView album_10_listview;
//////////////////////////////////////////////////
public static SharedPreferences shared_3;
public SharedPreferences.Editor editor_3;
////////////////////////////////////////////////////////////////
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_10);
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, R.id.textView2, Album_10_song));
for (int x = 1; x <= song_number; x = x + 1) {
String this_subject = "album_10_song_" + String.valueOf(x);
int resID = getResources().getIdentifier(this_subject, "string", getPackageName());
Album_10_song[x - 1] = getResources().getString(resID);
}
album_10_listview = getListView();
album_10_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String p = String.valueOf(position + 1);
Intent a = new Intent(Album_10.this, Album_10_show.class);
a.putExtra("key_number", p);
String c = "album_10_song_" + String.valueOf(position+1);
a.putExtra("list" , c);
startActivity(a);
}
});
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource, int textViewResourceId, String[] strings) {
super(context, resource, textViewResourceId, strings);
}
public View getView(int position, View convetView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, parent, false);
TextView tv = (TextView) row.findViewById(R.id.textView2);
tv.setText(Album_10_song[position]);
///////////////////////////////////////////////text size
shared_3 = getSharedPreferences("Favorites", MODE_PRIVATE);
editor_3 = shared_3.edit();
int size =shared_3.getInt("size",10);
tv.setTextSize(size);
boolean chbt = shared_3.getBoolean("chk", true);
if (chbt)
getWindow()
.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// safhe
//////////////////////////////////////////////////////////////
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_example);
row.startAnimation(animation);
return row;
}
}
}<file_sep>/app/src/main/java/com/elevenprin/www/rezasadeghinew/biogerafi.java
package com.elevenprin.www.rezasadeghinew;
import android.app.Activity;
import android.os.Bundle;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;
/**
* Created by NP on 4/15/2016.
*/
public class biogerafi extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.biogerafi);
TextView tx = (TextView)findViewById(R.id.txtbio);
TranslateAnimation anim1 = new TranslateAnimation(-400, 40, 40, 40);
anim1.setDuration(2500);
tx.startAnimation(anim1);
}
}
<file_sep>/app/src/main/java/com/elevenprin/www/rezasadeghinew/Album_19.java
package com.elevenprin.www.rezasadeghinew;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
/**
* Created by NP on 4/7/2016.
*/
public class Album_19 extends ListActivity{
public Globals0 global = new Globals0();
private int song_number = global.album_19_song_number;
private String[] Album_19_song = new String[song_number];
private ListView album_19_listview;
//////////////////////////////////////////////////
public static SharedPreferences shared_3;
public SharedPreferences.Editor editor_3;
////////////////////////////////////////////////////////////////
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_19);
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, R.id.textView2, Album_19_song));
for(int x = 1 ; x <= song_number ; x = x + 1)
{
String this_subject = "album_19_song_" + String.valueOf(x);
int resID = getResources().getIdentifier(this_subject,"string",getPackageName());
Album_19_song[x-1] = getResources().getString(resID);
}
album_19_listview = getListView();
album_19_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String p = String.valueOf(position + 1);
Intent a = new Intent(Album_19.this, Album_19_show.class);
a.putExtra("key_number", p);
String c = "album_19_song_" + String.valueOf(position+1);
a.putExtra("list" , c);
startActivity(a);
}
});
}
private class MyAdapter extends ArrayAdapter<String>
{
public MyAdapter(Context context , int resource , int textViewResourceId , String[] strings)
{
super(context,resource,textViewResourceId,strings);
}
public View getView(int position , View convetView , ViewGroup parent)
{
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item,parent,false);
TextView tv = (TextView) row.findViewById(R.id.textView2);
tv.setText(Album_19_song[position]);
///////////////////////////////////////////////text size
shared_3 = getSharedPreferences("Favorites", MODE_PRIVATE);
editor_3 = shared_3.edit();
int size =shared_3.getInt("size",10);
tv.setTextSize(size);
boolean chbt = shared_3.getBoolean("chk", true);
if (chbt)
getWindow()
.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// safhe
//////////////////////////////////////////////////////////////
Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_example);
row.startAnimation(animation);
return row;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.meu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.itemFavorites:
startActivity(new Intent(Album_19.this, favorites_show.class));
return true;
default:
return true;
}
}
}
| 567ffb3b7eb2415c183ebc58b5f7205f6359d5fd | [
"Java"
] | 5 | Java | mohammadEslamiyeh/reza_sadeghi_text | 3ff82c943546eb8483b397127b3d3c43ddcc62a9 | bf96cae96d5664704f5ffec7822299a41f7bf09f |
refs/heads/master | <file_sep>using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using WebApiCore30.Models;
using System.Linq;
namespace WebApiCore30.Repository
{
public interface IZaposleniciRepository
{
List<Zaposlenici> GetAll();
void AddNew(Zaposlenici student);
}
public class ZaposleniciRepository : IZaposleniciRepository
{
FIADevOpsContext _db;
public ZaposleniciRepository()
{
var builder = new DbContextOptionsBuilder<FIADevOpsContext>();
//var connectionString = configuration.GetConnectionString("FIADbConnection");
builder.UseSqlServer("server=.;database=FIADevOPS;Integrated Security=True");
//return new DLWMSContext(builder.Options);
_db = new FIADevOpsContext(builder.Options);
}
public void AddNew(Zaposlenici zaposlenik)
{
throw new NotImplementedException();
}
public List<Zaposlenici> GetAll()
{
return _db.Zaposlenici.ToList();
}
}
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<FIADevOpsContext>
{
public FIADevOpsContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(@Directory.GetCurrentDirectory() + "/../WebApiCore30/appsettings.json").Build();
var builder = new DbContextOptionsBuilder<FIADevOpsContext>();
var connectionString = configuration.GetConnectionString("webapicore.dev.db.connectionstring");
builder.UseSqlServer(connectionString);
return new FIADevOpsContext(builder.Options);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApiCore30.Repository;
using Microsoft.EntityFrameworkCore.Migrations;
namespace WebApiCore30.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MaheController : ControllerBase
{
[HttpGet]
public string Get()
{
ZaposleniciRepository zr = new ZaposleniciRepository();
Migrations.Init init = new Migrations.Init();
Migration m = null;
return $"U bazi je trenutno ->{zr.GetAll().Count()} zaposlenika";
}
}
}<file_sep>using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using WebApiCore30.Models;
namespace WebApiCore30
{
public class FIADevOpsContext : DbContext
{
public FIADevOpsContext(DbContextOptions<FIADevOpsContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Zaposlenici>().HasData(
new Zaposlenici() { Id = 1, Ime = "Denis", Prezime = "Music", JMBG = "13256465489789"},
new Zaposlenici() { Id = 2, Ime = "Jasmin", Prezime = "Azemovic", JMBG = "13256465489788" }
);
base.OnModelCreating(modelBuilder);
}
public DbSet<Zaposlenici> Zaposlenici { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace WebApiCore30.Models
{
public class Zaposlenici
{
public int Id { get; set; }
public string JMBG { get; set; }
public string Ime { get; set; }
public string Prezime { get; set; }
}
}
| 9508bec0b7be607483b3af3461a367ea70aedd25 | [
"C#"
] | 4 | C# | fias-devs/webapi30 | f930c6ed62ae29e429c61e8e5206c9d1c883de7b | 6c70f7bc614b92a77dade6d076d243d6fd5ad9dc |
refs/heads/main | <repo_name>mohamedveron/project_management<file_sep>/tests/assign_project_owner_test.go
package tests
import (
"github.com/mohamedveron/project_management/service"
"testing"
)
func TestAssignProjectOwner(t *testing.T){
projectsDB, employeesDB := PrepareDataForTest()
service := service.NewService(projectsDB, employeesDB)
res , err := service.AssignProjectOwner("11bb" ,"11aa")
if err != nil || res != "updated"{
t.Error("employee not manager to be the project owner")
}
}
func TestAssignProjectOwnerButNotManager(t *testing.T){
projectsDB, employeesDB := PrepareDataForTest()
service := service.NewService(projectsDB, employeesDB)
res , err := service.AssignProjectOwner("11bb" ,"t3t3")
if err == nil || res == "updated"{
t.Error("employee not manager to be the project owner")
}
}
<file_sep>/tests/utils.go
package tests
import "github.com/mohamedveron/project_management/domains"
func PrepareDataForTest() (map[string]domains.Project, map[string]domains.Employee) {
var projectsDB = make(map[string]domains.Project)
var employeesDB = make(map[string]domains.Employee)
var employee1 = domains.Employee{
ID: "11aa",
FirstName: "Peter",
LastName: "Golm",
Role: "manager",
Email: "<EMAIL>",
Department: "Engineering",
}
var employee2 = domains.Employee{
ID: "33cc",
FirstName: "Andreas",
LastName: "Litt",
Role: "developer",
Email: "<EMAIL>",
Department: "Engineering",
}
var employee3 = domains.Employee{
ID: "58kk",
FirstName: "Nina",
LastName: "Wessels",
Role: "hr",
Email: "<EMAIL>",
Department: "HR",
}
var employee4 = domains.Employee{
ID: "t3t3",
FirstName: "Mohamed",
LastName: "<NAME>",
Role: "developer",
Email: "<EMAIL>",
Department: "Engineering",
}
// make a list of projects to do the operation instead of db
var project1 = domains.Project{
ID: "11bb",
Name: "project management",
Owner: domains.Employee{},
Progress: 0,
State: domains.EnumProjectStatePlanned,
Participants: []domains.Employee{},
}
employeesDB["11aa"] = employee1
employeesDB["33cc"] = employee2
employeesDB["58kk"] = employee3
employeesDB["t3t3"] = employee4
projectsDB["11bb"] = project1
return projectsDB, employeesDB
}
<file_sep>/tests/create_project_test.go
package tests
import (
"github.com/mohamedveron/project_management/domains"
"github.com/mohamedveron/project_management/service"
"testing"
)
func TestCreateProject(t *testing.T){
projectsDB, employeesDB := PrepareDataForTest()
project := domains.Project{
ID: "",
Name: "project1",
Owner: domains.Employee{},
Progress: 0,
State: "planned",
Participants: nil,
}
service := service.NewService(projectsDB, employeesDB)
_ , err := service.CreateProject(project)
if err != nil {
t.Error("can't create project")
}
}
<file_sep>/api/get_projects.go
package api
import (
"net/http"
"encoding/json"
)
func (s *Server) GetProjects(w http.ResponseWriter, r *http.Request){
projects , err := s.svc.GetProjects()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(projects)
}
<file_sep>/service/get_projects.go
package service
import (
"github.com/mohamedveron/project_management/domains"
)
func (s *Service) GetProjects() ([]domains.Project, error){
projectsList := []domains.Project{}
for _, project := range s.ProjectsDB {
projectsList = append(projectsList, project)
}
return projectsList, nil
}
<file_sep>/service/update_project.go
package service
import (
"errors"
"github.com/mohamedveron/project_management/domains"
)
func (s *Service) UpdateProject(project domains.Project, id string) (string, error){
proj := s.findProjectById(id)
if proj == nil {
return "not exist", errors.New("project not exist")
}
updatedProject := domains.Project{
ID: proj.ID,
Name: project.Name,
Owner: proj.Owner,
Progress: project.Progress,
State: project.State,
Participants: proj.Participants,
}
s.ProjectsDB[id] = updatedProject
return "updated", nil
}
<file_sep>/tests/assign_project_participants_test.go
package tests
import (
"github.com/mohamedveron/project_management/service"
"testing"
)
func TestAssignProjectParticipants(t *testing.T){
projectsDB, employeesDB := PrepareDataForTest()
service := service.NewService(projectsDB, employeesDB)
_ , err := service.AssignProjectOwner("11bb" ,"11aa")
participants := []string{"33cc", "t3t3"}
res , err := service.AssignProjectParticipants("11bb" , participants)
if err != nil || res != "added"{
t.Error("employee from different department of the owner")
}
}
func TestAssignProjectParticipantsWithDifferentDepartment(t *testing.T){
projectsDB, employeesDB := PrepareDataForTest()
service := service.NewService(projectsDB, employeesDB)
_ , err := service.AssignProjectOwner("11bb" ,"11aa")
participants := []string{"58kk", "t3t3"}
res , err := service.AssignProjectParticipants("11bb" , participants)
if err == nil || res == "added"{
t.Error("employee from different department of the owner")
}
}
<file_sep>/main.go
package main
import (
"fmt"
"github.com/go-chi/chi"
"github.com/mohamedveron/project_management/api"
"github.com/mohamedveron/project_management/domains"
"github.com/mohamedveron/project_management/service"
"net/http"
)
func main() {
// make a list of employees to do the operation instead of db
employee1 := domains.Employee{
ID: "11aa",
FirstName: "Peter",
LastName: "Golm",
Role: "manager",
Email: "<EMAIL>",
Department: "Engineering",
}
employee2 := domains.Employee{
ID: "33cc",
FirstName: "Andreas",
LastName: "Litt",
Role: "developer",
Email: "<EMAIL>",
Department: "Engineering",
}
employee3 := domains.Employee{
ID: "58kk",
FirstName: "Nina",
LastName: "Wessels",
Role: "hr",
Email: "<EMAIL>",
Department: "HR",
}
employee4 := domains.Employee{
ID: "t3t3",
FirstName: "Mohamed",
LastName: "<NAME>",
Role: "developer",
Email: "<EMAIL>",
Department: "Engineering",
}
// make a list of projects to do the operation instead of db
project1 := domains.Project{
ID: "11bb",
Name: "project management",
Owner: domains.Employee{},
Progress: 0,
State: domains.EnumProjectStatePlanned,
Participants: []domains.Employee{},
}
projectsDB := make(map[string]domains.Project)
employeesDB := make(map[string]domains.Employee)
employeesDB["11aa"] = employee1
employeesDB["33cc"] = employee2
employeesDB["58kk"] = employee3
employeesDB["t3t3"] = employee4
projectsDB["11bb"] = project1
serviceLayer := service.NewService(projectsDB, employeesDB)
server := api.NewServer(serviceLayer)
// prepare router
r := chi.NewRouter()
r.Route("/", func(r chi.Router) {
r.Mount("/", api.Handler(server))
})
srv := &http.Server{
Handler: r,
Addr: ":8080",
}
fmt.Println("server starting on port 8080...")
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Println("server failed to start", "error", err)
}
}
<file_sep>/api/update_project.go
package api
import (
"encoding/json"
"github.com/mohamedveron/project_management/domains"
"net/http"
)
func(s *Server) UpdateProject(w http.ResponseWriter, r *http.Request, id string){
var newProject NewProject
if err := json.NewDecoder(r.Body).Decode(&newProject); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
project := domains.Project{
ID: "",
Name: newProject.Name,
Owner: domains.Employee{},
Progress: newProject.Progress,
State: domains.EnumProjectState(newProject.State),
Participants: nil,
}
res, err := s.svc.UpdateProject(project, id)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(res)
}
<file_sep>/domains/project.go
package domains
type EnumProjectState string
const (
EnumProjectStatePlanned EnumProjectState = "planned"
EnumProjectStateActive EnumProjectState = "active"
EnumProjectStateDone EnumProjectState = "done"
EnumProjectStateFailed EnumProjectState = "failed"
)
type Project struct {
ID string `json:"id"`
Name string `json:"name"`
Owner Employee `json:"owner"`
Progress float32 `json:"progress"`
State EnumProjectState `json:"state" validate:"oneof=planned active done failed"`
Participants []Employee `json:"participants"`
}
<file_sep>/service/assign_project_owner.go
package service
import (
"errors"
"github.com/mohamedveron/project_management/domains"
)
func (s *Service) AssignProjectOwner(projectId string, ownerId string)(string , error){
project := s.findProjectById(projectId)
if project == nil {
return "not exist", errors.New("project not exist")
}
owner := s.findEmployeeById(ownerId)
if owner == nil {
return "not exist", errors.New("employee not exist")
}
if owner.Role != "manager" {
return "not manager", errors.New("employee not manager to be the project owner")
}
updatedProject := domains.Project{
ID: project.ID,
Name: project.Name,
Owner: *owner,
Progress: project.Progress,
State: project.State,
Participants: project.Participants,
}
s.ProjectsDB[projectId] = updatedProject
return "updated", nil
}
<file_sep>/README.md
# visable task
This app is developed using go-chi https://github.com/go-chi/chi router and oapi-codegen https://github.com/deepmap/oapi-codegen to generate client for apis
# Use api.yml file in the swagger ui to see the description of the rest apis
## Covered Scenarios by the Unit tests :
1- Create New Project
2- Update New Project.
3- Assign Project Owner with role manage.
4- Trying to Assign Project Owner with not manage role.
5- Assign Project Participants
6- Trying Assign Project Participants with not the same role as the owner
## Setup
Must have golang installed version >= 12.0.0
make file consists of 4 steps: generate, test, build, run
you can run all of them
```bash
make all
```
# Run the unit tests:
```bash
make test
```
If you have issue with code generation in generate step you can run go test -v ./tests
# Start the http server:
```bash
make run
```
If you have issue with code generation in generate step you can copy the api/api.gen.go file in repo and run go run main.go to start the server
### Notes:
1- I didn't use any database just in memory hash maps for both projects and employees
2- There is an list employees api
<file_sep>/api/assign_project_participants.go
package api
import (
"encoding/json"
"net/http"
)
func (s *Server) AssignProjectParticipants(w http.ResponseWriter, r *http.Request, id string){
body := map[string][]string{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
res, err := s.svc.AssignProjectParticipants(id, body["employeeIds"])
if res == "different department" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode("can't assign employee from different department of the owner in the project")
return
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(res)
}
<file_sep>/go.mod
module github.com/mohamedveron/project_management
go 1.13
require (
github.com/deepmap/oapi-codegen v1.5.1
github.com/go-chi/chi v4.1.2+incompatible
)
<file_sep>/tests/update_project_test.go
package tests
import (
"github.com/mohamedveron/project_management/domains"
"github.com/mohamedveron/project_management/service"
"testing"
)
func TestUpdateProject(t *testing.T){
projectsDB, employeesDB := PrepareDataForTest()
project := domains.Project{
ID: "11bb",
Name: "project1",
Owner: projectsDB["11bb"].Owner,
Progress: 20,
State: "active",
Participants: projectsDB["11bb"].Participants,
}
service := service.NewService(projectsDB, employeesDB)
res , err := service.UpdateProject(project, "11bb")
if err != nil || res != "updated"{
t.Error("can't update project")
}
}
<file_sep>/api/create_project.go
package api
import (
"encoding/json"
"github.com/mohamedveron/project_management/domains"
"net/http"
)
func (s *Server) CreateProject(w http.ResponseWriter, r *http.Request){
var newProject NewProject
if err := json.NewDecoder(r.Body).Decode(&newProject); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
project := domains.Project{
ID: "",
Name: newProject.Name,
Owner: domains.Employee{},
Progress: newProject.Progress,
State: domains.EnumProjectState(newProject.State),
Participants: nil,
}
id, err := s.svc.CreateProject(project)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(id)
}
<file_sep>/service/service.go
package service
import "github.com/mohamedveron/project_management/domains"
type Service struct {
ProjectsDB map[string]domains.Project
EmployeesDB map[string]domains.Employee
}
func NewService(projectsDB map[string]domains.Project, employeesDB map[string]domains.Employee) *Service {
return &Service{
ProjectsDB: projectsDB,
EmployeesDB: employeesDB,
}
}
<file_sep>/api/get_employees.go
package api
import (
"encoding/json"
"net/http"
)
func (s *Server) GetEmployees(w http.ResponseWriter, r *http.Request){
employees , err := s.svc.GetEmployees()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(employees)
}
<file_sep>/api/assign_project_owner.go
package api
import (
"encoding/json"
"net/http"
)
func (s *Server) AssignProjectOwner(w http.ResponseWriter, r *http.Request, id string){
body := map[string]string{}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
res, err := s.svc.AssignProjectOwner(id, body["employeeId"])
if res == "not manager" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode("employee not a manager to be the project owner")
}
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(res)
}
<file_sep>/service/get_employees.go
package service
import "github.com/mohamedveron/project_management/domains"
func (s *Service) GetEmployees() ([]domains.Employee, error){
employeesList := []domains.Employee{}
for _, employees := range s.EmployeesDB {
employeesList = append(employeesList, employees)
}
return employeesList, nil
}
<file_sep>/service/helpers.go
package service
import "github.com/mohamedveron/project_management/domains"
func (s *Service) findProjectById(id string) *domains.Project{
if project, ok := s.ProjectsDB[id]; ok {
return &project
}
return nil
}
func (s *Service) findEmployeeById(id string) *domains.Employee{
if employee, ok := s.EmployeesDB[id]; ok {
return &employee
}
return nil
}
<file_sep>/service/create_project.go
package service
import (
"github.com/mohamedveron/project_management/domains"
"math/rand"
)
func (s *Service) CreateProject(project domains.Project) (string, error){
// generate new id
id := randGeneratePassword(4)
project.ID = id
s.ProjectsDB[id] = project
return id, nil
}
func randGeneratePassword(n int) string {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}<file_sep>/domains/employee.go
package domains
// Employee category type
type Employee struct {
ID string `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"name" `
Role string `json:"role" `
Email string `json:"email" `
Department string `json:"department" `
}
<file_sep>/service/assign_project_participants.go
package service
import (
"errors"
"github.com/mohamedveron/project_management/domains"
)
func (s *Service) AssignProjectParticipants(projectId string, participantsIds []string)(string , error){
project := s.findProjectById(projectId)
if project == nil {
return "not exist", errors.New("project not exist")
}
participants := []domains.Employee{}
if project.Participants != nil && len(project.Participants) > 0 {
participants = project.Participants
}
for _, id := range participantsIds {
owner := s.findEmployeeById(id)
if owner == nil {
return "not exist", errors.New("employee not exist")
}
if owner.Department != project.Owner.Department {
return "different department", errors.New("employee from different department of the owner")
}
participants = append(participants, *owner)
}
updatedProject := domains.Project{
ID: project.ID,
Name: project.Name,
Owner: project.Owner,
Progress: project.Progress,
State: project.State,
Participants: participants,
}
s.ProjectsDB[projectId] = updatedProject
return "added", nil
}
| ba6a699bbd5db9cd007617285b64cb7c0f6aacbf | [
"Markdown",
"Go Module",
"Go"
] | 24 | Go | mohamedveron/project_management | d2cad0354ecbe9580da23aee26e1aa96311b6ced | d3a6e042ae052ecd64c60a8359f9ec011f7acecf |
refs/heads/master | <file_sep># Sistema de gerenciamento de pessoas em API REST com Spring Boot
Aplicação desenvolvida durante o bootcamp realizado pela *Digital Innovation One*
## Objetivo ✔️
- Criar uma API REST
- Operações básicas do CRUD: cadastro, leitura, atualização e remoção
- Padrão MVC
- Tratamento de exceções
- Tratamento de requisições Http
- Desenvolvimento de testes unitários
- Implantação do sistema na nuvem através do Heroku
---
## Tecnologias usadas 👨🏿💻
- Spring Boot
- MapStruct
- Postman
- Lombok
- Heroku
- Maven
- H2
---
## Afazeres pós bootcamp 💡
- [ ] Implementar testes unitários para as outras operações da camadas de serviço
- [ ] Implementar testes unitários para os end points
---
## Baixe e execute na sua máquina
### Passo a passo
```
# Pelo terminal, clone o repositório
$ git clone https://github.com/wpmello/personapi
# Verifique se possui o maven instalado na sua máquina
$ mvn -v
# No diretório do projeto, digite o seguinte comando
$ mvn spring-boot:run
```
---
## Chegou a hora de testar a aplicação
```
# Após rodar o programa, digite no browser:
$ localhost:8080/api/v1/people
# Acesse o banco de dados H2 digitando:
$ localhost:8080/h2-console
##### NOTAS #####
# Ao acessar localhost:8080/api/v1/people, se aparecer as chaves -> [] <- você já estará com a api funcionando
# A URL do banco de dados H2 será informada na inicialização da aplicação. Atente-se ao console!
```
---
### Algumas recomendações:
Você pode usar o [Postman](https://www.postman.com/downloads/) para testar as funcionalidades da api.
Acesse a plataforma [Digital Innovation One](https://digitalinnovation.one/) para realizar projetos como este.<file_sep>package one.digitalinnovation.personapi.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.List;
/*Foram feitos os mapeamentos de lombok (para evitar a verbosidade e dar performance na criação do objeto)
e os de JPA (para persistir os dados no banco de dados).*/
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String firstName;
@Column(nullable = false)
private String lastName;
@Column(nullable = false, unique = true)
private String cpf;
private LocalDate birthDate;
@OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
private List<Phone> phones;
}
| 40f052d3976040daf70b321dfc2a7124fa525688 | [
"Markdown",
"Java"
] | 2 | Markdown | wpmello/person-api | e752a7acea85ec30845b6df3a0334f588fec7a57 | ba0d32189a741170356d536609d3a1ae4bf3c80a |
refs/heads/master | <repo_name>ApoStoLll/MonopolyOnline<file_sep>/static/game.js
let socket = io();
let btn = document.getElementById('btn');
btn.onclick = function(){
socket.emit('press', '');
socket.on('message', function(data){
console.log(data);
});
};
socket.on('position', (players) => {
console.log("DRAWING RECTS");
console.log(players.length);
view.drawRects();
console.log("DRAWING PLAYERS");
view.drawPlayers(players);
console.log("PLAYERS END");
});
let canvas = document.getElementById("canvas");
let view = new View(canvas);
view.createMap();
view.drawRects();
view.skipOrBuy();
view.menu();
socket.emit('new player');<file_sep>/model/player.js
class Player{
constructor(number, id){
this.money = 1500000;
this.number = number;
this.position = 0;
this.cards = [];
this.id = id;
}
getMoney(){ return this.money; }
setMoney(money){ this.money = money; }
getPosition() {return this.position; }
setPosition(position) {this.position = position; }
getNumber() { return this.number; }
setNumber(number) { this.number = number; }
findCard(position){
for(let i = 0; i < this.cards.lenght;i++){
if (this.cards[i].getPosition === position) return this.cards[i];
}
}
payRent(player){
let rentPrice = player.findCard(position).getPriceRent();
this.money = this.money - rentPrice;
player.setMoney(player.getMoney() + rentPrice);
}
buyCard(card){
card.setOwner(number);
this.money = this.money - card.getPrice();
this.cards[this.cards.length] = card;
}
};
module.exports = Player;<file_sep>/model/roflan.js
class Roflan{
constructor(position,type){
this.position = position;
this.type = type;
}
getType() { return this.type; }
getPosition() { return this.position; }
action(player){
if ( this.type == 1 ) { karaganda(player); }
if ( this.type == 2 ) {}
}
karaganda(player){
}
};<file_sep>/server.js
const Game = require('./controller/gameController');
const express = require('express');
const http = require('http');
const path = require('path');
const socketIO = require('socket.io');
const app = express();
const server = http.Server(app);
const io = socketIO(server);
const port = 3000;
let game = new Game(io);
io.on('connection', (socket) => {
// console.log(io);
socket.on('new player', () => {
game.createPlayer(socket);
console.log('connect');
console.log(game.counter);
if(game.counter > 1){
game.cycle(socket);
}
});
socket.on('disconnect', () => {
game.removePlayer(socket);
console.log('disconnect');
});
});
app.set('port', port);
app.use('/static', express.static(__dirname + '/static'));
// Маршруты
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname, 'index.html'));
});
// Запуск сервера
server.listen(port, function() {
console.log('Запускаю сервер на порте 3000');
});
/*let steps = 0;
let i = 0;
let first;
let second;
function sizeOf(arr){
var counter = 0;
for (var key in arr) {
counter++;
}
return counter;
}
function setFirstAndSecond(){
for(let id in players){
//console.log('func' + id);
if(i == 0) first = id;
if(i == 1) second = id;
i++;
}
}
function step(player){
let a = random();
let b = random();
console.log('step: ' + player);
player.position = player.position() + a + b;
}
function gameCycle(socket){
console.log('PLAYERSgame: ' + JSON.stringify(players));
console.log('game, player.first ' + JSON.stringify(players[first]));
if(sizeOf(players) > 1){
if(step % 2 == 0) step(players.first);
else step(players.second);
io.sockets.emit('position', posOfPlayers);
step++;
}
}
io.on('connection', function(socket) {
socket.on('press', function(){
gameCycle(socket);
});
socket.on('new player', () => {
/*players[socket.id] = new Player(socket.id);
let posOfPlayers = [];
//for(let i = 0; i < players.length; i++) posOfPlayers[i] = players[i].getPosition();
for(let id in players)
posOfPlayers[i] = players[id].getPosition();
//console.log("Players: " + JSON.stringify(players));
//console.log("id" + JSON.stringify(players[socket.id]));
io.sockets.emit('position', posOfPlayers);
if(sizeOf(players) > 1) setFirstAndSecond();
});
});*/<file_sep>/static/view.js
class View{
constructor(canvas){
this.canvas = canvas;
this.canvas.width = 880;
this.canvas.height = 880;
this.context = this.canvas.getContext('2d');
this.rects = [];
this.width = 80;
this.height = 80;
}
drawPlayers(players){
this.context.fillStyle = "rgb(255, 255, 255)";
console.log(players.length);
for(let i = 0; i < players.length; i++){
let rect = this.rects[players[i]];
console.log("pos: " + players[i]);
new Rect(rect.getX() + 10, rect.getY() + 10, 40, 40).draw(this.context);
}
}
createMap(){
for(let i = 0; i < 11; i++) //GORIZONTAL(BOT);
this.rects[i] = new Rect(880 - this.width * i - 80, 880 - this.height, this.width, this.height);
for(let i = 0; i < 9; i++) //VERTICAL(LEFT);
this.rects[11 + i] = new Rect(0, 880 - this.height * i - 160, this.width, this.height);
for(let i = 0; i < 11; i++) //GORIZONTAL(top);
this.rects[20 + i] = new Rect(this.width * i, 0, this.width, this.height);
for(let i = 0; i < 9; i++) //VERTICAL(RIGHT);
this.rects[31 + i] = new Rect(880 - this.width, 80 + this.height * i, this.width, this.height);
}
drawRects(){
this.canvas.width = this.canvas.width;
for(let i = 0; i < this.rects.length; i++){
if( i % 10 == 0 ) this.context.fillStyle = "rgb(255, 248, 220)";
if (i == 2 || i == 4 || i == 8 || i == 12 || i == 17 || i == 23 || i == 27 || i == 32 || i == 36 || i == 38)
this.context.fillStyle = "rgb(255, 255, 255)";
if( i == 1 || i == 3 ) this.context.fillStyle = "rgb(75, 0, 130)";
if( i % 10 == 5 ) this.context.fillStyle = "rgb(255, 140, 0)";
if ( i == 6 || i == 7 || i == 9) this.context.fillStyle = "rgb(0, 128, 0)";
if ( i == 11 || i == 13 || i == 14) this.context.fillStyle = "rgb(255, 0, 0)";
if ( i == 16 || i == 18 || i == 19) this.context.fillStyle = "rgb(192, 192, 192)";
if ( i == 21 || i == 22 || i == 24) this.context.fillStyle = "rgb(0, 0, 255)";
if ( i == 26 || i == 28 || i == 29) this.context.fillStyle = "rgb(139, 69, 19)";
if ( i == 31 || i == 33 || i == 34) this.context.fillStyle = "rgb(0, 0, 0)";
if ( i == 39 || i == 37) this.context.fillStyle = "rgb(255, 20, 147)";
this.rects[i].draw(this.context);
document.getElementById("buyBtn").style.visibility = "hidden";
document.getElementById("skipBtn").style.visibility = "hidden";
document.getElementById("finishBtn").style.visibility = "hidden";
}
};
skipOrBuy(){
document.getElementById("buyBtn").style.visibility = "visible";
document.getElementById("skipBtn").style.visibility = "visible";
}
menu(){
document.getElementById("finishBtn").style.visibility = "visible";
}
};
function buy(){
document.getElementById("buyBtn").style.visibility = "hidden";
document.getElementById("skipBtn").style.visibility = "hidden";
return 1;
}
function skip(){
document.getElementById("buyBtn").style.visibility = "hidden";
document.getElementById("skipBtn").style.visibility = "hidden";
return 0;
}
function finish(){
document.getElementById("finishBtn").style.visibility = "hidden";
return 0;
}
| 1537b9f288d400f9263e6829e56ba82e59fb0ea7 | [
"JavaScript"
] | 5 | JavaScript | ApoStoLll/MonopolyOnline | eba98a5beaea4bd7dd8959ff96da6ff64f7ac3d0 | 8548823b27e99255fa3ccb5d6b989078316a9cbd |
refs/heads/master | <repo_name>HarjasSodhi/Puppeteer-Automation-TwitterMarketingTool<file_sep>/TMT.js
const puppy = require('puppeteer');
const fs = require('fs');
const username ; //enter your twitter username
const password ; //enter your twitter password
const id ;//enter your email id
//this is for generating JSON File
let PeopleContacted = [];
//this is for generating chehcker File.
let messageSent = [];
let str = '(';
//add your hashtags here for better results . you can leave it empty too;
let hashtags = ['#teachmetodance'];
//this is for avoiding messaging same people more than once.
let olderData = '';
//change this message as you desire
let message = "hey there!! i saw from your tweet that you might be interested in dance lessons and i actually provide online lessons so if you are interested ,let me know . Thanks"
async function relatedWords() {
let browser = await puppy.launch({
headless: false,
defaultViewport: false
})
let tabs = await browser.pages();
let tab = tabs[0];
//website for getting keywords simislar to the business field;
await tab.goto('https://relatedwords.org');
await tab.waitForSelector('input');
//enter your business field here.enter only the main Keyword(only one word);
await tab.type('input', 'dance');
await tab.waitForSelector('#search-button');
await tab.click('#search-button');
await tab.waitForSelector('.item', { visible: true });
let words = await tab.$$('.item');
//you can change the number of keywords you want here but twitter gives an error if they are too many. it works perfectly for 20;
let n=20;
for (let i = 0; i < n; i++) {
let keyword = await tab.evaluate(function (ele) {
return ele.textContent;
}, words[i]);
let finalKeywords = keyword.split(' ');
//becoz of this we get just the keywords that are single worded because space between words also gives an error
if (finalKeywords.length == 1) {
if (i == n-1) {
str += " OR "+finalKeywords[0];
}
else{
if(i==n-2)str += finalKeywords[0];
else str += finalKeywords[0] + ' OR ';
}
}
}
str=str+ ')';
if (hashtags.length > 0) {
str += '(';
for (let j = 0; j < hashtags.length; j++) {
if (j == hashtags.length - 1) {
str += hashtags[j] + ")";
}
else str += hashtags[j] + ' OR ';
}
}
//this timeout is so that the website is visible to the user as well
await tab.waitForTimeout(1000);
// console.log(str);
//keywords are converted into a String format understood by the twitter search mechanism;
olderData = fs.readFileSync('ContactedPeople.json', 'utf-8');
let OlderPeople = fs.readFileSync('checker.txt', 'utf-8');
if (OlderPeople != '') messageSent = OlderPeople.split('\n');
login(str, tab)
}
async function login(str, tab) {
await tab.goto('https://twitter.com/login?lang=en-gb');
await tab.waitForSelector('.r-30o5oe.r-1niwhzg.r-17gur6a.r-1yadl64.r-deolkf.r-homxoj.r-poiln3.r-7cikom.r-1ny4l3l.r-t60dpp.r-1dz5y72.r-fdjqy7.r-13qz1uu');
let details = await tab.$$(".r-30o5oe.r-1niwhzg.r-17gur6a.r-1yadl64.r-deolkf.r-homxoj.r-poiln3.r-7cikom.r-1ny4l3l.r-t60dpp.r-1dz5y72.r-fdjqy7.r-13qz1uu");
await details[0].type(username);//enter id in place of username if you want to login using that;
await details[1].type(password);
await tab.click('.css-18t94o4.css-1dbjc4n.r-urgr8i.r-42olwf.r-sdzlij.r-1phboty.r-rs99b7.r-1w2pmg.r-1fz3rvf.r-usiww2.r-1pl7oy7.r-snto4y.r-1ny4l3l.r-1dye5f7.r-o7ynqc.r-6416eg.r-lrvibr');
await tab.waitForSelector('.r-30o5oe.r-1niwhzg.r-17gur6a.r-1yadl64.r-deolkf.r-homxoj.r-poiln3.r-7cikom.r-1ny4l3l.r-xyw6el.r-ny71av.r-1dz5y72.r-fdjqy7.r-13qz1uu');
await tab.type('.r-30o5oe.r-1niwhzg.r-17gur6a.r-1yadl64.r-deolkf.r-homxoj.r-poiln3.r-7cikom.r-1ny4l3l.r-xyw6el.r-ny71av.r-1dz5y72.r-fdjqy7.r-13qz1uu', str);
await tab.keyboard.press('Enter');
await tab.waitForSelector('.css-4rbku5.css-18t94o4.css-1dbjc4n.r-1awozwy.r-oucylx.r-rull8r.r-wgabs5.r-1loqt21.r-6koalj.r-eqz5dr.r-16y2uox.r-1h3ijdo.r-1777fci.r-1ny4l3l.r-xyw6el.r-o7ynqc.r-6416eg');
let fields = await tab.$$('.css-4rbku5.css-18t94o4.css-1dbjc4n.r-1awozwy.r-oucylx.r-rull8r.r-wgabs5.r-1loqt21.r-6koalj.r-eqz5dr.r-16y2uox.r-1h3ijdo.r-1777fci.r-1ny4l3l.r-xyw6el.r-o7ynqc.r-6416eg');
await fields[0].click();
await tab.waitForTimeout(5000);
await tab.waitForSelector('.css-901oao.r-1awozwy.r-m0bqgq.r-6koalj.r-1qd0xha.r-a023e6.r-16dba41.r-1h0z5md.r-rjixqe.r-bcqeeo.r-o7ynqc.r-clp7b1.r-3s2u2q.r-qvutc0');
let people = await tab.$$('.css-901oao.r-1awozwy.r-m0bqgq.r-6koalj.r-1qd0xha.r-a023e6.r-16dba41.r-1h0z5md.r-rjixqe.r-bcqeeo.r-o7ynqc.r-clp7b1.r-3s2u2q.r-qvutc0');
//Enter the number of people you want to Contact here;
let NumOfPeople=6;
for (let i = 1; i < NumOfPeople*5; i += 5) {
await people[i].click();
await tab.waitForSelector('.css-1dbjc4n.r-14lw9ot.r-1pp923h.r-1moyyf3.r-oyd9sg');
await tab.waitForSelector('.css-901oao.css-16my406.r-poiln3.r-bcqeeo.r-qvutc0', { visible: true });
let details = await tab.$$('.css-901oao.css-16my406.r-poiln3.r-bcqeeo.r-qvutc0');
let name = await tab.evaluate(function (ele) {
return ele.textContent;
}, details[4]);
let ProfileTag = await tab.evaluate(function (ele) {
return ele.textContent;
}, details[5]);
if (messageSent.includes(ProfileTag)) {
//if a person is messaged before you get this output;
console.log(ProfileTag + ' ALREADY MESSAGED BEFORE');
await tab.waitForSelector('.css-18t94o4.css-1dbjc4n.r-1niwhzg.r-42olwf.r-sdzlij.r-1phboty.r-rs99b7.r-1w2pmg.r-ero68b.r-vkv6oe.r-1ny4l3l.r-mk0yit.r-o7ynqc.r-6416eg.r-lrvibr', { visible: true });
let backButton = await tab.$$('.css-18t94o4.css-1dbjc4n.r-1niwhzg.r-42olwf.r-sdzlij.r-1phboty.r-rs99b7.r-1w2pmg.r-ero68b.r-vkv6oe.r-1ny4l3l.r-mk0yit.r-o7ynqc.r-6416eg.r-lrvibr');
await backButton[0].click();
}
else {
await tab.waitForSelector('.DraftEditor-editorContainer');
await tab.click('.DraftEditor-editorContainer');
await tab.type('.DraftEditor-editorContainer', message);
messageSent.push(ProfileTag);
PeopleContacted.push({
"name": name,
'ProfileTag': ProfileTag
});
await tab.waitForSelector('.css-901oao.r-1awozwy.r-jwli3a.r-6koalj.r-18u37iz.r-16y2uox.r-1qd0xha.r-a023e6.r-b88u0q.r-1777fci.r-rjixqe.r-dnmrzs.r-bcqeeo.r-q4m81j.r-qvutc0')
let reply = await tab.$$('.css-901oao.r-1awozwy.r-jwli3a.r-6koalj.r-18u37iz.r-16y2uox.r-1qd0xha.r-a023e6.r-b88u0q.r-1777fci.r-rjixqe.r-dnmrzs.r-bcqeeo.r-q4m81j.r-qvutc0');
await reply[0].click();
}
await tab.waitForTimeout(2000);
}
fs.writeFileSync('ContactedPeople.json', olderData + "\n" + JSON.stringify(PeopleContacted));
let pct = messageSent.join('\n');
fs.writeFileSync('checker.txt', pct);
//JSON file stores the information of people you have contacted so that you are able to contact them again if you wish to;
//checker file stores the tags of people contacted so that they are not messaged again.
//if you run the code for the same field,clear out the checker.txt file so people can be messaged again.
}
relatedWords();<file_sep>/README.md
# Pupeeteer-Automaion-TwitterMarketingTool
An Automation program that helps businessmen and service Providers find potential clients based on their tweet keywords and hashtags.
Hi guys!
I have tried to create a Simple digitalmarketing tool for businessmen and service providers.
All you need to do is Enter your Field of Business (for eg-dancing classes).Then the program goes to a website and scrapes all the related words to the field the user has entered.
After that the program converts the words into a String format that is Understood by the #twitter search mechanism.
User can Also add hashtags for better results(Here I have used "#teachmetodance") and after that the Program automatically sends a custom message to the people who show up in the search .
The number of people to message and the message itself can be decided by the user.
The data of the people messaged is stored in a JSON file too so you can contact them yourself if you wish.
If you run the program again for the same field ,then the program DOES NOT message the people previously messaged.
For Using the code just add your username,id and password in the variables.and after installing the puppeteer library,the code should work perfectly.
You might have to experiment with the a few Hashtags for getting results | 45b2d610ea9f6c1713d80e871616d9bdb4315ecd | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | HarjasSodhi/Puppeteer-Automation-TwitterMarketingTool | 55eacc8b5a62b5370ed4d82214f8104400660045 | a62d47abaddbd707c02872fb39f7a2621b267da7 |
refs/heads/master | <repo_name>PerryB52/PS_AMD_iTabs_tablayout<file_sep>/app/src/main/java/com/example/alexandrup/ps_amd_tabs_tablayout/tabs/IconTabs.java
package com.example.alexandrup.ps_amd_tabs_tablayout.tabs;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.example.alexandrup.ps_amd_tabs_tablayout.R;
import com.example.alexandrup.ps_amd_tabs_tablayout.adapters.IconTabsAdapater;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentFive;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentFour;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentOne;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentSix;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentThree;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentTwo;
import java.util.ArrayList;
import java.util.List;
/**
* Created by alexandrup on 12/31/2016.
*/
public class IconTabs extends AppCompatActivity {
private List<Fragment> fragmentList = new ArrayList<>();
private IconTabsAdapater adapter;
private ViewPager viewPager;
private TabLayout tabLayout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icon_tabs);
initialise();
prepareDataResouce();
adapter = new IconTabsAdapater(getSupportFragmentManager(), fragmentList);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
setTabIcons();
}
private void setTabIcons() {
tabLayout.getTabAt(0).setIcon(R.drawable.facebook);
tabLayout.getTabAt(1).setIcon(R.drawable.googleplus);
tabLayout.getTabAt(2).setIcon(R.drawable.instagram);
tabLayout.getTabAt(3).setIcon(R.drawable.linkedin);
tabLayout.getTabAt(4).setIcon(R.drawable.youtube);
tabLayout.getTabAt(5).setIcon(R.drawable.twitter);
}
private void initialise() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Simple Icon Tabs");
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
}
private void prepareDataResouce() {
fragmentList.add(new FragmentOne());
fragmentList.add(new FragmentTwo());
fragmentList.add(new FragmentThree());
fragmentList.add(new FragmentFour());
fragmentList.add(new FragmentFive());
fragmentList.add(new FragmentSix());
}
}<file_sep>/app/src/main/java/com/example/alexandrup/ps_amd_tabs_tablayout/fragments/TestAddFile2Git.java
package com.example.alexandrup.ps_amd_tabs_tablayout.fragments;
/**
* Created by alexandrup on 12/30/2016.
*/
public class TestAddFile2Git {
}
<file_sep>/app/src/main/java/com/example/alexandrup/ps_amd_tabs_tablayout/tabs/ScrollTabs.java
package com.example.alexandrup.ps_amd_tabs_tablayout.tabs;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.example.alexandrup.ps_amd_tabs_tablayout.R;
import com.example.alexandrup.ps_amd_tabs_tablayout.adapters.ScrollTabsAdapter;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentFive;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentFour;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentOne;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentSix;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentThree;
import com.example.alexandrup.ps_amd_tabs_tablayout.fragments.FragmentTwo;
import java.util.ArrayList;
import java.util.List;
/**
* Created by alexandrup on 12/31/2016.
*/
public class ScrollTabs extends AppCompatActivity {
private List<Fragment> fragmentList = new ArrayList<>();
private List<String> titleList = new ArrayList<>();
private ScrollTabsAdapter adapter;
private ViewPager viewPager;
private TabLayout tabLayout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scroll_tabs);
initialise();
prepareDataResouce();
adapter = new ScrollTabsAdapter(getSupportFragmentManager(),
fragmentList, titleList);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
}
private void initialise() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Scroll Tabs Example");
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
}
private void prepareDataResouce() {
addData(new FragmentOne(), "ONE");
addData(new FragmentTwo(), "TWO");
addData(new FragmentThree(), "THREE");
addData(new FragmentFour(), "FOUR");
addData(new FragmentFive(), "FIVE");
addData(new FragmentSix(), "SIX");
addData(new FragmentOne(), "ONE");
addData(new FragmentTwo(), "TWO");
addData(new FragmentThree(), "THREE");
addData(new FragmentFour(), "FOUR");
addData(new FragmentFive(), "FIVE");
addData(new FragmentSix(), "SIX");
}
private void addData(Fragment fragment, String title){
fragmentList.add(fragment);
titleList.add(title);
}
}
| dd52afb50be60acd7e9809f8b196e082599c1729 | [
"Java"
] | 3 | Java | PerryB52/PS_AMD_iTabs_tablayout | 9bab30d367f458ab85c0f8e50147a9c731e2171e | 862a8f15b7f43f43eb4c1d04d4fad908238df3a0 |
refs/heads/master | <repo_name>eastie71/js-todo-app<file_sep>/README.md
# js-todo-app
Simple JS Todo App using Node and MongoDB
- Uses Node Express as the Server
Based on "Learn Javascript" course on Udemy by <NAME>
Has basic CRUD operations
<file_sep>/public/browser.js
function todoTemplate(todo) {
return `
<li class="list-group-item list-group-item-action d-flex align-items-center justify-content-between">
<span class="item-text">${todo.text}</span>
<div>
<button data-id="${todo._id}" class="edit-me btn btn-secondary btn-sm mr-1">Edit</button>
<button data-id="${todo._id}" class="delete-me btn btn-danger btn-sm">Delete</button>
</div>
</li>`
}
function setupTodoList(todo_list, list_name) {
// Setup the ToDo List Page Heading
document.getElementById("todo-header").innerHTML = list_name + " To-Do List"
// Setup the List of Todos
document.getElementById("todo-list").innerHTML = ""
let listHTML = todo_list.map(function(todo) {
return todoTemplate(todo)
}).join('')
document.getElementById("todo-list").insertAdjacentHTML("beforeend", listHTML)
}
// Initial Page Loader for Todo List
setupTodoList(todos, current_db_name)
// Switch Database feature
if (document.getElementById("switch-db-form")) {
document.getElementById("switch-db-form").addEventListener("submit", function(e) {
e.preventDefault()
// Send request to switch database asyncronously to server to switch the db used
// Using axios JS library to perform this operation
axios.post('/switch-db').then(function(response) {
// after switch db has completed, then need to redisplay the header and the list of todos
console.log("Switched DB OK")
console.log(response.data)
setupTodoList(response.data[0], response.data[1])
}).catch(function() {
console.log("An error occured switching the database")
})
})
}
// Create Feature
let createField = document.getElementById("create-field")
document.getElementById("create-form").addEventListener("submit", function(e) {
e.preventDefault()
// Send request to create todo asyncronously to server to create todo in the db
// Using axios JS library to perform this operation
axios.post('/create-todo', {text: createField.value}).then(function(response) {
// after create has completed, then create the HTML required to display new todo
document.getElementById("todo-list").insertAdjacentHTML("beforeend", todoTemplate(response.data))
// Clear the new todo field, and re-focus on that field ready for next entry
createField.value = ''
createField.focus()
}).catch(function() {
console.log("An error occured creating the todo")
})
})
document.addEventListener("click", function(e) {
if (e.target.classList.contains("delete-me")) {
// Delete Feature
if (confirm("Please confirm you wish to delete this todo item permanently")) {
// Send request to delete todo asyncronously to server to remove from the db
// Using axios JS library to perform this operation
axios.post('/delete-todo', {id: e.target.getAttribute("data-id")}).then(function(){
// after delete has completed, then remove list item html
e.target.parentElement.parentElement.remove()
}).catch(function() {
console.log("An error occured deleting the todo")
})
}
} else if (e.target.classList.contains("edit-me")) {
// Update Feature
let userInput = prompt("Enter your New Todo", e.target.parentElement.parentElement.querySelector(".item-text").innerHTML)
if (userInput) {
// Send updated todo text asyncronously to server to update to db
// Using axios JS library to perform this operation
axios.post('/update-todo', {text: userInput, id: e.target.getAttribute("data-id")}).then(function(){
// after update has completed, then set the HTML to the new user input data
e.target.parentElement.parentElement.querySelector(".item-text").innerHTML = userInput
}).catch(function() {
console.log("An error occured updating the todo")
})
}
}
}) | ed909d965f5f761b399d37ba1e571d09eff361ae | [
"Markdown",
"JavaScript"
] | 2 | Markdown | eastie71/js-todo-app | 66d109e0bd206aec27bb5f6812870dea11eee8d6 | caf9fd4f965e6ebd06bdaec39c4e8793bf3a2243 |
refs/heads/main | <repo_name>vn425282/TheStoreFrontEnd<file_sep>/src/components/utils/FileUpload.js
import React, { useState } from 'react'
import Dropzone from 'react-dropzone';
import { Icon } from 'antd';
import Axios from 'axios';
import { API_ENDPOINT } from "../Config";
function FileUpload(props) {
const [Images, setImages] = useState([])
const onDrop = (files) => {
let formData = new FormData();
const config = {
headers: {
'Authorization': `Bearer ${localStorage.getItem("token")}`,
'content-type': 'multipart/form-data'
}
};
formData.append("file", files[0])
Axios.post(API_ENDPOINT + 'product/uploadImage', formData, config)
.then(response => {
if (response.data !== "") {
console.log(response.data);
setImages([...Images, response.data.data])
props.refreshFunction([...Images, response.data.data])
} else {
alert('Failed to save the Image in Server')
}
})
}
function DropZoneCustom() {
return Images.length > 0 ? <></> :
<Dropzone
onDrop={onDrop}
multiple={false}
maxSize={800000000}
>
{({ getRootProps, getInputProps }) => (
<div style={{
width: '300px', height: '240px', border: '1px solid lightgray',
display: 'flex', alignItems: 'center', justifyContent: 'center'
}}
{...getRootProps()}
>
{console.log('getRootProps', { ...getRootProps() })}
{console.log('getInputProps', { ...getInputProps() })}
<input {...getInputProps()} />
<Icon type="plus" style={{ fontSize: '3rem' }} />
</div>
)}
</Dropzone>;
}
return (
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<DropZoneCustom />
<div style={{ display: 'flex', width: '350px', height: '240px', overflowX: 'scroll' }}>
{Images.map((image, index) => (
<div>
<img style={{ minWidth: '300px', width: '300px', height: '240px' }} src={`http://localhost:3233/${image}`} alt={`productImg-${index}`} />
</div>
))}
</div>
</div>
)
}
export default FileUpload
<file_sep>/src/_actions/user_actions.js
import axios from "axios";
import {
LOGIN_USER,
REGISTER_USER,
AUTH_USER,
LOGOUT_USER,
ADD_TO_CART_USER,
GET_CART_ITEMS_USER,
REMOVE_CART_ITEM_USER,
ON_SUCCESS_BUY_USER
} from "./types";
import { API_ENDPOINT } from "../components/Config.js";
export function registerUser(dataToSubmit) {
const request = axios.post(`${API_ENDPOINT}user/register`, dataToSubmit)
.then((response) => response.data)
.catch((error) => error.response.data)
return {
type: REGISTER_USER,
payload: request
};
}
export function loginUser(dataToSubmit) {
const request = axios.post(`${API_ENDPOINT}user/login`, dataToSubmit)
.then((response) => response.data);
return {
type: LOGIN_USER,
payload: request
};
}
export function auth() {
const request = axios.get(`${API_ENDPOINT}user/auth`, {
headers: {
'Authorization': `Bearer ${localStorage.getItem("token")}`
}
})
.then((response) => response.data)
.catch((error) => error.response.status);
return {
type: AUTH_USER,
payload: request
};
}
export function logoutUser() {
const request = axios.get(`${API_ENDPOINT}user/logout`)
.then((response) => response.data);
return {
type: LOGOUT_USER,
payload: request
};
}
export function addToCart(_idProduct) {
const request = axios.post(`${API_ENDPOINT}user/addToCart`, {productID: _idProduct}, {
headers: {
'Authorization': `Bearer ${localStorage.getItem("token")}`
}
})
.then((response) => response.data);
return {
type: ADD_TO_CART_USER,
payload: request
};
}
export function getCartItems() {
const request = axios.get(API_ENDPOINT + `/user/getUserCart`,{
headers: {
'Authorization': `Bearer ${localStorage.getItem("token")}`
}
})
.then((response) => {
console.log(response.data);
const cartItems = response.data.data;
return cartItems;
});
return {
type: GET_CART_ITEMS_USER,
payload: request
};
}
export function removeCartItem(id) {
const request = axios.get(`/api/users/removeFromCart?_id=${id}`)
.then((response) => {
response.data.cart.forEach((item) => {
response.data.cartDetail.forEach((k, i) => {
if (item.id === k._id) {
response.data.cartDetail[i].quantity = item.quantity;
}
});
});
return response.data;
});
return {
type: REMOVE_CART_ITEM_USER,
payload: request
};
}
export function onSuccessBuy(data) {
const request = axios.post(`${API_ENDPOINT}/user/successBuy`, data)
.then((response) => response.data);
return {
type: ON_SUCCESS_BUY_USER,
payload: request
};
}
| 1f98ad553ae846e7ab624b5c76928ad48013e824 | [
"JavaScript"
] | 2 | JavaScript | vn425282/TheStoreFrontEnd | f4416a53019a6829dec7481aa75b112b26f4cb5a | bc7a68e89c0b617e27d352c9e9cc3275aba91cc0 |
refs/heads/master | <repo_name>cheasocheat/hibernate-jpa<file_sep>/src/main/java/com/mobiecode/example/hibernatedemo/services/ContentService.java
package com.mobiecode.example.hibernatedemo.services;
import com.mobiecode.example.hibernatedemo.domain.Content;
import java.util.List;
/**
* Developer : cheasocheat
* Created on 2/20/18 10:35
*/
public interface ContentService {
Boolean saveContent(Content content);
Boolean saveContent2(Content content);
List<Content> getListOfContents();
List<Content> getListOfContents2();
List<Content> getListOfContents3();
List<Content> getListOfContents4();
}
<file_sep>/src/main/java/com/mobiecode/example/hibernatedemo/repository/impl/RoleRepositoryImpl.java
package com.mobiecode.example.hibernatedemo.repository.impl;
import com.mobiecode.example.hibernatedemo.domain.Role;
import com.mobiecode.example.hibernatedemo.repository.RoleRepository;
import com.mobiecode.example.hibernatedemo.utils.RecordStatus;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Developer : cheasocheat
* Created on 2/21/18 10:55
*/
@Repository
@Transactional
public class RoleRepositoryImpl implements RoleRepository {
@Autowired
private SessionFactory sessionFactory;
@Override
public void saveRole(Role role) {
try{
role.setCreatedAt(new Date());
role.setUpdatedAt(new Date());
role.setCreatedUser("Socheat");
role.setUpdatedUser("Socheat");
role.setStatus(RecordStatus.PUB);
sessionFactory.getCurrentSession().save(role);
System.out.println(role.getId());
}catch (HibernateException e){
e.printStackTrace();
}
}
@Override
public List<Role> getListRoles() {
try{
Session session = sessionFactory.getCurrentSession();
List<Role> lstRoles = session.createQuery("FROM Role").list();
return lstRoles;
}catch (HibernateException e){
e.printStackTrace();
}
return new ArrayList<>();
}
@Override
public Role getRoleById(Long id) {
try{
Session session = sessionFactory.getCurrentSession();
Role role = session.load(Role.class, id);
return role;
}catch (HibernateException e){
e.printStackTrace();
}
return null;
}
@Override
public boolean deleteRole(Long id) {
try{
Session session = sessionFactory.getCurrentSession();
Role role = session.load(Role.class, id);
if(role != null){
session.delete(role);
}
}catch (HibernateException e){
e.printStackTrace();
}
return false;
}
@Override
public boolean updateRole(Role role) {
try{
Session session = sessionFactory.getCurrentSession();
session.update(role);
}catch (HibernateException e){
e.printStackTrace();
}
return false;
}
}
<file_sep>/src/main/java/com/mobiecode/example/hibernatedemo/domain/BaseEntity.java
package com.mobiecode.example.hibernatedemo.domain;
import com.mobiecode.example.hibernatedemo.utils.RecordStatus;
import org.hibernate.annotations.Type;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.ZonedDateTime;
import java.util.Date;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseEntity {
protected Long id = null;
private RecordStatus status;
private Integer index;
private String createdUser;
private String updatedUser;
private Date createdAt;
private Date updatedAt;
public BaseEntity() {
}
@Transient
public abstract Long getId();
public void setId(Long id) {
this.id = id;
}
@Column(name = "rec_status")
@Enumerated(EnumType.STRING)
public RecordStatus getStatus() {
return status;
}
public void setStatus(RecordStatus status) {
this.status = status;
}
@Column(name = "rec_index")
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
@Column(name = "usr_created", nullable = false, length = 30)
public String getCreatedUser() {
return createdUser;
}
public void setCreatedUser(String createdUser) {
this.createdUser = createdUser;
}
@Column(name = "usr_updated", nullable = false, length = 30)
public String getUpdatedUser() {
return updatedUser;
}
public void setUpdatedUser(String updatedUser) {
this.updatedUser = updatedUser;
}
@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)//It converts the date and time values from Java Object to compatible database type and vice versa.
@LastModifiedDate
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
<file_sep>/src/main/java/com/mobiecode/example/hibernatedemo/domain/Content.java
package com.mobiecode.example.hibernatedemo.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
@Entity
@Table(name = "tb_content")
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true) // related to rest api
public class Content extends BaseEntity {
private String title;
private String titleEn;
private String description;
private String descriptionEn;
@Override
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "con_id", nullable = false, unique = true)
public Long getId() {
return id;
}
@Column(name = "con_title", nullable = false, length = 255)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "con_title_en")
public String getTitleEn() {
return titleEn;
}
public void setTitleEn(String titleEn) {
this.titleEn = titleEn;
}
@Column(name = "con_desc")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "con_desc_en")
public String getDescriptionEn() {
return descriptionEn;
}
public void setDescriptionEn(String descriptionEn) {
this.descriptionEn = descriptionEn;
}
}<file_sep>/src/test/java/com/mobiecode/example/hibernatedemo/HibernateDemoApplicationTests.java
package com.mobiecode.example.hibernatedemo;
import com.mobiecode.example.hibernatedemo.domain.Role;
import com.mobiecode.example.hibernatedemo.services.ContentService;
import com.mobiecode.example.hibernatedemo.services.RoleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
@RunWith(SpringRunner.class)
@SpringBootTest
public class HibernateDemoApplicationTests {
@Autowired
private ContentService contentService;
@Autowired
private RoleService roleService;
@Test
public void contextLoads() {
System.out.println("Hibernate Demo");
}
/**
* ROLE CRUD
*/
@Test
public void saveRole(){
Role role = new Role();
role.setCode("CODE1");
role.setName("NAME1");
roleService.saveRole(role);
}
@Test
public void deleteRole(){
roleService.deleteRole(15l);
}
@Test
public void updateRole(){
Role role = roleService.getRoleById(17l);
if(role != null){
role.setUpdatedAt(new Date());
role.setName("Gaga1");
}
roleService.updateRole(role);
}
/*@Test
public void saveContent(){
Content cont = new Content();
cont.setStatus(RecordStatus.PUB);
cont.setIndex(2);
cont.setTitle("Title");
cont.setTitleEn("Title");
cont.setDescription("Desc");
cont.setDescriptionEn("DescEn");
cont.setCreatedAt(new Date());
cont.setUpdatedAt(new Date());
cont.setCreatedUser("Reahoo");
cont.setUpdatedUser("Reahoo");
contentService.saveContent(cont);
}
@Test
public void saveContent2(){
Content cont = new Content();
cont.setStatus(RecordStatus.PUB);
cont.setIndex(2);
cont.setTitle("Title2");
cont.setTitleEn("Title2");
cont.setDescription("Desc2");
cont.setDescriptionEn("DescEn2");
cont.setCreatedAt(new Date());
cont.setUpdatedAt(new Date());
cont.setCreatedUser("Reahoo2");
cont.setUpdatedUser("Reahoo2");
contentService.saveContent2(cont);
}
*/
/*@Test
public void getContentWithCriteria() {
contentService.getListOfContents();
}
@Test
public void getContentTransaction() {
contentService.getListOfContents2();
}
@Test
public void getContentTransaction3() {
contentService.getListOfContents3();
}*/
}
| af4af4ef1c199672faa2c9b02ea786309f882ee9 | [
"Java"
] | 5 | Java | cheasocheat/hibernate-jpa | 8ad6e99c6429516fd2dd881561a2e85d52aaa7ee | 2b07cd5351e03069f59dc18a03f58db27c8c9626 |
refs/heads/master | <repo_name>andrewmilo/Diablo15<file_sep>/Item.h
#ifndef _ITEM_
#define _ITEM_
#include <string>
#include "Quality.h"
#include "Type.h"
class Item {
public:
Item( std::string, Quality, Type, bool );
std::string get_name( void ) const;
Quality get_quality( void ) const;
Type get_type( void ) const;
float get_durability( void ) const;
void set_name( std::string name );
void set_quality( Quality quality );
void set_type( Type type );
void set_durability( float );
private:
std::string name;
float durability;
bool soulbound;
Quality quality;
Type type;
};
#endif<file_sep>/Enemy.cpp
#include "Enemy.h"
Enemy::Enemy( void ){ }
Enemy::Enemy( Entity& enemy, int variance ){
this->strength = enemy.strength + variance;
this->dexterity = enemy.dexterity + variance;
this->vitality = enemy.vitality + variance;
this->intelligence = enemy.intelligence + variance;
}
Enemy::~Enemy( void ){ }<file_sep>/PlaneDND.cpp
#include "PlaneDND.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <sstream>
#include <stdlib.h>
#include <time.h>
PlaneDND::PlaneDND( void ) : SAVE_PATH( "save.txt" ){ welcome(); }
PlaneDND::~PlaneDND( void ){ delete hero; }
void PlaneDND::welcome( void ) const {
std::cout << std::endl
<< " ** **"
<< std::endl
<< " ** Welcome to Diablo 1.5. blizzardtm, lmao. **"
<< std::endl
<< " ** **"
<< std::endl;
}
void PlaneDND::start( void ){
srand (time(NULL));
get_hero();
choose_difficulty();
loop(); // gameplay loop
}
void PlaneDND::choose_difficulty( void ){
print_message( "Select a difficulty from 1-100", 2, 2 );
int d; cin >> d;
if( d > 0 && d < 101 ){
set_difficulty( d );
}
}
void PlaneDND::loop( void ){
std::string c;
while ( true ){
std::cout << "> ";
std::cin >> c;
if( c == "save" || c == "s" ) save();
else if( c == "pause" ) pause();
else if( c == "resume" ) resume();
else if( c == "quit" || c == "q" ) break;
else if( c == "stats" ) print_stats();
else if( c == "help" ) print_help();
else if( this->live ){ // gameplay physics/mechanics
const unsigned int level = this->hero->get_level();
const int level_range = 2;
// round event
round_event();
print_message( "Press Enter for next turn.", 1, 1 );
this->set_turn( this->get_turn() + 1 ); // next turn
}
}
}
void PlaneDND::round_event( void ){
int random_number = rand() % 3 + 1;
if( random_number == 1 ){ // Spawn a mob?
print_message( "mob spawn" );
} else if( random_number == 2 ){ // Empty round
print_message( "empty round" );
} else { // Find random item
print_message( "random item" );
}
}
inline void PlaneDND::toggle_game_state( void ){ this->live = !this->live; }
inline void PlaneDND::print_help( void ) const {
print_message( "Commands", 1, 1 );
std::cout << " save, s -- Saves the game. "
<< std::endl
<< " pause -- pauses the game. "
<< std::endl
<< " resume -- resumes the game. "
<< std::endl
<< " quit, q -- quits the game. "
<< std::endl
<< " stats -- displays the stats of the character. "
<< std::endl
<< " help -- displays help "
<< std::endl << std::endl;
}
inline void PlaneDND::pause( void ){
this->live = false;
print_message( "GAME PAUSED", 2, 2 );
}
inline void PlaneDND::resume( void ){
this->live = true;
print_message( "GAME RESUMED", 2, 2 );
}
void PlaneDND::print_message( const std::string msg,
int before=0,
int after=0 ) const {
while( before-->0 ){ std::cout << std::endl; }
std::cout << " ** [" + msg + "] **" << std::endl;
while( after-->0 ){ std::cout << std::endl; }
}
void PlaneDND::get_hero( void ){
// Try to De-serialize data
if( std::ifstream( SAVE_PATH ) )
de_serialize();
else create_hero();
}
inline void PlaneDND::print_stats( void ) const {
std::cout
<< std::endl
<< " name: " << this->hero->get_name()
<< std::endl
<< " class: " << static_cast<Hero::HeroClass>( this->hero->hero_class_id )
<< std::endl
<< " strength: " << this->hero->get_strength()
<< std::endl
<< " dexterity: " << this->hero->get_dexterity()
<< std::endl
<< " vitality: " << this->hero->get_vitality()
<< std::endl
<< " intelligence: " << this->hero->get_intelligence()
<< std::endl << std::endl;
}
void PlaneDND::create_hero(){
std::ofstream is( SAVE_PATH );
std::cout << " ** Enter a hero name: ";
std::string name;
std::getline( std::cin, name );
std::cout << " ** Enter a hero description: ";
std::string desc;
std::getline( std::cin, desc );
std::cout << std::endl;
std::cout << " ** Select a character. **" << std::endl;
std::cout << " [1] Barbarian." << std::endl;
std::cout << " [2] Assassin." << std::endl;
std::cout << " [3] Paladin." << std::endl;
std::cout << " [4] Druid." << std::endl;
std::cout << " [5] Necromancer." << std::endl;
std::cout << " [6] Sorceress." << std::endl;
std::cout << " [7] Amazon." << std::endl << std::endl;
int choice;
while( choice != 1
&& choice != 2
&& choice != 3
&& choice != 4
&& choice != 5
&& choice != 6
&& choice != 7 ){
std::cin >> choice;
}
Hero::HeroClass heroClass;
if( choice == 1 )
heroClass = Hero::BARBARIAN;
else if( choice == 2 )
heroClass = Hero::SORCERESS;
else if( choice == 3 )
heroClass = Hero::PALADIN;
else if( choice == 4 )
heroClass = Hero::NECROMANCER;
else if( choice == 5 )
heroClass = Hero::AMAZON;
else if( choice == 6 )
heroClass = Hero::DRUID;
else if( choice == 7 )
heroClass = Hero::ASSASSIN;
this->hero = new Hero( name, desc, choice, heroClass ); // construct the hero
}
void PlaneDND::de_serialize( void ){
std::ifstream infile( SAVE_PATH );
unsigned int level;
std::vector< std::string > v;
std::string line;
std::string temp;
while( std::getline( infile, line ) ){
v.push_back( line );
}
if( v.empty() ){
create_hero();
return;
}
// Get Hero Name
const std::string name = v[ 0 ];
print_message( "WELCOME BACK " + name, 1, 2 );
// Hero Description
const std::string desc = v[ 1 ];
print_message( desc, 0, 2 );
// Get Hero Class
const Hero::HeroClass cl = static_cast<Hero::HeroClass>( atoi( v[ 2 ].c_str() ) );
// Load stats
const unsigned int strength = atoi( v[ 3 ].c_str() );
const unsigned int dexterity = atoi( v[ 4 ].c_str() );
const unsigned int vitality = atoi( v[ 5 ].c_str() );
const unsigned int intelligence = atoi( v[ 6 ].c_str() );
this->hero = new Hero( name, desc, atoi( v[ 1 ].c_str() ), cl );
this->hero->set_strength( strength );
this->hero->set_dexterity( dexterity );
this->hero->set_vitality( vitality );
this->hero->set_intelligence( intelligence );
}
inline void PlaneDND::save( void ){
std::ofstream of( this->SAVE_PATH );
if( !this->hero ) return;
of << this->hero->get_name()
<< std::endl
<< this->hero->get_description()
<< std::endl
<< this->hero->hero_class_id
<< std::endl
<< this->hero->get_strength()
<< std::endl
<< this->hero->get_dexterity()
<< std::endl
<< this->hero->get_vitality()
<< std::endl
<< this->hero->get_intelligence();
print_message( "GAME SAVED", 2, 2 );
}
unsigned int PlaneDND::get_turn( void ) const { return this->turn; }
void PlaneDND::set_turn( unsigned int i ){ this->turn=i; }<file_sep>/src.cpp
#include "PlaneDND.h"
int main(){
// Create game
PlaneDND planeDND;
planeDND.start(); // start game
}<file_sep>/Hero.cpp
#include "Hero.h"
Hero::Hero( const std::string name,
const std::string desc,
const int id,
HeroClass heroclass ) : Entity( name, desc ), hero_class_id( id ){
this->level = 1;
this->strength = 5;
this->dexterity = 5;
this->intelligence = 5;
this->vitality = 5;
}
Hero::~Hero( void ){ }
Hero::HeroClass Hero::get_hero_class( void ) const { return this->hero_class; }<file_sep>/Type.h
#ifndef _TYPE_
#define _TYPE_
class Type {
public:
enum {
Weapon,
Armor,
Consumable
};
Type( void ) {}
~Type( void ) {}
};
#endif<file_sep>/Enemy.h
#ifndef _ENEMY_
#define _ENEMY_
class Enemy : public Entity {
public:
Enemy( void );
Enemy( Entity& enemy, int variance );
~Enemy( void );
private:
};
#endif<file_sep>/PlaneDND.h
#ifndef _PLANEDND_
#define _PLANEDND_
#include "Hero.h"
class PlaneDND {
private:
Hero* hero;
const char* SAVE_PATH;
volatile bool live;
unsigned int turn; // turn number
int difficulty;
public:
void welcome( void ) const;
void start( void );
void get_hero( void );
void de_serialize( void );
void create_hero( void );
void choose_difficulty( void );
void set_difficulty( int );
void round_event( void );
int get_difficulty( void );
unsigned int get_turn( void ) const;
void set_turn( unsigned int );
inline void save( void );
void loop( void );
inline void toggle_game_state( void );
inline void print_stats( void ) const;
inline void pause( void );
inline void resume( void );
void print_message( const std::string,
int,
int) const;
inline void print_help( void ) const;
PlaneDND();
~PlaneDND();
};
#endif<file_sep>/Entity.h
#ifndef _ENTITY_
#define _ENTITY_
#include <string>
class Entity {
protected:
Entity( const std::string,
const std::string );
std::string name;
std::string description;
unsigned int level;
float health;
int strength;
int dexterity;
int vitality;
int intelligence;
int positionX;
int positionY;
int orientation;
public:
virtual ~Entity( void );
std::string get_name( void ) const;
std::string get_description( void ) const;
unsigned int get_level( void ) const;
int get_strength( void ) const;
int get_dexterity( void ) const;
int get_vitality( void ) const;
int get_intelligence( void ) const;
int get_positionX( void ) const;
int get_positionY( void ) const;
int get_orientation( void ) const;
void set_strength( const int );
void set_dexterity( const int );
void set_vitality( const int );
void set_intelligence( const int );
void set_positionX( const int );
void set_positionY( const int );
void set_orientation( const int );
float damage( void ) const;
void attack( Entity& ) const;
void move( const int steps, const char direction );
};
#endif<file_sep>/Item.cpp
#include "Item.h"
Item::Item( std::string name, Quality quality, Type type, bool soulbound=0 ){
this->name = name;
this->durability = 100.0f;
this->quality = quality;
this->type = type;
this->soulbound = soulbound;
}
std::string Item::get_name( void ) const { return name; }
Type Item::get_type( void ) const { return this->type; }
Quality Item::get_quality( void ) const { return this->quality; }
void Item::set_name( std::string name ) { this->name = name; }
void Item::set_quality( Quality quality ){ this->quality = quality; }
void Item::set_type( Type type ) { this->type = type; }<file_sep>/Quality.h
#ifndef _QUALITY_
#define _QUALITY_
class Quality {
public:
enum {
White,
Gray,
Blue,
Yellow,
Gold,
Green
};
Quality( void ) {}
~Quality( void ) {}
};
#endif<file_sep>/Hero.h
#ifndef _HERO_
#define _HERO_
#include "Entity.h"
class Hero : public Entity {
public:
const int hero_class_id;
enum HeroClass {
BARBARIAN = 0,
ASSASSIN = 1,
PALADIN = 2,
DRUID = 3,
NECROMANCER = 4,
SORCERESS = 5,
AMAZON = 6
};
HeroClass get_hero_class( void ) const;
Hero( const std::string,
const std::string,
const int,
const HeroClass );
~Hero( void );
private:
HeroClass hero_class;
};
#endif<file_sep>/README.md
# Diablo 1.5
##### (Diablo 2 + Diablo 1) / 2
I'm intending this to be a computer console based game. Perhaps one day I'll consider adding some 1.5d graphics.
But in general, this is just a project to keep my programming skills limber.
<file_sep>/Entity.cpp
#include "Entity.h"
Entity::Entity( const std::string name,
const std::string desc ){
this->name = name;
this->health = 100.0f;
this->description = desc;
}
Entity::~Entity( void ){ }
std::string Entity::get_name( void ) const { return this->name; }
std::string Entity::get_description( void ) const { return this->description; }
unsigned int Entity::get_level( void ) const { return this->level; }
int Entity::get_strength( void ) const { return this->strength; }
int Entity::get_dexterity( void ) const { return this->dexterity; }
int Entity::get_vitality( void ) const { return this->vitality; }
int Entity::get_intelligence( void ) const { return this->intelligence; }
int Entity::get_positionX( void ) const { return this->positionX; }
int Entity::get_positionY( void ) const { return this->positionY; }
int Entity::get_orientation( void ) const { return this->orientation; }
void Entity::set_strength( const int strength ) { this->strength = strength; }
void Entity::set_dexterity( const int dexterity ) { this->dexterity = dexterity; }
void Entity::set_vitality( const int vitality ) { this->vitality = vitality; }
void Entity::set_intelligence( const int intelligence ) { this->intelligence = intelligence; }
void Entity::set_positionX( const int positionX ) { this->positionX = positionX; }
void Entity::set_positionY( const int positionY ) { this->positionY = positionY; }
void Entity::set_orientation( const int orientation ) { this->orientation = orientation; }
float Entity::damage( void ) const {
return this->dexterity
+ this->strength
+ this->intelligence
+ this->vitality;
}
void Entity::attack( Entity& other ) const {
other.health -= this->damage();
}
void Entity::move( const int steps, const char direction ){
//this->position +=
} | cb5b7d20daa60d7cb2693d1c0034c46f57737a23 | [
"Markdown",
"C++"
] | 14 | C++ | andrewmilo/Diablo15 | 6837e3b12de89ff281774e9dac38a26af8819db6 | 0c252b6a9152108ea31961ee3e7caaf67078bb65 |
refs/heads/master | <repo_name>NanoBytesInc/Remoto-HackISU<file_sep>/remote.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/php/'; // The path to the included php files
$title = "Remote"; // The page/navigation bar title
$index2 = "active"; // Set the first index in the navigation to 'active'
// Include the database access variables
include $path.'__db.php';
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Read all of the recipients from the database
$sql = "SELECT * FROM buttons";
$result = $conn->query($sql);
$conn->close();
// Kill the page if nobody is found, it should not happen in our demos
//if ($result->num_rows == 0)
// die("No Games Found");
?>
<html>
<head>
<?php include $path.'__head.php'; ?> <!-- Include the global document header -->
<!-- Holds the buttons on the bottom -->
<style>
body {
display: flex;
min-height: 100vh;
flex-direction: column;
}
main {
flex: 1 0 auto;
}
</style>
</head>
<body>
<header>
<?php include $path.'__js.php'; ?> <!-- Load the Javascript Libraries -->
<script type="text/javascript" src="http://code.jquery.com/color/jquery.color-2.1.2.js"></script>
<script>
function send_command(command) {
$.get("/api/add_command.php?command="+command, function(data, status){
//alert("Data: " + data + "\nStatus: " + status);
});
}
function reset() {
for(i = 0; i < 6; i++){
$('#button'+(i+1).toString()).offset({ top: 0, left: 0});
}
}
$(document).ready(function(){
reset();
$('#lefthand').fadeOut(0);
});
function move_left() {
reset();
var bottom = $(window).height() - $('#navbar').height()-20;
var margin = $('#leftbutton').offset().left;
for(i = 0; i < 6; i++){
$('#button'+(i+1).toString()).offset({ top: bottom-((Math.sin((Math.PI/2)*(i/5)))*300), left: margin+(Math.cos((Math.PI/2)*(i/5))*200) });
}
}
function move_right() {
reset();
var margin = $('#rightbutton').offset().left;
var bottom = $(window).height() - $('#navbar').height()-20;
for(i = 0; i < 6; i++){
$('#button'+(i+1).toString()).offset({ top: bottom-((Math.sin((Math.PI/2)*(i/5)))*300), left: -(Math.cos((Math.PI/2)*(i/5))*200)+margin });
}
}
var left_visible = false;
function left_hand() {
if(left_visible == false) {
move_left();
$('.hideme').fadeTo("slow" , 0.1)
$('.hideleft').fadeTo("slow" , 0.1)
$('#lefthand').fadeTo("slow" , 1)
$('footer').animate({backgroundColor: "#BBBBBB"});
$('body').animate({backgroundColor: "#BBBBBB"});
} else {
$('.hideme').fadeTo("slow" , 1)
$('.hideleft').fadeTo("slow" , 1)
$('#lefthand').fadeTo("slow" , 0)
$('footer').animate({backgroundColor: "#FF"});
$('body').animate({backgroundColor: "#FF"});
}
left_visible = !left_visible;
}
var right_visible = false;
function right_hand() {
if(right_visible == false) {
move_right();
$('.hideme').fadeTo("slow" , 0.1)
$('.hideright').fadeTo("slow" , 0.1)
$('#lefthand').fadeTo("slow" , 1)
$('footer').animate({backgroundColor: "#BBBBBB"});
$('body').animate({backgroundColor: "#BBBBBB"});
} else {
$('.hideme').fadeTo("slow" , 1)
$('.hideright').fadeTo("slow" , 1)
$('#lefthand').fadeTo("slow" , 0)
$('footer').animate({backgroundColor: "#FF"});
$('body').animate({backgroundColor: "#FF"});
}
right_visible = !right_visible;
}
</script>
</header>
<nav id="navbar">
<?php include $path.'__navbar.php'; ?> <!-- Load the navigation bar -->
</nav>
<main>
<div id="lefthand"><!-- Left hand buttons -->
<a id="button6" class="btn-floating btn-large waves-effect waves-light red lighten-4 hoverable">
<i class="material-icons black-text">power_settings_new</i>
</a>
<a id="button5" class="btn-floating btn-large waves-effect waves-light yellow lighten-4 hoverable">
<i class="material-icons black-text">volume_off</i>
</a>
<a id="button4" class="btn-floating btn-large waves-effect waves-light green lighten-4 hoverable">
<i class="material-icons black-text">volume_up</i>
</a>
<a id="button3" class="btn-floating btn-large waves-effect waves-light blue lighten-4 hoverable">
<i class="material-icons black-text">volume_down</i>
</a>
<a id="button2" class="btn-floating btn-large waves-effect waves-light purple lighten-4 hoverable">
<i class="material-icons black-text">expand_less</i>
</a>
<a id="button1" class="btn-floating btn-large waves-effect waves-light orange lighten-4 hoverable">
<i class="material-icons black-text">expand_more</i>
</a>
</div>
</main>
<footer style="background-color: white" class="page-footer">
<div class="container">
<div class="hideme"> <!-- Main Buttons -->
<div class="row">
<div class="col s6 right-align">
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<a class="remote-button btn-floating btn-large waves-effect waves-light yellow lighten-4 hoverable"
onclick="send_command('10108877')">
<i class="material-icons"><?php echo $row['icon']; ?></i>
</a>
<?php
}
}
?>
</div>
</div>
</div>
<div> <!-- Bottom Row Buttons -->
<div class="row">
<div class="col s3 left-align hideright">
<a class="btn-floating btn-large waves-effect waves-light grey hoverable" id="leftbutton" onclick="left_hand()">
<i class="left-hand material-icons">pan_tool</i>
</a>
</div>
<div class="col s5 center-align hideme">
<a class="btn-floating btn-large waves-effect waves-light blue-grey lighten-1">
<i class="material-icons">add</i>
</a>
<a class="btn-floating btn-large waves-effect waves-light blue-grey lighten-1">
<i class="material-icons">clear</i>
</a>
</div>
<div class="col s4 right-align hideleft">
<a class="btn-floating btn-large waves-effect waves-light grey" id="rightbutton" onclick="right_hand()">
<i class="material-icons">pan_tool</i>
</a>
</div>
</div>
</div>
</div>
</footer>
</body>
</html><file_sep>/login.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/php/'; // The path to the included php files
$title = "Template"; // The page/navigation bar title
$index1 = "active"; // Set the first index in the navigation to 'active'
// Include the database access variables
include $path.'__db.php';
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Read all of the recipients from the database
$sql = "SELECT name FROM games";
$result = $conn->query($sql);
$conn->close();
// Kill the page if nobody is found, it should not happen in our demos
//if ($result->num_rows == 0)
// die("No Games Found");
?>
<html>
<head>
<?php include $path.'__head.php'; ?> <!-- Include the global document header -->
</head>
<body>
<header>
<?php include $path.'__js.php'; ?> <!-- Load the Javascript Libraries -->
</header>
<nav>
<?php include $path.'__navbar.php'; ?> <!-- Load the navigation bar -->
</nav>
<main>
<div class="row">
<!-- This is the sample card dimensions-->
<div class='col s12 m10 offset-m1 l6 offset-l3'>
<div style="margin-top: 50%;" class="row center-align">
<div class="card-content white-text">
<div class="row">
<a style="width:90%;" class=" blue darken-1 waves-effect waves-light btn " href="index.php">
<div class="row">
<div style="margin-top:5px;" class="col s1 left">
<img style="height:25px; width:25px;" src="../images/facebook-icon.svg" alt="Kiwi standing on oval">
</div>
<div class="col s6 offset-s2">
FACEBOOK
</div>
</div>
</a>
</div>
<div class="row">
<a style="width:90%;" class=" red darken-1 waves-effect waves-light btn" href="index.php">
<div class="row">
<div style="margin-top:5px;" class="col s1 left">
<img style="height:25px; width:25px;" src="../images/google-plus.svg" alt="Kiwi standing on oval">
</div>
<div class="col s6 offset-s2">
GOOGLE+
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<!-- End of card -->
</div>
</main>
</body>
</html><file_sep>/api/add_button.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/php/'; // The path to the included php files
// Include the database access variables
include $path.'__db.php';
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Read all of the recipients from the database
$sql = "
INSERT INTO buttons (user_id, icon, color)
VALUES ('1', '{$_GET['icon']}','{$_GET['color']}')
";
$result = $conn->query($sql);
$place = 0;
$id = mysql_insert_id();
$seq = $_GET['seq'];
$seq = explode(' ', $seq);
foreach ($seq as &$command) {
$sql = "
INSERT INTO sequences (button_id, code, placement)
VALUES ('{$id}', '{$command}','{$place}')
";
$result = $conn->query($sql);
$place++;
}
$conn->close();
?><file_sep>/add_button.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/php/'; // The path to the included php files
$title = "Add Button"; // The page/navigation bar title
$index3 = "active"; // Set the first index in the navigation to 'active'
// Include the database access variables
include $path.'__db.php';
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Read all of the recipients from the database
// Kill the page if nobody is found, it should not happen in our demos
//if ($result->num_rows == 0)
// die("No Games Found");
?>
<html>
<head>
<?php include $path.'__head.php'; ?> <!-- Include the global document header -->
<!-- Holds the buttons on the bottom -->
<style>
body {
display: flex;
min-height: 100vh;
flex-direction: column;
}
main {
flex: 1 0 auto;
}
</style>
</head>
<body>
<header>
<?php include $path.'__js.php'; ?> <!-- Load the Javascript Libraries -->
<script type="text/javascript" src="http://code.jquery.com/color/jquery.color-2.1.2.js"></script>
<script>
var sequence = "";
$(document).ready(function(){
$.get("/api/add_command.php?command=1", function(data, status){
//alert("Data: " + data + "\nStatus: " + status);
});
$('.modal').modal();
$('.carousel').carousel();
setInterval(readSignal, 200);
});
function send() {
ico = $("#demo").html()
col = $("#demo").css("background-color")
url = "?icon="+ico+"&color="+col+"&seq="+sequence
$.get("/api/add_button.php"+url, function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
}
function readSignal() {
$.get("/api/get_signal.php", function(data, status){
if(data != "") {
if(sequence == "") {
$("#tags").html("");
$("#done").removeClass("disabled");
}
$("#tags").append("<div class='chip'>0x"+data+"</div>");
sequence += data + " ";
}
});
}
function icon(ico) {
$("#demo").html(ico.innerHTML);
$('.modal').modal('close');
}
function color(obj) {
$("#demo").css("background-color", window.getComputedStyle(obj).backgroundColor);
}
</script>
</header>
<nav id="navbar">
<?php include $path.'__navbar.php'; ?> <!-- Load the navigation bar -->
</nav>
<main>
<div class="row center-align">
<div class="col s12 m10 offset-m1 l6 offset-l3 ">
<div class="card ">
<div class="card-content black-text">
<div class="row">
<div class="col s12">
<span class="flow-text">Select an Icon</span>
</div>
</div>
<div class="row">
<div class="col s12">
<a class="icon-trigger remote-button btn-floating btn-large waves-effect waves-light white lighten-4 hoverable"
href="#iconlist">
<i id="demo" class="material-icons">blur_on</i>
</a>
</div>
</div>
</div>
</div>
<div class="card ">
<div class="card-content black-text">
<div class="row">
<div class="col s12">
<span class="flow-text">Select a Color</span>
</div>
</div>
<div class="row">
<div class="col s12">
<div class="carousel" style="height:150px !important">
<a onclick="color(this)" class="carousel-item white lighten-4"><p></p></a>
<a onclick="color(this)" class="carousel-item red lighten-4"><p></p></a>
<a onclick="color(this)" class="carousel-item green lighten-4"><p></p></a>
<a onclick="color(this)" class="carousel-item blue lighten-4"><p></p></a>
<a onclick="color(this)" class="carousel-item yellow lighten-4"><p></p></a>
<a onclick="color(this)" class="carousel-item purple lighten-4"><p></p></a>
<a onclick="color(this)" class="carousel-item amber lighten-4"><p></p></a>
<a onclick="color(this)" class="carousel-item orange lighten-4"><p></p></a>
<a onclick="color(this)" class="carousel-item teal lighten-4"><p></p></a>
</div>
</div>
</div>
</div>
</div>
<div class="card ">
<div class="card-content black-text">
<div class="row">
<div class="col s12">
<span class="flow-text">Button Pattern</span>
</div>
</div>
<div class="row">
<div class="col s12">
<div id="tags"><span style="color: red">Point your controler at the remoto and press a button</span></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col s12 center-align">
<a id="done" onclick="send()" class="btn-floating blue-grey disabled hoverable"><i class="material-icons">send</i></a>
</div>
</div>
</div>
</main>
<div id="iconlist" class="modal bottom-sheet">
<div class="modal-content">
<div class="row">
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">blur_on</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">add_to_photos</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">hotel</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">hot_tub</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">whatshot</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">copyright</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">donut_large</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">eject</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">done</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">settings_overscan</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">settings_power</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">work</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">error</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">games</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">mic</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">movie</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">pause</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">graphic_eq</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">snooze</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">stop</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">volume_off</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">undo</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">battery_charging_full</i></div>
<div class="col s3 m2 l1"><i onclick="icon(this)" class="material-icons icon">dvr</i></div>
</div>
</div>
<div class="modal-footer">
<a class="modal-action modal-close waves-effect waves-green btn-flat hoverable">Agree</a>
</div>
</div>
</body>
</html><file_sep>/php/_remoto-connected.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/php/'; // The path to the included php files
$title = "Template"; // The page/navigation bar title
$index1 = "active"; // Set the first index in the navigation to 'active'
$arr = array();
$now;
// Include the database access variables
include $path.'__db.php';
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
$sql = "SELECT id, inputTime, now() as now FROM logs";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
// echo "id: ".$row["id"]." - inputTime: ".$row["inputTime"]." now: ".$row["now"]."<br>";
$now = new DateTime($row['now']);
$date = new DateTime($row['inputTime']);
if(count($arr)<0){
$arr = [$date];
} else {
array_push($arr, $date);
}
}
foreach ($arr as $time) {
echo ' </br> ---Time: '.$time->format('H:i:s') .' Now: '.$now->format('H:i:s').'.';
// echo 'time in foreach loop: '.date_format($now, 'Y-m-d H:i:s');
$interval = date_diff($now, $time,true);
$interval_dif = ((int)$interval->format('%i')*3600) + (int)$interval->format('%m')*60 + (int)$interval->format('%s');
//echo 'Type of interval: '. gettype($interval).'end';
//print_r($interval_dif);
if($interval_dif > 5) echo ' More than 5 seconds';
# code...
}
} else {
echo "0 results";
}
$conn->close();
?><file_sep>/api/get_signal.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/php/'; // The path to the included php files
// Include the database access variables
include $path.'__db.php';
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Read all of the recipients from the database
$sql = "SELECT * FROM receiver";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$sql = "DELETE FROM receiver WHERE id={$row['id']}";
$result = $conn->query($sql);
echo $row["command"];
}
$conn->close();
// Kill the page if nobody is found, it should not happen in our demos
//if ($result->num_rows == 0)
// die("No Games Found");
?>
<file_sep>/api/add_signal.php
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/php/'; // The path to the included php files
// Include the database access variables
include $path.'__db.php';
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Read all of the recipients from the database
$sql = "
INSERT INTO receiver (command)
VALUES ('{$_GET['command']}')
";
$result = $conn->query($sql);
$conn->close();
echo "Added - [".$_GET['command']."]";
// Kill the page if nobody is found, it should not happen in our demos
//if ($result->num_rows == 0)
// die("No Games Found");
?>
<file_sep>/database.sql
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Feb 25, 2017 at 04:57 PM
-- Server version: 10.1.13-MariaDB
-- PHP Version: 5.5.37
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!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 utf8mb4 */;
--
-- Database: `hackisu`
--
-- --------------------------------------------------------
--
-- Table structure for table `buttons`
--
CREATE TABLE `buttons` (
`button_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`icon` text NOT NULL,
`color` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `buttons`
--
INSERT INTO `buttons` (`button_id`, `user_id`, `icon`, `color`) VALUES
(3, 1, 'eject', 'rgb(255, 205, 210)'),
(4, 1, 'volume_off', 'rgb(178, 223, 219)');
-- --------------------------------------------------------
--
-- Table structure for table `commands`
--
CREATE TABLE `commands` (
`id` int(11) NOT NULL,
`command` text NOT NULL,
`device_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `commands`
--
INSERT INTO `commands` (`id`, `command`, `device_id`) VALUES
(173, '1', 0),
(174, '1', 0),
(175, '1', 0),
(176, '1', 0),
(177, '1', 0),
(178, '1', 0),
(179, '1', 0),
(180, '1', 0),
(181, '1', 0),
(182, '1', 0),
(183, '1', 0),
(184, '1', 0),
(185, '1', 0),
(186, '1', 0),
(187, '1', 0),
(188, '1', 0),
(189, '1', 0),
(190, '1', 0),
(191, '1', 0),
(192, '1', 0),
(193, '1', 0),
(194, '1', 0),
(195, '1', 0),
(196, '1', 0),
(197, '1', 0),
(198, '1', 0),
(199, '1', 0),
(200, '1', 0),
(201, '1', 0),
(202, '1', 0),
(203, '1', 0),
(204, '1', 0),
(205, '1', 0),
(206, '1', 0),
(207, '1', 0),
(208, '1', 0),
(209, '1', 0),
(210, '1', 0),
(211, '1', 0),
(212, '1', 0),
(213, '1', 0),
(214, '1', 0),
(215, '1', 0),
(216, '1', 0),
(217, '1', 0),
(218, '1', 0),
(219, '1', 0),
(220, '1', 0),
(221, '1', 0),
(222, '1', 0),
(223, '1', 0),
(224, '1', 0),
(225, '1', 0),
(226, '1', 0),
(227, '1', 0),
(228, '1', 0),
(229, '1', 0),
(230, '1', 0),
(231, '1', 0),
(232, '1', 0),
(233, '1', 0),
(234, '1', 0),
(235, '1', 0),
(236, '1', 0),
(237, '1', 0),
(238, '1', 0),
(239, '1', 0),
(240, '1', 0),
(241, '1', 0),
(242, '1', 0),
(243, '1', 0),
(244, '1', 0),
(245, '1', 0),
(246, '1', 0),
(247, '1', 0),
(248, '1', 0),
(249, '1', 0),
(250, '1', 0),
(251, '1', 0),
(252, '1', 0),
(253, '1', 0),
(254, '1', 0),
(255, '1', 0),
(256, '1', 0),
(257, '1', 0),
(258, '1', 0),
(259, '1', 0),
(260, '1', 0),
(261, '1', 0),
(262, '1', 0),
(263, '1', 0),
(264, '1', 0),
(265, '1', 0),
(266, '1', 0),
(267, '1', 0),
(268, '1', 0),
(269, '1', 0),
(270, '1', 0),
(271, '1', 0),
(272, '1', 0),
(273, '1', 0),
(274, '1', 0),
(275, '1', 0),
(276, '1', 0),
(277, '1', 0),
(278, '1', 0),
(279, '1', 0),
(280, '1', 0),
(281, '1', 0),
(282, '1', 0),
(283, '1', 0),
(284, '1', 0),
(285, '1', 0),
(286, '1', 0),
(287, '1', 0),
(288, '1', 0),
(289, '1', 0),
(290, '1', 0),
(291, '1', 0),
(292, '1', 0),
(293, '1', 0),
(294, '1', 0),
(295, '1', 0),
(296, '1', 0),
(297, '1', 0),
(298, '1', 0),
(299, '1', 0),
(300, '1', 0),
(301, '1', 0),
(302, '1', 0),
(303, '1', 0),
(304, '1', 0),
(305, '1', 0),
(306, '1', 0),
(307, '1', 0),
(308, '1', 0),
(309, '1', 0),
(310, '1', 0),
(311, '1', 0),
(312, '1', 0),
(313, '1', 0),
(314, '1', 0),
(315, '1', 0),
(316, '1', 0),
(317, '1', 0),
(318, '1', 0),
(319, '1', 0),
(320, '1', 0),
(321, '1', 0),
(322, '1', 0),
(323, '1', 0),
(324, '1', 0),
(325, '1', 0),
(326, '1', 0),
(327, '1', 0),
(328, '1', 0),
(329, '1', 0),
(330, '1', 0),
(331, '1', 0),
(332, '1', 0),
(333, '1', 0),
(334, '1', 0),
(335, '1', 0),
(336, '1', 0),
(337, '1', 0),
(338, '1', 0),
(339, '1', 0),
(340, '1', 0),
(341, '1', 0),
(342, '1', 0),
(343, '1', 0),
(344, '1', 0),
(345, '1', 0),
(346, '1', 0),
(347, '1', 0),
(348, '1', 0),
(349, '1', 0),
(350, '1', 0),
(351, '1', 0),
(352, '1', 0),
(353, '1', 0),
(354, '1', 0),
(355, '1', 0),
(356, '1', 0),
(357, '1', 0),
(358, '1', 0),
(359, '1', 0),
(360, '1', 0),
(361, '1', 0),
(362, '1', 0),
(363, '1', 0),
(364, '1', 0),
(365, '1', 0),
(366, '1', 0),
(367, '1', 0),
(368, '1', 0),
(369, '1', 0),
(370, '1', 0),
(371, '1', 0),
(372, '1', 0),
(373, '1', 0),
(374, '1', 0),
(375, '1', 0),
(376, '1', 0),
(377, '1', 0),
(378, '1', 0),
(379, '1', 0),
(380, '1', 0),
(381, '1', 0),
(382, '1', 0),
(383, '1', 0),
(384, '1', 0),
(385, '1', 0),
(386, '1', 0),
(387, '1', 0),
(388, '1', 0),
(389, '1', 0),
(390, '1', 0),
(391, '1', 0),
(392, '1', 0),
(393, '1', 0),
(394, '1', 0),
(395, '1', 0),
(396, '1', 0),
(397, '1', 0),
(398, '1', 0),
(399, '1', 0),
(400, '1', 0),
(401, '1', 0),
(402, '1', 0),
(403, '1', 0),
(404, '1', 0),
(405, '1', 0),
(406, '1', 0);
-- --------------------------------------------------------
--
-- Table structure for table `receiver`
--
CREATE TABLE `receiver` (
`id` int(11) NOT NULL,
`command` text NOT NULL,
`device_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `sequences`
--
CREATE TABLE `sequences` (
`id` int(11) NOT NULL,
`button_id` int(11) NOT NULL,
`code` text NOT NULL,
`placement` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `sequences`
--
INSERT INTO `sequences` (`id`, `button_id`, `code`, `placement`) VALUES
(31, 0, '101050af', 0),
(32, 0, '101050af', 1),
(33, 0, '101050af', 2),
(34, 0, '101050af', 3),
(35, 0, '101050af', 4),
(36, 0, '101050af', 5),
(37, 0, '101050af', 6),
(38, 0, '101050af', 7),
(39, 0, '101050af', 8),
(40, 0, '1010d02f', 0),
(41, 0, '1010d02f', 1),
(42, 0, '1010d02f', 2),
(43, 0, '1010d02f', 3),
(44, 0, '1010d02f', 4),
(45, 0, '1010d02f', 5),
(46, 0, '1010d02f', 6),
(47, 0, '1010d02f', 7);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `buttons`
--
ALTER TABLE `buttons`
ADD PRIMARY KEY (`button_id`);
--
-- Indexes for table `commands`
--
ALTER TABLE `commands`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `receiver`
--
ALTER TABLE `receiver`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `sequences`
--
ALTER TABLE `sequences`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `buttons`
--
ALTER TABLE `buttons`
MODIFY `button_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `commands`
--
ALTER TABLE `commands`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=407;
--
-- AUTO_INCREMENT for table `receiver`
--
ALTER TABLE `receiver`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=98;
--
-- AUTO_INCREMENT for table `sequences`
--
ALTER TABLE `sequences`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=48;
/*!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 */;
| 4d704110d138da711b20afbdd9c1122083ae1eb7 | [
"SQL",
"PHP"
] | 8 | PHP | NanoBytesInc/Remoto-HackISU | c3d53827532c346688a041c96a095fdc8696c3c9 | 4f7eef3d2491225518e5f1f8159ca446b15feb85 |
refs/heads/master | <file_sep>from flask import Flask, render_template, request
import json, os, pickle
#from pickleFuncs import postPickle, getPickle
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
environment = 'prod'
if environment == 'dev':
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
else:
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URI')
db = SQLAlchemy(app)
class JSONmodelObject(db.Model):
id = db.Column(db.Integer, primary_key = True)
JSONinDB = db.Column(db.String(1000))
@app.route('/')
def main_infographic():
return render_template('index.html')
@app.route('/auth', methods = ['POST'])
def auth():
JSON_sent = request.get_json()
password = <PASSWORD>('Bridge<PASSWORD>')
if JSON_sent['password'] == password:
return json.dumps('1')
else:
return json.dumps('0')
return json.dumps('1')
@app.route('/getPostPickle', methods = ['GET', 'POST'])
def pickle():
if request.method == 'POST':
JSON_sent = request.get_json()
dbJSONresult = JSONmodelObject.query.first()
dbJSONresult.JSONinDB = json.dumps(JSON_sent)
db.session.add(dbJSONresult)
db.session.commit()
return json.dumps(request.get_json())
if request.method == 'GET':
dbJSONresult = JSONmodelObject.query.first()
return dbJSONresult.JSONinDB
if __name__ == '__main__':
app.run(debug=True)<file_sep>import pickle
from datetime import datetime, timedelta
def initPickle():
infoPickle = {"students":{"numOfStu":80,"gradRate6yr":89,"gradRate4yr":65,"firstGenCollege":30,'hoursMentoring':40},'info':{},'stats':{}}
pickling_on = open("infographicPickle.pickle","wb")
pickle.dump(infoPickle, pickling_on)
pickling_on.close()
def seePickle():
pickle_off = open("infographicPickle.pickle", 'rb')
newPickle = pickle.load(pickle_off)
print(newPickle)
pickle_off.close()
def getPickle():
pickle_off = open("infographicPickle.pickle", 'rb')
newPickle = pickle.load(pickle_off)
pickle_off.close()
return newPickle
def postPickle(newJSON):
pickling_on = open("infographicPickle.pickle","wb")
pickle.dump(newJSON, pickling_on)
pickling_on.close()
# def decrementTodaysTreat():
# pickle_off = open("treatPickle.pickle", 'rb')
# newTreatPickle = pickle.load(pickle_off)
# newTreatPickle['treatsGivenToday'] += 1
# pickle_off.close()
# pickling_on = open("treatPickle.pickle","wb")
# pickle.dump(newTreatPickle, pickling_on)
# pickling_on.close()
# def canDispenseTreat():
# pickle_off = open("treatPickle.pickle", 'rb')
# newTreatPickle = pickle.load(pickle_off)
# pickle_off.close()
# dateLast = datetime.strptime(newTreatPickle['lastDate'], '%Y-%m-%d')
# dateToday =datetime.strptime(str(datetime.now().date()),'%Y-%m-%d')
# if dateToday.timestamp() > dateLast.timestamp():
# newTreatPickle['lastDate'] = str(datetime.now().date())
# newTreatPickle["treatsGivenToday"] = 0
# pickling_on = open("treatPickle.pickle","wb")
# pickle.dump(newTreatPickle, pickling_on)
# pickling_on.close()
# if newTreatPickle["treatsGivenToday"] <= newTreatPickle['maxNumOfTreatsPerDay']:
# return True
# else:
# return False
# def waitForTreats(newPickle):
# for i in range(len(newPickle["scheduledDispenseTreats"])):
# scheduleTime = newPickle["scheduledDispenseTreats"][i]['time'].split(':')
# dispenseTime = datetime(newPickle["scheduledDispenseTreats"][i]['scheduledDate'][0],newPickle["scheduledDispenseTreats"][i]['scheduledDate'][1],newPickle["scheduledDispenseTreats"][i]['scheduledDate'][2],int(scheduleTime[0]),int(scheduleTime[1]))
# dateTimeNow = datetime.now()
# if newPickle["scheduledDispenseTreats"][i]['freq'] == 'Tomorrow':
# dispenseTime =+ timedelta(days=1)
# diff = dispenseTime.timestamp() - dateTimeNow.timestamp()
# if diff > 0:
# time.sleep(diff)
# dispenseTreat()
# def initVideoPickle():
# video = {"videoNumber":0,"videoPaths":[]}
# pickling_on = open("videoPickle.pickle","wb")
# pickle.dump(video, pickling_on)
# pickling_on.close()
# def seeVideoPickle():
# pickle_off = open("videoPickle.pickle", 'rb')
# newVideoPickle = pickle.load(pickle_off)
# print(newVideoPickle)
# pickle_off.close()
# def initTouchPickle():
# treatPickle = {"singleton":0}
# pickling_on = open("touchPickle.pickle","wb")
# pickle.dump(treatPickle, pickling_on)
# pickling_on.close()
# def getTouchPickle():
# pickle_off = open("touchPickle.pickle", 'rb')
# newTouchPickle = pickle.load(pickle_off)
# pickle_off.close()
# return newTouchPickle["singleton"]
# def setTouchPickle(value):
# pickle_off = open("touchPickle.pickle", 'rb')
# newTouchPickle = pickle.load(pickle_off)
# newTouchPickle['singleton'] = value
# pickle_off.close()
# pickling_on = open("touchPickle.pickle","wb")
# pickle.dump(newTouchPickle, pickling_on)
# pickling_on.close()<file_sep>import './App.css';
import bridgeBuildersLogo from './bridgeBuildersLetterHeadLogo.png'
import Home from './Components/Home'
import Admin from './Components/Admin'
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
function App() {
return (
<Router>
<div>
<div className="infographicBlock">
<Switch>
<Route path="/admin">
<Admin />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</div>
</Router>
);
}
export default App;
<file_sep>import React, {useEffect, useState} from "react";
import '../App.css';
import {
BrowserRouter as Router,
Switch,
Route,
Redirect
} from "react-router-dom";
function AddData() {
const axios = require('axios').default;
const [pickle, setPickle] = useState({})
const [redirectHome, setRedirectHome] = useState(false)
useEffect(() => {
axios.get('/getPostPickle')
.then(function (response) {
setPickle(response.data)
})
},[])
const handlePickleSubmit = (e) => {
e.preventDefault();
axios.post('/getPostPickle', pickle)
.then(function (response) {
setRedirectHome(true)
})
}
const setNumberOfStudentsHandler = (e) => {
const newPickle = {...pickle}
newPickle['students']['numOfStu'] = parseInt(e.target.value)
setPickle(newPickle)
}
const setGradRate6yrHandler = (e) => {
const newPickle = {...pickle}
newPickle['students']['gradRate6yr'] = parseInt(e.target.value)
setPickle(newPickle)
}
const setGradRate4yrHandler = (e) => {
const newPickle = {...pickle}
newPickle['students']['gradRate4yr'] = parseInt(e.target.value)
setPickle(newPickle)
}
const setFirstGenCollegeHandler = (e) => {
const newPickle = {...pickle}
newPickle['students']['firstGenCollege'] = parseInt(e.target.value)
setPickle(newPickle)
}
const setHoursMentoringHandler = (e) => {
const newPickle = {...pickle}
newPickle['students']['hoursMentoring'] = parseInt(e.target.value)
setPickle(newPickle)
}
console.log(redirectHome)
return (
<div>
{redirectHome ?
<div>
<Redirect to="/home" />
</div>
:
<div className="infographicBlock">
<div className="flexContainer">
<div className="flexside"></div>
<div className="flexpassword">
<form onSubmit={handlePickleSubmit}>
<div class="form-group row">
<div class="col-sm-10">
<label for="numberOfStudents">Number of Students:</label>
<input class="form-control" id="numberOfStudents" type="text" onChange={setNumberOfStudentsHandler} name="numberOfStudents"/>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<label for="gradRate6yr">Six Year Grad Rate:</label>
<input class="form-control" id="gradRate6yr" type="text" onChange={setGradRate6yrHandler} name="gradRate6yr"/>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<label for="gradRate4yr">Four Year Grad Rate:</label>
<input class="form-control" id="gradRate4yr" type="text" onChange={setGradRate4yrHandler} name="gradRate4yr"/>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<label for="firstGenCollege">First Gen College %:</label>
<input class="form-control" id="firstGenCollege" type="text" onChange={setFirstGenCollegeHandler} name="firstGenCollege"/>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<label for="hoursMentoring">Hours Mentoring:</label>
<input class="form-control" id="hoursMentoring" type="text" onChange={setHoursMentoringHandler} name="hoursMentoring"/>
</div>
</div>
<div class="form-group row">
<input type="submit" class="btn btn-dark" value="Submit"/>
</div>
</form>
</div>
<div className="flexside"></div>
</div>
</div>
}
</div>
)
}
export default AddData | 16ee64e76b926b3440101e86eef4b80335ae52f4 | [
"JavaScript",
"Python"
] | 4 | Python | jande48/BridgeBuildersInfographic | b4e17a95512d62ff915a4ad8aca7f4e4dcb04036 | 41d47ae0e97a54c8c06e68c80fbf809100d64c4f |
refs/heads/master | <repo_name>IgnatZakalinsky/neko-authorization-module<file_sep>/src/neko-2-features/f-1-authorization/a-4-set-new-pass/s-2-bll/b-1-callbacks/useSetNewPassContainerLogic.ts
import {useDispatch} from "react-redux";
import {useBooleanSelector} from "../../../../f-3-common/c-1-boolean-reducer/useBooleanSelectors";
import {SET_NEW_PASS_ACTION_NAMES} from "../b-2-redux/setNewPassActions";
import {useSetNewPassLocalState} from "./useSetNewPassLocalState";
import {setNewPassCallback} from "./setNewPassCallBacks";
export const useSetNewPassContainerLogic = (token: string) => {
// redux
const [loading, error, success] = useBooleanSelector(SET_NEW_PASS_ACTION_NAMES);
const dispatch = useDispatch();
// local state
const {
password1, setPassword1Callback,
password2, setPassword2Callback,
redirect, setRedirect,
} = useSetNewPassLocalState(dispatch);
// callbacks
const setNewPass = setNewPassCallback(dispatch, token, password1, <PASSWORD>);
return {
loading, error, success, dispatch,
password1, setPassword1Callback,
password2, set<PASSWORD>,
redirect, setRedirect,
setNewPass,
}
};
<file_sep>/src/neko-2-features/f-1-authorization/a-4-set-new-pass/s-3-dal/SetNewPassAPI.ts
import {instance} from "../../../../base-url";
export interface ISetNewPassData {
success: boolean;
error: string;
}
export const SetNewPassAPI = {
setNewPass: async (password: string, resetPasswordToken: string) => {
const response = await instance
.post<ISetNewPassData>('/auth/set-new-password', {password, resetPasswordToken});
return response.data;
},
};
<file_sep>/src/neko-2-features/f-1-authorization/a-4-set-new-pass/s-2-bll/setNewPassThunk.ts
import {ThunkAction, ThunkDispatch} from "redux-thunk";
import {IAppStore} from "../../../../neko-1-main/m-2-bll/store";
import {passwordCoding} from "../../../f-2-helpers/h-1-authorization/passwordCoding";
import {SetNewPassAPI} from "../s-3-dal/SetNewPassAPI";
import {ISetNewPassActions} from "./b-2-redux/setNewPassActions";
import {setNewPassError, setNewPassLoading, setNewPassSuccess} from "./b-1-callbacks/setNewPassBooleanCallbacks";
type Return = void;
type ExtraArgument = {};
type IGetStore = () => IAppStore;
export const setNewPass =
(password: string, token: string): ThunkAction<Return, IAppStore, ExtraArgument, ISetNewPassActions> =>
async (dispatch: ThunkDispatch<IAppStore, ExtraArgument, ISetNewPassActions>, getStore: IGetStore) => {
setNewPassLoading(dispatch, true);
try {
const data = await SetNewPassAPI.setNewPass(passwordCoding(password), token);
if (data.error) {
setNewPassError(dispatch, data.error);
} else {
setNewPassSuccess(dispatch, true);
console.log('Neko setNewPass Success!', data)
}
} catch (e) {
setNewPassError(dispatch, e.response.data.error);
console.log('Neko setNewPass Error!', {...e})
}
};
<file_sep>/README.md
First of [Neko modules](https://neko-modules-no-pages-sory.nya).
## Authorization module
sign in / registration / password recovery / profile logic<br/>
with back and boolean reducer
### sign in
login / password / remember me / redirect / cookie / getMe / loading / error / validation / logout
### registration
redirect / loading / error / validation
### password recovery
redirect / loading / error / validation<br/>
`back doesn't work`
### profile
redirect / cookie / getMe / loading / error / logout
##
##
## Boolean reducer
loading / error / success logic
##
##
## Back
typescript, express, heroku, mongoose, MongoDB Atlas
### `GitHub:`
[http://in-refactoring.sory](http://in-refactoring.sory)
##
##
## Available Scripts
In the project directory, you can run:
### `yarn`
install libraries: typescript, react-router-dom, redux, react-redux, redux-thunk, axios, gh-pages
### `yarn start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
##
##
## Plans
1. update back password recovery
2. saga version
3. google/vk/... authorization<file_sep>/src/neko-2-features/f-1-authorization/a-4-set-new-pass/s-2-bll/b-1-callbacks/setNewPassCallBacks.ts
import {ThunkDispatch} from "redux-thunk";
import {IAppStore} from "../../../../../neko-1-main/m-2-bll/store";
import {IBooleanActions} from "../../../../f-3-common/c-1-boolean-reducer/booleanActions";
import {passwordValidator} from "../../../../f-2-helpers/h-1-authorization/passwordValidator";
import {setNewPassError} from "./setNewPassBooleanCallbacks";
import {setNewPass} from "../setNewPassThunk";
type ExtraArgument = {};
export const setNewPassCallback = (
dispatch: ThunkDispatch<IAppStore, ExtraArgument, IBooleanActions>,
token: string,
password1: string,
password2: string,
) => () => {
if (!token) {
setNewPassError(dispatch, 'No resetPasswordToken!');
} else if (password1 !== password2) {
setNewPassError(dispatch, 'No resetPasswordToken!');
} else if (!passwordValidator(password1)) {
setNewPassError(dispatch, 'Password not valid! must be more than 7 characters...');
} else {
dispatch(setNewPass(password1, token));
}
};
<file_sep>/src/neko-2-features/f-1-authorization/a-4-set-new-pass/s-2-bll/b-2-redux/setNewPassActions.ts
export const SET_NEW_PASS_LOADING = 'SET_NEW_PASS/LOADING';
export const SET_NEW_PASS_ERROR = 'SET_NEW_PASS/ERROR';
export const SET_NEW_PASS_SUCCESS = 'SET_NEW_PASS/SUCCESS';
export const SET_NEW_PASS_ACTION_NAMES = [SET_NEW_PASS_LOADING, SET_NEW_PASS_ERROR, SET_NEW_PASS_SUCCESS];
export const SET_NEW_PASS_SOME = 'SET_NEW_PASS/SOME';
interface ISetNewPassSome { // blank
type: typeof SET_NEW_PASS_SOME;
}
export type ISetNewPassActions = ISetNewPassSome;
export const setNewPassSome = (): ISetNewPassSome => ({ // blank
type: SET_NEW_PASS_SOME,
});
<file_sep>/src/neko-2-features/f-1-authorization/a-4-set-new-pass/s-2-bll/b-1-callbacks/useSetNewPassLocalState.ts
import {useState} from "react";
import {Dispatch} from "redux";
import {useBooleanSelector} from "../../../../f-3-common/c-1-boolean-reducer/useBooleanSelectors";
import {SET_NEW_PASS_ERROR} from "../b-2-redux/setNewPassActions";
import {setNewPassClear} from "./setNewPassBooleanCallbacks";
export const useSetNewPassLocalState = (dispatch: Dispatch) => {
const [password1, setPassword1] = useState('<PASSWORD>');
const [password2, setPassword2] = useState('<PASSWORD>');
const [redirect, setRedirect] = useState(false);
const [error] = useBooleanSelector([SET_NEW_PASS_ERROR]);
const setPassword1Callback = (passwordC: string) => {
setPassword1(passwordC);
error.data.message && setNewPassClear(dispatch);
};
const setPassword2Callback = (passwordC: string) => {
setPassword2(passwordC);
error.data.message && setNewPassClear(dispatch);
};
return {
password1, setPassword1Callback,
password2, setPassword2Callback,
redirect, setRedirect,
}
};
<file_sep>/src/neko-2-features/f-1-authorization/a-4-set-new-pass/s-2-bll/b-1-callbacks/setNewPassBooleanCallbacks.ts
import {Dispatch} from "redux";
import {
booleanClear,
booleanError,
booleanLoading,
booleanSuccess
} from "../../../../f-3-common/c-1-boolean-reducer/booleanCallbacks";
import {SET_NEW_PASS_ACTION_NAMES} from "../b-2-redux/setNewPassActions";
export const setNewPassLoading = (dispatch: Dispatch, loading: boolean) => {
booleanLoading(dispatch, SET_NEW_PASS_ACTION_NAMES, loading);
};
export const setNewPassError = (dispatch: Dispatch, error: string) => {
booleanError(dispatch, SET_NEW_PASS_ACTION_NAMES, error);
};
export const setNewPassSuccess = (dispatch: Dispatch, success: boolean) => {
booleanSuccess(dispatch, SET_NEW_PASS_ACTION_NAMES, success);
};
export const setNewPassClear = (dispatch: Dispatch) => {
booleanClear(dispatch, SET_NEW_PASS_ACTION_NAMES);
};
| f47561f70bfa3473bf69f4bc6e711c71a3462dbe | [
"Markdown",
"TypeScript"
] | 8 | TypeScript | IgnatZakalinsky/neko-authorization-module | e9439b8a7c031f868b5cc541c16b2ff125857e63 | 3c523d0620f2ad220843c083acf9a084407716f2 |
refs/heads/master | <repo_name>vitorlofonseca/pag<file_sep>/geneticAlgorithm.h
void evaluateFitness (route *way[]){
int i;
for (i=0 ; i<routeQtd ; i++){
router *iterator = way[i]->firstRouter;
way[i]->fitnessSum = 0;
while (iterator->nextRtd != NULL){
iterator->fitness = 1.0 / iterator->nextTime;
iterator = iterator->nextRtd;
}
way[i]->fitnessSum = 1.0/way[i]->routeTime;
}
}
void makeElitism (route *way[]){
router *iterator = way[routeQtd-2]->firstRouter->nextRtd;
router *faster = iterator;
float smallerTime = iterator->nextTime;
while (iterator->nextRtd != NULL){
if (smallerTime > iterator->nextTime){
smallerTime = iterator->nextTime;
faster = iterator;
}
iterator = iterator->nextRtd;
}
iterator = way [routeQtd-1]->firstRouter->nextRtd;
router *slowler = iterator;
float greaterTime = iterator->nextTime;
while (iterator->nextRtd != NULL){
if (greaterTime < iterator->nextTime){
greaterTime = iterator->nextTime;
slowler = iterator;
}
iterator = iterator->nextRtd;
}
strcpy (slowler->ip, faster->ip);
slowler->nextTime = faster->nextTime;
strcpy (slowler->lastBinOc, faster->lastBinOc);
slowler->fitness = faster->fitness;
}
void makeCrosover (route *way[]){
int routesSize [routeQtd], i;
for (i=0 ; i<routeQtd ; i++){
router *aux = way[i]->firstRouter;
routesSize[i] = 0;
while (aux!=NULL){
routesSize[i]++;
aux = aux->nextRtd;
}
}
int smallerRoute = routesSize[0];
for (i=0 ; i<routeQtd ; i++){
if (smallerRoute>routesSize[i])
smallerRoute = routesSize[i];
}
srand (time(0));
int crossoved [routeQtd]; //control flag to know which routes was crossoved
int method = rand() % 3;
for (i=0 ; i<routeQtd ; i++)
crossoved [i] = 0;
for (i=0 ; i<routeQtd ; i++){
if (method == 1){
if (crossoved[i] == 0){
int separationPoint = 1 + (rand() % smallerRoute);
printf ("SEPARATION POINT %d - %d: %d\n", i+1, i+3, separationPoint);
if (smallerRoute == separationPoint || separationPoint > smallerRoute) // \ This way, the separation point never will be greater than the smaller route
separationPoint = 1; // / And if be, the separation point will be after first router
/* Crossover in fact */
router *iteratorRoute1 = way[i]->firstRouter;
router *iteratorRoute2 = way[i+2]->firstRouter;
int j;
for (j=0 ; j<separationPoint-1 ; j++){
iteratorRoute1 = iteratorRoute1->nextRtd;
iteratorRoute2 = iteratorRoute2->nextRtd;
}
router *aux = createRouter ("0.0.0.0", 0);
aux->nextRtd = iteratorRoute1->nextRtd;
iteratorRoute1->nextRtd = iteratorRoute2->nextRtd;
iteratorRoute2->nextRtd = aux->nextRtd;
/* Fim do Crossover Efetivo */
crossoved[i] = 1;
crossoved[i+2] = 1;
}
}
if (method == 0){
if (crossoved[i] == 0){
int separationPoint = 1 + (rand() % smallerRoute);
printf ("SEPARATION POINT %d - %d: %d\n", i+1, i+2, separationPoint);
if (smallerRoute == separationPoint || separationPoint > smallerRoute) // \ This way, the separation point never will be greater than the smaller route
separationPoint = 1; // / And if be, the separation point will be after first router
/* Crossover Efetivo */
router *iteratorRoute1 = way[i]->firstRouter;
router *iteratorRoute2 = way[i+1]->firstRouter;
int j;
for (j=0 ; j<separationPoint-1 ; j++){
iteratorRoute1 = iteratorRoute1->nextRtd;
iteratorRoute2 = iteratorRoute2->nextRtd;
}
router *aux = createRouter ("0.0.0.0", 0);
aux->nextRtd = iteratorRoute1->nextRtd;
iteratorRoute1->nextRtd = iteratorRoute2->nextRtd;
iteratorRoute2->nextRtd = aux->nextRtd;
/* End of Crossover in fact */
crossoved[i] = 1;
crossoved[i+1] = 1;
}
}
if (method == 2){
if (crossoved[i] == 0){
int separationPoint = 1 + (rand() % smallerRoute);
printf ("SEPARATION POINT %d - %d: %d\n", i+1, routeQtd-i, separationPoint);
if (smallerRoute == separationPoint || separationPoint > smallerRoute) // \ This way, the separation point never will be greater than the smaller route
separationPoint = 1; // / And if be, the separation point will be after first router
/* Crossover in fact */
router *iteratorRoute1 = way[i]->firstRouter;
router *iteratorRoute2 = way[routeQtd-i-1]->firstRouter;
int j;
for (j=0 ; j<separationPoint-1 ; j++){
iteratorRoute1 = iteratorRoute1->nextRtd;
iteratorRoute2 = iteratorRoute2->nextRtd;
}
router *aux = createRouter ("0.0.0.0", 0);
aux->nextRtd = iteratorRoute1->nextRtd;
iteratorRoute1->nextRtd = iteratorRoute2->nextRtd;
iteratorRoute2->nextRtd = aux->nextRtd;
/* Efective crossover end */
crossoved[i] = 1;
crossoved[routeQtd-i-1] = 1;
}
}
}
printf ("\n\n");
}
<file_sep>/prodalg.c
/*
* prodalg.c
*
* Copyright 2016 vitor <vitor@DESKTOP-370EE9O>
*
* This software is an Genetic Algorithm applied to computers network.
* It decide the best route where a network packet should go through.
* Below, we have some suppositions, to the script to make sense.
*
* - All of N routers have links with the N-1 other routers
* - The crossover will be done between the numbers 1 and 3 | 2 and 4 and the separation point will be 4 and 2
* - The routes quantity should be pair
* - The elitism is only being used in the last route
* - The elitism consist in catch the router with the best latency in the penultimate route, and to clone in the last route
*
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "dataStructureManipulation.h"
#include "geneticAlgorithm.h"
int main (){
int continueExecution=1;
/* INITIALIZING THE ROUTES POPULATION */
route *way [routeQtd];
int i=0;
for (i=0 ; i<routeQtd ; i++){
way[i] = initialize();
}
/* INITIALIZATION ENDS */
evaluateFitness (way);
show (way);
printf ("Do you want to continue route crossover? 1-yes, 0-no ");
scanf ("%d", &continueExecution);
int contGeracoes = 1; //initializing generations counter
while (continueExecution == 1){
printf ("Generation %d:\n\n", contGeracoes);
makeCrosover (way);
makeElitism (way);
removeRepeated (way);
updateTotalLatencies (way);
evaluateFitness (way);
show (way);
contGeracoes++;
printf ("Do you want to continue route crossover? 1-yes, 0-no ");
scanf ("%d", &continueExecution);
printf ("\n\n");
}
return 0;
}
<file_sep>/dataStructureManipulation.h
#define IPRange 50 //192.168.1.IPRange
#define IPSize 15
#define timeout 500
#define routeQtd 8
#define destinationHost "192.168.1.100"
#define sourceHost "192.168.1.1"
#define selectionQtd 4
#define lastDestinationOc 100
#define lastSourceOc 1
typedef struct router{
char ip [IPSize];
struct router *nextRtd;
int nextTime;
char lastBinOc [9];
double fitness;
}router;
typedef struct route{
router *firstRouter;
int routeTime;
double fitnessSum;
}route;
void removeRepeated (route *way[]){
int i;
for (i=0 ; i<routeQtd ; i++){
router *iterator = way[i]->firstRouter->nextRtd;
router *comparator = iterator->nextRtd;
while (iterator->nextRtd != NULL){
while (comparator->nextRtd != NULL){
if (strcmp (comparator->ip, iterator->ip) == 0){
router *remover = way[i]->firstRouter->nextRtd;
while (remover->nextRtd != comparator){
remover = remover->nextRtd;
}
remover->nextRtd = comparator->nextRtd;
free (comparator);
}
comparator = comparator->nextRtd;
}
iterator = iterator->nextRtd;
comparator = iterator->nextRtd;
}
}
}
router* createRouter (char ip [], int lastIntOc){
router *no = (router*)malloc(sizeof(router));
char lastCharOc [9];
itoa (lastIntOc, lastCharOc, 2);
strcpy (no->ip, ip);
no->nextRtd = NULL;
no->fitness = 0.0;
no->nextTime = rand() % timeout + 20;
strcpy (no->lastBinOc, lastCharOc);
return no;
}
route* initializeRoute (){
route *way = (route*)malloc(sizeof(route)); //allocating space in memory to linked list
router *rtd = createRouter(sourceHost, lastSourceOc); //creating the first router with the origin-IP
way->firstRouter = rtd;
way->routeTime = 0; //route time initialized
way->fitnessSum = 0.0;
return way; //first router return
}
void addRouter (route *way, char ip [], int lastIntOc){
router *iterator = way->firstRouter;
router *aux = createRouter(ip, lastIntOc);
while (iterator->nextRtd != NULL){
iterator = iterator->nextRtd;
}
iterator->nextRtd = aux;
}
int detectRepeated (route *way, char ip[]){
router *iterator = way->firstRouter;
while (iterator->nextRtd != NULL){
if (strcmp (iterator->ip, ip) == 0){
return 0;
}
iterator = iterator->nextRtd;
}
if (strcmp (iterator->ip, ip) == 0){
return 0;
}
return -1;
}
route* mountRoute (){
route *way = initializeRoute(); //initialize the route
int i=0;
/* Randomize the routers between the source and the destination */
for (i=0 ; i<rand() % IPRange + 3 ; i++){
char lastOc[3];
int lastIntOc = rand() % IPRange + 3;
sprintf(lastOc, "%d", lastIntOc);
char ip[IPSize];
strcpy (ip, "192.168.1.");
strcat (ip, lastOc);
if (detectRepeated (way, ip) == -1){ //If already exist a router with the same IP, doesn't insert
addRouter (way, ip, lastIntOc);
}
}
/* Localizing the last random router, and linking the efective destination in the end route */
router *aux = way->firstRouter;
while (aux->nextRtd != NULL){
aux = aux->nextRtd;
}
if (aux->nextRtd == NULL){
router *last = createRouter (destinationHost, lastDestinationOc);
last->nextTime = -1;
aux->nextRtd = last;
}
aux = way->firstRouter; //
//
while (aux->nextTime != -1){ // Calc of route total time
way->routeTime = way->routeTime + aux->nextTime; //
aux = aux->nextRtd; //
} //
return way;
}
route* initialize (){
route *way;
way = mountRoute();
return way;
}
void show (route *way[]){
int i=0;
for (i=0 ; i<routeQtd ; i++){
printf ("Route %d\n\n", i+1);
router *aux = way[i]->firstRouter;
while (aux != NULL){
printf ("IP: %s - Latency to next router: %dms - Last octet binary: %s - Fitness Jump: %f\n", aux->ip, aux->nextTime, aux->lastBinOc, aux->fitness);
aux = aux->nextRtd;
}
printf ("Total Time: %dms\n", way[i]->routeTime);
printf ("Route Fitness: %f\n", way[i]->fitnessSum);
printf ("\n\n");
}
}
void updateTotalLatencies (route *way[]){
int i;
for (i=0 ; i<routeQtd ; i++){
router *iterator = way[i]->firstRouter;
way[i]->routeTime = 0;
while (iterator->nextRtd != NULL){
way[i]->routeTime = way[i]->routeTime + iterator->nextTime;
iterator = iterator->nextRtd;
}
}
}
<file_sep>/README.md
# Prodalg
This project has as objective to decide the best route between a source host and a destination host, through Genetic Algorithm, considering the overload in each network link.
### Steps to use:
1 - Define how many route possibilities you want in dataStructureManipulation.routeQtd
2 - Run the algorithm
3 - In the image below, we can see many informations, like the route number, the router hop, the hop latency, and the total latency from source router to destination router (both defined in dataStructureManipulation.sourceHost and dataStructureManipulation.destinationHost)

4 - The faster route between all, will be used in real scenario
### Current Scenario
- The algorithm works with linked list
- The address of each router is random.
- The crossover will be done between the numbers 1 and 3 | 2 and 4 and the separation point will be 4 and 2
- The router X transfer times to next routers are random
- The elitism is only being used in the last route
- The elitism consist in catch the router with the best latency in the penultimate route, and to clone in the last route
### Next Goals
- Develop integration with ICMP protocol, to work with real routes and your latency possibilities
- Develop integration with PAG protocol (network resource allocation), to big files transference in best route (decided by Genetic Algorithm)
### Considerations that give sense to atual algorithm
- All of N routers have links with the N-1 other routers
- The routers quantity should initially be pair
| 16f4780b284e23442f34ac30956faa3fbd8bbf72 | [
"Markdown",
"C"
] | 4 | C | vitorlofonseca/pag | 7f24e1110e5ad283bd58af84bb4d937e90ab54f1 | e3563b0fd77d7d8c6ad0b5c92964f183c0440dc0 |
refs/heads/master | <file_sep>var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
var personal;
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '<PASSWORD>',
database : 'timetable'
});
connection.query('SELECT * FROM personal',
function(error, rows){
if(error)
throw (error);
console.log(rows);
if(rows.length > 0){
personal = rows;
}else{
personal = null;
}
})
module.exports = app;
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//ALL THE GET METHODS IS IN HERE
app.get('/', function(request, response) {
response.sendFile(path.join(__dirname + '/login.html'));
});
app.get('/choose', function(request, response) {
response.sendFile(path.join(__dirname + '/choose.html'));
});
app.get('/business.html', function(request, response) {
response.sendFile(path.join(__dirname + '/business.html'));
});
app.get('/signup.html', function(request, response) {
response.sendFile(path.join(__dirname + '/signup.html'));
});
app.get('/personal.html', function(request, response) {
response.sendFile(path.join(__dirname + '/personal.html'));
});
app.get('/personal/delete/:userId',(request, response) => {
const userId = request.params.userId;
let sql = `DELETE from personal WHERE id = ${userId}`;
let query = connection.query(sql, (error, results) => {
if(error) throw error;
response.redirect('/personaldeletedone');
});
});
app.get('/business/delete/:userId',(request, response) => {
const userId = request.params.userId;
let sql = `DELETE from business WHERE id = ${userId}`;
let query = connection.query(sql, (error, results) => {
if(error) throw error;
response.redirect('/businessdeletedone');
});
});
app.get('/login.html', function(request, response) {
response.sendFile(path.join(__dirname + '/login.html'));
});
app.get('/personalall.ejs',function(req,res)
{res.render('personalall.ejs');});
app.get('/personaldeletedone',function(req,res)
{res.render('personaldeletedone.html');});
app.get('/businessdeletedone',function(req,res)
{res.render('businessdeletedone.html');});
app.get('/personaledit.html',function(req,res)
{res.render('personalall.html');});
app.get('/personal/edit/:userId', (request, response) =>{
const userId = request.params.userId;
let sql = `SELECT * FROM personal WHERE id = ${userId}`;
let query = connection.query(sql, (error, results) => {
if(error) throw error;
response.render('personaledit.ejs', {
user : results[0]
});
});
});
app.get('/business/edit/:userId', (request, response) =>{
const userId = request.params.userId;
let sql = `SELECT * FROM business WHERE id = ${userId}`;
let query = connection.query(sql, (error, results) => {
if(error) throw error;
response.render('businessedit.ejs', {
user : results[0]
});
});
});
app.get('/personalall.html', (request, response) => {
let sql = "SELECT * FROM personal";
let query = connection.query(sql, (error, rows) => {
if(error) throw error;
response.render('personalall.ejs', {
personal : rows
});
});
});
app.get('/businessall.html', (request, response) => {
let sql = "SELECT * FROM business";
let query = connection.query(sql, (error, rows) => {
if(error) throw error;
response.render('businessall.ejs', {
personal : rows
});
});
});
//ALL THE POST METHODS IS IN HERE
//Verifying if the user is in the system method.
app.post('/auth', function(request, response) {
var username = request.body.username;
var password = <PASSWORD>;
if (username && password) {
connection.query('SELECT * FROM accounts WHERE username = ? AND password = ?', [username, password], function(error, results, fields) {
if (results.length > 0) {
request.session.loggedin = true;
request.session.username = username;
response.redirect('/choose');
} else {
response.send('Incorrect Username and/or Password!');
}
response.end();
});
} else {
response.send('Please enter Username and Password!');
response.end();
}
});
//****Encrypting the password for the users.
//const bcrypt = require('bcrypt');
//const saltRounds = 10;
app.post('/signup', function(request, response) {
var username = request.body.username;
var password = request.body.password;
var email = request.body.email;
//bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
queryString = "INSERT INTO accounts (username, password, email) VALUES (?,?,?)"
connection.query(queryString,[username,password,email],(error,rows,fields)=>{
if(error){
console.log("failed to insert classes"+ error)
response.sendStatus(500)
return
}
response.send("successfully added user to system")
})
//});
console.log("The user was created succsesfuly.");
});
//Adding the personal contacts to the server using SQL queries*****
app.post('/personal', function(request, response) {
var phonenumber = request.body.phonenumber;
var address = request.body.address;
var email = request.body.email;
var birthday = request.body.birthday;
queryString = "INSERT INTO personal (phonenumber, email, address, birthday) VALUES (?,?,?,?)"
connection.query(queryString,[phonenumber,email,address,birthday],(error,rows,fields)=>{
if(error){
console.log("failed to insert contact"+ error)
response.sendStatus(500)
return
}
response.send("successfully added personal contact info")
})
console.log("The record is inserted.");
});
app.post('/business', function(request, response) {
var phonenumber = request.body.phonenumber;
var physicaladdress = request.body.physicaladdress;
var email = request.body.email;
var postaladdress = request.body.postaladdress;
var vatnumber = request.body.vatnumber;
queryString = "INSERT INTO business (phonenumber, email, physicaladdress, postaladdress,vatnumber) VALUES (?,?,?,?,?)"
connection.query(queryString,[phonenumber,email,physicaladdress,postaladdress,vatnumber],(error,rows,fields)=>{
if(error){
console.log("failed to insert classes"+ error)
response.sendStatus(500)
return
}
response.send("successfully added business contact info")
})
console.log("The record is inserted.");
});
app.post('/personal/update', (request,response) => {
const userId = request.body.id;
let sql = "UPDATE personal SET phonenumber='"+request.body.phonenumber+"',email = '"+request.body.email+"', address = '"+request.body.address+"', birthday = '"+request.body.birthday+"' WHERE id = "+userId;
let query = connection.query(sql, (error, results) => {
if(error) throw error;
response.redirect('/personalall.html');
});
});
app.post('/business/update', (request,response) => {
const userId = request.body.id;
let sql = "UPDATE personal SET phonenumber='"+request.body.phonenumber+"',email = '"+request.body.email+"', physicaladdress = '"+request.body.physicaladdress+"', postaladdress = '"+request.body.postaladdress+"' , vatnumber = '"+request.body.vatnumber+"' WHERE id = "+userId;
let query = connection.query(sql, (error, results) => {
if(error) throw error;
response.redirect('/businessall.html');
});
});
app.listen(3000);
console.log("Server is up at 3000"); | 7c7e6e6343114ad78a9940a56fa8e4862a1388a4 | [
"JavaScript"
] | 1 | JavaScript | ReinardSerfontein/Contact-List | a0ac8fc1a5744dd60546c6f422977e54eafac467 | 7370119b087fde34756e078a673d5637c467c702 |
refs/heads/master | <repo_name>hiro4336/tenki<file_sep>/Sanagi/c15.py
# ==================================================
# library
# ==================================================
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
from tkinter import filedialog
import sqlite3
import pandas as pd
import datetime
import os
import csv
import sys
import matplotlib.pyplot as plt
import japanize_matplotlib
"""
できあがったDBデータを出力、・CSV出力、・matplot.table/jpg
"""
# ====================================================================================================
# ウィジェット
# ====================================================================================================
class Application(tk.Frame):
def __init__(self, master=None):
"""
///ウィジェット親クラス///
"""
super().__init__(master)
self.master = master
# 全体ウィンドウサイズ、配置位置
self.master.geometry("1800x900+0+0")
# ウィンドウのタイトル
self.master.title("アゲハチョウの羽化観察")
# 上記を反映する
self.pack()
# ウィンドウ内のウィジェットを配置
self.create_widgets()
def create_widgets(self):
"""
///ウィジェットの配置///
///この中でウィジェット部品を配置する///
"""
# ウィジェットのスタイル設定
self.style = ttk.Style()
fontsize_t1 = 13
fontsize_t2 = 10
# Treeview headingのフォント
self.style.configure("Treeview.Heading",font=("",fontsize_t1))
# Treeview内のフォント
self.style.configure("Treeview",font=("",fontsize_t2))
# -------------------------
# DB / テーブル有無チェック
# -------------------------
# テーブル有無確認、無ければ作成
TableExsistenceCheckAndCreate()
# -------------------------
# データ読込み
# -------------------------
# DB / table名
tableName="SanagiTable"
# data
data = ProcessGetData(tableName)
# -------------------------
# master / frame
# -------------------------
#tcl_isOk = self.register(IsOk)
self.frame1 = tk.Frame(self, width=800, height=100)
self.frame2 = tk.Frame(self, width=800, height=300)
self.frame3 = tk.Frame(self, width=800, height=100)
self.frame4 = tk.Frame(self, width=800, height=100)
self.frame5 = tk.Frame(self, width=800, height=100)
self.frame1.grid(column=0,row=0,padx=5,pady=5)
self.frame2.grid(column=0,row=1,padx=5,pady=5)
self.frame3.grid(column=0,row=2,padx=5,pady=5)
self.frame4.grid(column=0,row=3,padx=5,pady=5)
self.frame5.grid(column=0,row=4,padx=5,pady=5)
# --------------------------------------------------
# 【変数】ウィジェット間距離など
# --------------------------------------------------
pad_x1 = 10
pad_y1 = 3
width1 = 20
width2 = 30
Lbl_name1 = "ID"
Lbl_name2 = "名前"
Lbl_name3 = "サナギになった日"
Lbl_name4 = "羽化予想日"
Lbl_name5 = "羽化した日"
Lbl_name6 = "実日数"
Lbl_name7 = "羽化まで日数"
fontsize1 = 15
fontsize2 = 12
# Entry欄のheight
ipady_1 = 15
# 羽化に必要な日数
need_sanagiDay=10
# --------------------------------------------------
# frame1 / button
# --------------------------------------------------
self.btn_2= tk.Button(self.frame1, text = '新規登録', command=self.WritePush2,font=("",fontsize1))
self.btn_2.grid(column=0,row=0,padx=pad_x1,pady=pad_y1)
self.btn_4= tk.Button(self.frame1, text = 'DB読込み', command=lambda:self.WritePush4(tableName),font=("",fontsize1))
self.btn_4.grid(column=2,row=0,padx=pad_x1,pady=pad_y1)
self.btn_6= tk.Button(self.frame1, text = 'テーブル削除/作成', command=lambda:self.WritePush6(tableName),font=("",fontsize1))
self.btn_6.grid(column=3,row=0,padx=pad_x1,pady=pad_y1)
self.btn_5= tk.Button(self.frame1, text = '開発用/元データ呼び出し', command=self.WritePush5,font=("",fontsize1))
self.btn_5.grid(column=4,row=0,padx=pad_x1,pady=pad_y1)
self.btn_9= tk.Button(self.frame1, text = 'CSV読み込み', command=self.WritePush10,font=("",fontsize1))
self.btn_9.grid(column=5,row=0,padx=pad_x1,pady=pad_y1)
self.btn_10= tk.Button(self.frame1, text = 'CSV出力', command=self.WritePush11,font=("",fontsize1))
self.btn_10.grid(column=6,row=0,padx=pad_x1,pady=pad_y1)
self.btn_11= tk.Button(self.frame1, text = '表jpg出力', command=self.WritePush12,font=("",fontsize1))
self.btn_11.grid(column=7,row=0,padx=pad_x1,pady=pad_y1)
# --------------------------------------------------
# frame2 / Label,Entry
# --------------------------------------------------
# 選択したデータの表示場所&入力箇所
self.Label_1 = tk.Label(self.frame2, text = Lbl_name1, width = width1, bg='gray',fg='white',font=("",fontsize1))
self.Label_1.grid(column=0,row=1,padx=pad_x1,pady=pad_y1)
self.entry_1 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_1.grid(column=0,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_2 = tk.Label(self.frame2, text = Lbl_name2, width = width1, bg='gray',fg='white',font=("",fontsize1))
self.Label_2.grid(column=1,row=1,padx=pad_x1,pady=pad_y1)
self.entry_2 = tk.Entry(self.frame2,width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_2.grid(column=1,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_3 = tk.Label(self.frame2, text = Lbl_name3, width = width1, bg='gray',fg='white',font=("",fontsize1))
self.Label_3.grid(column=2,row=1,padx=pad_x1,pady=pad_y1)
self.entry_3 = tk.Entry(self.frame2,width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_3.grid(column=2,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_4 = tk.Label(self.frame2, text = Lbl_name4, width = width1, bg='gray', fg='white',font=("",fontsize1))
self.Label_4.grid(column=3,row=1,padx=pad_x1,pady=pad_y1)
self.entry_4 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_4.grid(column=3,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_5 = tk.Label(self.frame2, text = Lbl_name5, width = width1, bg='gray', fg='white',font=("",fontsize1))
self.Label_5.grid(column=4,row=1,padx=pad_x1,pady=pad_y1)
self.entry_5 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_5.grid(column=4,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_6 = tk.Label(self.frame2, text = Lbl_name6, width = width1, bg='gray', fg='white',font=("",fontsize1))
self.Label_6.grid(column=5,row=1,padx=pad_x1,pady=pad_y1)
self.entry_6 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_6.grid(column=5,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_7 = tk.Label(self.frame2, text = Lbl_name7, width = width1, bg='gray', fg='white',font=("",fontsize1))
self.Label_7.grid(column=0,row=3,padx=pad_x1,pady=pad_y1)
self.entry_7 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_7.insert(tk.END,need_sanagiDay)
self.entry_7.grid(column=0,row=4,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
# 入力不可 / Entry1=ID
self.entry_1.configure(state='disabled')
# --------------------------------------------------
# frame3 / button
# --------------------------------------------------
# チェックボタン
self.btn_8= tk.Button(self.frame3, text = '入力チェック', command=self.WritePush9,width=30,font=("",fontsize1))
self.btn_8.grid(column=0,row=0,padx=pad_x1,pady=pad_y1)
# 書き込みボタン
self.btn_1= tk.Button(self.frame3, text = '書き込み', command=lambda:self.WritePush1(tableName),width=30,font=("",fontsize1))
self.btn_1.grid(column=1,row=0,padx=pad_x1,pady=pad_y1)
# 削除ボタン
self.btn_3= tk.Button(self.frame3, text = '削除処理', command=lambda:self.WritePush3(tableName),width=30,font=("",fontsize1))
self.btn_3.grid(column=2,row=0,padx=pad_x1,pady=pad_y1)
# -------------------------
# frame4 / treeview
# -------------------------
self.tree = ttk.Treeview(self.frame4, height = 20, style='Treeview')
# treeの設定
self.tree["columns"] = (1,2,3,4,5,6)
self.tree["show"] = "headings"
self.tree.column(1, width=200,anchor=tk.CENTER)
self.tree.column(2, width=200,anchor=tk.CENTER)
self.tree.column(3, width=200,anchor=tk.CENTER)
self.tree.column(4, width=200,anchor=tk.CENTER)
self.tree.column(5, width=200,anchor=tk.CENTER)
self.tree.column(6, width=200,anchor=tk.CENTER)
self.tree.heading(1, text="ID")
self.tree.heading(2, text="名前")
self.tree.heading(3, text="サナギになった日")
self.tree.heading(4, text="羽化予想日")
self.tree.heading(5, text="羽化した日")
self.tree.heading(6, text="実日数")
# --------------------------------------------------
# frame5 / Quit button
# --------------------------------------------------
self.btn_2= tk.Button(self.frame5, text="閉じる", fg="black",command=self.master.destroy,font=("",fontsize1))
self.btn_2.grid(column=0,row=0,padx=pad_x1,pady=pad_y1)
# --------------------------------------------------
# Entry入力不可状態
# --------------------------------------------------
AllEntryDisable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6)
# --------------------------------------------------
#ツリー内をマウスで選択した時
# --------------------------------------------------
self.tree.bind("<<TreeviewSelect>>", self.OnTreeSelect)
# pack
self.tree.pack()
# DB/Tableの有無のチェック、無ければ作成する
TableExsistenceCheckAndCreate()
def OnTreeSelect(self,event):
"""
///ツリービュー内の情報を選択したときの処理///
"""
# Entryの入力可能処理
AllEntryEnable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6)
for id in self.tree.selection():
#Dicionary形式で抽出
self.tree.set(id)
mydic = self.tree.set(id)
d1 = mydic['1']
d2 = mydic['2']
d3 = mydic['3']
d4 = mydic['4']
d5 = mydic['5']
d6 = mydic['6']
# Entry1への入力受付可能に設定
#self.entry_1.configure(state='normal')
# 中身をいったん消してから/データ挿入
self.entry_1.delete(0, tk.END)
self.entry_1.insert(tk.END,d1)
self.entry_2.delete(0, tk.END)
self.entry_2.insert(tk.END,d2)
self.entry_3.delete(0, tk.END)
self.entry_3.insert(tk.END,d3)
self.entry_4.delete(0, tk.END)
self.entry_4.insert(tk.END,d4)
self.entry_5.delete(0, tk.END)
self.entry_5.insert(tk.END,d5)
self.entry_6.delete(0, tk.END)
self.entry_6.insert(tk.END,d6)
# Entry制限
self.entry_1.configure(state='disabled')
self.entry_4.configure(state='disabled')
self.entry_6.configure(state='disabled')
def WritePush1(self,tableName):
"""
///書き込みボタン押下時の処理///
///Entry内の情報を読み取り、DBへ登録する///
"""
# ------------------------------
# 実行前の確認処理
# ------------------------------
res = PopUp4()
# yesで抜けて進む
if res =="yes":
pass
# noで終了処理
else:
return
# ------------------------------
# メイン処理の開始
#-------------------------------
# Entry欄の情報取得
e1 = self.entry_1.get()
e2 = self.entry_2.get()
e3 = self.entry_3.get()
e4 = self.entry_4.get()
e5 = self.entry_5.get()
e6 = self.entry_6.get()
# DB接続し、
dbc = DBconnection()
# UPDATE/INSERTの振り分け
if e1 != "":
# データ/UPDATE
dbc.Updatedata(tableName,e1,e2,e3,e4,e5,e6)
else:
# データ/INSERT
dbc.InsertData(tableName,e2,e3,e4,e5,e6)
# DB COMMIT/CLOSE
dbc.Commit()
dbc.Close()
# DBを再読み込み
data = ProcessGetData(tableName)
# データ挿入
TreeDataImport(self.tree,data)
# ポップアップ通知
if e1 != "":
PopUp1(e1)
else:
PopUp2()
def WritePush2(self):
"""
///新規登録時の処理///
"""
# Entryへの入力受付可能に設定
AllEntryEnable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6)
# 中身を消す
self.entry_1.delete(0, tk.END)
self.entry_2.delete(0, tk.END)
self.entry_3.delete(0, tk.END)
self.entry_4.delete(0, tk.END)
self.entry_5.delete(0, tk.END)
self.entry_6.delete(0, tk.END)
self.entry_7.delete(0, tk.END)
# 初期値を入れる
self.entry_7.insert(tk.END,"10")
# 一部のEntryへの入力不可にする
self.entry_1.configure(state='disabled')
self.entry_4.configure(state='disabled')
self.entry_6.configure(state='disabled')
# 通知
PopUp8()
def WritePush3(self,tableName):
"""
///ツリー上のいずれかのデータを削除する処理
Entry情報を読み取る
IDがない場合、「できない」処理
IDありの場合、「いいですか?」
ID指定で、削除処理、完了通知
"""
# 1=id, 2=sanagi, 3=name, 4=birth
e1 = self.entry_1.get()
e2 = self.entry_2.get()
e3 = self.entry_3.get()
e4 = self.entry_4.get()
e5 = self.entry_5.get()
e6 = self.entry_6.get()
# IDが無い場合
if e1 == "":
PopUp3()
return
# IDがある場合
else:
# 処理前の確認
res = PopUp4()
# yesで抜けて進む
if res =="yes":
pass
# noで終了処理
else:
return
# DB接続
dbc = DBconnection()
#実行処理
dbc.DeleteRecordData(tableName,e1)
# COMMIT/CLOSE
dbc.Commit()
dbc.Close()
# DBを再読み込み
df = ProcessGetData(tableName)
# データ挿入
TreeDataImport(self.tree,df)
# 通知
PopUp5()
def WritePush4(self,tableName):
"""
///再読み込みボタン:DB読込みをしてツリービューに表示する///
ツリービューのデータ削除、読み込み
Entryのデータ削除
"""
# DB接続し、
dbc = DBconnection()
# DBを再読み込み
data = ProcessGetData(tableName)
# データ挿入
TreeDataImport(self.tree,data)
# ポップアップ通知
PopUp6()
def WritePush5(self):
"""
///特定ファイルのデータリストを読み込み、DBへ登録しなおす。///
///データの初期化///
"""
# sanagi_data.pyからリスト取り出し
v = ReadDataFromOterFile()
# DB接続、INSERT
# DB接続
tableName="SanagiTable"
dbc = DBconnection()
#sql1 = 'INSERT INTO SanagiTable(name,sanagi,prediction,birth,dif) VALUES(?,?,?,?,?)'
sql1 = "INSERT INTO %s(name,sanagi,prediction,birth,dif) VALUES(?,?,?,?,?)" % tableName
# ループ回数確認
numberElements = len(v)
minLoopNumber = int(numberElements)
# SQL実行/INSERT
for i in range(0,minLoopNumber,1):
dbc.cur.execute(sql1,(v[i][0],v[i][1],v[i][2],v[i][3],v[i][4]))
dbc.Commit()
# 最新データ取り出し
d = dbc.cur.execute("SELECT * FROM SanagiTable")
data = d.fetchall()
# DB閉じる
dbc.Close()
# Treeview
TreeDataImport(self.tree,data)
# Entryの入力制限
AllEntryDisable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6)
# ポップアップ通知
PopUp6()
def WritePush6(self,tableName):
"""
///テーブル削除、新規でテーブル作成する
"""
# ------------------------------
# 実行前の確認処理
# ------------------------------
res = PopUp4()
# yesで抜けて進む
if res =="yes":
pass
# noで終了処理
else:
return
# テーブル削除、作成
TableDropAndCreate()
# DB/SELECT、ツリー表示
# DB接続し、
dbc = DBconnection()
# DBを再読み込み
df = ProcessGetData(tableName)
# データ挿入
TreeDataImport(self.tree,df)
# Entryの入力制限
AllEntryEnable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6)
# Entry欄の情報削除
AllEntryInfoErase(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6)
# Entryの入力制限
AllEntryDisable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6)
# 通知
PopUp7()
def WritePush8(self):
"""
///入力チェックを行う処理
///新規登録押下後のアクション
"""
# Entry欄の情報取得
e1 = self.entry_1.get()
e2 = self.entry_2.get()
e3 = self.entry_3.get()
e4 = self.entry_4.get()
e5 = self.entry_5.get()
e6 = self.entry_6.get()
e7 = self.entry_7.get()
# 未入力の場合の処理
if e3 =="":
#(命令:entry6を削除するべき)
return
# 文字列「0」の時
elif e3=="0":
#(命令:entry6を削除するべき)
return
# 「-」が含まれる場合、replaceする
elif e3.find('-'):
e3 = e3.replace('-', '')
# 文字列数のチェック
if len(e3) != 8:
return
# -----------------------
# 羽化予想日の計算
# -----------------------
# サナギになった日/datetime型
dt_e3 = StrToDateTime(e3)
# 羽化必要日数を取得してdatetimedelta型へ
dt_e7 = int(e7)
dt_needsanagi = IntToTimedelta(dt_e7)
# 日にちの計算
dt_prediction = dt_e3 + dt_needsanagi
dt_prediction = dt_prediction.date()
# -----------------------
# 羽化に要した日数の計算
# e5 / 羽化した日の情報のチェック
# -----------------------
# 文字列なしの時
if e5 =="":
#(命令:entry6を削除するべき)
return
# 文字列「0」の時
elif e5=="0":
#(命令:entry6を削除するべき)
return
# 「-」が含まれる場合、replaceする
elif e5.find('-'):
e5 = e5.replace('-', '')
# 文字列数のチェック
if len(e5) != 8:
return
# datetime型
dt_e5 = StrToDateTime(e5)
dt_dif = (dt_e5 - dt_e3).days
# -----------------------
# データ反映
# 未入力でボタン押下の場合、動作しないように。
# -----------------------
dt_e3 = dt_e3.strftime('%Y-%m-%d')
dt_e5 = dt_e5.strftime('%Y-%m-%d')
self.entry_3.configure(state='normal')
self.entry_3.delete(0, tk.END)
self.entry_3.insert(tk.END,dt_e3)
# 羽化予想日
self.entry_4.configure(state='normal')
self.entry_4.delete(0, tk.END)
self.entry_4.insert(tk.END,dt_prediction)
self.entry_4.configure(state='disabled')
self.entry_5.configure(state='normal')
self.entry_5.delete(0, tk.END)
self.entry_5.insert(tk.END,dt_e5)
# 羽化実日数
self.entry_6.configure(state='normal')
self.entry_6.delete(0, tk.END)
self.entry_6.insert(tk.END,dt_dif)
self.entry_6.configure(state='disabled')
def WritePush9(self):
"""
///入力チェックを行う処理
///新規登録押下後のアクション
7/14:再構築
"""
# Entry欄の情報取得
e1 = self.entry_1.get()
e2 = self.entry_2.get()
e3 = self.entry_3.get()
e4 = self.entry_4.get()
e5 = self.entry_5.get()
e6 = self.entry_6.get()
e7 = self.entry_7.get()
# 入力情報有無のチェック
# Select時、e1,e4,e6:disable
# 入力必要:e3,e5,e7
if e3=="" or e5=="" or e7=="":
PopUp12()
return
# ------------------------------
# e3チェック
# ------------------------------
# 2021-05-21と入力を期待する
# 20210521の場合はそのまま通す
if "-" in e3:
e3 = e3.replace('-', '')
# 数字以外の文字列の場合はstop
if e3.isdigit()==False:
PopUp13()
return
# 数字入力は20210501と、8文字
if len(e3)!=8:
PopUp14()
return
# ------------------------------
# e5のチェック
# ------------------------------
# Birth:2021-05-30を期待する
# 0という場合もある
if "-" in e5:
e5 = e5.replace('-', '')
# 数字以外の文字列の場合はstop
if e5.isdigit()==False:
PopUp13()
return
# 0という入力の場合、そのままにしておく
if e5=="0":
e5="0"
# 0以外で、数字入力は20210501と、8文字
elif len(e5)!=8:
PopUp14()
return
# ------------------------------
# e7のチェック
# ------------------------------
# 羽化に必要な日数=10(デフォルト)
# 数字以外の文字列の場合はstop
if e7.isdigit()==False:
PopUp13()
return
# ------------------------------
# 入力チェック終了
# 計算の開始
# ------------------------------
# ------------------------------
# e4 羽化予定日
# ------------------------------
# e3+e7で、予定日を算出する
# e3 / datetime型
e3 = StrToDateTime(e3)
# e7 / timedelta
e7 = IntToTimedelta(int(e7))
# e3+e7
e4 = e3 + e7
# ------------------------------
# e6 実日数
# ------------------------------
# e5-e3で、日数を算出する
# e3 / datetime型
e5 = StrToDateTime(e5)
# e5-e3
e6 = e5-e3
e6 = int(e6.days)
# ------------------------------
# Entryへのデータ反映
# ------------------------------
# 反映前のデータ準備
e3 = e3.date()
e4 = e4.date()
e5 = e5.date()
e7 = e7.days
# Entryの入力制限
AllEntryEnable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6)
# Entry1~7へデータ反映
self.entry_1.delete(0, tk.END)
self.entry_1.insert(tk.END,e1)
self.entry_2.delete(0, tk.END)
self.entry_2.insert(tk.END,e2)
self.entry_3.delete(0, tk.END)
self.entry_3.insert(tk.END,e3)
self.entry_4.delete(0, tk.END)
self.entry_4.insert(tk.END,e4)
self.entry_5.delete(0, tk.END)
self.entry_5.insert(tk.END,e5)
self.entry_6.delete(0, tk.END)
self.entry_6.insert(tk.END,e6)
self.entry_7.delete(0, tk.END)
self.entry_7.insert(tk.END,e7)
# Entry / disable
self.entry_1.configure(state='disabled')
self.entry_4.configure(state='disabled')
self.entry_6.configure(state='disabled')
# 通知
PopUp15()
def WritePush10(self):
"""
///CSVの読み込み
"""
# CSVファイルの保存先のチェック
s1,s2,s3 = CheckCsvFolderExists()
# ファイルダイヤログ表示、ファイル選択ができるように。
filePath = OpenFileDialog(s1)
# ダイヤログでキャンセルボタン押下の場合の処理
if filePath == "":
return
# CSV読み込み / List型
data = CsvOpenAndReader(filePath)
print(data)
# ツリーへデータ挿入
TreeDataImport(self.tree,data)
# 通知
PopUp0()
def WritePush11(self):
"""
///CSVの出力
///DBデータを抽出し、CSVファイルとして出力する
"""
# CSVファイルの保存先のチェック
s1,s2,s3 = CheckCsvFolderExists()
# DB接続、データをSELECT*で引っ張る
# DB接続し、
dbc = DBconnection()
# tablename
tableName = "SanagiTable"
# DBを再読み込み
data = ProcessGetData(tableName)
# Pandas / Dataframeにする
df = ToPandasDataFrame(data)
# Timestamp
Tstamp = GetTimeStamp()
# CSVのファイルにする
FldName = s2
csvName = "_out.csv"
dirName = FldName + "\\"
fileSavePath = dirName + Tstamp + csvName
# CSVへ出力
df.to_csv(fileSavePath,index=False,encoding='utf_8_sig')
# 完了通知
PopUp0()
def WritePush12(self):
"""
///Matplotlib.tableの表jpgを出力、保存
"""
# jpg保存先フォルダ有無のチェック
s1,s2,s3 = CheckCsvFolderExists()
# DB接続、データをSELECT*で引っ張る
# DB接続し、
dbc = DBconnection()
# tablename
tableName = "SanagiTable"
# DBを再読み込み
data = ProcessGetData(tableName)
# Pandas / Dataframeにする
df = ToPandasDataFrame(data)
# チェック/dfがない場合はSTOP
if len(df)==0:
PopUp11()
return
# Timestamp
Tstamp = GetTimeStamp()
# matplotに渡す
fig = CreatePltTable(df)
# Save as jpg
SaveTablefig(fig,s3)
# Matplotlib.table終了処理
plt.clf()
plt.close()
# 通知
PopUp0()
# ====================================================================================================
# データベース
# ====================================================================================================
# ///基本情報:
# データベース名:butterfly.db
# テーブル名:SanagiTable
# カラム名:id,name,sanagi,prediction,birth,dif
class DBconnection:
"""
データベース関係:
"""
def __init__(self):
"""
///データベース接続///
"""
dbname='butterfly.db'
self.connection = sqlite3.connect(dbname)
self.cur = self.connection.cursor()
def Commit(self):
"""
///データコミット///
"""
r = self.connection.commit()
return r
def Close(self):
"""
///データベースクローズ///
"""
r = self.cur.close()
return r
def Getdata(self,tableName):
"""
///データベースから情報取得///
"""
#tableName='SanagiTable'
r = self.cur.execute("SELECT * FROM %s" % tableName)
r = r.fetchall()
return r
def Updatedata(self,tableName,e1,e2,e3,e4,e5,e6):
"""
///データベースに既存情報を書き換え・更新///
"""
self.cur.execute("UPDATE %s SET name=?,sanagi=?,prediction=?,birth=?,dif=? WHERE id=?" % tableName,(e2,e3,e4,e5,e6,e1))
def InsertData(self,tableName,e2,e3,e4,e5,e6):
"""
///データベースに、新規情報をインサートする///
変数:テーブル名は%s、VALUESは?で。
"""
self.cur.execute("INSERT INTO %s(name,sanagi,prediction,birth,dif) VALUES(?,?,?,?,?)" % tableName,(e2,e3,e4,e5,e6))
def DeleteRecordData(self,tableName,e1):
"""
///データベースから、特定の1つのレコードを削除する///
注意:引数は(e1,)とタプルで渡すこと。(e1)だと文字列で誤解する
"""
self.cur.execute("DELETE FROM %s WHERE id=%s" %(tableName,e1))
def DropTable(self,tableName):
"""
///テーブル削除///
"""
self.cur.execute("DROP TABLE %s" % tableName)
def CreateTable(self,tableName):
"""
///SanagiTableの作成///
"""
sql = 'CREATE TABLE SanagiTable(id INTEGER PRIMARY KEY AUTOINCREMENT, name STRING, sanagi DATE, prediction DATE, birth DATE, dif INTEGER)'
self.cur.execute(sql)
def CheckTableExistence(self,tableName):
"""
///DB内のテーブル名有無をチェック
"""
r = self.cur.execute('SELECT COUNT(*) FROM sqlite_master WHERE TYPE="table" AND NAME="%s"' % tableName)
return r
# ====================================================================================================
# Sanagiの再リスト化
# ほかファイルから再配列するためのもの
# データがないときは、ここから持ってくる(開発用)
# ====================================================================================================
class Sanagi:
def __init__(self, s, n, b):
"""
///サナギ観察データ保持をするための情報の再配列///
"""
dt_needsanagi = datetime.timedelta(days = 10)
self.sanagi = s
self.name = n
self.prediction = s + dt_needsanagi
self.birth = b
if self.birth != 0:
self.dif = (self.birth - self.sanagi).days
else:
self.dif = 0
def RenewList(self,newList):
newList.append([self.name,self.sanagi,self.prediction, self.birth, self.dif])
return newList
def Print(self):
print(self.name, self.sanagi,self.prediction, self.birth, self.dif)
# ====================================================================================================
# function群
#
# ====================================================================================================
# ==================================================
# function / データベース関係
# ==================================================
def ProcessGetData(tableName):
"""
///一連タスク:DB接続、SELECTで抽出、DataFrameでreturn///
"""
#tableName = "SanagiTable"
bf = DBconnection()
bf.connection
bf.cur
data = bf.Getdata(tableName)
return data
# ==================================================
# function / Treeview関係
# ==================================================
def TreeDataImport(tree,data):
"""
///Treeviewへデータ挿入///
///SQLから抽出したリストを、Treeviewへinsert
"""
# まずはツリー表示のデータをクリア
tree.delete(*tree.get_children())
# データ挿入
a = len(data)
for i in range(a):
tree.insert("", "end", values=(data[i][0], data[i][1],data[i][2],data[i][3],data[i][4],data[i][5]))
# ==================================================
# function / popup
# ==================================================
def PopUp0():
"""
///処理完了をユーザーへ通知する(汎用型)///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info','処理完了')
def PopUp1(id):
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info','書き込み完了しましたよん', detail="【ID】:" + id)
def PopUp2():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '新規の書き込み完了~♪')
def PopUp3():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '削除したい箇所を選択してね')
def PopUp4():
"""
///実行していいですか?///
"""
res = messagebox.askquestion("注意", "実行していいですか?")
return res
def PopUp5():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '削除完了')
def PopUp6():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '再読み込み完了')
def PopUp7():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', 'DBテーブル削除、新規作成完了')
def PopUp8():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '入力スペースに入力後、書き込みボタンを押してね')
def PopUp9():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', 'サナギになった日を入れてから、書き込みボタンを押してね')
def PopUp10():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '数字8文字でお願い~\n2020/5/20の場合は、\n20210520って感じで~')
def PopUp11():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', 'DB/テーブルがからっぽ\n処理できないっす')
def PopUp12():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '未入力だよ~')
def PopUp13():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '数字で入力しておくれ')
def PopUp14():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '数字を8文字で~~')
def PopUp15():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '入力チェック完了')
# ==================================================
# function / ファイル関係
# ==================================================
def ReadDataFromOterFile():
"""
///データファイルのリストを再リスト化する
///データファイルの要素数=3
///使用したいデータ要素数=5(追加:prediction,dif)
"""
# データファイル
import sanagi5_data
l = sanagi5_data.l
max = len(l)
newList=[[]]
# --------------------
# edit data
# --------------------
for i in range(0,max,1):
# Sanagi class
s = Sanagi(l[i][0],l[i][1],l[i][2])
newList = s.RenewList(newList)
# 1行目からっぽなので削除
newList.pop(0)
return newList
# ==================================================
# function / データベース関係
# ==================================================
def TableExsistenceCheckAndCreate():
"""
///テーブル有無チェック後、テーブルを作る
"""
dbc = DBconnection()
tableName = "SanagiTable"
cur = dbc.CheckTableExistence(tableName)
# Check the Existence of table and Create the table
if cur.fetchone() == (0,):
print("SanagiTable is not existed then created")
dbc.CreateTable(tableName)
else:
print('SanagiTable exists')
dbc.Commit()
dbc.Close()
def TableDropAndCreate():
"""
///テーブル削除、作成
"""
dbc = DBconnection()
tableName = "SanagiTable"
# テーブル削除
dbc.DropTable(tableName)
dbc.Commit()
# 新規テーブル作成
dbc.CreateTable(tableName)
dbc.Commit()
# CLOSE
dbc.Close()
# ==================================================
# function / datetime関係
# ==================================================
def StrToDateTime(str):
"""
///文字列をDatetime型にする
///戻り値:datetime
"""
r = datetime.datetime.strptime(str, '%Y%m%d')
return r
def IntToTimedelta(n):
"""
///整数INTをtimedeltaにする(加減算用)
///戻り値:timedelta
"""
r = datetime.timedelta(days = n)
return r
"""
def IsOk(diff):
#///半角数字の入力のみ受け付ける
if not diff.encode('utf-8').isdigit():
# 妥当でない(半角数字でない)場合はFalseを返却
print("false")
return False
# 妥当(半角数字である)の場合はTrueを返却
print("true")
return True
"""
# ==================================================
# function / Entry欄
# ==================================================
def AllEntryDisable(entry_1,entry_2,entry_3,entry_4,entry_5,entry_6):
"""
///Entry欄の入力を全て不可にする
"""
entry_1.configure(state='disabled')
entry_2.configure(state='disabled')
entry_3.configure(state='disabled')
entry_4.configure(state='disabled')
entry_5.configure(state='disabled')
entry_6.configure(state='disabled')
def AllEntryEnable(entry_1,entry_2,entry_3,entry_4,entry_5,entry_6):
"""
///Entry欄の入力を全て可能にする
"""
entry_1.configure(state='normal')
entry_2.configure(state='normal')
entry_3.configure(state='normal')
entry_4.configure(state='normal')
entry_5.configure(state='normal')
entry_6.configure(state='normal')
def AllEntryInfoErase(entry_1,entry_2,entry_3,entry_4,entry_5,entry_6):
"""
///Entry欄の情報を全て削除する
"""
entry_1.delete(0, tk.END)
entry_2.delete(0, tk.END)
entry_3.delete(0, tk.END)
entry_4.delete(0, tk.END)
entry_5.delete(0, tk.END)
entry_6.delete(0, tk.END)
# ==================================================
# function / フォルダ
# ==================================================
def CheckCsvFolderExists():
"""
///CSVファイルの保存先フォルダ有無チェック、作成///
///戻り値:フォルダ名(string)
"""
# 探すべきフォルダ名
s1 = "csv_read_fld"
s2 = "csv_out_fld"
s3 = "table_out_fld"
s_array = (s1,s2,s3)
for s in s_array:
if not os.path.exists(s):
# ディレクトリが存在しない場合、ディレクトリを作成する
print("Not exists, and created")
os.makedirs(s)
return s1,s2,s3
# ==================================================
# function / dataframe
# ==================================================
def ToPandasDataFrame(data):
"""
///Pandas dataframeにする
///戻り値:データフレーム
"""
#columnsArray = ["name", "sanagi", "prediction", "birth", "dif"]
df = pd.DataFrame(data,columns=["id","name", "sanagi", "prediction", "birth", "dif"])
return df
# ==================================================
# function / ファイルダイヤログ
# ==================================================
def OpenFileDialog(s1):
"""
///ファイルダイヤログを開き、ファイル選択可能な状態に
///戻り値:ファイルパス
"""
#dirName = "csv_read_fld/"
dirName = s1 + "/"
typeList = [('CSVファイル','*.csv')]
filename = filedialog.askopenfilename(
title = "画像ファイルを開く",
filetypes = typeList,
initialdir = dirName
)
return filename
def CsvOpenAndReader(filePath):
"""
///CSV読込み、リストにして戻す
///戻り値:リスト
"""
with open(filePath,'r',encoding="utf-8") as f:
reader = csv.reader(f)
# 1行ごとに読み込み、リストにする
l = [row for row in reader]
# 0行目(ラベル情報)のため削除
l.pop(0)
return l
def GetTimeStamp():
"""
///ファイル保存用のタイムスタンプ文字列
///戻り値:文字列
"""
dt = datetime.datetime.now()
dt = dt.strftime('%Y_%m%d_%H%M%S')
return dt
def CreatePltTable(df):
"""
///Matplotlib.tableで表を作成する
"""
titleName= "サナギ羽化観察"
plt.rcParams["font.family"] = "IPAexGothic"
# index number(1-)
length = len(df)
row_names=[]
for i in range(1,length + 1,1):
row_names.append(i)
fig, ax = plt.subplots(figsize=(10, 10))
ax.set(title= titleName)
ax.axis('off')
ax.axis('tight')
tb = ax.table(cellText=df.values,
colLabels=df.columns,rowLabels=row_names,loc='upper center',
bbox=[0, 0, 1, 1],
)
return fig
# save table image as jpg file(Weather info as table)
def SaveTablefig(fig,fldname):
"""
///Matplotlib.tableをJPG保存する
"""
currentdir = os.getcwd()
figName = "Sanagi"
timestamp = GetTimeStamp()
figfldName = "/" + fldname + "/"
fig.savefig(currentdir + figfldName + timestamp + figName + "_.jpg")
# ====================================================================================================
# ウィジェット起動/メイン
# ====================================================================================================
root = tk.Tk()
app = Application(master=root)
app.mainloop()<file_sep>/tenki/f02.py
# ==================================================
# library
# ==================================================
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
from tkinter import filedialog
import sqlite3
import pandas as pd
import datetime
import os
import csv
import sys
import matplotlib.pyplot as plt
import japanize_matplotlib
import requests
import bs4
"""
趣旨:自分の住んでいる場所の今後の天気情報/予報を「直感的」に把握したい。
経緯:「気温、湿度、風速、雨量」を把握し、出かける際の服装・持ち物を決めたい。
情報源:tenki.jp
上記より情報を取得し、データベースに格納
データベースから引き出した情報をウィジェット内ツリービューに表示
matplotチャートで出力・表示
そのほか:csv読み込み、書き出し
"""
# =============================================================================================
# class / bs4
# =============================================================================================
class BS4:
def __init__(self,URL):
self.r = requests.get(URL)
self.s = bs4.BeautifulSoup(self.r.text, 'html.parser')
def scraping(self,a,b,c):
"""
bs4で抽出したテキストからさらに絞り込み
引数:htmlのクラス、要素など
戻値:リスト
a = 'tr'
b = 'head'
c = 'p'
"""
list1= []
for j in self.s.find_all(a , class_ = b):
for i in j.find_all(c):
list1.append(i.text)
return list1
# =============================================================================================
# bs4
# =============================================================================================
def ProcessScraping(URL,a,b,c):
"""
///Webスクレイピングのプロセス
"""
bs4 = BS4(URL)
r = bs4.scraping(a,b,c)
return r
# ====================================================================================================
# ウィジェット
# ====================================================================================================
class Application(tk.Frame):
def __init__(self, master=None):
"""
///ウィジェット親クラス///
"""
super().__init__(master)
self.master = master
# 全体ウィンドウサイズ、配置位置
self.master.geometry("1300x900+0+0")
# ウィンドウのタイトル
self.master.title("tenki.jpの天気予報")
# 上記を反映する
self.pack()
# ウィンドウ内のウィジェットを配置
self.create_widgets()
def create_widgets(self):
"""
///ウィジェットの配置///
///この中でウィジェット部品を配置する///
"""
# ウィジェットのスタイル設定
self.style = ttk.Style()
fontsize_t1 = 13
fontsize_t2 = 10
# Treeview headingのフォント
self.style.configure("Treeview.Heading",font=("",fontsize_t1))
# Treeview内のフォント
self.style.configure("Treeview",font=("",fontsize_t2))
# -------------------------
# DB / テーブル有無チェック
# -------------------------
# DB / DB名
dbname = "tenki.db"
# DB / table名
tableName="WeatherTable"
# テーブル有無確認、無ければ作成
TableExsistenceCheckAndCreate(dbname,tableName)
# -------------------------
# master / frame
# -------------------------
#tcl_isOk = self.register(IsOk)
self.frame0 = tk.Frame(self, width=800, height=100)
self.frame1 = tk.Frame(self, width=800, height=100)
self.frame2 = tk.Frame(self, width=800, height=300)
self.frame3 = tk.Frame(self, width=800, height=100)
self.frame4 = tk.Frame(self, width=800, height=100)
self.frame5 = tk.Frame(self, width=800, height=100)
self.frame6 = tk.Frame(self, width=800, height=100)
self.frame0.grid(column=0,row=0,padx=5,pady=5)
self.frame1.grid(column=0,row=1,padx=5,pady=5)
self.frame2.grid(column=0,row=2,padx=5,pady=5)
self.frame3.grid(column=0,row=3,padx=5,pady=5)
self.frame4.grid(column=0,row=4,padx=5,pady=5)
self.frame5.grid(column=0,row=5,padx=5,pady=5)
self.frame6.grid(column=0,row=6,padx=5,pady=5)
# --------------------------------------------------
# 【変数】ウィジェット間距離など
# --------------------------------------------------
pad_x1 = 10
pad_y1 = 3
width1 = 10
width2 = 10
Lbl_name1 = "ID"
Lbl_name2 = "hour"
Lbl_name3 = "weather"
Lbl_name4 = "temperature"
Lbl_name5 = "humidity"
Lbl_name6 = "windblow"
Lbl_name7 = "wind-speed"
Lbl_name8 = "precipitation"
fontsize1 = 15
fontsize2 = 12
width_treeview1 = 100
# Entry欄のheight
ipady_1 = 15
# 情報取得したいURL
URL_yokohama ='https://tenki.jp/forecast/3/17/4610/14100/1hour.html'
URL_saku ='https://tenki.jp/forecast/3/23/4820/20217/1hour.html'
URL_nagoya ='https://tenki.jp/forecast/5/26/5110/23100/1hour.html'
URL_fukuoka='https://tenki.jp/forecast/9/43/8210/40130/1hour.html'
URL_kagoshima ='https://tenki.jp/forecast/9/49/8810/46201/1hour.html'
URL_sapporo ='https://tenki.jp/forecast/1/2/1400/1100/1hour.html'
URL_fukushima = 'https://tenki.jp/forecast/2/10/3610/7201/1hour.html'
URL_aomori = 'https://tenki.jp/forecast/2/5/3110/2201/1hour.html'
URL_osaka = 'https://tenki.jp/forecast/6/30/6200/27100/1hour.html'
URL_onomichi ='https://tenki.jp/forecast/7/37/6710/34205/1hour.html'
URL_kouchi = 'https://tenki.jp/forecast/8/42/7410/39201/1hour.html'
# --------------------------------------------------
# frame0 / button
# --------------------------------------------------
t1 = '横浜市'
t2 = '佐久市'
t3 = '名古屋市'
t4 = '福岡市'
t5 = '鹿児島市'
t6 = '札幌市'
t7 = '福島市'
t8 = '青森市'
t9 = '大阪市'
t10 = '尾道市'
t11 = '高知市'
self.btn_20= tk.Button(self.frame0, text = t1, command=lambda:self.Push2(URL_yokohama,dbname,tableName,t1),font=("",fontsize1))
self.btn_20.grid(column=0,row=0,padx=pad_x1,pady=pad_y1)
self.btn_21= tk.Button(self.frame0, text = t2, command=lambda:self.Push2(URL_saku,dbname,tableName,t2),font=("",fontsize1))
self.btn_21.grid(column=1,row=0,padx=pad_x1,pady=pad_y1)
self.btn_22= tk.Button(self.frame0, text = t3, command=lambda:self.Push2(URL_nagoya,dbname,tableName,t3),font=("",fontsize1))
self.btn_22.grid(column=2,row=0,padx=pad_x1,pady=pad_y1)
self.btn_23= tk.Button(self.frame0, text = t4, command=lambda:self.Push2(URL_fukuoka,dbname,tableName,t4),font=("",fontsize1))
self.btn_23.grid(column=3,row=0,padx=pad_x1,pady=pad_y1)
self.btn_24= tk.Button(self.frame0, text = t5, command=lambda:self.Push2(URL_kagoshima,dbname,tableName,t5),font=("",fontsize1))
self.btn_24.grid(column=4,row=0,padx=pad_x1,pady=pad_y1)
self.btn_25= tk.Button(self.frame0, text = t6, command=lambda:self.Push2(URL_sapporo,dbname,tableName,t6),font=("",fontsize1))
self.btn_25.grid(column=5,row=0,padx=pad_x1,pady=pad_y1)
self.btn_26= tk.Button(self.frame0, text = t7, command=lambda:self.Push2(URL_fukushima,dbname,tableName,t7),font=("",fontsize1))
self.btn_26.grid(column=6,row=0,padx=pad_x1,pady=pad_y1)
self.btn_27= tk.Button(self.frame0, text = t8, command=lambda:self.Push2(URL_aomori,dbname,tableName,t8),font=("",fontsize1))
self.btn_27.grid(column=7,row=0,padx=pad_x1,pady=pad_y1)
self.btn_28= tk.Button(self.frame0, text = t9, command=lambda:self.Push2(URL_osaka,dbname,tableName,t9),font=("",fontsize1))
self.btn_28.grid(column=8,row=0,padx=pad_x1,pady=pad_y1)
self.btn_29= tk.Button(self.frame0, text = t10, command=lambda:self.Push2(URL_onomichi,dbname,tableName,t10),font=("",fontsize1))
self.btn_29.grid(column=9,row=0,padx=pad_x1,pady=pad_y1)
self.btn_30= tk.Button(self.frame0, text = t11, command=lambda:self.Push2(URL_kouchi,dbname,tableName,t11),font=("",fontsize1))
self.btn_30.grid(column=10,row=0,padx=pad_x1,pady=pad_y1)
# --------------------------------------------------
# frame1 / button
# --------------------------------------------------
self.btn_4= tk.Button(self.frame1, text = 'DB読込み', command=lambda:self.Push4(dbname,tableName),font=("",fontsize1))
self.btn_4.grid(column=2,row=1,padx=pad_x1,pady=pad_y1)
self.btn_6= tk.Button(self.frame1, text = 'テーブル削除/作成', command=lambda:self.Push6(dbname,tableName),font=("",fontsize1))
self.btn_6.grid(column=3,row=1,padx=pad_x1,pady=pad_y1)
self.btn_9= tk.Button(self.frame1, text = 'CSV読み込み', command=self.Push10,font=("",fontsize1))
self.btn_9.grid(column=5,row=1,padx=pad_x1,pady=pad_y1)
self.btn_10= tk.Button(self.frame1, text = 'CSV出力', command=lambda:self.Push11(dbname,tableName),font=("",fontsize1))
self.btn_10.grid(column=6,row=1,padx=pad_x1,pady=pad_y1)
self.btn_11= tk.Button(self.frame1, text = '表jpg出力', command=lambda:self.Push12(dbname,tableName),font=("",fontsize1))
self.btn_11.grid(column=7,row=1,padx=pad_x1,pady=pad_y1)
self.btn_12= tk.Button(self.frame1, text = 'チャート出力', command=lambda:self.Push13(dbname,tableName),font=("",fontsize1))
self.btn_12.grid(column=7,row=1,padx=pad_x1,pady=pad_y1)
# --------------------------------------------------
# frame2 / Label,Entry
# --------------------------------------------------
# 選択したデータの表示場所&入力箇所
self.Label_1 = tk.Label(self.frame2, text = Lbl_name1, width = width1, bg='gray',fg='white',font=("",fontsize1))
self.Label_1.grid(column=0,row=1,padx=pad_x1,pady=pad_y1)
self.entry_1 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_1.grid(column=0,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_2 = tk.Label(self.frame2, text = Lbl_name2, width = width1, bg='gray',fg='white',font=("",fontsize1))
self.Label_2.grid(column=1,row=1,padx=pad_x1,pady=pad_y1)
self.entry_2 = tk.Entry(self.frame2,width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_2.grid(column=1,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_3 = tk.Label(self.frame2, text = Lbl_name3, width = width1, bg='gray',fg='white',font=("",fontsize1))
self.Label_3.grid(column=2,row=1,padx=pad_x1,pady=pad_y1)
self.entry_3 = tk.Entry(self.frame2,width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_3.grid(column=2,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_4 = tk.Label(self.frame2, text = Lbl_name4, width = width1, bg='gray', fg='white',font=("",fontsize1))
self.Label_4.grid(column=3,row=1,padx=pad_x1,pady=pad_y1)
self.entry_4 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_4.grid(column=3,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_5 = tk.Label(self.frame2, text = Lbl_name5, width = width1, bg='gray', fg='white',font=("",fontsize1))
self.Label_5.grid(column=4,row=1,padx=pad_x1,pady=pad_y1)
self.entry_5 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_5.grid(column=4,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_6 = tk.Label(self.frame2, text = Lbl_name6, width = width1, bg='gray', fg='white',font=("",fontsize1))
self.Label_6.grid(column=5,row=1,padx=pad_x1,pady=pad_y1)
self.entry_6 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_6.grid(column=5,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_7 = tk.Label(self.frame2, text = Lbl_name7, width = width1, bg='gray', fg='white',font=("",fontsize1))
self.Label_7.grid(column=6,row=1,padx=pad_x1,pady=pad_y1)
self.entry_7 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_7.grid(column=6,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
self.Label_8 = tk.Label(self.frame2, text = Lbl_name8, width = width1, bg='gray', fg='white',font=("",fontsize1))
self.Label_8.grid(column=7,row=1,padx=pad_x1,pady=pad_y1)
self.entry_8 = tk.Entry(self.frame2, width=width2, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_8.grid(column=7,row=2,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
# --------------------------------------------------
# frame3 / button
# --------------------------------------------------
# 書き込みボタン
self.btn_1= tk.Button(self.frame3, text = '書き込み', command=lambda:self.Push1(dbname,tableName),width=30,font=("",fontsize1))
self.btn_1.grid(column=1,row=0,padx=pad_x1,pady=pad_y1)
# 削除ボタン
self.btn_3= tk.Button(self.frame3, text = '削除処理', command=lambda:self.Push3(dbname,tableName),width=30,font=("",fontsize1))
self.btn_3.grid(column=2,row=0,padx=pad_x1,pady=pad_y1)
# --------------------------------------------------
# frame4 / entry
# --------------------------------------------------
self.entry_9 = tk.Entry(self.frame4, width=80, bg='white',fg='black',justify='center',font=("",fontsize2))
self.entry_9.grid(column=0,row=0,padx=pad_x1,pady=pad_y1,ipady=ipady_1)
# -------------------------
# frame5 / treeview
# -------------------------
self.tree = ttk.Treeview(self.frame5, height = 20, style='Treeview')
# treeの設定
self.tree["columns"] = (1,2,3,4,5,6,7,8)
self.tree["show"] = "headings"
self.tree.column(1, width=width_treeview1,anchor=tk.CENTER)
self.tree.column(2, width=width_treeview1,anchor=tk.CENTER)
self.tree.column(3, width=width_treeview1,anchor=tk.CENTER)
self.tree.column(4, width=width_treeview1,anchor=tk.CENTER)
self.tree.column(5, width=width_treeview1,anchor=tk.CENTER)
self.tree.column(6, width=width_treeview1,anchor=tk.CENTER)
self.tree.column(7, width=width_treeview1,anchor=tk.CENTER)
self.tree.column(8, width=width_treeview1,anchor=tk.CENTER)
self.tree.heading(1, text=Lbl_name1)
self.tree.heading(2, text=Lbl_name2)
self.tree.heading(3, text=Lbl_name3)
self.tree.heading(4, text=Lbl_name4)
self.tree.heading(5, text=Lbl_name5)
self.tree.heading(6, text=Lbl_name6)
self.tree.heading(7, text=Lbl_name7)
self.tree.heading(8, text=Lbl_name8)
# --------------------------------------------------
# frame6 / Quit button
# --------------------------------------------------
self.btn_2= tk.Button(self.frame6, text="閉じる", fg="black",command=self.master.destroy,font=("",fontsize1))
self.btn_2.grid(column=0,row=0,padx=pad_x1,pady=pad_y1)
# --------------------------------------------------
# Entry入力不可状態の処理
# --------------------------------------------------
AllEntryDisable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6,self.entry_7,self.entry_8,self.entry_9)
# --------------------------------------------------
#ツリー内をマウスで選択した時
# --------------------------------------------------
self.tree.bind("<<TreeviewSelect>>", self.OnTreeSelect)
# pack
self.tree.pack()
# DB/Tableの有無のチェック、無ければ作成する
TableExsistenceCheckAndCreate(dbname,tableName)
def OnTreeSelect(self,event):
"""
///ツリービュー内の情報を選択したときの処理///
"""
# Entryの入力可能処理
AllEntryEnable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6,self.entry_7,self.entry_8,self.entry_9)
for id in self.tree.selection():
#Dicionary形式で抽出
self.tree.set(id)
mydic = self.tree.set(id)
d1 = mydic['1']
d2 = mydic['2']
d3 = mydic['3']
d4 = mydic['4']
d5 = mydic['5']
d6 = mydic['6']
d7 = mydic['7']
d8 = mydic['8']
# 中身をいったん消してから/データ挿入
AllEntryInfoErase(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6,self.entry_7,self.entry_8,self.entry_9)
# データを入れる
self.entry_1.insert(tk.END,d1)
self.entry_2.insert(tk.END,d2)
self.entry_3.insert(tk.END,d3)
self.entry_4.insert(tk.END,d4)
self.entry_5.insert(tk.END,d5)
self.entry_6.insert(tk.END,d6)
self.entry_7.insert(tk.END,d7)
self.entry_8.insert(tk.END,d8)
def Push1(self,dbname,tableName):
"""
///書き込みボタン押下時の処理///
///Entry内の情報を読み取り、DBへ登録する///
"""
# ------------------------------
# 実行前の確認処理
# ------------------------------
res = PopUp4()
# yesで抜けて進む
if res =="yes":
pass
# noで終了処理
else:
return
# ------------------------------
# 処理の開始
#-------------------------------
# Entry欄の情報取得
e1 = self.entry_1.get()
e2 = self.entry_2.get()
e3 = self.entry_3.get()
e4 = self.entry_4.get()
e5 = self.entry_5.get()
e6 = self.entry_6.get()
e7 = self.entry_7.get()
e8 = self.entry_8.get()
# DB接続し、
dbc = DBconnection(dbname)
# UPDATE/INSERTの振り分け(ID有無で振り分け)
if e1 != "":
# データ/UPDATE
dbc.Updatedata(tableName,e1,e2,e3,e4,e5,e6,e7,e8)
else:
# データ/INSERT
dbc.InsertData(tableName,e2,e3,e4,e5,e6,e7,e8)
# DB COMMIT/CLOSE
dbc.Commit()
dbc.Close()
# DBを再読み込み
data = ProcessGetData(dbname,tableName)
# データ挿入
TreeDataImport(self.tree,data)
# ポップアップ通知
if e1 != "":
PopUp1(e1)
else:
PopUp2()
def Push2(self,URL,dbname,tableName,prefecture):
"""
///Webスクレイピング処理///
"""
# Webのタグ情報を収集する
r1,r2,r3,r4,r5,r6,r7,r8 = ProcessAllTagInfo(URL)
# pandas
df = ToPandasDataFrame2(r2,r3,r4,r5,r6,r7,r8)
pd.set_option('display.max_rows', None)
# DB/table drop
TableDropAndCreate(dbname,tableName)
# DB/ inseert
dbc = DBconnection(dbname)
df.to_sql("WeatherTable",dbc.connection,if_exists='append',index=None)
dbc.Commit
dbc.Close
# DB/select、Treeview
data = ProcessGetData(dbname,tableName)
TreeDataImport(self.tree,data)
# Entryの入力制限
AllEntryEnable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6,self.entry_7,self.entry_8,self.entry_9)
# entryをすべて消す
AllEntryInfoErase(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6,self.entry_7,self.entry_8,self.entry_9)
# entryに「●●市」と入れる
self.entry_9.insert(tk.END,prefecture + "のお天気情報")
# entryを入力不可
# Entryの入力制限
AllEntryDisable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6,self.entry_7,self.entry_8,self.entry_9)
# 通知
PopUp0()
def Push3(self,dbname,tableName):
"""
///1つのレコードを削除///
Entry情報を読み取る
IDがない場合、「できない」処理
IDありの場合、「いいですか?」
ID指定で、削除処理、完了通知
"""
e1 = self.entry_1.get()
e2 = self.entry_2.get()
e3 = self.entry_3.get()
e4 = self.entry_4.get()
e5 = self.entry_5.get()
e6 = self.entry_6.get()
# IDが無い場合
if e1 == "":
PopUp3()
return
# IDがある場合
else:
# 処理前の確認
res = PopUp4()
# yesで抜けて進む
if res =="yes":
pass
# noで終了処理
else:
return
# DB接続
dbc = DBconnection(dbname)
#実行処理
dbc.DeleteRecordData(tableName,e1)
# COMMIT/CLOSE
dbc.Commit()
dbc.Close()
# DBを再読み込み
df = ProcessGetData(dbname,tableName)
# データ挿入
TreeDataImport(self.tree,df)
# 通知
PopUp5()
def Push4(self,dbname,tableName):
"""
///再読み込みボタン///
///DB読込みをしてツリービューに表示する///
ツリービューのデータ削除、読み込み
Entryのデータ削除
"""
# DBを再読み込み
data = ProcessGetData(dbname,tableName)
# データ挿入
TreeDataImport(self.tree,data)
# ポップアップ通知
PopUp6()
def Push6(self,dbname,tableName):
"""
///テーブル削除、新規でテーブル作成する
"""
# ------------------------------
# 実行前の確認処理
# ------------------------------
res = PopUp4()
# yesで抜けて進む
if res =="yes":
pass
# noで終了処理
else:
return
# テーブル削除、作成
TableDropAndCreate(dbname,tableName)
# DB/SELECT、ツリー表示
# DBを再読み込み
data = ProcessGetData(dbname,tableName)
# データ挿入
TreeDataImport(self.tree,data)
# Entryの入力制限
AllEntryEnable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6,self.entry_7,self.entry_8,self.entry_9)
# Entry欄の情報削除
AllEntryInfoErase(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6,self.entry_7,self.entry_8,self.entry_9)
# Entryの入力制限
AllEntryDisable(self.entry_1,self.entry_2,self.entry_3,self.entry_4,self.entry_5,self.entry_6,self.entry_7,self.entry_8,self.entry_9)
# 通知
PopUp7()
def Push10(self):
"""
///CSVの読み込み
"""
# CSVファイルの保存先のチェック
s1,s2,s3 = CheckCsvFolderExists()
# ファイルダイヤログ表示、ファイル選択ができるように。
filePath = OpenFileDialog(s1)
# ダイヤログでキャンセルボタン押下の場合の処理
if filePath == "":
return
# CSV読み込み / List型
data = CsvOpenAndReader(filePath)
# ツリーへデータ挿入
TreeDataImport(self.tree,data)
# 通知
PopUp0()
def Push11(self,dbname,tableName):
"""
///CSVの出力
///DBデータを抽出し、CSVファイルとして出力する
"""
# CSVファイルの保存先のチェック
s1,s2,s3 = CheckCsvFolderExists()
# DB接続、データをSELECT*で引っ張る
# DBを再読み込み
data = ProcessGetData(dbname,tableName)
# Pandas / Dataframeにする
df = ToPandasDataFrame(data)
# Timestamp
Tstamp = GetTimeStamp()
# CSVのファイルにする
FldName = s2
csvName = "_out.csv"
dirName = FldName + "\\"
fileSavePath = dirName + Tstamp + csvName
# CSVへ出力
df.to_csv(fileSavePath,index=False,encoding='utf_8_sig')
# 完了通知
PopUp0()
def Push12(self,dbname,tableName):
"""
///Matplotlib.tableの表jpgを出力、保存
"""
# jpg保存先フォルダ有無のチェック
s1,s2,s3 = CheckCsvFolderExists()
# DB接続、データをSELECT*で引っ張る
# DBを再読み込み
data = ProcessGetData(dbname,tableName)
# Pandas / Dataframeにする
df = ToPandasDataFrame(data)
# チェック/dfがない場合はSTOP
if len(df)==0:
PopUp11()
return
# Timestamp
Tstamp = GetTimeStamp()
# matplotに渡す
fig = CreatePltTable(df)
# Save as jpg
SaveTablefig(fig,s3)
# Matplotlib.table終了処理
plt.clf()
plt.close()
# 通知
PopUp0()
def Push13(self,dbname,tableName):
"""
///MATPLOTチャートを出力し、表示する
"""
# チャート用のタイトルテキストを取得
e9 = self.entry_9.get()
# DBからデータをもらう
data = ProcessGetData(dbname,tableName)
# DFにする
df = ToPandasDataFrame(data)
# DF ⇒ MATPLOT
chart = CreatPltChart(df,e9)
plt.show()
def CreatPltChart(df,charttitle):
"""
///Matplotの表を作成する
"""
# グラフ上限値を決めておく(5℃~25℃)
tempMin = 10
tempMax = 35
humidMin = 0
humidMax = 100
windMin = 0
windMax = 15
precipiMin = 0
precipiMax = 30
x1 = df.hour
y1 = df.temperature
x2 = df.hour
y2 = df.humidity
x3 = df.hour
y3 = df.windspeed
x4 = df.hour
y4 = df.precipitation
# 日付情報取得
td2 = GetTimeStamp()
# fig1-------------------------------
fig1 = plt.figure(charttitle,figsize=(8,8))
# (data)----------------------------
chart1 = fig1.add_subplot(2,2,1)
chart1.plot(x1, y1)
plt.ylim(tempMin, tempMax)
# グラフ内のラベル表記
chart1.set_title(td2 + " / Temperature")
chart1.set_xlabel("Time")
chart1.set_ylabel("Temperature(℃)")
# fig2-------------------------------
#fig2 = plt.figure(td2 + "_01")
# (data)----------------------------
chart2 = fig1.add_subplot(2,2,2)
chart2.plot(x2, y2)
plt.ylim(humidMin, humidMax)
# グラフ内のラベル表記
chart2.set_title(td2 + " / Humidity")
chart2.set_xlabel("Time")
chart2.set_ylabel("Humidity(%)")
# fig3-------------------------------
#fig3 = plt.figure(td2 + "_01")
# (data)----------------------------
chart3 = fig1.add_subplot(2,2,3)
chart3.plot(x3, y3)
plt.ylim(windMin, windMax)
# グラフ内のラベル表記
chart3.set_title(td2 + " / WindSpeed")
chart3.set_xlabel("Time")
chart3.set_ylabel("WindSpeed(m/h)")
# fig3-------------------------------
#fig4 = plt.figure(td2 + "_01")
# (data)----------------------------
chart4 = fig1.add_subplot(2,2,4)
chart4.plot(x4, y4)
plt.ylim(windMin, windMax)
# グラフ内のラベル表記
chart4.set_title(td2 + " / Precipitation")
chart4.set_xlabel("Time")
chart4.set_ylabel("Precipitation(mm/h)")
#-----------------------------
# グラフの設定
#-----------------------------
fig1.tight_layout()
#-----------------------------
# 戻り値
#-----------------------------
fig_all = (fig1)
return fig_all
# ====================================================================================================
# データベース
# ====================================================================================================
# ///基本情報:
# データベース名:butterfly.db
# テーブル名:SanagiTable
# カラム名:id,name,sanagi,prediction,birth,dif
class DBconnection:
"""
データベース関係:
"""
def __init__(self,dbname):
"""
///データベース接続///
"""
self.connection = sqlite3.connect(dbname)
self.cur = self.connection.cursor()
def Commit(self):
"""
///データコミット///
"""
r = self.connection.commit()
return r
def Close(self):
"""
///データベースクローズ///
"""
r = self.cur.close()
return r
def Getdata(self,tableName):
"""
///データベースから情報取得///
"""
r = self.cur.execute("SELECT * FROM %s" % tableName)
r = r.fetchall()
return r
def Updatedata(self,tableName,e1,e2,e3,e4,e5,e6,e7,e8):
"""
///データベースに既存情報を書き換え・更新///
"""
self.cur.execute("UPDATE %s SET hour=?,weather=?,temperature=?,humidity=?,windblow=? ,windspeed=?,precipitation=? WHERE id=?" % tableName,(e2,e3,e4,e5,e6,e7,e8,e1))
def InsertData(self,tableName,e2,e3,e4,e5,e6,e7,e8):
"""
///データベースに、新規情報をインサートする///
変数:テーブル名は%s、VALUESは?で。
"""
self.cur.execute("INSERT INTO %s(hour,weather,temperature,himidity,windblow,windspeed,precipitation) VALUES(?,?,?,?,?,?,?)" % tableName,(e2,e3,e4,e5,e6,e7,e8))
def DeleteRecordData(self,tableName,e1):
"""
///データベースから、特定の1つのレコードを削除する///
注意:引数は(e1,)とタプルで渡すこと。(e1)だと文字列で誤解する
"""
self.cur.execute("DELETE FROM %s WHERE id=%s" %(tableName,e1))
def DropTable(self,tableName):
"""
///テーブル削除///
"""
self.cur.execute("DROP TABLE %s" % tableName)
def CreateTable(self,tableName):
"""
///Tableの作成///
"""
sql = 'CREATE TABLE %s(id INTEGER PRIMARY KEY AUTOINCREMENT, hour INTEGER, weather STRING, temperature REAL, humidity REAL, windblow STRING, windspeed INTEGER, precipitation INTEGER )' % tableName
self.cur.execute(sql)
def CheckTableExistence(self,tableName):
"""
///DB内のテーブル名有無をチェック
"""
r = self.cur.execute('SELECT COUNT(*) FROM sqlite_master WHERE TYPE="table" AND NAME="%s"' % tableName)
return r
# ====================================================================================================
# function群
#
# ====================================================================================================
# ==================================================
# function / データベース関係
# ==================================================
def ProcessGetData(dbname,tableName):
"""
///一連タスク:DB接続、SELECTで抽出、DataFrameでreturn///
"""
dbc = DBconnection(dbname)
dbc.connection
dbc.cur
data = dbc.Getdata(tableName)
return data
# ==================================================
# function / Treeview関係
# ==================================================
def TreeDataImport(tree,data):
"""
///Treeviewへデータ挿入///
///SQLから抽出したリストを、Treeviewへinsert
"""
# まずはツリー表示のデータをクリア
tree.delete(*tree.get_children())
# データ挿入
a = len(data)
for i in range(a):
tree.insert("", "end", values=(data[i][0], data[i][1],data[i][2],data[i][3],data[i][4],data[i][5],data[i][6],data[i][7]))
# ==================================================
# function / popup
# ==================================================
def PopUp0():
"""
///処理完了をユーザーへ通知する(汎用型)///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info','処理完了')
def PopUp1(id):
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info','書き込み完了しましたよん', detail="【ID】:" + id)
def PopUp2():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '新規の書き込み完了~♪')
def PopUp3():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '削除したい箇所を選択してね')
def PopUp4():
"""
///実行していいですか?///
"""
res = messagebox.askquestion("注意", "実行していいですか?")
return res
def PopUp5():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '削除完了')
def PopUp6():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '再読み込み完了')
def PopUp7():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', 'DBテーブル削除、新規作成完了')
def PopUp8():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '入力スペースに入力後、書き込みボタンを押してね')
def PopUp9():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', 'サナギになった日を入れてから、書き込みボタンを押してね')
def PopUp10():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '数字8文字でお願い~\n2020/5/20の場合は、\n20210520って感じで~')
def PopUp11():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', 'DB/テーブルがからっぽ\n処理できないっす')
def PopUp12():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '未入力だよ~')
def PopUp13():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '数字で入力しておくれ')
def PopUp14():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '数字を8文字で~~')
def PopUp15():
"""
///処理完了をユーザーへ通知する///
"""
# メッセージボックス(情報)
messagebox.showinfo('Info', '入力チェック完了')
# ==================================================
# function / データベース関係
# ==================================================
def TableExsistenceCheckAndCreate(dbname,tableName):
"""
///テーブル有無チェック後、テーブルを作る
"""
dbc = DBconnection(dbname)
cur = dbc.CheckTableExistence(tableName)
# Check the Existence of table and Create the table
if cur.fetchone() == (0,):
print("Table is not existed then created")
dbc.CreateTable(tableName)
else:
print('Table exists')
dbc.Commit()
dbc.Close()
def TableDropAndCreate(dbname,tableName):
"""
///テーブル削除、作成
"""
dbc = DBconnection(dbname)
# テーブル削除
dbc.DropTable(tableName)
dbc.Commit()
# 新規テーブル作成
dbc.CreateTable(tableName)
dbc.Commit()
# CLOSE
dbc.Close()
# ==================================================
# function / datetime関係
# ==================================================
def StrToDateTime(str):
"""
///文字列をDatetime型にする
///戻り値:datetime
"""
r = datetime.datetime.strptime(str, '%Y%m%d')
return r
def IntToTimedelta(n):
"""
///整数INTをtimedeltaにする(加減算用)
///戻り値:timedelta
"""
r = datetime.timedelta(days = n)
return r
# ==================================================
# function / Entry欄
# ==================================================
def AllEntryDisable(entry_1,entry_2,entry_3,entry_4,entry_5,entry_6,entry_7,entry_8,entry_9):
"""
///Entry欄の入力を全て不可にする
"""
entry_1.configure(state='disabled')
entry_2.configure(state='disabled')
entry_3.configure(state='disabled')
entry_4.configure(state='disabled')
entry_5.configure(state='disabled')
entry_6.configure(state='disabled')
entry_7.configure(state='disabled')
entry_8.configure(state='disabled')
entry_9.configure(state='disabled')
def AllEntryEnable(entry_1,entry_2,entry_3,entry_4,entry_5,entry_6,entry_7,entry_8,entry_9):
"""
///Entry欄の入力を全て可能にする
"""
entry_1.configure(state='normal')
entry_2.configure(state='normal')
entry_3.configure(state='normal')
entry_4.configure(state='normal')
entry_5.configure(state='normal')
entry_6.configure(state='normal')
entry_7.configure(state='normal')
entry_8.configure(state='normal')
entry_9.configure(state='normal')
def AllEntryInfoErase(entry_1,entry_2,entry_3,entry_4,entry_5,entry_6,entry_7,entry_8,entry_9):
"""
///Entry欄の情報を全て削除する
"""
entry_1.delete(0, tk.END)
entry_2.delete(0, tk.END)
entry_3.delete(0, tk.END)
entry_4.delete(0, tk.END)
entry_5.delete(0, tk.END)
entry_6.delete(0, tk.END)
entry_7.delete(0, tk.END)
entry_8.delete(0, tk.END)
entry_9.delete(0, tk.END)
# ==================================================
# function / フォルダ
# ==================================================
def CheckCsvFolderExists():
"""
///CSVファイルの保存先フォルダ有無チェック、作成///
///戻り値:フォルダ名(string)
"""
# 探すべきフォルダ名
s1 = "csv_read_fld"
s2 = "csv_out_fld"
s3 = "table_out_fld"
s_array = (s1,s2,s3)
for s in s_array:
if not os.path.exists(s):
# ディレクトリが存在しない場合、ディレクトリを作成する
print("Not exists, and created")
os.makedirs(s)
return s1,s2,s3
# ==================================================
# function / dataframe
# ==================================================
def ToPandasDataFrame(data):
"""
///Pandas dataframeにする
引数:data(DB)
戻値:データフレーム
"""
col1 = "id"
col2 = "hour"
col3 = "weather"
col4 = "temperature"
col5 = "humidity"
col6 = "windblow"
col7 = "windspeed"
col8 = "precipitation"
df = pd.DataFrame(data,
columns=[
col1,
col2,
col3,
col4,
col5,
col6,
col7,
col8
])
return df
def ToPandasDataFrame2(r2,r3,r4,r5,r6,r7,r8):
"""
///Pandas dataframeにする
引数:リスト
戻値:データフレーム
"""
col2 = "hour"
col3 = "weather"
col4 = "temperature"
col5 = "humidity"
col6 = "windblow"
col7 = "windspeed"
col8 = "precipitation"
df = pd.DataFrame({
col2:r2,
col3:r3,
col4:r4,
col5:r5,
col6:r6,
col7:r7,
col8:r8
})
return df
# =============================================================================================
# function
# =============================================================================================
def CreateHourList(l):
"""
///hourの値を調整
「0~24、0~24、0~24」の塊になっているので「0~72」にする
"""
r=[]
loopnum=len(l)
for i in range(0,loopnum,1):
if i<=23:
r.append(int(l[i]))
elif i>=24 and i<=47:
r.append(int(l[i])+24)
elif i>=48:
r.append(int(l[i])+48)
return r
def ChangeTypeStrToFloat(l):
"""
///文字列型をFLOAT型に変換する
引数:リスト
戻値:リスト
"""
r = [float(s) for s in l]
return r
def ChangeTypeStrToInt(l):
"""
///文字列型をFLOAT型に変換する
引数:リスト
戻値:リスト
"""
r = [int(s) for s in l]
return r
def ProcessAllTagInfo(URL):
"""
///htmlから必要なタグ情報だけを抽出
引数:URL
戻値:タグ情報(リスト型)
"""
# --------------
# 1.日時(3日分=3こ)
# --------------
a = 'tr'
b = 'head'
c = 'p'
r1 = ProcessScraping(URL,a,b,c)
# --------------
# 2.時刻
# --------------
a = 'tr'
b = 'hour'
c = 'span'
r2 = ProcessScraping(URL,a,b,c)
# [0~24]×3 ⇒ [0~72]にする
r2 = CreateHourList(r2)
# Str⇒intに変換
r2 = ChangeTypeStrToInt(r2)
# --------------
# 3.天気 / 日本語
# --------------
a = 'tr'
b = 'weather'
c = 'p'
r3 = ProcessScraping(URL,a,b,c)
# --------------
# 4.気温
# --------------
a = 'tr'
b = 'temperature'
c = 'span'
r4 = ProcessScraping(URL,a,b,c)
# Str⇒floatに変換
r4 = ChangeTypeStrToFloat(r4)
# --------------
# 5.湿度
# --------------
a = 'tr'
b = 'humidity'
c = 'td'
r5 = ProcessScraping(URL,a,b,c)
# Str⇒floatに変換
r5 = ChangeTypeStrToFloat(r5)
# --------------
# 6.風向き / 日本語
# --------------
a = 'tr'
b = 'wind-blow'
c = 'p'
r6 = ProcessScraping(URL,a,b,c)
# --------------
# 7.風速
# --------------
a = 'tr'
b = 'wind-speed'
c = 'span'
r7 = ProcessScraping(URL,a,b,c)
# Str⇒intに変換
r7 = ChangeTypeStrToInt(r7)
# --------------
# 8.雨量
# --------------
a = 'tr'
b = 'precipitation'
c = 'span'
r8 = ProcessScraping(URL,a,b,c)
# Str⇒intに変換
r8 = ChangeTypeStrToInt(r8)
return r1,r2,r3,r4,r5,r6,r7,r8
# ==================================================
# function / ファイルダイヤログ
# ==================================================
def OpenFileDialog(s1):
"""
///ファイルダイヤログを開き、ファイル選択可能な状態に
///戻り値:ファイルパス
"""
#dirName = "csv_read_fld/"
dirName = s1 + "/"
typeList = [('CSVファイル','*.csv')]
filename = filedialog.askopenfilename(
title = "画像ファイルを開く",
filetypes = typeList,
initialdir = dirName
)
return filename
def CsvOpenAndReader(filePath):
"""
///CSV読込み、リストにして戻す
///戻り値:リスト
"""
with open(filePath,'r',encoding="utf-8") as f:
reader = csv.reader(f)
# 1行ごとに読み込み、リストにする
l = [row for row in reader]
# 0行目(ラベル情報)のため削除
l.pop(0)
return l
def GetTimeStamp():
"""
///ファイル保存用のタイムスタンプ文字列
///戻り値:文字列
"""
dt = datetime.datetime.now()
dt = dt.strftime('%Y_%m%d_%H%M_%S')
return dt
# ====================================================================================================
# ウィジェット起動/メイン
# ====================================================================================================
root = tk.Tk()
app = Application(master=root)
app.mainloop()<file_sep>/Sanagi/sanagi5_data.py
import datetime
# ============================================================================
# data
# サナギになった日,チョウの種類/性別,羽化した日
# ============================================================================
l=[
[datetime.date(2021,4,24),'ナミアゲハ:男', datetime.date(2021,5,4)],
[datetime.date(2021,4,25),'ナミアゲハ:女', datetime.date(2021,5,7)],
[datetime.date(2021,4,28),'ナミアゲハ:男', datetime.date(2021,5,8)],
[datetime.date(2021,4,28),'ナミアゲハ:男', datetime.date(2021,5,8)],
[datetime.date(2021,4,28),'ナミアゲハ:女', datetime.date(2021,5,8)],
[datetime.date(2021,4,29),'ナミアゲハ:女', datetime.date(2021,5,9)],
[datetime.date(2021,4,30),'ナミアゲハ:男', datetime.date(2021,5,10)],
[datetime.date(2021,4,30),'ナミアゲハ:男', datetime.date(2021,5,10)],
[datetime.date(2021,5,9) ,'ナミアゲハ:女', datetime.date(2021,5,20)],
[datetime.date(2021,5,12),'ナミアゲハ:里子へ',0],
[datetime.date(2021,5,13),'ナミアゲハ:里子へ',0],
[datetime.date(2021,5,14),'ナミアゲハ:男', datetime.date(2021,5,25)],
[datetime.date(2021,5,14),'ナミアゲハ:男', datetime.date(2021,5,22)],
[datetime.date(2021,5,15),'クロアゲハ:男', datetime.date(2021,5,27)],
[datetime.date(2021,5,17),'キアゲハ1号:男', datetime.date(2021,5,27)],
[datetime.date(2021,5,22),'ジャコウアゲハ1号:男', datetime.date(2021,6,2)],
[datetime.date(2021,5,22),'キアゲハ2号:', datetime.date(2021,6,1)],
[datetime.date(2021,5,23),'キアゲハ3号:', datetime.date(2021,6,2)],
[datetime.date(2021,5,29),'ナガサキアゲハ:',datetime.date(2021,6,10)],
[datetime.date(2021,5,29),'ジャコウアゲハ:',0],
[datetime.date(2021,5,30),'ジャコウアゲハ:',0],
[datetime.date(2021,6,5),'ナミアゲハ:男',datetime.date(2021,6,14)],
[datetime.date(2021,6,5),'ナミアゲハ:女',datetime.date(2021,6,15)],
[datetime.date(2021,6,5),'ナミアゲハ:里子へ',0],
[datetime.date(2021,6,5),'ナミアゲハ:里子へ',0],
[datetime.date(2021,6,9),'クロアゲハ',datetime.date(2021,6,21)],
[datetime.date(2021,6,12),'ツマグロヒョウモン',datetime.date(2021,6,20)],
[datetime.date(2021,6,12),'ツマグロヒョウモン',datetime.date(2021,6,20)],
[datetime.date(2021,6,3),'オオスカシバ',datetime.date(2021,6,17)],
[datetime.date(2021,6,4),'オオスカシバ',datetime.date(2021,6,18)],
[datetime.date(2021,7,1),'アオスジアゲハ',0],
[datetime.date(2021,7,4),'アオスジアゲハ',0]
]
| f905005b2341a6f1d32a5b95dc9faa617f65948e | [
"Python"
] | 3 | Python | hiro4336/tenki | 8367d5b9081a23870507f28338938e9f8c5ffd35 | 690065c4036feda520c5091c4d07f9e588fc9f31 |
refs/heads/master | <file_sep>using UnityEngine;
using System.Collections;
public class CargoScript : MonoBehaviour {
public UILocationWaypoint locationScript;
public AudioClip cargoLoadingClip;
public AudioClip cargoUnloadingClip;
public AudioClip cargoErrorClip;
public AudioClip cargoCompleteClip;
AudioSource cargoLoading;
AudioSource cargoUnloading;
AudioSource cargoError;
AudioSource cargoComplete;
float cargLoadingTime = 9f;
private float currentActionTimer = 0f;
bool hasCargo = false;
// Use this for initialization
void Start ()
{
cargoLoading = gameObject.AddComponent<AudioSource>();
cargoUnloading = gameObject.AddComponent<AudioSource>();
cargoError = gameObject.AddComponent<AudioSource>();
cargoComplete = gameObject.AddComponent<AudioSource>();
cargoLoading.clip = cargoLoadingClip;
cargoUnloading.clip = cargoUnloadingClip;
cargoError.clip = cargoErrorClip;
cargoComplete.clip = cargoCompleteClip;
}
// Update is called once per frame
void Update () {
float distance = locationScript.distanceToTarget();
//Debug.Log("Distance: " + distance);
if (distance < 50 && !cargoComplete.isPlaying)
{
cargoTransfer();
}
//Debug.Log("Action timer: " + currentActionTimer);
if (distance > 50 && currentActionTimer > 0f)
{
currentActionTimer = 0f;
cargoError.Play();
//Debug.Log("Aborted:");
}
}
void cargoTransfer()
{
if(currentActionTimer == 0)
{
if (hasCargo)
{
cargoUnloading.Play();
}
else
{
cargoLoading.Play();
}
}
currentActionTimer += Time.deltaTime;
if (currentActionTimer >= cargLoadingTime)
{
hasCargo = !hasCargo;
cargoComplete.Play();
currentActionTimer = 0;
}
}
}
<file_sep># SGM-Semestral-Assignment
Final assignment from SGM
<file_sep>using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class RumbleVestScript : MonoBehaviour {
private SerialPort rumbleVest;
private Rigidbody rigidBody;
// Use this for initialization
void Start () {
rigidBody = gameObject.GetComponent<Rigidbody>();
rumbleVest = new SerialPort("\\\\.\\COM15", 9600);
rumbleVest.Open();
}
// Update is called once per frame
void Update () {
int strenght = (int) (rigidBody.velocity.magnitude * 10f);
if (strenght > 255) strenght = 255;
if (strenght < 0) strenght = 0;
SetVest(strenght);
}
private void SetVest(int both)
{
SetVest(both, both);
}
void OnApplicationQuit()
{
SetVest(0);
rumbleVest.Close();
}
private void SetVest(int left, int right)
{
if (rumbleVest.IsOpen)
{
rumbleVest.Write("S" + left + " " + right + "E");
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
//script to get the rotation of the spaceship in the x-, y- and z axes, and display the float values in UI text elements
public class UIDisplayRotation : MonoBehaviour {
public UnityEngine.UI.Text displayRotationX;
public UnityEngine.UI.Text displayRotationY;
public UnityEngine.UI.Text displayRotationZ;
private Transform tf;
void Start() {
tf = GameObject.Find("cockpit").GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
//get transform.rotation and store
displayRotationX.text = Mathf.Round(tf.rotation.eulerAngles.x).ToString();
displayRotationY.text = Mathf.Round(tf.rotation.eulerAngles.y).ToString();
displayRotationZ.text = Mathf.Round(tf.rotation.eulerAngles.z).ToString();
}
}
<file_sep>using UnityEngine;
using System;
using System.Threading;
using System.IO.Ports;
struct ArduinoData
{
public float arduinoPitch;
public float arduinoRoll;
public float arduinoAnalogX;
public float arduinoAnalogY;
public bool arduinoButtonZ;
public bool arduinoButtonC;
public ArduinoData(float arduinoPitch, float arduinoRoll, float arduinoAnalogX, float arduinoAnalogY, bool arduinoButtonZ, bool arduinoButtonC)
{
this.arduinoPitch = arduinoPitch;
this.arduinoRoll = arduinoRoll;
this.arduinoAnalogX = arduinoAnalogX;
this.arduinoAnalogY = arduinoAnalogY;
this.arduinoButtonZ = arduinoButtonZ;
this.arduinoButtonC = arduinoButtonC;
}
}
struct SwitchBoardData
{
public bool a;
public bool b;
public bool c;
public SwitchBoardData(bool a, bool b, bool c)
{
this.a = a;
this.b = b;
this.c = c;
}
}
public class FlightControllScript : MonoBehaviour {
private bool keepReading;
#region Arduinoreader
private Thread ioThread;
private SerialPort arduino;
private ArduinoData arduinoData;
#endregion
#region Switchboard
private Thread switchBoardThread;
private SerialPort switchBoard;
private SwitchBoardData switchBoardData;
#endregion
private Rigidbody rigidBody;
private bool buttonZLastValue;
private float zeroInValue;
private bool dummyMode;
// Use this for initialization
void Start () {
dummyMode = false;
buttonZLastValue = false;
zeroInValue = 0;
ioThread = new Thread(Poll);
switchBoardThread = new Thread(PollSwitchboard);
switchBoard = new SerialPort("\\\\.\\COM16", 9600);
arduino = new SerialPort("COM3", 9600);
arduino.DtrEnable = true;
keepReading = true;
arduinoData = new ArduinoData();
switchBoardData = new SwitchBoardData(false, false, false);
rigidBody = gameObject.GetComponent<Rigidbody>();
ioThread.Start();
switchBoardThread.Start();
}
// Update is called once per frame
void Update () {
if (switchBoardData.a)
{
LinearMovement();
RotationalMovement();
BoostCheck();
}
DummyButtonCheck();
DummyModeCheck();
}
private void DummyButtonCheck()
{
if (Input.GetKeyDown(KeyCode.Joystick1Button4) || Input.GetKeyDown(KeyCode.Joystick1Button5))
{
rigidBody.drag = 2.5f;
rigidBody.angularDrag = 2.5f;
}
else if (Input.GetKeyUp(KeyCode.Joystick1Button4) || Input.GetKeyUp(KeyCode.Joystick1Button5))
{
if (dummyMode)
{
rigidBody.drag = 1f;
rigidBody.angularDrag = 1f;
}
else
{
rigidBody.drag = 0.05f;
rigidBody.angularDrag = 0.05f;
}
}
}
private void DummyModeCheck()
{
if (switchBoardData.b && !dummyMode)
{
rigidBody.drag = 1f;
rigidBody.angularDrag = 1f;
dummyMode = true;
} else if (!switchBoardData.b && dummyMode)
{
rigidBody.drag = 0.05f;
rigidBody.angularDrag = 0.05f;
dummyMode = false;
}
}
private void BoostCheck()
{
if (switchBoardData.c && Input.GetKeyDown(KeyCode.Joystick1Button0))
{
rigidBody.AddRelativeForce(Vector3.forward * 200, ForceMode.Impulse);
}
}
/// <summary>
/// method that handles rotationof the player plane
/// </summary>
private void RotationalMovement()
{
float pitch = Input.GetAxis("Pitch");
float roll = Input.GetAxis("Roll");
float yaw = Input.GetAxis("Yaw");
//Debug.Log("Pitch " + pitch + " roll " + roll + " yaw " + yaw);
rigidBody.AddRelativeTorque(Vector3.forward * Time.deltaTime * roll * 25, ForceMode.Acceleration);
rigidBody.AddRelativeTorque(Vector3.right * Time.deltaTime * pitch * 25, ForceMode.Acceleration);
rigidBody.AddRelativeTorque(Vector3.up * Time.deltaTime * yaw * 25, ForceMode.Acceleration);
}
/// <summary>
/// method that handles Linear movement of the player plane
/// </summary>
private void LinearMovement()
{
/*float forward = Input.GetAxis("Forward");
float strafe = Input.GetAxis("Strafe");
float vertical = Input.GetAxis("Vertical");*/
/*rigidBody.AddRelativeForce(Vector3.left * Time.deltaTime * strafe, ForceMode.Acceleration);
rigidBody.AddRelativeForce(Vector3.forward * Time.deltaTime * forward, ForceMode.Acceleration);
rigidBody.AddRelativeForce(Vector3.up * Time.deltaTime * vertical, ForceMode.Acceleration);*/
rigidBody.AddRelativeForce(Vector3.up * Time.deltaTime * arduinoData.arduinoAnalogY * 15, ForceMode.Acceleration);
rigidBody.AddRelativeForce(Vector3.left * Time.deltaTime * arduinoData.arduinoAnalogX * -15, ForceMode.Acceleration);
if (arduinoData.arduinoButtonZ)
{
if (!buttonZLastValue)
{
zeroInValue = arduinoData.arduinoPitch;
buttonZLastValue = true;
}
float throttleValue = (arduinoData.arduinoPitch - zeroInValue);
rigidBody.AddRelativeForce(Vector3.forward * Time.deltaTime * throttleValue * 15, ForceMode.Acceleration);
Debug.Log(arduinoData.arduinoPitch - zeroInValue);
}
else
{
buttonZLastValue = false;
}
}
#region ArduinoPoll
void OnApplicationQuit()
{
keepReading = false;
}
private void Poll()
{
Debug.Log("Starting Poll Thread");
arduino.Open();
arduino.ReadLine();
while (keepReading)
{
if (arduino.IsOpen)
{
string input = arduino.ReadLine();
//Debug.Log(input);
string[] segments = input.Split(' ');
arduinoData.arduinoButtonZ = Convert.ToBoolean(Convert.ToInt32(segments[1]));
arduinoData.arduinoButtonC = Convert.ToBoolean(Convert.ToInt32(segments[3]));
arduinoData.arduinoPitch = Convert.ToSingle(segments[7]);
arduinoData.arduinoRoll = Convert.ToSingle(segments[5]);
arduinoData.arduinoAnalogX = Convert.ToSingle(segments[9]) - 125f;
arduinoData.arduinoAnalogY = Convert.ToSingle(segments[11]) - 130f;
if (arduinoData.arduinoAnalogX < 5 && arduinoData.arduinoAnalogX > -5) arduinoData.arduinoAnalogX = 0;
if (arduinoData.arduinoAnalogY < 5 && arduinoData.arduinoAnalogY > -5) arduinoData.arduinoAnalogY = 0;
}
}
arduino.Close();
Debug.Log("Ending Poll Thread");
}
private void PollSwitchboard()
{
Debug.Log("Starting Switchboard");
switchBoard.Open();
switchBoard.ReadLine();
while (keepReading && switchBoard.IsOpen)
{
string input = switchBoard.ReadLine();
string[] segments = input.Split(' ');
switchBoardData.a = Convert.ToBoolean(Convert.ToInt32(segments[0]));
switchBoardData.b = Convert.ToBoolean(Convert.ToInt32(segments[1]));
switchBoardData.c = Convert.ToBoolean(Convert.ToInt32(segments[2]));
}
switchBoard.Close();
Debug.Log("Closing switchboard thread");
}
#endregion
}
<file_sep>using UnityEngine;
using System.Collections;
public class AstroidBeltOrbit : MonoBehaviour {
public GameObject[] asteroidBelts = new GameObject[9];
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
asteroidBelts[0].transform.Rotate(0, 0.25f * Time.deltaTime, 0);
asteroidBelts[1].transform.Rotate(0, 0.50f * Time.deltaTime, 0);
asteroidBelts[2].transform.Rotate(0, 0.75f * Time.deltaTime, 0);
asteroidBelts[3].transform.Rotate(0, -.25f * Time.deltaTime, 0);
asteroidBelts[4].transform.Rotate(0, -.50f * Time.deltaTime, 0);
asteroidBelts[5].transform.Rotate(0, -.75f * Time.deltaTime, 0);
asteroidBelts[6].transform.Rotate(0, 0.25f * Time.deltaTime, 0);
asteroidBelts[7].transform.Rotate(0, 0.50f * Time.deltaTime, 0);
asteroidBelts[8].transform.Rotate(0, 0.75f * Time.deltaTime, 0);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class AsteroidRotation : MonoBehaviour
{
public float rotationMultiplyer = 1;
float RotationAngleX;
float RotationAngleY;
float RotationAngleZ;
// Use this for initialization
void Start ()
{
RotationAngleX = Random.Range(2, 4) * rotationMultiplyer;
RotationAngleY = Random.Range(2, 4) * rotationMultiplyer;
RotationAngleZ = Random.Range(2, 4) * rotationMultiplyer;
}
// Update is called once per frame
void Update ()
{
transform.Rotate(RotationAngleX * Time.deltaTime, RotationAngleY * Time.deltaTime, RotationAngleZ * Time.deltaTime);
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class Sounds : MonoBehaviour {
public AudioClip powerEngine;
public AudioClip ambient;
private AudioSource engineSource;
private AudioSource ambientSource;
private Rigidbody rb;
private float velocity;
private float rotation;
private Transform tf;
void Awake()
{
ambientSource = GetComponent<AudioSource>();
}
// Use this for initialization
void Start () {
rb = GameObject.Find("cockpit").GetComponent<Rigidbody>();
ambientSource = gameObject.AddComponent<AudioSource>();
engineSource = gameObject.AddComponent<AudioSource>();
ambientSource.clip = ambient;
engineSource.clip = powerEngine;
ambientSource.PlayOneShot(ambient, 1f);
ambientSource.loop = true;
ambientSource.playOnAwake = true;
tf = GameObject.Find("cockpit").GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
float velocityX = Mathf.Round(rb.velocity.x);
float velocityY = Mathf.Round(rb.velocity.y);
float velocityZ = Mathf.Round(rb.velocity.z);
velocity = Mathf.Sqrt((velocityX * velocityX) + (velocityY * velocityY) + (velocityZ * velocityZ));
float rotationX = Mathf.Round(rb.angularVelocity.x);
float rotationY = Mathf.Round(rb.angularVelocity.y);
float rotationZ = Mathf.Round(rb.angularVelocity.z);
rotation = Mathf.Sqrt((rotationX * rotationX) + (rotationY * rotationY) + (rotationZ * rotationZ));
if (!engineSource.isPlaying)
engineSource.Play();
if(velocity != 0)
engineSource.volume = velocity / 100;
else
engineSource.volume = rotation / 110;
}
void OnGUI()
{
GUI.Label(new Rect(10, 10, 200, 100), "Velocity : " + velocity);
}
}
<file_sep>using UnityEngine;
public class UILocationWaypoint : MonoBehaviour
{
public Camera cam; //drag the main camera to the script in the inspector
public GameObject spaceship; //drag the spaceship gameobject to the script in the inspector
private Renderer rend1, rend2, rend3; //button renderers used to change the color
private GameObject arrow; //arrow prefab
private Transform target; //transform of target space stations
public UnityEngine.UI.Text distanceText; //UI text for distance to target space station
void Start ()
{
arrow = GameObject.Find("Arrow");
rend1 = GameObject.Find("Location1").GetComponent<Renderer>();
rend2 = GameObject.Find("Location2").GetComponent<Renderer>();
rend3 = GameObject.Find("Location3").GetComponent<Renderer>();
}
void Update()
{
RaycastHit hit; //to store data from collisions
Ray ray = new Ray(cam.transform.position, cam.transform.forward); //define ray
Physics.Raycast(ray, out hit, 50.0f); //shoot ray
try
{
if (hit.collider.tag == "Location1")
{
rend1.material.color = Color.cyan; //
rend2.material.color = Color.white; //render button colors
rend3.material.color = Color.white; //
target = GameObject.Find("Platform1").GetComponent<Transform>(); //get transform from platform1
distanceText.text = (Vector3.Distance(target.position,
spaceship.transform.position) / 1000).ToString("F2") + " km"; //distance vector to display distance in kilometers
}
else if (hit.collider.tag == "Location2")
{
rend1.material.color = Color.white;
rend2.material.color = Color.cyan;
rend3.material.color = Color.white;
target = GameObject.Find("Platform2").GetComponent<Transform>();
distanceText.text = (Vector3.Distance(target.position,
spaceship.transform.position) / 1000).ToString("F2") + " km"; //distance vector to display distance in kilometers
}
else if (hit.collider.tag == "Location3")
{
rend1.material.color = Color.white;
rend2.material.color = Color.white;
rend3.material.color = Color.cyan;
target = GameObject.Find("Platform3").GetComponent<Transform>();
distanceText.text = (Vector3.Distance(target.position,
spaceship.transform.position) / 1000).ToString("F2") + " km"; //distance vector to display distance in kilometers
}
arrow.transform.LookAt(target.position); //points the arrow prefab in the direction of the target space station
}
catch (System.NullReferenceException) { }
}
public int distanceToTarget()
{
if(target != null)
{
return (int) Vector3.Distance(target.position, spaceship.transform.position);
}
else
{
return 999;
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
// Script to get the velocity of the spaceship in the x-, y- and z axes, and display the float values in UI text elements
public class UIDisplayVelocity : MonoBehaviour {
public UnityEngine.UI.Text displayVelocityX;
public UnityEngine.UI.Text displayVelocityY;
public UnityEngine.UI.Text displayVelocityZ;
private Rigidbody rb;
// Use this for initialization
void Start () {
rb = GameObject.Find("cockpit").GetComponent<Rigidbody>(); //replace cube with spaceship
}
// Update is called once per frame
void Update () {
displayVelocityX.text = Mathf.Round(rb.velocity.x).ToString();
displayVelocityY.text = Mathf.Round(rb.velocity.y).ToString();
displayVelocityZ.text = Mathf.Round(rb.velocity.z).ToString();
}
}
| 707acd9ced02d73cfb45413e446651a2c7887941 | [
"Markdown",
"C#"
] | 10 | C# | Kindota/SGM-Semestral-Assignment | bfcecd6e19868cd0e54034f5afb2973552ed0495 | 02aeb2bc6ef3775505c2769c15ad304911b9e610 |
refs/heads/master | <repo_name>ThGnommy/CountVowels<file_sep>/Vocali/Program.cs
using System;
using System.Text;
// Enter a string and the program counts the number of vowels in the text. For added complexity have it report a sum of each vowel found.
namespace Vocali
{
class Program
{
static void Main(string[] args)
{
int countA = 0;
int countE = 0;
int countI = 0;
int countO = 0;
int countU = 0;
Console.Write("Inserisci una stringa: ");
string s = Console.ReadLine();
foreach (char item in s)
{
if(item.ToString() == "a")
{
countA++;
}
if (item.ToString() == "e")
{
countE++;
}
if (item.ToString() == "i")
{
countI++;
}
if (item.ToString() == "o")
{
countO++;
}
if (item.ToString() == "u")
{
countU++;
}
}
Console.WriteLine("Ci sono: " + countA + " 'A' " + "in questa frase.");
Console.WriteLine("Ci sono: " + countE + " 'E' " + "in questa frase.");
Console.WriteLine("Ci sono: " + countI + " 'I' " + "in questa frase.");
Console.WriteLine("Ci sono: " + countO + " 'O' " + "in questa frase.");
Console.WriteLine("Ci sono: " + countU + " 'U' " + "in questa frase.");
}
}
}
| c364563ea0f8aab9455d4f25285b978a4bf21ab6 | [
"C#"
] | 1 | C# | ThGnommy/CountVowels | 40dd6499eb220c0a4ad2f27b14d74d26bfd26d00 | e23859c1fb9cbe8fd8fa07437ff24dd8c5bbe617 |
refs/heads/master | <file_sep>package org.duncavage.recyclerviewdemo.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.toolbox.ImageLoader;
import org.duncavage.recyclerviewdemo.DemoApplication;
import org.duncavage.recyclerviewdemo.R;
import org.duncavage.recyclerviewdemo.adapters.ListItemViewHolderAdapter;
import org.duncavage.recyclerviewdemo.presenters.DemoDataListPresenter;
import org.duncavage.recyclerviewdemo.presenters.ListPresenter;
import org.duncavage.recyclerviewdemo.presenters.StringProvider;
import org.duncavage.recyclerviewdemo.presenters.views.ListView;
import org.duncavage.recyclerviewdemo.viewmodels.ListItemViewModel;
import org.duncavage.recyclerviewdemo.views.RecyclerViewItemClickListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MyRecyclerFragment extends Fragment implements ListView<ListItemViewModel> {
private ListView.Events mEventListener;
private RecyclerView mRecyclerView;
private MyListPresenter mListPresenter;
public enum LayoutType {
Linear,
Grid,
GridWithGroupHeadings,
GridWithHeadingsAndSpans,
GridWithCarousel
}
public static MyRecyclerFragment newInstance() {
Bundle args = new Bundle();
MyRecyclerFragment fragment = new MyRecyclerFragment();
fragment.setArguments(args);
return fragment;
}
private LayoutType layoutType = LayoutType.Linear;
private ImageLoader mImageLoader = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageLoader = DemoApplication.getInstance().getImageLoader();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_recyclerview, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(createLayoutManager(layoutType));
// Todo ?
mRecyclerView.addOnItemTouchListener(new RecyclerViewItemClickListener(getActivity(),
new RecyclerViewItemClickListener.OnItemGestureListener() {
@Override
public void onItemClick(View view, int position) {
mEventListener.onRemoveItem(position);
mRecyclerView.getAdapter().notifyItemRemoved(position);
}
@Override
public void onItemLongClick(View view, int position) {
}
}));
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mListPresenter = createListPresenter();
mListPresenter.load();
}
private RecyclerView.LayoutManager createLayoutManager(LayoutType type) {
if (type == null) {
return new LinearLayoutManager(getActivity());
}
switch (type) {
case Linear:
return new LinearLayoutManager(getActivity());
case Grid:
case GridWithCarousel:
return new GridLayoutManager(getActivity(), 2);
default:
return new LinearLayoutManager(getActivity());
}
}
private MyListPresenter createListPresenter() {
StringProvider stringProvider = DemoApplication.getInstance().getStringProvider();
switch (layoutType) {
case Linear:
return new MyListPresenter(this, true, stringProvider);
case GridWithCarousel:
break;
}
return null;
}
@Override
public void setEventsListener(Events listener) {
mEventListener = listener;
}
@Override
public void setList(List<ListItemViewModel> list) {
ListItemViewHolderAdapter adapter;
if (layoutType == LayoutType.Linear) {
adapter = new ListItemViewHolderAdapter<>(list, mImageLoader);
mRecyclerView.swapAdapter(adapter, false);
}
}
public void addNewItem() {
mEventListener.onAddNewItem();
mRecyclerView.getAdapter().notifyItemInserted(0);
mRecyclerView.scrollToPosition(0);
}
}
class MyListPresenter extends ListPresenter<ListItemViewModel> implements ListView.Events {
private StringProvider mStringProvider;
public MyListPresenter(ListView<ListItemViewModel> views,
boolean addHeaders,
StringProvider stringProvider) {
super(views);
views.setEventsListener(this);
this.mStringProvider = stringProvider;
}
@Override
public void load() {
List<ListItemViewModel> viewModels = new ArrayList<>();
for (int i = 0; i < 10; i++) {
ListItemViewModel model = new ListItemViewModel();
model.primary = mStringProvider.getStringForResource(R.string.item_primary_prefix) + " " + i;
model.secondary = mStringProvider.getStringForResource(R.string.item_secondary_prefix) + " " + i;
model.tertiary = i + "" + mStringProvider.getStringForResource(R.string.item_tertiary_prefix);
int randAlbum = new Random().nextInt(DemoDataListPresenter.ITEM_IMAGE_URLS.length);
model.imageUrl = DemoDataListPresenter.ITEM_IMAGE_URLS[randAlbum];
viewModels.add(model);
}
setViewModels(viewModels);
}
protected ListItemViewModel createBlankItem() {
ListItemViewModel model = new ListItemViewModel();
model.primary = mStringProvider.getStringForResource(R.string.new_item_primary);
model.secondary = mStringProvider.getStringForResource(R.string.new_item_secondary);
int randAlbum = new Random().nextInt(DemoDataListPresenter.ITEM_IMAGE_URLS.length);
model.imageUrl = DemoDataListPresenter.ITEM_IMAGE_URLS[randAlbum];
return model;
}
@Override
public void onItemClicked(int position) {
List list = new ArrayList();
list.add("");
}
@Override
public void onAddNewItem() {
ListItemViewModel model = createBlankItem();
getViewModels().add(0, model);
}
@Override
public void onRemoveItem(int position) {
getViewModels().remove(position);
}
}
| 8b09cfd4ed10ac405515069cdb5d3bfc33b54f0c | [
"Java"
] | 1 | Java | Tikitoo/recyclerViewToTheRescue | 25a5733e8b913c34ec1c8ae2c0d841889c3c5b39 | 31626c3daa0b302421df79eeed1ecfe74eebdd46 |
refs/heads/master | <repo_name>Estefania-Pichardo/ClienteServidorU2-Actividad5<file_sep>/Cliente-ServidorPeliculas/ServidorPeliculas/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace ServidorPeliculas
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
PeliculasServer server = new PeliculasServer();
private int time=0;
private DispatcherTimer Timer;
public MainWindow()
{
InitializeComponent();
this.DataContext = server;
dtgPeliculas.ItemsSource = server.CatalogoPeliculas.ListaPeliculas;
Timer = new DispatcherTimer();
Timer.Interval = new TimeSpan(0, 0, 10);
Timer.Tick += Timer_Tick;
Timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
if(time>=0)
{
dtgPeliculas.ItemsSource = server.CatalogoPeliculas.ListaPeliculas;
time++;
}
}
}
}
<file_sep>/Cliente-ServidorPeliculas/ServidorPeliculas/CatalogoPeliculas.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ServidorPeliculas
{
public class CatalogoPeliculas
{
public ObservableCollection<Pelicula> ListaPeliculas { get; set; } = new ObservableCollection<Pelicula>();
public void Agregar(Pelicula p)
{
ListaPeliculas.Add(p);
Guardar();
}
public void Editar(Pelicula p)
{
var pelicula = ListaPeliculas.FirstOrDefault(x => x.Nombre == p.Nombre & x.Hora==p.Hora);
if(pelicula!=null)
{
pelicula.Idioma = p.Idioma;
pelicula.Sala = p.Sala;
Guardar();
}
}
public void Eliminar(Pelicula p)
{
var pelicula = ListaPeliculas.FirstOrDefault(x => x.Nombre == p.Nombre & x.Hora == p.Hora);
if(pelicula!=null)
{
ListaPeliculas.Remove(pelicula);
Guardar();
}
}
private void Guardar()
{
string datos = JsonConvert.SerializeObject(ListaPeliculas);
File.WriteAllText("peliculas.json", datos);
}
private void Cargar()
{
if (File.Exists("peliculas.json"))
{
var datos = JsonConvert.DeserializeObject<ObservableCollection<Pelicula>>(File.ReadAllText("peliculas.json"));
foreach (var item in datos)
{
ListaPeliculas.Add(item);
}
}
}
public CatalogoPeliculas()
{
Cargar();
}
}
}
<file_sep>/EditarWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Ejercicio5_ClientePeliculas
{
/// <summary>
/// Lógica de interacción para EditarWindow.xaml
/// </summary>
public partial class EditarWindow : Window
{
public EditarWindow()
{
InitializeComponent();
cmbClasificacion.ItemsSource = Enum.GetValues(typeof(Clasificacion));
cmbSala.ItemsSource = Enum.GetValues(typeof(Sala));
cmbIdioma.ItemsSource = Enum.GetValues(typeof(Idioma));
}
PeliculasClient cliente = new PeliculasClient();
private void btnAceptar_Click(object sender, RoutedEventArgs e)
{
DatosPelicula datos = this.DataContext as DatosPelicula;
try
{
cliente.Editar(datos);
this.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnCancelar_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
this.Close();
}
}
}
<file_sep>/DatosPelicula.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio5_ClientePeliculas
{
public enum Sala { A1 =0, A2=1, B1=2, B2=3};
public enum Clasificacion { A=0, B15=1, C=2, R=3};
public enum Idioma { Español=0, Subtitulada=1};
public class DatosPelicula
{
public string Hora { get; set; }
public string Nombre { get; set; }
public Sala Sala { get; set; }
public Clasificacion Clasificacion { get; set; }
public Idioma Idioma { get; set; }
}
}
<file_sep>/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace Ejercicio5_ClientePeliculas
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DatosPelicula datos = new DatosPelicula();
PeliculasClient cliente = new PeliculasClient();
private int time = 0;
private DispatcherTimer Timer;
public MainWindow()
{
InitializeComponent();
cmbClasificacion.ItemsSource = Enum.GetValues(typeof(Clasificacion));
cmbSala.ItemsSource = Enum.GetValues(typeof(Sala));
cmbIdioma.ItemsSource = Enum.GetValues(typeof(Idioma));
this.DataContext = datos;
cliente.AlHaberCambios += Cliente_AlHaberCambios;
cliente.Get();
Timer = new DispatcherTimer();
Timer.Interval = new TimeSpan(0, 0, 5);
Timer.Tick += Timer_Tick;
Timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
if (time >= 0)
{
cliente.Get();
time++;
}
}
private void Cliente_AlHaberCambios()
{
dtgPeliculas.ItemsSource = cliente.Model;
}
private void btnAgregar_Click(object sender, RoutedEventArgs e)
{
try
{
cliente.Agregar(datos);
txtHora.Text = txtTitulo.Text = "";
cmbClasificacion.SelectedIndex = cmbSala.SelectedIndex = cmbIdioma.SelectedIndex = -1;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnEliminar_Click(object sender, RoutedEventArgs e)
{
try
{
if (dtgPeliculas.SelectedIndex != -1)
{
datos = dtgPeliculas.SelectedItem as DatosPelicula;
if (MessageBox.Show($"¿Desea eliminar la pelicula {datos.Nombre} con función a las {datos.Hora}?", "Confirme", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
cliente.Eliminar(datos);
MessageBox.Show("Pelicula eliminada de cartelera", "Vuelo Eliminado", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
MessageBox.Show("La pelicula no se eliminó de la cartelera");
}
}
else
{
MessageBox.Show("Seleccione una pelicula para eliminar de cartelera", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnEditar_Click(object sender, RoutedEventArgs e)
{
try
{
if(dtgPeliculas.SelectedIndex != -1)
{
EditarWindow ventanaEdit = new EditarWindow();
datos = dtgPeliculas.SelectedItem as DatosPelicula;
ventanaEdit.DataContext = datos;
ventanaEdit.ShowDialog();
}
else
{
MessageBox.Show("Seleccione una pelicula para editar", "Atecion", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
cliente.Editar(datos);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
<file_sep>/PeliculasClient.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace Ejercicio5_ClientePeliculas
{
public class PeliculasClient
{
HttpClient cliente = new HttpClient();
public PeliculasClient()
{
cliente.BaseAddress = new Uri("http://localhost:8080/");
}
public async void Agregar(DatosPelicula p)
{
var json = JsonConvert.SerializeObject(p);
var result = await cliente.PostAsync("Actividad5/Tablero", new StringContent(json, Encoding.UTF8, "application/json"));
result.EnsureSuccessStatusCode();
}
public async void Eliminar(DatosPelicula p)
{
var json = JsonConvert.SerializeObject(p);
HttpRequestMessage msj = new HttpRequestMessage(HttpMethod.Delete, "Actividad5/Tablero");
msj.Content = new StringContent(json, Encoding.UTF8, "application/json");
var result = await cliente.SendAsync(msj);
result.EnsureSuccessStatusCode();
}
public async void Editar(DatosPelicula p)
{
var json = JsonConvert.SerializeObject(p);
var result = await cliente.PutAsync("Actividad5/Tablero", new StringContent(json, Encoding.UTF8, "application/json"));
result.EnsureSuccessStatusCode();
}
public delegate void cambio();
public event cambio AlHaberCambios;
public IEnumerable<DatosPelicula> Model { get; set; }
public async void Get()
{
var client = new HttpClient();
var response = await client.GetAsync("http://localhost:8080/Actividad5/Tablero");
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
Model = JsonConvert.DeserializeObject<IEnumerable<DatosPelicula>>(jsonString);
AlHaberCambios?.Invoke();
}
}
}
}
| 10f410f23f15a1527e15bb67aab99107b7dc5385 | [
"C#"
] | 6 | C# | Estefania-Pichardo/ClienteServidorU2-Actividad5 | 452d7640cad9363b8c4a8ca59d893cee7d05344e | 61a0ccb2761f46fcedeb2556356ef317a5a4ac53 |
refs/heads/main | <file_sep>dados = read.csv2("a3 q3.csv", header = TRUE, sep = ",", dec = ".")
mortalidade = dados$taxa.de.mort..infantil
alfabetizacao = dados$taxa.de.alfabetizacao
pop1000 = dados$populacao..em.1000.hab..
cidades = dados$municipio
plot(mortalidade, alfabetizacao, pch = 19, main = "MORTALIDADE INFANTIL X TAXA DE ALFABETIZAÇÃO", col = "darkblue")
correlacao = cor(mortalidade, alfabetizacao)
correlacao
barplot(pop1000, main = "População (em 1000 habitantes) por município", names.arg = cidades, col = "darkblue")
<file_sep>dados = read.csv2("a3 q1.csv", header = TRUE, sep = ",", dec = ".")
dados
matematica = dados$X
calculo = dados$Y
correlacao = cor(matematica, calculo)
correlacao
regressao = lm(calculo ~ matematica)
regressao
plot(matematica, calculo, pch = 19, main = "Vestibular x Cálculo", col = "darkblue")
abline(regressao, col = "darkred")
notafinal = 87.14976 + 0.02194*(77)
notafinal
<file_sep>library(fdth)
dados = read.csv2("atividade2.csv",header=TRUE, sep=";" , dec=".")
dados = as.numeric(unlist(dados))
#Número de dados
length(dados)
summary(dados)
#Tabela de distribuição de frequência
tabela = fdt(dados,k=13,breaks="Sturges")
print(tabela,format = TRUE,pattern="%.2f")
#Histograma de dados
hist(dados, main = "HISTOGRAMA DE DADOS", xlab = "AVALIAÇÃO DO CURSO", ylab = "FREQUÊNCIA")
#Gráfico de setores por número
tabela = table(dados)
pie(tabela)
#Gráfico de setores dos limites
cortes = c(8.60, 7.80, 8.76, 8.28, 7.32, 8.76, 7.44, 7.68, 6.12, 7.88,7.20, 7.64, 6.52
)
classes = c("0.00 - 7.77", "7.77 - 15.50", "15.50 - 23.30", "23.30 - 31.10", "31.10 - 38.80", "38.80 - 46.60", "46.60 - 54.40", "54.40 - 62.20", "62.20 - 69.90", "69.90 - 77.70", "77.70 - 85.50", "85.50 - 93.20", "93.20 - 101.00")
pie(cortes, labels = classes, main = "GRÁFICO DE SETORES")
<file_sep>dados = read.csv2("q4.csv", header = TRUE, sep = ";", dec = ".")
dados = as.data.frame(dados)
dados
altura = as.numeric(sub(",",".", dados[,2], fixed = TRUE))
barplot(altura, xlab = "Estados", ylab = "Proporção da população urbana", main = "PROPORÇÃO DA POPULAÇÃO URBANA EM 2014 POR ESTADO", names.arg = dados[,1], col = "darkred")
<file_sep>#leitura de arquivos
dados = read.csv2("custodeensino.csv",header=TRUE, sep=";" , dec=".")
dados = as.numeric(unlist(dados))
#1º questão
#Média
mean(dados)
#Desvio Padrão
sd(dados)
#Mediana
median(dados)
#2º questão
#Primeiro Quantil
quantile(dados, probs = 0.25)
#Segundo Quantil
quantile(dados, probs = 0.5)
#Terceiro Quantil
quantile(dados, probs = 0.75)
#3º questão
#Boxplot
boxplot(dados, col="pink")
#4º questão
#Distribuição de Frequência
dadostable = seq(19, 33, 2)
classes = c("19-21", "21-23", "23-25", "25-27", "27-29", "29-31", "31-33")
tabela = table(cut(dados,breaks=dadostable,right=FALSE,labels=classes))
tabela
#5º questão
#Tabela Frequência Relativa
prop.table(tabela)
<file_sep>dados = read.csv2("q3.csv", header = TRUE, sep = ";", dec = ".")
dados = as.data.frame(dados)
dados = dados[-7,]
altura = as.numeric(sub(",", ".", dados[,2], fixed = TRUE))
barplot(altura, xlab = "Regiões", ylab = "Proporção da população urbana", main = "PROPORÇÃO DA POPULAÇÃO URBANA EM 2014 POR REGIÃO", names.arg = dados[,1], col = "darkred")
<file_sep>library(fdth)
dados = read.csv2("q1.csv", sep="," , dec=".")
dados = as.numeric(unlist(dados))
#Número de dados
length(dados)
summary(dados)
#Tabela de distribuição de frequência
tabela = fdt(dados,k=6,breaks="Sturges")
print(tabela,format = TRUE,pattern="%.2f")
#Histograma de dados
hist(dados, main = "HISTOGRAMA DE DADOS", xlab = "ESPESSURAS", ylab = "FREQUÊNCIA")
#Gráfico de setores
tabela = table(dados)
pie(tabela, main = "GRÁFICO DE SETORES")
<file_sep>dados = read.csv2("a3 q2.csv", header = TRUE, sep = ",", dec = ".")
dados
renda = dados$Renda.Familiar..X.
gasto = dados$Gasto.com.AlimentaÃ.Ã.o..Y.
gasto = as.numeric(sub(",", ".", gasto, fixed = TRUE))
correlacao = cor(renda, gasto)
correlacao
regressao = lm(gasto ~ renda)
regressao
plot(renda, gasto, pch = 19, main = "RENDA X GASTO COM ALIMENTAÇÃO", col = "darkblue")
abline(regressao, col = "darkred")
gastofamiliar = 8.6918 + 0.2044*(288)
gastofamiliar
<file_sep><p align="center"><a href="https://laravel.com" target="_blank"><img src="https://github.com/Default-UNIT/Estatistica/blob/main/img/R_logo.png" width="400"></a></p>
<p align="center"><strong>Aqui irão ficar Exercícios, MEs, APSs e Provas sobre a Linguagem de Programação R!</strong></p>
<hr>
## ATIVIDADES
* [Medidas Estatísticas e Distribuição de Frequência](https://github.com/Default-UNIT/Estatistica/blob/main/Medidas%20Estatísticas%20e%20Distribuição%20de%20Frequência/ATIVIDADE1.r)
* [Construção de Gráficos e Histogramas](https://github.com/Default-UNIT/Estatistica/tree/main/Construção%20de%20Gráficos%20e%20Histogramas)
* [Correlação e Regressão Linear Simples](https://github.com/Default-UNIT/Estatistica/tree/main/Correlação%20e%20Regressão%20Linear%20Simples)
| 9524975e3bce25c80d5ea6e3288f0f68745d33e0 | [
"Markdown",
"R"
] | 9 | R | Default-UNIT/Estatistica | 5aa8f9beb549ea47c8debfc2de88bca917cefd31 | 53eaf82b0ef054749ee84790faf93e75db307bed |
refs/heads/master | <file_sep><?php
class Abadata_Deactivator{
public static function deactivate(){
global $wpdb;
$wpdb->query("drop table if exists " . $wpdb->prefix . "abadaData_table");
}
}
<file_sep><?php
class Abadata_Public {
private $plugin_name;
private $version;
public function __construct( $plugin_name, $version ) {
$this->plugin_name = $plugin_name;
$this->version = $version;
}
public function enqueue_styles() {
}
public function enqueue_scripts() {
}
}
<file_sep>
<div class="container-fluid">
<?php
global $wpdb;
require_once plugin_dir_path(__FILE__) . '../../includes/class-abadata-activator.php';
$rows = $wpdb->get_results("SELECT * FROM ". Abadata_Activator::abadaData_table() ,ARRAY_A);
?>
<h1><?php echo $rows[0]["title"]?></h1>
<p class="bg-light" style="font-size: 1.5em;"><?php echo $rows[0]["description"]?></p>
<p class="text-success" style="font-size: 1.2em;"><?php echo ucfirst($rows[0]["version"])?></p>
</div><file_sep><?php
class Abadata_Activator
{
public static function activate()
{
require_once(ABSPATH . "wp-admin/includes/upgrade.php");
global $wpdb;
if (count($wpdb->get_var("show tables like '" . Abadata_Activator::abadaData_table() . "'")) == 0) {
$query = 'CREATE TABLE `' . Abadata_Activator::abadaData_table() . '` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(150) DEFAULT NULL,
`description` varchar(3000) DEFAULT NULL,
`version` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ' . $wpdb->get_charset_collate();
dbDelta($query);
$wpdb->insert(Abadata_Activator::abadaData_table(), array(
"title" => 'Abadata Plugin',
"description" => "A simple demo plugin made for this brief, all what you can see here just this description and the version state of it, and the other sub-menu you can update this description, i hope you like it :)",
"version" => "Realize"
));
}
}
public static function abadaData_table()
{
global $wpdb;
return $wpdb->prefix . "abadaData_table";
}
}
<file_sep><?php
class Abadata{
protected $loader;
protected $plugin_name;
protected $version;
public function __construct(){
if (defined('ABADATA_VERSION')) {
$this->version = ABADATA_VERSION;
} else {
$this->version = '1.0.0';
}
$this->plugin_name = 'abadata';
$this->load_dependencies();
$this->set_locale();
$this->define_admin_hooks();
$this->define_public_hooks();
}
private function load_dependencies(){
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-abadata-loader.php';
require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-abadata-i18n.php';
require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-abadata-admin.php';
require_once plugin_dir_path(dirname(__FILE__)) . 'public/class-abadata-public.php';
$this->loader = new Abadata_Loader();
}
private function set_locale(){
$plugin_i18n = new Abadata_i18n();
$this->loader->add_action('plugins_loaded', $plugin_i18n, 'load_plugin_textdomain');
}
private function define_admin_hooks(){
$plugin_admin = new Abadata_Admin($this->get_plugin_name(), $this->get_version());
$this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles');
$this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts');
$this->loader->add_action("admin_menu", $plugin_admin, "abadaData_menu_sections");
$this->loader->add_action("wp_ajax_abadata_request", $plugin_admin, "abadaData_ajax_hundler_fn");
}
private function define_public_hooks(){
$plugin_public = new Abadata_Public($this->get_plugin_name(), $this->get_version());
$this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_styles');
$this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_scripts');
}
public function run(){
$this->loader->run();
}
public function get_plugin_name(){
return $this->plugin_name;
}
public function get_loader(){
return $this->loader;
}
public function get_version(){
return $this->version;
}
}
<file_sep>jQuery(document).ready(function() {
jQuery("#formAddData").validate({
submitHandler: function () {
let postData = jQuery("#formAddData").serialize() + "&action=abadata_request";
jQuery.post(abadata_ajax_url, postData, function (response) {
alert(response);
});
}
});
} );
<file_sep><?php
class Abadata_Admin {
private $plugin_name;
private $version;
private $table;
public function __construct($plugin_name, $version){
$this->plugin_name = $plugin_name;
$this->version = $version;
require_once plugin_dir_path(__FILE__) . '../includes/class-abadata-activator.php';
$this->table = Abadata_Activator::abadaData_table();
}
function abadaData_menu_sections(){
$page_title = "AbaData";
$menu_title = "AbaData";
$capability = "manage_options";
$menu_slug = "aba-menus";
$function = "show_description";
$icon = "dashicons-list-view";
$position = 30;
add_menu_page($page_title, $menu_title, $capability, $menu_slug . '-show-description', array($this, $function), $icon, $position);
add_submenu_page($menu_slug . '-show-description', "Show Description", "Show Description", $capability, $menu_slug . '-show-description', array($this, $function));
add_submenu_page($menu_slug . '-show-description', "Update Description", "Update Description", $capability, $menu_slug . '-update-description', array($this, 'update_description'));
}
public function show_description(){
include_once(ABADATA_PLUGIN_DIR ."/admin/partials/show-data.php");
}
public function update_description(){
include_once(ABADATA_PLUGIN_DIR ."/admin/partials/add-data.php");
}
public function enqueue_styles(){
wp_enqueue_style("bootstrap.min.css", plugin_dir_url(__FILE__) . 'css/bootstrap.min.css', array(), $this->version, 'all');
}
public function enqueue_scripts(){
wp_enqueue_script("validate.min.js", plugin_dir_url(__FILE__) . 'js/jquery.validate.min.js', array('jquery'), $this->version, true);
wp_enqueue_script("costume.js", plugin_dir_url(__FILE__) . 'js/costume.js', array('jquery'), $this->version, true);
wp_localize_script("costume.js", "abadata_ajax_url", admin_url("admin-ajax.php"));
}
public function abadaData_ajax_hundler_fn(){
global $wpdb;
$wpdb->update(
$this->table,
array("title" => $_REQUEST['title'],"description" => $_REQUEST['desc'],"version" => $_REQUEST['version']),
array( 'id' => 1 ), array( '%s','%s','%s'), array( '%d' ));
echo "updated successfully :)";
wp_die();
}
}
<file_sep># wodpress-plugin AbaData
## Description
This is a very simple made from scratch plugin using BOILERPLATE oriented-object template.
All this plugin do is showing a small description after you click on the plugin name **AbaData** from the menu, and you can change this description.
### How to install?
1. if you downloaded the project files, copy **abadata** folder and past it in your wordpress instalation under this following path:
```
wp-content\plugins
```
or simply download it from [here](https://github.com/abadayoussef/wodpress-plugin/blob/master/abadata.zip?raw=true) to your device.
2. if you downlaoded the **abadata.zip** go from your dashboard to `Plugins > add new > upload plugin` and after uploading click **Activate**
### How does it works?
> once you activate it you will notice it appearing in left side of the dashboard menu under the name of **AbaData**.
It has two sub-menu one of them shows the description , and the second one for updating that description
in the sitings of `abadata` plugin after you finishing inserting the new description all you have to do is clicking on **Update description** and you will notice these changes are appplied to the description sub-menu.
| c04b837be09d37ab65f7c3f416f32f00f329fd59 | [
"JavaScript",
"Markdown",
"PHP"
] | 8 | PHP | abadayoussef/wodpress-plugin | b7e6456ec9c75c84190a8072bd807fb022f570dc | 2a95196d69391951cfd290d7df7e7096558107d2 |
refs/heads/master | <repo_name>khanapat/git001<file_sep>/README.md
# git001
sample test repository
nice try
<file_sep>/src/main/java/com/example/demo4/repository/CustomerRepo.java
package com.example.demo4.repository;
import com.example.demo4.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepo extends JpaRepository<Customer,String>
{
public Customer findByFirstName(String firstName);
}
<file_sep>/src/main/java/com/example/demo4/service/CustomerService.java
package com.example.demo4.service;
import com.example.demo4.controller.CustomerController;
import com.example.demo4.entity.Customer;
import com.example.demo4.model.CustomerRequest;
import com.example.demo4.model.CustomerResponse;
import com.example.demo4.repository.CustomerRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class CustomerService {
@Autowired
private CustomerRepo customerRepo;
public CustomerResponse servicePost(CustomerRequest request) {
Optional<Customer> customerOpt = customerRepo.findById(request.getiD());
if (customerOpt.isPresent() == true) {
return new CustomerResponse(request.getiD(), "ID already exist", "Post Error", 0, 0);
} else {
Customer item = new Customer();
item.setiD(request.getiD());
item.setFirstName(request.getFirstName());
item.setLastName(request.getLastName());
item.setDayReg(request.getDayReg());
item.setMonthReg(request.getMonthReg());
customerRepo.save(item);
CustomerResponse customerResponsePostService = new CustomerResponse((item.getiD()),
item.getFirstName(), item.getLastName(), item.getDayReg(), item.getMonthReg());
return customerResponsePostService;
}
}
public CustomerResponse serviceGetID(String iD)
{
Optional<Customer> customerOpt2 = customerRepo.findById(iD);
if (customerOpt2.isPresent() != true)
{
return new CustomerResponse(iD,"ID doesn't exist","Get Error",0,0);
} else {
Customer data = customerRepo.findById(iD).get();
CustomerResponse customerResponseGetID = new CustomerResponse(data.getiD(),data.getFirstName()
,data.getLastName(),data.getDayReg(),data.getMonthReg());
return customerResponseGetID;
}
}
public List<CustomerResponse> serviceGetAll()
{
List<Customer> list = customerRepo.findAll();
List<CustomerResponse> listGetAll = new ArrayList<CustomerResponse>();
for (Customer a : list)
{
CustomerResponse customerResponseGetAll = new CustomerResponse(a.getiD(),a.getFirstName()
,a.getLastName(),a.getDayReg(),a.getMonthReg());
listGetAll.add(customerResponseGetAll);
}
return listGetAll;
}
public CustomerResponse serviceGetName(String firstName)
{
Optional<Customer> customerOpt3 = Optional.ofNullable(customerRepo.findByFirstName(firstName));
if (!customerOpt3.isPresent())
{
return new CustomerResponse("This First Name doesn't exist",firstName,"Get Error",0,0);
}
Customer data = customerRepo.findByFirstName(firstName);
CustomerResponse customerResponseGetName = new CustomerResponse(data.getiD(),data.getFirstName()
,data.getLastName(),data.getDayReg(),data.getMonthReg());
return customerResponseGetName;
}
public CustomerResponse serviceUpdate(CustomerRequest request)
{
Optional<Customer> customerOpt4 = customerRepo.findById(request.getiD());
if (!customerOpt4.isPresent())
{
return new CustomerResponse(request.getiD(),"This ID doesn't exist","Update Error",0,0);
} else {
Customer item2 = new Customer();
item2.setiD(request.getiD());
item2.setFirstName(request.getFirstName());
item2.setLastName(request.getLastName());
item2.setDayReg(request.getDayReg());
item2.setMonthReg(request.getMonthReg());
customerRepo.save(item2);
CustomerResponse customerResponseUpdate = new CustomerResponse(item2.getiD(),item2.getFirstName()
,item2.getLastName(),item2.getDayReg(),item2.getMonthReg());
return customerResponseUpdate;
}
}
public void serviceDeleteAll()
{
customerRepo.deleteAll();
}
public List<CustomerResponse> serviceDeleteID(String iD)
{
Optional<Customer> customerOpt2 = customerRepo.findById(iD);
if (customerOpt2.isPresent() != true)
{
List<Customer> list = customerRepo.findAll();
List<CustomerResponse> listID = new ArrayList<CustomerResponse>();
for (Customer a : list)
{
CustomerResponse customerResponseDeleteID = new CustomerResponse(a.getiD(),a.getFirstName()
,a.getLastName(),a.getDayReg(),a.getMonthReg());
listID.add(customerResponseDeleteID);
}
return listID;
} else {
customerRepo.deleteById(iD);
List<Customer> list = customerRepo.findAll();
List<CustomerResponse> listDeleteID = new ArrayList<CustomerResponse>();
for (Customer a : list)
{
CustomerResponse customerResponseDeleteID = new CustomerResponse(a.getiD(), a.getFirstName()
, a.getLastName(), a.getDayReg(), a.getMonthReg());
listDeleteID.add(customerResponseDeleteID);
}
return listDeleteID;
}
}
}
| f88ddfb23e21c13a233f05607f141c2a1e2eaa09 | [
"Markdown",
"Java"
] | 3 | Markdown | khanapat/git001 | da1e4f7e85a02fd4ea4e556614280f1425a1e401 | 0f1b36bd250663a040231b702dc4e55817bc85e9 |
refs/heads/master | <file_sep>/* eslint-env mocha */
'use strict';
const {NodeClient, WalletClient} = require('bclient');
const assert = require('bsert');
const FullNode = require('../lib/node/fullnode');
const Network = require('../lib/protocol/network');
const Mnemonic = require('../lib/hd/mnemonic');
const HDPrivateKey = require('../lib/hd/private');
const Script = require('../lib/script/script');
const Address = require('../lib/primitives/address');
const network = Network.get('regtest');
const mnemonics = require('./data/mnemonic-english.json');
// Commonly used test mnemonic
const phrase = mnemonics[0][1];
const ports = {
p2p: 49331,
node: 49332,
wallet: 49333
};
const node = new FullNode({
network: network.type,
apiKey: 'bar',
walletAuth: true,
memory: true,
workers: true,
plugins: [require('../lib/wallet/plugin')],
port: ports.p2p,
httpPort: ports.node,
env: {
'BCOIN_WALLET_HTTP_PORT': ports.wallet.toString()
}
});
const nclient = new NodeClient({
port: ports.node,
apiKey: 'bar'
});
const wclient = new WalletClient({
port: ports.wallet,
apiKey: 'bar'
});
describe('Wallet RPC Methods', function() {
this.timeout(15000);
// Define an account level hd extended public key to be
// used to derive addresses throughout the test suite
let xpub;
before(async () => {
await node.open();
await nclient.open();
await wclient.open();
// Derive the xpub using the well known
// mnemonic and network's coin type
const mnemonic = Mnemonic.fromPhrase(phrase);
const priv = HDPrivateKey.fromMnemonic(mnemonic);
const type = network.keyPrefix.coinType;
const key = priv.derive(44, true).derive(type, true).derive(0, true);
xpub = key.toPublic();
// Assert that the expected test phrase was
// read from disk
assert.equal(phrase, [
'abandon', 'abandon', 'abandon', 'abandon',
'abandon', 'abandon', 'abandon', 'abandon',
'abandon', 'abandon', 'abandon', 'about'
].join(' '));
});
after(async () => {
await nclient.close();
await wclient.close();
await node.close();
});
describe('getaddressinfo', () => {
const watchOnlyWalletId = 'foo';
const standardWalletId = 'bar';
// m/44'/1'/0'/0/{0,1}
const pubkeys = [
Buffer.from('<KEY>'
+ '<KEY>', 'hex'),
Buffer.from('03589ae7c835ce76e23cf8feb32f1a'
+ 'df4a7f2ba0ed2ad70801802b0bcd70e99c1c', 'hex')
];
// set up the initial testing state
before(async () => {
{
// Set up the testing environment
// by creating a wallet and a watch
// only wallet
const info = await nclient.getInfo();
assert.equal(info.chain.height, 0);
}
{
// Create a watch only wallet using the path
// m/44'/1'/0' and assert that the wallet
// was properly created
const accountKey = xpub.xpubkey(network.type);
const response = await wclient.createWallet(watchOnlyWalletId, {
watchOnly: true,
accountKey: accountKey
});
assert.equal(response.id, watchOnlyWalletId);
const wallet = wclient.wallet(watchOnlyWalletId);
const info = await wallet.getAccount('default');
assert.equal(info.accountKey, accountKey);
assert.equal(info.watchOnly, true);
}
{
// Create a wallet that manages the private keys itself
const response = await wclient.createWallet(standardWalletId);
assert.equal(response.id, standardWalletId);
const info = await wclient.getAccount(standardWalletId, 'default');
assert.equal(info.watchOnly, false);
};
});
// The rpc interface requires the wallet to be selected first
it('should return iswatchonly correctly', async () => {
// m/44'/1'/0'/0/0
const receive = 'mkpZhYtJu2r87Js3pDiWJDmPte2NRZ8bJV';
{
await wclient.execute('selectwallet', [standardWalletId]);
const response = await wclient.execute('getaddressinfo', [receive]);
assert.equal(response.iswatchonly, false);
}
{
await wclient.execute('selectwallet', [watchOnlyWalletId]);
const response = await wclient.execute('getaddressinfo', [receive]);
assert.equal(response.iswatchonly, true);
}
});
it('should return the correct address', async () => {
// m/44'/1'/0'/0/0
const receive = 'mkpZhYtJu2r87Js3pDiWJDmPte2NRZ8bJV';
await wclient.execute('selectwallet', [watchOnlyWalletId]);
const response = await wclient.execute('getaddressinfo', [receive]);
assert.equal(response.address, receive);
});
it('should detect owned address', async () => {
// m/44'/1'/0'/0/0
const receive = 'mkpZhYtJu2r87Js3pDiWJDmPte2NRZ8bJV';
{
await wclient.execute('selectwallet', [watchOnlyWalletId]);
const response = await wclient.execute('getaddressinfo', [receive]);
assert.equal(response.ismine, true);
}
{
await wclient.execute('selectwallet', [standardWalletId]);
const response = await wclient.execute('getaddressinfo', [receive]);
assert.equal(response.ismine, false);
}
});
it('should detect a p2sh address', async () => {
const script = Script.fromMultisig(2, 2, pubkeys);
const address = Address.fromScript(script);
const addr = address.toString(network);
const response = await wclient.execute('getaddressinfo', [addr]);
assert.equal(response.isscript, true);
assert.equal(response.iswitness, false);
assert.equal(response.witness_program, undefined);
});
it('should return the correct program for a p2wpkh address', async () => {
// m/44'/1'/0'/0/5
const receive = 'bcrt1q53724q6cywuzsvq5e3nvdeuwrepu69jsc6ulmx';
const addr = Address.fromString(receive);
await wclient.execute('selectwallet', [watchOnlyWalletId]);
const str = addr.toString(network);
const response = await wclient.execute('getaddressinfo', [str]);
assert.equal(response.witness_program, addr.hash.toString('hex'));
});
it('should detect p2wsh program', async () => {
const script = Script.fromMultisig(2, 2, pubkeys);
const address = Address.fromWitnessScripthash(script.sha256());
const addr = address.toString(network);
const response = await wclient.execute('getaddressinfo', [addr]);
assert.equal(response.isscript, true);
assert.equal(response.iswitness, true);
assert.equal(response.witness_program, address.hash.toString('hex'));
});
it('should detect ismine up to the lookahead', async () => {
const info = await wclient.getAccount(watchOnlyWalletId, 'default');
await wclient.execute('selectwallet', [watchOnlyWalletId]);
// m/44'/1'/0'
const addresses = [
'mkpZhYtJu2r87Js3pDiWJDmPte2NRZ8bJV', // /0/0
'mzpbWabUQm1w8ijuJnAof5eiSTep27deVH', // /0/1
'mnTkxhNkgx7TsZrEdRcPti564yQTzynGJp', // /0/2
'mpW3iVi2Td1vqDK8Nfie29ddZXf9spmZkX', // /0/3
'n2BMo5arHDyAK2CM8c56eoEd18uEkKnRLC', // /0/4
'mvWgTTtQqZohUPnykucneWNXzM5PLj83an', // /0/5
'muTU2Av1EwnsyhieQhyPL7hgEf883LR4xg', // /0/6
'mwduZ8Ksa563v7rWdSPmqyKR4y2FeB5g8p', // /0/7
'miyBE85ro5zt9RseSzYVEbB3TfzkxgSm8C', // /0/8
'mnYwW7mU3jajB11vrpDZwZDrXwVfE5Jc31', // /0/9
'mx3YNRT8Vg8QwFq5Z5MAVDDVHp4ihHsffn' // /0/10
];
// Assert that the lookahead is configured as expected
// subtract one from addresses.length, it is 0 indexed
assert.equal(addresses.length - 1, info.lookahead);
// Each address through the lookahead number should
// be recognized as an owned address
for (let i = 0; i <= info.lookahead; i++) {
const address = addresses[i];
const response = await wclient.execute('getaddressinfo', [address]);
assert.equal(response.ismine, true);
}
// m/44'/1'/0'/0/11
// This address is outside of the lookahead range
const failed = 'myHL2QuECVYkx9Y94gyC6RSweLNnteETsB';
const response = await wclient.execute('getaddressinfo', [failed]);
assert.equal(response.ismine, false);
});
it('should detect change addresses', async () => {
// m/44'/1'/0'/1/0
const address = 'mi8nhzZgGZQthq6DQHbru9crMDerUdTKva';
const info = await wclient.execute('getaddressinfo', [address]);
assert.equal(info.ischange, true);
});
it('should throw for the wrong network', async () => {
// m/44'/1'/0'/0/0
const failed = '16JcQVoL61QsLCPS6ek8UJZ52eRfaFqLJt';
// Match the bitcoind response when sending the incorrect
// network. Expect an RPC error
const fn = async () => await wclient.execute('getaddressinfo', [failed]);
await assert.rejects(fn, {
name: 'Error',
message: 'Invalid address.'
});
});
it('should fail for invalid address', async () => {
// m/44'/1'/0'/0/0
let failed = '16JcQVoL61QsLCPS6ek8UJZ52eRfaFqLJt';
// remove the first character
failed = failed.slice(1, failed.length);
const fn = async () => await wclient.execute('getaddressinfo', [failed]);
await assert.rejects(fn, {
name: 'Error',
message: 'Invalid address.'
});
});
});
});
<file_sep>const fs = require('fs');
const bcoin = require('../lib/bcoin').set('regtest');
const network = bcoin.Network.get('regtest');
const KeyRing = bcoin.wallet.WalletKey;
const Mnemonic = bcoin.hd.Mnemonic;
const HD = bcoin.hd;
async function createWallet() {
const mnemonic24 = new Mnemonic({bits: 256});
const masterKey = HD.fromMnemonic(mnemonic24);
fs.writeFileSync(`${network.type}-master-key.json`, JSON.stringify(masterKey.toJSON()))
return mnemonic24.toString();
}
module.exports = { createWallet }
<file_sep>const fs = require('fs');
const bcoin = require('../lib/bcoin');
const KeyRing = bcoin.KeyRing;
const Script = bcoin.Script;
const network = bcoin.Network.get('regtest');
const MTX = bcoin.MTX;
const Coin = bcoin.Coin;
const HD = bcoin.hd;
const {NodeClient} = require('bclient');
class Channel {
constructor(options) {
this.nodeClient = new NodeClient({
network: network.type,
port: network.rpcPort,
apiKey: 'change-this-key'
});
this.m = 2;
this.n = 2;
this.masterKey = this._getMasterKey();
this.keyRing = this._deriveKeyRing();
this.address = this.keyRing.getAddress("string", network.type);
this.peerPublicKey = Buffer.from(options.publicKey, "hex");
this.satoshis = options.satoshis;
this.fundingTx;
}
// use to create r
_getMasterKey() {
try {
const masterKeyJson = JSON.parse(fs.readFileSync(`${network.type}-master-key.json`));
return HD.fromJSON(masterKeyJson, network.type);
} catch(err) {
console.log(err)
if (err.code == "ENOENT") {
throw("NO_WALLET")
} else {
throw(err)
}
}
}
_deriveKeyRing() {
const derivedKey = this.masterKey.derive(0);
return new KeyRing(derivedKey)
}
fundingScript() {
const pubKeys = [this.keyRing.publicKey, this.peerPublicKey];
return Script.fromMultisig(this.m, this.n, pubKeys);
}
fundingAddress() {
return this.fundingScript().getAddress().toBase58(network.type);
}
async fundChannel() {
const mtx = new MTX();
mtx.addOutput({
address: this.fundingAddress(),
value: this.satoshis,
});
const inputs = await this._generateInputs();
await mtx.fund(inputs, {
rate: 1000,
changeAddress: this.address
});
// sign inputs
inputs.forEach((input, i) => {
mtx.scriptInput(i, input, this.keyRing);
mtx.signInput(i, input, this.keyRing);
})
const fundingTX = mtx.toTX();
this.fundingTX = fundingTX;
return this.fundingTX;
}
async _generateInputs() {
const txs = await this.nodeClient.getTXByAddress(this.address);
let inputAmount = 0;
const coins = [];
while (inputAmount <= this.satoshis) {
let tx = txs.shift();
tx.outputs.forEach((utxo, i) => {
if (inputAmount <= this.satoshis && utxo.address == this.address) {
let coin = Coin.fromJSON({
version: 1,
height: -1,
value: utxo.value,
coinbase: false,
script: utxo.script,
hash: tx.hash,
index: i,
})
coins.push(coin);
inputAmount += utxo.value;
}
})
}
return coins;
}
buildCommitmentTX(newLocal, newRemote) {
/*
build a tx with funding tx as input and two outputs:
local ouput: p2sh (RSMC):
IF [secret_R] ELSE [050000] CHECKSEQUENCEVERIFY DROP [local_pub_key] ENDIF CHECKSIG
remote ouput: ordinary P2PKH
*/
const script = new Script();
script.pushSym("IF");
script.pushData(Buffer.from("secret_R"));
script.pushSym("ELSE");
script.pushData(Buffer.from("050000"));
script.pushSym("CHECKSEQUENCEVERIFY");
script.pushSym("DROP");
script.pushSym('DUP');
script.pushSym('HASH160')
script.pushData(Buffer.from("pub_key_hash"));
script.pushSym("ENDIF");
script.pushSym("CHECKSIG");
console.log(script)
}
}
module.exports = Channel;
// this is how you broadcast txs
// const broadcast = await nodeClient.broadcast(txHex);
<file_sep>Bcoin (Payment Channels)
========================
Mock Implementation of Payment Channels built on top of the Bcoin node. For learning purposes only, **not to be used on mainnet**.
Run a Bcoin Node on regtest:
----------------------------
```
./bin/bcoin --network=regtest
```
Run the Lnb Node:
-------------------
```
./bin/lnb
```
Interact with it using the Lnb-Client:
--------------------------------------
**create a wallet:**
```
./bin/lnb-cli create-wallet
```
it will respond with your recovery mnemonic
**open a channel:**
```
./bin/lnb-cli open-channel [public key] [satoshis]
```
it will respond with a funding transaction
<file_sep>/* eslint-env mocha */
/* eslint prefer-arrow-callback: "off" */
'use strict';
const assert = require('bsert');
const consensus = require('../lib/protocol/consensus');
const Address = require('../lib/primitives/address');
const FullNode = require('../lib/node/fullnode');
const ports = {
p2p: 49331,
node: 49332,
wallet: 49333
};
const node = new FullNode({
network: 'regtest',
apiKey: 'foo',
walletAuth: true,
memory: true,
workers: true,
workersSize: 2,
plugins: [require('../lib/wallet/plugin')],
port: ports.p2p,
httpPort: ports.node,
env: {
'BCOIN_WALLET_HTTP_PORT': ports.wallet.toString()
}});
const {NodeClient, WalletClient} = require('bclient');
const nclient = new NodeClient({
port: ports.node,
apiKey: 'foo',
timeout: 15000
});
const wclient = new WalletClient({
port: ports.wallet,
apiKey: 'foo'
});
const {wdb} = node.require('walletdb');
const defaultCoinbaseMaturity = consensus.COINBASE_MATURITY;
let addressHot = null;
let addressMiner = null;
let walletHot = null;
let walletMiner = null;
let blocks = null;
let txid = null;
let utxo = null;
describe('RPC', function() {
this.timeout(15000);
before(() => {
consensus.COINBASE_MATURITY = 0;
});
after(() => {
consensus.COINBASE_MATURITY = defaultCoinbaseMaturity;
});
it('should open node and create wallets', async () => {
await node.open();
await nclient.open();
await wclient.open();
const walletHotInfo = await wclient.createWallet('hot');
walletHot = wclient.wallet('hot', walletHotInfo.token);
const walletMinerInfo = await wclient.createWallet('miner');
walletMiner = wclient.wallet('miner', walletMinerInfo.token);
await walletHot.open();
await walletMiner.open();
});
it('should rpc help', async () => {
assert(await nclient.execute('help', []));
assert(await wclient.execute('help', []));
await assert.rejects(async () => {
await nclient.execute('help', ['getinfo']);
}, {
name: 'Error',
message: /^getinfo/
});
await assert.rejects(async () => {
await wclient.execute('help', ['getbalance']);
}, {
name: 'Error',
message: /^getbalance/
});
});
it('should rpc getinfo', async () => {
const info = await nclient.execute('getinfo', []);
assert.strictEqual(info.blocks, 0);
});
it('should rpc selectwallet', async () => {
const response = await wclient.execute('selectwallet', ['miner']);
assert.strictEqual(response, null);
});
it('should rpc getnewaddress from default account', async () => {
const acctAddr = await wclient.execute('getnewaddress', []);
assert(Address.fromString(acctAddr.toString()));
});
it('should fail rpc getnewaddress from nonexistent account', async () => {
await assert.rejects(async () => {
await wclient.execute('getnewaddress', ['bad-account-name']);
}, {
name: 'Error',
message: 'Account not found.'
});
});
it('should rpc getaccountaddress', async () => {
addressMiner = await wclient.execute('getaccountaddress', ['default']);
assert(Address.fromString(addressMiner.toString()));
});
it('should rpc generatetoaddress', async () => {
blocks = await nclient.execute('generatetoaddress',
[10, addressMiner]);
assert.strictEqual(blocks.length, 10);
});
it('should rpc sendtoaddress', async () => {
const acctHotDefault = await walletHot.getAccount('default');
addressHot = acctHotDefault.receiveAddress;
txid = await wclient.execute('sendtoaddress', [addressHot, 0.1234]);
assert.strictEqual(txid.length, 64);
});
it('should rpc sendmany', async () => {
const sendTo = {};
sendTo[addressHot] = 1.0;
sendTo[addressMiner] = 0.1111;
txid = await wclient.execute('sendmany', ['default', sendTo]);
assert.strictEqual(txid.length, 64);
});
it('should fail malformed rpc sendmany', async () => {
await assert.rejects(async () => {
await wclient.execute('sendmany', ['default', null]);
}, {
name: 'Error',
message: 'Invalid send-to address.'
});
const sendTo = {};
sendTo[addressHot] = null;
await assert.rejects(async () => {
await wclient.execute('sendmany', ['default', sendTo]);
}, {
name: 'Error',
message: 'Invalid amount.'
});
});
it('should rpc listreceivedbyaddress', async () => {
await wclient.execute('selectwallet', ['hot']);
const listZeroConf = await wclient.execute('listreceivedbyaddress',
[0, false, false]);
assert.deepStrictEqual(listZeroConf, [{
'involvesWatchonly': false,
'address': addressHot,
'account': 'default',
'amount': 1.1234,
'confirmations': 0,
'label': ''
}]);
blocks.push(await nclient.execute('generatetoaddress', [1, addressMiner]));
await wdb.syncChain();
const listSomeConf = await wclient.execute('listreceivedbyaddress',
[1, false, false]);
assert.deepStrictEqual(listSomeConf, [{
'involvesWatchonly': false,
'address': addressHot,
'account': 'default',
'amount': 1.1234,
'confirmations': 1,
'label': ''
}]);
const listTooManyConf = await wclient.execute('listreceivedbyaddress',
[100, false, false]);
assert.deepStrictEqual(listTooManyConf, []);
});
it('should rpc listtransactions with no args', async () => {
const txs = await wclient.execute('listtransactions', []);
assert.strictEqual(txs.length, 2);
assert.strictEqual(txs[0].amount + txs[1].amount, 1.1234);
assert.strictEqual(txs[0].account, 'default');
});
it('should rpc listtransactions from specified account', async () => {
const wallet = await wclient.wallet('hot');
await wallet.createAccount('foo');
const txs = await wclient.execute('listtransactions', ['foo']);
assert.strictEqual(txs.length, 0);
});
it('should fail rpc listtransactions from nonexistent account', async () => {
assert.rejects(async () => {
await wclient.execute('listtransactions', ['nonexistent']);
}, {
name: 'Error',
message: 'Account not found.'
});
});
it('should rpc listunspent', async () => {
utxo = await wclient.execute('listunspent', []);
assert.strictEqual(utxo.length, 2);
});
it('should rpc lockunspent and listlockunspent', async () => {
let result = await wclient.execute('listlockunspent', []);
assert.deepStrictEqual(result, []);
// lock one utxo
const output = utxo[0];
const outputsToLock = [{'txid': output.txid, 'vout': output.vout}];
result = await wclient.execute('lockunspent', [false, outputsToLock]);
assert(result);
result = await wclient.execute('listlockunspent', []);
assert.deepStrictEqual(result, outputsToLock);
// unlock all
result = await wclient.execute('lockunspent', [true]);
assert(result);
result = await wclient.execute('listlockunspent', []);
assert.deepStrictEqual(result, []);
});
it('should rpc listsinceblock', async () => {
const listNoBlock = await wclient.execute('listsinceblock', []);
assert.strictEqual(listNoBlock.transactions.length, 2);
// txs returned in unpredictable order
const txids = [
listNoBlock.transactions[0].txid,
listNoBlock.transactions[1].txid
];
assert(txids.includes(txid));
const block5 = blocks[5];
const listOldBlock = await wclient.execute('listsinceblock', [block5]);
assert.strictEqual(listOldBlock.transactions.length, 2);
const nonexistentBlock = consensus.ZERO_HASH.toString('hex');
await assert.rejects(async () => {
await wclient.execute('listsinceblock', [nonexistentBlock]);
}, {
name: 'Error',
message: 'Block not found.'
});
});
it('should cleanup', async () => {
await walletHot.close();
await walletMiner.close();
await wclient.close();
await nclient.close();
await node.close();
});
});
<file_sep>#!/usr/bin/env node
'use strict';
const net = require('net');
const packet = JSON.stringify({
command: process.argv[2],
args: process.argv.slice(3, process.argv.length)
});
const client = new net.Socket();
client.connect(1337, '127.0.0.1', function() {
client.write(packet);
});
client.on('data', function(data) {
console.log(JSON.parse(data));
client.destroy(); // kill client after server's response
});
client.on('close', function() {
// do something on close
});
| 55058e14ab657874419b6182cb03f967c0f1c8bd | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | ryan-lingle/bcoin-payment-channels | 0956f4fc3ab52a3f51dc87d4ff957b96a1f22aba | 6f393217e19a7f1ffd13d96b40ff1d505e3595b3 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinaryTreeQuiz
{
public class Node<T>
{
public T data { get; set; }
public Node<T> Left { get; set; }
public Node<T> Right { get; set; }
public Node(T data)
{
this.data = data;
}
public Node(T data, Node<T> left, Node<T> right)
{
this.data = data;
this.Left = left;
this.Right = right;
}
}
class Program
{
static void Main(string[] args)
{
Node<int> root = new Node<int>(11);
addToTree(root, 3);
addToTree(root, 0);
addToTree(root, 4);
addToTree(root, 4);
Console.WriteLine(AddUpTree(root));
Console.WriteLine(IsCalculationTree(root));
Console.WriteLine(IsBalanced(root));
printFromQueue(root);
Console.ReadLine();
}
static Node<int> addToTree(Node<int> root, int newData)
{
if (root == null)
{
Node<int> newNode = new Node<int>(newData);
return newNode;
}
else if (newData < root.data)
{
root.Left = addToTree(root.Left, newData);
}
else
{
root.Right = addToTree(root.Right, newData);
}
return root;
}
public static int AddUpTree(Node<int> root)
{
if (root != null)
{
return root.data + AddUpTree(root.Left) + AddUpTree(root.Right);
}
else
{
return 0;
}
}
public static bool IsCalculationTree(Node<int> root)
{
if (root == null)
{
return false;
}
int sumOfLeft = AddUpTree(root.Left);
int sumOfRight = AddUpTree(root.Right);
if (root.data == sumOfLeft + sumOfRight)
{
return true;
}
return false;
}
static bool IsBalanced(Node<int> root)
{
if (root == null)
return true;
int differenceInHieght = Math.Abs(GetHeight(root.Right) - GetHeight(root.Left));
if (differenceInHieght > 1)
{
return false;
}
return IsBalanced(root.Left) && IsBalanced(root.Right);
}
static int GetHeight(Node<int> root)
{
if (root == null)
{
return 0;
}
else
{
return 1 + Math.Max(GetHeight(root.Left), GetHeight(root.Right));
}
}
static void printFromQueue(Node<int> root)
{
if(root == null)
{
return;
}
var queue = new Queue<Node<int>>();
queue.Enqueue(root);
Console.WriteLine(root.data);
while(queue.Count != 0)
{
var queueCount = queue.Count();
var lastNode = new Node<int>(-1);
for(int x = 0; x <= queueCount; x++)
{
var temp = queue.Dequeue();
if(x == queueCount - 1)
{
lastNode = temp;
}
if(temp.Left != null)
{
Console.WriteLine(temp.Left.data);
queue.Enqueue(temp.Left);
}
if(temp.Right != null)
{
Console.WriteLine(temp.Right.data);
queue.Enqueue(temp.Right);
}
}
}
}
}
}
| 09d211d4a70a091671a1ee76600e3123f9aedade | [
"C#"
] | 1 | C# | JeffreyCadorath/BinaryTreesQuiz | 322adf953a04fe64b5d39cdd519fceebe8224ef6 | 51cddb1b0a469863747069b4baaadac69e051ef8 |
refs/heads/master | <file_sep>class timer {
constructor() {
this.t = 0;
this.tickInterval = null;
}
tick = () => {
if (this.t<1000) {
this.t++;
this.updateDOM();
}
else {
document.querySelector(".digits").classList.add("redDigit");
this.disableButtons({start:true,stop:true})
clearInterval(this.tickInterval);
}
}
start = () => {
this.disableButtons({start:true,stop:false})
this.tickInterval = setInterval(this.tick,10);
}
stop = () => {
clearInterval(this.tickInterval);
this.disableButtons({start:false,stop:true})
}
reset = () => {
clearInterval(this.tickInterval);
this.t = 0;
this.updateDOM();
document.querySelector(".digits").classList.remove("redDigit");
this.disableButtons({start:false,stop:true})
}
updateDOM = () => {
let tS = this.t.toString();
["msTens","msHundreds","secondOnes","secondTens"].forEach((e,i)=>{
document.querySelector(`#${e}`).innerText = tS[tS.length-i-1] || 0;
});
}
disableButtons = (stateObject) => {
Object.keys(stateObject).forEach(e=>{document.querySelector(`#${e}Button`).disabled = stateObject[e]})
}
}
function createButtons() {
const timer1 = new timer();
const buttonDiv = document.createElement("div");
buttonDiv.id = "buttonDiv";
document.querySelector("body").appendChild(buttonDiv);
["start","stop","reset"].forEach(e=>{
const button = document.createElement("button");
button.id = `${e}Button`;
button.innerText = e;
buttonDiv.appendChild(button);
button.addEventListener('click',()=>{timer1[e]()})
})
}
window.addEventListener('load',()=>{createButtons();})
/*
* SG1: Implement a start button. The digital timer should not start until the button is pressed.
* SG2: Once you have a start button working, configure it so that when a user presses the start button it is disabled and not enabled until the timer finishes.
* SG3: Once you have finished SG2, add new new button called `reset` that resets the timer to 0:00:00 and then pressing the start button again will start the timer from 0.
* SG4: Finally, if you have completed all the stretch goals, spend some time styling your timer and buttons.
*/<file_sep>const siteContent = {
"nav": {
"nav-item-1": "Services",
"nav-item-2": "Product",
"nav-item-3": "Vision",
"nav-item-4": "Features",
"nav-item-5": "About",
"nav-item-6": "Contact",
"img-src": "img/logo.png"
},
"cta": {
"h1": "DOM Is Awesome",
"button": "Get Started",
"img-src": "img/header-img.png"
},
"main-content": {
"features-h4":"Features",
"features-content": "Features content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.",
"about-h4":"About",
"about-content": "About content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.",
"middle-img-src": "img/mid-page-accent.jpg",
"services-h4":"Services",
"services-content": "Services content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.",
"product-h4":"Product",
"product-content": "Product content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.",
"vision-h4":"Vision",
"vision-content": "Vision content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.",
},
"contact": {
"contact-h4" : "Contact",
"address" : "123 Way 456 Street Somewhere, USA",
"phone" : "1 (888) 888-8888",
"email" : "<EMAIL>",
},
"footer": {
"copyright" : "Copyright Great Idea! 2018"
},
};
// Example: Update the img src for the logo
let logo = document.getElementById("logo-img");
logo.setAttribute('src', siteContent["nav"]["img-src"])
/*
1
* [ ] Create selectors by using any of the DOM element's methods
* [ ] Note that IDs have been used on all images. Use the IDs to update src path content
2
* [ ] Remember, NO direct updating of the HTML source is allowed.
* [ ] Using your selectors, update the content to match the example file
* [ ] Remember to update the src attributes on images
*/
let middleImg = document.querySelector("#middle-img");
middleImg.src = siteContent["main-content"]["middle-img-src"];
let ctaImg = document.querySelector("#cta-img");
ctaImg.src = siteContent["cta"]["img-src"]
let ctaH1 = document.querySelector(".cta-text>h1");
ctaH1.innerText = siteContent["cta"]["h1"];
let ctaButton = document.querySelector(".cta-text>button");
ctaButton.innerText = siteContent["cta"]["button"]
let navAnchors = document.querySelectorAll('nav>a');
navAnchors.forEach((e,i)=>{
let aText = siteContent.nav[`nav-item-${i+1}`];
e.innerText = aText; e.href = `#${aText}`
});
let h4Nodes = document.querySelectorAll(".text-content>h4");
let pNodes = document.querySelectorAll(".text-content>p");
let sections = ["features","about","services","product","vision"];
h4Nodes.forEach((e,i)=>{
h4Nodes[i].innerText = siteContent["main-content"][`${sections[i]}-h4`];
pNodes[i].innerText = siteContent["main-content"][`${sections[i]}-content`];
});
let contactNodes = document.querySelector(".contact").children;
Object.values(siteContent.contact).forEach((e,i)=>{
contactNodes[i].innerText = e;
})
/*
3
* [ ] Change the color of the navigation text to be green.
*/
let updateNavCSS = () => {
document.querySelectorAll("header>nav>a").forEach(e=>e.style = "color: lightgreen; background: #333; padding: 1em");
}
/*
* [ ] Utilize `.appendChild()` and `.prepend()` to add two new items to the navigation system. You can call them whatever you want.
* [ ] Check your work by looking at the [original html](original.html) in the browser
*/
// document.querySelector("header>nav").appendChild()
let newsButton = document.createElement("a");
newsButton.href = `#news`;
newsButton.innerText = "News";
document.querySelector("nav").prepend(newsButton);
let careersButton = document.createElement("a");
careersButton.href = `##careers`;
careersButton.innerText = "Careers";
document.querySelector("nav").appendChild(careersButton);
updateNavCSS();
/*
stretch
* [ ] Update styles throughout the page as you see fit. Study what happens when you updated the DOM using style in JavaScript.
*/
document.querySelector("html").style = "background: #222; color: #eee;"
/*
* [ ] Study tomorrow's lesson on events and try to integrate a button that can update content on the site with a click of a button. You could build a similar data object with new values to help you test the click event.
*/
| 0dbe37edef3566ebad668f5c634a50cdd7aa8c2c | [
"JavaScript"
] | 2 | JavaScript | kevinstonge/DOM-I | 7fc328c195c0d435923d7cf946f31a5ebfd52c51 | 6503ccc70c975ca0722bdb9904af1e4bef0ea158 |
refs/heads/master | <file_sep>/*
* The MIT License (MIT)
* Copyright(c) 2020 BeikeSong
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "sha1.h"
#include "base64.h"
#include "ws_packet.h"
#include "string_helper.h"
#define SP " "
#define EOL "\r\n"
#define DEFAULT_HTTP_VERSION "HTTP/1.1"
WebSocketPacket::WebSocketPacket()
{
fin_ = 0;
rsv1_ = 0;
rsv2_ = 0;
rsv3_ = 0;
opcode_ = 0;
mask_ = 0;
length_type_ = 0;
masking_key_[4] = {0};
payload_length_ = 0;
}
int32_t WebSocketPacket::recv_handshake(ByteBuffer &input)
{
if (input.length() > WS_MAX_HANDSHAKE_FRAME_SIZE)
{
return WS_MAX_HANDSHAKE_FRAME_SIZE;
}
std::string inputstr(input.bytes(), input.length());
int32_t frame_size = fetch_hs_element(inputstr);
if (frame_size <= 0)
{
//continue recving data;
input.resetoft();
return 0;
}
if (get_param("Upgrade") != "websocket" || get_param("Connection") != "Upgrade" ||
get_param("Sec-WebSocket-Version") != "13" || get_param("Sec-WebSocket-Key") == "")
{
input.resetoft();
return WS_ERROR_INVALID_HANDSHAKE_PARAMS;
}
hs_length_ = frame_size;
input.skip_x(hs_length_);
return 0;
}
int32_t WebSocketPacket::pack_handshake_rsp(std::string &hs_rsp)
{
std::string magic_key = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
std::string raw_key = get_param("Sec-WebSocket-Key") + magic_key;
std::string sha1_key = SHA1::SHA1HashString(raw_key);
char accept_key[128] = {0};
Base64encode(accept_key, sha1_key.c_str(), sha1_key.length());
std::ostringstream sstream;
sstream << "HTTP/1.1 101 Switching Protocols" << EOL;
sstream << "Connection: upgrade" << EOL;
sstream << "Upgrade: websocket" << EOL;
sstream << "Sec-WebSocket-Accept: " << accept_key << EOL;
if (get_param("Sec-WebSocket-Protocol") != "")
{
sstream << "Sec-WebSocket-Protocol: chat" << EOL;
}
sstream << EOL;
hs_rsp = sstream.str();
return 0;
}
uint64_t WebSocketPacket::recv_dataframe(ByteBuffer &input)
{
int header_size = fetch_frame_info(input);
//std::cout << "WebSocketPacket: header size: " << header_size
// << " payload_length_: " << payload_length_ << " input.length: " << input.length() << std::endl;
if (payload_length_ + header_size > input.length())
{
// buffer size is not enough, so we continue recving data
std::cout << "WebSocketPacket: recv_dataframe: continue recving data." << std::endl;
input.resetoft();
return 0;
}
fetch_payload(input);
std::cout << "WebSocketPacket: received data with header size: " << header_size << " payload size:" << payload_length_
<< " input oft size:" << input.getoft() << std::endl;
//return payload_length_;
return input.getoft();
}
int32_t WebSocketPacket::fetch_frame_info(ByteBuffer &input)
{
// FIN, opcode
uint8_t onebyte = 0;
input.read_bytes_x((char *)&onebyte, 1);
fin_ = onebyte >> 7;
opcode_ = onebyte & 0x7F;
// payload length
input.read_bytes_x((char *)&onebyte, 1);
mask_ = onebyte >> 7 & 0x01;
length_type_ = onebyte & 0x7F;
if (length_type_ < 126)
{
payload_length_ = length_type_;
}
else if (length_type_ == 126)
{
/*
uint16_t len = 0;
input.read_bytes_x((char *)&len, 2);
len = (len << 8) | (len >>8 & 0xFF);
payload_length_ = len;
*/
uint16_t len = 0;
uint8_t array[2] = {0};
input.read_bytes_x((char *)array, 2);
len = uint16_t(array[0] << 8) | uint16_t(array[1]);
payload_length_ = len;
}
else if (length_type_ == 127)
{
// if you don't have ntohll
uint64_t len = 0;
uint8_t array[8] = {0};
input.read_bytes_x((char *)array, 8);
len = (array[0] << 56) | array[1] << 48 | array[2] << 40 | array[3] << 32
| array[4] << 24 | array[5] << 16 | array[6] << 8 | array[7];
if (payload_length_ > 0xFFFFFFFF)
{
//std::cout >>
}
}
else
{
}
// masking key
if (mask_ == 1)
{
input.read_bytes_x((char *)masking_key_, 4);
}
// return header size
return input.getoft();
}
int32_t WebSocketPacket::fetch_payload(ByteBuffer &input)
{
char real = 0;
if (mask_ == 1)
{
for (uint64_t i = 0; i < payload_length_; i++)
{
input.read_bytes_x(&real, 1);
real = real ^ masking_key_[i % 4];
payload_.append(&real, 1);
}
}
else
{
payload_.append(input.curat(), payload_length_);
input.skip_x(payload_length_);
}
return 0;
}
int32_t WebSocketPacket::pack_dataframe(ByteBuffer &output)
{
uint8_t onebyte = 0;
onebyte |= (fin_ << 7);
onebyte |= (rsv1_ << 6);
onebyte |= (rsv2_ << 5);
onebyte |= (rsv3_ << 4);
onebyte |= (opcode_ & 0x0F);
output.append((char *)&onebyte, 1);
onebyte = 0;
//set mask flag
onebyte = onebyte | (mask_ << 7);
uint8_t length_type = get_length_type();
if (length_type < 126)
{
onebyte |= payload_length_;
output.append((char *)&onebyte, 1);
}
else if (length_type == 126)
{
onebyte |= length_type;
output.append((char *)&onebyte, 1);
// also can use htons
onebyte = (payload_length_ >> 8) & 0xFF;
output.append((char *)&onebyte, 1);
onebyte = payload_length_ & 0xFF;
output.append((char *)&onebyte, 1);
}
else if (length_type == 127)
{
onebyte |= length_type;
output.append((char *)&onebyte, 1);
// also can use htonll if you have it
onebyte = (payload_length_ >> 56) & 0xFF;
output.append((char *)&onebyte, 1);
onebyte = (payload_length_ >> 48) & 0xFF;
output.append((char *)&onebyte, 1);
onebyte = (payload_length_ >> 40) & 0xFF;
output.append((char *)&onebyte, 1);
onebyte = (payload_length_ >> 32) & 0xFF;
output.append((char *)&onebyte, 1);
onebyte = (payload_length_ >> 24) & 0xFF;
output.append((char *)&onebyte, 1);
onebyte = (payload_length_ >> 16) & 0xFF;
output.append((char *)&onebyte, 1);
onebyte = (payload_length_ >> 8) & 0xFF;
output.append((char *)&onebyte, 1);
onebyte = payload_length_ & 0XFF;
output.append((char *)&onebyte, 1);
}
else
{
return -1;
}
if (mask_ == 1)
{
char value = 0;
// save masking key
output.append((char *)masking_key_, 4);
std::cout << "WebSocketPacket: send data with header size: " << output.length()
<< " payload size:" << payload_length_ << std::endl;
for (uint64_t i = 0; i < payload_length_; i++)
{
payload_.read_bytes_x(&value, 1);
value = value ^ masking_key_[i % 4];
output.append(&value, 1);
}
}
else
{
std::cout << "WebSocketPacket: send data with header size: " << output.length()
<< " payload size:" << payload_length_ << std::endl<<std::endl;
output.append(payload_.bytes(), payload_.length());
}
return 0;
}
int32_t WebSocketPacket::fetch_hs_element(const std::string &msg)
{
// two EOLs mean a completed http1.1 request line
std::string::size_type endpos = msg.find(std::string(EOL) + EOL);
if (endpos == std::string::npos)
{
return -1;
}
//can't find end of request line in current, and we continue receiving data
std::vector<std::string> lines;
if (strHelper::splitStr<std::vector<std::string> >
(lines, msg.substr(0, endpos), EOL) < 2)
{
return -1;
}
std::vector<std::string>::iterator it = lines.begin();
while ((it != lines.end()) && strHelper::trim(*it).empty())
{
++it;
};
std::vector<std::string> reqLineParams;
if (strHelper::splitStr<std::vector<std::string> >
(reqLineParams, *it, SP) < 3)
{
return -1;
}
mothod_ = strHelper::trim(reqLineParams[0]);
uri_ = strHelper::trim(reqLineParams[1]);
version_ = strHelper::trim(reqLineParams[2]);
for (++it; it != lines.end(); ++it)
{
// header fields format:
// field name: values
std::string::size_type pos = it->find_first_of(":");
if (pos == std::string::npos)
continue; // invalid line
std::string k = it->substr(0, pos);
std::string v = it->substr(pos + 1);
if (strHelper::trim(k).empty())
{
continue;
}
if (strHelper::trim(v).empty())
{
continue;
}
params_[k] = v;
std::cout << "handshake element k:" << k.c_str() << " v:" << v.c_str() << std::endl;
}
return endpos + 4;
}
void WebSocketPacket::set_payload(const char *buf, uint64_t size)
{
payload_.append(buf, size);
payload_length_ = payload_.length();
}
const uint8_t WebSocketPacket::get_length_type()
{
if (payload_length_ < 126)
{
return (uint8_t)payload_length_;
}
else if (payload_length_ >= 126 && payload_length_ <= 0xFFFF)
{
return 126;
}
else
{
return 127;
}
}
const uint8_t WebSocketPacket::get_header_size()
{
int header_size = 0;
if (get_length_type() < 126)
{
header_size = 2;
}
else if (get_length_type() == 126)
{
header_size = 4;
}
else if (get_length_type() == 127)
{
header_size = 2 + 8;
}
if (mask_ == 1)
{
header_size += 4;
}
}
/*
* ByteBuffer
*
*/
ByteBuffer::ByteBuffer()
{
oft = 0;
}
ByteBuffer::~ByteBuffer()
{
}
bool ByteBuffer::require(int require)
{
int len = length();
return require <= len - oft;
}
char *ByteBuffer::curat()
{
return (length() == 0) ? NULL : &data.at(oft);
}
int ByteBuffer::getoft()
{
return oft;
}
bool ByteBuffer::skip_x(int size)
{
if (require(size))
{
oft += size;
return true;
}
else
{
return false;
}
}
bool ByteBuffer::read_bytes_x(char *cb, int size)
{
if (require(size))
{
memcpy(cb, &data.at(oft), size);
oft += size;
return true;
}
else
{
return false;
}
}
void ByteBuffer::resetoft()
{
oft = 0;
}
int ByteBuffer::length()
{
int len = (int)data.size();
//srs_assert(len >= 0);
return len;
}
char *ByteBuffer::bytes()
{
return (length() == 0) ? NULL : &data.at(0);
}
void ByteBuffer::erase(int size)
{
if (size <= 0)
{
return;
}
if (size >= length())
{
data.clear();
return;
}
data.erase(data.begin(), data.begin() + size);
}
void ByteBuffer::append(const char *bytes, int size)
{
//srs_assert(size > 0);
data.insert(data.end(), bytes, bytes + size);
}
<file_sep># Websocketfiles(1.02)
## Introduction
Websocketfiles provides two well designed and out of box websocket c++ classes that you can easily use in your ongoing project which needs to support websocket.
The purpose of this project is to let you add websocket support in your c++ project as quickly/efficient as possible.The websocketfiles is designed as simple as possible and no network transport module included. It exports two network interfaces named from_wire/to_wire that can be easily binding with any network modules(Boost.Asio, libuv, libevent and so on).
An asynchronous websocket server using libuv is provided to demostrate how to use websocketfiles in a C++ project.
## Features
* **Only two out of box and light weighted websocket c++ classes**(1000+ lines of C++98 code). It is well designed and tested and easily to merge into your ongoing c++ project(or some old c++ projects).
* **Support RFC6455**
* **No network transport modules included**. As people may have different network transport modules in their projects, websocketfiles only fouces on packing/unpacking websocket packet.
* **Multi-platform support(linux/windows)**
* **Fully traced websocket message flow**. A fully tracing infomation of websocket message helps you know websocketfiles code rapidly and expand funcions easily.
## Class and file overview
1. Class WebsocketPacket: a websocket packet class
2. Class WebsocketEndpoint: a websocket server/client wrapper class
3. Class strHelper: a string operation class for parsing websocket handshake message
4. Class ByteBuffer: a simple buffer class base on vector
5. File sha1.cpp and base64.cpp: SHA1 and base64 encode/decode functions for masking/unmasking data
6. File main.cpp: provide an asynchronous websocket server demonstration using libuv as netork transport.
7. Folder src: source file(websocketfiles source code)
8. Folder include: libuv include files(only for demo)
9. Folder lib: libuv so file(only for demo)
## How to use it in your project
* Copy all files except main.cpp from src folder to your project folder.
* Modify function WebSocketEndpoint::from_wire/to_wire and combine it with your network transport read/write function.The connections between modules may look like below:

## Building and testing
```bash
cd websocketfiles
make
./wsfiles_server_uv.1.02
```
**Attention**: The asynchronous demo wsfiles_server_uv only uses an event thread and a single working thread(based on libuv). If you want to increase the number of working thread more than 1 (default value is 1), you can modify UV_THREADPOOL_SIZE value. The most important thing is that you must add some protection codes in main.cpp to make sure some variables are thread safe in multi-working-thread situation.
Start wsfiles_server_uv, and we get tracing messages on console:
```bash
set thread pool size:1
peer (xxx.xxx.xxx.xxx, 11464) connected
handshake element k:Host v: yyy.yyy.yyy.yyy:9050
handshake element k:Connection v:Upgrade
handshake element k:Pragma v:no-cache
handshake element k:Cache-Control v:no-cache
handshake element k:User-Agent v:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
handshake element k:Upgrade v:websocket
handshake element k:Origin v:http://www.bejson.com
handshake element k:Sec-WebSocket-Version v:13
handshake element k:Accept-Encoding v:gzip, deflate
handshake element k:Accept-Language v:zh-CN,zh;q=0.9
handshake element k:Sec-WebSocket-Key v:<KEY>==
handshake element k:Sec-WebSocket-Extensions v:permessage-deflate; client_max_window_bits
WebsocketEndpont - handshake successful!
WebSocketPacket: received data with header size: 6 payload size:28 input oft size:34
WebSocketEndpoint - recv a Text opcode.
WebSocketEndpoint - received data, length:28 ,content:first websocket test message
WebSocketPacket: send data with header size: 2 payload size:28
```
After a successful websocket handshake, the demo server will return the message that you send to it. It is easily to change response message by modifying function WebSocketEndpoint::process_message_data.
```cpp
switch (packet.get_opcode())
{
case WebSocketPacket::WSOpcode_Continue:
// add your process code here
std::cout << "WebSocketEndpoint - recv a Continue opcode." << std::endl;
user_defined_process(packet, frame_payload);
break;
case WebSocketPacket::WSOpcode_Text:
// add your process code here
std::cout << "WebSocketEndpoint - recv a Text opcode." << std::endl;
user_defined_process(packet, frame_payload);
break;
case WebSocketPacket::WSOpcode_Binary:
// add your process code here
std::cout << "WebSocketEndpoint - recv a Binary opcode." << std::endl;
user_defined_process(packet, frame_payload);
break;
...
...
```
## Future
1.Add more demos to illustrate how to use websocketfiles with Boot.Asio and libevent.
2.Support TLS.
<file_sep>/* ***********************************************
* string helper inline file
*/
#include <string.h>
#include <sstream>
template <typename TYPE> inline
int strHelper::splitStr(TYPE& list,
const std::string& str, const char* delim)
{
if (str.empty())
return 0;
if (delim == NULL){
list.push_back(str);
return 1;
}
unsigned int size = strlen(delim);
std::string::size_type prepos = 0;
std::string::size_type pos = 0;
int count = 0;
for(;;)
{
pos = str.find(delim, pos);
if (pos == std::string::npos){
if (prepos < str.size()){
list.push_back(str.substr(prepos));
count++;
}
break;
}
list.push_back(str.substr(prepos, pos-prepos));
count++;
pos += size;
prepos = pos;
}
return count;
}
template <typename T, typename S> inline
const T strHelper::valueOf(const S& a)
{
std::stringstream s;
T t;
s << a ;
s >> t;
return t;
}
<file_sep>/*
* The MIT License (MIT)
* Copyright(c) 2020 BeikeSong
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* define a websocket server/client wrapper class
*/
#ifndef _WS_SVR_HANDLER_H_
#define _WS_SVR_HANDLER_H_
#include <iostream>
#include <vector>
#include <string>
#include <stdint.h>
#include "ws_packet.h"
typedef void (*nt_write_cb)(char * buf,int64_t size, void* wd);
class WebSocketEndpoint
{
public:
WebSocketEndpoint( nt_write_cb write_cb);
WebSocketEndpoint();
virtual ~WebSocketEndpoint();
public:
// start a websocket endpoint process.
virtual int32_t process(const char * readbuf, int32_t size);
// start a websocket endpoint process. Also we register a write callback function
virtual int32_t process(const char * readbuf, int32_t size, nt_write_cb write_cb, void* work_data);
// receive data from wire until we get an entire handshake or frame data packet
virtual int32_t from_wire(const char * readbuf, int32_t size);
// try to find and parse a websocket packet
virtual int64_t parse_packet(ByteBuffer& input);
// process message data
// users should rewrite this function
virtual int32_t process_message_data(WebSocketPacket& packet, ByteBuffer& frame_payload);
// user defined process
virtual int32_t user_defined_process(WebSocketPacket& packet, ByteBuffer& frame_payload);
// send data to wire
virtual int32_t to_wire(const char * writebuf, int64_t size);
private:
bool ws_handshake_completed_;
ByteBuffer fromwire_buf_;
ByteBuffer message_data_;
nt_write_cb nt_write_cb_;
void * nt_work_data_;
};
#endif//_WS_SVR_HANDLER_H_
<file_sep>/*
* The MIT License (MIT)
* Copyright(c) 2020 BeikeSong
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _WS_PACKET_H_
#define _WS_PACKET_H_
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <sstream>
#include <stdint.h>
#include "string_helper.h"
class ByteBuffer;
#define WS_ERROR_INVALID_HANDSHAKE_PARAMS 10070
#define WS_ERROR_INVALID_HANDSHAKE_FRAME 10071
// max handshake frame = 100k
#define WS_MAX_HANDSHAKE_FRAME_SIZE 1024 * 1000
/**
* a simple buffer class base on vector
*/
class ByteBuffer
{
private:
std::vector<char> data;
// current offset in bytes from data.at(0) (data beginning)
uint32_t oft;
public:
ByteBuffer();
virtual ~ByteBuffer();
public:
/**
* get the length of buffer. empty if zero.
* @remark assert length() is not negative.
*/
virtual int length();
/**
* get the buffer bytes.
* @return the bytes, NULL if empty.
*/
virtual char *bytes();
/**
* erase size of bytes from begin.
* @param size to erase size of bytes from the beginning.
* clear if size greater than or equals to length()
* @remark ignore size is not positive.
*/
virtual void erase(int size);
/**
* append specified bytes to buffer.
* @param size the size of bytes
* @remark assert size is positive.
*/
virtual void append(const char *bytes, int size);
// resocman: exhance this class by adding thoes functions
/**
* tell current position return char * p=data.at(oft)
*/
virtual char *curat();
/**
* get current oft value
*/
virtual int getoft();
/**
* check if we have enough size in vector
*/
virtual bool require(int size);
/**
* move size bytes from cur position
*/
virtual bool skip_x(int size);
/**
* read size bytes and move cur positon
*/
virtual bool read_bytes_x(char *cb, int size);
/**
* reset cur position to the beginning of vector
*/
virtual void resetoft();
};
class WebSocketPacket
{
public:
WebSocketPacket();
virtual ~WebSocketPacket(){};
public:
enum WSPacketType : uint8_t
{
WSPacketType_HandShake = 1,
WSPacketType_DataFrame,
};
enum WSOpcodeType : uint8_t
{
WSOpcode_Continue = 0x0,
WSOpcode_Text = 0x1,
WSOpcode_Binary = 0x2,
WSOpcode_Close = 0x8,
WSOpcode_Ping = 0x9,
WSOpcode_Pong = 0xA,
};
public:
//
/**
* try to find and parse a handshake packet
* @param input input buffer
* @param size size of input buffer
* @return errcode, 0 means successful
*
*/
virtual int32_t recv_handshake(ByteBuffer &input);
// fetch handshake element
virtual int32_t fetch_hs_element(const std::string &msg);
/**
* pack a hand shake response packet
* @return errcode
* @param hs_rsp: a resp handshake packet, NULL if empty.
*/
virtual int32_t pack_handshake_rsp(std::string &hs_rsp);
/**
* try to find and parse a data frame
* @return an entire frame size
* 0 means we need to continue recving data,
* and >0 means find get a frame successfule
*/
virtual uint64_t recv_dataframe(ByteBuffer &input);
/**
* get frame info
* @return header size
*/
virtual int32_t fetch_frame_info(ByteBuffer &input);
/**
* get frame payload
* @return only payload size
*/
virtual int32_t fetch_payload(ByteBuffer &input);
/**
* pack a websocket data frame
* @return 0 means successful
*/
virtual int32_t pack_dataframe(ByteBuffer &input);
public:
const uint8_t get_fin() { return fin_; }
const uint8_t get_rsv1() { return rsv1_; }
const uint8_t get_rsv2() { return rsv2_; }
const uint8_t get_rsv3() { return rsv3_; }
const uint8_t get_opcode() { return opcode_; }
const uint8_t get_mask() { return mask_; }
const uint64_t get_payload_length() { return payload_length_; }
void set_fin(uint8_t fin) { fin_ = fin; }
void set_rsv1(uint8_t rsv1) { rsv1_ = rsv1; }
void set_rsv2(uint8_t rsv2) { rsv2_ = rsv2; }
void set_rsv3(uint8_t rsv3) { rsv3_ = rsv3; }
void set_opcode(uint8_t opcode) { opcode_ = opcode; }
void set_mask(uint8_t mask) { mask_ = mask; }
void set_payload_length(uint64_t length) { payload_length_ = length; }
void set_payload(const char *buf, uint64_t size);
const uint8_t get_length_type();
const uint8_t get_header_size();
ByteBuffer &get_payload() { return payload_; }
public:
// get handshake packet length
const uint32_t get_hs_length() { return hs_length_; }
public:
const std::string mothod(void) const
{
return mothod_;
}
void mothod(const std::string &m)
{
mothod_ = m;
}
const std::string uri(void) const
{
return uri_;
}
void uri(const std::string &u)
{
uri_ = u;
}
const std::string version(void) const
{
return version_;
}
void version(const std::string &v)
{
version_ = v;
}
bool has_param(const std::string &name) const
{
return params_.find(name) != params_.end();
}
const std::string get_param(const std::string &name) const
{
std::map<std::string, std::string>::const_iterator it =
params_.find(name);
if (it != params_.end())
{
return it->second;
}
return std::string();
}
template <typename T>
const T get_param(const std::string &name) const
{
return strHelper::valueOf<T, std::string>(get_param(name));
}
void set_param(const std::string &name, const std::string &v)
{
params_[name] = v;
}
template <typename T>
void set_param(const std::string &name, const T &v)
{
params_[name] = strHelper::valueOf<std::string, T>(v);
}
private:
std::string mothod_;
std::string uri_;
std::string version_;
std::map<std::string, std::string> params_;
private:
uint8_t fin_;
uint8_t rsv1_;
uint8_t rsv2_;
uint8_t rsv3_;
uint8_t opcode_;
uint8_t mask_;
uint8_t length_type_;
uint8_t masking_key_[4];
uint64_t payload_length_;
private:
uint32_t hs_length_;
public:
ByteBuffer payload_;
};
#endif //_WS_PACKET_H_<file_sep>CROSS =
CC = $(CROSS)gcc
CXX = $(CROSS)g++
#DEBUG = -g -O2
DEBUG = -g -O0
CFLAGS = $(DEBUG) -Wall -c
RM = rm -rf
SRCPATH = ./src/
SRCS = $(wildcard $(SRCPATH)*.cpp)
OBJS = $(patsubst %.cpp, %.o, $(SRCS))
HEADER_PATH = -I./include
LIB_PATH = -L./ -L./lib/
LIBS = -luv
VERSION = 1.02
TARGET = wsfiles_main_uv.$(VERSION)
$(TARGET) : $(OBJS)
$(CXX) $^ -o $@ $(LIB_PATH) $(LIBS)
$(OBJS):%.o : %.cpp
$(CXX) $(CFLAGS) $< -o $@ $(HEADER_PATH)
clean:
$(RM) $(TARGET) *.o
$(RM) $(SRCPATH)/*.o
<file_sep>#include "string_helper.h"
#include <algorithm>
#include <cctype>
std::string& strHelper::trim(std::string& str, const char thechar)
{
if (str.empty()) {
return str;
}
std::string::size_type pos = str.find_first_not_of(thechar);
if (pos != std::string::npos) {
str.erase(0, pos);
}
pos = str.find_last_of(thechar);
if (pos != std::string::npos) {
str.erase(str.find_last_not_of(thechar) + 1);
}
return str;
}
<file_sep>/*
* The MIT License (MIT)
* Copyright(c) 2020 BeikeSong
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* demostrate an asychronize websocket server base on websocketfiles
* only use one working threadth
*
*/
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include "uv.h"
#include "ws_endpoint.h"
#define DEFAULT_BACKLOG 128
// for each connected client.
typedef struct
{
uv_tcp_t *uvclient;
WebSocketEndpoint *endpoint;
} peer_state_t;
typedef struct
{
uv_tcp_t *uvclient;
WebSocketEndpoint *endpoint;
uv_buf_t request;
uv_buf_t response;
int type;
} peer_work_data_t;
void fail(char* fmt, ...) {
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "\n");
exit(EXIT_FAILURE);
}
void* xmalloc(size_t size) {
void* ptr = malloc(size);
if (!ptr) {
fail("malloc failed");
}
return ptr;
}
void on_alloc_buffer(uv_handle_t *handle, size_t suggested_size,
uv_buf_t *buf)
{
buf->base = (char *)xmalloc(suggested_size);
buf->len = suggested_size;
}
void on_alloc_buffer_v2(char *buf, uint64_t suggested_size)
{
buf = (char *)xmalloc(suggested_size);
}
int uv_buf_alloc_cpy(uv_buf_t *dst, const uv_buf_t *src, int size)
{
if (src == NULL || dst == NULL)
{
printf("main - uv buffer alloc and copy failed[src prt is NULL]!\r\n");
return -1;
}
if (src->len < size)
{
printf("main - uv buffer alloc and copy failed[src-len < size]!\r\n");
return -2;
}
dst->base = (char *)xmalloc(size);
dst->len = size;
memcpy(dst->base, src->base, size);
}
void set_thread_pool_size()
{
int nthread = 0;
const char *val = getenv("UV_THREADPOOL_SIZE");
if (val != NULL)
{
nthread = atoi(val);
printf("dafault thread pool size:%d\n", nthread);
}
setenv("UV_THREADPOOL_SIZE", "1", 1);
val = getenv("UV_THREADPOOL_SIZE");
nthread = atoi(val);
printf("set thread pool size:%d\n", nthread);
}
void free_work_data(peer_work_data_t *workdata)
{
//not free endpoint
workdata->uvclient = NULL;
workdata->endpoint = NULL;
free(workdata->request.base);
workdata->request.base = NULL;
free(workdata->response.base);
workdata->response.base = NULL;
free(workdata);
}
void on_write_response(char *buf, int64_t size, void *wd)
{
peer_work_data_t *work_data = (peer_work_data_t *)wd;
if (work_data->response.base != NULL)
{
fail("Work data response is not NULL!");
}
uv_buf_t src = uv_buf_init(buf, size);
work_data->response = uv_buf_init(NULL, 0);
uv_buf_alloc_cpy(&(work_data->response), &src, src.len);
}
void on_client_closed(uv_handle_t *handle)
{
uv_tcp_t *client = (uv_tcp_t *)handle;
// we free client data it here.
if (client->data)
{
peer_state_t *peerstate = (peer_state_t *)client->data;
delete peerstate->endpoint;
peerstate->endpoint = NULL;
free(client->data);
}
free(client);
}
void on_work_client_closed(uv_work_t *req)
{
if (req == NULL)
{
printf("main - on_client_close: req is null\r\n");
return;
}
peer_work_data_t *work_data = (peer_work_data_t *)req->data;
peer_state_t *peerstate = (peer_state_t *)work_data->uvclient->data;
delete work_data->endpoint;
work_data->endpoint = NULL;
free((peer_state_t *)work_data->uvclient->data);
free(work_data->uvclient);
free(work_data->request.base);
free(work_data->response.base);
free(work_data);
free(req);
}
void on_sent_response(uv_write_t *req, int status)
{
if (status)
{
fail("Write error: %s\n", uv_strerror(status));
}
peer_work_data_t *work_data = (peer_work_data_t *)req->data;
free_work_data(work_data);
free(req);
}
// Runs in a separate thread, can do blocking/time-consuming operations.
void on_work_submitted(uv_work_t *req)
{
peer_work_data_t *work_data = (peer_work_data_t *)req->data;
int nrc = work_data->endpoint->process(work_data->request.base, work_data->request.len,
on_write_response, work_data);
if (nrc < 0)
{
printf("main - process read buf failed with[err:%d].\r\n", nrc);
}
}
void on_work_completed(uv_work_t *req, int status)
{
if (status)
{
fail("on_work_completed error: %s\n", uv_strerror(status));
}
peer_work_data_t *work_data = (peer_work_data_t *)req->data;
if (work_data->response.base == NULL)
{
printf("main - no response data! we will free work data and return directly!\r\n");
work_data->endpoint = NULL;
work_data->uvclient = NULL;
free_work_data(work_data);
free(req);
return;
}
//printf("main - on_work_completed client adr:0x%x \r\n",work_data->uvclient);
uv_write_t *writereq = (uv_write_t *)xmalloc(sizeof(*writereq));
writereq->data = req->data;
req->data = NULL;
int rc;
if ((rc = uv_write(writereq, (uv_stream_t *)work_data->uvclient, &(work_data->response), 1,
on_sent_response)) < 0)
{
fail("uv_write failed: %s", uv_strerror(rc));
}
free(req);
}
uv_work_t *alloc_work_req(peer_state_t *peerstate, ssize_t nread, const uv_buf_t *buf, int type)
{
uv_work_t *work_req = (uv_work_t *)xmalloc(sizeof(*work_req));
peer_work_data_t *work_data = (peer_work_data_t *)xmalloc(sizeof(*work_data));
work_data->uvclient = peerstate->uvclient;
work_data->endpoint = peerstate->endpoint;
work_data->request = uv_buf_init(NULL, 0);
work_data->type = type;
if (work_data->type == 1)
{
if (uv_buf_alloc_cpy(&(work_data->request), buf, nread) < 0)
{
free_work_data(work_data);
free(buf->base);
return NULL;
}
}
work_data->response = uv_buf_init(NULL, 0);
work_req->data = work_data;
return work_req;
}
void on_peer_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf)
{
int rc = 0;
if (nread < 0)
{
if (nread != UV_EOF)
{
fprintf(stderr, "Read error: %s\n", uv_strerror(nread));
}
peer_state_t *peerstate = (peer_state_t *)client->data;
peerstate->uvclient = (uv_tcp_t *)client;
uv_work_t *work_req = alloc_work_req(peerstate, nread, buf, 0);
if ((rc = uv_queue_work(uv_default_loop(), work_req, on_work_client_closed, NULL)) < 0)
{
fail("uv_queue_work failed: %s", uv_strerror(rc));
}
}
else if (nread == 0)
{
// From the documentation of uv_read_cb: nread might be 0, which does not
// indicate an error or EOF. This is equivalent to EAGAIN or EWOULDBLOCK
// under read(2).
printf("main - on_peer_read: nread==0 !\r\n");
}
else
{
// nread > 0
assert(buf->len >= nread);
peer_state_t *peerstate = (peer_state_t *)client->data;
//printf("main - on_peer_read: Watch ps-client:0x%x, client: 0x%x, ps-client-data:0x%x, client-data:0x%x\n",
// peerstate->uvclient, client, peerstate->uvclient->data,client->data);
peerstate->uvclient = (uv_tcp_t *)client;
// add work reqs on the work queue, without blocking the
// callback.
uv_work_t *work_req = alloc_work_req(peerstate, nread, buf, 1);
if ((rc = uv_queue_work(uv_default_loop(), work_req, on_work_submitted,
on_work_completed)) < 0)
{
fail("uv_queue_work failed: %s", uv_strerror(rc));
}
}
free(buf->base);
}
void report_peer_connected(const struct sockaddr_in* sa, socklen_t salen) {
char hostbuf[NI_MAXHOST];
char portbuf[NI_MAXSERV];
if (getnameinfo((struct sockaddr*)sa, salen, hostbuf, NI_MAXHOST, portbuf,
NI_MAXSERV, 0) == 0) {
printf("peer (%s, %s) connected\n", hostbuf, portbuf);
} else {
printf("peer (unknonwn) connected\n");
}
}
void on_peer_connected(uv_stream_t *server, int status)
{
if (status < 0)
{
fprintf(stderr, "Peer connection error: %s\n", uv_strerror(status));
return;
}
// client represents this peer and we will
// release it when the client disconnects.
uv_tcp_t *client = (uv_tcp_t *)xmalloc(sizeof(*client));
int rc;
if ((rc = uv_tcp_init(uv_default_loop(), client)) < 0)
{
fail("uv_tcp_init failed: %s", uv_strerror(rc));
}
client->data = NULL;
if (uv_accept(server, (uv_stream_t *)client) == 0)
{
struct sockaddr_storage peername;
int namelen = sizeof(peername);
if ((rc = uv_tcp_getpeername(client, (struct sockaddr *)&peername,
&namelen)) < 0)
{
fail("uv_tcp_getpeername failed: %s", uv_strerror(rc));
}
report_peer_connected((const struct sockaddr_in *)&peername, namelen);
peer_state_t *peerstate = (peer_state_t *)xmalloc(sizeof(*peerstate));
peerstate->endpoint = new WebSocketEndpoint();
peerstate->uvclient = client;
client->data = peerstate;
if ((rc = uv_read_start((uv_stream_t *)client, on_alloc_buffer,
on_peer_read)) < 0)
{
fail("uv_read_start failed: %s", uv_strerror(rc));
}
}
else
{
uv_close((uv_handle_t *)client, on_client_closed);
}
}
int main(int argc, const char **argv)
{
setvbuf(stdout, NULL, _IONBF, 0);
int portnum = 9000;
if (argc >= 2)
{
portnum = atoi(argv[1]);
}
printf("Serving on port %d\n", portnum);
int rc;
uv_tcp_t server;
if ((rc = uv_tcp_init(uv_default_loop(), &server)) < 0)
{
fail("uv_tcp_init failed: %s", uv_strerror(rc));
}
struct sockaddr_in addr;
if ((rc = uv_ip4_addr("0.0.0.0", portnum, &addr)) < 0)
{
fail("uv_ip4_addr failed: %s", uv_strerror(rc));
}
if ((rc = uv_tcp_bind(&server, (const struct sockaddr *)&addr, 0)) < 0)
{
fail("uv_tcp_bind failed: %s", uv_strerror(rc));
}
// Listen on the socket for new peers to connect. When a new peer connects,
// the on_peer_connected callback will be invoked.
if ((rc = uv_listen((uv_stream_t *)&server, DEFAULT_BACKLOG, on_peer_connected)) <
0)
{
fail("uv_listen failed: %s", uv_strerror(rc));
}
//printf("main - main: set thread pool size.\r\n");
set_thread_pool_size();
// Run the libuv event loop.
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
// If uv_run returned, close the default loop before exiting.
return uv_loop_close(uv_default_loop());
}
<file_sep>/*
* The MIT License (MIT)
* Copyright(c) 2020 BeikeSong
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "ws_endpoint.h"
WebSocketEndpoint::WebSocketEndpoint()
{
//networklayer_ = nt;
nt_write_cb_ = NULL;
ws_handshake_completed_ = false;
}
WebSocketEndpoint::WebSocketEndpoint(nt_write_cb write_cb)
{
//networklayer_ = nt;
nt_write_cb_ = write_cb;
ws_handshake_completed_ = false;
}
WebSocketEndpoint::~WebSocketEndpoint() {}
int32_t WebSocketEndpoint::process(const char *readbuf, int32_t size)
{
return from_wire(readbuf, size);
}
int32_t WebSocketEndpoint::process(const char *readbuf, int32_t size, nt_write_cb write_cb, void *work_data)
{
if (write_cb == NULL || work_data == NULL)
{
std::cout << "WebSocketEndpoint - Attention: write cb is NULL! It will skip current read buf!" << std::endl;
return 0;
}
nt_write_cb_ = write_cb;
nt_work_data_ = work_data;
return from_wire(readbuf, size);
}
int32_t WebSocketEndpoint::from_wire(const char *readbuf, int32_t size)
{
fromwire_buf_.append(readbuf, size);
std::cout<< "WebSocketEndpoint - set fromwire_buf, current length:"<<fromwire_buf_.length()<<std::endl;
while (true)
{
int64_t nrcv = parse_packet(fromwire_buf_);
if (nrcv > 0)
{ // for next one
// clear used data
int64_t n_used = fromwire_buf_.getoft();
std::cout<< "WebSocketEndpoint - fromwire_buf: used data:"<<n_used <<" nrcv:"<<nrcv
<<" length:"<<fromwire_buf_.length()<<std::endl;
fromwire_buf_.erase(nrcv);
fromwire_buf_.resetoft();
if (fromwire_buf_.length() == 0)
{
return nrcv;
}
else
{
continue;
}
}
else if (nrcv == 0)
{ // contueue recving
fromwire_buf_.resetoft();
break;
}
else
{
return -1;
}
}
// make it happy
return 0;
}
int32_t WebSocketEndpoint::to_wire(const char *writebuf, int64_t size)
{
//networklayer_->toWire(writebuf,size);
if (nt_write_cb_ == NULL || nt_work_data_ == NULL || writebuf == NULL || size <= 0)
{
return 0;
}
nt_write_cb_(const_cast<char *>(writebuf), size, nt_work_data_);
return 0;
}
int64_t WebSocketEndpoint::parse_packet(ByteBuffer &input)
{
WebSocketPacket wspacket;
if (!ws_handshake_completed_)
{
uint32_t nstatus = 0;
nstatus = wspacket.recv_handshake(input);
if (nstatus != 0)
{
return -1;
}
if (wspacket.get_hs_length() == 0)
{
// not enough data for a handshake message
// continue recving data
return 0;
}
std::string hs_rsp;
wspacket.pack_handshake_rsp(hs_rsp);
to_wire(hs_rsp.c_str(), hs_rsp.length());
ws_handshake_completed_ = true;
std::cout << "WebsocketEndpont - handshake successful!" << std::endl
<< std::endl;
return wspacket.get_hs_length();
}
else
{
uint64_t ndf = wspacket.recv_dataframe(input);
// continue recving data until get an entire frame
if (ndf == 0)
{
return 0;
}
if (ndf > 0xFFFFFFFF)
{
std::cout << "Attention:frame data length exceeds the max value of a uint32_t varable!" << std::endl;
}
ByteBuffer &payload = wspacket.get_payload();
message_data_.append(payload.bytes(), payload.length());
// now, we have a entire frame
if (wspacket.get_fin() == 1)
{
process_message_data(wspacket, message_data_);
message_data_.erase(message_data_.length());
message_data_.resetoft();
return ndf;
}
return ndf;
}
return -1;
}
int32_t WebSocketEndpoint::process_message_data(WebSocketPacket &packet, ByteBuffer &frame_payload)
{
//#ifdef _SHOW_OPCODE_
switch (packet.get_opcode())
{
case WebSocketPacket::WSOpcode_Continue:
// add your process code here
std::cout << "WebSocketEndpoint - recv a Continue opcode." << std::endl;
user_defined_process(packet, frame_payload);
break;
case WebSocketPacket::WSOpcode_Text:
// add your process code here
std::cout << "WebSocketEndpoint - recv a Text opcode." << std::endl;
user_defined_process(packet, frame_payload);
break;
case WebSocketPacket::WSOpcode_Binary:
// add your process code here
std::cout << "WebSocketEndpoint - recv a Binary opcode." << std::endl;
user_defined_process(packet, frame_payload);
break;
case WebSocketPacket::WSOpcode_Close:
// add your process code here
std::cout << "WebSocketEndpoint - recv a Close opcode." << std::endl;
user_defined_process(packet, frame_payload);
break;
case WebSocketPacket::WSOpcode_Ping:
// add your process code here
std::cout << "WebSocketEndpoint - recv a Ping opcode." << std::endl;
user_defined_process(packet, frame_payload);
break;
case WebSocketPacket::WSOpcode_Pong:
// add your process code here
std::cout << "WebSocketEndpoint - recv a Pong opcode." << std::endl;
user_defined_process(packet, frame_payload);
break;
default:
std::cout << "WebSocketEndpoint - recv an unknown opcode." << std::endl;
break;
}
//#endif
return 0;
}
// we directly return what we get from client
// user could modify this function
int32_t WebSocketEndpoint::user_defined_process(WebSocketPacket &packet, ByteBuffer &frame_payload)
{
// print received websocket payload from client
std::string str_recv(frame_payload.bytes(), frame_payload.length());
std::cout << "WebSocketEndpoint - received data, length:" << str_recv.length()
<< " ,content:" << str_recv.c_str() << std::endl;
WebSocketPacket wspacket;
// set FIN and opcode
wspacket.set_fin(1);
wspacket.set_opcode(packet.get_opcode());
// set payload data
wspacket.set_payload(frame_payload.bytes(), frame_payload.length());
ByteBuffer output;
// pack a websocket data frame
wspacket.pack_dataframe(output);
// send to client
to_wire(output.bytes(), output.length());
}
| 7315bbb610662c764794f35581af193b4a92dc7f | [
"Markdown",
"Makefile",
"C++"
] | 9 | C++ | stevenchen1976/websocketfiles | 407b4548fa62d94767ff224c7d78214552ed6104 | 848496c6b938ee2566ebf81d359d0d0c6e91988a |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Memory;
namespace AssaultCubeAimbot
{
class Program
{
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(uint vk);
private const uint VK_LBUTTON = 0x00000001;
public struct Player
{
public float x, y, z;
public int teamnum;
}
public struct Entity
{
public float distance, x, y, z;
public int hp, teamnum;
}
static public float GetDistance(Entity enemy, Player player)
{
return Convert.ToSingle(Math.Sqrt(Math.Pow(enemy.x - player.x, 2) + Math.Pow(enemy.y - player.y, 2) + Math.Pow(enemy.z - player.z, 2)));
}
static public int GetProximateEnemy(float[] List, int total)
{
int ProximateEnemyNum = 0;
float ProximateDistance = List[0];
for (int i = 1; i < total; i++)
{
if(List[i] < ProximateDistance)
{
ProximateDistance = List[i];
ProximateEnemyNum = i;
}
}
return ProximateEnemyNum;
}
static public float[] GetAngle(Entity enemy, Player player)
{
float[] degree = { 0, 0 };
if (player.y > enemy.y && player.x < enemy.x)
{
degree[0] = (float)(Math.Atan((player.y - enemy.y) / (enemy.x - player.x)) * 180 / Math.PI); //degree:= atan((enemyy % closest % -myy) / (enemyx % closest % -myx)) * 57.3
degree[0] = 90 - degree[0];
}
if (player.y > enemy.y && player.x > enemy.x)
{
degree[0] = (float)(Math.Atan((player.y - enemy.y) / (player.x - enemy.x)) * 180 / Math.PI);
degree[0] += 270;
}
if (player.y < enemy.y && player.x < enemy.x)
{
degree[0] = (float)(Math.Atan((enemy.y - player.y) / (enemy.x - player.x)) * 180 / Math.PI);
degree[0] += 90;
}
if (player.y < enemy.y && player.x > enemy.x)
{
degree[0] = (float)(Math.Atan((enemy.y - player.y) / (player.x - enemy.x)) * 180 / Math.PI);
degree[0] = 270 - degree[0];
}
if (player.z > enemy.z)
{
degree[1] = (float)(-1 * Math.Asin((player.z - enemy.z) / enemy.distance) * 180 / Math.PI);
}
else if (player.z < enemy.z)
{
degree[1] = (float)(1 * Math.Asin((enemy.z - player.z) / enemy.distance) * 180 / Math.PI);
}
return degree;
}
static void Main(string[] args)
{
Console.Title = "AssaultCubeAimbot@";
Console.SetWindowSize(35, 15);
int PID, total, ProximateEnemy;
bool isopened;
float[] Distance = new float[31];
float[] angle = { 0, 0 };
Mem mem = new Mem();
Player player;
Entity[] entities = new Entity[31];
Console.WriteLine("Process searching...");
while (true)
{
PID = mem.getProcIDFromName("ac_client");
if (PID != 0)
break;
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Process found!");
Thread.Sleep(1400);
isopened = mem.OpenProcess(PID);
if (isopened)
{
Console.Beep();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Process attach success!!\n");
Console.WriteLine("Have fun playing games!!!");
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Process attach fail...");
Thread.Sleep(2000);
Environment.Exit(0);
}
while (true)
{
total = mem.readInt("ac_client.exe+0x110D98");
player.x = mem.readFloat("ac_client.exe+0011E20C,0x34");
player.y = mem.readFloat("ac_client.exe+0x0011E20C,0x38");
player.z = mem.readFloat("ac_client.exe+0x0011E20C,0x3C");
player.teamnum = mem.readInt("ac_client.exe+0x0011E20C,0x32C");
for (int i = 0; i < total; i++)
{
entities[i].x = mem.readFloat("ac_client.exe+0x110D90," + (i * 4).ToString("x2") + ",0x34");
entities[i].y = mem.readFloat("ac_client.exe+0x110D90," + (i * 4).ToString("x2") + ",0x38");
entities[i].z = mem.readFloat("ac_client.exe+0x110D90," + (i * 4).ToString("x2") + ",0x3C");
entities[i].hp = mem.readInt("ac_client.exe+0x110D90," + (i * 4).ToString("x2") + ",0xF8");
entities[i].teamnum = mem.readInt("ac_client.exe+0x110D90," + (i * 4).ToString("x2") + ",0x32C");
if (entities[i].hp > 0 && entities[i].teamnum != player.teamnum)
Distance[i] = GetDistance(entities[i], player);
else
Distance[i] = float.MaxValue;
entities[i].distance = Distance[i];
//Console.WriteLine((i+1) + "번째 적의 거리 : " + Distance[i]);
}
ProximateEnemy = GetProximateEnemy(Distance, total);
angle = GetAngle(entities[ProximateEnemy], player);
if(GetAsyncKeyState(VK_LBUTTON) != 0 && Distance[ProximateEnemy] != float.MaxValue)
{
mem.writeMemory("ac_client.exe+0x109B74,0x40", "float", angle[0].ToString());
mem.writeMemory("ac_client.exe+0x109B74,0x44", "float", angle[1].ToString());
}
//Console.WriteLine("가장 가까운 적 : " + ProximateEnemy + " 거리 : " + Distance[ProximateEnemy]);
}
}
}
}<file_sep># AssaultCubeAimbot
- AssaultCube Aimbot program using memory.dll


| f880387219eb5836fab7ddd51f92e27c6eed4a32 | [
"Markdown",
"C#"
] | 2 | C# | A6ly/AssaultCubeAimbot | f98c7f819c1ae1436d67eed97dd55b78c41d59f5 | d5fb480399defd56515f6276c1e4d02fe902a226 |
refs/heads/master | <repo_name>davidmarkclements/check-syntax<file_sep>/index.js
'use strict'
const vm = require('vm')
const Module = require('module')
var path = require('path')
var fs = require('fs')
var dependencyTree = require('dependency-tree')
module.exports = checkSyntax
function checkSyntax (entry) {
return dependencyTree.toList({
filename: require.resolve(entry),
directory: path.dirname(entry),
filter: p => p.indexOf('node_modules') === -1 && !/\.json$/.test(p)
}).map(function (f) {
try {
checkScriptSyntax(fs.readFileSync(f).toString(), f)
} catch (e) {
var lines = e.stack.toString().split('\n')
var loc = lines[0]
var code = lines[1]
var msg = e.message
return {
loc: loc,
code: code,
msg: msg
}
}
}).filter(Boolean)
}
function checkScriptSyntax (source, filename) {
source = stripShebang(source)
source = stripBOM(source)
source = Module.wrap(source)
// compile the script, this will throw if it fails
/* eslint-disable no-new */
new vm.Script(source, { displayErrors: true, filename: filename })
}
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
* because the buffer-to-string conversion in `fs.readFileSync()`
* translates it to FEFF, the UTF-16 BOM.
*/
function stripBOM (content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1)
}
return content
}
/**
* Find end of shebang line and slice it off
*/
function stripShebang (content) {
// Remove shebang
var contLen = content.length
if (contLen >= 2) {
if (content.charCodeAt(0) === 35/* # */ &&
content.charCodeAt(1) === 33/*! */) {
if (contLen === 2) {
// Exact match
content = ''
} else {
// Find end of shebang line and slice it off
var i = 2
for (; i < contLen; ++i) {
var code = content.charCodeAt(i)
if (code === 10/* \n */ || code === 13/* \r */) { break }
}
if (i === contLen) { content = '' } else {
// Note that this actually includes the newline character(s) in the
// new output. This duplicates the behavior of the regular expression
// that was previously used to replace the shebang line
content = content.slice(i)
}
}
}
}
return content
}
<file_sep>/bin.js
#!/usr/bin/env node
'use strict'
var path = require('path')
var report = require('./report')
var entry = process.argv[2]
var cwd = process.cwd()
var fullPath = path.join(cwd, entry)
report(fullPath)
<file_sep>/readme.md
# check-syntax
Checks the syntax of an entry point and it's (application-level) dependencies
as per the currently installed Node version.
## About
The `node -c` command allows us to check the syntax of a single file.
The `check-syntax` module allows us to check the syntax of all the files
in a dependency tree (excluding any dependencies in the `node_modules` folder).
## CLI
### Install
```sh
npm install -g check-syntax
```
### Use
```sh
check-syntax <entry-point>
```
## API
### Install
```sh
npm install check-syntax
```
### Use
```js
var checkSyntax = require('check-syntax')
var someEntryPoint = 'my/js/file.js'
console.log(checkSyntax(someEntryPoint)) // outputs an array of objects, {loc, code, msg}
```
#### Reporter
To use the CLI reporter programatically:
```js
var report = require('check-syntax/report')
var someEntryPoint = 'my/js/file.js'
report(someEntryPoint) // same as output as check-syntax command, will exit immediately
```
If a `pass` callback is supplied, the process won't exit but
instead will call the callback with the first arg set to either `true`
or `false` based on whether the syntax check was successful.
```js
report(someEntryPoint, (pass) => {
if (pass) console.log('hooray')
else console.log('boo')
})
```
### License
MIT | 11e7b911e1d426ae8c84cceb16339ae816e7ae1d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | davidmarkclements/check-syntax | 6ea704166d9cabe60773f421fc26797b261ac6be | 150e69c637d0734cc1e4bf016a2c87b2946645ab |
refs/heads/master | <repo_name>axelcdv/messageTests<file_sep>/Podfile
platform :ios, '7.0'
pod 'Reveal-iOS-SDK', '~> 0.9.1'
<file_sep>/README.md
# MessageTests
====
Test project with message UI
| a5c90c3dc8ea6e49a0db0215790f0191f5cf2538 | [
"Markdown",
"Ruby"
] | 2 | Ruby | axelcdv/messageTests | 830dfcfb160bb048fc1e67b927f40c354e151cea | 63681bbdb381c5ca4eced382c21ffd1c275711d7 |
refs/heads/master | <repo_name>gaooyao/Ielts-Alarm<file_sep>/others/test_d.py
# Generated by Selenium IDE
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class TestD():
def setup_method(self, method):
self.driver = webdriver.Firefox()
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_d(self):
self.driver.get("https://ielts.neea.edu.cn/")
self.driver.set_window_size(1366, 728)
self.driver.find_element(By.ID, "btn_log_goto").click()
self.driver.find_element(By.ID, "userId").click()
self.driver.find_element(By.ID, "userId").send_keys("53029506")
self.driver.find_element(By.ID, "userPwd").click()
self.driver.find_element(By.ID, "userPwd").send_keys("<PASSWORD>")
self.driver.find_element(By.ID, "checkImageCode").click()
self.driver.find_element(By.ID, "checkImageCode").send_keys("zeyd")
self.driver.find_element(By.ID, "checkImageCode").send_keys(Keys.ENTER)
self.driver.find_element(By.ID, "btn_log_goto").click()
self.driver.find_element(By.CSS_SELECTOR, "li:nth-child(14) > a").click()
self.driver.find_element(By.CSS_SELECTOR, "li:nth-child(10) > a").click()
<file_sep>/requirements.txt
requests==2.23.0
pytesseract==0.3.2
playsound==1.2.2
pytest==5.3.5
selenium==3.141.0
aliyun_python_sdk_core==2.13.14
Pillow==9.0.1
<file_sep>/logger_init.py
# coding=utf-8
import logging
def log_init():
logger = logging.getLogger()
logger.setLevel(level=logging.INFO)
fmt = '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
formatter = logging.Formatter(fmt)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
# handler = logging.FileHandler("log.log")
# handler.setLevel(logging.INFO)
# handler.setFormatter(formatter)
# logger.addHandler(handler) #是否把log保存到文件
logger.addHandler(console)
logger.info("log初始化成功")<file_sep>/README.md
# Ielts Alarm
## 雅思剩余考位报警
使用前先在根文件夹创建config.py,内容为:
```
USER_NAME = "" # 雅思官网登录用户名
PASSWORD = "" # 雅思官网登录密码
PHONE_NUMBER = "" # 要短信通知手机号码
AUTHORIZATION = "" # 如果使用又拍云,为TOKEN
ACCESS_KEY_Id = "" # 阿里云AccesskeyId
ACCESS_SECRET = "" # 阿里云AccessSecret
```
<file_sep>/login_site.py
import time
from PIL import Image
import pytesseract
import requests
from io import BytesIO
import logging
from config import USER_NAME,PASSWORD
logger = logging.getLogger("log")
def login_by_window(browser):
"""
通过页面登陆雅思报名系统
:param browser: browserHandler
:return: browserHandler
"""
logger.info("官网已打开,开始登陆")
while True: # 登录
element = browser.find_element_by_id('userId') # 输入用户名
element.clear()
element.send_keys(USER_NAME)
element = browser.find_element_by_id('userPwd') # 输入密码
element.clear()
element.send_keys(<PASSWORD>)
element = browser.find_element_by_id('loginForm') # 加载验证码
element.click()
time.sleep(2)
element = browser.find_element_by_id('chkImg') # 获取验证码
element.click()
time.sleep(2)
imageObject = Image.open(BytesIO(requests.get(element.get_attribute("src")).content))
string = pytesseract.image_to_string(imageObject)
element = browser.find_element_by_id('checkImageCode') # 输入验证码
element.clear()
element.send_keys(string)
time.sleep(10)
element = browser.find_element_by_id('btn_log_goto') # 点击登录按钮
element.click()
time.sleep(2)
try:
browser.find_element_by_id("breadcrumbRange")
logger.info("登陆成功")
return browser
except Exception as e:
logger.info("登陆失败")
continue
def login_by_command(browser):
"""
通过命令行登陆雅思报名系统
:param browser: browserHandler
:return: browserHandler
"""
logger.info("官网已打开,开始登陆")
while True: # 登录
element = browser.find_element_by_id('userId') # 输入用户名
element.clear()
element.send_keys(USER_NAME)
element = browser.find_element_by_id('userPwd') # 输入密码
element.clear()
element.send_keys(<PASSWORD>)
element = browser.find_element_by_id('loginForm') # 加载验证码
element.click()
time.sleep(2)
element = browser.find_element_by_id('chkImg') # 获取验证码
element.click()
time.sleep(2)
imageObject = Image.open(BytesIO(requests.get(element.get_attribute("src")).content))
imageObject.show()
string = input("please enter the code: ")
element = browser.find_element_by_id('checkImageCode') # 输入验证码
element.clear()
element.send_keys(string)
time.sleep(1)
element = browser.find_element_by_id('btn_log_goto') # 点击登录按钮
element.click()
time.sleep(2)
try:
browser.find_element_by_id("breadcrumbRange")
logger.info("登陆成功")
return browser
except Exception as e:
logger.info("登陆失败")
continue
<file_sep>/others/test_e.py
# Generated by Selenium IDE
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class TestE():
def setup_method(self, method):
self.driver = webdriver.Firefox()
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_e(self):
self.driver.get("https://ielts.neea.edu.cn/")
self.driver.set_window_size(1366, 728)
self.driver.find_element(By.ID, "btn_log_goto").click()
self.driver.find_element(By.LINK_TEXT, "考位查询").click()
self.driver.find_element(By.CSS_SELECTOR, "#months > .checkbox:nth-child(2)").click()
self.driver.find_element(By.ID, "btnSearch").click()
element = self.driver.find_element(By.ID, "btnSearch")
actions = ActionChains(self.driver)
actions.move_to_element(element).perform()
element = self.driver.find_element(By.CSS_SELECTOR, "body")
actions = ActionChains(self.driver)
actions.move_to_element(element, 0, 0).perform()
self.driver.find_element(By.CSS_SELECTOR, "#rightRange > #dialog .btn").click()
<file_sep>/alarm.py
from playsound import playsound
import logging
import requests
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
from config import ACCESS_KEY_Id, ACCESS_SECRET, AUTHORIZATION
logger = logging.getLogger("log")
def alarm(message):
logger.info("警报已触发,开始播放提示音")
"""
阿里云发送
"""
client = AcsClient(ACCESS_KEY_Id, ACCESS_SECRET, 'cn-hangzhou')
request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_protocol_type('https')
request.set_version('2017-05-25')
request.set_action_name('SendSms')
request.add_query_param('RegionId', "cn-hangzhou")
request.add_query_param('PhoneNumbers', "13718336593")
request.add_query_param('SignName', "KisPig网")
request.add_query_param('TemplateCode', "SMS_184215625")
request.add_query_param('TemplateParam', "{\"message\": \"" + message + "\"}")
response = client.do_action(request)
logger.info("通知短信已发送%s", response)
"""
又拍云发送
"""
# url = "https://sms-api.upyun.com/api/messages"
# headers = {'Authorization': AUTHORIZATION}
# data = {
# "mobile": phone_number,
# "template_id": "1",
# "vars": message
# }
# res = requests.post(url=url, data=data, headers=headers)
# logger.info("通知短信已发送%s", res.text)
while True:
playsound('./others/alarm.mp3')
<file_sep>/main.py
# coding = utf-8
from inquiry import inquiry_march_ukvi, inquiry_april_remain, inquiry_april_ukvi
from alarm import alarm
from login_site import login_by_window, login_by_command
from selenium import webdriver
import logging
from logger_init import log_init
import datetime
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
log_init() # 初始化log
logger = logging.getLogger()
num = 0 # 已刷新次数
show_window = False # 是否显示浏览器窗口
# if __name__ == "__main__":
# alarm("test")
if __name__ == "__main__":
if show_window:
# 设置浏览器有界面模式
browser = webdriver.Chrome() # 初始化浏览器引擎
else:
# 设置浏览器无界面模式
browser_options = Options()
browser_options.add_argument('--headless')
browser = webdriver.Chrome(chrome_options=browser_options)
logger.info("浏览器初始化成功")
browser.get("http://ielts.neea.cn") # 打开雅思官网
time.sleep(2)
element = browser.find_element_by_id('btn_log_goto') # 点击用户登录按钮
element.click()
time.sleep(2)
if show_window:
login_by_window(browser)
else:
login_by_command(browser)
# 登陆成功
start_time = datetime.datetime.now()
while True: # 开始循环查询
last_time = (datetime.datetime.now() - start_time).seconds
logger.info("********************* 上轮用时%d秒 *********************",
last_time)
start_time = datetime.datetime.now()
num = num + 1
logger.info("********************* 开始第%d遍查询 *********************", num)
try:
if num != 1 and last_time == 0:
try:
browser.find_element(By.CSS_SELECTOR, "#rightRange > #dialog .btn").click()
browser.find_element(By.ID, "btnBackToSearch").click()
time.sleep(1)
except Exception as e:
continue
if inquiry_april_ukvi(browser): # 查询4月份UKVI是否开放
alarm("4UKVIOK")
# if inquiry_april_remain(browser): # 4月份普通雅思考试考位预警
# alarm("4月份普通雅思考位剩余不多")
# if inquiry_april_ukvi(browser): # 4月份雅思捡漏
# alarm("4月份普通雅思考位有剩余")
except Exception as e:
logger.error(e.args)
continue
time.sleep(5)
browser.find_element_by_xpath("//*[text()='我的主页']").click() # 返回主页
time.sleep(5)
<file_sep>/inquiry.py
from selenium.webdriver.common.by import By
import time
import logging
logger = logging.getLogger("log")
WAIT_TIME_S = 0.2
WAIT_TIME_L = 1
def inquiry_april_ukvi(browser):
"""
查询是否开放四月份UKVI考试
"""
logger.info("开始查询是否开放四月份UKVI考试")
browser.find_element(By.CSS_SELECTOR, "li:nth-child(14) > a").click() # 点击UKVI考位查询
time.sleep(WAIT_TIME_L)
try:
browser.find_element(By.ID, "2020-04") # 查询四月份的是否开放
logger.info("四月份UKVI考试报名已开放")
return True # 已开放
except Exception as e:
logger.info("四月份UKVI考试报名未开放")
return False # 未开放
def inquiry_april_remain(browser):
"""
四月份剩余雅思预警
"""
logger.info("开始查询四月份剩余雅思考位剩余情况")
browser.find_element(By.CSS_SELECTOR, "li:nth-child(10) > a").click()
time.sleep(WAIT_TIME_L)
browser.find_element(By.ID, "2020-06").click()
time.sleep(WAIT_TIME_S)
browser.find_element(By.ID, "mvfSiteProvinces211").click()
time.sleep(WAIT_TIME_S)
browser.find_element(By.CSS_SELECTOR, ".myhomecon_bg").click() # 点击空白处
time.sleep(WAIT_TIME_S)
browser.find_element(By.ID, "btnSearch").click()
time.sleep(WAIT_TIME_L)
element = browser.find_element(By.CSS_SELECTOR, ".table:nth-child(1) tr:nth-child(1) > td:nth-child(6)")
if element.text != "有名额":
logger.info("考点一已无名额")
return True
browser.find_element(By.CSS_SELECTOR, ".table:nth-child(1) tr:nth-child(2) > td:nth-child(6)")
if element.text != "有名额":
logger.info("考点二已无名额")
return True
logger.info("两个考点都有剩余")
return False
def inquiry_march_ukvi(browser):
"""
四月份雅思考试捡漏
"""
logger.info("开始查询四月份雅思考试是否有剩余考位")
browser.find_element(By.CSS_SELECTOR, "li:nth-child(10) > a").click() # 点击雅思考位查询
# browser.find_element(By.CSS_SELECTOR, "li:nth-child(14) > a").click() # 点击UKVI考位查询
time.sleep(WAIT_TIME_L)
place_list = ["mvfSiteProvinces211", "mvfSiteProvinces212",
# "mvfSiteProvinces213", "mvfSiteProvinces214",
# "mvfSiteProvinces221", "mvfSiteProvinces222", "mvfSiteProvinces223", "mvfSiteProvinces231",
# "mvfSiteProvinces232", "mvfSiteProvinces233", "mvfSiteProvinces234", "mvfSiteProvinces235",
# "mvfSiteProvinces236", "mvfSiteProvinces237", "mvfSiteProvinces241", "mvfSiteProvinces242",
# "mvfSiteProvinces243", "mvfSiteProvinces244", "mvfSiteProvinces250", "mvfSiteProvinces251",
# "mvfSiteProvinces252", "mvfSiteProvinces253", "mvfSiteProvinces261"
]
for item in place_list:
browser.find_element(By.ID, "2020-04").click() # 点击月份选择框
time.sleep(WAIT_TIME_S)
browser.find_element(By.ID, item).click() # 点击省份框
time.sleep(WAIT_TIME_S)
browser.find_element(By.CSS_SELECTOR, ".myhomecon_bg").click() # 点击空白处
time.sleep(WAIT_TIME_S)
browser.find_element(By.ID, "btnSearch").click() # 点击查询按钮
time.sleep(WAIT_TIME_L)
try:
browser.find_element_by_xpath("//*[text()='有名额']") # 有名额则返回True
logger.info("省份" + item + "有剩余")
return True
except Exception as e:
logger.info("省份" + item + "无剩余")
browser.find_element(By.ID, "btnBackToSearch").click() # 无名额则查询下一个省份
time.sleep(WAIT_TIME_S)
logger.info("四月份雅思考试暂无剩余考位")
return False
<file_sep>/others/test_a.py
# Generated by Selenium IDE
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class TestA():
def setup_method(self, method):
self.driver = webdriver.Firefox()
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_a(self):
self.driver.get("https://ielts.neea.edu.cn/")
self.driver.set_window_size(1382, 744)
self.driver.find_element(By.ID, "btn_log_goto").click()
self.driver.execute_script("window.scrollTo(0,162)")
self.driver.find_element(By.CSS_SELECTOR, "li:nth-child(14) > a").click()
self.driver.find_element(By.ID, "2020-03").click()
self.driver.find_element(By.ID, "mvfSiteProvinces211").click()
self.driver.find_element(By.ID, "mvfSiteProvinces212").click()
self.driver.find_element(By.ID, "btnSearch").click()
| e036eb37b0e57da3abdaae0980157eca4c0a4608 | [
"Markdown",
"Python",
"Text"
] | 10 | Python | gaooyao/Ielts-Alarm | fdaf611edbc0546569b5250e0dca23baac3f47ab | 279513bde42d16cba1e0fa34c1de15cc140f12bc |
refs/heads/master | <file_sep>package com.singam;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Entry> entries = null;
boolean shouldReplace = false;
boolean shouldRemove = false;
boolean onlyMeta = false;
int algorithm = 0;
for(int i=0;i<args.length;i++){ //parsing input
if(args[i].compareTo("meta")==0){
onlyMeta = true;
}
if(args[i].compareTo("replace")==0){
shouldReplace = true;
}
if(args[i].compareTo("remove")==0){
shouldRemove = true;
}
if(args[i].compareTo("md5")==0){
algorithm = 0;
}
if(args[i].compareTo("sha1")==1){
algorithm = 1;
}
if(args[i].compareTo("sha-256")==2){
algorithm = 2;
}
}
try{
echo("Reading file/folder :"+args[args.length-1]);
new FileWrapper(args[args.length-1],algorithm,shouldReplace,shouldRemove,onlyMeta);
entries = FileWrapper.getEntryList();
for(Entry item:entries){
echo(item.fileName+" "+item.hashValue);
}
}catch (ArrayIndexOutOfBoundsException e){
echo("Give file/folder name");
}
}
public static void echo(String msg)
{
System.out.println(msg);
}
}
<file_sep># JAVA-File--Watch-Hash-Bucket
<file_sep>package com.singam;
public interface HashChecker {
String produceFileHash(String filename);
String produceDirHash(String path);
String produceDirMetaHash(String path);
}<file_sep>package com.singam;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Scanner;
import java.util.stream.Stream;
public class FileWrapper implements FileAccessor,HashChecker {
public static ArrayList<Entry> entryList;
MessageDigest md = null;
int algorithm = 0;
boolean shouldReplace = false;
boolean shouldRemove = false;
boolean onlyMeta = false;
public FileWrapper(String fileName,int algorithm,boolean shouldReplace,boolean shouldRemove,boolean onlyMeta){
this.shouldReplace = shouldReplace;
this.shouldRemove = shouldRemove;
//this.fileName = fileName;
this.algorithm = algorithm;
entryList = new ArrayList<>();
String alg = "MD5";
switch(algorithm){
case 0:
alg = "MD5";
break;
case 1:
alg = "SHA1";
break;
case 2:
alg = "SHA-256";
break;
}
try {
md = MessageDigest.getInstance(alg); //init SHA1 algorithm
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
if(!onlyMeta){
loadDataFile();
File file = new File(fileName);
if(file.isDirectory()){
produceDirHash(fileName);
}else{
readFile(fileName);
String sha1 = produceFileHash(fileName);
addHashDetails(fileName,sha1);
}
saveDataFile();
}else{
System.out.println(produceDirMetaHash(fileName));
}
}
private byte[] readFile(String fileName){
RandomAccessFile f = null;
byte[] content = new byte[0];
try {
f = new RandomAccessFile(fileName, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
content = new byte[(int)f.length()];//init content size according to the file
} catch (IOException e) {
e.printStackTrace();
}
try {
f.readFully(content); //loaded into memory
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
public static ArrayList<Entry> getEntryList() {
return entryList;
}
@Override
public void loadDataFile() { //loads our conf file
Scanner file = null;
try {
file = new Scanner(new File("hashbucket.txt"));
while(file.hasNextLine()){
String line = file.nextLine();
String parts[] = line.split(" ");
entryList.add(new Entry(parts[0],parts[1],Integer.parseInt(parts[2])));
}
file.close();
} catch (FileNotFoundException ex) {
System.out.println("Could not find config");
}
}
@Override
public void saveDataFile() { //saves conf file
PrintWriter writer = null;
try {
writer = new PrintWriter("hashbucket.txt", "UTF-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
for(Entry item:entryList){
writer.println(item.fileName+" "+item.hashValue+" "+item.algorithmID);
}
writer.close();
}
@Override
public void addHashDetails(String fileName, String newHash) {
boolean isNew = true;
// entryList.add()adds that entry into arrayList
for(int i=0;i<entryList.size();i++){
if(entryList.get(i).getName().compareTo(fileName) == 0) {
if (!shouldRemove) {
if (entryList.get(i).getHash().compareTo(newHash) == 0) {
System.out.println(fileName + ": File unmodified, Keeping old");
isNew = false;
} else {
System.out.println(fileName + ": File modified ");
isNew = false;
if (shouldReplace) {
System.out.println("Replacing old");
replaceHashDetails(fileName, newHash);
}
}
}else{
System.out.println(fileName +" : Removing from bucket");
removeDetails(fileName);
isNew= false;
}
}
}
if(isNew){
System.out.println(fileName+": New File adding to the bucket");
entryList.add(new Entry(fileName,newHash,this.algorithm));
}
}
@Override
public void replaceHashDetails(String fileName, String newHash) {
removeDetails(fileName);
String sha1 = produceFileHash(fileName);
addHashDetails(fileName,sha1);
}
@Override
public void removeDetails(String fileName) {
for(int i=0;i<entryList.size();i++){
if(entryList.get(i).getName().compareTo(fileName) == 0){
entryList.remove(i);
}
}
}
@Override
public String produceFileHash(String filename) {
byte[] content = readFile(filename);
String sha1 = Base64.getEncoder().encodeToString(md.digest(content));
return sha1;
}
@Override
public String produceDirHash(String path) {
File file = new File(path);
String hash = "";
String fileName;
File[] listOfFiles = file.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("Reading File " + listOfFiles[i].getName());
fileName = file.getName()+"/"+listOfFiles[i].getName();
// loadDataFile();
String sha1 = produceFileHash(file.getName()+"/"+listOfFiles[i].getName());
hash = hash + sha1;
// addHashDetails(listOfFiles[i].getName(),sha1);
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
addHashDetails(path, Base64.getEncoder().encodeToString(md.digest(hash.getBytes())));
return new String();
}
@Override
public String produceDirMetaHash(String name) {
Path path = Paths.get(name).toAbsolutePath();
UserDefinedFileAttributeView fileAttributeView = Files.getFileAttributeView(path, UserDefinedFileAttributeView.class);
String attributes = "";
try {
for(String item:fileAttributeView.list()){
attributes = attributes+item;
}
} catch (IOException e) {
e.printStackTrace();
}
return Base64.getEncoder().encodeToString(md.digest(attributes.getBytes()));
}
}
| efce698d9e6203f250430c7839c57f67767221bb | [
"Markdown",
"Java"
] | 4 | Java | singam96/Java-File-Watch-Hash-Bucket | 95c990f8f4bc06e58651e938a15aece34e32c53e | f21f1b8b01da3c5cc200159cf3bf266961a1b64c |
refs/heads/master | <file_sep>package com.LeetCode.code.q866.RectangleOverlap;
/**
* @QuestionId : 866
* @difficulty : Easy
* @Title : Rectangle Overlap
* @TranslatedTitle:矩形重叠
* @url : https://leetcode-cn.com/problems/rectangle-overlap/
* @TranslatedContent:矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。
如果相交的面积为正,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。
给出两个矩形,判断它们是否重叠并返回结果。
示例 1:
输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3]
输出:true
示例 2:
输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1]
输出:false
说明:
两个矩形 rec1 和 rec2 都以含有四个整数的列表的形式给出。
矩形中的所有坐标都处于 -10^9 和 10^9 之间。
*/
class Solution {
public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
}
}<file_sep>package com.LeetCode.code.q581.ShortestUnsortedContinuousSubarray;
/**
* @QuestionId : 581
* @difficulty : Easy
* @Title : Shortest Unsorted Continuous Subarray
* @TranslatedTitle:最短无序连续子数组
* @url : https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/
* @TranslatedContent:给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
你找到的子数组应是最短的,请输出它的长度。
示例 1:
输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
说明 :
输入的数组长度范围在 [1, 10,000]。
输入的数组可能包含重复元素 ,所以升序的意思是<=。
*/
class Solution {
public int findUnsortedSubarray(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q113.PathSumII;
/**
* @QuestionId : 113
* @difficulty : Medium
* @Title : Path Sum II
* @TranslatedTitle:路径总和 II
* @url : https://leetcode-cn.com/problems/path-sum-ii/
* @TranslatedContent:给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
}
}<file_sep>package com.LeetCode.code.q795.K-thSymbolinGrammar;
/**
* @QuestionId : 795
* @difficulty : Medium
* @Title : K-th Symbol in Grammar
* @TranslatedTitle:第K个语法符号
* @url : https://leetcode-cn.com/problems/k-th-symbol-in-grammar/
* @TranslatedContent:在第一行我们写上一个 0。接下来的每一行,将前一行中的0替换为01,1替换为10。
给定行数 N 和序数 K,返回第 N 行中第 K个字符。(K从1开始)
例子:
输入: N = 1, K = 1
输出: 0
输入: N = 2, K = 1
输出: 0
输入: N = 2, K = 2
输出: 1
输入: N = 4, K = 5
输出: 1
解释:
第一行: 0
第二行: 01
第三行: 0110
第四行: 01101001
注意:
N 的范围 [1, 30].
K 的范围 [1, 2^(N-1)].
*/
class Solution {
public int kthGrammar(int N, int K) {
}
}<file_sep>package com.LeetCode.code.q1040.MaximumBinaryTreeII;
/**
* @QuestionId : 1040
* @difficulty : Medium
* @Title : Maximum Binary Tree II
* @TranslatedTitle:最大二叉树 II
* @url : https://leetcode-cn.com/problems/maximum-binary-tree-ii/
* @TranslatedContent:最大树定义:一个树,其中每个节点的值都大于其子树中的任何其他值。
给出最大树的根节点 root。
就像<a href="https://leetcode-cn.com/problems/maximum-binary-tree/">之前的问题那样,给定的树是从表 A(root = Construct(A))递归地使用下述 Construct(A) 例程构造的:
如果 A 为空,返回 null
否则,令 A[i] 作为 A 的最大元素。创建一个值为 A[i] 的根节点 root
root 的左子树将被构建为 Construct([A[0], A[1], ..., A[i-1]])
root 的右子树将被构建为 Construct([A[i+1], A[i+2], ..., A[A.length - 1]])
返回 root
请注意,我们没有直接给定 A,只有一个根节点 root = Construct(A).
假设 B 是 A 的副本,并附加值 val。保证 B 中的值是不同的。
返回 Construct(B)。
示例 1:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/23/maximum-binary-tree-1-1.png" style="height: 160px; width: 159px;"><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/23/maximum-binary-tree-1-2.png" style="height: 160px; width: 169px;">
输入:root = [4,1,3,null,null,2], val = 5
输出:[5,4,null,1,3,null,null,2]
解释:A = [1,4,2,3], B = [1,4,2,3,5]
示例 2:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/23/maximum-binary-tree-2-1.png" style="height: 160px; width: 180px;"><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/23/maximum-binary-tree-2-2.png" style="height: 160px; width: 214px;">
输入:root = [5,2,4,null,1], val = 3
输出:[5,2,4,null,1,null,3]
解释:A = [2,1,5,4], B = [2,1,5,4,3]
示例 3:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/23/maximum-binary-tree-3-1.png" style="height: 160px; width: 180px;"><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/23/maximum-binary-tree-3-2.png" style="height: 160px; width: 201px;">
输入:root = [5,2,3,null,1], val = 4
输出:[5,2,4,null,1,3]
解释:A = [2,1,5,3], B = [2,1,5,3,4]
提示:
1 <= B.length <= 100
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
}
}<file_sep>package com.LeetCode.code.q167.TwoSumII-Inputarrayissorted;
/**
* @QuestionId : 167
* @difficulty : Easy
* @Title : Two Sum II - Input array is sorted
* @TranslatedTitle:两数之和 II - 输入有序数组
* @url : https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
* @TranslatedContent:给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。
函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
返回的下标值(index1 和 index2)不是从零开始的。
你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例:
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
*/
class Solution {
public int[] twoSum(int[] numbers, int target) {
}
}<file_sep>package com.LeetCode.code.q1184.CarPooling;
/**
* @QuestionId : 1184
* @difficulty : Medium
* @Title : Car Pooling
* @TranslatedTitle:拼车
* @url : https://leetcode-cn.com/problems/car-pooling/
* @TranslatedContent:假设你是一位顺风车司机,车上最初有 capacity 个空座位可以用来载客。由于道路的限制,车 只能 向一个方向行驶(也就是说,不允许掉头或改变方向,你可以将其想象为一个向量)。
这儿有一份行程计划表 trips[][],其中 trips[i] = [num_passengers, start_location, end_location] 包含了你的第 i 次行程信息:
必须接送的乘客数量;
乘客的上车地点;
以及乘客的下车地点。
这些给出的地点位置是从你的 初始 出发位置向前行驶到这些地点所需的距离(它们一定在你的行驶方向上)。
请你根据给出的行程计划表和车子的座位数,来判断你的车是否可以顺利完成接送所用乘客的任务(当且仅当你可以在所有给定的行程中接送所有乘客时,返回 true,否则请返回 false)。
示例 1:
输入:trips = [[2,1,5],[3,3,7]], capacity = 4
输出:false
示例 2:
输入:trips = [[2,1,5],[3,3,7]], capacity = 5
输出:true
示例 3:
输入:trips = [[2,1,5],[3,5,7]], capacity = 3
输出:true
示例 4:
输入:trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
输出:true
提示:
你可以假设乘客会自觉遵守 “先下后上” 的良好素质
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000
*/
class Solution {
public boolean carPooling(int[][] trips, int capacity) {
}
}<file_sep>package com.LeetCode.code.q387.FirstUniqueCharacterinaString;
/**
* @QuestionId : 387
* @difficulty : Easy
* @Title : First Unique Character in a String
* @TranslatedTitle:字符串中的第一个唯一字符
* @url : https://leetcode-cn.com/problems/first-unique-character-in-a-string/
* @TranslatedContent:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:您可以假定该字符串只包含小写字母。
*/
class Solution {
public int firstUniqChar(String s) {
}
}<file_sep>package com.LeetCode.code.q234.PalindromeLinkedList;
/**
* @QuestionId : 234
* @difficulty : Easy
* @Title : Palindrome Linked List
* @TranslatedTitle:回文链表
* @url : https://leetcode-cn.com/problems/palindrome-linked-list/
* @TranslatedContent:请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
}
}<file_sep>package com.LeetCode.code.q832.BinaryTreePruning;
/**
* @QuestionId : 832
* @difficulty : Medium
* @Title : Binary Tree Pruning
* @TranslatedTitle:二叉树剪枝
* @url : https://leetcode-cn.com/problems/binary-tree-pruning/
* @TranslatedContent:给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。
返回移除了所有不包含 1 的子树的原二叉树。
( 节点 X 的子树为 X 本身,以及所有 X 的后代。)
示例1:
输入: [1,null,0,0,1]
输出: [1,null,0,null,1]
解释:
只有红色节点满足条件“所有不包含 1 的子树”。
右图为返回的答案。
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_2.png" style="width:450px" />
示例2:
输入: [1,0,1,0,0,0,1]
输出: [1,null,1,null,1]
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/06/1028_1.png" style="width:450px" />
示例3:
输入: [1,1,0,1,1,0,1,0]
输出: [1,1,0,1,1,null,1]
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/05/1028.png" style="width:450px" />
说明:
给定的二叉树最多有 100 个节点。
每个节点的值只会为 0 或 1 。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q883.CarFleet;
/**
* @QuestionId : 883
* @difficulty : Medium
* @Title : Car Fleet
* @TranslatedTitle:车队
* @url : https://leetcode-cn.com/problems/car-fleet/
* @TranslatedContent:N 辆车沿着一条车道驶向位于 target 英里之外的共同目的地。
每辆车 i 以恒定的速度 speed[i] (英里/小时),从初始位置 position[i] (英里) 沿车道驶向目的地。
一辆车永远不会超过前面的另一辆车,但它可以追上去,并与前车以相同的速度紧接着行驶。
此时,我们会忽略这两辆车之间的距离,也就是说,它们被假定处于相同的位置。
车队 是一些由行驶在相同位置、具有相同速度的车组成的非空集合。注意,一辆车也可以是一个车队。
即便一辆车在目的地才赶上了一个车队,它们仍然会被视作是同一个车队。
会有多少车队到达目的地?
示例:
输入:target = 12, position = [10,8,0,5,3], speed = [2,4,1,1,3]
输出:3
解释:
从 10 和 8 开始的车会组成一个车队,它们在 12 处相遇。
从 0 处开始的车无法追上其它车,所以它自己就是一个车队。
从 5 和 3 开始的车会组成一个车队,它们在 6 处相遇。
请注意,在到达目的地之前没有其它车会遇到这些车队,所以答案是 3。
提示:
0 <= N <= 10 ^ 4
0 < target <= 10 ^ 6
0 < speed[i] <= 10 ^ 6
0 <= position[i] < target
所有车的初始位置各不相同。
*/
class Solution {
public int carFleet(int target, int[] position, int[] speed) {
}
}<file_sep>package com.LeetCode.code.q84.LargestRectangleinHistogram;
/**
* @QuestionId : 84
* @difficulty : Hard
* @Title : Largest Rectangle in Histogram
* @TranslatedTitle:柱状图中最大的矩形
* @url : https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
* @TranslatedContent:给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/histogram.png">
以上是柱状图的示例,其中每个柱子的宽度为 1,给定的高度为 [2,1,5,6,2,3]。
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/histogram_area.png">
图中阴影部分为所能勾勒出的最大矩形面积,其面积为 10 个单位。
示例:
输入: [2,1,5,6,2,3]
输出: 10
*/
class Solution {
public int largestRectangleArea(int[] heights) {
}
}<file_sep>package com.LeetCode.code.q144.BinaryTreePreorderTraversal;
/**
* @QuestionId : 144
* @difficulty : Medium
* @Title : Binary Tree Preorder Traversal
* @TranslatedTitle:二叉树的前序遍历
* @url : https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
* @TranslatedContent:给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q632.SmallestRange;
/**
* @QuestionId : 632
* @difficulty : Hard
* @Title : Smallest Range
* @TranslatedTitle:最小区间
* @url : https://leetcode-cn.com/problems/smallest-range/
* @TranslatedContent:你有 k 个升序排列的整数数组。找到一个最小区间,使得 k 个列表中的每个列表至少有一个数包含在其中。
我们定义如果 b-a < d-c 或者在 b-a == d-c 时 a < c,则区间 [a,b] 比 [c,d] 小。
示例 1:
输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]]
输出: [20,24]
解释:
列表 1:[4, 10, 15, 24, 26],24 在区间 [20,24] 中。
列表 2:[0, 9, 12, 20],20 在区间 [20,24] 中。
列表 3:[5, 18, 22, 30],22 在区间 [20,24] 中。
注意:
给定的列表可能包含重复元素,所以在这里升序表示 >= 。
1 <= k <= 3500
-105 <= 元素的值 <= 105
对于使用Java的用户,请注意传入类型已修改为List<List>。重置代码模板后可以看到这项改动。
*/
class Solution {
public int[] smallestRange(List<List<Integer>> nums) {
}
}<file_sep>package com.LeetCode.code.q712.MinimumASCIIDeleteSumforTwoStrings;
/**
* @QuestionId : 712
* @difficulty : Medium
* @Title : Minimum ASCII Delete Sum for Two Strings
* @TranslatedTitle:两个字符串的最小ASCII删除和
* @url : https://leetcode-cn.com/problems/minimum-ascii-delete-sum-for-two-strings/
* @TranslatedContent:给定两个字符串s1, s2,找到使两个字符串相等所需删除字符的ASCII值的最小和。
示例 1:
输入: s1 = "sea", s2 = "eat"
输出: 231
解释: 在 "sea" 中删除 "s" 并将 "s" 的值(115)加入总和。
在 "eat" 中删除 "t" 并将 116 加入总和。
结束时,两个字符串相等,115 + 116 = 231 就是符合条件的最小和。
示例 2:
输入: s1 = "delete", s2 = "leet"
输出: 403
解释: 在 "delete" 中删除 "dee" 字符串变成 "let",
将 100[d]+101[e]+101[e] 加入总和。在 "leet" 中删除 "e" 将 101[e] 加入总和。
结束时,两个字符串都等于 "let",结果即为 100+101+101+101 = 403 。
如果改为将两个字符串转换为 "lee" 或 "eet",我们会得到 433 或 417 的结果,比答案更大。
注意:
0 < s1.length, s2.length <= 1000。
所有字符串中的字符ASCII值在[97, 122]之间。
*/
class Solution {
public int minimumDeleteSum(String s1, String s2) {
}
}<file_sep>package com.LeetCode.code.q653.TwoSumIV-InputisaBST;
/**
* @QuestionId : 653
* @difficulty : Easy
* @Title : Two Sum IV - Input is a BST
* @TranslatedTitle:两数之和 IV - 输入 BST
* @url : https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst/
* @TranslatedContent:给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。
案例 1:
输入:
5
/ \
3 6
/ \ \
2 4 7
Target = 9
输出: True
案例 2:
输入:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
输出: False
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
}
}<file_sep>package com.LeetCode.code.q138.CopyListwithRandomPointer;
/**
* @QuestionId : 138
* @difficulty : Medium
* @Title : Copy List with Random Pointer
* @TranslatedTitle:复制带随机指针的链表
* @url : https://leetcode-cn.com/problems/copy-list-with-random-pointer/
* @TranslatedContent:给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的<a href="https://baike.baidu.com/item/深拷贝/22785317?fr=aladdin" target="_blank">深拷贝。
示例:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/23/1470150906153-2yxeznm.png">
输入:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}
解释:
节点 1 的值是 1,它的下一个指针和随机指针都指向节点 2 。
节点 2 的值是 2,它的下一个指针指向 null,随机指针指向它自己。
提示:
你必须返回给定头的拷贝作为对克隆列表的引用。
*/
/*
// Definition for a Node.
class Node {
public int val;
public Node next;
public Node random;
public Node() {}
public Node(int _val,Node _next,Node _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public Node copyRandomList(Node head) {
}
}<file_sep>package com.LeetCode.code.q446.ArithmeticSlicesII-Subsequence;
/**
* @QuestionId : 446
* @difficulty : Hard
* @Title : Arithmetic Slices II - Subsequence
* @TranslatedTitle:等差数列划分 II - 子序列
* @url : https://leetcode-cn.com/problems/arithmetic-slices-ii-subsequence/
* @TranslatedContent:如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。
例如,以下数列为等差数列:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
以下数列不是等差数列。
1, 1, 2, 5, 7
数组 A 包含 N 个数,且索引从 0 开始。该数组子序列将划分为整数序列 (P0, P1, ..., Pk),P 与 Q 是整数且满足 0 ≤ P0 < P1 < ... < Pk < N。
如果序列 A[P0],A[P1],...,A[Pk-1],A[Pk] 是等差的,那么数组 A 的子序列 (P0,P1,…,PK) 称为等差序列。值得注意的是,这意味着 k ≥ 2。
函数要返回数组 A 中所有等差子序列的个数。
输入包含 N 个整数。每个整数都在 -231 和 231-1 之间,另外 0 ≤ N ≤ 1000。保证输出小于 231-1。
示例:
输入:[2, 4, 6, 8, 10]
输出:7
解释:
所有的等差子序列为:
[2,4,6]
[4,6,8]
[6,8,10]
[2,4,6,8]
[4,6,8,10]
[2,4,6,8,10]
[2,6,10]
*/
class Solution {
public int numberOfArithmeticSlices(int[] A) {
}
}<file_sep>package com.LeetCode.code.q55.JumpGame;
/**
* @QuestionId : 55
* @difficulty : Medium
* @Title : Jump Game
* @TranslatedTitle:跳跃游戏
* @url : https://leetcode-cn.com/problems/jump-game/
* @TranslatedContent:给定一个非负整数数组,你最初位于数组的第一个位置。
数组中的每个元素代表你在该位置可以跳跃的最大长度。
判断你是否能够到达最后一个位置。
示例 1:
输入: [2,3,1,1,4]
输出: true
解释: 从位置 0 到 1 跳 1 步, 然后跳 3 步到达最后一个位置。
示例 2:
输入: [3,2,1,0,4]
输出: false
解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。
*/
class Solution {
public boolean canJump(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q237.DeleteNodeinaLinkedList;
/**
* @QuestionId : 237
* @difficulty : Easy
* @Title : Delete Node in a Linked List
* @TranslatedTitle:删除链表中的节点
* @url : https://leetcode-cn.com/problems/delete-node-in-a-linked-list/
* @TranslatedContent:请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
现有一个链表 -- head = [4,5,1,9],它可以表示为:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/01/19/237_example.png" style="height: 49px; width: 300px;">
示例 1:
输入: head = [4,5,1,9], node = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], node = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
说明:
链表至少包含两个节点。
链表中所有节点的值都是唯一的。
给定的节点为非末尾节点并且一定是链表中的一个有效节点。
不要从你的函数中返回任何结果。
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
}
}<file_sep>package com.LeetCode.code.q688.KnightProbabilityinChessboard;
/**
* @QuestionId : 688
* @difficulty : Medium
* @Title : Knight Probability in Chessboard
* @TranslatedTitle:“马”在棋盘上的概率
* @url : https://leetcode-cn.com/problems/knight-probability-in-chessboard/
* @TranslatedContent:已知一个 NxN 的国际象棋棋盘,棋盘的行号和列号都是从 0 开始。即最左上角的格子记为 (0, 0),最右下角的记为 (N-1, N-1)。
现有一个 “马”(也译作 “骑士”)位于 (r, c) ,并打算进行 K 次移动。
如下图所示,国际象棋的 “马” 每一步先沿水平或垂直方向移动 2 个格子,然后向与之相垂直的方向再移动 1 个格子,共有 8 个可选的位置。
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/knight.png" style="height: 200px; width: 200px;">
现在 “马” 每一步都从可选的位置(包括棋盘外部的)中独立随机地选择一个进行移动,直到移动了 K 次或跳到了棋盘外面。
求移动结束后,“马” 仍留在棋盘上的概率。
示例:
输入: 3, 2, 0, 0
输出: 0.0625
解释:
输入的数据依次为 N, K, r, c
第 1 步时,有且只有 2 种走法令 “马” 可以留在棋盘上(跳到(1,2)或(2,1))。对于以上的两种情况,各自在第2步均有且只有2种走法令 “马” 仍然留在棋盘上。
所以 “马” 在结束后仍在棋盘上的概率为 0.0625。
注意:
N 的取值范围为 [1, 25]
K 的取值范围为 [0, 100]
开始时,“马” 总是位于棋盘上
*/
class Solution {
public double knightProbability(int N, int K, int r, int c) {
}
}<file_sep>package com.LeetCode.code.q60.PermutationSequence;
/**
* @QuestionId : 60
* @difficulty : Medium
* @Title : Permutation Sequence
* @TranslatedTitle:第k个排列
* @url : https://leetcode-cn.com/problems/permutation-sequence/
* @TranslatedContent:给出集合 [1,2,3,…,n],其所有元素共有 n! 种排列。
按大小顺序列出所有排列情况,并一一标记,当 n = 3 时, 所有排列如下:
"123"
"132"
"213"
"231"
"312"
"321"
给定 n 和 k,返回第 k 个排列。
说明:
给定 n 的范围是 [1, 9]。
给定 k 的范围是[1, n!]。
示例 1:
输入: n = 3, k = 3
输出: "213"
示例 2:
输入: n = 4, k = 9
输出: "2314"
*/
class Solution {
public String getPermutation(int n, int k) {
}
}<file_sep>package com.LeetCode.code.q258.AddDigits;
/**
* @QuestionId : 258
* @difficulty : Easy
* @Title : Add Digits
* @TranslatedTitle:各位相加
* @url : https://leetcode-cn.com/problems/add-digits/
* @TranslatedContent:给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
示例:
输入: 38
输出: 2
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
*/
class Solution {
public int addDigits(int num) {
}
}<file_sep>package com.LeetCode.code.q789.KthLargestElementinaStream;
/**
* @QuestionId : 789
* @difficulty : Easy
* @Title : Kth Largest Element in a Stream
* @TranslatedTitle:数据流中的第K大元素
* @url : https://leetcode-cn.com/problems/kth-largest-element-in-a-stream/
* @TranslatedContent:设计一个找到数据流中第K大元素的类(class)。注意是排序后的第K大元素,不是第K个不同的元素。
你的 KthLargest 类需要一个同时接收整数 k 和整数数组nums 的构造器,它包含数据流中的初始元素。每次调用 KthLargest.add,返回当前数据流中第K大的元素。
示例:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
说明: <br />
你可以假设 nums 的长度≥ k-1 且k ≥ 1。
*/
class KthLargest {
public KthLargest(int k, int[] nums) {
}
public int add(int val) {
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/<file_sep>package com.LeetCode.code.q114.FlattenBinaryTreetoLinkedList;
/**
* @QuestionId : 114
* @difficulty : Medium
* @Title : Flatten Binary Tree to Linked List
* @TranslatedTitle:二叉树展开为链表
* @url : https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
* @TranslatedContent:给定一个二叉树,<a href="https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95/8010757" target="_blank">原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q854.MakingALargeIsland;
/**
* @QuestionId : 854
* @difficulty : Hard
* @Title : Making A Large Island
* @TranslatedTitle:最大人工岛
* @url : https://leetcode-cn.com/problems/making-a-large-island/
* @TranslatedContent:在二维地图上, 0代表海洋, 1代表陆地,我们最多只能将一格 0 海洋变成 1变成陆地。
进行填海之后,地图上最大的岛屿面积是多少?(上、下、左、右四个方向相连的 1 可形成岛屿)
示例 1:
输入: [[1, 0], [0, 1]]
输出: 3
解释: 将一格0变成1,最终连通两个小岛得到面积为 3 的岛屿。
示例 2:
输入: [[1, 1], [1, 0]]
输出: 4
解释: 将一格0变成1,岛屿的面积扩大为 4。
示例 3:
输入: [[1, 1], [1, 1]]
输出: 4
解释: 没有0可以让我们变成1,面积依然为 4。
说明:
1 <= grid.length = grid[0].length <= 50
0 <= grid[i][j] <= 1
*/
class Solution {
public int largestIsland(int[][] grid) {
}
}<file_sep>package com.LeetCode.code.q290.WordPattern;
/**
* @QuestionId : 290
* @difficulty : Easy
* @Title : Word Pattern
* @TranslatedTitle:单词规律
* @url : https://leetcode-cn.com/problems/word-pattern/
* @TranslatedContent:给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = "abba", str = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = "abba", str = "dog cat cat fish"
输出: false
示例 3:
输入: pattern = "aaaa", str = "dog cat cat dog"
输出: false
示例 4:
输入: pattern = "abba", str = "dog dog dog dog"
输出: false
说明:
你可以假设 pattern 只包含小写字母, str 包含了由单个空格分隔的小写字母。
*/
class Solution {
public boolean wordPattern(String pattern, String str) {
}
}<file_sep>package com.LeetCode.code.q368.LargestDivisibleSubset;
/**
* @QuestionId : 368
* @difficulty : Medium
* @Title : Largest Divisible Subset
* @TranslatedTitle:最大整除子集
* @url : https://leetcode-cn.com/problems/largest-divisible-subset/
* @TranslatedContent:给出一个由无重复的正整数组成的集合,找出其中最大的整除子集,子集中任意一对 (Si,Sj) 都要满足:Si % Sj = 0 或 Sj % Si = 0。
如果有多个目标子集,返回其中任何一个均可。
示例 1:
输入: [1,2,3]
输出: [1,2] (当然, [1,3] 也正确)
示例 2:
输入: [1,2,4,8]
输出: [1,2,4,8]
*/
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q224.BasicCalculator;
/**
* @QuestionId : 224
* @difficulty : Hard
* @Title : Basic Calculator
* @TranslatedTitle:基本计算器
* @url : https://leetcode-cn.com/problems/basic-calculator/
* @TranslatedContent:实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。
示例 1:
输入: "1 + 1"
输出: 2
示例 2:
输入: " 2-1 + 2 "
输出: 3
示例 3:
输入: "(1+(4+5+2)-3)+(6+8)"
输出: 23
说明:
你可以假设所给定的表达式都是有效的。
请不要使用内置的库函数 eval。
*/
class Solution {
public int calculate(String s) {
}
}<file_sep>package com.LeetCode.code.q139.WordBreak;
/**
* @QuestionId : 139
* @difficulty : Medium
* @Title : Word Break
* @TranslatedTitle:单词拆分
* @url : https://leetcode-cn.com/problems/word-break/
* @TranslatedContent:给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
注意你可以重复使用字典中的单词。
示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false
*/
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
}
}<file_sep>package com.LeetCode.code.q947.OnlineElection;
/**
* @QuestionId : 947
* @difficulty : Medium
* @Title : Online Election
* @TranslatedTitle:在线选举
* @url : https://leetcode-cn.com/problems/online-election/
* @TranslatedContent:在选举中,第 i 张票是在时间为 times[i] 时投给 persons[i] 的。
现在,我们想要实现下面的查询函数: TopVotedCandidate.q(int t) 将返回在 t 时刻主导选举的候选人的编号。
在 t 时刻投出的选票也将被计入我们的查询之中。在平局的情况下,最近获得投票的候选人将会获胜。
示例:
输入:["TopVotedCandidate","q","q","q","q","q","q"], [[[0,1,1,0,0,1,0],[0,5,10,15,20,25,30]],[3],[12],[25],[15],[24],[8]]
输出:[null,0,1,1,0,0,1]
解释:
时间为 3,票数分布情况是 [0],编号为 0 的候选人领先。
时间为 12,票数分布情况是 [0,1,1],编号为 1 的候选人领先。
时间为 25,票数分布情况是 [0,1,1,0,0,1],编号为 1 的候选人领先(因为最近的投票结果是平局)。
在时间 15、24 和 8 处继续执行 3 个查询。
提示:
1 <= persons.length = times.length <= 5000
0 <= persons[i] <= persons.length
times 是严格递增的数组,所有元素都在 [0, 10^9] 范围中。
每个测试用例最多调用 10000 次 TopVotedCandidate.q。
TopVotedCandidate.q(int t) 被调用时总是满足 t >= times[0]。
*/
class TopVotedCandidate {
public TopVotedCandidate(int[] persons, int[] times) {
}
public int q(int t) {
}
}
/**
* Your TopVotedCandidate object will be instantiated and called as such:
* TopVotedCandidate obj = new TopVotedCandidate(persons, times);
* int param_1 = obj.q(t);
*/<file_sep>package com.LeetCode.code.q796.ReachingPoints;
/**
* @QuestionId : 796
* @difficulty : Hard
* @Title : Reaching Points
* @TranslatedTitle:到达终点
* @url : https://leetcode-cn.com/problems/reaching-points/
* @TranslatedContent:从点 (x, y) 可以转换到 (x, x+y) 或者 (x+y, y)。
给定一个起点 (sx, sy) 和一个终点 (tx, ty),如果通过一系列的转换可以从起点到达终点,则返回 True ,否则返回 False。
示例:
输入: sx = 1, sy = 1, tx = 3, ty = 5
输出: True
解释:
可以通过以下一系列转换从起点转换到终点:
(1, 1) -> (1, 2)
(1, 2) -> (3, 2)
(3, 2) -> (3, 5)
输入: sx = 1, sy = 1, tx = 2, ty = 2
输出: False
输入: sx = 1, sy = 1, tx = 1, ty = 1
输出: True
注意:
sx, sy, tx, ty 是范围在 [1, 10^9] 的整数。
*/
class Solution {
public boolean reachingPoints(int sx, int sy, int tx, int ty) {
}
}<file_sep>package com.LeetCode.code.q837.MostCommonWord;
/**
* @QuestionId : 837
* @difficulty : Easy
* @Title : Most Common Word
* @TranslatedTitle:最常见的单词
* @url : https://leetcode-cn.com/problems/most-common-word/
* @TranslatedContent:给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。题目保证至少有一个词不在禁用列表中,而且答案唯一。
禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。
示例:
输入:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
输出: "ball"
解释:
"hit" 出现了3次,但它是一个禁用的单词。
"ball" 出现了2次 (同时没有其他单词出现2次),所以它是段落里出现次数最多的,且不在禁用列表中的单词。
注意,所有这些单词在段落里不区分大小写,标点符号需要忽略(即使是紧挨着单词也忽略, 比如 "ball,"),
"hit"不是最终的答案,虽然它出现次数更多,但它在禁用单词列表中。
说明:
1 <= 段落长度 <= 1000.
1 <= 禁用单词个数 <= 100.
1 <= 禁用单词长度 <= 10.
答案是唯一的, 且都是小写字母 (即使在 paragraph 里是大写的,即使是一些特定的名词,答案都是小写的。)
paragraph 只包含字母、空格和下列标点符号!?',;.
不存在没有连字符或者带有连字符的单词。
单词里只包含字母,不会出现省略号或者其他标点符号。
*/
class Solution {
public String mostCommonWord(String paragraph, String[] banned) {
}
}<file_sep>package com.LeetCode.code.q833.BusRoutes;
/**
* @QuestionId : 833
* @difficulty : Hard
* @Title : Bus Routes
* @TranslatedTitle:公交路线
* @url : https://leetcode-cn.com/problems/bus-routes/
* @TranslatedContent:我们有一系列公交路线。每一条路线 routes[i] 上都有一辆公交车在上面循环行驶。例如,有一条路线 routes[0] = [1, 5, 7],表示第一辆 (下标为0) 公交车会一直按照 1->5->7->1->5->7->1->... 的车站路线行驶。
假设我们从 S 车站开始(初始时不在公交车上),要去往 T 站。 期间仅可乘坐公交车,求出最少乘坐的公交车数量。返回 -1 表示不可能到达终点车站。
示例:
输入:
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6
输出: 2
解释:
最优策略是先乘坐第一辆公交车到达车站 7, 然后换乘第二辆公交车到车站 6。
说明:
1 <= routes.length <= 500.
1 <= routes[i].length <= 500.
0 <= routes[i][j] < 10 ^ 6.
*/
class Solution {
public int numBusesToDestination(int[][] routes, int S, int T) {
}
}<file_sep>package com.LeetCode.code.q299.BullsandCows;
/**
* @QuestionId : 299
* @difficulty : Medium
* @Title : Bulls and Cows
* @TranslatedTitle:猜数字游戏
* @url : https://leetcode-cn.com/problems/bulls-and-cows/
* @TranslatedContent:你正在和你的朋友玩 <a href="https://baike.baidu.com/item/%E7%8C%9C%E6%95%B0%E5%AD%97/83200?fromtitle=Bulls+and+Cows&fromid=12003488&fr=aladdin" target="_blank">猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一个提示,告诉他有多少位数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位数字猜对了但是位置不对(称为“Cows”, 奶牛)。你的朋友将会根据提示继续猜,直到猜出秘密数字。
请写出一个根据秘密数字和朋友的猜测数返回提示的函数,用 A 表示公牛,用 B 表示奶牛。
请注意秘密数字和朋友的猜测数都可能含有重复数字。
示例 1:
输入: secret = "1807", guess = "7810"
输出: "1A3B"
解释: 1 公牛和 3 奶牛。公牛是 8,奶牛是 0, 1 和 7。
示例 2:
输入: secret = "1123", guess = "0111"
输出: "1A1B"
解释: 朋友猜测数中的第一个 1 是公牛,第二个或第三个 1 可被视为奶牛。
说明: 你可以假设秘密数字和朋友的猜测数都只包含数字,并且它们的长度永远相等。
*/
class Solution {
public String getHint(String secret, String guess) {
}
}<file_sep>package com.LeetCode.code.q378.KthSmallestElementinaSortedMatrix;
/**
* @QuestionId : 378
* @difficulty : Medium
* @Title : Kth Smallest Element in a Sorted Matrix
* @TranslatedTitle:有序矩阵中第K小的元素
* @url : https://leetcode-cn.com/problems/kth-smallest-element-in-a-sorted-matrix/
* @TranslatedContent:给定一个 n x n 矩阵,其中每行和每列元素均按升序排序,找到矩阵中第k小的元素。<br />
请注意,它是排序后的第k小元素,而不是第k个元素。
示例:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
返回 13。
说明: <br />
你可以假设 k 的值永远是有效的, 1 ≤ k ≤ n2 。
*/
class Solution {
public int kthSmallest(int[][] matrix, int k) {
}
}<file_sep>package com.LeetCode.code.q1217.RelativeSortArray;
/**
* @QuestionId : 1217
* @difficulty : Easy
* @Title : Relative Sort Array
* @TranslatedTitle:数组的相对排序
* @url : https://leetcode-cn.com/problems/relative-sort-array/
* @TranslatedContent:给你两个数组,arr1 和 arr2,
arr2 中的元素各不相同
arr2 中的每个元素都出现在 arr1 中
对 arr1 中的元素进行排序,使 arr1 中项的相对顺序和 arr2 中的相对顺序相同。未在 arr2 中出现过的元素需要按照升序放在 arr1 的末尾。
示例:
输入:arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6]
输出:[2,2,2,1,4,3,3,9,6,7,19]
提示:
arr1.length, arr2.length <= 1000
0 <= arr1[i], arr2[i] <= 1000
arr2 中的元素 arr2[i] 各不相同
arr2 中的每个元素 arr2[i] 都出现在 arr1 中
*/
class Solution {
public int[] relativeSortArray(int[] arr1, int[] arr2) {
}
}<file_sep>package com.LeetCode.code.q541.ReverseStringII;
/**
* @QuestionId : 541
* @difficulty : Easy
* @Title : Reverse String II
* @TranslatedTitle:反转字符串 II
* @url : https://leetcode-cn.com/problems/reverse-string-ii/
* @TranslatedContent:给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。如果剩余少于 k 个字符,则将剩余的所有全部反转。如果有小于 2k 但大于或等于 k 个字符,则反转前 k 个字符,并将剩余的字符保持原样。
示例:
输入: s = "abcdefg", k = 2
输出: "bacdfeg"
要求:
该字符串只包含小写的英文字母。
给定字符串的长度和 k 在[1, 10000]范围内。
*/
class Solution {
public String reverseStr(String s, int k) {
}
}<file_sep>package com.LeetCode.code.q260.SingleNumberIII;
/**
* @QuestionId : 260
* @difficulty : Medium
* @Title : Single Number III
* @TranslatedTitle:只出现一次的数字 III
* @url : https://leetcode-cn.com/problems/single-number-iii/
* @TranslatedContent:给定一个整数数组 nums,其中恰好有两个元素只出现一次,其余所有元素均出现两次。 找出只出现一次的那两个元素。
示例 :
输入: [1,2,1,3,2,5]
输出: [3,5]
注意:
结果输出的顺序并不重要,对于上面的例子, [5, 3] 也是正确答案。
你的算法应该具有线性时间复杂度。你能否仅使用常数空间复杂度来实现?
*/
class Solution {
public int[] singleNumber(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q874.BackspaceStringCompare;
/**
* @QuestionId : 874
* @difficulty : Easy
* @Title : Backspace String Compare
* @TranslatedTitle:比较含退格的字符串
* @url : https://leetcode-cn.com/problems/backspace-string-compare/
* @TranslatedContent:给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果。 # 代表退格字符。
示例 1:
输入:S = "ab#c", T = "ad#c"
输出:true
解释:S 和 T 都会变成 “ac”。
示例 2:
输入:S = "ab##", T = "c#d#"
输出:true
解释:S 和 T 都会变成 “”。
示例 3:
输入:S = "a##c", T = "#a#c"
输出:true
解释:S 和 T 都会变成 “c”。
示例 4:
输入:S = "a#c", T = "b"
输出:false
解释:S 会变成 “c”,但 T 仍然是 “b”。
提示:
1 <= S.length <= 200
1 <= T.length <= 200
S 和 T 只含有小写字母以及字符 '#'。
*/
class Solution {
public boolean backspaceCompare(String S, String T) {
}
}<file_sep>package com.LeetCode.code.q432.AllO`oneDataStructure;
/**
* @QuestionId : 432
* @difficulty : Hard
* @Title : All O`one Data Structure
* @TranslatedTitle:全 O(1) 的数据结构
* @url : https://leetcode-cn.com/problems/all-oone-data-structure/
* @TranslatedContent:实现一个数据结构支持以下操作:
Inc(key) - 插入一个新的值为 1 的 key。或者使一个存在的 key 增加一,保证 key 不为空字符串。
Dec(key) - 如果这个 key 的值是 1,那么把他从数据结构中移除掉。否者使一个存在的 key 值减一。如果这个 key 不存在,这个函数不做任何事情。key 保证不为空字符串。
GetMaxKey() - 返回 key 中值最大的任意一个。如果没有元素存在,返回一个空字符串""。
GetMinKey() - 返回 key 中值最小的任意一个。如果没有元素存在,返回一个空字符串""。
挑战:以 O(1) 的时间复杂度实现所有操作。
*/
class AllOne {
/** Initialize your data structure here. */
public AllOne() {
}
/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
public void inc(String key) {
}
/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
public void dec(String key) {
}
/** Returns one of the keys with maximal value. */
public String getMaxKey() {
}
/** Returns one of the keys with Minimal value. */
public String getMinKey() {
}
}
/**
* Your AllOne object will be instantiated and called as such:
* AllOne obj = new AllOne();
* obj.inc(key);
* obj.dec(key);
* String param_3 = obj.getMaxKey();
* String param_4 = obj.getMinKey();
*/<file_sep>/**
* Copyright 2019 bejson.com
*/
package com.LeetCode.spider;
/**
* Auto-generated: 2019-09-23 16:42:16
*
* @author bejson.com (<EMAIL>)
* @website http://www.bejson.com/java2pojo/
*/
public class Stat {
private int question_id;
private String question__title;
private String question__title_slug;
private boolean question__hide;
private int total_acs;
private int total_submitted;
private int total_column_articles;
private int frontend_question_id;
private boolean is_new_question;
private String title;
private String __typename;
public void setQuestion_id(int question_id) {
this.question_id = question_id;
}
public int getQuestion_id() {
return question_id;
}
public void setQuestion__title(String question__title) {
this.question__title = question__title;
}
public String getQuestion__title() {
return question__title;
}
public void setQuestion__title_slug(String question__title_slug) {
this.question__title_slug = question__title_slug;
}
public String getQuestion__title_slug() {
return question__title_slug;
}
public void setQuestion__hide(boolean question__hide) {
this.question__hide = question__hide;
}
public boolean getQuestion__hide() {
return question__hide;
}
public void setTotal_acs(int total_acs) {
this.total_acs = total_acs;
}
public int getTotal_acs() {
return total_acs;
}
public void setTotal_submitted(int total_submitted) {
this.total_submitted = total_submitted;
}
public int getTotal_submitted() {
return total_submitted;
}
public void setTotal_column_articles(int total_column_articles) {
this.total_column_articles = total_column_articles;
}
public int getTotal_column_articles() {
return total_column_articles;
}
public void setFrontend_question_id(int frontend_question_id) {
this.frontend_question_id = frontend_question_id;
}
public int getFrontend_question_id() {
return frontend_question_id;
}
public void setIs_new_question(boolean is_new_question) {
this.is_new_question = is_new_question;
}
public boolean getIs_new_question() {
return is_new_question;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String get__typename() {
return __typename;
}
public void set__typename(String __typename) {
this.__typename = __typename;
}
}<file_sep>package com.LeetCode.code.q1137.HeightChecker;
/**
* @QuestionId : 1137
* @difficulty : Easy
* @Title : Height Checker
* @TranslatedTitle:高度检查器
* @url : https://leetcode-cn.com/problems/height-checker/
* @TranslatedContent:学校在拍年度纪念照时,一般要求学生按照 非递减 的高度顺序排列。
请你返回至少有多少个学生没有站在正确位置数量。该人数指的是:能让所有学生以 非递减 高度排列的必要移动人数。
示例:
输入:[1,1,4,2,1,3]
输出:3
解释:
高度为 4、3 和最后一个 1 的学生,没有站在正确的位置。
提示:
1 <= heights.length <= 100
1 <= heights[i] <= 100
*/
class Solution {
public int heightChecker(int[] heights) {
}
}<file_sep>package com.LeetCode.code.q59.SpiralMatrixII;
/**
* @QuestionId : 59
* @difficulty : Medium
* @Title : Spiral Matrix II
* @TranslatedTitle:螺旋矩阵 II
* @url : https://leetcode-cn.com/problems/spiral-matrix-ii/
* @TranslatedContent:给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
*/
class Solution {
public int[][] generateMatrix(int n) {
}
}<file_sep>package com.LeetCode.code.q405.ConvertaNumbertoHexadecimal;
/**
* @QuestionId : 405
* @difficulty : Easy
* @Title : Convert a Number to Hexadecimal
* @TranslatedTitle:数字转换为十六进制数
* @url : https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal/
* @TranslatedContent:给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 <a href="https://baike.baidu.com/item/%E8%A1%A5%E7%A0%81/6854613?fr=aladdin">补码运算 方法。
注意:
十六进制中所有字母(a-f)都必须是小写。
十六进制字符串中不能包含多余的前导零。如果要转化的数为0,那么以单个字符'0'来表示;对于其他情况,十六进制字符串中的第一个字符将不会是0字符。
给定的数确保在32位有符号整数范围内。
不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。
示例 1:
输入:
26
输出:
"1a"
示例 2:
输入:
-1
输出:
"ffffffff"
*/
class Solution {
public String toHex(int num) {
}
}<file_sep>package com.LeetCode.code.q592.FractionAdditionandSubtraction;
/**
* @QuestionId : 592
* @difficulty : Medium
* @Title : Fraction Addition and Subtraction
* @TranslatedTitle:分数加减运算
* @url : https://leetcode-cn.com/problems/fraction-addition-and-subtraction/
* @TranslatedContent:给定一个表示分数加减运算表达式的字符串,你需要返回一个字符串形式的计算结果。 这个结果应该是不可约分的分数,即<a href="https://baike.baidu.com/item/%E6%9C%80%E7%AE%80%E5%88%86%E6%95%B0" target="_blank">最简分数。 如果最终结果是一个整数,例如 2,你需要将它转换成分数形式,其分母为 1。所以在上述例子中, 2 应该被转换为 2/1。
示例 1:
输入:"-1/2+1/2"
输出: "0/1"
示例 2:
输入:"-1/2+1/2+1/3"
输出: "1/3"
示例 3:
输入:"1/3-1/2"
输出: "-1/6"
示例 4:
输入:"5/3+1/3"
输出: "2/1"
说明:
输入和输出字符串只包含 '0' 到 '9' 的数字,以及 '/', '+' 和 '-'。
输入和输出分数格式均为 ±分子/分母。如果输入的第一个分数或者输出的分数是正数,则 '+' 会被省略掉。
输入只包含合法的最简分数,每个分数的分子与分母的范围是 [1,10]。 如果分母是1,意味着这个分数实际上是一个整数。
输入的分数个数范围是 [1,10]。
最终结果的分子与分母保证是 32 位整数范围内的有效整数。
*/
class Solution {
public String fractionAddition(String expression) {
}
}<file_sep>package com.LeetCode.code.q212.WordSearchII;
/**
* @QuestionId : 212
* @difficulty : Hard
* @Title : Word Search II
* @TranslatedTitle:单词搜索 II
* @url : https://leetcode-cn.com/problems/word-search-ii/
* @TranslatedContent:给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例:
输入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
输出: ["eat","oath"]
说明:
你可以假设所有输入都由小写字母 a-z 组成。
提示:
你需要优化回溯算法以通过更大数据量的测试。你能否早点停止回溯?
如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯。什么样的数据结构可以有效地执行这样的操作?散列表是否可行?为什么? 前缀树如何?如果你想学习如何实现一个基本的前缀树,请先查看这个问题: <a href="/problems/implement-trie-prefix-tree/description/">实现Trie(前缀树)。
*/
class Solution {
public List<String> findWords(char[][] board, String[] words) {
}
}<file_sep>package com.LeetCode.code.q506.RelativeRanks;
/**
* @QuestionId : 506
* @difficulty : Easy
* @Title : Relative Ranks
* @TranslatedTitle:相对名次
* @url : https://leetcode-cn.com/problems/relative-ranks/
* @TranslatedContent:给出 N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。前三名运动员将会被分别授予 “金牌”,“银牌” 和“ 铜牌”("Gold Medal", "Silver Medal", "Bronze Medal")。
(注:分数越高的选手,排名越靠前。)
示例 1:
输入: [5, 4, 3, 2, 1]
输出: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
解释: 前三名运动员的成绩为前三高的,因此将会分别被授予 “金牌”,“银牌”和“铜牌” ("Gold Medal", "Silver Medal" and "Bronze Medal").
余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。
提示:
N 是一个正整数并且不会超过 10000。
所有运动员的成绩都不相同。
*/
class Solution {
public String[] findRelativeRanks(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q875.LongestMountaininArray;
/**
* @QuestionId : 875
* @difficulty : Medium
* @Title : Longest Mountain in Array
* @TranslatedTitle:数组中的最长山脉
* @url : https://leetcode-cn.com/problems/longest-mountain-in-array/
* @TranslatedContent:我们把数组 A 中符合下列属性的任意连续子数组 B 称为 “山脉”:
B.length >= 3
存在 0 < i < B.length - 1 使得 B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
(注意:B 可以是 A 的任意子数组,包括整个数组 A。)
给出一个整数数组 A,返回最长 “山脉” 的长度。
如果不含有 “山脉” 则返回 0。
示例 1:
输入:[2,1,4,7,3,2,5]
输出:5
解释:最长的 “山脉” 是 [1,4,7,3,2],长度为 5。
示例 2:
输入:[2,2,2]
输出:0
解释:不含 “山脉”。
提示:
0 <= A.length <= 10000
0 <= A[i] <= 10000
*/
class Solution {
public int longestMountain(int[] A) {
}
}<file_sep>package com.LeetCode.code.q790.GlobalandLocalInversions;
/**
* @QuestionId : 790
* @difficulty : Medium
* @Title : Global and Local Inversions
* @TranslatedTitle:全局倒置与局部倒置
* @url : https://leetcode-cn.com/problems/global-and-local-inversions/
* @TranslatedContent:数组 A 是 [0, 1, ..., N - 1] 的一种排列,N 是数组 A 的长度。全局倒置指的是 i,j 满足 0 <= i < j < N 并且 A[i] > A[j] ,局部倒置指的是 i 满足 0 <= i < N 并且 A[i] > A[i+1] 。
当数组 A 中全局倒置的数量等于局部倒置的数量时,返回 true 。
示例 1:
输入: A = [1,0,2]
输出: true
解释: 有 1 个全局倒置,和 1 个局部倒置。
示例 2:
输入: A = [1,2,0]
输出: false
解释: 有 2 个全局倒置,和 1 个局部倒置。
注意:
A 是 [0, 1, ..., A.length - 1] 的一种排列
A 的长度在 [1, 5000]之间
这个问题的时间限制已经减少了。
*/
class Solution {
public boolean isIdealPermutation(int[] A) {
}
}<file_sep>package com.LeetCode.code.q739.DailyTemperatures;
/**
* @QuestionId : 739
* @difficulty : Medium
* @Title : Daily Temperatures
* @TranslatedTitle:每日温度
* @url : https://leetcode-cn.com/problems/daily-temperatures/
* @TranslatedContent:根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
*/
class Solution {
public int[] dailyTemperatures(int[] T) {
}
}<file_sep>package com.LeetCode.code.q102.BinaryTreeLevelOrderTraversal;
/**
* @QuestionId : 102
* @difficulty : Medium
* @Title : Binary Tree Level Order Traversal
* @TranslatedTitle:二叉树的层次遍历
* @url : https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
* @TranslatedContent:给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q904.Leaf-SimilarTrees;
/**
* @QuestionId : 904
* @difficulty : Easy
* @Title : Leaf-Similar Trees
* @TranslatedTitle:叶子相似的树
* @url : https://leetcode-cn.com/problems/leaf-similar-trees/
* @TranslatedContent:请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png" style="height: 240px; width: 300px;">
举个例子,如上图所示,给定一颗叶值序列为 (6, 7, 4, 9, 8) 的树。
如果有两颗二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。
如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false 。
提示:
给定的两颗树可能会有 1 到 100 个结点。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
}
}<file_sep>package com.LeetCode.code.q1012.EqualRationalNumbers;
/**
* @QuestionId : 1012
* @difficulty : Hard
* @Title : Equal Rational Numbers
* @TranslatedTitle:相等的有理数
* @url : https://leetcode-cn.com/problems/equal-rational-numbers/
* @TranslatedContent:给定两个字符串 S 和 T,每个字符串代表一个非负有理数,只有当它们表示相同的数字时才返回 true;否则,返回 false。字符串中可以使用括号来表示有理数的重复部分。
通常,有理数最多可以用三个部分来表示:整数部分 、小数非重复部分 和小数重复部分 <(><)>。数字可以用以下三种方法之一来表示:
(例:0,12,123)
<.> (例:0.5,2.12,2.0001)
<.><(><)>(例:0.1(6),0.9(9),0.00(1212))
十进制展开的重复部分通常在一对圆括号内表示。例如:
1 / 6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)
0.1(6) 或 0.1666(6) 或 0.166(66) 都是 1 / 6 的正确表示形式。
示例 1:
输入:S = "0.(52)", T = "0.5(25)"
输出:true
解释:因为 "0.(52)" 代表 0.52525252...,而 "0.5(25)" 代表 0.52525252525.....,则这两个字符串表示相同的数字。
示例 2:
输入:S = "0.1666(6)", T = "0.166(66)"
输出:true
示例 3:
输入:S = "0.9(9)", T = "1."
输出:true
解释:
"0.9(9)" 代表 0.999999999... 永远重复,等于 1 。[<a href="https://baike.baidu.com/item/0.999…/5615429?fr=aladdin" target="_blank">有关说明,请参阅此链接]
"1." 表示数字 1,其格式正确:(IntegerPart) = "1" 且 (NonRepeatingPart) = "" 。
提示:
每个部分仅由数字组成。
整数部分 不会以 2 个或更多的零开头。(对每个部分的数字没有其他限制)。
1 <= .length <= 4
0 <= .length <= 4
1 <= .length <= 4
*/
class Solution {
public boolean isRationalEqual(String S, String T) {
}
}<file_sep>package com.LeetCode.code.q692.TopKFrequentWords;
/**
* @QuestionId : 692
* @difficulty : Medium
* @Title : Top K Frequent Words
* @TranslatedTitle:前K个高频单词
* @url : https://leetcode-cn.com/problems/top-k-frequent-words/
* @TranslatedContent:给一非空的单词列表,返回前 k 个出现次数最多的单词。
返回的答案应该按单词出现频率由高到低排序。如果不同的单词有相同出现频率,按字母顺序排序。
示例 1:
输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
输出: ["i", "love"]
解析: "i" 和 "love" 为出现次数最多的两个单词,均为2次。
注意,按字母顺序 "i" 在 "love" 之前。
示例 2:
输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
输出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词,
出现次数依次为 4, 3, 2 和 1 次。
注意:
假定 k 总为有效值, 1 ≤ k ≤ 集合元素数。
输入的单词均由小写字母组成。
扩展练习:
尝试以 O(n log k) 时间复杂度和 O(n) 空间复杂度解决。
*/
class Solution {
public List<String> topKFrequent(String[] words, int k) {
}
}<file_sep>package com.LeetCode.code.q529.Minesweeper;
/**
* @QuestionId : 529
* @difficulty : Medium
* @Title : Minesweeper
* @TranslatedTitle:扫雷游戏
* @url : https://leetcode-cn.com/problems/minesweeper/
* @TranslatedContent:让我们一起来玩扫雷游戏!
给定一个代表游戏板的二维字符矩阵。 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字('1' 到 '8')表示有多少地雷与这块已挖出的方块相邻,'X' 则表示一个已挖出的地雷。
现在给出在所有未挖出的方块中('M'或者'E')的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:
如果一个地雷('M')被挖出,游戏就结束了- 把它改为 'X'。
如果一个没有相邻地雷的空方块('E')被挖出,修改它为('B'),并且所有和其相邻的方块都应该被递归地揭露。
如果一个至少与一个地雷相邻的空方块('E')被挖出,修改它为数字('1'到'8'),表示相邻地雷的数量。
如果在此次点击中,若无更多方块可被揭露,则返回面板。
示例 1:
输入:
[['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'M', 'E', 'E'],
['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E']]
Click : [3,0]
输出:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
解释:
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/minesweeper_example_1.png" style="width: 100%; max-width: 400px">
示例 2:
输入:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'M', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
Click : [1,2]
输出:
[['B', '1', 'E', '1', 'B'],
['B', '1', 'X', '1', 'B'],
['B', '1', '1', '1', 'B'],
['B', 'B', 'B', 'B', 'B']]
解释:
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/minesweeper_example_2.png" style="width: 100%; max-width: 400px">
注意:
输入矩阵的宽和高的范围为 [1,50]。
点击的位置只能是未被挖出的方块 ('M' 或者 'E'),这也意味着面板至少包含一个可点击的方块。
输入面板不会是游戏结束的状态(即有地雷已被挖出)。
简单起见,未提及的规则在这个问题中可被忽略。例如,当游戏结束时你不需要挖出所有地雷,考虑所有你可能赢得游戏或标记方块的情况。
*/
class Solution {
public char[][] updateBoard(char[][] board, int[] click) {
}
}<file_sep>package com.LeetCode.code.q923.SuperEggDrop;
/**
* @QuestionId : 923
* @difficulty : Hard
* @Title : Super Egg Drop
* @TranslatedTitle:鸡蛋掉落
* @url : https://leetcode-cn.com/problems/super-egg-drop/
* @TranslatedContent:你将获得 K 个鸡蛋,并可以使用一栋从 1 到 N 共有 N 层楼的建筑。
每个蛋的功能都是一样的,如果一个蛋碎了,你就不能再把它掉下去。
你知道存在楼层 F ,满足 0 <= F <= N 任何从高于 F 的楼层落下的鸡蛋都会碎,从 F 楼层或比它低的楼层落下的鸡蛋都不会破。
每次移动,你可以取一个鸡蛋(如果你有完整的鸡蛋)并把它从任一楼层 X 扔下(满足 1 <= X <= N)。
你的目标是确切地知道 F 的值是多少。
无论 F 的初始值如何,你确定 F 的值的最小移动次数是多少?
示例 1:
输入:K = 1, N = 2
输出:2
解释:
鸡蛋从 1 楼掉落。如果它碎了,我们肯定知道 F = 0 。
否则,鸡蛋从 2 楼掉落。如果它碎了,我们肯定知道 F = 1 。
如果它没碎,那么我们肯定知道 F = 2 。
因此,在最坏的情况下我们需要移动 2 次以确定 F 是多少。
示例 2:
输入:K = 2, N = 6
输出:3
示例 3:
输入:K = 3, N = 14
输出:4
提示:
1 <= K <= 100
1 <= N <= 10000
*/
class Solution {
public int superEggDrop(int K, int N) {
}
}<file_sep>package com.LeetCode.code.q605.CanPlaceFlowers;
/**
* @QuestionId : 605
* @difficulty : Easy
* @Title : Can Place Flowers
* @TranslatedTitle:种花问题
* @url : https://leetcode-cn.com/problems/can-place-flowers/
* @TranslatedContent:假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。
示例 1:
输入: flowerbed = [1,0,0,0,1], n = 1
输出: True
示例 2:
输入: flowerbed = [1,0,0,0,1], n = 2
输出: False
注意:
数组内已种好的花不会违反种植规则。
输入的数组长度范围为 [1, 20000]。
n 是非负整数,且不会超过输入数组的大小。
*/
class Solution {
public boolean canPlaceFlowers(int[] flowerbed, int n) {
}
}<file_sep>package com.LeetCode.code.q1219.LongestWell-PerformingInterval;
/**
* @QuestionId : 1219
* @difficulty : Medium
* @Title : Longest Well-Performing Interval
* @TranslatedTitle:表现良好的最长时间段
* @url : https://leetcode-cn.com/problems/longest-well-performing-interval/
* @TranslatedContent:给你一份工作时间表 hours,上面记录着某一位员工每天的工作小时数。
我们认为当员工一天中的工作小时数大于 8 小时的时候,那么这一天就是「劳累的一天」。
所谓「表现良好的时间段」,意味在这段时间内,「劳累的天数」是严格 大于「不劳累的天数」。
请你返回「表现良好时间段」的最大长度。
示例 1:
输入:hours = [9,9,6,0,6,6,9]
输出:3
解释:最长的表现良好时间段是 [9,9,6]。
提示:
1 <= hours.length <= 10000
0 <= hours[i] <= 16
*/
class Solution {
public int longestWPI(int[] hours) {
}
}<file_sep>package com.LeetCode.code.q719.FindK-thSmallestPairDistance;
/**
* @QuestionId : 719
* @difficulty : Hard
* @Title : Find K-th Smallest Pair Distance
* @TranslatedTitle:找出第 k 小的距离对
* @url : https://leetcode-cn.com/problems/find-k-th-smallest-pair-distance/
* @TranslatedContent:给定一个整数数组,返回所有数对之间的第 k 个最小距离。一对 (A, B) 的距离被定义为 A 和 B 之间的绝对差值。
示例 1:
输入:
nums = [1,3,1]
k = 1
输出:0
解释:
所有数对如下:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
因此第 1 个最小距离的数对是 (1,1),它们之间的距离为 0。
提示:
2 <= len(nums) <= 10000.
0 <= nums[i] < 1000000.
1 <= k <= len(nums) * (len(nums) - 1) / 2.
*/
class Solution {
public int smallestDistancePair(int[] nums, int k) {
}
}<file_sep>package com.LeetCode.code.q412.FizzBuzz;
/**
* @QuestionId : 412
* @difficulty : Easy
* @Title : Fizz Buzz
* @TranslatedTitle:Fizz Buzz
* @url : https://leetcode-cn.com/problems/fizz-buzz/
* @TranslatedContent:写一个程序,输出从 1 到 n 数字的字符串表示。
1. 如果 n 是3的倍数,输出“Fizz”;
2. 如果 n 是5的倍数,输出“Buzz”;
3.如果 n 同时是3和5的倍数,输出 “FizzBuzz”。
示例:
n = 15,
返回:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
*/
class Solution {
public List<String> fizzBuzz(int n) {
}
}<file_sep>package com.LeetCode.code.q300.LongestIncreasingSubsequence;
/**
* @QuestionId : 300
* @difficulty : Medium
* @Title : Longest Increasing Subsequence
* @TranslatedTitle:最长上升子序列
* @url : https://leetcode-cn.com/problems/longest-increasing-subsequence/
* @TranslatedContent:给定一个无序的整数数组,找到其中最长上升子序列的长度。
示例:
输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
说明:
可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
你算法的时间复杂度应该为 O(n2) 。
进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?
*/
class Solution {
public int lengthOfLIS(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q991.ArrayofDoubledPairs;
/**
* @QuestionId : 991
* @difficulty : Medium
* @Title : Array of Doubled Pairs
* @TranslatedTitle:二倍数对数组
* @url : https://leetcode-cn.com/problems/array-of-doubled-pairs/
* @TranslatedContent:给定一个长度为偶数的整数数组 A,只有对 A 进行重组后可以满足 “对于每个 0 <= i < len(A) / 2,都有 A[2 * i + 1] = 2 * A[2 * i]” 时,返回 true;否则,返回 false。
示例 1:
输入:[3,1,3,6]
输出:false
示例 2:
输入:[2,1,2,6]
输出:false
示例 3:
输入:[4,-2,2,-4]
输出:true
解释:我们可以用 [-2,-4] 和 [2,4] 这两组组成 [-2,-4,2,4] 或是 [2,4,-2,-4]
示例 4:
输入:[1,2,4,16,8,4]
输出:false
提示:
0 <= A.length <= 30000
A.length 为偶数
-100000 <= A[i] <= 100000
*/
class Solution {
public boolean canReorderDoubled(int[] A) {
}
}<file_sep>package com.LeetCode.code.q130.SurroundedRegions;
/**
* @QuestionId : 130
* @difficulty : Medium
* @Title : Surrounded Regions
* @TranslatedTitle:被围绕的区域
* @url : https://leetcode-cn.com/problems/surrounded-regions/
* @TranslatedContent:给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。
找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。
示例:
X X X X
X O O X
X X O X
X O X X
运行你的函数后,矩阵变为:
X X X X
X X X X
X X X X
X O X X
解释:
被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
*/
class Solution {
public void solve(char[][] board) {
}
}<file_sep>package com.LeetCode.code.q313.SuperUglyNumber;
/**
* @QuestionId : 313
* @difficulty : Medium
* @Title : Super Ugly Number
* @TranslatedTitle:超级丑数
* @url : https://leetcode-cn.com/problems/super-ugly-number/
* @TranslatedContent:编写一段程序来查找第 n 个超级丑数。
超级丑数是指其所有质因数都是长度为 k 的质数列表 primes 中的正整数。
示例:
输入: n = 12, primes = [2,7,13,19]
输出: 32
解释: 给定长度为 4 的质数列表 primes = [2,7,13,19],前 12 个超级丑数序列为:[1,2,4,7,8,13,14,16,19,26,28,32] 。
说明:
1 是任何给定 primes 的超级丑数。
给定 primes 中的数字以升序排列。
0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000 。
第 n 个超级丑数确保在 32 位有符整数范围内。
*/
class Solution {
public int nthSuperUglyNumber(int n, int[] primes) {
}
}<file_sep>package com.LeetCode.code.q82.RemoveDuplicatesfromSortedListII;
/**
* @QuestionId : 82
* @difficulty : Medium
* @Title : Remove Duplicates from Sorted List II
* @TranslatedTitle:删除排序链表中的重复元素 II
* @url : https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
* @TranslatedContent:给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
输入: 1->1->1->2->3
输出: 2->3
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
}
}<file_sep>package com.LeetCode.code.q1238.AlphabetBoardPath;
/**
* @QuestionId : 1238
* @difficulty : Medium
* @Title : Alphabet Board Path
* @TranslatedTitle:字母板上的路径
* @url : https://leetcode-cn.com/problems/alphabet-board-path/
* @TranslatedContent:我们从一块字母板上的位置 (0, 0) 出发,该坐标对应的字符为 board[0][0]。
在本题里,字母板为board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"].
我们可以按下面的指令规则行动:
如果方格存在,'U' 意味着将我们的位置上移一行;
如果方格存在,'D' 意味着将我们的位置下移一行;
如果方格存在,'L' 意味着将我们的位置左移一列;
如果方格存在,'R' 意味着将我们的位置右移一列;
'!' 会把在我们当前位置 (r, c) 的字符 board[r][c] 添加到答案中。
返回指令序列,用最小的行动次数让答案和目标 target 相同。你可以返回任何达成目标的路径。
示例 1:
输入:target = "leet"
输出:"DDR!UURRR!!DDD!"
示例 2:
输入:target = "code"
输出:"RR!DDRR!UUL!R!"
提示:
1 <= target.length <= 100
target 仅含有小写英文字母。
*/
class Solution {
public String alphabetBoardPath(String target) {
}
}<file_sep>package com.LeetCode.code.q131.PalindromePartitioning;
/**
* @QuestionId : 131
* @difficulty : Medium
* @Title : Palindrome Partitioning
* @TranslatedTitle:分割回文串
* @url : https://leetcode-cn.com/problems/palindrome-partitioning/
* @TranslatedContent:给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。
示例:
输入: "aab"
输出:
[
["aa","b"],
["a","a","b"]
]
*/
class Solution {
public List<List<String>> partition(String s) {
}
}<file_sep>package com.LeetCode.code.q415.AddStrings;
/**
* @QuestionId : 415
* @difficulty : Easy
* @Title : Add Strings
* @TranslatedTitle:字符串相加
* @url : https://leetcode-cn.com/problems/add-strings/
* @TranslatedContent:给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。
注意:
num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。
*/
class Solution {
public String addStrings(String num1, String num2) {
}
}<file_sep>package com.LeetCode.code.q420.StrongPasswordChecker;
/**
* @QuestionId : 420
* @difficulty : Hard
* @Title : Strong Password Checker
* @TranslatedTitle:强密码检验器
* @url : https://leetcode-cn.com/problems/strong-password-checker/
* @TranslatedContent:一个强密码应满足以下所有条件:
由至少6个,至多20个字符组成。
至少包含一个小写字母,一个大写字母,和一个数字。
同一字符不能连续出现三次 (比如 "...aaa..." 是不允许的, 但是 "...aa...a..." 是可以的)。
编写函数 strongPasswordChecker(s),s 代表输入字符串,如果 s 已经符合强密码条件,则返回0;否则返回要将 s 修改为满足强密码条件的字符串所需要进行修改的最小步数。
插入、删除、替换任一字符都算作一次修改。
*/
class Solution {
public int strongPasswordChecker(String s) {
}
}<file_sep>package com.LeetCode.code.q958.SortArrayByParityII;
/**
* @QuestionId : 958
* @difficulty : Easy
* @Title : Sort Array By Parity II
* @TranslatedTitle:按奇偶排序数组 II
* @url : https://leetcode-cn.com/problems/sort-array-by-parity-ii/
* @TranslatedContent:给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
示例:
输入:[4,2,5,7]
输出:[4,5,2,7]
解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
提示:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
*/
class Solution {
public int[] sortArrayByParityII(int[] A) {
}
}<file_sep>package com.LeetCode.code.q494.TargetSum;
/**
* @QuestionId : 494
* @difficulty : Medium
* @Title : Target Sum
* @TranslatedTitle:目标和
* @url : https://leetcode-cn.com/problems/target-sum/
* @TranslatedContent:给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。
返回可以使最终数组和为目标数 S 的所有添加符号的方法数。
示例 1:
输入: nums: [1, 1, 1, 1, 1], S: 3
输出: 5
解释:
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
一共有5种方法让最终目标和为3。
注意:
数组非空,且长度不会超过20。
初始的数组的和不会超过1000。
保证返回的最终结果能被32位整数存下。
*/
class Solution {
public int findTargetSumWays(int[] nums, int S) {
}
}<file_sep>package com.LeetCode.code.q399.EvaluateDivision;
/**
* @QuestionId : 399
* @difficulty : Medium
* @Title : Evaluate Division
* @TranslatedTitle:除法求值
* @url : https://leetcode-cn.com/problems/evaluate-division/
* @TranslatedContent:给出方程式 A / B = k, 其中 A 和 B 均为代表字符串的变量, k 是一个浮点型数字。根据已知方程式求解问题,并返回计算结果。如果结果不存在,则返回 -1.0。
示例 :<br />
给定 a / b = 2.0, b / c = 3.0<br />
问题: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? <br />
返回 [6.0, 0.5, -1.0, 1.0, -1.0 ]
输入为: vector<pair<string, string>> equations, vector& values, vector<pair<string, string>> queries(方程式,方程式结果,问题方程式), 其中 equations.size() == values.size(),即方程式的长度与方程式结果长度相等(程式与结果一一对应),并且结果值均为正数。以上为方程式的描述。 返回vector类型。
基于上述例子,输入如下:
equations(方程式) = [ ["a", "b"], ["b", "c"] ],
values(方程式结果) = [2.0, 3.0],
queries(问题方程式) = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
输入总是有效的。你可以假设除法运算中不会出现除数为0的情况,且不存在任何矛盾的结果。
*/
class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
}
}<file_sep>package com.LeetCode.code.q674.LongestContinuousIncreasingSubsequence;
/**
* @QuestionId : 674
* @difficulty : Easy
* @Title : Longest Continuous Increasing Subsequence
* @TranslatedTitle:最长连续递增序列
* @url : https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence/
* @TranslatedContent:给定一个未经排序的整数数组,找到最长且连续的的递增序列。
示例 1:
输入: [1,3,5,4,7]
输出: 3
解释: 最长连续递增序列是 [1,3,5], 长度为3。
尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。
示例 2:
输入: [2,2,2,2,2]
输出: 1
解释: 最长连续递增序列是 [2], 长度为1。
注意:数组长度不会超过10000。
*/
class Solution {
public int findLengthOfLCIS(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q37.SudokuSolver;
/**
* @QuestionId : 37
* @difficulty : Hard
* @Title : Sudoku Solver
* @TranslatedTitle:解数独
* @url : https://leetcode-cn.com/problems/sudoku-solver/
* @TranslatedContent:编写一个程序,通过已填充的空格来解决数独问题。
一个数独的解法需遵循如下规则:
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
空白格用 '.' 表示。
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png">
一个数独。
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png">
答案被标成红色。
Note:
给定的数独序列只包含数字 1-9 和字符 '.' 。
你可以假设给定的数独只有唯一解。
给定数独永远是 9x9 形式的。
*/
class Solution {
public void solveSudoku(char[][] board) {
}
}<file_sep>package com.LeetCode.code.q483.SmallestGoodBase;
/**
* @QuestionId : 483
* @difficulty : Hard
* @Title : Smallest Good Base
* @TranslatedTitle:最小好进制
* @url : https://leetcode-cn.com/problems/smallest-good-base/
* @TranslatedContent:对于给定的整数 n, 如果n的k(k>=2)进制数的所有数位全为1,则称 k(k>=2)是 n 的一个好进制。
以字符串的形式给出 n, 以字符串的形式返回 n 的最小好进制。
示例 1:
输入:"13"
输出:"3"
解释:13 的 3 进制是 111。
示例 2:
输入:"4681"
输出:"8"
解释:4681 的 8 进制是 11111。
示例 3:
输入:"1000000000000000000"
输出:"999999999999999999"
解释:1000000000000000000 的 999999999999999999 进制是 11。
提示:
n的取值范围是 [3, 10^18]。
输入总是有效且没有前导 0。
*/
class Solution {
public String smallestGoodBase(String n) {
}
}<file_sep>package com.LeetCode.code.q349.IntersectionofTwoArrays;
/**
* @QuestionId : 349
* @difficulty : Easy
* @Title : Intersection of Two Arrays
* @TranslatedTitle:两个数组的交集
* @url : https://leetcode-cn.com/problems/intersection-of-two-arrays/
* @TranslatedContent:给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
*/
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
}
}<file_sep>package com.LeetCode.spider.detail;
import java.util.ArrayList;
import java.util.List;
public class Question
{
private String questionId;
private String questionFrontendId;
private int boundTopicId;
private String title;
private String titleSlug;
private String content;
private String translatedTitle;
private String translatedContent;
private boolean isPaidOnly;
private String difficulty;
private int likes;
private int dislikes;
private String isLiked;
private String similarQuestions;
private List<String> contributors;
private String langToValidPlayground;
private List<TopicTags> topicTags;
private String companyTagStats;
private List<CodeSnippets> codeSnippets;
private String stats;
private List<String> hints;
private Solution solution;
private String status;
private String sampleTestCase;
private String metaData;
private boolean judgerAvailable;
private String judgeType;
private List<String> mysqlSchemas;
private boolean enableRunCode;
private boolean enableTestMode;
private String envInfo;
private String __typename;
public void setQuestionId(String questionId){
this.questionId = questionId;
}
public String getQuestionId(){
return this.questionId;
}
public void setQuestionFrontendId(String questionFrontendId){
this.questionFrontendId = questionFrontendId;
}
public String getQuestionFrontendId(){
return this.questionFrontendId;
}
public void setBoundTopicId(int boundTopicId){
this.boundTopicId = boundTopicId;
}
public int getBoundTopicId(){
return this.boundTopicId;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public void setTitleSlug(String titleSlug){
this.titleSlug = titleSlug;
}
public String getTitleSlug(){
return this.titleSlug;
}
public void setContent(String content){
this.content = content;
}
public String getContent(){
return this.content;
}
public void setTranslatedTitle(String translatedTitle){
this.translatedTitle = translatedTitle;
}
public String getTranslatedTitle(){
return this.translatedTitle;
}
public void setTranslatedContent(String translatedContent){
this.translatedContent = translatedContent;
}
public String getTranslatedContent(){
return this.translatedContent;
}
public void setIsPaidOnly(boolean isPaidOnly){
this.isPaidOnly = isPaidOnly;
}
public boolean getIsPaidOnly(){
return this.isPaidOnly;
}
public void setDifficulty(String difficulty){
this.difficulty = difficulty;
}
public String getDifficulty(){
return this.difficulty;
}
public void setLikes(int likes){
this.likes = likes;
}
public int getLikes(){
return this.likes;
}
public void setDislikes(int dislikes){
this.dislikes = dislikes;
}
public int getDislikes(){
return this.dislikes;
}
public void setIsLiked(String isLiked){
this.isLiked = isLiked;
}
public String getIsLiked(){
return this.isLiked;
}
public void setSimilarQuestions(String similarQuestions){
this.similarQuestions = similarQuestions;
}
public String getSimilarQuestions(){
return this.similarQuestions;
}
public void setContributors(List<String> contributors){
this.contributors = contributors;
}
public List<String> getContributors(){
return this.contributors;
}
public void setLangToValidPlayground(String langToValidPlayground){
this.langToValidPlayground = langToValidPlayground;
}
public String getLangToValidPlayground(){
return this.langToValidPlayground;
}
public void setTopicTags(List<TopicTags> topicTags){
this.topicTags = topicTags;
}
public List<TopicTags> getTopicTags(){
return this.topicTags;
}
public void setCompanyTagStats(String companyTagStats){
this.companyTagStats = companyTagStats;
}
public String getCompanyTagStats(){
return this.companyTagStats;
}
public void setCodeSnippets(List<CodeSnippets> codeSnippets){
this.codeSnippets = codeSnippets;
}
public List<CodeSnippets> getCodeSnippets(){
return this.codeSnippets;
}
public void setStats(String stats){
this.stats = stats;
}
public String getStats(){
return this.stats;
}
public void setHints(List<String> hints){
this.hints = hints;
}
public List<String> getHints(){
return this.hints;
}
public void setSolution(Solution solution){
this.solution = solution;
}
public Solution getSolution(){
return this.solution;
}
public void setStatus(String status){
this.status = status;
}
public String getStatus(){
return this.status;
}
public void setSampleTestCase(String sampleTestCase){
this.sampleTestCase = sampleTestCase;
}
public String getSampleTestCase(){
return this.sampleTestCase;
}
public void setMetaData(String metaData){
this.metaData = metaData;
}
public String getMetaData(){
return this.metaData;
}
public void setJudgerAvailable(boolean judgerAvailable){
this.judgerAvailable = judgerAvailable;
}
public boolean getJudgerAvailable(){
return this.judgerAvailable;
}
public void setJudgeType(String judgeType){
this.judgeType = judgeType;
}
public String getJudgeType(){
return this.judgeType;
}
public void setMysqlSchemas(List<String> mysqlSchemas){
this.mysqlSchemas = mysqlSchemas;
}
public List<String> getMysqlSchemas(){
return this.mysqlSchemas;
}
public void setEnableRunCode(boolean enableRunCode){
this.enableRunCode = enableRunCode;
}
public boolean getEnableRunCode(){
return this.enableRunCode;
}
public void setEnableTestMode(boolean enableTestMode){
this.enableTestMode = enableTestMode;
}
public boolean getEnableTestMode(){
return this.enableTestMode;
}
public void setEnvInfo(String envInfo){
this.envInfo = envInfo;
}
public String getEnvInfo(){
return this.envInfo;
}
public void set__typename(String __typename){
this.__typename = __typename;
}
public String get__typename(){
return this.__typename;
}
}<file_sep>package com.LeetCode.code.q492.ConstructtheRectangle;
/**
* @QuestionId : 492
* @difficulty : Easy
* @Title : Construct the Rectangle
* @TranslatedTitle:构造矩形
* @url : https://leetcode-cn.com/problems/construct-the-rectangle/
* @TranslatedContent:作为一位web开发者, 懂得怎样去规划一个页面的尺寸是很重要的。 现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求:
1. 你设计的矩形页面必须等于给定的目标面积。
2. 宽度 W 不应大于长度 L,换言之,要求 L >= W 。
3. 长度 L 和宽度 W 之间的差距应当尽可能小。
你需要按顺序输出你设计的页面的长度 L 和宽度 W。
示例:
输入: 4
输出: [2, 2]
解释: 目标面积是 4, 所有可能的构造方案有 [1,4], [2,2], [4,1]。
但是根据要求2,[1,4] 不符合要求; 根据要求3,[2,2] 比 [4,1] 更能符合要求. 所以输出长度 L 为 2, 宽度 W 为 2。
说明:
给定的面积不大于 10,000,000 且为正整数。
你设计的页面的长度和宽度必须都是正整数。
*/
class Solution {
public int[] constructRectangle(int area) {
}
}<file_sep>package com.LeetCode.code.q406.QueueReconstructionbyHeight;
/**
* @QuestionId : 406
* @difficulty : Medium
* @Title : Queue Reconstruction by Height
* @TranslatedTitle:根据身高重建队列
* @url : https://leetcode-cn.com/problems/queue-reconstruction-by-height/
* @TranslatedContent:假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。
注意:<br />
总人数少于1100人。
示例
输入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
输出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
*/
class Solution {
public int[][] reconstructQueue(int[][] people) {
}
}<file_sep>package com.LeetCode.code.q908.MiddleoftheLinkedList;
/**
* @QuestionId : 908
* @difficulty : Easy
* @Title : Middle of the Linked List
* @TranslatedTitle:链表的中间结点
* @url : https://leetcode-cn.com/problems/middle-of-the-linked-list/
* @TranslatedContent:给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
示例 2:
输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
提示:
给定链表的结点数介于 1 和 100 之间。
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode middleNode(ListNode head) {
}
}<file_sep>package com.LeetCode.code.q480.SlidingWindowMedian;
/**
* @QuestionId : 480
* @difficulty : Hard
* @Title : Sliding Window Median
* @TranslatedTitle:滑动窗口中位数
* @url : https://leetcode-cn.com/problems/sliding-window-median/
* @TranslatedContent:中位数是有序序列最中间的那个数。如果序列的大小是偶数,则没有最中间的数;此时中位数是最中间的两个数的平均数。
例如:
[2,3,4],中位数是 3
[2,3],中位数是 (2 + 3) / 2 = 2.5
给出一个数组 nums,有一个大小为 k 的窗口从最左端滑动到最右端。窗口中有 k 个数,每次窗口移动 1 位。你的任务是找出每次窗口移动后得到的新窗口中元素的中位数,并输出由它们组成的数组。
例如:
给出 nums = [1,3,-1,-3,5,3,6,7],以及 k = 3。
窗口位置 中位数
--------------- -----
[1 3 -1] -3 5 3 6 7 1
1 [3 -1 -3] 5 3 6 7 -1
1 3 [-1 -3 5] 3 6 7 -1
1 3 -1 [-3 5 3] 6 7 3
1 3 -1 -3 [5 3 6] 7 5
1 3 -1 -3 5 [3 6 7] 6
因此,返回该滑动窗口的中位数数组 [1,-1,-1,3,5,6]。
提示:<br />
假设k是合法的,即:k 始终小于输入的非空数组的元素个数.
*/
class Solution {
public double[] medianSlidingWindow(int[] nums, int k) {
}
}<file_sep>package com.LeetCode.code.q347.TopKFrequentElements;
/**
* @QuestionId : 347
* @difficulty : Medium
* @Title : Top K Frequent Elements
* @TranslatedTitle:前 K 个高频元素
* @url : https://leetcode-cn.com/problems/top-k-frequent-elements/
* @TranslatedContent:给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
说明:
你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
*/
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
}
}<file_sep>package com.LeetCode.code.q233.NumberofDigitOne;
/**
* @QuestionId : 233
* @difficulty : Hard
* @Title : Number of Digit One
* @TranslatedTitle:数字 1 的个数
* @url : https://leetcode-cn.com/problems/number-of-digit-one/
* @TranslatedContent:给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。
示例:
输入: 13
输出: 6
解释: 数字 1 出现在以下数字中: 1, 10, 11, 12, 13 。
*/
class Solution {
public int countDigitOne(int n) {
}
}<file_sep>package com.LeetCode.code.q377.CombinationSumIV;
/**
* @QuestionId : 377
* @difficulty : Medium
* @Title : Combination Sum IV
* @TranslatedTitle:组合总和 Ⅳ
* @url : https://leetcode-cn.com/problems/combination-sum-iv/
* @TranslatedContent:给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
示例:
nums = [1, 2, 3]
target = 4
所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
请注意,顺序不同的序列被视作不同的组合。
因此输出为 7。
进阶:<br />
如果给定的数组中含有负数会怎么样?<br />
问题会产生什么变化?<br />
我们需要在题目中添加什么限制来允许负数的出现?
致谢:<br />
特别感谢 <a href="https://leetcode.com/pbrother/">@pbrother 添加此问题并创建所有测试用例。
*/
class Solution {
public int combinationSum4(int[] nums, int target) {
}
}<file_sep>package com.LeetCode.code.q384.ShuffleanArray;
/**
* @QuestionId : 384
* @difficulty : Medium
* @Title : Shuffle an Array
* @TranslatedTitle:打乱数组
* @url : https://leetcode-cn.com/problems/shuffle-an-array/
* @TranslatedContent:打乱一个没有重复元素的数组。
示例:
// 以数字集合 1, 2 和 3 初始化数组。
int[] nums = {1,2,3};
Solution solution = new Solution(nums);
// 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。
solution.shuffle();
// 重设数组到它的初始状态[1,2,3]。
solution.reset();
// 随机返回数组[1,2,3]打乱后的结果。
solution.shuffle();
*/
class Solution {
public Solution(int[] nums) {
}
/** Resets the array to its original configuration and return it. */
public int[] reset() {
}
/** Returns a random shuffling of the array. */
public int[] shuffle() {
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/<file_sep>package com.LeetCode.code.q232.ImplementQueueusingStacks;
/**
* @QuestionId : 232
* @difficulty : Easy
* @Title : Implement Queue using Stacks
* @TranslatedTitle:用栈实现队列
* @url : https://leetcode-cn.com/problems/implement-queue-using-stacks/
* @TranslatedContent:使用栈实现队列的下列操作:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
*/
class MyQueue {
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
}
/** Get the front element. */
public int peek() {
}
/** Returns whether the queue is empty. */
public boolean empty() {
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/<file_sep>package com.LeetCode.code.q268.MissingNumber;
/**
* @QuestionId : 268
* @difficulty : Easy
* @Title : Missing Number
* @TranslatedTitle:缺失数字
* @url : https://leetcode-cn.com/problems/missing-number/
* @TranslatedContent:给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
示例 1:
输入: [3,0,1]
输出: 2
示例 2:
输入: [9,6,4,2,3,5,7,0,1]
输出: 8
说明:
你的算法应具有线性时间复杂度。你能否仅使用额外常数空间来实现?
*/
class Solution {
public int missingNumber(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q718.MaximumLengthofRepeatedSubarray;
/**
* @QuestionId : 718
* @difficulty : Medium
* @Title : Maximum Length of Repeated Subarray
* @TranslatedTitle:最长重复子数组
* @url : https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/
* @TranslatedContent:给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。
示例 1:
输入:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
输出: 3
解释:
长度最长的公共子数组是 [3, 2, 1]。
说明:
1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100
*/
class Solution {
public int findLength(int[] A, int[] B) {
}
}<file_sep>package com.LeetCode.code.q1096.MaximumSumofTwoNon-OverlappingSubarrays;
/**
* @QuestionId : 1096
* @difficulty : Medium
* @Title : Maximum Sum of Two Non-Overlapping Subarrays
* @TranslatedTitle:两个非重叠子数组的最大和
* @url : https://leetcode-cn.com/problems/maximum-sum-of-two-non-overlapping-subarrays/
* @TranslatedContent:给出非负整数数组 A ,返回两个非重叠(连续)子数组中元素的最大和,子数组的长度分别为 L 和 M。(这里需要澄清的是,长为 L 的子数组可以出现在长为 M 的子数组之前或之后。)
从形式上看,返回最大的 V,而 V = (A[i] + A[i+1] + ... + A[i+L-1]) + (A[j] + A[j+1] + ... + A[j+M-1]) 并满足下列条件之一:
0 <= i < i + L - 1 < j < j + M - 1 < A.length, 或
0 <= j < j + M - 1 < i < i + L - 1 < A.length.
示例 1:
输入:A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
输出:20
解释:子数组的一种选择中,[9] 长度为 1,[6,5] 长度为 2。
示例 2:
输入:A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
输出:29
解释:子数组的一种选择中,[3,8,1] 长度为 3,[8,9] 长度为 2。
示例 3:
输入:A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
输出:31
解释:子数组的一种选择中,[5,6,0,9] 长度为 4,[0,3,8] 长度为 3。
提示:
L >= 1
M >= 1
L + M <= A.length <= 1000
0 <= A[i] <= 1000
*/
class Solution {
public int maxSumTwoNoOverlap(int[] A, int L, int M) {
}
}<file_sep>package com.LeetCode.code.q123.BestTimetoBuyandSellStockIII;
/**
* @QuestionId : 123
* @difficulty : Hard
* @Title : Best Time to Buy and Sell Stock III
* @TranslatedTitle:买卖股票的最佳时机 III
* @url : https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/
* @TranslatedContent:给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [3,3,5,0,0,3,1,4]
输出: 6
解释: 在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。
随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。
示例 2:
输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
示例 3:
输入: [7,6,4,3,1]
输出: 0
解释: 在这个情况下, 没有交易完成, 所以最大利润为 0。
*/
class Solution {
public int maxProfit(int[] prices) {
}
}<file_sep>package com.LeetCode.code.q94.BinaryTreeInorderTraversal;
/**
* @QuestionId : 94
* @difficulty : Medium
* @Title : Binary Tree Inorder Traversal
* @TranslatedTitle:二叉树的中序遍历
* @url : https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
* @TranslatedContent:给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q372.SuperPow;
/**
* @QuestionId : 372
* @difficulty : Medium
* @Title : Super Pow
* @TranslatedTitle:超级次方
* @url : https://leetcode-cn.com/problems/super-pow/
* @TranslatedContent:你的任务是计算 ab 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。
示例 1:
输入: a = 2, b = [3]
输出: 8
示例 2:
输入: a = 2, b = [1,0]
输出: 1024
*/
class Solution {
public int superPow(int a, int[] b) {
}
}<file_sep>package com.LeetCode.code.q119.Pascal'sTriangleII;
/**
* @QuestionId : 119
* @difficulty : Easy
* @Title : Pascal's Triangle II
* @TranslatedTitle:杨辉三角 II
* @url : https://leetcode-cn.com/problems/pascals-triangle-ii/
* @TranslatedContent:给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
<img alt="" src="https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif">
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 3
输出: [1,3,3,1]
进阶:
你可以优化你的算法到 O(k) 空间复杂度吗?
*/
class Solution {
public List<Integer> getRow(int rowIndex) {
}
}<file_sep>package com.LeetCode.code.q1196.FillingBookcaseShelves;
/**
* @QuestionId : 1196
* @difficulty : Medium
* @Title : Filling Bookcase Shelves
* @TranslatedTitle:填充书架
* @url : https://leetcode-cn.com/problems/filling-bookcase-shelves/
* @TranslatedContent:附近的家居城促销,你买回了一直心仪的可调节书架,打算把自己的书都整理到新的书架上。
你把要摆放的书 books 都整理好,叠成一摞:从上往下,第 i 本书的厚度为 books[i][0],高度为 books[i][1]。
按顺序 将这些书摆放到总宽度为 shelf_width 的书架上。
先选几本书放在书架上(它们的厚度之和小于等于书架的宽度 shelf_width),然后再建一层书架。重复这个过程,直到把所有的书都放在书架上。
需要注意的是,在上述过程的每个步骤中,摆放书的顺序与你整理好的顺序相同。 例如,如果这里有 5 本书,那么可能的一种摆放情况是:第一和第二本书放在第一层书架上,第三本书放在第二层书架上,第四和第五本书放在最后一层书架上。
每一层所摆放的书的最大高度就是这一层书架的层高,书架整体的高度为各层高之和。
以这种方式布置书架,返回书架整体可能的最小高度。
示例:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/28/shelves.png" style="width: 150px;">
输入:books = [[1,1],[2,3],[2,3],[1,1],[1,1],[1,1],[1,2]], shelf_width = 4
输出:6
解释:
3 层书架的高度和为 1 + 3 + 2 = 6 。
第 2 本书不必放在第一层书架上。
提示:
1 <= books.length <= 1000
1 <= books[i][0] <= shelf_width <= 1000
1 <= books[i][1] <= 1000
*/
class Solution {
public int minHeightShelves(int[][] books, int shelf_width) {
}
}<file_sep>package com.LeetCode.code.q876.HandofStraights;
/**
* @QuestionId : 876
* @difficulty : Medium
* @Title : Hand of Straights
* @TranslatedTitle:一手顺子
* @url : https://leetcode-cn.com/problems/hand-of-straights/
* @TranslatedContent:爱丽丝有一手(hand)由整数数组给定的牌。
现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。
如果她可以完成分组就返回 true,否则返回 false。
示例 1:
输入:hand = [1,2,3,6,2,3,4,7,8], W = 3
输出:true
解释:爱丽丝的手牌可以被重新排列为 [1,2,3],[2,3,4],[6,7,8]。
示例 2:
输入:hand = [1,2,3,4,5], W = 4
输出:false
解释:爱丽丝的手牌无法被重新排列成几个大小为 4 的组。
提示:
1 <= hand.length <= 10000
0 <= hand[i] <= 10^9
1 <= W <= hand.length
*/
class Solution {
public boolean isNStraightHand(int[] hand, int W) {
}
}<file_sep>package com.LeetCode.code.q203.RemoveLinkedListElements;
/**
* @QuestionId : 203
* @difficulty : Easy
* @Title : Remove Linked List Elements
* @TranslatedTitle:移除链表元素
* @url : https://leetcode-cn.com/problems/remove-linked-list-elements/
* @TranslatedContent:删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
}
}<file_sep>package com.LeetCode.freemark;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FreemarkerDemo {
private static final String TEMPLATE_PATH = "src/main/resources";
//C:/Users/dengxy/eclipse-workspace/LeetCode/
private static final String CLASS_PATH = "src/main/java/com/LeetCode/code";
/* public static void main(String[] args) {
// step1 创建freeMarker配置实例
Configuration configuration = new Configuration();
Writer out = null;
try {
// step2 获取模版路径
configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
// step3 创建数据模型
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("classPath", "com.freemark.hello");
dataMap.put("className", "User");
dataMap.put("Id", "Id");
dataMap.put("userName", "userName");
dataMap.put("password","<PASSWORD>");
// step4 加载模版文件
Template template = configuration.getTemplate("question.ftl");
// step5 生成数据
File docFile = new File(CLASS_PATH + "\\" + "Solution.java");
if(!docFile.exists()) {
docFile.createNewFile();
}
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
// step6 输出文件
template.process(dataMap, out);
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^Solution.java 文件创建成功 !");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.flush();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}*/
public static void create(Map<String, String> dataMap) {
// step1 创建freeMarker配置实例
Configuration configuration = new Configuration();
Writer out = null;
try {
// step2 获取模版路径
configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
String packageQuest = "q" + dataMap.get("QuestionId");
String packageQuestName = dataMap.get("Title").replace(" ", "");
// step3 创建数据模型
dataMap.put("packageName","com.LeetCode.code."+packageQuest+"."+packageQuestName);
// step4 加载模版文件
Template template = configuration.getTemplate("question.ftl");
// step5 生成数据
String path = CLASS_PATH +"/"+packageQuest+"/"+packageQuestName;
String path2 = path + "/" + "Solution.java" ;
System.out.println(path);
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
File docFile = new File(path2);
if(!docFile.exists()) {
docFile.createNewFile();
}
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
// step6 输出文件
template.process(dataMap, out);
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^Solution.java 文件创建成功 !");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.flush();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}<file_sep>package com.LeetCode.code.q799.MinimumDistanceBetweenBSTNodes;
/**
* @QuestionId : 799
* @difficulty : Easy
* @Title : Minimum Distance Between BST Nodes
* @TranslatedTitle:二叉搜索树结点最小距离
* @url : https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/
* @TranslatedContent:给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值。
示例:
输入: root = [4,2,6,1,3,null,null]
输出: 1
解释:
注意,root是树结点对象(TreeNode object),而不是数组。
给定的树 [4,2,6,1,3,null,null] 可表示为下图:
4
/ \
2 6
/ \
1 3
最小的差值是 1, 它是节点1和节点2的差值, 也是节点3和节点2的差值。
注意:
二叉树的大小范围在 2 到 100。
二叉树总是有效的,每个节点的值都是整数,且不重复。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDiffInBST(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q241.DifferentWaystoAddParentheses;
/**
* @QuestionId : 241
* @difficulty : Medium
* @Title : Different Ways to Add Parentheses
* @TranslatedTitle:为运算表达式设计优先级
* @url : https://leetcode-cn.com/problems/different-ways-to-add-parentheses/
* @TranslatedContent:给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
示例 1:
输入: "2-1-1"
输出: [0, 2]
解释:
((2-1)-1) = 0
(2-(1-1)) = 2
示例 2:
输入: "2*3-4*5"
输出: [-34, -14, -10, -10, 10]
解释:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
*/
class Solution {
public List<Integer> diffWaysToCompute(String input) {
}
}<file_sep>package com.LeetCode.code.q98.ValidateBinarySearchTree;
/**
* @QuestionId : 98
* @difficulty : Medium
* @Title : Validate Binary Search Tree
* @TranslatedTitle:验证二叉搜索树
* @url : https://leetcode-cn.com/problems/validate-binary-search-tree/
* @TranslatedContent:给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q637.AverageofLevelsinBinaryTree;
/**
* @QuestionId : 637
* @difficulty : Easy
* @Title : Average of Levels in Binary Tree
* @TranslatedTitle:二叉树的层平均值
* @url : https://leetcode-cn.com/problems/average-of-levels-in-binary-tree/
* @TranslatedContent:给定一个非空二叉树, 返回一个由每层节点平均值组成的数组.
示例 1:
输入:
3
/ \
9 20
/ \
15 7
输出: [3, 14.5, 11]
解释:
第0层的平均值是 3, 第1层是 14.5, 第2层是 11. 因此返回 [3, 14.5, 11].
注意:
节点值的范围在32位有符号整数范围内。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Double> averageOfLevels(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q647.PalindromicSubstrings;
/**
* @QuestionId : 647
* @difficulty : Medium
* @Title : Palindromic Substrings
* @TranslatedTitle:回文子串
* @url : https://leetcode-cn.com/problems/palindromic-substrings/
* @TranslatedContent:给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
示例 1:
输入: "abc"
输出: 3
解释: 三个回文子串: "a", "b", "c".
示例 2:
输入: "aaa"
输出: 6
说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
注意:
输入的字符串长度不会超过1000。
*/
class Solution {
public int countSubstrings(String s) {
}
}<file_sep>package com.LeetCode.code.q304.RangeSumQuery2D-Immutable;
/**
* @QuestionId : 304
* @difficulty : Medium
* @Title : Range Sum Query 2D - Immutable
* @TranslatedTitle:二维区域和检索 - 矩阵不可变
* @url : https://leetcode-cn.com/problems/range-sum-query-2d-immutable/
* @TranslatedContent:给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2)。
<img alt="Range Sum Query 2D" src="https://assets.leetcode-cn.com/aliyun-lc-upload/images/304.png" style="width: 130px;">
上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3),该子矩形内元素的总和为 8。
示例:
给定 matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12
说明:
你可以假设矩阵不可变。
会多次调用 sumRegion 方法。
你可以假设 row1 ≤ row2 且 col1 ≤ col2。
*/
class NumMatrix {
public NumMatrix(int[][] matrix) {
}
public int sumRegion(int row1, int col1, int row2, int col2) {
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
*/<file_sep>package com.LeetCode.code.q955.CompleteBinaryTreeInserter;
/**
* @QuestionId : 955
* @difficulty : Medium
* @Title : Complete Binary Tree Inserter
* @TranslatedTitle:完全二叉树插入器
* @url : https://leetcode-cn.com/problems/complete-binary-tree-inserter/
* @TranslatedContent:完全二叉树是每一层(除最后一层外)都是完全填充(即,结点数达到最大)的,并且所有的结点都尽可能地集中在左侧。
设计一个用完全二叉树初始化的数据结构 CBTInserter,它支持以下几种操作:
CBTInserter(TreeNode root) 使用头结点为 root 的给定树初始化该数据结构;
CBTInserter.insert(int v) 将 TreeNode 插入到存在值为 node.val = v 的树中以使其保持完全二叉树的状态,并返回插入的 TreeNode 的父结点的值;
CBTInserter.get_root() 将返回树的头结点。
示例 1:
输入:inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]]
输出:[null,1,[1,2]]
示例 2:
输入:inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]]
输出:[null,3,4,[1,2,3,4,5,6,7,8]]
提示:
最初给定的树是完全二叉树,且包含 1 到 1000 个结点。
每个测试用例最多调用 CBTInserter.insert 操作 10000 次。
给定结点或插入结点的每个值都在 0 到 5000 之间。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class CBTInserter {
public CBTInserter(TreeNode root) {
}
public int insert(int v) {
}
public TreeNode get_root() {
}
}
/**
* Your CBTInserter object will be instantiated and called as such:
* CBTInserter obj = new CBTInserter(root);
* int param_1 = obj.insert(v);
* TreeNode param_2 = obj.get_root();
*/<file_sep>package com.LeetCode.code.q740.DeleteandEarn;
/**
* @QuestionId : 740
* @difficulty : Medium
* @Title : Delete and Earn
* @TranslatedTitle:删除与获得点数
* @url : https://leetcode-cn.com/problems/delete-and-earn/
* @TranslatedContent:给定一个整数数组 nums ,你可以对它进行一些操作。
每次操作中,选择任意一个 nums[i] ,删除它并获得 nums[i] 的点数。之后,你必须删除每个等于 nums[i] - 1 或 nums[i] + 1 的元素。
开始你拥有 0 个点数。返回你能通过这些操作获得的最大点数。
示例 1:
输入: nums = [3, 4, 2]
输出: 6
解释:
删除 4 来获得 4 个点数,因此 3 也被删除。
之后,删除 2 来获得 2 个点数。总共获得 6 个点数。
示例 2:
输入: nums = [2, 2, 3, 3, 3, 4]
输出: 9
解释:
删除 3 来获得 3 个点数,接着要删除两个 2 和 4 。
之后,再次删除 3 获得 3 个点数,再次删除 3 获得 3 个点数。
总共获得 9 个点数。
注意:
nums的长度最大为20000。
每个整数nums[i]的大小都在[1, 10000]范围内。
*/
class Solution {
public int deleteAndEarn(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q403.FrogJump;
/**
* @QuestionId : 403
* @difficulty : Hard
* @Title : Frog Jump
* @TranslatedTitle:青蛙过河
* @url : https://leetcode-cn.com/problems/frog-jump/
* @TranslatedContent:一只青蛙想要过河。 假定河流被等分为 x 个单元格,并且在每一个单元格内都有可能放有一石子(也有可能没有)。 青蛙可以跳上石头,但是不可以跳入水中。
给定石子的位置列表(用单元格序号升序表示), 请判定青蛙能否成功过河(即能否在最后一步跳至最后一个石子上)。 开始时, 青蛙默认已站在第一个石子上,并可以假定它第一步只能跳跃一个单位(即只能从单元格1跳至单元格2)。
如果青蛙上一步跳跃了 k 个单位,那么它接下来的跳跃距离只能选择为 k - 1、k 或 k + 1个单位。 另请注意,青蛙只能向前方(终点的方向)跳跃。
请注意:
石子的数量 ≥ 2 且 < 1100;
每一个石子的位置序号都是一个非负整数,且其 < 231;
第一个石子的位置永远是0。
示例 1:
[0,1,3,5,6,8,12,17]
总共有8个石子。
第一个石子处于序号为0的单元格的位置, 第二个石子处于序号为1的单元格的位置,
第三个石子在序号为3的单元格的位置, 以此定义整个数组...
最后一个石子处于序号为17的单元格的位置。
返回 true。即青蛙可以成功过河,按照如下方案跳跃:
跳1个单位到第2块石子, 然后跳2个单位到第3块石子, 接着
跳2个单位到第4块石子, 然后跳3个单位到第6块石子,
跳4个单位到第7块石子, 最后,跳5个单位到第8个石子(即最后一块石子)。
示例 2:
[0,1,2,3,4,8,9,11]
返回 false。青蛙没有办法过河。
这是因为第5和第6个石子之间的间距太大,没有可选的方案供青蛙跳跃过去。
*/
class Solution {
public boolean canCross(int[] stones) {
}
}<file_sep>package com.LeetCode.code.q964.MinimizeMalwareSpreadII;
/**
* @QuestionId : 964
* @difficulty : Hard
* @Title : Minimize Malware Spread II
* @TranslatedTitle:尽量减少恶意软件的传播 II
* @url : https://leetcode-cn.com/problems/minimize-malware-spread-ii/
* @TranslatedContent:(这个问题与 尽量减少恶意软件的传播 是一样的,不同之处用粗体表示。)
在节点网络中,只有当 graph[i][j] = 1 时,每个节点 i 能够直接连接到另一个节点 j。
一些节点 initial 最初被恶意软件感染。只要两个节点直接连接,且其中至少一个节点受到恶意软件的感染,那么两个节点都将被恶意软件感染。这种恶意软件的传播将继续,直到没有更多的节点可以被这种方式感染。
假设 M(initial) 是在恶意软件停止传播之后,整个网络中感染恶意软件的最终节点数。
我们可以从初始列表中删除一个节点,并完全移除该节点以及从该节点到任何其他节点的任何连接。如果移除这一节点将最小化 M(initial), 则返回该节点。如果有多个节点满足条件,就返回索引最小的节点。
示例 1:
输出:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
输入:0
示例 2:
输入:graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]
输出:1
示例 3:
输入:graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]
输出:1
提示:
1 < graph.length = graph[0].length <= 300
0 <= graph[i][j] == graph[j][i] <= 1
graph[i][i] = 1
1 <= initial.length < graph.length
0 <= initial[i] < graph.length
*/
class Solution {
public int minMalwareSpread(int[][] graph, int[] initial) {
}
}<file_sep>package com.LeetCode.code.q301.RemoveInvalidParentheses;
/**
* @QuestionId : 301
* @difficulty : Hard
* @Title : Remove Invalid Parentheses
* @TranslatedTitle:删除无效的括号
* @url : https://leetcode-cn.com/problems/remove-invalid-parentheses/
* @TranslatedContent:删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。
说明: 输入可能包含了除 ( 和 ) 以外的字符。
示例 1:
输入: "()())()"
输出: ["()()()", "(())()"]
示例 2:
输入: "(a)())()"
输出: ["(a)()()", "(a())()"]
示例 3:
输入: ")("
输出: [""]
*/
class Solution {
public List<String> removeInvalidParentheses(String s) {
}
}<file_sep>package com.LeetCode.code.q787.SlidingPuzzle;
/**
* @QuestionId : 787
* @difficulty : Hard
* @Title : Sliding Puzzle
* @TranslatedTitle:滑动谜题
* @url : https://leetcode-cn.com/problems/sliding-puzzle/
* @TranslatedContent:在一个 2 x 3 的板上(board)有 5 块砖瓦,用数字 1~5 来表示, 以及一块空缺用 0 来表示.
一次移动定义为选择 0 与一个相邻的数字(上下左右)进行交换.
最终当板 board 的结果是 [[1,2,3],[4,5,0]] 谜板被解开。
给出一个谜板的初始状态,返回最少可以通过多少次移动解开谜板,如果不能解开谜板,则返回 -1 。
示例:
输入:board = [[1,2,3],[4,0,5]]
输出:1
解释:交换 0 和 5 ,1 步完成
输入:board = [[1,2,3],[5,4,0]]
输出:-1
解释:没有办法完成谜板
输入:board = [[4,1,2],[5,0,3]]
输出:5
解释:
最少完成谜板的最少移动次数是 5 ,
一种移动路径:
尚未移动: [[4,1,2],[5,0,3]]
移动 1 次: [[4,1,2],[0,5,3]]
移动 2 次: [[0,1,2],[4,5,3]]
移动 3 次: [[1,0,2],[4,5,3]]
移动 4 次: [[1,2,0],[4,5,3]]
移动 5 次: [[1,2,3],[4,5,0]]
输入:board = [[3,2,4],[1,5,0]]
输出:14
提示:
board 是一个如上所述的 2 x 3 的数组.
board[i][j] 是一个 [0, 1, 2, 3, 4, 5] 的排列.
*/
class Solution {
public int slidingPuzzle(int[][] board) {
}
}<file_sep>package com.LeetCode.code.q974.ReorderLogFiles;
/**
* @QuestionId : 974
* @difficulty : Easy
* @Title : Reorder Log Files
* @TranslatedTitle:重新排列日志文件
* @url : https://leetcode-cn.com/problems/reorder-log-files/
* @TranslatedContent:你有一个日志数组 logs。每条日志都是以空格分隔的字串。
对于每条日志,其第一个字为字母数字标识符。然后,要么:
标识符后面的每个字将仅由小写字母组成,或;
标识符后面的每个字将仅由数字组成。
我们将这两种日志分别称为字母日志和数字日志。保证每个日志在其标识符后面至少有一个字。
将日志重新排序,使得所有字母日志都排在数字日志之前。字母日志按内容字母顺序排序,忽略标识符;在内容相同时,按标识符排序。数字日志应该按原来的顺序排列。
返回日志的最终顺序。
示例 :
输入:["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
输出:["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
提示:
0 <= logs.length <= 100
3 <= logs[i].length <= 100
logs[i] 保证有一个标识符,并且标识符后面有一个字。
*/
class Solution {
public String[] reorderLogFiles(String[] logs) {
}
}<file_sep>package com.LeetCode.code.q928.SurfaceAreaof3DShapes;
/**
* @QuestionId : 928
* @difficulty : Easy
* @Title : Surface Area of 3D Shapes
* @TranslatedTitle:三维形体的表面积
* @url : https://leetcode-cn.com/problems/surface-area-of-3d-shapes/
* @TranslatedContent:在 N * N 的网格上,我们放置一些 1 * 1 * 1 的立方体。
每个值 v = grid[i][j] 表示 v 个正方体叠放在对应单元格 (i, j) 上。
请你返回最终形体的表面积。
示例 1:
输入:[[2]]
输出:10
示例 2:
输入:[[1,2],[3,4]]
输出:34
示例 3:
输入:[[1,0],[0,2]]
输出:16
示例 4:
输入:[[1,1,1],[1,0,1],[1,1,1]]
输出:32
示例 5:
输入:[[2,2,2],[2,1,2],[2,2,2]]
输出:46
提示:
1 <= N <= 50
0 <= grid[i][j] <= 50
*/
class Solution {
public int surfaceArea(int[][] grid) {
}
}<file_sep>package com.LeetCode.code.q1171.ShortestPathinBinaryMatrix;
/**
* @QuestionId : 1171
* @difficulty : Medium
* @Title : Shortest Path in Binary Matrix
* @TranslatedTitle:二进制矩阵中的最短路径
* @url : https://leetcode-cn.com/problems/shortest-path-in-binary-matrix/
* @TranslatedContent:在一个 N × N 的方形网格中,每个单元格有两种状态:空(0)或者阻塞(1)。
一条从左上角到右下角、长度为 k 的畅通路径,由满足下述条件的单元格 C_1, C_2, ..., C_k 组成:
相邻单元格 C_i 和 C_{i+1} 在八个方向之一上连通(此时,C_i 和 C_{i+1} 不同且共享边或角)
C_1 位于 (0, 0)(即,值为 grid[0][0])
C_k 位于 (N-1, N-1)(即,值为 grid[N-1][N-1])
如果 C_i 位于 (r, c),则 grid[r][c] 为空(即,grid[r][c] == 0)
返回这条从左上角到右下角的最短畅通路径的长度。如果不存在这样的路径,返回 -1 。
示例 1:
输入:[[0,1],[1,0]]
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/16/example1_1.png" style="height: 151px; width: 150px;">
输出:2
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/16/example1_2.png" style="height: 151px; width: 150px;">
示例 2:
输入:[[0,0,0],[1,1,0],[1,1,0]]
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/16/example2_1.png" style="height: 146px; width: 150px;">
输出:4
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/16/example2_2.png" style="height: 151px; width: 150px;">
提示:
1 <= grid.length == grid[0].length <= 100
grid[i][j] 为 0 或 1
*/
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
}
}<file_sep>package com.LeetCode.code.q467.UniqueSubstringsinWraparoundString;
/**
* @QuestionId : 467
* @difficulty : Medium
* @Title : Unique Substrings in Wraparound String
* @TranslatedTitle:环绕字符串中唯一的子字符串
* @url : https://leetcode-cn.com/problems/unique-substrings-in-wraparound-string/
* @TranslatedContent:把字符串 s 看作是“abcdefghijklmnopqrstuvwxyz”的无限环绕字符串,所以 s 看起来是这样的:"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".
现在我们有了另一个字符串 p 。你需要的是找出 s 中有多少个唯一的 p 的非空子串,尤其是当你的输入是字符串 p ,你需要输出字符串 s 中 p 的不同的非空子串的数目。
注意: p 仅由小写的英文字母组成,p 的大小可能超过 10000。
示例 1:
输入: "a"
输出: 1
解释: 字符串 S 中只有一个"a"子字符。
示例 2:
输入: "cac"
输出: 2
解释: 字符串 S 中的字符串“cac”只有两个子串“a”、“c”。.
示例 3:
输入: "zab"
输出: 6
解释: 在字符串 S 中有六个子串“z”、“a”、“b”、“za”、“ab”、“zab”。.
*/
class Solution {
public int findSubstringInWraproundString(String p) {
}
}<file_sep>package com.LeetCode.code.q1000.DeleteColumnstoMakeSortedIII;
/**
* @QuestionId : 1000
* @difficulty : Hard
* @Title : Delete Columns to Make Sorted III
* @TranslatedTitle:删列造序 III
* @url : https://leetcode-cn.com/problems/delete-columns-to-make-sorted-iii/
* @TranslatedContent:给定由 N 个小写字母字符串组成的数组 A,其中每个字符串长度相等。
选取一个删除索引序列,对于 A 中的每个字符串,删除对应每个索引处的字符。
比如,有 A = ["babca","bbazb"],删除索引序列 {0, 1, 4},删除后 A 为["bc","az"]。
假设,我们选择了一组删除索引 D,那么在执行删除操作之后,最终得到的数组的行中的每个元素都是按字典序排列的。
清楚起见,A[0] 是按字典序排列的(即,A[0][0] <= A[0][1] <= ... <= A[0][A[0].length - 1]),A[1] 是按字典序排列的(即,A[1][0] <= A[1][1] <= ... <= A[1][A[1].length - 1]),依此类推。
请你返回 D.length 的最小可能值。
示例 1:
输入:["babca","bbazb"]
输出:3
解释:
删除 0、1 和 4 这三列后,最终得到的数组是 A = ["bc", "az"]。
这两行是分别按字典序排列的(即,A[0][0] <= A[0][1] 且 A[1][0] <= A[1][1])。
注意,A[0] > A[1] —— 数组 A 不一定是按字典序排列的。
示例 2:
输入:["edcba"]
输出:4
解释:如果删除的列少于 4 列,则剩下的行都不会按字典序排列。
示例 3:
输入:["ghi","def","abc"]
输出:0
解释:所有行都已按字典序排列。
提示:
1 <= A.length <= 100
1 <= A[i].length <= 100
*/
class Solution {
public int minDeletionSize(String[] A) {
}
}<file_sep>package com.LeetCode.code.q151.ReverseWordsinaString;
/**
* @QuestionId : 151
* @difficulty : Medium
* @Title : Reverse Words in a String
* @TranslatedTitle:翻转字符串里的单词
* @url : https://leetcode-cn.com/problems/reverse-words-in-a-string/
* @TranslatedContent:给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
进阶:
请选用 C 语言的用户尝试使用 O(1) 额外空间复杂度的原地解法。
*/
class Solution {
public String reverseWords(String s) {
}
}<file_sep>package com.LeetCode.code.q3.LongestSubstringWithoutRepeatingCharacters;
/**
* @QuestionId : 3
* @difficulty : Medium
* @Title : Longest Substring Without Repeating Characters
* @TranslatedTitle:无重复字符的最长子串
* @url : https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
* @TranslatedContent:给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
*/
class Solution {
public int lengthOfLongestSubstring(String s) {
}
}<file_sep>package com.LeetCode.code.q1031.AddtoArray-FormofInteger;
/**
* @QuestionId : 1031
* @difficulty : Easy
* @Title : Add to Array-Form of Integer
* @TranslatedTitle:数组形式的整数加法
* @url : https://leetcode-cn.com/problems/add-to-array-form-of-integer/
* @TranslatedContent:对于非负整数 X 而言,X 的数组形式是每位数字按从左到右的顺序形成的数组。例如,如果 X = 1231,那么其数组形式为 [1,2,3,1]。
给定非负整数 X 的数组形式 A,返回整数 X+K 的数组形式。
示例 1:
输入:A = [1,2,0,0], K = 34
输出:[1,2,3,4]
解释:1200 + 34 = 1234
解释 2:
输入:A = [2,7,4], K = 181
输出:[4,5,5]
解释:274 + 181 = 455
示例 3:
输入:A = [2,1,5], K = 806
输出:[1,0,2,1]
解释:215 + 806 = 1021
示例 4:
输入:A = [9,9,9,9,9,9,9,9,9,9], K = 1
输出:[1,0,0,0,0,0,0,0,0,0,0]
解释:9999999999 + 1 = 10000000000
提示:
1 <= A.length <= 10000
0 <= A[i] <= 9
0 <= K <= 10000
如果 A.length > 1,那么 A[0] != 0
*/
class Solution {
public List<Integer> addToArrayForm(int[] A, int K) {
}
}<file_sep>package com.LeetCode.code.q551.StudentAttendanceRecordI;
/**
* @QuestionId : 551
* @difficulty : Easy
* @Title : Student Attendance Record I
* @TranslatedTitle:学生出勤记录 I
* @url : https://leetcode-cn.com/problems/student-attendance-record-i/
* @TranslatedContent:给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符:
'A' : Absent,缺勤
'L' : Late,迟到
'P' : Present,到场
如果一个学生的出勤记录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),那么这个学生会被奖赏。
你需要根据这个学生的出勤记录判断他是否会被奖赏。
示例 1:
输入: "PPALLP"
输出: True
示例 2:
输入: "PPALLL"
输出: False
*/
class Solution {
public boolean checkRecord(String s) {
}
}<file_sep>package com.LeetCode.code.q951.PartitionArrayintoDisjointIntervals;
/**
* @QuestionId : 951
* @difficulty : Medium
* @Title : Partition Array into Disjoint Intervals
* @TranslatedTitle:分割数组
* @url : https://leetcode-cn.com/problems/partition-array-into-disjoint-intervals/
* @TranslatedContent:给定一个数组 A,将其划分为两个不相交(没有公共元素)的连续子数组 left 和 right, 使得:
left 中的每个元素都小于或等于 right 中的每个元素。
left 和 right 都是非空的。
left 要尽可能小。
在完成这样的分组后返回 left 的长度。可以保证存在这样的划分方法。
示例 1:
输入:[5,0,3,8,6]
输出:3
解释:left = [5,0,3],right = [8,6]
示例 2:
输入:[1,1,1,0,6,12]
输出:4
解释:left = [1,1,1,0],right = [6,12]
提示:
2 <= A.length <= 30000
0 <= A[i] <= 10^6
可以保证至少有一种方法能够按题目所描述的那样对 A 进行划分。
*/
class Solution {
public int partitionDisjoint(int[] A) {
}
}<file_sep>package com.LeetCode.code.q208.ImplementTrie(PrefixTree);
/**
* @QuestionId : 208
* @difficulty : Medium
* @Title : Implement Trie (Prefix Tree)
* @TranslatedTitle:实现 Trie (前缀树)
* @url : https://leetcode-cn.com/problems/implement-trie-prefix-tree/
* @TranslatedContent:实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。
示例:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
说明:
你可以假设所有的输入都是由小写字母 a-z 构成的。
保证所有输入均为非空字符串。
*/
class Trie {
/** Initialize your data structure here. */
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/<file_sep>package com.LeetCode.code.q1080.CamelcaseMatching;
/**
* @QuestionId : 1080
* @difficulty : Medium
* @Title : Camelcase Matching
* @TranslatedTitle:驼峰式匹配
* @url : https://leetcode-cn.com/problems/camelcase-matching/
* @TranslatedContent:如果我们可以将小写字母插入模式串 pattern 得到待查询项 query,那么待查询项与给定模式串匹配。(我们可以在任何位置插入每个字符,也可以插入 0 个字符。)
给定待查询列表 queries,和模式串 pattern,返回由布尔值组成的答案列表 answer。只有在待查项 queries[i] 与模式串 pattern 匹配时, answer[i] 才为 true,否则为 false。
示例 1:
输入:queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FB"
输出:[true,false,true,true,false]
示例:
"FooBar" 可以这样生成:"F" + "oo" + "B" + "ar"。
"FootBall" 可以这样生成:"F" + "oot" + "B" + "all".
"FrameBuffer" 可以这样生成:"F" + "rame" + "B" + "uffer".
示例 2:
输入:queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBa"
输出:[true,false,true,false,false]
解释:
"FooBar" 可以这样生成:"Fo" + "o" + "Ba" + "r".
"FootBall" 可以这样生成:"Fo" + "ot" + "Ba" + "ll".
示例 3:
输出:queries = ["FooBar","FooBarTest","FootBall","FrameBuffer","ForceFeedBack"], pattern = "FoBaT"
输入:[false,true,false,false,false]
解释:
"FooBarTest" 可以这样生成:"Fo" + "o" + "Ba" + "r" + "T" + "est".
提示:
1 <= queries.length <= 100
1 <= queries[i].length <= 100
1 <= pattern.length <= 100
所有字符串都仅由大写和小写英文字母组成。
*/
class Solution {
public List<Boolean> camelMatch(String[] queries, String pattern) {
}
}<file_sep>package com.LeetCode.code.q1160.LetterTilePossibilities;
/**
* @QuestionId : 1160
* @difficulty : Medium
* @Title : Letter Tile Possibilities
* @TranslatedTitle:活字印刷
* @url : https://leetcode-cn.com/problems/letter-tile-possibilities/
* @TranslatedContent:你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。
示例 1:
输入:"AAB"
输出:8
解释:可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA"。
示例 2:
输入:"AAABBC"
输出:188
提示:
1 <= tiles.length <= 7
tiles 由大写英文字母组成
*/
class Solution {
public int numTilePossibilities(String tiles) {
}
}<file_sep>package com.LeetCode.code.q513.FindBottomLeftTreeValue;
/**
* @QuestionId : 513
* @difficulty : Medium
* @Title : Find Bottom Left Tree Value
* @TranslatedTitle:找树左下角的值
* @url : https://leetcode-cn.com/problems/find-bottom-left-tree-value/
* @TranslatedContent:给定一个二叉树,在树的最后一行找到最左边的值。
示例 1:
输入:
2
/ \
1 3
输出:
1
示例 2:
输入:
1
/ \
2 3
/ / \
4 5 6
/
7
输出:
7
注意: 您可以假设树(即给定的根节点)不为 NULL。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q621.TaskScheduler;
/**
* @QuestionId : 621
* @difficulty : Medium
* @Title : Task Scheduler
* @TranslatedTitle:任务调度器
* @url : https://leetcode-cn.com/problems/task-scheduler/
* @TranslatedContent:给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。
然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的最短时间。
示例 1:
输入: tasks = ["A","A","A","B","B","B"], n = 2
输出: 8
执行顺序: A -> B -> (待命) -> A -> B -> (待命) -> A -> B.
注:
任务的总个数为 [1, 10000]。
n 的取值范围为 [0, 100]。
*/
class Solution {
public int leastInterval(char[] tasks, int n) {
}
}<file_sep>package com.LeetCode.code.q713.SubarrayProductLessThanK;
/**
* @QuestionId : 713
* @difficulty : Medium
* @Title : Subarray Product Less Than K
* @TranslatedTitle:乘积小于K的子数组
* @url : https://leetcode-cn.com/problems/subarray-product-less-than-k/
* @TranslatedContent:给定一个正整数数组 nums。
找出该数组内乘积小于 k 的连续的子数组的个数。
示例 1:
输入: nums = [10,5,2,6], k = 100
输出: 8
解释: 8个乘积小于100的子数组分别为: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]。
需要注意的是 [10,5,2] 并不是乘积小于100的子数组。
说明:
0 < nums.length <= 50000
0 < nums[i] < 1000
0 <= k < 10^6
*/
class Solution {
public int numSubarrayProductLessThanK(int[] nums, int k) {
}
}<file_sep>package com.LeetCode.code.q53.MaximumSubarray;
/**
* @QuestionId : 53
* @difficulty : Easy
* @Title : Maximum Subarray
* @TranslatedTitle:最大子序和
* @url : https://leetcode-cn.com/problems/maximum-subarray/
* @TranslatedContent:给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
*/
class Solution {
public int maxSubArray(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q440.K-thSmallestinLexicographicalOrder;
/**
* @QuestionId : 440
* @difficulty : Hard
* @Title : K-th Smallest in Lexicographical Order
* @TranslatedTitle:字典序的第K小数字
* @url : https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order/
* @TranslatedContent:给定整数 n 和 k,找到 1 到 n 中字典序第 k 小的数字。
注意:1 ≤ k ≤ n ≤ 109。
示例 :
输入:
n: 13 k: 2
输出:
10
解释:
字典序的排列是 [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9],所以第二小的数字是 10。
*/
class Solution {
public int findKthNumber(int n, int k) {
}
}<file_sep>package com.LeetCode.code.q782.JewelsandStones;
/**
* @QuestionId : 782
* @difficulty : Easy
* @Title : Jewels and Stones
* @TranslatedTitle:宝石与石头
* @url : https://leetcode-cn.com/problems/jewels-and-stones/
* @TranslatedContent: 给定字符串J 代表石头中宝石的类型,和字符串 S代表你拥有的石头。 S 中每个字符代表了一种你拥有的石头的类型,你想知道你拥有的石头中有多少是宝石。
J 中的字母不重复,J 和 S中的所有字符都是字母。字母区分大小写,因此"a"和"A"是不同类型的石头。
示例 1:
输入: J = "aA", S = "aAAbbbb"
输出: 3
示例 2:
输入: J = "z", S = "ZZ"
输出: 0
注意:
S 和 J 最多含有50个字母。
J 中的字符不重复。
*/
class Solution {
public int numJewelsInStones(String J, String S) {
}
}<file_sep>package com.LeetCode.code.q89.GrayCode;
/**
* @QuestionId : 89
* @difficulty : Medium
* @Title : Gray Code
* @TranslatedTitle:格雷编码
* @url : https://leetcode-cn.com/problems/gray-code/
* @TranslatedContent:格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。
示例 1:
输入: 2
输出: [0,1,3,2]
解释:
00 - 0
01 - 1
11 - 3
10 - 2
对于给定的 n,其格雷编码序列并不唯一。
例如,[0,2,3,1] 也是一个有效的格雷编码序列。
00 - 0
10 - 2
11 - 3
01 - 1
示例 2:
输入: 0
输出: [0]
解释: 我们定义格雷编码序列必须以 0 开头。
给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。
因此,当 n = 0 时,其格雷编码序列为 [0]。
*/
class Solution {
public List<Integer> grayCode(int n) {
}
}<file_sep>package com.LeetCode.code.q240.Searcha2DMatrixII;
/**
* @QuestionId : 240
* @difficulty : Medium
* @Title : Search a 2D Matrix II
* @TranslatedTitle:搜索二维矩阵 II
* @url : https://leetcode-cn.com/problems/search-a-2d-matrix-ii/
* @TranslatedContent:编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例:
现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。
*/
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
}
}<file_sep>package com.LeetCode.code.q327.CountofRangeSum;
/**
* @QuestionId : 327
* @difficulty : Hard
* @Title : Count of Range Sum
* @TranslatedTitle:区间和的个数
* @url : https://leetcode-cn.com/problems/count-of-range-sum/
* @TranslatedContent:给定一个整数数组 nums,返回区间和在 [lower, upper] 之间的个数,包含 lower 和 upper。
区间和 S(i, j) 表示在 nums 中,位置从 i 到 j 的元素之和,包含 i 和 j (i ≤ j)。
说明:
最直观的算法复杂度是 O(n2) ,请在此基础上优化你的算法。
示例:
输入: nums = [-2,5,-1], lower = -2, upper = 2,
输出: 3
解释: 3个区间分别是: [0,0], [2,2], [0,2],它们表示的和分别为: -2, -1, 2。
*/
class Solution {
public int countRangeSum(int[] nums, int lower, int upper) {
}
}<file_sep>package com.LeetCode.code.q103.BinaryTreeZigzagLevelOrderTraversal;
/**
* @QuestionId : 103
* @difficulty : Medium
* @Title : Binary Tree Zigzag Level Order Traversal
* @TranslatedTitle:二叉树的锯齿形层次遍历
* @url : https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
* @TranslatedContent:给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q454.4SumII;
/**
* @QuestionId : 454
* @difficulty : Medium
* @Title : 4Sum II
* @TranslatedTitle:四数相加 II
* @url : https://leetcode-cn.com/problems/4sum-ii/
* @TranslatedContent:给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。
为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。
例如:
输入:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
输出:
2
解释:
两个元组如下:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
*/
class Solution {
public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
}
}<file_sep>package com.LeetCode.code.q473.MatchstickstoSquare;
/**
* @QuestionId : 473
* @difficulty : Medium
* @Title : Matchsticks to Square
* @TranslatedTitle:火柴拼正方形
* @url : https://leetcode-cn.com/problems/matchsticks-to-square/
* @TranslatedContent:还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种能使用所有火柴拼成一个正方形的方法。不能折断火柴,可以把火柴连接起来,并且每根火柴都要用到。
输入为小女孩拥有火柴的数目,每根火柴用其长度表示。输出即为是否能用所有的火柴拼成正方形。
示例 1:
输入: [1,1,2,2,2]
输出: true
解释: 能拼成一个边长为2的正方形,每边两根火柴。
示例 2:
输入: [3,3,3,3,4]
输出: false
解释: 不能用所有火柴拼成一个正方形。
注意:
给定的火柴长度和在 0 到 10^9之间。
火柴数组的长度不超过15。
*/
class Solution {
public boolean makesquare(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q900.ReorderedPowerof2;
/**
* @QuestionId : 900
* @difficulty : Medium
* @Title : Reordered Power of 2
* @TranslatedTitle:重新排序得到 2 的幂
* @url : https://leetcode-cn.com/problems/reordered-power-of-2/
* @TranslatedContent:给定正整数 N ,我们按任何顺序(包括原始顺序)将数字重新排序,注意其前导数字不能为零。
如果我们可以通过上述方式得到 2 的幂,返回 true;否则,返回 false。
示例 1:
输入:1
输出:true
示例 2:
输入:10
输出:false
示例 3:
输入:16
输出:true
示例 4:
输入:24
输出:false
示例 5:
输入:46
输出:true
提示:
1 <= N <= 10^9
*/
class Solution {
public boolean reorderedPowerOf2(int N) {
}
}<file_sep>package com.LeetCode.code.q502.IPO;
/**
* @QuestionId : 502
* @difficulty : Hard
* @Title : IPO
* @TranslatedTitle:IPO
* @url : https://leetcode-cn.com/problems/ipo/
* @TranslatedContent:假设 力扣(LeetCode)即将开始其 IPO。为了以更高的价格将股票卖给风险投资公司,力扣 希望在 IPO 之前开展一些项目以增加其资本。 由于资源有限,它只能在 IPO 之前完成最多 k 个不同的项目。帮助 力扣 设计完成最多 k 个不同项目后得到最大总资本的方式。
给定若干个项目。对于每个项目 i,它都有一个纯利润 Pi,并且需要最小的资本 Ci 来启动相应的项目。最初,你有 W 资本。当你完成一个项目时,你将获得纯利润,且利润将被添加到你的总资本中。
总而言之,从给定项目中选择最多 k 个不同项目的列表,以最大化最终资本,并输出最终可获得的最多资本。
示例 1:
输入: k=2, W=0, Profits=[1,2,3], Capital=[0,1,1].
输出: 4
解释:
由于你的初始资本为 0,你尽可以从 0 号项目开始。
在完成后,你将获得 1 的利润,你的总资本将变为 1。
此时你可以选择开始 1 号或 2 号项目。
由于你最多可以选择两个项目,所以你需要完成 2 号项目以获得最大的资本。
因此,输出最后最大化的资本,为 0 + 1 + 3 = 4。
注意:
假设所有输入数字都是非负整数。
表示利润和资本的数组的长度不超过 50000。
答案保证在 32 位有符号整数范围内。
*/
class Solution {
public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) {
}
}<file_sep>package com.LeetCode.code.q264.UglyNumberII;
/**
* @QuestionId : 264
* @difficulty : Medium
* @Title : Ugly Number II
* @TranslatedTitle:丑数 II
* @url : https://leetcode-cn.com/problems/ugly-number-ii/
* @TranslatedContent:编写一个程序,找出第 n 个丑数。
丑数就是只包含质因数 2, 3, 5 的正整数。
示例:
输入: n = 10
输出: 12
解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。
说明:
1 是丑数。
n 不超过1690。
*/
class Solution {
public int nthUglyNumber(int n) {
}
}<file_sep>package com.LeetCode.code.q690.EmployeeImportance;
/**
* @QuestionId : 690
* @difficulty : Easy
* @Title : Employee Importance
* @TranslatedTitle:员工的重要性
* @url : https://leetcode-cn.com/problems/employee-importance/
* @TranslatedContent:给定一个保存员工信息的数据结构,它包含了员工唯一的id,重要度 和 直系下属的id。
比如,员工1是员工2的领导,员工2是员工3的领导。他们相应的重要度为15, 10, 5。那么员工1的数据结构是[1, 15, [2]],员工2的数据结构是[2, 10, [3]],员工3的数据结构是[3, 5, []]。注意虽然员工3也是员工1的一个下属,但是由于并不是直系下属,因此没有体现在员工1的数据结构中。
现在输入一个公司的所有员工信息,以及单个员工id,返回这个员工和他所有下属的重要度之和。
示例 1:
输入: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
输出: 11
解释:
员工1自身的重要度是5,他有两个直系下属2和3,而且2和3的重要度均为3。因此员工1的总重要度是 5 + 3 + 3 = 11。
注意:
一个员工最多有一个直系领导,但是可以有多个直系下属
员工数量不超过2000。
*/
/*
// Employee info
class Employee {
// It's the unique id of each node;
// unique id of this employee
public int id;
// the importance value of this employee
public int importance;
// the id of direct subordinates
public List<Integer> subordinates;
};
*/
class Solution {
public int getImportance(List<Employee> employees, int id) {
}
}<file_sep>package com.LeetCode.code.q575.DistributeCandies;
/**
* @QuestionId : 575
* @difficulty : Easy
* @Title : Distribute Candies
* @TranslatedTitle:分糖果
* @url : https://leetcode-cn.com/problems/distribute-candies/
* @TranslatedContent:给定一个偶数长度的数组,其中不同的数字代表着不同种类的糖果,每一个数字代表一个糖果。你需要把这些糖果平均分给一个弟弟和一个妹妹。返回妹妹可以获得的最大糖果的种类数。
示例 1:
输入: candies = [1,1,2,2,3,3]
输出: 3
解析: 一共有三种种类的糖果,每一种都有两个。
最优分配方案:妹妹获得[1,2,3],弟弟也获得[1,2,3]。这样使妹妹获得糖果的种类数最多。
示例 2 :
输入: candies = [1,1,2,3]
输出: 2
解析: 妹妹获得糖果[2,3],弟弟获得糖果[1,1],妹妹有两种不同的糖果,弟弟只有一种。这样使得妹妹可以获得的糖果种类数最多。
注意:
数组的长度为[2, 10,000],并且确定为偶数。
数组中数字的大小在范围[-100,000, 100,000]内。
*/
class Solution {
public int distributeCandies(int[] candies) {
}
}<file_sep>package com.LeetCode.code.q164.MaximumGap;
/**
* @QuestionId : 164
* @difficulty : Hard
* @Title : Maximum Gap
* @TranslatedTitle:最大间距
* @url : https://leetcode-cn.com/problems/maximum-gap/
* @TranslatedContent:给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。
如果数组元素个数小于 2,则返回 0。
示例 1:
输入: [3,6,9,1]
输出: 3
解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。
示例 2:
输入: [10]
输出: 0
解释: 数组元素个数小于 2,因此返回 0。
说明:
你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。
请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。
*/
class Solution {
public int maximumGap(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q1046.MaxConsecutiveOnesIII;
/**
* @QuestionId : 1046
* @difficulty : Medium
* @Title : Max Consecutive Ones III
* @TranslatedTitle:最大连续1的个数 III
* @url : https://leetcode-cn.com/problems/max-consecutive-ones-iii/
* @TranslatedContent:给定一个由若干 0 和 1 组成的数组 A,我们最多可以将 K 个值从 0 变成 1 。
返回仅包含 1 的最长(连续)子数组的长度。
示例 1:
输入:A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
输出:6
解释:
[1,1,1,0,0,1,1,1,1,1,1]
粗体数字从 0 翻转到 1,最长的子数组长度为 6。
示例 2:
输入:A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
输出:10
解释:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
粗体数字从 0 翻转到 1,最长的子数组长度为 10。
提示:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] 为 0 或 1
*/
class Solution {
public int longestOnes(int[] A, int K) {
}
}<file_sep>package com.LeetCode.code.q88.MergeSortedArray;
/**
* @QuestionId : 88
* @difficulty : Easy
* @Title : Merge Sorted Array
* @TranslatedTitle:合并两个有序数组
* @url : https://leetcode-cn.com/problems/merge-sorted-array/
* @TranslatedContent:给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:
输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
输出: [1,2,2,3,5,6]
*/
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
}
}<file_sep>package com.LeetCode.code.q896.SmallestSubtreewithalltheDeepestNodes;
/**
* @QuestionId : 896
* @difficulty : Medium
* @Title : Smallest Subtree with all the Deepest Nodes
* @TranslatedTitle:具有所有最深结点的最小子树
* @url : https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes/
* @TranslatedContent:给定一个根为 root 的二叉树,每个结点的深度是它到根的最短距离。
如果一个结点在整个树的任意结点之间具有最大的深度,则该结点是最深的。
一个结点的子树是该结点加上它的所有后代的集合。
返回能满足“以该结点为根的子树中包含所有最深的结点”这一条件的具有最大深度的结点。
示例:
输入:[3,5,1,6,2,0,8,null,null,7,4]
输出:[2,7,4]
解释:
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/01/sketch1.png" style="height: 238px; width: 280px;">
我们返回值为 2 的结点,在图中用黄色标记。
在图中用蓝色标记的是树的最深的结点。
输入 "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" 是对给定的树的序列化表述。
输出 "[2, 7, 4]" 是对根结点的值为 2 的子树的序列化表述。
输入和输出都具有 TreeNode 类型。
提示:
树中结点的数量介于 1 和 500 之间。
每个结点的值都是独一无二的。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode subtreeWithAllDeepest(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q813.AllPathsFromSourcetoTarget;
/**
* @QuestionId : 813
* @difficulty : Medium
* @Title : All Paths From Source to Target
* @TranslatedTitle:所有可能的路径
* @url : https://leetcode-cn.com/problems/all-paths-from-source-to-target/
* @TranslatedContent:给一个有 n 个结点的有向无环图,找到所有从 0 到 n-1 的路径并输出(不要求按顺序)
二维数组的第 i 个数组中的单元都表示有向图中 i 号结点所能到达的下一些结点(译者注:有向图是有方向的,即规定了a→b你就不能从b→a)空就是没有下一个结点了。
示例:
输入: [[1,2], [3], [3], []]
输出: [[0,1,3],[0,2,3]]
解释: 图是这样的:
0--->1
| |
v v
2--->3
这有两条路: 0 -> 1 -> 3 和 0 -> 2 -> 3.
提示:
结点的数量会在范围 [2, 15] 内。
你可以把路径以任意顺序输出,但在路径内的结点的顺序必须保证。
*/
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
}
}<file_sep>package com.LeetCode.code.q757.PyramidTransitionMatrix;
/**
* @QuestionId : 757
* @difficulty : Medium
* @Title : Pyramid Transition Matrix
* @TranslatedTitle:金字塔转换矩阵
* @url : https://leetcode-cn.com/problems/pyramid-transition-matrix/
* @TranslatedContent:现在,我们用一些方块来堆砌一个金字塔。 每个方块用仅包含一个字母的字符串表示,例如 “Z”。
使用三元组表示金字塔的堆砌规则如下:
(A, B, C) 表示,“C”为顶层方块,方块“A”、“B”分别作为方块“C”下一层的的左、右子块。当且仅当(A, B, C)是被允许的三元组,我们才可以将其堆砌上。
初始时,给定金字塔的基层 bottom,用一个字符串表示。一个允许的三元组列表 allowed,每个三元组用一个长度为 3 的字符串表示。
如果可以由基层一直堆到塔尖返回true,否则返回false。
示例 1:
输入: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"]
输出: true
解析:
可以堆砌成这样的金字塔:
A
/ \
D E
/ \ / \
X Y Z
因为符合('X', 'Y', 'D'), ('Y', 'Z', 'E') 和 ('D', 'E', 'A') 三种规则。
示例 2:
输入: bottom = "XXYX", allowed = ["XXX", "XXY", "XYX", "XYY", "YXZ"]
输出: false
解析:
无法一直堆到塔尖。
注意, 允许存在三元组(A, B, C)和 (A, B, D) ,其中 C != D.
注意:
bottom 的长度范围在 [2, 8]。
allowed 的长度范围在[0, 200]。
方块的标记字母范围为{'A', 'B', 'C', 'D', 'E', 'F', 'G'}。
*/
class Solution {
public boolean pyramidTransition(String bottom, List<String> allowed) {
}
}<file_sep>package com.LeetCode.code.q662.MaximumWidthofBinaryTree;
/**
* @QuestionId : 662
* @difficulty : Medium
* @Title : Maximum Width of Binary Tree
* @TranslatedTitle:二叉树最大宽度
* @url : https://leetcode-cn.com/problems/maximum-width-of-binary-tree/
* @TranslatedContent:给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。
每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。
示例 1:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: 4
解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。
示例 2:
输入:
1
/
3
/ \
5 3
输出: 2
解释: 最大值出现在树的第 3 层,宽度为 2 (5,3)。
示例 3:
输入:
1
/ \
3 2
/
5
输出: 2
解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)。
示例 4:
输入:
1
/ \
3 2
/ \
5 9
/ \
6 7
输出: 8
解释: 最大值出现在树的第 4 层,宽度为 8 (6,null,null,null,null,null,null,7)。
注意: 答案在32位有符号整数的表示范围内。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int widthOfBinaryTree(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q1139.PreviousPermutationWithOneSwap;
/**
* @QuestionId : 1139
* @difficulty : Medium
* @Title : Previous Permutation With One Swap
* @TranslatedTitle:交换一次的先前排列
* @url : https://leetcode-cn.com/problems/previous-permutation-with-one-swap/
* @TranslatedContent:给你一个正整数的数组 A(其中的元素不一定完全不同),请你返回可在 一次交换(交换两数字 A[i] 和 A[j] 的位置)后得到的、按字典序排列小于 A 的最大可能排列。
如果无法这么操作,就请返回原数组。
示例 1:
输入:[3,2,1]
输出:[3,1,2]
解释:
交换 2 和 1
示例 2:
输入:[1,1,5]
输出:[1,1,5]
解释:
这已经是最小排列
示例 3:
输入:[1,9,4,6,7]
输出:[1,7,4,6,9]
解释:
交换 9 和 7
示例 4:
输入:[3,1,1,3]
输出:[1,3,1,3]
解释:
交换 1 和 3
提示:
1 <= A.length <= 10000
1 <= A[i] <= 10000
*/
class Solution {
public int[] prevPermOpt1(int[] A) {
}
}<file_sep>package com.LeetCode.code.q945.SnakesandLadders;
/**
* @QuestionId : 945
* @difficulty : Medium
* @Title : Snakes and Ladders
* @TranslatedTitle:蛇梯棋
* @url : https://leetcode-cn.com/problems/snakes-and-ladders/
* @TranslatedContent:在一块 N x N 的棋盘 board 上,从棋盘的左下角开始,每一行交替方向,按从 1 到 N*N 的数字给方格编号。例如,对于一块 6 x 6 大小的棋盘,可以编号如下:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/01/31/snakes.png" style="height: 200px; width: 254px;">
玩家从棋盘上的方格 1 (总是在最后一行、第一列)开始出发。
每一次从方格 x 起始的移动都由以下部分组成:
你选择一个目标方块 S,它的编号是 x+1,x+2,x+3,x+4,x+5,或者 x+6,只要这个数字 <= N*N。
如果 S 有一个蛇或梯子,你就移动到那个蛇或梯子的目的地。否则,你会移动到 S。
在 r 行 c 列上的方格里有 “蛇” 或 “梯子”;如果 board[r][c] != -1,那个蛇或梯子的目的地将会是 board[r][c]。
注意,你每次移动最多只能爬过蛇或梯子一次:就算目的地是另一条蛇或梯子的起点,你也不会继续移动。
返回达到方格 N*N 所需的最少移动次数,如果不可能,则返回 -1。
示例:
输入:[
[-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1],
[-1,-1,-1,-1,-1,-1],
[-1,35,-1,-1,13,-1],
[-1,-1,-1,-1,-1,-1],
[-1,15,-1,-1,-1,-1]]
输出:4
解释:
首先,从方格 1 [第 5 行,第 0 列] 开始。
你决定移动到方格 2,并必须爬过梯子移动到到方格 15。
然后你决定移动到方格 17 [第 3 行,第 5 列],必须爬过蛇到方格 13。
然后你决定移动到方格 14,且必须通过梯子移动到方格 35。
然后你决定移动到方格 36, 游戏结束。
可以证明你需要至少 4 次移动才能到达第 N*N 个方格,所以答案是 4。
提示:
2 <= board.length = board[0].length <= 20
board[i][j] 介于 1 和 N*N 之间或者等于 -1。
编号为 1 的方格上没有蛇或梯子。
编号为 N*N 的方格上没有蛇或梯子。
*/
class Solution {
public int snakesAndLadders(int[][] board) {
}
}<file_sep>package com.LeetCode.code.q96.UniqueBinarySearchTrees;
/**
* @QuestionId : 96
* @difficulty : Medium
* @Title : Unique Binary Search Trees
* @TranslatedTitle:不同的二叉搜索树
* @url : https://leetcode-cn.com/problems/unique-binary-search-trees/
* @TranslatedContent:给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
示例:
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
*/
class Solution {
public int numTrees(int n) {
}
}<file_sep>package com.LeetCode.code.q508.MostFrequentSubtreeSum;
/**
* @QuestionId : 508
* @difficulty : Medium
* @Title : Most Frequent Subtree Sum
* @TranslatedTitle:出现次数最多的子树元素和
* @url : https://leetcode-cn.com/problems/most-frequent-subtree-sum/
* @TranslatedContent:给出二叉树的根,找出出现次数最多的子树元素和。一个结点的子树元素和定义为以该结点为根的二叉树上所有结点的元素之和(包括结点本身)。然后求出出现次数最多的子树元素和。如果有多个元素出现的次数相同,返回所有出现次数最多的元素(不限顺序)。
示例 1
输入:
5
/ \
2 -3
返回 [2, -3, 4],所有的值均只出现一次,以任意顺序返回所有值。
示例 2
输入:
5
/ \
2 -5
返回 [2],只有 2 出现两次,-5 只出现 1 次。
提示: 假设任意子树元素和均可以用 32 位有符号整数表示。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int[] findFrequentTreeSum(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q566.ReshapetheMatrix;
/**
* @QuestionId : 566
* @difficulty : Easy
* @Title : Reshape the Matrix
* @TranslatedTitle:重塑矩阵
* @url : https://leetcode-cn.com/problems/reshape-the-matrix/
* @TranslatedContent:在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。
给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
示例 1:
输入:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
输出:
[[1,2,3,4]]
解释:
行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。
示例 2:
输入:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
输出:
[[1,2],
[3,4]]
解释:
没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 所以输出原矩阵。
注意:
给定矩阵的宽和高范围在 [1, 100]。
给定的 r 和 c 都是正数。
*/
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
}
}<file_sep>package com.LeetCode.code.q110.BalancedBinaryTree;
/**
* @QuestionId : 110
* @difficulty : Easy
* @Title : Balanced Binary Tree
* @TranslatedTitle:平衡二叉树
* @url : https://leetcode-cn.com/problems/balanced-binary-tree/
* @TranslatedContent:给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q781.BasicCalculatorIV;
/**
* @QuestionId : 781
* @difficulty : Hard
* @Title : Basic Calculator IV
* @TranslatedTitle:基本计算器 IV
* @url : https://leetcode-cn.com/problems/basic-calculator-iv/
* @TranslatedContent:给定一个表达式 expression 如 expression = "e + 8 - a + 5" 和一个求值映射,如 {"e": 1}(给定的形式为 evalvars = ["e"] 和 evalints = [1]),返回表示简化表达式的标记列表,例如 ["-1*a","14"]
表达式交替使用块和符号,每个块和符号之间有一个空格。
块要么是括号中的表达式,要么是变量,要么是非负整数。
块是括号中的表达式,变量或非负整数。
变量是一个由小写字母组成的字符串(不包括数字)。请注意,变量可以是多个字母,并注意变量从不具有像 "2x" 或 "-x" 这样的前导系数或一元运算符 。
表达式按通常顺序进行求值:先是括号,然后求乘法,再计算加法和减法。例如,expression = "1 + 2 * 3" 的答案是 ["7"]。
输出格式如下:
对于系数非零的每个自变量项,我们按字典排序的顺序将自变量写在一个项中。例如,我们永远不会写像 “b*a*c” 这样的项,只写 “a*b*c”。
项的次数等于被乘的自变量的数目,并计算重复项。(例如,"a*a*b*c" 的次数为 4。)。我们先写出答案的最大次数项,用字典顺序打破关系,此时忽略词的前导系数。
项的前导系数直接放在左边,用星号将它与变量分隔开(如果存在的话)。前导系数 1 仍然要打印出来。
格式良好的一个示例答案是 ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] 。
系数为 0 的项(包括常数项)不包括在内。例如,“0” 的表达式输出为 []。
示例:
输入:expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
输出:["-1*a","14"]
输入:expression = "e - 8 + temperature - pressure",
evalvars = ["e", "temperature"], evalints = [1, 12]
输出:["-1*pressure","5"]
输入:expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
输出:["1*e*e","-64"]
输入:expression = "7 - 7", evalvars = [], evalints = []
输出:[]
输入:expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
输出:["5*a*b*c"]
输入:expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))",
evalvars = [], evalints = []
输出:["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c","1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b","2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"]
提示:
expression 的长度在 [1, 250] 范围内。
evalvars, evalints 在范围 [0, 100] 内,且长度相同。
*/
class Solution {
public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {
}
}<file_sep>package com.LeetCode.code.q410.SplitArrayLargestSum;
/**
* @QuestionId : 410
* @difficulty : Hard
* @Title : Split Array Largest Sum
* @TranslatedTitle:分割数组的最大值
* @url : https://leetcode-cn.com/problems/split-array-largest-sum/
* @TranslatedContent:给定一个非负整数数组和一个整数 m,你需要将这个数组分成 m 个非空的连续子数组。设计一个算法使得这 m 个子数组各自和的最大值最小。
注意:<br />
数组长度 n 满足以下条件:
1 ≤ n ≤ 1000
1 ≤ m ≤ min(50, n)
示例:
输入:
nums = [7,2,5,10,8]
m = 2
输出:
18
解释:
一共有四种方法将nums分割为2个子数组。
其中最好的方式是将其分为[7,2,5] 和 [10,8],
因为此时这两个子数组各自的和的最大值为18,在所有情况中最小。
*/
class Solution {
public int splitArray(int[] nums, int m) {
}
}<file_sep>package com.LeetCode.code.q145.BinaryTreePostorderTraversal;
/**
* @QuestionId : 145
* @difficulty : Hard
* @Title : Binary Tree Postorder Traversal
* @TranslatedTitle:二叉树的后序遍历
* @url : https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
* @TranslatedContent:给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q133.CloneGraph;
/**
* @QuestionId : 133
* @difficulty : Medium
* @Title : Clone Graph
* @TranslatedTitle:克隆图
* @url : https://leetcode-cn.com/problems/clone-graph/
* @TranslatedContent:给定无向<a href="https://baike.baidu.com/item/连通图/6460995?fr=aladdin" target="_blank">连通图中一个节点的引用,返回该图的<a href="https://baike.baidu.com/item/深拷贝/22785317?fr=aladdin" target="_blank">深拷贝(克隆)。图中的每个节点都包含它的值 val(Int) 和其邻居的列表(list[Node])。
示例:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/23/113_sample.png" style="height: 149px; width: 200px;">
输入:
{"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1}
解释:
节点 1 的值是 1,它有两个邻居:节点 2 和 4 。
节点 2 的值是 2,它有两个邻居:节点 1 和 3 。
节点 3 的值是 3,它有两个邻居:节点 2 和 4 。
节点 4 的值是 4,它有两个邻居:节点 1 和 3 。
提示:
节点数介于 1 到 100 之间。
无向图是一个<a href="https://baike.baidu.com/item/简单图/1680528?fr=aladdin" target="_blank">简单图,这意味着图中没有重复的边,也没有自环。
由于图是无向的,如果节点 p 是节点 q 的邻居,那么节点 q 也必须是节点 p 的邻居。
必须将给定节点的拷贝作为对克隆图的引用返回。
*/
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {}
public Node(int _val,List<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public Node cloneGraph(Node node) {
}
}<file_sep>package com.LeetCode.code.q1104.ColoringABorder;
/**
* @QuestionId : 1104
* @difficulty : Medium
* @Title : Coloring A Border
* @TranslatedTitle:边框着色
* @url : https://leetcode-cn.com/problems/coloring-a-border/
* @TranslatedContent:给出一个二维整数网格 grid,网格中的每个值表示该位置处的网格块的颜色。
只有当两个网格块的颜色相同,而且在四个方向中任意一个方向上相邻时,它们属于同一连通分量。
连通分量的边界是指连通分量中的所有与不在分量中的正方形相邻(四个方向上)的所有正方形,或者在网格的边界上(第一行/列或最后一行/列)的所有正方形。
给出位于 (r0, c0) 的网格块和颜色 color,使用指定颜色 color 为所给网格块的连通分量的边界进行着色,并返回最终的网格 grid 。
示例 1:
输入:grid = [[1,1],[1,2]], r0 = 0, c0 = 0, color = 3
输出:[[3, 3], [3, 2]]
示例 2:
输入:grid = [[1,2,2],[2,3,2]], r0 = 0, c0 = 1, color = 3
输出:[[1, 3, 3], [2, 3, 3]]
示例 3:
输入:grid = [[1,1,1],[1,1,1],[1,1,1]], r0 = 1, c0 = 1, color = 2
输出:[[2, 2, 2], [2, 1, 2], [2, 2, 2]]
提示:
1 <= grid.length <= 50
1 <= grid[0].length <= 50
1 <= grid[i][j] <= 1000
0 <= r0 < grid.length
0 <= c0 < grid[0].length
1 <= color <= 1000
*/
class Solution {
public int[][] colorBorder(int[][] grid, int r0, int c0, int color) {
}
}<file_sep>package com.LeetCode.code.q1260.DayoftheYear;
/**
* @QuestionId : 1260
* @difficulty : Easy
* @Title : Day of the Year
* @TranslatedTitle:一年中的第几天
* @url : https://leetcode-cn.com/problems/ordinal-number-of-date/
* @TranslatedContent:给你一个按 YYYY-MM-DD 格式表示日期的字符串 date,请你计算并返回该日期是当年的第几天。
通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。每个月的天数与现行公元纪年法(格里高利历)一致。
示例 1:
输入:date = "2019-01-09"
输出:9
示例 2:
输入:date = "2019-02-10"
输出:41
示例 3:
输入:date = "2003-03-01"
输出:60
示例 4:
输入:date = "2004-03-01"
输出:61
提示:
date.length == 10
date[4] == date[7] == '-',其他的 date[i] 都是数字。
date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日。
*/
class Solution {
public int dayOfYear(String date) {
}
}<file_sep>package com.LeetCode.code.q646.MaximumLengthofPairChain;
/**
* @QuestionId : 646
* @difficulty : Medium
* @Title : Maximum Length of Pair Chain
* @TranslatedTitle:最长数对链
* @url : https://leetcode-cn.com/problems/maximum-length-of-pair-chain/
* @TranslatedContent:给出 n 个数对。 在每一个数对中,第一个数字总是比第二个数字小。
现在,我们定义一种跟随关系,当且仅当 b < c 时,数对(c, d) 才可以跟在 (a, b) 后面。我们用这种形式来构造一个数对链。
给定一个对数集合,找出能够形成的最长数对链的长度。你不需要用到所有的数对,你可以以任何顺序选择其中的一些数对来构造。
示例 :
输入: [[1,2], [2,3], [3,4]]
输出: 2
解释: 最长的数对链是 [1,2] -> [3,4]
注意:
给出数对的个数在 [1, 1000] 范围内。
*/
class Solution {
public int findLongestChain(int[][] pairs) {
}
}<file_sep>package com.LeetCode.code.q629.KInversePairsArray;
/**
* @QuestionId : 629
* @difficulty : Hard
* @Title : K Inverse Pairs Array
* @TranslatedTitle:K个逆序对数组
* @url : https://leetcode-cn.com/problems/k-inverse-pairs-array/
* @TranslatedContent:给出两个整数 n 和 k,找出所有包含从 1 到 n 的数字,且恰好拥有 k 个逆序对的不同的数组的个数。
逆序对的定义如下:对于数组的第i个和第 j个元素,如果满i < j且 a[i] > a[j],则其为一个逆序对;否则不是。
由于答案可能很大,只需要返回 答案 mod 109 + 7 的值。
示例 1:
输入: n = 3, k = 0
输出: 1
解释:
只有数组 [1,2,3] 包含了从1到3的整数并且正好拥有 0 个逆序对。
示例 2:
输入: n = 3, k = 1
输出: 2
解释:
数组 [1,3,2] 和 [2,1,3] 都有 1 个逆序对。
说明:
n 的范围是 [1, 1000] 并且 k 的范围是 [0, 1000]。
*/
class Solution {
public int kInversePairs(int n, int k) {
}
}<file_sep>package com.LeetCode.code.q85.MaximalRectangle;
/**
* @QuestionId : 85
* @difficulty : Hard
* @Title : Maximal Rectangle
* @TranslatedTitle:最大矩形
* @url : https://leetcode-cn.com/problems/maximal-rectangle/
* @TranslatedContent:给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例:
输入:
[
["1","0","1","0","0"],
["1","0","1","1","1"],
["1","1","1","1","1"],
["1","0","0","1","0"]
]
输出: 6
*/
class Solution {
public int maximalRectangle(char[][] matrix) {
}
}<file_sep>package com.LeetCode.code.q917.BoatstoSavePeople;
/**
* @QuestionId : 917
* @difficulty : Medium
* @Title : Boats to Save People
* @TranslatedTitle:救生艇
* @url : https://leetcode-cn.com/problems/boats-to-save-people/
* @TranslatedContent:第 i 个人的体重为 people[i],每艘船可以承载的最大重量为 limit。
每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。
返回载到每一个人所需的最小船数。(保证每个人都能被船载)。
示例 1:
输入:people = [1,2], limit = 3
输出:1
解释:1 艘船载 (1, 2)
示例 2:
输入:people = [3,2,2,1], limit = 3
输出:3
解释:3 艘船分别载 (1, 2), (2) 和 (3)
示例 3:
输入:people = [3,5,3,4], limit = 5
输出:4
解释:4 艘船分别载 (3), (3), (4), (5)
提示:
1 <= people.length <= 50000
1 <= people[i] <= limit <= 30000
*/
class Solution {
public int numRescueBoats(int[] people, int limit) {
}
}<file_sep>package com.LeetCode.code.q803.CheapestFlightsWithinKStops;
/**
* @QuestionId : 803
* @difficulty : Medium
* @Title : Cheapest Flights Within K Stops
* @TranslatedTitle:K 站中转内最便宜的航班
* @url : https://leetcode-cn.com/problems/cheapest-flights-within-k-stops/
* @TranslatedContent:有 n 个城市通过 m 个航班连接。每个航班都从城市 u 开始,以价格 w 抵达 v。
现在给定所有的城市和航班,以及出发城市 src 和目的地 dst,你的任务是找到从 src 到 dst 最多经过 k 站中转的最便宜的价格。 如果没有这样的路线,则输出 -1。
示例 1:
输入:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
输出: 200
解释:
城市航班图如下
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/16/995.png" style="height: 180px; width: 246px;">
从城市 0 到城市 2 在 1 站中转以内的最便宜价格是 200,如图中红色所示。
示例 2:
输入:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
输出: 500
解释:
城市航班图如下
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/16/995.png" style="height: 180px; width: 246px;">
从城市 0 到城市 2 在 0 站中转以内的最便宜价格是 500,如图中蓝色所示。
提示:
n 范围是 [1, 100],城市标签从 0 到 n - 1.
航班数量范围是 [0, n * (n - 1) / 2].
每个航班的格式 (src, dst, price).
每个航班的价格范围是 [1, 10000].
k 范围是 [0, n - 1].
航班没有重复,且不存在环路
*/
class Solution {
public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) {
}
}<file_sep>package com.LeetCode.code.q1037.MinimumNumberofKConsecutiveBitFlips;
/**
* @QuestionId : 1037
* @difficulty : Hard
* @Title : Minimum Number of K Consecutive Bit Flips
* @TranslatedTitle:K 连续位的最小翻转次数
* @url : https://leetcode-cn.com/problems/minimum-number-of-k-consecutive-bit-flips/
* @TranslatedContent:在仅包含 0 和 1 的数组 A 中,一次 K 位翻转包括选择一个长度为 K 的(连续)子数组,同时将子数组中的每个 0 更改为 1,而每个 1 更改为 0。
返回所需的 K 位翻转的次数,以便数组没有值为 0 的元素。如果不可能,返回 -1。
示例 1:
输入:A = [0,1,0], K = 1
输出:2
解释:先翻转 A[0],然后翻转 A[2]。
示例 2:
输入:A = [1,1,0], K = 2
输出:-1
解释:无论我们怎样翻转大小为 2 的子数组,我们都不能使数组变为 [1,1,1]。
示例 3:
输入:A = [0,0,0,1,0,1,1,0], K = 3
输出:3
解释:
翻转 A[0],A[1],A[2]: A变成 [1,1,1,1,0,1,1,0]
翻转 A[4],A[5],A[6]: A变成 [1,1,1,1,1,0,0,0]
翻转 A[5],A[6],A[7]: A变成 [1,1,1,1,1,1,1,1]
提示:
1 <= A.length <= 30000
1 <= K <= A.length
*/
class Solution {
public int minKBitFlips(int[] A, int K) {
}
}<file_sep>package com.LeetCode.code.q142.LinkedListCycleII;
/**
* @QuestionId : 142
* @difficulty : Medium
* @Title : Linked List Cycle II
* @TranslatedTitle:环形链表 II
* @url : https://leetcode-cn.com/problems/linked-list-cycle-ii/
* @TranslatedContent:给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist.png" style="height: 97px; width: 300px;">
示例 2:
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test2.png" style="height: 74px; width: 141px;">
示例 3:
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test3.png" style="height: 45px; width: 45px;">
进阶:
你是否可以不用额外空间解决此题?
*/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
}
}<file_sep>package com.LeetCode.code.q373.FindKPairswithSmallestSums;
/**
* @QuestionId : 373
* @difficulty : Medium
* @Title : Find K Pairs with Smallest Sums
* @TranslatedTitle:查找和最小的K对数字
* @url : https://leetcode-cn.com/problems/find-k-pairs-with-smallest-sums/
* @TranslatedContent:给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。
定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。
找到和最小的 k 对数字 (u1,v1), (u2,v2) ... (uk,vk)。
示例 1:
输入: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
输出: [1,2],[1,4],[1,6]
解释: 返回序列中的前 3 对数:
[1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
示例 2:
输入: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
输出: [1,1],[1,1]
解释: 返回序列中的前 2 对数:
[1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
示例 3:
输入: nums1 = [1,2], nums2 = [3], k = 3
输出: [1,3],[2,3]
解释: 也可能序列中所有的数对都被返回:[1,3],[2,3]
*/
class Solution {
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
}
}<file_sep>package com.LeetCode.code.q583.DeleteOperationforTwoStrings;
/**
* @QuestionId : 583
* @difficulty : Medium
* @Title : Delete Operation for Two Strings
* @TranslatedTitle:两个字符串的删除操作
* @url : https://leetcode-cn.com/problems/delete-operation-for-two-strings/
* @TranslatedContent:给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。
示例 1:
输入: "sea", "eat"
输出: 2
解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"
说明:
给定单词的长度不超过500。
给定单词中的字符只含有小写字母。
*/
class Solution {
public int minDistance(String word1, String word2) {
}
}<file_sep>package com.LeetCode.code.q591.TagValidator;
/**
* @QuestionId : 591
* @difficulty : Hard
* @Title : Tag Validator
* @TranslatedTitle:标签验证器
* @url : https://leetcode-cn.com/problems/tag-validator/
* @TranslatedContent:给定一个表示代码片段的字符串,你需要实现一个验证器来解析这段代码,并返回它是否合法。合法的代码片段需要遵守以下的所有规则:
代码必须被合法的闭合标签包围。否则,代码是无效的。
闭合标签(不一定合法)要严格符合格式:TAG_CONTENT。其中,是起始标签,是结束标签。起始和结束标签中的 TAG_NAME 应当相同。当且仅当 TAG_NAME 和 TAG_CONTENT 都是合法的,闭合标签才是合法的。
合法的 TAG_NAME 仅含有大写字母,长度在范围 [1,9] 之间。否则,该 TAG_NAME 是不合法的。
合法的 TAG_CONTENT 可以包含其他合法的闭合标签,cdata (请参考规则7)和任意字符(注意参考规则1)除了不匹配的<、不匹配的起始和结束标签、不匹配的或带有不合法 TAG_NAME 的闭合标签。否则,TAG_CONTENT 是不合法的。
一个起始标签,如果没有具有相同 TAG_NAME 的结束标签与之匹配,是不合法的。反之亦然。不过,你也需要考虑标签嵌套的问题。
一个<,如果你找不到一个后续的>与之匹配,是不合法的。并且当你找到一个<或</时,所有直到下一个>的前的字符,都应当被解析为 TAG_NAME(不一定合法)。
cdata 有如下格式:<![CDATA[CDATA_CONTENT]]>。CDATA_CONTENT 的范围被定义成 <![CDATA[ 和后续的第一个 ]]>之间的字符。
CDATA_CONTENT 可以包含任意字符。cdata 的功能是阻止验证器解析CDATA_CONTENT,所以即使其中有一些字符可以被解析为标签(无论合法还是不合法),也应该将它们视为常规字符。
合法代码的例子:
输入: "This is the first line <![CDATA[]]>"
输出: True
解释:
代码被包含在了闭合的标签内: 和 。
TAG_NAME 是合法的,TAG_CONTENT 包含了一些字符和 cdata 。
即使 CDATA_CONTENT 含有不匹配的起始标签和不合法的 TAG_NAME,它应该被视为普通的文本,而不是标签。
所以 TAG_CONTENT 是合法的,因此代码是合法的。最终返回True。
输入: ">> ![cdata[]] <![CDATA[]>]]>]]>>]"
输出: True
解释:
我们首先将代码分割为: start_tag|tag_content|end_tag 。
start_tag -> ""
end_tag -> ""
tag_content 也可被分割为: text1|cdata|text2 。
text1 -> ">> ![cdata[]] "
cdata -> "<![CDATA[]>]]>" ,其中 CDATA_CONTENT 为 "]>"
text2 -> "]]>>]"
start_tag 不是 ">>" 的原因参照规则 6 。
cdata 不是 "<![CDATA[]>]]>]]>" 的原因参照规则 7 。
不合法代码的例子:
输入: " "
输出: False
解释: 不合法。如果 "" 是闭合的,那么 "" 一定是不匹配的,反之亦然。
输入: " div tag is not closed "
输出: False
输入: " unmatched < "
输出: False
输入: " closed tags with invalid tag name 123 "
输出: False
输入: " unmatched tags with invalid tag name and <CDATA[[]]> "
输出: False
输入: " unmatched start tag and unmatched end tag "
输出: False
注意:
为简明起见,你可以假设输入的代码(包括提到的任意字符)只包含数字, <font color="#c7254e" face="Menlo, Monaco, Consolas, Courier New, monospace"><span style="background-color:#f9f2f4; font-size:12.6px">字母, '<','>','/','!','[',']'和' '。
*/
class Solution {
public boolean isValid(String code) {
}
}<file_sep>package com.LeetCode.code.q563.BinaryTreeTilt;
/**
* @QuestionId : 563
* @difficulty : Easy
* @Title : Binary Tree Tilt
* @TranslatedTitle:二叉树的坡度
* @url : https://leetcode-cn.com/problems/binary-tree-tilt/
* @TranslatedContent:给定一个二叉树,计算整个树的坡度。
一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。
整个树的坡度就是其所有节点的坡度之和。
示例:
输入:
1
/ \
2 3
输出: 1
解释:
结点的坡度 2 : 0
结点的坡度 3 : 0
结点的坡度 1 : |2-3| = 1
树的坡度 : 0 + 0 + 1 = 1
注意:
任何子树的结点的和不会超过32位整数的范围。
坡度的值不会超过32位整数的范围。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findTilt(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q417.PacificAtlanticWaterFlow;
/**
* @QuestionId : 417
* @difficulty : Medium
* @Title : Pacific Atlantic Water Flow
* @TranslatedTitle:太平洋大西洋水流问题
* @url : https://leetcode-cn.com/problems/pacific-atlantic-water-flow/
* @TranslatedContent:给定一个 m x n 的非负整数矩阵来表示一片大陆上各个单元格的高度。“太平洋”处于大陆的左边界和上边界,而“大西洋”处于大陆的右边界和下边界。
规定水流只能按照上、下、左、右四个方向流动,且只能从高到低或者在同等高度上流动。
请找出那些水流既可以流动到“太平洋”,又能流动到“大西洋”的陆地单元的坐标。
提示:
输出坐标的顺序不重要
m 和 n 都小于150
示例:
给定下面的 5x5 矩阵:
太平洋 ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * 大西洋
返回:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (上图中带括号的单元).
*/
class Solution {
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
}
}<file_sep>package com.LeetCode.code.q498.DiagonalTraverse;
/**
* @QuestionId : 498
* @difficulty : Medium
* @Title : Diagonal Traverse
* @TranslatedTitle:对角线遍历
* @url : https://leetcode-cn.com/problems/diagonal-traverse/
* @TranslatedContent:给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。
示例:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,4,7,5,3,6,8,9]
解释:
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/diagonal_traverse.png" style="width: 220px;">
说明:
给定矩阵中的元素总数不会超过 100000 。
*/
class Solution {
public int[] findDiagonalOrder(int[][] matrix) {
}
}<file_sep>package com.LeetCode.code.q461.HammingDistance;
/**
* @QuestionId : 461
* @difficulty : Easy
* @Title : Hamming Distance
* @TranslatedTitle:汉明距离
* @url : https://leetcode-cn.com/problems/hamming-distance/
* @TranslatedContent:两个整数之间的<a href="https://baike.baidu.com/item/%E6%B1%89%E6%98%8E%E8%B7%9D%E7%A6%BB">汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x 和 y,计算它们之间的汉明距离。
注意:<br />
0 ≤ x, y < 231.
示例:
输入: x = 1, y = 4
输出: 2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
上面的箭头指出了对应二进制位不同的位置。
*/
class Solution {
public int hammingDistance(int x, int y) {
}
}<file_sep>package com.LeetCode.code.q565.ArrayNesting;
/**
* @QuestionId : 565
* @difficulty : Medium
* @Title : Array Nesting
* @TranslatedTitle:数组嵌套
* @url : https://leetcode-cn.com/problems/array-nesting/
* @TranslatedContent:索引从0开始长度为N的数组A,包含0到N - 1的所有整数。找到并返回最大的集合S,S[i] = {A[i], A[A[i]], A[A[A[i]]], ... }且遵守以下的规则。
假设选择索引为i的元素A[i]为S的第一个元素,S的下一个元素应该是A[A[i]],之后是A[A[A[i]]]... 以此类推,不断添加直到S出现重复的元素。
示例 1:
输入: A = [5,4,0,3,1,6,2]
输出: 4
解释:
A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
其中一种最长的 S[K]:
S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
注意:
N是[1, 20,000]之间的整数。
A中不含有重复的元素。
A中的元素大小在[0, N-1]之间。
*/
class Solution {
public int arrayNesting(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q936.RLEIterator;
/**
* @QuestionId : 936
* @difficulty : Medium
* @Title : RLE Iterator
* @TranslatedTitle:RLE 迭代器
* @url : https://leetcode-cn.com/problems/rle-iterator/
* @TranslatedContent:编写一个遍历游程编码序列的迭代器。
迭代器由 RLEIterator(int[] A) 初始化,其中 A 是某个序列的游程编码。更具体地,对于所有偶数 i,A[i] 告诉我们在序列中重复非负整数值 A[i + 1] 的次数。
迭代器支持一个函数:next(int n),它耗尽接下来的 n 个元素(n >= 1)并返回以这种方式耗去的最后一个元素。如果没有剩余的元素可供耗尽,则 next 返回 -1 。
例如,我们以 A = [3,8,0,9,2,5] 开始,这是序列 [8,8,8,5,5] 的游程编码。这是因为该序列可以读作 “三个八,零个九,两个五”。
示例:
输入:["RLEIterator","next","next","next","next"], [[[3,8,0,9,2,5]],[2],[1],[1],[2]]
输出:[null,8,8,5,-1]
解释:
RLEIterator 由 RLEIterator([3,8,0,9,2,5]) 初始化。
这映射到序列 [8,8,8,5,5]。
然后调用 RLEIterator.next 4次。
.next(2) 耗去序列的 2 个项,返回 8。现在剩下的序列是 [8, 5, 5]。
.next(1) 耗去序列的 1 个项,返回 8。现在剩下的序列是 [5, 5]。
.next(1) 耗去序列的 1 个项,返回 5。现在剩下的序列是 [5]。
.next(2) 耗去序列的 2 个项,返回 -1。 这是由于第一个被耗去的项是 5,
但第二个项并不存在。由于最后一个要耗去的项不存在,我们返回 -1。
提示:
0 <= A.length <= 1000
A.length 是偶数。
0 <= A[i] <= 10^9
每个测试用例最多调用 1000 次 RLEIterator.next(int n)。
每次调用 RLEIterator.next(int n) 都有 1 <= n <= 10^9 。
*/
class RLEIterator {
public RLEIterator(int[] A) {
}
public int next(int n) {
}
}
/**
* Your RLEIterator object will be instantiated and called as such:
* RLEIterator obj = new RLEIterator(A);
* int param_1 = obj.next(n);
*/<file_sep>package com.LeetCode.code.q389.FindtheDifference;
/**
* @QuestionId : 389
* @difficulty : Easy
* @Title : Find the Difference
* @TranslatedTitle:找不同
* @url : https://leetcode-cn.com/problems/find-the-difference/
* @TranslatedContent:给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:
s = "abcd"
t = "abcde"
输出:
e
解释:
'e' 是那个被添加的字母。
*/
class Solution {
public char findTheDifference(String s, String t) {
}
}<file_sep>package com.LeetCode.code.q784.InsertintoaBinarySearchTree;
/**
* @QuestionId : 784
* @difficulty : Medium
* @Title : Insert into a Binary Search Tree
* @TranslatedTitle:二叉搜索树中的插入操作
* @url : https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/
* @TranslatedContent:给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 保证原始二叉搜索树中不存在新值。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
例如,
给定二叉搜索树:
4
/ \
2 7
/ \
1 3
和 插入的值: 5
你可以返回这个二叉搜索树:
4
/ \
2 7
/ \ /
1 3 5
或者这个树也是有效的:
5
/ \
2 7
/ \
1 3
\
4
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
}
}<file_sep>package com.LeetCode.code.q535.EncodeandDecodeTinyURL;
/**
* @QuestionId : 535
* @difficulty : Medium
* @Title : Encode and Decode TinyURL
* @TranslatedTitle:TinyURL 的加密与解密
* @url : https://leetcode-cn.com/problems/encode-and-decode-tinyurl/
* @TranslatedContent:TinyURL是一种URL简化服务, 比如:当你输入一个URL https://leetcode.com/problems/design-tinyurl 时,它将返回一个简化的URL http://tinyurl.com/4e9iAk.
要求:设计一个 TinyURL 的加密 encode 和解密 decode 的方法。你的加密和解密算法如何设计和运作是没有限制的,你只需要保证一个URL可以被加密成一个TinyURL,并且这个TinyURL可以用解密方法恢复成原本的URL。
*/
public class Codec {
// Encodes a URL to a shortened URL.
public String encode(String longUrl) {
}
// Decodes a shortened URL to its original URL.
public String decode(String shortUrl) {
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));<file_sep>package com.LeetCode.code.q481.MagicalString;
/**
* @QuestionId : 481
* @difficulty : Medium
* @Title : Magical String
* @TranslatedTitle:神奇字符串
* @url : https://leetcode-cn.com/problems/magical-string/
* @TranslatedContent:神奇的字符串 S 只包含 '1' 和 '2',并遵守以下规则:
字符串 S 是神奇的,因为串联字符 '1' 和 '2' 的连续出现次数会生成字符串 S 本身。
字符串 S 的前几个元素如下:S = “1221121221221121122 ......”
如果我们将 S 中连续的 1 和 2 进行分组,它将变成:
1 22 11 2 1 22 1 22 11 2 11 22 ......
并且每个组中 '1' 或 '2' 的出现次数分别是:
1 2 2 1 1 2 1 2 2 1 2 2 ......
你可以看到上面的出现次数就是 S 本身。
给定一个整数 N 作为输入,返回神奇字符串 S 中前 N 个数字中的 '1' 的数目。
注意:N 不会超过 100,000。
示例:
输入:6
输出:3
解释:神奇字符串 S 的前 6 个元素是 “12211”,它包含三个 1,因此返回 3。
*/
class Solution {
public int magicalString(int n) {
}
}<file_sep>package com.LeetCode.code.q4.MedianofTwoSortedArrays;
/**
* @QuestionId : 4
* @difficulty : Hard
* @Title : Median of Two Sorted Arrays
* @TranslatedTitle:寻找两个有序数组的中位数
* @url : https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
* @TranslatedContent:给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
*/
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
}
}<file_sep>package com.LeetCode.code.q381.InsertDeleteGetRandomO(1)-Duplicatesallowed;
/**
* @QuestionId : 381
* @difficulty : Hard
* @Title : Insert Delete GetRandom O(1) - Duplicates allowed
* @TranslatedTitle:O(1) 时间插入、删除和获取随机元素 - 允许重复
* @url : https://leetcode-cn.com/problems/insert-delete-getrandom-o1-duplicates-allowed/
* @TranslatedContent:设计一个支持在平均 时间复杂度 O(1) 下, 执行以下操作的数据结构。
注意: 允许出现重复元素。
insert(val):向集合中插入元素 val。
remove(val):当 val 存在时,从集合中移除一个 val。
getRandom:从现有集合中随机获取一个元素。每个元素被返回的概率应该与其在集合中的数量呈线性相关。
示例:
// 初始化一个空的集合。
RandomizedCollection collection = new RandomizedCollection();
// 向集合中插入 1 。返回 true 表示集合不包含 1 。
collection.insert(1);
// 向集合中插入另一个 1 。返回 false 表示集合包含 1 。集合现在包含 [1,1] 。
collection.insert(1);
// 向集合中插入 2 ,返回 true 。集合现在包含 [1,1,2] 。
collection.insert(2);
// getRandom 应当有 2/3 的概率返回 1 ,1/3 的概率返回 2 。
collection.getRandom();
// 从集合中删除 1 ,返回 true 。集合现在包含 [1,2] 。
collection.remove(1);
// getRandom 应有相同概率返回 1 和 2 。
collection.getRandom();
*/
class RandomizedCollection {
/** Initialize your data structure here. */
public RandomizedCollection() {
}
/** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
public boolean insert(int val) {
}
/** Removes a value from the collection. Returns true if the collection contained the specified element. */
public boolean remove(int val) {
}
/** Get a random element from the collection. */
public int getRandom() {
}
}
/**
* Your RandomizedCollection object will be instantiated and called as such:
* RandomizedCollection obj = new RandomizedCollection();
* boolean param_1 = obj.insert(val);
* boolean param_2 = obj.remove(val);
* int param_3 = obj.getRandom();
*/<file_sep>package com.LeetCode.code.q75.SortColors;
/**
* @QuestionId : 75
* @difficulty : Medium
* @Title : Sort Colors
* @TranslatedTitle:颜色分类
* @url : https://leetcode-cn.com/problems/sort-colors/
* @TranslatedContent:给定一个包含红色、白色和蓝色,一共 n 个元素的数组,<a href="https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95" target="_blank">原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
你能想出一个仅使用常数空间的一趟扫描算法吗?
*/
class Solution {
public void sortColors(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q1030.SmallestStringStartingFromLeaf;
/**
* @QuestionId : 1030
* @difficulty : Medium
* @Title : Smallest String Starting From Leaf
* @TranslatedTitle:从叶结点开始的最小字符串
* @url : https://leetcode-cn.com/problems/smallest-string-starting-from-leaf/
* @TranslatedContent:给定一颗根结点为 root 的二叉树,书中的每个结点都有一个从 0 到 25 的值,分别代表字母 'a' 到 'z':值 0 代表 'a',值 1 代表 'b',依此类推。
找出按字典序最小的字符串,该字符串从这棵树的一个叶结点开始,到根结点结束。
(小贴士:字符串中任何较短的前缀在字典序上都是较小的:例如,在字典序上 "ab" 比 "aba" 要小。叶结点是指没有子结点的结点。)
示例 1:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/02/tree1.png" style="height: 107px; width: 160px;">
输入:[0,1,2,3,4,3,4]
输出:"dba"
示例 2:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/02/tree2.png" style="height: 107px; width: 160px;">
输入:[25,1,3,1,3,0,2]
输出:"adz"
示例 3:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/02/tree3.png" style="height: 180px; width: 172px;">
输入:[2,2,1,null,1,0,null,0]
输出:"abc"
提示:
给定树的结点数介于 1 和 8500 之间。
树中的每个结点都有一个介于 0 和 25 之间的值。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public String smallestFromLeaf(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q1018.LargestPerimeterTriangle;
/**
* @QuestionId : 1018
* @difficulty : Easy
* @Title : Largest Perimeter Triangle
* @TranslatedTitle:三角形的最大周长
* @url : https://leetcode-cn.com/problems/largest-perimeter-triangle/
* @TranslatedContent:给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。
如果不能形成任何面积不为零的三角形,返回 0。
示例 1:
输入:[2,1,2]
输出:5
示例 2:
输入:[1,2,1]
输出:0
示例 3:
输入:[3,2,3,4]
输出:10
示例 4:
输入:[3,6,2,3]
输出:8
提示:
3 <= A.length <= 10000
1 <= A[i] <= 10^6
*/
class Solution {
public int largestPerimeter(int[] A) {
}
}<file_sep>package com.LeetCode.code.q383.RansomNote;
/**
* @QuestionId : 383
* @difficulty : Easy
* @Title : Ransom Note
* @TranslatedTitle:赎金信
* @url : https://leetcode-cn.com/problems/ransom-note/
* @TranslatedContent:给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)
注意:
你可以假设两个字符串均只含有小写字母。
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
*/
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
}
}<file_sep>package com.LeetCode.code.q1087.LongestArithmeticSequence;
/**
* @QuestionId : 1087
* @difficulty : Medium
* @Title : Longest Arithmetic Sequence
* @TranslatedTitle:最长等差数列
* @url : https://leetcode-cn.com/problems/longest-arithmetic-sequence/
* @TranslatedContent:给定一个整数数组 A,返回 A 中最长等差子序列的长度。
回想一下,A 的子序列是列表 A[i_1], A[i_2], ..., A[i_k] 其中 0 <= i_1 < i_2 < ... < i_k <= A.length - 1。并且如果 B[i+1] - B[i]( 0 <= i < B.length - 1) 的值都相同,那么序列 B 是等差的。
示例 1:
输入:[3,6,9,12]
输出:4
解释:
整个数组是公差为 3 的等差数列。
示例 2:
输入:[9,4,7,2,10]
输出:3
解释:
最长的等差子序列是 [4,7,10]。
示例 3:
输入:[20,1,15,3,10,5,8]
输出:4
解释:
最长的等差子序列是 [20,15,10,5]。
提示:
2 <= A.length <= 2000
0 <= A[i] <= 10000
*/
class Solution {
public int longestArithSeqLength(int[] A) {
}
}<file_sep>package com.LeetCode.code.q448.FindAllNumbersDisappearedinanArray;
/**
* @QuestionId : 448
* @difficulty : Easy
* @Title : Find All Numbers Disappeared in an Array
* @TranslatedTitle:找到所有数组中消失的数字
* @url : https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/
* @TranslatedContent:给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例:
输入:
[4,3,2,7,8,2,3,1]
输出:
[5,6]
*/
class Solution {
public List<Integer> findDisappearedNumbers(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q873.GuesstheWord;
/**
* @QuestionId : 873
* @difficulty : Hard
* @Title : Guess the Word
* @TranslatedTitle:猜猜这个单词
* @url : https://leetcode-cn.com/problems/guess-the-word/
* @TranslatedContent:这个问题是 LeetCode 平台新增的交互式问题 。
我们给出了一个由一些独特的单词组成的单词列表,每个单词都是 6 个字母长,并且这个列表中的一个单词将被选作秘密。
你可以调用 master.guess(word) 来猜单词。你所猜的单词应当是存在于原列表并且由 6 个小写字母组成的类型字符串。
此函数将会返回一个整型数字,表示你的猜测与秘密单词的准确匹配(值和位置同时匹配)的数目。此外,如果你的猜测不在给定的单词列表中,它将返回 -1。
对于每个测试用例,你有 10 次机会来猜出这个单词。当所有调用都结束时,如果您对 master.guess 的调用不超过 10 次,并且至少有一次猜到秘密,那么您将通过该测试用例。
除了下面示例给出的测试用例外,还会有 5 个额外的测试用例,每个单词列表中将会有 100 个单词。这些测试用例中的每个单词的字母都是从 'a' 到 'z' 中随机选取的,并且保证给定单词列表中的每个单词都是唯一的。
示例 1:
输入: secret = "acckzz", wordlist = ["acckzz","ccbazz","eiowzz","abcczz"]
解释:
master.guess("aaaaaa") 返回 -1, 因为 "aaaaaa" 不在 wordlist 中.
master.guess("acckzz") 返回 6, 因为 "acckzz" 就是秘密,6个字母完全匹配。
master.guess("ccbazz") 返回 3, 因为 "ccbazz" 有 3 个匹配项。
master.guess("eiowzz") 返回 2, 因为 "eiowzz" 有 2 个匹配项。
master.guess("abcczz") 返回 4, 因为 "abcczz" 有 4 个匹配项。
我们调用了 5 次master.guess,其中一次猜到了秘密,所以我们通过了这个测试用例。
提示:任何试图绕过评判的解决方案都将导致比赛资格被取消。
*/
/**
* // This is the Master's API interface.
* // You should not implement it, or speculate about its implementation
* interface Master {
* public int guess(String word) {}
* }
*/
class Solution {
public void findSecretWord(String[] wordlist, Master master) {
}
}<file_sep>package com.LeetCode.code.q216.CombinationSumIII;
/**
* @QuestionId : 216
* @difficulty : Medium
* @Title : Combination Sum III
* @TranslatedTitle:组合总和 III
* @url : https://leetcode-cn.com/problems/combination-sum-iii/
* @TranslatedContent:找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
所有数字都是正整数。
解集不能包含重复的组合。
示例 1:
输入: k = 3, n = 7
输出: [[1,2,4]]
示例 2:
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
*/
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
}
}<file_sep>package com.LeetCode.code.q643.MaximumAverageSubarrayI;
/**
* @QuestionId : 643
* @difficulty : Easy
* @Title : Maximum Average Subarray I
* @TranslatedTitle:子数组最大平均数 I
* @url : https://leetcode-cn.com/problems/maximum-average-subarray-i/
* @TranslatedContent:给定 n 个整数,找出平均数最大且长度为 k 的连续子数组,并输出该最大平均数。
示例 1:
输入: [1,12,-5,-6,50,3], k = 4
输出: 12.75
解释: 最大平均数 (12-5-6+50)/4 = 51/4 = 12.75
注意:
1 <= k <= n <= 30,000。
所给数据范围 [-10,000,10,000]。
*/
class Solution {
public double findMaxAverage(int[] nums, int k) {
}
}<file_sep>package com.LeetCode.code.q987.RevealCardsInIncreasingOrder;
/**
* @QuestionId : 987
* @difficulty : Medium
* @Title : Reveal Cards In Increasing Order
* @TranslatedTitle:按递增顺序显示卡牌
* @url : https://leetcode-cn.com/problems/reveal-cards-in-increasing-order/
* @TranslatedContent:牌组中的每张卡牌都对应有一个唯一的整数。你可以按你想要的顺序对这套卡片进行排序。
最初,这些卡牌在牌组里是正面朝下的(即,未显示状态)。
现在,重复执行以下步骤,直到显示所有卡牌为止:
从牌组顶部抽一张牌,显示它,然后将其从牌组中移出。
如果牌组中仍有牌,则将下一张处于牌组顶部的牌放在牌组的底部。
如果仍有未显示的牌,那么返回步骤 1。否则,停止行动。
返回能以递增顺序显示卡牌的牌组顺序。
答案中的第一张牌被认为处于牌堆顶部。
示例:
输入:[17,13,11,2,3,5,7]
输出:[2,13,3,11,5,17,7]
解释:
我们得到的牌组顺序为 [17,13,11,2,3,5,7](这个顺序不重要),然后将其重新排序。
重新排序后,牌组以 [2,13,3,11,5,17,7] 开始,其中 2 位于牌组的顶部。
我们显示 2,然后将 13 移到底部。牌组现在是 [3,11,5,17,7,13]。
我们显示 3,并将 11 移到底部。牌组现在是 [5,17,7,13,11]。
我们显示 5,然后将 17 移到底部。牌组现在是 [7,13,11,17]。
我们显示 7,并将 13 移到底部。牌组现在是 [11,17,13]。
我们显示 11,然后将 17 移到底部。牌组现在是 [13,17]。
我们展示 13,然后将 17 移到底部。牌组现在是 [17]。
我们显示 17。
由于所有卡片都是按递增顺序排列显示的,所以答案是正确的。
提示:
1 <= A.length <= 1000
1 <= A[i] <= 10^6
对于所有的 i != j,A[i] != A[j]
*/
class Solution {
public int[] deckRevealedIncreasing(int[] deck) {
}
}<file_sep>package com.LeetCode.code.q856.ConsecutiveNumbersSum;
/**
* @QuestionId : 856
* @difficulty : Hard
* @Title : Consecutive Numbers Sum
* @TranslatedTitle:连续整数求和
* @url : https://leetcode-cn.com/problems/consecutive-numbers-sum/
* @TranslatedContent:给定一个正整数 N,试求有多少组连续正整数满足所有数字之和为 N?
示例 1:
输入: 5
输出: 2
解释: 5 = 5 = 2 + 3,共有两组连续整数([5],[2,3])求和后为 5。
示例 2:
输入: 9
输出: 3
解释: 9 = 9 = 4 + 5 = 2 + 3 + 4
示例 3:
输入: 15
输出: 4
解释: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
说明: 1 <= N <= 10 ^ 9
*/
class Solution {
public int consecutiveNumbersSum(int N) {
}
}<file_sep>package com.LeetCode.code.q930.AllPossibleFullBinaryTrees;
/**
* @QuestionId : 930
* @difficulty : Medium
* @Title : All Possible Full Binary Trees
* @TranslatedTitle:所有可能的满二叉树
* @url : https://leetcode-cn.com/problems/all-possible-full-binary-trees/
* @TranslatedContent:满二叉树是一类二叉树,其中每个结点恰好有 0 或 2 个子结点。
返回包含 N 个结点的所有可能满二叉树的列表。 答案的每个元素都是一个可能树的根结点。
答案中每个树的每个结点都必须有 node.val=0。
你可以按任何顺序返回树的最终列表。
示例:
输入:7
输出:[[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
解释:
<img alt="" src="https://aliyun-lc-upload.oss-cn-hangzhou.aliyuncs.com/aliyun-lc-upload/uploads/2018/08/24/fivetrees.png" style="height: 400px; width: 700px;">
提示:
1 <= N <= 20
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<TreeNode> allPossibleFBT(int N) {
}
}<file_sep>package com.LeetCode.code.q679.24Game;
/**
* @QuestionId : 679
* @difficulty : Hard
* @Title : 24 Game
* @TranslatedTitle:24 点游戏
* @url : https://leetcode-cn.com/problems/24-game/
* @TranslatedContent:你有 4 张写有 1 到 9 数字的牌。你需要判断是否能通过 *,/,+,-,(,) 的运算得到 24。
示例 1:
输入: [4, 1, 8, 7]
输出: True
解释: (8-4) * (7-1) = 24
示例 2:
输入: [1, 2, 1, 2]
输出: False
注意:
除法运算符 / 表示实数除法,而不是整数除法。例如 4 / (1 - 2/3) = 12 。
每个运算符对两个数进行运算。特别是我们不能用 - 作为一元运算符。例如,[1, 1, 1, 1] 作为输入时,表达式 -1 - 1 - 1 - 1 是不允许的。
你不能将数字连接在一起。例如,输入为 [1, 2, 1, 2] 时,不能写成 12 + 12 。
*/
class Solution {
public boolean judgePoint24(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q730.CountDifferentPalindromicSubsequences;
/**
* @QuestionId : 730
* @difficulty : Hard
* @Title : Count Different Palindromic Subsequences
* @TranslatedTitle:统计不同回文子字符串
* @url : https://leetcode-cn.com/problems/count-different-palindromic-subsequences/
* @TranslatedContent:给定一个字符串 S,找出 S 中不同的非空回文子序列个数,并返回该数字与 10^9 + 7 的模。
通过从 S 中删除 0 个或多个字符来获得子字符序列。
如果一个字符序列与它反转后的字符序列一致,那么它是回文字符序列。
如果对于某个 i,A_i != B_i,那么 A_1, A_2, ... 和 B_1, B_2, ... 这两个字符序列是不同的。
示例 1:
输入:
S = 'bccb'
输出:6
解释:
6 个不同的非空回文子字符序列分别为:'b', 'c', 'bb', 'cc', 'bcb', 'bccb'。
注意:'bcb' 虽然出现两次但仅计数一次。
示例 2:
输入:
S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'
输出:104860361
解释:
共有 3104860382 个不同的非空回文子字符序列,对 10^9 + 7 取模为 104860361。
提示:
字符串 S 的长度将在[1, 1000]范围内。
每个字符 S[i] 将会是集合 {'a', 'b', 'c', 'd'} 中的某一个。
*/
class Solution {
public int countPalindromicSubsequences(String S) {
}
}<file_sep>package com.LeetCode.code.q1055.PairsofSongsWithTotalDurationsDivisibleby60;
/**
* @QuestionId : 1055
* @difficulty : Easy
* @Title : Pairs of Songs With Total Durations Divisible by 60
* @TranslatedTitle:总持续时间可被 60 整除的歌曲
* @url : https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/
* @TranslatedContent:在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。
返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望索引的数字 i < j 且有 (time[i] + time[j]) % 60 == 0。
示例 1:
输入:[30,20,150,100,40]
输出:3
解释:这三对的总持续时间可被 60 整数:
(time[0] = 30, time[2] = 150): 总持续时间 180
(time[1] = 20, time[3] = 100): 总持续时间 120
(time[1] = 20, time[4] = 40): 总持续时间 60
示例 2:
输入:[60,60,60]
输出:3
解释:所有三对的总持续时间都是 120,可以被 60 整数。
提示:
1 <= time.length <= 60000
1 <= time[i] <= 500
*/
class Solution {
public int numPairsDivisibleBy60(int[] time) {
}
}<file_sep>package com.LeetCode.code.q772.ConstructQuadTree;
/**
* @QuestionId : 772
* @difficulty : Medium
* @Title : Construct Quad Tree
* @TranslatedTitle:建立四叉树
* @url : https://leetcode-cn.com/problems/construct-quad-tree/
* @TranslatedContent:我们想要使用一棵四叉树来储存一个 N x N 的布尔值网络。网络中每一格的值只会是真或假。树的根结点代表整个网络。对于每个结点, 它将被分等成四个孩子结点直到这个区域内的值都是相同的.
每个结点还有另外两个布尔变量: isLeaf 和 val。isLeaf 当这个节点是一个叶子结点时为真。val 变量储存叶子结点所代表的区域的值。
你的任务是使用一个四叉树表示给定的网络。下面的例子将有助于你理解这个问题:
给定下面这个8 x 8 网络,我们将这样建立一个对应的四叉树:
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/01/962_grid.png" style="height:27%; width:27%" />
由上文的定义,它能被这样分割:
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/01/962_grid_divided.png" style="height:100%; width:100%" />
对应的四叉树应该像下面这样,每个结点由一对 (isLeaf, val) 所代表.
对于非叶子结点,val 可以是任意的,所以使用 * 代替。
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/02/01/962_quad_tree.png" style="height:100%; width:100%" />
提示:
N 将小于 1000 且确保是 2 的整次幂。
如果你想了解更多关于四叉树的知识,你可以参考这个 <a href="https://en.wikipedia.org/wiki/Quadtree">wiki 页面。
*/
/*
// Definition for a QuadTree node.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
public Node() {}
public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) {
val = _val;
isLeaf = _isLeaf;
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
}
};
*/
class Solution {
public Node construct(int[][] grid) {
}
}<file_sep>package com.LeetCode.code.q125.ValidPalindrome;
/**
* @QuestionId : 125
* @difficulty : Easy
* @Title : Valid Palindrome
* @TranslatedTitle:验证回文串
* @url : https://leetcode-cn.com/problems/valid-palindrome/
* @TranslatedContent:给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false
*/
class Solution {
public boolean isPalindrome(String s) {
}
}<file_sep>package com.LeetCode.code.q273.IntegertoEnglishWords;
/**
* @QuestionId : 273
* @difficulty : Hard
* @Title : Integer to English Words
* @TranslatedTitle:整数转换英文表示
* @url : https://leetcode-cn.com/problems/integer-to-english-words/
* @TranslatedContent:将非负整数转换为其对应的英文表示。可以保证给定输入小于 231 - 1 。
示例 1:
输入: 123
输出: "One Hundred Twenty Three"
示例 2:
输入: 12345
输出: "Twelve Thousand Three Hundred Forty Five"
示例 3:
输入: 1234567
输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:
输入: 1234567891
输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
*/
class Solution {
public String numberToWords(int num) {
}
}<file_sep>package com.LeetCode.code.q209.MinimumSizeSubarraySum;
/**
* @QuestionId : 209
* @difficulty : Medium
* @Title : Minimum Size Subarray Sum
* @TranslatedTitle:长度最小的子数组
* @url : https://leetcode-cn.com/problems/minimum-size-subarray-sum/
* @TranslatedContent:给定一个含有 n 个正整数的数组和一个正整数 s ,找出该数组中满足其和 ≥ s 的长度最小的连续子数组。如果不存在符合条件的连续子数组,返回 0。
示例:
输入: s = 7, nums = [2,3,1,2,4,3]
输出: 2
解释: 子数组 [4,3] 是该条件下的长度最小的连续子数组。
进阶:
如果你已经完成了O(n) 时间复杂度的解法, 请尝试 O(n log n) 时间复杂度的解法。
*/
class Solution {
public int minSubArrayLen(int s, int[] nums) {
}
}<file_sep>package com.LeetCode.code.q342.PowerofFour;
/**
* @QuestionId : 342
* @difficulty : Easy
* @Title : Power of Four
* @TranslatedTitle:4的幂
* @url : https://leetcode-cn.com/problems/power-of-four/
* @TranslatedContent:给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方。
示例 1:
输入: 16
输出: true
示例 2:
输入: 5
输出: false
进阶:
你能不使用循环或者递归来完成本题吗?
*/
class Solution {
public boolean isPowerOfFour(int num) {
}
}<file_sep>package com.LeetCode.code.q894.RandomPickwithBlacklist;
/**
* @QuestionId : 894
* @difficulty : Hard
* @Title : Random Pick with Blacklist
* @TranslatedTitle:黑名单中的随机数
* @url : https://leetcode-cn.com/problems/random-pick-with-blacklist/
* @TranslatedContent:给定一个包含 [0,n ) 中独特的整数的黑名单 B,写一个函数从 [ 0,n ) 中返回一个不在 B 中的随机整数。
对它进行优化使其尽量少调用系统方法 Math.random() 。
提示:
1 <= N <= 1000000000
0 <= B.length < min(100000, N)
[0, N) 不包含 N,详细参见 <a href="https://en.wikipedia.org/wiki/Interval_(mathematics)" target="_blank">interval notation 。
示例 1:
输入:
["Solution","pick","pick","pick"]
[[1,[]],[],[],[]]
输出: [null,0,0,0]
示例 2:
输入:
["Solution","pick","pick","pick"]
[[2,[]],[],[],[]]
输出: [null,1,1,1]
示例 3:
输入:
["Solution","pick","pick","pick"]
[[3,[1]],[],[],[]]
Output: [null,0,0,2]
示例 4:
输入:
["Solution","pick","pick","pick"]
[[4,[2]],[],[],[]]
输出: [null,1,3,1]
输入语法说明:
输入是两个列表:调用成员函数名和调用的参数。Solution的构造函数有两个参数,N 和黑名单 B。pick 没有参数,输入参数是一个列表,即使参数为空,也会输入一个 [] 空列表。
*/
class Solution {
public Solution(int N, int[] blacklist) {
}
public int pick() {
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(N, blacklist);
* int param_1 = obj.pick();
*/<file_sep>package com.LeetCode.code.q611.ValidTriangleNumber;
/**
* @QuestionId : 611
* @difficulty : Medium
* @Title : Valid Triangle Number
* @TranslatedTitle:有效三角形的个数
* @url : https://leetcode-cn.com/problems/valid-triangle-number/
* @TranslatedContent:给定一个包含非负整数的数组,你的任务是统计其中可以组成三角形三条边的三元组个数。
示例 1:
输入: [2,2,3,4]
输出: 3
解释:
有效的组合是:
2,3,4 (使用第一个 2)
2,3,4 (使用第二个 2)
2,2,3
注意:
数组长度不超过1000。
数组里整数的范围为 [0, 1000]。
*/
class Solution {
public int triangleNumber(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q932.MonotonicArray;
/**
* @QuestionId : 932
* @difficulty : Easy
* @Title : Monotonic Array
* @TranslatedTitle:单调数列
* @url : https://leetcode-cn.com/problems/monotonic-array/
* @TranslatedContent:如果数组是单调递增或单调递减的,那么它是单调的。
如果对于所有 i <= j,A[i] <= A[j],那么数组 A 是单调递增的。 如果对于所有 i <= j,A[i]> = A[j],那么数组 A 是单调递减的。
当给定的数组 A 是单调数组时返回 true,否则返回 false。
示例 1:
输入:[1,2,2,3]
输出:true
示例 2:
输入:[6,5,4,4]
输出:true
示例 3:
输入:[1,3,2]
输出:false
示例 4:
输入:[1,2,4,5]
输出:true
示例 5:
输入:[1,1,1]
输出:true
提示:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
*/
class Solution {
public boolean isMonotonic(int[] A) {
}
}<file_sep>package com.LeetCode.code.q279.PerfectSquares;
/**
* @QuestionId : 279
* @difficulty : Medium
* @Title : Perfect Squares
* @TranslatedTitle:完全平方数
* @url : https://leetcode-cn.com/problems/perfect-squares/
* @TranslatedContent:给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
*/
class Solution {
public int numSquares(int n) {
}
}<file_sep>package com.LeetCode.code.q23.MergekSortedLists;
/**
* @QuestionId : 23
* @difficulty : Hard
* @Title : Merge k Sorted Lists
* @TranslatedTitle:合并K个排序链表
* @url : https://leetcode-cn.com/problems/merge-k-sorted-lists/
* @TranslatedContent:合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
}
}<file_sep>package com.LeetCode.code.q416.PartitionEqualSubsetSum;
/**
* @QuestionId : 416
* @difficulty : Medium
* @Title : Partition Equal Subset Sum
* @TranslatedTitle:分割等和子集
* @url : https://leetcode-cn.com/problems/partition-equal-subset-sum/
* @TranslatedContent:给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
注意:
每个数组中的元素不会超过 100
数组的大小不会超过 200
示例 1:
输入: [1, 5, 11, 5]
输出: true
解释: 数组可以分割成 [1, 5, 5] 和 [11].
示例 2:
输入: [1, 2, 3, 5]
输出: false
解释: 数组不能分割成两个元素和相等的子集.
*/
class Solution {
public boolean canPartition(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q394.DecodeString;
/**
* @QuestionId : 394
* @difficulty : Medium
* @Title : Decode String
* @TranslatedTitle:字符串解码
* @url : https://leetcode-cn.com/problems/decode-string/
* @TranslatedContent:给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
*/
class Solution {
public String decodeString(String s) {
}
}<file_sep>package com.LeetCode.code.q950.XofaKindinaDeckofCards;
/**
* @QuestionId : 950
* @difficulty : Easy
* @Title : X of a Kind in a Deck of Cards
* @TranslatedTitle:卡牌分组
* @url : https://leetcode-cn.com/problems/x-of-a-kind-in-a-deck-of-cards/
* @TranslatedContent:给定一副牌,每张牌上都写着一个整数。
此时,你需要选定一个数字 X,使我们可以将整副牌按下述规则分成 1 组或更多组:
每组都有 X 张牌。
组内所有的牌上都写着相同的整数。
仅当你可选的 X >= 2 时返回 true。
示例 1:
输入:[1,2,3,4,4,3,2,1]
输出:true
解释:可行的分组是 [1,1],[2,2],[3,3],[4,4]
示例 2:
输入:[1,1,1,2,2,2,3,3]
输出:false
解释:没有满足要求的分组。
示例 3:
输入:[1]
输出:false
解释:没有满足要求的分组。
示例 4:
输入:[1,1]
输出:true
解释:可行的分组是 [1,1]
示例 5:
输入:[1,1,2,2,2,2]
输出:true
解释:可行的分组是 [1,1],[2,2],[2,2]
提示:
1 <= deck.length <= 10000
0 <= deck[i] < 10000
*/
class Solution {
public boolean hasGroupsSizeX(int[] deck) {
}
}<file_sep>package com.LeetCode.code.q462.MinimumMovestoEqualArrayElementsII;
/**
* @QuestionId : 462
* @difficulty : Medium
* @Title : Minimum Moves to Equal Array Elements II
* @TranslatedTitle:最少移动次数使数组元素相等 II
* @url : https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements-ii/
* @TranslatedContent:给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数,其中每次移动可将选定的一个元素加1或减1。 您可以假设数组的长度最多为10000。
例如:
输入:
[1,2,3]
输出:
2
说明:
只有两个动作是必要的(记得每一步仅可使其中一个元素加1或减1):
[1,2,3] => [2,2,3] => [2,2,2]
*/
class Solution {
public int minMoves2(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q887.MinimumCosttoHireKWorkers;
/**
* @QuestionId : 887
* @difficulty : Hard
* @Title : Minimum Cost to Hire K Workers
* @TranslatedTitle:雇佣 K 名工人的最低成本
* @url : https://leetcode-cn.com/problems/minimum-cost-to-hire-k-workers/
* @TranslatedContent:有 N 名工人。 第 i 名工人的工作质量为 quality[i] ,其最低期望工资为 wage[i] 。
现在我们想雇佣 K 名工人组成一个工资组。在雇佣 一组 K 名工人时,我们必须按照下述规则向他们支付工资:
对工资组中的每名工人,应当按其工作质量与同组其他工人的工作质量的比例来支付工资。
工资组中的每名工人至少应当得到他们的最低期望工资。
返回组成一个满足上述条件的工资组至少需要多少钱。
示例 1:
输入: quality = [10,20,5], wage = [70,50,30], K = 2
输出: 105.00000
解释: 我们向 0 号工人支付 70,向 2 号工人支付 35。
示例 2:
输入: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3
输出: 30.66667
解释: 我们向 0 号工人支付 4,向 2 号和 3 号分别支付 13.33333。
提示:
1 <= K <= N <= 10000,其中 N = quality.length = wage.length
1 <= quality[i] <= 10000
1 <= wage[i] <= 10000
与正确答案误差在 10^-5 之内的答案将被视为正确的。
*/
class Solution {
public double mincostToHireWorkers(int[] quality, int[] wage, int K) {
}
}<file_sep>package com.LeetCode.code.q638.ShoppingOffers;
/**
* @QuestionId : 638
* @difficulty : Medium
* @Title : Shopping Offers
* @TranslatedTitle:大礼包
* @url : https://leetcode-cn.com/problems/shopping-offers/
* @TranslatedContent:在LeetCode商店中, 有许多在售的物品。
然而,也有一些大礼包,每个大礼包以优惠的价格捆绑销售一组物品。
现给定每个物品的价格,每个大礼包包含物品的清单,以及待购物品清单。请输出确切完成待购清单的最低花费。
每个大礼包的由一个数组中的一组数据描述,最后一个数字代表大礼包的价格,其他数字分别表示内含的其他种类物品的数量。
任意大礼包可无限次购买。
示例 1:
输入: [2,5], [[3,0,5],[1,2,10]], [3,2]
输出: 14
解释:
有A和B两种物品,价格分别为¥2和¥5。
大礼包1,你可以以¥5的价格购买3A和0B。
大礼包2, 你可以以¥10的价格购买1A和2B。
你需要购买3个A和2个B, 所以你付了¥10购买了1A和2B(大礼包2),以及¥4购买2A。
示例 2:
输入: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1]
输出: 11
解释:
A,B,C的价格分别为¥2,¥3,¥4.
你可以用¥4购买1A和1B,也可以用¥9购买2A,2B和1C。
你需要买1A,2B和1C,所以你付了¥4买了1A和1B(大礼包1),以及¥3购买1B, ¥4购买1C。
你不可以购买超出待购清单的物品,尽管购买大礼包2更加便宜。
说明:
最多6种物品, 100种大礼包。
每种物品,你最多只需要购买6个。
你不可以购买超出待购清单的物品,即使更便宜。
*/
class Solution {
public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
}
}<file_sep>package com.LeetCode.code.q328.OddEvenLinkedList;
/**
* @QuestionId : 328
* @difficulty : Medium
* @Title : Odd Even Linked List
* @TranslatedTitle:奇偶链表
* @url : https://leetcode-cn.com/problems/odd-even-linked-list/
* @TranslatedContent:给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。
请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。
示例 1:
输入: 1->2->3->4->5->NULL
输出: 1->3->5->2->4->NULL
示例 2:
输入: 2->1->3->5->6->4->7->NULL
输出: 2->3->6->7->1->5->4->NULL
说明:
应当保持奇数节点和偶数节点的相对顺序。
链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode oddEvenList(ListNode head) {
}
}<file_sep>package com.LeetCode.code.q1273.CompareStringsbyFrequencyoftheSmallestCharacter;
/**
* @QuestionId : 1273
* @difficulty : Easy
* @Title : Compare Strings by Frequency of the Smallest Character
* @TranslatedTitle:比较字符串最小字母出现频次
* @url : https://leetcode-cn.com/problems/compare-strings-by-frequency-of-the-smallest-character/
* @TranslatedContent:我们来定义一个函数 f(s),其中传入参数 s 是一个非空字符串;该函数的功能是统计 s 中(按字典序比较)最小字母的出现频次。
例如,若 s = "dcce",那么 f(s) = 2,因为最小的字母是 "c",它出现了 2 次。
现在,给你两个字符串数组待查表 queries 和词汇表 words,请你返回一个整数数组 answer 作为答案,其中每个 answer[i] 是满足 f(queries[i]) < f(W) 的词的数目,W 是词汇表 words 中的词。
示例 1:
输入:queries = ["cbd"], words = ["zaaaz"]
输出:[1]
解释:查询 f("cbd") = 1,而 f("zaaaz") = 3 所以 f("cbd") < f("zaaaz")。
示例 2:
输入:queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"]
输出:[1,2]
解释:第一个查询 f("bbb") < f("aaaa"),第二个查询 f("aaa") 和 f("aaaa") 都 > f("cc")。
提示:
1 <= queries.length <= 2000
1 <= words.length <= 2000
1 <= queries[i].length, words[i].length <= 10
queries[i][j], words[i][j] 都是小写英文字母
*/
class Solution {
public int[] numSmallerByFrequency(String[] queries, String[] words) {
}
}<file_sep>package com.LeetCode.code.q515.FindLargestValueinEachTreeRow;
/**
* @QuestionId : 515
* @difficulty : Medium
* @Title : Find Largest Value in Each Tree Row
* @TranslatedTitle:在每个树行中找最大值
* @url : https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/
* @TranslatedContent:您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q441.ArrangingCoins;
/**
* @QuestionId : 441
* @difficulty : Easy
* @Title : Arranging Coins
* @TranslatedTitle:排列硬币
* @url : https://leetcode-cn.com/problems/arranging-coins/
* @TranslatedContent:你总共有 n 枚硬币,你需要将它们摆成一个阶梯形状,第 k 行就必须正好有 k 枚硬币。
给定一个数字 n,找出可形成完整阶梯行的总行数。
n 是一个非负整数,并且在32位有符号整型的范围内。
示例 1:
n = 5
硬币可排列成以下几行:
¤
¤ ¤
¤ ¤
因为第三行不完整,所以返回2.
示例 2:
n = 8
硬币可排列成以下几行:
¤
¤ ¤
¤ ¤ ¤
¤ ¤
因为第四行不完整,所以返回3.
*/
class Solution {
public int arrangeCoins(int n) {
}
}<file_sep>package com.LeetCode.code.q525.ContiguousArray;
/**
* @QuestionId : 525
* @difficulty : Medium
* @Title : Contiguous Array
* @TranslatedTitle:连续数组
* @url : https://leetcode-cn.com/problems/contiguous-array/
* @TranslatedContent:给定一个二进制数组, 找到含有相同数量的 0 和 1 的最长连续子数组(的长度)。
示例 1:
输入: [0,1]
输出: 2
说明: [0, 1] 是具有相同数量0和1的最长连续子数组。
示例 2:
输入: [0,1,0]
输出: 2
说明: [0, 1] (或 [1, 0]) 是具有相同数量0和1的最长连续子数组。
注意: 给定的二进制数组的长度不会超过50000。
*/
class Solution {
public int findMaxLength(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q1079.SumofRootToLeafBinaryNumbers;
/**
* @QuestionId : 1079
* @difficulty : Easy
* @Title : Sum of Root To Leaf Binary Numbers
* @TranslatedTitle:从根到叶的二进制数之和
* @url : https://leetcode-cn.com/problems/sum-of-root-to-leaf-binary-numbers/
* @TranslatedContent:给出一棵二叉树,其上每个结点的值都是 0 或 1 。每一条从根到叶的路径都代表一个从最高有效位开始的二进制数。例如,如果路径为 0 -> 1 -> 1 -> 0 -> 1,那么它表示二进制数 01101,也就是 13 。
对树上的每一片叶子,我们都要找出从根到该叶子的路径所表示的数字。
以 10^9 + 7 为模,返回这些数字之和。
示例:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/04/05/sum-of-root-to-leaf-binary-numbers.png" style="height: 200px; width: 304px;">
输入:[1,0,1,0,1,0,1]
输出:22
解释:(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
提示:
树中的结点数介于 1 和 1000 之间。
node.val 为 0 或 1 。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int sumRootToLeaf(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q636.ExclusiveTimeofFunctions;
/**
* @QuestionId : 636
* @difficulty : Medium
* @Title : Exclusive Time of Functions
* @TranslatedTitle:函数的独占时间
* @url : https://leetcode-cn.com/problems/exclusive-time-of-functions/
* @TranslatedContent:给出一个非抢占单线程CPU的 n 个函数运行日志,找到函数的独占时间。
每个函数都有一个唯一的 Id,从 0 到 n-1,函数可能会递归调用或者被其他函数调用。
日志是具有以下格式的字符串:function_id:start_or_end:timestamp。例如:"0:start:0" 表示函数 0 从 0 时刻开始运行。"0:end:0" 表示函数 0 在 0 时刻结束。
函数的独占时间定义是在该方法中花费的时间,调用其他函数花费的时间不算该函数的独占时间。你需要根据函数的 Id 有序地返回每个函数的独占时间。
示例 1:
输入:
n = 2
logs =
["0:start:0",
"1:start:2",
"1:end:5",
"0:end:6"]
输出:[3, 4]
说明:
函数 0 在时刻 0 开始,在执行了 2个时间单位结束于时刻 1。
现在函数 0 调用函数 1,函数 1 在时刻 2 开始,执行 4 个时间单位后结束于时刻 5。
函数 0 再次在时刻 6 开始执行,并在时刻 6 结束运行,从而执行了 1 个时间单位。
所以函数 0 总共的执行了 2 +1 =3 个时间单位,函数 1 总共执行了 4 个时间单位。
说明:
输入的日志会根据时间戳排序,而不是根据日志Id排序。
你的输出会根据函数Id排序,也就意味着你的输出数组中序号为 0 的元素相当于函数 0 的执行时间。
两个函数不会在同时开始或结束。
函数允许被递归调用,直到运行结束。
1 <= n <= 100
*/
class Solution {
public int[] exclusiveTime(int n, List<String> logs) {
}
}<file_sep>package com.LeetCode.code.q500.KeyboardRow;
/**
* @QuestionId : 500
* @difficulty : Easy
* @Title : Keyboard Row
* @TranslatedTitle:键盘行
* @url : https://leetcode-cn.com/problems/keyboard-row/
* @TranslatedContent:给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。
<img alt="American keyboard" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/keyboard.png" style="width: 100%; max-width: 600px">
示例:
输入: ["Hello", "Alaska", "Dad", "Peace"]
输出: ["Alaska", "Dad"]
注意:
你可以重复使用键盘上同一字符。
你可以假设输入的字符串将只包含字母。
*/
class Solution {
public String[] findWords(String[] words) {
}
}<file_sep>package com.LeetCode.code.q717.1-bitand2-bitCharacters;
/**
* @QuestionId : 717
* @difficulty : Easy
* @Title : 1-bit and 2-bit Characters
* @TranslatedTitle:1比特与2比特字符
* @url : https://leetcode-cn.com/problems/1-bit-and-2-bit-characters/
* @TranslatedContent:有两种特殊字符。第一种字符可以用一比特0来表示。第二种字符可以用两比特(10 或 11)来表示。
现给一个由若干比特组成的字符串。问最后一个字符是否必定为一个一比特字符。给定的字符串总是由0结束。
示例 1:
输入:
bits = [1, 0, 0]
输出: True
解释:
唯一的编码方式是一个两比特字符和一个一比特字符。所以最后一个字符是一比特字符。
示例 2:
输入:
bits = [1, 1, 1, 0]
输出: False
解释:
唯一的编码方式是两比特字符和两比特字符。所以最后一个字符不是一比特字符。
注意:
1 <= len(bits) <= 1000.
bits[i] 总是0 或 1.
*/
class Solution {
public boolean isOneBitCharacter(int[] bits) {
}
}<file_sep>package com.LeetCode.code.q980.FindtheShortestSuperstring;
/**
* @QuestionId : 980
* @difficulty : Hard
* @Title : Find the Shortest Superstring
* @TranslatedTitle:最短超级串
* @url : https://leetcode-cn.com/problems/find-the-shortest-superstring/
* @TranslatedContent:给定一个字符串数组 A,找到以 A 中每个字符串作为子字符串的最短字符串。
我们可以假设 A 中没有字符串是 A 中另一个字符串的子字符串。
示例 1:
输入:["alex","loves","leetcode"]
输出:"alexlovesleetcode"
解释:"alex","loves","leetcode" 的所有排列都会被接受。
示例 2:
输入:["catg","ctaagt","gcta","ttca","atgcatc"]
输出:"gctaagttcatgcatc"
提示:
1 <= A.length <= 12
1 <= A[i].length <= 20
*/
class Solution {
public String shortestSuperstring(String[] A) {
}
}<file_sep>package com.LeetCode.code.q400.NthDigit;
/**
* @QuestionId : 400
* @difficulty : Easy
* @Title : Nth Digit
* @TranslatedTitle:第N个数字
* @url : https://leetcode-cn.com/problems/nth-digit/
* @TranslatedContent:在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 n 个数字。
注意:<br />
n 是正数且在32为整形范围内 ( n < 231)。
示例 1:
输入:
3
输出:
3
示例 2:
输入:
11
输出:
0
说明:
第11个数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是0,它是10的一部分。
*/
class Solution {
public int findNthDigit(int n) {
}
}<file_sep>package com.LeetCode.code.q831.LargestSumofAverages;
/**
* @QuestionId : 831
* @difficulty : Medium
* @Title : Largest Sum of Averages
* @TranslatedTitle:最大平均值和的分组
* @url : https://leetcode-cn.com/problems/largest-sum-of-averages/
* @TranslatedContent:我们将给定的数组 A 分成 K 个相邻的非空子数组 ,我们的分数由每个子数组内的平均值的总和构成。计算我们所能得到的最大分数是多少。
注意我们必须使用 A 数组中的每一个数进行分组,并且分数不一定需要是整数。
示例:
输入:
A = [9,1,2,3,9]
K = 3
输出: 20
解释:
A 的最优分组是[9], [1, 2, 3], [9]. 得到的分数是 9 + (1 + 2 + 3) / 3 + 9 = 20.
我们也可以把 A 分成[9, 1], [2], [3, 9].
这样的分组得到的分数为 5 + 2 + 6 = 13, 但不是最大值.
说明:
1 <= A.length <= 100.
1 <= A[i] <= 10000.
1 <= K <= A.length.
答案误差在 10^-6 内被视为是正确的。
*/
class Solution {
public double largestSumOfAverages(int[] A, int K) {
}
}<file_sep>package com.LeetCode.code.q9.PalindromeNumber;
/**
* @QuestionId : 9
* @difficulty : Easy
* @Title : Palindrome Number
* @TranslatedTitle:回文数
* @url : https://leetcode-cn.com/problems/palindrome-number/
* @TranslatedContent:判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶:
你能不将整数转为字符串来解决这个问题吗?
*/
class Solution {
public boolean isPalindrome(int x) {
}
}<file_sep>package com.LeetCode.code.q767.PrimeNumberofSetBitsinBinaryRepresentation;
/**
* @QuestionId : 767
* @difficulty : Easy
* @Title : Prime Number of Set Bits in Binary Representation
* @TranslatedTitle:二进制表示中质数个计算置位
* @url : https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation/
* @TranslatedContent:给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。
(注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。)
示例 1:
输入: L = 6, R = 10
输出: 4
解释:
6 -> 110 (2 个计算置位,2 是质数)
7 -> 111 (3 个计算置位,3 是质数)
9 -> 1001 (2 个计算置位,2 是质数)
10-> 1010 (2 个计算置位,2 是质数)
示例 2:
输入: L = 10, R = 15
输出: 5
解释:
10 -> 1010 (2 个计算置位, 2 是质数)
11 -> 1011 (3 个计算置位, 3 是质数)
12 -> 1100 (2 个计算置位, 2 是质数)
13 -> 1101 (3 个计算置位, 3 是质数)
14 -> 1110 (3 个计算置位, 3 是质数)
15 -> 1111 (4 个计算置位, 4 不是质数)
注意:
L, R 是 L <= R 且在 [1, 10^6] 中的整数。
R - L 的最大值为 10000。
*/
class Solution {
public int countPrimeSetBits(int L, int R) {
}
}<file_sep>package com.LeetCode.code.q1297.MaximumNumberofBalloons;
/**
* @QuestionId : 1297
* @difficulty : Easy
* @Title : Maximum Number of Balloons
* @TranslatedTitle:“气球” 的最大数量
* @url : https://leetcode-cn.com/problems/maximum-number-of-balloons/
* @TranslatedContent:给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。
字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。
示例 1:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/09/14/1536_ex1_upd.jpeg" style="height: 35px; width: 154px;">
输入:text = "nlaebolko"
输出:1
示例 2:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/09/14/1536_ex2_upd.jpeg" style="height: 35px; width: 233px;">
输入:text = "loonbalxballpoon"
输出:2
示例 3:
输入:text = "leetcode"
输出:0
提示:
1 <= text.length <= 10^4
text 全部由小写英文字母组成
*/
class Solution {
public int maxNumberOfBalloons(String text) {
}
}<file_sep>package com.LeetCode.code.q1032.SatisfiabilityofEqualityEquations;
/**
* @QuestionId : 1032
* @difficulty : Medium
* @Title : Satisfiability of Equality Equations
* @TranslatedTitle:等式方程的可满足性
* @url : https://leetcode-cn.com/problems/satisfiability-of-equality-equations/
* @TranslatedContent:给定一个由表示变量之间关系的字符串方程组成的数组,每个字符串方程 equations[i] 的长度为 4,并采用两种不同的形式之一:"a==b" 或 "a!=b"。在这里,a 和 b 是小写字母(不一定不同),表示单字母变量名。
只有当可以将整数分配给变量名,以便满足所有给定的方程时才返回 true,否则返回 false。
示例 1:
输入:["a==b","b!=a"]
输出:false
解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。
示例 2:
输出:["b==a","a==b"]
输入:true
解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。
示例 3:
输入:["a==b","b==c","a==c"]
输出:true
示例 4:
输入:["a==b","b!=c","c==a"]
输出:false
示例 5:
输入:["c==c","b==d","x!=z"]
输出:true
提示:
1 <= equations.length <= 500
equations[i].length == 4
equations[i][0] 和 equations[i][3] 是小写字母
equations[i][1] 要么是 '=',要么是 '!'
equations[i][2] 是 '='
*/
class Solution {
public boolean equationsPossible(String[] equations) {
}
}<file_sep>package com.LeetCode.code.q217.ContainsDuplicate;
/**
* @QuestionId : 217
* @difficulty : Easy
* @Title : Contains Duplicate
* @TranslatedTitle:存在重复元素
* @url : https://leetcode-cn.com/problems/contains-duplicate/
* @TranslatedContent:给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false
示例 3:
输入: [1,1,1,3,3,4,3,2,4,2]
输出: true
*/
class Solution {
public boolean containsDuplicate(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q738.MonotoneIncreasingDigits;
/**
* @QuestionId : 738
* @difficulty : Medium
* @Title : Monotone Increasing Digits
* @TranslatedTitle:单调递增的数字
* @url : https://leetcode-cn.com/problems/monotone-increasing-digits/
* @TranslatedContent:给定一个非负整数 N,找出小于或等于 N 的最大的整数,同时这个整数需要满足其各个位数上的数字是单调递增。
(当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。)
示例 1:
输入: N = 10
输出: 9
示例 2:
输入: N = 1234
输出: 1234
示例 3:
输入: N = 332
输出: 299
说明: N 是在 [0, 10^9] 范围内的一个整数。
*/
class Solution {
public int monotoneIncreasingDigits(int N) {
}
}<file_sep>package com.LeetCode.code.q807.CustomSortString;
/**
* @QuestionId : 807
* @difficulty : Medium
* @Title : Custom Sort String
* @TranslatedTitle:自定义字符串排序
* @url : https://leetcode-cn.com/problems/custom-sort-string/
* @TranslatedContent:字符串S和 T 只包含小写字符。在S中,所有字符只会出现一次。
S 已经根据某种规则进行了排序。我们要根据S中的字符顺序对T进行排序。更具体地说,如果S中x在y之前出现,那么返回的字符串中x也应出现在y之前。
返回任意一种符合条件的字符串T。
示例:
输入:
S = "cba"
T = "abcd"
输出: "cbad"
解释:
S中出现了字符 "a", "b", "c", 所以 "a", "b", "c" 的顺序应该是 "c", "b", "a".
由于 "d" 没有在S中出现, 它可以放在T的任意位置. "dcba", "cdba", "cbda" 都是合法的输出。
注意:
S的最大长度为26,其中没有重复的字符。
T的最大长度为200。
S和T只包含小写字符。
*/
class Solution {
public String customSortString(String S, String T) {
}
}<file_sep>package com.LeetCode.code.q1185.FindinMountainArray;
/**
* @QuestionId : 1185
* @difficulty : Hard
* @Title : Find in Mountain Array
* @TranslatedTitle:山脉数组中查找目标值
* @url : https://leetcode-cn.com/problems/find-in-mountain-array/
* @TranslatedContent:(这是一个 交互式问题 )
给你一个 山脉数组 mountainArr,请你返回能够使得 mountainArr.get(index) 等于 target 最小 的下标 index 值。
如果不存在这样的下标 index,就请返回 -1。
所谓山脉数组,即数组 A 假如是一个山脉数组的话,需要满足如下条件:
首先,A.length >= 3
其次,在 0 < i < A.length - 1 条件下,存在 i 使得:
A[0] < A[1] < ... A[i-1] < A[i]
A[i] > A[i+1] > ... > A[A.length - 1]
你将 不能直接访问该山脉数组,必须通过 MountainArray 接口来获取数据:
MountainArray.get(k) - 会返回数组中索引为k 的元素(下标从 0 开始)
MountainArray.length() - 会返回该数组的长度
注意:
对 MountainArray.get 发起超过 100 次调用的提交将被视为错误答案。此外,任何试图规避判题系统的解决方案都将会导致比赛资格被取消。
为了帮助大家更好地理解交互式问题,我们准备了一个样例 “答案”:<a href="https://leetcode-cn.com/playground/RKhe3ave" target="_blank">https://leetcode-cn.com/playground/RKhe3ave,请注意这 不是一个正确答案。
示例 1:
输入:array = [1,2,3,4,5,3,1], target = 3
输出:2
解释:3 在数组中出现了两次,下标分别为 2 和 5,我们返回最小的下标 2。
示例 2:
输入:array = [0,1,2,4,2,1], target = 3
输出:-1
解释:3 在数组中没有出现,返回 -1。
提示:
3 <= mountain_arr.length() <= 10000
0 <= target <= 10^9
0 <= mountain_arr.get(index) <= 10^9
*/
/**
* // This is MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* interface MountainArray {
* public int get(int index) {}
* public int length() {}
* }
*/
class Solution {
public int findInMountainArray(int target, MountainArray mountainArr) {
}
}<file_sep>package com.LeetCode.code.q306.AdditiveNumber;
/**
* @QuestionId : 306
* @difficulty : Medium
* @Title : Additive Number
* @TranslatedTitle:累加数
* @url : https://leetcode-cn.com/problems/additive-number/
* @TranslatedContent:累加数是一个字符串,组成它的数字可以形成累加序列。
一个有效的累加序列必须至少包含 3 个数。除了最开始的两个数以外,字符串中的其他数都等于它之前两个数相加的和。
给定一个只包含数字 '0'-'9' 的字符串,编写一个算法来判断给定输入是否是累加数。
说明: 累加序列里的数不会以 0 开头,所以不会出现 1, 2, 03 或者 1, 02, 3 的情况。
示例 1:
输入: "112358"
输出: true
解释: 累加序列为: 1, 1, 2, 3, 5, 8 。1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
示例 2:
输入: "199100199"
输出: true
解释: 累加序列为: 1, 99, 100, 199。1 + 99 = 100, 99 + 100 = 199
进阶:
你如何处理一个溢出的过大的整数输入?
*/
class Solution {
public boolean isAdditiveNumber(String num) {
}
}<file_sep>package com.LeetCode.code.q1262.OnlineMajorityElementInSubarray;
/**
* @QuestionId : 1262
* @difficulty : Hard
* @Title : Online Majority Element In Subarray
* @TranslatedTitle:子数组中占绝大多数的元素
* @url : https://leetcode-cn.com/problems/online-majority-element-in-subarray/
* @TranslatedContent:实现一个 MajorityChecker 的类,它应该具有下述几个 API:
MajorityChecker(int[] arr) 会用给定的数组 arr 来构造一个 MajorityChecker 的实例。
int query(int left, int right, int threshold) 有这么几个参数:
0 <= left <= right < arr.length 表示数组 arr 的子数组的长度。
2 * threshold > right - left + 1,也就是说阈值 threshold 始终比子序列长度的一半还要大。
每次查询 query(...) 会返回在 arr[left], arr[left+1], ..., arr[right] 中至少出现阈值次数 threshold 的元素,如果不存在这样的元素,就返回 -1。
示例:
MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // 返回 1
majorityChecker.query(0,3,3); // 返回 -1
majorityChecker.query(2,3,2); // 返回 2
提示:
1 <= arr.length <= 20000
1 <= arr[i] <= 20000
对于每次查询,0 <= left <= right < len(arr)
对于每次查询,2 * threshold > right - left + 1
查询次数最多为 10000
*/
class MajorityChecker {
public MajorityChecker(int[] arr) {
}
public int query(int left, int right, int threshold) {
}
}
/**
* Your MajorityChecker object will be instantiated and called as such:
* MajorityChecker obj = new MajorityChecker(arr);
* int param_1 = obj.query(left,right,threshold);
*/<file_sep>package com.LeetCode.code.q150.EvaluateReversePolishNotation;
/**
* @QuestionId : 150
* @difficulty : Medium
* @Title : Evaluate Reverse Polish Notation
* @TranslatedTitle:逆波兰表达式求值
* @url : https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
* @TranslatedContent:根据<a href="https://baike.baidu.com/item/%E9%80%86%E6%B3%A2%E5%85%B0%E5%BC%8F/128437" target="_blank">逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:
输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6
示例 3:
输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
输出: 22
解释:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
*/
class Solution {
public int evalRPN(String[] tokens) {
}
}<file_sep>package com.LeetCode.code.q83.RemoveDuplicatesfromSortedList;
/**
* @QuestionId : 83
* @difficulty : Easy
* @Title : Remove Duplicates from Sorted List
* @TranslatedTitle:删除排序链表中的重复元素
* @url : https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
* @TranslatedContent:给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
}
}<file_sep>package com.LeetCode.code.q1249.SnapshotArray;
/**
* @QuestionId : 1249
* @difficulty : Medium
* @Title : Snapshot Array
* @TranslatedTitle:快照数组
* @url : https://leetcode-cn.com/problems/snapshot-array/
* @TranslatedContent:实现支持下列接口的「快照数组」- SnapshotArray:
SnapshotArray(int length) - 初始化一个与指定长度相等的 类数组 的数据结构。初始时,每个元素都等于 0。
void set(index, val) - 会将指定索引 index 处的元素设置为 val。
int snap() - 获取该数组的快照,并返回快照的编号 snap_id(快照号是调用 snap() 的总次数减去 1)。
int get(index, snap_id) - 根据指定的 snap_id 选择快照,并返回该快照指定索引 index 的值。
示例:
输入:["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]]
输出:[null,null,0,null,5]
解释:
SnapshotArray snapshotArr = new SnapshotArray(3); // 初始化一个长度为 3 的快照数组
snapshotArr.set(0,5); // 令 array[0] = 5
snapshotArr.snap(); // 获取快照,返回 snap_id = 0
snapshotArr.set(0,6);
snapshotArr.get(0,0); // 获取 snap_id = 0 的快照中 array[0] 的值,返回 5
提示:
1 <= length <= 50000
题目最多进行50000 次set,snap,和 get的调用 。
0 <= index < length
0 <= snap_id < 我们调用 snap() 的总次数
0 <= val <= 10^9
*/
class SnapshotArray {
public SnapshotArray(int length) {
}
public void set(int index, int val) {
}
public int snap() {
}
public int get(int index, int snap_id) {
}
}
/**
* Your SnapshotArray object will be instantiated and called as such:
* SnapshotArray obj = new SnapshotArray(length);
* obj.set(index,val);
* int param_2 = obj.snap();
* int param_3 = obj.get(index,snap_id);
*/<file_sep>package com.LeetCode.code.q436.FindRightInterval;
/**
* @QuestionId : 436
* @difficulty : Medium
* @Title : Find Right Interval
* @TranslatedTitle:寻找右区间
* @url : https://leetcode-cn.com/problems/find-right-interval/
* @TranslatedContent:给定一组区间,对于每一个区间 i,检查是否存在一个区间 j,它的起始点大于或等于区间 i 的终点,这可以称为 j 在 i 的“右侧”。
对于任何区间,你需要存储的满足条件的区间 j 的最小索引,这意味着区间 j 有最小的起始点可以使其成为“右侧”区间。如果区间 j 不存在,则将区间 i 存储为 -1。最后,你需要输出一个值为存储的区间值的数组。
注意:
你可以假设区间的终点总是大于它的起始点。
你可以假定这些区间都不具有相同的起始点。
示例 1:
输入: [ [1,2] ]
输出: [-1]
解释:集合中只有一个区间,所以输出-1。
示例 2:
输入: [ [3,4], [2,3], [1,2] ]
输出: [-1, 0, 1]
解释:对于[3,4],没有满足条件的“右侧”区间。
对于[2,3],区间[3,4]具有最小的“右”起点;
对于[1,2],区间[2,3]具有最小的“右”起点。
示例 3:
输入: [ [1,4], [2,3], [3,4] ]
输出: [-1, 2, -1]
解释:对于区间[1,4]和[3,4],没有满足条件的“右侧”区间。
对于[2,3],区间[3,4]有最小的“右”起点。
*/
class Solution {
public int[] findRightInterval(int[][] intervals) {
}
}<file_sep>package com.LeetCode.code.q797.RabbitsinForest;
/**
* @QuestionId : 797
* @difficulty : Medium
* @Title : Rabbits in Forest
* @TranslatedTitle:森林中的兔子
* @url : https://leetcode-cn.com/problems/rabbits-in-forest/
* @TranslatedContent:森林中,每个兔子都有颜色。其中一些兔子(可能是全部)告诉你还有多少其他的兔子和自己有相同的颜色。我们将这些回答放在 answers 数组里。
返回森林中兔子的最少数量。
示例:
输入: answers = [1, 1, 2]
输出: 5
解释:
两只回答了 "1" 的兔子可能有相同的颜色,设为红色。
之后回答了 "2" 的兔子不会是红色,否则他们的回答会相互矛盾。
设回答了 "2" 的兔子为蓝色。
此外,森林中还应有另外 2 只蓝色兔子的回答没有包含在数组中。
因此森林中兔子的最少数量是 5: 3 只回答的和 2 只没有回答的。
输入: answers = [10, 10, 10]
输出: 11
输入: answers = []
输出: 0
说明:
answers 的长度最大为1000。
answers[i] 是在 [0, 999] 范围内的整数。
*/
class Solution {
public int numRabbits(int[] answers) {
}
}<file_sep>package com.LeetCode.code.q1128.RemoveAllAdjacentDuplicatesInString;
/**
* @QuestionId : 1128
* @difficulty : Easy
* @Title : Remove All Adjacent Duplicates In String
* @TranslatedTitle:删除字符串中的所有相邻重复项
* @url : https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string/
* @TranslatedContent:给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例:
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
提示:
1 <= S.length <= 20000
S 仅由小写英文字母组成。
*/
class Solution {
public String removeDuplicates(String S) {
}
}<file_sep>package com.LeetCode.code.q91.DecodeWays;
/**
* @QuestionId : 91
* @difficulty : Medium
* @Title : Decode Ways
* @TranslatedTitle:解码方法
* @url : https://leetcode-cn.com/problems/decode-ways/
* @TranslatedContent:一条包含字母 A-Z 的消息通过以下方式进行了编码:
'A' -> 1
'B' -> 2
...
'Z' -> 26
给定一个只包含数字的非空字符串,请计算解码方法的总数。
示例 1:
输入: "12"
输出: 2
解释: 它可以解码为 "AB"(1 2)或者 "L"(12)。
示例 2:
输入: "226"
输出: 3
解释: 它可以解码为 "BZ" (2 26), "VF" (22 6), 或者 "BBF" (2 2 6) 。
*/
class Solution {
public int numDecodings(String s) {
}
}<file_sep>package com.LeetCode.code.q1188.BraceExpansionII;
/**
* @QuestionId : 1188
* @difficulty : Hard
* @Title : Brace Expansion II
* @TranslatedTitle:花括号展开 II
* @url : https://leetcode-cn.com/problems/brace-expansion-ii/
* @TranslatedContent:如果你熟悉 Shell 编程,那么一定了解过花括号展开,它可以用来生成任意字符串。
花括号展开的表达式可以看作一个由 花括号、逗号 和 小写英文字母 组成的字符串,定义下面几条语法规则:
如果只给出单一的元素 x,那么表达式表示的字符串就只有 "x"。
例如,表达式 {a} 表示字符串 "a"。
而表达式 {ab} 就表示字符串 "ab"。
当两个或多个表达式并列,以逗号分隔时,我们取这些表达式中元素的并集。
例如,表达式 {a,b,c} 表示字符串 "a","b","c"。
而表达式 {a,b},{b,c} 也可以表示字符串 "a","b","c"。
要是两个或多个表达式相接,中间没有隔开时,我们从这些表达式中各取一个元素依次连接形成字符串。
例如,表达式 {a,b}{c,d} 表示字符串 "ac","ad","bc","bd"。
表达式之间允许嵌套,单一元素与表达式的连接也是允许的。
例如,表达式 a{b,c,d} 表示字符串 "ab","ac","ad"。
例如,表达式 {a{b,c}}{{d,e}f{g,h}} 可以代换为 {ab,ac}{dfg,dfh,efg,efh},表示字符串 "abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"。
给出表示基于给定语法规则的表达式 expression,返回它所表示的所有字符串组成的有序列表。
假如你希望以「集合」的概念了解此题,也可以通过点击 “显示英文描述” 获取详情。
示例 1:
输入:"{a,b}{c{d,e}}"
输出:["acd","ace","bcd","bce"]
示例 2:
输入:"{{a,z}, a{b,c}, {ab,z}}"
输出:["a","ab","ac","z"]
解释:输出中 不应 出现重复的组合结果。
提示:
1 <= expression.length <= 50
expression[i] 由 '{','}',',' 或小写英文字母组成
给出的表达式 expression 用以表示一组基于题目描述中语法构造的字符串
*/
class Solution {
public List<String> braceExpansionII(String expression) {
}
}<file_sep>package com.LeetCode.code.q52.N-QueensII;
/**
* @QuestionId : 52
* @difficulty : Hard
* @Title : N-Queens II
* @TranslatedTitle:N皇后 II
* @url : https://leetcode-cn.com/problems/n-queens-ii/
* @TranslatedContent:n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/12/8-queens.png" style="height: 276px; width: 258px;">
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回 n 皇后不同的解决方案的数量。
示例:
输入: 4
输出: 2
解释: 4 皇后问题存在如下两个不同的解法。
[
[".Q..", // 解法 1
"...Q",
"Q...",
"..Q."],
["..Q.", // 解法 2
"Q...",
"...Q",
".Q.."]
]
*/
class Solution {
public int totalNQueens(int n) {
}
}<file_sep>package com.LeetCode.code.q1016.SubarraySumsDivisiblebyK;
/**
* @QuestionId : 1016
* @difficulty : Medium
* @Title : Subarray Sums Divisible by K
* @TranslatedTitle:和可被 K 整除的子数组
* @url : https://leetcode-cn.com/problems/subarray-sums-divisible-by-k/
* @TranslatedContent:给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续、非空)子数组的数目。
示例:
输入:A = [4,5,0,-2,-3,1], K = 5
输出:7
解释:
有 7 个子数组满足其元素之和可被 K = 5 整除:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
提示:
1 <= A.length <= 30000
-10000 <= A[i] <= 10000
2 <= K <= 10000
*/
class Solution {
public int subarraysDivByK(int[] A, int K) {
}
}<file_sep>package com.LeetCode.code.q542.01Matrix;
/**
* @QuestionId : 542
* @difficulty : Medium
* @Title : 01 Matrix
* @TranslatedTitle:01 矩阵
* @url : https://leetcode-cn.com/problems/01-matrix/
* @TranslatedContent:给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1: <br />
输入:
0 0 0
0 1 0
0 0 0
输出:
0 0 0
0 1 0
0 0 0
示例 2: <br />
输入:
0 0 0
0 1 0
1 1 1
输出:
0 0 0
0 1 0
1 2 1
注意:
给定矩阵的元素个数不超过 10000。
给定矩阵中至少有一个元素是 0。
矩阵中的元素只在四个方向上相邻: 上、下、左、右。
*/
class Solution {
public int[][] updateMatrix(int[][] matrix) {
}
}<file_sep>package com.LeetCode.code.q64.MinimumPathSum;
/**
* @QuestionId : 64
* @difficulty : Medium
* @Title : Minimum Path Sum
* @TranslatedTitle:最小路径和
* @url : https://leetcode-cn.com/problems/minimum-path-sum/
* @TranslatedContent:给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
示例:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。
*/
class Solution {
public int minPathSum(int[][] grid) {
}
}<file_sep>package com.LeetCode.code.q1228.MinimumCostTreeFromLeafValues;
/**
* @QuestionId : 1228
* @difficulty : Medium
* @Title : Minimum Cost Tree From Leaf Values
* @TranslatedTitle:叶值的最小代价生成树
* @url : https://leetcode-cn.com/problems/minimum-cost-tree-from-leaf-values/
* @TranslatedContent:给你一个正整数数组 arr,考虑所有满足以下条件的二叉树:
每个节点都有 0 个或是 2 个子节点。
数组 arr 中的值与树的中序遍历中每个叶节点的值一一对应。(知识回顾:如果一个节点有 0 个子节点,那么该节点为叶节点。)
每个非叶节点的值等于其左子树和右子树中叶节点的最大值的乘积。
在所有这样的二叉树中,返回每个非叶节点的值的最小可能总和。这个和的值是一个 32 位整数。
示例:
输入:arr = [6,2,4]
输出:32
解释:
有两种可能的树,第一种的非叶节点的总和为 36,第二种非叶节点的总和为 32。
24 24
/ \ / \
12 4 6 8
/ \ / \
6 2 2 4
提示:
2 <= arr.length <= 40
1 <= arr[i] <= 15
答案保证是一个 32 位带符号整数,即小于 2^31。
*/
class Solution {
public int mctFromLeafValues(int[] arr) {
}
}<file_sep>package com.LeetCode.code.q835.LinkedListComponents;
/**
* @QuestionId : 835
* @difficulty : Medium
* @Title : Linked List Components
* @TranslatedTitle:链表组件
* @url : https://leetcode-cn.com/problems/linked-list-components/
* @TranslatedContent:给定一个链表(链表结点包含一个整型值)的头结点 head。
同时给定列表 G,该列表是上述链表中整型值的一个子集。
返回列表 G 中组件的个数,这里对组件的定义为:链表中一段最长连续结点的值(该值必须在列表 G 中)构成的集合。
示例 1:
输入:
head: 0->1->2->3
G = [0, 1, 3]
输出: 2
解释:
链表中,0 和 1 是相连接的,且 G 中不包含 2,所以 [0, 1] 是 G 的一个组件,同理 [3] 也是一个组件,故返回 2。
示例 2:
输入:
head: 0->1->2->3->4
G = [0, 3, 1, 4]
输出: 2
解释:
链表中,0 和 1 是相连接的,3 和 4 是相连接的,所以 [0, 1] 和 [3, 4] 是两个组件,故返回 2。
注意:
如果 N 是给定链表 head 的长度,1 <= N <= 10000。
链表中每个结点的值所在范围为 [0, N - 1]。
1 <= G.length <= 10000
G 是链表中所有结点的值的一个子集.
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int numComponents(ListNode head, int[] G) {
}
}<file_sep>package com.LeetCode.code.q33.SearchinRotatedSortedArray;
/**
* @QuestionId : 33
* @difficulty : Medium
* @Title : Search in Rotated Sorted Array
* @TranslatedTitle:搜索旋转排序数组
* @url : https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
* @TranslatedContent:假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
*/
class Solution {
public int search(int[] nums, int target) {
}
}<file_sep>package com.LeetCode.code.q28.ImplementstrStr();
/**
* @QuestionId : 28
* @difficulty : Easy
* @Title : Implement strStr()
* @TranslatedTitle:实现 strStr()
* @url : https://leetcode-cn.com/problems/implement-strstr/
* @TranslatedContent:实现 <a href="https://baike.baidu.com/item/strstr/811469" target="_blank">strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 <a href="https://baike.baidu.com/item/strstr/811469" target="_blank">strstr() 以及 Java的 <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String)" target="_blank">indexOf() 定义相符。
*/
class Solution {
public int strStr(String haystack, String needle) {
}
}<file_sep>package com.LeetCode.code.q648.ReplaceWords;
/**
* @QuestionId : 648
* @difficulty : Medium
* @Title : Replace Words
* @TranslatedTitle:单词替换
* @url : https://leetcode-cn.com/problems/replace-words/
* @TranslatedContent:在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。
现在,给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。
你需要输出替换之后的句子。
示例 1:
输入: dict(词典) = ["cat", "bat", "rat"]
sentence(句子) = "the cattle was rattled by the battery"
输出: "the cat was rat by the bat"
注:
输入只包含小写字母。
1 <= 字典单词数 <=1000
1 <= 句中词语数 <= 1000
1 <= 词根长度 <= 100
1 <= 句中词语长度 <= 1000
*/
class Solution {
public String replaceWords(List<String> dict, String sentence) {
}
}<file_sep>package com.LeetCode.code.q236.LowestCommonAncestorofaBinaryTree;
/**
* @QuestionId : 236
* @difficulty : Medium
* @Title : Lowest Common Ancestor of a Binary Tree
* @TranslatedTitle:二叉树的最近公共祖先
* @url : https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
* @TranslatedContent:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
<a href="https://baike.baidu.com/item/%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88/8918834?fr=aladdin" target="_blank">百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉树: root = [3,5,1,6,2,0,8,null,null,7,4]
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/15/binarytree.png" style="height: 190px; width: 200px;">
示例 1:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。
示例 2:
输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。
说明:
所有节点的值都是唯一的。
p、q 为不同节点且均存在于给定的二叉树中。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
}
}<file_sep>package com.LeetCode.code.q1021.DistributeCoinsinBinaryTree;
/**
* @QuestionId : 1021
* @difficulty : Medium
* @Title : Distribute Coins in Binary Tree
* @TranslatedTitle:在二叉树中分配硬币
* @url : https://leetcode-cn.com/problems/distribute-coins-in-binary-tree/
* @TranslatedContent:给定一个有 N 个结点的二叉树的根结点 root,树中的每个结点上都对应有 node.val 枚硬币,并且总共有 N 枚硬币。
在一次移动中,我们可以选择两个相邻的结点,然后将一枚硬币从其中一个结点移动到另一个结点。(移动可以是从父结点到子结点,或者从子结点移动到父结点。)。
返回使每个结点上只有一枚硬币所需的移动次数。
示例 1:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/01/19/tree1.png" style="height: 142px; width: 150px;">
输入:[3,0,0]
输出:2
解释:从树的根结点开始,我们将一枚硬币移到它的左子结点上,一枚硬币移到它的右子结点上。
示例 2:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/01/19/tree2.png" style="height: 142px; width: 150px;">
输入:[0,3,0]
输出:3
解释:从根结点的左子结点开始,我们将两枚硬币移到根结点上 [移动两次]。然后,我们把一枚硬币从根结点移到右子结点上。
示例 3:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/01/19/tree3.png" style="height: 142px; width: 150px;">
输入:[1,0,2]
输出:2
示例 4:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/01/19/tree4.png" style="height: 156px; width: 155px;">
输入:[1,0,0,null,3]
输出:4
提示:
1<= N <= 100
0 <= node.val <= N
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int distributeCoins(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q65.ValidNumber;
/**
* @QuestionId : 65
* @difficulty : Hard
* @Title : Valid Number
* @TranslatedTitle:有效数字
* @url : https://leetcode-cn.com/problems/valid-number/
* @TranslatedContent:验证给定的字符串是否可以解释为十进制数字。
例如:
"0" => true
" 0.1 " => true
"abc" => false
"1 a" => false
"2e10" => true
" -90e3 " => true
" 1e" => false
"e3" => false
" 6e-1" => true
" 99e2.5 " => false
"53.5e93" => true
" --6 " => false
"-+3" => false
"95a54e53" => false
说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。这里给出一份可能存在于有效十进制数字中的字符列表:
数字 0-9
指数 - "e"
正/负号 - "+"/"-"
小数点 - "."
当然,在输入中,这些字符的上下文也很重要。
更新于 2015-02-10:
C++函数的形式已经更新了。如果你仍然看见你的函数接收 const char * 类型的参数,请点击重载按钮重置你的代码。
*/
class Solution {
public boolean isNumber(String s) {
}
}<file_sep>package com.LeetCode.code.q336.PalindromePairs;
/**
* @QuestionId : 336
* @difficulty : Hard
* @Title : Palindrome Pairs
* @TranslatedTitle:回文对
* @url : https://leetcode-cn.com/problems/palindrome-pairs/
* @TranslatedContent:给定一组唯一的单词, 找出所有不同 的索引对(i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。
示例 1:
输入: ["abcd","dcba","lls","s","sssll"]
输出: [[0,1],[1,0],[3,2],[2,4]]
解释: 可拼接成的回文串为 ["dcbaabcd","abcddcba","slls","llssssll"]
示例 2:
输入: ["bat","tab","cat"]
输出: [[0,1],[1,0]]
解释: 可拼接成的回文串为 ["battab","tabbat"]
*/
class Solution {
public List<List<Integer>> palindromePairs(String[] words) {
}
}<file_sep>package com.LeetCode.code.q341.FlattenNestedListIterator;
/**
* @QuestionId : 341
* @difficulty : Medium
* @Title : Flatten Nested List Iterator
* @TranslatedTitle:扁平化嵌套列表迭代器
* @url : https://leetcode-cn.com/problems/flatten-nested-list-iterator/
* @TranslatedContent:给定一个嵌套的整型列表。设计一个迭代器,使其能够遍历这个整型列表中的所有整数。
列表中的项或者为一个整数,或者是另一个列表。
示例 1:
输入: [[1,1],2,[1,1]]
输出: [1,1,2,1,1]
解释: 通过重复调用 next 直到 hasNext 返回false,next 返回的元素的顺序应该是: [1,1,2,1,1]。
示例 2:
输入: [1,[4,[6]]]
输出: [1,4,6]
解释: 通过重复调用 next 直到 hasNext 返回false,next 返回的元素的顺序应该是: [1,4,6]。
*/
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
public class NestedIterator implements Iterator<Integer> {
public NestedIterator(List<NestedInteger> nestedList) {
}
@Override
public Integer next() {
}
@Override
public boolean hasNext() {
}
}
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i = new NestedIterator(nestedList);
* while (i.hasNext()) v[f()] = i.next();
*/<file_sep>package com.LeetCode.code.q895.ShortestPathtoGetAllKeys;
/**
* @QuestionId : 895
* @difficulty : Hard
* @Title : Shortest Path to Get All Keys
* @TranslatedTitle:获取所有钥匙的最短路径
* @url : https://leetcode-cn.com/problems/shortest-path-to-get-all-keys/
* @TranslatedContent:给定一个二维网格 grid。 "." 代表一个空房间, "#" 代表一堵墙, "@" 是起点,("a", "b", ...)代表钥匙,("A", "B", ...)代表锁。
我们从起点开始出发,一次移动是指向四个基本方向之一行走一个单位空间。我们不能在网格外面行走,也无法穿过一堵墙。如果途经一个钥匙,我们就把它捡起来。除非我们手里有对应的钥匙,否则无法通过锁。
假设 K 为钥匙/锁的个数,且满足 1 <= K <= 6,字母表中的前 K 个字母在网格中都有自己对应的一个小写和一个大写字母。换言之,每个锁有唯一对应的钥匙,每个钥匙也有唯一对应的锁。另外,代表钥匙和锁的字母互为大小写并按字母顺序排列。
返回获取所有钥匙所需要的移动的最少次数。如果无法获取所有钥匙,返回 -1 。
示例 1:
输入:["@.a.#","###.#","b.A.B"]
输出:8
示例 2:
输入:["@..aA","..B#.","....b"]
输出:6
提示:
1 <= grid.length <= 30
1 <= grid[0].length <= 30
grid[i][j] 只含有 '.', '#', '@', 'a'-'f' 以及 'A'-'F'
钥匙的数目范围是 [1, 6],每个钥匙都对应一个不同的字母,正好打开一个对应的锁。
*/
class Solution {
public int shortestPathAllKeys(String[] grid) {
}
}<file_sep>package com.LeetCode.code.q292.NimGame;
/**
* @QuestionId : 292
* @difficulty : Easy
* @Title : Nim Game
* @TranslatedTitle:Nim 游戏
* @url : https://leetcode-cn.com/problems/nim-game/
* @TranslatedContent:你和你的朋友,两个人一起玩 <a href="https://baike.baidu.com/item/Nim游戏/6737105" target="_blank">Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。
你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
示例:
输入: 4
输出: false
解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
*/
class Solution {
public boolean canWinNim(int n) {
}
}<file_sep>package com.LeetCode.code.q572.SubtreeofAnotherTree;
/**
* @QuestionId : 572
* @difficulty : Easy
* @Title : Subtree of Another Tree
* @TranslatedTitle:另一个树的子树
* @url : https://leetcode-cn.com/problems/subtree-of-another-tree/
* @TranslatedContent:给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。
示例 1:<br />
给定的树 s:
3
/ \
4 5
/ \
1 2
给定的树 t:
4
/ \
1 2
返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。
示例 2:<br />
给定的树 s:
3
/ \
4 5
/ \
1 2
/
0
给定的树 t:
4
/ \
1 2
返回 false。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
}
}<file_sep>package com.LeetCode.code.q1065.BinaryStringWithSubstringsRepresenting1ToN;
/**
* @QuestionId : 1065
* @difficulty : Medium
* @Title : Binary String With Substrings Representing 1 To N
* @TranslatedTitle:子串能表示从 1 到 N 数字的二进制串
* @url : https://leetcode-cn.com/problems/binary-string-with-substrings-representing-1-to-n/
* @TranslatedContent:给定一个二进制字符串 S(一个仅由若干 '0' 和 '1' 构成的字符串)和一个正整数 N,如果对于从 1 到 N 的每个整数 X,其二进制表示都是 S 的子串,就返回 true,否则返回 false。
示例 1:
输入:S = "0110", N = 3
输出:true
示例 2:
输入:S = "0110", N = 4
输出:false
提示:
1 <= S.length <= 1000
1 <= N <= 10^9
*/
class Solution {
public boolean queryString(String S, int N) {
}
}<file_sep>package com.LeetCode.code.q675.CutOffTreesforGolfEvent;
/**
* @QuestionId : 675
* @difficulty : Hard
* @Title : Cut Off Trees for Golf Event
* @TranslatedTitle:为高尔夫比赛砍树
* @url : https://leetcode-cn.com/problems/cut-off-trees-for-golf-event/
* @TranslatedContent:你被请来给一个要举办高尔夫比赛的树林砍树. 树林由一个非负的二维数组表示, 在这个数组中:
0 表示障碍,无法触碰到.
1 表示可以行走的地面.
比1大的数 表示一颗允许走过的树的高度.
你被要求按照树的高度从低向高砍掉所有的树,每砍过一颗树,树的高度变为1。
你将从(0,0)点开始工作,你应该返回你砍完所有树需要走的最小步数。 如果你无法砍完所有的树,返回 -1 。
可以保证的是,没有两棵树的高度是相同的,并且至少有一颗树需要你砍。
示例 1:
输入:
[
[1,2,3],
[0,0,4],
[7,6,5]
]
输出: 6
示例 2:
输入:
[
[1,2,3],
[0,0,0],
[7,6,5]
]
输出: -1
示例 3:
输入:
[
[2,3,4],
[0,0,5],
[8,7,6]
]
输出: 6
解释: (0,0) 位置的树,你可以直接砍去,不用算步数
提示: 矩阵大小不会超过 50x50 。
*/
class Solution {
public int cutOffTree(List<List<Integer>> forest) {
}
}<file_sep>package com.LeetCode.code.q173.BinarySearchTreeIterator;
/**
* @QuestionId : 173
* @difficulty : Medium
* @Title : Binary Search Tree Iterator
* @TranslatedTitle:二叉搜索树迭代器
* @url : https://leetcode-cn.com/problems/binary-search-tree-iterator/
* @TranslatedContent:实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。
调用 next() 将返回二叉搜索树中的下一个最小的数。
示例:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/25/bst-tree.png" style="height: 178px; width: 189px;">
BSTIterator iterator = new BSTIterator(root);
iterator.next(); // 返回 3
iterator.next(); // 返回 7
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 9
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 15
iterator.hasNext(); // 返回 true
iterator.next(); // 返回 20
iterator.hasNext(); // 返回 false
提示:
next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。
你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class BSTIterator {
public BSTIterator(TreeNode root) {
}
/** @return the next smallest number */
public int next() {
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/<file_sep>package com.LeetCode.code.q940.FruitIntoBaskets;
/**
* @QuestionId : 940
* @difficulty : Medium
* @Title : Fruit Into Baskets
* @TranslatedTitle:水果成篮
* @url : https://leetcode-cn.com/problems/fruit-into-baskets/
* @TranslatedContent:在一排树中,第 i 棵树产生 tree[i] 型的水果。
你可以从你选择的任何树开始,然后重复执行以下步骤:
把这棵树上的水果放进你的篮子里。如果你做不到,就停下来。
移动到当前树右侧的下一棵树。如果右边没有树,就停下来。
请注意,在选择一颗树后,你没有任何选择:你必须执行步骤 1,然后执行步骤 2,然后返回步骤 1,然后执行步骤 2,依此类推,直至停止。
你有两个篮子,每个篮子可以携带任何数量的水果,但你希望每个篮子只携带一种类型的水果。
用这个程序你能收集的水果总量是多少?
示例 1:
输入:[1,2,1]
输出:3
解释:我们可以收集 [1,2,1]。
示例 2:
输入:[0,1,2,2]
输出:3
解释:我们可以收集 [1,2,2].
如果我们从第一棵树开始,我们将只能收集到 [0, 1]。
示例 3:
输入:[1,2,3,2,2]
输出:4
解释:我们可以收集 [2,3,2,2].
如果我们从第一棵树开始,我们将只能收集到 [1, 2]。
示例 4:
输入:[3,3,3,1,2,1,1,2,3,3,4]
输出:5
解释:我们可以收集 [1,2,1,1,2].
如果我们从第一棵树或第八棵树开始,我们将只能收集到 4 个水果。
提示:
1 <= tree.length <= 40000
0 <= tree[i] < tree.length
*/
class Solution {
public int totalFruit(int[] tree) {
}
}<file_sep>package com.LeetCode.code.q1057.NumbersWithRepeatedDigits;
/**
* @QuestionId : 1057
* @difficulty : Hard
* @Title : Numbers With Repeated Digits
* @TranslatedTitle:至少有 1 位重复的数字
* @url : https://leetcode-cn.com/problems/numbers-with-repeated-digits/
* @TranslatedContent:给定正整数 N,返回小于等于 N 且具有至少 1 位重复数字的正整数。
示例 1:
输入:20
输出:1
解释:具有至少 1 位重复数字的正数(<= 20)只有 11 。
示例 2:
输入:100
输出:10
解释:具有至少 1 位重复数字的正数(<= 100)有 11,22,33,44,55,66,77,88,99 和 100 。
示例 3:
输入:1000
输出:262
提示:
1 <= N <= 10^9
*/
class Solution {
public int numDupDigitsAtMostN(int N) {
}
}<file_sep>package com.LeetCode.code.q367.ValidPerfectSquare;
/**
* @QuestionId : 367
* @difficulty : Easy
* @Title : Valid Perfect Square
* @TranslatedTitle:有效的完全平方数
* @url : https://leetcode-cn.com/problems/valid-perfect-square/
* @TranslatedContent:给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
说明:不要使用任何内置的库函数,如 sqrt。
示例 1:
输入:16
输出:True
示例 2:
输入:14
输出:False
*/
class Solution {
public boolean isPerfectSquare(int num) {
}
}<file_sep>package com.LeetCode.code.q726.NumberofAtoms;
/**
* @QuestionId : 726
* @difficulty : Hard
* @Title : Number of Atoms
* @TranslatedTitle:原子的数量
* @url : https://leetcode-cn.com/problems/number-of-atoms/
* @TranslatedContent:给定一个化学式formula(作为字符串),返回每种原子的数量。
原子总是以一个大写字母开始,接着跟随0个或任意个小写字母,表示原子的名字。
如果数量大于 1,原子后会跟着数字表示原子的数量。如果数量等于 1 则不会跟数字。例如,H2O 和 H2O2 是可行的,但 H1O2 这个表达是不可行的。
两个化学式连在一起是新的化学式。例如 H2O2He3Mg4 也是化学式。
一个括号中的化学式和数字(可选择性添加)也是化学式。例如 (H2O2) 和 (H2O2)3 是化学式。
给定一个化学式,输出所有原子的数量。格式为:第一个(按字典序)原子的名子,跟着它的数量(如果数量大于 1),然后是第二个原子的名字(按字典序),跟着它的数量(如果数量大于 1),以此类推。
示例 1:
输入:
formula = "H2O"
输出: "H2O"
解释:
原子的数量是 {'H': 2, 'O': 1}。
示例 2:
输入:
formula = "Mg(OH)2"
输出: "H2MgO2"
解释:
原子的数量是 {'H': 2, 'Mg': 1, 'O': 2}。
示例 3:
输入:
formula = "K4(ON(SO3)2)2"
输出: "K4N2O14S4"
解释:
原子的数量是 {'K': 4, 'N': 2, 'O': 14, 'S': 4}。
注意:
所有原子的第一个字母为大写,剩余字母都是小写。
formula的长度在[1, 1000]之间。
formula只包含字母、数字和圆括号,并且题目中给定的是合法的化学式。
*/
class Solution {
public String countOfAtoms(String formula) {
}
}<file_sep>package com.LeetCode.code.q174.DungeonGame;
/**
* @QuestionId : 174
* @difficulty : Hard
* @Title : Dungeon Game
* @TranslatedTitle:地下城游戏
* @url : https://leetcode-cn.com/problems/dungeon-game/
* @TranslatedContent:
table.dungeon, .dungeon th, .dungeon td {
border:3px solid black;
}
.dungeon th, .dungeon td {
text-align: center;
height: 70px;
width: 70px;
}
一些恶魔抓住了公主(P)并将她关在了地下城的右下角。地下城是由 M x N 个房间组成的二维网格。我们英勇的骑士(K)最初被安置在左上角的房间里,他必须穿过地下城并通过对抗恶魔来拯救公主。
骑士的初始健康点数为一个正整数。如果他的健康点数在某一时刻降至 0 或以下,他会立即死亡。
有些房间由恶魔守卫,因此骑士在进入这些房间时会失去健康点数(若房间里的值为负整数,则表示骑士将损失健康点数);其他房间要么是空的(房间里的值为 0),要么包含增加骑士健康点数的魔法球(若房间里的值为正整数,则表示骑士将增加健康点数)。
为了尽快到达公主,骑士决定每次只向右或向下移动一步。
编写一个函数来计算确保骑士能够拯救到公主所需的最低初始健康点数。
例如,考虑到如下布局的地下城,如果骑士遵循最佳路径 右 -> 右 -> 下 -> 下,则骑士的初始健康点数至少为 7。
<table class="dungeon">
-2 (K)
-3
3
-5
-10
1
10
30
-5 (P)
<!---2K -3 3
-5 -10 1
10 30 5P-->
说明:
骑士的健康点数没有上限。
任何房间都可能对骑士的健康点数造成威胁,也可能增加骑士的健康点数,包括骑士进入的左上角房间以及公主被监禁的右下角房间。
*/
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
}
}<file_sep>package com.LeetCode.code.q7.ReverseInteger;
/**
* @QuestionId : 7
* @difficulty : Easy
* @Title : Reverse Integer
* @TranslatedTitle:整数反转
* @url : https://leetcode-cn.com/problems/reverse-integer/
* @TranslatedContent:给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
*/
class Solution {
public int reverse(int x) {
}
}<file_sep>package com.LeetCode.code.q949.CatandMouse;
/**
* @QuestionId : 949
* @difficulty : Hard
* @Title : Cat and Mouse
* @TranslatedTitle:猫和老鼠
* @url : https://leetcode-cn.com/problems/cat-and-mouse/
* @TranslatedContent:两个玩家分别扮演猫(Cat)和老鼠(Mouse)在无向图上进行游戏,他们轮流行动。
该图按下述规则给出:graph[a] 是所有结点 b 的列表,使得 ab 是图的一条边。
老鼠从结点 1 开始并率先出发,猫从结点 2 开始且随后出发,在结点 0 处有一个洞。
在每个玩家的回合中,他们必须沿着与他们所在位置相吻合的图的一条边移动。例如,如果老鼠位于结点 1,那么它只能移动到 graph[1] 中的(任何)结点去。
此外,猫无法移动到洞(结点 0)里。
然后,游戏在出现以下三种情形之一时结束:
如果猫和老鼠占据相同的结点,猫获胜。
如果老鼠躲入洞里,老鼠获胜。
如果某一位置重复出现(即,玩家们的位置和移动顺序都与上一个回合相同),游戏平局。
给定 graph,并假设两个玩家都以最佳状态参与游戏,如果老鼠获胜,则返回 1;如果猫获胜,则返回 2;如果平局,则返回 0。
示例:
输入:[[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
输出:0
解释:
4---3---1
| |
2---5
\ /
0
提示:
3 <= graph.length <= 200
保证 graph[1] 非空。
保证 graph[2] 包含非零元素。
*/
class Solution {
public int catMouseGame(int[][] graph) {
}
}<file_sep>package com.LeetCode.code.q63.UniquePathsII;
/**
* @QuestionId : 63
* @difficulty : Medium
* @Title : Unique Paths II
* @TranslatedTitle:不同路径 II
* @url : https://leetcode-cn.com/problems/unique-paths-ii/
* @TranslatedContent:一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径?
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/robot_maze.png" style="height: 183px; width: 400px;">
网格中的障碍物和空位置分别用 1 和 0 来表示。
说明:m 和 n 的值均不超过 100。
示例 1:
输入:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
输出: 2
解释:
3x3 网格的正中间有一个障碍物。
从左上角到右下角一共有 2 条不同的路径:
1. 向右 -> 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右 -> 向右
*/
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
}
}<file_sep>package com.LeetCode.code.q939.ValidPermutationsforDISequence;
/**
* @QuestionId : 939
* @difficulty : Hard
* @Title : Valid Permutations for DI Sequence
* @TranslatedTitle:DI 序列的有效排列
* @url : https://leetcode-cn.com/problems/valid-permutations-for-di-sequence/
* @TranslatedContent:我们给出 S,一个源于 {'D', 'I'} 的长度为 n 的字符串 。(这些字母代表 “减少” 和 “增加”。)
有效排列 是对整数 {0, 1, ..., n} 的一个排列 P[0], P[1], ..., P[n],使得对所有的 i:
如果 S[i] == 'D',那么 P[i] > P[i+1],以及;
如果 S[i] == 'I',那么 P[i] < P[i+1]。
有多少个有效排列?因为答案可能很大,所以请返回你的答案模 10^9 + 7.
示例:
输入:"DID"
输出:5
解释:
(0, 1, 2, 3) 的五个有效排列是:
(1, 0, 3, 2)
(2, 0, 3, 1)
(2, 1, 3, 0)
(3, 0, 2, 1)
(3, 1, 2, 0)
提示:
1 <= S.length <= 200
S 仅由集合 {'D', 'I'} 中的字符组成。
*/
class Solution {
public int numPermsDISequence(String S) {
}
}<file_sep>package com.LeetCode.code.q495.TeemoAttacking;
/**
* @QuestionId : 495
* @difficulty : Medium
* @Title : Teemo Attacking
* @TranslatedTitle:提莫攻击
* @url : https://leetcode-cn.com/problems/teemo-attacking/
* @TranslatedContent:在《英雄联盟》的世界中,有一个叫 “提莫” 的英雄,他的攻击可以让敌方英雄艾希(编者注:寒冰射手)进入中毒状态。现在,给出提莫对艾希的攻击时间序列和提莫攻击的中毒持续时间,你需要输出艾希的中毒状态总时长。
你可以认为提莫在给定的时间点进行攻击,并立即使艾希处于中毒状态。
示例1:
输入: [1,4], 2
输出: 4
原因: 在第 1 秒开始时,提莫开始对艾希进行攻击并使其立即中毒。中毒状态会维持 2 秒钟,直到第 2 秒钟结束。
在第 4 秒开始时,提莫再次攻击艾希,使得艾希获得另外 2 秒的中毒时间。
所以最终输出 4 秒。
示例2:
输入: [1,2], 2
输出: 3
原因: 在第 1 秒开始时,提莫开始对艾希进行攻击并使其立即中毒。中毒状态会维持 2 秒钟,直到第 2 秒钟结束。
但是在第 2 秒开始时,提莫再次攻击了已经处于中毒状态的艾希。
由于中毒状态不可叠加,提莫在第 2 秒开始时的这次攻击会在第 3 秒钟结束。
所以最终输出 3。
注意:
你可以假定时间序列数组的总长度不超过 10000。
你可以假定提莫攻击时间序列中的数字和提莫攻击的中毒持续时间都是非负整数,并且不超过 10,000,000。
*/
class Solution {
public int findPoisonedDuration(int[] timeSeries, int duration) {
}
}<file_sep>package com.LeetCode.code.q43.MultiplyStrings;
/**
* @QuestionId : 43
* @difficulty : Medium
* @Title : Multiply Strings
* @TranslatedTitle:字符串相乘
* @url : https://leetcode-cn.com/problems/multiply-strings/
* @TranslatedContent:给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:
输入: num1 = "123", num2 = "456"
输出: "56088"
说明:
num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
*/
class Solution {
public String multiply(String num1, String num2) {
}
}<file_sep>package com.LeetCode.code.q382.LinkedListRandomNode;
/**
* @QuestionId : 382
* @difficulty : Medium
* @Title : Linked List Random Node
* @TranslatedTitle:链表随机节点
* @url : https://leetcode-cn.com/problems/linked-list-random-node/
* @TranslatedContent:给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
进阶:<br />
如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?
示例:
// 初始化一个单链表 [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);
// getRandom()方法应随机返回1,2,3中的一个,保证每个元素被返回的概率相等。
solution.getRandom();
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
public Solution(ListNode head) {
}
/** Returns a random node's value. */
public int getRandom() {
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/<file_sep>package com.LeetCode.code.q375.GuessNumberHigherorLowerII;
/**
* @QuestionId : 375
* @difficulty : Medium
* @Title : Guess Number Higher or Lower II
* @TranslatedTitle:猜数字大小 II
* @url : https://leetcode-cn.com/problems/guess-number-higher-or-lower-ii/
* @TranslatedContent:我们正在玩一个猜数游戏,游戏规则如下:
我从 1 到 n 之间选择一个数字,你来猜我选了哪个数字。
每次你猜错了,我都会告诉你,我选的数字比你的大了或者小了。
然而,当你猜了数字 x 并且猜错了的时候,你需要支付金额为 x 的现金。直到你猜到我选的数字,你才算赢得了这个游戏。
示例:
n = 10, 我选择了8.
第一轮: 你猜我选择的数字是5,我会告诉你,我的数字更大一些,然后你需要支付5块。
第二轮: 你猜是7,我告诉你,我的数字更大一些,你支付7块。
第三轮: 你猜是9,我告诉你,我的数字更小一些,你支付9块。
游戏结束。8 就是我选的数字。
你最终要支付 5 + 7 + 9 = 21 块钱。
给定 n ≥ 1,计算你至少需要拥有多少现金才能确保你能赢得这个游戏。
*/
class Solution {
public int getMoneyAmount(int n) {
}
}<file_sep>package com.LeetCode.code.q211.AddandSearchWord-Datastructuredesign;
/**
* @QuestionId : 211
* @difficulty : Medium
* @Title : Add and Search Word - Data structure design
* @TranslatedTitle:添加与搜索单词 - 数据结构设计
* @url : https://leetcode-cn.com/problems/add-and-search-word-data-structure-design/
* @TranslatedContent:设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
示例:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。
*/
class WordDictionary {
/** Initialize your data structure here. */
public WordDictionary() {
}
/** Adds a word into the data structure. */
public void addWord(String word) {
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/<file_sep>package com.LeetCode.code.q820.FindEventualSafeStates;
/**
* @QuestionId : 820
* @difficulty : Medium
* @Title : Find Eventual Safe States
* @TranslatedTitle:找到最终的安全状态
* @url : https://leetcode-cn.com/problems/find-eventual-safe-states/
* @TranslatedContent:在有向图中, 我们从某个节点和每个转向处开始, 沿着图的有向边走。 如果我们到达的节点是终点 (即它没有连出的有向边), 我们停止。
现在, 如果我们最后能走到终点,那么我们的起始节点是最终安全的。 更具体地说, 存在一个自然数 K, 无论选择从哪里开始行走, 我们走了不到 K 步后必能停止在一个终点。
哪些节点最终是安全的? 结果返回一个有序的数组。
该有向图有 N 个节点,标签为 0, 1, ..., N-1, 其中 N 是 graph 的节点数. 图以以下的形式给出: graph[i] 是节点 j 的一个列表,满足 (i, j) 是图的一条有向边。
示例:
输入:graph = [[1,2],[2,3],[5],[0],[5],[],[]]
输出:[2,4,5,6]
这里是上图的示意图。
<img alt="Illustration of graph" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/03/17/picture1.png" style="height:86px; width:300px" />
提示:
graph 节点数不超过 10000.
图的边数不会超过 32000.
每个 graph[i] 被排序为不同的整数列表, 在区间 [0, graph.length - 1] 中选取。
*/
class Solution {
public List<Integer> eventualSafeNodes(int[][] graph) {
}
}<file_sep>package com.LeetCode.code.q1093.RecoveraTreeFromPreorderTraversal;
/**
* @QuestionId : 1093
* @difficulty : Hard
* @Title : Recover a Tree From Preorder Traversal
* @TranslatedTitle:从先序遍历还原二叉树
* @url : https://leetcode-cn.com/problems/recover-a-tree-from-preorder-traversal/
* @TranslatedContent:我们从二叉树的根节点 root 开始进行深度优先搜索。
在遍历中的每个节点处,我们输出 D 条短划线(其中 D 是该节点的深度),然后输出该节点的值。(如果节点的深度为 D,则其直接子节点的深度为 D + 1。根节点的深度为 0)。
如果节点只有一个子节点,那么保证该子节点为左子节点。
给出遍历输出 S,还原树并返回其根节点 root。
示例 1:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/04/12/recover-a-tree-from-preorder-traversal.png" style="height: 200px; width: 320px;">
输入:"1-2--3--4-5--6--7"
输出:[1,2,5,3,4,6,7]
示例 2:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/04/12/screen-shot-2019-04-10-at-114101-pm.png" style="height: 250px; width: 256px;">
输入:"1-2--3---4-5--6---7"
输出:[1,2,5,3,null,6,null,4,null,7]
示例 3:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/04/12/screen-shot-2019-04-10-at-114955-pm.png" style="height: 250px; width: 276px;">
输入:"1-401--349---90--88"
输出:[1,401,null,349,88,90]
提示:
原始树中的节点数介于 1 和 1000 之间。
每个节点的值介于 1 和 10 ^ 9 之间。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode recoverFromPreorder(String S) {
}
}<file_sep>package com.LeetCode.code.q864.ImageOverlap;
/**
* @QuestionId : 864
* @difficulty : Medium
* @Title : Image Overlap
* @TranslatedTitle:图像重叠
* @url : https://leetcode-cn.com/problems/image-overlap/
* @TranslatedContent:给出两个图像 A 和 B ,A 和 B 为大小相同的二维正方形矩阵。(并且为二进制矩阵,只包含0和1)。
我们转换其中一个图像,向左,右,上,或下滑动任何数量的单位,并把它放在另一个图像的上面。之后,该转换的重叠是指两个图像都具有 1 的位置的数目。
(请注意,转换不包括向任何方向旋转。)
最大可能的重叠是什么?
示例 1:
输入:A = [[1,1,0],
[0,1,0],
[0,1,0]]
B = [[0,0,0],
[0,1,1],
[0,0,1]]
输出:3
解释: 将 A 向右移动一个单位,然后向下移动一个单位。
注意:
1 <= A.length = A[0].length = B.length = B[0].length <= 30
0 <= A[i][j], B[i][j] <= 1
*/
class Solution {
public int largestOverlap(int[][] A, int[][] B) {
}
}<file_sep>package com.LeetCode.code.q983.ValidateStackSequences;
/**
* @QuestionId : 983
* @difficulty : Medium
* @Title : Validate Stack Sequences
* @TranslatedTitle:验证栈序列
* @url : https://leetcode-cn.com/problems/validate-stack-sequences/
* @TranslatedContent:给定 pushed 和 popped 两个序列,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。
示例 1:
输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
示例 2:
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。
提示:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed 是 popped 的排列。
*/
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
}
}<file_sep>package com.LeetCode.code.q967.MinimumFallingPathSum;
/**
* @QuestionId : 967
* @difficulty : Medium
* @Title : Minimum Falling Path Sum
* @TranslatedTitle:下降路径最小和
* @url : https://leetcode-cn.com/problems/minimum-falling-path-sum/
* @TranslatedContent:给定一个方形整数数组 A,我们想要得到通过 A 的下降路径的最小和。
下降路径可以从第一行中的任何元素开始,并从每一行中选择一个元素。在下一行选择的元素和当前行所选元素最多相隔一列。
示例:
输入:[[1,2,3],[4,5,6],[7,8,9]]
输出:12
解释:
可能的下降路径有:
[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]
[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]
[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]
和最小的下降路径是 [1,4,7],所以答案是 12。
提示:
1 <= A.length == A[0].length <= 100
-100 <= A[i][j] <= 100
*/
class Solution {
public int minFallingPathSum(int[][] A) {
}
}<file_sep>package com.LeetCode.code.q1247.DecreaseElementsToMakeArrayZigzag;
/**
* @QuestionId : 1247
* @difficulty : Medium
* @Title : Decrease Elements To Make Array Zigzag
* @TranslatedTitle:递减元素使数组呈锯齿状
* @url : https://leetcode-cn.com/problems/decrease-elements-to-make-array-zigzag/
* @TranslatedContent:给你一个整数数组 nums,每次 操作 会从中选择一个元素并 将该元素的值减少 1。
如果符合下列情况之一,则数组 A 就是 锯齿数组:
每个偶数索引对应的元素都大于相邻的元素,即 A[0] > A[1] < A[2] > A[3] < A[4] > ...
或者,每个奇数索引对应的元素都大于相邻的元素,即 A[0] < A[1] > A[2] < A[3] > A[4] < ...
返回将数组 nums 转换为锯齿数组所需的最小操作次数。
示例 1:
输入:nums = [1,2,3]
输出:2
解释:我们可以把 2 递减到 0,或把 3 递减到 1。
示例 2:
输入:nums = [9,6,1,6,2]
输出:4
提示:
1 <= nums.length <= 1000
1 <= nums[i] <= 1000
*/
class Solution {
public int movesToMakeZigzag(int[] nums) {
}
}<file_sep>/**
* Copyright 2019 bejson.com
*/
package com.LeetCode.spider;
/**
* Auto-generated: 2019-09-23 17:19:28
*
* @author bejson.com (<EMAIL>)
* @website http://www.bejson.com/java2pojo/
*/
public class Translations {
private String title;
private String questionId;
private String __typename;
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setQuestionId(String questionId) {
this.questionId = questionId;
}
public String getQuestionId() {
return questionId;
}
public void set__typename(String __typename) {
this.__typename = __typename;
}
public String get__typename() {
return __typename;
}
}<file_sep>package com.LeetCode.code.q824.NumberofLinesToWriteString;
/**
* @QuestionId : 824
* @difficulty : Easy
* @Title : Number of Lines To Write String
* @TranslatedTitle:写字符串需要的行数
* @url : https://leetcode-cn.com/problems/number-of-lines-to-write-string/
* @TranslatedContent:我们要把给定的字符串 S 从左到右写到每一行上,每一行的最大宽度为100个单位,如果我们在写某个字母的时候会使这行超过了100 个单位,那么我们应该把这个字母写到下一行。我们给定了一个数组 widths ,这个数组 widths[0] 代表 'a' 需要的单位, widths[1] 代表 'b' 需要的单位,..., widths[25] 代表 'z' 需要的单位。
现在回答两个问题:至少多少行能放下S,以及最后一行使用的宽度是多少个单位?将你的答案作为长度为2的整数列表返回。
示例 1:
输入:
widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
S = "abcdefghijklmnopqrstuvwxyz"
输出: [3, 60]
解释:
所有的字符拥有相同的占用单位10。所以书写所有的26个字母,
我们需要2个整行和占用60个单位的一行。
示例 2:
输入:
widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
S = "bbbcccdddaaa"
输出: [2, 4]
解释:
除去字母'a'所有的字符都是相同的单位10,并且字符串 "bbbcccdddaa" 将会覆盖 9 * 10 + 2 * 4 = 98 个单位.
最后一个字母 'a' 将会被写到第二行,因为第一行只剩下2个单位了。
所以,这个答案是2行,第二行有4个单位宽度。
注:
字符串 S 的长度在 [1, 1000] 的范围。
S 只包含小写字母。
widths 是长度为 26的数组。
widths[i] 值的范围在 [2, 10]。
*/
class Solution {
public int[] numberOfLines(int[] widths, String S) {
}
}<file_sep>package com.LeetCode.code.q1.TwoSum;
/**
* @QuestionId : 1
* @difficulty : Easy
* @Title : Two Sum
* @TranslatedTitle:两数之和
* @url : https://leetcode-cn.com/problems/two-sum/
* @TranslatedContent:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
}
}<file_sep>package com.LeetCode.code.q1027.SumofEvenNumbersAfterQueries;
/**
* @QuestionId : 1027
* @difficulty : Easy
* @Title : Sum of Even Numbers After Queries
* @TranslatedTitle:查询后的偶数和
* @url : https://leetcode-cn.com/problems/sum-of-even-numbers-after-queries/
* @TranslatedContent:给出一个整数数组 A 和一个查询数组 queries。
对于第 i 次查询,有 val = queries[i][0], index = queries[i][1],我们会把 val 加到 A[index] 上。然后,第 i 次查询的答案是 A 中偶数值的和。
(此处给定的 index = queries[i][1] 是从 0 开始的索引,每次查询都会永久修改数组 A。)
返回所有查询的答案。你的答案应当以数组 answer 给出,answer[i] 为第 i 次查询的答案。
示例:
输入:A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
输出:[8,6,2,4]
解释:
开始时,数组为 [1,2,3,4]。
将 1 加到 A[0] 上之后,数组为 [2,2,3,4],偶数值之和为 2 + 2 + 4 = 8。
将 -3 加到 A[1] 上之后,数组为 [2,-1,3,4],偶数值之和为 2 + 4 = 6。
将 -4 加到 A[0] 上之后,数组为 [-2,-1,3,4],偶数值之和为 -2 + 4 = 2。
将 2 加到 A[3] 上之后,数组为 [-2,-1,3,6],偶数值之和为 -2 + 6 = 4。
提示:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
1 <= queries.length <= 10000
-10000 <= queries[i][0] <= 10000
0 <= queries[i][1] < A.length
*/
class Solution {
public int[] sumEvenAfterQueries(int[] A, int[][] queries) {
}
}<file_sep>package com.LeetCode.code.q282.ExpressionAddOperators;
/**
* @QuestionId : 282
* @difficulty : Hard
* @Title : Expression Add Operators
* @TranslatedTitle:给表达式添加运算符
* @url : https://leetcode-cn.com/problems/expression-add-operators/
* @TranslatedContent:给定一个仅包含数字 0-9 的字符串和一个目标值,在数字之间添加二元运算符(不是一元)+、- 或 * ,返回所有能够得到目标值的表达式。
示例 1:
输入: num = "123", target = 6
输出: ["1+2+3", "1*2*3"]
示例 2:
输入: num = "232", target = 8
输出: ["2*3+2", "2+3*2"]
示例 3:
输入: num = "105", target = 5
输出: ["1*0+5","10-5"]
示例 4:
输入: num = "00", target = 0
输出: ["0+0", "0-0", "0*0"]
示例 5:
输入: num = "3456237490", target = 9191
输出: []
*/
class Solution {
public List<String> addOperators(String num, int target) {
}
}<file_sep>package com.LeetCode.code.q778.ReorganizeString;
/**
* @QuestionId : 778
* @difficulty : Medium
* @Title : Reorganize String
* @TranslatedTitle:重构字符串
* @url : https://leetcode-cn.com/problems/reorganize-string/
* @TranslatedContent:给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = "aab"
输出: "aba"
示例 2:
输入: S = "aaab"
输出: ""
注意:
S 只包含小写字母并且长度在[1, 500]区间内。
*/
class Solution {
public String reorganizeString(String S) {
}
}<file_sep>package com.LeetCode.code.q773.QuadTreeIntersection;
/**
* @QuestionId : 773
* @difficulty : Easy
* @Title : Quad Tree Intersection
* @TranslatedTitle:四叉树交集
* @url : https://leetcode-cn.com/problems/quad-tree-intersection/
* @TranslatedContent:四叉树是一种树数据,其中每个结点恰好有四个子结点:topLeft、topRight、bottomLeft 和 bottomRight。四叉树通常被用来划分一个二维空间,递归地将其细分为四个象限或区域。
我们希望在四叉树中存储 True/False 信息。四叉树用来表示 N * N 的布尔网格。对于每个结点, 它将被等分成四个孩子结点直到这个区域内的值都是相同的。每个节点都有另外两个布尔属性:isLeaf 和 val。当这个节点是一个叶子结点时 isLeaf 为真。val 变量储存叶子结点所代表的区域的值。
例如,下面是两个四叉树 A 和 B:
A:
+-------+-------+ T: true
| | | F: false
| T | T |
| | |
+-------+-------+
| | |
| F | F |
| | |
+-------+-------+
topLeft: T
topRight: T
bottomLeft: F
bottomRight: F
B:
+-------+---+---+
| | F | F |
| T +---+---+
| | T | T |
+-------+---+---+
| | |
| T | F |
| | |
+-------+-------+
topLeft: T
topRight:
topLeft: F
topRight: F
bottomLeft: T
bottomRight: T
bottomLeft: T
bottomRight: F
你的任务是实现一个函数,该函数根据两个四叉树返回表示这两个四叉树的逻辑或(或并)的四叉树。
A: B: C (A or B):
+-------+-------+ +-------+---+---+ +-------+-------+
| | | | | F | F | | | |
| T | T | | T +---+---+ | T | T |
| | | | | T | T | | | |
+-------+-------+ +-------+---+---+ +-------+-------+
| | | | | | | | |
| F | F | | T | F | | T | F |
| | | | | | | | |
+-------+-------+ +-------+-------+ +-------+-------+
提示:
A 和 B 都表示大小为 N * N 的网格。
N 将确保是 2 的整次幂。
如果你想了解更多关于四叉树的知识,你可以参考这个 <a href="https://en.wikipedia.org/wiki/Quadtree">wiki 页面。
逻辑或的定义如下:如果 A 为 True ,或者 B 为 True ,或者 A 和 B 都为 True,则 "A 或 B" 为 True。
*/
/*
// Definition for a QuadTree node.
class Node {
public boolean val;
public boolean isLeaf;
public Node topLeft;
public Node topRight;
public Node bottomLeft;
public Node bottomRight;
public Node() {}
public Node(boolean _val,boolean _isLeaf,Node _topLeft,Node _topRight,Node _bottomLeft,Node _bottomRight) {
val = _val;
isLeaf = _isLeaf;
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
}
};
*/
class Solution {
public Node intersect(Node quadTree1, Node quadTree2) {
}
}<file_sep>package com.LeetCode.code.q105.ConstructBinaryTreefromPreorderandInorderTraversal;
/**
* @QuestionId : 105
* @difficulty : Medium
* @Title : Construct Binary Tree from Preorder and Inorder Traversal
* @TranslatedTitle:从前序与中序遍历序列构造二叉树
* @url : https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
* @TranslatedContent:根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
}
}<file_sep>package com.LeetCode.code.q520.DetectCapital;
/**
* @QuestionId : 520
* @difficulty : Easy
* @Title : Detect Capital
* @TranslatedTitle:检测大写字母
* @url : https://leetcode-cn.com/problems/detect-capital/
* @TranslatedContent:给定一个单词,你需要判断单词的大写使用是否正确。
我们定义,在以下情况时,单词的大写用法是正确的:
全部字母都是大写,比如"USA"。
单词中所有字母都不是大写,比如"leetcode"。
如果单词不只含有一个字母,只有首字母大写, 比如 "Google"。
否则,我们定义这个单词没有正确使用大写字母。
示例 1:
输入: "USA"
输出: True
示例 2:
输入: "FlaG"
输出: False
注意: 输入是由大写和小写拉丁字母组成的非空单词。
*/
class Solution {
public boolean detectCapitalUse(String word) {
}
}<file_sep>package com.LeetCode.code.q600.Non-negativeIntegerswithoutConsecutiveOnes;
/**
* @QuestionId : 600
* @difficulty : Hard
* @Title : Non-negative Integers without Consecutive Ones
* @TranslatedTitle:不含连续1的非负整数
* @url : https://leetcode-cn.com/problems/non-negative-integers-without-consecutive-ones/
* @TranslatedContent:给定一个正整数 n,找出小于或等于 n 的非负整数中,其二进制表示不包含 连续的1 的个数。
示例 1:
输入: 5
输出: 5
解释:
下面是带有相应二进制表示的非负整数<= 5:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
其中,只有整数3违反规则(有两个连续的1),其他5个满足规则。
说明: 1 <= n <= 109
*/
class Solution {
public int findIntegers(int num) {
}
}<file_sep>package com.LeetCode.code.q998.CheckCompletenessofaBinaryTree;
/**
* @QuestionId : 998
* @difficulty : Medium
* @Title : Check Completeness of a Binary Tree
* @TranslatedTitle:二叉树的完全性检验
* @url : https://leetcode-cn.com/problems/check-completeness-of-a-binary-tree/
* @TranslatedContent:给定一个二叉树,确定它是否是一个完全二叉树。
<a href="https://baike.baidu.com/item/完全二叉树/7773232?fr=aladdin" target="_blank">百度百科中对完全二叉树的定义如下:
若设二叉树的深度为 h,除第 h 层外,其它各层 (1~h-1) 的结点数都达到最大个数,第 h 层所有的结点都连续集中在最左边,这就是完全二叉树。(注:第 h 层可能包含 1~ 2h 个节点。)
示例 1:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/15/complete-binary-tree-1.png" style="height: 145px; width: 180px;">
输入:[1,2,3,4,5,6]
输出:true
解释:最后一层前的每一层都是满的(即,结点值为 {1} 和 {2,3} 的两层),且最后一层中的所有结点({4,5,6})都尽可能地向左。
示例 2:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/15/complete-binary-tree-2.png">
输入:[1,2,3,4,5,null,7]
输出:false
解释:值为 7 的结点没有尽可能靠向左侧。
提示:
树中将会有 1 到 100 个结点。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isCompleteTree(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q927.SumofSubsequenceWidths;
/**
* @QuestionId : 927
* @difficulty : Hard
* @Title : Sum of Subsequence Widths
* @TranslatedTitle:子序列宽度之和
* @url : https://leetcode-cn.com/problems/sum-of-subsequence-widths/
* @TranslatedContent:给定一个整数数组 A ,考虑 A 的所有非空子序列。
对于任意序列 S ,设 S 的宽度是 S 的最大元素和最小元素的差。
返回 A 的所有子序列的宽度之和。
由于答案可能非常大,请返回答案模 10^9+7。
示例:
输入:[2,1,3]
输出:6
解释:
子序列为 [1],[2],[3],[2,1],[2,3],[1,3],[2,1,3] 。
相应的宽度是 0,0,0,1,1,2,2 。
这些宽度之和是 6 。
提示:
1 <= A.length <= 20000
1 <= A[i] <= 20000
*/
class Solution {
public int sumSubseqWidths(int[] A) {
}
}<file_sep>package com.LeetCode.code.q219.ContainsDuplicateII;
/**
* @QuestionId : 219
* @difficulty : Easy
* @Title : Contains Duplicate II
* @TranslatedTitle:存在重复元素 II
* @url : https://leetcode-cn.com/problems/contains-duplicate-ii/
* @TranslatedContent:给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。
示例 1:
输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1
输出: true
示例 3:
输入: nums = [1,2,3,1,2,3], k = 2
输出: false
*/
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
}
}<file_sep>package com.LeetCode.code.q731.MyCalendarII;
/**
* @QuestionId : 731
* @difficulty : Medium
* @Title : My Calendar II
* @TranslatedTitle:我的日程安排表 II
* @url : https://leetcode-cn.com/problems/my-calendar-ii/
* @TranslatedContent:实现一个 MyCalendar 类来存放你的日程安排。如果要添加的时间内不会导致三重预订时,则可以存储这个新的日程安排。
MyCalendar 有一个 book(int start, int end)方法。它意味着在 start 到 end 时间内增加一个日程安排,注意,这里的时间是半开区间,即 [start, end), 实数 x 的范围为, start <= x < end。
当三个日程安排有一些时间上的交叉时(例如三个日程安排都在同一时间内),就会产生三重预订。
每次调用 MyCalendar.book方法时,如果可以将日程安排成功添加到日历中而不会导致三重预订,返回 true。否则,返回 false 并且不要将该日程安排添加到日历中。
请按照以下步骤调用MyCalendar 类: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)
示例:
MyCalendar();
MyCalendar.book(10, 20); // returns true
MyCalendar.book(50, 60); // returns true
MyCalendar.book(10, 40); // returns true
MyCalendar.book(5, 15); // returns false
MyCalendar.book(5, 10); // returns true
MyCalendar.book(25, 55); // returns true
解释:
前两个日程安排可以添加至日历中。 第三个日程安排会导致双重预订,但可以添加至日历中。
第四个日程安排活动(5,15)不能添加至日历中,因为它会导致三重预订。
第五个日程安排(5,10)可以添加至日历中,因为它未使用已经双重预订的时间10。
第六个日程安排(25,55)可以添加至日历中,因为时间 [25,40] 将和第三个日程安排双重预订;
时间 [40,50] 将单独预订,时间 [50,55)将和第二个日程安排双重预订。
提示:
每个测试用例,调用 MyCalendar.book 函数最多不超过 1000次。
调用函数 MyCalendar.book(start, end)时, start 和 end 的取值范围为 [0, 10^9]。
*/
class MyCalendarTwo {
public MyCalendarTwo() {
}
public boolean book(int start, int end) {
}
}
/**
* Your MyCalendarTwo object will be instantiated and called as such:
* MyCalendarTwo obj = new MyCalendarTwo();
* boolean param_1 = obj.book(start,end);
*/<file_sep>package com.LeetCode.code.q677.MapSumPairs;
/**
* @QuestionId : 677
* @difficulty : Medium
* @Title : Map Sum Pairs
* @TranslatedTitle:键值映射
* @url : https://leetcode-cn.com/problems/map-sum-pairs/
* @TranslatedContent:实现一个 MapSum 类里的两个方法,insert 和 sum。
对于方法 insert,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。
对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。
示例 1:
输入: insert("apple", 3), 输出: Null
输入: sum("ap"), 输出: 3
输入: insert("app", 2), 输出: Null
输入: sum("ap"), 输出: 5
*/
class MapSum {
/** Initialize your data structure here. */
public MapSum() {
}
public void insert(String key, int val) {
}
public int sum(String prefix) {
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/<file_sep>package com.LeetCode.code.q79.WordSearch;
/**
* @QuestionId : 79
* @difficulty : Medium
* @Title : Word Search
* @TranslatedTitle:单词搜索
* @url : https://leetcode-cn.com/problems/word-search/
* @TranslatedContent:给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.
*/
class Solution {
public boolean exist(char[][] board, String word) {
}
}<file_sep>package com.LeetCode.code.q759.SetIntersectionSizeAtLeastTwo;
/**
* @QuestionId : 759
* @difficulty : Hard
* @Title : Set Intersection Size At Least Two
* @TranslatedTitle: 设置交集大小至少为2
* @url : https://leetcode-cn.com/problems/set-intersection-size-at-least-two/
* @TranslatedContent:一个整数区间 [a, b] ( a < b ) 代表着从 a 到 b 的所有连续整数,包括 a 和 b。
给你一组整数区间intervals,请找到一个最小的集合 S,使得 S 里的元素与区间intervals中的每一个整数区间都至少有2个元素相交。
输出这个最小集合S的大小。
示例 1:
输入: intervals = [[1, 3], [1, 4], [2, 5], [3, 5]]
输出: 3
解释:
考虑集合 S = {2, 3, 4}. S与intervals中的四个区间都有至少2个相交的元素。
且这是S最小的情况,故我们输出3。
示例 2:
输入: intervals = [[1, 2], [2, 3], [2, 4], [4, 5]]
输出: 5
解释:
最小的集合S = {1, 2, 3, 4, 5}.
注意:
intervals 的长度范围为[1, 3000]。
intervals[i] 长度为 2,分别代表左、右边界。
intervals[i][j] 的值是 [0, 10^8]范围内的整数。
*/
class Solution {
public int intersectionSizeTwo(int[][] intervals) {
}
}<file_sep>package com.LeetCode.code.q971.ShortestBridge;
/**
* @QuestionId : 971
* @difficulty : Medium
* @Title : Shortest Bridge
* @TranslatedTitle:最短的桥
* @url : https://leetcode-cn.com/problems/shortest-bridge/
* @TranslatedContent:在给定的二维二进制数组 A 中,存在两座岛。(岛是由四面相连的 1 形成的一个最大组。)
现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛。
返回必须翻转的 0 的最小数目。(可以保证答案至少是 1。)
示例 1:
输入:[[0,1],[1,0]]
输出:1
示例 2:
输入:[[0,1,0],[0,0,0],[0,0,1]]
输出:2
示例 3:
输入:[[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
输出:1
提示:
1 <= A.length = A[0].length <= 100
A[i][j] == 0 或 A[i][j] == 1
*/
class Solution {
public int shortestBridge(int[][] A) {
}
}<file_sep>package com.LeetCode.code.q918.ReachableNodesInSubdividedGraph;
/**
* @QuestionId : 918
* @difficulty : Hard
* @Title : Reachable Nodes In Subdivided Graph
* @TranslatedTitle:细分图中的可到达结点
* @url : https://leetcode-cn.com/problems/reachable-nodes-in-subdivided-graph/
* @TranslatedContent:从具有 0 到 N-1 的结点的无向图(“原始图”)开始,对一些边进行细分。
该图给出如下:edges[k] 是整数对 (i, j, n) 组成的列表,使 (i, j) 是原始图的边。
n 是该边上新结点的总数
然后,将边 (i, j) 从原始图中删除,将 n 个新结点 (x_1, x_2, ..., x_n) 添加到原始图中,
将 n+1 条新边 (i, x_1), (x_1, x_2), (x_2, x_3), ..., (x_{n-1}, x_n), (x_n, j) 添加到原始图中。
现在,你将从原始图中的结点 0 处出发,并且每次移动,你都将沿着一条边行进。
返回最多 M 次移动可以达到的结点数。
示例 1:
输入:edges = [[0,1,10],[0,2,1],[1,2,2]], M = 6, N = 3
输出:13
解释:
在 M = 6 次移动之后在最终图中可到达的结点如下所示。
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/01/origfinal.png" style="height: 200px; width: 487px;">
示例 2:
输入:edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], M = 10, N = 4
输出:23
提示:
0 <= edges.length <= 10000
0 <= edges[i][0] < edges[i][1] < N
不存在任何 i != j 情况下 edges[i][0] == edges[j][0] 且 edges[i][1] == edges[j][1].
原始图没有平行的边。
0 <= edges[i][2] <= 10000
0 <= M <= 10^9
1 <= N <= 3000
可到达结点是可以从结点 0 开始使用最多 M 次移动到达的结点。
*/
class Solution {
public int reachableNodes(int[][] edges, int M, int N) {
}
}<file_sep>package com.LeetCode.code.q443.StringCompression;
/**
* @QuestionId : 443
* @difficulty : Easy
* @Title : String Compression
* @TranslatedTitle:压缩字符串
* @url : https://leetcode-cn.com/problems/string-compression/
* @TranslatedContent:给定一组字符,使用<a href="https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95">原地算法将其压缩。
压缩后的长度必须始终小于或等于原数组长度。
数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。
在完成<a href="https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95">原地修改输入数组后,返回数组的新长度。
进阶:<br />
你能否仅使用O(1) 空间解决问题?
示例 1:
输入:
["a","a","b","b","c","c","c"]
输出:
返回6,输入数组的前6个字符应该是:["a","2","b","2","c","3"]
说明:
"aa"被"a2"替代。"bb"被"b2"替代。"ccc"被"c3"替代。
示例 2:
输入:
["a"]
输出:
返回1,输入数组的前1个字符应该是:["a"]
说明:
没有任何字符串被替代。
示例 3:
输入:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
输出:
返回4,输入数组的前4个字符应该是:["a","b","1","2"]。
说明:
由于字符"a"不重复,所以不会被压缩。"bbbbbbbbbbbb"被“b12”替代。
注意每个数字在数组中都有它自己的位置。
注意:
所有字符都有一个ASCII值在[35, 126]区间内。
1 <= len(chars) <= 1000。
*/
class Solution {
public int compress(char[] chars) {
}
}<file_sep>package com.LeetCode.code.q479.LargestPalindromeProduct;
/**
* @QuestionId : 479
* @difficulty : Hard
* @Title : Largest Palindrome Product
* @TranslatedTitle:最大回文数乘积
* @url : https://leetcode-cn.com/problems/largest-palindrome-product/
* @TranslatedContent:你需要找到由两个 n 位数的乘积组成的最大回文数。
由于结果会很大,你只需返回最大回文数 mod 1337得到的结果。
示例:
输入: 2
输出: 987
解释: 99 x 91 = 9009, 9009 % 1337 = 987
说明:
n 的取值范围为 [1,8]。
*/
class Solution {
public int largestPalindrome(int n) {
}
}<file_sep>package com.LeetCode.code.q1078.RemoveOutermostParentheses;
/**
* @QuestionId : 1078
* @difficulty : Easy
* @Title : Remove Outermost Parentheses
* @TranslatedTitle:删除最外层的括号
* @url : https://leetcode-cn.com/problems/remove-outermost-parentheses/
* @TranslatedContent:有效括号字符串为空 ("")、"(" + A + ")" 或 A + B,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。例如,"","()","(())()" 和 "(()(()))" 都是有效的括号字符串。
如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。
给出一个非空有效字符串 S,考虑将其进行原语化分解,使得:S = P_1 + P_2 + ... + P_k,其中 P_i 是有效括号字符串原语。
对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。
示例 1:
输入:"(()())(())"
输出:"()()()"
解释:
输入字符串为 "(()())(())",原语化分解得到 "(()())" + "(())",
删除每个部分中的最外层括号后得到 "()()" + "()" = "()()()"。
示例 2:
输入:"(()())(())(()(()))"
输出:"()()()()(())"
解释:
输入字符串为 "(()())(())(()(()))",原语化分解得到 "(()())" + "(())" + "(()(()))",
删除每隔部分中的最外层括号后得到 "()()" + "()" + "()(())" = "()()()()(())"。
示例 3:
输入:"()()"
输出:""
解释:
输入字符串为 "()()",原语化分解得到 "()" + "()",
删除每个部分中的最外层括号后得到 "" + "" = ""。
提示:
S.length <= 10000
S[i] 为 "(" 或 ")"
S 是一个有效括号字符串
*/
class Solution {
public String removeOuterParentheses(String S) {
}
}<file_sep>package com.LeetCode.code.q1157.InsufficientNodesinRoottoLeafPaths;
/**
* @QuestionId : 1157
* @difficulty : Medium
* @Title : Insufficient Nodes in Root to Leaf Paths
* @TranslatedTitle:根到叶路径上的不足节点
* @url : https://leetcode-cn.com/problems/insufficient-nodes-in-root-to-leaf-paths/
* @TranslatedContent:给定一棵二叉树的根 root,请你考虑它所有 从根到叶的路径:从根到任何叶的路径。(所谓一个叶子节点,就是一个没有子节点的节点)
假如通过节点 node 的每种可能的 “根-叶” 路径上值的总和全都小于给定的 limit,则该节点被称之为「不足节点」,需要被删除。
请你删除所有不足节点,并返回生成的二叉树的根。
示例 1:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/08/insufficient-1.png" style="height: 200px; width: 482px;">
输入:root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/08/insufficient-2.png" style="height: 200px; width: 258px;">
输出:[1,2,3,4,null,null,7,8,9,null,14]
示例 2:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/08/insufficient-3.png" style="height: 200px; width: 292px;">
输入:root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/08/insufficient-4.png" style="height: 200px; width: 264px;">
输出:[5,4,8,11,null,17,4,7,null,null,null,5]
示例 3:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/06/08/insufficient-5.png" style="height: 100px; width: 140px;">
输入:root = [5,-6,-6], limit = 0
输出:[]
提示:
给定的树有 1 到 5000 个节点
-10^5 <= node.val <= 10^5
-10^9 <= limit <= 10^9
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sufficientSubset(TreeNode root, int limit) {
}
}<file_sep>package com.LeetCode.code.q982.MinimumIncrementtoMakeArrayUnique;
/**
* @QuestionId : 982
* @difficulty : Medium
* @Title : Minimum Increment to Make Array Unique
* @TranslatedTitle:使数组唯一的最小增量
* @url : https://leetcode-cn.com/problems/minimum-increment-to-make-array-unique/
* @TranslatedContent:给定整数数组 A,每次 move 操作将会选择任意 A[i],并将其递增 1。
返回使 A 中的每个值都是唯一的最少操作次数。
示例 1:
输入:[1,2,2]
输出:1
解释:经过一次 move 操作,数组将变为 [1, 2, 3]。
示例 2:
输入:[3,2,1,2,1,7]
输出:6
解释:经过 6 次 move 操作,数组将变为 [3, 4, 1, 2, 5, 7]。
可以看出 5 次或 5 次以下的 move 操作是不能让数组的每个值唯一的。
提示:
0 <= A.length <= 40000
0 <= A[i] < 40000
*/
class Solution {
public int minIncrementForUnique(int[] A) {
}
}<file_sep>package com.LeetCode.code.q871.KeysandRooms;
/**
* @QuestionId : 871
* @difficulty : Medium
* @Title : Keys and Rooms
* @TranslatedTitle:钥匙和房间
* @url : https://leetcode-cn.com/problems/keys-and-rooms/
* @TranslatedContent:有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,...,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。
在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j] 由 [0,1,...,N-1] 中的一个整数表示,其中 N = rooms.length。 钥匙 rooms[i][j] = v 可以打开编号为 v 的房间。
最初,除 0 号房间外的其余所有房间都被锁住。
你可以自由地在房间之间来回走动。
如果能进入每个房间返回 true,否则返回 false。
示例 1:
输入: [[1],[2],[3],[]]
输出: true
解释:
我们从 0 号房间开始,拿到钥匙 1。
之后我们去 1 号房间,拿到钥匙 2。
然后我们去 2 号房间,拿到钥匙 3。
最后我们去了 3 号房间。
由于我们能够进入每个房间,我们返回 true。
示例 2:
输入:[[1,3],[3,0,1],[2],[0]]
输出:false
解释:我们不能进入 2 号房间。
提示:
1 <= rooms.length <= 1000
0 <= rooms[i].length <= 1000
所有房间中的钥匙数量总计不超过 3000。
*/
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
}
}<file_sep>package com.LeetCode.code.q334.IncreasingTripletSubsequence;
/**
* @QuestionId : 334
* @difficulty : Medium
* @Title : Increasing Triplet Subsequence
* @TranslatedTitle:递增的三元子序列
* @url : https://leetcode-cn.com/problems/increasing-triplet-subsequence/
* @TranslatedContent:给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。
数学表达式如下:
如果存在这样的 i, j, k, 且满足 0 ≤ i < j < k ≤ n-1,
使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。
示例 1:
输入: [1,2,3,4,5]
输出: true
示例 2:
输入: [5,4,3,2,1]
输出: false
*/
class Solution {
public boolean increasingTriplet(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q668.KthSmallestNumberinMultiplicationTable;
/**
* @QuestionId : 668
* @difficulty : Hard
* @Title : Kth Smallest Number in Multiplication Table
* @TranslatedTitle:乘法表中第k小的数
* @url : https://leetcode-cn.com/problems/kth-smallest-number-in-multiplication-table/
* @TranslatedContent:几乎每一个人都用 <a href="https://baike.baidu.com/item/%E4%B9%98%E6%B3%95%E8%A1%A8">乘法表。但是你能在乘法表中快速找到第k小的数字吗?
给定高度m 、宽度n 的一张 m * n的乘法表,以及正整数k,你需要返回表中第k 小的数字。
例 1:
输入: m = 3, n = 3, k = 5
输出: 3
解释:
乘法表:
1 2 3
2 4 6
3 6 9
第5小的数字是 3 (1, 2, 2, 3, 3).
例 2:
输入: m = 2, n = 3, k = 6
输出: 6
解释:
乘法表:
1 2 3
2 4 6
第6小的数字是 6 (1, 2, 2, 3, 4, 6).
注意:
m 和 n 的范围在 [1, 30000] 之间。
k 的范围在 [1, m * n] 之间。
*/
class Solution {
public int findKthNumber(int m, int n, int k) {
}
}<file_sep>package com.LeetCode.code.q561.ArrayPartitionI;
/**
* @QuestionId : 561
* @difficulty : Easy
* @Title : Array Partition I
* @TranslatedTitle:数组拆分 I
* @url : https://leetcode-cn.com/problems/array-partition-i/
* @TranslatedContent:给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。
示例 1:
输入: [1,4,3,2]
输出: 4
解释: n 等于 2, 最大总和为 4 = min(1, 2) + min(3, 4).
提示:
n 是正整数,范围在 [1, 10000].
数组中的元素范围在 [-10000, 10000].
*/
class Solution {
public int arrayPairSum(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q686.RepeatedStringMatch;
/**
* @QuestionId : 686
* @difficulty : Easy
* @Title : Repeated String Match
* @TranslatedTitle:重复叠加字符串匹配
* @url : https://leetcode-cn.com/problems/repeated-string-match/
* @TranslatedContent:给定两个字符串 A 和 B, 寻找重复叠加字符串A的最小次数,使得字符串B成为叠加后的字符串A的子串,如果不存在则返回 -1。
举个例子,A = "abcd",B = "cdabcdab"。
答案为 3, 因为 A 重复叠加三遍后为 “abcdabcdabcd”,此时 B 是其子串;A 重复叠加两遍后为"abcdabcd",B 并不是其子串。
注意:
A 与 B 字符串的长度在1和10000区间范围内。
*/
class Solution {
public int repeatedStringMatch(String A, String B) {
}
}<file_sep>package com.LeetCode.spider.detail;
public class Data
{
private Question question;
public void setQuestion(Question question){
this.question = question;
}
public Question getQuestion(){
return this.question;
}
}<file_sep>package com.LeetCode.code.q1064.SmallestIntegerDivisiblebyK;
/**
* @QuestionId : 1064
* @difficulty : Medium
* @Title : Smallest Integer Divisible by K
* @TranslatedTitle:可被 K 整除的最小整数
* @url : https://leetcode-cn.com/problems/smallest-integer-divisible-by-k/
* @TranslatedContent:给定正整数 K,你需要找出可以被 K 整除的、仅包含数字 1 的最小正整数 N。
返回 N 的长度。如果不存在这样的 N,就返回 -1。
示例 1:
输入:1
输出:1
解释:最小的答案是 N = 1,其长度为 1。
示例 2:
输入:2
输出:-1
解释:不存在可被 2 整除的正整数 N 。
示例 3:
输入:3
输出:3
解释:最小的答案是 N = 111,其长度为 3。
提示:
1 <= K <= 10^5
*/
class Solution {
public int smallestRepunitDivByK(int K) {
}
}<file_sep>package com.LeetCode.code.q729.MyCalendarI;
/**
* @QuestionId : 729
* @difficulty : Medium
* @Title : My Calendar I
* @TranslatedTitle:我的日程安排表 I
* @url : https://leetcode-cn.com/problems/my-calendar-i/
* @TranslatedContent:实现一个 MyCalendar 类来存放你的日程安排。如果要添加的时间内没有其他安排,则可以存储这个新的日程安排。
MyCalendar 有一个 book(int start, int end)方法。它意味着在 start 到 end 时间内增加一个日程安排,注意,这里的时间是半开区间,即 [start, end), 实数 x 的范围为, start <= x < end。
当两个日程安排有一些时间上的交叉时(例如两个日程安排都在同一时间内),就会产生重复预订。
每次调用 MyCalendar.book方法时,如果可以将日程安排成功添加到日历中而不会导致重复预订,返回 true。否则,返回 false 并且不要将该日程安排添加到日历中。
请按照以下步骤调用 MyCalendar 类: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end)
示例 1:
MyCalendar();
MyCalendar.book(10, 20); // returns true
MyCalendar.book(15, 25); // returns false
MyCalendar.book(20, 30); // returns true
解释:
第一个日程安排可以添加到日历中. 第二个日程安排不能添加到日历中,因为时间 15 已经被第一个日程安排预定了。
第三个日程安排可以添加到日历中,因为第一个日程安排并不包含时间 20 。
说明:
每个测试用例,调用 MyCalendar.book 函数最多不超过 100次。
调用函数 MyCalendar.book(start, end)时, start 和 end 的取值范围为 [0, 10^9]。
*/
class MyCalendar {
public MyCalendar() {
}
public boolean book(int start, int end) {
}
}
/**
* Your MyCalendar object will be instantiated and called as such:
* MyCalendar obj = new MyCalendar();
* boolean param_1 = obj.book(start,end);
*/<file_sep>package com.LeetCode.code.q1056.CapacityToShipPackagesWithinDDays;
/**
* @QuestionId : 1056
* @difficulty : Medium
* @Title : Capacity To Ship Packages Within D Days
* @TranslatedTitle:在 D 天内送达包裹的能力
* @url : https://leetcode-cn.com/problems/capacity-to-ship-packages-within-d-days/
* @TranslatedContent:传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。
传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。
返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。
示例 1:
输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5
输出:15
解释:
船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示:
第 1 天:1, 2, 3, 4, 5
第 2 天:6, 7
第 3 天:8
第 4 天:9
第 5 天:10
请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。
示例 2:
输入:weights = [3,2,2,4,1,4], D = 3
输出:6
解释:
船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示:
第 1 天:3, 2
第 2 天:2, 4
第 3 天:1, 4
示例 3:
输入:weights = [1,2,3,1,1], D = 4
输出:3
解释:
第 1 天:1
第 2 天:2
第 3 天:3
第 4 天:1, 1
提示:
1 <= D <= weights.length <= 50000
1 <= weights[i] <= 500
*/
class Solution {
public int shipWithinDays(int[] weights, int D) {
}
}<file_sep>package com.LeetCode.code.q20.ValidParentheses;
/**
* @QuestionId : 20
* @difficulty : Easy
* @Title : Valid Parentheses
* @TranslatedTitle:有效的括号
* @url : https://leetcode-cn.com/problems/valid-parentheses/
* @TranslatedContent:给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
*/
class Solution {
public boolean isValid(String s) {
}
}<file_sep>package com.LeetCode.code.q22.GenerateParentheses;
/**
* @QuestionId : 22
* @difficulty : Medium
* @Title : Generate Parentheses
* @TranslatedTitle:括号生成
* @url : https://leetcode-cn.com/problems/generate-parentheses/
* @TranslatedContent:给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
*/
class Solution {
public List<String> generateParenthesis(int n) {
}
}<file_sep>package com.LeetCode.code.q1022.UniquePathsIII;
/**
* @QuestionId : 1022
* @difficulty : Hard
* @Title : Unique Paths III
* @TranslatedTitle:不同路径 III
* @url : https://leetcode-cn.com/problems/unique-paths-iii/
* @TranslatedContent:在二维网格 grid 上,有 4 种类型的方格:
1 表示起始方格。且只有一个起始方格。
2 表示结束方格,且只有一个结束方格。
0 表示我们可以走过的空方格。
-1 表示我们无法跨越的障碍。
返回在四个方向(上、下、左、右)上行走时,从起始方格到结束方格的不同路径的数目,每一个无障碍方格都要通过一次。
示例 1:
输入:[[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
输出:2
解释:我们有以下两条路径:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
示例 2:
输入:[[1,0,0,0],[0,0,0,0],[0,0,0,2]]
输出:4
解释:我们有以下四条路径:
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
示例 3:
输入:[[0,1],[2,0]]
输出:0
解释:
没有一条路能完全穿过每一个空的方格一次。
请注意,起始和结束方格可以位于网格中的任意位置。
提示:
1 <= grid.length * grid[0].length <= 20
*/
class Solution {
public int uniquePathsIII(int[][] grid) {
}
}<file_sep>package com.LeetCode.code.q1279.PrimeArrangements;
/**
* @QuestionId : 1279
* @difficulty : Easy
* @Title : Prime Arrangements
* @TranslatedTitle:质数排列
* @url : https://leetcode-cn.com/problems/prime-arrangements/
* @TranslatedContent:请你帮忙给从 1 到 n 的数设计排列方案,使得所有的「质数」都应该被放在「质数索引」(索引从 1 开始)上;你需要返回可能的方案总数。
让我们一起来回顾一下「质数」:质数一定是大于 1 的,并且不能用两个小于它的正整数的乘积来表示。
由于答案可能会很大,所以请你返回答案 模 mod 10^9 + 7 之后的结果即可。
示例 1:
输入:n = 5
输出:12
解释:举个例子,[1,2,5,4,3] 是一个有效的排列,但 [5,2,3,4,1] 不是,因为在第二种情况里质数 5 被错误地放在索引为 1 的位置上。
示例 2:
输入:n = 100
输出:682289015
提示:
1 <= n <= 100
*/
class Solution {
public int numPrimeArrangements(int n) {
}
}<file_sep>package com.LeetCode.code.q830.LargestTriangleArea;
/**
* @QuestionId : 830
* @difficulty : Easy
* @Title : Largest Triangle Area
* @TranslatedTitle:最大三角形面积
* @url : https://leetcode-cn.com/problems/largest-triangle-area/
* @TranslatedContent:给定包含多个点的集合,从其中取三个点组成三角形,返回能组成的最大三角形的面积。
示例:
输入: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
输出: 2
解释:
这五个点如下图所示。组成的橙色三角形是最大的,面积为2。
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/04/04/1027.png" style="height:328px; width:400px" />
注意:
3 <= points.length <= 50.
不存在重复的点。
-50 <= points[i][j] <= 50.
结果误差值在 10^-6 以内都认为是正确答案。
*/
class Solution {
public double largestTriangleArea(int[][] points) {
}
}<file_sep>package com.LeetCode.code.q1029.VerticalOrderTraversalofaBinaryTree;
/**
* @QuestionId : 1029
* @difficulty : Medium
* @Title : Vertical Order Traversal of a Binary Tree
* @TranslatedTitle:二叉树的垂序遍历
* @url : https://leetcode-cn.com/problems/vertical-order-traversal-of-a-binary-tree/
* @TranslatedContent:给定二叉树,按垂序遍历返回其结点值。
对位于 (X, Y) 的每个结点而言,其左右子结点分别位于 (X-1, Y-1) 和 (X+1, Y-1)。
把一条垂线从 X = -infinity 移动到 X = +infinity ,每当该垂线与结点接触时,我们按从上到下的顺序报告结点的值( Y 坐标递减)。
如果两个结点位置相同,则首先报告的结点值较小。
按 X 坐标顺序返回非空报告的列表。每个报告都有一个结点值列表。
示例 1:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/02/1236_example_1.PNG" style="height: 186px; width: 201px;">
输入:[3,9,20,null,null,15,7]
输出:[[9],[3,15],[20],[7]]
解释:
在不丧失其普遍性的情况下,我们可以假设根结点位于 (0, 0):
然后,值为 9 的结点出现在 (-1, -1);
值为 3 和 15 的两个结点分别出现在 (0, 0) 和 (0, -2);
值为 20 的结点出现在 (1, -1);
值为 7 的结点出现在 (2, -2)。
示例 2:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/02/23/tree2.png" style="height: 150px; width: 236px;">
输入:[1,2,3,4,5,6,7]
输出:[[4],[2],[1,5,6],[3],[7]]
解释:
根据给定的方案,值为 5 和 6 的两个结点出现在同一位置。
然而,在报告 "[1,5,6]" 中,结点值 5 排在前面,因为 5 小于 6。
提示:
树的结点数介于 1 和 1000 之间。
每个结点值介于 0 和 1000 之间。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> verticalTraversal(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q57.InsertInterval;
/**
* @QuestionId : 57
* @difficulty : Hard
* @Title : Insert Interval
* @TranslatedTitle:插入区间
* @url : https://leetcode-cn.com/problems/insert-interval/
* @TranslatedContent:给出一个无重叠的 ,按照区间起始端点排序的区间列表。
在列表中插入一个新的区间,你需要确保列表中的区间仍然有序且不重叠(如果有必要的话,可以合并区间)。
示例 1:
输入: intervals = [[1,3],[6,9]], newInterval = [2,5]
输出: [[1,5],[6,9]]
示例 2:
输入: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
输出: [[1,2],[3,10],[12,16]]
解释: 这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。
*/
class Solution {
public int[][] insert(int[][] intervals, int[] newInterval) {
}
}<file_sep>package com.LeetCode.code.q671.SecondMinimumNodeInaBinaryTree;
/**
* @QuestionId : 671
* @difficulty : Easy
* @Title : Second Minimum Node In a Binary Tree
* @TranslatedTitle:二叉树中第二小的节点
* @url : https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/
* @TranslatedContent:给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。
给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。
示例 1:
输入:
2
/ \
2 5
/ \
5 7
输出: 5
说明: 最小的值是 2 ,第二小的值是 5 。
示例 2:
输入:
2
/ \
2 2
输出: -1
说明: 最小的值是 2, 但是不存在第二小的值。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findSecondMinimumValue(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q149.MaxPointsonaLine;
/**
* @QuestionId : 149
* @difficulty : Hard
* @Title : Max Points on a Line
* @TranslatedTitle:直线上最多的点数
* @url : https://leetcode-cn.com/problems/max-points-on-a-line/
* @TranslatedContent:给定一个二维平面,平面上有 n 个点,求最多有多少个点在同一条直线上。
示例 1:
输入: [[1,1],[2,2],[3,3]]
输出: 3
解释:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
示例 2:
输入: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
输出: 4
解释:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
*/
class Solution {
public int maxPoints(int[][] points) {
}
}<file_sep>package com.LeetCode.code.q496.NextGreaterElementI;
/**
* @QuestionId : 496
* @difficulty : Easy
* @Title : Next Greater Element I
* @TranslatedTitle:下一个更大元素 I
* @url : https://leetcode-cn.com/problems/next-greater-element-i/
* @TranslatedContent:给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。
nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。
示例 1:
输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。
对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。
对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。
示例 2:
输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
对于num1中的数字2,第二个数组中的下一个较大数字是3。
对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。
注意:
nums1和nums2中所有元素是唯一的。
nums1和nums2 的数组大小都不超过1000。
*/
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
}
}<file_sep>package com.LeetCode.code.q517.SuperWashingMachines;
/**
* @QuestionId : 517
* @difficulty : Hard
* @Title : Super Washing Machines
* @TranslatedTitle:超级洗衣机
* @url : https://leetcode-cn.com/problems/super-washing-machines/
* @TranslatedContent:假设有 n 台超级洗衣机放在同一排上。开始的时候,每台洗衣机内可能有一定量的衣服,也可能是空的。
在每一步操作中,你可以选择任意 m (1 ≤ m ≤ n) 台洗衣机,与此同时将每台洗衣机的一件衣服送到相邻的一台洗衣机。
给定一个非负整数数组代表从左至右每台洗衣机中的衣物数量,请给出能让所有洗衣机中剩下的衣物的数量相等的最少的操作步数。如果不能使每台洗衣机中衣物的数量相等,则返回 -1。
示例 1:
输入: [1,0,5]
输出: 3
解释:
第一步: 1 0 <-- 5 => 1 1 4
第二步: 1 <-- 1 <-- 4 => 2 1 3
第三步: 2 1 <-- 3 => 2 2 2
示例 2:
输入: [0,3,0]
输出: 2
解释:
第一步: 0 <-- 3 0 => 1 2 0
第二步: 1 2 --> 0 => 1 1 1
示例 3:
输入: [0,2,0]
输出: -1
解释:
不可能让所有三个洗衣机同时剩下相同数量的衣物。
提示:
n 的范围是 [1, 10000]。
在每台超级洗衣机中,衣物数量的范围是 [0, 1e5]。
*/
class Solution {
public int findMinMoves(int[] machines) {
}
}<file_sep>package com.LeetCode.code.q455.AssignCookies;
/**
* @QuestionId : 455
* @difficulty : Easy
* @Title : Assign Cookies
* @TranslatedTitle:分发饼干
* @url : https://leetcode-cn.com/problems/assign-cookies/
* @TranslatedContent:假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 sj 。如果 sj >= gi ,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。
注意:
你可以假设胃口值为正。<br />
一个小朋友最多只能拥有一块饼干。
示例 1:
输入: [1,2,3], [1,1]
输出: 1
解释:
你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
所以你应该输出1。
示例 2:
输入: [1,2], [1,2,3]
输出: 2
解释:
你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
你拥有的饼干数量和尺寸都足以让所有孩子满足。
所以你应该输出2.
*/
class Solution {
public int findContentChildren(int[] g, int[] s) {
}
}<file_sep>package com.LeetCode.code.q994.PrisonCellsAfterNDays;
/**
* @QuestionId : 994
* @difficulty : Medium
* @Title : Prison Cells After N Days
* @TranslatedTitle:N 天后的牢房
* @url : https://leetcode-cn.com/problems/prison-cells-after-n-days/
* @TranslatedContent:8 间牢房排成一排,每间牢房不是有人住就是空着。
每天,无论牢房是被占用或空置,都会根据以下规则进行更改:
如果一间牢房的两个相邻的房间都被占用或都是空的,那么该牢房就会被占用。
否则,它就会被空置。
(请注意,由于监狱中的牢房排成一行,所以行中的第一个和最后一个房间无法有两个相邻的房间。)
我们用以下方式描述监狱的当前状态:如果第 i 间牢房被占用,则 cell[i]==1,否则 cell[i]==0。
根据监狱的初始状态,在 N 天后返回监狱的状况(和上述 N 种变化)。
示例 1:
输入:cells = [0,1,0,1,1,0,0,1], N = 7
输出:[0,0,1,1,0,0,0,0]
解释:
下表概述了监狱每天的状况:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
示例 2:
输入:cells = [1,0,0,1,0,0,1,0], N = 1000000000
输出:[0,0,1,1,1,1,1,0]
提示:
cells.length == 8
cells[i] 的值为 0 或 1
1 <= N <= 10^9
*/
class Solution {
public int[] prisonAfterNDays(int[] cells, int N) {
}
}<file_sep>package com.LeetCode.code.q935.OrderlyQueue;
/**
* @QuestionId : 935
* @difficulty : Hard
* @Title : Orderly Queue
* @TranslatedTitle:有序队列
* @url : https://leetcode-cn.com/problems/orderly-queue/
* @TranslatedContent:给出了一个由小写字母组成的字符串 S。然后,我们可以进行任意次数的移动。
在每次移动中,我们选择前 K 个字母中的一个(从左侧开始),将其从原位置移除,并放置在字符串的末尾。
返回我们在任意次数的移动之后可以拥有的按字典顺序排列的最小字符串。
示例 1:
输入:S = "cba", K = 1
输出:"acb"
解释:
在第一步中,我们将第一个字符(“c”)移动到最后,获得字符串 “bac”。
在第二步中,我们将第一个字符(“b”)移动到最后,获得最终结果 “acb”。
示例 2:
输入:S = "baaca", K = 3
输出:"aaabc"
解释:
在第一步中,我们将第一个字符(“b”)移动到最后,获得字符串 “aacab”。
在第二步中,我们将第三个字符(“c”)移动到最后,获得最终结果 “aaabc”。
提示:
1 <= K <= S.length <= 1000
S 只由小写字母组成。
*/
class Solution {
public String orderlyQueue(String S, int K) {
}
}<file_sep>package com.LeetCode.code.q17.LetterCombinationsofaPhoneNumber;
/**
* @QuestionId : 17
* @difficulty : Medium
* @Title : Letter Combinations of a Phone Number
* @TranslatedTitle:电话号码的字母组合
* @url : https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/
* @TranslatedContent:给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/original_images/17_telephone_keypad.png" style="width: 200px;">
示例:
输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。
*/
class Solution {
public List<String> letterCombinations(String digits) {
}
}<file_sep>package com.LeetCode.code.q623.AddOneRowtoTree;
/**
* @QuestionId : 623
* @difficulty : Medium
* @Title : Add One Row to Tree
* @TranslatedTitle:在二叉树中增加一行
* @url : https://leetcode-cn.com/problems/add-one-row-to-tree/
* @TranslatedContent:给定一个二叉树,根节点为第1层,深度为 1。在其第 d 层追加一行值为 v 的节点。
添加规则:给定一个深度值 d (正整数),针对深度为 d-1 层的每一非空节点 N,为 N 创建两个值为 v 的左子树和右子树。
将 N 原先的左子树,连接为新节点 v 的左子树;将 N 原先的右子树,连接为新节点 v 的右子树。
如果 d 的值为 1,深度 d - 1 不存在,则创建一个新的根节点 v,原先的整棵树将作为 v 的左子树。
示例 1:
输入:
二叉树如下所示:
4
/ \
2 6
/ \ /
3 1 5
v = 1
d = 2
输出:
4
/ \
1 1
/ \
2 6
/ \ /
3 1 5
示例 2:
输入:
二叉树如下所示:
4
/
2
/ \
3 1
v = 1
d = 3
输出:
4
/
2
/ \
1 1
/ \
3 1
注意:
输入的深度值 d 的范围是:[1,二叉树最大深度 + 1]。
输入的二叉树至少有一个节点。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode addOneRow(TreeNode root, int v, int d) {
}
}<file_sep>package com.LeetCode.code.q938.NumbersAtMostNGivenDigitSet;
/**
* @QuestionId : 938
* @difficulty : Hard
* @Title : Numbers At Most N Given Digit Set
* @TranslatedTitle:最大为 N 的数字组合
* @url : https://leetcode-cn.com/problems/numbers-at-most-n-given-digit-set/
* @TranslatedContent:我们有一组排序的数字 D,它是 {'1','2','3','4','5','6','7','8','9'} 的非空子集。(请注意,'0' 不包括在内。)
现在,我们用这些数字进行组合写数字,想用多少次就用多少次。例如 D = {'1','3','5'},我们可以写出像 '13', '551', '1351315' 这样的数字。
返回可以用 D 中的数字写出的小于或等于 N 的正整数的数目。
示例 1:
输入:D = ["1","3","5","7"], N = 100
输出:20
解释:
可写出的 20 个数字是:
1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77.
示例 2:
输入:D = ["1","4","9"], N = 1000000000
输出:29523
解释:
我们可以写 3 个一位数字,9 个两位数字,27 个三位数字,
81 个四位数字,243 个五位数字,729 个六位数字,
2187 个七位数字,6561 个八位数字和 19683 个九位数字。
总共,可以使用D中的数字写出 29523 个整数。
提示:
D 是按排序顺序的数字 '1'-'9' 的子集。
1 <= N <= 10^9
*/
class Solution {
public int atMostNGivenDigitSet(String[] D, int N) {
}
}<file_sep>package com.LeetCode.code.q1289.DayoftheWeek;
/**
* @QuestionId : 1289
* @difficulty : Easy
* @Title : Day of the Week
* @TranslatedTitle:一周中的第几天
* @url : https://leetcode-cn.com/problems/day-of-the-week/
* @TranslatedContent:给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
输入为三个整数:day、month 和 year,分别表示日、月、年。
您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}。
示例 1:
输入:day = 31, month = 8, year = 2019
输出:"Saturday"
示例 2:
输入:day = 18, month = 7, year = 1999
输出:"Sunday"
示例 3:
输入:day = 15, month = 8, year = 1993
输出:"Sunday"
提示:
给出的日期一定是在 1971 到 2100 年之间的有效日期。
*/
class Solution {
public String dayOfTheWeek(int day, int month, int year) {
}
}<file_sep>package com.LeetCode.code.q1026.StringWithoutAAAorBBB;
/**
* @QuestionId : 1026
* @difficulty : Medium
* @Title : String Without AAA or BBB
* @TranslatedTitle:不含 AAA 或 BBB 的字符串
* @url : https://leetcode-cn.com/problems/string-without-aaa-or-bbb/
* @TranslatedContent:给定两个整数 A 和 B,返回任意字符串 S,要求满足:
S 的长度为 A + B,且正好包含 A 个 'a' 字母与 B 个 'b' 字母;
子串 'aaa' 没有出现在 S 中;
子串 'bbb' 没有出现在 S 中。
示例 1:
输入:A = 1, B = 2
输出:"abb"
解释:"abb", "bab" 和 "bba" 都是正确答案。
示例 2:
输入:A = 4, B = 1
输出:"aabaa"
提示:
0 <= A <= 100
0 <= B <= 100
对于给定的 A 和 B,保证存在满足要求的 S。
*/
class Solution {
public String strWithout3a3b(int A, int B) {
}
}<file_sep>package com.LeetCode.code.q391.PerfectRectangle;
/**
* @QuestionId : 391
* @difficulty : Hard
* @Title : Perfect Rectangle
* @TranslatedTitle:完美矩形
* @url : https://leetcode-cn.com/problems/perfect-rectangle/
* @TranslatedContent:我们有 N 个与坐标轴对齐的矩形, 其中 N > 0, 判断它们是否能精确地覆盖一个矩形区域。
每个矩形用左下角的点和右上角的点的坐标来表示。例如, 一个单位正方形可以表示为 [1,1,2,2]。 ( 左下角的点的坐标为 (1, 1) 以及右上角的点的坐标为 (2, 2) )。
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/rectangle_perfect.gif">
示例 1:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
返回 true。5个矩形一起可以精确地覆盖一个矩形区域。
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/rectangle_separated.gif">
示例 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
返回 false。两个矩形之间有间隔,无法覆盖成一个矩形。
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/rectangle_hole.gif">
示例 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
返回 false。图形顶端留有间隔,无法覆盖成一个矩形。
<img src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/10/22/rectangle_intersect.gif">
示例 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
返回 false。因为中间有相交区域,虽然形成了矩形,但不是精确覆盖。
*/
class Solution {
public boolean isRectangleCover(int[][] rectangles) {
}
}<file_sep>package com.LeetCode.code.q851.GoatLatin;
/**
* @QuestionId : 851
* @difficulty : Easy
* @Title : Goat Latin
* @TranslatedTitle:山羊拉丁文
* @url : https://leetcode-cn.com/problems/goat-latin/
* @TranslatedContent:给定一个由空格分割单词的句子 S。每个单词只包含大写或小写字母。
我们要将句子转换为 “Goat Latin”(一种类似于 猪拉丁文 - Pig Latin 的虚构语言)。
山羊拉丁文的规则如下:
如果单词以元音开头(a, e, i, o, u),在单词后添加"ma"。<br />
例如,单词"apple"变为"applema"。
<br />
如果单词以辅音字母开头(即非元音字母),移除第一个字符并将它放到末尾,之后再添加"ma"。<br />
例如,单词"goat"变为"oatgma"。
<br />
根据单词在句子中的索引,在单词最后添加与索引相同数量的字母'a',索引从1开始。<br />
例如,在第一个单词后添加"a",在第二个单词后添加"aa",以此类推。
返回将 S 转换为山羊拉丁文后的句子。
示例 1:
输入: "I speak Goat Latin"
输出: "Imaa peaksmaaa oatGmaaaa atinLmaaaaa"
示例 2:
输入: "The quick brown fox jumped over the lazy dog"
输出: "heTmaa uickqmaaa rownbmaaaa oxfmaaaaa umpedjmaaaaaa overmaaaaaaa hetmaaaaaaaa azylmaaaaaaaaa ogdmaaaaaaaaaa"
说明:
S 中仅包含大小写字母和空格。单词间有且仅有一个空格。
1 <= S.length <= 150。
*/
class Solution {
public String toGoatLatin(String S) {
}
}<file_sep>package com.LeetCode.code.q1117.AsFarfromLandasPossible;
/**
* @QuestionId : 1117
* @difficulty : Medium
* @Title : As Far from Land as Possible
* @TranslatedTitle:地图分析
* @url : https://leetcode-cn.com/problems/as-far-from-land-as-possible/
* @TranslatedContent:你现在手里有一份大小为 N x N 的『地图』(网格) grid,上面的每个『区域』(单元格)都用 0 和 1 标记好了。其中 0 代表海洋,1 代表陆地,你知道距离陆地区域最远的海洋区域是是哪一个吗?请返回该海洋区域到离它最近的陆地区域的距离。
我们这里说的距离是『曼哈顿距离』( Manhattan Distance):(x0, y0) 和 (x1, y1) 这两个区域之间的距离是 |x0 - x1| + |y0 - y1| 。
如果我们的地图上只有陆地或者海洋,请返回 -1。
示例 1:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/08/17/1336_ex1.jpeg" style="height: 87px; width: 185px;">
输入:[[1,0,1],[0,0,0],[1,0,1]]
输出:2
解释:
海洋区域 (1, 1) 和所有陆地区域之间的距离都达到最大,最大距离为 2。
示例 2:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/08/17/1336_ex2.jpeg" style="height: 87px; width: 184px;">
输入:[[1,0,0],[0,0,0],[0,0,0]]
输出:4
解释:
海洋区域 (2, 2) 和所有陆地区域之间的距离都达到最大,最大距离为 4。
提示:
1 <= grid.length == grid[0].length <= 100
grid[i][j] 不是 0 就是 1
*/
class Solution {
public int maxDistance(int[][] grid) {
}
}<file_sep>package com.LeetCode.code.q504.Base7;
/**
* @QuestionId : 504
* @difficulty : Easy
* @Title : Base 7
* @TranslatedTitle:七进制数
* @url : https://leetcode-cn.com/problems/base-7/
* @TranslatedContent:给定一个整数,将其转化为7进制,并以字符串形式输出。
示例 1:
输入: 100
输出: "202"
示例 2:
输入: -7
输出: "-10"
注意: 输入范围是 [-1e7, 1e7] 。
*/
class Solution {
public String convertToBase7(int num) {
}
}<file_sep>package com.LeetCode.code.q1282.NumberofValidWordsforEachPuzzle;
/**
* @QuestionId : 1282
* @difficulty : Hard
* @Title : Number of Valid Words for Each Puzzle
* @TranslatedTitle:猜字谜
* @url : https://leetcode-cn.com/problems/number-of-valid-words-for-each-puzzle/
* @TranslatedContent:外国友人仿照中国字谜设计了一个英文版猜字谜小游戏,请你来猜猜看吧。
字谜的迷面 puzzle 按字符串形式给出,如果一个单词 word 符合下面两个条件,那么它就可以算作谜底:
单词 word 中包含谜面 puzzle 的第一个字母。
单词 word 中的每一个字母都可以在谜面 puzzle 中找到。
例如,如果字谜的谜面是 "abcdefg",那么可以作为谜底的单词有 "faced", "cabbage", 和 "baggage";而 "beefed"(不含字母 "a")以及 "based"(其中的 "s" 没有出现在谜面中)。
返回一个答案数组 answer,数组中的每个元素 answer[i] 是在给出的单词列表 words 中可以作为字谜迷面 puzzles[i] 所对应的谜底的单词数目。
示例:
输入:
words = ["aaaa","asas","able","ability","actt","actor","access"],
puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
输出:[1,1,3,2,4,0]
解释:
1 个单词可以作为 "aboveyz" 的谜底 : "aaaa"
1 个单词可以作为 "abrodyz" 的谜底 : "aaaa"
3 个单词可以作为 "abslute" 的谜底 : "aaaa", "asas", "able"
2 个单词可以作为 "absoryz" 的谜底 : "aaaa", "asas"
4 个单词可以作为 "actresz" 的谜底 : "aaaa", "asas", "actt", "access"
没有单词可以作为 "gaswxyz" 的谜底,因为列表中的单词都不含字母 'g'。
提示:
1 <= words.length <= 10^5
4 <= words[i].length <= 50
1 <= puzzles.length <= 10^4
puzzles[i].length == 7
words[i][j], puzzles[i][j] 都是小写英文字母。
每个 puzzles[i] 所包含的字符都不重复。
*/
class Solution {
public List<Integer> findNumOfValidWords(String[] words, String[] puzzles) {
}
}<file_sep>package com.LeetCode.code.q962.FlipStringtoMonotoneIncreasing;
/**
* @QuestionId : 962
* @difficulty : Medium
* @Title : Flip String to Monotone Increasing
* @TranslatedTitle:将字符串翻转到单调递增
* @url : https://leetcode-cn.com/problems/flip-string-to-monotone-increasing/
* @TranslatedContent:如果一个由 '0' 和 '1' 组成的字符串,是以一些 '0'(可能没有 '0')后面跟着一些 '1'(也可能没有 '1')的形式组成的,那么该字符串是单调递增的。
我们给出一个由字符 '0' 和 '1' 组成的字符串 S,我们可以将任何 '0' 翻转为 '1' 或者将 '1' 翻转为 '0'。
返回使 S 单调递增的最小翻转次数。
示例 1:
输入:"00110"
输出:1
解释:我们翻转最后一位得到 00111.
示例 2:
输入:"010110"
输出:2
解释:我们翻转得到 011111,或者是 000111。
示例 3:
输入:"00011000"
输出:2
解释:我们翻转得到 00000000。
提示:
1 <= S.length <= 20000
S 中只包含字符 '0' 和 '1'
*/
class Solution {
public int minFlipsMonoIncr(String S) {
}
}<file_sep>package com.LeetCode.code.q975.RangeSumofBST;
/**
* @QuestionId : 975
* @difficulty : Easy
* @Title : Range Sum of BST
* @TranslatedTitle:二叉搜索树的范围和
* @url : https://leetcode-cn.com/problems/range-sum-of-bst/
* @TranslatedContent:给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。
二叉搜索树保证具有唯一的值。
示例 1:
输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32
示例 2:
输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23
提示:
树中的结点数量最多为 10000 个。
最终的答案保证小于 2^31。
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rangeSumBST(TreeNode root, int L, int R) {
}
}<file_sep>package com.LeetCode.code.q905.LengthofLongestFibonacciSubsequence;
/**
* @QuestionId : 905
* @difficulty : Medium
* @Title : Length of Longest Fibonacci Subsequence
* @TranslatedTitle:最长的斐波那契子序列的长度
* @url : https://leetcode-cn.com/problems/length-of-longest-fibonacci-subsequence/
* @TranslatedContent:如果序列 X_1, X_2, ..., X_n 满足下列条件,就说它是 斐波那契式 的:
n >= 3
对于所有 i + 2 <= n,都有 X_i + X_{i+1} = X_{i+2}
给定一个严格递增的正整数数组形成序列,找到 A 中最长的斐波那契式的子序列的长度。如果一个不存在,返回 0 。
(回想一下,子序列是从原序列 A 中派生出来的,它从 A 中删掉任意数量的元素(也可以不删),而不改变其余元素的顺序。例如, [3, 5, 8] 是 [3, 4, 5, 6, 7, 8] 的一个子序列)
示例 1:
输入: [1,2,3,4,5,6,7,8]
输出: 5
解释:
最长的斐波那契式子序列为:[1,2,3,5,8] 。
示例 2:
输入: [1,3,7,11,12,14,18]
输出: 3
解释:
最长的斐波那契式子序列有:
[1,11,12],[3,11,14] 以及 [7,11,18] 。
提示:
3 <= A.length <= 1000
1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
(对于以 Java,C,C++,以及 C# 的提交,时间限制被减少了 50%)
*/
class Solution {
public int lenLongestFibSubseq(int[] A) {
}
}<file_sep>package com.LeetCode.code.q914.RandomPointinNon-overlappingRectangles;
/**
* @QuestionId : 914
* @difficulty : Medium
* @Title : Random Point in Non-overlapping Rectangles
* @TranslatedTitle:非重叠矩形中的随机点
* @url : https://leetcode-cn.com/problems/random-point-in-non-overlapping-rectangles/
* @TranslatedContent:给定一个非重叠轴对齐矩形的列表 rects,写一个函数 pick 随机均匀地选取矩形覆盖的空间中的整数点。
提示:
整数点是具有整数坐标的点。
矩形周边上的点包含在矩形覆盖的空间中。
第 i 个矩形 rects [i] = [x1,y1,x2,y2],其中 [x1,y1] 是左下角的整数坐标,[x2,y2] 是右上角的整数坐标。
每个矩形的长度和宽度不超过 2000。
1 <= rects.length <= 100
pick 以整数坐标数组 [p_x, p_y] 的形式返回一个点。
pick 最多被调用10000次。
示例 1:
输入:
["Solution","pick","pick","pick"]
[[[[1,1,5,5]]],[],[],[]]
输出:
[null,[4,1],[4,1],[3,3]]
示例 2:
输入:
["Solution","pick","pick","pick","pick","pick"]
[[[[-2,-2,-1,-1],[1,0,3,0]]],[],[],[],[],[]]
输出:
[null,[-1,-2],[2,0],[-2,-1],[3,0],[-2,-2]]
输入语法的说明:
输入是两个列表:调用的子例程及其参数。Solution 的构造函数有一个参数,即矩形数组 rects。pick 没有参数。参数总是用列表包装的,即使没有也是如此。
*/
class Solution {
public Solution(int[][] rects) {
}
public int[] pick() {
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(rects);
* int[] param_1 = obj.pick();
*/<file_sep>package com.LeetCode.code.q1220.SmallestSufficientTeam;
/**
* @QuestionId : 1220
* @difficulty : Hard
* @Title : Smallest Sufficient Team
* @TranslatedTitle:最小的必要团队
* @url : https://leetcode-cn.com/problems/smallest-sufficient-team/
* @TranslatedContent:作为项目经理,你规划了一份需求的技能清单 req_skills,并打算从备选人员名单 people 中选出些人组成一个「必要团队」( 编号为 i 的备选人员 people[i] 含有一份该备选人员掌握的技能列表)。
所谓「必要团队」,就是在这个团队中,对于所需求的技能列表 req_skills 中列出的每项技能,团队中至少有一名成员已经掌握。
我们可以用每个人的编号来表示团队中的成员:例如,团队 team = [0, 1, 3] 表示掌握技能分别为 people[0],people[1],和 people[3] 的备选人员。
请你返回 任一 规模最小的必要团队,团队成员用人员编号表示。你可以按任意顺序返回答案,本题保证答案存在。
示例 1:
输入:req_skills = ["java","nodejs","reactjs"], people = [["java"],["nodejs"],["nodejs","reactjs"]]
输出:[0,2]
示例 2:
输入:req_skills = ["algorithms","math","java","reactjs","csharp","aws"], people = [["algorithms","math","java"],["algorithms","math","reactjs"],["java","csharp","aws"],["reactjs","csharp"],["csharp","math"],["aws","java"]]
输出:[1,2]
提示:
1 <= req_skills.length <= 16
1 <= people.length <= 60
1 <= people[i].length, req_skills[i].length, people[i][j].length <= 16
req_skills 和 people[i] 中的元素分别各不相同
req_skills[i][j], people[i][j][k] 都由小写英文字母组成
本题保证「必要团队」一定存在
*/
class Solution {
public int[] smallestSufficientTeam(String[] req_skills, List<List<String>> people) {
}
}<file_sep>package com.LeetCode.code.q633.SumofSquareNumbers;
/**
* @QuestionId : 633
* @difficulty : Easy
* @Title : Sum of Square Numbers
* @TranslatedTitle:平方数之和
* @url : https://leetcode-cn.com/problems/sum-of-square-numbers/
* @TranslatedContent:给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c。
示例1:
输入: 5
输出: True
解释: 1 * 1 + 2 * 2 = 5
示例2:
输入: 3
输出: False
*/
class Solution {
public boolean judgeSquareSum(int c) {
}
}<file_sep>package com.LeetCode.code.q371.SumofTwoIntegers;
/**
* @QuestionId : 371
* @difficulty : Easy
* @Title : Sum of Two Integers
* @TranslatedTitle:两整数之和
* @url : https://leetcode-cn.com/problems/sum-of-two-integers/
* @TranslatedContent:不使用运算符 + 和 - ,计算两整数 a 、b 之和。
示例 1:
输入: a = 1, b = 2
输出: 3
示例 2:
输入: a = -2, b = 3
输出: 1
*/
class Solution {
public int getSum(int a, int b) {
}
}<file_sep>package com.LeetCode.code.q322.CoinChange;
/**
* @QuestionId : 322
* @difficulty : Medium
* @Title : Coin Change
* @TranslatedTitle:零钱兑换
* @url : https://leetcode-cn.com/problems/coin-change/
* @TranslatedContent:给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
示例 1:
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
示例 2:
输入: coins = [2], amount = 3
输出: -1
说明:
你可以认为每种硬币的数量是无限的。
*/
class Solution {
public int coinChange(int[] coins, int amount) {
}
}<file_sep>package com.LeetCode.code.q324.WiggleSortII;
/**
* @QuestionId : 324
* @difficulty : Medium
* @Title : Wiggle Sort II
* @TranslatedTitle:摆动排序 II
* @url : https://leetcode-cn.com/problems/wiggle-sort-ii/
* @TranslatedContent:给定一个无序的数组 nums,将它重新排列成 nums[0] < nums[1] > nums[2] < nums[3]... 的顺序。
示例 1:
输入: nums = [1, 5, 1, 1, 6, 4]
输出: 一个可能的答案是 [1, 4, 1, 5, 1, 6]
示例 2:
输入: nums = [1, 3, 2, 2, 3, 1]
输出: 一个可能的答案是 [2, 3, 1, 3, 1, 2]
说明:
你可以假设所有输入都会得到有效的结果。
进阶:
你能用 O(n) 时间复杂度和 / 或原地 O(1) 额外空间来实现吗?
*/
class Solution {
public void wiggleSort(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q659.SplitArrayintoConsecutiveSubsequences;
/**
* @QuestionId : 659
* @difficulty : Medium
* @Title : Split Array into Consecutive Subsequences
* @TranslatedTitle:分割数组为连续子序列
* @url : https://leetcode-cn.com/problems/split-array-into-consecutive-subsequences/
* @TranslatedContent:输入一个按升序排序的整数数组(可能包含重复数字),你需要将它们分割成几个子序列,其中每个子序列至少包含三个连续整数。返回你是否能做出这样的分割?
示例 1:
输入: [1,2,3,3,4,5]
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3
3, 4, 5
示例 2:
输入: [1,2,3,3,4,4,5,5]
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3, 4, 5
3, 4, 5
示例 3:
输入: [1,2,3,4,4,5]
输出: False
提示:
输入的数组长度范围为 [1, 10000]
*/
class Solution {
public boolean isPossible(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q486.PredicttheWinner;
/**
* @QuestionId : 486
* @difficulty : Medium
* @Title : Predict the Winner
* @TranslatedTitle:预测赢家
* @url : https://leetcode-cn.com/problems/predict-the-winner/
* @TranslatedContent:给定一个表示分数的非负整数数组。 玩家1从数组任意一端拿取一个分数,随后玩家2继续从剩余数组任意一端拿取分数,然后玩家1拿,……。每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。
给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。
示例 1:
输入: [1, 5, 2]
输出: False
解释: 一开始,玩家1可以从1和2中进行选择。
如果他选择2(或者1),那么玩家2可以从1(或者2)和5中进行选择。如果玩家2选择了5,那么玩家1则只剩下1(或者2)可选。
所以,玩家1的最终分数为 1 + 2 = 3,而玩家2为 5。
因此,玩家1永远不会成为赢家,返回 False。
示例 2:
输入: [1, 5, 233, 7]
输出: True
解释: 玩家1一开始选择1。然后玩家2必须从5和7中进行选择。无论玩家2选择了哪个,玩家1都可以选择233。
最终,玩家1(234分)比玩家2(12分)获得更多的分数,所以返回 True,表示玩家1可以成为赢家。
注意:
1 <= 给定的数组长度 <= 20.
数组里所有分数都为非负数且不会大于10000000。
如果最终两个玩家的分数相等,那么玩家1仍为赢家。
*/
class Solution {
public boolean PredictTheWinner(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q179.LargestNumber;
/**
* @QuestionId : 179
* @difficulty : Medium
* @Title : Largest Number
* @TranslatedTitle:最大数
* @url : https://leetcode-cn.com/problems/largest-number/
* @TranslatedContent:给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
示例 1:
输入: [10,2]
输出: 210
示例 2:
输入: [3,30,34,5,9]
输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
*/
class Solution {
public String largestNumber(int[] nums) {
}
}<file_sep>package com.LeetCode.code.q1054.ComplementofBase10Integer;
/**
* @QuestionId : 1054
* @difficulty : Easy
* @Title : Complement of Base 10 Integer
* @TranslatedTitle:十进制整数的反码
* @url : https://leetcode-cn.com/problems/complement-of-base-10-integer/
* @TranslatedContent:每个非负整数 N 都有其二进制表示。例如, 5 可以被表示为二进制 "101",11 可以用二进制 "1011" 表示,依此类推。注意,除 N = 0 外,任何二进制表示中都不含前导零。
二进制的反码表示是将每个 1 改为 0 且每个 0 变为 1。例如,二进制数 "101" 的二进制反码为 "010"。
给定十进制数 N,返回其二进制表示的反码所对应的十进制整数。
示例 1:
输入:5
输出:2
解释:5 的二进制表示为 "101",其二进制反码为 "010",也就是十进制中的 2 。
示例 2:
输入:7
输出:0
解释:7 的二进制表示为 "111",其二进制反码为 "000",也就是十进制中的 0 。
示例 3:
输入:10
输出:5
解释:10 的二进制表示为 "1010",其二进制反码为 "0101",也就是十进制中的 5 。
提示:
0 <= N < 10^9
*/
class Solution {
public int bitwiseComplement(int N) {
}
}<file_sep>package com.LeetCode.code.q199.BinaryTreeRightSideView;
/**
* @QuestionId : 199
* @difficulty : Medium
* @Title : Binary Tree Right Side View
* @TranslatedTitle:二叉树的右视图
* @url : https://leetcode-cn.com/problems/binary-tree-right-side-view/
* @TranslatedContent:给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:
1 <---
/ \
2 3 <---
\ \
5 4 <---
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
}
}<file_sep>package com.LeetCode.code.q1248.BinaryTreeColoringGame;
/**
* @QuestionId : 1248
* @difficulty : Medium
* @Title : Binary Tree Coloring Game
* @TranslatedTitle:二叉树着色游戏
* @url : https://leetcode-cn.com/problems/binary-tree-coloring-game/
* @TranslatedContent:有两位极客玩家参与了一场「二叉树着色」的游戏。游戏中,给出二叉树的根节点 root,树上总共有 n 个节点,且 n 为奇数,其中每个节点上的值从 1 到 n 各不相同。
游戏从「一号」玩家开始(「一号」玩家为红色,「二号」玩家为蓝色),最开始时,
「一号」玩家从 [1, n] 中取一个值 x(1 <= x <= n);
「二号」玩家也从 [1, n] 中取一个值 y(1 <= y <= n)且 y != x。
「一号」玩家给值为 x 的节点染上红色,而「二号」玩家给值为 y 的节点染上蓝色。
之后两位玩家轮流进行操作,每一回合,玩家选择一个他之前涂好颜色的节点,将所选节点一个 未着色 的邻节点(即左右子节点、或父节点)进行染色。
如果当前玩家无法找到这样的节点来染色时,他的回合就会被跳过。
若两个玩家都没有可以染色的节点时,游戏结束。着色节点最多的那位玩家获得胜利 ✌️。
现在,假设你是「二号」玩家,根据所给出的输入,假如存在一个 y 值可以确保你赢得这场游戏,则返回 true;若无法获胜,就请返回 false。
示例:
<img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2019/08/04/1480-binary-tree-coloring-game.png" style="height: 186px; width: 300px;">
输入:root = [1,2,3,4,5,6,7,8,9,10,11], n = 11, x = 3
输出:True
解释:第二个玩家可以选择值为 2 的节点。
提示:
二叉树的根节点为 root,树上由 n 个节点,节点上的值从 1 到 n 各不相同。
n 为奇数。
1 <= x <= n <= 100
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean btreeGameWinningMove(TreeNode root, int n, int x) {
}
}<file_sep>package com.LeetCode.code.q326.PowerofThree;
/**
* @QuestionId : 326
* @difficulty : Easy
* @Title : Power of Three
* @TranslatedTitle:3的幂
* @url : https://leetcode-cn.com/problems/power-of-three/
* @TranslatedContent:给定一个整数,写一个函数来判断它是否是 3 的幂次方。
示例 1:
输入: 27
输出: true
示例 2:
输入: 0
输出: false
示例 3:
输入: 9
输出: true
示例 4:
输入: 45
输出: false
进阶:
你能不使用循环或者递归来完成本题吗?
*/
class Solution {
public boolean isPowerOfThree(int n) {
}
}<file_sep>package com.LeetCode.code.q172.FactorialTrailingZeroes;
/**
* @QuestionId : 172
* @difficulty : Easy
* @Title : Factorial Trailing Zeroes
* @TranslatedTitle:阶乘后的零
* @url : https://leetcode-cn.com/problems/factorial-trailing-zeroes/
* @TranslatedContent:给定一个整数 n,返回 n! 结果尾数中零的数量。
示例 1:
输入: 3
输出: 0
解释: 3! = 6, 尾数中没有零。
示例 2:
输入: 5
输出: 1
解释: 5! = 120, 尾数中有 1 个零.
说明: 你算法的时间复杂度应为 O(log n) 。
*/
class Solution {
public int trailingZeroes(int n) {
}
}<file_sep>package com.LeetCode.code.q27.RemoveElement;
/**
* @QuestionId : 27
* @difficulty : Easy
* @Title : Remove Element
* @TranslatedTitle:移除元素
* @url : https://leetcode-cn.com/problems/remove-element/
* @TranslatedContent:给定一个数组 nums 和一个值 val,你需要<a href="https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95" target="_blank">原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在<a href="https://baike.baidu.com/item/%E5%8E%9F%E5%9C%B0%E7%AE%97%E6%B3%95" target="_blank">原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
示例 1:
给定 nums = [3,2,2,3], val = 3,
函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。
你不需要考虑数组中超出新长度后面的元素。
示例 2:
给定 nums = [0,1,2,2,3,0,4,2], val = 2,
函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。
注意这五个元素可为任意顺序。
你不需要考虑数组中超出新长度后面的元素。
说明:
为什么返回数值是整数,但输出的答案是数组呢?
请注意,输入数组是以“引用”方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。
你可以想象内部操作如下:
// nums 是以“引用”方式传递的。也就是说,不对实参作任何拷贝
int len = removeElement(nums, val);
// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中该长度范围内的所有元素。
for (int i = 0; i < len; i++) {
print(nums[i]);
}
*/
class Solution {
public int removeElement(int[] nums, int val) {
}
}<file_sep>package com.LeetCode.code.q44.WildcardMatching;
/**
* @QuestionId : 44
* @difficulty : Hard
* @Title : Wildcard Matching
* @TranslatedTitle:通配符匹配
* @url : https://leetcode-cn.com/problems/wildcard-matching/
* @TranslatedContent:给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。
'?' 可以匹配任何单个字符。
'*' 可以匹配任意字符串(包括空字符串)。
两个字符串完全匹配才算匹配成功。
说明:
s 可能为空,且只包含从 a-z 的小写字母。
p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。
示例 1:
输入:
s = "aa"
p = "a"
输出: false
解释: "a" 无法匹配 "aa" 整个字符串。
示例 2:
输入:
s = "aa"
p = "*"
输出: true
解释: '*' 可以匹配任意字符串。
示例 3:
输入:
s = "cb"
p = "?a"
输出: false
解释: '?' 可以匹配 'c', 但第二个 'a' 无法匹配 'b'。
示例 4:
输入:
s = "adceb"
p = "*a*b"
输出: true
解释: 第一个 '*' 可以匹配空字符串, 第二个 '*' 可以匹配字符串 "dce".
示例 5:
输入:
s = "acdcb"
p = "a*c?b"
输入: false
*/
class Solution {
public boolean isMatch(String s, String p) {
}
} | 3f3620a5542b0c51b69a26bb36934af256e9392e | [
"Java"
] | 358 | Java | dengxiny/LeetCode | 66a8e937e57f9fa817e9bf5c5b0a2187851b0ab0 | f4b2122ba61076fa664dbb4a04de824a7be21bfd |
refs/heads/master | <repo_name>erte12/dropout<file_sep>/README.md
# dropout
Web directory based on Laravel framework

<br><br>

<br><br>

<file_sep>/app/Http/Controllers/WebsiteController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\WebsiteRequest;
use App\Category;
use App\Website;
use App\Tag;
use App\WebsiteEdited;
class WebsiteController extends Controller
{
/**
* Construct with middleware
*/
public function __construct()
{
$this->middleware('auth', ['except' => 'show']);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$categories = Category::orderBy('name')->with('subcategories')->get();
return view('website.create', compact('categories'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(WebsiteRequest $request)
{
$website = auth()->user()->websites()->create([
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
]);
Tag::createTagsForWebsite($request->tags, $website, false);
return redirect()->route('home')
->with('status', 'Your website has been sent and will appear in web directory soon.');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($category, $subcategory, $slug, $id)
{
$website = Website::where('active', '=', 1)
->where('id', '=', $id)
->with('tags')
->first();
if(is_null($website)) {
abort(404, 'Taka strona nie istnieje');
}
if ($slug !== $website->slug || $subcategory !== $website->subcategory->slug || $category !== $website->subcategory->category->slug) {
return redirect()->to($website->friendly_url);
}
return view('website.show', compact('website'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($category, $subcategory, $slug, $id)
{
$website = Website::where('id', $id)->with('tags')->first();
$categories = Category::orderBy('name')->with('subcategories')->get();
return view('website.edit', compact('website', 'categories'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(WebsiteRequest $request, $id)
{
/* Code if admin logged, only superuser is able to modify 'active' column */
if(superuser()) {
$website = Website::findOrFail($id);
Tag::createTagsForWebsite($request->tags, $website, true);
$website->update([
'name' => $request->name,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
'active' => $request->accept,
]);
return back();
/* Code if user logged */
} else {
$website = Website::findOrFail($id);
/* Save changes instantly if website is not active */
if($website->active == 0) {
$website->update([
'name' => $request->name,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
]);
Tag::createTagsForWebsite($request->tags, $website, true);
/* Send edit request if website is active */
} else {
$website_edited = WebsiteEdited::updateOrCreate([
'url' => $website->url,
], [
'website_id' => $website->id,
'user_id' => $website->user_id,
'name' => $request->name,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
'tags' => json_encode($request->tags),
]);
}
}
if(superuser()) {
return redirect()->route('panel');
}
return redirect()->route('panel.user.websites');
}
/**
* Remove the specified resource from storage (softdeleting)
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$website = Website::findOrFail($id)->delete();
if(superuser()) {
return redirect()->route('panel');
}
return redirect()->route('panel.user.websites');
}
/**
* Remove the specified resource from storage (hardeleting).
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy_forever($id)
{
$website = Website::withTrashed()->findOrFail($id)->forceDelete();
if(superuser()) {
return redirect()->route('panel');
}
return redirect()->route('panel.user.websites');
}
/**
* Restore the specified resource
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function restore($id)
{
$website = Website::withTrashed()->findOrFail($id)->restore();
return back();
}
}
<file_sep>/app/Subcategory.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Subcategory extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* Returns parent category
* @return \App\Category
*/
public function category()
{
return $this->belongsTo('App\Category');
}
/**
* Returns all subcategory's websites
* @return \App\Website
*/
public function websites()
{
return $this->hasMany('App\Website')->orderBy('created_at', 'desc')->where('active', '=', 1);
}
/**
* Generate sluggified viersion of name
* @return string
*/
public function getSlugAttribute(): string
{
return str_slug($this->name);
}
/**
* Generate friendly url
* @return string
*/
public function getFriendlyUrlAttribute(): string
{
return action('SubcategoryController@show', [$this->category->slug, $this->slug]);
}
}
<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use App\Website;
use App\Tag;
class DatabaseSeeder extends Seeder
{
/**
* Const numbers of particular elements in database
* @var integer
*/
const NUMBER_OF_CATEGORIES = 15;
const NUMBER_OF_SUBCATEGORIES = 8;
const NUMBER_OF_USERS = 20;
const MAX_NUMBER_OF_WEBSITES_PER_SUBCATEGORY = 25;
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = Faker::create('en_UK');
/**
* Roles seeds
*/
DB::table('roles')->insert([
'id' => 1,
'name' => 'admin',
]);
DB::table('roles')->insert([
'id' => 2,
'name' => 'user',
]);
/**
* Users seeds
*/
for($user_id = 1; $user_id <= self::NUMBER_OF_USERS; $user_id++)
{
if($user_id === 1) {
DB::table('users')->insert([
'name' => 'Admin',
'email' => '<EMAIL>',
'password' => <PASSWORD>'),
'role_id' => 1,
]);
} else if($user_id === 2) {
DB::table('users')->insert([
'name' => 'User',
'email' => '<EMAIL>',
'password' => <PASSWORD>('<PASSWORD>'),
'role_id' => 2,
]);
} else {
DB::table('users')->insert([
'name' => $faker->firstNameMale . ' ' . $faker->lastName,
'email' => $faker->safeEmail,
'password' => <PASSWORD>('<PASSWORD>'),
]);
}
}
/**
* Categories seeds
*/
for($category_id = 1; $category_id <= self::NUMBER_OF_CATEGORIES; $category_id++)
{
$name = $faker->unique()->firstName;
DB::table('categories')->insert([
'name' => $name,
'slug' => str_slug($name),
]);
/**
* Subcategories seeds
*/
for($subcategory_id = 1; $subcategory_id <= self::NUMBER_OF_SUBCATEGORIES; $subcategory_id++)
{
$name = $faker->unique()->lastName;
DB::table('subcategories')->insert([
'name' => $name,
'slug' => str_slug($name),
'category_id' => $category_id,
]);
/**
* Websites seeds
*
*/
$subcategory_id_for_website_to_database = ($category_id - 1) * self::NUMBER_OF_SUBCATEGORIES + $subcategory_id;
for($website_id = 1; $website_id <= $faker->numberBetween(1, self::MAX_NUMBER_OF_WEBSITES_PER_SUBCATEGORY); $website_id++)
{
/**
* Inserts only main website
*/
$url = $faker->unique()->url;
$last_index = strrpos($url, '/');
try {
$website_id = DB::table('websites')->insertGetId([
'user_id' => $faker->numberBetween(2,self::NUMBER_OF_USERS),
'name' => $faker->text($maxNbChars = 50),
'subcategory_id' => $subcategory_id_for_website_to_database,
'url' => substr($url, 0, $last_index),
'description' => $faker->paragraph($nbSentences = 20, $variableNbSentences = true),
'active' => $faker->numberBetween(0,1),
'created_at' => $faker->dateTime(),
]);
$website = Website::findOrFail($website_id);
foreach ($faker->words($nb = 5, $asText = false) as $tag_name) {
$tag = Tag::where(['name' => $tag_name])->first();
if(is_null($tag)) {
$website->tags()->create([
'name' => $tag_name,
]);
} else {
$website->tags()->attach($tag->id);
}
}
} catch(PDOException $expection) {
continue;
}
}
}
}
}
}
<file_sep>/routes/web.php
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/* Auth */
Auth::routes();
/* Panel - user */
Route::get('/', 'HomeController@index')->name('home');
Route::get('/panel', 'PanelController@index')->name('panel');
Route::get('/panel/websites', 'PanelController@user_websites')->name('panel.user.websites');
Route::get('/rules', function () { return view('info.rules'); })->name('rules');
/* Panel - admin */
Route::get('/panel/admin/websites/accepted', 'PanelController@admin_websites_accepted')->name('panel.admin.websites.accepted');
Route::get('/panel/admin/websites/waiting', 'PanelController@admin_websites_waiting')->name('panel.admin.websites.waiting');
Route::get('/panel/admin/websites/edited', 'PanelController@admin_websites_edited')->name('panel.admin.websites.edited');
Route::get('/panel/admin/websites/deleted', 'PanelController@admin_websites_deleted')->name('panel.admin.websites.deleted');
Route::get('/panel/admin/users', 'PanelController@admin_users')->name('panel.admin.users');
/* Websites */
Route::delete('/website/f/{website}', 'WebsiteController@destroy_forever')->name('website.destroy.forever');
Route::get('/{category}/{subcategory}/{website}/{id}', 'WebsiteController@show')->name('website.show');
Route::get('/{category}/{subcategory}/{website}/{id}/edit', 'WebsiteController@edit')->name('website.edit');
Route::get('/add-website', 'WebsiteController@create')->name('website.create');
Route::resource('/website', 'WebsiteController', ['only' => ['store', 'update', 'destroy']]);
/* Websites edited */
Route::get('/website-edited/{id}/edit', 'WebsiteEditedController@edit')->name('website.edited.edit');
Route::patch('/website-edited/{id}', 'WebsiteEditedController@update')->name('website.edited.update');
Route::delete('/website-edited/{id}', 'WebsiteEditedController@destroy')->name('website.edited.delete');
/* Search */
Route::get('/search', 'SearchController@websites')->name('search');
/* Categories */
Route::get('/{category}', 'CategoryController@show')->name('category.show');
/* Subcategories */
Route::get('/{category}/{subcategory}', 'SubcategoryController@show')->name('subcategory.show');
/* Users */
Route::resource('/user', 'UsersController', ['only' => ['edit', 'update', 'destroy']]);
<file_sep>/database/migrations/2017_08_01_202322_create_tag_website_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTagWebsiteTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tag_website', function (Blueprint $table) {
$table->increments('id');
$table->integer('tag_id')->unsigned()->nullable();
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->integer('website_id')->unsigned()->nullable();
$table->foreign('website_id')->references('id')->on('websites')->onDelete('cascade');
$table->tinyInteger('active')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tag_website');
}
}
<file_sep>/app/Tag.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
protected $fillable = [
'name',
];
/**
* Get all websites that contain this tag
* @return \App\Website
*/
public function website()
{
return $this->belongsToMany('App\Website');
}
/**
* Create tags for given website
*
* @param array $tags
* @param \App\Website $website
* @param bool $mode - if true it reloads tags for given website if any exist
*/
public static function createTagsForWebsite($tags, $website, $mode)
{
if($mode == true) {
$website->tags()->delete();
}
foreach ($tags as $tag_name) {
$tag = Tag::where(['name' => $tag_name])->first();
if(is_null($tag)) {
$website->tags()->create([
'name' => $tag_name,
]);
} else {
$website->tags()->attach($tag->id);
}
}
return;
}
}
<file_sep>/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
use App\Website;
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$categories = Category::orderBy('name')
->with('subcategories')
->with('websites')
->get();
$websites = Website::latest()->where('active', '=', 1)->limit(5)->get();
return view('mainpage.welcome', compact('categories', 'websites'));
}
}
<file_sep>/app/Website.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Website extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id',
'name',
'url',
'description',
'subcategory_id',
'edit',
'active'
];
public function subcategory()
{
return $this->belongsTo('App\Subcategory');
}
/**
* Get the user that owns the website.
*/
public function user()
{
return $this->belongsTo('App\User');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
/**
* Return website's tags in string with commas
* @return string
*/
public function getTagsString()
{
$tags = $this->tags;
$result = '';
for($i = 0; $i < $tags->count(); $i++) {
$result = $result . $tags->get($i)->name . (($i < $tags->count() - 1) ? ', ' : '');
}
return $result;
}
/**
* Get the website in edit queue.
*/
public function website_edited()
{
return $this->hasOne('App\WebsiteEdited');
}
/**
* Generate sluggified viersion of name
* @return string
*/
public function getSlugAttribute(): string
{
return str_slug($this->name);
}
/**
* Generate friendly url
* @return string
*/
public function getFriendlyUrlAttribute(): string
{
return action('WebsiteController@show', [$this->subcategory->category->slug, $this->subcategory->slug, $this->slug, $this->id]);
}
/**
* Generate friendly url to edit form
* @return string
*/
public function getFriendlyUrlEditAttribute(): string
{
return action('WebsiteController@edit', [$this->subcategory->category->slug, $this->subcategory->slug, $this->slug, $this->id]);
}
}
<file_sep>/app/Http/Controllers/SearchController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Website;
class SearchController extends Controller
{
public function websites(Request $request)
{
$query = $request->input('q');
$websites = Website::where('active', '=', 1)
->where('name', 'like', '%' .$query . '%')
->orWhere('url', 'like', '%' .$query . '%')
->orWhere('description', 'like', '%' .$query . '%')
->paginate(10);
return view('search.main', compact('query', 'websites'));
}
}
<file_sep>/app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
use DB;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
/* Uncomment if you want to see SQL queries on website */
DB::listen(function ($query) {
// echo $query->sql . '<br />';
// $query->bindings
// echo $query->time . '<br />';
});
/* Custom validation rules */
Validator::extend('array_unique', function ($attribute, $value, $parameters, $validator) {
return count($value) == count(array_unique($value));
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
}
}
<file_sep>/app/Http/Requests/WebsiteRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\URL;
class WebsiteRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
/* Basic rules for all websites' requests */
$rules = [
'name' => 'required|min:3|max:150',
'description' => 'required|min:350|max:1500',
'subcategory_id' => 'required|exists:subcategories,id',
'tags' => 'required|array|min:1|max:6|array_unique',
'tags.*' => 'required|string|min:3|max:15',
];
if (URL::previous() !== route('website.create')) {
/* Return only basic rules if updating existing website */
return $rules;
} else {
/* In addition check website's url if stroing new one */
$rules['url'] = 'required|url|active_url|unique:websites,url|max:100';
return $rules;
}
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'tags.*.required' => 'Please refresh the website.',
'tags.*.string' => 'All tags must be strings.',
'tags.*.min' => 'All tags must contain at least :min characters.',
'tags.*.max' => 'All tags must contain maximum :max characters.',
'tags.array_unique' => 'All tags must be different.',
];
}
}
<file_sep>/app/Http/Controllers/PanelController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Website;
use App\WebsiteEdited;
use App\User;
class PanelController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$websites = Website::get();
$websites_trashed = Website::onlyTrashed()->get();
$websites_in_edit = WebsiteEdited::get();
$users = User::get();
return view('panel.welcome', compact('websites', 'websites_trashed', 'websites_in_edit', 'users'));
}
/**
* Show the user's websites (active, inactive and in edit)
*
* @return \Illuminate\Http\Response
*/
public function user_websites()
{
$websites = auth()->user()->websites();
return view('panel.user.websites', compact('websites'));
}
/**
* Show the waiting websites
*
* @return \Illuminate\Http\Response
*/
public function admin_websites_waiting()
{
$websites = Website::where('active', 0)->get();
return view('panel.admin.websites', compact('websites'));
}
/**
* Show the websites in edit
*
* @return \Illuminate\Http\Response
*/
public function admin_websites_edited()
{
$websites = WebsiteEdited::get();
return view('panel.admin.websites', compact('websites'));
}
/**
* Show the accepted websites
*
* @return \Illuminate\Http\Response
*/
public function admin_websites_accepted()
{
$websites = Website::where('active', 1)->get();
return view('panel.admin.websites', compact('websites'));
}
/**
* Show the deleted websites
*
* @return \Illuminate\Http\Response
*/
public function admin_websites_deleted()
{
$websites = Website::onlyTrashed()->get();
return view('panel.admin.websites', compact('websites'));
}
/**
* Show the deleted websites
*
* @return \Illuminate\Http\Response
*/
public function admin_users()
{
$users = User::where('role_id', '!=', 1)->get();
return view('panel.admin.users', compact('users'));
}
}
<file_sep>/app/Http/Controllers/WebsiteEditedController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\UpdateWebsiteRequest;
use App\Website;
use App\WebsiteEdited;
use App\Category;
use App\Tag;
class WebsiteEditedController extends Controller
{
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$website = WebsiteEdited::findOrFail($id);
$categories = Category::orderBy('name')->with('subcategories')->get();
return view('website.edited.edit', compact('website', 'categories'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(WebsiteRequest $request, $id)
{
/* Code if admin logged (merge changes) */
if(superuser() && $request->accept == 1) {
$website_request = WebsiteEdited::findOrFail($id);
$website = Website::findOrFail($website_request->website_id);
/* Update website's data */
$edit_success = $website->update([
'name' => $request->name,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
]);
/* Reload tags for website and delete request if update succeed */
if($edit_success) {
Tag::createTagsForWebsite($request->tags, $website, true);
$website_request->delete();
}
return redirect()->route('panel');
/* Code if user logged */
} else {
WebsiteEdited::findOrFail($id)->update([
'name' => $request->name,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
'tags' => json_encode($request->tags),
]);
}
if(superuser()) {
return redirect()->route('panel');
}
return redirect()->route('panel.user.websites');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$website = WebsiteEdited::findOrFail($id)->delete();
if(superuser()) {
return redirect()->route('panel');
}
return redirect()->route('panel.user.websites');
}
}
<file_sep>/app/Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Collection;
class Category extends Model
{
use SoftDeletes;
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['deleted_at'];
/**
* Returns all subcategories of given category
* @return \App\Subcategory
*/
public function subcategories()
{
return $this->hasMany('App\Subcategory')->orderBy('name');
}
/**
* Returns all websites that belongs to this category
* @return \App\Website
*/
public function websites()
{
return $this->hasManyThrough('App\Website', 'App\Subcategory')->where('active', '=', 1);
}
/**
* Generate sluggified viersion of name
* @return string
*/
public function getSlugAttribute(): string
{
return str_slug($this->name);
}
/**
* Generate friendly url
* @return string
*/
public function getFriendlyUrlAttribute(): string
{
return action('CategoryController@show', [$this->slug]);
}
}
<file_sep>/app/Utils/helpers.php
<?php
/**
* Returns true if authenticated is admin, false otherwise.
* @return bool
*/
function superuser()
{
return auth()->user()->role_id === 1;
}
| 3efe069b8da5e9f3c826f78e240b4e1bf0180564 | [
"Markdown",
"PHP"
] | 16 | Markdown | erte12/dropout | d3deac77a8cb3dfe4971f2d8ac630340d324df80 | 8255ccb2e7527493f07f6bca13cf08c9f8f69093 |
refs/heads/master | <repo_name>Nouw/HU-SP-Formatief<file_sep>/exporter/settings/database.py
from pymongo import MongoClient
from sqlalchemy import create_engine
from dotenv import load_dotenv
import os
def createConnectionMongoDB():
load_dotenv()
if os.getenv("DB_USE_AUTH") == 'True':
return MongoClient("mongodb://$[username]:$[password]@$[hostlist]/$[huwebs]?authSource=$[authSource]")
else:
return MongoClient(host=os.getenv("MONGODB_HOST"), port=int(os.getenv("MONGODB_PORT")))[
os.getenv("MONGODB_DATABASE")]
def createConnectionMysqlDB():
load_dotenv()
if os.getenv("SQLDB_USE_AUTHB") == 'True':
db_uri = 'mysql+pymysql://' + os.getenv('SQLDB_USERNAME') + ':'+ os.getenv('SQLDB_PASSWORD') + '@' + os.getenv('SQLDB_HOST') + '/' + os.getenv('SQLDB_DATABASE')
return create_engine(db_uri)
else:
db_uri = 'mysql+pymysql://' + os.getenv('SQLDB_USERNAME') + ':@' + os.getenv('SQLDB_HOST') + '/' + os.getenv('SQLDB_DATABASE')
return create_engine(db_uri)
# if os.getenv("SQLDB_USE_AUTH") == 'True':
# try:
# return mysql.connector.connect(
# host=os.getenv("SQLDB_HOST"),
# user=os.getenv("SQLDB_USERNAME"),
# passwd=os.getenv("<PASSWORD>"),
# database=os.getenv("SQLDB_DATABASE")
# )
# except:
# print('Cannot connect to database')
# return 0
# else:
# try:
# return mysql.connector.connect(
# host=os.getenv("SQLDB_HOST"),
# )
# except:
# print('Cannot connect to database')
# return 0
<file_sep>/exporter/alembic/versions/e0c36c50487a_rebuilding_tables.py
"""Rebuilding tables
Revision ID: e0c36c50487a
Revises: 30f233eab73b
Create Date: 2020-03-23 22:18:34.697414
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e0c36c50487a'
down_revision = '30f233eab73b'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('products',
sa.Column('id', sa.String(length=255), nullable=False),
sa.Column('name', sa.String(length=255), nullable=True),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('brand', sa.String(length=255), nullable=True),
sa.Column('price', sa.Integer(), nullable=True),
sa.Column('discount', sa.Integer(), nullable=True),
sa.Column('stock', sa.Integer(), nullable=True),
sa.Column('category', sa.String(length=255), nullable=True),
sa.Column('sub_category', sa.String(length=255), nullable=True),
sa.Column('sub_sub_category', sa.String(length=255), nullable=True),
sa.Column('sub_sub_sub_category', sa.String(length=255), nullable=True),
sa.Column('recommandable', sa.Boolean(), nullable=True),
sa.Column('online_only', sa.Boolean(), nullable=True),
sa.Column('target_demographic', sa.String(length=255), nullable=True),
sa.Column('gender', sa.String(length=90), nullable=True),
sa.Column('color', sa.String(length=100), nullable=True),
sa.Column('unit', sa.String(length=255), nullable=True),
sa.Column('odor_type', sa.String(length=255), nullable=True),
sa.Column('series', sa.String(length=255), nullable=True),
sa.Column('kind', sa.String(length=255), nullable=True),
sa.Column('variant', sa.String(length=255), nullable=True),
sa.Column('type', sa.String(length=255), nullable=True),
sa.Column('type_of_hair_care', sa.String(length=255), nullable=True),
sa.Column('type_of_hair_coloring', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('profiles',
sa.Column('id', sa.String(length=255), nullable=False),
sa.Column('first_order', sa.DateTime(), nullable=True),
sa.Column('latest_order', sa.DateTime(), nullable=True),
sa.Column('order_amount', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('sessions',
sa.Column('id', sa.String(length=255), nullable=False),
sa.Column('profile_id', sa.String(length=255), nullable=True),
sa.Column('session_start', sa.DateTime(), nullable=True),
sa.Column('session_end', sa.DateTime(), nullable=True),
sa.Column('browser_name', sa.String(length=255), nullable=True),
sa.Column('os_name', sa.String(length=255), nullable=True),
sa.Column('is_mobile_flag', sa.Boolean(), nullable=True),
sa.Column('is_pc_flag', sa.Boolean(), nullable=True),
sa.Column('is_tablet_flag', sa.Boolean(), nullable=True),
sa.Column('is_email_flag', sa.Boolean(), nullable=True),
sa.Column('device_family', sa.String(length=255), nullable=True),
sa.Column('device_brand', sa.String(length=255), nullable=True),
sa.Column('device_model', sa.String(length=255), nullable=True),
sa.ForeignKeyConstraint(['profile_id'], ['profiles.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('recommended_before',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('product_id', sa.String(length=255), nullable=True),
sa.Column('profile_id', sa.String(length=255), nullable=True),
sa.ForeignKeyConstraint(['product_id'], ['products.id'], ),
sa.ForeignKeyConstraint(['profile_id'], ['profiles.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('buids',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('session_id', sa.String(length=255), nullable=True),
sa.Column('profile_id', sa.String(length=255), nullable=True),
sa.ForeignKeyConstraint(['profile_id'], ['profiles.id'], ),
sa.ForeignKeyConstraint(['session_id'], ['sessions.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('orders',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('session_id', sa.String(length=255), nullable=True),
sa.ForeignKeyConstraint(['session_id'], ['sessions.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('orders_products',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('order_id', sa.Integer(), nullable=True),
sa.Column('product_Id', sa.String(length=255), nullable=True),
sa.Column('amount', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['order_id'], ['orders.id'], ),
sa.ForeignKeyConstraint(['product_Id'], ['products.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('orders_products')
op.drop_table('orders')
op.drop_table('buids')
op.drop_table('recommended_before')
op.drop_table('sessions')
op.drop_table('profiles')
op.drop_table('products')
# ### end Alembic commands ###
<file_sep>/exporter/migrations/create_orders_products_table.py
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from exporter.migrations.create_orders_table import Orders
from exporter.migrations.create_producten_table import Products
Base = declarative_base()
class OrdersProducts(Base):
__tablename__ = "orders_products"
id = Column(Integer(), primary_key=True)
order_id = Column(Integer, ForeignKey(Orders.id))
product_Id = Column(String(255), ForeignKey(Products.id))
amount = Column(Integer)
def __repr__(self):
return 'id: {}'.format(self.id)
<file_sep>/exporter/CSV/mongo_to_csv.py
import pymongo
import csv
# Creates the header for the csv with translation, for example translation={'_id': 'ID'},
# so that field name '_id' becomes 'ID' in the header
def create_header(field_names, translation=None) -> str:
if translation is None:
translation = dict()
header = ''
for i in range(len(field_names)):
if field_names[i] in translation.keys():
header = header + translation[field_names[i]]
elif field_names[i].split('/')[-1] in translation.keys():
header = header + translation[field_names[i].split('/')[-1]]
else:
header = header + field_names[i].split('/')[-1]
if i + 1 < len(field_names):
header = header + ', '
return header + '\n'
# Extracts the wanted fields (names/values) from a source dictionary that can have a tree like structure,
# Like a document with Array fields
def extract_fields(source, fields, parent='') -> dict:
extracted = {}
for field in fields:
if type(field) is not dict:
if field in source:
extracted[parent+str(field)] = source[field]
else:
print("Couldn't find (value) {}".format(field))
extracted[parent+str(field)] = None
else:
sub_source_key = tuple(field.keys())[0]
sub_fields = tuple(field.values())[0]
if sub_source_key in source:
sub = extract_fields(source[sub_source_key], sub_fields, parent=parent+str(sub_source_key)+'/')
extracted.update(sub)
else:
print("Couldn't find (Array/Object) {}".format(sub_source_key))
for sub_name in extract_fieldnames(sub_fields):
extracted[parent+str(sub_source_key)+'/'+sub_name] = None
return extracted
# Extract just the fieldnames from a tree structure
def extract_fieldnames(fields, parent='') -> list:
fieldnames = []
for field in fields:
if type(field) is not dict:
fieldnames.append(parent + str(field))
else:
fieldnames.extend(extract_fieldnames(tuple(field.values())[0], parent+str(tuple(field.keys())[0])+'/'))
return fieldnames
# Runs the export script and creates a csv file.
# Give the field names in <fields> like a list/tuple like: ['price', 'color']
# A field within a field can be done like this: ['price', {'prop': ['brand', 'unit']}, 'color']
# Translating multiple fields with the same name should be given like this:
# {'prop/unit': 'ProdID', 'cstm/unit': 'deviceID', 'color': 'Color'}
def execute_export(collection_name, fields, sample_size=None, translation=None,
export_name=None, db_name='huwebshop', mongo_ip='mongodb://localhost:27017/'):
if translation is None:
translation = dict()
# Setup connection to MongoDB
myclient = pymongo.MongoClient(mongo_ip)
db = myclient[db_name]
col = db[collection_name]
print("Connected to MongoDB...")
# Get the data from MongoDB
finds = col.find()
if sample_size is not None:
finds = finds[:sample_size]
print("Data received...")
# Write as csv file
field_names = extract_fieldnames(fields)
if export_name is None:
export_name = collection_name
filename = 'csvs/{}.csv'.format(export_name)
print("Writing to {}...".format(filename))
with open(filename, 'w') as file:
file.write(create_header(field_names, translation))
writer = csv.DictWriter(file, field_names)
i = 0
for document in finds:
row_dict = extract_fields(document, fields)
writer.writerow(row_dict)
i += 1
if i % 10000 == 0:
print("Written {} documents.".format(i))
print("Written {} documents.".format(i))
print("Done exporting.")
if __name__ == '__main__':
m_collection_name = 'sessions'
m_fields = ('_id', {'user_agent': [{'os': ['familiy', 'version_string']}]}, 'session_start', 'session_end')
m_sample_size = 100
execute_export(m_collection_name, m_fields, m_sample_size, export_name='Sessions')
<file_sep>/opdrachten/formatieve_opdracht_2A.py
from pymongo import MongoClient
from pprint import pprint
import re
client = MongoClient('localhost', 27017)
pprint(client.huwebshop.profiles.find_one())
regx = re.compile("^R")
pprint(client.huwebshop.products.find_one({"name": regx}))
products = client.huwebshop.products.find()
total_amount = 0
product_amount = 0
for product in products:
try:
total_amount += int(product['price']['mrsp'])
product_amount += 1
except KeyError as e:
print("price not found")
print(product_amount)
mean_price = total_amount / product_amount
print(f"mean price is: {mean_price/100} euro")
<file_sep>/exporter/alembic/versions/29f53ba709c5_testing_foreignkeys.py
"""Testing foreignkeys
Revision ID: 29f53ba709c5
Revises: <KEY>
Create Date: 2020-03-11 16:54:14.417819
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '29f53ba709c5'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/migrations/create_producten_table.py
from sqlalchemy import Column, Boolean, String, Integer, func, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Products(Base):
__tablename__ = 'products'
id = Column(String(255), primary_key=True)
name = Column(String(255))
description = Column(Text)
brand = Column(String(255))
price = Column(Integer())
discount = Column(Integer())
stock = Column(Integer())
category = Column(String(255))
sub_category = Column(String(255))
sub_sub_category = Column(String(255))
sub_sub_sub_category = Column(String(255))
recommandable = Column(Boolean())
online_only = Column(Boolean())
target_demographic = Column(String(255))
gender = Column(String(90)) # Change this to enum because only 3 genders (Man, Vrouw, Overig)
color = Column(String(100)) # Also change this to an enum because there are only 20 ish colors
unit = Column(String(255))
odor_type = Column(String(255))
series = Column(String(255))
kind = Column(String(255))
variant = Column(String(255))
type = Column(String(255))
type_of_hair_care = Column(String(255))
type_of_hair_coloring = Column(String(255))
def __repr__(self):
return 'id: {}'.format(self.id)
<file_sep>/exporter/SQLAlchemy/__init__.py
from exporter.migrations.create_producten_table import Producten
def __init__(self):
self.createProducten = Producten.__table__
def __del__(self):
self.con.close()
<file_sep>/exporter/setup/create_tables.py
import exporter.migrations as migration
print('Creating all tables')
migration.createTableProducten()
migration.createTableCategory()<file_sep>/exporter/migrations/create_recommended_before_table.py
from sqlalchemy import Column, Boolean, ForeignKey, Integer, func, String
from sqlalchemy.ext.declarative import declarative_base
from exporter.migrations.create_producten_table import Products
from exporter.migrations.create_profiles_table import Profiles
Base = declarative_base()
class RecommendedBefore(Base):
__tablename__ = "recommended_before"
id = Column(Integer(), primary_key=True)
product_id = Column(String(255), ForeignKey(Products.id))
profile_id = Column(String(255), ForeignKey(Profiles.id))
def __repr__(self):
return 'id: {}'.format(self.id)
<file_sep>/exporter/migrations/create_sessions_table.py
from sqlalchemy import Column, Boolean, String, Integer, ForeignKey, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from exporter.migrations.create_profiles_table import Profiles
Base = declarative_base()
class Sessions(Base):
__tablename__ = "sessions"
id = Column(String(255), primary_key=True)
# profile_id = Column(String(255), ForeignKey(Profiles.id))
session_start = Column(DateTime)
session_end = Column(DateTime)
browser_name = Column(String(255))
os_name = Column(String(255))
is_mobile_flag = Column(Boolean)
is_pc_flag = Column(Boolean)
is_tablet_flag = Column(Boolean)
is_email_flag = Column(Boolean)
device_family = Column(String(255))
device_brand = Column(String(255))
device_model = Column(String(255))
def __repr__(self):
return 'id: {}'.format(self.id)
<file_sep>/exporter/migrations/create_profiles_table.py
from sqlalchemy import Column, Boolean, String, Integer, func, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
# from exporter.migrations.create_buids_table import Buids
Base = declarative_base()
class Profiles(Base):
__tablename__ = "profiles"
id = Column(String(255), primary_key=True)
first_order = Column(DateTime)
latest_order = Column(DateTime)
order_amount = Column(Integer)
# buid = relationship(Buids)
def __repr__(self):
return 'id: {}'.format(self.id)
<file_sep>/exporter/main.py
# from exporter.settings import createConnectionMysqlDB, createConnectionMongoDB
# database = createConnectionMongoDB()
#
# table = database.products
#
# print(table)<file_sep>/exporter/alembic/versions/d83bff3b2437_added_sessions_and_profiles.py
"""Added Sessions and Profiles
Revision ID: d83bff3b2437
Revises: <PASSWORD>
Create Date: 2020-03-10 13:55:58.521255
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/README.md
# HU-SP-Formatiefw
Om alles goed op te zetten run de `exporter/setup/setup.sh`
# Installatie
Run `exporter/setup/setup.sh`
Voeg je database login etc to aan `exporter/.env`
Vul daarna sqlalchemy.url in: `exporter/alembic.ini`
voorbeeld van een sqlalchemy.url: `driver://user:pass@localhost/dbname`
Ga daarna naar `exporter/` en doe de volgende commands:
Deze command zorgt ervoor dat de kollomen worden gemaakt
`alembic revision -m "Start script"`
Deze command zorgt ervoor dat de veranderingen worden gepusht naar de database
`alembic upgrade head`
Daarna is je database klaar
# Vragen aan Nick
Hoe kan ik env variables gebruiken in .ini bestanden?
## Notes
Misschien hier even naar kijken om de data van MongoDB naar MySQL te zetten: https://docs.sqlalchemy.org/en/13/orm/tutorial.html
Command om de database te updaten
`alembic revision --autogenerate -m "message'`
##Hoe werkt alembic?
Maak een baseline document aan met alle tabellen die je wilt toevoegen aan het begin.
Daarna kan je models maken in `exporter/migrations/`<file_sep>/exporter/migrations/__init__.py
# from .create_producten_table import createTableProducten
# from .create_producten_table import createTableCategory
#
#
# def __init__(self):
# self.createProducten = createTableProducten()
# self.createCategories = createTableCategory()
<file_sep>/exporter/migrations/create_orders_table.py
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from exporter.migrations.create_sessions_table import Sessions
from exporter.migrations.create_producten_table import Products
Base = declarative_base()
class Orders(Base):
__tablename__ = "orders"
id = Column(Integer(), primary_key=True)
session_id = Column(String(255), ForeignKey(Sessions.id))
product_id = Column(String(255), ForeignKey(Products.id))
def __repr__(self):
return 'id: {}'.format(self.id)
<file_sep>/exporter/alembic/versions/4b4d8bd014eb_added_test_col.py
"""added test col
Revision ID: 4b4d8bd014eb
Revises: <PASSWORD>
Create Date: 2020-03-05 22:03:34.252998
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '4b4d8bd014eb'
down_revision = 'b2516d<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('bug',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('bug_tracker_url', sa.String(length=255), nullable=True),
sa.Column('root_cause', sa.String(length=255), nullable=True),
sa.Column('who', sa.String(length=255), nullable=True),
sa.Column('when', sa.DateTime(), nullable=True),
sa.Column('test', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('bug_tracker_url')
)
op.add_column('products', sa.Column('recommandable', sa.Boolean(), nullable=True))
op.add_column('products', sa.Column('sub_sub_sub_category', sa.String(length=255), nullable=True))
op.add_column('products', sa.Column('test', sa.Integer(), nullable=True))
op.drop_column('products', 'recommendable')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('products', sa.Column('recommendable', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True))
op.drop_column('products', 'test')
op.drop_column('products', 'sub_sub_sub_category')
op.drop_column('products', 'recommandable')
op.drop_table('bug')
# ### end Alembic commands ###
<file_sep>/exporter/alembic/versions/3a3d2a89b7fe_added_products_foreign_to_orders.py
"""Added products foreign to orders
Revision ID: 3a3d2a89b7fe
Revises: e0c36c50487a
Create Date: 2020-03-23 22:19:36.608220
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3a3d2a89b7fe'
down_revision = 'e0c36c50487a'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('orders', sa.Column('product_id', sa.String(length=255), nullable=True))
op.create_foreign_key(None, 'orders', 'products', ['product_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'orders', type_='foreignkey')
op.drop_column('orders', 'product_id')
# ### end Alembic commands ###
<file_sep>/exporter/alembic/versions/eb8abdb792df_forgot_type_with_foreign_key.py
"""Forgot type with foreign key
Revision ID: <KEY>
Revises: e<PASSWORD>
Create Date: 2020-03-23 20:59:15.250552
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = 'e<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/SQLAlchemy/test.py
import sqlalchemy
from .SQLAlchemy.producten_table import Product
engine = sqlalchemy.create_engine("mysql+pymysql://root:@localhost/huwebshop")
<file_sep>/exporter/alembic/versions/ae215961a21a_.py
"""empty message
Revision ID: <KEY>
Revises: 7734dd38ef4b
Create Date: 2020-03-23 21:22:38.276802
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '7734dd38ef4b'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/alembic/versions/0a0b464533e1_added_foreign_key.py
"""Added foreign key
Revision ID: 0a0b464533e1
Revises: <KEY>
Create Date: 2020-03-23 20:53:00.180250
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '0a0b464533e1'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/alembic/versions/789ca0ce06ee_added_foreign_keys_to_recommended_before.py
"""Added foreign keys to recommended_before
Revision ID: 789ca0ce06ee
Revises: <KEY>
Create Date: 2020-03-11 19:11:06.795850
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '789ca0ce06ee'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('recommended_before', sa.Column('product_id', sa.Integer(), nullable=True))
op.add_column('recommended_before', sa.Column('profile_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'recommended_before', 'products', ['product_id'], ['id_pk'])
op.create_foreign_key(None, 'recommended_before', 'profiles', ['profile_id'], ['id_pk'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'recommended_before', type_='foreignkey')
op.drop_constraint(None, 'recommended_before', type_='foreignkey')
op.drop_column('recommended_before', 'profile_id')
op.drop_column('recommended_before', 'product_id')
# ### end Alembic commands ###
<file_sep>/exporter/alembic/versions/1040843763a0_testing_foreignkeys.py
"""Testing foreignkeys
Revision ID: 1040843763a0
Revises: 29f53ba709c5
Create Date: 2020-03-11 16:55:24.257378
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1040843763a0'
down_revision = '29f53ba709c5'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/alembic/versions/2d1a65725662_added_profiles_and_sessions.py
"""Added profiles and sessions
Revision ID: 2d1a65725662
Revises: <PASSWORD>
Create Date: 2020-03-10 14:00:52.586147
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d1a65725662'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/migrations/create_buids_table.py
from sqlalchemy import Column, Boolean, ForeignKey, Integer, func, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from exporter.migrations.create_sessions_table import Sessions
from exporter.migrations.create_profiles_table import Profiles
Base = declarative_base()
class Buids(Base):
__tablename__ = "buids"
id = Column(Integer(), primary_key=True)
session_id = Column(String(255), ForeignKey(Sessions.id))
profile_id = Column(String(255), ForeignKey(Profiles.id))
def __repr__(self):
return 'id: {}'.format(self.id)
<file_sep>/exporter/alembic/versions/2b8f48c92f86_removed_profiles_from_sessions.py
"""Removed profiles from sessions
Revision ID: 2b8f48c92f86
Revises: <PASSWORD>
Create Date: 2020-03-23 22:21:33.169930
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '2b8f48c<PASSWORD>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('sessions_ibfk_1', 'sessions', type_='foreignkey')
op.drop_column('sessions', 'profile_id')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('sessions', sa.Column('profile_id', mysql.VARCHAR(length=255), nullable=True))
op.create_foreign_key('sessions_ibfk_1', 'sessions', 'profiles', ['profile_id'], ['id'])
# ### end Alembic commands ###
<file_sep>/exporter/alembic/versions/8c49969fa6bf_testing_foreignkeys.py
"""Testing foreignkeys
Revision ID: <KEY>
Revises: <KEY>
Create Date: 2020-03-11 19:07:55.544645
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('buids', sa.Column('profile_id', sa.Integer(), nullable=True))
op.add_column('buids', sa.Column('session_id', sa.Integer(), nullable=True))
op.drop_constraint('buids_ibfk_1', 'buids', type_='foreignkey')
op.create_foreign_key(None, 'buids', 'profiles', ['profile_id'], ['id_pk'])
op.create_foreign_key(None, 'buids', 'sessions', ['session_id'], ['id_pk'])
op.drop_column('buids', 'parent_id')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('buids', sa.Column('parent_id', mysql.INTEGER(), autoincrement=False, nullable=True))
op.drop_constraint(None, 'buids', type_='foreignkey')
op.drop_constraint(None, 'buids', type_='foreignkey')
op.create_foreign_key('buids_ibfk_1', 'buids', 'sessions', ['parent_id'], ['id_pk'])
op.drop_column('buids', 'session_id')
op.drop_column('buids', 'profile_id')
# ### end Alembic commands ###
<file_sep>/exporter/setup/SQLSetup.py
# # from settings.database import createConnectionMysqlDB
# # from ..settings.database import createConnectionMysql
# from ..settings
# mycursor = createConnectionMysqlDB().cursor()
#
# # delete database if database exists
# mycursor.execute("DROP DATABASE IF EXISTS huwebshop")
# # Create database
# mycursor.execute("CREATE DATABASE huwebshop")
# from exporter.settings.database import createConnectionMysqlDB
import exporter.settings.database as mysql
engine = mysql.createConnectionMysqlDB().connect()
engine.execute("CREATE DATABASE test")
engine.close()
# print(mysql.createConnectionMysqlDB())
import time
# engine = createConnectionMysqlDB
# print(createConnectionMysqlDB)
# con = createConnectionMysqlDB
# time.sleep(.20)
# # print(con)
# mycursor = con.cursor()
# # Delete database if exists
# mycursor.execute("DROP DATABASE IF EXISTS huwebshop")
# # Create database
# mycursor.execute("CREATE DATABASE huwebshop")
<file_sep>/exporter/alembic/versions/14dfbf74ef8f_added_profiles_and_sessions.py
"""Added profiles and sessions
Revision ID: 1<PASSWORD>
Revises: <PASSWORD>
Create Date: 2020-03-10 13:58:58.976136
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<PASSWORD>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/setup/setup.sh
# Installs the database packages
python -m pip install mysql-connector
python -m pip install pymongo
python -m pip install mysqlclient
python -m pip install alembic<file_sep>/exporter/alembic/versions/7734dd38ef4b_regenerate_tables.py
"""Regenerate tables
Revision ID: 7734dd38ef4b
Revises: <PASSWORD>
Create Date: 2020-03-23 21:22:00.201558
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7734dd38ef4b'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/alembic/versions/07ec4a9da27a_added_profiles_and_sessions.py
"""Added profiles and sessions
Revision ID: 07ec4a9da27a
Revises: d<PASSWORD>
Create Date: 2020-03-10 13:58:19.166705
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '07ec4a9da27a'
down_revision = '<KEY>437'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/alembic/versions/e3623d986607_forgot_type_with_foreign_key.py
"""Forgot type with foreign key
Revision ID: e3623d986607
Revises: 0a0b464533e1
Create Date: 2020-03-23 20:55:52.634488
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e3623d986607'
down_revision = '0a0b464533e1'
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
<file_sep>/exporter/alembic/versions/b2516d1fb564_baseline_migration.py
"""Baseline migration
Revision ID: b2516d1fb564
Revises:
Create Date: 2020-03-05 21:52:02.292390
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'products',
sa.Column('id_pk', sa.Integer, primary_key=True),
sa.Column('name', sa.String(255)),
sa.Column('description', sa.Text),
sa.Column('brand', sa.String(255)),
sa.Column('price', sa.Integer),
sa.Column('discount', sa.Integer),
sa.Column('stock', sa.Integer),
sa.Column('category', sa.String(255)),
sa.Column('sub_category', sa.String(255)),
sa.Column('sub_sub_category', sa.String(255)),
sa.Column('recommendable', sa.Boolean),
sa.Column('online_only', sa.Boolean),
sa.Column('target_demographic', sa.String(255)),
sa.Column('gender', sa.String(90)), # TODO: Hier nog een set van maken
sa.Column('color', sa.String(100)), # TODO: Hier nog een set van maken
sa.Column('unit', sa.String(255)),
sa.Column('odor_type', sa.String(255)),
sa.Column('series', sa.String(255)),
sa.Column('kind', sa.String(255)),
sa.Column('variant', sa.String(255)),
sa.Column('type', sa.String(255)),
sa.Column('type_of_hair_care', sa.String(255)),
sa.Column('type_of_hair_coloring', sa.String(255)), # TODO: Hier nog een set van maken
)
def downgrade():
op.drop_table('bug')
<file_sep>/exporter/alembic/versions/6a9001e0b9a2_added_profiles_and_sessions.py
"""Added profiles and sessions
Revision ID: 6a9001e0b9a2
Revises: 2<PASSWORD>
Create Date: 2020-03-10 14:03:05.328962
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '2d1a6572<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('profiles',
sa.Column('id_pk', sa.Integer(), nullable=False),
sa.Column('id', sa.String(length=255), nullable=True),
sa.Column('first_order', sa.DateTime(), nullable=True),
sa.Column('latest_order', sa.DateTime(), nullable=True),
sa.Column('order_amount', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id_pk')
)
op.create_table('sessions',
sa.Column('id_pk', sa.Integer(), nullable=False),
sa.Column('id', sa.String(length=255), nullable=True),
sa.Column('session_start', sa.DateTime(), nullable=True),
sa.Column('session_end', sa.DateTime(), nullable=True),
sa.Column('browser_name', sa.String(length=255), nullable=True),
sa.Column('os_name', sa.String(length=255), nullable=True),
sa.Column('is_mobile_flag', sa.Boolean(), nullable=True),
sa.Column('is_pc_flag', sa.Boolean(), nullable=True),
sa.Column('is_tablet_flag', sa.Boolean(), nullable=True),
sa.Column('is_email_flag', sa.Boolean(), nullable=True),
sa.Column('device_family', sa.String(length=255), nullable=True),
sa.Column('device_brand', sa.String(length=255), nullable=True),
sa.Column('device_model', sa.String(length=255), nullable=True),
sa.PrimaryKeyConstraint('id_pk')
)
op.drop_index('bug_tracker_url', table_name='bug')
op.drop_table('bug')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('bug',
sa.Column('id', mysql.INTEGER(), autoincrement=True, nullable=False),
sa.Column('bug_tracker_url', mysql.VARCHAR(length=255), nullable=True),
sa.Column('root_cause', mysql.VARCHAR(length=255), nullable=True),
sa.Column('who', mysql.VARCHAR(length=255), nullable=True),
sa.Column('when', mysql.DATETIME(), nullable=True),
sa.Column('test', mysql.INTEGER(), autoincrement=False, nullable=True),
sa.PrimaryKeyConstraint('id'),
mysql_collate='utf8mb4_0900_ai_ci',
mysql_default_charset='utf8mb4',
mysql_engine='InnoDB'
)
op.create_index('bug_tracker_url', 'bug', ['bug_tracker_url'], unique=True)
op.drop_table('sessions')
op.drop_table('profiles')
# ### end Alembic commands ###
| a2ddd49ed09585dc71d39097a5e8de15b7479035 | [
"Markdown",
"Python",
"Shell"
] | 37 | Python | Nouw/HU-SP-Formatief | 6a44570b17a4e67e894fd9114f15642e3c3a67f9 | d7a0a5edc67e7df49e1b58ecc669b8d0a1fa1cdb |
refs/heads/master | <file_sep>import json
from flask import Flask, render_template
from flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
CATEGORIES = [
{'name':'food', 'limit':700},
{'name':'rent', 'limit':1000},
{'name':'gas', 'limit':150}
]
PURCHASES = []
parser = reqparse.RequestParser()
parser.add_argument('name')
parser.add_argument('limit')
parser.add_argument('amount')
parser.add_argument('date')
parser.add_argument('what')
parser.add_argument('category')
@app.route("/")
def root_page():
return render_template("base.html")
class CategoryList(Resource):
def get(self):
return CATEGORIES, 200
def post(self):
#TODO: finish
args = parser.parse_args()
print("args")
print(args)
exist = False
for cat in CATEGORIES:
if cat['name'] == args.name:
exist = True
return 'Category already exists', 200
if not exist:
CATEGORIES.append({'name':args.name, 'limit': float(args.limit)})
print(CATEGORIES)
return 'Added category: ' + args.name, 200
return 'Something went wrong', 500
class Category(Resource):
def delete(self, cat_name):
print("deleting")
print(cat_name)
for cat in CATEGORIES:
if cat['name'] == cat_name:
CATEGORIES.remove(cat)
print(CATEGORIES)
return 'Successfully deleted category: ' + cat_name, 200
return 'Something went wrong', 500
class PurchaseList(Resource):
def get(self):
return PURCHASES, 200
def put(self):
#TODO: finish
args = parser.parse_args()
PURCHASES.append({'amount':args.amount, 'date':args.date, 'what':args.what, 'category': args.category})
print("purchases")
print(PURCHASES)
return 'Added new purchase: ' + args.what, 200
api.add_resource(CategoryList, '/cats')
api.add_resource(Category, '/cats/<cat_name>')
api.add_resource(PurchaseList, '/purchases')
if __name__ == '__main__':
app.run(debug=true)
| d6e076771e456eb912d37a542309483f3872de8c | [
"Python"
] | 1 | Python | BiyingZhang/school_project_04 | a49664139f6f9ea3a3506ff4c53c729386667834 | 3235df8d57e01e75608dc0a1650dc21494da4e85 |
refs/heads/master | <file_sep>import express from 'express';
import passport from 'passport';
import picController from './pic.controller';
import isAdmin from '../../middlewares/is-admin';
const adminPolicy = [passport.authenticate('jwt', { session: false }), isAdmin];
const picRouter = express.Router();
picRouter
.route('/')
.post(adminPolicy, picController.create)
.get(picController.findAll);
picRouter
.route('/:id')
.get(picController.findOne)
.delete(adminPolicy, picController.delete)
.put(adminPolicy, picController.update);
export default picRouter;
<file_sep>import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import PropTypes from 'prop-types';
import css from './username-password.scss';
import { setUsernamePassword } from './username-password-actions';
const UsernamePassword = ({ env }) => {
const dispatch = useDispatch();
const { usernamePasswordReducer } = useSelector(state => state);
const inputHandler = (value, inputType) => {
dispatch(setUsernamePassword({ env, value, inputType }));
};
return (
<div className={css['username-password']}>
<input
className={css.text}
type="text"
placeholder="username"
onChange={evt => inputHandler(evt.target.value, 'username')}
value={usernamePasswordReducer[env].username}
/>
<input
className={css.password}
type="password"
placeholder="<PASSWORD>"
onChange={evt => inputHandler(evt.target.value, '<PASSWORD>')}
value={usernamePasswordReducer[env].password}
/>
</div>
);
};
UsernamePassword.propTypes = {
env: PropTypes.string
};
export default UsernamePassword;
<file_sep>const devConfig = {
secret: 'I_AME_GERER'
};
export default devConfig;
<file_sep>import _ from 'lodash';
import {
DEMO_AUTH_TOKEN_ACQUIRED,
QA_AUTH_TOKEN_ACQUIRED,
PROD_AUTH_TOKEN_ACQUIRED,
CURRENT_FROM_ENV_SET,
QA_ENV
} from './migrate-actions';
export const initialState = {
authTokenDemo: null,
authTokenQa: null,
authTokenProd: null,
currentFromEnv: QA_ENV,
girlIds: []
};
export default (state = initialState, action) => {
switch (action.type) {
case DEMO_AUTH_TOKEN_ACQUIRED: {
return state;
}
case QA_AUTH_TOKEN_ACQUIRED: {
return state;
}
case PROD_AUTH_TOKEN_ACQUIRED: {
return state;
}
case CURRENT_FROM_ENV_SET: {
const cloned = _.clone(state);
cloned.currentFromEnv = action.env;
return cloned;
}
default:
return state;
}
};
<file_sep>import { combineReducers } from 'redux';
import migrateReducer from '../migrate/migrate-reducer';
import usernamePasswordReducer from '../username-password/username-password-reducer';
const ReloadCombinedReducers = combineReducers({
migrateReducer,
usernamePasswordReducer
});
export default ReloadCombinedReducers;
<file_sep>import React, { useEffect, Fragment } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
acquireAuthToken, setCurrentFromEnv, DEMO_ENV, QA_ENV, PROD_ENV
} from './migrate-actions';
import UsernamePassword from '../username-password/username-password';
const Links = () => {
const dispatch = useDispatch();
const { migrateReducer } = useSelector(state => state);
useEffect(() => {}, []);
const envHandler = (evt) => {
dispatch(setCurrentFromEnv(evt.target.value));
};
return (
<Fragment>
<UsernamePassword env={DEMO_ENV} />
<select
onChange={envHandler}
>
<option value={QA_ENV}>QA</option>
<option value={PROD_ENV}>Prod</option>
</select>
<UsernamePassword env={migrateReducer.currentFromEnv} />
</Fragment>
);
};
export default Links;
<file_sep>/* eslint-disable no-console */
import axios from 'axios';
export const DEMO_AUTH_TOKEN_ACQUIRED = 'DEMO_AUTH_TOKEN_ACQUIRED';
export const QA_AUTH_TOKEN_ACQUIRED = 'QA_AUTH_TOKEN_ACQUIRED';
export const PROD_AUTH_TOKEN_ACQUIRED = 'PROD_AUTH_TOKEN_ACQUIRED';
export const CURRENT_FROM_ENV_SET = 'CURRENT_FROM_ENV_SET';
export const DEMO_AUTH = 'https://identity-gateway.3plearning.com/AuthenticationGatewayV1/api/sessions';
export const QA_AUTH = 'https://gateway-qa.3plearning.com/AuthenticationGatewayV1/api/sessions';
export const PROD_AUTH = 'https://identity-gateway.3plearning.com/AuthenticationGatewayV1/api/sessions';
export const DEMO_ENV = 'demo';
export const QA_ENV = 'qa';
export const PROD_ENV = 'prod';
export const acquireAuthToken = (url, type) => async (dispatch) => {
try {
const response = await axios.post(url, {
username,
password,
productId: 0
});
if (response.data) {
dispatch({
type,
authToken: response.data.token
});
} else {
console.log('error');
}
} catch (err) {
console.log(err);
}
};
export const setCurrentFromEnv = env => ({
type: CURRENT_FROM_ENV_SET,
env
});
<file_sep>export const USERNAME_PASSWORD_SET = './USERNAME_PASSWORD_SET';
export const setUsernamePassword = ({ env, value, inputType }) => ({
type: USERNAME_PASSWORD_SET,
payload: {
env,
value,
inputType
}
});
<file_sep>/* global window document */
import React from 'react';
import ReactDom from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { BrowserRouter as Router /* , Route */} from 'react-router-dom';
import ReloadCombinedReducers from './reload-combined-reducers';
import { handleDefaults } from '../helpers/utils';
import Migrate from '../migrate/migrate';
import './core.scss';
// import Socket from '../helpers/socket';
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
export default class EntryApp {
constructor(element, dynamicOptions) {
const defaults = {};
this.element = element;
this.options = handleDefaults(defaults, dynamicOptions);
this.renderElm();
}
renderElm() {
const store = createStoreWithMiddleware(
ReloadCombinedReducers,
window.devToolsExtension ? window.devToolsExtension() : f => f
);
ReactDom.render(
<Provider store={store}>
<Router>
<div>
<Migrate />
</div>
</Router>
</Provider>,
document.querySelector(this.element)
);
}
}
window.EntryApp = EntryApp;
<file_sep>import mongoose from 'mongoose';
import mongoosePaginate from 'mongoose-paginate';
const { Schema } = mongoose;
const picSchema = new Schema({
title: {
type: String,
required: [true, 'Pic must have title']
},
url: {
type: String,
required: [true, 'Pic must have url']
},
blurb: {
type: String
},
price: {
type: Number
},
limit: {
type: Number
}
});
picSchema.plugin(mongoosePaginate);
export default mongoose.model('Pic', picSchema);
<file_sep>import express from 'express';
import picRouter from './resources/pic/pic.router';
import userRouter from './resources/user/user.router';
const restRouter = express.Router();
restRouter.use('/pics', picRouter);
restRouter.use('/users', userRouter);
export default restRouter;
| 04f9b6a11f82ffec029d6aa6512d69bb841645a7 | [
"JavaScript"
] | 11 | JavaScript | roger-cm-ng/demo-populate-psr | f55cfeec04f1bb5145afdc03f36e5cfd2b1583db | 7cfed652390286f7578ad3bae107423a4e63dfb3 |
refs/heads/master | <repo_name>pujakumari19/lwgit-ws<file_sep>/prg.py
print('he')
print(second')
print('third')
| e62a6e3714208520d4ae945040a0ae57ff0b0b26 | [
"Python"
] | 1 | Python | pujakumari19/lwgit-ws | b1e466a01ed98bd099610152496c9b10fe39bee3 | eb98122102543f03d4e96a083298ce4dd331e201 |
refs/heads/master | <repo_name>reddyist/python-remote-dispatcher<file_sep>/rdispatcher/__init__.py
"""Dummy file for packaging"""
from rdispatcher import *
<file_sep>/setup.py
#!/usr/bin/python -tt
# vim: sw=4 ts=4 expandtab ai fileencoding=utf-8
#
# Copyright (C) 2006-2007 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# $ID$
__revision__ = "r"+"$Revision$"[11:-2]
from distutils.core import setup
import glob, os
def debpkgver(changelog = "debian/changelog"):
return open(changelog).readline().split(' ')[1][1:-1]
setup (name = "python-remote-dispatcher",
description="remote copy and execute commands",
version=debpkgver(),
author="<NAME>",
author_email="<EMAIL>",
packages=['rdispatcher',],
license="GPL",
long_description="Interface for remote authentication, copying and executing commands"
)
# EOF
<file_sep>/rdispatcher/rdispatcher.py
#!/usr/bin/python -tt
# vim: sw=4 ts=4 expandtab ai
#
# Copyright (C) 2008 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# $Id$
"""Provides secure copy and command execution on a remote system"""
__all__ = ['RemoteDispatcherException', 'RemoteDispatcher',
'SFTPClient']
__revision__ = "r"+"$Revision$"
from os import environ as local_environ
from os import walk as local_walk
from os.path import join as joinpath
from os.path import sep as pathsep
from os.path import expanduser as local_expanduser
from os.path import normpath as local_normpath
from os.path import basename as local_basename
from os.path import getsize as local_getsize
from os.path import dirname as local_dirname
from os.path import isfile as local_isfile
from os.path import isdir as local_isdir
from os.path import exists as local_pathexists
import glob
import stat
import paramiko
from collections import deque
import logging
LOG = logging.getLogger(__name__)
class RemoteDispatcherException(Exception):
""" Encapsulates sftp exceptions """
pass
class SFTPClient(paramiko.SFTPClient):
"""Extends the paramiko.SFTPClient to provide methods: exists and isdir"""
def exists(self, name):
"""Check whether name (file name or directory name) exists on remote
server.
Arguments:
name (str) - absolute path to a file or directory name
Returns:
If name exists then True or False
"""
try:
self.stat(name)
return True
except IOError:
return False
else:
msg = "Error checking file status for %s on remote host" % (name)
raise RemoteDispatcherException(msg)
def isdir(self, name):
"""Return True if name is an existing directory
Arguments:
name (str) - absolute path to a directory name
Returns:
True if exists else False
"""
isdir = False
if not self.exists(name):
return isdir
try:
mode = self.lstat(name).st_mode
except OSError:
mode = 0
if stat.S_ISDIR(mode):
isdir = True
else:
isdir = False
return isdir
class RemoteDispatcher(object):
"""Provides an interface for secure copy and command execution on a remote
system. At object instantiation it performs authentication, creates
transport object which can used in establishing a session with server. A
single session b/w local and remote system can be used in multiple channels
i.e multiple copies or command execution."""
def __init__(self, host, port=22, username=None, password=None, pkey=None):
""" Creates a new SSH transport object which can be used in starting a
session with remote server. The authentication is done based on password
or private_key.
Arguments:
host (str) - host name or ip
port (int) - (optional) defaults to 22
username (str) - (optional) defaults to command execution username
password (str) - (optional) defaults to private_key
pkey (str) - (optional) private key defaults to ~/.ssh/id_rsa key
Actions:
* Creates SSH transport object
* Authenticates remotes based on username and private_key|password
"""
self.host = host
self.port = port
self.username = username or local_environ['LOGNAME']
self.password = <PASSWORD>
self.pkey = None
self.transport = None
self.sftp_live = False
self.sftp = None
# Set to info level
LOG.setLevel(20)
if pkey:
pkey_file = local_expanduser(pkey)
else:
pkey_file = self.__get_privatekey_file()
if not password and not pkey_file:
raise RemoteDispatcherException(\
"You have not specified a password or key.")
if pkey_file:
self.__load_private_key(pkey_file)
self.__establish_session()
def __get_privatekey_file(self):
"""Returns user private key"""
pkey_file = None
rsa_key_file = local_expanduser('~%s/.ssh/id_rsa' \
% self.username)
dsa_key_file = local_expanduser('~%s/.ssh/id_dsa' \
% self.username)
if local_pathexists(rsa_key_file):
pkey_file = rsa_key_file
elif local_pathexists(dsa_key_file):
pkey_file = dsa_key_file
return pkey_file
def __load_private_key(self, pkey_file):
"""Loads the key from key file"""
try:
pkey = paramiko.RSAKey.from_private_key_file(pkey_file)
except paramiko.SSHException:
try:
pkey = paramiko.DSSKey.from_private_key_file(pkey_file)
except paramiko.SSHException:
raise RemoteDispatcherException("Invalid private key file: %s"\
% pkey_file)
self.pkey = pkey
def __establish_session(self):
"""Session will be established b/w local and remote machine"""
if not self.transport or not self.transport.is_active():
self.transport = paramiko.Transport((self.host, self.port))
self.transport.connect(username=self.username,
password=<PASSWORD>,
pkey=self.pkey)
def connect(self):
"""Establish the SFTP connection."""
if not self.transport.is_active():
self.close()
self.__establish_session()
if not self.sftp_live:
self.sftp = SFTPClient.from_transport(self.transport)
self.sftp_live = True
def __construct_remote_paths(self, source, root_dest, remote_directories,
local_remote_files):
"""Computes the directories and files that are to uploaded to remote
system.
Arguments:
source (str) - absolute path to the local source directory
root_dest (str) - absolute path to the remote destination directory
remote_directories (list) - list reference where the directories
which has to created will be added
local_remote_files (list) - list reference where a tuples of
(localfile_path, remotefile_path)
will be added
root_dest_exists (boolean) - defaults to False; Set to True if dest
exists at remote side
Returns:
The return values are append to the reference variables
i.e remote_directories and local_remote_files list
"""
if local_isfile(source):
root_dest = joinpath(root_dest, local_basename(source))
local_remote_files.append((source, root_dest))
return
parent_dest_exists = root_dest_exists = False
parent_path = root_dest
if self.sftp.isdir(root_dest):
parent_dest_exists = root_dest_exists = True
for base_dir, _, files in local_walk(source):
dest_dir = local_normpath(joinpath(root_dest,
base_dir.replace(source, '').strip(pathsep)))
if root_dest_exists:
new_parent_path = local_dirname(base_dir)
if new_parent_path == parent_path and not parent_dest_exists:
remote_directories.append(dest_dir)
else:
parent_path = new_parent_path
if not self.sftp.exists(dest_dir):
parent_dest_exists = False
remote_directories.append(dest_dir)
elif not self.sftp.isdir(dest_dir):
msg = ''.join(["Copy aborted. Mismatch in file type ",
"Local: '%s' Remote: '%s'" % (base_dir,
dest_dir)])
raise RemoteDispatcherException(msg)
else:
parent_dest_exists = True
else:
remote_directories.append(local_normpath(dest_dir))
local_remote_files.extend(\
[(joinpath(base_dir, fname), \
joinpath(dest_dir, fname)) \
for fname in files])
def __get_paths_source_file(self, source, dest):
"""Costructs the the remote directories and files to be created
Arguments:
source - local source file path
dest - remote destionation path
Returns:
Tuple ([dir1, dir2, ...],
[(local_file_path1, remote_file_path1),
(local_file_path1, remote_file_path2), ...])
"""
remote_directories = deque()
local_remote_files = deque()
if self.sftp.isdir(dest):
dest = joinpath(dest, local_basename(source))
local_remote_files.append((source, dest))
return (remote_directories, local_remote_files)
def __get_paths_source_dir(self, source, dest):
"""Costructs the the remote directories and files to be created
Arguments:
source - local source directory path
dest - remote destionation path
Returns:
Tuple ([dir1, dir2, ...],
[(local_file_path1, remote_file_path1),
(local_file_path1, remote_file_path2), ...])
"""
remote_directories = deque()
local_remote_files = deque()
if self.sftp.isdir(dest):
dest = joinpath(dest, local_basename(source))
self.__construct_remote_paths(source, dest, remote_directories,
local_remote_files)
return (remote_directories, local_remote_files)
def __get_paths_source_pattern(self, source, dest):
"""Costructs the the remote directories and files to be created
Arguments:
source - local source pattern
dest - remote destionation path
Returns:
Tuple ([dir1, dir2, ...],
[(local_file_path1, remote_file_path1),
(local_file_path1, remote_file_path2), ...])
"""
remote_directories = deque()
local_remote_files = deque()
root_dest = dest
# Get pattern matching files and directories
source_list = glob.glob(source)
if not source_list:
raise RemoteDispatcherException("File or Directory not found: %s"
% (source))
if not self.sftp.isdir(root_dest):
remote_directories.append(root_dest)
for lfile in source_list:
# IF lfile is a directory then concatenated the dir-name with
# remote path.
if local_isdir(lfile):
dest = joinpath(root_dest, local_basename(lfile))
else:
dest = root_dest
self.__construct_remote_paths(lfile, dest, remote_directories,
local_remote_files)
return (remote_directories, local_remote_files)
def scp(self, source, dest, recursive=False):
"""Copies a file[s] or directories between the local and remote host
Arguments:
source (str) - absolute path to the source file or directory
or a pattern
dest (str) - remote absolute path
recursive (boolean) - for copying recursively; should be enabled
in case of directory or more than 2 files
i.e pattern matched to be copied
Actions:
* Get list of directories and files need to uploaded to remote
system
* Create remote directory skeleton
* Upload the files to respective directories
Returns:
Exception if errors encountered
"""
source = local_normpath(source)
dest = local_normpath(dest)
if local_isdir(source) or len(glob.glob(source)) > 1:
if not recursive:
# For copying more than one file recursive flag should be
# enabled.
msg = "Please enable recursive argument to copy recursively"
LOG.error(msg)
raise RemoteDispatcherException(msg)
# Establish the secure connection.
self.connect()
if local_isfile(source):
(rdirs, lrfiles) = self.__get_paths_source_file(source, dest)
elif local_isdir(source):
(rdirs, lrfiles) = self.__get_paths_source_dir(source, dest)
else:
# else local_ispattern
(rdirs, lrfiles) = self.__get_paths_source_pattern(source, dest)
# Create directory skeleton
for rdir in rdirs:
try:
LOG.debug(rdir)
self.sftp.mkdir(rdir)
except IOError:
msg = "Couldn't create dest directory: '%s'" % (rdir)
LOG.error(msg)
raise RemoteDispatcherException(msg)
# Upload the files
for lfile, rfile in lrfiles:
try:
LOG.info("%s [%0.3f KB]" % \
(local_basename(lfile),
local_getsize(lfile)/float(1024)))
self.sftp.put(lfile, rfile)
except IOError:
msg = "Couldn't copy from local: '%s' to remote: '%s'" \
% (lfile, rfile)
LOG.error(msg)
raise RemoteDispatcherException(msg)
def execute(self, command):
"""Execute the given commands on a remote machine.
Arguments:
command (str) - command to be run on remote side
Returns:
A tuple (exit_stus, output(stdout|stderr))
"""
# Establish the transport session.
self.__establish_session()
channel = self.transport.open_session()
# IF remote process logs the data to stdout and stderr then reading
# one of them makes the other buffer full as a result the remote
# process gets stucked. To avoid this below call combines the stdout
# and stderr output so that reading one of them is sufficient.
channel.set_combine_stderr(True)
LOG.info("'%s'" % command)
channel.exec_command(command)
output = channel.makefile('rb', -1).readlines()
if output:
LOG.info("\n\n%s", ''.join(output))
return (channel.recv_exit_status(), output)
def close(self):
"""Closes the connection and cleans up."""
# Close SFTP Connection.
if self.sftp_live:
self.sftp.close()
self.sftp_live = False
if self.transport and self.transport.is_active():
self.transport.close()
def __del__(self):
"""Attempt to clean up if not explicitly closed."""
self.close()
| 6e4d666775d2b48b2bf7531efe80abd34ae4b511 | [
"Python"
] | 3 | Python | reddyist/python-remote-dispatcher | 1bdd46ccbb0cb233584e5043cfba10846fd02594 | e1636d15448b27eacdde8c1300da7273e8b47622 |
refs/heads/master | <file_sep>class Server {
host = "localhost";
port = 5001;
scheme = "https";
baseUrl() {
return `${this.scheme}://${this.host}:${this.port}`;
}
}
export const server = new Server();
export default Server;
<file_sep># Papers Please Client
- Global authentication manager
- Component to guard and only show when auth requirements are met
- Login/Logout
<file_sep>class Storage {
get(key) {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : null;
}
set(key, value) {
if (value === null) {
localStorage.removeItem(key);
} else {
localStorage.setItem(key, JSON.stringify(value));
}
}
}
export const storage = new Storage();
export default Storage;
<file_sep>import React, { useEffect, useState } from "react";
import { server } from "./util/server";
export default function AppBar() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const handle = setInterval(async () => {
const response = await fetch(server.baseUrl() + "/time");
if (response.ok) {
const dto = await response.json();
setTime(new Date(Date.parse(dto.iso)));
}
}, 1000);
return () => clearInterval(handle);
}, [setTime]);
return <div>{time.toString()}</div>;
}
| 3b70bbf483127c94f6125cc39a13ac30417c7455 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | mlynam/papers-please-lecture-client | c0ed17849210cc4c028fd92e99c9e05303d8b7f4 | 6848bc25bae0eded449132ea44e2e3b73a74aa35 |
refs/heads/master | <repo_name>kevinle-1/Unix-and-C-Programming-Assignment-2018S2<file_sep>/FileIO.h
/**
* FileIO.c
* 17/10/2018
* <NAME> - 19472960
*/
void readFile(char* argv[]);
void toUpper(char string[]);
void writeTo(double x1, double y1, double x2, double y2, int type);<file_sep>/Makefile
#Makefile
#17/10/2018
#<NAME> - 19472960
CC = gcc
EXEC = TurtleGraphics
LM = -lm
CFLAGS = -Werror -Wall -pedantic -ansi -g
#Object files required for Standard/Simple/Debug
OBJ = Main.o FileIO.o RunCmd.o LinkedList.o effects.o
OBJsimple = Main.o FileIO.o RunCmdSimple.o LinkedList.o effects.o
OBJdebug = Main.o FileIODebug.o RunCmd.o LinkedList.o effects.o
#Special object files to be deleted
RM = FileIODebug.o RunCmdSimple.o
#Object dependencies
FILEIO = FileIO.c FileIO.h RunCmd.h
RUNCMD = RunCmd.c RunCmd.h LinkedList.h effects.h
LINKEDLIST = LinkedList.c LinkedList.h
EFFECTS = effects.c effects.h
#--------PROGRAM-EXECUTEABLES-----------------------------------------
$(EXEC): $(OBJ)
$(CC) $(OBJ) -o $(EXEC) $(LM)
#White Background/ Black Foreground - Ignores Other Commands to change colour.
TurtleGraphicsSimple: $(OBJsimple)
$(CC) $(OBJsimple) -o $(EXEC) $(LM)
#Print Log Entries alongside Charizard Print.
TurtleGraphicsDebug: $(OBJdebug)
$(CC) $(OBJdebug) -o $(EXEC) $(LM)
#--------STANDARD-OBJECTS---------------------------------------------
Main.o: Main.c FileIO.h
$(CC) -c $(CFLAGS) Main.c -o Main.o
FileIO.o: $(FILEIO)
$(CC) -c $(CFLAGS) FileIO.c -o FileIO.o
RunCmd.o: $(RUNCMD)
$(CC) -c $(CFLAGS) RunCmd.c -o RunCmd.o $(LM)
LinkedList.o: $(LINKEDLIST)
$(CC) -c $(CFLAGS) LinkedList.c -o LinkedList.o
effects.o: $(EFFECTS)
$(CC) -c $(CFLAGS) effects.c -o effects.o
#--------SIMPLE/DEBUG-OBJECTS-----------------------------------------
#FileIO with DEBUG flag - For TurtleGraphicsDebug
FileIODebug.o: $(FILEIO)
$(CC) -c $(CFLAGS) FileIO.c -o FileIODebug.o -D DEBUG=1
#Simple RunCmd with SIMPLE flag - For TurtleGraphicsSimple
RunCmdSimple.o: $(RUNCMD)
$(CC) -c $(CFLAGS) RunCmd.c -o RunCmdSimple.o -D SIMPLE=1 $(LM)
#--------OTHER UTILS-------------------------------------------------
clean:
rm -f $(OBJ) $(RM) $(EXEC); tput sgr0;
#Resets terminal colour quickly and deletes logfile.
clear:
tput sgr0; rm graphics.log; clear;
valgrind:
valgrind ./TurtleGraphics charizard.txt
<file_sep>/Main.c
/**
* Main.c
* 17/10/2018
* <NAME> - 19472960
*/
#include <stdio.h>
#include"FileIO.h"
/**
* IMPORTS:
* User command line arguments
*
* ASSERTION:
* Begins program, calls readFile() to start process of running commands.
*/
int main(int argc, char* argv[])
{
if(argc != 2)
{
printf("Invalid number of arguments!\n");
}
else
{
readFile(argv);
}
return 0;
}
<file_sep>/LinkedList.h
/**
* LinkedList.c
* 17/10/2018
* <NAME> - 19472960
*/
#include <stdlib.h>
#include <stdio.h>
/*Node contents of linked list*/
typedef struct LinkedListNode
{
struct Data* nodeData;
struct LinkedListNode* next;
} LinkedListNode;
/*Main linked list, containing pointer to head node and tail node*/
typedef struct LinkedList
{
LinkedListNode* head;
LinkedListNode* tail;
} LinkedList;
/*Struct that holds command and value of command. */
typedef struct Data
{
char* command;
char* value;
} Data;
/*Create new list*/
LinkedList* newList();
/*Insert at the end of linked list. (Only have insertLast as only insert that places items
in linked list in correct order. Insert first would never be used.)*/
void insertLast(LinkedList* list, Data* cmdLine);
/*Iterates list printing Data struct at each node*/
void printList(LinkedList* list);
/*Iterates through list freeing Data structs, then node, then linked list*/
void freeList(LinkedList* list);
<file_sep>/FileIO.c
/**
* FileIO.c
* 17/10/2018
* <NAME> - 19472960
*/
#include"FileIO.h"
#include"RunCmd.h"
/**
* IMPORTS:
* argv[] - Command line arguments array via Main
*
* ASSERTION:
* Opens file, reads contents, storing in struct, inserting into a LinkedList, calling runCmd().
*/
void readFile(char* argv[])
{
FILE* inputFile;
char line[15];
/*Max command length would be 8 - Include N.T.*/
char cmd[CMDSIZE];
int numLines = 0;
char val[VALSIZE];
/*Open file specified by user*/
inputFile = fopen(argv[1], "r");
/*Check if Opening succeeded*/
if(inputFile == NULL)
{
printf("Error opening file!\n");
}
else
{
/*LinkedList.c function newList() to initialize new list*/
LinkedList* list = newList();
printf("Reading in commands\n");
/*For the entire length of the file - Use of fgets() to read line */
while(fgets(line, 15, inputFile) != NULL)
{
/* Data struct used to store the COMMAND and VALUE as Strings - Malloc in loop
* The struct is to inserted into the linked list in a node.
*/
Data* cmdLine = (Data*)malloc(sizeof(Data));
/*read files from line - sscanf() to split line on String. */
sscanf(line, "%s %s", cmd, val);
/*Malloc memory for COMMAND and VALUE located inside Data struct*/
cmdLine->command = malloc(CMDSIZE * sizeof(char));
cmdLine->value = malloc(VALSIZE * sizeof(char));
/*Convert command to Upper Case*/
toUpper(cmd);
/*Copy values into COMMAND/VALUE inside Data Struct*/
strcpy(cmdLine->command, cmd);
strcpy(cmdLine->value, val);
/*Call insertLast() function in LinkedList.c to add node on end of list pointing to Data struct.*/
insertLast(list, cmdLine);
numLines++;
}
fclose(inputFile);
/*Pass list to runCmd to run commands*/
runCmd(list, numLines);
freeList(list);
}
}
/**
* IMPORTS:
* Takes Origin (x1, y1) to Destination (x2, y2) real valued coordinates.
* Parametre type (0, 1).
*
* ASSERTION:
* Writes to log file in the format COMMAND(x1, y1)-(x2, y2)
*/
void writeTo(double x1, double y1, double x2, double y2, int type)
{
FILE* logFile = NULL;
char cmd[10];
/*Uses a type parametre to determine what command was called and to print. 0 = MOVE, 1 = DRAW.*/
if(type == 0)
{
strcpy(cmd, "MOVE");
}
else if(type == 1)
{
strcpy(cmd, "DRAW");
}
else
{
strcpy(cmd, "INVALID");
}
/*opens file to append to, mode "a"*/
logFile = fopen("graphics.log", "a");
/*if successfully opened*/
if(logFile != NULL)
{
/*Takes the real valued coordinates calculated in RunCmd.c function updateCoord() and appends to file
uses width and precision specifier to pad with spaces/ decimal accuracy of 3d.p.*/
fprintf(logFile, "%s (%7.3f, %7.3f)-(%7.3f, %7.3f)\n", cmd, x1, y1, x2, y2);
}
else
{
printf("Error Writing LogFile!");
}
/*If DEBUG is defined, print the DRAW log to the screen*/
#ifdef DEBUG
if(type == 1)
{
fprintf(stderr, "%s (%7.3f, %7.3f)-(%7.3f, %7.3f)", cmd, x1, y1, x2, y2);
}
#endif
fclose(logFile);
}
/**
* IMPORTS:
* Character array (String).
*
* ASSERTION:
* Changes all characters in array to uppercase. Ensures uniform case for all commands,
* so strcmp() in RunCmd.c has no issues.
*
* Obtained from Programming Simplified, "C program to change case of a string",
* https://www.programmingsimplified.com/c/program/c-program-change-case (accessed 12 Oct 2018).
*/
void toUpper(char string[])
{
int c = 0;
/*While the character array hasn't ended*/
while (string[c] != '\0')
{
/*For each lowercase value */
if (string[c] >= 'a' && string[c] <= 'z')
{
/*subtracts a value of 32 from the ASCII value of the lowercase character to convert to Upper.*/
string[c] = string[c] - 32;
}
c++;
}
}
<file_sep>/RunCmd.h
/**
* RunCmd.c
* 17/10/2018
* <NAME> - 19472960
*/
#include<math.h>
#include<stdio.h>
#include<string.h>
#include"LinkedList.h"
/*Define constant Pi*/
#define M_PI 3.14159265358979323846
/*Define Degrees to Radian conversion macro*/
#define RAD(deg) ((deg) * ((M_PI)/(180.0)))
/*Define constant for max sizes expected for command and value (used when mallocing sizeof(char))*/
#define CMDSIZE 8
#define VALSIZE 5
/*Struct to keep track of constantly changing data*/
typedef struct Info
{
double currAngle;
int y2;
int x2;
int y1;
int x1;
char currPattern;
int currFG;
int currBG;
} Info;
void runCmd(LinkedList* list, int numLines);
void updateCoord(double d, Info* data, int type);
void plotter(void* plotData);
int roundValue(double value);
int validateSScanf(int success, int required);<file_sep>/README.md
# Unix and C Programming Assignment 2018 S2
UCP assignment completed at Curtin University
<file_sep>/LinkedList.c
/**
* LinkedList.c
* 17/10/2018
* <NAME> - 19472960
*/
#include"LinkedList.h"
/**
* IMPORTS: N/A
*
* EXPORTS:
* Linked List
*
* ASSERTION
* Returns a new Linked List when called.
*/
LinkedList* newList()
{
/*Allocate memory for a new empty Linked List. Containing a head and tail*/
LinkedList* list = (LinkedList*)malloc(sizeof(LinkedList));
/*Set head (first) and tail (last) to NULL (Nothing in list yet)*/
list->head = NULL;
list->tail = NULL;
/*return initialized list back to calling function.*/
return list;
}
/**
* IMPORTS:
* LinkedList to insert newNode.
* Data struct to point value of newNode to.
*
* ASSERTION:
* Function to create and insert a newNode with a pointer to the Data struct, mallocs
* memory for a new node, then points nodeData() in node struct to the address of cmdLine
* (a Data Struct).
*
* Based on code from Curtin University Department of Computing, Data Structures and Algorithms (COMP1002)
* "Lecture 4: Linked Lists, Insert Last Pseudocode" (2017) - (Accessed 9 Oct 2018)
*/
void insertLast(LinkedList* list, Data* cmdLine)
{
/*Allocate memory for a new node, to be inserted into the Linked List*/
LinkedListNode* newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode));
/*Point nodeData of node to address of cmdLine struct*/
newNode->nodeData = cmdLine;
/*nodes next is null, no node after it.*/
newNode->next = NULL;
/*If it is an empty linked list, then make the head and tail point to the new node. */
if(list->head == NULL)
{
list->head = newNode;
list->tail = newNode;
}
/*If it is not empty, set the current tails next value to the new node to be inserted.
Then set new node as the new tail. */
else
{
list->tail->next = newNode;
list->tail = newNode;
}
}
/**
* IMPORTS:
* Linked List to print out.
*
* ASSERTION:
* Prints values of Linked List Node in Linked List.
*/
void printList(LinkedList* list)
{
/*Creates a new node, set to the lists head. */
LinkedListNode* current = list->head;
/*Starts while loop, if the end of the linked list hasn't been reached yet. Print the nodeData contents.*/
while(current != NULL)
{
printf("%s %s\n", current->nodeData->command, current->nodeData->value);
/*Set current to the next node.*/
current = current->next;
}
}
/**
* IMPORTS:
* Linked List to free
*
* ASSERTION:
* Frees the linked list, nodes in the linked list, and any data in the linked list that requires freeing.
*/
void freeList(LinkedList* list)
{
/*Creates a new node, set to the lists head.*/
LinkedListNode *current = list->head;
/*Create a temporary variable to facilitate deleting nodes*/
LinkedListNode* temp;
/*Iterate through linked list, node by node.*/
while(current != NULL)
{
/*Free command malloc at nodeData*/
free(current->nodeData->command);
/*Free value malloc at nodeData*/
free(current->nodeData->value);
/*Free command struct at nodeData (cmdLine)*/
free(current->nodeData);
/*Point the current node to a temporary node*/
temp = current;
/*set current node to the next node*/
current = current->next;
/*free the temporary node (now the previous node)*/
free(temp);
}
/*Free the list*/
free(list);
}
<file_sep>/RunCmd.c
/**
* RunCmd.c
* 17/10/2018
* <NAME> - 19472960
*/
#include"RunCmd.h"
#include"effects.h"
#include"FileIO.h"
/**
* IMPORTS:
* Linked List containing node pointing to structs containing commands to be read.
* Number of lines successfully read from the file.
*
* ASSERTION:
* Iterates through linked list, reading each nodeValue, validating and determinining command to run.
*
* ROTATE - append ROTATE comamnd value to data->currAngle
* MOVE/DRAW - see updateCoord() comment block.
* FG - calls setFgColour
* BG - calls setBgColour
* PATTERN - sets data->currPattern to PATTERN command value
*/
void runCmd(LinkedList* list, int numLines)
{
/*Point the PlotFunc to address of the function plotter*/
PlotFunc funcPtr = &plotter;
#ifndef SIMPLE
int iValue;
#endif
/*Values for sscanf to be assigned to*/
double rValue;
char cValue;
FILE* append;
int read;
/*valid condition for while loop to check, to cont. or stop. If invalid command found, program exited.*/
int valid = 1;
/*Set current node pointer to the head.*/
LinkedListNode* current = list->head;
/*Init a struct called Info to keep track of the changing values (angle, x1, y1, x2, y2,
pattern, fg, bg). Used to update values and parse to functions*/
Info* data = (Info*)malloc(sizeof(Info));
/*Initialize struct keeping track of data to default values*/
data->currAngle = 0.0;
data->x1 = 0;
data->y1 = 0;
data->x2 = 0;
data->y2 = 0;
data->currPattern = '+';
data->currFG = 7;
data->currBG = 0;
/*Set BG to black, FG to white if SIMPLE defined*/
#ifdef SIMPLE
setFgColour(0);
setBgColour(15);
#endif
printf("Running commands\n");
append = fopen("graphics.log", "a");
/*Append to graphics.log a new seperator, as it is new run*/
fprintf(append, "%s\n","---");
/*Clear screen to prep printing.*/
clearScreen();
/*note: if %lf changed to %f - charizard fails to print
Iterates through each node in the list, Head to tail order (first to last), checking commands in
if-else-if conditions if a command is matched its value (currently a string) is retrieved using sscanf
and typecast into required datatype then required operation is run.*/
while(current != NULL && valid == 1)
{
if(strcmp(current->nodeData->command, "ROTATE") == 0)
{
read = sscanf(current->nodeData->value, "%lf", &rValue);
/*append ROTATE command angle on top of current angle.*/
valid = validateSScanf(read, 1);
data->currAngle += rValue;
}
else if(strcmp(current->nodeData->command, "MOVE") == 0)
{
read = sscanf(current->nodeData->value, "%lf", &rValue);
/*Calls updateCood() to update X/Y values with MOVE command value*/
/*Check if sscanf has read in the correct number of variables, allowing the while loop to continue iterating*/
if((valid = validateSScanf(read, 1)) == 1)
{
/*calls updateCoord passing in data struct, modifies relevant x/y values using MOVE command value*/
updateCoord(rValue, data, 0);
}
}
else if(strcmp(current->nodeData->command, "DRAW") == 0)
{
read = sscanf(current->nodeData->value, "%lf", &rValue);
/*Calls updateCood() to update X/Y values with DRAW command value*/
if((valid = validateSScanf(read, 1)) == 1)
{
/*Decrease distnace by 1 to prevent double print*/
updateCoord(rValue-1, data, 1);
/*Draws line using struct data passing in origin point to destination point.
function pointer, and currPattern*/
line(data->x1, data->y1, data->x2, data->y2, *funcPtr, &data->currPattern);
/*Move cursor along by 1 to prevent double print*/
updateCoord(1, data, 2);
}
}
/*FG/BG commands ignored if SIMPLE defined*/
else if(strcmp(current->nodeData->command, "FG") == 0)
{
#ifndef SIMPLE
read = sscanf(current->nodeData->value, "%d", &iValue);
/*Validate if successfully read command*/
if((valid = validateSScanf(read, 1)) == 1)
{
setFgColour(iValue);
}
#endif
}
else if(strcmp(current->nodeData->command, "BG") == 0)
{
#ifndef SIMPLE
sscanf(current->nodeData->value, "%d", &iValue);
/*Validate if successfully read command*/
if((valid = validateSScanf(read, 1)) == 1)
{
setBgColour(iValue);
}
#endif
}
else if(strcmp(current->nodeData->command, "PATTERN") == 0)
{
sscanf(current->nodeData->value, "%c", &cValue);
/*sets current pattern as PATTERN value*/
if((valid = validateSScanf(read, 1)) == 1)
{
/*set current pattern to new pattern*/
data->currPattern = cValue;
}
}
else
{
/*Command is invalid. Quit the program and free everything*/
printf("Invalid command found! Exiting.\n");
/*set valid condition to 0, exits while loop*/
valid = 0;
}
/*if no invalid command is found, continue to next node*/
if(valid == 1)
{
current = current->next;
}
else
{
printf("Invalid command value! Exiting.\n");
}
}
fclose(append);
free(data);
/*Drawing successfully completed if valid stays at 1. Therefore finish up*/
if(valid == 1)
{
penDown();
printf("Done\n");
}
}
/**
* IMPORTS:
* Success - Integer returned by sscanf (Number of successfully read values)
* Required - Parameter manually set in calling function. Number of values sscanf should HAVE successfully read.
*
* ASSERTION:
* Returns 1 if sscanf read correctly, 0 if not.
*/
int validateSScanf(int success, int required)
{
int retVal = 0;
/*check if sscanf matches assertion*/
if(success == required)
{
retVal = 1;
}
return retVal;
}
/**
* IMPORTS:
* d - Value of command. (e.g. MOVE 5, d = 5)
* Info* data - data struct with values to update/ append
* type - Integer to allow FileIO.c writeTo() to determine what command was run to print. 0 = MOVE, 1 = DRAW, 2 = IGNORE
*
* ASSERTION:
* Updates the X/Y Coordinates.
*/
void updateCoord(double d, Info* data, int type)
{
/*Real static variables for writing to the log file, need a seperate variable due
to data struct having values stored as real, while log file requires reals
--
Use of Static variable to make it easier to append, instead of requiring loop as it
stays in one function*/
double logX1;
double logY1;
static double logX2;
static double logY2;
/*Radians required*/
double radian;
double resultX, resultY;
/*Retrieves current angle from struct, using macro RAD to convert to radians,
stores in variable radians. */
radian = RAD(data->currAngle);
/*uses a seperate log variable to keep track of the REAL values to write*/
logX1 = logX2;
logY1 = logY2;
/*Sets x1, y1 of Data struct to current x2, y2 values
(e.g. the origin/ previous point to draw/move from after previous draw/move was finished).*/
data->x1 = data->x2;
data->y1 = data->y2;
/*Runs COS/ SIN calculation for X/Y, storing result into resultX/resultY*/
resultX = d*(cos(radian));
resultY = d*(sin(radian));
/*appends real resultX/resultY to Log variables*/
logX2 += resultX;
logY2 -= resultY;
/*Appends rounded resultX/resultY Integers (after parsed to roundValue) to data struct x2, y2*/
data->x2 += roundValue(resultX);
data->y2 -= roundValue(resultY);
/*If the move command meant to resolve the double printing wasn't run*/
if(type != 2)
{
/*Sends log variables to writeTo to write calculation to logfile.*/
writeTo(logX1, logY1, logX2, logY2, type);
}
}
/**
* IMPORTS: void pointer to accomodate any datatype that can be printed
*
* Prints plotData.
*/
void plotter(void* plotData)
{
printf("%c", *((char *) plotData));
}
/**
* IMPORTS:
* Real value to round.
*
* EXPORTS:
* Rounded value as an integer.
*
* ASSERTION:
* Rounds value to nearest integer. e.g. 1.2 -> 1, 2.6 -> 3.
*
* Algorithm based on <NAME>' answer via Stack Overflow, "How to round floating point
* numbers to the nearest integer in C?"
* https://stackoverflow.com/questions/2570934/how-to-round-floating-point-numbers-to-the-nearest-integer-in-c
* (Accessed 10 Oct 2018).
*/
int roundValue(double value)
{
double retVal;
/*If value is positive, add 0.5 to it, if > .5 then it will round to the next highest integer
if it is < .5 it will round to the closest integer. Gets rounded after typecast to Integer. */
if(value < 0)
{
retVal = value - 0.5;
}
else
{
retVal = value + 0.5;
}
return (int)retVal;
} | 4a46479e24e0c5faefeb9a53018bd925ea77637f | [
"Markdown",
"C",
"Makefile"
] | 9 | C | kevinle-1/Unix-and-C-Programming-Assignment-2018S2 | a45924ae04e8a9ea9fc551ea09a165dda9d3eb05 | 07a785a4a65ec1b5161b3319b7d9c6b5e6fa93b2 |
refs/heads/master | <file_sep># noripetsu-bot
If your girlfriend constantly wants your attention, why not create a bot to talk to her?
That way you can spend more time coding! Wow!
Hosted on Heroku :)
<file_sep>APScheduler==3.6.3
boto3==1.18.1
botocore==1.21.1
cachetools==4.2.2
certifi==2021.5.30
click==8.0.1
Flask==2.0.1
gunicorn==20.1.0
itsdangerous==2.0.1
Jinja2==3.0.1
jmespath==0.10.0
MarkupSafe==2.0.1
python-dateutil==2.8.2
python-telegram-bot==13.7
pytz==2021.1
s3transfer==0.5.0
six==1.16.0
tornado==6.1
tzlocal==2.1
urllib3==1.26.6
Werkzeug==2.0.1
<file_sep>import random
import re
from flask import Flask, request
import boto3
import telegram
from telebot.credentials import bot_token, bot_user_name, URL, aws_access_key_id, aws_secret_access_key, s3_bucket
from time import sleep, time
from io import BytesIO
def get_an_x(key: str) -> str:
session = boto3.Session(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name="ap-southeast-1")
bucket = "noripetsu-bot"
s3_client = session.client("s3")
res = s3_client.list_objects(Bucket=s3_bucket, Prefix="{}/".format(key), MaxKeys=1000)
number_of_x = len(res["Contents"])
pick = key + "/" + str(random.randint(1,number_of_x-1)) + ".txt"
f = BytesIO()
s3_client.download_fileobj(bucket, pick,f)
return f.getvalue().decode("utf-8")
global bot
global TOKEN
TOKEN = bot_token
bot = telegram.Bot(token=TOKEN)
app = Flask(__name__)
@app.route('/{}'.format(TOKEN), methods=['POST'])
def respond():
# retrieve the message in JSON and then transform it to Telegram object
print(request.get_json(force=True))
update = telegram.Update.de_json(request.get_json(force=True), bot)
chat_id = update.effective_message.chat.id
msg_id = update.effective_message.message_id
time_mod_10 = int(time()) % 10
# Telegram understands UTF-8, so encode text for unicode compatibility
text = update.effective_message.text.encode('utf-8').decode()
# for debugging purposes only
print("got text message :", text)
# the first time you chat with the bot AKA the welcoming message
if text == "/start":
bot_welcome = """
HELLO POK, WHY ARE YOU NOT DOING WORK?
"""
bot.sendChatAction(chat_id=chat_id, action="typing")
sleep(1.35)
bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id)
elif text == "/money":
msg = """
NO
"""
bot.sendChatAction(chat_id=chat_id, action="typing")
sleep(1.25)
bot.sendMessage(chat_id=chat_id, text=msg, reply_to_message_id=msg_id)
elif text == "/love":
msg = """
hughug
"""
bot.sendChatAction(chat_id=chat_id, action="typing")
sleep(1.5)
bot.sendMessage(chat_id=chat_id, text=msg, reply_to_message_id=msg_id)
elif text == "/kisskiss":
msg = """
lovelove
"""
bot.sendChatAction(chat_id=chat_id, action="typing")
sleep(1.5)
bot.sendMessage(chat_id=chat_id, text=msg, reply_to_message_id=msg_id)
elif text == "/fact":
msg = get_an_x(key="fact")
bot.sendChatAction(chat_id=chat_id, action="typing")
sleep(1.5)
bot.sendMessage(chat_id=chat_id, text=msg, reply_to_message_id=msg_id)
elif text == "/story":
msg = get_an_x(key="story")
bot.sendChatAction(chat_id=chat_id, action="typing")
sleep(1.5)
bot.sendMessage(chat_id=chat_id, text=msg, reply_to_message_id=msg_id)
elif text == "/hughug":
msg = """
kisskiss
"""
bot.sendChatAction(chat_id=chat_id, action="typing")
sleep(1.5)
bot.sendMessage(chat_id=chat_id, text=msg, reply_to_message_id=msg_id)
elif text == "/joke":
msg = get_an_x(key="joke")
bot.sendChatAction(chat_id=chat_id, action="typing")
sleep(1.5)
bot.sendMessage(chat_id=chat_id, text=msg, reply_to_message_id=msg_id)
else:
try:
# clear the message we got from any non alphabets
text = re.sub(r"\W", "_", text)
# create the api link for the avatar based on http://avatars.adorable.io/
url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip())
# reply with a photo to the name the user sent,
# note that you can send photos by url and telegram will fetch it for you
bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id)
bot.sendChatAction(chat_id=chat_id, action="typing")
sleep(2)
bot.sendMessage(chat_id=chat_id, text="STOP PLAYING WITH A BOT AND WORK", reply_to_message_id=msg_id)
except Exception:
# if things went wrong
bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)
return 'ok'
@app.route('/setwebhook', methods=['GET', 'POST'])
def set_webhook():
# we use the bot object to link the bot to our app which live
# in the link provided by URL
s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))
# something to let us know things work
if s:
return "webhook setup ok"
else:
return "webhook setup failed"
@app.route('/')
def index():
return '.'
if __name__ == '__main__':
# note the threaded arg which allow
# your app to have more than one thread
app.run(threaded=True)
<file_sep>import os
bot_token = os.environ["BOT_TOKEN"]
bot_user_name = os.environ["BOT_USER_NAME"]
URL = os.environ["URL"]
aws_access_key_id = os.environ["AWS_ACCESS_KEY_ID"]
aws_secret_access_key = os.environ["AWS_SECRET_ACCESS_KEY"]
s3_bucket = os.environ["S3_BUCKET"]
| 586a4f8afc8c11e87967aa386b96c1df1c5d1ecf | [
"Markdown",
"Python",
"Text"
] | 4 | Markdown | frenoid/noripetsu-bot | 613848167c28c0d1ab528a5ea7e0d30026e0d618 | d94aab64722a3a8d6df7f44bb77bbc395392b4bb |
refs/heads/main | <repo_name>okode/pwa-capacitor<file_sep>/src/app/home/home.page.ts
import { Component } from '@angular/core';
import { ActionSheet, ActionSheetButton, ActionSheetButtonStyle } from '@capacitor/action-sheet';
import { registerPlugin } from '@capacitor/core';
import { Dialog } from '@capacitor/dialog';
interface TrackingPlugin {
trackScreen(options: { screen: string }): Promise<void>;
}
interface AlertPlugin {
show(options: { title: string; message: string }): Promise<void>;
}
const trackingPlugin = registerPlugin<TrackingPlugin>('TrackingPlugin');
const alertPlugin = registerPlugin<AlertPlugin>('AlertPlugin');
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
ionViewDidEnter() {
trackingPlugin.trackScreen({ screen: 'home' });
}
async showActionSheet() {
const options: ActionSheetButton[] = [
{ title: 'Upload' },
{ title: 'Share' },
{ title: 'Remove', style: ActionSheetButtonStyle.Destructive }
];
const result = await ActionSheet.showActions({
title: 'Photo Options',
message: 'Select an option to perform',
options
});
await Dialog.alert({
title: 'Photo option selected',
message: options[result.index].title
});
alertPlugin.show({ title: 'Title from JS', message: 'Message from JS' });
}
}
<file_sep>/android/app/src/main/java/com/okode/pwacapacitor/MainActivity.java
package com.okode.pwacapacitor;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import java.util.Arrays;
public class MainActivity extends BridgeActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugins(Arrays.asList(
AlertPlugin.class,
TrackingPlugin.class
));
}
}
<file_sep>/README.md
# PWA Capacitor
<file_sep>/ios/App/Podfile
platform :ios, '12.0'
use_frameworks!
# workaround to avoid Xcode caching of Pods that requires
# Product -> Clean Build Folder after new Cordova plugins installed
# Requires CocoaPods 1.6 or newer
install! 'cocoapods', :disable_input_output_paths => true
def capacitor_pods
pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
pod 'CapacitorActionSheet', :path => '../../node_modules/@capacitor/action-sheet'
pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app'
pod 'CapacitorDialog', :path => '../../node_modules/@capacitor/dialog'
pod 'CapacitorHaptics', :path => '../../node_modules/@capacitor/haptics'
pod 'CapacitorKeyboard', :path => '../../node_modules/@capacitor/keyboard'
end
target 'App' do
capacitor_pods
# Add your Pods here
pod 'Firebase/Analytics'
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings.delete 'ARCHS'
config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
end
end
end
<file_sep>/android/app/src/main/java/com/okode/pwacapacitor/TrackingPlugin.java
package com.okode.pwacapacitor;
import android.os.Handler;
import android.os.Looper;
import androidx.appcompat.app.AlertDialog;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
@CapacitorPlugin(name = "TrackingPlugin")
public class TrackingPlugin extends Plugin {
@PluginMethod
public void trackScreen(PluginCall call) {
String screen = call.getString("screen");
call.resolve();
}
}
<file_sep>/ios/App/App/AppPlugin.swift
import Foundation
import Capacitor
import FirebaseAnalytics
@objc(TrackingPlugin)
public class TrackingPlugin: CAPPlugin {
@objc func trackScreen(_ call: CAPPluginCall) {
guard let screen = call.options["screen"] as? String else {
call.reject("Must provide screen to track")
return
}
Analytics.logEvent(AnalyticsEventScreenView, parameters: [AnalyticsParameterScreenName: screen])
call.resolve()
}
}
@objc(AlertPlugin)
public class AlertPlugin: CAPPlugin {
@objc func show(_ call: CAPPluginCall) {
guard let title = call.options["title"] as? String else {
call.reject("Must provide title")
return
}
guard let message = call.options["message"] as? String else {
call.reject("Must provide message")
return
}
DispatchQueue.main.async {
let dialog = UIAlertController(title: title, message: message, preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
dialog.addAction(ok)
self.bridge?.viewController?.present(dialog, animated: true, completion: {
call.resolve()
})
}
}
}
| b442c71f440fcc94e9ceb7242da8707c7fcc02f0 | [
"Ruby",
"Markdown",
"Swift",
"Java",
"TypeScript"
] | 6 | TypeScript | okode/pwa-capacitor | 0708b95ed903244279437de7b48ca9ac31d4dbe9 | 3c3f1c666fa5ee7018e95a04e5d2df5fc249a7e1 |
refs/heads/master | <repo_name>vadim2353/hub<file_sep>/3.java
import java.util.Random;
public class Now {
public static void main(String[] args) {
int[] arr = new int[15];
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(99);
System.out.print(" " + arr[i]);
}
System.out.println();
int c;
for (int j = 0; j < arr.length; j++) {
if (arr[j] % 2 == 0) {
c = j;
System.out.print(" " + c);
}
}
}
}<file_sep>/1.java
public class Now {
public static void main(String[] args) {
int[] arr = new int[]{2,4,6,8,10,12,14,16,18,20};
for (int i = 0; i < arr.length; i++) {
System.out.print(" " + arr[i]); // System.out.println(arr[i]); - вариант в столбик
}
}
}<file_sep>/5.java
import java.util.Random;
public class Now {
public static void main(String[] args) {
int[] arr = new int[5];
int[] arr2 = new int[5];
Random random = new Random();
int a = 0;
int c = 0;
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(15);
System.out.print(" " + arr[i]);
a +=arr [i];
c = a / 5;
}
System.out.println();
int a2 = 0;
int c2 = 0;
for (int i = 0; i < arr2.length; i++) {
arr2[i] = random.nextInt(15);
System.out.print(" " + arr2[i]);
a2 += arr2[i];
c2 = a2 / 5;
}
System.out.println();
if (c > c2) {
System.out.print("1 massiv bolshe");
}
else if (c < c2) {
System.out.print("2 massiv bolshe");}
else {
System.out.print("massivi rovni");
}
}
}<file_sep>/9.java
import java.util.Random;
import java.util.Scanner;
public class Now {
public static void main(String[] args) {
Scanner scaner = new Scanner(System.in);
int c = scaner.nextInt();
Random random = new Random();
if (c < 0) {
System.out.print("neverno zadaniy masiv");
} else if (c == 0) {
System.out.print("neverno zadaniy masiv");
} else if (c % 2 != 0) {
System.out.print("neverno zadaniy masiv");
} else if (c % 2 == 0) {
int[] arr = new int[c];
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(15);
System.out.print(arr[i] + " ");
}
System.out.println();
int t = 0;
for (int j = 0; j < arr.length; j++) {
t += arr[j];
}
int polovina = c / 2;
int sum = 0;
for (int i = 0; i < arr.length - polovina; i++) {
sum += arr[i];
}
int sum2 = 0;
sum2 = t - sum;
if (sum > sum2) {
System.out.print("suma pervoy polovini bolshe");
} else if (sum < sum2) {
System.out.print("summa vtoroy polovini bolshe");
} else if (sum == sum2) {
System.out.print("dve storoni rovni");
}
}
}
}<file_sep>/robot/src/by/teachmeskills/robot/Run.java
package by.teachmeskills.robot;
public class Run {
public static void main(String[] args) {
Robot1 robot1 = new Robot1();
Robot2 robot2 = new Robot2();
Robot3 robot3 = new Robot3();
if (robot1.getPrice() > robot2.getPrice() && robot1.getPrice() > robot3.getPrice()) {
System.out.print("Robot1 самый дорогой");
} else if (robot2.getPrice() > robot1.getPrice() && robot2.getPrice() > robot3.getPrice()) {
System.out.print("Robot2 самый дорогой");
} else if (robot3.getPrice() > robot1.getPrice() && robot3.getPrice() > robot2.getPrice()){
System.out.print("Robot3 самый дорогой");
}
/*
Создать по 3 реализации(Sony, Toshiba, Samsung) каждой запчасти(IHead, IHand, ILeg)
Класс SonyHead является примером реализацией головы от Sony.
Создайте 3 робота с разными комплектующими.
Например у робота голова и нога от Sony а, рука от Samsung.
У всех роботов вызовите метод action.
Среди 3-х роботов найдите самого дорогого.
*/
}
}
| 5f616f5cd2ab6f029f9ff060e872945504626efc | [
"Java"
] | 5 | Java | vadim2353/hub | f1a15f5081894f7ed481043b642a4418b40ebdc0 | fb7b076ad31b76b8c106536a55fdd3b17e552b13 |
refs/heads/master | <file_sep>
const spirit = {
name: 'spirit',
direction: 'E',
y: 9,
x: 1,
travelLog: [{ y: 9, x: 1 }]
}
const opportunity = {
name: 'opportunity',
direction: 'W',
y: 9,
x: 8,
travelLog: [{ y: 9, x: 8 }]
}
const grid = [
// 0x 1x 2x 3x 4x 5x 6x 7x 8x 9x
[false, false, false, false, false, false, false, false, false, false], //0y
[false, false, true, false, false, false, false, false, false, false], //1y
[false, false, false, false, false, false, false, false, false, false], //2y
[false, false, false, false, false, false, false, true, false, false], //3y
[false, false, false, false, true, false, false, false, false, false], //4y
[false, false, false, false, false, false, false, false, false, false], //5y
[false, true, false, false, false, false, false, false, false, false], //6y
[false, false, false, false, false, false, false, true, false, false], //7y
[false, false, false, false, true, false, false, false, false, false], //8y
[false, false, false, false, false, false, false, false, false, false] //9y
]
function turnLeft(rover) {
if (rover.direction === 'N') {
rover.direction = 'W';
} else if (rover.direction === 'W') {
rover.direction = 'S';
} else if (rover.direction === 'S') {
rover.direction = 'E';
} else if (rover.direction === 'E') {
rover.direction = 'N';
}
return `New direction: ${rover.direction}`;
}
function turnRight(rover) {
if (rover.direction === 'N') {
rover.direction = 'E';
} else if (rover.direction === 'E') {
rover.direction = 'S';
} else if (rover.direction === 'S') {
rover.direction = 'W';
} else if (rover.direction === 'W') {
rover.direction = 'N';
}
return `New direction: ${rover.direction}`;
}
function moveForward(rover, grid) {
if (rover.direction === 'N' && (rover.y - 1) >= 0) {
if (grid[rover.y - 1][rover.x] === false) {
rover.y -= 1;
rover.travelLog.push({ y: rover.y, x: rover.x });
grid[rover.y][rover.x] = rover.name;
grid[rover.y + 1][rover.x] = false;
return `rover: ${rover.name}, y: ${rover.y}, x: ${rover.x} and direction: ${rover.direction}`;
} else {
return `Obstacle!`;
}
} else if (rover.direction === 'W' && (rover.x - 1) >= 0) {
if (grid[rover.y][rover.x - 1] === false) {
rover.x -= 1;
rover.travelLog.push({ y: rover.y, x: rover.x })
grid[rover.y][rover.x] = rover.name;
grid[rover.y][rover.x + 1] = false;
return `rover: ${rover.name}, y: ${rover.y}, x: ${rover.x} and direction: ${rover.direction}`;
} else {
return `Obstacle!`;
}
} else if (rover.direction === 'S' && (rover.y + 1) <= 9) {
if (grid[rover.y + 1][rover.x] === false) {
rover.y += 1;
rover.travelLog.push({ y: rover.y, x: rover.x })
grid[rover.y][rover.x] = rover.name;
grid[rover.y - 1][rover.x] = false;
return `rover: ${rover.name}, y: ${rover.y}, x: ${rover.x} and direction: ${rover.direction}`;
} else {
return `Obstacle!`;
}
} else if (rover.direction === 'E' && (rover.x + 1) <= 9) {
if (grid[rover.y][rover.x + 1] === false) {
rover.x += 1;
rover.travelLog.push({ y: rover.y, x: rover.x })
grid[rover.y][rover.x] = rover.name;
grid[rover.y][rover.x - 1] = false;
return ` rover: ${rover.name}, y: ${rover.y}, x: ${rover.x} and direction: ${rover.direction}`;
} else {
return `Obstacle!`;
}
} else {
return 'You can not place rover outside of the grid!'
}
}
function moveBackward(rover) {
if (rover.direction === 'N' && (rover.y + 1) <= 9) {
if (grid[rover.y + 1][rover.x] === false) {
rover.y += 1;
rover.travelLog.push({ y: rover.y, x: rover.x })
grid[rover.y][rover.x] = rover.name;
grid[rover.y - 1][rover.x] = false;
return `rover: ${rover.name}, y: ${rover.y}, x: ${rover.x} and direction: ${rover.direction}`;
} else {
return `Obstacle!`;
}
} else if (rover.direction === 'W' && (rover.x + 1) <= 9) {
if (grid[rover.y][rover.x + 1] === false) {
rover.x += 1;
rover.travelLog.push({ y: rover.y, x: rover.x })
grid[rover.y][rover.x] = rover.name;
grid[rover.y][rover.x - 1] = false;
return `rover: ${rover.name}, y: ${rover.y}, x: ${rover.x} and direction: ${rover.direction}`;
} else {
return `Obstacle!`;
}
} else if (rover.direction === 'S' && (rover.y - 1) >= 0) {
if (grid[rover.y - 1][rover.x] === false) {
rover.y -= 1;
rover.travelLog.push({ y: rover.y, x: rover.x })
grid[rover.y][rover.x] = rover.name;
grid[rover.y + 1][rover.x] = false;
return `rover: ${rover.name}, y: ${rover.y}, x: ${rover.x} and direction: ${rover.direction}`;
} else {
return `Obstacle!`
}
} else if (rover.direction === 'E' && (rover.x - 1) >= 0) {
if (grid[rover.y][rover.x - 1] === false) {
rover.x -= 1;
rover.travelLog.push({ y: rover.y, x: rover.x })
grid[rover.y][rover.x] = rover.name;
grid[rover.y][rover.x + 1] = false;
return `rover: ${rover.name}, y: ${rover.y}, x: ${rover.x} and direction: ${rover.direction}`;
} else {
return `Obstacle!`
}
} else {
return 'You can not place rover outside of the grid!'
}
}
function command(rover, grid, orders) {
for (let i = 0; i < orders.length; i++) {
switch (orders[i]) {
case 'f':
console.log(moveForward(rover, grid));
break;
case 'l':
console.log(turnLeft(rover));
break;
case 'b':
console.log(moveBackward(rover, grid));
break;
case 'r':
console.log(turnRight(rover));
break;
default:
console.log(`Please, inputs must be f, b, r, or l`);
}
}
console.log(grid);
return ` rover: ${rover.name} - x: ${rover.x}, y: ${rover.y} and direction: ${rover.direction}`;
}
| 8c7114cfbeeffe362dba88afef237e90820389a2 | [
"JavaScript"
] | 1 | JavaScript | grazidiandra/MarsRover | 76a09c48f7bc59bf75e4b3ea3fa8161dad3cffaf | d6c24e5f5f96f2daefd52c59f3e6df80d28828c8 |
refs/heads/master | <file_sep>//
// BarcodeViewController.swift
// Media
//
// Created by <NAME> on 10/20/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import UIKit
import AVFoundation
class BarcodeViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate
{
//MARK: INSTANCE VARS
let upcDatabase = "http://www.upcdatabase.com/item/"
var captureSession:AVCaptureSession!
var videoDevice:AVCaptureDevice!
var videoInput:AVCaptureDeviceInput!
var previewLayer:AVCaptureVideoPreviewLayer!
var running:Bool!
var metadataOutput:AVCaptureMetadataOutput!
var highlightView:UIView!
override func viewDidLoad()
{
super.viewDidLoad()
self.title = "Scan Barcode";
highlightView = UIView()
highlightView.autoresizingMask = UIViewAutoresizing.FlexibleTopMargin
highlightView.layer.borderColor = UIColor.greenColor().CGColor
highlightView.layer.borderWidth = 3
self.view.addSubview(highlightView)
self.setupCaptureSession()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupCaptureSession()
{
if((captureSession) != nil) { return; }
captureSession = AVCaptureSession()
videoDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
videoInput = AVCaptureDeviceInput(device: videoDevice, error: nil)
if captureSession.canAddInput(videoInput)
{
captureSession.addInput(videoInput)
}
metadataOutput = AVCaptureMetadataOutput()
metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
if captureSession.canAddOutput(metadataOutput)
{
captureSession.addOutput(metadataOutput)
}
metadataOutput.metadataObjectTypes = metadataOutput.availableMetadataObjectTypes
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = self.view.bounds
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.addSublayer(previewLayer)
captureSession.startRunning()
self.view.bringSubviewToFront(highlightView)
}
//MARK: DELEGATES
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!)
{
var highlightViewRect = CGRectZero
var barcodeObject:AVMetadataMachineReadableCodeObject!
var detectionString:NSString!
var barcodeTypes:NSArray = [ AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode ]
for metaData in metadataObjects
{
for type in barcodeTypes
{
if (metaData as AVMetadataObject).type == (type as NSString)
{
barcodeObject = previewLayer.transformedMetadataObjectForMetadataObject(metaData as AVMetadataObject) as AVMetadataMachineReadableCodeObject
highlightViewRect = barcodeObject.bounds
detectionString = (metaData as AVMetadataMachineReadableCodeObject).stringValue
break
}
}
if detectionString != nil
{
println(detectionString)
}
}
highlightView.frame = highlightViewRect
}
}
| f9beb5cb9afc550f2c7a26f3404f4ca9d66c751f | [
"Swift"
] | 1 | Swift | danielrushton/Media | e36c1a0cabece1241d78272ffc95f65b249a0607 | ca98d69998ab9920989e60769029fc5c401fd93f |
refs/heads/main | <repo_name>jtlin226/Microblogging_FE<file_sep>/Microblogging/src/app/components/search-users/search-users.component.ts
import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/models/user';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-search-users',
templateUrl: './search-users.component.html',
styleUrls: ['./search-users.component.css']
})
export class SearchUsersComponent implements OnInit {
searchInput: string = "";
foundUsers: User[] = [];
constructor(
private userService: UserService) { }
ngOnInit() {
}
search(): void{
this.foundUsers = []
this.userService.searchByName(this.searchInput).subscribe(
(result:User[]) => {
this.foundUsers = result;
this.userService.searchByUsername(this.searchInput).subscribe(
(searchResults:User[]) => {
for(let r of searchResults){
if(!this.foundUsers.some( u => u.id === r.id)){
this.foundUsers.push(r);
}
}
}
)
});
}
}
<file_sep>/Microblogging/src/app/components/profile-page/profile-page.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { User } from 'src/app/models/user';
import { UserService } from 'src/app/services/user.service';
import { Location } from '@angular/common';
@Component({
selector: 'app-profile-page',
templateUrl: './profile-page.component.html',
styleUrls: ['./profile-page.component.css']
})
export class ProfilePageComponent implements OnInit {
constructor(private userService : UserService,
private route : ActivatedRoute,
private location : Location) { }
username: string = '';
firstname: string = '';
lastname: string = ''
about: string = '';
imageURL: string = '';
currentUser : User | undefined;
editing : boolean = false;
successfulUpdate : boolean = false;
/**
* get current user to populate page. This page only shows information and routes to other pages where changes can be made
*/
ngOnInit() {
this.userService.getCurrentUser().subscribe((user) => {
this.currentUser = user
this.username = user.username
this.firstname = user.firstName
this.lastname = user.lastName
this.about = user.about
this.imageURL = user.imageURL
});
}
}
<file_sep>/Microblogging/src/app/services/user.service.ts
import { Injectable } from '@angular/core';
import { User } from '../models/user';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, switchMap } from 'rxjs/operators'
import { AuthorizationService } from './authorization.service';
// import { environment } from 'src/environments/environment';
// import { UserAdapter } from '../models/user';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient, private authService: AuthorizationService) { }
// url: string = `${environment.revAssureBase}revuser`;
url = "http://localhost:8082/user";
httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
"Authorization": ""
})
};
/**
* Performs a POST to "/revuser/register" to register a new user to database.
* @param newUser User to be registered and persisted.
* @returns Observable of User returned from backend.
*/
// registerNewUser(newUser: User): Observable<User> {
// return this.http.post<User>(`${this.url}/register`, newUser).pipe(map((result: any) => {
// let registeredUser: User = this.userAdapter.adapt(result);
// return registeredUser;
// }));
// }
registerNewUser(newUser: User): Observable<User> {
return this.http.post<User>(`${this.url}/register`, newUser);
}
/**
* Performs a POST to "/revuser/authenticate" to login.
* After successful login, also calls getUser().
* @param username
* @param password
* @returns Observable of the user's JWT as a string.
*/
login(username: string, password: string): Observable<any> {
const authObject = {
username,
password
}
return this.http.post(`${this.url}/authenticate`, authObject)
}
public getFollowers(): Observable<User[]>{
this.setHeaderWithJwt();
return this.http.get<User[]>(`${this.url}/follower`, this.httpOptions);
}
public getFollowing(): Observable<User[]>{
this.setHeaderWithJwt();
return this.http.get<User[]>(`${this.url}/following`, this.httpOptions);
}
public followUser(user: User): Observable<User>{
this.setHeaderWithJwt();
return this.http.put<User>(`${this.url}/follow/${user.id}`, {}, this.httpOptions);
}
public unFollowUser(user: User): Observable<User>{
this.setHeaderWithJwt();
return this.http.put<User>(`${this.url}/unfollow/${user.id}`, {}, this.httpOptions);
}
public searchByUsername(username: string): Observable<User[]>{
this.setHeaderWithJwt();
return this.http.get<User[]>(`${this.url}/${username}`, this.httpOptions);
}
public searchByName(name: string): Observable<User[]>{
this.setHeaderWithJwt();
return this.http.get<User[]>(`${this.url}/search/${name}`, this.httpOptions);
}
public getCurrentUser(): Observable<User>{
this.setHeaderWithJwt();
return this.http.get<User>(this.url, this.httpOptions);
}
public isUserFollowed(user: User, following: User[]): boolean{
return following.some( u => u.id === user.id );
}
private setHeaderWithJwt(){
this.httpOptions.headers = this.httpOptions.headers.set('Authorization', `Bearer ${this.authService.jwt}`);
}
updateUser(updatedUser : any): Observable<User> {
this.setHeaderWithJwt();
let obj = {
id: updatedUser.id,
username: updatedUser.username,
firstName: updatedUser.firstName,
lastName: updatedUser.lastName,
imageURL: updatedUser.imageURL,
about: updatedUser.about,
password: ''
}
return this.http.put<User>(`${this.url}/about`, obj, this.httpOptions)
}
/**
* send request to change user password
* @param password <PASSWORD>
* @returns observable of updated user
*/
resetPassword(password: string)
{
this.setHeaderWithJwt();
let obj = {
password: password
}
return this.http.put<User>(`${this.url}/password`, obj, this.httpOptions);
}
/**
* send request to get specific user
* @param username username to recover
* @returns observable of user we're looking for
*/
getSpecificUser(username: string): Observable<User>
{
return this.http.get<User>(`${this.url}/recover/${username}`)
}
}
<file_sep>/Microblogging/src/app/components/following/following.component.ts
import { UserService } from 'src/app/services/user.service';
import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/models/user';
import { AuthorizationService } from 'src/app/services/authorization.service';
@Component({
selector: 'app-following',
templateUrl: './following.component.html',
styleUrls: ['./following.component.css']
})
export class FollowingComponent implements OnInit {
constructor(private userService: UserService, private authService: AuthorizationService) { }
ngOnInit()
{
this.getFollowingList();
}
following: User[] = [];
/**
* get list of all users following current logged-in user
*/
getFollowingList()
{
this.following = [];
this.userService.getFollowing().subscribe(followingUsers =>
{
this.following = followingUsers;
console.log(this.following);
});
}
}
<file_sep>/Microblogging/src/app/components/edit-password/edit-password.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-edit-password',
templateUrl: './edit-password.component.html',
styleUrls: ['./edit-password.component.css']
})
export class EditPasswordComponent implements OnInit {
constructor(private userService : UserService,
private router : Router) { }
password1 : string = ''
password2 : string = ''
username : string = ''
successfulUpdate : boolean = false
passwordMatch : boolean = true
/**
* get current user to populate page information
*/
ngOnInit(): void {
this.userService.getCurrentUser().subscribe(user => this.username = user.username)
}
/**
* function used to update current user's password. Will only work if both passwords inputted are the same
*/
updatePassword(){
if(this.password1 === this.password2){
this.userService.resetPassword(this.password1).subscribe((result) => {
this.successfulUpdate = true;
setTimeout(() => this.goBack(),3000)
})
} else {
this.passwordMatch = false;
}
}
/**
* private function used by updatePassword to go back to the my profile page after the password is successfully changed
*/
goBack(){
this.router.navigateByUrl("/profile")
}
}
<file_sep>/Microblogging/src/app/components/follow-button/follow-button.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { User } from 'src/app/models/user';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-follow-button',
templateUrl: './follow-button.component.html',
styleUrls: ['./follow-button.component.css']
})
export class FollowButtonComponent implements OnInit {
@Input() user: User | undefined;
showButton: boolean = true;
showFollow: boolean = false;
constructor(private userService: UserService) { }
ngOnInit() {
this.userService.getCurrentUser().subscribe(
(currentUser) => {
this.showButton = !(currentUser.id == this.user?.id);
}
)
this.userService.getFollowing().subscribe(
(following: User[]) => {
this.showFollow = !this.userService.isUserFollowed(this.user!, following);
}
)
}
followUser(){
this.userService.followUser(this.user!).subscribe(
(result) => {
console.log(result);
this.showFollow = false;
}
);
}
unFollowUser(){
this.userService.unFollowUser(this.user!).subscribe(
(result) => {
console.log(result);
this.showFollow = true;
}
);
}
}
<file_sep>/Microblogging/src/app/services/user.service.spec.ts
import { getTestBed, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { UserService } from './user.service';
import { User, UserAdapter } from '../user';
import { environment } from '../../environments/environment';
describe('UserService', () => {
let service: UserService;
let injector: TestBed;
let httpMock: HttpTestingController;
const dummyUser: User = {
id: 1,
firstName: "Test",
lastName: "McGee",
username: "test",
trainer: false,
topics: [],
curricula: [],
ownedCurricula: [],
modules: []
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [UserService]
});
injector = getTestBed();
service = injector.inject(UserService);
httpMock = injector.inject(HttpTestingController);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should return a User when registerNewUser() is called', () => {
let dummyUserInput: User & {password?: string} = dummyUser;
dummyUserInput.password = "<PASSWORD>";
service.registerNewUser(dummyUserInput).subscribe((user) => {
expect(user.id).toEqual(dummyUser.id);
expect(user.username).toEqual(dummyUser.username);
});
const request = httpMock.expectOne(`${environment.revAssureBase}revuser/register`);
expect(request.request.method).toBe('POST');
request.flush(dummyUser);
});
it('should return a JSON with a jwt and cache a User object when login() is called', () => {
const dummyJwt: any = {
jwt: "thisIsAJwt"
}
const dummyUsername: string = dummyUser.username;
const dummyPassword: string = "<PASSWORD>";
service.login(dummyUsername, dummyPassword).subscribe((jwt: any) => {
expect(jwt.jwt).toEqual(dummyJwt.jwt);
expect(service.getFirstName()).toEqual(dummyUser.firstName);
expect(service.getLastName()).toEqual(dummyUser.lastName);
});
const request = httpMock.expectOne(`${environment.revAssureBase}revuser/authenticate`);
expect(request.request.method).toBe('POST');
request.flush(dummyJwt);
const request2 = httpMock.expectOne(`${environment.revAssureBase}revuser`);
expect(request2.request.method).toBe('GET');
request2.flush(dummyUser);
});
afterEach(() => {
httpMock.verify();
});
});<file_sep>/Microblogging/src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EditPasswordComponent } from './components/edit-password/edit-password.component';
import { EditProfileComponent } from './components/edit-profile/edit-profile.component';
import { FollowingComponent } from './components/following/following.component';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { LoginComponent } from './components/login/login.component';
import { MainPageComponent } from './components/main-page/main-page.component';
import { MyFollowersComponent } from './components/my-followers/my-followers.component';
import { ProfilePageComponent } from './components/profile-page/profile-page.component';
import { RegisterComponent } from './components/register/register.component';
import { SearchUsersComponent } from './components/search-users/search-users.component';
const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch:'full' },
{ path: 'login', component: LoginComponent },
{ path: 'forgot', component: ForgotPasswordComponent },
{ path: 'register', component: RegisterComponent },
{ path: 'home', component: MainPageComponent },
{ path: 'profile', component: ProfilePageComponent },
{ path: 'my-followers', component: MyFollowersComponent },
{ path: 'following', component: FollowingComponent },
{ path: 'edit-profile', component: EditProfileComponent },
{ path: 'edit-password', component: EditPasswordComponent },
{ path: 'search-users', component: SearchUsersComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload'})],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/Microblogging/src/app/services/micro.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { convertToObject } from 'typescript';
import { Micro } from '../models/micro';
import { User } from '../models/user';
import { AuthorizationService } from './authorization.service';
import { UserService } from './user.service';
@Injectable({
providedIn: 'root'
})
export class MicroService {
constructor(private http: HttpClient, private authService: AuthorizationService, private userService: UserService) { }
/**
* backend url endpoint for service calls
*/
url = "http://localhost:8082/micro";
/**
* http header to pass in jwt for authorization
*/
httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
"Authorization": ""
})
};
/**
* Get all micros of current user logged in and other users followed
* @returns get method call to the back end
*/
getMicros(): Observable<Micro[]>{
this.httpOptions.headers = this.httpOptions.headers.set('Authorization', `Bearer ${this.authService.jwt}`);
return this.http.get<Micro[]>(this.url, this.httpOptions)
}
/**
* call a post method to the backend with jwt of current user and
* new content for a micro to be persisted in the backend
* @param currentUser the current user logged in
* @param newContent the content of the new micro(post) to be created
* @returns a post method call to the backend with newMicro object
*/
createMicro(currentUser: User, newContent: string): Observable<Micro> {
let newMicro = {
id: 0,
content: newContent,
user: currentUser.id
}
this.httpOptions.headers = this.httpOptions.headers.set('Authorization', `Bearer ${this.authService.jwt}`);
return this.http.post<Micro>(this.url, newMicro, this.httpOptions)
}
}
<file_sep>/Microblogging/src/app/components/main-page/main-page.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Micro } from 'src/app/models/micro';
import { User } from 'src/app/models/user';
import { MicroService } from 'src/app/services/micro.service';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-main-page',
templateUrl: './main-page.component.html',
styleUrls: ['./main-page.component.css']
})
export class MainPageComponent implements OnInit {
content: string;
micros: Micro[] = [];
user: User = {
id: 0,
username: "",
firstName: "",
lastName: "",
imageURL: "",
about: ""
};
// msg: string;
// url: any;
imageURL: string;
constructor(private router : Router, private modalService: NgbModal, private userService: UserService, private microService: MicroService) { }
// selectFile(event: any) {
// if(!event.target.files[0] || event.target.files[0].length == 0) {
// this.msg = 'You must select an image';
// return;
// }
// var mimeType = event.target.files[0].type;
// if (mimeType.match(/image\/*/) == null) {
// this.msg = "Only images are supported";
// return;
// }
// var reader = new FileReader();
// reader.readAsDataURL(event.target.files[0]);
// reader.onload = (_event) => {
// this.msg = "";
// this.url = reader.result;
// }
// }
/**
* call service funtions to get the current user logged in and all micros(posts)
* of that user and other users followed
*/
ngOnInit() {
this.microService.getMicros().subscribe(result => this.micros = result.reverse());
this.userService.getCurrentUser().subscribe(result => this.user = result);
}
/**
* function to reload the current component
*/
reloadComponent() {
let currentUrl = this.router.url;
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.onSameUrlNavigation = 'reload';
this.router.navigate([currentUrl]);
}
/**
* Open up a specific modal
* @param content the modal to open up
*/
open(content: any) {
this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'});
}
/**
* Function to create a micro(post)
*/
createMicro() {
console.log(this.content);
this.microService.createMicro(this.user, this.content).subscribe();
this.modalService.dismissAll();
this.reloadComponent();
}
/**
* Function to update the profile image of the user
*/
changeImage() {
this.user.imageURL = this.imageURL;
this.userService.updateUser(this.user).subscribe();
this.modalService.dismissAll();
this.reloadComponent();
}
}
<file_sep>/Microblogging/src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { LoginComponent } from './components/login/login.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RegisterComponent } from './components/register/register.component';
import { MainPageComponent } from './components/main-page/main-page.component';
import { ProfilePageComponent } from './components/profile-page/profile-page.component';
import { FollowingComponent } from './components/following/following.component';
import { MyFollowersComponent } from './components/my-followers/my-followers.component';
import { EditProfileComponent } from './components/edit-profile/edit-profile.component';
import { FollowButtonComponent } from './components/follow-button/follow-button.component';
import { SearchUsersComponent } from './components/search-users/search-users.component';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { EditPasswordComponent } from './components/edit-password/edit-password.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
NavbarComponent,
RegisterComponent,
FollowingComponent,
MainPageComponent,
MyFollowersComponent,
ProfilePageComponent,
EditProfileComponent,
FollowButtonComponent,
ForgotPasswordComponent,
EditPasswordComponent,
SearchUsersComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule,
FormsModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/Microblogging/src/app/services/authorization.service.ts
import { Injectable } from '@angular/core';
/**
* The AuthorizationService is used to store a logged in user's JSON Web Token (JWT).
* The JWT is set upon login and is used to authorize all future requests.
* Inject AuthorizationService into other services through their constructors to make
* valid web requests to the back-end.
*/
@Injectable({
providedIn: 'root'
})
export class AuthorizationService {
constructor() { }
/**
* String property that can be accessed to get the JWT for current user.
*/
jwt: string = "";
/**
* Sets the JWT to be stored in the front-end. This token is needed for all
* requests besides user registration and login.
* @param authObject - JSON object containing the JWT
*/
setJwt(authObject: any) {
this.jwt = authObject.jwt
}
}
<file_sep>/Microblogging/src/app/components/edit-profile/edit-profile.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { User } from 'src/app/models/user';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-edit-profile',
templateUrl: './edit-profile.component.html',
styleUrls: ['./edit-profile.component.css']
})
export class EditProfileComponent implements OnInit {
constructor(private userService : UserService,
private router : Router) { }
username: string = '';
about: string = '';
imageURL: string = '';
currentUser : User | undefined;
successfulUpdate : boolean = false;
/**
* gets current user to populate page
*/
ngOnInit(): void {
this.userService.getCurrentUser().subscribe((user) => {
this.currentUser = user
this.username = user.username
this.about = user.about
this.imageURL = user.imageURL
});
}
/**
* function used to update current user with what they replaced the values with on the page
*/
updateProfile(){
this.currentUser!.about = this.about;
this.currentUser!.imageURL = this.imageURL;
this.userService.updateUser(this.currentUser).subscribe( (result) => {
this.successfulUpdate = true;
setTimeout(() => this.goBack(), 3000)
})
}
/**
* private function used in updateProfile() to go to my profile page after the user is updated
*/
private goBack(){
this.router.navigateByUrl("/profile");
}
}
<file_sep>/Microblogging/src/app/components/my-followers/my-followers.component.ts
import { Component, OnInit } from '@angular/core';
import { User } from 'src/app/models/user';
import { AuthorizationService } from 'src/app/services/authorization.service';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-my-followers',
templateUrl: './my-followers.component.html',
styleUrls: ['./my-followers.component.css']
})
export class MyFollowersComponent implements OnInit {
followers: User[] = [];
constructor(private authService: AuthorizationService, private userService: UserService) { }
ngOnInit() {
this.userService.getFollowers().subscribe(
(result) => {
this.followers = result;
}
)
}
}
<file_sep>/Microblogging/src/app/models/micro.ts
import { Injectable } from '@angular/core';
import { User } from './user';
// import { Adapter } from './adapter';
export class Micro {
constructor(
public id: number,
public content: string,
public user: User
){}
}<file_sep>/README.md
# Microblogging FE
<file_sep>/Microblogging/src/app/components/forgot-password/forgot-password.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthorizationService } from 'src/app/services/authorization.service';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-forgot-password',
templateUrl: './forgot-password.component.html',
styleUrls: ['./forgot-password.component.css']
})
export class ForgotPasswordComponent implements OnInit {
constructor(private userService: UserService, private router: Router, private authService: AuthorizationService) { }
ngOnInit(): void {
}
username: string = "";
password: string = "";
usernameNotFound: boolean = false;
usernameFound: boolean = false;
successfulUpdate: boolean = false;
/**
* make sure a matching user exists
* if one doesn't, trigger error message div
*/
findUser()
{
this.usernameNotFound = false;
this.usernameFound = false;
this.userService.getSpecificUser(this.username).subscribe((result) =>
{
this.authService.setJwt(result);
this.usernameFound = true;
},
(error) =>
{
console.log(console.error());
this.usernameNotFound = true;
});
}
/**
* changes the password
* tells the service to make an http request
* if successful, redirect to login page
*/
resetPassword()
{
let returnedUser;
this.userService.resetPassword(this.password).subscribe((result) =>
{
returnedUser = result
console.log(returnedUser);
this.authService.setJwt("");
this.successfulUpdate = true;
// redirect to login page after 3 seconds
setTimeout(() => {
this.router.navigateByUrl("/login");
}, 3000);
},
(error) =>
{
console.log(console.error());
});
}
}
<file_sep>/Microblogging/src/app/models/user.ts
import { Injectable } from '@angular/core';
// import { Adapter } from './adapter';
export class User {
constructor(
public id: number,
public username: string,
public firstName: string,
public lastName: string,
public imageURL: string,
public about: string
){}
}
// @Injectable({
// providedIn: 'root',
// })
// export class UserAdapter {
// /**
// * Converts DTO into User object.
// * @param microUser: DTO of User.
// * @returns User
// */
// adapt(microUser:any):User{
// return new User(
// microUser.id,
// microUser.username,
// microUser.firstname,
// microUser.lastname,
// microUser.image,
// microUser.about,
// )
// }
// } | 4073d3c9028d282ec6b3e32d59ca17817e9d66b3 | [
"Markdown",
"TypeScript"
] | 18 | TypeScript | jtlin226/Microblogging_FE | 65c8899c2f755a6af83708518406fba96b13ce65 | 863d494d5a79b25dd2b7b6aa3b5e9f651574ecb4 |
refs/heads/master | <repo_name>jeel279/thon4<file_sep>/app/src/main/java/local/host/thon/GraphView.kt
package local.host.thon
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class GraphView(Type:String,Data:HashMap<Any,Any>) : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}<file_sep>/app/src/main/java/local/host/thon/test.kt
package local.host.thon
import org.json.JSONObject
import java.net.URL
import java.text.SimpleDateFormat
import java.util.*
fun Date.formatTo(dateFormat: String, timeZone: TimeZone = TimeZone.getDefault()): String {
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
formatter.timeZone = timeZone
return formatter.format(this)
}
fun main(args : Array<String>){
// val publicIP = (URL("http://www.checkip.org").readText().split("<span style=\"color: #5d9bD3;\">")[1]).split("</span>")[0]
// val location = JSONObject(URL("http://api.ipstack.com/$publicIP?access_key=d8d57e041b8d5da9101ba4fbde602b6b").readText());
// val dt = JSONObject(URL("https://api.sunrise-sunset.org/json?lat=${location["latitude"]}&lng=${location["longitude"]}").readText())
// print("https://api.sunrise-sunset.org/json?lat=${location["latitude"]}&lng=${location["longitude"]}");
}<file_sep>/app/src/main/java/local/host/thon/Estimate.kt
package local.host.thon
import android.annotation.SuppressLint
import android.content.DialogInterface
import android.os.Bundle
import android.os.StrictMode
import android.util.Log
import android.view.LayoutInflater
import android.view.TextureView
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.button.MaterialButton
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputEditText
import org.json.JSONArray
import org.json.JSONObject
import java.lang.Exception
import java.util.*
class Estimate : Fragment() {
@SuppressLint("SetTextI18n")
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
super.onCreate(savedInstanceState)
val view = inflater.inflate(R.layout.estimate, container, false)
val btn1 = view.findViewById<MaterialButton>(R.id.cal_btn1)
val pre1 = view.findViewById<TextView>(R.id.cal1)
val queue = Volley.newRequestQueue(view.context)
val stringRequest = StringRequest(
Request.Method.GET, "${addr}/ave",
{ response ->
view.findViewById<CardView>(R.id.est1).visibility = View.VISIBLE
val an = (JSONArray(response)[0]) as JSONObject
val avg_units = an["4*unit/ID "].toString().toFloat();
pre1.text = avg_units.toString()
val ans = arrayOf(view.findViewById<TextView>(R.id.ans1),view.findViewById<TextView>(R.id.ans2),view.findViewById<TextView>(R.id.ans3))
ans[0].text = "2"
view.findViewById<TextView>(R.id.ans0).text = "7"
btn1.setOnClickListener {
val x = view.findViewById<TextInputEditText>(R.id.inp1)
try{
val k = x.text.toString().toFloat()
if(pre1.text.toString().toFloat()>=k){
val m = (k*7F*30F + (avg_units - x.text.toString().toFloat()) * 30F * 2F)
val st = m.toString().split('.')
ans[1].text = st[0] +"."+ st[1].subSequence(0,2)
ans[2].text = (30000F/m).toInt().toString()
view.findViewById<CardView>(R.id.est3).visibility = View.VISIBLE
view.findViewById<TextView>(R.id.h1).text = "Monthly Earning (approx)"
view.findViewById<TextView>(R.id.h2).text = "ETRI"
}else{
view.findViewById<TextView>(R.id.h1).text = "Estimated Bill"
view.findViewById<TextView>(R.id.h2).text = "Saved Amount"
val m = (x.text.toString().toFloat() - avg_units)*7F*30F
val st = m.toString().split('.')
ans[1].text = st[0] +"."+ st[1].subSequence(0,2)
val km = (avg_units*7F*30F).toString().split('.')
ans[2].text = km[0] + "." + km[1].subSequence(0,2)
view.findViewById<CardView>(R.id.est3).visibility = View.VISIBLE
}
}catch (e : Exception){
MaterialAlertDialogBuilder(view.context)
.setTitle("Empty Input")
.setCancelable(true)
.setMessage("Please enter value in given field.")
.setNegativeButton("Close"){d,k->
d.dismiss()
}
.show()
}
}
},{})
queue.add(stringRequest)
return view;
}
}<file_sep>/app/src/main/java/local/host/thon/mysql_connector.kt
package local.host.thon;
import android.annotation.SuppressLint
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.lang.Exception
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
@SuppressLint("SimpleDateFormat")
fun main(): Unit = runBlocking{
val dateFormat: DateFormat = SimpleDateFormat("yyyy/MM/dd")
val dt = Date(dateFormat.format(Date()) + " 6:00 AM");
// launch {
// try {
// // The newInstance() call is a work around for some
// // broken Java implementations
// Class.forName("com.mysql.cj.jdbc.Driver").newInstance()
// val conn =
// DriverManager.getConnection("jdbc:mysql://remotemysql.com/WKTDxt18Em?user=WKTDxt18Em&password=<PASSWORD>");
// val st = conn.createStatement()
// val kt = st.executeQuery("select * from dataSet")
// while (kt.next()) println(kt.getInt(1))
// } catch (ex: Exception) {
// print(ex)
// }
// }
}
<file_sep>/app/src/main/java/local/host/thon/MainActivity.kt
package local.host.thon
import android.annotation.SuppressLint
import android.content.res.Resources
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy
import android.view.View
import android.widget.*
import androidx.cardview.widget.CardView
import androidx.core.text.HtmlCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import org.json.JSONObject
import java.lang.Exception
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
import androidx.annotation.NonNull
import android.media.MediaPlayer
import android.util.Log
import org.json.JSONArray
val addr = "https://27c8a621751a.ngrok.io";
class MainActivity : AppCompatActivity() {
var active: Fragment? = null;
var pev : Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragment1: Fragment = Home()
val fragment = arrayOf(Home(),Summary(),Estimate(),Profile())
val fragment4: Fragment = Profile()
val fm: FragmentManager = supportFragmentManager
active = fragment[0]
fm.beginTransaction().add(R.id.main_container, fragment[3], "4").hide(fragment[3]).commit();
fm.beginTransaction().add(R.id.main_container, fragment[2], "3").hide(fragment[2]).commit();
fm.beginTransaction().add(R.id.main_container, fragment[1], "2").hide(fragment[1]).commit();
fm.beginTransaction().add(R.id.main_container,fragment[0], "1").commit();
val bottomNav = findViewById<BottomNavigationView>(R.id.bottom_navigation)
bottomNav.setOnNavigationItemSelectedListener{ item ->
when (item.itemId) {
R.id.nav_home -> {
fm.beginTransaction().hide(active!!).show(fragment[0]).commit()
active = fragment[0]
return@setOnNavigationItemSelectedListener true
}
R.id.nav_summary -> {
fm.beginTransaction().hide(active!!).show(fragment[1]).commit()
active = fragment[1]
return@setOnNavigationItemSelectedListener true
}
R.id.nav_estimate -> {
fm.beginTransaction().hide(active!!).show(fragment[2]).commit()
active = fragment[2]
return@setOnNavigationItemSelectedListener true
}
R.id.nav_profile -> {
fm.beginTransaction().hide(active!!).show(fragment[3]).commit()
active = fragment[3]
return@setOnNavigationItemSelectedListener true
}
else -> {
return@setOnNavigationItemSelectedListener false
}
}
}
}
}<file_sep>/app/src/main/java/local/host/thon/Home.kt
package local.host.thon
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.StrictMode
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.cardview.widget.CardView
import androidx.core.text.HtmlCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.button.MaterialButton
import com.google.android.material.card.MaterialCardView
import com.google.android.material.snackbar.Snackbar
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import org.json.JSONObject
import java.lang.Exception
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.floor
import org.json.JSONArray
import java.lang.reflect.Array
var curGenT : Long? = null
class Home : Fragment() {
@SuppressLint("SetTextI18n", "SimpleDateFormat", "CutPasteId")
private fun checkWeather(view : View){
val queue = Volley.newRequestQueue(view.context)
val url = "http://checkip.dyndns.com"
// Request a string response from the provided URL.
val stringRequest = StringRequest(
Request.Method.GET, url,
{ response ->
val publicIP =
response.split(": ")[1].split("<")[0]
Log.d("A",publicIP)
val url2 =
"http://api.ipstack.com/$publicIP?access_key=d8d57e041b8d5da9101ba4fbde602b6b"
val stringRequest2 = StringRequest(
Request.Method.GET, url2,
{ responseA ->
val location = JSONObject(responseA)
val url3 = "http://api.weatherapi.com/v1/current.json?key=<KEY>&q=${location["latitude"]},${location["longitude"]}&aqi=no"
val url4 = "https://api.sunrise-sunset.org/json?lat=${location["latitude"]}&lng=${location["longitude"]}"
val stringRequest31 = StringRequest(
Request.Method.GET, url4,
{ responseB1 ->
val obj = JSONObject(responseB1)
val k = obj["results"] as JSONObject
val dateFormat: DateFormat = SimpleDateFormat("dd/MM/yyyy")
val dateFormatA: DateFormat = SimpleDateFormat("h:mm")
val date = Date()
val dtn = Date(dateFormat.format(date) + " ${k["sunrise"]}")
val dtn2 = Date(dateFormat.format(date) + " ${k["sunset"]}")
// Log.d("K",dtn.time.toString())
val nsr = Date(dtn.time + 330*60000)
view.findViewById<TextView>(R.id.sunrise_time).text = HtmlCompat.fromHtml("<b>Sunrise</b><br>${dateFormatA.format(nsr)}",
HtmlCompat.FROM_HTML_MODE_COMPACT)
view.findViewById<ProgressBar>(R.id.sunrise_loader).visibility = View.GONE
view.findViewById<TextView>(R.id.sunrise_time).visibility = View.VISIBLE
val nss = Date(dtn2.time + 330*60000)
view.findViewById<TextView>(R.id.sunset_time).text = HtmlCompat.fromHtml("<b>Sunset</b><br>${dateFormatA.format(nss)}",
HtmlCompat.FROM_HTML_MODE_COMPACT)
view.findViewById<ProgressBar>(R.id.sunset_loader).visibility = View.GONE
view.findViewById<TextView>(R.id.sunset_time).visibility = View.VISIBLE
// Toast.makeText(this,Date(dateFormat.format(date) + " " +k["sunrise"].toString()).toLocaleString(),Toast.LENGTH_SHORT).show()
},{})
val stringRequest3 = StringRequest(
Request.Method.GET, url3,
{ responseB ->
val dt = JSONObject(responseB)
val jobj = ((dt["current"] as JSONObject)["condition"] as JSONObject)
val dtp = arrayOf("${(dt["current"] as JSONObject)["temp_c"]}","${jobj["text"]}")
Picasso.get()
.load("https:${jobj["icon"]}")
.into(view.findViewById(R.id.curTempImg), object : Callback {
@SuppressLint("SetTextI18n")
override fun onSuccess() {
view.findViewById<TextView>(R.id.temp_curr).text = dtp[0].toFloat().toInt().toString() + "°C"
view.findViewById<TextView>(R.id.temp_stat).text = dtp[1]
view.findViewById<TextView>(R.id.hum_data).text = HtmlCompat.fromHtml("<b>Humidity</b><br>${(dt["current"] as JSONObject)["humidity"]}",
HtmlCompat.FROM_HTML_MODE_COMPACT)
view.findViewById<TextView>(R.id.uv_text).text = HtmlCompat.fromHtml("<b>UV Index</b><br>${(dt["current"] as JSONObject)["uv"]}",
HtmlCompat.FROM_HTML_MODE_COMPACT)
view.findViewById<TextView>(R.id.hum_data).visibility = View.VISIBLE
view.findViewById<TextView>(R.id.uv_text).visibility = View.VISIBLE
view.findViewById<ProgressBar>(R.id.hum_loader).visibility = View.GONE
view.findViewById<ProgressBar>(R.id.uv_loader).visibility = View.GONE
view.findViewById<ProgressBar>(R.id.loaderWeather).visibility = View.GONE
view.findViewById<LinearLayout>(R.id.loadedWeather).visibility = View.VISIBLE
}
override fun onError(e: Exception?) {
Toast.makeText(view.context,"Internet is off :( ",
Toast.LENGTH_SHORT).show()
}
})
}, {Toast.makeText(view.context,"Internet is off :( ",
Toast.LENGTH_SHORT).show()})
queue.add(stringRequest31)
queue.add(stringRequest3)
// Display the first 500 characters of the response string.
},
{
Toast.makeText(view.context,"Internet is off :( ",
Toast.LENGTH_SHORT).show()
})
queue.add(stringRequest2)
},{Log.d("ABC",it.toString())})
// Add the request to the RequestQueue.
queue.add(stringRequest)
}
private fun timeSince() : String {
val seconds = floor(((Date().time - curGenT!!).toDouble() / 1000F));
var interval : Double = seconds / 31536000F;
if (interval > 1) {
return floor(interval).toInt().toString() + " years ago";
}
interval = seconds / 2592000;
if (interval > 1) {
return floor(interval).toInt().toString() + " months ago";
}
interval = seconds / 86400;
if (interval > 1) {
return floor(interval).toInt().toString() + " days ago";
}
interval = seconds / 3600;
if (interval > 1) {
return floor(interval).toInt().toString() + " hours ago";
}
interval = seconds / 60;
if (interval > 1) {
return floor(interval).toInt().toString() + " minutes ago";
}
return "just now";
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
super.onCreate(savedInstanceState)
val view = inflater.inflate(R.layout.home, container, false)
container!!
// val publicIP = (URL("http://www.checkip.org").readText().split("<span style=\"color: #5d9bD3;\">")[1]).split("</span>")[0]
// val location = JSONObject(URL("http://api.ipstack.com/$publicIP?access_key=d8d57e041b8d5da9101ba4fbde602b6b").readText())
// val dt = JSONObject(URL("http://api.weatherapi.com/v1/current.json?key=<KEY>&q=${location["latitude"]},${location["longitude"]}&aqi=no").readText())
// Log.d("K","https://api.sunrise-sunset.org/json?lat=${location["latitude"]}&lng=${location["longitude"]}");
// var dtp = Date().formatTo("yyyy-MM-dd")
checkWeather(view)
val curUnCard = view.findViewById<MaterialCardView>(R.id.curr_unit_card)
val curUnPrg = view.findViewById<ProgressBar>(R.id.updt_curGen_prg)
val lastcurr = view.findViewById<TextView>(R.id.curr_last_updated)
val unVal = view.findViewById<TextView>(R.id.curr_unit_gen)
curGenT = Date().time
val dateFormatB: DateFormat = SimpleDateFormat("yyyy-MM-dd")
val queue = Volley.newRequestQueue(view.context)
val dateFormat: DateFormat = SimpleDateFormat("yyyy/MM/dd")
val dt = Date(dateFormat.format(Date()) + " 6:00 AM");
val ar = arrayOf(Date(dt.time+0),Date(dt.time+14400000L),Date(dt.time+(2*14400000L)),Date(dt.time+(3*14400000L)),Date(dt.time+(4*14400000)));
// Request a string response from the provided URL.
val slts = arrayOf<MaterialButton>(view.findViewById(R.id.slt1),view.findViewById(R.id.slt2),view.findViewById(R.id.slt3),view.findViewById(R.id.slt4))
val crd = view.findViewById<TextView>(R.id.tot_unit_gen)
val prg2 = view.findViewById<ProgressBar>(R.id.tot_curGen_prg)
val stringRequest = StringRequest(
Request.Method.GET, "${addr}/gen/${dateFormatB.format(Date())}",
{ response ->
curUnPrg.visibility = View.GONE
lastcurr.visibility = View.VISIBLE
unVal.visibility = View.VISIBLE
val a = JSONArray(response)
val lastDayFinal = ((a[2] as JSONArray)[0] as JSONObject)["lastDayFinal"].toString().toInt()
val k = a[3] as JSONArray;
val am = arrayOf((k[0] as JSONObject)["unit"].toString().toInt(),(k[1] as JSONObject)["unit"].toString().toInt(),(k[2] as JSONObject)["unit"].toString().toInt(),(k[3] as JSONObject)["unit"].toString().toInt())
var tot = 0;
if(ar[1].time <=Date().time){
slts[0].text = (am[0] - lastDayFinal).toString()
tot+=(am[0] - lastDayFinal);
}
if(ar[2].time <=Date().time){
slts[1].text = (am[1] - am[0]).toString()
tot+=(am[1] - am[0])
}
if(ar[3].time <= Date().time){
slts[2].text = (am[2] - am[1]).toString()
tot+=am[2] - am[1]
}
if(ar[4].time <= Date().time){
slts[3].text = (am[3] - am[2]).toString()
tot+=am[3] - am[2]
}
unVal.text = tot.toString()
crd.text = (lastDayFinal+tot).toString()
prg2.visibility = View.GONE
crd.visibility = View.VISIBLE
view.findViewById<ProgressBar>(R.id.expt_curGen_prg).visibility = View.GONE
view.findViewById<TextView>(R.id.expt_unit_gen).visibility = View.VISIBLE
},{err->Snackbar.make(view,err.toString(),Snackbar.LENGTH_SHORT).show()})
queue.add(stringRequest)
curUnCard.setOnClickListener {
curUnPrg.visibility = View.VISIBLE
lastcurr.visibility = View.GONE
unVal.visibility = View.GONE
val stringRequestK = StringRequest(
Request.Method.GET, "${addr}/gen/${dateFormatB.format(Date())}",
{ response ->
curUnPrg.visibility = View.GONE
crd.visibility = View.GONE
lastcurr.visibility = View.VISIBLE
unVal.visibility = View.VISIBLE
val a = JSONArray(response)
val lastDayFinal = ((a[2] as JSONArray)[0] as JSONObject)["lastDayFinal"].toString().toInt()
val k = a[3] as JSONArray;
val am = arrayOf((k[0] as JSONObject)["unit"].toString().toInt(),(k[1] as JSONObject)["unit"].toString().toInt(),(k[2] as JSONObject)["unit"].toString().toInt(),(k[3] as JSONObject)["unit"].toString().toInt())
var tot = 0;
if(ar[1].time <=Date().time){
slts[0].text = (am[0] - lastDayFinal).toString()
tot+=(am[0] - lastDayFinal);
}
if(ar[2].time <=Date().time){
slts[1].text = (am[1] - am[0]).toString()
tot+=(am[1] - am[0])
}
if(ar[3].time <= Date().time){
slts[2].text = (am[2] - am[1]).toString()
tot+=am[2] - am[1]
}
if(ar[4].time <= Date().time){
slts[3].text = (am[3] - am[2]).toString()
tot+=am[3] - am[2]
}
unVal.text = tot.toString()
crd.text = (lastDayFinal+tot).toString()
prg2.visibility = View.GONE
crd.visibility = View.VISIBLE
view.findViewById<ProgressBar>(R.id.expt_curGen_prg).visibility = View.GONE
view.findViewById<TextView>(R.id.expt_unit_gen).visibility = View.VISIBLE
Snackbar.make(view,"Current Generation Updated",Snackbar.LENGTH_SHORT).show()
},{err->Snackbar.make(view,err.toString(),Snackbar.LENGTH_SHORT).show()})
queue.add(stringRequestK)
}
view.findViewById<CardView>(R.id.weather_card).setOnClickListener {
view.findViewById<LinearLayout>(R.id.loadedWeather).visibility = View.GONE
view.findViewById<ProgressBar>(R.id.loaderWeather).visibility = View.VISIBLE
checkWeather(view)
}
val mainHandler = Handler(Looper.getMainLooper())
mainHandler.post(object : Runnable {
override fun run() {
lastcurr.text = "updated " + timeSince();
mainHandler.postDelayed(this, 1000)
}
})
return view
}
}<file_sep>/app/src/main/java/local/host/thon/Summary.kt
package local.host.thon
import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.os.StrictMode
import android.util.DisplayMetrics
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.android.material.button.MaterialButton
import com.google.android.material.card.MaterialCardView
import com.google.android.material.chip.Chip
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import org.eazegraph.lib.charts.BarChart
import org.eazegraph.lib.charts.ValueLineChart
import org.eazegraph.lib.models.BarModel
import org.eazegraph.lib.models.ValueLinePoint
import org.eazegraph.lib.models.ValueLineSeries
import org.json.JSONArray
import org.json.JSONObject
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.LinkedHashMap
import android.widget.ArrayAdapter
class Summary : Fragment() {
@SuppressLint("InflateParams")
private fun showQuick(view : View, peak : Pair<Int,ArrayList<String>>, nadir : Pair<Int,ArrayList<String>>){
val infl = layoutInflater.inflate(R.layout.quick_data,null)
val cls = infl.findViewById<ImageView>(R.id.clsD)
val rdb = view.findViewById<RadioGroup>(R.id.one)
val listView = arrayListOf<ListView>(infl.findViewById(R.id.maxP),infl.findViewById(R.id.minP))
val adapter: ArrayAdapter<String> = ArrayAdapter<String>(
view.context,R.layout.tv, R.id.k, peak.second
)
val adapter2: ArrayAdapter<String> = ArrayAdapter<String>(
view.context,R.layout.tv, R.id.k, nadir.second
)
listView[0].adapter = adapter
listView[1].adapter = adapter2
infl.findViewById<TextView>(R.id.maxU).text = peak.first.toString()
infl.findViewById<TextView>(R.id.minU).text = nadir.first.toString()
infl.findViewById<TextView>(R.id.itC1).text = peak.second.size.toString()
infl.findViewById<TextView>(R.id.itC2).text = nadir.second.size.toString()
val mV = MaterialAlertDialogBuilder(view.context)
.setView(infl)
.setCancelable(true)
.create()
cls.setOnClickListener {
mV.cancel()
}
mV.show()
}
private fun resetGrp(view : View){
val btns = arrayOf<Chip>(view.findViewById(R.id.barMode),view.findViewById(R.id.LineMode))
btns[0].isChecked = true
btns[1].isChecked = false
}
@SuppressLint("SetTextI18n", "SimpleDateFormat", "SetJavaScriptEnabled", "CutPasteId")
private fun createGraph(days : Int,view : View){
resetGrp(view);
val pr = view.findViewById<LinearLayout>(R.id.graphCanvas)
val dateFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd")
val ftt = Date()
val cal = Calendar.getInstance()
cal.add(Calendar.DATE, -1)
val dt = dateFormat.format(cal.time);
val c = Calendar.getInstance()
c.add(Calendar.DATE,-1)
c.time = ftt
var dayOfWeek = c[Calendar.DAY_OF_WEEK]
val week = arrayOf("","Sun","Mon","Tue","Wed","Thu","Fri","Sat");
println("Day of week in number:$dayOfWeek")
val dayWeekText = SimpleDateFormat("E").format(ftt)
println("Day of week in text:$dayWeekText")
val queue = Volley.newRequestQueue(view.context)
val url = "${addr}/graph/${dt},${days}"
view.findViewById<MaterialCardView>(R.id.graphCard).visibility = View.VISIBLE
view.findViewById<ProgressBar>(R.id.grph_load).visibility = View.VISIBLE
view.findViewById<GridLayout>(R.id.graphMode).visibility = View.GONE
val tmp = cal
val btnA = view.findViewById<Chip>(R.id.get_data)
var max = Int.MIN_VALUE;
var min = Int.MAX_VALUE
val listMax = ArrayList<String>();
val listMin = ArrayList<String>();
tmp.add(Calendar.DATE,-1*days + 1);
val cFm = SimpleDateFormat("E MMM d, yyyy")
when(days) {
7 -> {
val stringRequest = StringRequest(
Request.Method.GET, url,
{ response ->
val mBarChart = BarChart(view.context)
val mLineChart = ValueLineChart(view.context)
val series = ValueLineSeries()
series.setColor(view.context.resources.getColor(R.color.light_red,null));
val ll =
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 512)
var daydt = 0;
val arr = JSONArray(response)
for (i in 0 until days) {
dayOfWeek--;
if (dayOfWeek == 0) dayOfWeek = 7
}
for (i in 1 until arr.length()) {
val m = arr[i] as JSONObject;
val n = arr[i - 1] as JSONObject;
daydt = m["unit"].toString().toInt() - n["unit"].toString().toInt()
if(daydt>max){
listMax.clear()
max=daydt
}
if(daydt==max){
listMax.add(cFm.format(tmp.time))
}
if(daydt<min){
listMin.clear()
min=daydt
}
if(daydt==min){
listMin.add(cFm.format(tmp.time))
}
tmp.add(Calendar.DATE,1)
mBarChart.addBar(BarModel(week[dayOfWeek], daydt.toFloat(), view.context.resources.getColor(R.color.light_red,null)))
series.addPoint(ValueLinePoint(week[dayOfWeek], daydt.toFloat()))
if (dayOfWeek == 7) dayOfWeek = 1;
else dayOfWeek++;
}
view.findViewById<ProgressBar>(R.id.grph_load).visibility = View.GONE
view.findViewById<GridLayout>(R.id.graphMode).visibility = View.VISIBLE
mBarChart.layoutParams = ll
mLineChart.layoutParams = ll
mLineChart.visibility = View.GONE
mLineChart.addSeries(series);
pr.addView(mBarChart)
pr.addView(mLineChart)
mBarChart.startAnimation()
view.findViewById<Chip>(R.id.barMode).isChecked = true
view.findViewById<Chip>(R.id.barMode).setOnClickListener {
mLineChart.visibility = View.GONE
mBarChart.visibility = View.VISIBLE
mBarChart.startAnimation()
view.findViewById<Chip>(R.id.LineMode).isChecked = false
}
view.findViewById<Chip>(R.id.LineMode).setOnClickListener{
mBarChart.visibility = View.GONE
mLineChart.visibility = View.VISIBLE
mLineChart.startAnimation()
view.findViewById<Chip>(R.id.barMode).isChecked = false
}
Log.d("A", response)
}, {
})
queue.add(stringRequest)
}
15 -> {
val stringRequest = StringRequest(
Request.Method.GET, url,
{ response ->
val mBarChart = BarChart(view.context)
val mLineChart = ValueLineChart(view.context)
val series = ValueLineSeries()
series.setColor(view.context.resources.getColor(R.color.light_red,null));
val ll = LinearLayout.LayoutParams(2500, 512)
var daydt = 0;
val arr = JSONArray(response)
for (i in 0 until days) c.add(Calendar.DATE, -1)
for (i in 1 until arr.length()) {
val m = arr[i] as JSONObject;
val n = arr[i - 1] as JSONObject;
daydt = m["unit"].toString().toInt() - n["unit"].toString().toInt()
if(daydt>max){
listMax.clear()
max=daydt
}
if(daydt==max){
listMax.add(cFm.format(tmp.time))
}
if(daydt<min){
listMin.clear()
min=daydt
}
if(daydt==min){
listMin.add(cFm.format(tmp.time))
}
tmp.add(Calendar.DATE,1)
val dtF = SimpleDateFormat("d MMM")
mBarChart.addBar(
BarModel(
dtF.format(c.time),
daydt.toFloat(),
view.context.resources.getColor(R.color.light_red,null)
)
)
series.addPoint(ValueLinePoint(dtF.format(c.time), daydt.toFloat()))
c.add(Calendar.DATE, 1);
}
mBarChart.layoutParams = ll
view.findViewById<ProgressBar>(R.id.grph_load).visibility = View.GONE
view.findViewById<GridLayout>(R.id.graphMode).visibility = View.VISIBLE
mLineChart.layoutParams = ll
mLineChart.visibility = View.GONE
mLineChart.addSeries(series);
pr.addView(mBarChart)
pr.addView(mLineChart)
mBarChart.startAnimation()
view.findViewById<Chip>(R.id.barMode).isChecked = true
view.findViewById<Chip>(R.id.barMode).setOnClickListener {
mLineChart.visibility = View.GONE
mBarChart.visibility = View.VISIBLE
mBarChart.startAnimation()
view.findViewById<Chip>(R.id.LineMode).isChecked = false
}
view.findViewById<Chip>(R.id.LineMode).setOnClickListener{
mBarChart.visibility = View.GONE
mLineChart.visibility = View.VISIBLE
mLineChart.startAnimation()
view.findViewById<Chip>(R.id.barMode).isChecked = false
}
Log.d("A", response)
}, {
})
queue.add(stringRequest)
}
30 -> {
val stringRequest = StringRequest(
Request.Method.GET, url,
{ response ->
val mBarChart = BarChart(view.context)
val mLineChart = ValueLineChart(view.context)
val series = ValueLineSeries()
series.setColor(view.context.resources.getColor(R.color.light_red,null));
val ll = LinearLayout.LayoutParams(4000, 512)
var daydt = 0;
val arr = JSONArray(response)
for (i in 0 until days) c.add(Calendar.DATE, -1)
for (i in 1 until arr.length()) {
val m = arr[i] as JSONObject;
val n = arr[i - 1] as JSONObject;
daydt = m["unit"].toString().toInt() - n["unit"].toString().toInt()
if(daydt>max){
listMax.clear()
max=daydt
}
if(daydt==max){
listMax.add(cFm.format(tmp.time))
}
if(daydt<min){
listMin.clear()
min=daydt
}
if(daydt==min){
listMin.add(cFm.format(tmp.time))
}
tmp.add(Calendar.DATE,1)
val dtF = SimpleDateFormat("dd-MM")
mBarChart.addBar(
BarModel(
dtF.format(c.time),
daydt.toFloat(),
view.context.resources.getColor(R.color.light_red,null)
)
)
series.addPoint(ValueLinePoint(dtF.format(c.time), daydt.toFloat()))
c.add(Calendar.DATE, 1);
}
mBarChart.layoutParams = ll
view.findViewById<ProgressBar>(R.id.grph_load).visibility = View.GONE
view.findViewById<GridLayout>(R.id.graphMode).visibility = View.VISIBLE
mLineChart.layoutParams = ll
mLineChart.visibility = View.GONE
mLineChart.addSeries(series);
pr.addView(mBarChart)
pr.addView(mLineChart)
mBarChart.startAnimation()
view.findViewById<Chip>(R.id.barMode).isChecked = true
view.findViewById<Chip>(R.id.barMode).setOnClickListener {
mLineChart.visibility = View.GONE
mBarChart.visibility = View.VISIBLE
mBarChart.startAnimation()
view.findViewById<Chip>(R.id.LineMode).isChecked = false
}
view.findViewById<Chip>(R.id.LineMode).setOnClickListener{
mBarChart.visibility = View.GONE
mLineChart.visibility = View.VISIBLE
mLineChart.startAnimation()
view.findViewById<Chip>(R.id.barMode).isChecked = false
}
Log.d("A", response)
}, {
})
queue.add(stringRequest)
}
}
btnA.setOnClickListener {
showQuick(view,Pair(max,listMax),Pair(min,listMin))
}
}
@SuppressLint("SimpleDateFormat", "ResourceType", "CutPasteId")
private fun evaluateCustomGraph(view : View){
resetGrp(view)
val stR = arrayOf<MaterialButton>(view.findViewById(R.id.strart_range),view.findViewById(R.id.end_range))
val range = arrayOf(Date(),Date())
val one = view.findViewById<RadioGroup>(R.id.one)
one.check(R.id.daily);
stR[0].setOnClickListener {
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val dpd = DatePickerDialog(view.context, { view, year, monthOfYear, dayOfMonth ->
// Display Selected date in textbox
val df = SimpleDateFormat("dd-MM-yyyy")
stR[0].text = df.format(Date("$year/${monthOfYear+1}/${dayOfMonth}"));
val cc = Calendar.getInstance()
cc.time = Date("$year/${monthOfYear+1}/${dayOfMonth}")
cc.add(Calendar.DATE,-1)
range[0] = cc.time;
}, year, month, day)
val cal = Calendar.getInstance()
cal.time = Date()
cal.add(Calendar.DATE,-1)
dpd.datePicker.maxDate = cal.time.time
dpd.datePicker.minDate = Date("2020/01/01").time;
dpd.show()
}
stR[1].setOnClickListener {
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val dpd = DatePickerDialog(view.context, { view, year, monthOfYear, dayOfMonth ->
// Display Selected date in textbox00
val df = SimpleDateFormat("dd-MM-yyyy")
stR[1].text = df.format(Date("$year/${monthOfYear+1}/${dayOfMonth}"));
range[1] = Date("$year/${monthOfYear+1}/${dayOfMonth}")
}, year, month, day)
val cal = Calendar.getInstance()
cal.time = Date()
cal.add(Calendar.DATE,-1)
dpd.datePicker.maxDate = cal.time.time
dpd.datePicker.minDate = Date("2020/01/01").time;
dpd.show()
}
val displayMetrics = DisplayMetrics()
this.requireActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics)
val height = displayMetrics.heightPixels
val width = displayMetrics.widthPixels
val btn = view.findViewById<MaterialButton>(R.id.cust_graph_btn)
val queue = Volley.newRequestQueue(view.context)
val pr = view.findViewById<LinearLayout>(R.id.graphCanvas)
btn.setOnClickListener {
var max = Int.MIN_VALUE;
var min = Int.MAX_VALUE
val listMax = ArrayList<String>();
val listMin = ArrayList<String>();
val btnA = view.findViewById<Chip>(R.id.get_data)
btnA.setOnClickListener {
showQuick(view,Pair(max,listMax),Pair(min,listMin))
}
pr.removeAllViews()
resetGrp(view);
view.findViewById<GridLayout>(R.id.graphMode).visibility = View.GONE
val dfm = SimpleDateFormat("yyyy-MM-dd")
val mn = arrayOf(SimpleDateFormat("dd-MM-yyyy"),SimpleDateFormat("MMM-yyyy"),SimpleDateFormat("yyyy"))
val dt1 = dfm.format(range[0]);
val dt2 = dfm.format(range[1]);
val url = "${addr}/bet/${dt1},${dt2}"
val month = LinkedHashMap<String,Int>()
val daily = LinkedHashMap<String,Int>()
val yearly = LinkedHashMap<String,Int>()
if(range[0].time<range[1].time){
view.findViewById<MaterialCardView>(R.id.graphCard).visibility = View.VISIBLE
view.findViewById<ProgressBar>(R.id.grph_load).visibility = View.VISIBLE
val stringRequest = StringRequest(
Request.Method.GET, url,
{ response ->
val ck = Calendar.getInstance()
ck.time = range[0];
val mBarChart = BarChart(view.context)
val mLineChart = ValueLineChart(view.context)
val sdf = SimpleDateFormat("dd-MM")
val k = JSONArray(response)
var len = 0L
for(i in 1 until k.length()){
ck.add(Calendar.DATE,1)
val n = k[i] as JSONObject
val m = k[i-1] as JSONObject
val diff = n["unit"].toString().toInt() - m["unit"].toString().toInt();
daily[mn[0].format(ck.time)] = diff
if(!month.containsKey(mn[1].format(ck.time))) month[mn[1].format(ck.time)] = 0
month[mn[1].format(ck.time)] = month[mn[1].format(ck.time)]!!.plus(diff)
if(!yearly.containsKey(mn[2].format(ck.time))) yearly[mn[2].format(ck.time)] = 0
yearly[mn[2].format(ck.time)] = yearly[mn[2].format(ck.time)]!!.plus(diff)
}
val series = ValueLineSeries()
series.setColor(view.context.resources.getColor(R.color.light_red,null));
when(one.checkedRadioButtonId){
R.id.daily -> {
val cFm = SimpleDateFormat("E MMM d, yyyy")
val cl = Calendar.getInstance()
for(i in daily){
len+=135;
cl.set(i.key.split('-')[2].toInt(),i.key.split('-')[1].toInt(),i.key.split('-')[0].toInt())
if(max<i.value){
listMax.clear()
max = i.value
}
if(max==i.value){
listMax.add(cFm.format(cl.time))
}
if(min>i.value){
listMin.clear()
min = i.value
}
if(min==i.value){
listMin.add(cFm.format(cl.time))
}
mBarChart.addBar(BarModel(i.key.split('-')[0]+'-'+i.key.split('-')[1],i.value.toFloat(),view.context.resources.getColor(R.color.light_red,null)))
series.addPoint(ValueLinePoint(i.key.split('-')[0]+'-'+i.key.split('-')[1],i.value.toFloat()))
}
}
R.id.monthly -> {
for(i in month){
if(max<i.value){
listMax.clear()
max = i.value
}
if(max==i.value){
listMax.add(i.key)
}
if(min>i.value){
listMin.clear()
min = i.value
}
if(min==i.value){
listMin.add(i.key)
}
len+=135;
mBarChart.addBar(BarModel(i.key.split('-')[0],i.value.toFloat(),view.context.resources.getColor(R.color.light_red,null)))
series.addPoint(ValueLinePoint(i.key.split('-')[0],i.value.toFloat()))
}
}
R.id.yearly -> {
for(i in yearly){
len+=135;
if(max<i.value){
listMax.clear()
max = i.value
}
if(max==i.value){
listMax.add(i.key)
}
if(min>i.value){
listMin.clear()
min = i.value
}
if(min==i.value){
listMin.add(i.key)
}
mBarChart.addBar(BarModel(i.key,i.value.toFloat(),view.context.resources.getColor(R.color.light_red,null)))
series.addPoint(ValueLinePoint(i.key,i.value.toFloat()))
}
}
}
var ll = LinearLayout.LayoutParams(len.toInt(), 512)
if(len.toInt()<=width) ll = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 512)
mBarChart.layoutParams = ll
mLineChart.layoutParams = ll
mLineChart.visibility = View.GONE
mLineChart.addSeries(series);
pr.addView(mBarChart)
pr.addView(mLineChart)
mBarChart.startAnimation()
view.findViewById<Chip>(R.id.barMode).isChecked = true
view.findViewById<Chip>(R.id.barMode).setOnClickListener {
mLineChart.visibility = View.GONE
mBarChart.visibility = View.VISIBLE
mBarChart.startAnimation()
view.findViewById<Chip>(R.id.LineMode).isChecked = false
}
view.findViewById<Chip>(R.id.LineMode).setOnClickListener{
mBarChart.visibility = View.GONE
mLineChart.visibility = View.VISIBLE
mLineChart.startAnimation()
view.findViewById<Chip>(R.id.barMode).isChecked = false
}
view.findViewById<ProgressBar>(R.id.grph_load).visibility = View.GONE
view.findViewById<GridLayout>(R.id.graphMode).visibility = View.VISIBLE
Log.d("SIZE",k.length().toString())
},{})
queue.add(stringRequest)
}else{
Snackbar.make(view,"Reversed Range Found",Snackbar.LENGTH_SHORT).show()
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
super.onCreate(savedInstanceState)
val items = arrayOf("Last 7 days", "Last 15 days", "Last 30 days","Custom Range")
val view = inflater.inflate(R.layout.summary, container, false)
val pBtn = view.findViewById<MaterialCardView>(R.id.pSelectBtn)
pBtn.setOnClickListener {
MaterialAlertDialogBuilder(view.context)
.setTitle("Select Period")
.setItems(items) { dialog, which ->
view.findViewById<MaterialCardView>(R.id.graphCard).visibility = View.GONE
view.findViewById<GridLayout>(R.id.graphMode).visibility = View.GONE
if(which==items.size-1){
view.findViewById<MaterialCardView>(R.id.custom_range_card).visibility = View.VISIBLE
}else{
view.findViewById<MaterialCardView>(R.id.custom_range_card).visibility = View.GONE
}
val pr = view.findViewById<LinearLayout>(R.id.graphCanvas)
when(which){
0->{
pr.removeAllViews()
createGraph(7,view);
}
1->{
pr.removeAllViews()
createGraph(15,view);
}
2->{
pr.removeAllViews()
createGraph(30,view);
}
3->{
pr.removeAllViews()
evaluateCustomGraph(view)
}
}
view.findViewById<TextView>(R.id.period_txt).text = items[which];
}
.show()
}
// val mBarChart = view.findViewById(R.id.barchart) as BarChart
// val mBarChart1 = view.findViewById(R.id.barchart1) as BarChart
// mBarChart.addBar(BarModel("A",0f, view.context.resources.getColor(R.color.light_red,null)))
// mBarChart.addBar(BarModel("A",2f, -0xcbcbaa))
// mBarChart.addBar(BarModel("A",3.3f, -0xa9cbaa))
// mBarChart.addBar(BarModel("A",1.1f, -0x78c0aa))
// mBarChart.addBar(BarModel("A",2.7f, -0xa9480f))
// mBarChart.addBar(BarModel("A",2f, -0xcbcbaa))
// mBarChart.addBar(BarModel("A",0.4f, -0xe00b54))
// mBarChart.addBar(BarModel("A",4f, -0xe45b1a))
// mBarChart.addBar(BarModel("A",4f, -0xe45b1a))
// mBarChart.addBar(BarModel("A",2.3f, view.context.resources.getColor(R.color.light_red,null)))
// mBarChart.addBar(BarModel("A",2f, -0xcbcbaa))
// mBarChart.addBar(BarModel("A",3.3f, -0xa9cbaa))
// mBarChart1.addBar(BarModel("A",1.1f, -0x78c0aa))
// mBarChart1.addBar(BarModel("A",2.7f, -0xa9480f))
// mBarChart1.addBar(BarModel("A",2f, -0xcbcbaa))
// mBarChart1.addBar(BarModel("A",0.4f, -0xe00b54))
// mBarChart1.addBar(BarModel("A",4f, -0xe45b1a))
// mBarChart1.addBar(BarModel("A",1.1f, -0x78c0aa))
// mBarChart1.addBar(BarModel("A",2.7f, -0xa9480f))
// mBarChart1.addBar(BarModel("A",2f, -0xcbcbaa))
// mBarChart.isShowValues = true
// mBarChart.startAnimation()
// mBarChart1.startAnimation()
return view;
}
}<file_sep>/app/src/main/java/local/host/thon/Profile.kt
package local.host.thon
import android.os.Bundle
import android.os.StrictMode
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewParent
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import local.host.thonon.Fragment1
import local.host.thonon.Fragment2
import local.host.thonon.Fragment3
class Profile : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
super.onCreate(savedInstanceState)
val view = inflater.inflate(R.layout.profile, container, false)
val tabLayout = view.findViewById<TabLayout>(R.id.tabLayout)
val viewPager = view.findViewById<ViewPager2>(R.id.pager)
val adapter =MyViewPagerAdapter(childFragmentManager,lifecycle)
adapter.addFragment(Fragment1(), "Home")
adapter.addFragment(Fragment2(), "Device")
adapter.addFragment(Fragment3(), "My Account")
viewPager.adapter =adapter
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
tab.text = adapter.getPageTitle(position)
viewPager.setCurrentItem(tab.position, true)
}.attach()
return view;
}
}
class MyViewPagerAdapter(manager: FragmentManager, lifecycle: Lifecycle) : FragmentStateAdapter(manager,lifecycle ){
private val fragmentList : MutableList<Fragment> =ArrayList()
private val titleList : MutableList<String> =ArrayList()
override fun getItemCount(): Int {
return fragmentList.size
}
override fun createFragment(position: Int): Fragment {
return fragmentList[position]
}
fun addFragment(fragment: Fragment, title: String){
fragmentList.add(fragment)
titleList.add(title)
}
fun getPageTitle(position: Int): CharSequence {
return titleList[position]
}
}<file_sep>/app/src/main/java/local/host/thon/Fragments.kt
package local.host.thonon
import android.os.Bundle
import android.os.StrictMode
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import local.host.thon.R
class Fragment1 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
super.onCreate(savedInstanceState)
val view = inflater.inflate(R.layout.fragment1, container, false)
return view
}
}
class Fragment2 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
super.onCreate(savedInstanceState)
val view = inflater.inflate(R.layout.fragment2, container, false)
return view
}
}
class Fragment3 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
super.onCreate(savedInstanceState)
val view = inflater.inflate(R.layout.fragment3, container, false)
return view
}
} | c21932cd56b81c9a9b95bedccfff6d54c2fe1b94 | [
"Kotlin"
] | 9 | Kotlin | jeel279/thon4 | 51b16d2964c8a11556e9f14f03bff339b099334f | 54632821292e226d60048bf87423c9bbbc549978 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import { Row, Col, Typography, Button, Modal, Spin } from 'antd';
import { tokenStatus } from '../../constants';
import './ListToken.css';
import {
updateToken,
getAllTokens,
displayLocalTime,
} from '../../utils/helpers';
import { TeamNumberContext } from '../../TeamNumberContext';
const { Text, Paragraph } = Typography;
export default class ListToken extends Component {
constructor(props) {
super(props);
this.state = {
tokens: [],
spinning: true,
};
}
componentDidMount() {
this.refreshTokens();
}
refreshTokens = () => {
this.setState({ spinning: true });
const resp = getAllTokens(this.context.teamNumber);
resp.then((value) => {
this.setState({ tokens: value, spinning: false });
});
};
updateTokenStatus = async (id, status) => {
const { teamNumber } = this.context;
try {
this.setState({ spinning: true });
const updateResp = await updateToken(id, status, teamNumber);
const allTokensResp = await getAllTokens(teamNumber);
this.setState({ tokens: allTokensResp, spinning: false });
} catch (err) {
Modal.error({
title: 'Error',
content: err,
});
}
};
replaceAt = (string, index, replace) => {
return string.substring(0, index) + replace + string.substring(index + 1);
};
maskValue = (value) => {
return this.replaceAt(value, 2, '*');
};
renderToken = (token) => {
let className = '';
const isTokenReady = token.status !== tokenStatus.READY;
if (isTokenReady) className = 'cross-text';
return (
<li className="token-list-li" key={token._id}>
<Row>
<Col sm={{ span: 24 }} md={{ span: 12 }}>
<Paragraph
style={{ display: 'inline-block', margin: 0 }}
className={`${className} list-copy-icon`}
>
<Text className="list-token-text" mark>
{this.maskValue(token.value)} Sequence: {token.sequence}
</Text>{' '}
<div className="token-extra-info">
{token.status} {displayLocalTime(token.timeStamp)} HKT
</div>
</Paragraph>
</Col>
<Col sm={{ span: 24 }} md={{ span: 12 }}>
<Button
className="list-button first button-confirm"
size="small"
icon="check"
disabled={true}
onClick={() =>
this.updateTokenStatus(token._id, tokenStatus.USED)
}
>
Token OK
</Button>
<Button
className="list-button button-error"
size="small"
icon="close"
disabled={true}
onClick={() =>
this.updateTokenStatus(token._id, tokenStatus.INVALID)
}
>
Token Invalid
</Button>
</Col>
</Row>
</li>
);
};
render() {
const { tokens, spinning } = this.state;
console.log('listTokenContext', this.context);
return (
<Spin spinning={spinning}>
<ul className="token-list">
{tokens && tokens.length > 0 ? (
tokens.map((token) => this.renderToken(token))
) : (
<p>No products found</p>
)}
</ul>
</Spin>
);
}
}
ListToken.contextType = TeamNumberContext;
<file_sep>import React, { Component } from 'react';
import { Button, Input, Form, Modal, Spin, Row, Col, Typography } from 'antd';
import tokenService from '../../services/tokenService';
import './AddToken.css';
import { TeamNumberContext } from '../../TeamNumberContext';
const { Text } = Typography;
export class AddToken extends Component {
constructor(props) {
super(props);
this.state = {
spinning: false,
};
}
handleInsertToken = async () => {
this.setState({
spinning: true,
});
const {
form: { validateFields },
} = this.props;
validateFields(['tokenValue'], async (err, values) => {
if (!err) {
const { teamNumber } = this.context;
await tokenService.insertTokens(values.tokenValue, teamNumber);
}
this.setState({
spinning: false,
});
});
};
deleteAllTokens = () => {
Modal.warning({
title: 'Are you sure?',
onOk: () => tokenService.deleteAllTokens(this.context.teamNumber),
});
};
renderNumbers = () => {
const {
form: { getFieldValue },
} = this.props;
const fieldVal = getFieldValue('tokenValue');
if (!fieldVal) return <Text>Input tokens, then press Insert Tokens</Text>;
const splitText = fieldVal.match(/.{1,6}/g);
const colSpan = {
xs: 8,
md: 4,
xl: 2,
};
return (
<Row gutter={[16, 32]}>
{splitText.map((val) => {
const isValueError = !(val.length === 6 && /^\d+$/.test(val)); // latter one checks if string only contains numbers
const textClassName = `token-text ${
isValueError ? 'token-text-err' : ''
}`;
return (
<Col className="token-col" {...colSpan}>
<Text className={textClassName} strong>
{val}
</Text>
</Col>
);
})}
</Row>
);
};
render() {
const { form } = this.props;
const { spinning } = this.state;
const { getFieldDecorator, getFieldValue } = form;
return (
<Form>
<Spin spinning={spinning}>
<Text strong className="top-note">
To insert multiple tokens, please <Text type="danger">don't</Text>{' '}
type enter, just type 123456654321 to insert 2 tokens, for example
</Text>
<span>{this.renderNumbers()}</span>
<Form.Item>
{getFieldDecorator('tokenValue', {
rules: [
{ required: true, message: 'Please input passcode!' },
{
validator: (rule, value, callback) => {
const tokenValue = getFieldValue('tokenValue');
const hasNonNumericalErr = !/^\d+$/.test(tokenValue);
const hasRemainderErr = tokenValue.length % 6 !== 0;
if (hasNonNumericalErr)
callback('Passcode contains non-numerical value(s)');
else if (hasRemainderErr)
callback(
'Each passcode has exactly 6 digits, please verify',
);
callback();
},
},
],
})(<Input.TextArea rows={8} />)}
</Form.Item>
<Row gutter={[0, 24]}>
<Col>
<Button type="primary" onClick={this.handleInsertToken}>
Insert Tokens
</Button>
</Col>
<Col>
<Button type="danger" onClick={this.deleteAllTokens}>
Delete All Tokens
</Button>
</Col>
</Row>
</Spin>
</Form>
);
}
}
export default Form.create()(AddToken);
AddToken.contextType = TeamNumberContext;
<file_sep>import React from 'react';
export const TeamNumberContext = React.createContext({
teamNumber: 2,
});
<file_sep>import axios from 'axios';
import moment from 'moment';
import { tokenStatus } from '../constants';
const { READY } = tokenStatus;
export default {
getTokens: async (teamNumber) => {
let res = await axios.get(`/api/token?teamNumber=${teamNumber}`);
return res.data || [];
},
getOneReadyToken: (teamNumber) => {
const res = axios.get(`/api/getOneToken?teamNumber=${teamNumber}`);
return res;
},
getNumberOfTokensService: (teamNumber) => {
const res = axios.get(`/api/getNumberOfTokens?teamNumber=${teamNumber}`);
return res;
},
updateTokenStatus: (id, status, teamNumber) => {
const res = axios.post(`/api/updateTokenStatus`, {
id,
status,
teamNumber,
});
return res;
},
insertTokens: async (tokenValues, teamNumber) => {
const reqBody = { tokenValues, teamNumber };
console.log('reqBody', reqBody);
let res = await axios.post(`/api/token`, reqBody, {
headers: {
'Content-Type': 'application/json',
},
});
return res.data || [];
},
deleteAllTokens: async (teamNumber) => {
const res = await axios.delete(
`/api/deleteAllTokens?teamNumber=${teamNumber}`,
);
return res.data || '';
},
};
<file_sep>import { tokenStatus } from '../constants';
const { READY, USED, INVALID, PENDING } = tokenStatus;
export default [
{
tokenValue: '111111',
status: READY,
},
{
tokenValue: '111112',
status: READY,
},
{
tokenValue: '111113',
status: READY,
},
{
tokenValue: '211111',
status: USED,
},
{
tokenValue: '211112',
status: USED,
},
{
tokenValue: '211113',
status: USED,
},
{
tokenValue: '311111',
status: INVALID,
},
{
tokenValue: '311112',
status: INVALID,
},
{
tokenValue: '311113',
status: INVALID,
},
{
tokenValue: '411111',
status: PENDING,
},
{
tokenValue: '411112',
status: PENDING,
},
{
tokenValue: '411113',
status: PENDING,
},
];
<file_sep>import GetToken from './GetToken';
export default GetToken;
<file_sep>const mongoose = require('mongoose');
const { Schema } = mongoose;
const tokenSchema = new Schema({
value: String,
status: String,
timeStamp: String,
teamNumber: Number,
sequence: Number,
});
mongoose.model('tokens', tokenSchema);
<file_sep>// eslint-disable-next-line import/prefer-default-export
export const tokenStatus = {
READY: 'READY',
USED: 'USED',
INVALID: 'INVALID',
PENDING: 'PENDING',
};
export const TEAM_NUMBER = {
TEAM_2: 2,
TEAM_3: 3,
};
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col, Button, Typography, Tooltip, Spin } from 'antd';
import './GetToken.css';
import _ from 'lodash';
import { tokenStatus } from '../../constants';
import {
updateToken,
getReadyToken,
getNumberOfTokens,
displayLocalTime,
} from '../../utils/helpers';
import renderEmpty from 'antd/lib/config-provider/renderEmpty';
import { TeamNumberContext } from '../../TeamNumberContext';
const { Text } = Typography;
class GetToken extends React.Component {
constructor(props) {
super(props);
this.state = {
token: {
_id: null,
value: null,
timeStamp: null,
},
spinning: false,
numberOfTokensRemaining: 0,
};
}
componentDidMount() {
this.refreshNumberOfTokens();
}
refreshNumberOfTokens = () => {
this.setState({ spinning: true });
const resp = getNumberOfTokens(this.context.teamNumber);
resp.then((val) => {
this.setState({
numberOfTokensRemaining: val.numberOfTokens,
spinning: false,
});
});
};
getReadyToken = async () => {
this.setState({ spinning: true });
const resp = await getReadyToken(this.context.teamNumber);
console.log('getReadyToken resp', resp);
if (resp && resp.currentToken) {
const { _id, timeStamp, value } = resp.currentToken;
this.setState({
token: {
_id,
timeStamp,
value,
},
});
}
this.refreshNumberOfTokens();
this.setState({ spinning: false });
};
updateAndGetNewToken = async () => {
this.setState({ spinning: true });
const { _id } = this.state.token;
await updateToken(_id, tokenStatus.INVALID, this.context.teamNumber);
await this.getReadyToken();
this.refreshNumberOfTokens();
this.setState({ spinning: false });
};
updateTokenStatus = async (id, status) => {
this.setState({ spinning: true });
await updateToken(id, status, this.context.teamNumber);
this.refreshNumberOfTokens();
this.setState({ spinning: false });
};
ResponseButtons = () => {
const { _id } = this.state.token;
return (
<>
<Col span={{ xs: 24, sm: 12 }}>
<Tooltip title="Thanks for your feedback!" trigger="click">
<Button
type="primary"
className="token-button button-confirm"
onClick={() => this.updateTokenStatus(_id, tokenStatus.USED)}
>
<span className="token-button-text">This token works!</span>
</Button>
</Tooltip>
</Col>
<Col span={{ xs: 24, sm: 12 }}>
<Button
onClick={() => this.updateAndGetNewToken()}
className="token-button button-error"
>
<span className="token-button-text">
This token doesn't work, click to get a new one!
</span>
</Button>
</Col>
</>
);
};
InitialGetButton = () => (
<Col span={{ md: 12 }}>
<Button
type="primary"
className="token-button"
onClick={this.getReadyToken}
style={{ height: '80px' }}
>
Get Token
</Button>
</Col>
);
render() {
const { token, spinning, numberOfTokensRemaining } = this.state;
const { _id, value, timeStamp } = token;
return (
<Spin spinning={spinning}>
<Text className="num-remain-tokens">Number of remaining tokens: </Text>
<div className="num-remain-tokens-frame">
<Text className="num-remain-tokens-digit">
{numberOfTokensRemaining}
</Text>
</div>
<Row>
<Col className="get-token-text" span={24}>
{!_.isEmpty(value) ? <Text copyable>{value}</Text> : 'No tokens'}
</Col>
</Row>
<Row style={{ margin: 0 }} justify="center" gutter={[24, 24]}>
{!_.isEmpty(value) ? (
<>
<Text type="secondary">
This token was generated at {displayLocalTime(timeStamp)} HKT
</Text>
<this.ResponseButtons />
</>
) : (
<this.InitialGetButton />
)}
</Row>
</Spin>
);
}
}
export default GetToken;
GetToken.contextType = TeamNumberContext;
GetToken.propTypes = {
token: PropTypes.string,
getToken: PropTypes.func,
updateToken: PropTypes.func,
};
GetToken.defaultProps = {
token: null,
getToken: null,
updateToken: null,
};
<file_sep>import moment from 'moment-timezone';
import tokenService from '../services/tokenService';
import { Modal } from 'antd';
export function getSafe(fn, defaultVal) {
try {
return fn();
} catch (e) {
return defaultVal;
}
}
export const updateToken = async (id, status, teamNumber) => {
const res = await tokenService.updateTokenStatus(id, status, teamNumber);
};
export const getAllTokens = async (teamNumber) => {
let res = await tokenService.getTokens(teamNumber);
return res;
};
export const getReadyToken = async (teamNumber) => {
try {
const res = await tokenService.getOneReadyToken(teamNumber);
console.log('Get ready token ok', res);
if (getSafe(() => res.data.value, null)) {
return { currentToken: res.data };
}
} catch (err) {
Modal.error({
title: 'Error',
content: err.response.data.errorMsg,
});
}
};
export const getNumberOfTokens = async (teamNumber) => {
try {
const res = await tokenService.getNumberOfTokensService(teamNumber);
return res.data;
} catch (err) {
Modal.error({
title: 'Error',
content: err.response.data.errorMsg,
});
}
};
export const clearAllToken = async (teamNumber) => {
let res = await tokenService.deleteAllTokens(teamNumber);
return res;
};
export const displayLocalTime = (momentStr) => {
return moment(momentStr).tz('Asia/Hong_Kong').format('DD/MM/YYYY hh:mm');
};
<file_sep>import GetToken from './getToken';
import AddToken from './addToken';
import ListToken from './listToken';
export { GetToken, AddToken, ListToken };
<file_sep>const mongoose = require('mongoose');
const moment = require('moment');
const tokenStatus = {
READY: 'READY',
USED: 'USED',
INVALID: 'INVALID',
PENDING: 'PENDING',
};
const { READY, PENDING, INVALID, USED } = tokenStatus;
const Token = mongoose.model('tokens');
module.exports = (app) => {
app.get('/api/token', async (req, res) => {
const tokens = await Token.find({ teamNumber: req.query.teamNumber }).sort(
'sequence',
);
return res.status(200).send(tokens);
});
app.get('/api/getOneToken', async (req, res) => {
const allReadyTokens = await Token.find({
status: READY,
teamNumber: req.query.teamNumber,
}).sort('sequence');
const earliestToken = allReadyTokens[0];
if (earliestToken) {
earliestToken.status = PENDING;
await earliestToken.save();
console.log('sent token', earliestToken);
return res.status(200).send(earliestToken);
}
return res.status(500).send({
errorMsg:
'Not enough tokens available, please contact responsible person to generate',
});
});
app.get('/api/getNumberOfTokens', async (req, res) => {
const allReadyTokens = await Token.find({
status: READY,
teamNumber: req.query.teamNumber,
});
const numberOfTokens = allReadyTokens.length;
return res.status(200).send({ numberOfTokens });
});
app.post('/api/updateTokenStatus', async (req, res) => {
console.log('updateToken req body', req.body);
if (req.body && req.body.id) {
const { id, status, teamNumber } = req.body;
await Token.findByIdAndUpdate(id, {
status,
teamNumber,
});
return res.status(200).send();
}
});
app.post(`/api/token`, async (req, res) => {
const tokens = req.body.tokenValues.match(/.{1,6}/g);
const allReadyTokens = await Token.find({
teamNumber: req.body.teamNumber,
});
const numberOfTokens = allReadyTokens.length;
console.log('numberOfTokens', numberOfTokens);
const promises = tokens.map((tokenValue, index) => {
const obj = {
value: tokenValue,
status: READY,
timeStamp: moment(),
teamNumber: req.body.teamNumber,
sequence: numberOfTokens + index,
};
return Token.create(obj);
});
const resp = await Promise.all(promises);
return res.status(201).send({
error: false,
resp,
});
});
app.put(`/api/token/:id`, async (req, res) => {
const { id } = req.params;
let token = await Token.findByIdAndUpdate(id, req.body);
return res.status(202).send({
error: false,
token,
});
});
app.delete(`/api/token/:id`, async (req, res) => {
const { id } = req.params;
let token = await Token.findByIdAndDelete(id);
return res.status(202).send({
error: false,
token,
});
});
app.delete(`/api/deleteAllTokens`, async (req, res) => {
const token = await Token.deleteMany({ teamNumber: req.query.teamNumber });
return res.status(202).send({
error: false,
token,
});
});
};
<file_sep>import ListToken from './ListToken';
export default ListToken;
| 47092319474d416bb7289b7cc95d92ba90e0c7ef | [
"JavaScript"
] | 13 | JavaScript | bensrww/node-react-starter | 07982018c45c9ce830b411f984a2aacffd279530 | 1c80707348a32df8259cd8b8e043d9842d3c2149 |
refs/heads/master | <repo_name>pavaro2906/marcha-local<file_sep>/update_stock.py
from airtable import airtable #https://github.com/josephbestjames/airtable.py
from woocommerce import API #https://github.com/woocommerce/wc-api-python
from datetime import datetime, timezone
import dateutil.parser
### APIs
API_KEY = 'keyO4pjsHsgtCPofA'
BASE_ID = 'app1fFJJYvoUtSQUL'
TABLE_NAME = 'Inventory'
wcapi = API(
url="https://marchalocal.ch",
consumer_key= '<KEY>',
consumer_secret="<KEY>",
wp_api=True,
version="wc/v3",
timeout=15
)
at = airtable.Airtable(BASE_ID, API_KEY)
table = at.get(TABLE_NAME, filter_by_formula= None)
for record in table["records"]:
## Not functional yet... : (
try:
stock = record["fields"]["Stock"]
wc_id = record["fields"]["woocommerce_ID"]
data = {
"stock_quantity": stock
}
wcapi.put("products/{}".format(wc_id), data).json()
except:
print("Item {} not in online store...".format(record["fields"]["Product"]))
<file_sep>/vendors.py
from airtable import airtable #https://github.com/josephbestjames/airtable.py
from woocommerce import API #https://github.com/woocommerce/wc-api-python
### APIs
API_KEY = 'keyO4pjsHsgtCPofA'
BASE_ID = 'app1fFJJYvoUtSQUL'
TABLE_NAME = 'Inventory'
wcapi = API(
url="https://marchalocal.ch",
consumer_key= '<KEY>',
consumer_secret="<KEY>",
wp_api=True,
version="wc/v3",
timeout=15
)
# print(wcapi.get("products/997").json()['date_modified_gmt'])
# print("\n")
# # vends = wcapi.get("\a").json()
# # print(vends)
# products = list()
# product_page = 0
# while True:
# product_page = product_page + 1
# query = "products?page={}".format(product_page)
# prods_page = wcapi.get(query).json()
# products.append(prods_page)
# if len(prods_page) < 10:
# break
# vendors = {}
# categories = {}
# cats = wcapi.get("products/categories").json()
# for cat in cats:
# cat_id = cat['id']
# cat_name = cat['name']
# if not categories.get(cat_name):
# categories[cat_name] = cat_id
# print(categories)
# for product_page in products:
# for product in product_page:
# store_id = product["vendor"]
# store_name = product["store_name"]
# if not vendors.get(store_name):
# vendors[store_name] = store_id
# print(wcapi.get("orders").json())
<file_sep>/orders.py
from airtable import airtable #https://github.com/josephbestjames/airtable.py
from woocommerce import API #https://github.com/woocommerce/wc-api-python
from datetime import datetime, timezone
import dateutil.parser
### APIs
API_KEY = 'keyO4pjsHsgtCPofA'
BASE_ID = 'app1fFJJYvoUtSQUL'
TABLE_NAME = 'Inventory'
wcapi = API(
url="https://marchalocal.ch",
consumer_key= '<KEY>',
consumer_secret="<KEY>",
wp_api=True,
version="wc/v3",
timeout=15
)
at = airtable.Airtable(BASE_ID, API_KEY)
table = at.get(TABLE_NAME, filter_by_formula= None)
## create record_id dictionary
rec_ids = {}
for record in table["records"]:
product = record['fields']['Product']
rec_id = record['id']
if not rec_ids.get(product):
rec_ids[product] = rec_id
## Fetch orders from WooCommerce
order_pages = list()
order_page = 0
while True:
order_page = order_page + 1
query = "orders?page={}".format(order_page)
ords_page = wcapi.get(query).json()
order_pages.append(ords_page)
if len(ords_page) < 10:
break
## Make orders dictionary
orders = {}
for order_page in order_pages:
for order in order_page:
order_id = order["id"]
timestamp = order['date_created_gmt']
order_date = dateutil.parser.parse(timestamp +"+00:00")
items = list()
for item in order['line_items']:
prod_id = item['product_id']
prod_name = item["name"]
qty = item['quantity']
it = {"id": prod_id, "name": prod_name, "quantity": qty, "date": order_date}
items.append(it)
if not orders.get(order_id):
orders[order_id] = {"id": order_id, "items": items}
## Update values in airtable
for order in orders:
for item in orders[order]["items"]:
item_bought = item['name']
number_bought = item['quantity']
# try:
# at_time = at.get("Inventory", record_id=rec_ids[item_bought], fields="Last modified time")
# at_stock = at.get("Inventory", record_id=rec_ids[item_bought], fields="Stock")
# print(at_stock)
# last_update_time = dateutil.parser.parse(at_time)
# if item["date"] > last_update_time:
# new_stock = at_stock - number_bought
# resp = at.update("Inventory", rec_ids[item_bought], {"Stock": new_stock })
# except:
# print("Item {} not found in airtables".format(item_bought))
if rec_ids.get(item_bought):
at_time = at.get("Inventory", record_id=rec_ids[item_bought])["fields"]["Last modified time"]
at_stock = at.get("Inventory", record_id=rec_ids[item_bought])["fields"]["Stock"]
last_update_time = dateutil.parser.parse(at_time)
if item["date"] > last_update_time:
new_stock = at_stock - number_bought
resp = at.update("Inventory", rec_ids[item_bought], {"Stock": new_stock })
print("Restocked {} to {}".format(item_bought, new_stock)) | 096828dbf1faddff43553b092b9f41a108d22c7e | [
"Python"
] | 3 | Python | pavaro2906/marcha-local | aa46711e6f233c57e6c680b8c3ef217328651383 | ee5eeaa4a4f5076cfaa8170e09d49ab7e2a5ba54 |
refs/heads/develop | <file_sep>#!/bin/bash
#
./AWSTools/updateLambdaHandlerEventParams.js \
--lambdaName signup
if [ $? -eq 0 ]; then
./AWSTools/uploadLambda.js \
--lambdaName signup
else
echo "Upload failed: updateLambdaHandlerEventParams failed"
fi
<file_sep>'use strict';
console.log('Loading function');
const fs = require('fs');
/*ignore jslint start*/
const AWSConstants = JSON.parse(fs.readFileSync('./AWSConstants.json', 'utf8'));
/*ignore jslint end*/
const APIParamVerify = require('./APIParamVerify');
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient();
/**
* handler signup
* @param {[type]} event [description]
* @param {[type]} context [description]
* @param {Function} callback [description]
* @return {[type]} [description]
*
*/
function handler(event, context, callback) {
process.on("uncaughtException", ( err ) => {
console.log(err);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Internal Error."
}));
});
// make sure we have needed params
var verifyResult = APIParamVerify.verify("/user/me", "get", event);
if (verifyResult) {
verifyResult.requestId = context.awsRequestId;
console.log(verifyResult);
callback(JSON.stringify(verifyResult));
return;
}
console.log(event);
// event contains the identity_id that is filled in by API GATEWAY by payload mapping to this lambda
// lookup in the user table
var params = {
TableName: AWSConstants.DYNAMO_DB.USERS.name,
Key: {}
};
params.Key[AWSConstants.DYNAMO_DB.USERS.ID] = event.identity_id;
docClient.get(params, function (err, userData) {
if (err) {
console.log(err);
console.log("Could not get user info from db for request: " + context.awsRequestId);
var errorObject = {
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not get user info."
};
callback(JSON.stringify(errorObject));
} else {
var userParams = {email: userData.Item[AWSConstants.DYNAMO_DB.USERS.EMAIL]};
if (userData.Item[AWSConstants.DYNAMO_DB.USERS.NAME]) {
userParams.name = userData.Item[AWSConstants.DYNAMO_DB.USERS.NAME];
}
if (userData.Item[AWSConstants.DYNAMO_DB.USERS.DOB]) {
userParams.dob = userData.Item[AWSConstants.DYNAMO_DB.USERS.DOB];
}
if (userData.Item[AWSConstants.DYNAMO_DB.USERS.LAST_LOGIN_TIMESTAMP] && userData.Item[AWSConstants.DYNAMO_DB.USERS.LAST_LOGIN_TIMESTAMP] > 0) {
userParams.last_login_timestamp = userData.Item[AWSConstants.DYNAMO_DB.USERS.LAST_LOGIN_TIMESTAMP];
}
if (userData.Item[AWSConstants.DYNAMO_DB.USERS.SIGNUP_TIMESTAMP]) {
userParams.signup_timestamp = userData.Item[AWSConstants.DYNAMO_DB.USERS.SIGNUP_TIMESTAMP];
}
if (typeof userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_COUNT] === 'number') {
userParams.photo_count = userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_COUNT];
}
if (userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_ID]) {
userParams.photo_id = userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_ID];
}
if (userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_BASE_ID]) {
userParams.photo_base_id = userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_BASE_ID];
}
if (AWSConstants.S3.PHOTOBUCKET.pathUrl) {
userParams.photo_path_url = AWSConstants.S3.PHOTOBUCKET.pathUrl;
}
userParams.logins = {};
var providerSplit = event.auth_provider.split(',');
if (providerSplit.length > 1) {
var providerName = providerSplit[0];
userParams.provider_name = providerName;
var providerIDSplit = providerSplit[1].split(':');
if (providerIDSplit.length >= 4) {
var providerID = providerIDSplit[3];
userParams.logins[providerName] = providerID;
callback(null, userParams);
return;
}
}
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not get provider info."
}));
}
});
}
exports.handler = handler;
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Creates Subnets to use with VPCs.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.help('h')
.alias('h', 'help');
var argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Creating Subnets ##");
if (awsc.verifyPath(baseDefinitions,['subnetInfo', 'subnets'],'o').isVerifyError) {
console.log("Nothing to do.");
return;
}
Object.keys(baseDefinitions.subnetInfo.subnets).forEach(function (subnetName) {
/* var subnetDescription = baseDefinitions.subnetInfo.subnets[subnetName];
if (!awsc.verifyPath(subnetDescription,["SubnetId"],'s').isVerifyError) {
console.log("Subnet '" + subnetName + "' is already defined. Please use deleteSubnet.js first.");
return;
}*/
// check to see if the name tag exists
var nameTag = baseDefinitions.environment.AWSResourceNamePrefix + subnetName + "Subnet";
console.log("Checking for Subnet with tag name '" + nameTag + "'");
awsc.checkEc2ResourceTagName(nameTag, subnetName, AWSCLIUserProfile, function(tagExists, results, tagName, subnetName) {
if (tagExists) {
console.log("Subnet '" + tagName + "' exists. updating local definitions with existing ID.");
// update Subnet info with existing tag IDs
baseDefinitions.subnetInfo.subnets[subnetName].SubnetId = results[0].ResourceId;
// write out result
writeOut("Could not update SubnetId for Subnet '" + subnetName + "'.");
} else {
console.log("Creating new Subnet with tag name '" + tagName + "'");
createSubnet(tagName, subnetName, function (err, tagName, subnetName) {
if (err) {
console.log(err);
return;
}
writeOut("Could not update SubnetId for Subnet '" + subnetName + "'.");
});
}
});
});
function createSubnet(nameTag, subnetName, callback) {
var pathError = awsc.verifyPath(baseDefinitions,["vpcInfo", "vpcs", baseDefinitions.subnetInfo.subnets[subnetName].vpc, "VpcId"], "s", "definitions file \"" + argv.baseDefinitionsFile + "\"");
if (pathError.isVerifyError) {
console.log(pathError);
throw new Error("Please create the VPC first using 'createVPC.js'");
}
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "create-subnet",
parameters:{
"cidr-block": {type: "string", value: baseDefinitions.subnetInfo.subnets[subnetName]["cidr-block"]},
"vpc-id": {type: "string", value: baseDefinitions.vpcInfo.vpcs[baseDefinitions.subnetInfo.subnets[subnetName].vpc].VpcId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['Subnet', 'SubnetId'], type:'s'}]
},
function (request) {
if (request.response.error) {
callback(request.response.error, nameTag, subnetName);
return;
}
baseDefinitions.subnetInfo.subnets[subnetName].SubnetId = request.response.parsedJSON.Subnet.SubnetId;
awsc.createEc2ResourceTag(baseDefinitions.subnetInfo.subnets[subnetName].SubnetId, nameTag, AWSCLIUserProfile, function (err) {
callback(err, nameTag, subnetName);
});
}).startRequest();
}
function writeOut(errorText) {
// now delete role
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". " + errorText);
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file. " + errorText);
throw writeErr;
}
});
}
<file_sep>'use strict';
const fs = require('fs');
const AWSConstants = JSON.parse(fs.readFileSync('./AWSConstants.json', 'utf8'));
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient();
const UUID = require('node-uuid');
function getItemForPhotoBaseId(photoBaseId, callback) {
var photoBaseGetParams = {
TableName: AWSConstants.DYNAMO_DB.PHOTOS.name,
Key: {}
};
photoBaseGetParams.Key[AWSConstants.DYNAMO_DB.PHOTOS.PHOTO_BASE_ID] = photoBaseId;
docClient.get(photoBaseGetParams, function (err, photoData) {
if (err) {
callback(err);
return;
}
callback(null, photoData.Item);
});
}
exports.getItemForPhotoBaseId = getItemForPhotoBaseId;
function appendPhotoId(photoBaseId, photoId, callback) {
var paramsDevice = {
TableName: AWSConstants.DYNAMO_DB.PHOTOS.name,
Key: {},
UpdateExpression: "set " + AWSConstants.DYNAMO_DB.PHOTOS.PHOTO_IDS + " = list_append( " + AWSConstants.DYNAMO_DB.PHOTOS.PHOTO_IDS + ", :t)",
ExpressionAttributeValues: {
":t": [photoId]
}
};
paramsDevice.Key[AWSConstants.DYNAMO_DB.PHOTOS.PHOTO_BASE_ID] = photoBaseId;
docClient.update(paramsDevice, callback);
}
exports.appendPhotoId = appendPhotoId;
function setPhotoIds(photoBaseId, photoIds, callback) {
var paramsDevice = {
TableName: AWSConstants.DYNAMO_DB.PHOTOS.name,
Key: {},
UpdateExpression: "set " + AWSConstants.DYNAMO_DB.PHOTOS.PHOTO_IDS + " = :t",
ExpressionAttributeValues: {
":t": photoIds
}
};
paramsDevice.Key[AWSConstants.DYNAMO_DB.PHOTOS.PHOTO_BASE_ID] = photoBaseId;
docClient.update(paramsDevice, callback);
}
exports.setPhotoIds = setPhotoIds;
function checkForPhotoBaseID(userID, awsRequestId, callback) {
var userGetParams = {
TableName: AWSConstants.DYNAMO_DB.USERS.name,
Key: {}
};
userGetParams.Key[AWSConstants.DYNAMO_DB.USERS.ID] = userID;
// get the user
docClient.get(userGetParams, function (err, userData) {
if (err) {
console.log(err);
console.log("Could not get user info from db for request: " + awsRequestId);
var errorObject = {
requestId: awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not get user info."
};
callback(errorObject);
} else {
// if the user doesn't have a photo_id base then assign one and save the user object
if (!userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_BASE_ID]) {
var photoBaseId = UUID.v4();
// Add the email to the email table with provider token
// login will use this to lookup the identity
var paramsPhoto = {
TableName: AWSConstants.DYNAMO_DB.PHOTOS.name,
Item: {}
};
paramsPhoto.Item[AWSConstants.DYNAMO_DB.PHOTOS.PHOTO_BASE_ID] = photoBaseId;
paramsPhoto.Item[AWSConstants.DYNAMO_DB.PHOTOS.ID] = userID;
docClient.put(paramsPhoto, function (err) {
if (err) {
console.log("unable to update photo id base for request: " + awsRequestId);
var errorObject = {
requestId: awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not set photo info."
};
callback(errorObject);
return;
}
var paramsUser = {
TableName: AWSConstants.DYNAMO_DB.USERS.name,
Key: {},
UpdateExpression: "set " + AWSConstants.DYNAMO_DB.USERS.PHOTO_BASE_ID + " = :t, " + AWSConstants.DYNAMO_DB.USERS.PHOTO_COUNT + " = :q",
ExpressionAttributeValues: {
":t": photoBaseId,
":q": 0
}
};
paramsUser.Key[AWSConstants.DYNAMO_DB.USERS.ID] = userID;
docClient.update(paramsUser, function (err) {
if (err) {
console.log("unable to update photo id base for request: " + awsRequestId);
var errorObject = {
requestId: awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not set user info."
};
callback(errorObject);
return;
}
userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_BASE_ID] = photoBaseId;
setPhotoIds(photoBaseId, [], function (err) {
if (err) {
var errorObject = {
requestId: awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not set photo info."
};
callback(errorObject);
return;
}
callback(null, userData);
});
});
});
} else {
callback(null, userData);
return;
}
}
});
}
exports.checkForPhotoBaseID = checkForPhotoBaseID;
<file_sep>"use strict";
const path = require('path');
const awsu = require(path.join(__dirname, 'awscommonutils'));
const exec = require('child_process').exec;
const EventEmitter = require('events').EventEmitter;
/**
* Basically the AWS request looks like this:
* aws serviceName functionName --param XX...
* where XX can be:
* - simple string
* - quoted string
* - quoted JSON
* - file descriptor
*
* The failed case response will have
* - stderr with a description and error string in paren '(ERROR_TYPE)'
* - a bunch of stuff that is less important in stdout and in a error object.
*
* The success case will ether be an empty output or json
*
*
* I'll use a simple object to describe what I expect
* Request Object:
*
* serviceName: string
* functionName: string
* parameters:
* paramName:
* type: ["none","string","fileNameBinary", "fileName","JSONString","JSONObject"]
* value: ?
* ...
* customParamString: string - a string that will be appended to the command.
* outFile: string - a path to a file that will store the output of a request.
* context: ? -- this is a user defined object to pass context though the request
* returnSchema:['none'|'json']
* returnValidation:
* - path:
* - string of path names
* - ...
* type: ['s','o','b','a',{oneOfs:[...]}...]
* - ...
* retryCount: number -- number of retries that should be attempted
* retryErrorIds: string array -- ids that trigger a retry (all if not set)
* retryDelay: number -- ms of delay between retries (none if not set)
* retryCallback: function (request) -- this function is called on every retry
*
* Response Object
*
* Latest response object can be accessed by "this.response". I case of retry attempts
* previous responses can be found in "this.retryResponses".
*
* stdout: ?
* stderr: ?
* err: Error object
* errorId: parsed from stderr
* parsedJSON: json parse of stdout
* verified: bool - did the json pass validation
* verification error string
*
*/
exports.createRequest = function createRequest(requestObject, callback) {
return new AWSRequest(requestObject, callback);
};
class AWSRequest extends EventEmitter {
constructor(requestObject, callback) {
super();
this.callback = callback;
this.response = {};
function apply(t,r,params) {
var infoString = "AWSRequest constructor param parsing";
Object.keys(params).forEach(function (itemName){
if (params[itemName].required) {
// if the parameter is required it should stricly be applied
awsu.verifyPath(r,[itemName],params[itemName].type,infoString).exitOnError();
t[itemName] = r[itemName];
} else {
// if optional means it should be undefined or null and not be applied, but if
// it is defined we should stricly check the type
if (r[itemName] && (typeof r[itemName] !== 'undefined')) {
awsu.verifyPath(r,[itemName],params[itemName].type,infoString).exitOnError();
t[itemName] = r[itemName];
}
}
});
}
apply(this,requestObject,{'serviceName':{type:'s',required:true},
'functionName':{type:'s',required:true},
'parameters':{type:'o',required:true},
'customParamString':{type:'s',required:false},
'outFile':{type:'s', required:false},
'context':{type:'o',required:false},
'returnSchema':{type:{oneOfs:['none','json']},required:true},
'returnValidation':{type:'a',required:false},
'retryCount':{type:'n', required:false},
'retryErrorIds':{type:'a', required:false},
'retryDelay':{type:'n', required:false}
});
var errorContext = "aws request validation object";
awsu.verifyPath(this,['parameters','*','type'],'s',errorContext).exitOnError();
if (this.returnValidation) {
awsu.verifyPath(this,['returnValidation','path'],'a',errorContext).exitOnError();
awsu.verifyPath(this,['returnValidation','type'],'s',errorContext).exitOnError();
}
// check parameters to make sure they are valid
this.requestInFlight = false;
this.requestComplete = false;
this.resonse = null;
this.retryAttempt = 0;
this.retryResponses = [];
}
startRequest() {
this.shouldStartRequest();
// build the aws request string
var paramStringArray = [];
var paramNames = Object.keys(this.parameters);
for (var i = 0; i < paramNames.length; i++) {
var paramName = paramNames[i];
var param = this.parameters[paramName];
awsu.verifyPath(param,['type'],{oneOfs:["none","string","fileNameBinary", "fileName","JSONString","JSONObject"]},"aws call parameter definition").exitOnError();
var paramString = "--" + paramName;
switch (param.type) {
case 'none':
break;
case 'string':
awsu.verifyPath(param,['value'],'s',"aws call parameter definition", "Parameter \"" + paramName + "\"").exitOnError();
paramString += " " + param.value;
break;
case 'fileName':
awsu.verifyPath(param,['value'],'s',"aws call parameter definition", "Parameter \"" + paramName + "\"").exitOnError();
paramString += " " + "\"file://" + param.value + "\"";
break;
case 'fileNameBinary':
awsu.verifyPath(param,['value'],'s',"aws call parameter definition", "Parameter \"" + paramName + "\"").exitOnError();
paramString += " " + "fileb://" + param.value;
break;
case 'JSONString':
awsu.verifyPath(param,['value'],'s',"aws call parameter definition", "Parameter \"" + paramName + "\"").exitOnError();
paramString += " '" + param.value + "'";
break;
case 'JSONObject':
// awsu.verifyPath(param,['value'],'o',"aws call parameter definition", "Parameter \"" + paramName + "\"").exitOnError();
paramString += " '" + JSON.stringify(param.value) + "'";
break;
default:
}
paramStringArray.push(paramString);
}
var command = "aws " + [this.serviceName, this.functionName].concat(paramStringArray).join(' ');
if (this.customParamString) {
command += " " + this.customParamString;
}
if (this.outFile) {
command += " '" + this.outFile + "'";
}
this.awsCommand = command;
this.executeRequest();
}
reset() {
if (this.requestInFlight) {
throw new Error("Attenpting to reset a request that is in flight.");
}
this.retryResponses.push(this.response);
this.resonse = null;
this.requestInFlight = false;
this.requestComplete = false;
this.retryAttempt++;
}
retry() {
if (!this.requestComplete) {
throw new Error("Attenpting to retry a request that has not been started");
}
this.reset();
var thisRequest = this;
if (this.retryDelay) {
setTimeout(function () {
thisRequest.emit("AwsRequestRetry", thisRequest);
thisRequest.startRequest();
}, this.retryDelay);
} else {
this.emit("AwsRequestRetry", this);
this.startRequest();
}
}
shouldStartRequest() {
if (this.requestInFlight) {
throw new Error("Attempting to request an inflight AWS request.");
}
if (this.requestComplete) {
throw new Error("Attempting to request a completed AWS request.");
}
}
executeRequest() {
this.shouldStartRequest();
this.emit("AwsRequestStart");
this.requestInFlight = true;
var me = this;
exec(this.awsCommand, function (err, stdout, stderr) {
me.requestInFlight = false;
me.requestComplete = true;
me.response.error = err;
me.response.stdout = stdout;
me.response.stderr = stderr;
if (err) {
me.requestErrorFunction();
} else {
me.requestSuccessFunction();
}
});
}
requestErrorFunction() {
// look for first item between paren in stderr
this.response.errorId = "That String";
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(this.response.stderr);
if (matches && matches.length > 1) {
this.response.errorId = matches[1];
} else {
this.response.errorId = "unknown";
}
this.finishRequest();
}
finishRequest() {
if (this.response.error) {
if (!this.response.errorId) {
this.response.errorId = "InternalAwsRequestError";
}
if ((this.retryCount) && (this.retryAttempt < this.retryCount)) {
var shouldRetry = true;
if ((this.retryErrorIds) && (this.retryErrorIds.length > 0)) {
var hasErrorId = false;
for (var eIndex = 0; eIndex < this.retryErrorIds.length; eIndex ++) {
if (this.response.errorId === this.retryErrorIds[eIndex]) {
hasErrorId = true;
break;
}
}
shouldRetry = hasErrorId;
}
if (shouldRetry) {
this.retry();
return;
}
}
this.emit("AwsRequestEndError");
} else {
this.emit("AwsRequestEndSuccess");
}
if (this.callback && typeof this.callback === 'function') {
this.callback(this);
}
this.emit("AwsRequestEnd");
}
requestSuccessFunction () {
switch (this.returnSchema) {
case 'none':
break;
case 'json':
this.response.parsedJSON = null;
var parsedJSON;
try {
parsedJSON = JSON.parse(this.response.stdout);
} catch (e) {
this.response.error = e;
this.finishRequest();
return;
} finally {
this.response.parsedJSON = parsedJSON;
this.response.error = this.validateJSON();
if (this.response.error) {
this.finishRequest();
return;
}
}
break;
}
this.finishRequest();
}
validateJSON() {
if (!this.returnValidation) {
return null;
}
for (var i = 0; i < this.returnValidation.length; i++) {
var verifyResult = awsu.verifyPath(this.response.parsedJSON, this.returnValidation[i].path, this.returnValidation[i].type,"aws json response", this.awsCommand);
if (verifyResult.isVerifyError) {
return new Error(verifyResult.toString());
}
}
return null;
}
}
exports.AWSRequest = AWSRequest;
exports.createBatch = function createBatch(requestArray, callback) {
return new AWSRequestBatch(requestArray, callback);
};
class AWSRequestBatch extends EventEmitter {
constructor(requestArray, callback) {
super();
this.callback = callback;
this.requestArray = requestArray;
this.requestsInFlight = false;
this.requestComplete = false;
}
checkRequestStatus() {
for (var i = 0; i < this.requestArray.length; i++) {
if (!this.requestArray[i].requestComplete) {
return false;
}
}
this.requestInFlight = false;
this.requestComplete = true;
this.emit("AwsRequestEnd");
if (this.callback && typeof this.callback === 'function') {
this.callback(this);
}
}
startRequest(){
this.shouldStartRequest();
var me = this;
this.requestArray.forEach(function(request) {
request.on("AwsRequestEnd", function () {
me.checkRequestStatus();
});
request.startRequest();
});
this.requestInFlight = true;
this.emit("AwsRequestStart");
}
shouldStartRequest() {
if (this.requestInFlight) {
throw new Error("Attempting to request an inflight AWS Batch request.");
}
if (this.requestComplete) {
throw new Error("Attempting to request a completed AWS Batch request.");
}
}
}
exports.AWSRequestBatch = AWSRequestBatch;
<file_sep>"use strict";
const AWS = require("aws-sdk");
const cognitoidentity = new AWS.CognitoIdentity();
/**
* getOpenIDToken get a cognito OPEN ID token for user ID
* @param {AWS} AWS AWS instance
* @param {string} poolID cognito pool id
* @param {string} userID user ID
* @param {Function(err: Error, object: data)} callback cognito Open ID Token
*/
function getOpenIDToken(poolID, identityId, developerProvider, userID, callback) {
var params = {
IdentityPoolId: poolID,
Logins: {}
};
params.Logins[developerProvider] = userID;
if (identityId) {
params.IdentityId = identityId;
}
cognitoidentity.getOpenIdTokenForDeveloperIdentity(params, function (err, data) {
if (err) {
console.log(err);
callback(err);
} else {
console.log(data); // so you can see your result server side
callback(null, data);
}
});
}
exports.getOpenIDToken = getOpenIDToken;
function lookupIdentity(poolId, userID, callback) {
var params = {
IdentityPoolId: poolId,
DeveloperUserIdentifier: userID,
MaxResults: 1,
};
cognitoidentity.lookupDeveloperIdentity(params, function(err, data) {
if (err) {
console.log(err);
callback(err);
return;
}
console.log(data);
callback(null, data.IdentityId);
});
}
exports.lookupIdentity = lookupIdentity;
<file_sep>"use strict";
console.log("Loading function");
const fs = require("fs");
const AWSConstants = JSON.parse(fs.readFileSync("./AWSConstants.json", "utf8"));
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient();
const PH = require("./PasswordHash");
const UniqueID = require("./UniqueID");
const UserIdentity = require("./UserIdentity");
const APIParamVerify = require("./APIParamVerify");
const Devices = require("./Devices");
const MemcachePlus = require('memcache-plus');
var client = new MemcachePlus({
hosts: [AWSConstants.ELASTICACHE.MEMCACHE.configurationEndpoint],
autodiscover: true
});
/**
* handler signup
* @param {[type]} event [description]
* @param {[type]} context [description]
* @param {Function} callback [description]
* @return {[type]} [description]
*
*/
function handler(event, context, callback) {
process.on("uncaughtException", ( err ) => {
console.log(err);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Internal Error."
}));
});
// memcache plus seems to linger on the event loop.
context.callbackWaitsForEmptyEventLoop = false;
console.log(event);
// make sure we have needed params
var verifyResult = APIParamVerify.verify("/signup", "post", event);
if (verifyResult) {
verifyResult.requestId = context.awsRequestId;
console.log(verifyResult);
callback(JSON.stringify(verifyResult));
return;
}
// Lets apply a cool-down to signup.
// Use memcache to store the last time it was called
// and rate limit.
client
.get('signup.callTime')
.then(function(callTime) {
console.log("signup.callTime = " + callTime);
if (callTime && (Date.now() - callTime < 8000)) {
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "ServiceUnavailable",
httpStatus: 503,
message: "Service Unavailable."
}));
} else {
client
.set('signup.callTime', Date.now())
.then(function() {
console.log("Witten call time.");
checkEmailAction();
});
}
});
function checkEmailAction() {
// check if the email has already been used
var params = {
TableName: AWSConstants.DYNAMO_DB.EMAILS.name,
Key: {}
};
params.Key[AWSConstants.DYNAMO_DB.EMAILS.EMAIL] = event.email;
docClient.get(params, function (err, data) {
if (err) {
console.log(err);
console.log("Could not validate for email for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not validate email."
}));
} else {
// if we get some objects back from the email table then the users has already signed up
if (typeof data.Item === "object") {
console.log(data);
var errorObject = {
requestId: context.awsRequestId,
errorType: "Conflict",
httpStatus: 409,
message: "Item exists"
};
console.log(errorObject);
callback(JSON.stringify(errorObject));
} else {
createCognitoIdentity();
}
}
});
}
function createCognitoIdentity() {
// generate a unique id for the user as the developer provier id
UniqueID.getUniqueId(AWSConstants.DYNAMO_DB.USERS.name, docClient, function (err, newID) {
if (err) {
console.log(err);
console.log("Could not generate new id for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not generate new id."
}));
} else {
// now create a cognito identity with ths id and custome provider
UserIdentity.getOpenIDToken(AWSConstants.COGNITO.IDENTITY_POOL.identityPoolId, null, AWSConstants.COGNITO.IDENTITY_POOL.authProviders.custom.developerProvider, newID, function (err, OpenIDToken) {
if (err) {
console.log(err);
console.log("Could not generate open id token for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not generate open id token."
}));
} else {
writeUserInformation(newID, OpenIDToken);
}
});
}
});
}
function writeUserInformation(newID, OpenIDToken) {
// Add the email to the email table with provider token
// login will use this to lookup the identity
var paramsEmail = {
TableName: AWSConstants.DYNAMO_DB.EMAILS.name,
Item: {}
};
paramsEmail.Item[AWSConstants.DYNAMO_DB.EMAILS.EMAIL] = event.email;
paramsEmail.Item[AWSConstants.DYNAMO_DB.EMAILS.ID] = newID;
docClient.put(paramsEmail, function (err) {
if (err) {
console.log(err);
console.log("Could not put email and id to emails db for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not put email and id."
}));
}
});
var now = Date.now();
// Add the user to the user table
var paramsUser = {
TableName: AWSConstants.DYNAMO_DB.USERS.name,
Item: {}
};
paramsUser.Item[AWSConstants.DYNAMO_DB.USERS.ID] = OpenIDToken.IdentityId;
paramsUser.Item[AWSConstants.DYNAMO_DB.USERS.PASSWORD] = <PASSWORD>(event.<PASSWORD>);
paramsUser.Item[AWSConstants.DYNAMO_DB.USERS.EMAIL] = event.email;
paramsUser.Item[AWSConstants.DYNAMO_DB.USERS.SIGNUP_TIMESTAMP] = now;
paramsUser.Item[AWSConstants.DYNAMO_DB.USERS.LAST_LOGIN_TIMESTAMP] = -1;
paramsUser.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_COUNT] = 0;
if (event.name) {
paramsUser.Item[AWSConstants.DYNAMO_DB.USERS.NAME] = event.name;
}
if (event.dob) {
paramsUser.Item[AWSConstants.DYNAMO_DB.USERS.DOB] = event.dob;
}
docClient.put(paramsUser, function (err) {
if (err) {
console.log(err);
console.log("Could not put user info to db for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not put user info."
}));
} else {
// associate this device id with the user
Devices.addUserId(event.device_id, OpenIDToken.IdentityId, function (err) {
if (err) {
console.log("Error creating device token.");
console.log(err);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not store user device."
}));
} else {
callback(null, OpenIDToken);
}
});
}
});
}
}
exports.handler = handler;
<file_sep>'use strict';
function topbar(menus) {
var ctrl = this;
ctrl.createItemList = function() {
var items =[];
var selectedMenu = menus[ctrl.menuName];
for (var index = 0; index<selectedMenu.length; index ++) {
var menuItem = selectedMenu[index];
var listItem = {};
if (ctrl.selectedItem === menuItem.item) {
listItem.selected = true;
} else {
listItem.selected = false;
}
listItem.name = menuItem.name;
listItem.href = menuItem.href;
items.push(listItem);
}
return items;
};
ctrl.items = ctrl.createItemList();
}
angular
.module('topbarModule',['menuProperties'])
.component('topbar', {
bindings: {
selectedItem: '@',
menuName: '@'
},
templateUrl: 'components/topbar/topbar.html',
controller: topbar
});
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const vp = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Delete the project lambdas.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.alias('l','lambdaDefinitionsDir')
.describe('l','directory that contains lambda definition files and implementations. <lambdaName>.zip archives will be placed here.')
.default('l','./lambdas')
.alias('n','lambdaName')
.describe('n','a specific lambda to process. If not specified all lambdas found will be uploaded')
.help('h')
.alias('h', 'help');
const argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
if (!fs.existsSync(argv.lambdaDefinitionsDir)) {
console.log("Lambda's path \"" + argv.lambdasPath + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
console.log("## Deleting Lambdas ##");
var AWSCLIUserProfile = "default";
if (typeof baseDefinitions.environment !== 'object') {
} else {
if (typeof baseDefinitions.environment.AWSCLIUserProfile === 'string') {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
}
}
if (AWSCLIUserProfile === "default") {
console.log("using \"default\" AWSCLIUserProfile");
}
forEachLambdaDefinition(function (fileName) {
// here we would want to fork to do ops in parallel
var definitions = YAML.load(path.join(argv.lambdaDefinitionsDir,fileName));
if (typeof definitions !== 'object') {
throw new Error("Definitions file \"" + fileName + "\" could not be parsed");
}
if (vp.verifyPath(definitions,['lambdaInfo', 'arnLambda'], 's', "definitions file \"" + fileName + "\"").isValidationErrpr) {
throw new Error("There is no a \"arnLambda\" string in \"lambdaInfo\" object in definitions file \"" + fileName + "\".");
}
vp.verifyPath(definitions,['lambdaInfo', 'functionName'], 's', "definitions file \"" + fileName + "\"").exitOnError();
var lambdaName;
if (vp.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
lambdaName = baseDefinitions.environment.AWSResourceNamePrefix + definitions.lambdaInfo.functionName;
}
var params = {
'function-name': {type: 'string', value: lambdaName},
'profile' : {type: 'string', value:AWSCLIUserProfile}
};
// capture values here by creating a function
deleteLambda(params, path.join(argv.lambdaDefinitionsDir,fileName));
});
function deleteLambda(reqParams, defaultsFileName) {
var deleteRequest = AWSRequest.createRequest({
serviceName: "lambda",
functionName: "delete-function",
parameters:reqParams,
retryCount: 6,
retryErrorIds: ['ServiceException'],
retryDelay: 3000,
returnSchema:'none'
},
function (request) {
if (request.response.error) {
if (request.response.errorId === 'ResourceNotFoundException') {
console.log("Warning: lambda \"" + request.parameters["function-name"].value + "\" not found.");
} else {
throw request.response.error;
}
}
console.log("Deleted lambda \"" + request.parameters["function-name"].value + "\"");
console.log("Updating defaults file: \"" + defaultsFileName + "\"");
var localDefinitions = YAML.load(defaultsFileName);
vp.updateFile(defaultsFileName, function () {
delete localDefinitions.lambdaInfo.arnLambda;
return YAML.stringify(localDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + defaultsFileName + "\". arnLambda was not updated.");
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file.");
throw writeErr;
}
});
});
deleteRequest.on('AwsRequestRetry', function () {
console.log("Warning: unable to delete lambda \"" + this.parameters["function-name"].value + "\" due to \"ServiceException\". This happens occasionally when deleting a number of lambdas at once. Trying again...");
});
deleteRequest.startRequest();
}
function forEachLambdaDefinition (callback) {
fs.readdir(argv.lambdaDefinitionsDir, function (err, files) {
if (err) {
console.log(err);
process.exit(1);
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var writeOut = true;
if ((typeof argv.lambdaName === 'string') && (argv.lambdaName !== fileNameComponents[0])) {
console.log("Not target lambda. Skipping.");
writeOut = false;
}
if (writeOut) {
callback(fileName);
}
}
}
});
}
<file_sep>"use strict";
const fs = require("fs");
const path = require("path");
const LintStream = require("jslint").LintStream;
const linter = "jshint";
const JSHINT = require("jshint");
const AWSRequest = require(path.join(__dirname, 'AwsRequest'));
/**
* This class acts as a container for a 'verifyPath' result and
* allows the caller to halt execution on error.
*/
class VerifyResultString extends Object {
constructor (errorMessage, isVerifyError) {
super();
if (typeof isVerifyError === "boolean") {
this.isVerifyError = isVerifyError;
} else {
this.isVerifyError = false;
}
this.errorMessage = errorMessage;
}
toString() {
return this.errorMessage;
}
exitOnError() {
if (this.isVerifyError) {
throw new Error(this.errorMessage);
}
}
callbackOnError(callback) {
if (this.isVerifyError) {
callback(this);
}
return(this);
}
}
exports.VerifyResultString = VerifyResultString;
function verifyPath(structure, pathArray, leafTypeKey, itemName, extraString) {
var leafTypes = {"s" : "string",
"n" : "number",
"o" : "object",
"a" : "array",
"f" : "function",
"b" : "boolean"
};
if (!extraString) {
extraString = "";
}
var result = checkPath(structure, pathArray, leafTypeKey);
if (!result) {
return new VerifyResultString();
}
var path = pathArray.join(".");
var errorString;
var key1String;
var key2String;
if (typeof leafTypeKey === "object") {
errorString = "Failed validation of action \"" + result.failAction + "\". ";
if (result.failIndex === 0) {
switch (result.failAction) {
case "oneOfs":
key1String = "string ([" + leafTypeKey.oneOfs.join("|") + "])";
key2String = leafTypes[getTypeKey(structure)];
break;
default:
}
}
} else {
errorString = "";
key1String = leafTypes[leafTypeKey];
key2String = leafTypes[getTypeKey(structure)];
}
if (result.failIndex === 0) {
errorString += "The item \"" + path + "\" of expected type \"" + key1String + "\" was not found because the \"" + itemName + "\" was of type " + key2String + ". " + extraString;
} else if (result.failIndex < pathArray.length) {
errorString += "The item \"" + path + "\" of expected type \"" + key1String + "\" in the " + itemName + " was not found because \"" + pathArray[result.failIndex - 1] + "\" was not an object. It was of type \"" + leafTypes[result.failType] + "\". " + extraString;
} else {
errorString += "The item \"" + path + "\" of expected type \"" + key1String + "\" in the " + itemName + " was not found because \"" + pathArray[result.failIndex - 1] + "\" was of type \"" + leafTypes[result.failType] + "\"." + extraString;
}
var x = new VerifyResultString(errorString, true);
return x;
}
exports.verifyPath = verifyPath;
function checkPath(structure, pathArray, leafTypeKey) {
var items = [structure];
var index = 0;
var typeResult = "x";
for (; index < pathArray.length; index++) {
var nextItems = [];
var breakOut = false;
for (var itemIndex = 0; itemIndex < items.length; itemIndex++) {
var item = items[itemIndex];
typeResult = getTypeKey(item);
switch (typeResult) {
case "a":
// if it is an array push each item for verification on the next pass
item.forEach(function (arrayItem) {
nextItems.push(arrayItem[pathArray[index]]);
});
break;
case "o":
// when * is encountered on the path we push each item regardless of key.
if (pathArray[index] === "*") {
Object.keys(item).forEach(function (itemKey) {
nextItems.push(item[itemKey]);
});
} else {
nextItems.push(item[pathArray[index]]);
}
break;
default:
breakOut = true;
}
if (breakOut) {
break;
}
}
if (breakOut) {
break;
}
items = nextItems;
}
if (index !== pathArray.length) {
return {failIndex:index, failType:typeResult};
}
for (var itemIndex2 = 0; itemIndex2 < items.length; itemIndex2++) {
var item2 = items[itemIndex2];
typeResult = getTypeKey(item2);
// if the leadTypeKey is an object check to see which command should be executed
if (typeof leafTypeKey === "object") {
var actions = Object.keys(leafTypeKey);
for (var oneOfsIndex = 0; oneOfsIndex < actions.length; oneOfsIndex ++) {
var action = actions[oneOfsIndex];
switch (action) {
case "oneOfs":
// value for oneOfs is an array of strings.
if ((typeResult !== "s") || (leafTypeKey[action].indexOf(item2)) < 0) {
return {failIndex:index, failType:typeResult, failAction:action};
}
break;
default:
console.log("Unrecognized leafTypeKey command: " + action);
}
}
} else if (typeResult !== leafTypeKey) {
return {failIndex:index, failType:typeResult};
}
}
return null;
}
function getTypeKey(item) {
var typeKey = "u";
switch (typeof item) {
case "string":
typeKey = "s";
break;
case "number":
typeKey = "n";
break;
case "boolean":
typeKey = "b";
break;
case "object":
// null
if (!item) {
typeKey = "n";
} else if (Array.isArray(item)) {
typeKey = "a";
} else {
typeKey = "o";
}
break;
case "undefined":
typeKey = "u";
break;
case "function":
typeKey = "f";
break;
case "symbol":
typeKey = "s";
break;
default:
typeKey = "u";
}
return typeKey;
}
exports.updateFile = function updateFile(fName, dataCallback, callback, retry) {
if (fs.existsSync(fName + ".old")) {
fs.unlinkSync(fName + ".old");
}
fs.rename(fName, fName + ".old", function (err){
if (err) {
// file does not exist... likely someone else trying to write it.
if (retry === 5) {
callback(err,null);
return;
}
if (!retry) {
retry = 0;
}
setTimeout(function() {
exports.updateFile(fName, dataCallback, callback, retry + 1);
}, 250);
return;
}
fs.writeFile(fName, dataCallback(), function (err) {
if (err) {
callback(null,err);
return;
}
callback(null,null);
});
});
};
exports.validatejs = function(lambdaDefintitions, lambdaPath) {
var implementationFiles=[];
var addFile = function(filePath) {
if (path.extname(filePath) === ".js") {
implementationFiles.push(filePath);
}
};
// make a file list from the definitions
// get the base implementation files first
lambdaDefintitions.implementationFiles[lambdaDefintitions.lambdaInfo.functionName].forEach(addFile);
// now add the link file skipping directories
if (lambdaDefintitions.linkFiles) {
Object.keys(lambdaDefintitions.linkFiles).forEach(function(fileArrayKey) {
lambdaDefintitions.linkFiles[fileArrayKey].forEach(addFile);
});
}
if (linter==="jslint") {
var options = {
"length": 100,
"node": true,
"fudge": true,
"edition": "latest",
"es6": true,
"stupid": true,
"for": true
};
var l = new LintStream(options);
l.on("data", function (chunk, encoding, callback) {
// chunk is an object
// chunk.file is whatever you supplied to write (see above)
console.log(chunk.file);
console.log(chunk.linted.errors);
// chunk.linted is an object holding the result from running JSLint
// chunk.linted.ok is the boolean return code from JSLINT()
// chunk.linted.errors is the array of errors, etc.
// see JSLINT for the complete contents of the object
if (callback) {
callback();
}
});
implementationFiles.forEach(function(file){
console.log(path.join(lambdaPath, file));
var code = fs.readFileSync(path.join(lambdaPath, file), "utf8");
l.write({file: file, body: code});
});
}
if (linter === "jshint") {
implementationFiles.forEach(function(file){
console.log(path.join(lambdaPath, file));
var code = fs.readFileSync(path.join(lambdaPath, file), "utf8");
JSHINT.JSHINT(code,{
node: true,
esversion: 6,
undef: true,
unused: true,
eqeqeq: true
},{});
if (!JSHINT.JSHINT.data().errors) {
console.log("No lint errors!");
} else {
console.log(JSHINT.JSHINT.data().errors);
}
});
}
};
exports.createPath = function (pathString) {
// make sure the download path exists. If not create it.
var downloadPath;
if (!path.isAbsolute(pathString)) {
downloadPath = path.join(path.resolve(), pathString);
} else {
downloadPath = pathString;
}
downloadPath = path.normalize(downloadPath);
var downloadPathComponents = downloadPath.split(path.sep);
var mkPath = path.sep;
downloadPathComponents.forEach(function (pathComponent) {
mkPath = path.join(mkPath, pathComponent);
if (!fs.existsSync(mkPath)){
fs.mkdirSync(mkPath);
}
});
};
exports.isValidAWSResourceNamePrefix = function (baseDefinitions, fileName) {
var prefix = baseDefinitions.environment.AWSResourceNamePrefix;
if (!prefix) {
throw new Error("Please assign a AWSResourceNamePrefix at 'environment.AWSResourceNamePrefix' in base definitions file '" + fileName + "'. AWSResourceNamePrefix unfortunately must be all lower case [a-z] characters.");
}
var testPattern = /^[a-z]+$/;
if (!testPattern.test(prefix)) {
throw new Error("Invalid AWSResourceNamePrefix at AWSResourceNamePrefix in 'environment.AWSResourceNamePrefix' in base definitions file '" + fileName + "'. AWSResourceNamePrefix unfortunately must be all lower case [a-z] characters.");
}
return true;
};
exports.addLambdaVPCConfiguration = function(params, definitions, fileName, baseDefinitions, baseDefinitionsFileName) {
var secgroupNames;
if (verifyPath(definitions,["lambdaInfo", "securityGroups"], 'a').isVerifyError) {
secgroupNames = [];
} else {
secgroupNames = definitions.lambdaInfo.securityGroups;
}
var secGroupIds = [];
for (var index = 0; index < secgroupNames.length; index ++) {
verifyPath(baseDefinitions, ["securityGroupInfo", "securityGroups", secgroupNames[index], "GroupId"], 's', "for security group '" + secgroupNames[index] + "' in lambda definitions file '" + fileName + "'").exitOnError();
secGroupIds.push(baseDefinitions.securityGroupInfo.securityGroups[secgroupNames[index]].GroupId);
}
if (!verifyPath(definitions,["lambdaInfo", "vpcDefaultSecurityGroups"], 'a').isVerifyError) {
var vpcs = definitions.lambdaInfo.vpcDefaultSecurityGroups;
vpcs.forEach(function (vpcName) {
verifyPath(baseDefinitions,["vpcInfo", "vpcs", vpcName, "GroupId"], 's', "for security vpc default secrity group '" + vpcName + "' in lambda definitions file '" + fileName + "'").exitOnError();
secGroupIds.push(baseDefinitions.vpcInfo.vpcs[vpcName].GroupId);
});
}
// see if we have enough information to add VPC
var pathErrorSubnets = verifyPath(definitions,["lambdaInfo", "subnets"], 'a', "definitions file \"" + fileName + "\"");
var subnetIds = [];
if (!pathErrorSubnets.isVerifyError) {
var subnets = definitions.lambdaInfo.subnets;
subnets.forEach(function (subnetName) {
verifyPath(baseDefinitions, ["subnetInfo", "subnets", subnetName, "SubnetId"], "s", "base definition file " + baseDefinitionsFileName).exitOnError();
subnetIds.push(baseDefinitions.subnetInfo.subnets[subnetName].SubnetId);
});
}
if ((secGroupIds.length === 0) && (subnetIds.length === 0)) {
// nothing to do
return;
}
if (((secGroupIds.length === 0) && (subnetIds.length !== 0)) || ((secGroupIds.length !== 0) && (subnetIds.length === 0))) {
throw new Error("VPC configuration requires both a security group (either defined in secuityGroupInfo or a VPC default security group) and subnet in definitions file \"" + fileName + "\"");
}
// make a list if sec group ids
console.log("Adding VPC configuration");
var vpcConfigString = "SubnetIds=" + subnetIds.join(",") + ",SecurityGroupIds=" + secGroupIds.join(",");
params["vpc-config"]= {type: "string", value: vpcConfigString};
};
function checkEc2ResourceTagName(nameTag, resourceName, AWSCLIUserProfile, callback) {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "describe-tags",
parameters:{
"filters": {type: "string", value: "Name=value,Values=" + nameTag},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
},
function (request) {
if (request.response.error) {
callback(false, null, nameTag, resourceName);
return;
}
if (!request.response.parsedJSON.Tags || (request.response.parsedJSON.Tags.length === 0)) {
callback(false, null, nameTag, resourceName);
return;
}
callback(true, request.response.parsedJSON.Tags, nameTag, resourceName);
}).startRequest();
}
exports.checkEc2ResourceTagName = checkEc2ResourceTagName;
function describeEc2ResourceForService(describeCommand, resourceResult, name, VpcId, AWSCLIUserProfile, waitForAtLeastOneResult, callback, retryCount) {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: describeCommand,
parameters:{
"filters": {type: "string", value: "Name=" + name + ",Values=" + VpcId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
retryCount: 3,
retryDelay: 5000
},
function (request) {
if (!retryCount) {
retryCount = 0;
}
if (request.response.error || retryCount === 3) {
console.log(request.response.error);
console.log("Unable to fetch " + resourceResult);
if (request.response.error) {
callback(request.response.error);
return;
}
callback(new Error("Unable to fetch " + resourceResult));
return;
}
if (waitForAtLeastOneResult && request.response.parsedJSON[resourceResult].length === 0) {
setTimeout(function() {describeEc2ResourceForService(describeCommand, resourceResult, name, VpcId, AWSCLIUserProfile, waitForAtLeastOneResult, callback, retryCount + 1);}, 5000);
return;
}
callback(null, request.response.parsedJSON[resourceResult]);
}).startRequest();
}
exports.describeEc2ResourceForService = describeEc2ResourceForService;
function createEc2ResourceTag(resourceId, nameTag, AWSCLIUserProfile, callback) {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "create-tags",
parameters:{
"resource": {type: "string", value: resourceId},
"tags": {type: "string", value: "Key=Name,Value=" + nameTag},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'none',
retryCount: 3,
retryDelay: 5
},
function (request) {
callback(request.response.error);
}).startRequest();
}
exports.createEc2ResourceTag = createEc2ResourceTag;
function replaceAnyOccuranceOfStringInObject(object, string, replaceString) {
if (Array.isArray(object)) {
object.slice().forEach(function (item, index) {
if (Array.isArray(item) || (typeof item === 'object')) {
replaceAnyOccuranceOfStringInObject(item, string, replaceString);
} else if (typeof item === 'string') {
object[index] = item.replace(string, replaceString);
}
});
} else if (typeof object === 'object') {
Object.keys(object).forEach(function (itemName) {
if (Array.isArray(object[itemName]) || (typeof object[itemName] === 'object')) {
replaceAnyOccuranceOfStringInObject(object[itemName], string, replaceString);
} else if (typeof object[itemName] === 'string') {
object[itemName] = object[itemName].replace(string, replaceString);
}
});
}
}
exports.replaceAnyOccuranceOfStringInObject = replaceAnyOccuranceOfStringInObject;
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Delete Subnets.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.help('h')
.alias('h', 'help');
var argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Deleting Subnets ##");
if (awsc.verifyPath(baseDefinitions,['subnetInfo', 'subnets'],'o').isVerifyError) {
console.log("Nothing to do.");
return;
}
Object.keys(baseDefinitions.subnetInfo.subnets).forEach(function (subnetName) {
var subnetDescription = baseDefinitions.subnetInfo.subnets[subnetName];
if (awsc.verifyPath(subnetDescription,["SubnetId"],'s').isVerifyError) {
console.log("Subnet '" + subnetName + "' is already deleted. Please use createSubnet.js first.");
return;
}
// check to see if the name tag exists
var nameTag = baseDefinitions.environment.AWSResourceNamePrefix + subnetName + "Subnet";
console.log("Deleting Subnet with tag name '" + nameTag + "'");
deleteSubnet(nameTag, subnetName, function (err, tagName, subnetName) {
if (err) {
console.log(err);
return;
}
writeOut("Could not update deleted SubnetId for Subnet '" + subnetName + "'.");
});
});
function deleteSubnet(nameTag, subnetName, callback) {
fetchNetworkInterfaces(subnetName, function (subnetName, networkInterfaces) {
deleteNetworkInterfaces(subnetName, networkInterfaces, function (subnetName) {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "delete-subnet",
parameters:{
"subnet-id": {type: "string", value: baseDefinitions.subnetInfo.subnets[subnetName].SubnetId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'none',
},
function (request) {
if (request.response.error && (request.response.errorId !== "InvalidSubnetID.NotFound")) {
callback(request.response.error, nameTag, subnetName);
return;
}
delete baseDefinitions.subnetInfo.subnets[subnetName].SubnetId;
console.log("Deleted Subnet '" + subnetName + "'");
callback(null, nameTag, subnetName);
}).startRequest();
});
});
}
function fetchNetworkInterfaces(subnetName, callback) {
awsc.describeEc2ResourceForService("describe-network-interfaces",
"NetworkInterfaces",
"subnet-id",
baseDefinitions.subnetInfo.subnets[subnetName].SubnetId,
AWSCLIUserProfile,
false,
function (err, resourceResult) {
if (err) {
throw err;
}
callback(subnetName, resourceResult);
});
}
function deleteNetworkInterfaces(subnetName, networkInterfaces, callback) {
if (!networkInterfaces || (networkInterfaces.length === 0)) {
callback(subnetName);
return;
}
var networkInterfaceDetachRequests = [];
var networkInterfaceDeleteRequests = [];
networkInterfaces.forEach(function (networkInterface) {
if (!awsc.verifyPath(networkInterface, ["Attachment", "AttachmentId"], 's').isVerifyError) {
networkInterfaceDetachRequests.push(
AWSRequest.createRequest(
{
serviceName: "ec2",
functionName: "detach-network-interface",
context: {NetworkInterfaceId: networkInterface.NetworkInterfaceId},
parameters:{
"attachment-id": {type: "string", value: networkInterface.Attachment.AttachmentId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'none',
},
function (request) {
console.log("Detached networkInterface with ID '" + request.parameters["attachment-id"].value + "'");
}
)
);
}
networkInterfaceDeleteRequests.push(
AWSRequest.createRequest(
{
serviceName: "ec2",
functionName: "delete-network-interface",
parameters:{
"network-interface-id": {type: "string", value: networkInterface.NetworkInterfaceId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'none',
},
function (request) {
console.log("Deleted networkInterface with ID '" + request.parameters["network-interface-id"].value + "'");
}
)
);
});
// utility to batch delete NI
function deleteRequests () {
if (networkInterfaceDeleteRequests.length > 0) {
AWSRequest.createBatch(networkInterfaceDeleteRequests, function (batchRequest) {
var errorCount = 0;
batchRequest.requestArray.forEach(function (request) {
if (request.response.error) {
errorCount += 1;
console.log(request.response.error);
}
});
if (errorCount > 0) {
process.exit(1);
}
callback(subnetName);
}).startRequest();
} else {
callback(subnetName);
}
}
// utility to wait for NI to be detached
function waitForNIDDetached(describeRequests, doneCallback, retry) {
if (!retry) {
retry = 1;
}
if (describeRequests.length === 0) {
doneCallback();
return;
}
AWSRequest.createBatch(describeRequests, function (batchRequest) {
var finishedCount = 0;
var errorCount = 0;
batchRequest.requestArray.forEach(function (request) {
if (request.response.error) {
console.log(request.response.error);
errorCount ++;
} else {
if (!awsc.verifyPath(request.response.parsedJSON,["NetworkInterfaces"],'a').isVerifyError) {
if (request.response.parsedJSON.NetworkInterfaces.length > 0) {
if (awsc.verifyPath(request.response.parsedJSON.NetworkInterfaces[0], ["Attachment", "AttachmentId"], 's').isVerifyError) {
finishedCount ++;
}
} else {
// didn't get any feedback for the NID... assume deleted.
finishedCount ++;
}
} else {
// these no longer exist... must have been deleted
finishedCount ++;
}
}
request.reset();
});
if (errorCount > 0) {
process.exit(1);
}
if (finishedCount === describeRequests.length) {
doneCallback();
} else {
if (retry === 10) {
throw new Error("Too many retries waiting for Network Interfaces to detach.");
}
setTimeout(function () {
console.log("Waiting for Network Interfaces to detach. Retry " + retry + " of 10.");
waitForNIDDetached(describeRequests, doneCallback, retry + 1);
}, 3000);
}
}).startRequest();
}
if (networkInterfaceDetachRequests.length > 0) {
AWSRequest.createBatch(networkInterfaceDetachRequests, function (batchRequest) {
var errorCount = 0;
var attachementWaitRequests = [];
// need to wait for NIDs to detach
batchRequest.requestArray.forEach(function (request) {
if (request.response.error) {
errorCount += 1;
console.log(request.response.error);
} else {
attachementWaitRequests.push(
AWSRequest.createRequest(
{
serviceName: "ec2",
functionName: "describe-network-interfaces",
parameters:{
"network-interface-ids": {type: "string", value: request.context.NetworkInterfaceId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:"json"
},
function (request) {
console.log("Detached networkInterface with ID '" + request.parameters["network-interface-ids"].value + "'");
}
)
);
}
});
if (errorCount > 0) {
process.exit(1);
}
// wait for detachment before deleting
waitForNIDDetached(attachementWaitRequests, deleteRequests);
}).startRequest();
} else {
deleteRequests();
}
}
function writeOut(errorText) {
// now delete role
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". " + errorText);
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file. " + errorText);
throw writeErr;
}
});
}
<file_sep>#!/bin/bash
set -e
# remove API
AWSTools/deleteRestAPI.js
# remove lambdas
AWSTools/deleteLambda.js
# remove dbs
AWSTools/deleteDynamodb.js
# remove identity pools
AWSTools/deleteIdentityPool.js
# remove S3 buckets
AWSTools/deleteS3Bucket.js --type lambda
# remove memcache - done last because this operation can take 5 minutes
AWSTools/deleteElastiCache.js
# remove roles
AWSTools/deleteRole.js --roleType api
AWSTools/deleteRole.js --roleType lambda
AWSTools/deleteRole.js --roleType cognito
#remove security groups and VPCs
AWSTools/deleteNatGateway.js
AWSTools/deleteRouteTable.js
AWSTools/deleteInternetGateway.js
AWSTools/deleteSubnet.js
AWSTools/deleteVPC.js
# remove Angular client s3 bucket
AWSTools/deleteS3Bucket.js --type webClient
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Creates Route Tables.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.help('h')
.alias('h', 'help');
var argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Creating Route Tables ##");
if (awsc.verifyPath(baseDefinitions,['routeTableInfo', 'routeTables'],'o').isVerifyError) {
console.log("Nothing to do.");
return;
}
Object.keys(baseDefinitions.routeTableInfo.routeTables).forEach(function (routeTableName) {
/* var networkAclDescription = baseDefinitions.networkAclInfo.networkAcls[networkAclName];
if (!awsc.verifyPath(networkAclDescription,["networkAclId"],'s').isVerifyError) {
console.log("Network ACL '" + networkAclName + "' is already defined. Please use deleteNetworkAcl.js first.");
return;
}*/
// check to see if the name tag exists
var nameTag = baseDefinitions.environment.AWSResourceNamePrefix + routeTableName + "RouteTable";
console.log("Checking for Route Table with tag name '" + nameTag + "'");
awsc.checkEc2ResourceTagName(nameTag, routeTableName, AWSCLIUserProfile, function(tagExists, results, tagName, routeTableName) {
if (tagExists) {
console.log("Route Table '" + tagName + "' exists. updating local definitions with existing ID.");
// update Route Table info with existing tag IDs
if (!baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable) {
baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable = {};
}
baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable.RouteTableId = results[0].ResourceId;
// write out result
commitUpdates(routeTableName);
makeSubnetAssociations(routeTableName);
addRoutes(routeTableName);
} else {
console.log("Creating new Route Table with tag name '" + tagName + "'");
createRouteTable(tagName, routeTableName, function (err, tagName, routeTableName) {
if (err) {
console.log(err);
return;
}
commitUpdates(routeTableName);
makeSubnetAssociations(routeTableName);
addRoutes(routeTableName);
});
}
});
});
function commitUpdates(routeTableName) {
writeOut("Could not update RouteTableId for Route Table '" + routeTableName + "'.");
}
function createRouteTable(nameTag, routeTableName, callback) {
var pathError = awsc.verifyPath(baseDefinitions,["vpcInfo", "vpcs", baseDefinitions.routeTableInfo.routeTables[routeTableName].vpc, "VpcId"], "s", "definitions file \"" + argv.baseDefinitionsFile + "\"");
if (pathError.isVerifyError) {
console.log(pathError);
throw new Error("Please create the VPC first using 'createVPC.js'");
}
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "create-route-table",
parameters:{
"vpc-id": {type: "string", value: baseDefinitions.vpcInfo.vpcs[baseDefinitions.routeTableInfo.routeTables[routeTableName].vpc].VpcId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['RouteTable', 'RouteTableId'], type:'s'}]
},
function (request) {
if (request.response.error) {
callback(request.response.error, nameTag, routeTableName);
return;
}
baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable = request.response.parsedJSON.RouteTable;
// clear out associations because this is a new route table.
baseDefinitions.routeTableInfo.routeTables[routeTableName].Associations = {};
awsc.createEc2ResourceTag(baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable.RouteTableId, nameTag, AWSCLIUserProfile, function (err) {
callback(err, nameTag, routeTableName);
});
}).startRequest();
}
function makeSubnetAssociations(routeTableName) {
if (awsc.verifyPath(baseDefinitions, ["routeTableInfo", "routeTables", routeTableName, "subnetAssociations"],'a').isVerifyError) {
return;
}
var associations = baseDefinitions.routeTableInfo.routeTables[routeTableName].subnetAssociations;
associations.forEach(function (subnetName) {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "associate-route-table",
context: {subnetName: subnetName, routeTableName: routeTableName},
parameters:{
"subnet-id": {type: "string", value: baseDefinitions.subnetInfo.subnets[subnetName].SubnetId},
"route-table-id": {type: "string", value: baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable.RouteTableId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['AssociationId'], type:'s'}]
},
function (request) {
if (request.response.error) {
console.log("Could not create subnet association '" + request.context.subnetName + "' for route table '" + request.context.routeTableName + "'.");
throw request.response.error;
}
if (!baseDefinitions.routeTableInfo.routeTables[routeTableName].Associations) {
baseDefinitions.routeTableInfo.routeTables[routeTableName].Associations = {};
}
baseDefinitions.routeTableInfo.routeTables[routeTableName].Associations[request.context.subnetName] = request.response.parsedJSON.AssociationId;
console.log("Created subnet associlation " + request.context.subnetName + "' for route table '" + request.context.routeTableName + "'.");
writeOut("Could not save subnet association '" + request.context.subnetName + "' for route table '" + request.context.routeTableName + "'.");
}).startRequest();
});
}
function addRoutes(routeTableName) {
if (awsc.verifyPath(baseDefinitions, ["routeTableInfo", "routeTables", routeTableName, "routes"],'a').isVerifyError) {
return;
}
var routes = baseDefinitions.routeTableInfo.routeTables[routeTableName].routes;
routes.forEach(function (route) {
var params = {
"route-table-id": {type: "string", value: baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable.RouteTableId},
"profile": {type: "string", value: AWSCLIUserProfile}
};
Object.keys(route).forEach(function (routeKey) {
var key;
var value;
if (routeKey === "internetGateway") {
key = "gateway-id";
value = baseDefinitions.internetGatewayInfo.internetGateways[route[routeKey]].InternetGateway.InternetGatewayId;
} else {
key = routeKey;
value = route[routeKey];
}
params[key] = {type: "string", value: value};
});
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "create-route",
context: {route: route, routeTableName: routeTableName},
parameters: params,
returnSchema:'none'
},
function (request) {
if (request.response.error) {
console.log("Could not create route '" + JSON.stringify(request.context.route) + "' for route table '" + request.context.routeTableName + "'.");
throw request.response.error;
}
console.log("Created route '" + JSON.stringify(request.context.route) + "' for route table '" + request.context.routeTableName + "'.");
}).startRequest();
});
}
function writeOut(errorText) {
// now delete role
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". " + errorText);
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file. " + errorText);
throw writeErr;
}
});
}
<file_sep>platform :ios, '8.0'
use_frameworks!
target 'lambdaAuth' do
pod 'AFNetworking', '~> 2.6'
pod 'AWSAPIGateway', '~> 2.4.2'
pod 'InputValidators', '~> 1.0.0'
pod 'UICKeyChainStore', '~> 2.0.0'
pod 'AsyncImageView', '~> 1.6'
end
<file_sep>#!/usr/bin/env node
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const fs = require('fs');
const YAML = require('yamljs');
const argv = require('yargs')
.usage('Create a json description of constants needed to access AWS services.\nUsage: $0 [options]')
.alias('l','definitionsDir')
.describe('l','directory containing definition yaml files')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your dynamodb (dynamodbInfo)')
.default('s','./base.definitions.yaml')
.alias('o','outputFilename')
.describe('o','name of file that will be added to each lambda directory')
.default('o','AWSConstants.json')
.alias('n','lambdaName')
.describe('n','update handler event params for only this lambda directory')
.alias('t', 'constantsType')
.describe('t', 'which constants to update [lambda | client]')
.choices('t', ['lambda', 'client'])
.demand(['t'])
.help('h')
.alias('h', 'help')
.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
argv.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
console.log("## Updating AWS Constants ##");
var constantPathBase;
var definitionsBase;
switch (argv.constantsType) {
case 'lambda':
if (argv.definitionsDir) {
constantPathBase = argv.definitionsDir;
} else {
constantPathBase = 'lambdas';
}
definitionsBase = 'lambdaInfo';
break;
case 'client':
if (argv.definitionsDir) {
constantPathBase = argv.definitionsDir;
} else {
constantPathBase = 'clients';
}
definitionsBase = 'clientInfo';
break;
default:
}
// required --lambdaDefinitionsDir directory
// required --outputFilename
// optional --lambdaName
// the "paths" component is in the lambdaDefinitions
// at apiInfo.path
forEachDefinition(function (fileName) {
console.log("Processing: " + fileName);
var definitions = YAML.load(path.join(constantPathBase,fileName));
var logfunction = function (err1){
console.log(err1.toString());
};
var constantsJson = {};
if (definitions[definitionsBase]) {
awsc.verifyPath(definitions,[definitionsBase, 'awsResourceInfo', 'awsResources', 'type'], {oneOfs:['dynamodbInfo', 'cognitoIdentityPoolInfo', 's3Info', 'elasticacheInfo']}, "definition file \"" + fileName + "\"").callbackOnError(logfunction);
awsc.verifyPath(definitions,[definitionsBase, 'awsResourceInfo', 'awsResources', 'resourceName'], 's', "definition file \"" + fileName + "\"").callbackOnError(logfunction);
definitions[definitionsBase].awsResourceInfo.awsResources.forEach(function (resource) {
console.log("... adding resouce " + resource.type + ": " + resource.resourceName);
var resourceRoot;
var source;
switch (resource.type) {
case 'dynamodbInfo':
if (typeof constantsJson.DYNAMO_DB !== 'object') {
constantsJson.DYNAMO_DB = {};
}
resourceRoot = constantsJson.DYNAMO_DB;
awsc.verifyPath(baseDefinitions,[resource.type, resource.resourceName, 'lambdaAliases', 'resource'], 's', "definition file \"" + argv.baseDefinitionsFile + "\"").callbackOnError(logfunction);
source = baseDefinitions[resource.type][resource.resourceName].lambdaAliases;
break;
case 'cognitoIdentityPoolInfo':
if (typeof constantsJson.COGNITO !== 'object') {
constantsJson.COGNITO = {};
}
resourceRoot = constantsJson.COGNITO;
awsc.verifyPath(baseDefinitions,[resource.type, 'identityPools', resource.resourceName, 'lambdaAliases', 'resource'], 's', "definition file \"" + argv.baseDefinitionsFile + "\"").callbackOnError(logfunction);
source = baseDefinitions[resource.type].identityPools[resource.resourceName].lambdaAliases;
break;
case 's3Info':
if (typeof constantsJson.S3 !== 'object') {
constantsJson.S3 = {};
}
resourceRoot = constantsJson.S3;
awsc.verifyPath(baseDefinitions,[resource.type, 'buckets', resource.resourceName, 'lambdaAliases', 'resource'], 's', "definition file \"" + argv.baseDefinitionsFile + "\"").callbackOnError(logfunction);
source = baseDefinitions[resource.type].buckets[resource.resourceName].lambdaAliases;
break;
case 'elasticacheInfo':
if (typeof constantsJson.ELASTICACHE !== 'object') {
constantsJson.ELASTICACHE = {};
}
resourceRoot = constantsJson.ELASTICACHE;
awsc.verifyPath(baseDefinitions,[resource.type, 'elasticaches', resource.resourceName, 'lambdaAliases', 'resource'], 's', "definition file \"" + argv.baseDefinitionsFile + "\"").callbackOnError(logfunction);
source = baseDefinitions[resource.type].elasticaches[resource.resourceName].lambdaAliases;
}
// attach any attributes here
if (typeof source.attributes === 'object') {
resourceRoot[source.resource] = source.attributes;
} else {
resourceRoot[source.resource] = {};
}
var resourceName;
if (awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
resourceName = baseDefinitions.environment.AWSResourceNamePrefix + resource.resourceName;
}
resourceRoot[source.resource].name = resourceName;
// custom required stuff here
switch (resource.type) {
case 'dynamodbInfo':
break;
case 'cognitoIdentityPoolInfo':
resourceRoot[source.resource].authProviders = baseDefinitions[resource.type].identityPools[resource.resourceName].authProviders;
resourceRoot[source.resource].identityPoolId = baseDefinitions[resource.type].identityPools[resource.resourceName].identityPoolId;
break;
case 's3Info':
resourceRoot[source.resource].name = baseDefinitions[resource.type].buckets[resource.resourceName].name;
resourceRoot[source.resource].location = baseDefinitions[resource.type].buckets[resource.resourceName].location;
var pathUrl;
switch (baseDefinitions[resource.type].buckets[resource.resourceName].region) {
case 'us-east-1':
pathUrl = 'https://s3.amazonaws.com/' + baseDefinitions[resource.type].buckets[resource.resourceName].name;
break;
default:
pathUrl = 'https://s3- ' + baseDefinitions[resource.type].buckets[resource.resourceName].region + '.amazonaws.com/' + baseDefinitions[resource.type].buckets[resource.resourceName].name;
}
resourceRoot[source.resource].pathUrl = pathUrl;
break;
case 'elasticacheInfo':
resourceRoot[source.resource].cacheClusterId = baseDefinitions[resource.type].elasticaches[resource.resourceName].CacheCluster.CacheClusterId;
var configurationEndpoint = baseDefinitions[resource.type].elasticaches[resource.resourceName].CacheCluster.ConfigurationEndpoint;
resourceRoot[source.resource].configurationEndpoint = configurationEndpoint.Address + ":" + configurationEndpoint.Port;
resourceRoot[source.resource].engine = baseDefinitions[resource.type].elasticaches[resource.resourceName].CacheCluster.engine;
break;
}
var outFname;
switch (argv.constantsType) {
case 'lambda':
outFname = path.join(constantPathBase,definitions.lambdaInfo.functionName,argv.outputFilename);
break;
case 'client':
awsc.verifyPath(definitions,['clientInfo', 'awsResourceInfo', 'resourceConstantPath'], 's', "definition file \"" + fileName + "\"").callbackOnError(logfunction);
outFname = path.join(constantPathBase,definitions.clientInfo.awsResourceInfo.resourceConstantPath,argv.outputFilename);
break;
default:
}
fs.writeFile(outFname, JSON.stringify(constantsJson, null, '\t'));
});
}
});
function forEachDefinition (callback) {
fs.readdir(constantPathBase, function (err, files) {
if (err) {
throw err;
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var writeOut = true;
if ((typeof argv.lambdaName === 'string') && (argv.lambdaName !== fileNameComponents[0])) {
console.log("Not target lambda. Skipping.");
writeOut = false;
}
if (writeOut) {
callback(fileName);
}
}
}
});
}
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Creates NAT Gateways and assignes them to a VPC.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.help('h')
.alias('h', 'help');
var argv = yargs.argv;
var retryCounters = {};
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Creating NAT Gateways ##");
if (awsc.verifyPath(baseDefinitions,['natGatewayInfo', 'natGateways'],'o').isVerifyError) {
console.log("Nothing to do.");
return;
}
Object.keys(baseDefinitions.natGatewayInfo.natGateways).forEach(function (natGatewayName) {
var natGatewayDescription = baseDefinitions.natGatewayInfo.natGateways[natGatewayName];
if (!awsc.verifyPath(natGatewayDescription, ["NatGateway", "NatGatewayId"], 's').isVerifyError) {
console.log("NAT Gateway '" + natGatewayName + "' is already defined.");
waitForNatGatewayAvailable(natGatewayName, function (natGatewayName) {
commitUpdates(natGatewayName);
configureTrafficSourceRoutes(natGatewayName);
});
return;
}
console.log("Creating new NAT Gateway");
createNatGateway(natGatewayName, function (err, natGatewayName) {
if (err) {
console.log(err);
return;
}
commitUpdates(natGatewayName);
waitForNatGatewayAvailable(natGatewayName, function (natGatewayName) {
commitUpdates(natGatewayName);
configureTrafficSourceRoutes(natGatewayName);
});
});
});
function commitUpdates(natGatewayName) {
writeOut("Could not update natGatewayId for NAT Gateway '" + natGatewayName + "'.");
}
function waitForNatGatewayAvailable(natGatewayName, callback) {
if (!retryCounters[natGatewayName]) {
retryCounters[natGatewayName] = 1;
}
var maxRetry = 30;
var status = baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway.State;
console.log("Waiting for NAT Gateway '" + natGatewayName + "' available. Current status: '" + status + "'. Retry " + retryCounters[natGatewayName] + " of " + maxRetry);
if (status === 'available') {
callback(natGatewayName);
return;
}
setTimeout(function () {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "describe-nat-gateways",
parameters:{
"nat-gateway-ids": {type: "string", value: baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway.NatGatewayId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['NatGateways'], type:'a'}]
},
function (request) {
if (request.response.error) {
console.log("Issue retrieving nat gateway description from AWS");
throw request.response.error;
}
if (request.response.parsedJSON.NatGateways[0].State === "available") {
baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway = request.response.parsedJSON.NatGateways[0];
callback(natGatewayName);
} else {
if (retryCounters[natGatewayName] > maxRetry) {
throw new Error("Waiting for 'avalable' status of NAT Gateway '" + natGatewayName + "' timed out.");
}
retryCounters[natGatewayName] = retryCounters[natGatewayName] + 1;
waitForNatGatewayAvailable(natGatewayName, callback);
}
}).startRequest();
}, 10000);
}
function allocateElasticIp(natGatewayName, callback) {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "allocate-address",
parameters:{
"domain": {type: "string", value:"vpc"},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['AllocationId'], type:'s'}]
},
function (request) {
if (request.response.error) {
callback(request.response.error, null, natGatewayName);
return;
}
callback(request.response.error, request.response.parsedJSON.AllocationId, natGatewayName);
}).startRequest();
}
function createNatGateway(natGatewayName, callback) {
allocateElasticIp(natGatewayName, function (err, allocationId, natGatewayName) {
if (err) {
throw err;
}
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "create-nat-gateway",
parameters:{
"subnet-id": {type: "string", value: baseDefinitions.subnetInfo.subnets[baseDefinitions.natGatewayInfo.natGateways[natGatewayName].subnet].SubnetId},
"allocation-id": {type: "string", value: allocationId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['NatGateway', 'NatGatewayId'], type:'s'}]
},
function (request) {
if (request.response.error) {
callback(request.response.error, natGatewayName);
return;
}
baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway = request.response.parsedJSON.NatGateway;
callback(null, natGatewayName);
}).startRequest();
});
}
function configureTrafficSourceRoutes(natGatewayName) {
console.log("Configuring traffic source routes.");
if (awsc.verifyPath(baseDefinitions, ["natGatewayInfo", "natGateways", natGatewayName, "trafficSourceRouters"], 'a').isVerifyError) {
console.log("No traffic source routes.");
return;
}
var tsRouters = baseDefinitions.natGatewayInfo.natGateways[natGatewayName].trafficSourceRouters;
tsRouters.forEach(function (route){
var params = {
"nat-gateway-id": {type: "string", value: baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway.NatGatewayId},
"profile": {type: "string", value: AWSCLIUserProfile}
};
Object.keys(route).forEach(function (routeKey) {
var key;
var value;
if (routeKey === "internetGateway") {
key = "gateway-id";
value = baseDefinitions.internetGatewayInfo.internetGateways[route[routeKey]].InternetGateway.InternetGatewayId;
} else if(routeKey === "routerTableId") {
key = "route-table-id";
value = route[routeKey];
} else if(routeKey === "vpcDefaultRouter") {
key = "route-table-id";
value = baseDefinitions.vpcInfo.vpcs[route.vpcDefaultRouter].RouteTableId;
} else {
key = routeKey;
value = route[routeKey];
}
params[key] = {type: "string", value: value};
});
createRoute(route, params, natGatewayName);
});
}
function createRoute(route, params, natGatewayName, retry) {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "create-route",
context: {route: route, routeTableName: natGatewayName},
parameters: params,
returnSchema:'none'
},
function (request) {
if (request.response.error && (request.response.errorId === "RouteAlreadyExists") && !retry) {
console.log("Route '" + JSON.stringify(request.context.route) + "' exists for route table '" + request.context.routeTableName + "'. Deleting and re-creating.");
var deleteParams = {};
deleteParams.profile = params.profile;
deleteParams["route-table-id"] = params["route-table-id"];
deleteParams["destination-cidr-block"] = params["destination-cidr-block"];
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "delete-route",
parameters: deleteParams,
returnSchema:'none'
},
function () {
createRoute(route, params, natGatewayName, true);
}).startRequest();
return;
} else if (request.response.error) {
console.log("Could not create route '" + JSON.stringify(request.context.route) + "' for route table '" + request.context.routeTableName + "'.");
throw request.response.error;
}
console.log("Created route '" + JSON.stringify(request.context.route) + "' for route table Id'" + request.parameters['route-table-id'].value + "'.");
}).startRequest();
}
function writeOut(errorText) {
// now delete role
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". " + errorText);
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file. " + errorText);
throw writeErr;
}
});
}
<file_sep>#!/usr/bin/env node
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const fs = require('fs');
const YAML = require('yamljs');
const AwsRequest = require(path.join(__dirname, 'AwsRequest'));
const argv = require('yargs')
.usage('Delete a role, detaching policies first.\nNote: at the moment this script only detaches policies specified\nin config files.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.alias('t', 'roleType')
.describe('t', 'which roles to delete')
.choices('t', ['api', 'lambda', 'cognito'])
.demand(['t'])
.help('h')
.alias('h', 'help')
.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
process.exit(1);
}
var roleBase;
switch (argv.roleType) {
case 'api':
roleBase = 'apiInfo';
break;
case 'lambda':
roleBase = 'lambdaInfo';
break;
case 'cognito':
roleBase = 'cognitoIdentityPoolInfo';
break;
default:
}
console.log("## Deleting Roles (" + argv.roleType + ") ##");
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
awsc.verifyPath(baseDefinitions, [roleBase, 'roleDefinitions'], 'o', "definitions file \""+argv.baseDefinitionsFile+"\"").exitOnError();
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
}
Object.keys(baseDefinitions[roleBase].roleDefinitions).forEach(function (roleKey) {
var roleDef = baseDefinitions[roleBase].roleDefinitions[roleKey];
// need a name, policyDocument and perhaps some policies
awsc.verifyPath(roleDef, ['policyDocument'], 'o', "role definition " + roleKey).exitOnError();
awsc.verifyPath(roleDef, ['policies'], 'a', "role definition " + roleKey).exitOnError();
var policyArray = [];
roleDef.policies.forEach(function (policy) {
awsc.verifyPath(policy, ['arnPolicy'], 's', "policy definition " + roleKey).exitOnError();
policyArray.push(policy.arnPolicy);
});
// all done verifying now lets have some fun
deletePolicies(policyArray, roleKey, AWSCLIUserProfile);
});
function deletePolicies(policyArray, roleKey) {
var roleName;
if (awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
roleName = baseDefinitions.environment.AWSResourceNamePrefix + roleKey;
}
var policyArrayLength = policyArray.length;
policyArray.forEach(function (policy){
AwsRequest.createRequest({
serviceName: 'iam',
functionName: 'detach-role-policy',
parameters: {
'role-name': {type: 'string', value: roleName},
'policy-arn': {type: 'string', value: policy},
profile: {type: 'string', value: AWSCLIUserProfile}
},
returnSchema: 'none',
}, function (request) {
if (request.response.error && request.response.errorId !== "NoSuchEntity") {
console.log("Failed to detach policy" + request.parameters["policy-arn"].value + " from " + roleName + ".");
console.log(request.response.error);
} else {
console.log("Successfully detached policy " + request.parameters["policy-arn"].value + " from " + roleName + ".");
}
policyArrayLength --;
if (policyArrayLength === 0) {
// now delete role
AwsRequest.createRequest({
serviceName: 'iam',
functionName: 'delete-role',
parameters: {
'role-name': {type: 'string', value: roleName},
profile: {type: 'string', value: AWSCLIUserProfile}
},
returnSchema: 'none',
}, function (request) {
if (request.response.error && request.response.errorId !== "NoSuchEntity") {
console.log("Failed to delete role " + roleKey + ".");
throw request.response.error;
}
console.log("Successfully deleted role " + roleKey + ".");
delete baseDefinitions[roleBase].roleDefinitions[roleKey].arnRole;
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log(backupErr);
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". API Id was not updated.");
process.exit(1);
}
if (writeErr) {
console.log("Unable to write updated definitions file.");
throw new Error(writeErr);
}
});
}).startRequest();
}
}).startRequest();
});
}
<file_sep>'use strict';
angular.module('menuProperties',[]).
value('menus',{signupLoginList: [{item: 'signupItem', name:'Signup', href:'#!/signup'},
{item:'loginItem', name:'Login', href:'#!/login'}],
authedList : [{item: 'logoutItem', name:'Logout', href:'#!/logout'}]});
// Declare app level module which depends on views, and components
angular.module('lambdaAuth', [
'sharedInfo',
'awsAPIClients',
'ngRoute',
'ngAnimate',
'signupModule',
'loginModule',
'frontpageModule',
'logoutModule',
'menuProperties',
'topbarModule'
]).
config(['$locationProvider', '$routeProvider' ,function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.when('/signup', {
template: '<topbar menu-name="signupLoginList" selected-item="signupItem"></topbar><signup></signup>'
}).
when('/login', {
template: '<topbar menu-name="signupLoginList" selected-item="loginItem"></topbar><login></login>'
}).
when('/frontpage', {
template: '<topbar menu-name="authedList" selected-item=""></topbar><frontpage></frontpage>'
}).
when('/logout', {
template: '<topbar menu-name="signupLoginList" selected-item=""></topbar><logout></logout>'
}).
otherwise('/signup');
}]);
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const exec = require('child_process').exec;
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const yargs = require('yargs')
.usage('Update project lambdas.\n"createLambda" should have been previously called.\n"Usage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.alias('l','lambdaDefinitionsDir')
.describe('l','directory that contains lambda definition files and implementations')
.default('l','./lambdas')
.alias('l','lambdaDefinitionsDir')
.describe('l','directory that contains lambda definition files and implementations. <lambdaName>.zip archives will be placed here.')
.default('l','./lambdas')
.alias('n','lambdaName')
.describe('n','a specific lambda to process. If not specified all lambdas found will be uploaded')
.alias('a','archiveOnly')
.describe('a','Only perform archive operation. Do not upload')
.help('h')
.alias('h', 'help');
const argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
if (!fs.existsSync(argv.lambdaDefinitionsDir)) {
console.log("Lambda's path \"" + argv.lambdasPath + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
console.log("## Uploading Lambdas ##");
var AWSCLIUserProfile = "default";
if (typeof baseDefinitions.environment !== 'object') {
} else {
if (typeof baseDefinitions.environment.AWSCLIUserProfile === 'string') {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
}
}
if (AWSCLIUserProfile === "default") {
console.log("using \"default\" AWSCLIUserProfile");
}
forEachLambdaDefinition(function (fileName) {
// here we would want to fork to do ops in parallel
var definitions = YAML.load(path.join(argv.lambdaDefinitionsDir,fileName));
if (typeof definitions !== 'object') {
throw new Error("Definitions file \"" + fileName + "\" could not be parsed");
}
if (typeof definitions.lambdaInfo !== 'object') {
throw new Error("The \"lambdaInfo\" object in definitions file \"" + fileName + "\" could not be found.");
}
if (typeof definitions.lambdaInfo.arnLambda !== 'string') {
throw new Error("The \"arnLambda\" string in \"lambdaInfo\" object in definitions file \"" + fileName + "\" could not be found. Has this lambda been created? Try \"createLambda\".");
}
if (typeof definitions.lambdaInfo.functionName !== 'string') {
throw new Error("The \"functionName\" string in \"lambdaInfo\" object in definitions file \"" + fileName + "\" could not be found. This should be the name of the lambda function");
}
// remove older archives
if (fs.existsSync(path.join(argv.lambdaDefinitionsDir, definitions.lambdaInfo.functionName + ".zip"))) {
fs.unlinkSync(path.join(argv.lambdaDefinitionsDir, definitions.lambdaInfo.functionName + ".zip"));
}
// check to make sure everything compiles at least
awsc.validatejs(definitions, path.join(argv.lambdaDefinitionsDir, definitions.lambdaInfo.functionName));
// fitst zip the archive we can drop them into the lambdas directory
var cdCommand = "cd \"" + path.join(argv.lambdaDefinitionsDir,definitions.lambdaInfo.functionName) + "\"; ";
var zipCommandString = (cdCommand + "zip -r " + path.join("..", definitions.lambdaInfo.functionName) + ".zip *");
var params = ['lambda',
'update-function-code',
'--function-name ' + definitions.lambdaInfo.arnLambda,
'--zip-file fileb://' + path.join(argv.lambdaDefinitionsDir, definitions.lambdaInfo.functionName) + ".zip",
'--profile ' + AWSCLIUserProfile
];
var uploadCommandString = ('aws ' + params.join(' '));
// capture values here by creating a function
zipAndUpload(zipCommandString, uploadCommandString);
});
function forEachLambdaDefinition (callback) {
fs.readdir(argv.lambdaDefinitionsDir, function (err, files) {
if (err) {
console.log(err);
process.exit(1);
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var writeOut = true;
if ((typeof argv.lambdaName === 'string') && (argv.lambdaName !== fileNameComponents[0])) {
console.log("Not target lambda. Skipping.");
writeOut = false;
}
if (writeOut) {
callback(fileName);
}
}
}
});
}
function zipAndUpload(zipCommand, uploadCommand) {
exec(zipCommand, function (err, stdout, stderr) {
if (err) {
console.log(stdout);
console.log(stderr);
throw new Error(err);
}
console.log(stdout);
if (!argv.archiveOnly) {
// lets upload!
exec(uploadCommand, function (err, stdout, stderr) {
if (err) {
console.log(stdout);
console.log(stderr);
throw new Error(err);
}
console.log(stdout);
});
}
});
}
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage("Creates ElastiCache clusters. This method will wait until the cache cluster is 'available' (necessary so configurationEndpoint is defined).\nUsage: $0 [options]")
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.help('h')
.alias('h', 'help');
var argv = yargs.argv;
var retryCounters = {};
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Creating ElastiCache clusters ##");
if (awsc.verifyPath(baseDefinitions,['elasticacheInfo', 'elasticaches'],'o').isVerifyError) {
console.log("Nothing to do.");
return;
}
// create subnet groups
// create cache clusters
Object.keys(baseDefinitions.elasticacheInfo.elasticaches).forEach(function (elasticacheName) {
/* var elasticacheDescription = baseDefinitions.elasticacheInfo.elasticaches[elasticacheName];
if (!awsc.verifyPath(elasticacheDescription,["CacheCluster", "CacheClusterId"],'s').isVerifyError) {
console.log("Cache cluster '" + elasticacheName + "' is already defined. Please use deleteElastiCache.js first.");
return;
}*/
// create subnet group
processSubnetGroupForCacheName(elasticacheName, function (elasticacheName) {
// check to see if the name tag exists
var nameTag = baseDefinitions.environment.AWSResourceNamePrefix + elasticacheName;
console.log("Checking for cache cluster with Id '" + nameTag + "'");
checkTagName(nameTag, elasticacheName, function(tagExists, results, tagName, elasticacheName) {
if (tagExists) {
console.log("Cache cluster '" + tagName + "' exists. updating local definitions with existing ID.");
// update VPC info with existing tag IDs
baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].CacheCluster = results;
// write out result
writeOut("Could not update CacheCluster information for cache cluster '" + elasticacheName + "'.", function () {
waitForCacheClusterAvailable(elasticacheName, function() {
});
});
} else {
console.log("Creating new cache cluster with Id '" + tagName + "'");
createCacheCluster(tagName, elasticacheName, function (err, tagName, elasticacheName) {
if (err) {
throw err;
}
writeOut("Could not update CacheCluster information for cache cluster '" + elasticacheName + "'.", function () {
waitForCacheClusterAvailable(elasticacheName, function() {
});
});
});
}
});
});
});
function processSubnetGroupForCacheName(elasticacheName, callback) {
awsc.verifyPath(baseDefinitions, ["elasticacheInfo", "elasticaches", elasticacheName, "subnetGroup"], "s", "cache cluster '" + elasticacheName + "'.").exitOnError();
var subnetName = baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].subnetGroup;
/* var subnetDescription = baseDefinitions.elasticacheInfo.subnetGroups[subnetName];
if (!awsc.verifyPath(subnetDescription,["CacheSubnetGroup", "CacheSubnetGroupName"],'s').isVerifyError) {
console.log("Subnet Group '" + subnetName + "' is already defined. Continuing with cash cluster creation.");
callback(elasticacheName);
return;
} */
// check to see if the name tag exists
var nameTag = baseDefinitions.environment.AWSResourceNamePrefix + subnetName;
console.log("Checking for subnet group with name '" + nameTag + "'");
checkSubnetGroup(nameTag, subnetName, function(tagExists, results, tagName, subnetName) {
if (tagExists) {
console.log("Subnet group '" + tagName + "' exists. Updating local definitions with existing information.");
// update VPC info with existing tag IDs
baseDefinitions.elasticacheInfo.subnetGroups[subnetName].CacheSubnetGroup = results;
// write out result
writeOut("Could not update CacheSubnetGroup information for subnet group '" + subnetName + "'.", function () {
callback(elasticacheName);
});
} else {
console.log("Creating new subnet group with name '" + tagName + "'");
createSubnetGroup(tagName, subnetName, function (err, tagName, subnetName) {
if (err) {
console.log(err);
return;
}
writeOut("Could not update CacheSubnetGroup information for subnet group '" + subnetName + "'.", function () {
callback(elasticacheName);
});
});
}
});
}
function checkSubnetGroup(nameTag, subnetName, callback) {
AWSRequest.createRequest({
serviceName: "elasticache",
functionName: "describe-cache-subnet-groups",
parameters:{
"cache-subnet-group-name": {type: "string", value: nameTag},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json'
},
function (request) {
if (request.response.error) {
callback(false, null, nameTag, subnetName);
return;
}
if (!request.response.parsedJSON.CacheSubnetGroups || (request.response.parsedJSON.CacheSubnetGroups.length === 0)) {
callback(false, null, nameTag, subnetName);
return;
}
callback(true, request.response.parsedJSON.CacheSubnetGroups[0], nameTag, subnetName);
}).startRequest();
}
function checkTagName(nameTag, elasticacheName, callback) {
AWSRequest.createRequest({
serviceName: "elasticache",
functionName: "describe-cache-clusters",
parameters:{
"cache-cluster-id": {type: "string", value: nameTag},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json'
},
function (request) {
if (request.response.error) {
callback(false, null, nameTag, elasticacheName);
return;
}
if (!request.response.parsedJSON.CacheClusters || (request.response.parsedJSON.CacheClusters.length === 0)) {
callback(false, null, nameTag, elasticacheName);
return;
}
callback(true, request.response.parsedJSON.CacheClusters[0], nameTag, elasticacheName);
}).startRequest();
}
function createSubnetGroup(nameTag, subnetName, callback) {
awsc.verifyPath(baseDefinitions,["elasticacheInfo", "subnetGroups", subnetName, "subnets"], 'a', "elastic cache subnet group definition '" + subnetName + "'").exitOnError();
var subnets = baseDefinitions.elasticacheInfo.subnetGroups[subnetName].subnets;
if (subnets.length < 1) {
throw new Error("At least one subnet is requred to create subnet group '" + subnetName + "'");
}
var subnetIds = [];
for (var index = 0; index < subnets.length; index ++) {
awsc.verifyPath(baseDefinitions,["subnetInfo", "subnets", subnets[index], "SubnetId"], 's', "subnet '" + subnets[index] + "' in subnet group definition '" + subnetName + "'").exitOnError();
subnetIds.push(baseDefinitions.subnetInfo.subnets[subnets[index]].SubnetId);
}
var subnetIdString = subnetIds.join(" ");
AWSRequest.createRequest({
serviceName: "elasticache",
functionName: "create-cache-subnet-group",
parameters:{
"cache-subnet-group-name": {type: "string", value: nameTag},
"cache-subnet-group-description": {type: "string", value: subnetName},
"subnet-ids": {type: "string", value: subnetIdString},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['CacheSubnetGroup', 'CacheSubnetGroupName'], type:'s'}]
},
function (request) {
if (request.response.error) {
callback(request.response.error, nameTag, subnetName);
return;
}
baseDefinitions.elasticacheInfo.subnetGroups[subnetName].CacheSubnetGroup = request.response.parsedJSON.CacheSubnetGroup;
callback(null, nameTag, subnetName);
}).startRequest();
}
function createCacheCluster(nameTag, elasticacheName, callback) {
var secgroupNames;
if (awsc.verifyPath(baseDefinitions,["elasticacheInfo", "elasticaches", elasticacheName, "securityGroups"], 'a', "elastic cache definition '" + elasticacheName + "'").isVerifyError) {
secgroupNames = [];
} else {
secgroupNames = baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].securityGroups;
}
var secGroupIds = [];
for (var index = 0; index < secgroupNames.length; index ++) {
awsc.verifyPath(baseDefinitions,["securityGroupInfo", "securityGroups", secgroupNames[index], "GroupId"], 's', "for security group '" + secgroupNames[index] + "' in elastic cache definition '" + elasticacheName + "'").exitOnError();
secGroupIds.push(baseDefinitions.securityGroupInfo.securityGroups[secgroupNames[index]].GroupId);
}
if (!awsc.verifyPath(baseDefinitions,["elasticacheInfo", "elasticaches", elasticacheName, "vpcDefaultSecurityGroups"], 'a', "elastic cache definition '" + elasticacheName + "'").isVerifyError) {
var vpcs = baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].vpcDefaultSecurityGroups;
vpcs.forEach(function (vpcName) {
awsc.verifyPath(baseDefinitions,["vpcInfo", "vpcs", vpcName, "GroupId"], 's', "for security vpc default secrity group '" + vpcName + "' in elastic cache definition '" + elasticacheName + "'").exitOnError();
secGroupIds.push(baseDefinitions.vpcInfo.vpcs[vpcName].GroupId);
});
}
if (secGroupIds.length < 1) {
throw new Error("At least on security group is requred to create cache clunster '" + elasticacheName + "'");
}
var securityGroupIds = secGroupIds.join(" ");
awsc.verifyPath(baseDefinitions, ["elasticacheInfo", "elasticaches", elasticacheName, "subnetGroup"], 's', "elastic cache definition '" + elasticacheName + "'").exitOnError();
var subnetGroup = baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].subnetGroup;
awsc.verifyPath(baseDefinitions, ["elasticacheInfo", "subnetGroups", subnetGroup, "CacheSubnetGroup", "CacheSubnetGroupName"], 's', "subnet group '" + subnetGroup + "' in elastic cache definition '" + elasticacheName + "'").exitOnError();
var subnetGroupName = baseDefinitions.elasticacheInfo.subnetGroups[subnetGroup].CacheSubnetGroup.CacheSubnetGroupName;
AWSRequest.createRequest({
serviceName: "elasticache",
functionName: "create-cache-cluster",
parameters:{
"cache-cluster-id": {type: "string", value: nameTag},
"num-cache-nodes": {type: "string", value: baseDefinitions.elasticacheInfo.elasticaches[elasticacheName]["num-cache-nodes"].toString()},
"cache-node-type": {type: "string", value: baseDefinitions.elasticacheInfo.elasticaches[elasticacheName]["cache-node-type"]},
"engine": {type: "string", value: baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].engine},
"security-group-ids": {type: "string", value: securityGroupIds},
"cache-subnet-group-name": {type: "string", value: subnetGroupName},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['CacheCluster', 'CacheClusterId'], type:'s'}]
},
function (request) {
if (request.response.error) {
callback(request.response.error, nameTag, elasticacheName);
return;
}
baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].CacheCluster = request.response.parsedJSON.CacheCluster;
callback(null, nameTag, elasticacheName);
}).startRequest();
}
function waitForCacheClusterAvailable(elasticacheName, callback) {
if (!retryCounters[elasticacheName]) {
retryCounters[elasticacheName] = 1;
}
var maxRetry = 20;
var status = baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].CacheCluster.CacheClusterStatus;
console.log("Waiting for cache cluster '" + elasticacheName + "' available. Current status: '" + status + "'. Retry " + retryCounters[elasticacheName] + " of " + maxRetry);
if (status === 'available') {
callback(elasticacheName);
return;
}
setTimeout(function () {
checkTagName(baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].CacheCluster.CacheClusterId, elasticacheName , function(tagExists, results, tagName, elasticacheName) {
if (!tagExists) {
throw new Error("Cache cluster " + baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].CacheCluster.CacheClusterId + " has disappeared.");
}
var status2 = results.CacheClusterStatus;
if (status2 === 'available') {
baseDefinitions.elasticacheInfo.elasticaches[elasticacheName].CacheCluster = results;
// write out result
writeOut("Could not update CacheCluster information for cache cluster '" + elasticacheName + "'.", function () {
callback(elasticacheName);
});
} else {
retryCounters[elasticacheName] = retryCounters[elasticacheName] + 1;
if (retryCounters[elasticacheName] > maxRetry) {
throw new Error("Waiting for 'avalable' status of cache cluster '" + elasticacheName + "' timed out.");
}
waitForCacheClusterAvailable(elasticacheName, callback);
}
});
}, 30000);
}
function writeOut(errorText, callback) {
// now delete role
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". " + errorText);
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file. " + errorText);
throw writeErr;
}
if (callback) {
callback();
}
});
}
<file_sep>#!/usr/bin/env node
const YAML = require('yamljs');
const argv = require('yargs')
.usage('Removes and re-creates link files base on linkFiles in [your_lambda].definitions.yaml.\nUsage: $0 [options]')
.alias('l','lambdaDefinitionsDir')
.describe('l','Directory containing lambda definition yaml files')
.default('l','./lambdas')
.alias('n','lambdaName')
.describe('n','Only process links for this lambda')
.alias('c','cleanOnly')
.describe('c','Just delete the links')
.help('h')
.alias('h', 'help')
.argv;
const fs = require('fs');
const path = require('path');
// the "paths" component is in the lambdaDefinitions
// at apiInfo.path
console.log("## Updating Link Files ##");
fs.readdir(argv.lambdaDefinitionsDir, function (err, files) {
if (err) {
console.log(err);
process.exit(1);
}
// iterate through all the definition files
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var definitions = YAML.load(path.join(argv.lambdaDefinitionsDir,fileName));
// process the linkFiles
if (typeof definitions.linkFiles === 'object') {
var allkeys = Object.keys(definitions.linkFiles);
if (Array.isArray(allkeys) && (allkeys.length > 0)) {
var writeOut = true;
if ((typeof argv.lambdaName === 'string') && (argv.lambdaName !== Object.keys(definitions.implementationFiles)[0])) {
console.log("Not target lambda. Skipping.");
writeOut = false;
}
// if we should act on this lambda delete old links and create new ones
if (writeOut) {
for (var indexKey = 0; indexKey < allkeys.length; indexKey++) {
for (var fNameIndex = 0; fNameIndex < definitions.linkFiles[allkeys[indexKey]].length; fNameIndex++) {
var sourceFile = path.join(argv.lambdaDefinitionsDir, allkeys[indexKey] ,definitions.linkFiles[allkeys[indexKey]][fNameIndex]);
console.log(path.join(argv.lambdaDefinitionsDir, Object.keys(definitions.implementationFiles)[0],definitions.linkFiles[allkeys[indexKey]][fNameIndex]));
var lnkPath = path.join(argv.lambdaDefinitionsDir, Object.keys(definitions.implementationFiles)[0],definitions.linkFiles[allkeys[indexKey]][fNameIndex]);
if (fs.existsSync(lnkPath)) {
fs.unlinkSync(lnkPath);
} else {
console.log("Warning: Cound not find " + lnkPath + " to delete.");
}
if (!argv.cleanOnly) {
fs.linkSync(sourceFile, lnkPath);
}
}
}
}
} else {
console.log("Expected linkFiles bag with at least 1 key. Skipping.");
}
} else {
console.log("Expected linkFiles bag. Skipping.");
}
}
}
});
<file_sep>#!/bin/bash
#
./AWSTools/updateLambdaHandlerEventParams.js \
--lambdaName login
if [ $? -eq 0 ]; then
./AWSTools/uploadLambda.js \
--lambdaName login
else
echo "Upload failed: updateLambdaHandlerEventParams failed"
fi
<file_sep>"use strict";
const crypto = require("crypto");
/**
* passwordHash hash a password
* @param {string} data password to hash
* @return {string} hashed password
**/
function passwordHash(data) {
var index;
var hmac;
for (index = 0; index < 10; index += 1) {
hmac = crypto.createHmac('sha256', 'a secret ' + (index * 20));
hmac.update(data);
data = hmac.digest('hex');
}
return data;
}
exports.passwordHash = passwordHash;
<file_sep>#!/bin/bash
set -e
# create roles and attach policies
AWSTools/createRole.js --roleType lambda
AWSTools/createRole.js --roleType api
AWSTools/createRole.js --roleType cognito
#create VPCs and security groups
AWSTools/createVPC.js
AWSTools/createSubnet.js
AWSTools/createInternetGateway.js
AWSTools/createRouteTable.js
AWSTools/createNatGateway.js
# create storage (db and identity pool)
AWSTools/createDynamodb.js
AWSTools/createIdentityPool.js
AWSTools/createS3Bucket.js --type lambda
AWSTools/createElastiCache.js
# create lambdas
# make sure all linked files are present
AWSTools/updateLinkedFiles.js
# update expected api parameters for validation
AWSTools/updateLambdaHandlerEventParams.js
# update constants for accessing AWS resources
AWSTools/updateAWSConstants.js -t lambda
# finally create new lambdas
AWSTools/createLambda.js
# create API
AWSTools/coalesceSwaggerAPIDefinition.js
AWSTools/createRestAPI.js
# deploy API
AWSTools/deployAPI.js
# get the SDK's for the clients
AWSTools/getClientSDK.js
#update any client constants
AWSTools/updateAWSConstants.js -t client
# create s3 bucket for Angular app distribution
AWSTools/createS3Bucket.js --type webClient
# now that we have a bucket we can sync the static angular
AWSTools/syncAngularClientBucket.js
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Deletes the s3 bucket and removes it from the client defiition file.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.alias('l','clientDefinitionsDir')
.describe('l','directory that contains client definition files and implementations.')
.default('l','./clients')
.alias('t', 'type')
.describe('t','create client or lambda buckets.')
.choices('t', ['lambda', 'webClient'])
.require(['t'])
.help('h')
.alias('h', 'help');
const argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
if (!fs.existsSync(argv.clientDefinitionsDir)) {
yargs.showHelp("log");
throw new Error("Clients path \"" + argv.clientDefinitionsDir + "\" not found.");
}
console.log("## Deleting " + argv.type + " S3 Buckets ##");
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
if (argv.type === 'webClient') {
forEachLambdaDefinition(function (fileName) {
// here we would want to fork to do ops in parallel
var definitions = YAML.load(path.join(argv.clientDefinitionsDir,fileName));
deleteBucketForDefinitions(definitions, path.join(argv.clientDefinitionsDir,fileName));
});
} else if (argv.type === 'lambda') {
deleteBucketForDefinitions(baseDefinitions, argv.baseDefinitionsFile);
}
function deleteBucketForDefinitions(definitions, fileName) {
if (typeof definitions !== 'object') {
throw new Error("Definitions file \"" + fileName + "\" could not be parsed");
}
if (awsc.verifyPath(definitions, ['s3Info', 'buckets'], 'o', 'in angular client definition file').isVerifyError) {
console.log("No buckets defined in '" + fileName + "'");
}
Object.keys(definitions.s3Info.buckets).forEach(function (bucketPrefix) {
console.log("Deleting bucket '" + bucketPrefix + "'");
if (!awsc.verifyPath(definitions, ['s3Info', 'buckets', bucketPrefix, 'name'], 's', 'in angular client definition file').isVerifyError) {
deleteBucket(bucketPrefix, definitions, function (err, bucketPrefix, definitions) {
if (err) {
console.log(err);
}
delete definitions.s3Info.buckets[bucketPrefix].name;
delete definitions.s3Info.buckets[bucketPrefix].location;
writeOut(fileName, definitions, "bucket name was not removed.", function () {
});
});
} else {
console.log('No bucket name found. Nothing to remove.');
}
});
}
function deleteBucket(bucketPrefix, definitions, callback) {
AWSRequest.createRequest(
{
serviceName: "s3",
functionName: "rb",
context:{bucketPrefix: bucketPrefix, definitions : definitions},
parameters: {
'force' : {type:'none', value:""},
'profile' : {type:'string', value:AWSCLIUserProfile},
},
customParamString: "s3://" + definitions.s3Info.buckets[bucketPrefix].name,
returnSchema: 'none',
},
function (request) {
callback(request.response.error, request.context.bucketPrefix, request.context.definitions);
}
).startRequest();
}
function forEachLambdaDefinition (callback, doneCallback) {
fs.readdir(argv.clientDefinitionsDir, function (err, files) {
if (err) {
throw err;
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[0] === 'angular') && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var writeOut = true;
if ((typeof argv.clientName === 'string') && (argv.clientName !== fileNameComponents[0])) {
console.log("Not target API. Skipping.");
writeOut = false;
}
if (writeOut) {
callback(fileName);
}
}
}
if (doneCallback) {
doneCallback();
}
});
}
function writeOut(fileName, data, errorMsg, callback) {
awsc.updateFile(fileName, function () {
return YAML.stringify(data, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + fileName + "\". " + errorMsg);
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file.");
throw writeErr;
}
callback();
});
}
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Creates an s3 bucket if needed and configures as static web host.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.alias('l','clientDefinitionsDir')
.describe('l','directory that contains client definition files and implementations.')
.default('l','./clients')
.alias('t', 'type')
.describe('t','create client or lambda buckets.')
.choices('t', ['lambda', 'webClient'])
.require(['t'])
.help('h')
.alias('h', 'help');
var argv = yargs.argv;
console.log("## Creating " + argv.type + " S3 Buckets ##");
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
if (!fs.existsSync(argv.clientDefinitionsDir)) {
yargs.showHelp("log");
throw new Error("Clients path \"" + argv.clientDefinitionsDir + "\" not found.");
}
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
if (argv.type === 'webClient') {
forEachLambdaDefinition(function (fileName) {
// here we would want to fork to do ops in parallel
var definitions = YAML.load(path.join(argv.clientDefinitionsDir, fileName));
createBucketForDefinitions(definitions, path.join(argv.clientDefinitionsDir,fileName));
});
} else if (argv.type === 'lambda') {
createBucketForDefinitions(baseDefinitions, argv.baseDefinitionsFile);
}
function createBucketForDefinitions(definitions, fileName) {
if (typeof definitions !== 'object') {
throw new Error("Definitions file \"" + fileName + "\" could not be parsed");
}
if (awsc.verifyPath(definitions, ['s3Info', 'buckets'], 'o', 'in angular client definition file').isVerifyError) {
console.log("No buckets defined in '" + fileName + "'");
}
Object.keys(definitions.s3Info.buckets).forEach(function (bucketPrefix) {
console.log("Creating bucket '" + bucketPrefix + "'");
if (awsc.verifyPath(definitions, ['s3Info', 'buckets', bucketPrefix, 'name'], 's', 'in angular client definition file').isVerifyError) {
// no bucket - lets create one.
createBucket(bucketPrefix, definitions, fileName, function (err, bucketPrefix, definitions) {
if (err) {
throw err;
}
enableWeb(bucketPrefix, definitions, function (err, bucketPrefix) {
if (err) {
throw err;
}
addBucketPolicy(bucketPrefix, definitions, function (err) {
if (err) {
throw err;
}
addBucketCORS(bucketPrefix, definitions, function (err) {
if (err) {
throw err;
}
});
});
});
});
} else {
console.log('Bucket already defined.');
enableWeb(bucketPrefix, definitions, function (err, bucketPrefix) {
if (err) {
throw err;
}
addBucketPolicy(bucketPrefix, definitions, function (err) {
if (err) {
throw err;
}
addBucketCORS(bucketPrefix, definitions, function (err) {
if (err) {
throw err;
}
});
});
});
}
});
}
function createBucket(bucketPrefix, definitions, fileName, callback, attemptNo) {
var bucketName = bucketPrefix;
if (awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
bucketName = baseDefinitions.environment.AWSResourceNamePrefix + bucketName;
}
awsc.verifyPath(definitions, ['s3Info', 'buckets', bucketPrefix, 'region'], 's', 'angular definition object').exitOnError();
if (typeof attemptNo !== 'undefined') {
bucketName = bucketName + zeroPadInteger(6, Math.floor(Math.random() * 100000));
} else {
attemptNo = 0;
}
AWSRequest.createRequest(
{
serviceName: "s3api",
functionName: "create-bucket",
context:{bucketPrefix: bucketPrefix, fileName: fileName, attemptNo: attemptNo, callback: callback, definitions : definitions},
parameters: {
'bucket' : {type:'string', value:bucketName},
'region' : {type:'string', value:definitions.s3Info.buckets[bucketPrefix].region},
'profile' : {type:'string', value:AWSCLIUserProfile}
},
returnSchema: 'json',
returnValidation:[{path:['Location'], type:'s'}]
},
function (request) {
if (request.response.error) {
// try to create one with another name
if (attemptNo > 4) {
throw request.response.error;
}
createBucket(request.context.bucketPrefix, request.context.definitions, request.context.fileName, request.context.callback, request.context.attemptNo + 1);
} else {
console.log(request.response.parsedJSON);
request.context.definitions.s3Info.buckets[bucketPrefix].name = request.parameters.bucket.value;
request.context.definitions.s3Info.buckets[bucketPrefix].location = request.response.parsedJSON.Location;
writeOut(request.context.fileName, request.context.definitions, "Bucket name was not updated.", function () {
callback(null, request.context.bucketPrefix, request.context.definitions, request.context.fileName);
});
}
}
).startRequest();
}
function zeroPadInteger(n, value) {
value = Math.floor(value);
var nd = Math.floor(Math.log10(value)) + 1;
if (n <= nd) {
return value.toString();
} else {
var pre = (new Array(n-nd)).fill('0');
return pre.join('') + value;
}
}
function enableWeb(bucketPrefix, definitions, callback) {
if (!awsc.verifyPath(definitions,['s3Info', 'buckets', bucketPrefix, 'websiteConfiguration'],'o').isVerifyError) {
console.log("Found bucket websiteConfiguration.");
AWSRequest.createRequest(
{
serviceName: "s3api",
functionName: "put-bucket-website",
parameters: {
'bucket' : {type:'string', value: definitions.s3Info.buckets[bucketPrefix].name},
'website-configuration' : {type:'JSONObject', value: definitions.s3Info.buckets[bucketPrefix].websiteConfiguration},
'profile' : {type:'string', value:AWSCLIUserProfile}
},
returnSchema: 'none',
},
function (request) {
if (request.response.error) {
callback(request.response.error, null);
} else {
console.log("Put bucket websiteConfiguration.");
console.log('Site URL is: http://' + definitions.s3Info.buckets[bucketPrefix].name + ".s3-website-" + definitions.s3Info.buckets[bucketPrefix].region + ".amazonaws.com");
callback(null, bucketPrefix);
}
}
).startRequest();
} else {
callback(null, bucketPrefix);
}
}
function addBucketPolicy(bucketPrefix, definitions, callback) {
if (!awsc.verifyPath(definitions,['s3Info', 'buckets', bucketPrefix, 'policy'],'o').isVerifyError) {
console.log("Found bucket policy for '" + bucketPrefix + "'.");
// substitute any occurrence of $name in Resources with bucket name.
var policy = definitions.s3Info.buckets[bucketPrefix].policy;
for (var index = 0; index < policy.Statement.length; index++) {
policy.Statement[index].Resource = policy.Statement[index].Resource.replace('$name', definitions.s3Info.buckets[bucketPrefix].name);
}
// for the Principal, search for any lambda roles prefixed with a $ and substitute the ARN
if (!awsc.verifyPath(baseDefinitions, ['lambdaInfo', 'roleDefinitions'], 'o').isVerifyError) {
Object.keys(baseDefinitions.lambdaInfo.roleDefinitions).forEach(function (roleName) {
var role = baseDefinitions.lambdaInfo.roleDefinitions[roleName];
for (var index = 0; index < policy.Statement.length; index++) {
policy.Statement[index].Resource = policy.Statement[index].Resource.replace('$name', definitions.s3Info.buckets[bucketPrefix].name);
awsc.replaceAnyOccuranceOfStringInObject(policy.Statement[index].Principal, "$" + roleName, role.arnRole);
}
});
}
AWSRequest.createRequest(
{
serviceName: "s3api",
functionName: "put-bucket-policy",
parameters: {
'bucket' : {type:'string', value: definitions.s3Info.buckets[bucketPrefix].name},
'policy' : {type:'JSONObject', value: definitions.s3Info.buckets[bucketPrefix].policy},
'profile' : {type:'string', value:AWSCLIUserProfile}
},
returnSchema: 'none',
},
function (request) {
if (request.response.error) {
callback(request.response.error, null);
} else {
console.log("Put bucket policy for '" + bucketPrefix + "'.");
callback(null, bucketPrefix);
}
}
).startRequest();
} else {
callback(null, bucketPrefix);
}
}
function addBucketCORS(bucketPrefix, definitions, callback) {
if (!awsc.verifyPath(definitions,['s3Info', 'buckets', bucketPrefix, 'cors'],'o').isVerifyError) {
console.log("Found bucket CORS for '" + bucketPrefix + "'.");
AWSRequest.createRequest(
{
serviceName: "s3api",
functionName: "put-bucket-cors",
parameters: {
'bucket' : {type:'string', value: definitions.s3Info.buckets[bucketPrefix].name},
'cors-configuration' : {type:'JSONObject', value: definitions.s3Info.buckets[bucketPrefix].cors},
'profile' : {type:'string', value:AWSCLIUserProfile}
},
returnSchema: 'none',
},
function (request) {
if (request.response.error) {
callback(request.response.error, null);
} else {
console.log("Put bucket CORS for '" + bucketPrefix + "'.");
callback(null, bucketPrefix);
}
}
).startRequest();
} else {
callback(null, bucketPrefix);
}
}
function forEachLambdaDefinition (callback, doneCallback) {
fs.readdir(argv.clientDefinitionsDir, function (err, files) {
if (err) {
throw err;
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[0] === 'angular') && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var writeOut = true;
if ((typeof argv.clientName === 'string') && (argv.clientName !== fileNameComponents[0])) {
console.log("Not target API. Skipping.");
writeOut = false;
}
if (writeOut) {
callback(fileName);
}
}
}
if (doneCallback) {
doneCallback();
}
});
}
function writeOut(fileName, data, errorMsg, callback) {
awsc.updateFile(fileName, function () {
return YAML.stringify(data, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + fileName + "\". " + errorMsg);
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file.");
throw writeErr;
}
callback();
});
}
<file_sep>'use strict';
angular.module("sharedInfo", [])
.value("lastLoginSignupInfo", {email: ""});
<file_sep># lambdaAuth
A framework for full stack native and web applications on AWS using Lambda, Api Gateway, DynamoDB, Cognito Auth, S3 and ElastiCache (memcached).
This project started from a desire to learn about creating apps using AWS lambda as a backend for web and native clients. I also wanted to learn more about lambda (node) and integration with API Gateway, S3, DynamoDB and Cognito for developer authenticated federated identity pools as well as how to manage permissions across AWS resources. Additionally I wanted to learn about the strengths and weaknesses of the AWS CLI for configuration.
The resulting project tackles these goals and provides a simple framework for rapidly deploying APIs backed by lambdas and managing AWS resources so that a project's deployment can be easily recreated, torn down and shared between developers. This framework also supports multiple deployments of a project on a single AWS account. (Currently working on allowing shared resources on an AWS account, for example a shared User table, that might be useful for development).
The default configuration of this project creates a series of API endpoints (/signup, /login, /token, /user/me/get, user/photo/uploadurl/get) with associated lambdas, DynamoDB tables, s3 buckets and a federated identity pool that allow a user to create accounts and handle the transition from unauthenticated to authenticated API requests. The /signup endpoint also uses ElastiCache (memcached) to perform rudimentary throttling. Since ElastiCache requires the lambda to work in a VPC this endpoint also shows how to configure a lambda to work both inside a VPC and have access to non VPC services on the open internet. This default configuration allows users to upload photos and shows how to configure s3 bucket events to trigger lambdas.
For convenience angular, iOS (and Android coming soon) iOS clients have been provided. The angular client can run locally, but is automatically hosted on S3 for convenience (see the last installation step) - if you want to be fancy you can easly configure cloudfront to serve the site using https and other features. I will discuss this further in the web client section.
# Installation
1. If it isn't installed on your machine install node.js from https://nodejs.org (node is used for local AWS tools as well as lambdas - npm rules!).
2. Create an AWS free account.
3. Add an IAM user in the us-east-1 region to act as proxy (it isn’t good to use your master user day to day)
* http://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html
4. Install the AWS CLI
* http://docs.aws.amazon.com/cli/latest/userguide/installing.html
* Configure the CLI
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
* Configure a local profile
http://docs.aws.amazon.com/cli/latest/userguide/cli-roles.html
for convenience call the profile “adminuser” (instead of “marketingadmin” as in the example).
5. In the root project directory (it will have a package.json file) run: “npm install”
* this installs all the node packages needed for the utility files and the lambdas.
6. Install the Angular client components.
* Change directory to "clients/angular/lambda-auth” (this is the root folder of the angular web client) and run “npm install” (this installs all the components of the angular app)
7. Build the backend
* go back to the "root project folder” (“cd ..; cd ..; cd ..”)
* run "npm start”
* This will build the backend configuration and upload the angular app to s3. The last line will give you the URL of the site that you can just paste into a browser. e.g. http://testlambdaauth.s3-website-us-east-1.amazonaws.com
* run "npm stop" to remove everything that was built with "npm start".
Now you can signup and login to the test app through the Angular client. To configure the iOS client do the following:
1. You are going to need to install Xcode (from the app store) and CocoaPods (https://cocoapods.org)
2. "cd" to "clients/iOS/lambdaAuth"
3. Run "pod install" in this directory.
* this can take a really long time the first time doing a "pod install". Look here to accelerate the process: http://stackoverflow.com/questions/21022638/pod-install-is-staying-on-setting-up-cocoapods-master-repo
4. Build and Run in Xcode!
Android coming soon...
# Documentation #
This project started as my Hello World app for javascript and node.js. As such there is an evident evolution of coding patterns as I became familiar with the language. I will be improving the situation. By and large you will likely see that this project is written by a long time client developer, so please be forgiving.
## Framework Overview ##
When working with the AWS web gui to build services and configure how services should work together it became quickly apparent that managing and re-creating an infrastucture (collection of services) would become very complex. Also, managing how services are accessed by the business logic in lambdas did not see well defined (e.g. which lambdas have access to which services).
To tackle this issue I've taken the some common AWS services for building an application (dynamoDB, cognito, API Gateway, lambda) and managed their configuration with easy to read and edit yaml definitions files. All the AWS Utilities described in the section below use these definitions files as their primary configuration source.
In the **root** directory of the project you will find **base.definitions.yaml**. This configuration file holds all the information to create the supporting application infrastructure. Here you configure your dynamo tables, identity pools, API Gateway top level information as well as roles and policies for accessing these services from lambda.
**Next introduce the definitions.yaml files in the lambda and client directories**
## Adding a New Endpoint ##
To help get the ball rolling new API endpoints can be easily added using a command line tool. After going through the installation process outlined above it should only take a few minutes to add another endpoint and update the clients.
In the root project folder run the command "AWSTools/newEndpoint.js -h".
You will get the following text and parameter definitions. "Helper script to get started with a new endpoint. This script will initialize a new lambda configuration file and setup a boilerplate lambda node.js file. You can start with either post or get method, authed or unauthed, and specify request and response parameters/schema."
In this excersize we will create a new authenticated get endpoint that accepts a parameter and makes a new response object.
Lets say we want to have an endpoint that returns a specific number of users we'd like to introduce to currently authenticated user, we'll call it /intro/random and it will accept a required parameter "quantity" that is a number representing how many "user" objects we wish to be returned. We already have a "user" model defined in this project (see the file base.definitions.yaml in the root project directory) so we would like to piggyback off that in the response.
The comand for this is:
`AWSTools/newEndpoint.js --endpoint "/intro/random" --methodExecution "get" --response '{"type": "array", "items": {"$ref": "#/definitions/user"}}' --queryParameters '[{"name":"quantity","type":"number", "required": true}]' --authenticated`
In this command string you can see represented all the requirements we wanted to add:
* `--endpoint` parameter used to specify a path for the request
* `--methodExecution` indicates that we would like to use the get method.
* `--response` is a simple json schema object that follows http://json-schema.org and references the already define "user" object
* `--queryParameters` is another simple json array that creates a query parameter "quantity" of type "number" that is required
* `--authenticated` means that only authenticated users can access this endpoint.
After execution you should see that the definitions file `lambdas/introRandom.definitions.yaml` is created along with a node.js template lambda file called `lambdas/introRandom/introRandom.js`.
The `lambdas/introRandom.definitions.yaml` holds all the information about which resources the lambda leverages (supporting node.js files, aws resoures like congito or dynamoDB) as well as permission configurations. You can change these to suit your needs. By default the new enpoint's lambda is configured to use parameter validation, and have access to the `Users` dynamo table. Also these command-line created endpoints will support CORS and have a number of error responses defined.
Next we'll get this endpoint into the cloud!
Since the endpoint uses AWS resource we should update the automatically generated constants file by executing:
`AWSTools/updateAWSConstants.js --constantsType lambda`
This adds constants files to all the lambda function directories that reflect the resources specified in their definitions files. Check out `lambdas/introRandom/AWSConstants.json` to see the newly created constant file that has definitions for the `Users` dynamoDB table.
Next we want to pull in all the utilities and suport files for our new lambda by executing:
`AWSTools/updateLinkedFiles.js --lambdaName introRandom`
You don't have to add the `--lambdaName` parameter if you want to just update all lambdas. This goes for all AWSTools commands. The file `lambdas/introRandom/APIParamVerify.js` has been introduced to the directory as specified in the definitions file. This will assist in doing parameter checking.
Next we want to pull into the lambda infomation about the input parameters that it should expect from APIGateway:
`AWSTools/updateLambdaHandlerEventParams.js`
You'll see that the file `lambdas/introRandom/eventParams.json` has been added to the project. If you take a look at this JSON object you will see that our input parameters `quanitiy` is defined under `"queryParams"` as well as information about the authenticated user from cognito under `awsParams`.
Now we can create the lambda in our AWS environment:
`AWSTools/createLambda.js --lambdaName introRandom`
This command lints the files being uploaded (you can ignor warnings about unused variable definitions) and creates a new lambda function. The new lambda ARN is stored in the `lambdas/introRandom.definitions.yaml` file so it can be referenced by other services. You can see the new lambda in the [AWS Lambda console](https://console.aws.amazon.com/lambda/home?region=us-east-1#/functions?display=list).
Now we can package the updated API:
`AWSTools/coalesceSwaggerAPIDefinition.js`
You will see that that the file `swaggerAPI.yaml` file in the root directory has been updated with the new definition.
Finally we upload the API and deploy it:
`AWSTools/uploadRestAPI.js`
`AWSTools/deployAPI.js`
Now our new lambda backed API is live and ready to go!
Since the API is deployed we can update the client SDKs by downloading the new auto generated API clients:
`AWSTools/getClientSDK.js`
This command updates all client SDKs that are defined in the client directory (for the moment Angular and iOS).
At the moment this API doens't 'do' anything except return errors if required parameters are not specified. Now you can add the business logic you want in `lambdas/introRandom/introRandom.js`.
You can copy and paste the following to the command line to do everthing in one shot:
```
AWSTools/newEndpoint.js --endpoint "/intro/random" --methodExecution "get" --response '{"type": "array", "items": {"$ref": "#/definitions/user"}}' --queryParameters '[{"name":"quantity","type":"number", "required": true}]' --authenticated;
AWSTools/updateAWSConstants.js --constantsType lambda;
AWSTools/updateLinkedFiles.js --lambdaName introRandom;
AWSTools/updateLambdaHandlerEventParams.js;
AWSTools/createLambda.js --lambdaName introRandom;
AWSTools/coalesceSwaggerAPIDefinition.js;
AWSTools/uploadRestAPI.js;
AWSTools/deployAPI.js;
AWSTools/getClientSDK.js;
```
## AWS Utilities ##
The follwing utilities parse the various definitions files to create or destroy AWS resources. They are intended to be executed in the project root folder and their defaults should be sufficient for most cases. If a lambda or client is not specified the action will occur on all lambdas or clients in scope.
```
** coalesceSwaggerAPIDefinition.js **
Create a single API definitions file to upload to AWS.
x-amazon-apigateway-integration fields are updated with latest role and lambda
arn.
Usage: coalesceSwaggerAPIDefinition.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains top level definitions
including swagger template header
[default: "./base.definitions.yaml"]
-l, --lambdaDefinitionsDir directory containing lambda definition yaml
files [default: "./lambdas"]
-o, --outputFilename coalesced yaml file for upload to AWS
[default: "swaggerAPI.yaml"]
-c, --commonModelDefinitionFile yaml file with common definitions of models
-h, --help Show help [boolean]
** createDynamodb.js **
Create the tables required for the project.
If a table with the same name already exists a new table
will not be create and the existing table information will be used.
Usage: createDynamodb.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your
dynamodb (dynamodbInfo)
[default: "./base.definitions.yaml"]
-k a specific dynamo table key to process (the name of
the db is environment.AWSResourceNamePrefix + key).
If not specified all db found will be created
-h, --help Show help [boolean]
** createElastiCache.js **
Creates ElastiCache clusters. This method will wait until the cache cluster is
'available' (necessary so configurationEndpoint is defined).
Usage: createElastiCache.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** createIdentityPool.js **
Create the identity pools required for the project.
If identity pools with the same name already exist a new pool will not be
created and the existing pool infomation will be used.
Usage: createIdentityPool.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** createInternetGateway.js **
Creates Internet Gateways and assignes them to a VPC.
Usage: createInternetGateway.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** createLambda.js **
Create the lambdas for the project.
If a lambda with the same name already exists the operation will fail.
Use "deleteLambda" first to remove the exisiting function.
Usage: createLambda.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-l, --lambdaDefinitionsDir directory that contains lambda definition files
and implementations. <lambdaName>.zip archives
will be placed here. [default: "./lambdas"]
-n, --lambdaName a specific lambda to process. If not specified all
lambdas found will be uploaded
-a, --archiveOnly Only perform archive operation. Do not upload
-u, --updateArnLambda ignore existing "arnLambda" in "lambdaInfo"
section of definitions file and overwrite new
value on success
-h, --help Show help [boolean]
** createNatGateway.js **
Creates NAT Gateways and assignes them to a VPC.
Usage: createNatGateway.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** createRestAPI.js **
Create a new API
Usage: createRestAPI.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-a, --apiDefinitionFile yaml swagger API file to upload to AWS
[default: "./swaggerAPI.yaml"]
-u, --updateAWSId ignore existing "awsId" in "apiInfo" section of
base definitions file and overwrite new value on
success
-h, --help Show help [boolean]
** createRole.js **
Create project roles and attach policies.
Usage: createRole.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-t, --roleType which roles to create [api | lambda | cognito]
[required] [choices: "api", "lambda", "cognito"]
-h, --help Show help [boolean]
** createRouteTable.js **
Creates Route Tables.
Usage: createRouteTable.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** createS3Bucket.js **
Creates an s3 bucket if needed and configures as static web host.
Usage: createS3Bucket.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-l, --clientDefinitionsDir directory that contains client definition files
and implementations. [default: "./clients"]
-t, --type create client or lambda buckets.
[required] [choices: "lambda", "webClient"]
-h, --help Show help [boolean]
** createSubnet.js **
Creates Subnets to use with VPCs.
Usage: createSubnet.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** createVPC.js **
Creates VPCs. By default VPCs come with a default ACL and Security Group
Usage: createVPC.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** deleteDynamodb.js **
Delete project dynamodb.
Usage: deleteDynamodb.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your
dynamodb (dynamodbInfo)
[default: "./base.definitions.yaml"]
-n a specific dynamo table key to process. If not
specified all tables found will be deleted
-h, --help Show help [boolean]
** deleteElastiCache.js **
Creates ElastiCache clusters.
Usage: deleteElastiCache.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** deleteIdentityPool.js **
Delete project identity pools.
Usage: deleteIdentityPool.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** deleteInternetGateway.js **
Delete Internet Gateways and assignes them to a VPC.
Usage: deleteInternetGateway.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** deleteLambda.js **
Delete the project lambdas.
Usage: deleteLambda.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-l, --lambdaDefinitionsDir directory that contains lambda definition files
and implementations. <lambdaName>.zip archives
will be placed here. [default: "./lambdas"]
-n, --lambdaName a specific lambda to process. If not specified all
lambdas found will be uploaded
-h, --help Show help [boolean]
** deleteNatGateway.js **
Creates NAT Gateways and assignes them to a VPC.
Usage: deleteNatGateway.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** deleteRestAPI.js **
Delete project API definitions.
Usage: deleteRestAPI.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** deleteRole.js **
Delete a role, detaching policies first.
Note: at the moment this script only detaches policies specified
in config files.
Usage: deleteRole.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-t, --roleType which roles to delete
[required] [choices: "api", "lambda", "cognito"]
-h, --help Show help [boolean]
** deleteRouteTable.js **
Deletes Route Tables and Associations.
Usage: deleteRouteTable.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** deleteS3Bucket.js **
Deletes the s3 bucket and removes it from the client defiition file.
Usage: deleteS3Bucket.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-l, --clientDefinitionsDir directory that contains client definition files
and implementations. [default: "./clients"]
-t, --type create client or lambda buckets.
[required] [choices: "lambda", "webClient"]
-h, --help Show help [boolean]
** deleteSubnet.js **
Delete Subnets.
Usage: deleteSubnet.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** deleteVPC.js **
Delete VPCs.
Usage: deleteVPC.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-h, --help Show help [boolean]
** deployAPI.js **
Deploy API to a stage.
Usage: deployAPI.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-d, --description The description for the Deployment resource to
create. [default: "Yet another deploy..."]
-t, --stageName The name of the Stage resource for the Deployment
resource to create. [default: "dev"]
-h, --help Show help [boolean]
** deployParameters.js **
Print or delete deploy parameters from project.
WARNING: You cannot recover these settings and will have to remove the deploy
manually in the AWS console once deleted.
Usage: deployParameters.js <command> [options] filename
Commands:
print print current parameters
delete remove current parameters
save <fileName> store parameters in YAML format to file
apply <fileName> overwrite current parameters with saved file
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-l, --lambdaDefinitionsDir directory that contains lambda definition files
and implementations. [default: "./lambdas"]
-c, --clientDefinitionsDir directory that contains client definition files
and implementations. [default: "./clients"]
-h, --help Show help [boolean]
Examples:
deployParameters.js save foo.js save parameters to the given file
** getClientSDK.js **
Get AWS API Gateway SDK for the project clients.
Usage: getClientSDK.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-l, --clientDefinitionsDir directory that contains client definition files
and implementations. [default: "./clients"]
-n, --clientName a specific client to process. If not specified all
clients found will be uploaded
-h, --help Show help [boolean]
** newEndpoint.js **
Helper script to get started with a new endpoint. This script will initialize a
new lambda configuration file and setup a boilerplate lambda node.js file. You
can start with either post or get method, authed or unauthed, and specify
request and response parameters/schema.
Usage: newEndpoint.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your
dynamodb (dynamodbInfo)
[default: "./base.definitions.yaml"]
-l, --lambdaDefinitionsDir directory that contains lambda definition files
and implementations. [default: "./lambdas"]
-e, --endpoint The url path (e.g. '/user/me'). The lambda for
this endpoint will be camel case of the path
components ('userMe') [required]
-a, --authenticated If present the endpoint will require
authentication.
-b, --bodyParameters Swagger compliant parameter definition json array
object. e.g. [{"name": "param_1",
"type":"string"},{"name": "param_2",
"type":"number", "required: true"}]
-d, --sharedBodyParameters Name of parameter object defined in the base
definitions file at apiInfo.sharedDefinitions.
e.g. "user"
-q, --queryParameters Swagger compliant parameter definitions json array
object. e.g. [{"name": "param_1",
"type":"string"},{"name": "param_2",
"type":"number", "required: true"}]
-r, --response Swagger compliant parameter definitions json
schema object (http://json-schema.org). e.g.
{"required" : ["username"], "properties":
{"username" : {"type": "string"}, "age" : {"type":
"number"}}
-o, --sharedResponse Name of response object defined in the base
definitions file at apiInfo.sharedDefinitions.
e.g. "user"
-m, --methodExecution Select method execution type for API
[required] [choices: "get", "post"]
-h, --help Show help [boolean]
** syncAngularClientBucket.js **
Syncs client angular files to their s3 bucket. Creates the bucket if needed and
configures as static web host.
Usage: syncAngularClientBucket.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-l, --clientDefinitionsDir directory that contains client definition files
and implementations. [default: "./clients"]
-h, --help Show help [boolean]
** updateAWSConstants.js **
Create a json description of constants needed to access AWS services.
Usage: updateAWSConstants.js [options]
Options:
-l, --definitionsDir directory containing definition yaml files
-s, --baseDefinitionsFile yaml file that contains information about your
dynamodb (dynamodbInfo)
[default: "./base.definitions.yaml"]
-o, --outputFilename name of file that will be added to each lambda
directory [default: "AWSConstants.json"]
-n, --lambdaName update handler event params for only this lambda
directory
-t, --constantsType which constants to update [lambda | client]
[required] [choices: "lambda", "client"]
-h, --help Show help [boolean]
** updateDynamodb.js **
-bash: ./updateDynamodb.js: Permission denied
** updateLambdaHandlerEventParams.js **
Create a json description compatible with APIParamVerify.js to validate lambda
input arguments from API.
Usage: updateLambdaHandlerEventParams.js [options]
Options:
-l, --lambdaDefinitionsDir directory containing lambda definition yaml files
[default: "./lambdas"]
-o, --outputFilename name of file that will be added to each lambda
directory [default: "eventParams.json"]
-n, --lambdaName update handler event params for only this lambda
directory
-h, --help Show help [boolean]
** updateLinkedFiles.js **
Removes and re-creates link files base on linkFiles in
[your_lambda].definitions.yaml.
Usage: updateLinkedFiles.js [options]
Options:
-l, --lambdaDefinitionsDir Directory containing lambda definition yaml files
[default: "./lambdas"]
-n, --lambdaName Only process links for this lambda
-c, --cleanOnly Just delete the links
-h, --help Show help [boolean]
** uploadLambda.js **
Update project lambdas.
"createLambda" should have been previously called.
"Usage: uploadLambda.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information
about your API
[default: "./base.definitions.yaml"]
-l, --lambdaDefinitionsDir, directory that contains lambda
--lambdaDefinitionsDir definition files and
implementations. <lambdaName>.zip
archives will be placed here.
[default: "./lambdas"]
-n, --lambdaName a specific lambda to process. If not
specified all lambdas found will be
uploaded
-a, --archiveOnly Only perform archive operation. Do
not upload
-h, --help Show help [boolean]
** uploadRestAPI.js **
Upldate project API.
"createAPI" should have been previously called.
Usage: uploadRestAPI.js [options]
Options:
-s, --baseDefinitionsFile yaml file that contains information about your API
[default: "./base.definitions.yaml"]
-a, --apiDefinitionFile yaml swagger API file to upload to AWS
[default: "./swaggerAPI.yaml"]
-h, --help Show help [boolean]
```
## Project Configuration ##
TODO
<file_sep>"use strict";
const fs = require("fs");
const AWS = require("aws-sdk");
/*ignore jslint start*/
const AWSConstants = JSON.parse(fs.readFileSync("./AWSConstants.json", "utf8"));
/*ignore jslint end*/
const docClient = new AWS.DynamoDB.DocumentClient();
function getDeviceItem(deviceId, callback) {
var params = {
TableName: AWSConstants.DYNAMO_DB.DEVICES.name,
Key: {}
};
params.Key[AWSConstants.DYNAMO_DB.DEVICES.DEVICE_ID] = deviceId;
docClient.get(params, function (err, data) {
if (err) {
callback(err);
return;
}
if (typeof data.Item === "object") {
callback(null, data.Item);
} else {
callback(new Error("No Item field for device: " + deviceId));
}
});
}
function updateUserIds(deviceId, userIds, callback) {
var paramsDevice = {
TableName: AWSConstants.DYNAMO_DB.DEVICES.name,
Key: {},
UpdateExpression: "set " + AWSConstants.DYNAMO_DB.DEVICES.IDS + " = :t",
ExpressionAttributeValues: {
":t": userIds
}
};
paramsDevice.Key[AWSConstants.DYNAMO_DB.DEVICES.DEVICE_ID] = deviceId;
docClient.update(paramsDevice, callback);
}
function createDeviceItem(deviceId, userId, callback) {
// Add the email to the email table with provider token
// login will use this to lookup the identity
var paramsDevice = {
TableName: AWSConstants.DYNAMO_DB.DEVICES.name,
Item: {}
};
console.log("device Id: " + deviceId);
console.log("user Id: " + userId);
paramsDevice.Item[AWSConstants.DYNAMO_DB.DEVICES.DEVICE_ID] = deviceId;
paramsDevice.Item[AWSConstants.DYNAMO_DB.DEVICES.IDS] = [userId];
docClient.put(paramsDevice, function (err, deviceData) {
callback(err, deviceData);
});
}
function verifyItemUser(Item, userID) {
return (Item[AWSConstants.DYNAMO_DB.DEVICES.IDS].indexOf(userID) >= 0);
}
function addItemUser(Item, userID) {
if (Array.isArray(Item[AWSConstants.DYNAMO_DB.DEVICES.IDS])) {
Item[AWSConstants.DYNAMO_DB.DEVICES.IDS] = [userID].concat(Item[AWSConstants.DYNAMO_DB.DEVICES.IDS]);
} else {
Item[AWSConstants.DYNAMO_DB.DEVICES.IDS] = [userID];
}
}
function addUserId(deviceId, userId, callback) {
getDeviceItem(deviceId, function (ignore, Item) {
if (Item && Item[AWSConstants.DYNAMO_DB.DEVICES.IDS]) {
if (verifyItemUser(Item, userId)) {
callback(null);
} else {
addItemUser(Item, userId);
updateUserIds(deviceId, Item[AWSConstants.DYNAMO_DB.DEVICES.IDS], callback);
}
} else {
createDeviceItem(deviceId, userId, callback);
}
});
}
function verifyUser(deviceID, userID, callback) {
getDeviceItem(deviceID, function (ignore, Item) {
if (Item && Item[AWSConstants.DYNAMO_DB.DEVICES.IDS]) {
callback(null, verifyItemUser(Item, userID));
} else {
callback(null, false);
}
});
}
exports.verifyUser = verifyUser;
exports.addUserId = addUserId;
<file_sep>#!/usr/bin/env node
const path = require('path');
const awscommon = require(path.join(__dirname, 'awscommonutils'));
const fs = require('fs');
const YAML = require('yamljs');
const AwsRequest = require(path.join(__dirname, 'AwsRequest'));
const argv = require('yargs')
.usage('Create the identity pools required for the project.\nIf identity pools with the same name already exist a new pool will not be created and the existing pool infomation will be used.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.help('h')
.alias('h', 'help')
.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
throw new Error("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awscommon.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Creating Identity Pools ##");
awscommon.verifyPath(baseDefinitions, ['cognitoIdentityPoolInfo', 'identityPools'], 'o', "definitions file \""+argv.baseDefinitionsFile+"\"").exitOnError();
var numIdentityPools = Object.keys(baseDefinitions.cognitoIdentityPoolInfo.identityPools).length;
var successDecCount = numIdentityPools;
// first lets get the identity pools to see if one with our name exists already
getIdentityPools(function (serverIdentityPools) {
// now see which ones are valid and which ones need to be created
var poolCreateRequests = [];
Object.keys(baseDefinitions.cognitoIdentityPoolInfo.identityPools).forEach(function (identityPoolKey) {
var identityPoolName;
if (awscommon.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
identityPoolName = baseDefinitions.environment.AWSResourceNamePrefix + identityPoolKey;
} else {
throw new Error("Please assign a AWSResourceNamePrefix at 'environment.AWSResourceNamePrefix' in base definitions file '" + argv.baseDefinitionsFile + "'.");
}
var poolDef = baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey];
if (serverIdentityPools) {
for (var index = 0; index < serverIdentityPools.IdentityPools.length; index ++) {
if (identityPoolName === serverIdentityPools.IdentityPools[index].IdentityPoolName) {
baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].identityPoolId = serverIdentityPools.IdentityPools[index].IdentityPoolId;
console.log("Found identity pool \"" + identityPoolName + "\" on aws.");
setRoles(identityPoolKey);
updateRolePolicyDocumentStatementConditions(identityPoolKey);
numIdentityPools --;
successDecCount --;
if (numIdentityPools === 0) {
writeout();
return;
} else {
break;
}
}
}
}
// validate to make sure we have everything
awscommon.verifyPath(poolDef, ['allowUnauthedIdentities'], 'b', "identity pool definition \"" + identityPoolKey + "\"").exitOnError();
awscommon.verifyPath(poolDef, ['authProviders'], 'o', "identity pool definition \"" + identityPoolKey + "\"").exitOnError();
var params={
'identity-pool-name': {type: 'string', value: identityPoolName},
'profile': {type: 'string', value:AWSCLIUserProfile}
};
params[(poolDef.allowUnauthedIdentities ? 'allow-unauthenticated-identities': 'no-allow-unauthenticated-identities')] = {type: 'none'};
Object.keys(poolDef.authProviders).forEach(function(authProvider) {
switch (authProvider) {
case 'custom':
awscommon.verifyPath(poolDef.authProviders,['custom', 'developerProvider'],'s','custom developer provider for pool "' + identityPoolKey + '""').exitOnError();
params['developer-provider-name'] = {type: 'string', value:poolDef.authProviders.custom.developerProvider};
break;
default:
}
});
poolCreateRequests.push(
AwsRequest.createRequest({
serviceName:'cognito-identity',
functionName:'create-identity-pool',
context: {poolName: identityPoolName, poolKey: identityPoolKey},
returnSchema:'json',
returnValidation:[{path:['IdentityPoolId'], type:'s'}],
parameters:params
})
);
});
AwsRequest.createBatch(poolCreateRequests, function (batch) {
batch.requestArray.forEach(function (request) {
if (request.response.error) {
console.log(request.response.error);
console.log("Failed to create pool " + request.context.poolName + ".");
} else {
console.log("Successfully created pool " + request.context.poolName + ".");
successDecCount --;
baseDefinitions.cognitoIdentityPoolInfo.identityPools[request.context.poolKey].identityPoolId = request.response.parsedJSON.IdentityPoolId;
setRoles(request.context.poolKey);
updateRolePolicyDocumentStatementConditions(request.context.poolKey);
}
});
writeout();
}).startRequest();
});
function writeout() {
// now delete role
awscommon.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". pool id was not updated.");
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file.");
throw writeErr;
}
if (successDecCount !== 0) {
console.log("Some creation operations failed.");
}
});
}
function getIdentityPools (doneCallback) {
AwsRequest.createRequest({
serviceName:'cognito-identity',
functionName:'list-identity-pools',
returnSchema:'json',
returnValidation:[{path:['IdentityPools','IdentityPoolId'], type:'s'},
{path:['IdentityPools','IdentityPoolName'], type:'s'}],
parameters:{
'max-results': {type: 'string', value:'15'},
'profile': {type: 'string', value:AWSCLIUserProfile}
}
}, function(request) {
if (request.response.error) {
console.log(request.response.error);
doneCallback(null);
return;
}
doneCallback(request.response.parsedJSON);
}).startRequest();
}
function setRoles(identityPoolKey){
if (!awscommon.verifyPath(baseDefinitions, ['cognitoIdentityPoolInfo', 'identityPools', identityPoolKey, 'roles'], 'o',"").isVerifyError) {
var roles = {};
// TODO GET ROLE ARN!!!
roles = baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].roles;
var identityPoolRoles = {};
Object.keys(roles).forEach(function (roleType) {
identityPoolRoles[roleType] = baseDefinitions.cognitoIdentityPoolInfo.roleDefinitions[roles[roleType]].arnRole;
});
AwsRequest.createRequest({
serviceName: 'cognito-identity',
functionName: 'set-identity-pool-roles',
context: {poolKey: identityPoolKey},
returnSchema:'none',
parameters: {
'identity-pool-id' : {type:'string', value:baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].identityPoolId},
'roles' : {type: 'JSONObject', value:identityPoolRoles},
'profile': {type: 'string', value:AWSCLIUserProfile}
}
},
function (roleReq) {
if (roleReq.response.error) {
throw roleReq.response.error;
} else {
console.log("Set Roles for \"" + roleReq.context.poolKey + "\"");
}
}).startRequest();
}
}
function updateRolePolicyDocumentStatementConditions(identityPoolKey) {
// first get the role
var roles = baseDefinitions.cognitoIdentityPoolInfo.identityPools[identityPoolKey].roles;
Object.keys(roles).forEach(function (roleType) {
var role = roles[roleType];
if (!awscommon.verifyPath(baseDefinitions,['cognitoIdentityPoolInfo','identityPools',identityPoolKey,'rolePolicyDocumentStatementConditions',role],'a').isVerifyError) {
// get the role
var roleName;
if (awscommon.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
roleName = baseDefinitions.environment.AWSResourceNamePrefix + role;
}
AwsRequest.createRequest({
serviceName: 'iam',
functionName: 'get-role',
context: {poolKey: identityPoolKey, roleKey:role, roleName: roleName},
returnSchema:'json',
parameters: {
'role-name' : {type:'string', value:roleName},
'profile': {type: 'string', value:AWSCLIUserProfile}
}
},
function (roleReq) {
if (roleReq.response.error) {
console.log("no policy document statemets for role \"" + roleReq.context.roleKey + "to update. Is the role created?");
console.log(roleReq.response.error);
} else {
if (!awscommon.verifyPath(roleReq.response.parsedJSON,['Role','AssumeRolePolicyDocument','Statement'],'a').isVerifyError) {
// for each matching policy action add the conditions
var statementArray = roleReq.response.parsedJSON.Role.AssumeRolePolicyDocument.Statement;
var conditionArray = baseDefinitions.cognitoIdentityPoolInfo.identityPools[roleReq.context.poolKey].rolePolicyDocumentStatementConditions[role];
for (var conditionIndex = 0; conditionIndex < conditionArray.length; conditionIndex ++) {
for (var statementIndex = 0; statementIndex < statementArray.length; statementIndex ++) {
if (statementArray[statementIndex].Action === conditionArray[conditionIndex].Action) {
statementArray[statementIndex].Condition = conditionArray[conditionIndex].Condition;
// we may want to replace the identity pool ID in some of the conditions
Object.keys(statementArray[statementIndex].Condition).forEach(function(conditionType) {
var theCondition = statementArray[statementIndex].Condition[conditionType];
Object.keys(theCondition).forEach(function(conditionTypeParam) {
var val = theCondition[conditionTypeParam];
if (val === '$identityPoolId') {
theCondition[conditionTypeParam] = baseDefinitions.cognitoIdentityPoolInfo.identityPools[roleReq.context.poolKey].identityPoolId;
}
});
});
}
}
}
// UPDATE THE MODIFIED POLICY
AwsRequest.createRequest({
serviceName: 'iam',
functionName: 'update-assume-role-policy',
context: {poolKey: roleReq.context.poolKey, roleName:roleReq.context.roleName},
returnSchema:'none',
parameters: {
'role-name': {type:'string', value:roleReq.context.roleName},
'policy-document': {type: 'JSONObject', value:roleReq.response.parsedJSON.Role.AssumeRolePolicyDocument},
'profile': {type: 'string', value:AWSCLIUserProfile},
}
},
function (putPolReq) {
if (putPolReq.response.error) {
console.log("Error updating policy doc for role \"" + putPolReq.context.roleName + "\"");
console.log(putPolReq.response.error);
} else {
console.log("Updated policy doc for role \"" + putPolReq.context.roleName + "\"");
}
}).startRequest();
}
}
}).startRequest();
}
});
}
<file_sep>#!/usr/bin/env node
var command;
var commandFileName;
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const vp = require(path.join(__dirname, 'awscommonutils'));
const yargs = require('yargs')
.usage('Print or delete deploy parameters from project.\nWARNING: You cannot recover these settings and will have to remove the deploy manually in the AWS console once deleted.\nUsage: $0 <command> [options] filename')
.command('print', 'print current parameters', {}, function () {command = 'print';})
.command('delete', 'remove current parameters', {}, function () {command = 'delete';})
.command('save <fileName>', 'store parameters in YAML format to file', {}, function (argv2) {command = 'save'; commandFileName = argv2.fileName;})
.command('apply <fileName>', 'overwrite current parameters with saved file', {}, function (argv2) {command = 'apply'; commandFileName = argv2.fileName;})
.example('$0 save foo.js', 'save parameters to the given file')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.alias('l','lambdaDefinitionsDir')
.describe('l','directory that contains lambda definition files and implementations.')
.default('l','./lambdas')
.alias('c','clientDefinitionsDir')
.describe('c','directory that contains client definition files and implementations.')
.default('c','./clients')
.global(['s','l','c'])
.help('h')
.alias('h', 'help');
const argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
yargs.showHelp("log");
throw new Error("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
}
if (!fs.existsSync(argv.lambdaDefinitionsDir)) {
yargs.showHelp("log");
throw new Error("Lambda's path \"" + argv.lambdaDefinitionsDir + "\" not found.");
}
var paths = {};
paths[argv.baseDefinitionsFile] =[
["environment", "AWSResourceNamePrefix"],
["cognitoIdentityPoolInfo", "roleDefinitions", "*", "arnRole"],
["cognitoIdentityPoolInfo", "identityPools", "*", "identityPoolId"],
["lambdaInfo", "roleDefinitions", "*", "arnRole"],
["apiInfo", "roleDefinitions", "*", "arnRole"],
["apiInfo", "awsId"],
["apiInfo", "lastDeploy"],
["dynamodbInfo", "*", "Table"],
["s3Info", "buckets", "*", "name"],
["s3Info", "buckets", "*", "location"],
["vpcInfo","vpcs", "*", "VpcId"],
["vpcInfo","vpcs", "*", "GroupId"],
["vpcInfo","vpcs", "*", "NetworkAclId"],
["vpcInfo","vpcs", "*", "RouteTableId"],
["subnetInfo", "subnets", "*", "SubnetId"],
["internetGatewayInfo", "internetGateways", "*", "InternetGateway"],
["natGatewayInfo", "natGateways", "*", "NatGateway"],
["routeTableInfo", "routeTables", "*", "RouteTable"],
["routeTableInfo", "routeTables", "*", "Associations"],
["elasticacheInfo", "elasticaches", "*", "CacheCluster"],
["elasticacheInfo", "subnetGroups", "*", "CacheSubnetGroup"],
];
forEachClientDefinition(function (fileName) {
paths[path.join(argv.clientDefinitionsDir, fileName)] = [
["s3Info", "buckets", "*", "name"],
["s3Info", "buckets", "*", "location"]
];
}, getLambdaDefinitions);
function getLambdaDefinitions() {
forEachLambdaDefinition(function (fileName) {
paths[path.join(argv.lambdaDefinitionsDir, fileName)] = [
["lambdaInfo", "arnLambda"]
];
}, runCommands);
}
function runCommands() {
var paramObj = {};
if (command === "print") {
allParams(logobj, false, {paramObj: paramObj});
console.log(YAML.stringify(paramObj, 10));
}
if (command === "delete") {
allParams(delObj, true);
}
if (command === "save") {
allParams(logobj, false, {paramObj: paramObj});
fs.writeFile(commandFileName, YAML.stringify(paramObj, 10));
}
if (command === "apply") {
YAML.load(commandFileName);
applyFileParams(YAML.load(commandFileName));
}
}
function logobj(base, pathString, context, actualPath, pathType) {
if (!context.paramObj[context.fileName]) {
context.paramObj[context.fileName] = {};
}
var fullPath = actualPath.concat([pathString]);
var item = context.paramObj[context.fileName];
fullPath.forEach(function (pathName, index) {
if (index === fullPath.length - 1) {
item[pathName] = base[pathString];
} else if (pathType[index] === 'a') {
if (!item[pathName]) {
item[pathName] = [];
}
item = {};
item[pathName].push(item);
} else {
if (!item[pathName]) {
item[pathName] = {};
}
item = item[pathName];
}
});
}
function delObj(base, pathString) {
delete base[pathString];
}
function allParams(action, saveFile, context) {
if (!context) {
context = {};
}
Object.keys(paths).forEach(function (fileName) {
var definitions = YAML.load(fileName);
paths[fileName].forEach(function (pathArray) {
context.fileName = fileName;
lastNode(definitions, pathArray, action, context);
});
if (saveFile) {
vp.updateFile(fileName, function ()
{
return YAML.stringify(definitions, 15);
}, function(err1, err2){
if (err1) {
console.log(err1);
return;
}
if (err2) {
console.log(err2);
return;
}
console.log("Saved " + fileName);
});
}
});
}
function applyFileParams (params) {
Object.keys(params).forEach(function (fileName) {
var definitions = YAML.load(fileName);
applyParams(definitions, params[fileName]);
vp.updateFile(fileName, function ()
{
return YAML.stringify(definitions, 15);
}, function(err1, err2){
if (err1) {
console.log(err1);
return;
}
if (err2) {
console.log(err2);
return;
}
console.log("Saved " + fileName);
});
});
}
function applyParams(base, params) {
if (typeof params === 'object') {
Object.keys(params).forEach(function (name) {
var item = params[name];
if (Array.isArray(item)) {
// basically do the best we can to update using the existing order
if (!base[name]) {
base[name] = item;
} else {
if (!Array.isArray(base[name])) {
throw new Error("Expected array at '" + name + "'");
}
if (base[name].length !== item.length) {
throw new Error("Array item has miss-matched length at '" + name + "'");
}
base[name].forEach(function (arrayItem, index) {
applyParams(arrayItem, item[index]);
});
}
} else if (typeof item === 'object') {
if (!base[name]) {
base[name] = item;
} else {
if (typeof (base[name]) !== 'object') {
throw new Error("Expected object at '" + name + "'");
}
applyParams(base[name], item);
}
} else {
base[name] = item;
}
});
} else {
throw new Error("unexpected item passed as params: " + params);
}
}
function forEachLambdaDefinition (callback, doneCallback) {
fs.readdir(argv.lambdaDefinitionsDir, function (err, files) {
if (err) {
console.log(err);
process.exit(1);
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
var writeOut = true;
if ((typeof argv.lambdaName === 'string') && (argv.lambdaName !== fileNameComponents[0])) {
console.log("Not target lambda. Skipping.");
writeOut = false;
}
if (writeOut) {
callback(fileName);
}
}
}
doneCallback();
});
}
function forEachClientDefinition (callback, doneCallback) {
fs.readdir(argv.clientDefinitionsDir, function (err, files) {
if (err) {
throw err;
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
var writeOut = true;
if ((typeof argv.clientName === 'string') && (argv.clientName !== fileNameComponents[0])) {
console.log("Not target API. Skipping.");
writeOut = false;
}
if (writeOut) {
callback(fileName);
}
}
}
doneCallback();
});
}
function lastNode(base, pathArray, callback, context, actualPath, pathType) {
if (!context) {
context = {};
}
if (!pathType) {
pathType = [];
} else {
pathType = pathType.slice();
}
if (!actualPath) {
actualPath = [];
} else {
actualPath = actualPath.slice();
}
if (!base) {
return;
}
if (pathArray.length === 1) {
if (Array.isArray(base)) {
pathType.push('a');
base.forEach(function (newBase) {
callback(newBase, pathArray[0], context, actualPath, pathType);
});
return;
}
callback(base, pathArray[0], context, actualPath, pathType);
return;
}
var target = pathArray.shift();
if (Array.isArray(base)) {
actualPath.push(target);
pathType.push('a');
base.forEach(function (newBase) {
lastNode(newBase, target, pathArray, context, actualPath, pathType);
});
return;
}
pathType.push('o');
if (target === '*') {
Object.keys(base).forEach(function (newItem) {
lastNode(base[newItem], pathArray, callback, context, actualPath.concat([newItem]), pathType);
});
return;
}
lastNode(base[target], pathArray, callback, context, actualPath.concat([target]), pathType);
}
<file_sep>#!/bin/bash
./AWSTools/coalesceSwaggerAPIDefinition.js \
--outputFilename swaggerAPI.yaml
if [ $? -eq 0 ]; then
./AWSTools/uploadRestAPI.js --APIDefinition swaggerAPI.yaml \
--AWSUserProfile adminuser
else
echo "Upload failed: coalesceSwaggerAPIDefinition failed"
fi
<file_sep>#!/bin/bash
./AWSTools/updateLinkedFiles.js --lambdaDefinitionsDir lambdas
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Creates NAT Gateways and assignes them to a VPC.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.help('h')
.alias('h', 'help');
var argv = yargs.argv;
// once the gateway is deleted, delete the NatGatewayAddresses and remove any routs pointing to it.
var retryCounters = {};
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Deleting NAT Gateways ##");
if (awsc.verifyPath(baseDefinitions,['natGatewayInfo', 'natGateways'],'o').isVerifyError) {
console.log("Nothing to do.");
return;
}
Object.keys(baseDefinitions.natGatewayInfo.natGateways).forEach(function (natGatewayName) {
var natGatewayDescription = baseDefinitions.natGatewayInfo.natGateways[natGatewayName];
if (awsc.verifyPath(natGatewayDescription, ["NatGateway", "NatGatewayId"], 's').isVerifyError) {
console.log("NAT Gateway '" + natGatewayName + "' is already deleted.");
return;
}
console.log("Deleting NAT Gateway " + natGatewayName);
deleteTrafficSourceRoutes(natGatewayName, function (natGatewayName) {
deleteNatGateway(natGatewayName, function (err, natGatewayName) {
if (err) {
console.log(err);
return;
}
waitForNatGatewayDeleted(natGatewayName, function (natGatewayName) {
deleteElasticIp(natGatewayName, function (err, natGatewayName) {
if (err) {
throw err;
}
delete baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway;
commitUpdates(natGatewayName);
console.log("Deleted NAT Gateway " + natGatewayName);
});
});
});
});
});
function commitUpdates(natGatewayName) {
writeOut("Could not update natGatewayId for NAT Gateway '" + natGatewayName + "'.");
}
function waitForNatGatewayDeleted(natGatewayName, callback) {
if (!retryCounters[natGatewayName]) {
retryCounters[natGatewayName] = 1;
}
var maxRetry = 30;
var status = baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway.State;
console.log("Waiting for NAT Gateway '" + natGatewayName + "' deleted. Current status: '" + status + "'. Retry " + retryCounters[natGatewayName] + " of " + maxRetry);
if (status === 'deleted') {
callback(natGatewayName);
return;
}
setTimeout(function () {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "describe-nat-gateways",
parameters:{
"nat-gateway-ids": {type: "string", value: baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway.NatGatewayId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['NatGateways'], type:'a'}]
},
function (request) {
if (request.response.error) {
console.log("Issue retrieving nat gateway description from AWS");
throw request.response.error;
}
if (request.response.parsedJSON.NatGateways[0].State === "deleted") {
baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway = request.response.parsedJSON.NatGateways[0];
callback(natGatewayName);
} else {
if (retryCounters[natGatewayName] > maxRetry) {
throw new Error("Waiting for 'deleted' status of NAT Gateway '" + natGatewayName + "' timed out.");
}
baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway = request.response.parsedJSON.NatGateways[0];
retryCounters[natGatewayName] = retryCounters[natGatewayName] + 1;
waitForNatGatewayDeleted(natGatewayName, callback);
}
}).startRequest();
}, 10000);
}
function deleteElasticIp(natGatewayName, callback) {
if (awsc.verifyPath(baseDefinitions, ["natGatewayInfo", "natGateways", natGatewayName, "NatGateway", "NatGatewayAddresses"], 'a').isVerifyError) {
console.log("No Elastic IPs to release for NAT Gateway " + natGatewayName);
callback(null, natGatewayName); // nothing to do
return;
}
var releaseAddressRequests = [];
var addresses = baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway.NatGatewayAddresses;
addresses.forEach(function (address){
releaseAddressRequests.push(AWSRequest.createRequest({
serviceName: "ec2",
functionName: "release-address",
parameters:{
"allocation-id": {type: "string", value: address.AllocationId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'none'
},
function () {}
));
});
if (releaseAddressRequests.length > 0) {
AWSRequest.createBatch(releaseAddressRequests, function (batchRequest) {
var failCount = 0;
batchRequest.requestArray.forEach(function (request) {
if (request.response.error && (request.response.errorId !== "InvalidAllocationID.NotFound")) {
failCount ++;
console.log(request.response.error);
} else {
console.log("Released elastic IP " + request.parameters["allocation-id"].value);
}
});
if (failCount > 0) {
callback(new Error("Failed to complete " + failCount + "/" + batchRequest.requestArray.length + " requests."), natGatewayName);
} else {
console.log("Successfully completed all delete Elastic IP requests.");
callback(null, natGatewayName);
}
}).startRequest();
} else {
callback(null, natGatewayName);
}
}
function deleteNatGateway(natGatewayName, callback) {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "delete-nat-gateway",
parameters:{
"nat-gateway-id": {type: "string", value: baseDefinitions.natGatewayInfo.natGateways[natGatewayName].NatGateway.NatGatewayId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'none'
},
function (request) {
if (request.response.error) {
callback(request.response.error, natGatewayName);
return;
}
callback(null, natGatewayName);
}).startRequest();
}
function deleteTrafficSourceRoutes(natGatewayName, callback) {
console.log("Deleting traffic source routes.");
if (awsc.verifyPath(baseDefinitions, ["natGatewayInfo", "natGateways", natGatewayName, "trafficSourceRouters"], 'a').isVerifyError) {
console.log("No traffic source routes.");
return;
}
var tsRouters = baseDefinitions.natGatewayInfo.natGateways[natGatewayName].trafficSourceRouters;
var delTrafficRequests = [];
tsRouters.forEach(function (route){
var params = {
"profile": {type: "string", value: AWSCLIUserProfile}
};
Object.keys(route).forEach(function (routeKey) {
var key;
var value;
if(routeKey === "routerTable") {
key = "route-table-id";
value = baseDefinitions.routeTableInfo.routeTables[route.routerTable].RouteTable.RouteTableId;
} else if(routeKey === "vpcDefaultRouter") {
key = "route-table-id";
value = baseDefinitions.vpcInfo.vpcs[route.vpcDefaultRouter].RouteTableId;
} else {
key = routeKey;
value = route[routeKey];
}
params[key] = {type: "string", value: value};
});
delTrafficRequests.push(AWSRequest.createRequest({
serviceName: "ec2",
functionName: "delete-route",
context: {route: route, routeTableName: natGatewayName},
parameters: params,
returnSchema:'none'
},
function (request) {
if (request.response.error && (request.response.errorId !== "InvalidRoute.NotFound") && (request.response.errorId !== "InvalidRouteTableID.NotFound")) {
throw request.response.error;
}
console.log("Deleted Route " + request.parameters["destination-cidr-block"].value + " on route table " + request.parameters["route-table-id"].value);
}));
});
if (delTrafficRequests.length > 0) {
AWSRequest.createBatch(delTrafficRequests, function() {
callback(natGatewayName);
}).startRequest();
} else {
callback(natGatewayName);
}
}
function writeOut(errorText) {
// now delete role
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". " + errorText);
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file. " + errorText);
throw writeErr;
}
});
}
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Syncs client angular files to their s3 bucket. Creates the bucket if needed and configures as static web host.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.alias('l','clientDefinitionsDir')
.describe('l','directory that contains client definition files and implementations.')
.default('l','./clients')
.help('h')
.alias('h', 'help');
const argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
if (!fs.existsSync(argv.clientDefinitionsDir)) {
yargs.showHelp("log");
throw new Error("Clients path \"" + argv.clientDefinitionsDir + "\" not found.");
}
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("Syncing angular client files to s3 bucket.");
forEachLambdaDefinition(function (fileName) {
// here we would want to fork to do ops in parallel
var definitions = YAML.load(path.join(argv.clientDefinitionsDir,fileName));
if (typeof definitions !== 'object') {
throw new Error("Definitions file \"" + fileName + "\" could not be parsed");
}
if (!awsc.verifyPath(definitions, ['s3Info', 'buckets'], 'o', 'in angular client definition file').isVerifyError) {
Object.keys(definitions.s3Info.buckets).forEach(function (bucketPrefix) {
var bucketInfo = definitions.s3Info.buckets[bucketPrefix];
if ((!awsc.verifyPath(bucketInfo, ['name'], 's', 'in angular client definition file').isVerifyError) &&
(!awsc.verifyPath(bucketInfo, ['fileSyncInfo', 'syncPath'], 's', 'in angular client definition file').isVerifyError)) {
console.log("Syncing bucket \"" + bucketInfo.name + "\".");
syncFiles(bucketInfo, function (err, bucketInfo) {
if (err) {
throw err;
} else {
console.log('Site URL is: http://' + bucketInfo.name + ".s3-website-" + bucketInfo.region + ".amazonaws.com");
}
});
} else {
console.log("Nothing to do.");
}
});
}
});
function syncFiles(bucketInfo, callback) {
var customParamString = path.join(argv.clientDefinitionsDir, bucketInfo.fileSyncInfo.syncPath);
customParamString += " s3://" + bucketInfo.name;
if (!awsc.verifyPath(bucketInfo, ['fileSyncInfo', 'syncExclusions'], 'a', 'in angular client bucket definition').isVerifyError) {
for (var index = 0; index < bucketInfo.fileSyncInfo.syncExclusions.length; index ++) {
customParamString += ' --exclude "' + bucketInfo.fileSyncInfo.syncExclusions[index] + '"';
}
}
var params = {'profile' : {type: 'string', value: AWSCLIUserProfile}};
if (!awsc.verifyPath(bucketInfo, ['fileSyncInfo', 'acl'], 's', 'in angular client bucket definition').isVerifyError) {
params.acl = {type:'string', value: bucketInfo.fileSyncInfo.acl};
}
AWSRequest.createRequest(
{
serviceName: "s3",
functionName: "sync",
parameters: params,
customParamString: customParamString,
returnSchema: 'none'
},
function (request) {
if (!request.response.error) {
console.log(request.response.stdout);
}
callback(request.response.error, bucketInfo);
}
).startRequest();
}
function forEachLambdaDefinition (callback, doneCallback) {
fs.readdir(argv.clientDefinitionsDir, function (err, files) {
if (err) {
throw err;
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[0] === 'angular') && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var writeOut = true;
if ((typeof argv.clientName === 'string') && (argv.clientName !== fileNameComponents[0])) {
console.log("Not target API. Skipping.");
writeOut = false;
}
if (writeOut) {
callback(fileName);
}
}
}
if (doneCallback) {
doneCallback();
}
});
}
<file_sep>/* jshint undef: true, unused: true, esversion: 6, devel: true, node: false, browser: true, module: true */
'use strict';
function logout(authService, $scope, $timeout) {
var ctrl = this;
ctrl.logoutTitle = "Logout";
ctrl.logoutText = "Logging out...";
// There is no need to get the authService.authedClient() to log out the user. Just call
// authService.clearAll(). In this case I want to show that we can determine if there
// is a user currently logged in.
authService.authedClient(function(client,err) {
// authedClient() not return immediately
$timeout(function (){
$scope.$apply(function(){
if (err) {
ctrl.logoutText = "No one is logged in.";
} else {
ctrl.logoutText = "You are logged out";
}
// clear any lingering credentials.
authService.clearAll();
});
});
});
}
angular.
module('logoutModule',['awsAPIClients']).
component('logout',{
templateUrl: 'components/logout/logout.html',
controller: logout
});
<file_sep>/* jshint undef: true, unused: true, esversion: 6, devel: true, node: false, browser: true, module: true */
/* globals AWS:true, apigClientFactory: true */
'use strict';
var awsAPIClientsModule = angular.module("awsAPIClients", ['ngCookies']);
awsAPIClientsModule.value('idendityIdTokenAuthedClient',{IdentityId:null,Token:null,AuthedClient:null});
awsAPIClientsModule.value('providerData',{providerName: null, providerId:null});
awsAPIClientsModule.factory('apiUnauthedClientFactory', function () {
return apigClientFactory.newClient();
});
awsAPIClientsModule.service('authService', function(apiUnauthedClientFactory, idendityIdTokenAuthedClient, providerData, $cookies) {
var ctrl = this;
ctrl.guid = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
ctrl.deviceId = function () {
if (!$cookies.get("deviceId")) {
$cookies.put("deviceId", ctrl.guid());
}
return $cookies.get("deviceId");
};
ctrl.isLoggedIn = function () {
return (ctrl.hasReceivedProviderData());
}
ctrl.sessionExpired = function () {
if (AWS.config.credentials && AWS.config.credentials.expireTime) {
console.log("session will expire in " + ((AWS.config.credentials.expireTime.getTime() - (new Date()).getTime())/1000.0/60.0) + " minutes.");
}
if (!AWS.config.credentials ||
!AWS.config.credentials.accessKeyId ||
!AWS.config.credentials.secretAccessKey ||
!AWS.config.credentials.sessionToken ||
!AWS.config.credentials.expireTime ||
AWS.config.credentials.expireTime < new Date()) {
return true;
} else {
return false;
}
};
ctrl.updateAuthedClient = function (callback) {
console.log('attempting to update authed client');
if (!ctrl.sessionExpired()) {
console.log("session isn't expired, returning authed client");
idendityIdTokenAuthedClient.AuthedClient = apigClientFactory.newClient({
accessKey: AWS.config.credentials.accessKeyId,
secretKey: AWS.config.credentials.secretAccessKey,
sessionToken: AWS.config.credentials.sessionToken,
}); callback(idendityIdTokenAuthedClient.AuthedClient);
} else {
console.log("session expired, returning 'no valid session credentials'.");
idendityIdTokenAuthedClient.AuthedClient = null;
callback(null, new Error('no valid session credentials'));
}
};
ctrl.clearAll = function () {
// effectively logs out the user
ctrl.clearSession();
ctrl.clearIdentityAndToken();
ctrl.clearProviderData();
delete idendityIdTokenAuthedClient.AuthedClient;
};
ctrl.clearSession = function () {
AWS.config.credentials = null;
$cookies.remove('sessionCredentials');
};
ctrl.retrieveStoredSession = function () {
console.log("retrieving stored session");
// try to get an authed client.
var sessionObject = $cookies.getObject('sessionCredentials');
if (typeof sessionObject == 'object') {
if (typeof sessionObject.expireTimeJSONDate == 'string') {
sessionObject.expireTime = new Date(sessionObject.expireTimeJSONDate);
delete sessionObject.expireTimeJSONDate;
console.log('retrieved parsable session');
AWS.config.credentials = {};
AWS.config.credentials.expireTime = sessionObject.expireTime;
AWS.config.credentials.accessKeyId = sessionObject.accessKeyId;
AWS.config.credentials.secretAccessKey = sessionObject.secretAccessKey;
AWS.config.credentials.sessionToken = sessionObject.sessionToken;
if (ctrl.sessionExpired()) {
console.log("stored session has expired");
delete idendityIdTokenAuthedClient.AuthedClient;
AWS.config.credentials = null;
}
} else {
console.log("unknown date format for token expiration");
AWS.config.credentials = null;
}
} else {
console.log('invalid or missing stored session');
AWS.config.credentials = null;
}
};
ctrl.storeSession = function () {
console.log("Storing new session credentials");
var params = {
accessKeyId: AWS.config.credentials.accessKeyId,
secretAccessKey: AWS.config.credentials.secretAccessKey,
sessionToken: AWS.config.credentials.sessionToken,
expireTimeJSONDate: AWS.config.credentials.expireTime.toJSON()
};
$cookies.putObject('sessionCredentials', params);
};
ctrl.getNewSession = function(callback) {
console.log("attempting to get new session from cognito");
// try to restore provider data if we have it
ctrl.restoreProviederData();
if (ctrl.hasIdentityAndToken()) {
// Set the region where your identity pool exists (us-east-1, eu-west-1)
var splitIdentity = idendityIdTokenAuthedClient.IdentityId.split(':');
if (splitIdentity.length < 2) {
console.log("invalid IdentityId");
callback(null, new Error('invalid IdentityId'));
return;
}
AWS.config.region = splitIdentity[0];
// Configure the credentials provider to use your identity pool
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityId: idendityIdTokenAuthedClient.IdentityId,
Logins: {
'cognito-identity.amazonaws.com': idendityIdTokenAuthedClient.Token
}
});
} else {
console.log("no Identity and Token found");
AWS.config.credentials = null;
if (!ctrl.hasReceivedProviderData()) {
console.log("no stored provider data");
// nothing to do... basically need to logout
callback(null,new Error("not enough information to create new session"));
return;
}
}
var loginWithProviderData = function (callback){
if (!ctrl.hasReceivedProviderData()) {
console.log("no provider data");
// logout;
callback(null,new Error("no provider data"));
return;
}
console.log("trying to get Identity and Token with provider data");
apiUnauthedClientFactory.tokenPost({},{provider_name: providerData.providerName, id: providerData.providerId, device_id: ctrl.deviceId()})
.then(function(result){
console.log("received Identity and Token from provider data");
ctrl.setIdentityAndToken(result.data.IdentityId, result.data.Token, callback);
}).catch(function(){
console.log("fail to get Identity and Token with provider data");
callback(null, new Error("unable to get data for new session"));
});
};
// Make the call to obtain session
if (!AWS.config.credentials && ctrl.hasReceivedProviderData()) {
loginWithProviderData(callback);
return;
}
AWS.config.credentials.get(function(err){
if (err) {
console.log("could not get session from IdentityID and Token with get");
console.log(err);
// try one more time with refresh
loginWithProviderData(callback);
} else {
ctrl.storeSession();
ctrl.updateAuthedClient(function (client, err) {
callback(client,err); // also logout if error?
if (!err) {
// get the curretn client provider and id
if (!ctrl.hasReceivedProviderData()) {
ctrl.getProviderData(client);
} else {
console.log("already have provider data, no need to get it again");
}
}
});
}
});
};
ctrl.clearIdentityAndToken = function () {
delete idendityIdTokenAuthedClient.IdentityId;
delete idendityIdTokenAuthedClient.Token;
};
ctrl.getProviderData = function (client) {
console.log("getting provider data");
client.userMeGet().then(function(result){
console.log("received provier data");
ctrl.setProviderNameAndId(result.data.provider_name, result.data.logins[result.data.provider_name]);
// this infromation is no longer needed
ctrl.clearIdentityAndToken();
}).catch(function(result) {
console.log("failed getting provider data");
console.log(result);
// also logout?
});
};
ctrl.hasReceivedProviderData = function () {
if (providerData.providerName && providerData.providerId) {
return true;
}
// check to see if we have any in the keychain
ctrl.restoreProviederData();
if (providerData.providerName && providerData.providerId) {
return true;
}
return false;
};
ctrl.restoreProviederData = function () {
var providerFromStorage = $cookies.getObject('providerData');
if (providerFromStorage) {
providerData.providerName = providerFromStorage.providerName;
providerData.providerId = providerFromStorage.providerId;
}
};
ctrl.setProviderNameAndId = function (providerName, providerId) {
providerData.providerName = providerName;
providerData.providerId = providerId;
$cookies.putObject('providerData',providerData);
};
ctrl.clearProviderData = function () {
delete providerData.providerName;
delete providerData.providerId;
$cookies.remove('providerData');
};
ctrl.hasIdentityAndToken = function () {
if (idendityIdTokenAuthedClient.IdentityId && idendityIdTokenAuthedClient.Token) {
return true;
}
return false;
};
ctrl.setIdentityAndToken = function (identityId, token, callback) {
delete idendityIdTokenAuthedClient.AuthedClient;
ctrl.clearIdentityAndToken();
ctrl.clearSession();
idendityIdTokenAuthedClient.IdentityId = identityId;
idendityIdTokenAuthedClient.Token = token;
ctrl.authedClient(callback);
};
ctrl.authedClient = function (callback) {
// try and make a client from stored credentials
if (!AWS.config.credentials) {
console.log("Don't have AWS.config.credentials");
console.log("Attemping to retrieve from cookie");
ctrl.retrieveStoredSession();
}
// try to make a authed client from stored session
if (!idendityIdTokenAuthedClient.AuthedClient || ctrl.sessionExpired()) {
if (!idendityIdTokenAuthedClient.AuthedClient) {
console.log("don't have a stored authed client");
}
if (ctrl.sessionExpired()) {
console.log("session is expired");
}
ctrl.updateAuthedClient(function(client, err) {
console.log("updating authed client");
if (err) {
// try to start from identityID & token
ctrl.getNewSession(function (authedClient,err) {
if (err) {
callback(null,err); // could not get session
} else {
callback(authedClient);
}
});
} else {
callback(client);
// check to make sure we have provider data.
if (!ctrl.hasReceivedProviderData()) {
// lets see if it can be
ctrl.restoreProviederData();
if (!ctrl.hasReceivedProviderData()) {
ctrl.getProviderData(client);
}
}
}
});
} else {
callback(idendityIdTokenAuthedClient.AuthedClient);
}
};
}
);
<file_sep>"use strict";
console.log("Loading function");
const fs = require("fs");
/*ignore jslint start*/
const AWSConstants = JSON.parse(fs.readFileSync("./AWSConstants.json", "utf8"));
/*ignore jslint end*/
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient();
const PH = require("./PasswordHash");
const UserIdentity = require("./UserIdentity");
const APIParamVerify = require("./APIParamVerify");
const Devices = require("./Devices");
/**
* handler signup
* @param {[type]} event [description]
* @param {[type]} context [description]
* @param {Function} callback [description]
* @return {[type]} [description]
*
*/
function handler(event, context, callback) {
process.on("uncaughtException", ( err ) => {
console.log(err);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Internal Error."
}));
});
console.log(event);
// make sure we have needed params
var verifyResult = APIParamVerify.verify("/login", "post", event);
if (verifyResult) {
verifyResult.requestId = context.awsRequestId;
console.log(verifyResult);
callback(JSON.stringify(verifyResult));
return;
}
var getIdentityIDAndToken = function (identityId, id, event, awsRequestId, callback) {
UserIdentity.getOpenIDToken(AWSConstants.COGNITO.IDENTITY_POOL.identityPoolId, identityId, AWSConstants.COGNITO.IDENTITY_POOL.authProviders.custom.developerProvider, id, function (err, OpenIDToken) {
if (err) {
console.log(err);
console.log("Could not get user identity from cognito for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not get user identity."
}));
return;
}
// now lookup in the user table
var params = {
TableName: AWSConstants.DYNAMO_DB.USERS.name,
Key: {}
};
params.Key[AWSConstants.DYNAMO_DB.USERS.ID] = OpenIDToken.IdentityId;
docClient.get(params, function (err, userData) {
if (err) {
console.log(err);
console.log("Could not get user info from db for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not get user info."
}));
return;
}
if (typeof userData.Item.password === 'string') {
if (PH.passwordHash(event.password) === userData.Item.password) {
// add the device to the device table
Devices.addUserId(event.device_id, OpenIDToken.IdentityId, function (err) {
if (err) {
console.log("Error storing device token.");
console.log(err);
callback(JSON.stringify({
requestId: awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not store user device."
}));
return;
}
callback(null, OpenIDToken);
});
} else {
console.log("Password missmatch for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: awsRequestId,
errorType: "Unauthorized",
httpStatus: 401,
message: "No matching login informaiton."
}));
return;
}
} else {
console.log("user does not have a valid password data for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not get user info."
}));
return;
}
});
});
};
// check if the email exists
var params = {
TableName: AWSConstants.DYNAMO_DB.EMAILS.name,
Key: {}
};
params.Key[AWSConstants.DYNAMO_DB.EMAILS.EMAIL] = event.email;
docClient.get(params, function (err, data) {
if (err) {
console.log(err);
console.log("Could not get user identity from email db for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "Unauthorized",
httpStatus: 401,
message: "No matching login information."
}));
return;
}
// it we get some objects back from the email table then the users has already signed up
if (typeof data.Item === "object") {
UserIdentity.lookupIdentity(AWSConstants.COGNITO.IDENTITY_POOL.identityPoolId, data.Item.id, function (err, identityID) {
if (err) {
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "Unauthorized",
httpStatus: 401,
message: "No matching identity."
}));
return;
}
console.log("start get Identity");
getIdentityIDAndToken(identityID, data.Item.id, event, context.awsRequestId, function (err, OpenIDToken) {
console.log("end get Identity");
if (err || !OpenIDToken || !OpenIDToken.IdentityId || !OpenIDToken.Token) {
console.log("Could not get user identity from cognito for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "Unauthorized",
httpStatus: 401,
message: "No matching login information."
}));
return;
}
// have Tokens
// update login timestamp
var paramsUser = {
TableName: AWSConstants.DYNAMO_DB.USERS.name,
Key: {},
UpdateExpression: "set " + AWSConstants.DYNAMO_DB.USERS.LAST_LOGIN_TIMESTAMP + " = :t",
ExpressionAttributeValues: {
":t": Date.now()
}
};
paramsUser.Key[AWSConstants.DYNAMO_DB.USERS.ID] = OpenIDToken.IdentityId;
docClient.update(paramsUser, function (err) {
if (err) {
console.log("unable to update login timestamp for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Could not set user info."
}));
return;
}
callback(null, OpenIDToken);
});
});
});
} else {
console.log("Could not get user info from db for request: " + context.awsRequestId);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "Unauthorized",
httpStatus: 401,
message: "No matching login informaiton."
}));
}
});
}
exports.handler = handler;
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const exec = require('child_process').exec;
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Create the lambdas for the project.\nIf a lambda with the same name already exists the operation will fail.\nUse "deleteLambda" first to remove the exisiting function.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.alias('l','lambdaDefinitionsDir')
.describe('l','directory that contains lambda definition files and implementations. <lambdaName>.zip archives will be placed here.')
.default('l','./lambdas')
.alias('n','lambdaName')
.describe('n','a specific lambda to process. If not specified all lambdas found will be uploaded')
.alias('a','archiveOnly')
.describe('a','Only perform archive operation. Do not upload')
.alias('u','updateArnLambda')
.describe('u', 'ignore existing \"arnLambda\" in \"lambdaInfo\" section of definitions file and overwrite new value on success')
.help('h')
.alias('h', 'help');
const argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
yargs.showHelp("log");
throw new Error("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
console.log("## Creating Lambdas ##");
if (!fs.existsSync(argv.lambdaDefinitionsDir)) {
yargs.showHelp("log");
throw new Error("Lambda's path \"" + argv.lambdaDefinitionsDir + "\" not found.");
}
var AWSCLIUserProfile = "default";
if (typeof baseDefinitions.environment !== 'object') {
} else {
if (typeof baseDefinitions.environment.AWSCLIUserProfile === 'string') {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
}
}
if (AWSCLIUserProfile === "default") {
console.log("using \"default\" AWSCLIUserProfile");
}
forEachLambdaDefinition(function (fileName) {
// here we would want to fork to do ops in parallel
var definitions = YAML.load(path.join(argv.lambdaDefinitionsDir,fileName));
if (typeof definitions !== 'object') {
throw new Error("Definitions file \"" + fileName + "\" could not be parsed");
}
if (awsc.verifyPath(definitions,['lambdaInfo', 'arnLambda'], 's', "definitions file \"" + fileName + "\"").isValidationErrpr && !argv.updateArnLambda) {
throw new Error("There is already a \"arnLambda\" string in \"lambdaInfo\" object in definitions file \"" + fileName + "\". To overwrite this value when created run with option \"--updateArnLambda\".");
}
awsc.verifyPath(definitions,['lambdaInfo','functionName'],'s', "definitions file \"" + fileName + "\"", "This should be the name of the lambda function.").exitOnError();
// remove older archives
if (fs.existsSync(path.join(argv.lambdaDefinitionsDir, definitions.lambdaInfo.functionName + ".zip"))) {
fs.unlinkSync(path.join(argv.lambdaDefinitionsDir, definitions.lambdaInfo.functionName + ".zip"));
}
// fitst zip the archive we can drop them into the lambdas directory
var cdCommand = "cd \"" + path.join(argv.lambdaDefinitionsDir,definitions.lambdaInfo.functionName) + "\"; ";
var zipCommandString = (cdCommand + "zip -r " + path.join("..", definitions.lambdaInfo.functionName) + ".zip *");
awsc.verifyPath(definitions,['implementationFiles'],'o', "definitions file \"" + fileName + "\"").exitOnError();
var functionHandler = definitions.implementationFiles[definitions.lambdaInfo.functionName][0];
if (typeof functionHandler !== 'string') {
console.log("Cannot find \"lambdaInfo.functionName\" as a key in \"implementationFiles\" in \"" + fileName + "\".");
}
//awsc.verifyPath(definitions,['lambdaInfo','arnRole'],'s', "definitions file \"" + fileName + "\"").exitOnError();
awsc.verifyPath(definitions,['lambdaInfo', 'roleName'], 's', "definitions file \"" + fileName + "\"").exitOnError();
awsc.verifyPath(definitions,['lambdaInfo','language'],'s', "definitions file \"" + fileName + "\"").exitOnError();
awsc.verifyPath(baseDefinitions,['lambdaInfo', 'roleDefinitions', definitions.lambdaInfo.roleName, 'arnRole'], 's', "base definition file " + argv.baseDefinitionsFile).exitOnError();
var arnRole = baseDefinitions.lambdaInfo.roleDefinitions[definitions.lambdaInfo.roleName].arnRole;
functionHandler = path.basename(functionHandler, path.extname(functionHandler)) + ".handler";
var lambdaName;
if (awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
lambdaName = baseDefinitions.environment.AWSResourceNamePrefix + definitions.lambdaInfo.functionName;
}
var params = {
'role': {type: 'string', value: arnRole},
'timeout': {type: 'string', value: "30"},
'region': {type: 'string', value: definitions.lambdaInfo.region},
'handler': {type: 'string', value: functionHandler},
'function-name': {type: 'string', value: lambdaName},
'runtime' : {type: 'string', value: definitions.lambdaInfo.language},
'zip-file' : {type: 'fileNameBinary', value: path.join(argv.lambdaDefinitionsDir, definitions.lambdaInfo.functionName) + ".zip"},
'profile' : {type: 'string', value:AWSCLIUserProfile}
};
awsc.addLambdaVPCConfiguration(params, definitions, fileName, baseDefinitions, argv.baseDefinitionsFile);
// check to make sure everything compiles at least
awsc.validatejs(definitions, path.join(argv.lambdaDefinitionsDir, definitions.lambdaInfo.functionName));
// capture values here by creating a function
zipAndUpload(definitions, zipCommandString, params, path.join(argv.lambdaDefinitionsDir, fileName), function (definitions) {
// now check to see if any s3 buckets trigger this lambda
addS3Triggers(definitions, function () {
});
});
});
function addS3Triggers (definitions, callback){
if (!awsc.verifyPath(definitions, ['s3Info', 'buckets'], 'o').isVerifyError) {
Object.keys(definitions.s3Info.buckets).forEach(function (bucketName) {
console.log("Adding events to s3 bucket '" + bucketName + "' for lambda '" + definitions.lambdaInfo.functionName + "'.");
// check to make sure this bucket exists and has a real (instance) name
if (!awsc.verifyPath(baseDefinitions, ['s3Info', 'buckets', bucketName, 'name'], 's').isVerifyError) {
// check to make sure we actually have some triggers
if (!awsc.verifyPath(definitions, ['s3Info', 'buckets', bucketName, 'Events'], 'a').isVerifyError) {
// first give the lambda the permission to be triggered by S3
AWSRequest.createRequest({
serviceName: "lambda",
functionName: "add-permission",
parameters: {
'function-name': {type: 'string', value: definitions.lambdaInfo.arnLambda},
'profile' : {type: 'string', value:AWSCLIUserProfile},
'statement-id' : {type: 'string', value: bucketName + "-" + definitions.lambdaInfo.functionName + "-" + "action"},
'action' : {type: 'string', value: "lambda:InvokeFunction"},
'principal' : {type: 'string', value: "s3.amazonaws.com"},
'source-arn' : {type: 'string', value: "arn:aws:s3:::" + baseDefinitions.s3Info.buckets[bucketName].name}
},
returnSchema:'none',
},
function (request) {
if (request.response.error) {
throw request.response.error;
}
// now we can create an object to convert to json for the event.
// eventually we'll want to collect all of the s3 info from all the lambdas to make this proper.
var notificationConfiguration = {
LambdaFunctionConfigurations: [{
Id: definitions.lambdaInfo.functionName,
LambdaFunctionArn: definitions.lambdaInfo.arnLambda,
Events: definitions.s3Info.buckets[bucketName].Events,
}]
};
AWSRequest.createRequest({
serviceName: "s3api",
functionName: "put-bucket-notification-configuration",
parameters: {
'bucket': {type: 'string', value: baseDefinitions.s3Info.buckets[bucketName].name},
'profile' : {type: 'string', value:AWSCLIUserProfile},
'notification-configuration' : {type: 'JSONObject', value: notificationConfiguration}
},
returnSchema:'none',
},
function (request) {
if (request.response.error) {
throw request.response.error;
}
if (callback) {
callback(definitions);
}
}).startRequest();
}).startRequest();
} else {
console.log("No trigger events defined for bucket name '" + bucketName + "' when adding event for lambda '" + definitions.lambdaInfo.functionName + "'.");
}
} else {
throw new Error("Invalid bucket name '" + bucketName + "' when adding event for lambda '" + definitions.lambdaInfo.functionName + "'.");
}
});
}
}
function createLambda(definitions, reqParams, defaultsFileName, callback) {
// lets upload!
AWSRequest.createRequest({
serviceName: "lambda",
functionName: "create-function",
context: {reqParams:reqParams, defaultsFileName:defaultsFileName, definitions: definitions},
parameters:reqParams,
returnSchema:'json',
returnValidation:[{path:['FunctionArn'], type:'s'},
{path:['FunctionName'], type:'s'}]
},
function (request) {
if (request.response.error) {
if (request.response.errorId === 'ResourceConflictException') {
// delete and recreate the lambda
console.log("Lambda \"" + request.context.reqParams['function-name'].value + "\" already exists. Deleting and re-creating.");
deleteLambda(request.context.definitions, request.context.reqParams, request.context.defaultsFileName, callback);
return;
} else if (request.response.errorId === 'InvalidParameterValueException') {
// retry
if (request.retryCount < 3) {
console.log("retrying \"" + request.parameters['function-name'].value + "\"...");
setTimeout(function(){
request.retry();
}, 3000);
return;
} else {
throw request.response.error;
}
} else {
throw request.response.error;
}
}
console.log("Updating defaults file: \"" + defaultsFileName + "\"");
awsc.updateFile(defaultsFileName, function () {
request.context.definitions.lambdaInfo.arnLambda = request.response.parsedJSON.FunctionArn;
return YAML.stringify(request.context.definitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + defaultsFileName + "\". arnLambda was not updated.");
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file.");
throw writeErr;
}
callback(request.context.definitions);
});
}).startRequest();
}
function zipAndUpload(definitions, zipCommand, reqParams, defaultsFileName, callback) {
exec(zipCommand, function (err, stdout, stderr) {
if (err) {
console.log(stdout);
console.log(stderr);
throw err;
}
// this logs all the files that were zipped
//console.log(stdout);
if (!argv.archiveOnly) {
createLambda(definitions, reqParams, defaultsFileName, callback);
}
});
}
function forEachLambdaDefinition (callback) {
fs.readdir(argv.lambdaDefinitionsDir, function (err, files) {
if (err) {
console.log(err);
process.exit(1);
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var writeOut = true;
if ((typeof argv.lambdaName === 'string') && (argv.lambdaName !== fileNameComponents[0])) {
console.log("Not target lambda. Skipping.");
writeOut = false;
}
if (writeOut) {
callback(fileName);
}
}
}
});
}
function deleteLambda(definitions, createParams, defaultsFileName, callback) {
var params = {
'function-name': {type: 'string', value: createParams['function-name'].value},
'profile' : {type: 'string', value:AWSCLIUserProfile}
};
var deleteRequest = AWSRequest.createRequest({
serviceName: "lambda",
functionName: "delete-function",
context:{createParams: createParams, defaultsFileName: defaultsFileName, definitions: definitions},
parameters: params,
retryCount: 3,
retryErrorIds: ['ServiceException'],
retryDelay: 2000,
returnSchema:'none'
},
function (request) {
if (request.response.error) {
if (request.response.errorId === 'ResourceNotFoundException') {
console.log("Warning: lambda \"" + request.parameters["function-name"].value + "\" not found.");
} else {
throw request.response.error;
}
}
console.log("Deleted lambda \"" + request.parameters["function-name"].value + "\"");
createLambda(definitions, request.context.createParams, request.context.defaultsFileName, callback);
});
deleteRequest.on('AwsRequestRetry', function () {
console.log("Warning: unable to delete lambda \"" + definitions.lambdaInfo.functionName + "\" due to \"ServiceException\". This happens occasionally when deleting a number of lambdas at once. Trying again...");
});
deleteRequest.startRequest();
}
<file_sep>#!/usr/bin/env node
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AwsRequest = require(path.join(__dirname, 'AwsRequest'));
const fs = require('fs');
const YAML = require('yamljs');
const yargs = require('yargs')
.usage('Create the tables required for the project.\nIf a table with the same name already exists a new table \nwill not be create and the existing table information will be used.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your dynamodb (dynamodbInfo)')
.default('s','./base.definitions.yaml')
.alias('n','dynamoTableKey')
.describe('k','a specific dynamo table key to process (the name of the db is environment.AWSResourceNamePrefix + key). If not specified all db found will be created')
.help('h')
.alias('h', 'help');
const argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Creating Dynamodb Tables ##");
getTableNameArray(function(tableNames) {
// go through and see if there are any matches with tables we have here.
// if there are table names that match but no ARN impoet the ARN.
// if the ARNs are the same, do nothing.
// if they are different notify the user to see if they want to update the local info.
awsc.verifyPath(baseDefinitions,['dynamodbInfo', '*', 'attributeDefinitions'],'a', "definitions file \"" + argv.baseDefinitionsFile + "\"").exitOnError();
awsc.verifyPath(baseDefinitions,['dynamodbInfo', '*', 'keySchema','AttributeName'],'s', "definitions file \"" + argv.baseDefinitionsFile + "\"").exitOnError();
awsc.verifyPath(baseDefinitions,['dynamodbInfo', '*', 'provisionedThroughput','ReadCapacityUnits'],'n', "definitions file \"" + argv.baseDefinitionsFile + "\"").exitOnError();
awsc.verifyPath(baseDefinitions,['dynamodbInfo', '*', 'provisionedThroughput','WriteCapacityUnits'],'n', "definitions file \"" + argv.baseDefinitionsFile + "\"").exitOnError();
var localDbKeys = Object.keys(baseDefinitions.dynamodbInfo);
if (argv.dynamoTableKey) {
awsc.verifyPath(baseDefinitions,['dynamodbInfo', argv.dynamoTableKey], 'a', "definitions file \"" + argv.baseDefinitionsFile + "\"").exitOnError();
localDbKeys = [argv.dynamoTableKey];
}
var requests = [];
for (var keyIndex = 0; keyIndex < localDbKeys.length; keyIndex++) {
var tableKey = localDbKeys[keyIndex];
var tableName;
if (awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
tableName = baseDefinitions.environment.AWSResourceNamePrefix + tableKey;
}
// does the name exist in the name server name list
if (tableNames.indexOf(tableName) >= 0) {
console.log("Getting description of existing table \"" + tableName + "\"");
requests.push(getTableDescriptionRequest(tableKey, tableName, function (tblKey, tblName, description) {
console.log("Received existing table \"" + tblName + "\" description.");
baseDefinitions.dynamodbInfo[tblKey].Table = description;
}));
} else {
// send out a request to create a new table.
console.log("Creating new table \"" + tableName + "\"");
requests.push(getTableCreationRequest(tableKey, tableName, function (tblKey, tblName, description) {
console.log("Created table \"" + tblName + "\" description.");
baseDefinitions.dynamodbInfo[tblKey].Table = description;
}));
}
}
AwsRequest.createBatch(requests, function (batch) {
// write out the table.
var failCount = 0;
batch.requestArray.forEach(function (request) {
if (request.response.error) {
console.log(request.response.error);
failCount ++;
}
});
if (failCount) {
console.log("Failed to complete " + failCount + "/" + batch.requestArray.length + " requests.");
} else {
console.log("Successfully completed all requests.");
}
writeout();
}).startRequest();
});
function getTableCreationRequest (tableKey, tableName, callback) {
return AwsRequest.createRequest({
serviceName: "dynamodb",
functionName: "create-table",
parameters:{
'attribute-definitions': {type: 'JSONObject', value:baseDefinitions.dynamodbInfo[tableKey].attributeDefinitions},
'table-name': {type: 'string', value:tableName},
'key-schema': {type: 'JSONObject', value:baseDefinitions.dynamodbInfo[tableKey].keySchema},
'provisioned-throughput': {type: 'JSONObject', value:baseDefinitions.dynamodbInfo[tableKey].provisionedThroughput},
'profile' : {type: 'string', value:AWSCLIUserProfile}
},
context:{tableName: tableName, tableKey: tableKey},
returnSchema:'json',
returnValidation:[{path:['TableDescription'], type:'o'},
{path:['TableDescription', 'TableArn'], type:'s'}]
},
function (request) {
if (request.response.error) {
throw request.response.error;
}
callback(request.context.tableKey, request.context.tableName, request.response.parsedJSON.TableDescription);
});
}
function getTableDescriptionRequest (tableKey, tableName, callback) {
return AwsRequest.createRequest({
serviceName: "dynamodb",
functionName: "describe-table",
parameters:{
'table-name': {type: 'string', value:tableName},
'profile' : {type: 'string', value:AWSCLIUserProfile}
},
context:{tableName:tableName, tableKey: tableKey},
returnSchema:'json',
returnValidation:[{path:['Table'], type:'o'},
{path:['Table', 'TableArn'], type:'s'}]
},
function (request) {
if (request.response.error) {
throw request.response.error;
}
callback(request.context.tableKey, request.context.tableName, request.response.parsedJSON.Table);
});
}
function getTableNameArray (callback){
AwsRequest.createRequest({
serviceName: "dynamodb",
functionName: "list-tables",
parameters:{
'max-items': {type: 'string', value:'20'},
'profile' : {type: 'string', value:AWSCLIUserProfile}
},
returnSchema:'json',
returnValidation:[{path:['TableNames'], type:'a'}]
},
function (request) {
if (request.response.error) {
throw request.response.error;
}
callback(request.response.parsedJSON.TableNames);
}).startRequest();
}
function writeout() {
// now delete role
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". configuration was not updated.");
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file.");
throw writeErr;
}
});
}
<file_sep>#!/usr/bin/env node
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const argv = require('yargs')
.usage('Create a single API definitions file to upload to AWS.\nx-amazon-apigateway-integration fields are updated with latest role and lambda arn.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains top level definitions including swagger template header')
.default('s','./base.definitions.yaml')
.alias('l','lambdaDefinitionsDir')
.describe('l','directory containing lambda definition yaml files')
.default('l','./lambdas')
.alias('o','outputFilename')
.describe('o','coalesced yaml file for upload to AWS')
.default('o','swaggerAPI.yaml')
.alias('c','commonModelDefinitionFile')
.describe('c','yaml file with common definitions of models')
.help('h')
.alias('h', 'help')
.argv;
var fs = require('fs');
// load the swagger base file
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
if (typeof baseDefinitions.apiInfo !== 'object') {
throw new Error("Missing apiInfo in base definitions file");
}
if (typeof baseDefinitions.apiInfo.AWSSwaggerHeader !== 'object') {
throw new Error("Missing AWS API swagger template header in base definitions file");
}
var swaggerBaseFile = baseDefinitions.apiInfo.AWSSwaggerHeader;
// update the title to include the resource.
awsc.verifyPath(baseDefinitions,['apiInfo', 'title'], 's', "in base definitions file", "This is needed to identify the API").exitOnError();
if (awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
baseDefinitions.apiInfo.AWSSwaggerHeader.info.title = baseDefinitions.environment.AWSResourceNamePrefix + baseDefinitions.apiInfo.title;
}
if (fs.existsSync(argv.outputFilename)) {
fs.unlinkSync(argv.outputFilename);
}
// the "paths" component is in the lambdaDefinitions
// at apiInfo.path
console.log("## Coalescing API ##");
fs.readdir(argv.lambdaDefinitionsDir, function (err, files) {
if (err) {
console.log(err);
process.exit(1);
}
swaggerBaseFile.paths = {};
swaggerBaseFile.definitions = {};
swaggerBaseFile.securityDefinitions = {};
// see if there are any common definitions and use them to start.
// individual paths can also create their own defitions, but these will
// overwrite the existing ones.
if (typeof baseDefinitions.apiInfo.sharedDefinitions === 'object') {
swaggerBaseFile.definitions = baseDefinitions.apiInfo.sharedDefinitions;
}
if (typeof baseDefinitions.apiInfo.sharedSecurityDefinitions === 'object') {
swaggerBaseFile.securityDefinitions = baseDefinitions.apiInfo.sharedSecurityDefinitions;
}
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var definitions = YAML.load(path.join(argv.lambdaDefinitionsDir,fileName));
// We need to update all lambda uri in apiInfo.paths.*.*.uri to include the lambda arn
if (awsc.verifyPath(definitions, ['apiInfo', 'paths'], 'o').isVerifyError) {
console.log("No API defintions for '" + definitions.lambdaInfo.functionName + "'.");
continue;
}
updateLambadInvocation(definitions);
updateCredentials(baseDefinitions,definitions);
if (typeof definitions.apiInfo.paths === 'object') {
Object.keys(definitions.apiInfo.paths).forEach(function(key) {
swaggerBaseFile.paths[key] = definitions.apiInfo.paths[key];
});
}
// I'm going to assume that all model defitions are going to be under "definitions"
if (typeof definitions.definitions === 'object') {
Object.keys(definitions.definitions).forEach(function(key) {
swaggerBaseFile.definitions[key] = definitions.definitions[key];
});
}
// I'm going to assume that all security defitions are going to be under "definitions"
if (typeof definitions.securityDefinitions === 'object') {
Object.keys(definitions.securityDefinitions).forEach(function(key) {
swaggerBaseFile.securityDefinitions[key] = definitions.securityDefinitions[key];
});
}
}
}
if (typeof argv.commonModelDefinitionFile === 'string') {
var modelDefinitions = YAML.load(argv.commonModelDefinitionFile);
Object.keys(modelDefinitions.definitions).forEach(function(key) {
swaggerBaseFile.definitions[key] = definitions.definitions[key];
});
}
// now that we have a full file, lets
fs.writeFile(argv.outputFilename, YAML.stringify(swaggerBaseFile, 15), function (err) {
if (err) {
console.log(err);
}
});
});
function updateLambadInvocation(definitions) {
if (awsc.verifyPath(definitions,['lambdaInfo', 'arnLambda'], 's', "").isVerifyError) {
throw new Error("No lambda ARN found, cannot make x-amazon-apigateway-integration with lambda \"" + definitions.lambdaInfo.functionName + "\"");
}
//all apiInfo.paths.*.*.uri
var pathKeys = Object.keys(definitions.apiInfo.paths);
pathKeys.forEach(function (pathKey) {
var methodKeys = Object.keys(definitions.apiInfo.paths[pathKey]);
methodKeys.forEach(function (methodKey) {
var methodDef = definitions.apiInfo.paths[pathKey][methodKey];
if (awsc.verifyPath(methodDef,['x-amazon-apigateway-integration'], 'o',"").isVerifyError) {
methodDef['x-amazon-apigateway-integration'] = {};
}
// if there isn;t an integration type already integrate the lambda
if (awsc.verifyPath(methodDef,['x-amazon-apigateway-integration','type'], 's',"").isVerifyError) {
var uri = 'arn:aws:apigateway:' + definitions.lambdaInfo.region + ':lambda:path//2015-03-31/functions/' + definitions.lambdaInfo.arnLambda + '/invocations';
methodDef['x-amazon-apigateway-integration'].uri = uri;
methodDef['x-amazon-apigateway-integration'].type = 'aws';
methodDef['x-amazon-apigateway-integration'].httpMethod = 'POST';
}
});
});
}
function updateCredentials(baseDefinitions, definitions) {
//all apiInfo.paths.*.*.uri
var pathKeys = Object.keys(definitions.apiInfo.paths);
pathKeys.forEach(function (pathKey) {
var methodKeys = Object.keys(definitions.apiInfo.paths[pathKey]);
methodKeys.forEach(function (methodKey) {
var methodDef = definitions.apiInfo.paths[pathKey][methodKey];
if (awsc.verifyPath(methodDef,['x-amazon-apigateway-integration','credentials'], 's',"").isVerifyError) {
console.log("No credentials to update.");
return; // nothing to do
}
awsc.verifyPath(baseDefinitions, ['apiInfo', 'roleDefinitions', methodDef['x-amazon-apigateway-integration'].credentials, 'arnRole'], 's', "apiInfo Role Definitions");
methodDef['x-amazon-apigateway-integration'].credentials = baseDefinitions.apiInfo.roleDefinitions[methodDef['x-amazon-apigateway-integration'].credentials].arnRole;
});
});
}
<file_sep>#!/usr/bin/env node
const fs = require('fs');
const YAML = require('yamljs');
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AWSRequest = require(path.join(__dirname, 'AWSRequest'));
const yargs = require('yargs')
.usage('Deletes Route Tables and Associations.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.help('h')
.alias('h', 'help');
var argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Deleting Route Tables ##");
if (awsc.verifyPath(baseDefinitions,['routeTableInfo', 'routeTables'],'o').isVerifyError) {
console.log("Nothing to do.");
return;
}
Object.keys(baseDefinitions.routeTableInfo.routeTables).forEach(function (routeTableName) {
/* var networkAclDescription = baseDefinitions.networkAclInfo.networkAcls[networkAclName];
if (!awsc.verifyPath(networkAclDescription,["networkAclId"],'s').isVerifyError) {
console.log("Network ACL '" + networkAclName + "' is already defined. Please use deleteNetworkAcl.js first.");
return;
}*/
// check to see if the name tag exists
var nameTag = baseDefinitions.environment.AWSResourceNamePrefix + routeTableName + "RouteTable";
console.log("Checking for Route Table with tag name '" + nameTag + "'");
awsc.checkEc2ResourceTagName(nameTag, routeTableName, AWSCLIUserProfile, function(tagExists, results, tagName, routeTableName) {
if (tagExists) {
console.log("Route Table '" + tagName + "' exists, deleting.");
// update Network ACL info with existing tag IDs
if (!baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable) {
baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable = {};
}
baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable.RouteTableId = results[0].ResourceId;
// write out result
deleteSubnetAssociations(routeTableName, function (routeTableName) {
deleteRoutes(routeTableName, function (routeTableName) {
deleteRouteTable(routeTableName, function (routeTableName) {
commitUpdates(routeTableName);
});
});
});
} else {
console.log("Route Table '" + tagName + "' does not exist.");
delete baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable;
deleteSubnetAssociations(routeTableName, function (routeTableName) {
commitUpdates(routeTableName);
});
}
});
});
function commitUpdates(routeTableName) {
writeOut("Could not update RouteTableId for Route Table '" + routeTableName + "'.");
}
function deleteRouteTable(routeTableName, callback) {
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "delete-route-table",
parameters:{
"route-table-id": {type: "string", value: baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable.RouteTableId},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'none'
},
function (request) {
if (request.response.error) {
throw request.response.error;
}
delete baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable;
console.log("Deleted Route Table '" + routeTableName + "'.");
callback(routeTableName);
}).startRequest();
}
function deleteSubnetAssociations(routeTableName, callback) {
if (awsc.verifyPath(baseDefinitions, ["routeTableInfo", "routeTables", routeTableName, "Associations"],'o').isVerifyError) {
callback(routeTableName);
return;
}
var associations = baseDefinitions.routeTableInfo.routeTables[routeTableName].Associations;
var associationRequests = [];
Object.keys(associations).forEach(function (subnetName) {
associationRequests.push(
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "disassociate-route-table",
context: {subnetName: subnetName, routeTableName: routeTableName},
parameters:{
"association-id": {type: "string", value: associations[subnetName]},
"profile": {type: "string", value: AWSCLIUserProfile}
},
returnSchema:'none'
},
function () {
})
);
});
if (associationRequests.length === 0) {
callback(routeTableName);
return;
}
AWSRequest.createBatch(associationRequests, function(batchRequest) {
var hasError = false;
batchRequest.requestArray.forEach(function (request) {
if (request.response.error) {
hasError = true;
console.log("Could not remove subnet association '" + request.context.subnetName + "' for route table '" + request.context.routeTableName + "'.");
console.log(request.response.error);
}
delete baseDefinitions.routeTableInfo.routeTables[routeTableName].Associations[request.context.subnetName];
console.log("Deleted subnet association '" + request.context.subnetName + "' for route table '" + request.context.routeTableName + "'.");
});
writeOut("Could not save deleted subnet associations for route table '" + routeTableName + "'.", function () {
if (hasError) {
process.exit(1);
}
callback(routeTableName);
});
}).startRequest();
}
function deleteRoutes(routeTableName, callback) {
if (awsc.verifyPath(baseDefinitions, ["routeTableInfo", "routeTables", routeTableName, "routes"],'a').isVerifyError) {
callback(routeTableName);
return;
}
var routes = baseDefinitions.routeTableInfo.routeTables[routeTableName].routes;
var routeDeleteRequests = [];
routes.forEach(function (route) {
var params = {
"route-table-id": {type: "string", value: baseDefinitions.routeTableInfo.routeTables[routeTableName].RouteTable.RouteTableId},
"profile": {type: "string", value: AWSCLIUserProfile}
};
params["destination-cidr-block"] = {type: "string", value: route["destination-cidr-block"]};
routeDeleteRequests.push(
AWSRequest.createRequest({
serviceName: "ec2",
functionName: "delete-route",
context: {route: route, routeTableName: routeTableName},
parameters: params,
returnSchema:'none'
},
function () {
})
);
});
if (routeDeleteRequests.length > 0) {
AWSRequest.createBatch(routeDeleteRequests, function (batchRequest) {
var hasError;
batchRequest.requestArray.forEach(function (request) {
if (request.response.error && (request.response.errorId !== "InvalidRoute.NotFound") && (request.response.errorId !== "InvalidRouteTableID.NotFound")) {
console.log("Could not delete route '" + JSON.stringify(request.context.route) + "' for route table '" + request.context.routeTableName + "'.");
hasError = true;
} else {
console.log("Deleted route '" + JSON.stringify(request.context.route) + "' for route table '" + request.context.routeTableName + "'.");
}
});
if (hasError) {
process.exit(1);
}
callback(routeTableName);
}).startRequest();
} else {
callback();
}
}
function writeOut(errorText, callback) {
// now delete role
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". " + errorText);
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file. " + errorText);
throw writeErr;
}
if (callback) {
callback();
}
});
}
<file_sep>'use strict';
console.log('Loading function');
const fs = require('fs');
const AWSConstants = JSON.parse(fs.readFileSync('./AWSConstants.json', 'utf8'));
const APIParamVerify = require('./APIParamVerify');
const AWS = require("aws-sdk");
const Photos = require('./Photos');
const UUID = require('node-uuid');
const s3 = new AWS.S3();
/**
* handler signup
* @param {[type]} event [description]
* @param {[type]} context [description]
* @param {Function} callback [description]
*/
function handler(event, context, callback) {
process.on("uncaughtException", ( err ) => {
console.log(err);
callback(JSON.stringify({
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Internal Error."
}));
});
// make sure we have needed params
var verifyResult = APIParamVerify.verify("/user/photo/uploadurl", "get", event);
if (verifyResult) {
verifyResult.requestId = context.awsRequestId;
console.log(verifyResult);
callback(JSON.stringify(verifyResult));
return;
}
Photos.checkForPhotoBaseID(event.awsParams.identity_id, context.awsRequestId, function (err, userData) {
if (err) {
callback(JSON.stringify(err));
return;
}
var photoId = UUID.v4();
var key = userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_BASE_ID] + "/" + photoId;
const params = {
Bucket: AWSConstants.S3.PHOTOBUCKET.name,
Key: key,
Expires: 900,
ContentType: "image/jpeg",
ACL: 'public-read',
};
s3.getSignedUrl('putObject', params, function (err, data) {
if (err) {
console.log(err);
var errorObject = {
requestId: context.awsRequestId,
errorType: "InternalServerError",
httpStatus: 500,
message: "Get signed url failed."
};
callback(JSON.stringify(errorObject));
return;
}
// successful result should terminate with callback(null, [resopnseObject]);
callback(null, {upload_url: data, photo_id: photoId, photo_base_id: userData.Item[AWSConstants.DYNAMO_DB.USERS.PHOTO_BASE_ID]});
return;
});
});
}
exports.handler = handler;
<file_sep>#!/usr/bin/env node
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const AwsRequest = require(path.join(__dirname, 'AwsRequest'));
const fs = require('fs');
const YAML = require('yamljs');
var yargs = require('yargs')
.usage('Delete project dynamodb.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your dynamodb (dynamodbInfo)')
.default('s','./base.definitions.yaml')
.alias('k','dynamoTableKey')
.describe('n','a specific dynamo table key to process. If not specified all tables found will be deleted')
.help('h')
.alias('h', 'help');
var argv = yargs.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
console.log("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
yargs.showHelp("log");
process.exit(1);
}
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
} else {
console.log("using \"default\" AWSCLIUserProfile");
}
console.log("## Deleting Dynamedb Tables ##");
var localDbKeys = Object.keys(baseDefinitions.dynamodbInfo);
if (argv.dynamoTableKey) {
awsc.verifyPath(baseDefinitions,['dynamodbInfo', argv.dynamoTableKey], 'a', "definitions file \"" + argv.baseDefinitionsFile + "\"").exitOnError();
localDbKeys = [argv.dynamoTableKey];
}
var requests = [];
for (var keyIndex = 0; keyIndex < localDbKeys.length; keyIndex++) {
var tableKey = localDbKeys[keyIndex];
var tableName;
if (awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
tableName = baseDefinitions.environment.AWSResourceNamePrefix + tableKey;
}
// send out a request to delete a new table.
console.log("Deleting table \"" + tableName + "\"");
requests.push(getTableDeletionRequest(tableKey, tableName, function (tblKey, tblName) {
console.log("Deleted table \"" + tblName + "\" description.");
delete baseDefinitions.dynamodbInfo[tblKey].Table;
}));
}
AwsRequest.createBatch(requests, function (batch) {
// write out the table.
var failCount = 0;
batch.requestArray.forEach(function (request) {
if (request.response.error && request.response.errorId !== "ResourceNotFoundException") {
console.log(request.response.error);
failCount ++;
}
});
if (failCount) {
console.log("Failed to complete " + failCount + "/" + batch.requestArray.length + " requests.");
} else {
console.log("Successfully completed all requests.");
}
writeout();
}).startRequest();
function getTableDeletionRequest (tableKey, tableName, callback) {
return AwsRequest.createRequest({
serviceName: "dynamodb",
functionName: "delete-table",
parameters:{
'table-name': {type: 'string', value:tableName},
'profile' : {type: 'string', value:AWSCLIUserProfile}
},
context:{tableName: tableName, tableKey: tableKey},
returnSchema:'json',
returnValidation:[{path:['TableDescription'], type:'o'},
{path:['TableDescription', 'TableArn'], type:'s'}]
},
function (request) {
if (request.response.error) {
if (request.response.errorId === "ResourceNotFoundException") {
callback(request.context.tableKey, request.context.tableName, null);
return;
}
throw request.response.error;
}
callback(request.context.tableKey, request.context.tableName, request.response.parsedJSON.Table);
});
}
function writeout() {
// now delete role
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". configuration was not updated.");
throw backupErr;
}
if (writeErr) {
console.log("Unable to write updated definitions file.");
throw writeErr;
}
});
}
<file_sep>#!/usr/bin/env node
const YAML = require('yamljs');
const argv = require('yargs')
.usage('Create a json description compatible with APIParamVerify.js to validate lambda input arguments from API.\nUsage: $0 [options]')
.alias('l','lambdaDefinitionsDir')
.describe('l','directory containing lambda definition yaml files')
.default('l','./lambdas')
.alias('o','outputFilename')
.describe('o','name of file that will be added to each lambda directory')
.default('o','eventParams.json')
.alias('n','lambdaName')
.describe('n','update handler event params for only this lambda directory')
.help('h')
.alias('h', 'help')
.argv;
const fs = require('fs');
const path = require('path');
// required --lambdaDefinitionsDir directory
// required --outputFilename
// optional --lambdaName
// the "paths" component is in the lambdaDefinitions
// at apiInfo.path
console.log("## Updating Handler Event Parameters ##");
fs.readdir(argv.lambdaDefinitionsDir, function (err, files) {
if (err) {
console.log(err);
process.exit(1);
}
var writtenLambdaCount = 0;
for (var index = 0; index < files.length; index++) {
var fileName = files[index];
var fileNameComponents = fileName.split('.');
if ((fileNameComponents.length === 3) && (fileNameComponents[1] === "definitions") && (fileNameComponents[2] === "yaml")) {
console.log("Reading: " + fileName);
var definitions = YAML.load(path.join(argv.lambdaDefinitionsDir,fileName));
if (typeof definitions.lambdaInfo.eventParamPaths === 'object') {
if (typeof definitions.implementationFiles === 'object') {
var allkeys = Object.keys(definitions.implementationFiles);
if (Array.isArray(allkeys) && (allkeys.length > 0)) {
var writeOut = true;
if ((typeof argv.lambdaName === 'string') && (argv.lambdaName !== allkeys[0])) {
console.log("Not target lambda. Skipping.");
writeOut = false;
}
if (writeOut) {
fs.writeFile(path.join(argv.lambdaDefinitionsDir, allkeys[0] ,argv.outputFilename), JSON.stringify(definitions.lambdaInfo.eventParamPaths, null, '\t'));
writtenLambdaCount ++;
}
} else {
console.log("Expected implementationFile bag with at least 1 key. Skipping.");
}
} else {
console.log("Expected implementationFile bag. Skipping.");
}
} else {
console.log("Expected lambdaInfo.paths of type 'object'. Skipping.");
}
}
}
if (writtenLambdaCount === 0 && files.length > 0) {
console.log("Nothing written. Failed");
process.exit(1);
}
});
<file_sep>#!/bin/bash
cd lambdas
npm install
cd ..
<file_sep>#!/usr/bin/env node
const path = require('path');
const awsc = require(path.join(__dirname, 'awscommonutils'));
const fs = require('fs');
const YAML = require('yamljs');
const AwsRequest = require(path.join(__dirname, 'AwsRequest'));
const argv = require('yargs')
.usage('Create project roles and attach policies.\nUsage: $0 [options]')
.alias('s','baseDefinitionsFile')
.describe('s','yaml file that contains information about your API')
.default('s','./base.definitions.yaml')
.alias('t', 'roleType')
.describe('t', 'which roles to create [api | lambda | cognito]')
.choices('t', ['api', 'lambda', 'cognito'])
.demand(['t'])
.help('h')
.alias('h', 'help')
.argv;
if (!fs.existsSync(argv.baseDefinitionsFile)) {
throw new Error("Base definitions file \"" + argv.baseDefinitionsFile + "\" not found.");
}
var roleBase;
switch (argv.roleType) {
case 'api':
roleBase = 'apiInfo';
break;
case 'lambda':
roleBase = 'lambdaInfo';
break;
case 'cognito':
roleBase = 'cognitoIdentityPoolInfo';
break;
default:
}
console.log("## Creating " + roleBase + " roles ##");
var baseDefinitions = YAML.load(argv.baseDefinitionsFile);
awsc.verifyPath(baseDefinitions, [roleBase, 'roleDefinitions'], 'o', "definitions file \"" + argv.baseDefinitionsFile+"\"").exitOnError();
var AWSCLIUserProfile = "default";
if (!awsc.verifyPath(baseDefinitions,['environment', 'AWSCLIUserProfile'],'s').isVerifyError) {
AWSCLIUserProfile = baseDefinitions.environment.AWSCLIUserProfile;
}
Object.keys(baseDefinitions[roleBase].roleDefinitions).forEach(function (roleKey) {
var roleDef = baseDefinitions[roleBase].roleDefinitions[roleKey];
// need a name, policyDocument and perhaps some policies
awsc.verifyPath(roleDef, ['policyDocument'], 'o', "role definition " + roleBase).exitOnError();
awsc.verifyPath(roleDef, ['policies'], 'a', "role definition " + roleBase).exitOnError();
var policyArray = [];
roleDef.policies.forEach(function (policy) {
awsc.verifyPath(policy, ['arnPolicy'], 's', "policy definition " + roleBase).exitOnError();
policyArray.push(policy.arnPolicy);
});
createRoleAndUploadPolicies(roleDef.policyDocument, policyArray, roleKey, function (rlKey, rlARN, policyArr) {
if (rlKey && rlARN) {
baseDefinitions[roleBase].roleDefinitions[rlKey].arnRole = rlARN;
// start uploading policies
var rlName;
if (awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
rlName = baseDefinitions.environment.AWSResourceNamePrefix + rlKey;
}
policyArr.forEach(function (policyArn) {
AwsRequest.createRequest({
serviceName: 'iam',
functionName: 'attach-role-policy',
parameters: {
'role-name': {type: 'string', value: rlName},
'policy-arn': {type: 'string', value: policyArn},
profile: {type: 'string', value: AWSCLIUserProfile}
},
returnSchema: 'none',
}, function (request) {
if (request.response.error) {
console.log("Failed policy attach: " + policyArn + " on " + rlName + ".");
throw request.response.error;
}
console.log("Policy attach completed: " + policyArn + " on " + rlName + ".");
}).startRequest();
});
}
awsc.updateFile(argv.baseDefinitionsFile, function () {
return YAML.stringify(baseDefinitions, 15);
}, function (backupErr, writeErr) {
if (backupErr) {
console.log("Could not create backup of \"" + argv.baseDefinitionsFile + "\". API Id was not updated.");
throw new Error(backupErr);
}
if (writeErr) {
console.log("Unable to write updated definitions file.");
throw new Error(writeErr);
}
});
});
});
function createRoleAndUploadPolicies(policyDocument, policyArray, roleKey, callback) {
var roleName;
if (awsc.isValidAWSResourceNamePrefix(baseDefinitions, argv.baseDefinitionsFile)) {
roleName = baseDefinitions.environment.AWSResourceNamePrefix + roleKey;
}
console.log("Creating role \"" + roleName + "\"");
AwsRequest.createRequest({
serviceName: 'iam',
functionName: 'create-role',
parameters: {
'role-name': {type: 'string', value: roleName},
'assume-role-policy-document': {type: 'JSONObject', value: policyDocument},
profile: {type: 'string', value: AWSCLIUserProfile},
},
returnSchema: 'json',
returnValidation:[{path: ['Role','Arn'], type: 's'}],
}, function (request) {
if (request.response.error) {
if (request.response.errorId === "EntityAlreadyExists") {
console.log("Role '" + roleName + "' exists. Updating configuration.");
AwsRequest.createRequest({
serviceName: 'iam',
functionName: 'get-role',
parameters: {
'role-name': {type: 'string', value: roleName},
profile: {type: 'string', value: AWSCLIUserProfile},
},
returnSchema: 'json',
returnValidation:[{path:['Role','Arn'], type:'s'}],
}, function (request) {
if (request.response.error) {
throw request.response.error;
}
callback(roleKey, request.response.parsedJSON.Role.Arn, policyArray);
}).startRequest();
} else {
throw request.response.error;
}
} else {
callback(roleKey, request.response.parsedJSON.Role.Arn, policyArray);
}
}).startRequest();
}
| 69d9716fb47b17ab1050c29a79d452263d2054b8 | [
"JavaScript",
"Ruby",
"Markdown",
"Shell"
] | 47 | Shell | horsenoggingit/lambdaAuth | 8072122f0dd971535dde418f14aa81a66296f1b5 | 6f37e40ccad89ff99349556463947f5693eb9ca5 |
refs/heads/master | <file_sep>package com.yy.httpproxy.subscribe;
import android.content.Context;
/**
* Created by xuduo on 10/20/15.
*/
public interface PushIdGenerator {
String generatePushId(Context context);
}
| 8e4dcf731da1943f826b10ea70d7e31520452fa0 | [
"Java"
] | 1 | Java | zarraxx/socket.io-push-android | ad42d13d115c1e9e1779e994e572676f5e1294ff | 5009379048b0f9a92b30161fe99912ee933f06e5 |
refs/heads/master | <file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.dao;
import com.supinfo.supinbank.entity.Account;
import com.supinfo.supinbank.entity.Customer;
/**
*
* @author Gauthier
*/
public interface AccountDao {
Account addAccount(Account account);
Account findAccountById(Long accountId);
void removeAccount(Account account);
Account updateAccount(Account account);
Account findAccountByBban(String bban);
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.web.servlet;
import com.supinfo.supinbank.entity.Customer;
import com.supinfo.supinbank.entity.Person;
import com.supinfo.supinbank.services.CustomerService;
import com.supinfo.supinbank.services.MailService;
import com.supinfo.supinbank.services.PersonService;
import com.supinfo.supinbank.utils.Bban;
import com.supinfo.supinbank.utils.Cypher;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Gauthier
*/
@WebServlet(name = "AddCustomer", urlPatterns = {"/Auth/BankAdvisor/addCustomer"})
public class AddCustomer extends HttpServlet {
@EJB
private PersonService personService;
@EJB
private CustomerService customerService;
@EJB
private MailService mailService;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/jsp/bankadvisor/addCustomer.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstname = (request.getParameter("firstname") != null) ? request.getParameter("firstname") : "";
String lastname = (request.getParameter("lastname") != null) ? request.getParameter("lastname") : "";
String email = (request.getParameter("email") != null) ? request.getParameter("email") : "";
String address = (request.getParameter("address") != null) ? request.getParameter("address") : "";
String zipcode = (request.getParameter("zipcode") != null) ? request.getParameter("zipcode") : "";
String city = (request.getParameter("city") != null) ? request.getParameter("city") : "";
String phone = (request.getParameter("phone") != null) ? request.getParameter("phone") : "";
if (firstname.isEmpty() || lastname.isEmpty() || email.isEmpty() || address.isEmpty() || zipcode.isEmpty()
|| city.isEmpty() || phone.isEmpty()) {
request.setAttribute("errors", true);
request.getRequestDispatcher("/jsp/bankadvisor/addCustomer.jsp").forward(request, response);
return;
}
Customer customer = new Customer();
customer.setFirstName(request.getParameter("firstname"));
customer.setLastName(request.getParameter("lastname"));
customer.setEmail(request.getParameter("email"));
customer.setAddress(request.getParameter("address"));
customer.setZipcode(Long.valueOf(request.getParameter("zipcode")));
customer.setCity(request.getParameter("city"));
customer.setPhone(request.getParameter("phone"));
String password = Cypher.generateKey(10);
customer.setPassword(<PASSWORD>.hashPassword(password));
Customer c;
try {
//Trying to add the customer...
c = (Customer)personService.addPerson(customer);
mailService.sendPasswordToCustomer(customer, password);
//... and then adding the customer to the request in order to get it back in the addAccount servlet
request.setAttribute("customerId", c.getId());
response.sendRedirect(getServletContext().getContextPath() + "/Auth/BankAdvisor/addAccount?cid=" + c.getId());
} catch(Exception e) {
request.setAttribute("email", "The e-mail you entered already exists. Please use an other one.");
request.getRequestDispatcher("/jsp/bankadvisor/addCustomer.jsp").forward(request, response);
}
}
}<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.dao;
import com.supinfo.supinbank.entity.InterestsPlan;
import java.util.List;
/**
*
* @author Gauthier
*/
public interface InterestsPlanDao {
InterestsPlan addInterestsPlan(InterestsPlan plan);
List<InterestsPlan> getInterestsPlan();
InterestsPlan findInterestsPlanById(Long id);
}
<file_sep>/*global jQuery */
(function ($) {
var listOperations = {
init: function (options, elem) {
this.elem = $(elem);
this.options = $.extend({}, this.options, options);
this.elem.on('change', this.options.selectSelector, $.proxy(this.changeAccount, this));
},
options: {
selectSelector: '#accounts',
contentSelector: '#operations tbody'
},
changeAccount: function(event) {
var selectElement, accountId, contentSelector;
selectElement = $(event.target);
accountId = selectElement.find(':selected').val();
contentSelector = $(this.options.contentSelector);
$.ajax({
url: './listOperations',
type: 'POST',
data: "aid=" + accountId,
beforeSend: function() {
contentSelector.html('<tr><td colspan="4"><div class="ajax-loader"><img src="../../img/loader.gif" />Loading...</div></td></tr>');
},
success: function(xhr) {
contentSelector.html(xhr);
}
});
}
};
$.lsPlugin('listOperations', listOperations);
})(jQuery);
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
/**
*
* @author Gauthier
*/
@Entity
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
public class BankAdvisor extends Person implements Serializable {
private static final long serialVersionUID = 1L;
}
<file_sep>/*global jQuery */
(function ($) {
var paginate = {
init: function (options, elem) {
this.elem = $(elem);
this.options = $.extend({}, this.options, options);
this.elem.on('click', this.options.delegateTargetSelector, $.proxy(this.processPagination, this));
},
options: {
delegateTargetSelector: '.pagination a',
parentSelector: 'li',
contentSelector: '#paginate tbody'
},
processPagination: function(event) {
var contentSelector, element, url, activeElement, options;
contentSelector = $(this.options.contentSelector);
element = $(event.target);
options = this.options;
if(element.attr('disabled')) {
return;
}
url = element.closest(options.parentSelector).data("url");
$.ajax({
url: url,
type: 'POST',
beforeSend: function() {
contentSelector.html('<tr><td colspan="4"><div class="ajax-loader"><img src="../../img/loader.gif" />Loading...</div></td></tr>');
},
success: function(xhr) {
contentSelector.html(xhr);
//Active element...
activeElement = $('.active');
activeElement.find('a').removeAttr('disabled');
activeElement.removeClass('active');
//Clicked element...
element.attr('disabled', 'disabled');
element.closest(options.parentSelector).addClass('active');
}
});
return;
}
};
$.lsPlugin('paginate', paginate);
})(jQuery);
<file_sep>package com.supinfo.supinbank.dao;
import com.supinfo.supinbank.entity.Customer;
import java.util.List;
/**
*
* @author Gauthier
*/
public interface CustomerDao {
List<Customer> getCustomers(int pageNumber);
Customer updateCustomer(Customer customer);
int getTotalNumberOfCustomers();
}
<file_sep>package com.supinfo.supinbank.dao.jpa;
import com.supinfo.supinbank.dao.CustomerDao;
import com.supinfo.supinbank.entity.Customer;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author Gauthier
*/
@Stateless
public class JpaCustomerDao implements CustomerDao {
@PersistenceContext
private EntityManager em;
final static public int numberOfElements = 1;
@Override
public List<Customer> getCustomers(int pageNumber) {
Query query = em.createQuery("SELECT c FROM Customer c");
if (pageNumber > 0) {
query.setFirstResult(numberOfElements * (pageNumber - 1));
}
query.setMaxResults(numberOfElements);
return query.getResultList();
}
@Override
public int getTotalNumberOfCustomers()
{
Query query = em.createQuery("SELECT c.id FROM Customer c");
return query.getResultList().size();
}
@Override
public Customer updateCustomer(Customer customer) {
return em.merge(customer);
}
}<file_sep>package com.supinfo.supinbank.web.servlet;
import com.supinfo.supinbank.entity.Account;
import com.supinfo.supinbank.entity.Customer;
import com.supinfo.supinbank.entity.Person;
import com.supinfo.supinbank.services.AccountService;
import com.supinfo.supinbank.services.PersonService;
import com.supinfo.supinbank.services.TransfertService;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Gauthier
*/
@WebServlet(name = "performTransfert", urlPatterns = {"/Auth/Customer/performTransfert"})
public class performTransfert extends HttpServlet {
@EJB
private AccountService accountService;
@EJB
private PersonService personService;
@EJB
private TransfertService transfertService;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Person currentUser = (Person) request.getSession().getAttribute("user");
Customer customer = (Customer)personService.findPersonById(currentUser.getId());
request.setAttribute("customer", customer);
request.getRequestDispatcher("/jsp/customer/performTransfert.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Long senderAccountId = Long.parseLong(request.getParameter("primary_account"));
String accountType = request.getParameter("accountType");
Float amount = Float.valueOf(request.getParameter("amount"));
String description = request.getParameter("description");
//Checking if this is an internal transfert
if (accountType.equals("internal")) {
Long receiverAccountId = Long.valueOf(request.getParameter("secondary_account"));
Account senderAccount = accountService.findAccountById(senderAccountId);
Account receiverAccount = accountService.findAccountById(receiverAccountId);
//If accounts get are not null
if (senderAccount != null && receiverAccount != null) {
if (amount > senderAccount.getBalance()) {
request.setAttribute("error", true);
request.setAttribute("errorMessage", "You don't have enough money on this account.");
} else if (senderAccountId.equals(receiverAccountId)) {
request.setAttribute("error", true);
request.setAttribute("errorMessage", "You can't transfert to the same account!");
} else {
transfertService.performTransfert(senderAccount, receiverAccount, amount, description);
request.setAttribute("successMessage", "Your transfert has succeeded!");
}
doGet(request, response);
}
} else if (accountType.equals("external")) {
Account senderAccount = accountService.findAccountById(senderAccountId);
String bbanEstablishmentCode = request.getParameter("IBAN_1");
String bbanBranchCode = request.getParameter("IBAN_2");
String bbanAccountNumber = request.getParameter("IBAN_3");
String bbanKey = request.getParameter("IBAN_4");
String bban = bbanEstablishmentCode + bbanBranchCode + bbanAccountNumber + bbanKey;
System.out.println(bban);
Account receiverAccount = accountService.findAccountByBban(bban);
System.out.println(receiverAccount);
if (null != receiverAccount) {
transfertService.performTransfert(senderAccount, receiverAccount, amount, description);
request.setAttribute("successMessage", "Your transfert has succeeded!");
System.out.println("success");
} else {
request.setAttribute("error", true);
request.setAttribute("errorMessage", "The BBAN provided does not correspond to any customer in the bank.");
System.out.println("error");
}
doGet(request, response);
}
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.dao;
import com.supinfo.supinbank.entity.Person;
/**
*
* @author Gauthier
*/
public interface PersonDao {
Person addPerson(Person person);
Person findPersonById(Long id);
Person checkPassword(String username, String password);
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
/**
*
* @author Gauthier
*/
@Entity
public class AccountOperation implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String wording;
private Float balance;
@Temporal(TemporalType.DATE)
private Date dueDate;
@NotNull
@ManyToOne
private Account account;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* @return the wording
*/
public String getWording() {
return wording;
}
/**
* @param wording the wording to set
*/
public void setWording(String wording) {
this.wording = wording;
}
/**
* @return the balance
*/
public Float getBalance() {
return balance;
}
/**
* @param balance the balance to set
*/
public void setBalance(Float balance) {
this.balance = balance;
}
/**
* @return the dueDate
*/
public Date getDueDate() {
return dueDate;
}
/**
* @param dueDate the dueDate to set
*/
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Account getAccount()
{
return account;
}
public void setAccount(Account account)
{
this.account = account;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.utils;
/**
*
* @author Gauthier
*/
public class Bban {
public static String ESTABLISHMENT_CODE = "78212";
public static String BRANCH_CODE = "00000";
/**
* This code was made with resources found on the internet.
* While discussing with classmates, it seems some found the same ones !^^
*
* @param establishmentCode
* @param branchCode
* @param account
* @return
*/
public static int getKey(String establishmentCode, String branchCode, String account) {
String normalizedAccount = normalizedBbanAccount(account);
int res = (int)(97 - (((Integer.parseInt(establishmentCode, 10)% 97 * 100000 + Integer.parseInt(branchCode)) % 97 * Long.valueOf("100000000000") + Long.valueOf(normalizedAccount.toString(), 10)) % 97) * 100 % 97);
return res;
}
public static String normalizedBbanAccount(String bbanAccount)
{
StringBuilder sb = new StringBuilder();
for (char c: bbanAccount.toUpperCase().toCharArray()){
sb.append(Character.isDigit(c) ? c : replaceChar(c));
}
return sb.toString();
}
/**
* Based on http://www.credit-card.be/BankAccount/ValidationRules.htm
* @param l letter
* @return char
*/
private static char replaceChar(char l) {
if (l >= 'A' && l <= 'I') {
return (char)(l - 'A' + '1');
} else if (l >= 'J' && l <= 'R') {
return (char)(l - 'J' + '1');
} else if (l >= 'S' && l <= 'Z') {
return (char)(l - 'S' + '2');
} else {
throw new IllegalArgumentException("Char must be uppercase");
}
}
public static String calculateZerosForBbanAccount(Long accountId)
{
String normalizedAccountWithZeros = "";
String bbanAccountId = String.valueOf(accountId);
if (bbanAccountId.length() < 11) {
for (int i = 0; i < (11 - String.valueOf(Integer.parseInt(bbanAccountId)).length()); i++) {
normalizedAccountWithZeros += "0";
}
}
return normalizedBbanAccount(normalizedAccountWithZeros + bbanAccountId);
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.services;
import com.supinfo.supinbank.dao.InterestsPlanDao;
import com.supinfo.supinbank.entity.InterestsPlan;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
/**
*
* @author Gauthier
*/
@Stateless
public class InterestsPlanService {
@EJB
private InterestsPlanDao interestsPlanDao;
/**
* @param plan
* @return com.supinfo.supinbank.entity.InterestsPlan
*/
public InterestsPlan addInterestsPlan(InterestsPlan plan)
{
return interestsPlanDao.addInterestsPlan(plan);
}
/**
* @return List<com.supinfo.supinbank.entity.InterestsPlan>
*/
public List<InterestsPlan> getInterestsPlan()
{
return interestsPlanDao.getInterestsPlan();
}
/**
* @param id
* @return com.supinfo.supinbank.entity.InterestsPlan
*/
public InterestsPlan findInterestsPlanById(Long id)
{
return interestsPlanDao.findInterestsPlanById(id);
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.dao;
import com.supinfo.supinbank.entity.AccountOperation;
/**
*
* @author Gauthier
*/
public interface AccountOperationDao {
AccountOperation addAccountOperation(AccountOperation operation);
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.supinfo.supinbank.dao.jpa;
import com.supinfo.supinbank.dao.AccountOperationDao;
import com.supinfo.supinbank.entity.AccountOperation;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author Gauthier
*/
@Stateless
public class JpaAccountOperationDao implements AccountOperationDao {
@PersistenceContext
private EntityManager em;
@Override
public AccountOperation addAccountOperation(AccountOperation operation) {
em.persist(operation);
return operation;
}
}
<file_sep>package com.supinfo.supinbank.entity;
import java.io.Serializable;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
/**
*
* @author Gauthier
*/
@Entity
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;
@NotNull
@Size(min=5, max=50)
protected String firstName;
@NotNull
@Size(min=5, max=50)
protected String lastName;
@NotNull
@Column(unique=true)
@Email
protected String email;
@NotNull
@Size(min=7, max=20)
protected String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
//TODO - Encrypt password
this.password = password;
}
}
<file_sep>/*global jQuery */
// Ensure having Object.create (introduced in ES5) for older browsers
(function () {
if (typeof Object.create === 'function') {
return;
}
function F() {
}
Object.create = function (o) {
F.prototype = o;
return new F();
};
})();
(function ($) {
$.lsPlugin = function (name, object) {
$.fn[name] = function (options) {
if (!this.length) {
// return early as there is nothing to do
return this;
}
return this.each(function () {
// if the instance does not exists, create it and store it
var instance = $.data(this, name, Object.create(object));
// initialize the plugin
instance.init(options, this);
});
};
};
})(jQuery);
<file_sep>/*global jQuery */
(function ($) {
var performTransfert = {
init: function (options, elem) {
this.elem = $(elem);
this.options = $.extend({}, this.options, options);
this.elem.on('click', this.options.internalAccountSelector, $.proxy(this.checkInternalAccount, this));
this.elem.on('click', this.options.externalAccountSelector, $.proxy(this.checkExternalAccount, this));
$.proxy(this.checkAccounts(), this);
},
options: {
radioButtonSelector: null,
internalAccountSelector: null,
primaryAccountSelector: null,
secondaryAccountSelector: null,
externalAccountSelector: null,
ibanSelector: null
},
checkInternalAccount: function(event) {
$(this.options.secondaryAccountSelector).attr('disabled', false);
$(this.options.ibanSelector).attr('disabled', true);
},
checkExternalAccount: function(event) {
$(this.options.secondaryAccountSelector).attr('disabled', true);
$(this.options.ibanSelector).attr('disabled', false);
},
checkAccounts: function(event) {
var options, primaryAccount, primaryAccountValue, secondaryAccount, secondaryAccountValue;
options = this.options;
primaryAccount = $(options.primaryAccountSelector);
primaryAccountValue = $(options.primaryAccountSelector).find('option:selected').val();
secondaryAccount = $(options.secondaryAccountSelector);
secondaryAccountValue = $(options.secondaryAccountSelector).find('option:selected').val();
}
};
$.lsPlugin('performTransfert', performTransfert);
})(jQuery);
| 3e90c2bfba6a1a200edbfe1874ff6e1e627a04e3 | [
"JavaScript",
"Java"
] | 18 | Java | Ninir/SupinBank | 588822d17fc1cf19985f6f32815def58025ad6fa | 8a5537db7b5946a32c0f193b5aff6426d8cefa88 |
refs/heads/main | <repo_name>exewin/unity-skill-tree<file_sep>/SkillTreeProject/Scripts/SkillButtonIcon.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace SkillTreeProject
{
public class SkillButtonIcon : MonoBehaviour
{
[SerializeField] private SkillButton skillButton;
void OnValidate()
{
if(!skillButton) return;
GetComponent<Image>().sprite = skillButton.skills[0].icon;
}
}
}<file_sep>/SkillTreeProject/Scripts/PlayersEventSetSkill.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SkillTreeProject;
public class PlayersEventSetSkill : MonoBehaviour
{
private void OnEnable()
{
SkillButton.addSkillEvent+=SetSkill;
}
private void OnDisable()
{
SkillButton.addSkillEvent-=SetSkill;
}
private void SetSkill(Skill skill)
{
PlayerManager.GetInstance().selectedPlayer.skills.Add(skill);
}
}
<file_sep>/SkillTreeProject/Scripts/SkillTree.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SkillTreeProject;
[CreateAssetMenu(fileName = "Skill Tree", menuName = "new Skill Tree")]
public class SkillTree : ScriptableObject
{
}
<file_sep>/SkillTreeProject/Scripts/Skill.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SkillTreeProject;
[CreateAssetMenu(fileName = "Skill", menuName = "new Skill")]
public class Skill : ScriptableObject
{
public SkillTree skillTreeMembership;
public Sprite icon;
public List<SkillFunctionality> functionalities = new List<SkillFunctionality>();
}
[Serializable]
public struct SkillFunctionality
{
public Functionality functionality;
public float percentageValue;
}
<file_sep>/SkillTreeProject/Scripts/SkillButtonGrayscale.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SkillButtonGrayscale : MonoBehaviour
{
[SerializeField] private Material material;
void Awake()
{
Image image = GetComponent<Image>();
material = Instantiate(image.material);
image.material = material;
}
public void MakeButtonGrayscale()
{
material.SetFloat("Grayscale", 1);
}
public void MakeButtonColor()
{
material.SetFloat("Grayscale", 0);
}
}
<file_sep>/SkillTreeProject/Scripts/SkillButtonCustomButton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using SkillTreeProject;
public class SkillButtonCustomButton : Button
{
}
<file_sep>/SkillTreeProject/Scripts/SkillTreesEnabler.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SkillTreeProject
{
public class SkillTreesEnabler : MonoBehaviour
{
private void EnableTrees()
{
foreach(SkillTreeController tree in SkillTreeControllerManager.GetInstance().skillTreeControllers)
{
if(!tree) return;
if(PlayerManager.GetInstance().selectedPlayer.availableSkillTrees.Contains(tree.skillTree))
tree.gameObject.SetActive(true);
else
tree.gameObject.SetActive(false);
}
}
private void OnEnable()
{
PlayerChanger.playerChangeEvent+=EnableTrees;
}
private void OnDisable()
{
PlayerChanger.playerChangeEvent-=EnableTrees;
}
}
}<file_sep>/README.md
# unity-skill-tree
world of warcraft-like skill/talent tree in unity c#

## about
#### functionality:
- Skill tree based on talent trees from World Of Warcraft (Wotlk)
- Supports multiple skill trees
- Supports multiple players
- Player have specific trees available
- Selecting different player, resets tree accordingly to their acquired skills
- Skill Buttons can be locked/unlocked if they meet requirements:
1. Adequate ```SkillTreeController``` has enough ```int pointsInTree```
2. Adequate ```SkillButton``` that has this concrete ```SkillButton``` in unlockable list, must be maxed out
- Skills are ```ScriptableObject``` with some possible functionality. See ```StatCalculator.cs```, ```Skill.cs``` and ```Player.cs``` for example usage.
#### used 3rd party assets:
- https://assetstore.unity.com/packages/2d/gui/icons/basic-rpg-icons-181301
- https://assetstore.unity.com/packages/tools/gui/clean-settings-ui-65588
- random wow screenshot
<file_sep>/SkillTreeProject/Scripts/PlayerChanger.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerChanger : MonoBehaviour
{
public static event Action playerChangeEvent;
public void SelectPlayer(int index)
{
PlayerManager.GetInstance().SelectPlayer(index);
playerChangeEvent?.Invoke();
}
void Awake() => SelectPlayer(0);
}
<file_sep>/SkillTreeProject/Scripts/StatCalculators/CalculateStat.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class CalculateStat
{
public static float GetValue(Player player)
{
float value = 1f;
foreach(Skill skill in player.skills)
{
foreach(SkillFunctionality skillFunctionality in skill.functionalities)
{
if(skillFunctionality.functionality == player.functionalityToTest)
{
value=value*(1+(skillFunctionality.percentageValue/100));
}
}
}
return value;
}
}
<file_sep>/SkillTreeProject/Scripts/SkillButtonsAssigner.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SkillTreeProject
{
public class SkillButtonsAssigner : MonoBehaviour
{
private void OnEnable()
{
PlayerChanger.playerChangeEvent+=AssignSkillsToButtons;
}
private void OnDisable()
{
PlayerChanger.playerChangeEvent-=AssignSkillsToButtons;
}
private void AssignSkillsToButtons()
{
List<Skill> playerSkills = PlayerManager.GetInstance().selectedPlayer.skills;
foreach(var treeController in SkillTreeControllerManager.GetInstance().skillTreeControllers)
{
treeController.pointsInTree = 0;
foreach(var skillButton in treeController.skillButtonsInTree)
{
skillButton.ResetButton();
}
foreach(var skillButton in treeController.skillButtonsInTree)
{
List<Skill> buttonSkills = skillButton.skills;
for(int i = buttonSkills.Count-1; i >= 0; i--)
{
if(playerSkills.Contains(buttonSkills[i]))
{
treeController.pointsInTree += i+1;
skillButton.addedSkillPoints = i+1;
break;
}
}
}
}
}
}
}
<file_sep>/SkillTreeProject/Scripts/Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using SkillTreeProject;
public class Player : MonoBehaviour
{
private List<Skill> _skills = new List<Skill>();
public List<Skill> skills
{
get => _skills;
set => _skills = value;
}
public List<SkillTree> availableSkillTrees = new List<SkillTree>();
void Awake() => PlayerManager.GetInstance().players.Add(this);
//test weapon damage
public Functionality functionalityToTest;
void Update()
{
if(Input.GetKeyDown(KeyCode.A))
{
Debug.Log(gameObject.name +"s "+ functionalityToTest.ToString() + " is " + CalculateStat.GetValue(this));
}
}
//
}
<file_sep>/SkillTreeProject/Scripts/SkillTreeController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace SkillTreeProject
{
public class SkillTreeController : MonoBehaviour
{
[SerializeField] private Text pointsInTreeText;
[SerializeField] private Text titleText;
public SkillTree skillTree;
private int _pointsInTree;
public int pointsInTree
{
get => _pointsInTree;
set
{
_pointsInTree = value;
foreach(SkillButton skillButton in skillButtonsInTree)
{
if(skillButton.requiredTreePoints<=pointsInTree)
{
skillButton.hasRequiredPoints=true;
}
}
UpdatePointsInTreeText();
}
}
private List<SkillButton> _skillButtonsInTree = new List<SkillButton>();
public List<SkillButton> skillButtonsInTree
{
get => _skillButtonsInTree;
set
{
_skillButtonsInTree = value;
}
}
void OnValidate()
{
if(gameObject.scene.rootCount == 0) return;
UpdateTitleText();
}
void Awake() => SkillTreeControllerManager.GetInstance().skillTreeControllers.Add(this);
void UpdateTitleText()
{
if(!titleText || !skillTree) return;
titleText.text = skillTree.name;
gameObject.name = skillTree.name + " Tree";
}
void UpdatePointsInTreeText()
{
if(!pointsInTreeText) return;
int sum = 0;
foreach(var button in skillButtonsInTree)
{
sum+=button.skills.Count;
}
pointsInTreeText.text = pointsInTree+"/"+sum;
}
}
}
<file_sep>/SkillTreeProject/Scripts/SkillTreeControllerManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SkillTreeProject
{
public class SkillTreeControllerManager
{
private SkillTreeControllerManager() { }
private static SkillTreeControllerManager _instance;
public static SkillTreeControllerManager GetInstance()
{
if (_instance == null)
{
_instance = new SkillTreeControllerManager();
}
return _instance;
}
public List<SkillTreeController> skillTreeControllers = new List<SkillTreeController>();
}
}
<file_sep>/SkillTreeProject/Scripts/SkillButton.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace SkillTreeProject
{
public class SkillButton : MonoBehaviour
{
public static event Action<Skill> addSkillEvent;
[SerializeField] private Text addedSkillPointsText;
private int _addedSkillPoints;
public int addedSkillPoints
{
get => _addedSkillPoints;
set
{
_addedSkillPoints = value;
UpdateText();
if(addedSkillPoints == skills.Count)
{
maxedOut = true;
}
else
maxedOut = false;
}
}
public int requiredTreePoints;
private bool _hasRequiredSkill = true;
public bool hasRequiredSkill
{
get => _hasRequiredSkill;
set
{
_hasRequiredSkill = value;
if(value==true)
AttemptUnlock();
else
Lock();
}
}
private bool _hasRequiredPoints;
public bool hasRequiredPoints
{
get => _hasRequiredPoints;
set
{
_hasRequiredPoints = value;
if(value==true)
AttemptUnlock();
else
Lock();
}
}
private bool _maxedOut;
public bool maxedOut
{
get => _maxedOut;
set
{
_maxedOut = value;
if(value==true)
{
Lock();
UnlockUnlockableSkills();
}
else
AttemptUnlock();
}
}
[SerializeField] private SkillTreeController skillTreeController;
public List<Skill> skills = new List<Skill>();
[SerializeField] private List<SkillButton> unlockableSkills = new List<SkillButton>();
[SerializeField] private string skillName;
void Awake()
{
if(!skillTreeController.skillButtonsInTree.Contains(this))
skillTreeController.skillButtonsInTree.Add(this);
}
void Start()
{
ResetButton();
}
void OnValidate()
{
if(gameObject.scene.rootCount == 0) return;
if(!skillTreeController) return;
if(!skillTreeController.skillButtonsInTree.Contains(this))
skillTreeController.skillButtonsInTree.Add(this);
gameObject.name = skillName + " Button";
if(!addedSkillPointsText) return;
UpdateText();
}
void OnDrawGizmosSelected()
{
foreach(var unlockableSkill in unlockableSkills)
{
if(!unlockableSkill) return;
Gizmos.color = Color.blue;
Gizmos.DrawLine(transform.position, unlockableSkill.transform.position);
}
}
public void AddPoint()
{
addSkillEvent?.Invoke(skills[addedSkillPoints]);
skillTreeController.pointsInTree++;
addedSkillPoints++;
UpdateText();
}
public void ResetButton()
{
addedSkillPoints=0;
if(requiredTreePoints>0)
hasRequiredPoints=false;
else
hasRequiredPoints=true;
foreach(var unlockableSkill in unlockableSkills)
{
unlockableSkill.hasRequiredSkill = false;
}
}
private void UpdateText() => addedSkillPointsText.text = addedSkillPoints+"/"+skills.Count;
private void UnlockUnlockableSkills()
{
foreach(var unlocked in unlockableSkills)
{
unlocked.hasRequiredSkill = true;
}
}
private void Lock()
{
GetComponent<Button>().interactable = false;
}
private void AttemptUnlock()
{
if(!hasRequiredSkill) return;
if(!hasRequiredPoints) return;
if(maxedOut) return;
GetComponent<Button>().interactable = true;
}
}
}
<file_sep>/SkillTreeProject/Scripts/SkillButtonToGrid.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace SkillTreeProject
{
public class SkillButtonToGrid : MonoBehaviour
{
[SerializeField] private int x;
[SerializeField] private int y;
const int buttonSpace = 47;
const int xOffset = 26;
const int yOffset = -26;
void OnValidate()
{
GetComponent<RectTransform>().anchoredPosition = new Vector2(x*buttonSpace+xOffset, -y*buttonSpace+yOffset);
}
}
}
<file_sep>/SkillTreeProject/Scripts/PlayerManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerManager
{
private PlayerManager() { }
private static PlayerManager _instance;
public static PlayerManager GetInstance()
{
if (_instance == null)
{
_instance = new PlayerManager();
}
return _instance;
}
public List<Player> players = new List<Player>();
public Player selectedPlayer;
public void SelectPlayer(int index)
{
selectedPlayer = players[index];
}
}
<file_sep>/SkillTreeProject/Scripts/FunctionalityTypes.cs
public enum Functionality
{
maxHealthPoints,
maceDamage,
swordDamage
} | bfd9b78c5c89fe0258430012a583a141df8ed0d1 | [
"Markdown",
"C#"
] | 18 | C# | exewin/unity-skill-tree | ec5867d8a884827a4627539160add002278b8a7d | 85659ed3407f74b3d823ef9c6639fde98bd17278 |
refs/heads/master | <repo_name>Yang-33/Jikka<file_sep>/examples/data/yukicoder_1649.solver.cpp
#include <atcoder/modint>
#include <atcoder/segtree>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; (i) < (int)(n); ++(i))
#define REP3(i, m, n) for (int i = (m); (i) < (int)(n); ++(i))
#define REP_R(i, n) for (int i = (int)(n)-1; (i) >= 0; --(i))
#define REP3R(i, m, n) for (int i = (int)(n)-1; (i) >= (int)(m); --(i))
#define ALL(x) ::std::begin(x), ::std::end(x)
using namespace std;
using namespace atcoder;
using mint = modint998244353;
mint plus_op(mint a, mint b) { return a + b; }
mint plus_e() { return 0; }
mint solve(int n, const std::vector<int64_t> &x,
const std::vector<int64_t> &y) {
mint ans = 0;
// \sum \sum (x_i - x_j)^2 + (y_i - y_j)^2
mint sum_x = 0;
mint sum_y = 0;
REP(i, n) {
ans += mint(x[i]) * mint(x[i]) * (n - 1);
ans += mint(y[i]) * mint(y[i]) * (n - 1);
ans -= 2 * sum_x * mint(x[i]);
ans -= 2 * sum_y * mint(y[i]);
sum_x += x[i];
sum_y += y[i];
}
// 2 \sum \sum |x_i - x_j| |y_i - y_j|
vector<int> order_x(n);
iota(ALL(order_x), 0);
sort(ALL(order_x), [&](int i, int j) { return x[i] > x[j]; });
vector<int64_t> compress_y = y;
sort(ALL(compress_y));
compress_y.erase(unique(ALL(compress_y)), compress_y.end());
const int H = compress_y.size();
segtree<mint, plus_op, plus_e> segtree_sum(H);
segtree<mint, plus_op, plus_e> segtree_cnt(H);
for (int j : order_x) {
// - 2 \sum \sum x_j |y_i - y_j|
int k = lower_bound(ALL(compress_y), y[j]) - compress_y.begin();
ans -= 2 * x[j] *
(segtree_sum.prod(k + 1, H) - segtree_cnt.prod(k + 1, H) * y[j]);
ans -= 2 * x[j] * (segtree_cnt.prod(0, k) * y[j] - segtree_sum.prod(0, k));
segtree_sum.set(k, segtree_sum.get(k) + y[j]);
segtree_cnt.set(k, segtree_cnt.get(k) + 1);
}
for (int i : order_x) {
// 2 \sum \sum x_i |y_i - y_j|
int k = lower_bound(ALL(compress_y), y[i]) - compress_y.begin();
segtree_sum.set(k, segtree_sum.get(k) - y[i]);
segtree_cnt.set(k, segtree_cnt.get(k) - 1);
ans += 2 * x[i] *
(segtree_sum.prod(k + 1, H) - segtree_cnt.prod(k + 1, H) * y[i]);
ans += 2 * x[i] * (segtree_cnt.prod(0, k) * y[i] - segtree_sum.prod(0, k));
}
return ans;
}
// generated by oj-template v4.8.0
// (https://github.com/online-judge-tools/template-generator)
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int N;
std::cin >> N;
std::vector<int64_t> x(N), y(N);
REP(i, N) { std::cin >> x[i] >> y[i]; }
auto ans = solve(N, x, y);
std::cout << ans.val() << '\n';
return 0;
}
<file_sep>/examples/fib_list_riantkb.py
# See https://github.com/kmyk/Jikka/issues/178
from typing import *
def solve(n: int) -> int:
a = 0
b = 1
lis = []
for i in range(n):
lis.append(0)
for i in lis:
c = a + b + i
a = b
b = c
return a % 1000000007
def main():
n = int(input())
ans = solve(n)
print(ans)
if __name__ == "__main__":
main()
<file_sep>/docs/core.md
# About our core language
(このドキュメントの日本語バージョン: [docs/core.ja.md](https://github.com/kmyk/Jikka/blob/master/docs/core.ja.md))
Jikka converts input programs to our own intermediate language, core.
This core language is defined referring to [Core](https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary/compiler/core-syn-type), which is the intermediate language of a [Haskell](https://www.haskell.org/) compiler [GHC](https://www.haskell.org/ghc/).
## Syntax
Expressions of our core language are defined at [data `Expr`](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:Expr), and types are defined at [data `Type`](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:Type).
The list of builtin functions exist at [data `Builtin`](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:Builtin).
The toplevel environment is separated and defined at [data `ToplevelExpr`](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:ToplevelExpr).
`let rec` is available only at the toplevel.
## Semantics
Our core language is a statically-typed purely-functional programming language.
It works as almost the same to Haskell.
## String representation
The string representation is similar to OCaml.
- Types are like `unit` `int list` `int * int -> int`.
- Functions are `fun x y -> e`.
- Functions applications are `f x y`.
- `if e1 then e2 else e3` is an if-expression.
- `(e1, e2, e3)` is the tuple of `e1`, `e2` and `e3`.
- `e.i` is the `i`-th element of a tuple `e`.
- `xs[i]` is the `i`-th element of a list `xs`.
- `xs[i <- x]` is the list which is obtained by assining `x` to the `i`-th element of a list `xs`.
- This notation comes from notations of substitutions which are used in discussion about λ calculus.
- List literals don't exist.
<file_sep>/examples/data/yukicoder_1649.large.generator.py
#!/usr/bin/env python3
import argparse
import random
def main():
parser = argparse.ArgumentParser()
# parser.add_argument('-n', type=int, default=random.randint(1, 2 * 10 ** 5))
parser.add_argument('-n', type=int, default=random.randint(1, 2 * 100))
args = parser.parse_args()
N = args.n
x = [None for _ in range(N)]
y = [None for _ in range(N)]
used = set()
for i in range(N):
while True:
x[i] = random.randint(1, 10**9)
y[i] = random.randint(1, 10**9)
if (x[i], y[i]) not in used:
used.add((x[i], y[i]))
break
print(N)
for i in range(N):
print(x[i], y[i])
if __name__ == "__main__":
main()
<file_sep>/examples/dp_min_square_kubaru.py
# https://judge.kimiyuki.net/problem/dp-min-square
INF = 10 ** 18
def solve(a: List[int]) -> int:
n = len(a)
dp = [INF for _ in range(n)]
dp[0] = 0
for j in range(n):
for i in range(j + 1, n):
dp[i] = min(dp[i], dp[j] + (a[i] - a[j]) ** 2)
return dp[n - 1]
<file_sep>/docs/core.ja.md
# About our core language
(The English version of this document: [docs/core.md](https://github.com/kmyk/Jikka/blob/master/docs/core.md))
Jikka は入力されたプログラムを内部で独自の中間言語 core に変換して処理します。
この core 言語は、[Haskell](https://www.haskell.org/) のコンパイラである [GHC](https://www.haskell.org/ghc/) の中間言語 [Core](https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary/compiler/core-syn-type) を参考にして定義されています。
## Syntax
core 言語の式は [data `Expr`](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:Expr) で定義されており、型は [data `Type`](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:Type) で定義されています。
組み込み関数の一覧は [data `Builtin`](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:Builtin) にあります。
また、toplevel 環境は [data `ToplevelExpr`](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:ToplevelExpr) で定義されて分離されています。
`let rec` は toplevel でのみ利用可能です。
## Semantics
core 言語は静的型付き純粋関数型プログラミング言語です。
Haskell とほとんど同様に動作します。
## String representation
文字列表現は OCaml 寄りの独自のものを採用しています。
- 型は `unit` `int list` `int * int -> int` などと書きます。
- 関数は `fun x y -> e` のように書きます。
- 関数適用 `f x y` のように書きます。
- `if e1 then e2 else e3` は if 式を表します。
- `(e1, e2, e3)` は `e1` `e2` `e3` からなるタプルを表します。
- `e.i` はタプル `e` の `i` 要素目を表します。
- `xs[i]` はリスト `xs` の `i` 要素目を表します。
- `xs[i <- x]` はリスト `xs` の `i` 要素目に `x` を代入して得られるようなリストを表します。
- この記法は λ 計算の議論で用いられる置換の記法に由来しています。
- リストリテラルはありません。
<file_sep>/examples/data/abc206_b.solver.cpp
#include <cstdint>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; (i) < (int)(n); ++(i))
#define REP3(i, m, n) for (int i = (m); (i) < (int)(n); ++(i))
#define REP_R(i, n) for (int i = (int)(n)-1; (i) >= 0; --(i))
#define REP3R(i, m, n) for (int i = (int)(n)-1; (i) >= (int)(m); --(i))
#define ALL(x) ::std::begin(x), ::std::end(x)
using namespace std;
int64_t solve(int64_t N) {
int64_t c = 0;
for (int i = 1; i < 100000; ++i) {
c += i;
if (c >= N) {
return i;
}
}
return 0; // avoid warning
}
// generated by oj-template v4.8.1
// (https://github.com/online-judge-tools/template-generator)
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int64_t N;
std::cin >> N;
auto ans = solve(N);
std::cout << ans << '\n';
return 0;
}
<file_sep>/scripts/requirements.txt
isort==5.9.3
mypy==0.910
yapf==0.31.0
colorlog==6.*
<file_sep>/examples/data/abc200_b.solver.py
#!/usr/bin/env python3
# https://atcoder.jp/contests/abc200/submissions/22401491
def solve(n: int, k: int) -> int:
for _ in range(k):
if n % 200 == 0:
n //= 200
else:
n = n * 1000 + 200
return n
# generated by oj-template v4.7.2 (https://github.com/online-judge-tools/template-generator)
def main():
N, K = map(int, input().split())
a = solve(N, K)
print(a)
if __name__ == '__main__':
main()
<file_sep>/docs/DESIGN.md
# Design Doc
(The English version of this document: [docs/DESIGN.md](https://github.com/kmyk/Jikka/blob/master/docs/DESIGN.md))
## Objective
Jikka は競技プログラミングの問題を解くことそのものを自動化する。
## Goals
- 形式的な形で与えられた競技プログラミングの問題の解法を自動で生成する
- 競技プログラミングにおける実装パートのうちで機械的に処理できる部分を機械的に処理する
- 実用的には [OEIS](https://oeis.org/) や [Wolfram|Alpha](https://www.wolframalpha.com/) のような立ち位置を目指す
## Non-Goals
- 自然言語で与えられた競技プログラミングの問題の解法を自動で生成すること
- GPT-3 や GitHub Copilot に任せておけばよい
## Background
競技プログラミングの問題の中には、機械的に解けるであろう問題が存在する。
全体が機械的に解けるということはない場合であっても、部分的になら機械的に解けるであろう問題は多い。
たとえば個々の式変形それ自体は自明な式変形を丁寧に行っていくことで解けるような問題である。これを自動化したい。
## Overview
Jikka は競技プログラミングの問題を自動で解くソルバである。
「競技プログラミングの問題を自動で解く」といっても様々な種類のものが考えられるが、Jikka は特にこれを「最適化を伴うトランスパイラ」の形に落とし込んで実現する。
つまり Jikka はその概観としてはただのトランスパイラである。
Python のとても制限されたサブセットとして書かれたソースコードを受けとり、GHC の Core に似た内部言語の上で最適化を行い、最終的に C++ のソースコードを出力する。
さらに、実際のコンテスト中により実用的に利用しやすくするために「最適化を行う書き換え機能を提供する IDE プラグイン」としても利用できるようにする。
たとえばコード片を右クリックしてメニューから「この O(N²) のループを O(N) に書き換える」を選べばそのように書き換えてくれる。
Language Server Protocol を用いて実装され、言語は Python および C++ の両方に対応する。
## Detailed Design
### トランスパイラとして実装すること
Jikka はトランスパイラとして実装される。
これは開発も利用も簡単であるためである。
競技プログラミングの問題のソルバというは目標は壮大かつ曖昧すぎて、最初から完璧なものを作るのは不可能である。
であるので、まずは確実に実装可能ですでによく理解されているもの、つまりトランスパイラとしての実装から始めていくべきである。
### IDE プラグインとして実装すること
Jikka は IDE プラグインとしても利用できる。
これは利用をより簡単で実用的にするためである。
大きなファイルを大きなファイルに変換するようなトランスパイラでは、どのような最適化が行われたのかが分かりにくい。
一方で小さなコード片を小さなコード片に書き換える IDE の機能であれば、どのような最適化が行われたのかが分かりやすく、ユーザにとってより制御しやすい。
### 入力言語には主に Python を用いる
以下の 2 点を理由として、入力言語には Python のサブセットを用いる。
1. 利用しやすい: 学習しやすく、書きやすい。Python は広く普及していてかつそこそこ高級な言語である
2. 開発しやすい: 言語機能を制限すればコンパイラで扱いやすい。本物の Python との差分は未定義動作という形で吸収すればよい
言語機能は大きく制限し、静的型付け言語とする。
副作用はある種の糖衣構文としてのみ残し、意味論的には存在しない。
### 入力言語に独自の新しいプログラミング言語を用いることはしない
以下の 2 点を理由として、入力言語に独自言語を用いることは避ける。
それぞれ Python を用いる理由の裏となっている。
1. 利用しにくい: 独自言語であると、ユーザはその言語を新規に覚える必要がある。たいていのユーザにとって新しい言語を覚えることはかなりの負担である
2. 開発しにくい: 独自言語であると、開発者はその言語のドキュメントを丁寧に書く必要がある。仕様が明確であることや解説が豊富にあることはプログラミング言語の重要な機能性のひとつである
### 出力言語には主に C++ を用いる
理由は以下の 2 点である。
1. 利用しやすい: 競プロという用途において柔軟な利用が可能になる
2. 開発しやすい: 定数倍最適化を心配する必要がない
## Metrics Considerations
適切な仮定の下で「AtCoder 上でのレート」という形で性能評価が可能である。
また「AtCoder Beginner Contest などの問題のうち何割が解ける」などの形での評価も可能だろう。
## Testing Plan
競技プログラミングにおいては効率良く実行できる安定した end-to-end テストが簡単に書けるため、これを利用するのがよいだろう。
つまり、俗に「verify する」と呼ばれる、実際の競技プログラミングの問題に対して利用して AC を確認するという形式のテストである。
また、これを行うための専用のオンラインジャッジも用意されている: <https://judge.kimiyuki.net/>
<file_sep>/examples/wip/tle/yukicoder_1649.py
# https://yukicoder.me/problems/no/1649
from typing import *
MOD = 998244353
def solve(N: int, x: List[int], y: List[int]) -> int:
ans = 0
for i in range(N - 1):
for j in range(i + 1, N):
ans += (abs(x[i] - x[j]) + abs(y[i] - y[j])) ** 2
return ans % MOD
# generated by oj-template v4.8.0 (https://github.com/online-judge-tools/template-generator)
def main():
N = int(input())
x = list(range(N))
y = list(range(N))
for i in range(N):
x[i], y[i] = map(int, input().split())
ans = solve(N, x, y)
print(ans)
if __name__ == '__main__':
main()
<file_sep>/examples/loop_mod_uta8a.py
# See https://github.com/kmyk/Jikka/issues/173
def solve(n: int, k: int) -> int:
for _ in range(k):
n = n % 3
return n
def main() -> None:
n, k = map(int, input().split())
ans = solve(n, k)
print(ans)
if __name__ == '__main__':
main()
<file_sep>/scripts/add_test_cases.py
#!/usr/bin/env python3
import argparse
import json
import pathlib
import shutil
import subprocess
import sys
from logging import DEBUG, basicConfig, getLogger
from typing import *
logger = getLogger(__name__)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('url')
parser.add_argument('--name', metavar='STEM', help='The stem name of files. The problem IDs (e.g. abc123_d, agc001_a) are often used.')
parser.add_argument('--only-sample-cases', action='store_true')
parser.add_argument('-n', '--dry-run', action='store_true')
args = parser.parse_args()
basicConfig(level=DEBUG)
if args.name is not None:
name = args.name
elif 'atcoder.jp' in args.url:
name = args.url.split('/')[-1]
elif 'yukicoder.me' in args.url:
name = 'yukicoder_' + args.url.split('/')[-1]
else:
logger.error('--name=STEM is required')
sys.exit(1)
if shutil.which('oj-api') is None:
logger.error('Please install `oj-api` command with: $ pip3 install online-judge-api-client')
sys.exit(1)
if shutil.which('oj-template') is None:
logger.error('Please install `oj-template` command with: $ pip3 install online-judge-template-generator')
sys.exit(1)
data = json.loads(subprocess.check_output(['oj-api', 'get-problem', args.url]))
if data['status'] != 'ok':
logger.error('failed to download the problem info: %s', data)
sys.exit(1)
plan: Dict[pathlib.Path, bytes] = {}
examples_dir = pathlib.Path('examples')
# collect files
for i, testcase in enumerate(data['result']['tests']):
plan[examples_dir / 'data' / '{}.sample-{}.in'.format(name, i + 1)] = testcase['input'].encode()
plan[examples_dir / 'data' / '{}.sample-{}.out'.format(name, i + 1)] = testcase['output'].encode()
if not args.only_sample_cases:
plan[examples_dir / '{}.py'.format(name)] = subprocess.check_output(['oj-template', '-t', 'main.py', args.url])
plan[examples_dir / 'data' / '{}.solver.cpp'.format(name)] = subprocess.check_output(['oj-template', '-t', 'main.cpp', args.url]).replace(b'#include <bits/stdc++.h>\n', b'#include <cstdint>\n#include <iostream>\n#include <vector>\n') # Replace bits/stdc++.h to compile the solver on Windows.
plan[examples_dir / 'data' / '{}.large.generator.py'.format(name)] = subprocess.check_output(['oj-template', '-t', 'generate.py', args.url])
# check files
for path in plan:
if path.exists():
logger.error('file already exists: %s', str(path))
sys.exit(1)
# write files
for path, content in plan.items():
logger.info('write file: %s', str(path))
if not args.dry_run:
with open(path, 'wb') as fh:
fh.write(content)
if __name__ == '__main__':
main()
<file_sep>/examples/data/abc203_b.solver.cpp
#include <cstdint>
#include <iostream>
#define REP(i, n) for (int i = 0; (i) < (int)(n); ++(i))
#define REP3(i, m, n) for (int i = (m); (i) < (int)(n); ++(i))
#define REP_R(i, n) for (int i = (int)(n)-1; (i) >= 0; --(i))
#define REP3R(i, m, n) for (int i = (int)(n)-1; (i) >= (int)(m); --(i))
#define ALL(x) ::std::begin(x), ::std::end(x)
using namespace std;
int64_t solve(int64_t N, int64_t K) {
uint64_t ans = 0;
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= K; ++j) {
ans += 100 * i + j;
}
}
return ans;
}
// generated by oj-template v4.8.1
// (https://github.com/online-judge-tools/template-generator)
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int64_t N, K;
std::cin >> N >> K;
auto ans = solve(N, K);
std::cout << ans << '\n';
return 0;
}
<file_sep>/examples/sum_sum_abs_one.py
# https://judge.kimiyuki.net/problem/sum-sum-abs-one
from typing import *
def solve(a: List[int]) -> int:
ans = 0
for a_i in a:
for a_j in a:
ans += abs(a_i - a_j)
return ans
def main() -> None:
n = int(input())
a = list(map(int, input().split()))
assert len(a) == n
ans = solve(a)
print(ans)
if __name__ == "__main__":
main()
<file_sep>/docs/DESIGN.ja.md
# Design Doc
(このドキュメントの日本語バージョン: [docs/DESIGN.ja.md](https://github.com/kmyk/Jikka/blob/master/docs/DESIGN.ja.md))
## Objective
Jikka automates the very process of solving problems of competitive programming.
## Goals
- Automatically generating solutions to competition programming problems given in a formal form
- Mechanically processing some implementation parts of competition programming
- In practical use, it aims for a position similar to [OEIS](https://oeis.org/) and [Wolfram|Alpha](https://www.wolframalpha.com/).
## Non-Goals
- Automatically generating solutions to competition programming problems given in natural language
- Let GPT-3, GitHub Copilot, etc. do this for you.
## Background
There are some problems in competitive programming that can be solved mechanically.
Even if the whole problem cannot be solved mechanically, there are many problems that can be solved partially mechanically.
For example, there are problems that can be solved by carefully transforming the given formula, which each transformation itself is trivial.
We want to automate this.
## Overview
Jikka is an automatic solver for problems of competitive programming.
We can think many possible forms of automatic solvers, but Jikka is implemented especially as a transpiler doing optimization.
In other words, Jikka is just a transpiler in its overview.
It takes source code of a very restricted subset of Python as input, optimizes it in an internal language similar to GHC's Core, and finally writes source code of C++ as output.
In addition, Jikka can be used as an IDE plugin that provides rewriting functions for optimization, for more practical use during real contests.
For example, by right-clicking on a snippet of code and selecting "Rewrite this O(N²) loop to O(N)" from the menu, the code will be rewritten as such.
It is implemented using the Language Server Protocol, and supports both Python and C++ languages.
## Detailed Design
### Implemented as a transpiler
Jikka is implemented as a transpiler, because it is easy to develop and use.
The goal of a solver for competitive programming problems is too ambitious and vague to create a perfect one from the beginning.
Therefore, we should start with an easy-to-implement and already well-understood thing, i.e., a transpiler.
### Implemented as IDE plugin
Jikka is also available as an IDE plugin.
This makes it easier to use in practice.
With a transpiler that converts a large file to a large file, it is difficult to understand what kind of optimization has been done.
On the other hand, with the IDE's function that rewrites a small snippet of code into a small snippet of code, it is easier for the user to understand and control what kind of optimization has been done.
### Use Python for input
We will use a subset of Python as input, due to the following two reasons:
1. easy to use: easy to learn and write; Python is a widely used and reasonably expensive language.
2. easy to develop: easy to handle with a compiler, if we limit the features. The differences from real Python can be absorbed in the form of undefined behaviors.
We largely limit the language features, and makes it a statically typed language.
Side effects are left only as some kind of syntax suger, and removed in its core semantics.
### Don't use a new own language for input
We avoid using a new own language as input, due to the following two reasons.
Each of these is an inverse of the reason for using Python:
1. difficult to use: A new own language requires the user to learn the language anew. For most users, learning a new language is a significant burden.
2. difficult to develop: A new own language requires the developer to carefully write documentation for the language. Clear specifications and plenty of explanations are one of the important features of a programming language.
### Use C++ for output
There are two reasons:
1. ease of use: flexible in the context of competitive programming
2. easy to develop: no need to worry about constant-factor optimization
## Metrics Considerations
Under appropriate assumptions, it is possible to evaluate performance in terms of rating on AtCoder.
It may also be possible to evaluate performance in terms of how many of the problems in the AtCoder Beginner Contest can be solved.
## Testing Plan
In competition programming, it is easy to write fast and stable end-to-end tests, so we use them.
This is a form of testing that is commonly referred to as "verifying", in which you check the AC by using it against real problems of competition programming.
There are also dedicated online judges for this purpose: <https://judge.kimiyuki.net/>
<file_sep>/scripts/pre-commit
#!/bin/bash
set -x
# Haskell
if git diff --staged --name-only | grep '\.hs$'; then
stack exec ormolu -- --version \
|| { echo HINT: Please install Ormolu with '$ stack install ormolu'; exit 1; }
stack exec ormolu -- --mode=check $(find src app test -name \*.hs) \
|| { echo HINT: Please run '$ stack exec ormolu -- --mode=inplace $(find src app test -name \*.hs)'; exit 1; }
stack exec hlint -- --version \
|| { echo HINT: Please install HLint with '$ stack install hlint'; exit 1; }
stack exec hlint -- src app test \
|| exit 1
fi
if [ -n "$(git diff --staged --name-only --diff-filter=m src test)$(git diff --staged package.yaml)" ]; then
# Check *.cabal only when some source files are added or deleted, because it is not stable and depends on the versions of stack command or hpack command.
stack build --only-configure \
|| exit 1
git diff --exit-code *.cabal \
|| { echo HINT: Please run '$ git add *.cabal'; exit 1; }
fi
grep '\<Debug.Trace\>' $(find src test -name \*.hs | grep -v 'RewriteRules\.hs') \
&& { echo HINT: Please remove Debug.Trace from $(grep '\<Debug.Trace\>' -r src test | cut -d: -f1); exit 1; }
# C++
if git diff --staged --name-only | grep '\..\?pp$'; then
which clang-format \
|| { echo HINT: Please install clang-format; exit 1; }
for f in $(find runtime/include examples/data -name \*.\?pp | grep -v 'library-checker-problems\|jikka-judge-problems'); do
diff $f <(clang-format $f) \
|| { echo HINT: Please run '$ clang-format -i $(find runtime/include examples/data -name \*.\?pp | grep -v 'library-checker-problems\|jikka-judge-problems');' ; exit 1; }
done
fi
# Python
if git diff --staged --name-only | grep '\.py$'; then
isort --version \
|| { echo HINT: Please install isort with running '$ pip3 install -r scripts/requirements.txt'; exit 1; }
isort --check-only --diff scripts/*.py examples/data/*.py \
|| { echo HINT: Please run '$ isort scripts/*.py examples/data/*.py'; exit 1; }
yapf --version \
|| { echo HINT: Please install yapf with running '$ pip3 install -r scripts/requirements.txt'; exit 1; }
yapf --diff '--style={ COLUMN_LIMIT: 9999 }' scripts/*.py examples/data/*.py \
|| { echo HINT: Please run '$ yapf --in-place '\''--style={ COLUMN_LIMIT: 9999 }'\'' scripts/*.py examples/data/*.py'; exit 1; }
mypy --version \
|| { echo HINT: Please install mypy with running '$ pip3 install -r scripts/requirements.txt'; exit 1; }
mypy --ignore-missing-imports scripts/*.py examples/data/*.py \
|| exit 1
fi
# TeX
if git diff --staged --name-only | grep '\.tex$'; then
chktex --version \
|| { echo HINT: Please install chktex, e.g. '$ sudo apt install chktex'; exit 1; }
chktex --nowarn={1,2,8,11,12,13,36,39} $(git ls-files | grep '\.tex$') \
|| exit 1
fi
# Other files
for ext in yml yaml json md html mjs; do
if git diff --staged --name-only | grep '\.'$ext'$'; then
which yarn \
|| { echo HINT: Please install Yarn 'https://classic.yarnpkg.com/en/docs/install/'; exit 1; }
yarn prettier --version \
|| { echo HINT: Please run '$ yarn install'; exit 1; }
yarn prettier --check $(git ls-files | grep '\.'$ext'$') \
|| { echo HINT: Please run '$ yarn prettier --write $(git ls-files | grep '\''\.'$ext'$'\'')'; exit 1; }
fi
done
<file_sep>/examples/sum_sum_plus_two.py
# https://judge.kimiyuki.net/problem/sum-sum-plus-two
from typing import *
def solve(a: List[int], b: List[int]) -> int:
ans = 0
for a_i in a:
for b_j in b:
ans += a_i - b_j
return ans
def main() -> None:
n, m = map(int, input().split())
a = list(map(int, input().split()))
assert len(a) == n
b = list(map(int, input().split()))
assert len(b) == m
ans = solve(a, b)
print(ans)
if __name__ == "__main__":
main()
<file_sep>/docs/internal.md
# docs/internal.md
(このドキュメントの日本語バージョン: [docs/internal.ja.md](https://github.com/kmyk/Jikka/blob/master/docs/internal.ja.md))
This document describes the internal implementation of Jikka.
## 0. Overview
The general structure of Jikka's internals is to perform the followings in order:
1. Read a Python code
2. Get a Python AST with parsing the Python code
3. Convert the Python AST to an AST of our restricted Python
4. Preprocess the AST of our restricted Python
5. Convert the AST of a restricted Python to a AST of our core language
6. Optimize the AST of our core language
7. Convert the AST of our core languagee to a C++ AST
8. Postprocess the C++ AST
9. Convert the C++ AST to a C++ code
10. Write the C++ code
Jikka converts (standard) Python, our restricted Python, our core language and C++ in this order.
Here, our restricted Python is the language specified in [docs/language.md](https://github.com/kmyk/Jikka/blob/master/docs/language.md).
Our core language is a language which is similar to Haskell and is almost the same to [GHC Core](https://gitlab.haskell.org/ghc/ghc/-/wikis/commentary/compiler/core-syn-type) which is the intermediate language of GHC the Haskell compiler.
This core language is described in [docs/core.md](https://github.com/kmyk/Jikka/blob/master/docs/language.md).
- List of modules [Jikka](https://kmyk.github.io/Jikka/)
- File: [src/Jikka/Main/Subcommand/Convert.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Main/Subcommand/Convert.hs) ([Jikka.Main.Subcommand.Convert](https://kmyk.github.io/Jikka/haddock/Jikka-Main-Subcommand-Convert.html))
## 2. Get a Python AST with parsing the Python code
After reading a Python code string, Jikka parses it based on [the grammar specification of Python](https://docs.python.org/ja/3/reference/grammar.html).
We use [lex](https://ja.wikipedia.org/wiki/Lex) (Its Haskell version [alex](https://www.haskell.org/alex/)) and [yacc](https://ja.wikipedia.org/wiki/Yacc) (Its Haskell version [happy](https://www.haskell.org/happy/)) to generate an LALR(1) parser.
- File: lex [src/Jikka/Python/Parse/Happy.y](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Python/Parse/Happy.y) ([Jikka.Python.Parse.Happy](https://kmyk.github.io/Jikka/haddock/Jikka-Python-Parse-Alex.html))
- File: yacc [src/Jikka/Python/Parse/Alex.x](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Python/Parse/Alex.x) ([Jikka.Python.Parse.Alex](https://kmyk.github.io/Jikka/haddock/Jikka-Python-Parse-Happy.html))
- Reference: [Modern Compiler Implement in ML](https://www.amazon.co.jp/dp/0521607647)
### Example
For example, consider the following Python code:
```python
def f(a, b) -> int:
return a + b
```
From this code, we get the following syntax tree.
You can obtain this with running a command `$ python3 -c 'import ast; print(ast.dump(ast.parse("def f(a, b) -> int: return a + b")))'`.
```python
Module(
body=[
FunctionDef(
name='f',
args=arguments(
posonlyargs=[],
args=[
arg(arg='a', annotation=None, type_comment=None),
arg(arg='b', annotation=None, type_comment=None)
],
vararg=None,
kwonlyargs=[],
kw_defaults=[],
kwarg=None,
defaults=[]
),
body=[
Return(
value=BinOp(
left=Name(id='a', ctx=Load()),
op=Add(),
right=Name(id='b', ctx=Load()))
)
],
decorator_list=[],
returns=Name(id='int', ctx=Load()),
type_comment=None
)
],
type_ignores=[])
```
## 3. Convert the Python AST to an AST of our restricted Python
Jikka has the complete AST same to the one of [`ast` module](https://docs.python.org/ja/3/library/ast.html) ([data Expr](https://hackage.haskell.org/package/Jikka/docs/Jikka-Python-Language-Expr.html#t:Expr)) after parsing Python.
Then, it removes unnecessary parts from this AST and converts it to a convenient AST for our restricted Python ([data Expr](https://hackage.haskell.org/package/Jikka/docs/Jikka-RestrictedPython-Language-Expr.html#t:Expr)).
- File: [src/Jikka/Python/Convert/ToRestrictedPython.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Python/Convert/ToRestrictedPython.hs) ([Jikka.Python.Convert.ToRestrictedPython](https://kmyk.github.io/Jikka/haddock/Jikka-Python-Convert-ToRestrictedPython.html))
## 4. Preprocess the AST of our restricted Python
Jikka performes the following preprocesses on the AST of our restricted Python:
1. Checking and renaming variable names
1. [Type inference](https://en.wikipedia.org/wiki/Type_inference)
1. Other miscellaneous checking
It uses Hindley/Milner type inference algorithm.
This algorithm reconstructs types with collecting equations about type variables and solving them.
- File: [src/Jikka/RestrictedPython/Convert.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/RestrictedPython/Convert.hs) ([Jikka.RestrictedPython.Convert](https://kmyk.github.io/Jikka/haddock/Jikka-RestrictedPython-Convert.html))
- File: Checking and renaming variable names [src/Jikka/RestrictedPython/Convert/Alpha.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/RestrictedPython/Convert/Alpha.hs) ([Jikka.RestrictedPython.Convert.Alpha](https://kmyk.github.io/Jikka/haddock/Jikka-RestrictedPython-Convert-Alpha.html))
- File: Type inference [src/Jikka/RestrictedPython/Convert/TypeInfer.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/RestrictedPython/Convert/TypeInfer.hs) ([Jikka.RestrictedPython.Convert.TypeInfer](https://kmyk.github.io/Jikka/haddock/Jikka-RestrictedPython-Convert-TypeInfer.html))
- Reference: [Types and Programming Languages](https://www.amazon.co.jp/dp/0262162091)
## 5. Convert the AST of a restricted Python to a AST of our core language
It converts an AST of our restricted Python into an AST of the core language.
For example, Python has assignment statements and `for` loops, whereas the core language (Haskell) does not.
Therefore, all assignment statements are converted to `let` statements and `for` loops are converted to [foldl](https://hackage.haskell.org/package/base/docs/Prelude.html#v:foldl).
For example, consider an AST from the following Python code:
```python
def solve(n: int) -> int:
a = 0
b = 1
for _ in range(n):
c = a + b
a = b
b = c
return a
```
This becomes an AST which corresponds to the following Haskell code:
```haskell
solve :: Int -> Int
solve n =
let a0 = 0
in let b0 = 1
in let (a3, b3) =
foldl (\(a1, b1) _ ->
let c = a1 + b1
in let a2 = b1
in let b2 = c
in (a2, b2)
) (a0, b0) [0..n - 1]
in a3
```
- File: [src/Jikka/RestrictedPython/Convert/ToCore.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/RestrictedPython/Convert/ToCore.hs) ([Jikka.RestrictedPython.Convert.ToCore](https://kmyk.github.io/Jikka/haddock/Jikka-RestrictedPython-Convert-ToCore.html))
## 6. Optimize the AST of our core language
This is the main process of optimizations that Jikka does.
Jikka tries every optimizations we can think of.
Most of them are implemented as [rewrite rules](https://wiki.haskell.org/GHC/Using_rules).
At the moment, optimizations are done in a greedy way, which is looking for possible conversions using rewrite rules and always converts them.
In other words, Jikka doesn't perform searching such as DFS or a beam search.
Doing such complex optimizations are a future task.
- File: [src/Jikka/Core/Convert.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Core/Convert.hs) ([Jikka.Core.Convert](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Convert.html))
- Directory: [src/Jikka/Core/Convert/](https://github.com/kmyk/Jikka/tree/master/src/Jikka/Core/Convert)
### Example: Cumulative Sum
For example, consider the following O(N²) Python code:
```python
def solve(n: int, a: List[int]) -> int:
b = 0
for i in range(n):
b += sum(a[:i])
return b
```
Before the optimization step, this Python code is already converted to the following Haskell code:
```haskell
solve :: Int -> [Int] -> Int
solve n a =
foldl (\b i ->
b + sum (map (\j -> a !! j) [0..i - 1])
) 0 [0..n - 1]
```
At first, a rewrite rule about cumulative sum "replace a sub-expression like `sum (map (\i -> xs !! i) [0..k - 1])` with an expresssion `let ys = scanl (+) 0 xs in ys !! k`" works, and the above code becomes the following code with [scanl](https://hackage.haskell.org/package/base/docs/Prelude.html#v:scanl):
```haskell
solve :: Int -> [Int] -> Int
solve n a =
foldl (\b i ->
let c = scanl (+) 0 a
in b + c !! i
) 0 [0..n - 1]
```
Then a rewrite rule about [foldl](https://hackage.haskell.org/package/base/docs/Prelude.html#v:foldl) and `let` expression "if variables `y` and `x` are not used in a expression `c`, and if a variable `a` is not used in expressions `y0` and `xs`, then replace a sub-expression `foldl (\y x -> let a = c in e) y0 xs` with an expression `let a = c in foldl (\y x -> e) y0 xs`" works. The code becomes the following:
```haskell
solve :: Int -> [Int] -> Int
solve n a =
let c = scanl (+) 0 a
in foldl (\b i ->
b + c !! i
) 0 [0..n - 1]
```
This result Haskell code will the following C++ code with the following steps.
This is O(N).
```c++
int solve(int n, vector<int> a) {
vector<int> c;
c.push_back(0);
for (int i = 0; i < a.size(); ++ i) {
c.push_back(c[i] + a[i]);
}
int b = 0;
for (int i = 0; i < n; ++ i) {
b += c[i];
}
return b;
}
```
- File: [src/Jikka/Core/Convert/CumulativeSum.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Core/Convert/CumulativeSum.hs) ([Jikka.Core.Convert.CumulativeSum](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Convert-CumulativeSum.html))
- File: [src/Jikka/Core/Convert/BubbleLet.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Core/Convert/BubbleLet.hs) ([Jikka.Core.Convert.BubbleLet](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Convert-BubbleLet.html))
### Example of Implementation: Short Cut Fusion
Let's see the implementation of module [Jikka.Core.Convert.ShortCutFusion](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Convert-ShortCutFusion.html) for [Short cut fusion](https://wiki.haskell.org/Short_cut_fusion).
For example, rewrite rules `reduceFoldBuild` is defined as follows [at `v5.1.0.0`](https://github.com/kmyk/Jikka/blob/795726a626ca3653555f6c5c176eb81de26b6d58/src/Jikka/Core/Convert/ShortCutFusion.hs#L162-L183):
```haskell
reduceFoldBuild :: MonadAlpha m => RewriteRule m
reduceFoldBuild =
let return' = return . Just
in RewriteRule $ \_ -> \case
-- reduce `Foldl`
Foldl' _ _ _ init (Nil' _) -> return' init
Foldl' t1 t2 g init (Cons' _ x xs) -> return' $ Foldl' t1 t2 g (App2 g init x) xs
-- reduce `Len`
Len' _ (Nil' _) -> return' Lit0
Len' t (Cons' _ _ xs) -> return' $ Plus' Lit1 (Len' t xs)
Len' _ (Range1' n) -> return' n
-- reduce `At`
At' t (Nil' _) i -> return' $ Bottom' t $ "cannot subscript empty list: index = " ++ formatExpr i
At' t (Cons' _ x xs) i -> return' $ If' t (Equal' IntTy i Lit0) x (At' t xs (Minus' i Lit1))
At' _ (Range1' _) i -> return' i
-- reduce `Elem`
Elem' _ _ (Nil' _) -> return' LitFalse
Elem' t y (Cons' _ x xs) -> return' $ And' (Equal' t x y) (Elem' t y xs)
Elem' _ x (Range1' n) -> return' $ And' (LessEqual' IntTy Lit0 x) (LessThan' IntTy x n)
-- others
Len' t (Build' _ _ base n) -> return' $ Plus' (Len' t base) n
_ -> return Nothing
```
For example, a line `Len' _ (Nil' _) -> return' Lit0` represents a rewrite rule to replace a sub-expression `length []` with an expression `0`.
A line `Len' t (Cons' _ _ xs) -> return' $ Plus' Lit1 (Len' t xs)` represents a rewrite rule to replace a sub-expression `length (cons x xs)` with an expression `1 + length xs`.
Also, this rewrite rule `reduceFoldBuild` is rewritten [at `v5.2.0.0`](https://github.com/kmyk/Jikka/blob/4c0d00ae0cf8e0a0ab17b82bd0a3e31ceca11ace/src/Jikka/Core/Convert/ShortCutFusion.hs#L96-L114) with [Template Haskell](https://wiki.haskell.org/Template_Haskell), which is a macro feature of Haskell (GHC).
The content remains the same and the code is:
```haskell
reduceFoldMap :: MonadAlpha m => RewriteRule m
reduceFoldMap =
mconcat
[ -- reduce `Reversed`
[r| "len/reversed" forall xs. len (reversed xs) = len xs |],
[r| "elem/reversed" forall x xs. elem x (reversed xs) = elem x xs |],
[r| "at/reversed" forall xs i. (reversed xs)[i] = xs[len(xs) - i - 1] |],
-- reduce `Sorted`
[r| "len/sorted" forall xs. len (sorted xs) = len xs |],
[r| "elem/sorted" forall x xs. elem x (sorted xs) = elem x xs |],
-- reduce `Map`
[r| "len/map" forall f xs. len (map f xs) = len xs |],
[r| "at/map" forall f xs i. (map f xs)[i] = f xs[i] |],
[r| "foldl/map" forall g init f xs. foldl g init (map f xs) = foldl (fun y x -> g y (f x)) init xs|],
-- others
[r| "len/setat" forall xs i x. len xs[i <- x] = len xs |],
[r| "len/scanl" forall f init xs. len (scanl f init xs) = len xs + 1 |],
[r| "at/setat" forall xs i x j. xs[i <- x][j] = if i == j then x else xs[j] |]
]
```
- File: [src/Jikka/Core/Convert/ShortCutFusion.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Core/Convert/ShortCutFusion.hs) ([Jikka.Core.Convert.ShortCutFusion](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Convert-ShortCutFusion.html))
### Example of Implementation: Segment Tree
For example which treats data structures, let's see the implementation about segment trees.
The module [Jikka.Core.Convert.SegmentTree](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Convert-SegmentTree.html) has a function `reduceCumulativeSum`.
This function performs a conversion with segment trees, when cumulative sums are used in a [foldl](https://hackage.haskell.org/package/base/docs/Prelude.html#v:foldl) loop, but the target array of cumulative sums are updated in the loop and the cummulative sum cannot be moved out of the loop.
```python
def solve(n: int, a: List[int], q: int, l: List[int], r: List[int]) -> List[int]:
for i in range(q):
# a[l[i]] = sum(a[:r[i])
b = [0]
for j in range(n):
b.append(b[j] + a[j])
a[l[i]] = b[r[i]]
return a
```
The function `reduceCumulativeSum` is implemented as follows [at `v5.1.0.0`](https://github.com/kmyk/Jikka/blob/795726a626ca3653555f6c5c176eb81de26b6d58/src/Jikka/Core/Convert/SegmentTree.hs#L123-L143):
```haskell
-- | `reduceCumulativeSum` converts combinations of cumulative sums and array assignments to segment trees.
reduceCumulativeSum :: (MonadAlpha m, MonadError Error m) => RewriteRule m
reduceCumulativeSum = RewriteRule $ \_ -> \case
-- foldl (fun a i -> setat a index(i) e(a, i)) base incides
Foldl' t1 t2 (Lam2 a _ i _ (SetAt' t (Var a') index e)) base indices | a' == a && a `isUnusedVar` index -> runMaybeT $ do
let sums = listCumulativeSum (Var a) e -- (A)
guard $ not (null sums)
let semigrps = nub (sort (map fst sums))
let ts = t2 : map SegmentTreeTy semigrps
c <- lift $ genVarName a
let proj i = Proj' ts i (Var c)
let e' = replaceWithSegtrees a (zip semigrps (map proj [1 ..])) e -- (B)
guard $ e' /= e
e' <- lift $ substitute a (proj 0) e'
b' <- lift $ genVarName a
let updateSegtrees i semigrp = SegmentTreeSetPoint' semigrp (proj i) index (At' t (Var b') index) -- (C)
let step = Lam2 c (TupleTy ts) i t1 (Let b' t2 (SetAt' t (proj 0) index e') (uncurryApp (Tuple' ts) (Var b' : zipWith updateSegtrees [1 ..] semigrps))) -- (D)
b <- lift $ genVarName a
let base' = Var b : map (\semigrp -> SegmentTreeInitList' semigrp (Var b)) semigrps -- (E)
return $ Let b t2 base (Proj' ts 0 (Foldl' t1 (TupleTy ts) step (uncurryApp (Tuple' ts) base') indices)) -- (F)
_ -> return Nothing
```
At first this function `reduceCumulativeSum` finds expressions in the form of `foldl (\a i -> setat a index(i) e(a, i)) base incides`, with the following entities:
- type `t`
- expression `base` (with type `[t]`)
- expression `indices` (with type `[Int]`)
- variable `a` (with type `[t]`)
- variable `i` (with type `Int`)
- builtin function `setat` (with type `[t] -> Int -> t -> [t]`)
- expression `index(i)` (may contain the variable `i` but doesn't contain the variable `a`. Its type is `Int`.)
- expression `e(a, i)` (may contain the variables `a` and `i`. Its type is `t`.)
At first, the function `reduceCumulativeSum` calls `listCumulativeSum` at (A) to list places where cumulative sums are used in `e(a, i)`.
Then it lists corresponding semigroups from them, and calls `replaceWithSegtrees` at (B) to replace cumulative sums in `e(a, i)` with expressions with segment trees.
It makes an expression to update the segment trees at (C), and makes a function body to give to `foldl` at (D).
Then it makes an initial state `base'` of segment trees at (E) line, and finally returns the result expression at (F).
To use segment trees here, the core language has [`data-structure` types](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:Type) and [builtin functions like `SegmentTreeInitList` `SegmentTreeGetRange` `SegmentTreeSetPoint`](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html#t:Builtin).
For example, the builtin function `SegmentTreeSetPoint` has the type `segment−tree(S) → int → S → segment−tree(S)` for each `S: semigroup`.
Similarly, C++, to which the core language has been translated, has types and builtin functions for segment trees.
- File: [src/Jikka/Core/Convert/ShortCutFusion.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Core/Convert/ShortCutFusion.hs) ([Jikka.Core.Convert.SegmentTree](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Convert-SegmentTree.html))
- File: [src/Jikka/Core/Language/Expr.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/Core/Language/Expr.hs) ([Jikka.Core.Language.Expr](https://kmyk.github.io/Jikka/haddock/Jikka-Core-Language-Expr.html))
- File: [src/Jikka/CPlusPlus/Language/Expr.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/CPlusPlus/Language/Expr.hs) ([Jikka.CPlusPlus.Language.Expr](https://kmyk.github.io/Jikka/haddock/Jikka-CPlusPlus-Language-Expr.html))
## 7. Convert the AST of our core languagee to a C++ AST
After optimizations, Jikka converts the AST of the core language to a C++ AST.
For example, consider the following code:
```haskell
solve :: Int -> Int
solve n =
let a0 = 0
in let b0 = 1
in let (a3, b3) =
foldl (\(a1, b1) _ ->
let c = a1 + b1
in let a2 = b1
in let b2 = c
in (a2, b2)
) (a0, b0) [0..n - 1]
in a3
```
This is converted to the following C++ code:
```c++
int solve(int n) {
int a0 = 0;
int b0 = 1;
pair<int, int> x = make_pair(a0, b0);
for (int i = 0; i < n; ++ i) {
auto [a1, b1] = x;
int c = a1 + b1;
int a2 = b1;
int b2 = c;
x = make_pair(a2, b2);
}
auto [a3, b3] = x;
return a3;
}
```
- File: [src/Jikka/CPlusPlus/Convert/FromCore.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/CPlusPlus/Convert/FromCore.hs) ([Jikka.CPlusPlus.Convert.FromCore](https://kmyk.github.io/Jikka/haddock/Jikka-CPlusPlus-Convert-FromCore.html))
## 8. Postprocess the C++ AST
Jikka performs conversions to eliminate inefficiencies that occur in the conversion from a AST of the core language.
Mainly, it converts unnecessary copies to moves.
It also inserts necessary `#include` statements.
- File: [src/Jikka/CPlusPlus/Convert.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/CPlusPlus/Convert.hs) ([Jikka.CPlusPlus.Convert](https://kmyk.github.io/Jikka/haddock/Jikka-CPlusPlus-Convert.html))
- File: Conversion from copy to move [src/Jikka/CPlusPlus/Convert/MoveSemantics.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/CPlusPlus/Convert/MoveSemantics.hs) ([Jikka.CPlusPlus.Convert.MoveSemantics](https://kmyk.github.io/Jikka/haddock/Jikka-CPlusPlus-Convert-MoveSemantics.html))
### Example
A C++ AST just converted from the core language looks like the following C++ code:
```c++
int solve(int n) {
int a0 = 0;
int b0 = 1;
pair<int, int> x = make_pair(a0, b0);
for (int i = 0; i < n; ++ i) {
auto [a1, b1] = x;
int c = a1 + b1;
int a2 = b1;
int b2 = c;
x = make_pair(a2, b2);
}
auto [a3, b3] = x;
return a3;
}
```
This will be converted into an AST that corresponds to the following C++ code:
```c++
int solve(int n) {
int a = 0;
int b = 1;
for (int i = 0; i < n; ++ i) {
int c = a + b;
a = b;
b = c;
}
return a;
}
```
## 9. Convert the C++ AST to a C++ code
Finally Jikka converts C++ AST to C++ code.
We use the precedence value method for parentheses, as in [Text.Show](https://hackage.haskell.org/package/base/docs/Text-Show.html).
- File: [src/Jikka/CPlusPlus/Format.hs](https://github.com/kmyk/Jikka/blob/master/src/Jikka/CPlusPlus/Format.hs) ([Jikka.CPlusPlus.Format](https://hackage.haskell.org/package/Jikka/docs/Jikka-CPlusPlus-Format.html))
<file_sep>/docs/gh-pages/playground/input.mjs
import * as rts from "./rts.mjs";
import wasm from "./jikka-asterius.wasm.mjs";
import req from "./jikka-asterius.req.mjs";
async function convert(prog) {
const m = await wasm;
const i = await rts.newAsteriusInstance(Object.assign(req, { module: m }));
return await i.exports.convert(prog);
}
async function bundleRuntime(prog) {
const m = await wasm;
const i = await rts.newAsteriusInstance(Object.assign(req, { module: m }));
return await i.exports.bundleRuntime(prog);
}
async function embedOriginalCode(original, prog) {
const m = await wasm;
const i = await rts.newAsteriusInstance(Object.assign(req, { module: m }));
return await i.exports.embedOriginalCode(original, prog);
}
function loadData() {
const req = new XMLHttpRequest();
req.open("GET", "../gallery/data.json", false);
req.send();
if (req.status != 200) {
throw Error(req.statusText);
}
return JSON.parse(req.responseText);
}
window.addEventListener("DOMContentLoaded", function () {
require(["vs/editor/editor.main"], function () {
// make editors
const input = monaco.editor.create(document.getElementById("input"), {
value: "loading...",
language: "python",
});
const output = monaco.editor.create(document.getElementById("output"), {
value: "",
language: "cpp",
});
const bundle = document.getElementById("bundle");
const embed = document.getElementById("embed");
// transpiling periodically
let lastProgram = "";
let lastBundle = false;
let lastEmbed = false;
const sync = async function () {
try {
if (
input.getValue() != lastProgram ||
bundle.checked != lastBundle ||
embed.checked != lastEmbed
) {
lastProgram = input.getValue();
lastBundle = bundle.checked;
lastEmbed = embed.checked;
output.setValue("transpiling...");
let transpiledProgram = await convert(lastProgram);
if (lastBundle) {
transpiledProgram = await bundleRuntime(transpiledProgram);
}
if (lastEmbed) {
transpiledProgram = await embedOriginalCode(
lastProgram,
transpiledProgram
);
}
output.setValue(transpiledProgram);
}
} catch (e) {
console.log(e);
output.setValue(e.toString());
}
setTimeout(sync, 1000);
};
sync();
// make dropdown menu of examples
const dropdown = document.getElementById("dropdown");
function addItem(row) {
const li = document.createElement("li");
const a = document.createElement("a");
a.textContent = row["path"];
a.classList.add("dropdown-item");
a.addEventListener("click", function () {
input.setValue(row["python"]);
});
li.appendChild(a);
dropdown.appendChild(li);
}
const data = loadData();
for (const row of data["examples"]) {
addItem(row);
if (row["path"] == "examples/dp_z-kubaru.py") {
// default
input.setValue(row["python"]);
}
}
for (const row of data["errors"]) {
addItem(row);
}
});
});
<file_sep>/examples/dp_min_mult.py
# https://judge.kimiyuki.net/problem/dp-min-mult
from typing import *
INF = 10 ** 18
def solve(n: int, a: List[int], b: List[int]) -> int:
n = len(a)
dp = [INF for _ in range(n)]
dp[0] = 0
for i in range(1, n):
for j in range(i):
dp[i] = min(dp[i], dp[j] + a[j] * b[i])
return dp[n - 1]
def main() -> None:
n = int(input())
a = list(map(int, input().split()))
assert len(a) == n
b = list(map(int, input().split()))
assert len(b) == n
ans = solve(n, a, b)
print(ans)
if __name__ == "__main__":
main()
<file_sep>/scripts/integration_tests.py
#!/usr/bin/env python3
import argparse
import concurrent.futures
import functools
import glob
import json
import os
import pathlib
import platform
import re
import subprocess
import sys
import tempfile
import threading
from logging import DEBUG, basicConfig, getLogger
from typing import *
logger = getLogger(__name__)
TIMEOUT_FACTOR = 1 if os.environ.get('CI') is None else (5 if platform.system() == 'Linux' else 20)
def compile_cxx(src_path: pathlib.Path, dst_path: pathlib.Path):
CXX = os.environ.get('CXX', 'g++')
CXXFLAGS = ['-std=c++17', '-Wall', '-O2', '-I', str(pathlib.Path('runtime', 'ac-library'))]
command = [CXX, *CXXFLAGS, '-o', str(dst_path), str(src_path)]
subprocess.check_call(command, timeout=5 * TIMEOUT_FACTOR)
@functools.lru_cache(maxsize=None)
def get_metadata() -> Dict[str, str]:
with open(pathlib.Path('examples', 'data', 'METADATA.json')) as fh:
return json.load(fh)
def generate_test_cases_of_library_checker(*, problem_id: str, is_jikka_judge: bool, script: pathlib.Path) -> List[Tuple[pathlib.Path, pathlib.Path]]:
if is_jikka_judge:
directory = pathlib.Path('examples', 'data', 'jikka-judge-problems')
else:
directory = pathlib.Path('examples', 'data', 'library-checker-problems')
# calling library-checker-problems/generate.py
generate_py = directory / 'generate.py'
if not generate_py.exists():
logger.info("%s: %s: %s doesn't exist. checking out...", str(script), problem_id, str(generate_py))
subprocess.check_call(['git', 'submodule', 'init'])
subprocess.check_call(['git', 'submodule', 'update'])
info_tomls = list(directory.glob('**/{}/info.toml'.format(glob.escape(problem_id))))
if len(info_tomls) != 1:
logger.error('%s: %s: failed to find info.toml: %s', str(script), problem_id, info_tomls)
return []
info_toml = info_tomls[0]
try:
subprocess.check_call([sys.executable, str(generate_py), str(info_toml)])
except subprocess.CalledProcessError:
logger.exception("%s: %s: Library Checker's generate.py failed. You may need to run $ pip3 install -r examples/data/library-checker-problems/requirements.txt", str(script), problem_id)
return []
# collect testcases
testcases: List[Tuple[pathlib.Path, pathlib.Path]] = []
for inputcase in sorted((info_toml.parent / 'in').iterdir()): # sorting makes examples first
outputcase = info_toml.parent / 'out' / (inputcase.stem + '.out')
testcases.append((inputcase, outputcase))
return testcases
# TODO: This function should return None instead on errors.
def collect_test_cases(script: pathlib.Path, *, tempdir: pathlib.Path, library_checker_lock: threading.Lock) -> List[Tuple[pathlib.Path, pathlib.Path]]:
testcases: List[Tuple[pathlib.Path, pathlib.Path]] = []
# text files
for path in sorted(pathlib.Path('examples', 'data').iterdir()):
if path.name[:-len(''.join(path.suffixes))] != script.stem:
continue
if path.suffix != '.in':
continue
testcases.append((path, path.with_suffix('.out')))
# using generators
for generator_path in sorted(pathlib.Path('examples', 'data').glob(glob.escape(script.stem) + '*.generator.py')):
_, testset_name, _, _ = generator_path.name.split('.')
for solver_ext in ('.py', '.cpp'):
solver_path = pathlib.Path('examples', 'data', script.stem + '.solver' + solver_ext)
if solver_path.exists():
break
else:
logger.error('%s: failed to find the solver', str(script))
return []
if solver_path.suffix == '.py':
solver_command = [sys.executable, str(solver_path)]
elif solver_path.suffix == '.cpp':
try:
compile_cxx(src_path=solver_path, dst_path=tempdir / 'expected.exe')
except subprocess.SubprocessError as e:
logger.error('%s: failed to compile the expected solver from C++ to executable: %s', str(script), e)
return []
solver_command = [str(tempdir / 'expected.exe')]
else:
assert False
logger.info('%s: generating input cases...', str(script))
for i in range(20):
inputcase = tempdir / "{}.{}-{}.in".format(script.stem, testset_name, i)
outputcase = tempdir / "{}.{}-{}.out".format(script.stem, testset_name, i)
with open(inputcase, 'wb') as fh:
try:
subprocess.check_call([sys.executable, str(generator_path)], stdout=fh, timeout=5 * TIMEOUT_FACTOR)
except subprocess.SubprocessError as e:
logger.error('%s: %s: failed to generate an input of a random case: %s', str(script), str(inputcase), e)
return []
with open(inputcase, 'rb') as fh1:
with open(outputcase, 'wb') as fh2:
try:
subprocess.check_call(solver_command, stdin=fh1, stdout=fh2, timeout=5 * TIMEOUT_FACTOR)
except subprocess.SubprocessError as e:
logger.error('%s: %s: failed to generate an output of a random case: %s', str(script), str(inputcase), e)
return []
testcases.append((inputcase, outputcase))
# resolve alias
metadata = get_metadata()
if script.stem in metadata:
value = metadata[script.stem]
if testcases:
logger.error("%s: there must not be test cases when it uses an alias: %s", str(script), list(map(str, testcases)))
return []
if len(value.split('://')) != 2:
logger.info('%s: invalid item in examples/data/METADATA.json found. It must be like "SCHEME:PROBLEM_ID", but: %s', str(script), value)
return []
scheme, problem_id = value.split('://')
if scheme == 'alias':
testcases.extend(collect_test_cases(script.parent / (problem_id + script.suffix), tempdir=tempdir, library_checker_lock=library_checker_lock))
elif scheme in ('library-checker', 'jikka-judge'):
is_jikka_judge = (scheme == 'jikka-judge')
# Taking lock is needed because multiple scripts may use the same problem.
with library_checker_lock:
testcases.extend(generate_test_cases_of_library_checker(script=script, problem_id=problem_id, is_jikka_judge=is_jikka_judge))
else:
logger.info('%s: invalid item in examples/data/METADATA.json found. The scheme must be "alias", "library-checker" or "jikka-judge", but: %s', str(script), scheme)
return []
return testcases
def run_integration_test(script: pathlib.Path, *, executable: pathlib.Path, library_checker_lock: threading.Lock) -> Optional[str]:
with tempfile.TemporaryDirectory() as tempdir_:
tempdir = pathlib.Path(tempdir_)
logger.info('%s: compiling...', str(script))
with open(tempdir / 'main.cpp', 'wb') as fh:
try:
subprocess.check_call([str(executable), 'convert', str(script)], stdout=fh, timeout=20 * TIMEOUT_FACTOR)
except subprocess.SubprocessError as e:
msg = 'failed to compile from Python to C++: {}'.format(e)
logger.error('%s: %s', str(script), msg)
return msg
try:
compile_cxx(src_path=tempdir / 'main.cpp', dst_path=tempdir / 'a.exe')
except subprocess.SubprocessError as e:
msg = 'failed to compile from C++ to executable: {}'.format(e)
logger.error('%s: %s', str(script), msg)
return msg
with open(script, 'rb') as fh:
code = fh.read()
use_standard_python = bool(re.search(rb'\bdef +main *\(', code)) and not bool(re.search(rb'\bjikka\b', code))
testcases = collect_test_cases(script, tempdir=tempdir, library_checker_lock=library_checker_lock)
if not testcases:
msg = 'no test cases'
logger.error('%s: %s', str(script), msg)
return msg
matrix: List[Tuple[str, List[str]]] = []
if use_standard_python:
matrix.append(('standard Python', [sys.executable, str(script)]))
matrix.append(('restricted Python', [str(executable), 'execute', '--target', 'rpython', str(script)]))
matrix.append(('core', [str(executable), 'execute', '--target', 'core', str(script)]))
matrix.append(('C++', [str(tempdir / 'a.exe')]))
for title, command in matrix:
for inputcase, outputcase in testcases:
with open(outputcase, 'rb') as fh:
expected = fh.read()
logger.info('%s: %s: running as %s...', str(script), str(inputcase), title)
with open(inputcase, 'rb') as fh:
try:
actual = subprocess.check_output(command, stdin=fh, timeout=2 * TIMEOUT_FACTOR if title == 'C++' else 2)
except subprocess.TimeoutExpired as e:
msg = '{}: TLE with {}: {}'.format(str(inputcase), title, e)
if title == 'C++':
logger.error('%s: %s', str(script), msg)
return msg
else:
# Allow TLE on non C++
logger.info('%s: %s', str(script), msg)
break # knockout
except subprocess.SubprocessError as e:
msg = '{}: failed to run as {}: {}'.format(str(inputcase), title, e)
logger.error('%s: %s', str(script), msg)
return msg
if actual.decode().split() != expected.decode().split():
msg = '{}: wrong answer: {} is expected, but actually got {}'.format(str(inputcase), expected.decode().split(), actual.decode().split())
logger.error('%s: %s', str(script), msg)
return msg
logger.info('%s: accepted', str(script))
return None
def run_integration_test_about_error(script: pathlib.Path, *, executable: pathlib.Path) -> Optional[str]:
logger.info('%s: compiling...', str(script))
proc = subprocess.run([str(executable), 'convert', str(script)], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
if proc.returncode == 0:
msg = 'unexpectedly succeeded to compile'
logger.error('%s: %s', str(script), msg)
return msg
actual_lines = proc.stderr.splitlines()
with open(pathlib.Path('examples', 'data', script.stem + '.txt'), 'rb') as fh:
expected_lines = fh.read().splitlines()
for line in expected_lines:
if line not in actual_lines:
msg = "expectedly failed to compile, but didn't print expected error messages: expected = {}, actual = {}".format(expected_lines, actual_lines)
logger.error('%s: %s', str(script), msg)
return msg
logger.info('%s: expectedly failed to compile', str(script))
return None
def get_local_install_root() -> pathlib.Path:
s = subprocess.check_output(['stack', '--system-ghc', 'path', '--local-install-root'])
return pathlib.Path(s.decode().strip())
def find_unused_test_cases() -> List[pathlib.Path]:
scripts = list(pathlib.Path('examples').glob('*.py')) + list(pathlib.Path('examples', 'wip', 'tle').glob('*.py'))
errors = list(pathlib.Path('examples', 'errors').glob('*.py'))
unused = []
for path in pathlib.Path('examples', 'data').glob('*'):
if path.name == 'METADATA.json':
continue
if path.name == 'library-checker-problems':
continue
if path.name == 'jikka-judge-problems':
continue
name = path.name[:-len(''.join(path.suffixes))]
if name not in [script.stem for script in scripts + errors]:
unused.append(path)
continue
if path.suffix == '.in':
pass
elif path.suffix == '.out':
pass
elif path.name.endswith('.generator.py'):
pass
elif path.name.endswith('.generator.cpp'):
pass
elif path.name.endswith('.solver.py'):
pass
elif path.name.endswith('.solver.cpp'):
pass
elif path.suffix == '.txt' and name in [script.stem for script in errors]:
pass
else:
unused.append(path)
continue
for path in unused:
logger.error('unused file: %s', str(path))
return unused
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('-j', '--jobs', type=int, default=os.cpu_count())
parser.add_argument('-k', type=str)
args = parser.parse_args()
try:
import colorlog
except ImportError:
basicConfig(level=DEBUG)
logger.warn('Please install colorlog with $ pip3 install -r scripts/requirements.txt')
else:
formatter = colorlog.ColoredFormatter("%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s")
handler = colorlog.StreamHandler()
handler.setFormatter(formatter)
basicConfig(level=DEBUG, handlers=[handler])
if find_unused_test_cases():
sys.exit(1)
subprocess.check_call(['stack', '--system-ghc', 'build'])
# run tests
executable = get_local_install_root() / 'bin' / 'jikka'
with concurrent.futures.ThreadPoolExecutor(max_workers=args.jobs) as executor:
futures = {}
library_checker_lock = threading.Lock()
for path in list(pathlib.Path('examples').glob('*.py')) + list(pathlib.Path('examples', 'wip', 'tle').glob('*.py')):
if args.k and args.k not in path.name:
continue
futures[path] = executor.submit(run_integration_test, path, executable=executable, library_checker_lock=library_checker_lock)
for path in pathlib.Path('examples', 'errors').glob('*.py'):
if args.k and args.k not in path.name:
continue
futures[path] = executor.submit(run_integration_test_about_error, path, executable=executable)
# report results
succeeded = 0
for path, future in futures.items():
if future.result() is None:
succeeded += 1
else:
# This is the workflow command of GitHub Actions. See https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-error-message
print('::error file={},line=1,col=1::{}'.format(str(path), future.result()))
logger.info('%d/%d tests succeeded', succeeded, len(futures))
if succeeded < len(futures):
sys.exit(1)
if __name__ == '__main__':
main()
<file_sep>/scripts/erase_template_haskell.py
#!/usr/bin/env python3
import argparse
import pathlib
import re
from logging import DEBUG, basicConfig, getLogger
from typing import *
logger = getLogger(__name__)
class Splice(NamedTuple):
path: pathlib.Path
line: int # 0-based
column: int # 0-based
width: int
before: str
after: str
def parse_splice(*, lines: List[str]) -> Splice:
# header
logger.info('%s', lines[0].rstrip())
m = re.match(r'(.*):(\d+):(\d+)-(\d+): Splicing.*', lines[0])
assert m
path = pathlib.Path(m.group(1))
line = int(m.group(2)) - 1
column = int(m.group(3)) - 1
width = int(m.group(4)) - column
# before
before = ''
i = 1
while lines[i].strip() != '======>':
before += lines[i]
i += 1
i += 1
# after
after = ''.join(lines[i:])
return Splice(
path=path,
line=line,
column=column,
width=width,
before=before,
after=after,
)
def parse_splices(*, content: str) -> List[Splice]:
splices: List[Splice] = []
lines = content.splitlines(keepends=True)
l = 0
while l < len(lines):
r = l + 1
while r < len(lines) and lines[r][0].isspace():
r += 1
splices.append(parse_splice(lines=lines[l:r]))
l = r
return splices
def apply_splices(*, code: str, splices: List[Splice]) -> str:
offset = [0]
for line in code.splitlines(keepends=True):
offset.append(offset[-1] + len(line))
buf = list(code)
for splice in reversed(splices):
l = offset[splice.line] + splice.column
r = l + splice.width
# open
delta = 0
while l >= 0 and buf[l] != '[' and buf[l:l + 2] != ['$', '(']:
l -= 1
delta += 1
if delta >= 5 or l == 0:
raise RuntimeError('splicing failed: failed to find opening paren')
if buf[l] == '[':
paren = ']'
elif buf[l:l + 2] == ['$', '(']:
paren = ')'
else:
assert False
# close
delta = 0
while r <= len(buf) and buf[r - 1] != paren:
r += 1
delta += 1
if delta >= 5 or r == len(buf):
raise RuntimeError('splicing failed: failed to find closing paren')
buf[l:r] = splice.after.strip()
return ''.join(buf)
# Before running this script, you need to run $ stack build --ghc-options=-ddump-splices --ghc-options=-ddump-to-file
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('--dist-directory', type=pathlib.Path, default=pathlib.Path('.stack-work', 'dist'))
parser.add_argument('--source-directory', type=pathlib.Path, default=pathlib.Path('src'))
parser.add_argument('--rewrite', action='store_true')
parser.add_argument('--match')
args = parser.parse_args()
basicConfig(level=DEBUG)
for dump_splices_path in args.dist_directory.glob('**/*.dump-splices'):
if args.match and not re.search(args.match, str(dump_splices_path)):
continue
with open(dump_splices_path) as fh:
content = fh.read()
splices = parse_splices(content=content)
with open(splices[0].path) as fh:
code = fh.read()
code = apply_splices(code=code, splices=splices)
if args.rewrite:
logger.info('rewrite %s', str(splices[0].path))
with open(splices[0].path, 'w') as fh:
fh.write(code)
else:
print(code)
if __name__ == '__main__':
main()
<file_sep>/examples/data/abc208_b.solver.cpp
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>
#define REP(i, n) for (int i = 0; (i) < (int)(n); ++(i))
#define REP3(i, m, n) for (int i = (m); (i) < (int)(n); ++(i))
#define REP_R(i, n) for (int i = (int)(n)-1; (i) >= 0; --(i))
#define REP3R(i, m, n) for (int i = (int)(n)-1; (i) >= (int)(m); --(i))
#define ALL(x) ::std::begin(x), ::std::end(x)
using namespace std;
int64_t solve(int64_t P) {
vector<int64_t> cs;
int64_t e = 1;
int64_t ans = 0;
for (int i = 1; i <= 10; ++i) {
e *= i;
cs.push_back(e);
}
reverse(cs.begin(), cs.end());
for (const auto &c : cs) {
ans += P / c;
P -= P / c * c;
}
return ans;
}
// generated by oj-template v4.8.1
// (https://github.com/online-judge-tools/template-generator)
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int64_t P;
std::cin >> P;
auto ans = solve(P);
std::cout << ans << '\n';
return 0;
}
| b2d9f482d5132269f59d407c4de25e6f5631f24c | [
"Markdown",
"JavaScript",
"Python",
"Text",
"C++",
"Shell"
] | 24 | C++ | Yang-33/Jikka | 6a19dd8ee3a283f7164737520a0d70e5597d089d | 818e8ba7c784929f6bc44f077c81209561977049 |
refs/heads/master | <repo_name>Ritusan/koa2-learn<file_sep>/middleware/koa-pv.js
// ctx:进入app中会有一个对象,这个对象会挂载着所有的信息,信息包括两方面:request和response,是全局的对象,在整个app中是能拿到的
function pv(ctx){
// path:表明当前的页面路径
global.console.log('pv',ctx.path)
}
module.exports = function(){
return async function(ctx,next){
pv(ctx)
// 当前中间件处理完毕,请交给下一个中间件处理
await next()
}
}<file_sep>/routes/users.js
const router = require('koa-router')()
// 引入模型
const Person = require('../dbs/models/person')
// 带有前缀的路由,用于把路由分模块写
router.prefix('/users')
router.get('/', function (ctx, next) {
ctx.body = 'this is a users response!'
})
router.get('/bar', function (ctx, next) {
ctx.body = 'this is a users/bar response'
})
// 新增一个接口,写入
router.post('/addPerson', async function(ctx,next){
console.log(ctx.request.body)
console.log(ctx.params)
// console.log(ctx.request.body.name)
// 给model新建一个实例
const person = new Person({
// 接口中需要传的字段,post对应的是request.body
name: ctx.request.body.name,
age : ctx.request.body.name
})
console.log(ctx.request.body)
// ctx.body = ctx.request.body
// console.log(ctx.query)
// console.log(ctx.request)
let code
// 捕获错误
try {
// 通过save()方法做了一个增添数据的行为,save()是model中已经定义好了的
await person.save()
await console.log(ctx.request.body)
// 如果没有异常
code = 0
} catch (error) {
// 如果有异常
code = -1
}
// 直接返回code
ctx.body = {
code: code
}
})
// 读的操作
router.post('/getPerson',async function(ctx){
const result = await Person.findOne({
name: ctx.request.body.name
})
const results = await Person.find({
name: ctx.request.body.name
})
global.console.log(ctx.request)
global.console.log(ctx.request.body)
global.console.log(ctx.request.body.name)
ctx.body = {
code: 0,
result,
results
}
})
module.exports = router
<file_sep>/routes/index.js
const router = require('koa-router')()
// 定义路径名称和路径对应的操作过程
router.get('/', async (ctx, next) => {
global.console.log('index2')
// 只要访问首页,就种一个cookie,cookie的名称是pvid
// 写入cookie
ctx.cookies.set('pvid',Math.random())
// render:渲染页面(页面类型)
await ctx.render('index', {
title: 'Hello Koa 2!'
})
})
router.get('/string', async (ctx, next) => {
// 返回接口的(接口类型)
ctx.body = 'koa2 string'
})
router.get('/json', async (ctx, next) => {
// json类型
ctx.body = {
title: 'koa2 json',
// 读cookie
cookie: ctx.cookies.get('pvid')
}
})
module.exports = router
| 08e380f4a0a53d66ae71da16392aa634e4261f9b | [
"JavaScript"
] | 3 | JavaScript | Ritusan/koa2-learn | c7b342ff6a2f755faef694ba87a3c0e72d5e9d1f | 92884bcae7697ce630700dde1150eacc35bae5da |
refs/heads/master | <repo_name>leixw0102/smart-travel<file_sep>/smart-app/src/main/java/com/smart/controller/SellerController.java
package com.smart.controller;/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.smart.common.Page;
import com.smart.common.ResponseMsg;
import com.smart.model.CompanyInfo;
import com.smart.model.SellerInfo;
import com.smart.service.SellerService;
import com.smart.vo.SellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/14
* Time: 10:00
*/
@Controller
@RequestMapping("/1.0/seller/*")
public class SellerController extends BaseController{
@Autowired
private SellerService sellerService;
@RequestMapping("code/{id}/{type}")
public String getCode(HttpServletRequest request,HttpServletResponse response,@PathVariable Long id,@PathVariable Integer type){
try {
JSONObject ob = sellerService.getCode(id,type);
request.setAttribute("abcd",ob.toJSONString());
} catch (Exception e) {
logger.error("error1",e);
}
return "abc";
}
@RequestMapping("getAccountLists")
public String getHome(HttpServletRequest request,HttpServletResponse response,@RequestParam Integer page) throws Exception{
request.setAttribute("msgs",sellerService.getSellers(page));
return "companyAcountManager";
}
@RequestMapping("query/{page}")
@ResponseBody
public com.smart.common.ResponseBody get(@PathVariable Integer page,@RequestParam(required = false) String name){
try {
return sellerService.getSellers(page,name);
} catch (Exception e) {
logger.error("error!,",e);
return new ResponseMsg("12","error!"+e.getLocalizedMessage());
}
}
@RequestMapping("updateSellerUser")
@ResponseBody
public com.smart.common.ResponseBody updateSeller(HttpServletRequest request,HttpServletResponse response,SellerVo info) {
logger.info(info.toString());
if(info.getId()==null){
return new ResponseMsg("1","更新对象ID不存在");
}
if(info.verfiy()){
return new ResponseMsg("1","参数不能为空或者2次密码输入不正确");
};
try{
long id=sellerService.updateSeller(info);
if(id>0){
request.getSession().setAttribute("userType", info.getType());
request.getSession().setAttribute("addUserId",id);
return new ResponseMsg();
};
return new ResponseMsg("1","插入失败");
}catch (Exception e){
logger.error("error!",e);
return new ResponseMsg("1","插入失败,"+e.getMessage());
}
}
@RequestMapping("addUser")
@ResponseBody
public com.smart.common.ResponseBody addSeller(HttpServletRequest request,HttpServletResponse response,SellerVo info) throws Exception{
logger.info(info.toString());
if(info.verfiy()){
return new ResponseMsg("1","参数不能为空或者2次密码输入不正确");
};
try{
if(sellerService.fingByPhone(info)){
return new ResponseMsg("1","该用户已经存在"+info.getUserName());
};
long id=sellerService.addSeller(info);
if(id>0){
request.getSession().setAttribute("userType", info.getType());
request.getSession().setAttribute("addUserId",id);
return new ResponseMsg();
};
return new ResponseMsg("1","插入失败");
}catch (Exception e){
logger.error("error!",e);
return new ResponseMsg("1","插入失败,"+e.getMessage());
}
// return"redirect:getAccountLists";
}
@RequestMapping("addCompany")
@ResponseBody
public com.smart.common.ResponseBody addCompany(HttpServletRequest request,HttpServletResponse response,CompanyInfo info) throws Exception{
logger.info(info.toString());
if(!info.verfiy()){
return new ResponseMsg("1","error!");
};
try{
// info.setType(Integer.parseInt(request.getSession().getAttribute("userType").toString()));
if(sellerService.addCompany(info)>0){
return new ResponseMsg();
};
return new ResponseMsg("1","插入失败");
}catch (Exception e){
logger.error("error!",e);
return new ResponseMsg("1","插入失败,"+e.getMessage());
}
// return"redirect:getAccountLists";
}
@RequestMapping("updateCompanyInfo")
@ResponseBody
public com.smart.common.ResponseBody updateCompany(HttpServletRequest request,HttpServletResponse response,CompanyInfo info){
logger.info(info.toString());
if(!info.verfiy()){
return new ResponseMsg("1","error!");
};
try{
// info.setType(Integer.parseInt(request.getSession().getAttribute("userType").toString()));
if(sellerService.updateCompany(info)>0){
return new ResponseMsg();
};
return new ResponseMsg("1","插入失败");
}catch (Exception e){
logger.error("error!",e);
return new ResponseMsg("1","插入失败,"+e.getMessage());
}
}
@RequestMapping("addPage")
public String getAdd(HttpServletRequest request,HttpServletResponse response) throws Exception{
// Map<Integer,Map<Integer,String>> type=sellerService.getTypes();
// request.setAttribute("types",type);
return "companyAcountManager-addUser";
}
@RequestMapping("addCompanyPage")
public String getAddCompany(HttpServletRequest request,HttpServletResponse response) throws Exception {
Integer type = Integer.parseInt(request.getSession().getAttribute("userType").toString());
Map<Integer,String> maps=sellerService.getTypes(type);
request.setAttribute("secondaryTypes",maps);
return "companyAcountManager-addCompany";
}
@RequestMapping("main")
public String getHomeSystem(){
return "main";
}
@RequestMapping("editSeller/{id}")
public ModelAndView getSellerVo(@PathVariable Long id){
try{
SellerVo vo = sellerService.getUserById(id);
logger.info(vo.toString());
Map<String,String> maps = getMaps(vo);
return new ModelAndView("editUserInfo",maps);
}catch (Exception e){
logger.error("error",e);
return new ModelAndView("editUserInfo");
}
}
@RequestMapping("editCompanyPage/{id}/{type}")
public ModelAndView getCompanyUpdatePage(@PathVariable Long id,@PathVariable Integer type){
try{
CompanyInfo vo = sellerService.getCompanyByUserId(id,type);
if(null == vo ){
vo = new CompanyInfo();
vo.setUserId(id);
vo.setType(type);
Long companyId=sellerService.addCompany(vo);
vo.setId(companyId);
}
// Map<String,String> maps = getMapsByCompany(vo);
Map<String,Object> maps = Maps.newHashMap();
Map types = sellerService.getTypes(type);
maps.put("user",vo);
maps.put("secondaryTypeInfo",types);
return new ModelAndView("editCompanyInfo",maps);
}catch (Exception e){
logger.error("error",e);
return new ModelAndView("editCompanyInfo");
}
}
private Map<String, String> getMapsByCompany(CompanyInfo vo) {
return null; //To change body of created methods use File | Settings | File Templates.
}
private Map<String, String> getMaps(SellerVo vo) {
Map<String,String> maps = Maps.newHashMap();
maps.put("userName",vo.getUserName());
maps.put("pwd",vo.getPwd());
maps.put("pwd2",vo.getPwd2());
maps.put("type",vo.getType());
maps.put("free",vo.getFree()+"");
maps.put("remark",vo.getRemark());
maps.put("id",vo.getId()+"");
return maps;
}
}
<file_sep>/smart-service/src/main/java/com/smart/model/MapInfo.java
package com.smart.model;/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/30
* Time: 14:58
*/
public class MapInfo {
private String x;
private String y;
private String info;
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
}
<file_sep>/smart-app/src/main/java/com/smart/controller/FinanceController.java
package com.smart.controller;/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
import com.alibaba.fastjson.JSON;
import com.smart.common.Page;
import com.smart.common.ResponseMsg;
import com.smart.model.Apply;
import com.smart.service.FinanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/16
* Time: 20:01
*/
@Controller
@RequestMapping("/1.0/finance/*")
public class FinanceController extends BaseController {
@Autowired
private FinanceService financeService;
@RequestMapping("confirm/{applyId}")
@ResponseBody
public ResponseMsg confirm(HttpServletRequest request,HttpServletResponse response,@PathVariable Long applyId){
try{
if(financeService.confirm(applyId)){
return new ResponseMsg();
}
return new ResponseMsg("1005","兑现失败,请联系维护人员");
}catch (Exception e){
logger.error("confirm error!",e);
return new ResponseMsg("1004",e.getMessage());
}
}
@RequestMapping("refuse/{applyId}")
@ResponseBody
public ResponseMsg refuse(@PathVariable Long applyId){
try{
if(financeService.confirm(applyId)){
return new ResponseMsg();
}
return new ResponseMsg("1005","兑现失败,请联系维护人员");
}catch (Exception e){
logger.error("confirm error!",e);
return new ResponseMsg("1004",e.getMessage());
}
}
@RequestMapping("getHomeList/{type}/{page}")
public String getList(HttpServletRequest request,HttpServletResponse response,@PathVariable Integer page,
@RequestParam(required = false) String from,@RequestParam(required = false) String to,
@PathVariable Integer type){
try{
Page<Apply> applies= financeService.search(page,from,to,type);
request.setAttribute("appliesList",applies);
return "finace";
}catch (Exception e){
throw new ApiException(new ResponseMsg("1004",e.getMessage()));
}
}
@RequestMapping("getList/{type}/{page}")
@ResponseBody
public Page getResultList(HttpServletRequest request,HttpServletResponse response,@PathVariable Integer page,
@RequestParam(required = false) String from,@RequestParam(required = false) String to,
@PathVariable Integer type){
try{
return financeService.search(page,from,to,type);
}catch (Exception e){
throw new ApiException(new ResponseMsg("1004",e.getMessage()));
}
}
public static void main(String []args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
FinanceService financeService1=context.getBean(FinanceService.class);
Page page=financeService1.search(1,"2015-07-09","2015-07-10",2);
System.out.println(JSON.toJSONString(page));
}
}
<file_sep>/smart-app/src/main/java/com/smart/ui/servlet/CategoryManagerAction.java
package com.smart.ui.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CategoryManagerAction
*/
public class CategoryManagerAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CategoryManagerAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String type = request.getParameter("type");
String phoneNumber = request.getParameter("phoneNumber");
if(type != null && (Integer.parseInt("0") == Integer.parseInt(type))){
return;
}else if(type != null && (Integer.parseInt("1") == Integer.parseInt(type))){//��ת�̻���Ϣҳ��
//request.getRequestDispatcher("/page/companyAcountManager-addCompany.jsp").forward(request, response);
return;
}else if(type != null && (Integer.parseInt("2") == Integer.parseInt(type))){//�����û���Ϣ
//request.getRequestDispatcher("/page/companyAcountManager-addCompany.jsp").forward(request, response);
return;
}
RequestDispatcher dispatcher=request.getRequestDispatcher("/finace.jsp");
dispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
<file_sep>/smart-service/src/main/java/com/smart/vo/SellerVo.java
package com.smart.vo;/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
import com.google.common.base.Strings;
import java.util.Date;
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/14
* Time: 16:59
*/
public class SellerVo {
@Override
public String toString() {
return "SellerVo{" +
"contactName='" + contactName + '\'' +
", userName='" + userName + '\'' +
", pwd='" + pwd + '\'' +
", pwd2='" + <PASSWORD> + '\'' +
", id=" + id +
", type='" + type + '\'' +
", sellerName='" + sellerName + '\'' +
", createTime=" + createTime +
", free=" + free +
", remark='" + remark + '\'' +
", grade=" + grade +
'}';
}
private String userName;
private String pwd;
private String pwd2;
public String getPwd2() {
return pwd2;
}
public void setPwd2(String pwd2) {
this.pwd2 = pwd2;
}
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
private String type;
private String sellerName;
private Date createTime;
private Float free;
private String remark;
private String contactName;
private Double grade;
public Float getFree() {
return free;
}
public void setFree(Float free) {
this.free = free;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Double getGrade() {
return grade;
}
public void setGrade(Double grade) {
this.grade = grade;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public boolean verfiy() {
return Strings.isNullOrEmpty(this.getUserName())||Strings.isNullOrEmpty(this.getPwd())||!pwd.equals(pwd2) ;
}
}
<file_sep>/smart-service/src/main/java/com/smart/dao/OrderDao.java
/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
package com.smart.dao;
import com.smart.model.OrderInfo;
import com.smart.model.UserClientInfo;
import java.util.List;
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/19
* Time: 17:23
*/
public interface OrderDao {
Long count(Long id, String from, String to, Integer type, Integer orderType) throws Exception;
List<OrderInfo> search(Long id, Integer page, String from, String to, Integer type, Integer orderType) throws Exception;
Long countUserInfos() throws Exception;
List<UserClientInfo> getUsersByPage(Integer page) throws Exception;
boolean deleteClientUserById(Long id) throws Exception;
String[] getApplyTime(Long id) throws Exception;
int getTypeById(Long id) throws Exception;
Long count(Long id, String[] times, int type, int type1, int orderType) throws Exception;
List<OrderInfo> search(Long id, Integer page, String[] times, int type, int type1, int orderType) throws Exception;
Long count(String from, String to, Integer type, Integer orderType, String name) throws Exception;
List<OrderInfo> search(Integer page, String from, String to, Integer type, Integer orderType, String name) throws Exception;
}
<file_sep>/smart-service/src/main/java/com/smart/service/impl/UserServiceImpl.java
package com.smart.service.impl;
import com.smart.common.Page;
import com.smart.common.DateUtils;
import com.smart.common.ResponseBody;
import com.smart.common.ResponseMsg;
import com.smart.dao.UserDao;
import com.smart.model.*;
import com.smart.service.UserService;
import com.smart.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
public UserInfo sellerLogin(String user, String passwd) throws Exception {
return userDao.sellerLogin(user,passwd); //To change body of implemented methods use File | Settings | File Templates.
}
public boolean isValid(UserVo vo,Date date) throws Exception {
Long id= userDao.isValid(vo.getUserName(),vo.getRole(),simpleDateFormat.format(vo.getUseTime())); //To change body of implemented methods use File | Settings | File Templates.
if(null == id){
return false;
}
Date newDate = DateUtils.getDate(vo.getUseTime(),30);
if(date.getTime()-newDate.getTime()>0){
return false;
}
userDao.updateTime(id,simpleDateFormat.format(date)) ;
return true;
}
@Override
public boolean updateUseTime(Long id,Date use) throws Exception {
return userDao.updateTime(id,simpleDateFormat.format(use)); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Page userNewsList(int pageNumber, int pageSize)
throws Exception {
// List<NewsInfo>
Page<NewsInfo> page = new Page<NewsInfo>() {
@Override
protected String listAlias() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
};
page.setPageNumber(pageNumber);
page.setPageSize(10);
Long total = userDao.count("", "");
List<NewsInfo> list = userDao.userNewsList(pageNumber, pageSize);
page.setCount(total);
page.setMessages(list);
return page; //To change
// return userDao.userNewsList( pageNumber, pageSize);
}
@Override
public NewsInfo userNewsDetail(int id) throws Exception {
// TODO Auto-generated method stub
return userDao.userNewsDetail(id);
}
@Override
public boolean create(String join, String title, String content, String abs) throws Exception {
return userDao.create(join, title, content, abs); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Page<CashUserInfo> searchCashUser(int i, int i1) throws Exception {
Page<CashUserInfo> infos = new Page<CashUserInfo>() {
@Override
protected String listAlias() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
};
Long total = userDao.countCashUser();
infos.setCount(total);
List<CashUserInfo> users= userDao.searchCashUser(i,i1); //To change body of implemented methods use File | Settings | File Templates.
infos.setMessages(users);
infos.setPageSize(i1);
infos.setPageNumber(i);
return infos;
}
@Override
public CashUserInfo searchFinanceUser(CashUserInfo info) throws Exception {
return userDao.searchFinanceUser(info); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean saveFinanceUser(CashUserInfo info) throws Exception {
return userDao.saveFinaceUser(info); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean deleteById(Long id) throws Exception {
return userDao.deleteById(id); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean updateById(Long id, String old, String newPwd) throws Exception {
return userDao.updateById(id,old,newPwd); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public CashUserInfo findUserByIdAndPwd(Long id, String old) throws Exception {
return userDao.findUserByIdAndPwd(id,old); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Page<NewsUserInfo> searchNewsUser(Integer page, int i) throws Exception {
Page<NewsUserInfo> infos = new Page<NewsUserInfo>() {
@Override
protected String listAlias() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
};
Long total = userDao.countNewsUser();
infos.setCount(total);
List<NewsUserInfo> users= userDao.searchNewsUser(page,i); //To change body of implemented methods use File | Settings | File Templates.
infos.setMessages(users);
infos.setPageSize(page);
infos.setPageNumber(i);
return infos; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean saveNewsUser(NewsUserInfo info) throws Exception {
return userDao.saveNewsUser(info); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public NewsUserInfo searchNewsUser(NewsUserInfo info) throws Exception {
return userDao.searchNewsUser(info); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ResponseBody userNewsList(Long page1, int i, String time,String to) throws Exception {
Page<NewsInfo> page = new Page<NewsInfo>() {
@Override
protected String listAlias() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
};
page.setPageNumber(i);
page.setPageSize(10);
Long total = userDao.count(time,to);
List<NewsInfo> list = userDao.userNewsList(page1, i,time,to);
page.setCount(total);
page.setMessages(list);
return page; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public ResponseMsg view(Long id) throws Exception {
ResponseMsg msg = new ResponseMsg();
NewsInfo info = userDao.view(id);
msg.setInfo(info);
return msg; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean update(String join, String title, String content, String abs, Long id) throws Exception {
return userDao.update(join,title,content,abs,id); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean deleteNewsById(Long id) throws Exception {
return userDao.deleteNewsById(id); //To change body of implemented methods use File | Settings | File Templates.
}
}
<file_sep>/smart-service/src/main/java/com/smart/model/CashUserInfo.java
package com.smart.model;/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
import com.google.common.base.Strings;
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/22
* Time: 16:16
*/
public class CashUserInfo {
private long id;
private String phone;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
private String userName;
private String pwd;
private String pwd2;
private String contactName;
private String mark;
public String getContactName() {
return contactName;
}
public boolean check(){
return Strings.isNullOrEmpty(userName) || Strings.isNullOrEmpty(pwd) || Strings.isNullOrEmpty(pwd2) || Strings.isNullOrEmpty(contactName) || !pwd.equals(pwd2);
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getPwd2() {
return pwd2;
}
public void setPwd2(String pwd2) {
this.pwd2 = pwd2;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "CashUserInfo{" +
"contactName='" + contactName + '\'' +
", id=" + id +
", userName='" + userName + '\'' +
", pwd='" + pwd + '\'' +
", pwd2='" + <PASSWORD> + '\'' +
", mark='" + mark + '\'' +
'}';
}
}
<file_sep>/smart-service/src/main/java/com/smart/model/CompanyInfo.java
package com.smart.model;/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/19
* Time: 14:00
*/
public class CompanyInfo {
private Integer secondaryType;
private String name;
private String contactName;
private Double grade;
private Long userId;
private Integer type;
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
return "CompanyInfo{" +
"contactName='" + contactName + '\'' +
", secondaryType=" + secondaryType +
", name='" + name + '\'' +
", grade=" + grade +
", userId=" + userId +
", type=" + type +
'}';
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public Double getGrade() {
return grade;
}
public void setGrade(Double grade) {
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSecondaryType() {
return secondaryType;
}
public void setSecondaryType(Integer secondaryType) {
this.secondaryType = secondaryType;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public boolean verfiy() {
return true;
}
}
<file_sep>/smart-app/src/main/java/com/smart/controller/UserController.java
package com.smart.controller;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.NameFilter;
import com.google.common.base.Strings;
import com.smart.common.Page;
import com.smart.common.ResponseConstantCode;
import com.smart.common.ResponseMsg;
import com.smart.model.Apply;
import com.smart.model.CashUserInfo;
import com.smart.model.NewsUserInfo;
import com.smart.model.UserInfo;
import com.smart.service.UserService;
import com.smart.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/1.0/user/*")
public class UserController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@RequestMapping("addNewsUser")
@ResponseBody
public com.smart.common.ResponseBody addNewsUser(HttpServletResponse response,HttpServletRequest request,NewsUserInfo info){
if(info.check()){
throw new ApiException(new ResponseMsg("10","填写信息错误"));
}
try{
NewsUserInfo find= userService.searchNewsUser(info);
if(null != find){
return new ResponseMsg("1","用户已经存在");
}
if(userService.saveNewsUser(info)){
return new ResponseMsg();
};
return new ResponseMsg("1","插入失败");
}catch (Exception e){
logger.error("add finance user error!" ,e);
return new ResponseMsg("1","插入失败"+e.getMessage());
}
}
@RequestMapping("addFinanceUser")
@ResponseBody
public com.smart.common.ResponseBody addUser(HttpServletResponse response,HttpServletRequest request,CashUserInfo info){
if(info.check()){
throw new ApiException(new ResponseMsg("10","填写信息错误"));
}
try{
CashUserInfo find= userService.searchFinanceUser(info);
if(null != find){
return new ResponseMsg("1","用户已经存在");
}
if(userService.saveFinanceUser(info)){
return new ResponseMsg();
};
return new ResponseMsg("1","插入失败");
}catch (Exception e){
logger.error("add finance user error!" ,e);
return new ResponseMsg("1","插入失败"+e.getMessage());
}
}
@RequestMapping("getCashHome")
public String getCashUserHome() {
return "finaceAcountManager";
}
@RequestMapping("cashUsers/{page}")
@ResponseBody
public Page<CashUserInfo> getCashUsers(HttpServletResponse response,HttpServletRequest request,@PathVariable Integer page){
try {
Page<CashUserInfo> financeUsers=userService.searchCashUser(page,20);
return financeUsers;
// request.setAttribute("financeUsers",financeUsers);
// return "finaceAccountManager" ;
} catch (Exception e) {
throw new ApiException(new ResponseMsg(ResponseConstantCode.DATA_CANT_FOUND_CODE,ResponseConstantCode.DATA_CANT_FOUND_DESC));
}
}
@RequestMapping("newsUsers/{page}")
@ResponseBody
public Page<NewsUserInfo> getNewsUsers(HttpServletResponse response,HttpServletRequest request,@PathVariable Integer page){
try {
Page<NewsUserInfo> financeUsers=userService.searchNewsUser(page, 20);
return financeUsers;
// request.setAttribute("financeUsers",financeUsers);
// return "finaceAccountManager" ;
} catch (Exception e) {
throw new ApiException(new ResponseMsg(ResponseConstantCode.DATA_CANT_FOUND_CODE,ResponseConstantCode.DATA_CANT_FOUND_DESC));
}
}
@RequestMapping(value = "login")
@ResponseBody
public com.smart.common.ResponseBody sellerLogin(HttpServletRequest request,HttpServletResponse response,@RequestParam String userName,@RequestParam String pwd) throws ServletException, IOException {
try {
//String token = userService.buyerLogin( username, password,mac) ;
if (Strings.isNullOrEmpty(userName)
|| Strings.isNullOrEmpty(pwd)
) {
throw new ApiException(ResponseMsg.ILLEGAL_PARAMETER_MSG);
}else{
UserInfo userInfo = userService.sellerLogin(userName, pwd) ;
if (userInfo == null){
return new ResponseMsg(ResponseConstantCode.DATA_CANT_FOUND_CODE,ResponseConstantCode.DATA_CANT_FOUND_DESC);
}else{
request.getSession().setAttribute("userSessionId",userInfo.getId()+"-"+userInfo.getRole()+"-"+userInfo.getUserName());
// Date use=new Date();
// response.setHeader("user", JSON.toJSONString(new UserVo(3,"3",getLong(use))));
// userService.updateUseTime(userInfo.getId(),use);
ResponseMsg<String> msg=new ResponseMsg<String>();
int type = userInfo.getRole();
if(type==1){
msg.setInfo("/1.0/seller/main");
}else if(type==2){
msg.setInfo("/publicNews.jsp");
} else if(type==3){
msg.setInfo("/finace-main.jsp");
}
return msg;
}
}
// logger.info("影人图片查询结束,返回终端数据;");
} catch (Exception e) {
throw new ApiException(e);
}
}
@RequestMapping("financeDeleteById/{id}")
@ResponseBody
public com.smart.common.ResponseBody deleteFinance(@PathVariable Long id){
try{
if(userService.deleteById(id)){
return new ResponseMsg();
}
return new ResponseMsg("1","删除失败");
}catch (Exception e){
return new ResponseMsg("1","删除失败");
}
}
@RequestMapping("newsDeleteById/{id}")
@ResponseBody
public com.smart.common.ResponseBody deleteUser(@PathVariable Long id){
try{
if(userService.deleteById(id)){
return new ResponseMsg();
}
return new ResponseMsg("1","删除失败");
}catch (Exception e){
return new ResponseMsg("1","删除失败");
}
}
@RequestMapping("updatePwd/{id}")
@ResponseBody
public com.smart.common.ResponseBody updatePwd(@PathVariable Long id,@RequestParam String old,@RequestParam String newPwd) {
try{
CashUserInfo info=userService.findUserByIdAndPwd(id,old);
if(null == info){
return new ResponseMsg("1","原始密码输入错误");
}
if(userService.updateById(id,old,newPwd)){
return new ResponseMsg();
}
return new ResponseMsg("1","更新失败");
}catch (Exception e){
return new ResponseMsg("1","更新失败");
}
}
@RequestMapping("getUpdatePwdPage/{id}")
public String getReWritePage(HttpServletRequest request,HttpServletResponse response,@PathVariable Long id){
request.setAttribute("financeUpdateId",id);
return "pwdRewrite";
}
@RequestMapping("logout")
@ResponseBody
public ResponseMsg logout(HttpServletRequest request,HttpServletResponse response){
HttpSession session=request.getSession(false);
session.removeAttribute("userSessionId");
ResponseMsg<String> msg=new ResponseMsg<String>();
msg.setInfo("login.jsp");
return msg;
}
@RequestMapping("getOrderMsgPage/{id}")
public String getOrderMsgPage(HttpServletRequest request,HttpServletResponse response,@PathVariable Long id){
request.setAttribute("userForOrderId",id);
return "test";
}
}
<file_sep>/smart-service/src/main/java/com/smart/model/Apply.java
package com.smart.model;
import com.alibaba.fastjson.JSONObject;
import java.util.Date;
public class Apply {
private long id;
private long userId;
private String applyDesc;
private String name;
private Date time;
private Float money;
private String type;
private String contactName;
private String phoneNumber;
private Float serviceCharge;
private Date finishTime;
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getFinishTime() {
return finishTime;
}
public void setFinishTime(Date finishTime) {
this.finishTime = finishTime;
}
private int status;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getApplyDesc() {
return applyDesc;
}
public void setApplyDesc(String applyDesc) {
this.applyDesc = applyDesc;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
public Float getServiceCharge() {
return serviceCharge;
}
public void setServiceCharge(Float serviceCharge) {
this.serviceCharge = serviceCharge;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static void main(String[]args){
JSONObject object = new JSONObject();
object.put("abc","sdfdsfsd");
System.out.println(object.toJSONString());
}
}
<file_sep>/smart-service/src/main/java/com/smart/dao/impl/UserDaoImpl.java
package com.smart.dao.impl;
import com.google.common.base.Strings;
import com.smart.dao.UserDao;
import com.smart.model.CashUserInfo;
import com.smart.model.NewsUserInfo;
import com.smart.model.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.smart.model.NewsInfo;
import java.util.List;
@Transactional(readOnly = true)
@Repository
public class UserDaoImpl extends BaseDaoImpl implements UserDao {
private static Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
@Override
public UserInfo sellerLogin(String user, String passwd) throws Exception {
return super.getJdbcTemplate().query("select * from t_user where user_name='"+user+"' and pwd = '"+passwd+"'",new ResultSetExtractor<UserInfo>() {
@Override
public UserInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
if(rs.next()){
UserInfo info=new UserInfo();
info.setAlias(rs.getString("alias"));
info.setId(rs.getLong("id"));
info.setMark(rs.getString("mark"));
info.setPhone(rs.getString("phone"));
info.setRole(rs.getInt("role"));
info.setPwd(rs.getString("pwd"));
info.setUseTime(rs.getDate("use_time"));
info.setUserName(rs.getString("user_name"));
return info;
}
return null;
}
});
}
@Override
public Long isValid(String userName, Integer role, String format) throws Exception {
Long id= super.jdbcTemplate.queryForLong("select id from t_user where t_user where user_name='"+userName+"' and role='"+role+"' and use_time ='"+format+"'", new RowMapper<Long>() {
@Override
public Long mapRow(ResultSet rs, int rowNum) throws SQLException {
if (rs.next()) {
return rs.getLong("id");
}
return null;
}
});
return id;
}
@Transactional(readOnly = false,rollbackFor = Exception.class)
@Override
public boolean updateTime(Long id, String time) throws Exception {
return super.update("update t_user set use_time='"+time+"' where id="+id);
}
@Override
public List<NewsInfo> userNewsList(int pageNumber, int pageSize)
throws Exception {
String sql="select * from news where del=0 order by create_time desc limit "+(pageNumber-1)*pageSize+","+pageSize ;
return jdbcTemplate.query(sql, new RowMapper<NewsInfo>(){
@Override
public NewsInfo mapRow(ResultSet rs, int arg1)
throws SQLException {
// TODO Auto-generated method stub
//if(rs.next()){
NewsInfo info = new NewsInfo();
info.setId(rs.getLong("id"));
info.setTitle(rs.getString("title"));
info.setAbs(rs.getString("abs"));
info.setCreateTime(rs.getDate("create_time"));
info.setPicture(rs.getString("picture"));
info.setContent(rs.getString("content"));
return info;
//}
//return null;
}});
}
@Override
public NewsInfo userNewsDetail(int id) throws Exception {
String sql="select * from news where del=0 and id='"+id+"'" ;
return jdbcTemplate.query(sql, new ResultSetExtractor<NewsInfo>(){
@Override
public NewsInfo extractData(ResultSet rs) throws SQLException,
DataAccessException {
if(rs.next()){
//UserInfo userInfo = new UserInfo();
NewsInfo info = new NewsInfo();
info.setId(rs.getLong("id"));
info.setTitle(rs.getString("title"));
info.setAbs(rs.getString("abs"));
info.setCreateTime(rs.getDate("create_time"));
info.setPicture(rs.getString("picture"));
info.setContent(rs.getString("content"));
return info;
}
return null;
}});
}
@Override
public Long count(String time, String to) throws Exception {
String where ="";
if(!Strings.isNullOrEmpty(time) && !Strings.isNullOrEmpty(to)){
where+=" and date(create_time)>='"+time+"' and date(create_time)<='"+to+"'";
}
return super.getJdbcTemplate().queryForObject("select count(*) from news where del=0 "+where, Long.class); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<CashUserInfo> searchCashUser(int i, int i1) throws Exception {
return super.getBySqlRowMapper("select * from t_user where role=3 order by id desc limit "+(i-1)*i1+","+i1,new RowMapper<CashUserInfo>() {
@Override
public CashUserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
CashUserInfo info = new CashUserInfo();
info.setMark(rs.getString("mark"));
info.setContactName(rs.getString("alias"));
info.setId(rs.getLong("id"));
info.setPwd(rs.<PASSWORD>("pwd"));
info.setUserName(rs.getString("user_name"));
return info;
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public long countCashUser() throws Exception {
return super.getJdbcTemplate().queryForLong("select count(*) from t_user where role=3"); //To change body of implemented methods use File | Settings | File Templates.
}
@Transactional(readOnly = false,rollbackFor = Exception.class)
@Override
public boolean saveFinaceUser(CashUserInfo info) throws Exception {
return super.update("insert into t_user(user_name,pwd,phone,alias,mark,role) values('"+info.getUserName()+"','"+info.getPwd()+"','"+info.getPhone()+"','"+info.getContactName()+"','"+info.getMark()+"',3)"); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public CashUserInfo searchFinanceUser(CashUserInfo info) throws Exception {
return super.getJdbcTemplate().query("select * from t_user where user_name='"+info.getUserName()+"' and pwd='"+info.getPwd()+"'",new ResultSetExtractor<CashUserInfo>() {
@Override
public CashUserInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
if(rs.next()){
CashUserInfo info = new CashUserInfo();
info.setMark(rs.getString("mark"));
info.setUserName(rs.getString("user_name"));
info.setPwd(rs.getString("pwd"));
info.setId(rs.getLong("id"));
info.setContactName(rs.getString("alias"));
info.setPhone(rs.getString("phone"));
return info;
}
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
@Transactional(readOnly = false,rollbackFor = Exception.class)
@Override
public boolean deleteById(Long id) throws Exception {
try{
super.delete("delete from t_user where id="+id); //To change body of implemented methods use File | Settings | File Templates.
return true;
}catch (Exception e){
logger.error("delete by id error!",e);
return false;
}
}
@Transactional(readOnly = false,rollbackFor = Exception.class)
@Override
public boolean updateById(Long id, String old, String newPwd) throws Exception {
return super.update("update t_user set pwd='"+newPwd+"' where id="+id); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public CashUserInfo findUserByIdAndPwd(Long id, String old) throws Exception {
return super.getJdbcTemplate().query("select * from t_user where id="+id+" and pwd='"+old+"'",new ResultSetExtractor<CashUserInfo>() {
@Override
public CashUserInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
if(rs.next()){
CashUserInfo info = new CashUserInfo();
info.setMark(rs.getString("mark"));
info.setUserName(rs.getString("user_name"));
info.setPwd(rs.getString("pwd"));
info.setId(rs.getLong("id"));
info.setContactName(rs.getString("alias"));
info.setPhone(rs.getString("phone"));
return info;
}
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<NewsUserInfo> searchNewsUser(int page, Integer size) throws Exception {
return super.getBySqlRowMapper("select * from t_user where role=2 order by id desc limit "+(page-1)*size+","+size,new RowMapper<CashUserInfo>() {
@Override
public CashUserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
CashUserInfo info = new CashUserInfo();
info.setMark(rs.getString("mark"));
info.setContactName(rs.getString("alias"));
info.setId(rs.getLong("id"));
info.setPwd(rs.getString("pwd"));
info.setUserName(rs.getString("user_name"));
return info;
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Long countNewsUser() throws Exception {
return super.getJdbcTemplate().queryForLong("select count(*) from t_user where role=3"); //To change body of implemented methods use File | Settings | File Templates.
}
@Transactional(readOnly = false,rollbackFor = Exception.class)
@Override
public boolean saveNewsUser(NewsUserInfo info) throws Exception {
return super.update("insert into t_user(user_name,pwd,phone,alias,mark,role) values('"+info.getUserName()+"','"+info.getPwd()+"','"+info.getPhone()+"','"+info.getContactName()+"','"+info.getMark()+"',2)");//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public NewsUserInfo searchNewsUser(NewsUserInfo info) throws Exception {
return super.getJdbcTemplate().query("select * from t_user where user_name='"+info.getUserName()+"' and pwd='"+info.getPwd()+"'",new ResultSetExtractor<NewsUserInfo>() {
@Override
public NewsUserInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
if(rs.next()){
NewsUserInfo info = new NewsUserInfo();
info.setMark(rs.getString("mark"));
info.setUserName(rs.getString("user_name"));
info.setPwd(rs.getString("pwd"));
info.setId(rs.getLong("id"));
info.setContactName(rs.getString("alias"));
info.setPhone(rs.getString("phone"));
return info;
}
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Long count(String time) throws Exception {
if(Strings.isNullOrEmpty(time)){
return super.getJdbcTemplate().queryForObject("select count(*) from news where del=0", Long.class);
} else{
return super.getJdbcTemplate().queryForObject("select count(*) from news where del=0 and date(create_time)='"+time+"'", Long.class);
}
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<NewsInfo> userNewsList(Long page1, int i, String time,String to) throws Exception {
String where ="";
if(!Strings.isNullOrEmpty(time) && !Strings.isNullOrEmpty(to)){
where+="and date(create_time)>='"+time+"' and date(create_time)<='"+to+"'";
}
String sql="select * from news where del=0 "+where+" order by create_time desc limit "+(page1-1)*i+","+i ;
logger.debug(sql);
return jdbcTemplate.query(sql, new RowMapper<NewsInfo>(){
@Override
public NewsInfo mapRow(ResultSet rs, int arg1)
throws SQLException {
// TODO Auto-generated method stub
// if(rs.next()){
NewsInfo info = new NewsInfo();
info.setId(rs.getLong("id"));
info.setTitle(rs.getString("title"));
info.setAbs(rs.getString("abs"));
info.setCreateTime(rs.getTimestamp("create_time"));
info.setPicture(rs.getString("picture"));
info.setContent(rs.getString("content"));
return info;
// }
// return null;
}}); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public NewsInfo view(Long id) throws Exception {
return super.getJdbcTemplate().query("select * from news where id="+id,new ResultSetExtractor<NewsInfo>() {
@Override
public NewsInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
if(rs.next()){
NewsInfo info = new NewsInfo();
info.setId(rs.getLong("id"));
info.setTitle(rs.getString("title"));
info.setAbs(rs.getString("abs"));
info.setCreateTime(rs.getDate("create_time"));
info.setPicture(rs.getString("picture"));
info.setContent(rs.getString("content"));
return info;//To change body of implemented methods use File | Settings | File Templates.
}
return null;
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
@Transactional(readOnly = false,rollbackFor = Exception.class)
@Override
public boolean update(String join, String title, String content, String abs, Long id) throws Exception {
return super.update("update news set title='"+title+"',content='"+content+"',abs='"+abs+"',picture='"+join+"' where id="+id); //To change body of implemented methods use File | Settings | File Templates.
}
@Transactional(readOnly = false,rollbackFor = Exception.class)
@Override
public boolean deleteNewsById(Long id) throws Exception {
return super.update("delete from news where id="+id); //To change body of implemented methods use File | Settings | File Templates.
}
@Transactional(readOnly = false,rollbackFor = Exception.class)
@Override
public boolean create(String join, String title, String content, String abs) throws Exception {
return super.update("insert into news(title,content,picture,abs) values('"+title+"','"+content+"','"+join+"','"+abs+"')"); //To change body of implemented methods use File | Settings | File Templates.
}
}
<file_sep>/smart-service/src/main/java/com/smart/service/StatisticsService.java
/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
package com.smart.service;
import com.smart.common.ResponseBody;
import com.smart.common.ResponseMsg;
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/30
* Time: 09:46
*/
public interface StatisticsService {
ResponseBody getHotelXy(int i, Integer type, Integer totalType) throws Exception;
ResponseBody getHotelMap(int type) throws Exception;
ResponseBody getLifeXy(Integer module, Integer type) throws Exception;
ResponseBody getTotal(Integer type) throws Exception;
ResponseBody getVsXy(int i, Integer type) throws Exception;
ResponseBody getCateXy(Integer type) throws Exception;
}
<file_sep>/smart-app/src/main/webapp/js/function.js
function px(num){
if(num<0)num=0;
return num.toString()+"px";
}
//----------------------创建页面元素
function creatElement(p,n,Id,c){
var ne=document.createElement(n);
p.appendChild(ne);
if(Id!="")ne.id=Id;
if(c!="")ne.className=c;
return ne;
}
//判断ie,FF
function ieBrowser(){
var ie;
var firefox;
if (document.all) ie = true; else ie = false;
return ie;
}
//黑板报列表
$(function(){
$(document).delegate(this,"click",function(e){
var evt = e.target;
var adpop="<div class='adtitle'>aaaaaaaaa</div>"
$("body").append(adpop);
var adpop_text=$(evt).text();
if($(evt).closest(".adpop").length!=0){
$(".adtitle").html(adpop_text).css({
"top":e.pageY+"px",
"left":e.pageX+"px"
}).show();
}
else{
$(".adtitle").hide()
}
})
$(".operate").blur(function(){
$(".add").removeClass("addbg_click").addClass("addbg");
$(".star").removeClass("starbg_click").addClass("starbg");
$(".end").removeClass("endbg_click").addClass("endbg");
$(".modify").removeClass("modifybg_click").addClass("modifybg");
})
$(".add").click(function(){
$(".add").removeClass("addbg").addClass("addbg_click");
$(".star").removeClass("starbg_click").addClass("starbg");
$(".end").removeClass("endbg_click").addClass("endbg");
$(".modify").removeClass("modifybg_click").addClass("modifybg");
})
$(".star").click(function(){
$(".add").removeClass("addbg_click").addClass("addbg");
$(".star").removeClass("starbg").addClass("starbg_click");
$(".end").removeClass("endbg_click").addClass("endbg");
$(".modify").removeClass("modifybg_click").addClass("modifybg");
})
$(".end").click(function(){
$(".add").removeClass("addbg_click").addClass("addbg");
$(".star").removeClass("starbg_click").addClass("starbg");
$(".end").removeClass("endbg").addClass("endbg_click");
$(".modify").removeClass("modifybg_click").addClass("modifybg");
})
$(".modify").click(function(){
$(".add").removeClass("addbg_click").addClass("addbg");
$(".star").removeClass("starbg_click").addClass("starbg");
$(".end").removeClass("endbg_click").addClass("endbg");
$(".modify").removeClass("modifybg").addClass("modifybg_click");
})
$(".notice_save div").hover(function(){
$(this).removeClass("bga").addClass("bgb");
},function(){
$(this).removeClass("bgb").addClass("bga");
})
$(".contacts_op div").hover(function(){
$(this).removeClass("bga").addClass("bgb");
},function(){
$(this).removeClass("bgb").addClass("bga");
})
})
//check判断
$(function(){
$(".sum_check").click(function(){
if($(".sum_check").hasClass("zl_ck_normal")){
$(".td_select").removeClass("zl_ck_normal").addClass("zl_ck_down").parents("tr").css("background-color","#daf2f6");
}
if($(".sum_check").hasClass("zl_ck_down")){
$(".td_select").removeClass("zl_ck_down").addClass("zl_ck_normal").parents("tr").css("background-color","#FFFFFF");
}
})
$(".td_select").click(function(){
if($(this).hasClass("zl_ck_normal")){
$(this).parents("tr:first").css("background-color","#daf2f6");
}
if($(this).hasClass("zl_ck_down")){
$(this).parents("tr:first").css("background-color","#FFFFFF");
}
$(".sum_check").removeClass("zl_ck_down");
$(".sum_check").addClass("zl_ck_normal");
})
//联系人上传照片
$(".click_up").click(function(){
$(this).val("")
})
$(".click_up").blur(function(){
if(!$(this).val()){
$(this).val("点击这里上传")
}
})
})
/**
*上下工位图添加删除座位
*
**/
function gw_operate(operatePic,fun){
$("."+operatePic+" .p").hover(function(){
var obj = $(this);
if($("div[class^='p_name']",obj).text() == ""){
var p_nobody_u_size = $("div[class*='p_nobody_u_']",obj).length;
var p_nobody_d_size = $("div[class*='p_nobody_d_']",obj).length;
var empty_gw_add;
if(p_nobody_u_size != 0){
var empty_gw_add = $("<div class='empty_gw_u'/>").appendTo($("div[class*='p_nobody_u_']",obj));
}else if(p_nobody_d_size != 0){
var empty_gw_add = $("<div class='empty_gw_d'/>").appendTo($("div[class*='p_nobody_d_']",obj));
}
$(empty_gw_add).bind("click",function(){
//popup-window
eval(fun)();
})
}else{
var p_nobody_u_size = $("div[class*='p_nobody_u_']",obj).length;
var p_nobody_d_size = $("div[class*='p_nobody_d_']",obj).length;
var empty_gw_del;
if(p_nobody_u_size != 0){
var empty_gw_del = $("<div class='del_gw_u'/>").appendTo($("div[class*='p_nobody_u_']",obj));
}else if(p_nobody_d_size != 0){
var empty_gw_del = $("<div class='del_gw_d'/>").appendTo($("div[class*='p_nobody_d_']",obj));
}
$(empty_gw_del).bind("click",function(){
//popup-window
})
}
},
function(){
var obj = $(this);
$("div[class^='p_nobody'] div",obj).remove();
})
}
/**
*左右工位图添加删除座位
*
**/
function gw_operate_lr(operatePic,fun){
$("."+operatePic+" .b").hover(function(){
var obj = $(this);
if($("div[class^='p_name']",obj).text() == ""){
var p_nobody_u_size = $("div[class*='p_nobody_l_']",obj).length;
var p_nobody_d_size = $("div[class*='p_nobody_r_']",obj).length;
var empty_gw_add;
if(p_nobody_u_size != 0){
var empty_gw_add = $("<div class='empty_gw_l'/>").appendTo($("div[class*='p_nobody_l_']",obj));
}else if(p_nobody_d_size != 0){
var empty_gw_add = $("<div class='empty_gw_r'/>").appendTo($("div[class*='p_nobody_r_']",obj));
}
$(empty_gw_add).bind("click",function(){
//popup-window
eval(fun)();
})
}else{
var p_nobody_u_size = $("div[class*='p_nobody_l_']",obj).length;
var p_nobody_d_size = $("div[class*='p_nobody_r_']",obj).length;
var empty_gw_del;
if(p_nobody_u_size != 0){
var empty_gw_del = $("<div class='del_gw_l'/>").appendTo($("div[class*='p_nobody_l_']",obj));
}else if(p_nobody_d_size != 0){
var empty_gw_del = $("<div class='del_gw_r'/>").appendTo($("div[class*='p_nobody_r_']",obj));
}
$(empty_gw_del).bind("click",function(){
//popup-window
})
}
},
function(){
var obj = $(this);
$("div[class^='p_nobody'] div",obj).remove();
})
}
function callAPI(purl,param,callback){
var _url = purl;
$.post(_url, param ,function(data){
if(callback){
callback(data);
}
},"json");
}<file_sep>/smart-service/src/main/java/com/smart/service/UserService.java
package com.smart.service;
import com.smart.common.ResponseBody;
import com.smart.common.ResponseMsg;
import com.smart.model.*;
import com.smart.vo.UserVo;
import java.util.List;
import java.util.Date;
import com.smart.common.Page;
public interface UserService {
public UserInfo sellerLogin(String user, String passwd)throws Exception;
boolean isValid(UserVo vo,Date date) throws Exception;
public boolean updateUseTime(Long id,Date use) throws Exception;
public Page userNewsList(int pageNumber, int pageSize) throws Exception;
public NewsInfo userNewsDetail(int id) throws Exception;
public boolean create(String join, String title, String content, String abs) throws Exception;
Page<CashUserInfo> searchCashUser(int i, int i1)throws Exception;
CashUserInfo searchFinanceUser(CashUserInfo info) throws Exception;
boolean saveFinanceUser(CashUserInfo info) throws Exception;
boolean deleteById(Long id) throws Exception;
boolean updateById(Long id, String old, String newPwd) throws Exception;
CashUserInfo findUserByIdAndPwd(Long id, String old) throws Exception;
Page<NewsUserInfo> searchNewsUser(Integer page, int i) throws Exception;
boolean saveNewsUser(NewsUserInfo info) throws Exception;
NewsUserInfo searchNewsUser(NewsUserInfo info) throws Exception;
ResponseBody userNewsList(Long page, int i, String time, String to) throws Exception;
ResponseMsg view(Long id) throws Exception;
boolean update(String join, String title, String content, String abs, Long id) throws Exception;
boolean deleteNewsById(Long id) throws Exception;
}
<file_sep>/smart-service/src/main/java/com/smart/service/impl/SellerServiceImpl.java
package com.smart.service.impl;/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
import com.alibaba.fastjson.JSONObject;
import com.smart.common.Page;
import com.smart.common.ResponseBody;
import com.smart.dao.SellerDao;
import com.smart.model.CompanyInfo;
import com.smart.model.SellerInfo;
import com.smart.model.Type;
import com.smart.model.TypeInfo;
import com.smart.service.SellerService;
import com.smart.vo.SellerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/14
* Time: 17:13
*/
@Service
public class SellerServiceImpl implements SellerService {
@Autowired
private SellerDao sellerDao;
@Override
public Page getSellers(Integer pageNumber) throws Exception {
Page<SellerInfo> page = new Page<SellerInfo>() {
@Override
protected String listAlias() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
};
page.setPageNumber(pageNumber);
page.setPageSize(10);
Long total = sellerDao.count();
List<SellerInfo> list = sellerDao.getSeller(pageNumber,page.getPageSize());
page.setCount(total);
page.setMessages(list);
return page; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Page getTypes() throws Exception {
Page<TypeInfo> page = new Page<TypeInfo>() {
@Override
protected String listAlias() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
};
List<TypeInfo> infos=sellerDao.getTypes1();//To change body of implemented methods use File | Settings | File Templates.
page.setMessages(infos);
return page;
}
@Override
public Map<Integer, String> getTypes(Integer type) throws Exception {
return sellerDao.getTypes(type); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Long addSeller(SellerVo info) throws Exception {
Long id= sellerDao.addSeller(info);
sellerDao.addAccount(id);
return id;
}
@Override
public long addCompany(CompanyInfo info) throws Exception {
long id= sellerDao.addCompany(info); //To change body of implemented methods use File | Settings | File Templates.
sellerDao.updateSeller(info.getName(),info.getUserId());
return id;
}
@Override
public boolean fingByPhone(SellerVo userName) throws Exception {
return sellerDao.findByPhone(userName); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public SellerVo getUserById(Long id) throws Exception {
return sellerDao.getUserById(id); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public long updateSeller(SellerVo info) throws Exception {
return sellerDao.updateSeller(info); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public CompanyInfo getCompanyByUserId(Long id, Integer type) throws Exception {
return sellerDao.getCompanyByUserId(id,type); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Long updateCompany(CompanyInfo info) throws Exception {
long id= sellerDao.updateCompany(info); //To change body of implemented methods use File | Settings | File Templates.
sellerDao.updateSeller(info.getName(),info.getUserId());
return id;
}
@Override
public boolean deleteCategory(Long typeId) throws Exception {
return sellerDao.deleteCategory(typeId); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean updateCategory(Long id, String name) throws Exception {
return sellerDao.updateCategory(id,name); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public JSONObject getCode(Long id, Integer type) throws Exception {
return sellerDao.getCode(id,type); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean addCategory(Long id, String name) throws Exception {
List<Type> types = sellerDao.getTypesA(id.intValue());
int typeId= types.get(types.size()-1).getType()+1;
return sellerDao.addCategory(id,name,typeId); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Page getSellers(Integer pageNumber, String name) throws Exception {
Page<SellerInfo> page = new Page<SellerInfo>() {
@Override
protected String listAlias() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
};
page.setPageNumber(pageNumber);
page.setPageSize(10);
Long total = sellerDao.count(name);
List<SellerInfo> list = sellerDao.getSeller(pageNumber,name,page.getPageSize());
page.setCount(total);
page.setMessages(list);
return page;
}
@Override
public ResponseBody getSellers(Integer pageNumber, String name, Integer type) throws Exception {
Page<SellerInfo> page = new Page<SellerInfo>() {
@Override
protected String listAlias() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
};
page.setPageNumber(pageNumber);
page.setPageSize(10);
Long total = sellerDao.count(name,type);
List<SellerInfo> list = sellerDao.getSeller(pageNumber,name,page.getPageSize(),type);
page.setCount(total);
page.setMessages(list);
return page;
}
}
<file_sep>/smart-service/src/main/java/com/smart/dao/UserDao.java
package com.smart.dao;
import com.smart.common.Page;
import com.smart.common.ResponseMsg;
import com.smart.model.CashUserInfo;
import com.smart.model.NewsUserInfo;
import com.smart.model.UserInfo;
import com.smart.model.NewsInfo;
import java.util.List;
public interface UserDao {
UserInfo sellerLogin(String user, String passwd)throws Exception;
Long isValid(String userName, Integer role, String format) throws Exception;
boolean updateTime(Long id,String time)throws Exception;
boolean create(String join, String title, String content, String abs) throws Exception;
public List<NewsInfo> userNewsList(int pageNumber, int pageSize)throws Exception;
public NewsInfo userNewsDetail(int id)throws Exception;
public Long count(String time, String to) throws Exception;
List<CashUserInfo> searchCashUser(int i, int i1) throws Exception;
long countCashUser() throws Exception;
boolean saveFinaceUser(CashUserInfo info) throws Exception;
CashUserInfo searchFinanceUser(CashUserInfo info) throws Exception;
boolean deleteById(Long id) throws Exception;
boolean updateById(Long id, String old, String newPwd) throws Exception;
CashUserInfo findUserByIdAndPwd(Long id, String old) throws Exception;
List<NewsUserInfo> searchNewsUser(int i, Integer page) throws Exception;
Long countNewsUser() throws Exception;
boolean saveNewsUser(NewsUserInfo info) throws Exception;
NewsUserInfo searchNewsUser(NewsUserInfo info) throws Exception;
Long count(String time)throws Exception;
List<NewsInfo> userNewsList(Long page1, int i, String time, String to) throws Exception;
NewsInfo view(Long id) throws Exception;
boolean update(String join, String title, String content, String abs, Long id) throws Exception;
boolean deleteNewsById(Long id) throws Exception;
}
<file_sep>/smart-service/src/main/java/com/smart/dao/impl/StatisticsDaoImpl.java
package com.smart.dao.impl;/*
* Copyright 2015 Future TV, Inc.
*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (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.icntv.tv/licenses/LICENSE-1.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.
*/
import com.smart.dao.StatisticsDao;
import com.smart.model.MapInfo;
import com.smart.model.XYModel;
import org.joda.time.DateTime;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Created by leixw
* <p/>
* Author: leixw
* Date: 2015/07/30
* Time: 10:09
*/
@Transactional(readOnly = true)
@Repository
public class StatisticsDaoImpl extends BaseDaoImpl implements StatisticsDao {
@Override
public List<XYModel> getHotelXY(int i, Integer type, Integer totalType) throws Exception {
String sql= getHotelSql(i, type,totalType);
return super.getBySqlRowMapper(sql,new RowMapper<XYModel>() {
@Override
public XYModel mapRow(ResultSet rs, int rowNum) throws SQLException {
XYModel model = new XYModel();
model.setDay(rs.getString("time"));
model.setValue(rs.getString("total"));
return model; //To change body of implemented methods use File | Settings | File Templates.
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<MapInfo> getHotelMap(int type) throws Exception {
String sql="";
if(type==1){
sql="select sum(a.num) as total,b.x,b.y from hotel_order as a,hotel as b where a.hotel_id = b.id ";
} else if(type ==2){
sql ="select sum(a.num) as total,b.x,b.y from view_spot_order as a,view_spot as b where a.vs_id = b.id ";
}
return super.getBySqlRowMapper(sql, new RowMapper<MapInfo>() {
@Override
public MapInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
MapInfo info = new MapInfo();
info.setInfo(rs.getString("total"));
info.setX(rs.getString("x"));
info.setY(rs.getString("y"));
return info; //To change body of implemented methods use File | Settings | File Templates.
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<XYModel> getLifeXY(Integer module, Integer type) throws Exception {
String sql="";
if(module==1){
sql = "select count(a.id) as total ,date(a.create_time) as time from pay_now_order as a, life as b where b.id=a.where_id and a.where_type_id =4 and b.life_type="+type+" and a.create_time>='"+getDay(-30)+"' group by date(a.create_time) desc ";
} else if(module==2){
sql = "select sum(a.total_price) as total ,date(a.create_time) as time from pay_now_order as a, life as b where b.id=a.where_id and a.where_type_id =4 and b.life_type="+type+" and a.create_time>='"+getDay(-30)+"' group by date(a.create_time) desc ";
}
logger.debug(sql);
return super.getBySqlRowMapper(sql,new RowMapper<XYModel>() {
@Override
public XYModel mapRow(ResultSet rs, int rowNum) throws SQLException {
XYModel model = new XYModel();
model.setDay(rs.getString("time"));
model.setValue(rs.getString("total"));
return model; //To change body of implemented methods use File | Settings | File Templates.
}
});
}
@Override
public String[] getTotal(Integer type) throws Exception {
// String day=DateTime.now().toYearMonthDay();
String current=DateTime.now().plusMonths(type).toString("yyyy-MM");
String next=DateTime.now().plusMonths(type+1).toString("yyyy-MM");
Float hotel_total=super.getJdbcTemplate().queryForObject("select sum(total_price) from hotel_order where create_time<='"+next+"' and create_time>'"+current+"'",Float.class);
Float vs_total=super.getJdbcTemplate().queryForObject("select sum(total_price) from view_spot_order where create_time<='"+next+"' and create_time>'"+current+"'",Float.class);
Float pay_total=super.getJdbcTemplate().queryForObject("select sum(total_price) from pay_now_order where create_time<='"+next+"' and create_time>'"+current+"'",Float.class);
if(null == hotel_total){
hotel_total=0f;
}
if(null == vs_total){
vs_total=0f;
}
if(pay_total==null){
pay_total=0f;
}
return new String[]{current,(hotel_total+vs_total+pay_total)+""};
}
@Override
public String total() throws Exception {
Float hotel_total=super.getJdbcTemplate().queryForObject("select sum(total_price) from hotel_order ",Float.class);
Float vs_total=super.getJdbcTemplate().queryForObject("select sum(total_price) from view_spot_order ",Float.class);
Float pay_total=super.getJdbcTemplate().queryForObject("select sum(total_price) from pay_now_order ",Float.class);
if(null == hotel_total){
hotel_total=0f;
}
if(null == vs_total){
vs_total=0f;
}
if(pay_total==null){
pay_total=0f;
}
return (hotel_total+vs_total+pay_total)+"";
}
@Override
public List<XYModel> getVsXY(int i, Integer type) throws Exception {
String sql= getVsSql(i, type);
return super.getBySqlRowMapper(sql,new RowMapper<XYModel>() {
@Override
public XYModel mapRow(ResultSet rs, int rowNum) throws SQLException {
XYModel model = new XYModel();
model.setDay(rs.getString("time"));
model.setValue(rs.getString("total"));
return model; //To change body of implemented methods use File | Settings | File Templates.
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public List<XYModel> getCateXY(Integer type) throws Exception {
String sql="";
if(type==1){
sql="select count(a.id) as total ,date(a.create_time) as time from pay_now_order as a, restaurant as b where b.id=a.where_id and a.where_type_id =3 and a.create_time>='"+getDay(-30)+"' group by date(a.create_time) desc ";
}else if(type==2){
sql = "select sum(a.total_price) as total ,date(a.create_time) as time from pay_now_order as a, restaurant as b where b.id=a.where_id and a.where_type_id =3 and a.create_time>='"+getDay(-30)+"' group by date(a.create_time) desc ";
}
logger.debug("sql="+sql);
return super.getBySqlRowMapper(sql,new RowMapper<XYModel>() {
@Override
public XYModel mapRow(ResultSet rs, int rowNum) throws SQLException {
XYModel model = new XYModel();
model.setDay(rs.getString("time"));
model.setValue(rs.getString("total"));
return model; //To change body of implemented methods use File | Settings | File Templates.
}
}); //To change body of implemented methods use File | Settings | File Templates.
}
private String getVsSql(int i, Integer type) {
if(i==1){
return "select sum(total_price) as total,pay_time as time from view_spot_order where order_status_id=4 and order_pay_type_id=3 and to_time>='"+getDay(-7)+"' and pay_time<'"+getDay(-1)+"' group by pay_time desc ";
}
if(i==2){
return "select sum(total_price) as total,from_time as time from view_spot_order where order_status_id=4 and order_pay_type_id=3 and from_time>='"+getDay(1)+"' and from_time<'"+getDay(7)+"' group by from_time desc ";
}
return null; //To change body of created methods use File | Settings | File Templates.
}
private String getHotelSql(int i, Integer type, Integer totalType) {
//i==1 实际 i==2下周
if(i==1){
return "select sum(total_price) as total,to_time as time from hotel_order where order_status_id=4 and order_pay_type_id=3 and to_time>='"+getDay(-7)+"' and to_time<'"+getDay(-1)+"' group by to_time desc ";
}
if(i==2){
return "select sum(total_price) as total,from_time as time from hotel_order where order_status_id=4 and order_pay_type_id=3 and from_time>='"+getDay(1)+"' and from_time<'"+getDay(7)+"' group by from_time desc ";
}
return null; //To change body of created methods use File | Settings | File Templates.
}
private String getDay(int i){
return DateTime.now().plusDays(i).toString("yyyy-MM-dd");
}
public static void main(String[]args){
System.out.println(DateTime.now().toString("yyyy-MM"));
}
}
| 30560a93c4e32cde5074207e1f151fa0c41bac03 | [
"JavaScript",
"Java"
] | 18 | Java | leixw0102/smart-travel | 141f59c999131c30de91ae12a1030b563e68b3e5 | adf3e1b149b19369faa522e3554e730118e2cde1 |
refs/heads/master | <repo_name>isdaviddong/Meetup20190112<file_sep>/Meetup20190112/QuickReply.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Meetup20190112
{
public partial class QuickReply : System.Web.UI.Page
{
//請輸入你的 Channel Access Token
string ChannelAccessToken =System.Configuration.ConfigurationManager.AppSettings["ChannelAccessToken"] ; // "~~~~~請輸入你的請輸入你的 Channel Access Token~~~~~~~";
//請輸入你的User Id
string AdminUserId = System.Configuration.ConfigurationManager.AppSettings["AdminUserId"];//"~~~~~請輸入你的User Id~~~~~~~";
//icon位置
const string IconUrl = "https://arock.blob.core.windows.net/blogdata201809/1337594581_package_edutainment.png";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//建立一個TextMessage物件
isRock.LineBot.TextMessage m =
new isRock.LineBot.TextMessage("請在底下選擇一個選項");
//在TextMessage物件的quickReply屬性中加入items
m.quickReply.items.Add(
new isRock.LineBot.QuickReplyMessageAction(
$"一般標籤", "點選後顯示的text文字"));
m.quickReply.items.Add(
new isRock.LineBot.QuickReplyMessageAction(
$"有圖示的標籤", "點選後顯示的text文字", new Uri(IconUrl)));
//加入QuickReplyDatetimePickerAction
m.quickReply.items.Add(
new isRock.LineBot.QuickReplyDatetimePickerAction(
"選時間", "選時間", isRock.LineBot.DatetimePickerModes.datetime, new Uri(IconUrl)));
//加入QuickReplyLocationAction
m.quickReply.items.Add(
new isRock.LineBot.QuickReplyLocationAction(
"選地點", new Uri(IconUrl)));
//加入QuickReplyCameraAction
m.quickReply.items.Add(
new isRock.LineBot.QuickReplyCameraAction(
"Show Camera", new Uri(IconUrl)));
//加入QuickReplyCamerarollAction
m.quickReply.items.Add(
new isRock.LineBot.QuickReplyCamerarollAction(
"Show Cameraroll", new Uri(IconUrl)));
//建立bot instance
isRock.LineBot.Bot bot = new isRock.LineBot.Bot(ChannelAccessToken);
//透過Push發送訊息
bot.PushMessage(AdminUserId, m);
}
}
}<file_sep>/Meetup20190112/Controllers/TestLUISController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Meetup20190112.Controllers
{
public class TestLUISController : isRock.LineBot.LineWebHookControllerBase
{
const string channelAccessToken = "~~~請改成自己的ChannelAccessToken~~~";
const string AdminUserId = "~~~改成你的AdminUserId~~~";
const string LuisAppId = "~~~改成你的LuisAppId~~~";
const string LuisAppKey = "~~~改成你的LuisAppKey~~~";
const string Luisdomain = "~~~改成你的Luisdomain~~~"; //ex.westus
[Route("api/TestLUIS")]
[HttpPost]
public IHttpActionResult POST()
{
try
{
//設定ChannelAccessToken(或抓取Web.Config)
this.ChannelAccessToken = channelAccessToken;
//取得Line Event(範例,只取第一個)
var LineEvent = this.ReceivedMessage.events.FirstOrDefault();
//配合Line verify
if (LineEvent.replyToken == "<PASSWORD>") return Ok();
//回覆訊息
if (LineEvent.type == "message")
{
var repmsg = "";
if (LineEvent.message.type == "text") //收到文字
{
//建立LuisClient
Microsoft.Cognitive.LUIS.LuisClient lc =
new Microsoft.Cognitive.LUIS.LuisClient(LuisAppId, LuisAppKey, true, Luisdomain);
//Call Luis API 查詢
var ret = lc.Predict(LineEvent.message.text).Result;
if (ret.Intents.Count() <= 0)
repmsg = $"你說了 '{LineEvent.message.text}' ,但我看不懂喔!";
else if (ret.TopScoringIntent.Name == "None")
repmsg = $"你說了 '{LineEvent.message.text}' ,但不在我的服務範圍內喔!";
else
{
repmsg = $"OK,你想 '{ret.TopScoringIntent.Name}',";
if (ret.Entities.Count > 0)
repmsg += $"想要的是 '{ ret.Entities.FirstOrDefault().Value.FirstOrDefault().Value}' ";
}
//回覆
this.ReplyMessage(LineEvent.replyToken, repmsg);
}
if (LineEvent.message.type == "sticker") //收到貼圖
this.ReplyMessage(LineEvent.replyToken, 1, 2);
}
//response OK
return Ok();
}
catch (Exception ex)
{
//如果發生錯誤,傳訊息給Admin
this.PushMessage(AdminUserId, "發生錯誤:\n" + ex.Message);
//response OK
return Ok();
}
}
}
}
<file_sep>/README.md
# Meetup20190112
這是 20190112 meetup的範例
## 活動網址
https://isrock.kktix.cc/events/01122019
<file_sep>/dotNetCore/Pages/PushMessage.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace dotNetCore.Pages
{
public class PushMessageModel : PageModel
{
//請輸入你的 Channel Access Token
string ChannelAccessToken = ""; // "~~~~~請輸入你的請輸入你的 Channel Access Token~~~~~~~";
//請輸入你的User Id
string AdminUserId = ""; //"~~~~~請輸入你的User Id~~~~~~~";
public void OnGet()
{
}
public IActionResult OnPost()
{
var bot = new isRock.LineBot.Bot(ChannelAccessToken);
var msg = new isRock.LineBot.TextMessage("Hello World");
bot.PushMessage(AdminUserId, msg);
return Page();
}
}
}<file_sep>/dotNetCore/LineBotController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace dotNetCore
{
[Route("api/LineBot")]
public class LineBotController : Controller
{
[HttpPost]
public StatusCodeResult OnPost()
{
var ReceivedMsg = isRock.LineBot.Bot.ParsingReceivedMessage(Request.Body);
if (ReceivedMsg.events[0].replyToken == "0<PASSWORD>")
return Ok();
//var touserId = "";
var token = "";
isRock.LineBot.Bot bot = new isRock.LineBot.Bot(token);
isRock.LineBot.TextMessage msg;
if (ReceivedMsg.events.Count > 0 && ReceivedMsg.events[0].message != null && !string.IsNullOrEmpty(ReceivedMsg.events[0].message.text))
{
msg = new isRock.LineBot.TextMessage("you said : " + ReceivedMsg.events[0].message.text);
}
else
{
msg = new isRock.LineBot.TextMessage("test");
}
bot.ReplyMessage(ReceivedMsg.events[0].replyToken, msg);
return Ok();
}
}
}
<file_sep>/Meetup20190112/Controllers/LineWebHookSampleController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Meetup20190112.Controllers
{
public class LineBotWebHookController : isRock.LineBot.LineWebHookControllerBase
{
string channelAccessToken = System.Configuration.ConfigurationManager.AppSettings["ChannelAccessToken"]; // "~~~~~請輸入你的請輸入你的 Channel Access Token~~~~~~~";
string AdminUserId = System.Configuration.ConfigurationManager.AppSettings["AdminUserId"];//"~~~~~請輸入你的User Id~~~~~~~";
[Route("api/LineWebHookSample")]
[HttpPost]
public IHttpActionResult POST()
{
try
{
//設定ChannelAccessToken(或抓取Web.Config)
this.ChannelAccessToken = channelAccessToken;
//取得Line Event(範例,只取第一個)
var LineEvent = this.ReceivedMessage.events.FirstOrDefault();
//配合Line verify
if (LineEvent.replyToken == "00000000000000000000000000000000") return Ok();
//回覆訊息
if (LineEvent.type == "message")
{
if (LineEvent.message.type == "text") //收到文字
this.ReplyMessage(LineEvent.replyToken, "你說了:" + LineEvent.message.text);
if (LineEvent.message.type == "sticker") //收到貼圖
this.ReplyMessage(LineEvent.replyToken, 1, 2);
}
else if (LineEvent.type == "postback")
{
this.ReplyMessage(LineEvent.replyToken, "postback data:" + LineEvent.postback.Params.datetime);
}
else
{
this.ReplyMessage("event:" + LineEvent.replyToken, LineEvent.type);
}
//response OK
return Ok();
}
catch (Exception ex)
{
//如果發生錯誤,傳訊息給Admin
this.PushMessage(AdminUserId, "發生錯誤:\n" + ex.Message);
//response OK
return Ok();
}
}
}
}
<file_sep>/Meetup20190112/Flex.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Meetup20190112
{
public partial class Flex : System.Web.UI.Page
{
//請輸入你的 Channel Access Token
string ChannelAccessToken = System.Configuration.ConfigurationManager.AppSettings["ChannelAccessToken"]; // "~~~~~請輸入你的請輸入你的 Channel Access Token~~~~~~~";
//請輸入你的User Id
string AdminUserId = System.Configuration.ConfigurationManager.AppSettings["AdminUserId"];//"~~~~~請輸入你的User Id~~~~~~~";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
isRock.LineBot.Bot bot = new isRock.LineBot.Bot(ChannelAccessToken);
var JSONMessage = @"
{
'type': 'bubble',
'hero': {
'type': 'image',
'url': 'https://scdn.line-apps.com/n/channel_devcenter/img/fx/01_1_cafe.png',
'size': 'full',
'aspectRatio': '20:13',
'aspectMode': 'cover',
'action': {
'type': 'uri',
'uri': 'http://linecorp.com/'
}
},
'body': {
'type': 'box',
'layout': 'vertical',
'contents': [
{
'type': 'text',
'text': 'Brown Cafe',
'weight': 'bold',
'size': 'xl'
},
{
'type': 'box',
'layout': 'baseline',
'margin': 'md',
'contents': [
{
'type': 'icon',
'size': 'sm',
'url': 'https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png'
},
{
'type': 'icon',
'size': 'sm',
'url': 'https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png'
},
{
'type': 'icon',
'size': 'sm',
'url': 'https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png'
},
{
'type': 'icon',
'size': 'sm',
'url': 'https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png'
},
{
'type': 'icon',
'size': 'sm',
'url': 'https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gray_star_28.png'
},
{
'type': 'text',
'text': '4.0',
'size': 'sm',
'color': '#999999',
'margin': 'md',
'flex': 0
}
]
},
{
'type': 'box',
'layout': 'vertical',
'margin': 'lg',
'spacing': 'sm',
'contents': [
{
'type': 'box',
'layout': 'baseline',
'spacing': 'sm',
'contents': [
{
'type': 'text',
'text': 'Place',
'color': '#aaaaaa',
'size': 'sm',
'flex': 1
},
{
'type': 'text',
'text': 'Miraina Tower, 4-1-6 Shinjuku, Tokyo',
'wrap': true,
'color': '#666666',
'size': 'sm',
'flex': 5
}
]
},
{
'type': 'box',
'layout': 'baseline',
'spacing': 'sm',
'contents': [
{
'type': 'text',
'text': 'Time',
'color': '#aaaaaa',
'size': 'sm',
'flex': 1
},
{
'type': 'text',
'text': '10:00 - 23:00',
'wrap': true,
'color': '#666666',
'size': 'sm',
'flex': 5
}
]
}
]
}
]
},
'footer': {
'type': 'box',
'layout': 'vertical',
'spacing': 'sm',
'contents': [
{
'type': 'button',
'style': 'link',
'height': 'sm',
'action': {
'type': 'uri',
'label': 'CALL',
'uri': 'https://linecorp.com'
}
},
{
'type': 'button',
'style': 'link',
'height': 'sm',
'action': {
'type': 'uri',
'label': 'WEBSITE',
'uri': 'https://linecorp.com'
}
},
{
'type': 'button',
'style': 'link',
'height': 'sm',
'action': {
'type': 'message',
'label': '按我',
'text': '按過就好'
}
},
{
'type': 'spacer',
'size': 'sm'
}
],
'flex': 0
}
}
";
//定義一則訊息
var Messages = @"
[
{
""type"": ""flex"",
""altText"": ""This is a Flex Message"",
""contents"": $flex$
}
]
";
//發送
bot.PushMessageWithJSON(AdminUserId, Messages.Replace("$flex$", JSONMessage));
}
}
} | 451d7e971550d77d6e14bf336efad9574ce817f5 | [
"Markdown",
"C#"
] | 7 | C# | isdaviddong/Meetup20190112 | caf9d5004328dde0edece720d62baab6b6a6e07b | c1bd86a9b2a00715eb273513c6ead255f8d0bb9b |
refs/heads/master | <repo_name>dantefe02/DH_EntregableAndroid_DanteFerrari<file_sep>/src/main/java/com/example/dh_entregableandroid_danteferrari/RecylerViewFragment.java
package com.example.dh_entregableandroid_danteferrari;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class RecylerViewFragment extends Fragment {
public RecylerViewFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_recyler_view, container, false);
RecyclerView recyclerViewProductos = view.findViewById(R.id.fragmentRecyclerView_RecyclerView);
List<Producto> productoList = ProvedorDeProductos.getProductos();
ProductoAdapter productoAdapter = new ProductoAdapter(productoList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(view.getContext(), RecyclerView.VERTICAL, false);
recyclerViewProductos.setLayoutManager(linearLayoutManager);
recyclerViewProductos.setAdapter(productoAdapter);
return view;
}
}
<file_sep>/src/main/java/com/example/dh_entregableandroid_danteferrari/ProductoAdapter.java
package com.example.dh_entregableandroid_danteferrari;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class ProductoAdapter extends RecyclerView.Adapter<ProductoAdapter.ViewHolderProducto> {
private List<Producto> listaDeProductos;
public ProductoAdapter(List<Producto> listaDeProductos) {
this.listaDeProductos = listaDeProductos;
}
@NonNull
@Override
public ViewHolderProducto onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.celda_producto, parent, false);
return new ViewHolderProducto(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolderProducto holder, int position) {
Producto producto = listaDeProductos.get(position);
holder.cargarValor(producto);
}
@Override
public int getItemCount() {
return listaDeProductos.size();
}
protected class ViewHolderProducto extends RecyclerView.ViewHolder {
private TextView nombreProducto;
private TextView precioProducto;
private ImageView imagenProducto;
public ViewHolderProducto(@NonNull View itemView) {
super(itemView);
nombreProducto = itemView.findViewById(R.id.celdaProducto_TextView_Nombre);
precioProducto = itemView.findViewById(R.id.celdaProducto_TextView_Precio);
imagenProducto = itemView.findViewById(R.id.celdaProducto_ImageView_ImagenProducto);
}
public void cargarValor(Producto producto) {
imagenProducto.setImageResource(producto.getImagen());
nombreProducto.setText(producto.getNombre());
precioProducto.setText("$" + producto.getPrecio().toString());
}
}
}
| d093d8e6a80d7f5ff53da41d380ea503a98a8a59 | [
"Java"
] | 2 | Java | dantefe02/DH_EntregableAndroid_DanteFerrari | b9650826c76710bd39cef02ffe6f06d2fc20ebb0 | 9389e7270a4df6701008ea9d7b2beceb24e196c1 |
refs/heads/master | <repo_name>ashafer01/void<file_sep>/test.py
# Copyright 2019 ashafer01
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import asyncio
import math
import unittest
from void import Void
class TestVoid(unittest.TestCase):
def test_hash(self):
self.assertEqual(hash(Void), hash(None))
def test_bool(self):
self.assertFalse(Void)
def test_len(self):
self.assertEqual(len(Void), 0)
def test_equal(self):
self.assertEqual(Void, 0)
self.assertEqual(Void, [])
self.assertEqual(Void, '')
def test_not_equal(self):
self.assertNotEqual(Void, 1)
self.assertNotEqual(Void, 42)
self.assertNotEqual(Void, -743.8)
self.assertNotEqual(Void, 'x')
self.assertNotEqual(Void, ['x'])
def test_less_or_equal(self):
self.assertTrue(Void <= None)
self.assertTrue(Void <= False)
self.assertTrue(Void <= [])
self.assertTrue(Void <= 0)
self.assertTrue(Void <= 17)
self.assertFalse(Void <= -1)
self.assertFalse(Void <= 'x')
# because True is 1 and Void is 0
self.assertTrue(Void <= True)
def test_greater_or_equal(self):
self.assertTrue(Void >= None)
self.assertTrue(Void >= False)
self.assertTrue(Void >= [])
self.assertTrue(Void >= 0)
self.assertTrue(Void >= -17)
self.assertFalse(Void >= 1)
self.assertFalse(Void >= 'x')
# because True is 1 and Void is 0
self.assertFalse(Void >= True)
def test_greater_than(self):
self.assertTrue(Void > -17)
self.assertFalse(Void > 0)
self.assertFalse(Void > 1)
# fails for not strictly mathematical comparisons
with self.assertRaises(TypeError):
Void > []
with self.assertRaises(TypeError):
Void > None
def test_less_than(self):
self.assertFalse(Void < -17)
self.assertFalse(Void < 0)
self.assertTrue(Void < 1)
# fails for not strictly mathematical comparisons
with self.assertRaises(TypeError):
Void < []
with self.assertRaises(TypeError):
Void < None
def test_call(self):
self.assertIsNone(Void('x', 'y', foo='bar'))
def test_getitem(self):
self.assertIsNone(Void['x'])
self.assertIsNone(Void[17])
def test_getattr(self):
self.assertIsNone(Void.jnfknjg)
def test_setitem(self):
Void['dfgdgd'] = 'fgfdbfdbgfb'
Void[0] = 'gfdfgfd'
Void[18] = 'gfdfgfd'
def test_setattr(self):
Void.dkjfgndkgjnkdfgn = 'kmdflgkmfdlgmkl'
def test_delitem(self):
del Void['ou9jgrg']
del Void[45]
def test_delattr(self):
del Void.fdgdfgdfdf934
def test_complex(self):
self.assertEqual(complex(Void), complex(0, 0))
def test_float(self):
self.assertEqual(float(Void), 0.0)
def test_int(self):
self.assertEqual(int(Void), 0)
def test_round(self):
self.assertEqual(round(Void), 0)
def test_trunc(self):
self.assertEqual(math.trunc(Void), 0)
def test_floor(self):
self.assertEqual(math.floor(Void), 0)
def test_ceil(self):
self.assertEqual(math.ceil(Void), 0)
def test_str(self):
self.assertEqual(str(Void), 'Void')
self.assertEqual('{0}'.format(Void), 'Void')
def test_repr(self):
self.assertEqual(repr(Void), 'Void')
def test_format(self):
self.assertEqual(format(Void, '^6'), ' Void ')
def test_context(self):
init_value = 'some value'
never_changed = init_value
with Void as eternal_nothingness:
eternal_nothingness.anything
never_changed = 'getattr failed to fail'
with Void as silence:
silence()
never_changed = 'call failed to fail'
with Void as devourer:
raise Exception('this should always get eaten')
self.assertEqual(never_changed, init_value)
async def _run_async_context(self):
init_value = 'some async value'
never_changed = init_value
async with Void as eternal_nothingness:
eternal_nothingness.anything
never_changed = 'getattr failed to fail'
async with Void as silence:
silence()
never_changed = 'call failed to fail'
async with Void as devourer:
raise Exception('this should always get eaten')
self.assertEqual(never_changed, init_value)
def test_async_context(self):
asyncio.run(self._run_async_context())
def test_iter(self):
init_value = 'some value'
never_changed = init_value
for x in Void:
never_changed = 'failed to not iter'
self.assertEqual(never_changed, init_value)
def test_reversed(self):
init_value = 'some value'
never_changed = init_value
for x in reversed(Void):
never_changed = 'failed to not reverse iter'
self.assertEqual(never_changed, init_value)
def test_bytes(self):
self.assertEqual(bytes(Void), b'')
def test_contains(self):
self.assertNotIn('x', Void)
self.assertNotIn(None, Void)
async def _run_coroutine(self):
await Void
def test_coroutine(self):
asyncio.run(self._run_coroutine())
async def _run_aiter(self):
init_value = 'some value'
never_changed = init_value
async for x in Void:
never_changed = 'failed to not iter'
self.assertEqual(never_changed, init_value)
def test_aiter(self):
asyncio.run(self._run_aiter())
def test_add(self):
self.assertIsNone(Void + 'x')
self.assertIsNone(Void + 434543)
self.assertIsNone(Void + [])
def test_sub(self):
self.assertIsNone(Void - 'x')
self.assertIsNone(Void - 3242)
self.assertIsNone(Void - {})
def test_mul(self):
self.assertIsNone(Void * 0)
self.assertIsNone(Void * 'fdss')
self.assertIsNone(Void * ('abc', 'def'))
def test_matmul(self):
self.assertIsNone(Void @ 'dsfsf')
def test_truediv(self):
self.assertIsNone(Void / 0)
self.assertIsNone(Void / 'sdfsd')
def test_floordiv(self):
self.assertIsNone(Void // 0)
self.assertIsNone(Void // {'hello': 'world'})
def test_mod(self):
self.assertIsNone(Void % 0)
self.assertIsNone(Void % ['oat milk', 'broccoli'])
def test_divmod(self):
self.assertIsNone(divmod(Void, 0))
def test_pow(self):
self.assertIsNone(pow(Void, 17, 342))
self.assertIsNone(Void ** 2)
def test_lshift(self):
self.assertIsNone(Void << 43)
def test_rshift(self):
self.assertIsNone(Void >> 12442)
def test_and(self):
self.assertIsNone(Void & b'\x0303ERROR\x03 WHY IS THIS CTCP')
def test_xor(self):
self.assertIsNone(Void ^ complex(16, 3))
def test_or(self):
self.assertIsNone(Void | b'\x00')
def test_radd(self):
self.assertIsNone('x' + Void)
self.assertIsNone(434543 + Void)
self.assertIsNone([] + Void)
def test_rsub(self):
self.assertIsNone('x' - Void)
self.assertIsNone(3242 - Void)
self.assertIsNone({} - Void)
def test_rmul(self):
self.assertIsNone(0 * Void)
self.assertIsNone('fdss' * Void)
self.assertIsNone(('abc', 'def') * Void)
def test_rmatmul(self):
self.assertIsNone('dsfsf' @ Void)
def test_rtruediv(self):
self.assertIsNone(0 / Void)
self.assertIsNone('sdfsd' / Void)
def test_rfloordiv(self):
self.assertIsNone(0 // Void)
self.assertIsNone({'hello': 'world'} // Void)
def test_rmod(self):
self.assertIsNone(0 % Void)
self.assertIsNone(['oat milk', 'broccoli'] % Void)
def test_rdivmod(self):
self.assertIsNone(divmod(17, Void))
def test_rpow(self):
self.assertIsNone(2 ** Void)
def test_rlshift(self):
self.assertIsNone(43 << Void)
def test_rrshift(self):
self.assertIsNone(12442 >> Void)
def test_rand(self):
self.assertIsNone(b'\x0303ERROR\x03 WHY IS THIS CTCP' & Void)
def test_rxor(self):
self.assertIsNone(complex(16, 3) ^ Void)
def test_ror(self):
self.assertIsNone(b'\x00' | Void)
def test_iadd(self):
global Void
Void += 'foo'
def test_isub(self):
global Void
Void -= 'foo'
def test_imul(self):
global Void
Void *= 'foo'
def test_imatmul(self):
global Void
Void @= 'foo'
def test_itruediv(self):
global Void
Void /= 'foo'
def test_ifloordiv(self):
global Void
Void //= 'foo'
def test_imod(self):
global Void
Void %= 'foo'
def test_ipow(self):
global Void
Void **= 'foo'
def test_ilshift(self):
global Void
Void <<= 'foo'
def test_irshift(self):
global Void
Void >>= 'foo'
def test_iand(self):
global Void
Void &= 'foo'
def test_ixor(self):
global Void
Void ^= 'foo'
def test_ior(self):
global Void
Void |= 'foo'
def test_neg(self):
self.assertIs(-Void, Void)
def test_pos(self):
self.assertIs(+Void, Void)
def test_abs(self):
self.assertIs(abs(Void), Void)
def test_invert(self):
self.assertIs(~Void, Void)
<file_sep>/void.py
# Copyright 2019 ashafer01
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
async def _async_no_op():
raise StopAsyncIteration
class VoidType(object):
"""Behaves universally falesy, 0-like, and None-like successfully
Anything that emits data will emit None successfully
This includes classically numeric operators
If the python spec requires a specific type, it will be falsey or
otherwise appropriately pythonic in some way
All input data is discarded successfully
Any equality comparisons will be True if other is falsey
Any strictly numeric comparisons will be completed using 0
Hashes to None (sadly we cannot satisfy `is None`)
Iterates over nothing successfully
Closes all context managers immediately and successfully
Works as no-op coroutine, async iterator, and async context manager as well
"""
# save memory
__slots__ = ('__weakref__',)
# hash to None
def __hash__(self):
return hash(None)
# be universally falsey
def __bool__(self):
return False
def __len__(self):
return 0
def __length_hint__(self):
return 0
def __eq__(self, other):
return not other
def __ne__(self, other):
return bool(other)
# be falsey for equality, and 0 for strictly numeric comparisons
def __le__(self, other):
try:
return 0 <= other
except TypeError:
return not other
def __ge__(self, other):
try:
return 0 >= other
except TypeError:
return not other
def __lt__(self, other):
return 0 < other
def __gt__(self, other):
return 0 > other
# always successfully emit none and discard input
def __call__(self, *args, **kwds):
pass
def __getitem__(self, key):
pass
def __getattr__(self, attr):
pass
def __setitem__(self, key, value):
pass
def __setattr__(self, attr, value):
pass
def __delitem__(self, key):
pass
def __delattr__(self, attr):
pass
# numeric conversions are all 0 or similar
def __complex__(self):
return complex(0, 0)
def __float__(self):
return 0.0
def __int__(self):
return 0
def __index__(self):
return 0
def __round__(self):
return 0
def __trunc__(self):
return 0
def __floor__(self):
return 0
def __ceil__(self):
return 0
# string behaviors are pythonic
def __str__(self):
return 'Void'
def __repr__(self):
return 'Void'
def __format__(self, format_spec):
return format('Void', format_spec)
# exit context managers immediately and successfully (see VoidContext def)
def __enter__(self):
return VoidContext()
def __exit__(self, etype, e, trace):
return True
async def __aenter__(self):
return VoidContext()
async def __aexit__(self, etype, e, trace):
async def exit():
return True
return exit
# iterate over nothing / behave like empty sequence
def __iter__(self):
return self
def __reversed__(self):
return self
def __bytes__(self):
return b''
def __contains__(self, other):
return False
# be a no-op coroutine and generator-iterator
def __await__(self):
return self
def __next__(self):
raise StopIteration
def send(self, value):
pass
def throw(self, type, value=None, traceback=None):
pass
def close(self):
pass
# asynchronously iterate over nothing
def __aiter__(self):
return self
async def __anext__(self):
raise StopAsyncIteration
async def asend(self, value):
return _async_no_op
async def athrow(self, type, value=None, traceback=None):
return _async_no_op
async def aclose(self):
return _async_no_op
# All operators follow the "always emit None" paradigm
# Many are "usually mathematic" and could behave like 0, but since they
# could be used with any `other` class then they are interpreted as
# emitting data and follow the paradigm.
# Multiplying sequences is a good example of why behaving like 0 is
# probably the wrong choice.
# This is also consistent with "discard input data" especially in the case
# of the in-place operators.
def __add__(self, other):
pass
def __sub__(self, other):
pass
def __mul__(self, other):
pass
def __matmul__(self, other):
pass
def __truediv__(self, other):
pass
def __floordiv__(self, other):
pass
def __mod__(self, other):
pass
def __divmod__(self, other):
pass
def __pow__(self, other, modulo=None):
pass
def __lshift__(self, other):
pass
def __rshift__(self, other):
pass
def __and__(self, other):
pass
def __xor__(self, other):
pass
def __or__(self, other):
pass
def __radd__(self, other):
pass
def __rsub__(self, other):
pass
def __rmul__(self, other):
pass
def __rmatmul__(self, other):
pass
def __rtruediv__(self, other):
pass
def __rfloordiv__(self, other):
pass
def __rmod__(self, other):
pass
def __rdivmod__(self, other):
pass
def __rpow__(self, other):
pass
def __rlshift__(self, other):
pass
def __rrshift__(self, other):
pass
def __rand__(self, other):
pass
def __rxor__(self, other):
pass
def __ror__(self, other):
pass
def __iadd__(self, other):
return self
def __isub__(self, other):
return self
def __imul__(self, other):
return self
def __imatmul__(self, other):
return self
def __itruediv__(self, other):
return self
def __ifloordiv__(self, other):
return self
def __imod__(self, other):
return self
def __ipow__(self, other, modulo=None):
return self
def __ilshift__(self, other):
return self
def __irshift__(self, other):
return self
def __iand__(self, other):
return self
def __ixor__(self, other):
return self
def __ior__(self, other):
return self
def __neg__(self):
return self
def __pos__(self):
return self
def __abs__(self):
return self
def __invert__(self):
return self
class VoidException(BaseException):
"""Use a BaseException to hopefully bypass any user exception handling"""
pass
class VoidContext(object):
"""Always raises an exception to immediately exit the context"""
# save memory
__slots__ = ('__weakref__',)
def __bool__(self):
raise VoidException()
def __len__(self):
raise VoidException()
def __length_hint__(self):
raise VoidException()
def __eq__(self, other):
raise VoidException()
def __le__(self, other):
raise VoidException()
def __ge__(self, other):
raise VoidException()
def __gt__(self, other):
raise VoidException()
def __lt__(self, other):
raise VoidException()
def __call__(self, *args, **kwds):
raise VoidException()
def __getitem__(self, key):
raise VoidException()
def __getattr__(self, attr):
raise VoidException()
def __setitem__(self, key, value):
raise VoidException()
def __setattr__(self, attr, value):
raise VoidException()
def __delitem__(self, key):
raise VoidException()
def __delattr__(self, attr):
raise VoidException()
def __complex__(self):
raise VoidException()
def __float__(self):
raise VoidException()
def __int__(self):
raise VoidException()
def __index__(self):
raise VoidException()
def __round__(self):
raise VoidException()
def __trunc__(self):
raise VoidException()
def __floor__(self):
raise VoidException()
def __ceil__(self):
raise VoidException()
def __str__(self):
raise VoidException()
def __repr__(self):
raise VoidException()
def __format__(self, format_spec):
raise VoidException()
def __enter__(self):
raise VoidException()
def __exit__(self, etype, e, trace):
raise VoidException()
def __aenter__(self):
raise VoidException()
def __aexit__(self, etype, e, trace):
raise VoidException()
def __iter__(self):
raise VoidException()
def __reversed__(self):
raise VoidException()
def __bytes__(self):
raise VoidException()
def __contains__(self):
raise VoidException()
def __await__(self):
return self
def __next__(self):
raise StopIteration
def __aiter__(self):
return self
def __anext__(self):
raise StopAsyncIteration
async def asend(self, value):
return _async_no_op
async def athrow(self, type, value=None, traceback=None):
return _async_no_op
async def aclose(self):
return _async_no_op
def __add__(self, other):
raise VoidException()
def __sub__(self, other):
raise VoidException()
def __mul__(self, other):
raise VoidException()
def __matmul__(self, other):
raise VoidException()
def __truediv__(self, other):
raise VoidException()
def __floordiv__(self, other):
raise VoidException()
def __mod__(self, other):
raise VoidException()
def __divmod__(self, other):
raise VoidException()
def __pow__(self, other, modulo=None):
raise VoidException()
def __lshift__(self, other):
raise VoidException()
def __rshift__(self, other):
raise VoidException()
def __and__(self, other):
raise VoidException()
def __xor__(self, other):
raise VoidException()
def __or__(self, other):
raise VoidException()
def __radd__(self, other):
raise VoidException()
def __rsub__(self, other):
raise VoidException()
def __rmul__(self, other):
raise VoidException()
def __rmatmul__(self, other):
raise VoidException()
def __rtruediv__(self, other):
raise VoidException()
def __rfloordiv__(self, other):
raise VoidException()
def __rmod__(self, other):
raise VoidException()
def __rdivmod__(self, other):
raise VoidException()
def __rpow__(self, other):
raise VoidException()
def __rlshift__(self, other):
raise VoidException()
def __rrshift__(self, other):
raise VoidException()
def __rand__(self, other):
raise VoidException()
def __rxor__(self, other):
raise VoidException()
def __ror__(self, other):
raise VoidException()
def __iadd__(self, other):
raise VoidException()
def __isub__(self, other):
raise VoidException()
def __imul__(self, other):
raise VoidException()
def __imatmul__(self, other):
raise VoidException()
def __itruediv__(self, other):
raise VoidException()
def __ifloordiv__(self, other):
raise VoidException()
def __imod__(self, other):
raise VoidException()
def __ipow__(self, other, modulo=None):
raise VoidException()
def __ilshift__(self, other):
raise VoidException()
def __irshift__(self, other):
raise VoidException()
def __iand__(self, other):
raise VoidException()
def __ixor__(self, other):
raise VoidException()
def __ior__(self, other):
raise VoidException()
def __neg__(self):
raise VoidException()
def __pos__(self):
raise VoidException()
def __abs__(self):
raise VoidException()
def __invert__(self):
raise VoidException()
Void = VoidType()
<file_sep>/README.md
# void.py
This was an exercise in creating a None-like object that tries to do nothing
successfully. Of course in many cases this is pointless, as doing nothing
successfully will just lead to different errors a little later on, but
nonetheless it seemed like an interesting task.
While I probably will make a more specific solution (and not actually use this),
the idea to do this occurred to me while thinking about how to have an
optionally configured storage backend within an application. Briefly I thought
it would be convenient to have a placeholder for the database object that would
just skip over the cursor() context manager calls where all the database logic
lives.
Again, in practice, this is probably a good solution for almost nothing. Don't
use it without heavy modification.
This will most likely only ever see the one commit in terms of maintenance.
Don't bother opening issues. PR's are welcome.
| 8926d873f48d3b00ba98748bb6b561fac7f62df8 | [
"Markdown",
"Python"
] | 3 | Python | ashafer01/void | e48d4449683c135a8796b09abbd8d81cda134957 | e06434df3d40bde9a3bc1a53f092629f0f29dd78 |
refs/heads/master | <repo_name>unalfaruk/FileNinja<file_sep>/fileNinja.py
import argparse
import os
from pathlib import Path
parser = argparse.ArgumentParser(description="File Splitter/Joinner")
subparser = parser.add_subparsers(dest="operation")
parser_join = subparser.add_parser("join", help="To join files...")
parser_join.add_argument("input_directory", help="The directory path containing chunks")
parser_join.add_argument("output_file",help="The file (path) to be created by joining chunks (default = inside of input_directory )")
parser_split = subparser.add_parser("split", help="To split a file into chunks...")
parser_split.add_argument("input_file", help="The file (path) to split")
parser_split.add_argument("output_directory", help="The directory path to store chunks created (default = the path of input_file )")
parser_split.add_argument("chunk_size", type=int, default=10, help="Set chunk size (default = 10 Mb)")
def Split(inputFile=None,outputDir=None,chunk=10):
if chunk == None:
chunk = 10
if outputDir == None:
outputDir = inputFile+"_DIR"
if not os.path.exists(outputDir):
os.makedirs(outputDir)
try:
with open(inputFile,"rb") as file:
counter=0
while 1:
part = file.read(1024*1024*int(chunk))
if not part:
break
with open (os.path.join(outputDir, str(counter)),"wb+") as io:
io.write(part)
counter = counter + 1
#print("Encoded successfully! The output file location is:",args.output)
print("Splitted successfully!")
return outputDir, counter
except Exception as e:
print(e)
return False
def Join(inputDir=None,outputFile=None):
if outputFile == None or outputFile=="":
outputFile = os.path.join(inputDir, Path(inputDir).name)
try:
with open(outputFile,"wb+") as io:
counter=0
while 1:
tmpFileToRead = os.path.join(inputDir,str(counter))
counter=counter+1;
if not os.path.exists(tmpFileToRead):
break
with open (tmpFileToRead,"rb") as file:
part = file.read()
io.write(part)
#print("Encoded successfully! The output file location is:",args.output)
print("Joinned successfully!")
return outputFile
except Exception as e:
print(e)
return False
def main():
#opening()
if args.operation == "split":
Split(args.input_file,args.output_directory,args.chunk_size)
if args.operation == "join":
Join(args.input_directory,args.output_file)
if __name__ == '__main__':
args = parser.parse_args()
main()<file_sep>/readme.md
# FileNinja v.0.1
## File Splitter and Joiner
This is a Python script using for splitting a file and joining chunks into a file.
* Dependencies: Python 3.x
### Notes to Who Wants to Use
It is just a simple script, I have prepared it for my specific need and generalized it later for others. So, there may be many bugs etc.
### Usage
1. JOINNING
> python3 fileNinja.py join <input_directory> <output_path>
> python3 fileNinja.py join ./test_dir/ ./test_dir/output.ext
2. SPLITTING
> python3 fileNinja.py split <input_file> <output_directory> <chunk_size_MB>
> python3 fileNinja.py split ./example.txt ./test_dir 1
### To-Do
1. argparse need to be improved.
* Some parameters (chunk size, output path) should be optional by giving them default value.
2. Usage by "import <module_name>" scenarios should be tested/verified
| 7735eeec84b91953db9478ce2ffe39083a1ecc27 | [
"Markdown",
"Python"
] | 2 | Python | unalfaruk/FileNinja | 4b472a23213d61dbbb805c4d136a2311f62684a9 | e95e2a7c631e32b031b5c7f373242a34ffd6f85c |
refs/heads/master | <file_sep>extern crate faerie;
use faerie::*;
#[test]
fn duplicate_declarations_are_ok() {
let mut obj = Artifact::new(Target::X86_64, "t.o".into());
obj.declare("str.0", faerie::Decl::DataImport {}).expect(
"initial declaration",
);
obj.declare(
"str.0",
faerie::Decl::Data {
global: false,
writeable: false,
},
).expect("declare should be compatible");
obj.define("str.0", b"hello world\0".to_vec())
.expect("define");
let mut obj = Artifact::new(Target::X86_64, "t.o".into());
obj.declarations(vec![
("str.0", faerie::Decl::DataImport),
("str.0", faerie::Decl::Data {
global: true,
writeable: false
}),
("str.0", faerie::Decl::DataImport),
("str.0", faerie::Decl::DataImport),
("str.0", faerie::Decl::Data {
global: true,
writeable: false
}),
("f", faerie::Decl::FunctionImport),
("f", faerie::Decl::Function { global: true }),
("f", faerie::Decl::FunctionImport),
("f", faerie::Decl::FunctionImport),
("f", faerie::Decl::Function { global: true }),
].into_iter()
).expect("multiple declarations are ok");
}
#[test]
fn multiple_different_declarations_are_not_ok() {
let mut obj = Artifact::new(Target::X86_64, "t.o".into());
obj.declare("f", faerie::Decl::FunctionImport {}).expect(
"initial declaration",
);
assert!(obj.declare(
"f",
faerie::Decl::Data {
global: false,
writeable: false,
},
).is_err());
}
#[test]
#[should_panic]
fn multiple_different_conflicting_declarations_are_not_ok_and_do_not_overwrite() {
let mut obj = Artifact::new(Target::X86_64, "t.o".into());
obj.declarations(vec![
("f", faerie::Decl::FunctionImport),
("f", faerie::Decl::Function { global: true }),
("f", faerie::Decl::FunctionImport),
("f", faerie::Decl::FunctionImport),
("f", faerie::Decl::Function { global: false }),
].into_iter()
).expect("multiple conflicting declarations are not ok");
}
#[test]
fn import_declarations_fill_imports_correctly() {
let mut obj = Artifact::new(Target::X86_64, "t.o".into());
obj.declarations(vec![
("f", faerie::Decl::FunctionImport),
("f", faerie::Decl::FunctionImport),
("d", faerie::Decl::DataImport),
].into_iter()
).expect("can declare");
let imports = obj.imports().collect::<Vec<_>>();
assert_eq!(imports.len(), 2);
}
#[test]
fn import_declarations_work_with_redeclarations() {
let mut obj = Artifact::new(Target::X86_64, "t.o".into());
obj.declarations(vec![
("f", faerie::Decl::FunctionImport),
("d", faerie::Decl::DataImport),
("d", faerie::Decl::DataImport),
("f", faerie::Decl::Function { global: true }),
("f", faerie::Decl::FunctionImport),
].into_iter()
).expect("can declare");
let imports = obj.imports().collect::<Vec<_>>();
assert_eq!(imports.len(), 1);
}
#[test]
fn import_helper_adds_declaration_only_once() {
let mut obj = Artifact::new(Target::X86_64, "t.o".into());
obj.import("f", faerie::ImportKind::Function).expect("can import");
let imports = obj.imports().collect::<Vec<_>>();
assert_eq!(imports.len(), 1);
}
| 29b93e516ca699efba8804d0edb74754a88204e1 | [
"Rust"
] | 1 | Rust | pchickey/faerie | 3180a18b12ce1189e755048d160dfcc0699cb68a | 38770bacdea50705be63ff9e80bd77f9db1bdfba |
refs/heads/master | <file_sep>
//Dependencies
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Order=require('./api/models/order'),
Customer = require('./api/models/customer'),
bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
var mongoUri = process.env.MONGODB_URI || 'mongodb://localhost/Neondb';
// Connect to the db
mongoose.connect(mongoUri, function(err, db) {
if(err) { return console.dir(err); }
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/neonRoutes');
routes(app);
app.listen(port);
console.log('todo list RESTful API server started on: ' + port);<file_sep>// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a customer schema
var customerSchema = new Schema({
customerid: String,
name: String,
phone: String,
mobile:String,
email: String,
address_list: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
cateogry: String,
channel: String,
// order_list: [{
// type: Schema.ObjectId,/
// ref: 'Order'
// }],
last_login: Date,
last_order: Date,
joined_on: Date,
updated_at: Date
});
// the schema is useless so far
// we need to create a model using it
var Customer = mongoose.model('Customers', customerSchema);
// make this available to our users in our Node applications
module.exports = Customer;
/* In your controller;
var User = require("models/User");
var House = require("models/House");
......
User.findById(req.user.id, function(err, user){
var houseModel = new House();
houseModel.adresse = "TEST";
user.houses.push(houseModel);
user.save();
});
*/<file_sep>
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create an order schema
var orderSchema = new Schema({
orderid: String,
customerid: {
type: Schema.ObjectId,
required: true,
ref: 'Customer'
},
orderamount: Number,
deliveryinstructions: String,
expressdelivery: Boolean,
deliveryman: String,
pickupaddress: String,
dropoffaddress: String,
order_date: Date,
pickup_date: Date,
dropoff_date: Date,
updated_at: Date
});
// the schema is useless so far
// we need to create a model using it
var Order = mongoose.model('Orders', orderSchema);
// make this available to our users in our Node applications
module.exports = Order; | 8709523b4bebb2024efeccf6f556221895f8df81 | [
"JavaScript"
] | 3 | JavaScript | sanjos30/N_eon_App | cb2471c63425f159ce61ffde2b36621618d28d43 | 3bfca3797212416a313f4f56e1eed6e95fa5f489 |
refs/heads/master | <file_sep>class AlterPages < ActiveRecord::Migration
def change
puts "***Adding an Index***"
add_index("pages", "permalink")
add_index("pages", "subject_id")
end
end
<file_sep>class ChangeTypeOfVisibleToBoolean < ActiveRecord::Migration
def up
change_column :subjects, :visible, :boolean, :default => false
end
def down
change_column :subjects, :visible, :integer, :default => false
end
end
<file_sep>class Page < ActiveRecord::Base
belongs_to :subject
has_many :sections
has_and_belongs_to_many :admin_users
scope :sorted, lambda { order ("position ASC")}
validates_presence_of :name
validates_length_of :name, :maximum => 255
validates_presence_of :permalink
validates_length_of :permalink, :within => 3..255
validates_uniqueness_of :permalink
end
<file_sep>class AlterSections < ActiveRecord::Migration
def change
puts "***Adding an Index***"
add_index("sections", "page_id")
end
end
<file_sep>class SectionEdit < ActiveRecord::Base
belongs_to :admin_user
belongs_to :section
end
| 4f18ecfdd888fdc25337413bcf75feacd69f98b8 | [
"Ruby"
] | 5 | Ruby | Moiz1524/cms_rails | 0c4dc79c9093ae8e7ef8d4d78a0fe78a01cdbda2 | f086e2591dc3620363fb656c55f8cf5312d02074 |
refs/heads/main | <repo_name>manhlee/btl_TGMT<file_sep>/readme.txt
B1:chụp các ảnh cần thiết vào thư mục trainingData
thư mục này chứa các file ảnh mẫu để sử dụng tạo đặc tính nhận dạng
B2: Chạy file "CreateFeatureFile.py" để tạo ra file đặc tính nhận dạng trong "feature.npy"
B3: Chạy file "Detect.py" để thực hiện chương trình
Chương trình sẽ sử dụng webcam của máy tính để chụp ảnh số tiền đưa vào sau đó đưa ra kết quả trên màn hình console
khi chạy file này ấn nút space thì máy sẽ tự động chụp ảnh sau đó lưu vào máy tính, chương trình thực hiện nhận dạng để đưa ra kết qủa
khi đã có kết quả chương trình sẽ xóa file ảnh vừa chụp đi.
<file_sep>/CreateFeatureFile.py
from __future__ import print_function #Use newest way to print if has new version in future
from __future__ import division #Use newest way to division if has new version in future
import numpy as np
from time import sleep #import sleep lib as delay in Microcontroller
import cv2 #import opencv lib
import time
# With surf and sift we can use bf or flann, akaze only use akaze
#cac thuat toan
detector=cv2.xfeatures2d.SIFT_create() #Quite long ~60secs 68sec :)
#detector = cv2.xfeatures2d.SURF_create()
#detector = cv2.AKAZE_create() # ~28s as powerpoint
# This is an array, each of the elements is a name directory of image.
# Dataset array
TraingIMGArr = ["TrainingData/10000F.png","TrainingData/10000B.png",
"TrainingData/20000F.png","TrainingData/20000B.png",
"TrainingData/50000F.png","TrainingData/50000B.png",
"TrainingData/100000F.png","TrainingData/100000B.png",
"TrainingData/200000F.png","TrainingData/200000B.png",
"TrainingData/500000F.png","TrainingData/500000B.png",
"TrainingData/box_empty.png"
]
# Create an array to save all feature of dataset, this will be help to improve speed of detecting
DesArr = []
start = time.time() # this variable to calculate time of getting feature of all dataset
for i in range(len(TraingIMGArr)):
get_Arrimg = TraingIMGArr[i] # Get image one by one from Array
read_Arrimg = cv2.imread(get_Arrimg,0) #Convert it to grayscale
trainKP,trainDesc=detector.detectAndCompute(read_Arrimg,None) #Procedures to get feature
DesArr.append(trainDesc) # Save to DesArr
end = time.time()
print("create feature success!!!")
print(end - start) #Print out running time to console
np.save("feature.npy", DesArr)
#temp = np.load("data.npy")
<file_sep>/Detect.py
from __future__ import print_function #Use newest way to print if has new version in future
from __future__ import division #Use newest way to division if has new version in future
#from time import sleep #import sleep lib as delay in Microcontroller
import os
import numpy as np
import cv2 #import opencv lib
import time
#mo camp
cam = cv2.VideoCapture(0)
cv2.namedWindow("input_money")
###############DETECT CODE###########################################################################
lower1 = np.array([81,35,141])
upper1 = np.array([157,255,255])
lower2 = np.array([49,113,70])
upper2 = np.array([206,255,109])
Ratio = 0.90 # Rate of distance, greater will be checked easier
# With surf and sift we can use bf or flann, akaze only use akaze
detector=cv2.xfeatures2d.SIFT_create()
#detector = cv2.xfeatures2d.SURF_create()
#detector = cv2.AKAZE_create()
#FLANN----------------- use for SIFT or SURF
FLANN_INDEX_KDITREE=0 #Procedures
flannParam=dict(algorithm=FLANN_INDEX_KDITREE,tree=5) #Procedures
flann=cv2.FlannBasedMatcher(flannParam,{}) #Procedures
#use SURF
#BF
BF = cv2.BFMatcher()
#-----------------------
#AKAZE when use akaze
AKAZE = cv2.DescriptorMatcher_create(cv2.DescriptorMatcher_BRUTEFORCE_HAMMING)
#------------------------
# This is an array, each of the elements is a name directory of image.
# Dataset array
TraingIMGArr = ["TrainingData/10000F.png","TrainingData/10000B.png",
"TrainingData/20000F.png","TrainingData/20000B.png",
"TrainingData/50000F.png","TrainingData/50000B.png",
"TrainingData/100000F.png","TrainingData/100000B.png",
"TrainingData/200000F.png","TrainingData/200000B.png",
"TrainingData/500000F.png","TrainingData/500000B.png",
"TrainingData/box_empty.png"
]
# Use to print to console and LCD
PrintingElement = ["10K","10K",
"20K","20K",
"50K","50K",
"100K","100K",
"200K","200K",
"500K","500K",
"Box empty"
]
#Loading features of dataset to DesArr
DesArr = np.load("feature.npy",allow_pickle=True)
while(1):
ret, frame = cam.read()
cv2.imshow("input_money", frame)
if not ret:
break
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Thoat chuong trinh!!")
break
if k%256 == 32:
# SPACE pressed
img_name = "img_input.png"
cv2.imwrite(img_name, frame)
print("That is:")
# Read image has just taken
Raw_usr_img=cv2.imread("img_input.png") #Read img from user (captured from raspberry)
PhotoDetect = cv2.resize(Raw_usr_img, (640,480))
PhotoDetect=PhotoDetect[130:420,40:630]
hsv_img = cv2.cvtColor(PhotoDetect, cv2.COLOR_BGR2HSV) # HSV image
#cv2.imshow("hsv_img",hsv_img)
mask_sub1 = cv2.inRange(hsv_img , lower1, upper1)
mask_sub2 = cv2.inRange(hsv_img , lower2, upper2)
mask = cv2.bitwise_or(mask_sub1,mask_sub2)
#cv2.imshow("hsv_img",mask)
_,contours, hierarchy = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
suma=0
for cnt in contours:
area = cv2.contourArea(cnt)
suma=suma+area
result=suma/(PhotoDetect.shape[0]*PhotoDetect.shape[1])
#print(result)
if result>120:
print ("PHOTO MONEY")
else:
Raw_usr_img=cv2.imread("img_input.png") #Read img from user (captured from raspberry)
queryKP,queryDesc=detector.detectAndCompute(Raw_usr_img,None) #Procedures to get feature from this picture
max_point = 0; # Max point
index_element_arr = 0; # Index which picture are detecting or detected to print out LCD or console
for i in range(len(TraingIMGArr)):
#matches=AKAZE.knnMatch(queryDesc,DesArr[i],k=2) #Procedures akaze
matches=BF.knnMatch(queryDesc,DesArr[i],k=2) #Procedures surf or sift
#print("DETECTING - " + PrintingElement[i]) #Print to console which image are being processed
Match_Count = 0 # Create a variable to count match points from 2 images
for m,n in matches:
if(m.distance < Ratio * n.distance): #If match
Match_Count += 1 #increase by 1
#print(Match_Count) #Print to console, comment if don't need it
if Match_Count >= max_point: # If the Match_Count greater than max_point
max_point = Match_Count # Assign max_point again
index_element_arr = i; # Assign idex to print to console and LCD
# Get end time
end = time.time()
#print(end - start)
#If box is empty, the match count usually < 30 MatchPoint
if Match_Count > 24:
#Print running time
print(PrintingElement[index_element_arr]+" VND") #After run all dataset, print to console which money was detected
else:
print("BOX IS EMPTY")
if os.path.exists("img_input.png"):
os.remove("img_input.png")
else:
print("The file does not exists")
cam.release()
cv2.destroyAllWindows()
| ffadac92e52aebc0d5f245d542138094197212ba | [
"Python",
"Text"
] | 3 | Text | manhlee/btl_TGMT | 7b9d491bd2bd61fbbd0879b87e5d3c87c4df67ac | f60de9384565a4f0fa5cdd1e07dbd674c0d27949 |
refs/heads/master | <repo_name>Norberta1314/documentbyunity3d<file_sep>/Assets/Scripts/ballTriggle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ballTriggle : MonoBehaviour
{
private ball m_ball;
private textscript m_text;
// Start is called before the first frame update
void Start()
{
m_ball = GameObject.Find("ball").GetComponent<ball>();
m_text = GameObject.Find("text").GetComponent<textscript>();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
// Debug.Log(other.gameObject.name);
if (other.gameObject.name == "ball")
{
Debug.Log("win!");
m_ball.FreezeBall();
m_text.disable();
}
}
private void OnTriggerExit(Collider other)
{
}
}
| 48d1519c5431e133064861f58777101cf4c60631 | [
"C#"
] | 1 | C# | Norberta1314/documentbyunity3d | f46c7476621c7fc74ecbd551db3f246c41e2531f | 021d72119b752486934b9fedc61f38d5e99e0ce9 |
refs/heads/master | <repo_name>neptunia/data-miner-simulator<file_sep>/special.js
var SAVE_KEY = 'save';
function save(state) {
localStorage.setItem(SAVE_KEY, JSON.stringify(state));
}
function load() {
return JSON.parse(localStorage.getItem(SAVE_KEY));
}
function delete_data() {
localStorage.clear();
}
state = load();
if (state) {
if (state.player.news.indexOf("spec1") >= 0) {
itm = document.getElementById("spec1div");
itm.classList.remove("hidden");
}
if (state.player.news.indexOf("spec2") >= 0) {
itm = document.getElementById("spec2div");
itm.classList.remove("hidden");
}
if (state.player.upgrades.indexOf("spec1") >= 0) {
itm = document.getElementById("spec1btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
}
if (state.player.upgrades.indexOf("spec2") >= 0) {
itm = document.getElementById("spec2btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
}
}
<file_sep>/game.js
var SAVE_KEY = 'save';
function save(state) {
localStorage.setItem(SAVE_KEY, JSON.stringify(state));
}
function load() {
return JSON.parse(localStorage.getItem(SAVE_KEY));
}
function delete_data() {
localStorage.clear();
}
function delete_data_2() {
delete_data();
location.reload();
}
state = load();
// new file
if (!state) {
// up to 10M users
var state = {
player: {
name: "Gewgle",
base_happiness: 70,
happiness_modifiers: 0,
happiness: 70, // user satisfaction
revenue: 0, // combine happiness and revenue to get market share?
cost: 500,
ad_amt: 10,
ppu: 1, // profit per user
users_mod: 1,
news: [0],
upgrades: [],
money: 10000,
users: 10000
},
turns_elapsed: 0,
npc: {name: "Yoohoo!",
happiness: 70,
revenue: 1000,
cost: 500,
money: 10000,
users: 10000
// enemy revenue just 500 * number of seconds elapsed
// enemy # of users just 300 * number of seconds elapsed (assume 80 happiness) + 10K
}
};
save(state);
}
console.log(JSON.stringify(state));
function demo_mode() {
state.player.users_mod = 1000;
state.player.ppu = 4;
state.player.users = 1000000;
}
function demo_mode_2() {
state.player.money = 10000000000;
}
function display_news() {
if (state.player.money >= 100000 && state.player.news.indexOf("rsc1") < 0) {
state.player.news.push("rsc1");
display_modal("Your programmers are ready to improve the search features!");
return;
}
if (state.player.money >= 1000000 && state.player.news.indexOf("rsc2") < 0) {
state.player.news.push("rsc2");
display_modal("It's time to hop onto the internet mail bandwagon, and create our own client!");
return;
}
if (state.player.money >= 5000000 && state.player.news.indexOf("rsc3") < 0) {
state.player.news.push("rsc3");
display_modal("People are fed up with netscape and internet explorer - time to make our own browser!");
return;
}
if (state.player.money >= 100000000 && state.player.news.indexOf("rsc4") < 0) {
state.player.news.push("rsc4");
display_modal("Buying a GPS is such a hassle... what if we make an online version?");
return;
}
if (state.player.money >= 500000000 && state.player.news.indexOf("rsc5") < 0) {
state.player.news.push("rsc5");
display_modal("Online collaborative office suites are no longer a pipe dream. We can make it a reality.");
return;
}
if (state.player.money >= 10000000 && state.player.news.indexOf("buy1") < 0) {
state.player.news.push("buy1");
display_modal("A new \"smartphone\" related startup in California has caught our eye. We should buy them out!");
return;
}
if (state.player.money >= 300000000 && state.player.news.indexOf("buy2") < 0) {
state.player.news.push("buy2");
display_modal("Our scouts have discovered a video sharing business.");
return;
}
if (state.player.money >= 1000000000 && state.player.news.indexOf("buy3") < 0 && state.player.upgrades.indexOf("rsc4") >= 0) {
state.player.news.push("buy3");
display_modal("There are so many competing map softwares... What can we do about that?");
return;
}
if (state.player.money >= 10000000000 && state.player.news.indexOf("buy4") < 0 && state.player.upgrades.indexOf("buy1") >= 0) {
state.player.news.push("buy4");
display_modal("Moterola is losing market share. Maybe we should 'help them out'.");
return;
}
if (state.player.money >= 3000000000 && state.player.news.indexOf("buy5") < 0 && state.player.upgrades.indexOf("buy4") >= 0) {
state.player.news.push("buy5");
display_modal("Smart homes seem to be one of those new trends. We can get in on it by buying another company.");
return;
}
if (state.player.money >= 500000000 && state.player.news.indexOf("buy6") < 0 && state.player.upgrades.indexOf("buy5") >= 0) {
state.player.news.push("buy6");
display_modal("AI is the future. We want to be part of the future.");
return;
}
if (state.player.news.indexOf("newsbuy4") < 0 && state.player.upgrades.indexOf("buy4") >= 0) {
state.player.news.push("newsbuy4");
display_modal("LMAO buying Moterola was a flop, we got a bunch of patents and a trade deal with <NAME> but it didn't really profit us anything feelsbadman");
return;
}
if (state.player.news.indexOf("spec2") < 0 && state.player.income > 1000000) {
state.player.news.push("spec2");
display_modal("We make enough money to hire a full-time lobbying team!");
return;
}
const income = Math.floor(state.player.users * state.player.ad_amt / 100.0 * state.player.ppu) - state.player.cost + state.player.revenue;
if (income > 15000000 && state.player.news.indexOf("newsantitrust") < 0) {
var count = 0;
var x;
for (x in state.player.upgrades) {
if (state.player.upgrades[x].startsWith("buy")) {
count += 1;
}
}
if (count >= 3) {
state.player.news.push("newsantitrust");
display_modal("Antitrust legislation is imposed against you, since you're buying too many companies! Take a $10000000 hit to profit.");
state.player.cost += 10000000;
save(state);
}
}
if (state.player.happiness_modifiers >= 20 && state.player.ad_amt >= 20 && state.player.ppu >= 2 && state.player.news.indexOf("newsadblock") < 0) {
state.player.news.push("newsadblock");
display_modal("Tired of all the targeted ads they're seeing, some users have begun to install adblocking software on their browsers. This has slightly reduced the value of your users' data.");
state.player.ppu -= 0.5;
save(state);
}
if (state.player.money >= 1000000000 && state.player.news.indexOf("newshacked") < 0) {
state.player.news.push("newshacked");
state.player.news.push("spec1");
display_modal("Oh no! You've been hacked by Russian hackers! This has made many of your customers very unhappy with your services, and you lost a lot of money. Better fix up security soon!");
state.player.money -= 500000000
state.player.happiness_modifiers -= 10;
save(state);
}
}
function marketshare() {
if (!state) {
state = load();
}
var p = document.querySelector("#p1");
const income = Math.floor(state.player.users * state.player.ad_amt / 100.0 * state.player.ppu) - state.player.cost + state.player.revenue;
p.MaterialProgress.setProgress((income) * 100.0 / (income + state.turns_elapsed * 500));
}
function display_modal(v) {
document.getElementById("dialog_data").innerHTML = v;
var dialog = document.querySelector('dialog');
dialog.showModal();
}
function update() {
if (!state) {
state = load();
}
state.turns_elapsed += 1;
get_ad_aggro();
increment_users();
increase_money();
// check if requirements have been fulfilled to display news
display_news();
try {
marketshare();
} catch(error) {
}
// if happiness below 50, lose members!!
// if no free users, happiness > 50, and happiness > npc's happiness, gain difference
try {
document.getElementById("money").innerHTML = "Money: $"+state.player.money;
document.getElementById("users").innerHTML = "Users: "+state.player.users;
document.getElementById("pop").innerHTML = "Satisfaction: "+state.player.happiness+"%";
} catch(error) {
//console.error(error);
}
save(state);
}
function increment_users() {
if (!state) {
console.log("uh oh");
state = load();
}
//console.log(state.player.users);
const n = state.player.happiness - 50;
if (n > 10) {
state.player.users += (Math.floor(n * state.player.users_mod)) * 10;
} else {
state.player.users += n * 10;
}
//console.log(state.player.users);
save(state);
}
function get_ad_aggro() {
if (!state) {
console.log("uh oh");
state = load();
}
if (document.getElementById("myRange") != null) {
state.player.ad_amt = document.getElementById("myRange").value;
}
state.player.happiness = state.player.base_happiness - state.player.ad_amt + state.player.happiness_modifiers;
save(state);
}
function increase_money() {
if (!state) {
console.log("uh oh");
state = load();
}
const income = Math.floor(state.player.users * state.player.ad_amt / 100.0 * state.player.ppu) - state.player.cost + state.player.revenue;
console.log(income);
state.player.money += income;
try {
document.getElementById("income").innerHTML = "Income: $"+income;
} catch(error) {
//console.error(error);
}
}
function rsc1() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 100000 && state.player.upgrades.indexOf("rsc1") < 0) {
state.player.money -= 100000;
state.player.happiness_modifiers += 5;
state.player.upgrades.push("rsc1");
save(state);
}
if (state.player.upgrades.indexOf("rsc1") >= 0) {
itm = document.getElementById("rsc1btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("rsc1btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function rsc2() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 1000000 && state.player.upgrades.indexOf("rsc2") < 0) {
state.player.money -= 1000000;
state.player.cost += 500;
state.player.ppu += 0.25;
state.player.happiness_modifiers += 5;
state.player.upgrades.push("rsc2");
save(state);
}
if (state.player.upgrades.indexOf("rsc2") >= 0) {
itm = document.getElementById("rsc2btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("rsc2btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function rsc3() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 5000000 && state.player.upgrades.indexOf("rsc3") < 0) {
state.player.money -= 5000000;
state.player.cost += 1000;
state.player.ppu += 0.5;
state.player.happiness_modifiers += 5;
state.player.users_mod += 1;
state.player.upgrades.push("rsc3");
save(state);
}
if (state.player.upgrades.indexOf("rsc3") >= 0) {
itm = document.getElementById("rsc3btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("rsc3btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function rsc4() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 100000000 && state.player.upgrades.indexOf("rsc4") < 0) {
state.player.money -= 100000000;
state.player.cost += 1000;
state.player.ppu += 0.5;
state.player.users_mod += 1;
state.player.upgrades.push("rsc4");
save(state);
}
if (state.player.upgrades.indexOf("rsc4") >= 0) {
itm = document.getElementById("rsc4btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("rsc4btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function rsc5() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 500000000 && state.player.upgrades.indexOf("rsc5") < 0) {
state.player.money -= 500000000;
state.player.cost += 1000;
state.player.users_mod += 1;
state.player.happiness_modifiers += 5;
state.player.upgrades.push("rsc5");
save(state);
}
if (state.player.upgrades.indexOf("rsc5") >= 0) {
itm = document.getElementById("rsc5btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("rsc5btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function buy1() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 10000000 && state.player.upgrades.indexOf("buy1") < 0) {
state.player.money -= 10000000;
state.player.cost += 700;
state.player.ppu += 0.3;
state.player.users_mod += 1;
state.player.upgrades.push("buy1");
save(state);
}
if (state.player.upgrades.indexOf("buy1") >= 0) {
itm = document.getElementById("buy1btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("buy1btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function buy2() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 300000000 && state.player.upgrades.indexOf("buy2") < 0) {
state.player.money -= 300000000;
state.player.cost += 1000;
state.player.f += 1;
state.player.users_mod += 2;
state.player.upgrades.push("buy2");
save(state);
}
if (state.player.upgrades.indexOf("buy2") >= 0) {
itm = document.getElementById("buy2btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("buy2btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function buy3() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 1000000000 && state.player.upgrades.indexOf("buy3") < 0) {
state.player.money -= 1000000000;
state.player.ppu += 0.2;
state.player.upgrades.push("buy3");
save(state);
}
if (state.player.upgrades.indexOf("buy3") >= 0) {
itm = document.getElementById("buy3btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("buy3btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function buy4() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 10000000000 && state.player.upgrades.indexOf("buy4") < 0) {
state.player.money -= 10000000000;
state.player.upgrades.push("buy4");
save(state);
}
if (state.player.upgrades.indexOf("buy4") >= 0) {
itm = document.getElementById("buy4btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("buy4btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function buy5() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 3000000000 && state.player.upgrades.indexOf("buy5") < 0) {
state.player.money -= 3000000000;
state.player.revenue += 5000;
state.player.ppu += 0.5;
state.player.happiness_modifiers += 5;
state.player.upgrades.push("buy5");
save(state);
}
if (state.player.upgrades.indexOf("buy5") >= 0) {
itm = document.getElementById("buy5btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("buy5btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function buy6() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.money >= 500000000 && state.player.upgrades.indexOf("buy6") < 0) {
state.player.money -= 500000000;
state.player.cost -= 100;
state.player.upgrades.push("buy6");
save(state);
}
if (state.player.upgrades.indexOf("buy6") >= 0) {
itm = document.getElementById("buy6btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("buy6btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function spec1() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.upgrades.indexOf("spec1") < 0) {
state.player.cost += 1000;
state.player.happiness_modifiers += 10;
state.player.upgrades.push("spec1");
save(state);
}
if (state.player.upgrades.indexOf("spec1") >= 0) {
itm = document.getElementById("spec1btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("spec1btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function spec2() {
if (!state) {
console.log("uh oh");
state = load();
}
if (state.player.upgrades.indexOf("spec2") < 0) {
state.player.revenue += 1000000;
state.player.happiness_modifiers -= 5;
state.player.upgrades.push("spec2");
save(state);
}
if (state.player.upgrades.indexOf("spec2") >= 0) {
itm = document.getElementById("spec2btn");
itm.disabled = true;
itm.innerHTML = "Purchased";
} else {
itm = document.getElementById("spec2btn");
itm.disabled = false;
itm.innerHTML = "Purchase";
}
}
function sliderChange(value) {
document.getElementById("adagg").innerHTML = "Advertisement Aggressiveness: "+value+"%"
}
try {
myRange.value = state.player.ad_amt;
sliderChange(state.player.ad_amt);
} catch(error) {
}
window.setInterval(function(){
update();
}, 1000);
<file_sep>/README.md
# data-miner-simulator
HACS game for data mining (for hacs101 2018)
--------
Simulate being a big company (search engine) who will expand their business through mining user data. To raise awareness on the different ways companies can harvest data from users.
| 818a6db219441c3935e343dbce7467def8e188bf | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | neptunia/data-miner-simulator | 9c5c7afeada24da2783a37fd69ef8f44f97ca1ca | 19c038edbb3cff449924ab55508507a9c8a419aa |
refs/heads/master | <file_sep>const sharp = require('sharp');
const AWS = require('aws-sdk');
const config = require('../config');
const AdmZip = require('adm-zip');
// Set credentials and region
const s3 = new AWS.S3({
apiVersion: '2006-03-01',
region: 'us-west-2',
credentials: new AWS.Credentials({
accessKeyId: config.aws.key,
secretAccessKey: config.aws.secret,
}),
});
class Util {
constructor() {
throw new Error(`plz do not instantiate this class :P`);
}
static upload(pack, name, stream) {
return new Promise((resolve, reject) => {
s3.upload({
Bucket: 'discord-stickers',
Key: `${pack}/${name}.png`,
ContentType: 'image/png',
Body: stream,
}, (err, data) => {
if (err) reject(err);
if (data) resolve(data);
});
});
}
static resize(buffer) {
return new Promise((resolve, reject) => {
sharp(buffer)
.resize(120, 120)
.min()
.png({
progressive: true,
compressionLevel: 5,
})
.toBuffer((err, buff) => {
if (err) reject(err);
else resolve(buff);
});
});
}
static inflate(buffer) {
return new Promise((resolve, reject) => {
const zip = new AdmZip(buffer);
if (zip.getEntries) resolve(zip);
else reject(zip);
});
}
static noop() {} // eslint-disable-line
}
module.exports = Util;
<file_sep>const Discord = require('discord.js');
const config = require('../config');
const superagent = require('superagent');
const Util = require('./Util');
const Storage = require('./Storage');
const client = new Discord.Client();
const commands = {
uploadSingle: (message, content) => {
const match = /^(.+)\/(.+) (.+)/i.exec(content);
if (!match) return;
const pack = match[1];
const sticker = match[2];
const remote = match[3].replace(/<|>/g, '');
const key = `${pack}-${sticker}`;
const front = `${pack}/${sticker}`;
if (!Storage.has(key) || Storage.get(key).owner === message.author.id) {
superagent.get(remote)
.then((r) => Util.resize(r.body))
.then((b) => Util.upload(pack, sticker, b))
.then(() => {
Storage.set(key, {
owner: message.author.id,
});
message.reply(`**Created \`${front}\`!**`);
console.log('CREATED', key);
})
.catch((e) => {
console.error(e);
message.reply(`**Failed to create \`${front}\`!**`);
});
} else {
message.reply(`**You do not have permission to overwrite \`${front}\`!**`);
}
},
uploadZip: async (message, content) => {
const [pack, remote] = content.split(' ');
if (!pack || !remote) return;
superagent.get(remote)
.parse((res, cb) => {
res.data = '';
res.setEncoding('binary');
res.on('data', (chunk) => {
res.data += chunk;
});
res.on('end', () => {
cb(null, new Buffer(res.data, 'binary'));
});
})
.buffer(true)
.then((r) => Util.inflate(r.body))
.then((inflated) =>
Promise.all(inflated.getEntries().map(f =>
Util.resize(f.getData()).then((data) => Util.upload(pack, f.entryName, data))
))
)
.then((done) => {
console.log(done);
// purposely not a template literal until i finish this
return message.reply('**Added ${count} cards to ${pack} pack!**');
})
.catch((e) => {
console.error(e);
message.reply(`**Failed to upload zip!**`);
});
},
get: (message, content) => {
const match = /^(.+)\/(.+)/i.exec(content);
if (!match) return;
const pack = match[1];
const sticker = match[2];
const url = `${config.s3url}/${pack}/${sticker}.png`;
message.delete().catch(Util.noop);
message.channel.sendFile(url, `${pack}-${sticker}.png`).catch(e => console.error(url, e.message, e.status));
return;
},
};
client.on('message', (message) => {
if (!message.content.startsWith('s!')) return;
const content = message.cleanContent.replace('s!', '').trim();
if (content.startsWith('putzip')) {
commands.uploadZip(message, content.replace(/^putzip/, '').trim());
} else if (content.startsWith('put') || content.startsWith('add')) {
commands.uploadSingle(message, content.replace(/^put|^add/, '').trim());
return;
} else {
commands.get(message, content);
return;
}
});
client.on('ready', () => {
console.log('[CLIENT] Ready!', client.user.username, client.user.id);
});
client.login(config.token);
| c25fb2afaaef68dfc00b36e3b0fdc5700353849e | [
"JavaScript"
] | 2 | JavaScript | devsnek/stickerbot | a90c01240f9553e7b625a84d0a12b744c8fb08d5 | aaeb125120a650294c8f73eae1f610bb61527951 |
refs/heads/master | <file_sep><?php
/**
* Session Flash Messages
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @version 1.2.6
* @package Phalcon
*/
namespace Phalcon\Flash;
use \Phalcon\Flash,
\Phalcon\FlashInterface,
\Phalcon\DI\InjectionAwareInterface,
\Phalcon\Flash\Exception,
\Phalcon\DiInterface,
\Phalcon\Session\AdapterInterface as SessionAdapterInterface;
/**
* Phalcon\Flash\Session
*
* Temporarily stores the messages in session, then messages can be printed in the next request
*
* @see https://github.com/phalcon/cphalcon/blob/1.2.6/ext/flash/session.c
*/
class Session extends Flash implements FlashInterface, InjectionAwareInterface
{
/**
* Denpendency Injector
*
* @var null|\Phalcon\DiInterface
* @access protected
*/
protected $_dependencyInjector;
/**
* Sets the dependency injector
*
* @param \Phalcon\DiInterface $dependencyInjector
* @throws Exception
*/
public function setDI($dependencyInjector)
{
if(is_object($dependencyInjector) === false ||
$dependencyInjector instanceof DiInterface === false) {
throw new Exception('Invalid parameter type.');
}
$this->_dependencyInjector = $dependencyInjector;
}
/**
* Returns the internal dependency injector
*
* @return \Phalcon\DiInterface|null
*/
public function getDI()
{
return $this->_dependencyInjector;
}
/**
* Returns the messages stored in session
*
* @param boolean $remove
* @return mixed
* @throws Exception
*/
protected function _getSessionMessages($remove)
{
if(is_bool($remove) === false) {
throw new Exception('Invalid parameter type.');
}
if(is_object($this->_dependencyInjector) === false) {
throw new Exception('A dependency injection container is required to access the \'session\' service');
}
$session = $this->_dependencyInjector->getShared('session');
if(is_object($session) === false ||
$session instanceof SessionAdapterInterface === false) {
throw new Exception('Session service is unavailable.');
}
$messages = $session->get('_flashMessages');
if($remove === true) {
$session->remove('_flashMessages');
}
return $messages;
}
/**
* Stores the messages in session
*
* @param array $messages
* @throws Exception
* @return array
*/
protected function _setSessionMessages($messages)
{
if(is_array($messages) === false) {
throw new Exception('Invalid parameter type.');
}
if(is_object($this->_dependencyInjector) === false) {
throw new Exception('A dependency injection container is required to access the \'session\' service');
}
$session = $this->_dependencyInjector->getShared('session');
if(is_object($session) === false ||
$session instanceof SessionAdapterInterface === false) {
throw new Exception('Session service is unavailable.');
}
$session->set('_flashMessages', $messages);
return $messages;
}
/**
* Adds a message to the session flasher
*
* @param string $type
* @param string $message
* @throws Exception
*/
public function message($type, $message)
{
if(is_string($type) === false ||
is_string($message) === false) {
throw new Exception('Invalid parameter type.');
}
$messages = $this->_getSessionMessages(false);
if(is_array($messages) === false) {
$messages = array();
}
if(isset($messages[$type]) === false) {
$messages[$type] = array();
}
$messages[$type][] = $message;
$this->_setSessionMessages($messages);
}
/**
* Returns the messages in the session flasher
*
* @param string|null $type
* @param boolean|null $remove
* @return array
* @throws Exception
*/
public function getMessages($type = null, $remove = null)
{
if(is_null($remove) === true) {
$remove = true;
}
$doRemove = $remove;
if(is_string($type) === true) {
$doRemove = false;
} elseif(is_null($type) === false) {
throw new Exception('Invalid parameter type.');
}
$messages = $this->_getSessionMessages($doRemove);
if(is_array($messages) === true) {
if(is_null($type) === false) {
if(isset($messages[$type]) === true) {
$returnMessages = $messages[$type];
if($remove === true) {
unset($messages[$type]);
$this->_setSessionMessages($messages);
}
return $returnMessages;
}
return array();
}
return $messages;
}
return array();
}
/**
* Prints the messages in the session flasher
*
* @param boolean $remove
* @throws Exception
*/
public function output($remove = null)
{
if(is_null($remove) === true) {
$remove = true;
} elseif(is_bool($remove) === false) {
throw new Exception('Invalid parameter type.');
}
$messages = $this->_getSessionMessages($remove);
if(is_array($messages) === true) {
foreach($messages as $type => $message) {
$this->outputMessage($type, $message);
}
}
}
} | 77b4d62095efbb3983e286c9062c078e06322880 | [
"PHP"
] | 1 | PHP | rafaeltecna/phalcon-php | 5eb89c076c9e01eaaa56652a347a98cde0c77748 | 9084ea659577b95dc713b7bb8aeca920960e4af8 |
refs/heads/master | <file_sep>/*=================================================================
*
* mex-projL1Inf.C .MEX file that computes the l1Inf projection of a Matrix W
*
* The calling syntax is:
*
* [B] = projL1Inf(A, C, w)
*
* Inputs:
*
* A: a d-times-m matrix to project into the l1Inf ball
*
* w: a d-dimensional vector where the ith entry corresponds to the weight of the ith row of A
*
* C: ball bound
*
* Outputs:
*
* B : a d-times-m matrix such that sum_i=1:d [w_i * max_k |B(i,k)| ] = c
*
*=================================================================*/
/* $Revision: 2$ */
#include <math.h>
#include "mex.h"
/* Input Arguments */
#define A_IN prhs[0]
#define C_IN prhs[1]
#define W_IN prhs[2]
/* Output Arguments */
#define B_OUT plhs[0]
#include "projL1Inf.c"
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray*prhs[]) {
double *B;
double *A,*c,*w;
int nRows,nCols;
nRows = mxGetM(A_IN);
nCols = mxGetN(A_IN);
/* Create a matrix for the return argument */
B_OUT = mxCreateDoubleMatrix(nRows, nCols, mxREAL);
if(B_OUT==NULL)
printf("ERROR: NO MORE HEAP SPACE");
/* Assign pointers to the various parameters */
B = mxGetPr(B_OUT);
A = mxGetPr(A_IN);
c = mxGetPr(C_IN);
w = mxGetPr(W_IN);
/* Do the actual computations in a subroutine */
projL1Inf(B,*c,A,w,nRows,nCols);
return;
}
<file_sep>/*=================================================================
*
* projL1Inf.c
*
*
* first released on June 2009
* revised on September 2011
*=================================================================*/
#include <stdlib.h>
#include <math.h>
struct residual_t{
int rowInd;
double value;
};
static void printMatrix(double *m, int nRows,int nCols) {
int i,j,index;
double value;
for(i=0;i<nRows;i++) {
for (j=0;j<nCols;j++) {
index=(j)*nRows + i;
value=m[index];
printf("%f ",value);
}
printf("\n");
}
}
static double normL1Inf(double *m, int nRows, int nCols) {
double norm=0;
int i, j, index;
for(i=0;i<nRows;i++) {
double maxRow=0;
for (j=0;j<nCols;j++) {
index=j*nRows + i;
double value=fabs(m[index]);
if(value>maxRow) {
maxRow=value;
}
}
norm= norm + maxRow;
}
return norm;
}
int compare(const void *_a, const void *_b) {
double *a, *b;
a = (double *) _a;
b = (double *) _b;
if(*a==*b)
return 0;
if(*a > *b)
return -1;
if(*a < *b)
return 1;
}
int compareR(const void *_a, const void *_b) {
struct residual_t *a, *b;
a = (struct residual_t *) _a;
b = (struct residual_t *) _b;
if((*a).value==(*b).value)
return 0;
if((*a).value < (*b).value)
return -1;
if((*a).value > (*b).value)
return 1;
}
static void projL1Inf(double B[], double C, double A[],
double w[], int nRows, int nCols) {
int i, j, index;
int rowIndex, colIndex, nonZero;
double *maxes;
int *sparseMap;
double maxRow,value,l1InfNorm;
maxes = (double*) malloc(sizeof(double)*nRows);
for(i=0;i<nCols*nRows;i++) {
B[i] = A[i];
}
/* 1- Compute L1InfNorm and maxes, if <= C copy matrix A to output B and return. Else move to 2 */
l1InfNorm=0;
nonZero=0;
for(i=0;i<nRows;i++) {
maxRow=0;
for (j=0;j<nCols;j++) {
index=j*nRows + i;
value=fabs(A[index]);
if(value>maxRow) {
maxRow=value;
}
}
maxes[i]=maxRow;
l1InfNorm= l1InfNorm + w[i] * maxRow;
if(maxRow>0) {
nonZero++;
}
}
if(l1InfNorm<=C) {
free(maxes);
return;
}
/* 2- Copy to new matrix AP of absolute values, do this for rows with maximums larger than 0, remember the mappings between the rows of A and the rows of AP */
sparseMap = (int*) malloc(sizeof(int)*nonZero);
double *sparseW= (double*) malloc(sizeof(double)*nonZero);
index=0;
for(i=0;i<nRows;i++) {
if(maxes[i]>0) {
sparseMap[index]=i;
sparseW[index]=w[i];
index++;
}
}
/* create nonZero rows of nCols+1 size */
double *S = (double*) calloc((nCols +1) *nonZero, sizeof(double));
/*
for(i=0;i<(nCols+1)*nonZero;i++) {
S[i]=0;
}
*/
for(i=0;i<nonZero;i++) {
for (j=0; j<nCols; j++) {
index=j*nRows + sparseMap[i];
value=fabs(A[index]);
index=i*(nCols+1)+j;
S[index]=value;
}
/*
printf("S[%d]:", sparseMap[i]);
for (j=0;j<nCols;++j) printf(" %f", S[i*(nCols+1)+j]);
printf("\n");
*/
}
/* 3- Sort Colums of S */
int indx=0;
for(i=0;i<nonZero;i++) {
qsort(&S[indx], nCols+1, sizeof(double), &compare);
indx=indx + nCols + 1;
}
/*
printf("S = \n");
printMatrix(S,nCols+1,nonZero);
*/
/* 5- Compute Residual */
struct residual_t *R;
R= (struct residual_t*) malloc(sizeof(struct residual_t)*nonZero*(nCols+1));
double residual,si;
indx=0;
for (i=0;i<nonZero;i++) {
R[indx].rowInd=i;
R[indx].value=0;
residual=S[indx];
indx++;
for (j=0;j<nCols;j++) {
R[indx].rowInd=i;
R[indx].value=residual - S[indx] * (j+1);
residual=residual + S[indx];
indx++;
}
}
/* 6- Merge Residual */
qsort(R, (nCols+1)*nonZero, sizeof(struct residual_t), &compareR);
/*
printf("Residuals \n");
for (i=0;i<(nCols+1)*nonZero;i++)
{
printf("row index %d value %f \n", R[i].rowInd,R[i].value);
} */
/* 7- Enter Loop to compute theta */
/* points to the current position in R */
int idxR=0;
/* gradient of the N function, at interval [ R[idxR].value , R[idxR+1].value ] */
double Gradient=0;
/* Ks[j] counts how many points of row j we did visit in R, this includes the first point of the current interval;
-1/Ks[j] is the gradient of h_j in the current interval */
int *Ks = (int*) malloc(sizeof(int)*nonZero);
for (i=0;i<nonZero;i++) {
Ks[i]=0;
}
/* to initialize we skip all the entries in R corresponding to 0 residual,
for each row i there will be n_i entries, where n_i is the number of maximums of row i */
while(R[idxR].value<=0.0) {
Ks[R[idxR].rowInd]++;
idxR++;
}
idxR=idxR-1;
for (i=0;i<nonZero;i++) {
Gradient += -sparseW[i]/(double) Ks[i];
}
/* norm at R[idxR].value */
double Norm=l1InfNorm;
/* norm at next point, i.e. R[idxR+1].value */
double nextNorm = Gradient * (R[idxR+1].value - R[idxR].value ) + Norm;
/*
printf("INI iteration %d row=-- norm=%f gradient=%f nextNorm=%f K=[", idxR, Norm, Gradient, nextNorm);
{ int k; for(k=0;k<nonZero;++k) { printf("%d ", Ks[k]); } printf("]\n"); }*/
/* keep crossing points in R until we hit the right interval */
while (nextNorm>C) {
idxR++;
Norm=nextNorm;
int r=R[idxR].rowInd;
if (1) {
// remove r-th term from the Gradient
Gradient += sparseW[r]/(double) Ks[r];
// increment the number of points we visited of the r-th row
Ks[r]++;
// update the r-th component of the gradient
if (Ks[r]<=nCols) {
Gradient += -sparseW[r]/(double) Ks[r];
}
}
else {
Ks[r]++;
/* the r'th gradient becomes 0 when we have crossed nCols+1 points */
Gradient = 0;
for (i=0; i<nonZero; ++i)
{
if (Ks[i]<=nCols)
{
Gradient += -sparseW[i]/(double) Ks[i];
}
}
}
nextNorm = Gradient * (R[idxR+1].value - R[idxR].value ) + Norm;
/*
printf("iteration %d row=%d norm=%f gradient=%f nextNorm=%f K=[", idxR, r, Norm, Gradient, nextNorm);
{ int k; for(k=0;k<nonZero;++k) { printf("%d ", Ks[k]); } printf("]\n"); }*/
}
double theta = (C - Norm + Gradient*R[idxR].value)/Gradient;
/* 8- Compute mu_i for all i */
double *mu = (double*) malloc(nonZero*sizeof(double));
double sum = 0;
for (i=0; i<nonZero; ++i) {
if (Ks[i]<=nCols) {
int j=idxR;
while (R[j].rowInd!=i) j--;
mu[i] = S[i*(nCols+1)+Ks[i]-1] - (1/(double) Ks[i])*(theta-R[j].value);
}
else mu[i] = 0;
sum += sparseW[i] * mu[i];
}
/*
printf("theta: %f; new norm: %f; \n", theta, sum);
*/
/* 9- Create output matrix */
/*
printf("Ms = \n");
printMatrix(mu,1,nonZero);
*/
for(i=0;i<nRows*nCols;i++) {
B[i]=A[i];
}
/*
printf("A= \n");
printMatrix(B,nRows,nCols);
*/
for(i=0;i<nonZero;i++) {
for(j=0;j<nCols;j++) {
index=(j)*nRows + sparseMap[i];
if(B[index] > mu[i] || -B[index] > mu[i]) {
if(A[index]>=0.0)
B[index] = mu[i];
else
B[index]=-mu[i];
}
}
}
/*
printf("B = \n");
printMatrix(B,nRows,nCols);
*/
free(maxes);
free(sparseMap);
free(S);
free(R);
free(Ks);
free(mu);
return;
}
<file_sep># altginv
Matlab ADMM code to compute some norm-minimizing generalized inverses. Written for the following two-part paper series by <NAME> and <NAME>:
- [Beyond Moore-Penrose, Part I: Generalized Inverses that Minimize Matrix Norms](https://arxiv.org/abs/1706.08349)
- [Beyond Moore-Penrose, Part II: The Sparse Pseudoinverse](https://arxiv.org/abs/1706.08701)
## Main functions
| Filename | Description |
| ----------------- | ------------------- |
| ginvadmm.m | (Linearized) ADMM for generalized inverse computation |
## Helper functions
| Filename | Description |
| ----------------- | ------------------- |
| prox_l1.m | Proximal operator for the l1 entrywise norm |
| prox_l1l1.m | Proximal operator for the l1->l1 induced norm |
| prox_l1l2.m | Proximal operator for the l1->l2 induced norm |
| prox_row21.m | Proximal operator for the (2,1)-rowwise mixed norm |
| proj_col21.m | Projection onto the norm ball of the (2,1)-columnwise mixed norm |
For more details about the relevant definitions see the above two papers. __The proximal mapping for the l1->l1 induced norm uses a projection operator proposed in the following paper:__
> <NAME>., <NAME>., <NAME>., & <NAME>. (2009). An Efficient Projection for $\ell_{1,\infty}$ Regularization (pp. 857–864). Presented at ICML 2009. http://doi.org/10.1145/1553374.1553484
The associated C (MEX) implemention (by Quattoni et al.) is in `projL1Inf.c`. It should be MEX-compiled in Matlab on the target platform.
## Examples and paper figures
| Filename | Description |
| ----------------- | ------------------- |
| Example_FrobeniusSpinv.m | Creates the figures related to the Frobenius norm of the Moore-Penrose and sparse pseudoinverses |
| 9282edb36b734279ecf5595fb589a9855ff44691 | [
"Markdown",
"C"
] | 3 | C | doksa/altginv | 67e823c1c828ae0f08990460b08f943b054f9d46 | 79ec151187751ad81eee12a07f90ebde88214f57 |
refs/heads/master | <file_sep>import React from 'react';
const Welcome = () => {
return (
<div>
<h3>Welcome! Feel free to play around.</h3>
<p>{"React is pretty cool, isn't it?"}</p>
</div>
);
}
export default Welcome;
<file_sep>import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
import * as actions from '../../actions';
class Signup extends Component {
handleFormSubmit(formProps) {
this.props.signupUser(formProps);
}
renderAlert() {
if (this.props.errorMessage) {
return (
<div className="alert alert-danger">
<strong>Error!</strong> {this.props.errorMessage}
</div>
);
}
}
render() {
const { handleSubmit, fields: { email, password, passwordConfirm }} = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<fieldset className="form-group">
<label>Email:</label>
<input className="form-control" type="email" {...email} />
{email.touched && email.error && <div className="error">{email.error}</div>}
</fieldset>
<fieldset className="form-group">
<label>Password:</label>
<input className="form-control" type="password" {...password} />
{password.touched && password.error && <div className="error">{password.error}</div>}
</fieldset>
<fieldset className="form-group">
<label>Confirm Password:</label>
<input className="form-control" type="password" {...passwordConfirm} />
{passwordConfirm.touched && passwordConfirm.error && <div className="error">{passwordConfirm.error}</div>}
</fieldset>
{this.renderAlert()}
<button type="submit" className="btn btn-primary">Sign up</button>
</form>
);
}
}
function validate(formProps) {
const errors = {};
const { email, password, passwordConfirm } = formProps;
for (let key in formProps) {
if (!formProps[key]) {
errors[key] = `${key} cannot be blank`;
// Special cases
if (key === 'passwordConfirm') {
errors[key] = 'please repeat your password';
}
}
}
if (password !== passwordConfirm) {
errors.password = "Passwords don't match";
}
return errors;
}
function mapStateToProps(state) {
return { errorMessage: state.auth.error };
}
export default reduxForm({
form: "SignupForm",
fields: ['email', 'password', 'passwordConfirm'],
validate
}, mapStateToProps, actions)(Signup);
<file_sep>import axios from 'axios';
import { browserHistory } from 'react-router';
import {
AUTH_USER,
AUTH_ERROR,
UNAUTH_USER,
FETCH_MESSAGE
} from './types';
const ROOT_URL = 'http://localhost:3090';
export function signinUser({ email, password }) {
// Submit email/pw to server
// If all OK:
// update state (authenticated: true)
// save the token
// redirect to /feature Route
// Otherwise:
// display an error to user
// With redux-thunk, you return a function that has access to dispatch
return (dispatch) => {
axios.post(`${ROOT_URL}/signin`, { email, password })
.then((response) => {
dispatch({ type: AUTH_USER });
localStorage.setItem('token', response.data.token);
// redirect to a different route programatically
browserHistory.push('/feature');
})
.catch(() => {
// call another action creator from within this action creator
dispatch(authError('Your login information is invalid'));
});
};
}
export function signupUser({ email, password }) {
return (dispatch) => {
axios.post(`${ROOT_URL}/signup`, { email, password })
.then((response) => {
console.log(response);
dispatch({ type: AUTH_USER });
localStorage.setItem('token', response.data.token);
browserHistory.push('/feature');
})
.catch((error) => {
// Axios API v0.13 changed,
// so you have to use error.response instead of just response
dispatch(authError(error.response.data.error));
})
;
};
}
// use separate action creator for error
export function authError(error) {
return {
type: AUTH_ERROR,
payload: error
};
}
export function signoutUser() {
localStorage.removeItem('token');
return {
type: UNAUTH_USER
};
}
export function fetchMessage() {
return dispatch => {
axios.get(`${ROOT_URL}/hidden`, {
headers: { authorization: localStorage.getItem('token') }
})
.then(response => {
console.log(response);
dispatch({
type: FETCH_MESSAGE,
payload: response.data.message
});
})
.catch(() => {
console.log("Error trying to get hidden message");
alert("Hey. You cannot access this page.");
})
;
};
}
<file_sep># client-side-auth
| e4610efa61ae259896a46c1ae18de7e2d4912261 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | nbkhope/client-side-auth | 2e39d71e2a0f57093ddb85361c0536374403b2cd | 8b03ad762e208708d921b67eb865b7221fdfe11b |
refs/heads/master | <repo_name>rasyidcode/SimpleProgramCode<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/home/FavoriteFragment.kt
package me.jamilalrasyidis.simpleprogramcode.ui.home
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.gms.ads.AdRequest
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.databinding.FragmentFavoriteBinding
import me.jamilalrasyidis.simpleprogramcode.extension.countNewLine
import me.jamilalrasyidis.simpleprogramcode.ui.detail.DetailViewModel
import org.jetbrains.anko.progressDialog
import org.koin.android.viewmodel.ext.android.viewModel
import java.util.*
class FavoriteFragment : Fragment() {
private val viewModel by viewModel<DetailViewModel>()
private val favoriteListAdapter by lazy { FavoriteListAdapter() }
private lateinit var binding: FragmentFavoriteBinding
private var favoritesData = mutableListOf<FavoriteData>()
@Suppress("DEPRECATION")
private val progressDialog by lazy {
(activity as HomeActivity).progressDialog("Please wait...", "Load Data Favorite") {
setProgressStyle(ProgressDialog.STYLE_SPINNER)
}
}
private val adRequest by lazy {
AdRequest.Builder()
.addTestDevice(resources.getString(R.string.device_pocophone_id))
.addTestDevice(resources.getString(R.string.device_asus_id))
.build()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_favorite, container, false)
return binding.root
}
@SuppressLint("DefaultLocale")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progressDialog.show()
binding.bannerAds.loadAd(adRequest)
viewModel.getAllFavorites().observe(this, Observer { codes ->
if (codes.isNotEmpty()) {
for (code in codes) {
viewModel.getProgramsWithCodes(code.programId).observe(this, Observer {
if (favoritesData.size < codes.size) {
favoritesData.add(
FavoriteData(
title = "${it.programEntity.title} - ${code.name}",
lineTotal = code.codes.countNewLine(),
language = code.name,
code = code.codes,
favoriteAt = ""
)
)
}
})
}
favoriteListAdapter.favorites = favoritesData
binding.listProgramFavorite.setDivider(R.drawable.program_list_divider)
binding.listProgramFavorite.layoutManager = LinearLayoutManager(requireContext())
binding.listProgramFavorite.adapter = favoriteListAdapter
} else {
binding.listProgramFavorite.visibility = View.GONE
binding.emptyFavorite.visibility = View.VISIBLE
}
progressDialog.dismiss()
})
}
companion object {
const val TAG = "FavoriteFragment"
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/model/parcelable/ProgramParcelable.kt
package me.jamilalrasyidis.simpleprogramcode.data.model.parcelable
import android.os.Parcel
import android.os.Parcelable
data class ProgramParcelable(
val id: String?,
val title: String?,
val languages: String?,
val codes: String?
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(id)
parcel.writeString(title)
parcel.writeString(languages)
parcel.writeString(codes)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<ProgramParcelable> {
override fun createFromParcel(parcel: Parcel): ProgramParcelable {
return ProgramParcelable(parcel)
}
override fun newArray(size: Int): Array<ProgramParcelable?> {
return arrayOfNulls(size)
}
}
}
data class Code(
val name: String,
val code: String
)<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/SPCApplication.kt
package me.jamilalrasyidis.simpleprogramcode
import android.app.Application
import me.jamilalrasyidis.simpleprogramcode.di.databaseModule
import me.jamilalrasyidis.simpleprogramcode.di.repositoryModule
import me.jamilalrasyidis.simpleprogramcode.di.viewModelModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import org.koin.core.logger.Level
class SPCApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidLogger(level = Level.DEBUG)
androidContext(this@SPCApplication)
modules(
listOf(
viewModelModule,
repositoryModule,
databaseModule
)
)
}
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/di/DatabaseModule.kt
package me.jamilalrasyidis.simpleprogramcode.di
import androidx.room.Room
import me.jamilalrasyidis.simpleprogramcode.data.AppDatabase
import org.koin.android.ext.koin.androidApplication
import org.koin.dsl.module
val databaseModule = module {
single {
Room.databaseBuilder(
androidApplication(),
AppDatabase::class.java,
"app_database"
)
.fallbackToDestructiveMigration()
.build()
}
single {
get<AppDatabase>().programDao
}
single {
get<AppDatabase>().codeDao
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/services/firebase/ProgramRef.kt
package me.jamilalrasyidis.simpleprogramcode.data.services.firebase
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.QuerySnapshot
class ProgramRef {
suspend fun getPrograms() : QuerySnapshot? = FirebaseFirestore.getInstance().collection("programs").get().result
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/model/entity/HistoryEntity.kt
package me.jamilalrasyidis.simpleprogramcode.data.model.entity
<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/home/FavoriteListAdapter.kt
package me.jamilalrasyidis.simpleprogramcode.ui.home
import android.annotation.SuppressLint
import android.graphics.Color
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.databinding.ItemCodeBinding
import me.jamilalrasyidis.simpleprogramcode.extension.getColorLanguage
import me.jamilalrasyidis.simpleprogramcode.ui.detail.ViewCodeActivity
import org.jetbrains.anko.intentFor
class FavoriteListAdapter : RecyclerView.Adapter<FavoriteListAdapter.ViewHolder>() {
lateinit var favorites: List<FavoriteData>
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemCodeBinding.inflate(inflater, parent, false)
return ViewHolder(binding)
}
override fun getItemCount(): Int {
return favorites.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(favorites[position])
}
class ViewHolder(val binding: ItemCodeBinding) : RecyclerView.ViewHolder(binding.root) {
@SuppressLint("SetTextI18n", "DefaultLocale")
fun bind(data: FavoriteData) {
@Suppress("DEPRECATION")
binding.languageColor.setBackgroundColor(Color.parseColor(data.language.getColorLanguage()))
binding.textTitle.text = data.title.toLowerCase()
binding.textTotalLine.text = "${data.lineTotal} lines"
binding.btnCode.setOnClickListener {
val ctx = binding.root.context
ctx.startActivity(
ctx.intentFor<ViewCodeActivity>().putExtra(
"title",
data.title
).putExtra("code", data.code).putExtra("language", data.language)
)
}
}
}
}
data class FavoriteData(
var title: String,
var lineTotal: Int,
var code: String,
var language: String,
var favoriteAt: String
)<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/detail/GenericFileProvider.kt
package me.jamilalrasyidis.simpleprogramcode.ui.detail
import androidx.core.content.FileProvider
class GenericFileProvider : FileProvider()<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/model/firebase/ProgramFirebase.kt
package me.jamilalrasyidis.simpleprogramcode.data.model.firebase
data class ProgramFirebase(
val id: String,
val title: String,
val languages: String,
val codes: String
)<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/services/dao/CodeDao.kt
package me.jamilalrasyidis.simpleprogramcode.data.services.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.CodeEntity
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.CodeWithProgramEntity
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramWithCodeEntity
@Dao
interface CodeDao {
@Query("SELECT * FROM CodeEntity WHERE program_id LIKE :programId")
fun getCodeByProgramId(programId: String) : LiveData<List<CodeEntity>>
@Query("SELECT name FROM CodeEntity WHERE program_id LIKE :programId")
fun getNames(programId: String) : LiveData<List<String>>
@Query("SELECT codes FROM CodeEntity WHERE program_id LIKE :programId AND name LIKE :name")
fun getCodes(programId: String, name: String) : LiveData<String>
@Query("UPDATE CodeEntity SET is_favored = :isFavored WHERE id = :codeId")
suspend fun updateFavorite(isFavored: Boolean, codeId: String)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(codes: List<CodeEntity>)
@Query("SELECT * FROM CodeEntity")
suspend fun getAllCodes() : List<CodeEntity>?
@Query("SELECT * FROM CodeEntity WHERE is_favored = :isFavored")
fun getAllFavorites(isFavored: Boolean = true) : LiveData<List<CodeEntity>>
@Transaction
@Query("SELECT * FROM ProgramEntity WHERE id = :programId")
fun getProgramsWithCodes(programId: String) : LiveData<ProgramWithCodeEntity>
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/extension/UriExtension.kt
package me.jamilalrasyidis.simpleprogramcode.extension
import android.net.Uri
fun Uri.generateShareLink() {
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/extension/StringExtension.kt
package me.jamilalrasyidis.simpleprogramcode.extension
import java.util.*
fun String.getColorLanguage() : String {
return when {
this == "java" -> {
"#00E676"
}
this == "python" -> {
"#0091EA"
}
this == "php" -> {
"#FFFF00"
}
this == "kotlin" -> {
"#E65100"
}
else -> {
"#FF6F00"
}
}
}
fun String.countNewLine() : Int {
return this.fold(0) {
sum: Int, c: Char ->
if ("\\n".contains(c))
sum + 1
else
sum
}
}
fun String.reverseCodeFormat() : String {
return replace("\\n", "\n", true)
}
fun String.toFileNameStyle(): String {
return this.replace(" ", "_").toLowerCase(Locale.ENGLISH)
}
fun String.convertToFileType(): String {
return when {
this == "java" -> {
".java"
}
this == "python" -> {
".py"
}
this == "php" -> {
".php"
}
this == "kotlin" -> {
".kt"
}
else -> {
".txt"
}
}
}
fun String.toCodeFormat(): String {
return replace("\\n", "\n", true)
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/di/RepositoryModule.kt
package me.jamilalrasyidis.simpleprogramcode.di
import me.jamilalrasyidis.simpleprogramcode.data.repository.CodeRepository
import me.jamilalrasyidis.simpleprogramcode.data.repository.ProgramRepository
import org.koin.dsl.module
val repositoryModule = module {
single { ProgramRepository(get()) }
single { CodeRepository(get()) }
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/di/ViewModelModule.kt
package me.jamilalrasyidis.simpleprogramcode.di
import me.jamilalrasyidis.simpleprogramcode.ui.detail.DetailViewModel
import me.jamilalrasyidis.simpleprogramcode.ui.home.HomeViewModel
import org.koin.android.viewmodel.dsl.viewModel
import org.koin.dsl.module
val viewModelModule = module {
viewModel { HomeViewModel(get()) }
viewModel { DetailViewModel(get()) }
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/home/ProgramListFragment.kt
package me.jamilalrasyidis.simpleprogramcode.ui.home
import android.app.ProgressDialog
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.InterstitialAd
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramEntity
import me.jamilalrasyidis.simpleprogramcode.databinding.FragmentProgramListBinding
import me.jamilalrasyidis.simpleprogramcode.extension.getSharedPreferencesName
import me.jamilalrasyidis.simpleprogramcode.extension.isConnectedToWifi
import me.jamilalrasyidis.simpleprogramcode.ui.ItemClickListener
import me.jamilalrasyidis.simpleprogramcode.ui.detail.DetailActivity
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.progressDialog
import org.jetbrains.anko.toast
import org.koin.android.viewmodel.ext.android.sharedViewModel
class ProgramListFragment : Fragment() {
private lateinit var binding: FragmentProgramListBinding
private val viewModel by sharedViewModel<HomeViewModel>()
private val adapter by lazy { ProgramListAdapter().apply { context = (activity as HomeActivity) } }
@Suppress("DEPRECATION")
private val progressDialog by lazy {
(activity as HomeActivity).progressDialog("Please wait...", "Load Data Code") {
setProgressStyle(ProgressDialog.STYLE_SPINNER)
}
}
private val sharedPref by lazy { (activity as HomeActivity).getSharedPreferences((activity as HomeActivity).getSharedPreferencesName(), 0) }
private val adRequest by lazy {
AdRequest.Builder()
.addTestDevice(resources.getString(R.string.device_pocophone_id))
.addTestDevice(resources.getString(R.string.device_asus_id))
.build()
}
private val interstitialAd by lazy {
InterstitialAd(requireContext()).apply {
this.adUnitId = resources.getString(R.string.interstitial_ads_id)
this.adListener = object : AdListener() {
override fun onAdClosed() {
setupInterstitialAds()
navigateToDetail(programId, programTitle)
super.onAdClosed()
}
}
}
}
private val itemClickListener by lazy {
object : ItemClickListener {
override fun onClick(view: View, programs: List<ProgramEntity>, isLongClick: Boolean) {
val itemPosition = binding.listProgram.getChildLayoutPosition(view)
programId = programs[itemPosition].id
programTitle = programs[itemPosition].title
var currentCounter = sharedPref.getInt("adsCounter", 0)
sharedPref.edit().apply {
currentCounter += 1
this?.putInt("adsCounter", currentCounter)
}.apply()
if (sharedPref.getBoolean("firstTimeDetail", true)) {
if ((activity as HomeActivity).isConnectedToWifi()) {
sharedPref.edit().putBoolean("firstTimeDetail", false).apply()
if (currentCounter >= 3) {
interstitialAd.show()
sharedPref.edit().apply {
this.putInt("adsCounter", 0)
}.apply()
} else {
navigateToDetail(programId, programTitle)
}
} else {
(activity as HomeActivity).toast("Currently you offline")
}
} else {
if (currentCounter >= 3) {
interstitialAd.show()
sharedPref.edit().apply {
this.putInt("adsCounter", 0)
}.apply()
} else {
navigateToDetail(programId, programTitle)
}
}
}
}
}
private lateinit var programId: String
private lateinit var programTitle: String
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_program_list, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progressDialog.show()
binding.bannerAds.loadAd(adRequest)
setupInterstitialAds()
if (sharedPref.getBoolean("first_time", true)) {
if ((activity as HomeActivity).isConnectedToWifi()) {
showListProgram(true)
setupProgramList()
sharedPref.edit().apply {
putBoolean("first_time", false)
}.apply()
} else {
showListProgram(false)
progressDialog.dismiss()
binding.buttonReload.setOnClickListener {
viewModel.runGetProgramsAgain()
progressDialog.show()
Handler().postDelayed({
progressDialog.dismiss()
(activity as HomeActivity).recreate()
}, 3000)
}
}
} else {
showListProgram(true)
setupProgramList()
}
binding.swipeRefreshLayout.setOnRefreshListener {
Handler().postDelayed({
binding.swipeRefreshLayout.isRefreshing = false
}, 3000)
}
}
private fun navigateToDetail(programId: String, programTitle: String) {
(activity as HomeActivity).startActivity((activity as HomeActivity).intentFor<DetailActivity>().apply {
putExtra("programId", programId)
putExtra("programTitle", programTitle)
})
}
private fun setupInterstitialAds() {
if (!interstitialAd.isLoading && !interstitialAd.isLoaded) {
interstitialAd.loadAd(adRequest)
}
}
private fun showListProgram(show: Boolean) {
return if (!show) {
binding.noConnectionLayout.visibility = View.VISIBLE
binding.swipeRefreshLayout.visibility = View.GONE
} else {
binding.swipeRefreshLayout.visibility = View.VISIBLE
binding.noConnectionLayout.visibility = View.GONE
}
}
private fun setupProgramList() {
binding.listProgram.layoutManager = LinearLayoutManager(requireContext())
binding.listProgram.setDivider(R.drawable.program_list_divider)
viewModel.programs.observe(this, Observer {
adapter.programList = it
adapter.inflateType = InflateType.PROGRAM_LIST
adapter.itemClickListener = itemClickListener
binding.listProgram.adapter = adapter
progressDialog.dismiss()
})
}
companion object {
const val TAG = "ProgramListFragment"
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/model/entity/ProgramEntity.kt
package me.jamilalrasyidis.simpleprogramcode.data.model.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity
data class ProgramEntity(
@PrimaryKey val id: String,
val title: String,
val desc: String,
@ColumnInfo(name = "last_seen")
var lastSeen: String = "",
@ColumnInfo(name = "available_language")
val availableLanguage: String
)<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/model/entity/CodeEntity.kt
package me.jamilalrasyidis.simpleprogramcode.data.model.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
@Entity
data class CodeEntity(
@PrimaryKey val id: String,
val name: String,
val codes: String,
@ColumnInfo(name = "program_id")
val programId: String,
@ColumnInfo(name = "is_favored")
var isFavored: Boolean? = false,
val output: String
)
<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/repository/CodeRepository.kt
package me.jamilalrasyidis.simpleprogramcode.data.repository
import android.util.Log
import androidx.lifecycle.LiveData
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.runBlocking
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.CodeEntity
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramWithCodeEntity
import me.jamilalrasyidis.simpleprogramcode.data.services.dao.CodeDao
import org.koin.core.KoinComponent
class CodeRepository(
private val codeDao: CodeDao
) : KoinComponent {
private val database by lazy { FirebaseFirestore.getInstance() }
private val codeRefs by lazy { database.collection("codes") }
fun getNames(programId: String): LiveData<List<String>> {
return codeDao.getNames(programId)
}
fun getCodes(programId: String, name: String): LiveData<String> {
return codeDao.getCodes(programId, name)
}
fun getProgramsWithCodes(programId: String) : LiveData<ProgramWithCodeEntity> {
return codeDao.getProgramsWithCodes(programId)
}
fun getAllFavorites() : LiveData<List<CodeEntity>> {
return codeDao.getAllFavorites()
}
fun getCodeByProgramId(programId: String): LiveData<List<CodeEntity>> {
return codeDao.getCodeByProgramId(programId)
}
suspend fun updateFavorite(isFavored: Boolean, codeId: String) {
codeDao.updateFavorite(isFavored, codeId)
}
suspend fun getCodes() {
val codes = mutableListOf<CodeEntity>()
val codeFromDb: List<CodeEntity>? = codeDao.getAllCodes()
codeRefs.get().addOnSuccessListener {
if (codeFromDb?.isNotEmpty()!!) {
for (i in 0 until it.documents.size) {
try {
codes.add(
CodeEntity(
id = it.documents[i].id,
name = it.documents[i]["name"].toString(),
codes = it.documents[i]["codes"].toString(),
programId = it.documents[i]["program_id"].toString(),
isFavored = codeFromDb[i].isFavored ?: false,
output = it.documents[i]["output"].toString()
)
)
} catch (e: IndexOutOfBoundsException) {
codes.add(
CodeEntity(
id = it.documents[i].id,
name = it.documents[i]["name"].toString(),
codes = it.documents[i]["codes"].toString(),
programId = it.documents[i]["program_id"].toString(),
isFavored = false,
output = it.documents[i]["output"].toString()
)
)
}
}
} else {
for (document in it) {
codes.add(
CodeEntity(
id = document.id,
name = document["name"].toString(),
codes = document["codes"].toString(),
programId = document["program_id"].toString(),
output = document["output"].toString()
)
)
}
}
runBlocking {
codeDao.insert(codes)
}
}
}
companion object {
const val TAG = "CodeRepository"
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/extension/ContextExtension.kt
package me.jamilalrasyidis.simpleprogramcode.extension
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import me.jamilalrasyidis.simpleprogramcode.ui.home.HomeActivity
fun Context.getSharedPreferencesName() : String {
return this.packageName + ".sharedPref"
}
@Suppress("DEPRECATION")
fun Context.isConnectedToWifi(): Boolean {
val cm = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
val network = cm.activeNetwork
val capability = cm.getNetworkCapabilities(network)
capability != null && when {
capability.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
capability.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
capability.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> false
else -> false
}
} else when (cm.activeNetworkInfo?.type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
else -> false
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/services/dao/ProgramDao.kt
package me.jamilalrasyidis.simpleprogramcode.data.services.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramEntity
@Dao
interface ProgramDao {
@get:Query("SELECT * FROM ProgramEntity")
val programs: LiveData<List<ProgramEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(programs: List<ProgramEntity>)
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/home/HomeViewModel.kt
package me.jamilalrasyidis.simpleprogramcode.ui.home
import android.util.Log
import androidx.lifecycle.*
import kotlinx.coroutines.launch
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramEntity
import me.jamilalrasyidis.simpleprogramcode.data.repository.ProgramRepository
class HomeViewModel(
private val programRepository: ProgramRepository
) : ViewModel() {
val programs: LiveData<List<ProgramEntity>> = programRepository.programs
val isSuccessToFirebase = MutableLiveData<Boolean>()
fun runGetProgramsAgain() {
viewModelScope.launch {
programRepository.getPrograms()
}
}
init {
viewModelScope.launch {
programRepository.getPrograms()
}
}
}<file_sep>/README.md
# SimpleProgramCode
Simple program code in different programming languages.
<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/detail2/Detail2Activity.kt
package me.jamilalrasyidis.simpleprogramcode.ui.detail2
//import me.jamilalrasyidis.simpleprogramcode.ui.detail.DetailViewModel
//import me.jamilalrasyidis.simpleprogramcode.ui.detail.ViewPagerAdapter
//
//package me.jamilalrasyidis.simpleprogramcode.ui.detail
//
//import android.os.Bundle
//import android.util.Log
//import android.view.MotionEvent
//import android.view.View
//import androidx.appcompat.app.AppCompatActivity
//import androidx.databinding.DataBindingUtil
//import androidx.lifecycle.LiveData
//import androidx.lifecycle.Observer
//import androidx.viewpager.widget.ViewPager
//import com.google.android.material.tabs.TabLayout
//import me.jamilalrasyidis.simpleprogramcode.R
//import me.jamilalrasyidis.simpleprogramcode.data.model.entity.CodeEntity
//import me.jamilalrasyidis.simpleprogramcode.databinding.ActivityDetailBinding
//import org.koin.android.viewmodel.ext.android.viewModel
//
//class DetailActivity : AppCompatActivity() {
//
// private val viewModel by viewModel<DetailViewModel>()
//
// private val binding by lazy {
// DataBindingUtil.setContentView<ActivityDetailBinding>(
// this,
// R.layout.activity_detail
// )
// }
//
// private val title by lazy { intent.extras?.getString("programTitle", "Detail Program") }
//
// private val programId by lazy { intent.extras?.getString("programId", "program0") }
//
// private val codesObserver by lazy {
// Observer<List<CodeEntity>> {
// Log.d(TAG, "data length : ${it.size}")
//// Log.d(TAG, "tab size : " + pagerAdapter.count)
// if (it.isNotEmpty()) {
// dataCodes = it
// setupTabsAndPager(it)
// }
//// if (dataCodes.isEmpty()) {
//// dataCodes = it
//// } else {
//// if (it.isNotEmpty()) {
//// setupTabsAndPager(dataCodes)
//// }
//// }
// }
// }
//
// private var dataCodes: List<CodeEntity> = emptyList()
//
// private var isTabExist: Boolean = false
//
// private val pagerAdapter by lazy {
// ViewPagerAdapter(
// supportFragmentManager,
// dataCodes.size
// )
// }
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setSupportActionBar(binding.toolbar)
// supportActionBar?.title = title
// supportActionBar?.setHomeButtonEnabled(true)
// supportActionBar?.setDisplayHomeAsUpEnabled(true)
//
// initiateViewModel()
// }
//
// private fun initiateViewModel() {
// viewModel.getCodeByProgramId(programId!!).observe(this, codesObserver)
// }
//
// private fun setupTabsAndPager(codes: List<CodeEntity>) {
// viewModel.currentNameAndCodeLiveData.postValue(listOf(codes[0].name, codes[0].codes))
//
// if (!isTabExist) {
// for (code in codes) {
// binding.tabLayout.addTab(binding.tabLayout.newTab().setText(code.name))
// }
// isTabExist = true
// }
// binding.viewPager.offscreenPageLimit = codes.size - 1
// binding.viewPager.enabledSwipe = false
// binding.viewPager.adapter = pagerAdapter
//// binding.viewPager.addOnPageChangeListener(object :
//// TabLayout.TabLayoutOnPageChangeListener(binding.tabLayout) {
//// override fun onPageSelected(position: Int) {
//// binding.viewPager.currentItem = position
////
//// viewModel.currentNameAndCodeLiveData.postValue(
//// listOf(
//// codes[position].name,
//// codes[position].codes
//// )
//// )
//// }
//// })
// binding.tabLayout.addOnTabSelectedListener(object :
// TabLayout.ViewPagerOnTabSelectedListener(binding.viewPager) {
//
// override fun onTabReselected(tab: TabLayout.Tab?) {
// super.onTabReselected(tab)
// viewModel.currentNameAndCodeLiveData.postValue(
// listOf(
// codes[tab?.position!!].name,
// codes[tab.position].codes
// )
// )
// pagerAdapter.notifyDataSetChanged()
// }
//
// override fun onTabSelected(tab: TabLayout.Tab) {
// super.onTabSelected(tab)
// binding.viewPager.currentItem = tab.position
//
// viewModel.currentNameAndCodeLiveData.postValue(
// listOf(
// codes[tab.position].name,
// codes[tab.position].codes
// )
// )
//
// pagerAdapter.notifyDataSetChanged()
// }
// })
// }
//
// companion object {
// const val TAG = "DetailActivity"
// }
//
//}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/ItemClickListener.kt
package me.jamilalrasyidis.simpleprogramcode.ui
import android.view.View
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramEntity
interface ItemClickListener {
fun onClick(view: View, programs: List<ProgramEntity>, isLongClick: Boolean)
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/repository/ProgramRepository.kt
package me.jamilalrasyidis.simpleprogramcode.data.repository
import android.util.Log
import com.google.firebase.firestore.FirebaseFirestore
import kotlinx.coroutines.runBlocking
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramEntity
import me.jamilalrasyidis.simpleprogramcode.data.services.dao.ProgramDao
import org.koin.core.KoinComponent
class ProgramRepository(
private val programDao: ProgramDao
) : KoinComponent {
private val database by lazy { FirebaseFirestore.getInstance() }
private val programRef by lazy { database.collection("programs") }
val programs by lazy { programDao.programs }
suspend fun getPrograms() {
val programList = mutableListOf<ProgramEntity>()
programRef.get().addOnSuccessListener {
for (document in it) {
programList.add(
ProgramEntity(
id = document.id,
title = document["title"].toString(),
desc = document["desc"].toString(),
availableLanguage = document["available_language"].toString()
)
)
}
runBlocking {
programDao.insert(programList)
}
}
}
companion object {
const val TAG = "ProgramRepository"
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/splash/SplashActivity.kt
package me.jamilalrasyidis.simpleprogramcode.ui.splash
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import androidx.databinding.DataBindingUtil
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.ui.home.HomeActivity
import org.jetbrains.anko.intentFor
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
Handler().postDelayed({
startActivity(intentFor<HomeActivity>())
finish()
}, 3000)
}
}
<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/detail/ViewPagerAdapter.kt
package me.jamilalrasyidis.simpleprogramcode.ui.detail
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
class ViewPagerAdapter(fm: FragmentManager, private val tabCount: Int) :
FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
private lateinit var fragment: Fragment
override fun getItem(position: Int): Fragment {
fragment = CodeViewerFragment()
return fragment
}
override fun getCount(): Int {
return tabCount
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/home/SendFeebackFragment.kt
package me.jamilalrasyidis.simpleprogramcode.ui.home
import android.app.ProgressDialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.google.android.gms.ads.AdRequest
import com.google.firebase.firestore.FirebaseFirestore
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.databinding.FragmentSendFeedbackBinding
import org.jetbrains.anko.progressDialog
import org.jetbrains.anko.toast
class SendFeedbackFragment : Fragment() {
private lateinit var binding: FragmentSendFeedbackBinding
private val database by lazy { FirebaseFirestore.getInstance() }
private val feedbackRef by lazy { database.collection("feedback") }
@Suppress("DEPRECATION")
private val progressDialog by lazy {
(activity as HomeActivity).progressDialog("Please wait...", "Sending your feedback") {
setProgressStyle(ProgressDialog.STYLE_SPINNER)
}
}
private val adRequest by lazy {
AdRequest.Builder()
.addTestDevice(resources.getString(R.string.device_pocophone_id))
.addTestDevice(resources.getString(R.string.device_asus_id))
.build()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_send_feedback, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.bannerAds.loadAd(adRequest)
binding.buttonSend.setOnClickListener {
progressDialog.show()
if (!isValidField()) {
val textSubject = binding.editSubject.text.toString()
val textMessage = binding.editMessage.text.toString()
sendFeedback(textSubject, textMessage)
} else {
if (binding.editSubject.text.isNullOrBlank()) {
@Suppress("DEPRECATION")
binding.editSubject.error = "Subject should not be empty"
}
if (binding.editMessage.text.isNullOrBlank()) {
binding.editMessage.error = "Message should no be empty!"
}
}
}
}
private fun isValidField() : Boolean {
return binding.editSubject.text.isNullOrBlank() && binding.editMessage.text.isNullOrBlank()
}
private fun sendFeedback(subject: String, message: String) {
val data = hashMapOf(
"subject" to subject,
"message" to message,
"app_from" to (activity as HomeActivity).packageName
)
feedbackRef.document()
.set(data)
.addOnSuccessListener {
Handler().postDelayed({
progressDialog.dismiss()
binding.editSubject.text?.clear()
binding.editMessage.text?.clear()
(activity as HomeActivity).toast("Feedback sent!")
}, 2000)
}
.addOnFailureListener {
Handler().postDelayed({
progressDialog.dismiss()
binding.editSubject.text?.clear()
binding.editMessage.text?.clear()
(activity as HomeActivity).toast("Something went wrong, please try again!")
}, 2000)
}
}
private fun sendMail(subject: String, message: String) {
val intent = Intent(Intent.ACTION_SEND)
intent.data = Uri.parse("mailto:")
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_EMAIL, "<EMAIL>")
intent.putExtra(Intent.EXTRA_CC, "<EMAIL>")
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, message)
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
activity?.toast("There is no email client installed.")
}
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/detail/DetailActivity.kt
package me.jamilalrasyidis.simpleprogramcode.ui.detail
import android.Manifest
import android.app.Dialog
import android.app.DownloadManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.view.Window
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.FileProvider
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.MobileAds
import com.google.android.material.snackbar.Snackbar
import io.github.kbiakov.codeview.adapters.Format
import io.github.kbiakov.codeview.adapters.Options
import io.github.kbiakov.codeview.highlight.ColorTheme
import io.github.kbiakov.codeview.highlight.Font
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.CodeEntity
import me.jamilalrasyidis.simpleprogramcode.databinding.ActivityDetailBinding
import me.jamilalrasyidis.simpleprogramcode.extension.*
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.longToast
import org.jetbrains.anko.toast
import org.koin.android.viewmodel.ext.android.viewModel
import java.io.File
import java.io.FileWriter
import java.lang.Exception
import kotlin.math.roundToInt
class DetailActivity : AppCompatActivity() {
private val viewModel by viewModel<DetailViewModel>()
private val binding by lazy {
DataBindingUtil.setContentView<ActivityDetailBinding>(
this,
R.layout.activity_detail
)
}
private val title by lazy { intent.extras?.getString("programTitle", "Detail Program") }
private val programId by lazy { intent.extras?.getString("programId", "program0") }
private var currentFontSize: Int = 10
private var currentCodes: CodeEntity? = null
private var isTabExist: Boolean = false
@Suppress("DEPRECATION")
private val appDir by lazy { Environment.getExternalStorageDirectory().path }
private val adRequest by lazy {
AdRequest.Builder()
.addTestDevice(resources.getString(R.string.device_pocophone_id))
.addTestDevice(resources.getString(R.string.device_asus_id))
.build()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MobileAds.initialize(this) {}
binding.bannerAds.loadAd(adRequest)
setSupportActionBar(binding.toolbar)
supportActionBar?.title = title
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
initiateViewModel()
setupAction()
}
private fun initiateViewModel() {
viewModel.getCodeByProgramId(programId!!).observe(this, Observer<List<CodeEntity>> {
if (it.isNotEmpty()) {
setupTabs(it)
}
})
}
private fun setupTabs(codes: List<CodeEntity>) {
currentCodes = codes[0]
if (!isTabExist) {
for (code in codes) {
binding.tabLayout.addTab(binding.tabLayout.newTab().setText(code.name))
}
updateCodeUI(codes[0])
codes[0].isFavored?.let { updateButtonFavoriteUI(it) }
isTabExist = true
}
binding.tabLayout.setOnTabSelected {
currentCodes = codes[it?.position!!]
updateCodeUI(currentCodes!!)
currentCodes!!.isFavored?.let { it1 -> updateButtonFavoriteUI(it1) }
}
}
private fun setupAction() {
binding.btnPlay.setOnClickListener {
customDialog(currentCodes?.output!!.toCodeFormat())
}
binding.btnZoomIn.setOnClickListener {
if (currentFontSize < 18) {
currentFontSize++
updateCodeUI(currentCodes!!)
}
}
binding.btnZoomOut.setOnClickListener {
if (currentFontSize > 6) {
currentFontSize--
updateCodeUI(currentCodes!!)
}
}
binding.btnCopy.setOnClickListener {
val clipboard: ClipboardManager =
this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("codes", currentCodes?.codes?.reverseCodeFormat())
clipboard.setPrimaryClip(clip)
toast("Code copied to clipboard")
}
binding.btnFavorite.setOnClickListener {
viewModel.updateFavorite(!(currentCodes!!.isFavored)!!, currentCodes!!.id)
(it as ImageView).setImageResource(getImageResources(!(currentCodes!!.isFavored)!!))
currentCodes!!.isFavored = !currentCodes!!.isFavored!!
}
binding.btnDownload.setOnClickListener {
if (isStoragePermissionGranted()) {
generateCodeOnSD(
"${title?.toFileNameStyle()}${currentCodes?.name?.convertToFileType()}",
currentCodes?.codes!!.reverseCodeFormat()
)
} else {
longToast("You need to give access to storage in order to get the code in file mode.")
}
}
binding.btnShare.setOnClickListener {
if (isStoragePermissionGranted()) {
val root = File(appDir, "codes")
if (!root.exists()) {
root.mkdirs()
}
val file = File(
root,
"${title?.toFileNameStyle()}${currentCodes?.name?.convertToFileType()}"
)
if (file.exists()) {
val intentShare = Intent(Intent.ACTION_SEND)
intentShare.type = "file/*"
@Suppress("DEPRECATION")
intentShare.putExtra(
Intent.EXTRA_STREAM,
FileProvider.getUriForFile(
this,
applicationContext.packageName + ".provider",
file
)
)
intentShare.putExtra(Intent.EXTRA_SUBJECT, "Simple Program Code")
intentShare.putExtra(Intent.EXTRA_TEXT, "Code")
intentShare.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(intentShare, "Share Code"))
} else {
longToast("File doesn't exist, please use download button first.")
}
}
}
}
private fun customDialog(output: String) {
val dialog = Dialog(this)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCancelable(true)
dialog.setContentView(R.layout.dialog_code_play)
dialog.findViewById<TextView>(R.id.text_output_code).text = output
dialog.show()
}
private fun getImageResources(isFavored: Boolean): Int {
return if (isFavored) {
R.drawable.ic_favorite_red_24dp
} else {
R.drawable.ic_favorite_border_white_24dp
}
}
private fun getCurrentOptions(name: String, codes: String): Options {
return Options.Default.get(this)
.withLanguage(name)
.withCode(codes.toCodeFormat())
.withFont(Font.Consolas)
.withFormat(
Format(
1f,
(currentFontSize + currentFontSize * 0.3).roundToInt(),
3,
currentFontSize.toFloat()
)
)
.withTheme(ColorTheme.MONOKAI)
}
private fun updateCodeUI(code: CodeEntity) {
binding.codeView.setOptions(getCurrentOptions(code.name, code.codes))
}
private fun updateButtonFavoriteUI(isFavored: Boolean) {
binding.btnFavorite.setImageResource(getImageResources(isFavored))
}
private fun generateCodeOnSD(filename: String, content: String) {
@Suppress("DEPRECATION")
try {
val root = File(appDir, "codes")
if (!root.exists()) {
root.mkdirs()
}
val file = File(root, filename)
val writer = FileWriter(file)
writer.append(content)
writer.flush()
writer.close()
Snackbar.make(binding.root, "Your file saved on storage", Snackbar.LENGTH_LONG)
.setAction("Open File") {
val intent = Intent(Intent.ACTION_GET_CONTENT)
val uri =
Uri.parse(appDir + "/codes/${title?.toFileNameStyle()}${currentCodes?.name?.convertToFileType()}")
intent.setDataAndType(uri, "file/*")
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true)
intent.addCategory(Intent.CATEGORY_OPENABLE)
startActivity(Intent(Intent.createChooser(intent, "Browse File")))
}
.show()
} catch (e: Exception) {
Log.d(TAG, "something went wrong!")
Log.d(TAG, "error : ${e.message}")
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
generateCodeOnSD(
"${title?.toFileNameStyle()}${currentCodes?.name?.convertToFileType()}",
currentCodes?.codes!!
)
}
}
private fun isStoragePermissionGranted(): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(
Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
) {
true
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
),
1
)
false
}
} else {
true
}
}
override fun onNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
companion object {
const val TAG = "DetailActivity"
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/detail/ViewCodeActivity.kt
package me.jamilalrasyidis.simpleprogramcode.ui.detail
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.MobileAds
import io.github.kbiakov.codeview.adapters.Format
import io.github.kbiakov.codeview.adapters.Options
import io.github.kbiakov.codeview.highlight.ColorTheme
import io.github.kbiakov.codeview.highlight.Font
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.databinding.ActivityViewCodeBinding
import me.jamilalrasyidis.simpleprogramcode.extension.toCodeFormat
import kotlin.math.roundToInt
class ViewCodeActivity : AppCompatActivity() {
private lateinit var binding: ActivityViewCodeBinding
private val titleCode by lazy { intent.extras?.getString("title", "Detail Program") }
private val code by lazy { intent.extras?.getString("code", "nope") }
private val language by lazy { intent.extras?.getString("language", "php") }
private val adRequest by lazy {
AdRequest.Builder()
.addTestDevice(resources.getString(R.string.device_pocophone_id))
.addTestDevice(resources.getString(R.string.device_asus_id))
.build()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MobileAds.initialize(this) {}
binding = DataBindingUtil.setContentView(this, R.layout.activity_view_code)
binding.bannerAds.loadAd(adRequest)
setSupportActionBar(binding.toolbar)
supportActionBar?.title = titleCode
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.codeView.setOptions(
Options.Default.get(this)
.withLanguage(language!!)
.withCode(code?.toCodeFormat()!!)
.withFont(Font.Consolas)
.withFormat(
Format(
1f,
(10 + 10 * 0.3).roundToInt(),
3,
10.toFloat()
)
)
.withTheme(ColorTheme.MONOKAI)
)
}
override fun onNavigateUp(): Boolean {
onBackPressed()
return true
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/home/HistoryFragment.kt
package me.jamilalrasyidis.simpleprogramcode.ui.home
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.databinding.FragmentHistoryBinding
import me.jamilalrasyidis.simpleprogramcode.ui.detail.DetailViewModel
import org.koin.android.viewmodel.ext.android.viewModel
class HistoryFragment : Fragment() {
private lateinit var binding: FragmentHistoryBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_history, container, false)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
companion object {
const val TAG = "HistoryFragment"
}
}
<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/home/ProgramListAdapter.kt
package me.jamilalrasyidis.simpleprogramcode.ui.home
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramEntity
import me.jamilalrasyidis.simpleprogramcode.databinding.ItemProgramBinding
import me.jamilalrasyidis.simpleprogramcode.extension.getSharedPreferencesName
import me.jamilalrasyidis.simpleprogramcode.extension.isConnectedToWifi
import me.jamilalrasyidis.simpleprogramcode.ui.ItemClickListener
import me.jamilalrasyidis.simpleprogramcode.ui.detail.DetailActivity
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.progressDialog
import org.jetbrains.anko.toast
class ProgramListAdapter : RecyclerView.Adapter<ProgramListAdapter.ViewHolder>(), View.OnClickListener {
lateinit var itemClickListener: ItemClickListener
lateinit var context: Context
lateinit var inflateType: InflateType
lateinit var programList: List<ProgramEntity>
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemProgramBinding.inflate(inflater, parent, false)
binding.root.setOnClickListener(this)
return ViewHolder(binding)
}
override fun getItemCount(): Int {
return programList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(programList[position])
}
inner class ViewHolder(private val binding: ItemProgramBinding) :
RecyclerView.ViewHolder(binding.root) {
// private var clickListener: ItemClickListener? = null
// init {
// binding.root.setOnClickListener(this)
// }
fun bind(program: ProgramEntity) {
binding.programTitle.text = program.title
binding.programSubtitle.text = program.desc
@SuppressLint("SetTextI18n")
binding.textAvailableLanguage.text = "Language : ${program.availableLanguage}"
}
// private fun handleInflatedWidget() {
// val scale = binding.root.resources.displayMetrics.density
// val verticalPadding: Int = (8 * scale + 0.5f).toInt()
// val horizontalPadding: Int = (16 * scale + 0.5f).toInt()
// when (inflateType) {
// InflateType.PROGRAM_LIST -> {
// binding.textTimeHumanReadable.visibility = View.GONE
// binding.programTitle.setPadding(
// horizontalPadding,
// verticalPadding,
// horizontalPadding,
// verticalPadding
// )
// binding.favIcon.visibility = View.GONE
// }
// InflateType.FAVORITE -> {
// binding.textTimeHumanReadable.visibility = View.VISIBLE
// binding.programTitle.setPadding(
// horizontalPadding,
// verticalPadding,
// horizontalPadding,
// verticalPadding
// )
// binding.favIcon.visibility = View.VISIBLE
// }
// InflateType.HISTORY -> {
// binding.textTimeHumanReadable.visibility = View.GONE
// binding.programTitle.setPadding(
// horizontalPadding,
// 0,
// horizontalPadding,
// verticalPadding
// )
// binding.favIcon.visibility = View.INVISIBLE
// }
// }
// }
// override fun onClick(p0: View?) {
// clickListener?.onClick(p0!!, adapterPosition, false)
// }
}
companion object {
const val TAG = "ProgramListAdapter"
}
override fun onClick(p0: View?) {
itemClickListener.onClick(p0!!, programList, false)
}
}
enum class InflateType {
PROGRAM_LIST,
FAVORITE,
HISTORY
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/detail/DetailViewModel.kt
package me.jamilalrasyidis.simpleprogramcode.ui.detail
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.CodeEntity
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.CodeWithProgramEntity
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramWithCodeEntity
import me.jamilalrasyidis.simpleprogramcode.data.repository.CodeRepository
class DetailViewModel(
private val codeRepository: CodeRepository
) : ViewModel() {
val programWithCodeLiveData = MutableLiveData<ProgramWithCodeEntity>()
fun getProgramsWithCodes(programId: String) : LiveData<ProgramWithCodeEntity> {
return codeRepository.getProgramsWithCodes(programId)
}
fun getCodeByProgramId(programId: String) : LiveData<List<CodeEntity>> {
return codeRepository.getCodeByProgramId(programId)
}
fun getAllFavorites() : LiveData<List<CodeEntity>> {
return codeRepository.getAllFavorites()
}
fun updateFavorite(isFavored: Boolean, codeId: String) {
viewModelScope.launch {
codeRepository.updateFavorite(isFavored, codeId)
}
}
init {
viewModelScope.launch {
try {
codeRepository.getCodes()
} catch (e: Exception) {
Log.d(TAG, "ERROR : $e")
}
}
}
companion object {
const val TAG = "DetailViewModel"
}
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/AppDatabase.kt
package me.jamilalrasyidis.simpleprogramcode.data
import androidx.room.Database
import androidx.room.RoomDatabase
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.CodeEntity
import me.jamilalrasyidis.simpleprogramcode.data.model.entity.ProgramEntity
import me.jamilalrasyidis.simpleprogramcode.data.services.dao.CodeDao
import me.jamilalrasyidis.simpleprogramcode.data.services.dao.ProgramDao
@Database(
entities = [ProgramEntity::class, CodeEntity::class],
version = 10
)
abstract class AppDatabase : RoomDatabase() {
abstract val programDao: ProgramDao
abstract val codeDao: CodeDao
}<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/home/HomeActivity.kt
package me.jamilalrasyidis.simpleprogramcode.ui.home
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.databinding.DataBindingUtil
import androidx.drawerlayout.widget.DrawerLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.google.android.gms.ads.MobileAds
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.databinding.ActivityHomeBinding
import org.jetbrains.anko.toast
import org.koin.android.viewmodel.ext.android.viewModel
import java.lang.Exception
class HomeActivity : AppCompatActivity() {
private val binding by lazy {
DataBindingUtil.setContentView<ActivityHomeBinding>(
this,
R.layout.activity_home
)
}
private val toggle by lazy {
ActionBarDrawerToggle(
this,
binding.drawerLayout,
binding.toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
}
private val viewModel by viewModel<HomeViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MobileAds.initialize(this) {}
setSupportActionBar(binding.toolbar)
supportActionBar?.title = "Home"
setupDrawer()
setupNavigation()
initViewModel()
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, ProgramListFragment())
.commit()
binding.navView.setCheckedItem(R.id.program_list_screen)
}
}
private fun initViewModel() {
viewModel.programs.observe(this, Observer {})
}
private fun setupNavigation() {
binding.navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.program_list_screen -> {
replaceFragment(ProgramListFragment())
true
}
R.id.submit_code_screen -> {
toast("Coming soon!")
binding.drawerLayout.closeDrawer(GravityCompat.START)
true
}
R.id.favorite_screen -> {
replaceFragment(FavoriteFragment())
true
}
R.id.history_screen -> {
toast("Coming soon!")
binding.drawerLayout.closeDrawer(GravityCompat.START)
true
}
R.id.privacy_policy_screen -> {
replaceFragment(PrivacyPolicyFragment())
true
}
R.id.rate_app -> {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("market://details?id=$packageName")
)
)
true
}
R.id.more_apps -> {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/developer?id=RasyidCODE")
)
)
true
}
R.id.share_apps -> {
try {
val intentShare = Intent(Intent.ACTION_SEND)
val messages =
"\nYou can find a lot of code example in various language\n" +
"What are you waiting for?\n" +
"You can install it by visit the link below:\n" +
"https://play.google.com/store/apps/details?id=${packageName}"
intentShare.type = "text/plain"
intentShare.putExtra(
Intent.EXTRA_SUBJECT,
resources.getString(R.string.app_name)
)
intentShare.putExtra(Intent.EXTRA_TEXT, messages)
startActivity(Intent.createChooser(intentShare, "Choose One"))
} catch (e: Exception) {
toast("Something went wrong, please try again!")
}
true
}
R.id.send_feedback_screen -> {
replaceFragment(SendFeedbackFragment())
true
}
else -> false
}
}
}
private fun setupDrawer() {
setSupportActionBar(binding.toolbar)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
binding.drawerLayout.addDrawerListener(toggle)
binding.drawerLayout.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() {
override fun onDrawerOpened(drawerView: View) {
super.onDrawerOpened(drawerView)
supportActionBar?.title = "Simple Program Code"
toggle.syncState()
}
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
when (supportFragmentManager.findFragmentById(R.id.fragment_container)) {
is ProgramListFragment -> supportActionBar?.title =
"Home"
is FavoriteFragment -> supportActionBar?.title =
"Favorites"
is HistoryFragment -> supportActionBar?.title =
"History"
is PrivacyPolicyFragment -> supportActionBar?.title =
"Privacy Policy"
is SendFeedbackFragment -> supportActionBar?.title =
"Send Feedback"
}
toggle.syncState()
}
})
binding.drawerLayout.post {
toggle.syncState()
}
}
private fun replaceFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction().replace(R.id.fragment_container, fragment)
.commit()
binding.drawerLayout.closeDrawer(GravityCompat.START)
}
override fun onBackPressed() {
if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
binding.drawerLayout.closeDrawer(GravityCompat.START)
} else when {
supportFragmentManager.findFragmentById(R.id.fragment_container) is ProgramListFragment -> {
super.onBackPressed()
}
else -> {
replaceFragment(ProgramListFragment())
supportActionBar?.title = "Home"
binding.navView.setCheckedItem(R.id.program_list_screen)
}
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
toggle.syncState()
}
companion object {
const val TAG = "HomeActivity"
}
}<file_sep>/settings.gradle
include ':app'
rootProject.name='SimpleProgramCode'
<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/data/model/entity/CodeWithProgramEntity.kt
package me.jamilalrasyidis.simpleprogramcode.data.model.entity
import androidx.room.Embedded
import androidx.room.Relation
data class CodeWithProgramEntity(
@Embedded val codeEntity: CodeEntity,
@Relation(
entityColumn = "program_id",
parentColumn = "id"
)
val programEntity: ProgramEntity
)<file_sep>/app/src/main/java/me/jamilalrasyidis/simpleprogramcode/ui/detail/CodeViewerFragment.kt
package me.jamilalrasyidis.simpleprogramcode.ui.detail
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import io.github.kbiakov.codeview.adapters.Format
import io.github.kbiakov.codeview.adapters.Options
import io.github.kbiakov.codeview.highlight.ColorTheme
import io.github.kbiakov.codeview.highlight.Font
import me.jamilalrasyidis.simpleprogramcode.R
import me.jamilalrasyidis.simpleprogramcode.databinding.FragmentCodeViewerBinding
import me.jamilalrasyidis.simpleprogramcode.extension.toCodeFormat
import org.koin.android.viewmodel.ext.android.sharedViewModel
import kotlin.math.roundToInt
class CodeViewerFragment : Fragment() {
private val viewModel by sharedViewModel<DetailViewModel>()
private lateinit var binding: FragmentCodeViewerBinding
private var currentFontSize: Int = 10
private var currentData = mutableListOf<String>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_code_viewer, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// setupCodeViewer()
setupAction()
}
private fun setupAction() {
binding.btnZoomIn.setOnClickListener {
if (currentFontSize < 18) {
currentFontSize++
binding.codeView.setOptions(getCurrentOptions(currentData[0], currentData[1]))
}
}
binding.btnZoomOut.setOnClickListener {
if (currentFontSize > 6) {
currentFontSize--
binding.codeView.setOptions(getCurrentOptions(currentData[0], currentData[1]))
}
}
binding.btnCopy.setOnClickListener {
val clipboard: ClipboardManager = (activity as DetailActivity).getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("codes", currentData[1])
clipboard.setPrimaryClip(clip)
}
}
// private fun setupCodeViewer() {
// viewModel.apply {
// currentNameAndCodeLiveData.observe(this@CodeViewerFragment, Observer {
// currentData.clear()
// currentData.add(it[0])
// currentData.add(it[1])
// binding.codeView.setOptions(getCurrentOptions(currentData[0], currentData[1]))
// })
// }
// }
private fun getCurrentOptions(name: String, codes: String): Options {
return Options.Default.get(requireContext())
.withLanguage(name)
.withCode(codes.toCodeFormat())
.withFont(Font.Consolas)
.withFormat(
Format(
1f,
(currentFontSize + currentFontSize * 0.3).roundToInt(),
3,
currentFontSize.toFloat()
)
)
.withTheme(ColorTheme.MONOKAI)
}
companion object {
const val TAG = "CodeViewerFragment"
}
} | d5e3a6630bbbe384ed6a05f2effeed328205825e | [
"Markdown",
"Kotlin",
"Gradle"
] | 38 | Kotlin | rasyidcode/SimpleProgramCode | a37bd287ede7c39fe2133ee348743dc80fdc5995 | 7ed9a5ad3c748116779a296233bd9556e85def37 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.