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 | <file_sep># Discount
Every coupon is loaded with a discount. The discount might be in currency (only value) or percentage (value and percentage).
<file_sep>import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
# Allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-coupon-management',
version='0.3.2',
packages=['coupon_management'],
include_package_data=True,
license='MIT License',
description='A Django app that makes the use of coupon management and easy to handle',
long_description=README,
long_description_content_type="text/markdown",
url='https://github.com/krishnaansh/django-coupon-management',
author='Krishna',
author_email='<EMAIL>',
download_url='https://github.com/krishnaansh/django-coupon-management/archive/refs/tags/v0.3.2.zip',
keywords =['django', 'coupon', 'management', 'coupon manage', 'promotion'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.8',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content'
]
)
<file_sep># django-coupon-management
## A Django app that makes the use of coupon management and easy to handle!



django-coupon-management is a coupon management to use of coupons validity and to boost your website.
### Downloading
django-coupon-management is available on The Python Package Index (PyPI). You can simply use ***pip*** to install it:
```bash
$ pip install django-coupon-management
```
### Installing
1 - Add ```coupon_management``` inside INSTALLED_APPS in settings.py:
```python
INSTALLED_APPS = [
...
'coupon_management',
]
```
2 - (Optional) If you want to use more than 12 chars (default) for your coupon code, add ```DSC_COUPON_CODE_LENGTH``` variable in settings.py:
```python
DSC_COUPON_CODE_LENGTH = 16
```
3 - Run the migrations:
```bash
$ python manage.py makemigrations
$ python manage.py migrate
```
And that's it! django-coupon-management should appear in your admin as ```Coupon Managements```.
### Changelog
***[https://github.com/krishnaansh/django-coupon-management/blob/master/CHANGELOG.txt](https://github.com/krishnaansh/django-coupon-management/blob/master/CHANGELOG.txt)***
### Documentation
***[https://github.com/krishnaansh/django-coupon-management/blob/master/docs/README.md](https://github.com/krishnaansh/django-coupon-management/blob/master/docs/README.md)***
### Download
***[https://github.com/krishnaansh/django-coupon-management/archive/refs/tags/0.3.2.zip](https://github.com/krishnaansh/django-coupon-management/archive/refs/tags/0.3.2.zip)***
<file_sep># Coupon User:
Every time a user uses a coupon, he will be added to a list called ```Coupon Users``` in admin.
<file_sep>from django.db import models
from django.utils import timezone
from coupon_management.helpers import (get_random_code,
get_coupon_code_length,
get_user_model)
# Create your models here.
# ========================
class Ruleset(models.Model):
allowed_users = models.ForeignKey('AllowedUsersRule', on_delete=models.CASCADE, verbose_name="Valid Users")
max_uses = models.ForeignKey('MaxUsesRule', on_delete=models.CASCADE, verbose_name="Max Usage Count")
validity = models.ForeignKey('ValidityRule', on_delete=models.CASCADE, verbose_name="Coupoun Expiration")
def __str__(self):
return "Ruleset Nº{0}".format(self.id)
class Meta:
verbose_name = "Coupon Validation"
verbose_name_plural = "Coupon Validation"
class AllowedUsersRule(models.Model):
user_model = get_user_model()
users = models.ManyToManyField(user_model, verbose_name="Users", blank=True)
all_users = models.BooleanField(default=False, verbose_name="All users?")
def __str__(self):
# return "AllowedUsersRule Nº{0}".format(self.id)
return "ValidUsers Nº{0}".format(self.id)
class Meta:
verbose_name = "Valid User"
verbose_name_plural = "Valid Users"
class MaxUsesRule(models.Model):
max_uses = models.BigIntegerField(default=0, verbose_name="Maximum Usage")
is_infinite = models.BooleanField(default=False, verbose_name="Infinite Usage?")
uses_per_user = models.IntegerField(default=1, verbose_name="Usage per user")
def __str__(self):
return "MaxUsesRule Nº{0}". format(self.id)
class Meta:
verbose_name = "Coupon Usage Condition"
verbose_name_plural = "Coupon Usage Conditions"
class ValidityRule(models.Model):
expiration_date = models.DateTimeField(verbose_name="Expiration date")
is_active = models.BooleanField(default=False, verbose_name="Is active?")
def __str__(self):
return "ValidityRule Nº{0}". format(self.id)
class Meta:
verbose_name = "Coupon Exipiration"
verbose_name_plural = "Coupon Exipirations"
class CouponUser(models.Model):
user_model = get_user_model()
user = models.ForeignKey(user_model, on_delete=models.CASCADE, verbose_name="User")
coupon = models.ForeignKey('Coupon', on_delete=models.CASCADE, verbose_name="Coupon")
times_used = models.IntegerField(default=0, editable=False, verbose_name="Usage Count")
def __str__(self):
return str(self.user)
class Meta:
verbose_name = "Coupon User"
verbose_name_plural = "Coupon Users"
class Discount(models.Model):
value = models.IntegerField(default=0, verbose_name="Value")
is_percentage = models.BooleanField(default=False, verbose_name="Is percentage?")
def __str__(self):
if self.is_percentage:
return "{0}%".format(self.value)
# return "{0}% - Discount".format(self.value)
return "${0}".format(self.value)
class Meta:
verbose_name = "Discount"
verbose_name_plural = "Discounts"
class Coupon(models.Model):
code_length = get_coupon_code_length()
code = models.CharField(max_length=code_length, default=get_random_code, verbose_name="Coupon Code", unique=True)
discount = models.ForeignKey('Discount', on_delete=models.CASCADE)
times_used = models.IntegerField(default=0, editable=False, verbose_name="Usage Count")
created = models.DateTimeField(editable=False, verbose_name="Coupon Creation date")
ruleset = models.ForeignKey('Ruleset', on_delete=models.CASCADE, verbose_name="Coupon Validation")
def __str__(self):
return self.code
def use_coupon(self, user):
coupon_user, created = CouponUser.objects.get_or_create(user=user, coupon=self)
coupon_user.times_used += 1
coupon_user.save()
self.times_used += 1
self.save()
def get_discount(self):
return {
"value": self.discount.value,
"is_percentage": self.discount.is_percentage
}
def get_discounted_value(self, initial_value):
discount = self.get_discount()
if discount['is_percentage']:
new_price = initial_value - ((initial_value * discount['value']) / 100)
new_price = new_price if new_price >= 0.0 else 0.0
else:
new_price = initial_value - discount['value']
new_price = new_price if new_price >= 0.0 else 0.0
return new_price
def save(self, *args, **kwargs):
if not self.id:
self.created = timezone.now()
return super(Coupon, self).save(*args, **kwargs)
<file_sep>default_app_config = 'coupon_management.apps.CouponManagementConfig'<file_sep># Documentation
### Coupon
##### [https://github.com/krishnaansh/django-coupon-management/blob/master/docs/models/Coupon.md](https://github.com/krishnaansh/django-coupon-management/blob/master/docs/models/Coupon.md)
### Discount
##### [https://github.com/krishnaansh/django-coupon-management/blob/master/docs/models/Discount.md](https://github.com/krishnaansh/django-coupon-management/blob/master/docs/models/Discount.md)
### Coupon Validation
##### [https://github.com/krishnaansh/django-coupon-management/blob/master/docs/models/Ruleset.md](https://github.com/krishnaansh/django-coupon-management/blob/master/docs/models/Ruleset.md)
### Coupon User
##### [https://github.com/krishnaansh/django-coupon-management/blob/master/docs/models/Coupon_User.md](https://github.com/krishnaansh/django-coupon-management/blob/master/docs/models/Coupon_User.md)
### Validations Guide
##### [https://github.com/krishnaansh/django-coupon-management/blob/master/docs/validation/Validations.md](https://github.com/krishnaansh/django-coupon-management/blob/master/docs/validation/Validations.md)
### Usage Example
```python
# views.py - Example only
# /use-coupon/?coupon_code=COUPONTEST01
from django.contrib.auth.models import User
from django.http import HttpResponse
from coupon_management.validations import validate_coupon
from coupon_management.models import Coupon
class UseCouponView(View):
def get(self, request, *args, **kwargs):
coupon_code = request.GET.get("coupon_code")
user = User.objects.get(username=request.user.username)
status = validate_coupon(coupon_code=coupon_code, user=user)
if status['valid']:
coupon = Coupon.objects.get(code=coupon_code)
coupon.use_coupon(user=user)
return HttpResponse("OK")
return HttpResponse(status['message'])
```
To use django-coupon-management accordingly, you'll need to validate the coupon first with the coupon code and the user that will use the coupon.
To validate the coupon, use the method ```validate_coupon()``` from ```coupon_management.validators```. This method returns a dict with one key (if valid) or two keys (if not valid):
```python
VALID = {
"valid": True
}
INVALID = {
"valid": False,
"message": "Some message telling why it's not valid"
}
```
If it's valid, you can safely call the function ```use_coupon()``` from the Coupon instance.
Please note that I used the default User model from Django in this example. If you use a custom authentication system, you'll need to use the proper User model from your custom auth app!
<file_sep># Coupon
Each coupon has a ***code***, ***discount*** and set of rules (known as ***coupon validatino*** in the admin).
Every time you click ```Add Coupon```, a new coupon code will be generated randomly for you. Don't worry, you can set your own personal code if you wish.
Each Coupon Validation has three basic validation that you need to supply: ***Valid Users***, ***Max Usage Count*** and ***Validity rule***.
## Methods (Instance)
- ##### coupon.use_coupon(user=\<User Object\>) -> None
##### Example:
```python
from django.contrib.auth.models import User
from coupon_management.validations import validate_coupon
from coupon_management.models import Coupon
coupon_code = "COUPONTEST01"
user = User.objects.get(username="john_doe")
status = validate_coupon(coupon_code=coupon_code, user=user)
if status['valid']:
coupon = Coupon.objects.get(code=coupon_code)
coupon.use_coupon(user=user)
```
<hr>
- ##### coupon.get_discount() -> Dict
Returns a dict with two keys, with the discount ***value*** and if it's ***percentage*** or not.
##### Example:
```python
from django_simple_coupons.models import Coupon
coupon_code = "COUPONTEST01"
coupon = Coupon.objects.get(code=coupon_code)
discount = coupon.get_discount() # Example: {'value': 50, 'is_percentage': True}
```
<hr>
- ##### coupon.get_discounted_value(initial_value=<int/float>) -> Float
Returns a float with the new, discounted value.
##### Example:
```python
from coupon_management.models import Coupon
coupon_code = "COUPONTEST01"
coupon = Coupon.objects.get(code=coupon_code)
''' Example: Returns 50.0 if discount is 50% or 80.0 if discount is $20 '''
discount_value = coupon.get_discounted_value(initial_value=100.0)
```
<file_sep>from django.apps import AppConfig
class CouponManagementConfig(AppConfig):
name = 'coupon_management'
verbose_name = 'Coupon Management'
<file_sep># Coupon Validations
Every coupon needs a set of rules to make it valid and useable.
For now, django-simple-coupons use three basic rules:
##### Valid User:
Defines which users are allowed to use the coupon.
##### Max Usage Count:
Defines how many uses the coupon should have in general and for each user.
##### Validity rule:
Defines the expiration date for the coupon and if it's active or not.
<file_sep># Validations
To ensure that the rules from the ruleset are being followed, some validations are required. If you call ```coupon.use_coupon(user)``` without validating first, it'll always assume that the coupon is valid and will be used regardless if it's really valid or not.
There's a couple of functions to check if a coupon is valid before using it.
## Functions
- ##### validate_coupon(coupon_code=\<str\>, user=\<User Object\>) -> Dict
This is the main validation function to call, you don't need to call another function. With it, you can validate the coupon and the user that will be using that coupon.
Returns a dict with one key (if valid), or two keys (if not valid).
##### Example:
```python
from django.contrib.auth.models import User
from coupon_management.validations import validate_coupon
user = User.objects.get(username="john_doe")
coupon_code_valid = "COUPONTEST01"
valid = validate_coupon(coupon_code=coupon_code_valid, user=user)
# {'valid': True}
coupon_code_invalid = "DUMMYCOUPON0"
invalid = validate_coupon(coupon_code=coupon_code_invalid, user=user)
# {'valid': False, 'message': 'Coupon does not exist!'}
```
After validating the coupon and the user, you can call ```coupon.use_coupon(user)``` without any problem.
<file_sep>from django.contrib import admin
from coupon_management.models import (Coupon,
Discount,
Ruleset,
CouponUser,
AllowedUsersRule,
MaxUsesRule,
ValidityRule)
from coupon_management.actions import (reset_coupon_usage, delete_expired_coupons)
# Register your models here.
# ==========================
@admin.register(Coupon)
class CouponAdmin(admin.ModelAdmin):
list_display = ('code', 'discount', 'ruleset', 'times_used', 'created', )
actions = [delete_expired_coupons]
@admin.register(Discount)
class DiscountAdmin(admin.ModelAdmin):
pass
@admin.register(Ruleset)
class RulesetAdmin(admin.ModelAdmin):
list_display = ('__str__', 'allowed_users', 'max_uses', 'validity', )
@admin.register(CouponUser)
class CouponUserAdmin(admin.ModelAdmin):
list_display = ('user', 'coupon', 'times_used', )
actions = [reset_coupon_usage]
@admin.register(AllowedUsersRule)
class AllowedUsersRuleAdmin(admin.ModelAdmin):
def get_model_perms(self, request):
return {}
@admin.register(MaxUsesRule)
class MaxUsesRuleAdmin(admin.ModelAdmin):
def get_model_perms(self, request):
return {}
@admin.register(ValidityRule)
class ValidityRuleAdmin(admin.ModelAdmin):
def get_model_perms(self, request):
return {}
| 18991e73a5d20504bf812d5602bd21c0beba9632 | [
"Markdown",
"Python"
] | 12 | Markdown | yacaeh/django-coupon-management | 31ea9cb3a6b83fe4a7e3bd2061fc39cf5860b0ae | c1b4600d0f5f5aa74131211f1b3ce1970bbea78f |
refs/heads/master | <repo_name>moazhamed/Todo<file_sep>/app/src/main/java/com/example/todo/TodoRecyclerAdapter.java
package com.example.todo;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.todo.DataBase.Model.Todo;
import java.util.List;
public class TodoRecyclerAdapter extends RecyclerView.Adapter<TodoRecyclerAdapter.ViewHolder> {
List<Todo> items;
OnItemClickListener onItemClickListener;
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public Todo getSwipedItem (int pos ){
return items.get(pos);
}
public interface OnItemClickListener{
public void OnItemClick(int pos , Todo todo);
}
public TodoRecyclerAdapter(List<Todo> items) {
this.items = items;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todo_card_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position) {
final Todo item = items.get(position);
viewHolder.title.setText(item.getTitle());
viewHolder.date.setText(item.getDateTime());
if (onItemClickListener!=null){
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onItemClickListener.OnItemClick(position , item);
}
});
}
}
public void changeData(List<Todo> items){
this.items = items;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
if(items==null){
return 0;
}
return items.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView date;
public ViewHolder(View view) {
super(view);
title = view.findViewById(R.id.title_);
date = view.findViewById(R.id.date);
}
}
}
<file_sep>/app/src/main/java/com/example/todo/HomeActivity.java
package com.example.todo;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.Toast;
import com.example.todo.DataBase.Model.Todo;
import com.example.todo.DataBase.MyDataBase;
import java.util.List;
public class HomeActivity extends BaseActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
TodoRecyclerAdapter adapter;
SwipeRefreshLayout swipeRefreshLayout;
Todo swipedItem = null;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.recycler_view);
swipeRefreshLayout = findViewById(R.id.swipeLayout);
layoutManager = new LinearLayoutManager(activity);
adapter = new TodoRecyclerAdapter(null);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
adapter.setOnItemClickListener(new TodoRecyclerAdapter.OnItemClickListener() {
@Override
public void OnItemClick(int pos, Todo todo) {
AddTodoActivity.todo = todo;
Intent intent = new Intent(HomeActivity.this, AddTodoActivity.class);
startActivity(intent);
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
getAllTodosFromDatabase();
}
});
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.DOWN, ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int pos = viewHolder.getAdapterPosition();
Todo item = adapter.getSwipedItem(pos);
swipedItem = item;
DeleteTodo(item);
}
});
itemTouchHelper.attachToRecyclerView(recyclerView);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
Intent intent = new Intent(HomeActivity.this, AddTodoActivity.class);
startActivity(intent);
}
});
}
public void AddTodo(Todo item) {
MyDataBase
.getInstance(activity)
.todoDao()
.AddTodo(swipedItem);
getAllTodosFromDatabase();
swipedItem=null;
}
public void DeleteTodo(Todo item) {
MyDataBase.getInstance(activity)
.todoDao()
.RemoveTodo(item);
Snackbar.make(findViewById(R.id.swipeLayout), R.string.item_deleted, 4000)
.setAction(R.string.undo, new View.OnClickListener() {
@Override
public void onClick(View v) {
AddTodo(swipedItem);
}
}).show();
}
public void getAllTodosFromDatabase() {
List<Todo> items = MyDataBase.getInstance(activity)
.todoDao()
.getAllTodo();
adapter.changeData(items);
swipeRefreshLayout.setRefreshing(false);
}
@Override
protected void onStart() {
super.onStart();
getAllTodosFromDatabase();
}
}
<file_sep>/app/src/main/java/com/example/todo/AddTodoActivity.java
package com.example.todo;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.example.todo.DataBase.DOAs.TodoDao;
import com.example.todo.DataBase.Model.Todo;
import com.example.todo.DataBase.MyDataBase;
import java.util.Calendar;
public class AddTodoActivity extends BaseActivity implements View.OnClickListener {
protected EditText title;
protected TextView date;
protected EditText content;
protected Button addButton;
static Todo todo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_add_todo);
initView();
if (todo != null) {
addButton.setText(R.string.update);
title.setText(todo.getTitle());
date.setText(todo.getDateTime());
content.setText(todo.getContent());
}
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.add_button) {
if (todo == null) {
String sTitle = title.getText().toString();
String sdate = date.getText().toString();
String scontent = content.getText().toString();
Todo todoItem = new Todo(sTitle, scontent, sdate);
MyDataBase.getInstance(this)
.todoDao().AddTodo(todoItem);
showConfirmationMessage(R.string.success, R.string.todo_added_successfully,
R.string.ok,
new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
finish();
}
}).setCancelable(false);
} else {
String sTitle = title.getText().toString();
String sdate = date.getText().toString();
String scontent = content.getText().toString();
todo.setTitle(sTitle);
todo.setContent(scontent);
todo.setDateTime(sdate);
MyDataBase.getInstance(activity)
.todoDao()
.UpdateTodo(todo);
showConfirmationMessage(R.string.success, R.string.todo_updated_successfully,
R.string.ok,
new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
dialog.dismiss();
finish();
}
}).setCancelable(false);
}
}
}
@Override
protected void onDestroy() {
todo = null;
super.onDestroy();
}
private void initView() {
title = findViewById(R.id.title);
date = findViewById(R.id.date);
content = findViewById(R.id.content);
addButton = findViewById(R.id.add_button);
addButton.setOnClickListener(AddTodoActivity.this);
}
int hourOfDay = -1;
int minutes = -1;
public void openDatePicker(View view) {
Calendar calendar = Calendar.getInstance();
TimePickerDialog timePickerDialog = new TimePickerDialog(activity,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hour, int minute) {
hourOfDay = hour;
minutes = minute;
date.setText(hour + ": " + minute);
}
}, calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
false);
timePickerDialog.show();
}
}
| c05dca57eff5bb0b39efda4b7fe8750985307744 | [
"Java"
] | 3 | Java | moazhamed/Todo | 7437ff8a1be824f7e80dc4ff7e5de026b92203a6 | 904e634fd9e5bc7684a05817de4eda0b62968f57 |
refs/heads/master | <repo_name>silencerN/ChatSocketDemo<file_sep>/services/socketio.js
/*
封装socket.io,为了获取server以便监听.
*/
var socketio = {};
var socket_io = require('socket.io');
var io={};
//获取io
var socketio = function(server){
io = socket_io(server);
io.on('connection', function (socket) {
console.log('connection successful!');
var user;
socket.on('NewJoin', function(msg){
console.log('NewJoin: '+ msg);
user=msg;
socket.broadcast.emit('NewPlayerJoin','Welcome New Plyaer : '+msg);
});
socket.on('chat message', function(msg){
console.log('chat message: '+ msg);
io.emit('chat message', msg);
});
socket.on('disconnect', function(){
console.log('receive disconnect event, user : ' +user);
socket.broadcast.emit('PlayerLeave',user + ' has disconnect! ');
})
})
};
module.exports = socketio; | 1ada5d455142e243b3a836987224fa708a01b762 | [
"JavaScript"
] | 1 | JavaScript | silencerN/ChatSocketDemo | bd29682c5f2397711e133a2294f705ddc9dc387a | a33d6ac714a4b913bf605cced1c2284a0f96efa2 |
refs/heads/master | <repo_name>mrflip/dexy_scribe<file_sep>/README.md
Scripts for compiling an asciidoc book with dexy
* final -- artifacts as rendered into html, pdf, etc
* dexy for going from raw (`big_data_for_chimps`) to compiled (`output`)
* rake (git-scribe) for going from `dexy`d to `final`
## Setup
Please use
* Ruby 1.9.2+ -- I recommend using [rbenv](https://github.com/sstephenson/rbenv) with [ruby-build](https://github.com/sstephenson/ruby-build).
* Python 2.6 or 2.7 (not 3.0), with `pip`
Run these commands:
```bash
cd dexy_scribe
git submodule update --init
git submodule foreach git checkout master
gem install bundler
bundle update
bundle exec rake init
```
They should be fine to re-run if something breaks in the middle.
## Running
<file_sep>/Gemfile
source 'http://rubygems.org'
gem 'configliere'
# gem 'gorillib', :github => 'infochimps-labs/gorillib', :branch => 'version_1'
# gem 'wukong', :github => 'infochimps-labs/wukong', :branch => 'master'
gem 'gorillib', :path => '../core/gorillib'
gem 'wukong', :path => '../core/wukong_og'
gem 'git-scribe', :path => './vendor/git-scribe'
gem 'yajl-ruby', :platform => :mri
gem 'i18n'
gem 'active_support'
# SciRuby/sciruby
# Gems you would use if hacking on this gem (rather than with it)
group :support do
gem 'pry'
gem 'rake'
#
gem 'guard', ">= 1.0"
gem 'guard-shell'
# lets you use pow to drive live reloading of generated pages
gem 'guard-livereload'
gem 'rack'
end
# Gems for testing and coverage
group :test do
gem 'rspec', "~> 2.8"
gem 'guard-rspec', ">= 0.6"
if RUBY_PLATFORM.include?('darwin')
gem 'rb-fsevent', ">= 0.9"
end
end
<file_sep>/Guardfile
# -*- ruby -*-
require 'pry'
ignore %r{(?:\.git|data|images)/}
ignore %r{^(?:output|output-long|output-scribe|artifacts|logs|vendor)}
notification :off
interactor :off
require 'guard/notifiers/emacs'
::Guard::Notifier::DEFAULTS.merge!(
:success => '#e7fde4',
:failed => '#faeedc',
:default => '#eee8d6',
)
book_dir = "big_data_for_chimps"
# Add files and commands to this file, like the example:
# watch(%r{file/path}) { `command(s)` }
#
guard 'shell' do
ENV['BOOK_CONTENTS'] = File.expand_path(book_dir)
watch(/#{book_dir}\/([^\/]+)\.asciidoc/) do |match|
system('dexy', '--loglevel', 'DEBUG', '--directory', 'big_data_for_chimps') and # , '--run', "match[0]"
system 'rake', '--trace', 'gen:html', '--', "--book_file=output/#{match[0]}"
end
watch(/#{book_dir}\/code\/.+\.rake/){|match|
# binding.pry
system 'rake', '-f', match[0], '--trace' }
watch(%r{#{book_dir}/code/.+\.rb\z}) do |match|
rakefile = File.join(File.dirname(match[0]), 'tasks.rake')
system 'rake', '-f', rakefile, '--trace' if File.exist?(rakefile)
end
end
guard 'livereload' do
watch(/(.*).asciidoc/){|match| [ "html/#{match[1]}.html", "html/working.html"] }
end
<file_sep>/Rakefile
require 'logger'
require 'configliere' ; Settings.use :commandline
require 'gorillib/model'
Log = Logger.new($stderr).tap{|log| log.level = Logger::DEBUG } unless defined?(Log)
ENV['BOOK_CONTENTS'] = File.expand_path('big_data_for_chimps')
load 'tasks/git_scribe.rake'
Settings.resolve!
#
# Top-level rake tasks
#
# run if no task specified
task :default => :book
# dummy task to force generation
task :force
desc "Generate all documents"
task :gen
desc "Remove generated artifacts for all file types"
task :clean
namespace :book do
desc "Merge book files with code and its output"
task :dexy do
sh 'dexy', '--loglevel', 'DEBUG', '--directory', 'big_data_for_chimps'
end
end
task :book => ['book:dexy', 'gen:html']
namespace :init do
desc "Install and initialize dexy"
task :dexy do
cd('vendor/dexy'){ sh('pip install -e .') }
sh('dexy setup')
end
end
desc "Installs prerequisites for book"
task :init => ['init:dexy']
# --------------------------------------------------------------------------
#
# Rake Task definitions for book
#
HtmlTask.new.tasks
PdfTask.new.tasks
DocbookTask.new.tasks
EpubTask.new.tasks
# MobiTask.new.tasks
| 276be258ae9ba2e6e80ab8152270e067d2ca34d1 | [
"Markdown",
"Ruby"
] | 4 | Markdown | mrflip/dexy_scribe | f3504ab8762dbdebbe4028ba5c67b0b5ba2c92d4 | 0e5831b76ed678834b629c5e45b1a145aee910e3 |
refs/heads/master | <file_sep>[English](./CONTRIBUTING.md) | 简体中文
# 参与共建
想要给 Web Console Boilerplate 贡献自己的一份力量?
本文档会指导你如何为 Web Console Boilerplate 贡献一份自己的力量,请在你要提 issue 或者 pull request 之前花几分钟来阅读一遍本文档。
## 行为准则
这里有一份[行为准则](./CODE_OF_CONDUCT.md),希望所有的贡献者都能遵守,请花时间阅读一遍全文以确保你能明白哪些是可以做的,哪些是不可以做的。
## Bugs
本仓库使用 [GitHub Issues](https://github.com/NicolasSchwarzer/web-console-boilerplate/issues) 来做 bug 追踪。在你报告一个 bug 之前,请先确保已经搜索过已有的 issue。
## 新增功能
如果你有新增功能的想法,我同样推荐你提 feature request issue。
## 第一次贡献
如果你还不清楚怎么在 GitHub 上提 pull request,可以通过下列免费视频来学习:
[如何为 GitHub 上的开源仓库贡献代码](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
## Pull Request
作者会关注所有的 pull request,并 review 以及合并你的代码,也有可能要求你做一些修改或者告诉你为什么不能接受这样的修改。
**在你发送 pull request 之前**,请确认你是按照下面的步骤来做的:
1. Fork 该仓库并基于 `master` 分支新建你自己的分支。
2. 在项目根目录下运行了 `npm install`。
3. 确保你的代码通过了 Lint 检查 `npm run lint`。小贴士:Lint 会在你 git commit 的时候自动运行。
## 开发流程
在你 clone 了 Web Console Boilerplate 的代码并且使用 `npm install` 安装完依赖后,你还可以运行下面几个常用的命令:
1. `npm start` 在本地运行 Web Console Boilerplate。
2. `npm run lint` 检查代码风格。
3. `npm run lint-fix` 检查并修复代码风格。
4. `npm run build` 构建 Web Console Boilerplate 的 production 版本到 build 目录。
5. `npm run analyze` 可视化分析 bundle 大小。
<file_sep>const { join } = require('path');
const autoprefixer = require('autoprefixer');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: [
// As of babel 7.4.0, @babel/polyfill has been deprecated,
// in favor of directly including core-js/stable (to polyfill ECMAScript features),
// and regenerator-runtime/runtime (needed to use transpiled generator functions),
// for more information: https://babeljs.io/docs/en/next/babel-polyfill.html
'core-js/stable',
'regenerator-runtime/runtime',
join(__dirname, '../src/index.jsx'),
],
},
output: {
// Use [contenthash] to persist chunk (js entry file) hash.
chunkFilename: 'public/[id].[contenthash].js', // Non-entry chunk file name.
filename: 'public/[id].[contenthash].js', // Entry chunk file name.
path: join(__dirname, '../build'),
publicPath: '/', // Base url to access static assets.
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
babelrc: false, // Do not search relative configuration files.
configFile: false, // Do not use project-wide configuration file.
cacheDirectory: true, // Cache loader results in 'node_modules/.cache/babel-loader'.
presets: [
'@babel/preset-env',
'@babel/preset-react',
],
plugins: [
// Ant design supports tree shaking, but it needs additional import of css,
// so we use import plugin to achieve import on demand & auto css import:
// https://ant.design/docs/react/introduce#Use-modularized-antd
['babel-plugin-import', { libraryName: 'antd', libraryDirectory: 'es', style: 'css' }],
// Decorator must comes before class-properties, and legacy must comes with loose:
// https://babeljs.io/docs/en/babel-plugin-proposal-decorators#note-compatibility-with-babel-plugin-proposal-class-properties
['@babel/plugin-proposal-decorators', { legacy: true }],
['@babel/plugin-proposal-class-properties', { loose: true }],
'@babel/plugin-transform-runtime', // Externalise references to helpers and builtins.
],
},
},
},
{
// Please note that import same scss file in two different scss files,
// will produce style code duplication,
// because import handled by sass-loader is beyond webpack module mechanism,
// only the css we got after sass-loader processing is treated as a module.
test: /\.scss$/, // Use scss to write styles.
exclude: /node_modules/, // Extract app's css chunk.
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: { // Enable css modules.
localIdentName: '[local]--[hash:base64:5]', // Local unique name for, e.g. class.
context: join(__dirname, '../src'), // Use src directory as basic loader context.
},
importLoaders: 2, // Transformed by 2 loaders (sass & postcss) before @import.
},
},
{
loader: 'postcss-loader',
options: {
plugins: [
autoprefixer({
overrideBrowserslist: ['last 2 versions'],
}),
],
},
},
'sass-loader',
],
},
{
test: /\.css$/,
include: /node_modules/, // Extract vendors' css chunk.
use: [
MiniCssExtractPlugin.loader,
'css-loader',
],
},
{
test: /\.(?:bmp|gif|jpe?g|png)$/, // Resolve all image files.
use: {
loader: 'url-loader',
options: {
limit: 8192, // Use default fallback file-loader if file size equals or exceeds limit.
// Options for default fallback file-loader,
// persists files' relative paths in the output directory,
// with 20 length content hash for persistant cache.
name: '[path][name].[contenthash:20].[ext]',
outputPath: 'public/assets',
context: 'src/assets',
},
},
},
{
test: /\.(?:eot|otf|svg|ttf|woff2?)$/, // Resolve all font & svg files.
use: {
loader: 'file-loader',
options: {
name: '[path][name].[contenthash:20].[ext]',
outputPath: 'public/assets',
context: 'src/assets',
},
},
},
],
},
resolve: {
alias: {
'@': join(__dirname, '../src'), // Alias corresponding to paths in jsconfig.json.
},
extensions: ['.js', '.jsx', '.json'],
},
// Optimization for persistent cache:
// https://webpack.js.org/guides/caching
optimization: {
namedChunks: true, // Persist chunk ids with the chunk name.
runtimeChunk: 'single', // Extract webpack runtime & manifest.
// Override partial default splitChunks configuration:
// https://webpack.js.org/plugins/split-chunks-plugin/#optimizationsplitchunks
splitChunks: {
minSize: 0, // Allow chunk to be generated no matter what chunk size.
cacheGroups: {
// Extract vendors' libraries into one chunk.
vendors: {
test: /node_modules/,
name: 'vendors',
chunks: 'all',
priority: -10,
},
// Extract common code into one chunk, which will be loaded on demand,
// except for code also imported in app entry chunk,
// and except for code in node_modules due to priority too.
default: {
name: 'common',
minChunks: 2,
priority: -20,
reuseExistingChunk: true,
},
},
},
// Determine used & unused exports for each module, prerequisite for tree shaking.
usedExports: true,
},
plugins: [
new MiniCssExtractPlugin({
// Use [contenthash] to persist css chunk (entry file) hash.
chunkFilename: 'public/[id].[contenthash].css', // Non-entry chunk file name.
filename: 'public/[id].[contenthash].css', // Entry chunk file name.
}),
new HtmlWebpackPlugin({
chunks: ['runtime', 'vendors', 'app'], // inject runtime, vendors & app chunk.
template: join(__dirname, '../public/index.html'),
}),
],
performance: {
hints: false, // Do not warn or report errors when any chunk's size exceeds 250kb.
},
};
<file_sep>import React, { memo } from 'react';
import styles from './index.scss';
function Profile() {
return <div className={styles.container}>Profile Page</div>;
}
export default memo(Profile);
<file_sep>/**
* Error boundary component to catch errors in descendant components:
* https://reactjs.org/docs/error-boundaries.html
*/
import React, { PureComponent } from 'react';
import { createPortal } from 'react-dom';
import PropTypes from 'prop-types';
import styles from './index.scss';
export default class ErrorBoundary extends PureComponent {
// Modal container dom to render error details in development environment.
errorContainerEl = document.createElement('div');
static propTypes = {
children: PropTypes.node,
};
static defaultProps = {
children: undefined,
};
state = {
hasError: false,
errorStack: '',
componentStack: '',
};
static getDerivedStateFromError() {
// Change state to render fallback UI.
return { hasError: true };
}
componentDidMount() {
// Attach to body on mounted.
document.body.appendChild(this.errorContainerEl);
}
componentWillUnmount() {
// Detach from body on unmount.
document.body.removeChild(this.errorContainerEl);
}
componentDidCatch(error, info) {
if (process.env.NODE_ENV === 'development') {
// Only render error details in development environment.
this.setState({
errorStack: error.stack || '',
componentStack: info.componentStack || '',
});
} else {
// TODO: log error stack & component stack to error tracking services.
}
}
renderErrorDetails() {
const { errorStack, componentStack } = this.state;
if (errorStack || componentStack) {
return createPortal(
<div className={styles.errorContainer}>
<span className={styles.errorTitle}>Oops, error occurs!</span>
{!!errorStack && (
<>
<br />
<br />
{errorStack}
</>
)}
{!!componentStack && (
<>
<br />
<br />
<span className={styles.errorTitle}>Component stack:</span>
<br />
{componentStack}
</>
)}
</div>,
this.errorContainerEl,
);
}
return null;
}
render() {
const { children } = this.props;
const { hasError } = this.state;
if (hasError) {
return (
<>
<div className={styles.fallback}>
Oops, error occurs! Please contact administrator!
</div>
{this.renderErrorDetails()}
</>
);
}
return children;
}
}
<file_sep>import React, { memo, useState, useMemo, useCallback } from 'react';
import PropTypes from 'prop-types';
import { Link, withRouter } from 'react-router-dom';
import { Layout, Menu, Icon, Avatar } from 'antd';
import classNames from 'classnames';
import avatar from '@/assets/github-black.png';
import styles from './index.scss';
const { Header, Sider, Content } = Layout;
const pathReg = /^\/([\w-]+)(?:\/.*)?$/;
function Panel({ history: { push }, location: { pathname }, children }) {
const [collapsed, setCollapsed] = useState(false);
// Memoize menu selected keys via hook useMemo,
// what is memoization: https://en.wikipedia.org/wiki/Memoization
const selectedKeys = useMemo(() => [pathname.replace(pathReg, '$1')], [pathname]);
// Memoize menu onClick callback via hook useCallback.
const onMenuClick = useCallback(({ key }) => push(`/${key}`), [push]);
// Memoize collapsed toggle function via hook useCallback.
const toggleCollapsed = useCallback(
() => setCollapsed((prevCollapsed) => !prevCollapsed),
// The dependency setCollapsed will never mutate, and so is toggleCollapsed,
// thus there's no eslint error reported here.
[],
);
return (
<Layout className={styles.container}>
<Sider trigger={null} collapsible collapsed={collapsed}>
<Link
className={classNames(styles.logo, { [styles.collapsed]: collapsed })}
to="/"
>
{collapsed ? 'Boilerplate' : 'Web Console Boilerplate'}
</Link>
<Menu
className={styles.menu}
theme="dark"
mode="inline"
selectedKeys={selectedKeys}
onClick={onMenuClick}
>
<Menu.Item key="dashboard">
<Icon type="dashboard" />
<span>Dashboard</span>
</Menu.Item>
<Menu.Item key="profile">
<Icon type="user" />
<span>Profile</span>
</Menu.Item>
<Menu.Item key="settings">
<Icon type="setting" />
<span>Settings</span>
</Menu.Item>
</Menu>
</Sider>
<Layout>
<Header className={styles.header}>
<Icon
className={styles.trigger}
type={collapsed ? 'menu-unfold' : 'menu-fold'}
onClick={toggleCollapsed}
/>
<div className={styles.headerRightContainer}>
<a
className={styles.headerMenuItem}
href="https://github.com/NicolasSchwarzer/web-console-boilerplate#readme"
target="_blank"
rel="noopener noreferrer"
>
Docs
</a>
<a
className={styles.avatarContainer}
href="https://github.com/NicolasSchwarzer/web-console-boilerplate"
target="_blank"
rel="noopener noreferrer"
>
<Avatar size={48} src={avatar} />
</a>
</div>
</Header>
<Content className={styles.content}>
{children}
</Content>
</Layout>
</Layout>
);
}
Panel.propTypes = {
history: PropTypes.shape({
push: PropTypes.func.isRequired,
}).isRequired,
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
children: PropTypes.node,
};
Panel.defaultProps = {
children: undefined,
};
export default withRouter(memo(Panel));
<file_sep>import React, { memo } from 'react';
import styles from './index.scss';
function Settings() {
return <div className={styles.container}>Settings Page</div>;
}
export default memo(Settings);
<file_sep>const { join } = require('path');
const merge = require('webpack-merge');
const config = require('./webpack.config.default');
const devConfig = merge(config, {
mode: 'development',
devServer: {
compress: true, // Enable gzip compress.
contentBase: join(__dirname, '../build'), // Base folder to serve.
historyApiFallback: true, // Enable SPA support.
open: true, // Open your default browser on start.
overlay: true, // Show compilation error in the browser window overlay.
port: 8000,
watchOptions: {
ignored: /node_modules/,
},
},
devtool: 'source-map',
});
// Print detail filename and line number in the component stack trace for error boundary.
devConfig.module.rules[0].use.options.plugins.push('@babel/plugin-transform-react-jsx-source');
// Use '[path][name]__[local]' in css modules for development in favor of better debugging.
devConfig.module.rules[1].use[1].options.modules.localIdentName = '[path][name]__[local]';
module.exports = devConfig;
<file_sep>import React, { Suspense, lazy, memo } from 'react';
import { Switch, Redirect, Route } from 'react-router-dom';
import Panel from '@/layouts/Panel';
import ErrorBoundary from '@/components/ErrorBoundary';
import ImportSpin from '@/components/ImportSpin';
import NotFound from '@/pages/NotFound';
import './index.scss';
/**
* Use Suspense & lazy to do code splitting,
* if you want ssr, library splitting & full dynamic import, please use @loadable/component instead:
* for reference: https://reactjs.org/docs/code-splitting.html#reactlazy,
* https://www.smooth-code.com/open-source/loadable-components/docs/loadable-vs-react-lazy/
*
* Use webpackChunkName to persist splitted (non-entry) chunk file name.
*/
const Dashboard = lazy(() => import(/* webpackChunkName: "dashboard" */ '@/pages/Dashboard'));
const Profile = lazy(() => import(/* webpackChunkName: "profile" */ '@/pages/Profile'));
const Settings = lazy(() => import(/* webpackChunkName: "settings" */ '@/pages/Settings'));
function App() {
return (
<Panel>
<ErrorBoundary>
<Suspense fallback={<ImportSpin />}>
<Switch>
<Redirect exact from="/" to="/dashboard" />
<Route exact path="/dashboard" component={Dashboard} />
<Route exact path="/profile" component={Profile} />
<Route exact path="/settings" component={Settings} />
<Route component={NotFound} />
</Switch>
</Suspense>
</ErrorBoundary>
</Panel>
);
}
// Use memo to optimize performance of function components.
export default memo(App);
<file_sep>English | [简体中文](./CONTRIBUTING_zh-CN.md)
# Contributing to Web Console Boilerplate
Want to contribute to Web Console Boilerplate? There are a few things you need to know.
The following is a set of guidelines for contributing to Web Console Boilerplate. Please spend several minutes in reading these guidelines before you create an issue or pull request.
## Code of Conduct
I have adopted a [Code of Conduct](./CODE_OF_CONDUCT.md) that I expect project participants to adhere to. Please read the full text so that you can understand what actions will and will not be tolerated.
## Bugs
I'm using [GitHub Issues](https://github.com/NicolasSchwarzer/web-console-boilerplate/issues) for bug tracing. Before you report a bug, please make sure you've searched existed issues.
## Proposing a Change
If you intend to introduce new feature, I also recommend create a feature request issue.
## Your First Pull Request
Working on your first pull request? You can learn how from this free video series:
[How to Contribute to an Open Source Project on GitHub](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github)
## Sending a Pull Request
The author is monitoring for pull requests. I will review your pull request and either merge it, request changes to it, or close it with an explanation.
**Before submitting a pull request**, please make sure the following is done:
1. Fork the repository and create your branch from `master`.
2. Run `npm install` in the repository root.
3. Make sure your code lints via running `npm run lint`. Tip: Lint runs automatically when you git commit.
## Development Workflow
After cloning Web Console Boilerplate, run `npm install` to fetch its dependencies. Then, you can run several commands:
1. `npm start` runs Web Console Boilerplate locally.
2. `npm run lint` checks the code style.
3. `npm run lint-fix` checks and fixes the code style.
4. `npm run build` creates production build of Web Console Boilerplate.
5. `npm run analyze` displays an interactive zoomable treemap to visualize size of webpack output files.
<file_sep>/**
* Spin component for dynamic import.
*/
import React, { memo } from 'react';
import { Icon } from 'antd';
import styles from './index.scss';
function ImportSpin() {
return (
<div className={styles.container}>
<Icon className={styles.spinner} type="loading" />
</div>
);
}
export default memo(ImportSpin);
<file_sep>import React, { memo } from 'react';
import styles from './index.scss';
function NotFound() {
return <div className={styles.container}>Page Not Found</div>;
}
export default memo(NotFound);
<file_sep>import React, { memo } from 'react';
import styles from './index.scss';
import logo from '@/assets/react.svg';
function Dashboard() {
return (
<>
<img className={styles.logo} src={logo} />
<div className={styles.container}>
<a
className={styles.icon}
href="https://github.com/NicolasSchwarzer/web-console-boilerplate"
target="_blank"
rel="noopener noreferrer"
/>
<span className={styles.title}>Dashboard Page</span>
</div>
</>
);
}
export default memo(Dashboard);
<file_sep>English | [简体中文](./README_zh-CN.md)
# Web Console Boilerplate
[](https://lgtm.com/projects/g/NicolasSchwarzer/web-console-boilerplate/alerts/) [](https://lgtm.com/projects/g/NicolasSchwarzer/web-console-boilerplate/alerts/) [](https://david-dm.org/NicolasSchwarzer/web-console-boilerplate) [](https://david-dm.org/NicolasSchwarzer/web-console-boilerplate?type=dev) [](https://github.com/NicolasSchwarzer/web-console-boilerplate/issues) [](https://github.com/NicolasSchwarzer/web-console-boilerplate/pulls) [](https://github.com/NicolasSchwarzer/web-console-boilerplate/blob/master/LICENSE) [](https://app.fossa.io/projects/git%2Bgithub.com%2FNicolasSchwarzer%2Fweb-console-boilerplate?ref=badge_shield) [](./CONTRIBUTING.md#your-first-pull-request)
A boilerplate of web console project which saves your time on project initialization.
## Features
* **Web project boilerplate**, aims for React developers, with React Router and Ant Design engaged.
* **Full usage of React new features**, includes strict mode, error boundaries, lazy load, memoization, fragments, Hooks and so on...
* **Webpack configuration with best practice**, supports tree shaking, code splitting, persistant cache, live reload, bundle analysis and so on...
* **Code style check**, automatically runs ESLint and StyleLint on Git commit, whose rules are based on `eslint-config-airbnb` and `stylelint-config-standard`.
* **Please notice**: Here uses ESLint 5.x.x instead of latest 6.x.x, because of the incompatibility between 6.x.x and [the VSCode extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint). For more details, please refer to issue [#696](https://github.com/microsoft/vscode-eslint/issues/696) and comment [#507855728](https://github.com/microsoft/vscode-eslint/issues/696#issuecomment-507855728).
## Getting Started
```shell
# Install dependencies.
$ npm install
# Start dev server.
$ npm start
# Get production build.
$ npm run build
# Check code style.
$ npm run lint
# Fix code style.
$ npm run lint-fix
```
## Usage
This repository is a boilerplate, I recommend you make a copy of it to start your own project. **Please note that you should remove the `.npmrc` file in favor of generating a `package-lock.json` file for better reliability**.
## Contributing
Welcome all contributions. Please read the [Contributing Guide](./CONTRIBUTING.md) first.
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2FNicolasSchwarzer%2Fweb-console-boilerplate?ref=badge_large)
<file_sep>[English](./README.md) | 简体中文
# Web Console Boilerplate
[](https://lgtm.com/projects/g/NicolasSchwarzer/web-console-boilerplate/alerts/) [](https://lgtm.com/projects/g/NicolasSchwarzer/web-console-boilerplate/alerts/) [](https://david-dm.org/NicolasSchwarzer/web-console-boilerplate) [](https://david-dm.org/NicolasSchwarzer/web-console-boilerplate?type=dev) [](https://github.com/NicolasSchwarzer/web-console-boilerplate/issues) [](https://github.com/NicolasSchwarzer/web-console-boilerplate/pulls) [](https://github.com/NicolasSchwarzer/web-console-boilerplate/blob/master/LICENSE) [](https://app.fossa.io/projects/git%2Bgithub.com%2FNicolasSchwarzer%2Fweb-console-boilerplate?ref=badge_shield) [](./CONTRIBUTING_zh-CN.md#%E7%AC%AC%E4%B8%80%E6%AC%A1%E8%B4%A1%E7%8C%AE)
Web 控制台项目模板,节省你的项目初始化时间。
## 特性
* **Web 项目模板**,为 React 开发者定制,目前集成了 React Router 和 Ant Design。
* **大量使用 React 新特性**,包括严格模式、错误边界、懒加载、memoization、fragments、Hooks 等等...
* **Webpack 配置最佳实践**,支持 tree shaking、代码分割、持久化缓存、热重载、bundle 大小分析等等...
* **代码风格检查**,在代码提交时会自动运行 ESLint 和 StyleLint,检查规则基于 `eslint-config-airbnb` 和 `stylelint-config-standard`。
* **注意**:ESLint 仍然使用 5.x.x 版本,最新的 6.x.x 版本和 [VSCode ESLint 插件](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) 存在兼容性问题,详情请参见插件 issue [#696](https://github.com/microsoft/vscode-eslint/issues/696) 和评论 [#507855728](https://github.com/microsoft/vscode-eslint/issues/696#issuecomment-507855728)。
## 开始
```shell
# 安装依赖。
$ npm install
# 本地开发。
$ npm start
# 构建应用。
$ npm run build
# 代码风格检查。
$ npm run lint
# 代码风格修复。
$ npm run lint-fix
```
## 使用
拷贝本项目模板,基于该模板来开发你自己的项目。**注意:请移除 `.npmrc` 文件,这样可以在安装依赖时生成 `package-lock.json`,以保证依赖安装的可靠性**。
## 参与共建
请参考[贡献指南](./CONTRIBUTING_zh-CN.md)。
## License
[](https://app.fossa.io/projects/git%2Bgithub.com%2FNicolasSchwarzer%2Fweb-console-boilerplate?ref=badge_large)
| d3bf745e118a5bd1b3559e7a832e499e48e384a5 | [
"Markdown",
"JavaScript"
] | 14 | Markdown | NicolasSchwarzer/web-console-boilerplate | 58212aa776592db3c06aff4d164a55126f729cb1 | e967715882a75785766c5a34d038bb61aafc8020 |
refs/heads/main | <file_sep>#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <malloc.h>
#include <stdio.h>
typedef void* LDataType;
typedef struct _LNode {
LDataType Data;
struct _Node* Next;
} LNode;
LNode* SLL_CreateNewNode(LDataType NewData);
void SLL_InsertNewHead(LNode** List, LNode* NewHead);
void SLL_DestroyAllLNodes(LNode* Node);
#endif // LINKEDLIST_H<file_sep>#include<stdio.h>
#include <malloc.h>
//#define TEST_PRINT
const int N;
int Path[1000];
int KPath[1000];
typedef struct line {
int index;
struct line* l_next;
} Line;
typedef struct node {
int acorn;
Line* line;
} Node;
Line* make_line(int i) {
Line* new_line = (Line*)malloc(sizeof(Line));
new_line->index = i;
new_line->l_next = NULL;
return new_line;
}
void DestroyAll(Node** node) {
for (int i = 0; i < N; i++) {
for (Line* line = node[i]->line; line;) {
Line* cur = line;
line = line->l_next;
free(cur);
}
free(node[i]);
}
free(node);
}
typedef struct stack_ {
int next;
int n;
int acorn;
} stack_t;
void copy_path() {
for (int i = 0; i < N; i++)
Path[i] = KPath[i];
}
void dfs(int* max, Node** graph, int n, int cmax, int idx, int end) {
KPath[n] = idx;
if (n == N - 1) {
if (idx == end && *max < cmax + graph[n][idx].acorn) {
*max = cmax + graph[n][idx].acorn;
copy_path();
}
return;
}
for (Line* line = graph[n][idx].line; line; line = line->l_next) {
#ifdef TEST_PRINT
printf("\nn:%d, idx:%d, acorn:%d", n, idx, graph[n][idx].acorn);
#endif
dfs(max, graph, n + 1, cmax + graph[n][idx].acorn, line->index, end);
}
}
int DFS(Node** graph) {
int max = 0;
int end = 0;
for (Node* g = graph[N - 1]; ~((++g)->acorn);end++);
dfs(&max, graph, 0, 0, 0, end);
return max;
}
int main() {
char map[50][50];
int i, j;
scanf("%d", &N);
for (i = 0; i < N; i++)
scanf("%s", map[i]);
// 기초 세팅 / 노드 할당 / 영역 개수 / 도토리 개수
Node** graph = (Node**)malloc(sizeof(Node*) * (N + 1));
for (i = 0; i < N; i++) {
int cur_idx = 0;
graph[i] = (Node*)malloc(sizeof(Node) * ((N + 1) / 2 + 1));
graph[i][cur_idx].acorn = 0;
graph[i][cur_idx].line = NULL;
for (j = 0; j < N; j++) {
switch (map[i][j]) {
case 'D':
graph[i][cur_idx].acorn++;
case '.':
map[i][j] = cur_idx;
break;
case 'U':
if (j + 1 < N && map[i][j + 1] != 'U') {
graph[i][++cur_idx].acorn = 0;
graph[i][cur_idx].line = NULL;
}
break;
}
}
graph[i][cur_idx + 1].acorn = -1;
#ifdef TEST_PRINT
printf("\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%c", map[i][j] < '0' ? map[i][j] + '0' : map[i][j]);
printf("\n");
}
#endif
}
#ifdef TEST_PRINT
printf("\n");
for (i = 0; i < N; i++) {
for (j = 0; ~(graph[i][j].acorn); j++)
printf("%d ", graph[i][j].acorn);
printf("\n");
}
#endif
// 간선 만들기
for (i = 0; i < N - 1; i++) {
Node* node_list = graph[i];
Line** line = &node_list->line;
for (int cur = -1, j = 0; j < N; j++) {
if (map[i][j] == 'U') {
if (i + 1 < N && map[i][j + 1] != 'U') {
node_list++;
line = &node_list->line;
cur = -1;
}
}
else if (map[i + 1][j] != cur && map[i + 1][j] != 'U') {
cur = map[i + 1][j];
if (*line == NULL)
*line = make_line(cur);
else {
(*line)->l_next = make_line(cur);
line = &(*line)->l_next;
}
}
}
}
#ifdef TEST_PRINT
printf("\n");
for (i = 0; i < N; i++) {
for (j = 0; ~(graph[i][j].acorn); j++) {
printf("%d:%d; ", j, graph[i][j].acorn);
for (Line* cur = graph[i][j].line; cur; cur = cur->l_next)
printf("%d ", cur->index);
printf("/");
}
printf("\n");
}
#endif
int max;
max = DFS(graph);
printf("\n\n%d\n", max);
for (i = 0; i < N; i++)
printf("%d ", Path[i]);
DestroyAll(graph);
getchar();
}
<file_sep>#include "LinkedListQueue.h"
LinkedQueue* LQ_CreateQueue() {
LinkedQueue* NewQ = (LinkedQueue*)malloc(sizeof(LinkedQueue));
NewQ->Last = NULL;
NewQ->First = NULL;
return NewQ;
}
QNode* LQ_CreateNode(QDataType Data) {
QNode* NewNode = (QNode*)malloc(sizeof(QNode));
NewNode->Data = Data;
NewNode->Rear = NULL;
return NewNode;
}
void LQ_Enqueue(LinkedQueue* Q, QNode* NewData) {
if (Q->First == NULL)
Q->First = NewData;
else
Q->Last->Rear = NewData;
Q->Last = NewData;
Q->Count++;
}
QNode* LQ_Dequeue(LinkedQueue* Q) {
QNode* Popped = Q->First;
Q->First = Q->First->Rear;
Q->Count--;
return Popped;
}
void LQ_DestroyQueue(LinkedQueue* Q) {
QNode* F = Q->First, * S;
while (F != NULL) {
S = F;
F = F->Rear;
free(S);
}
free(Q);
}<file_sep>#ifndef LINKED_LIST_QUEUE_H
#define LINKED_LIST_QUEUE_H
#include <malloc.h>
#include "Graph.h"
typedef Vertex* QDataType;
typedef struct _Node {
QDataType Data;
struct Node* Rear;
} QNode;
typedef struct _LinkedQueue {
QNode* First;
QNode* Last;
int Count;
} LinkedQueue;
LinkedQueue* LQ_CreateQueue();
QNode* LQ_CreateNode(QDataType Data);
void LQ_Enqueue(LinkedQueue* Q, QNode* NewData);
QNode* LQ_Dequeue(LinkedQueue* Q);
void LQ_DestroyQueue(LinkedQueue* Q);
#endif // LINKED_LIST_QUEUE_H<file_sep>#include "PriorityQueue.h"
PriorityQueue* PQ_Create(int InitialSize) {
PriorityQueue* NewPQ = (PriorityQueue*)malloc(sizeof(PriorityQueue));
NewPQ->Capacity = InitialSize;
NewPQ->UsedSize = 0;
NewPQ->Nodes = (PQNode*)malloc(sizeof(PQNode) * InitialSize);
return NewPQ;
}
void PQ_Destroy(PriorityQueue* PQ) {
free(PQ->Nodes);
free(PQ);
}
void PQ_Enqueue(PriorityQueue* PQ, PQNode NewNode) {
int CurrentPosition = PQ->UsedSize;
int ParentPosition = PQ_GetParent(CurrentPosition);
if (CurrentPosition == PQ->Capacity) {
if (PQ->Capacity == 0)
PQ->Capacity = 1;
PQ->Capacity *= 2;
PQNode* keep = (PQNode*)realloc(PQ->Nodes, sizeof(PQNode) * PQ->Capacity);
if (keep == NULL) {
keep = (PQNode*)malloc(sizeof(PQNode) * PQ->Capacity);
memmove(keep, PQ->Nodes, sizeof(PQNode) * CurrentPosition);
free(PQ->Nodes);
}
PQ->Nodes = keep;
}
PQ->Nodes[CurrentPosition] = NewNode;
while (CurrentPosition > 0
&& PQ->Nodes[CurrentPosition].Priority < PQ->Nodes[ParentPosition].Priority) {
PQ_SwapNodes(PQ, CurrentPosition, ParentPosition);
CurrentPosition = ParentPosition;
ParentPosition = PQ_GetParent(CurrentPosition);
}
PQ->UsedSize++;
}
void PQ_SwapNodes(PriorityQueue* PQ, int index1, int index2) {
PQNode Temp = PQ->Nodes[index1];
PQ->Nodes[index1] = PQ->Nodes[index2];
PQ->Nodes[index2] = Temp;
}
void PQ_Dequeue(PriorityQueue* PQ, PQNode* Root) {
int ParentPosition = 0,
LeftPosition = 0,
RightPosition = 0;
*Root = PQ->Nodes[0];
PQ_SwapNodes(PQ, 0, --PQ->UsedSize);
LeftPosition = PQ_GetLeftChild(0);
RightPosition = LeftPosition + 1;
while (1) {
int SelectedChild = 0;
if (LeftPosition >= PQ->UsedSize)
break;
if (RightPosition >= PQ->UsedSize)
SelectedChild = LeftPosition;
else {
if (PQ->Nodes[LeftPosition].Priority > PQ->Nodes[RightPosition].Priority)
SelectedChild = RightPosition;
else
SelectedChild = LeftPosition;
}
if (PQ->Nodes[SelectedChild].Priority < PQ->Nodes[ParentPosition].Priority) {
PQ_SwapNodes(PQ, SelectedChild, ParentPosition);
ParentPosition = SelectedChild;
}
else
break;
LeftPosition = PQ_GetLeftChild(ParentPosition);
RightPosition = LeftPosition + 1;
}
if (PQ->Nodes < PQ->Capacity / 2) {
PQ->Capacity /= 2;
PQ->Nodes = (PQNode*)realloc(PQ->Nodes, sizeof(PQNode) * PQ->Capacity);
}
}
int PQ_GetParent(int Index) {
return (Index - 1) / 2;
}
int PQ_GetLeftChild(int Index) {
return Index * 2 + 1;
}
int PQ_IsEmpty(PriorityQueue* PQ) {
return PQ->UsedSize == 0;
}<file_sep>#include "GraphSort.h"
void TopologicalSort(Vertex* V, LNode** List) {
while (V != NULL && V->Visited == NotVisited) {
TS_DFS(V, List);
V = V->Next;
}
}
void TS_DFS(Vertex* V, LNode** List) {
Edge* E = NULL;
V->Visited = Visited;
for (E = V->AdjacencyList; E != NULL; E = E->Next)
if (E->Target != NULL && E->Target->Visited == NotVisited)
TS_DFS(E->Target, List);
printf("%c\n", V->Data);
SLL_InsertNewHead(List, SLL_CreateNewNode(V));
}<file_sep>#ifndef PRIORITYQUEUE_H
#define PRIORITYQUEUE_H
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
typedef int PriorityType;
typedef struct _PQNode {
PriorityType Priority;
void* Data;
} PQNode;
typedef struct _PriorityQueue {
PQNode* Nodes;
int Capacity;
int UsedSize;
} PriorityQueue;
PriorityQueue* PQ_Create(int InitialSize);
void PQ_Destroy(PriorityQueue* PQ);
void PQ_Enqueue(PriorityQueue* PQ, PQNode NewData);
void PQ_Dequeue(PriorityQueue* PQ, PQNode* Root);
void PQ_SwapNodes(PriorityQueue* PQ, int index1, int index2);
int PQ_GetParent(int Index);
int PQ_GetLeftChild(int Index);
int PQ_IsEmpty(PriorityQueue* PQ);
#endif // PRIORITYQUEUE_H<file_sep>#ifndef GRAPHSORT_H
#define GRAPHSORT_H
#include "Graph.h"
#include "linkedList.h"
void TopologicalSort(Vertex* V, LNode** List);
void TS_DFS(Vertex* V, LNode** List);
#endif // GRAPHSORT_H<file_sep>//#include "Graph.h"
//#include "GraphSort.h"
//
//void main(void) {
// int i;
// LNode* SortedList = NULL;
// LNode* CurrentNode = NULL;
// Vertex* VertexList[10];
//
// Graph* graph = CreateGraph();
//
// for (i = 0; i < 8; i++)
// VertexList[i] = CreateVertex('A' + i);
//
//
// AddVertex(graph, VertexList[0]);
// AddVertex(graph, VertexList[2]);
// AddVertex(graph, VertexList[1]);
// AddVertex(graph, VertexList[3]);
// AddVertex(graph, VertexList[4]);
// AddVertex(graph, VertexList[5]);
// AddVertex(graph, VertexList[6]);
// AddVertex(graph, VertexList[7]);
//
// AddEdge(VertexList[0], CreateEdge(VertexList[0], VertexList[2], 0));
// AddEdge(VertexList[0], CreateEdge(VertexList[0], VertexList[3], 0));
//
// AddEdge(VertexList[1], CreateEdge(VertexList[1], VertexList[2], 0));
// AddEdge(VertexList[1], CreateEdge(VertexList[1], VertexList[4], 0));
//
// AddEdge(VertexList[2], CreateEdge(VertexList[2], VertexList[5], 0));
//
// AddEdge(VertexList[3], CreateEdge(VertexList[3], VertexList[5], 0));
// AddEdge(VertexList[3], CreateEdge(VertexList[3], VertexList[6], 0));
//
// AddEdge(VertexList[4], CreateEdge(VertexList[4], VertexList[6], 0));
//
// AddEdge(VertexList[5], CreateEdge(VertexList[5], VertexList[7], 0));
//
// AddEdge(VertexList[6], CreateEdge(VertexList[6], VertexList[7], 0));
//
// TopologicalSort(graph->Vertices, &SortedList);
//
// printf("Topological Sort Result : ");
//
// for (CurrentNode = SortedList; CurrentNode != NULL; CurrentNode = CurrentNode->Next)
// printf("%C ", ((Vertex*)CurrentNode->Data)->Data);
//
// DestroyGraph(graph);
//
// SLL_DestroyAllLNodes(SortedList);
//}<file_sep>#ifndef GRAPH_H
#define GRAPH_H
#include <stdio.h>
#include <stdlib.h>
#include "PriorityQueue.h"
enum VisitMode {Visited, NotVisited};
typedef int ElementType;
typedef struct _Vertex {
ElementType Data;
int Visited;
int Index;
struct _Vertex* Next;
struct _Edge* AdjacencyList;
} Vertex;
typedef struct _Edge {
int Weight;
struct _Edge* Next;
Vertex* From;
Vertex* Target;
} Edge;
typedef struct _Graph {
Vertex* Vertices;
int VertexCount;
} Graph;
Graph* CreateGraph();
void DestroyGraph(Graph* G);
Vertex* CreateVertex(ElementType Data);
void DestroyVertex(Vertex* V);
Edge* CreateEdge(Vertex* From, Vertex* Target, int Weight);
void AddVertex(Graph* G, Vertex* V);
void AddEdge(Vertex* V, Edge* E);
void PrintGraph(Graph* G);
#endif // GRAPH_H<file_sep>#include "LinkedList.h"
LNode* SLL_CreateNewNode(LDataType NewData) {
LNode* NewLNode = (LNode*)malloc(sizeof(LNode));
NewLNode->Data = NewData;
NewLNode->Next = NULL;
return NewLNode;
}
void SLL_InsertNewHead(LNode** List, LNode* NewHead) {
NewHead->Next = *List;
*List = NewHead;
}
void SLL_DestroyAllLNodes(LNode* Node) {
LNode* cur;
while (Node != NULL) {
cur = Node;
Node = Node->Next;
free(cur);
}
}<file_sep>#ifndef UNION_SET_H
#define UNION_SET_H
#include <stdio.h>
#include <stdlib.h>
typedef struct _Disjoint {
struct _DisjointSet* Parent;
void* Data;
} DisjointSet;
void DS_UnionSet(DisjointSet* Set1, DisjointSet* Set2);
DisjointSet* DS_FindSet(DisjointSet* Set);
DisjointSet* DS_MakeSet(void* NewData);
#endif // UNION_SET_H<file_sep>#ifndef GRAPH_TRAVERSAL_H
#define GRAPH_TRAVERSAL_H
#include "Graph.h"
#include "LinkedListQueue.h"
void DFS(Vertex* V);
void BFS(Vertex* V);
#endif // GRAPH_TRAVERSAL_H<file_sep>#ifndef MST_H
#define MST_H
#include "Graph.h"
#include "Disjoint_Set.h"
void Prim(Graph* G, Vertex* StartVertex, Graph* MST);
void Kruskal(Graph* G, Graph* MST);
#endif | 8c4f397d1badb58f8ede8f9e9dd32ea5b1be4830 | [
"C"
] | 14 | C | jmj073/Graph | 59b12dd00465ef212c8a5200261b1e49b02864c7 | ebb0316350110ad699dcca5b4a4300603e65c50e |
refs/heads/master | <file_sep>public class Hanoi {
private int n;
private String source, auxiliary, destination;
private StringBuilder sb = null;
public Hanoi(int n){
this.n = n;
this.source = "S";
this.auxiliary = "A";
this.destination = "D";
}
public void solve(int n, String source, String auxiliary, String destination){
if(n == 1){
sb.append(String.format("Slide Disk %d from rod %s to rod %s\n", n, source, destination));
}
else{
solve(n - 1, source, destination, auxiliary);
sb.append(String.format("Slide Disk %d from rod %s to rod %s\n", n, source, destination));
solve(n - 1, auxiliary, source, destination);
}
}
public String solve(){
if(sb == null){
sb = new StringBuilder();
solve(this.n, this.source, this.auxiliary, this.destination);
return sb.toString();
}
return sb.toString();
}
}
<file_sep># Hanoi towers
1. Console output
2. Recursive solution
3. Some Junit TestCases
| 34dac21d3db3ad043bf70ae301dbe2f02fe32087 | [
"Markdown",
"Java"
] | 2 | Java | gosftw/HSHanoiStageOne | b64f9dcf47eba45a4c88441995c97be9edf75317 | f9c826d66f8038c44639c4ea9d49b88a8dbdc78f |
refs/heads/master | <file_sep># InSalesNetApi
Шаблон библиотеки для интеграции приложения .Net с интернет-магазином на платформе InSales.ru.
Реализована загрузка категорий, продуктов и создание продукта, обновление модификации.
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace ShopHelperNet
{
static class CommandsList
{
static public string cCategories = "categories.json";
static public string cAddProduct = "products.json";
static public string cGetProducts = "products.json";
static public string cGetProductById = "products/{0}.json";
static public string cModifyVariant = "products/{0}/variants/{1}.json";
static public string cModifyGroupVariant = "products/variants_group_update.json";
}
public class ShopHelper
{
string FUrl, FUser, FPassword, FAccept, FContentType, FProtocol;
public ShopHelper(string url, string user, string password, string protocol = "https")
{
FUrl = url;
FUser = user;
FPassword = <PASSWORD>;
FAccept = "application/json";
FContentType = "application/json";
FProtocol = protocol;
}
string getAuth()
{
return System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(FUser + ":" + FPassword));
}
string getRequest(string command)
{
HttpWebRequest request = (HttpWebRequest)getCommandRequest(command);
request.Method = "GET";
request.Accept = FAccept;
request.ContentType = FContentType;
request.Headers["Authorization"] = "Basic " + getAuth();
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
StreamReader reader = new StreamReader(response.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
return output.ToString();
}
string postRequest(string command, byte[] data)
{
HttpWebRequest request = (HttpWebRequest)getCommandRequest(command);
request.ContentType = FContentType;
request.Method = "POST";
request.Headers["Authorization"] = "Basic " + getAuth();
request.Accept = FAccept;
request.ContentLength = data.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse response = request.GetResponseAsync().Result;
StreamReader reader = new StreamReader(response.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
response.Close();
return output.ToString();
}
string putRequest(string command, byte[] data)
{
HttpWebRequest request = (HttpWebRequest)getCommandRequest(command);
request.ContentType = FContentType;
request.Method = "PUT";
request.Headers["Authorization"] = "Basic " + getAuth();
request.Accept = FAccept;
request.ContentLength = data.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
WebResponse response = request.GetResponseAsync().Result;
StreamReader reader = new StreamReader(response.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
response.Close();
return output.ToString();
}
private WebRequest getCommandRequest(string command)
{
return WebRequest.Create(FProtocol + "://" + FUrl + "/" + command);
}
static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}
public List<Category> getCategories()
{
string s = getRequest(CommandsList.cCategories);
return JsonConvert.DeserializeObject<List<Category>>(s);
}
public Product AddProduct(Product product)
{
ProductWrapper pw = new ProductWrapper();
pw.product = product;
MemoryStream stream = new MemoryStream();
string res= JsonConvert.SerializeObject(pw);
byte[] data = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(res);
res = postRequest(CommandsList.cAddProduct, data);
return JsonConvert.DeserializeObject<Product>(res);
}
public VariantForUpdate ModifyVariant(int product_id, int variant_id, VariantForUpdate v)
{
VariantForUpdateWrapper w = new VariantForUpdateWrapper();
w.variant = v;
v.id = variant_id;
string res = JsonConvert.SerializeObject(w);
byte[] data = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(res);
res = putRequest(string.Format(CommandsList.cModifyVariant, product_id, variant_id), data);
return JsonConvert.DeserializeObject<VariantForUpdate>(res);
}
public List<PutResult> ModifyVariantGroup(VariantForUpdateGroup v)
{
string res = JsonConvert.SerializeObject(v);
byte[] data = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(res);
res = putRequest(CommandsList.cModifyGroupVariant, data);
return JsonConvert.DeserializeObject<List<PutResult>>(res);
}
public List<Product> getProducts(int Page = 0, int perPage = 0)
{
string parameters = Page > 0 ? string.Format("page={0}", Page) : "";
parameters += (parameters != "" ? "&" : "") + (perPage > 0 ? string.Format("per_page={0}", perPage) : "");
string req = (CommandsList.cGetProducts + (parameters != "" ? "?" + parameters : ""));
string s = getRequest(req);
return JsonConvert.DeserializeObject<List<Product>>(s);
}
public Product getProduct(int id)
{
string req = string.Format(CommandsList.cGetProductById, id);
string s = getRequest(req);
return JsonConvert.DeserializeObject<Product>(s);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShopHelperNet;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
namespace ShopIntegrationNetConsole
{
class Program
{
static void Main(string[] args)
{
ShopHelper helper = new ShopHelper("https://myshop-##myshop##.myinsales.ru/admin", "##login##", "##password##");
List<Category> l = helper.getCategories();
Product p = new Product();
if ((l != null) && (l.Count > 0))
p.category_id = l[0].id;
else
p.category_id = 0;
p.title = "CSharp product";
Variants_Attribute v = new Variants_Attribute();
v.price = 100;
v.sku = "12345567";
p.variants.Add(v);
p = helper.AddProduct(p);
Console.ReadLine();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace ShopHelperNet
{
[DataContract]
public class Category
{
[DataMember]
public DateTime created_at;
[DataMember]
public int id;
[DataMember(Name = "parent-id")]
public int parent_id;
[DataMember]
public int position;
[DataMember]
public string title;
[DataMember]
public DateTime updated_at;
}
[DataContract]
public class Variants_Attribute
{
[DataMember]
public decimal? price;
[DataMember]
public decimal? cost_price;
[DataMember]
public decimal? old_price;
[DataMember]
public string sku;
[DataMember(EmitDefaultValue = false)]
public int id;
[DataMember]
public DateTime updated_at;
}
[DataContract]
public class Product
{
[DataMember(EmitDefaultValue = false)]
public int id;
[DataMember]
public int category_id;
string FTitle;
[DataMember]
public string title { get { if (FTitle != null) return FTitle; else return ""; }
set { FTitle = value; } }
string FDescription;
[DataMember]
public string description
{
get { if (FDescription != null) return FDescription; else return ""; }
set { FDescription = value; }
}
[DataMember]
public string short_description;
[DataMember]
public string permalink;
[DataMember(Name = "variants_attributes")]
List<Variants_Attribute> variants_attributes
{ get { return variants; } }
[DataMember(Name = "variants", EmitDefaultValue = false)]
List<Variants_Attribute> variants_for_create
{ get { if (id == 0) return null; else return variants; } set { variants = value; } }
public List<Variants_Attribute> variants;
[DataMember]
public DateTime updated_at;
public Product()
{
variants = new List<Variants_Attribute>();
}
}
[DataContract]
public class ProductWrapper
{
[DataMember]
public Product product;
}
[DataContract]
public class VariantForUpdate
{
[DataMember]
public int id;
[DataMember]
public decimal price;
[DataMember]
public decimal quantity;
}
[DataContract]
public class VariantForUpdateWrapper
{
[DataMember]
public VariantForUpdate variant;
}
[DataContract]
public class VariantForUpdateGroup
{
[DataMember]
public List<VariantForUpdate> variants;
}
[DataContract]
public class PutResult
{
[DataMember]
public int id;
[DataMember]
public string status;
}
}
| 596d6f451f869b093e1530c7f12728f7682c287b | [
"Markdown",
"C#"
] | 4 | Markdown | dk76/InSalesNetApi | b5a18e618a643e756262637cc76cd78ba1af2821 | 63d61f10bdf1b20aaad44717ff3c1f62184ea64b |
refs/heads/master | <file_sep>// pages/goods_list/goodslist.js
const util = require('../../utils/util.js')
Page({
/**
* 页面的初始数据
*/
data: {
filter: {},
isDown:false,
isUp: false,
type: 'style',
typeId: '',
page: 1, // 当前页码
totalPage: 1, // 总页码
pageArray: [], // 分页列表
goodsItmes: [],
ptItems: [], // 普通分类
spItems: [], // 饰品分类
bannerUrl: "http://hyym.oocpo.com/5909d384c59411e98ad35254008e9dc2.jpg?ran=" + Math.random()
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
// 获取商品列表
// type为style或category
// typeId为style_id或category_id
const type = options.type
const typeId = options.typeId
this.setData({ type: type, typeId: typeId })
var filter = { title: options.title, page: 1, sort_order: 'order__desc' }
if (type == 'style') {
filter['style_id'] = typeId
} else {
filter['category_id'] = typeId
}
this.setData({ filter: filter })
this.getGoodsList()
this.getSpList()
this.getPtList()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
/**
* 获取饰品列表
*/
getSpList() {
util.getCategoryList('1').then(res => {
this.setData({ spItems: res.data })
})
},
/**
* 获取普通列表
*/
getPtList() {
if (this.data.type == 'style') {
// 风格搜索要获取物品分类
util.getCategoryList('0').then(res => {
this.setData({ ptItems: res.data })
})
} else {
// 物品搜索要获取风格分类
util.getStyleList().then(res => {
this.setData({ ptItems: res.data })
})
}
},
/**
* 获取商品列表
*/
getGoodsList(top=false) {
wx.cloud.callFunction({
name: 'databaseOper',
data: {
collection: 'furniture',
type: 'get',
where: this.data.filter
}
}).then(res => {
const result = res.result
const pageArray = util.pagination(result.page, result.totalPage)
this.setData({ goodsItmes: result.data, page: result.page, totalPage: result.totalPage, pageArray: pageArray })
if (top) {
wx.pageScrollTo({ scrollTop: 0, duration: 300 })
}
})
},
onClickDown:function(){
if(this.data.isDown){
this.setData({
isDown: false
})
}else{
this.setData({
isDown: true,
isUp:false
})
}
},
onClickUp: function () {
if (this.data.isUp) {
this.setData({
isUp: false
})
} else {
this.setData({
isUp: true,
isDown: false
})
}
},
onClickPrev: function () {
if (this.data.page > 1) {
const page = this.data.page - 1
this.setData({ page: page, 'filter.page': page })
this.getGoodsList(true)
}
},
onClickNext: function () {
if (this.data.page < this.data.totalPage) {
const page = this.data.page + 1
this.setData({ page: page, 'filter.page': page })
this.getGoodsList(true)
}
},
onClickPage: function (e) {
const page = e.currentTarget.dataset.page
if (page != this.data.page) {
this.setData({ page: page, 'filter.page': page })
this.getGoodsList(true)
}
},
onFilterChange(e) {
const id = e.currentTarget.dataset.id
var type = e.currentTarget.dataset.type
if (this.data.type == 'style') {
// 从当前风格中筛选物品
this.setData({ page: 1, 'filter.page': 1, 'filter.category_id': id })
} else {
if (type == 'pt') {
// 从当前物品类中筛选风格
this.setData({ page: 1, 'filter.page': 1, 'filter.style_id': id })
} else {
// 因为饰品没有风格,所以
this.setData({ page: 1, 'filter.page': 1, 'filter.category_id': id })
}
}
this.setData({ typeId: id })
this.getGoodsList()
if (type == 'pt') {
this.onClickDown()
} else {
this.onClickUp()
}
}
})<file_sep>/**
* 时间格式化
*/
const db = wx.cloud.database()
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
/**
* 判断字符串是否在列表中
*/
const isInArray = (arr, value) => {
for (var i = 0; i < arr.length; i++) {
if (value === arr[i]) {
return true;
}
}
return false;
}
/**
* 获取分页数组,最多显示7个页码
*/
const pagination = (page, totalPage) => {
const offset = totalPage - 7 < 1 ? 6 : 3
const beginPage = page - offset < 1 ? 1 : page - offset
const endPage = page + offset > totalPage ? totalPage : page + offset
var pageArray = []
for (let i = beginPage; i <= endPage; i++) {
pageArray.push(i)
}
return pageArray
}
/**
* 提交订单
*/
const orderCommit = (commitData, products, types, ) => {
const userId = wx.getStorageSync('userId')
const now = formatTime(new Date())
// 验证手机号
return new Promise((resolve, reject) => {
if (commitData.name.length < 2) {
reject('请正确填写姓名')
} else if (!(/^1[3|4|5|7|8][0-9]\d{4,8}$/.test(commitData.phone))) {
reject('请正确填写手机号')
} else if (!userId) {
reject('获取用户信息失败,请联系客服处理')
} else {
wx.cloud.callFunction({
name: 'databaseOper',
data: {
collection: 'order',
type: 'add',
data: {
order_id: '',
status: 0,
types: types.toString(),
name: commitData.name,
phone: commitData.phone,
address: commitData.address,
style: commitData.style,
user_id: userId,
updated: now,
created: now,
products: products
}
}
}).then(res => {
console.log('提交订单成功')
resolve()
}).catch(e => {
console.log('提交订单失败', e)
reject('提交订单失败,请联系管理员处理')
})
}
})
}
const getCategoryList = type => {
return db.collection('category').where({
type: type
}).limit(20).get()
}
const getStyleList = _id => {
if (_id) {
return db.collection('style').doc(_id).get()
} else {
return db.collection('style').limit(20).get()
}
}
const cacheCategory = type => {
db.collection('category').where({
type: type
}).limit(20).get().then(res => {
wx.setStorageSync('categoryItems', res.data)
})
}
const cacheStyle = () => {
db.collection('style').limit(20).get().then(res => {
wx.setStorageSync('styleItems', res.data)
})
}
const cacheBanner = position => {
wx.cloud.callFunction({
name: 'databaseOper',
data: {
collection: 'banner',
type: 'get',
where: { page: 1, position: position, sort_order: 'order__asc' }
}
}).then(res => {
const data = res.result.data
const dataSymbol = (position == 0) ? 'bannerData1' : 'bannerData2'
wx.setStorageSync(dataSymbol, data.slice(0, 6))
})
}
const cacheDesigner = () => {
wx.cloud.callFunction({
name: 'databaseOper',
data: {
collection: 'designer',
type: 'get',
where: { page: 1 }
}
}).then(res => {
const result = res.result
const total = result.total > 16 ? 16 : result.total
var designerList = []
for (let i = 0; i < result.total; i = i + 4) {
designerList.push({
deslist: result.data.slice(i, i + 4)
})
}
wx.setStorageSync('desData', designerList)
})
}
module.exports = {
formatTime: formatTime,
isInArray: isInArray,
pagination: pagination,
orderCommit: orderCommit,
getCategoryList: getCategoryList,
getStyleList: getStyleList,
cacheCategory: cacheCategory,
cacheStyle: cacheStyle,
cacheBanner: cacheBanner,
cacheDesigner: cacheDesigner
}
<file_sep># furniture_wechat
家具微信小程序端
<file_sep>// pages/experience/experience.js
Page({
/**
* 页面的初始数据
*/
data: {
// 得胜
latitudeDs: 25.055060,
longitudeDs: 102.745150,
markersDs: [{
iconPath: '../../images/icon/markers.svg',
latitude: 25.055060,
longitude: 102.745150,
name: '华韵亿美'
}],
// 红星
latitudeHx: 24.994446,
longitudeHx: 102.683608,
markersHx: [{
iconPath: '../../images/icon/markers.svg',
latitude: 24.994446,
longitude: 102.683608,
name: '华韵亿美'
}],
covers: [],
polygons: [],
enable3d: false,
showCompass: true,
enableOverlooking: false,
enableZoom: true,
enableScroll: true,
enableRotate: false,
drawPolygon: false,
enableSatellite: false,
enableTraffic: false,
aboutUrl: "http://hyym.oocpo.com/f3433a06d92811e98ad35254008e9dc2.jpg?ran=" + Math.random()
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database({
env: 'product-0yhcc'
})
/**
* 保存用户信息
*/
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
const user = await db.collection('user').where({
openid: wxContext.OPENID
}).get()
if (user.data.length == 0) {
console.log('>>> start register')
return await db.collection('user').add({
data: {
avatarUrl: event.avatarUrl,
nickName: event.nickName,
gender: event.gender,
city: event.city,
country: event.country,
language: event.language,
province: event.province,
openid: wxContext.OPENID,
unionid: wxContext.UNIONID
}
})
} else {
console.log('>>> has registed')
return user.data[0]
}
}<file_sep>const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database({
env: 'product-0yhcc'
})
/**
* 集合增删改查操作
*/
exports.main = async (event, context) => {
const cName = event.collection
const type = event.type
const id = event._id ? event._id : ''
const data = event.data ? event.data : {}
var res = {}
if (type === 'doc') {
return await db.collection(cName).doc(id).get()
} else if (type === 'get') {
var filter = event.where ? event.where : {}
var order = {}
const page = filter.page ? parseInt(filter.page) : 1
const pageSize = filter.pageSize ? filter.pageSize : 16
const offset = (page - 1) * pageSize
console.log('>>> filter', filter)
delete filter.page
delete filter.pageSize
Object.keys(filter).forEach(key => {
var value = filter[key]
if (typeof(value) == 'string') {
var vls = value.split('__')
if (vls.length == 2 && vls[0] == 'like') {
filter[key] = { '$regex': vls[1], '$options': 'i' }
} else if (vls.length == 2 && vls[0] == 'order') {
order['field'] = key
order['order'] = vls[1]
delete filter[key]
}
}
})
const countRes = await db.collection(cName).where(filter).count()
const total = countRes.total
const totalPage = Math.ceil(total / pageSize)
console.log('>>> where', filter)
console.log('>>> order', order)
if (order.field && order.order) {
res = await db.collection(cName).where(filter).orderBy(order.field, order.order).skip(offset).limit(pageSize).get()
} else {
res = await db.collection(cName).where(filter).skip(offset).limit(pageSize).get()
}
return {
data: res.data,
page: page,
pageSize: pageSize,
total: total,
totalPage: totalPage
}
} else if (type === 'add') {
return await db.collection(cName).add({
data: data
})
} else if (type === 'update') {
return await db.collection(cName).doc(id).update({
data: data
})
} else if (type === 'delete') {
return await db.collection(cName).doc(id).remove()
} else {
return new Promise((resolve, reject) => {
reject(new Error('type paramert is error'));
})
}
}
<file_sep>// pages/prodea/prodea.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
id: '',
isShow: false,
isAll: false,
isPop: false,
itemDetail: {},
currentSwiper4: 0,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
const _id = options._id
const db = wx.cloud.database()
db.collection('furniture').doc(_id).get().then(res => {
this.setData({ itemDetail: res.data })
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
swiperChange4: function (e) {
this.setData({
currentSwiper4: e.detail.current
})
},
onClickPop: function(){
this.setData({
isPop:true
})
},
onClickPopOpen(e) {
this.setData({
isPop: true,
popTit: e.target.dataset.val
})
console.log(this.data.popTit);
},
onClickPopClose() {
this.setData({
isPop: false
})
},
/**
* 添加到搭配间
*/
onClickPopShow() {
var that = this;
const userId = wx.getStorageSync('userId')
console.log('userId', userId)
if (userId) {
const db = wx.cloud.database()
db.collection('cart').where({
user_id: userId,
product_id: that.data.itemDetail._id
}).count().then(res => {
if (res.total == 0) {
return wx.cloud.callFunction({
name: 'databaseOper',
data: {
collection: 'cart',
type: 'add',
data: {
user_id: userId,
title: that.data.itemDetail.title,
product_id: that.data.itemDetail._id,
img: that.data.itemDetail.img[0],
style_id: that.data.itemDetail.style_id,
price: that.data.itemDetail.price,
checked: false
}
}
})
}
}).then(res => {
that.setData({
isShow: true
})
setTimeout(function () {
that.setData({ isShow: false })
}, 1500)
})
} else {
that.setData({
isShow: true
})
setTimeout(function () {
that.setData({ isShow: false })
}, 1500)
}
}
})<file_sep>// pages/case_deatils/casedea.js
const util = require('../../utils/util.js')
Page({
/**
* 页面的初始数据
*/
data: {
itemDetail: {},
commitData: {
name: '',
phone: '',
address: ''
},
isPop: false
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
const _id = options._id
const db = wx.cloud.database()
db.collection('case').doc(_id).get().then(res => {
this.setData({ itemDetail: res.data })
return util.getStyleList(res.data.style_id)
}).then(res => {
this.setData({ 'itemDetail.styleTitle': res.data.title })
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
/**
* 提交信息时,输入框内容变更时触发
*/
inputChange(e) {
const item = e.currentTarget.dataset.item
const value = e.detail.value
const key = 'commitData.' + item
this.setData({
[key]: value
})
},
onClickPopOpen(e) {
this.setData({
isPop: true
})
},
onClickPopClose() {
this.setData({
isPop: false
})
},
/**
* 提交我想这样搭
*/
onClickCommit: function () {
const commitData = this.data.commitData
const products = [this.data.itemDetail]
const types = 2
util.orderCommit(commitData, products, types).then(res => {
this.onClickPopClose()
wx.showModal({
title: '预定成功',
content: '我们将会尽快联系您,请您保持电话畅通',
showCancel: false,
confirmText: '确定'
})
}).catch(err => {
wx.showModal({
title: '错误',
content: err,
showCancel: false,
confirmText: '确定'
})
})
}
})<file_sep>// pages/collocation/collocation.js
const app = getApp()
const util = require('../../utils/util.js')
Page({
/**
* 页面的初始数据
*/
data: {
isAll:false,
isPop:false,
popTit:'',
popItem: '',
cartItmes: [],
selectedItems: {},
commitData: {
name: '',
phone: '',
address: ''
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({ cartItmes: wx.getStorageSync('cartItems') })
this.getCartList()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
getCartList() {
var userId = wx.getStorageSync('userId')
wx.cloud.callFunction({
name: 'databaseOper',
data: {
collection: 'cart',
type: 'get',
where: {
user_id: userId, pageSize: 30
}
}
}).then(res => {
const data = res.result.data
this.setData({ cartItmes: data })
wx.setStorageSync('cartItems', data)
})
},
onClickAll:function(){
var flag = false;
if(this.data.isAll){
flag = false
} else {
flag = true
}
this.setData({
isAll: flag
})
for (let i = 0; i < this.data.cartItmes.length; i++) {
const key = 'cartItmes[' + i + '].checked'
const val = this.data.cartItmes[i].checked
this.setData({ [key]: flag })
}
},
onClickPopOpen(e) {
this.setData({
isPop: true,
popTit: e.target.dataset.val,
popItem: e.target.dataset.item
})
},
onClickPopClose() {
this.setData({
isPop: false
})
},
/**
* 点击删除
*/
onClickDelete(e) {
const id = e.currentTarget.dataset.id
wx.cloud.callFunction({
name: 'databaseOper',
data: {
collection: 'cart',
type: 'delete',
_id: id
}
}).then(res => {
this.getCartList()
})
},
/**
* 选择变更后触发
*/
checkboxChange(e) {
for (let i = 0; i < this.data.cartItmes.length; i++) {
const key = 'cartItmes[' + i + '].checked'
const isIn = util.isInArray(e.detail.value, this.data.cartItmes[i]._id)
if (isIn) {
this.setData({ [key]: true })
} else {
this.setData({ [key]: false })
}
}
},
/**
* 提交信息时,输入框内容变更时触发
*/
inputChange(e) {
const item = e.currentTarget.dataset.item
const value = e.detail.value
const key = 'commitData.' + item
this.setData({
[key]: value
})
},
/**
* 提交订单
*/
onClickCommit() {
const types = this.data.popItem
const commitData = this.data.commitData
const products = []
// 获取所选物品
this.data.cartItmes.forEach(element => {
if (element.checked) {
products.push(element)
}
})
if (types === '1' && products.length === 0) {
wx.showModal({
title: '错误',
content: '请先选择物品',
showCancel: false,
confirmText: '确定'
})
} else {
util.orderCommit(commitData, products, types).then(res => {
this.onClickPopClose()
wx.showModal({
title: '预定成功',
content: '我们将会尽快联系您,请您保持电话畅通',
showCancel: false,
confirmText: '确定'
})
}).catch(err => {
wx.showModal({
title: '错误',
content: err,
showCancel: false,
confirmText: '确定'
})
})
}
}
})<file_sep>// pages/colldea/colldea.js
const util = require('../../utils/util.js')
Page({
/**
* 页面的初始数据
*/
data: {
selectShow: false,//控制下拉列表的显示隐藏,false隐藏、true显示
selectData: [],//下拉列表的数据
index: 0,//选择的下拉列表下标
itemDetail: {},
commitData: {
name: '',
phone: '',
address: '',
style: ''
}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getItemDetail()
this.getStyleList()
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
getItemDetail() {
const db = wx.cloud.database()
db.collection('soft').get().then(res => {
if (res.data.length > 0) {
this.setData({ itemDetail: res.data[0] })
}
})
},
getStyleList() {
util.getStyleList().then(res => {
this.setData({ selectData: res.data })
})
},
// 点击下拉显示框
selectTap() {
this.setData({
selectShow: !this.data.selectShow
});
},
// 点击下拉列表
optionTap(e) {
let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
let key = 'commitData.style'
let val = this.data.selectData[Index].title
this.setData({
index: Index,
selectShow: !this.data.selectShow,
[key]: val
})
},
/**
* 提交信息时,输入框内容变更时触发
*/
inputChange(e) {
const item = e.currentTarget.dataset.item
const value = e.detail.value
const key = 'commitData.' + item
this.setData({
[key]: value
})
},
/**
* 提交全屋软装搭配
*/
onClickCommit: function () {
const commitData = this.data.commitData
const products = [this.data.itemDetail]
const types = 0
util.orderCommit(commitData, products, types).then(res => {
wx.showModal({
title: '预定成功',
content: '我们将会尽快联系您,请您保持电话畅通',
showCancel: false,
confirmText: '确定'
})
}).catch(err => {
wx.showModal({
title: '错误',
content: err,
showCancel: false,
confirmText: '确定'
})
})
}
})<file_sep>//index.js
//获取应用实例
const app = getApp()
Page({
data: {
bannerData1: [],
bannerData2: [],
designerPage: 1,
designerTotalPage: 1,
desData:[] ,
currentSwiper: 0,
currentSwiper2: 0,
currentSwiper3: 0,
height:0,
height2: 0,
userInfo: {},
hasUserInfo: true,
colldeaUrl: "http://hyym.oocpo.com/72461fcec59411e98ad35254008e9dc2.jpg?ran=" + Math.random(),
caseUrl: "http://hyym.oocpo.com/2a61941ad92911e98ad35254008e9dc2.jpg?ran=" + Math.random(),
aboutUrl: "http://hyym.oocpo.com/f3433a06d92811e98ad35254008e9dc2.jpg?ran=" + Math.random()
},
onLoad: function () {
app.authForbidCallBack = res => {
this.setData({ hasUserInfo: false })
}
app.userInfoReadyCallback = res => {
this.setData({ hasUserInfo: true })
}
app.cacheCallback = res => {
this.setData({ bannerData1: wx.getStorageSync('bannerData1') })
this.setData({ bannerData2: wx.getStorageSync('bannerData2') })
this.setData({ desData: wx.getStorageSync('desData') })
console.log(this.data.bannerData2)
}
},
onShow: function () {
this.setData({ bannerData1: wx.getStorageSync('bannerData1') })
this.setData({ bannerData2: wx.getStorageSync('bannerData2') })
this.setData({ desData: wx.getStorageSync('desData') })
},
bindGetUserInfo: function (e) {
var that = this
wx.getSetting({
success: res => {
// 再次获取用户是否同意
if (res.authSetting['scope.userInfo']) {
// 注册
wx.cloud.callFunction({
name: "register",
data: e.detail.userInfo,
success: res => {
app.globalData.userInfo = e.detail.userInfo
that.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
console.log("注册成功", res)
wx.setStorageSync('userId', res.result._id)
}
})
} else {
console.log('user forbid')
}
}
})
},
setConHeight:function(e){
var imgWidth = e.detail.width;
var imgHeight = e.detail.height;
var sysInfo = wx.getSystemInfoSync();
var screeWidth = sysInfo.screenWidth;
var scale = screeWidth / imgWidth;
this.setData({
height: imgHeight * scale
})
},
swiperChange: function (e) {
this.setData({
currentSwiper: e.detail.current
})
},
setConHeight2: function (e) {
var imgWidth = e.detail.width;
var imgHeight = e.detail.height;
var sysInfo = wx.getSystemInfoSync();
var screeWidth = sysInfo.screenWidth;
var scale = screeWidth / imgWidth;
this.setData({
height2: imgHeight * scale
})
},
swiperChange2: function (e) {
this.setData({
currentSwiper2: e.detail.current
})
},
swiperChange3: function (e) {
this.setData({
currentSwiper3: e.detail.current
})
}
})
| 1fb2c6b975989d0401552d5ca92ecb49f933460c | [
"JavaScript",
"Markdown"
] | 11 | JavaScript | grey-swan/furniture_wechat | cf76b4b4661d02eb577f6ba37ada6a31cc88f9f8 | 3bf06ce73e62204817b10f53cab7a54d973c4498 |
refs/heads/master | <repo_name>achyuat/Grim<file_sep>/learnScrape.py
import urllib
import random
#from urllib.request import urlopen
import requests
from bs4 import BeautifulSoup
rl = input("enter the website url 'the code is made to work for https://alpha.wallhaven.cc'")
tag = input("enter the topic/tag")
tag = tag.replace(" ","+")
url = rl+"/search?q=%s&search_image="%tag
#url = "https://alpha.wallhaven.cc/search?q=water+fall&search_image="
store = requests.get(url)
soup = BeautifulSoup(store.content,"html.parser")
links = soup.find_all("a")
finallist=[]
for link in links :
s = str(link)
if "wallpaper" in s:
#print(link.get("href"))
#urllib.request.urlretrieve(link.get("href").jpg, "grub.jpg")
finallist.append(str(link.get("href")))
#finallist.append((link.get("href")))
#print(finallist)
asdf =random.choice(finallist)
print(asdf)
#..................................................everything below this is to download the file but it isn't working yet
#asdf = asdf+".jpg"
#urllib.request.urlopen(asdf, "grub.jpg")
'''resource = urllib.request.urlopen(asdf)
output = open("file01.jpg","wb")
output.write(resource.read())
output.close()'''
#urllib.urlretrieve(asdf,"grubimg.jpg") | 6de61ce8d4a401a4cbe593108f27de6d91569512 | [
"Python"
] | 1 | Python | achyuat/Grim | c1ea0d59b47760fac61d89f657fd79b67bff53c6 | 00e4e2e52518c80ff50c277e84814d7e2f550faa |
refs/heads/master | <repo_name>Lredhdx/JAVAfiftypractice<file_sep>/Practice22.java
package fiftypratice;
/**
* 题目:利用递归方法求5!。
*
* */
public class Practice22 {
public static void main(String[] args) {
int n=5;
Fac sum=new Fac();
System.out.println("5!="+sum.Fac(n));
}
}
class Fac{
//public int n;
public long Fac(int n){
long value=0;
if(n==1){
value=1;
return value;
}
else {
return n*Fac(n-1);
}
}
}<file_sep>/Practice02.java
package fiftypratice;
/**
*
* 判断101-200之间有多少个素数,并输出所有素数。
*/
public class Practice02 {
public static void main(String[] args) {
int count=0;
int m=0;
boolean b=false;
System.out.println("101-200之间的素数有:");
for(int i=101;i<=200;i++){
for(int j=2;j<i;j++){
if(i%j==0){
b=false;
break;
}else{
b=true;
}
}
if(b==true){
m++;
count++;
System.out.print(i+" ");
if(m%5==0){
System.out.println();
}
}
}
System.out.println();
System.out.println("共有"+count+"个");
}
}
<file_sep>/Practice24.java
package fiftypratice;
import java.util.Scanner;
/**
* 题目:给一个不多于5位的正整数,
* 要求:一、求它是几位数,二、逆序打印出各位数字。
*
*
* */
public class Practice24 {
public static void main(String[] args) {
/*System.out.println("请输入一个不多于五位的正整数:");
Scanner s=new Scanner(System.in);
int n;
int count=1;
n=s.nextInt();
int temp=n;
if(s!=null){
s.close();
}
while(n/10!=0){
count++;
n=n/10;
}
System.out.println("这是一个"+count+"位数");
System.out.println("它的逆序为:");
int a[]=new int[count];
for(int i=0;i<a.length;i++){
a[i]=temp%10;
temp=temp/10;
System.out.print(a[i]);
}*/
//方法二:
Scanner s = new Scanner(System.in);
System.out.print("请输入一个正整数:");
long a = s.nextLong();
if(s!=null){
s.close();
}
String ss = Long.toString(a);
char[] ch = ss.toCharArray();
int j=ch.length;
System.out.println(a + "是一个"+ j +"位数。");
System.out.print("按逆序输出是:");
for(int i=j-1; i>=0; i--) {
System.out.print(ch[i]);
}
}
}
<file_sep>/Practice32.java
package fiftypratice;
import java.util.Scanner;
/**
* 题目:取一个整数a从右端开始的4~7位。
* */
public class Practice32 {
public static void main(String[] args) {
System.out.println("请输入一个超过七位的整数:");
Scanner s=new Scanner(System.in);
long a=s.nextLong();
if(s!=null){
s.close();
}
String ss=Long.toString(a);
char []arr=ss.toCharArray();
int l=arr.length;
System.out.println(""+arr[l-7]+arr[l-6]+arr[l-5]+arr[l-4]);
}
}
<file_sep>/Practice20.java
package fiftypratice;
/**
* 题目:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...
* 求出这个数列的前20项之和。
*
* */
public class Practice20 {
public static void main(String[] args) {
double sum=0;
double f,m=2,n=1,t;
for(int i=1;i<=20;i++){
f=m/n;
sum=sum+f;
t=m;
m=m+n;
n=t;
}
System.out.println("这个数列的前20项之和为:"+sum);
}
}
<file_sep>/Practice03.java
package fiftypratice;
/**
* 打印出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,
* 其各位数字立方和等于该数本身。
*
*
*/
public class Practice03 {
public static void main(String[] args) {
System.out.println("三位数水仙花数有:");
int m,n,t,j;
for(int i=100;i<=999;i++){
m=i%10;//得到个位数;
j=i/10;
n=j%10;//得到十位数;
t=i/100;//得到百位数;
if(i==(m*m*m+n*n*n+t*t*t)){
System.out.print(i+" ");
}else{
continue;
}
}
}
}
<file_sep>/Practice17.java
package fiftypratice;
/**
* 题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,
* 又多吃了一个 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。
* 以后每天早上都吃了前一天剩下 的一半零一个。
* 到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。
*
* */
public class Practice17 {
public static void main(String[] args) {
int n=1;
for(int i=2;i<=10;i++){
n=n+1;
n=2*n;
}
System.out.println(n);
}
}
<file_sep>/Practice34.java
package fiftypratice;
import java.util.Scanner;
/**
* 题目:输入3个数a,b,c,按大小顺序输出。
* */
public class Practice34 {
public static void main(String[] args) {
System.out.println("请输入三个数:");
int a,b,c;
Scanner s=new Scanner(System.in);
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
if(s!=null){
s.close();
}
select(a,b,c);
}
public static void select(int a,int b,int c){
if(a>b){
int t=b;
b=a;
a=t;
} if(a>c){
int t=c;
c=a;
a=t;
} if(b>c){
int t=c;
c=b;
b=t;
}
System.out.println("a="+a+" "+"b="+b+" "+"c="+c);
}
}
<file_sep>/Practice28.java
package fiftypratice;
import java.util.Arrays;
import java.util.Scanner;
/**
* 题目:对10个数进行排序
*
* */
public class Practice28 {
public static void main(String[] args) {
int arr[]=new int[10];
System.out.println("Please input ten number:");
Scanner s=new Scanner(System.in);
for(int i=0;i<arr.length;i++){
arr[i]=s.nextInt();
}
if(s!=null){
s.close();
}
for(int j=0;j<arr.length-1;j++){
for(int i=j+1;i<arr.length;i++){
//int max=arr[i];
if(arr[i]>arr[j]){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
String info=Arrays.toString(arr);
System.out.println("The result of selecting sort:"+info);
}
}
<file_sep>/Practice43.java
package fiftypratice;
/**
* 题目:求0—7所能组成的奇数个数。
组成1位数是4个。
组成2位数是7*4个。
组成3位数是7*8*4个。
组成4位数是7*8*8*4个。
......
*
* */
public class Practice43 {
public static void main(String[] args) {
int sum=4;
int j;
System.out.println("组成1位数是:"+sum+"个");
sum=sum*7;
System.out.println("组成2位数是:"+sum+"个");
for(j=3;j<=7;j++){
sum*=8;
System.out.println("组成"+j+"位数是:"+sum+"个");
}
// Scanner s=new Scanner(System.in);
}
}
<file_sep>/Practice25.java
package fiftypratice;
import java.util.Scanner;
/**
* 题目:一个5位数,判断它是不是回文数。
* 即12321是回文数,个位与万位相同,十位与千位相同。
*
* */
public class Practice25 {
public static void main(String[] args) {
System.out.println("请输入一个五位数:");
int n=0;
Scanner s=new Scanner(System.in);
n=s.nextInt();
if(s!=null){
s.close();
}
String ss=Integer.toString(n);//或者 String ss=String.valueOf(n);
char []ch=ss.toCharArray();
if((ch[0]==ch[4])&&(ch[1]==ch[3])){
System.out.println("该数是回文数!");
}else{
System.out.println("该数不是回文数!");
}
//更好的方法 不需要限制位数
/*Scanner s = new Scanner(System.in);
boolean is =true;
System.out.print("请输入一个正整数:");
long a = s.nextLong();
String ss = Long.toString(a);
char[] ch = ss.toCharArray();
int j=ch.length;
for(int i=0; i<j/2; i++) {
if(ch[i]!=ch[j-i-1]){is=false;}
}
if(is==true){System.out.println("这是一个回文数");}
else {System.out.println("这不是一个回文数");}
* */
}
}
<file_sep>/Practice06.java
package fiftypratice;
import java.util.Scanner;
/**
* 输入两个正整数m和n,求其最大公约数和最小公倍数。
" 在循环中,只要除数不等于0,用较大数除以较小的数,
将小的一个数作为下一轮循环的大数,取得的余数作为下一轮循环的较小的数,
如此循环直到较小的数的值为0,返回较大的数,
此数即为最大公约数,最小公倍数为两数之积除以最大公约数。"
*
* */
public class Practice06 {
public static void main(String[] args) {
System.out.println("请输入两个正整数:");
int m,n;
int max,min;
Scanner s=new Scanner(System.in);
m=s.nextInt();
n=s.nextInt();
if(s!=null){
s.close();
}
if(m>=n){
max=m;
min=n;
}
else{
max=n;
min=m;
}
while(min!=0){
int r;
r=max%min;
max=min;
min=r;
}
System.out.println("它们的最大公约数为:"+max);
int d;
d=m*n/max;
System.out.println("它们的最小公倍数为:"+d);
}
}
<file_sep>/Practice21.java
package fiftypratice;
/**
* 题目:求1+2!+3!+...+20!的和
*
* */
public class Practice21 {
public static void main(String[] args) {
long sum=0;
long fac=1;
for(int i=1;i<=20;i++){
fac=fac*i;
sum+=fac;
}
System.out.println("1+2!+3!+...+20!="+sum);
}
}
<file_sep>/Practice13.java
package fiftypratice;
/**
*一个整数,它加上100后是一个完全平方数,
*再加上168又是一个完全平方数,请问该数是多少?
*
* */
public class Practice13 {
public static void main(String[] args) {
for(int i=0;i<=100000;i++){
if(Math.sqrt(i+100)%1==0){
if(Math.sqrt(i+268)%1==0){
System.out.println("该数是"+i);
}
}
}
}
}
<file_sep>/Practice35.java
package fiftypratice;
import java.util.Arrays;
import java.util.Scanner;
/*
* 题目:输入数组,最大的与第一个元素交换,
* 最小的与最后一个元素交换,输出数组。
* */
/*此题解法有误,若最大值交换的第一个元素是最小值,则条件二无法满足;
* */
public class Practice35 {
public static void main(String[] args) {
System.out.println("请输入一个元素为5的数组:");
int a[]=new int[5];
Scanner s=new Scanner(System.in);
for(int i=0;i<a.length;i++){
a[i]=s.nextInt();
}
if(s!=null){
s.close();
}
int min=a[0];
int max=a[0];
int index1=0;
int index2=0;
for(int i=0;i<a.length;i++){
if(a[i]>=max){
max=a[i];
index1=i;
}
if(a[i]<=min){
min=a[i];
index2=i;
}
}
if(index1 != 0) {
int temp = a[0];
a[0] = a[index1];
a[index1] = temp;
}
if(index2 != a.length-1) {
int temp = a[a.length-1];
a[a.length-1] = a[index2];
a[index2] = temp;
}
String t= Arrays.toString(a);
System.out.println(t);
}
}
<file_sep>/Practice23.java
package fiftypratice;
/**
* 题目:有5个人坐在一起,问第五个人多少岁?
* 他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。
* 问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。
* 最后问第一个人,他说是10岁。请问第五个人多大?
* */
public class Practice23 {
public static void main(String[] args) {
int age=10;
for(int i=5;i>=2;i--){
age+=2;
}
System.out.println("第五个人年龄:"+age+"岁");
}
}
<file_sep>/Practice12.java
package fiftypratice;
import java.util.Scanner;
/**
*
* "企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;
* 利润高于10万元,低于20万元时,低于10万元的部分按10%提成,
高于10万元的部分,可可提成7.5%;20万到40万之间时,高于20万元的部分,
可提成5%;40万到60万之间时高于40万元的部分,
可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,
高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润,
求应发放奖金总数? "
*/
public class Practice12 {
public static void main(String[] args) {
int n;
System.out.println("请输入当月利润:"+"万元。");
Scanner s=new Scanner(System.in);
n=s.nextInt();
if(s!=null){
s.close();
}
double a=0;
if(n<10){
a=0.1*n;
}
else if(n>=10&&n<20){
a=0.1*10+0.075*(n-10);
}
else if(n>=20&&n<40){
a=0.1*10+10*0.075+0.05*(n-20);
}
else if(n>=40&&n<60){
a=10*0.175+0.05*20+0.03*(n-40);
}
else if(n>=60&&n<100){
a=10*0.175+0.05*20+0.03*20+0.015*(n-60);
}
else if(n>=100){
a=10*0.175+0.05*20+0.03*20+0.015*40+0.01*(n-100);
}
System.out.println("应发奖金数为:"+a+"万元");
}
}
<file_sep>/Practice42.java
package fiftypratice;
/**
*
* 题目:809*??=800*??+9*??+1
其中??代表的两位数,8*??的结果为两位数,
9*??的结果为3位数。求??代表的两位数,及809*??后的结果。
题目错了!809x=800x+9x+1 这样的方程无解。去掉那个1就有解了。
* */
public class Practice42 {
public static void main(String[] args) {
int a=809,b,i;
for(i=10;i<13;i++)
{b=i*a ;
if(8*i<100&&9*i>=100)
System.out.println ("809*"+i+"="+"800*"+i+"+"+"9*"+i+"="+b);}// TODO Auto-generated method stub
}
}
<file_sep>/Practice07.java
package fiftypratice;
import java.util.Scanner;
/**
* 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
*
* */
public class Practice07 {
public static void main(String[] args) {
System.out.println("请输入一行字符:");
Scanner s=new Scanner(System.in);
String str=s.nextLine();
if(s!=null){
s.close();
}
int letter=0,space=0,number=0,other=0;
char[]ch=null;
ch=str.toCharArray();
for(int i=0;i<ch.length;i++){
if(ch[i]>='0'&&ch[i]<='9'){
number++;
}else if((ch[i]>='a'&&ch[i]<='z')||
(ch[i]>='A'&&ch[i]<='Z')){
letter++;
}else if(ch[i]==' '){
space++;
}else{
other++;
}
}
System.out.println("该段字符串的字母、数字、空格、"
+"其他字符的个数分别为:");
System.out.print(letter+" ");
System.out.print(number+" ");
System.out.print(space+" ");
System.out.print(other);
}
}
<file_sep>/Practice40.java
package fiftypratice;
import java.util.Scanner;
/**
* 题目:字符串排序。
*
* */
public class Practice40 {
public static void main(String[] args) {
System.out.println("请输入字符串数组字符串数:");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
System.out.println("请输入一个字符串数组:");
String [] arr=new String[n+1];
for(int i=0;i<arr.length;i++){
arr[i]=s.nextLine();
}
if(s!=null){
s.close();
}
for(int i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(compare(arr[i],arr[j])==false){
String t=arr[j];
arr[j]=arr[i];
arr[i]=t;
}
}
}
System.out.println("排序后:");
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
public static boolean compare(String s1,String s2){
boolean flag=true;
for(int i=0;i<s1.length()&&i<s2.length();i++){
if(s1.charAt(i)>s2.charAt(i)){
flag=false;
break;
}else if(s1.charAt(i)<s2.charAt(i)){
flag=true;
break;
}else {
if(s1.length() < s2.length()) {
flag = true;
} else {
flag = false;
}
}
}
return flag;
}
}
<file_sep>/Practice15.java
package fiftypratice;
import java.util.Scanner;
/**
* 题目:输入三个整数x,y,z,请把这三个数由小到大输出。
* */
public class Practice15 {
public static void main(String[] args) {
int x,y,z;
//int min,mid,max;
System.out.println("请输入三个整数:");
Scanner s=new Scanner(System.in);
x=s.nextInt();
y=s.nextInt();
z=s.nextInt();
if(s!=null){
s.close();
}
//min=x;
if(x>y){
int temp;
temp=x;
x=y;
y=temp;
}
if(x>z){
int temp;
temp=x;
x=z;
z=temp;
}
if(y>z){
int temp;
temp=z;
z=y;
y=temp;
}
System.out.println("从小到大依次为:");
System.out.print(x+" ");
System.out.print(y+" ");
System.out.print(z);
}
}
<file_sep>/Practice04.java
package fiftypratice;
import java.util.Scanner;
/**
*将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
*"对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
*(1)如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。
*(2)如果n <> k,但n能被k整除,则应打印出k的值,
* 并用n除以k的商,作为新的正整数你n,重复执行第一步。
*(3)如果n不能被k整除,则用k+1作为k的值,重复执行第一步。"
*
*
* */
public class Practice04 {
public static void main(String[] args) {
System.out.println("请输入一个正整数:");
Scanner in=new Scanner(System.in);
int n=0;
n=in.nextInt();
if(in!=null){
in.close();
}
System.out.println("分解质因数的结果为:");
System.out.print(n+"=");
int k=2;
while(k<=n){
if(k==n){
System.out.println(k);
break;
}
else if(n%k==0){
System.out.print(k+"*");
n=n/k;
}
else{
k++;
}
}
}
}
<file_sep>/Practice45.java
package fiftypratice;
import java.util.Scanner;
/**
* 题目:判断一个素数能被几个9整除
//题目错了吧?能被9整除的就不是素数了!所以改成整数了。
*
* */
public class Practice45 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int temp=n;
int count=0;
for(int i=0;temp%9==0;){
temp=temp/9;
count++;
}
System.out.println(count);
}
}
<file_sep>/Practice44.java
package fiftypratice;
import java.util.Scanner;
/**
* 题目:一个偶数总能表示为两个素数之和。
//由于用除sqrt(n)的方法求出的素数不包括2和3,
//因此在判断是否是素数程序中人为添加了一个3。
* */
public class Practice44 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n;
do{
System.out.print("请输入一个大于6的偶数:");
n=s.nextInt();
}while(n<6||n%2!=0);
for(int i=3;i<=n/2;i+=2){
if(fun(i)&&fun(n-i)){
System.out.println(n+"="+i+"+"+(n-i));
}
}
}
static boolean fun(int a){
boolean flag=false;
if(a==3){
flag=true;
return flag;
}
for(int i=2;i<=Math.sqrt(a);i++){
if(a%i==0){
flag=false;
break;
}else {
return true;
}
}
return flag;
}
}
<file_sep>/Practice37.java
package fiftypratice;
import java.util.Scanner;
/**
* 题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),
* 凡报到3的人退出圈子,问最后留下的是原来第几号的那位。
* */
public class Practice37 {
public static void main(String[] args) {
System.out.println("请输入人数n:");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
boolean []a=new boolean[n];
for(int i=0;i<a.length;i++){
a[i]=true;
}
int t=n;
int index=0;
int count=0;
while(t>1){
if(a[index]==true){
count++;
if(count==3){
count=0;
a[index]=false;
t--;
}
}
index++;
if(index==n){
index=0;
}
}
for(int i=0; i<n; i++) {
if(a[i] == true) {
System.out.println("原排在第"+(i+1)+"位的人留下了。");
}
}
if(s!=null){
s.close();
}
}
}
<file_sep>/Practice46.java
package fiftypratice;
import java.util.Scanner;
//题目:两个字符串连接程序
public class Practice46 {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("请输入一个字符串");
String str1=s.nextLine();
System.out.println("请输入一个字符串");
String str2=s.nextLine();
String str=str1+str2;
System.out.println(str);
if(s!=null){
s.close();
}
}
}
<file_sep>/Practice18.java
package fiftypratice;
/**
* 题目:两个乒乓球队进行比赛,各出三人。
* 甲队为a,b,c三人,乙队为x,y,z三人。
* 已抽签决定比赛名单。有人向队员打听比赛的名单。
* a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
*
* */
public class Practice18 {
static char[] m={'a','b','c'};
static char[] n={'x','y','z'};
public static void main(String[] args) {
//static char[] m={'a','b','c'};
for(int i=0;i<m.length;i++){
for(int j=0;j<n.length;j++){
if(m[i]=='a'&&n[j]=='x'){
continue;
}
else if(m[i]=='a'&&n[j]=='y'){
continue;
}
else if((m[i]=='a'&&n[j]=='x')||
m[i]=='c'&&n[j]=='z'){
continue;
}
else if((m[i]=='b'&&n[j]=='z')
||(m[i]=='b'&&n[j]=='y')){
continue;
}
else {System.out.println(m[i]+" vs "+n[j]);}
}
}
}
}
| dbf3a2398503fb612862fb71a73a490ca09aca51 | [
"Java"
] | 27 | Java | Lredhdx/JAVAfiftypractice | 5a9764858c897c5514d3c9d1a1fc585ce84cb277 | 1953272dd7e5a0a761eed2418a64d696be0d301b |
refs/heads/master | <file_sep>#!/bin/bash
for i in {1..255}; do
python2.7 scanport80.py $i &
done
<file_sep># BTFW-port-80-scanner
Behind the firewall port 80 (HTTP/HTTPS) scanner for restricted company internets
Is Nmap shows the whole 80 ports as open when scanning large interval of IP adresses? Is this because the Firewall your company is using?
Don't try each IP's by hand, automate it using this python+bash script. Replace ```target_host``` in python script with the IP interval you want to scan.
Python is used for socket, and bash script is used for multi processing made simple (because I don't know multi threading in python). Simpler is better.
Usage
```
./scanport80.sh
```
Use your ```grep``` skills to filter raw http respond outputs like this:
```
./scanport80.sh | grep cisco -B5 | grep Trying
```
<file_sep>import socket
import time
import sys
target_host = "192.168.56."
target_port = 80
for i in range (1,255):
#compose socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target_hosttmp = target_host + str(sys.argv[1])
print "Trying %s" %target_hosttmp
#connect the client
client.connect((target_hosttmp,target_port))
#send some data
client.send("GET / HTTP/1.1\r\nHost: google.com\r\n\r\n")
#receive some data
print "RESP"
try:
response = client.recv(4096)
print response
except:
print "NO RESP"
continue
| 3f4b564721c923ae83afbd1889a033a8fc1d885f | [
"Markdown",
"Python",
"Shell"
] | 3 | Shell | 773517913/BTFW-port-80-scanner | 951c2e47181059570e54891cf10f6365da509388 | 8c979206411eccaea65a389eba48e0b22261ab24 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lecture5
{
/* Sukurti naują tipą/klasę pavadinimu "Person" su 3 kintamaisiais(Name, Surname, Age)
Nebenaudojam žodelio static!
● main metode sukurti 5 egzempliorius, objektus Asmuo.Kiekvienam iš egzempliorių priskirti kitą vardą ir metus
● Atspausdinti objekto kintamuosius į konsolę
● Sukurti metodą pavadinimu "SayHello", kuris išvestų į konsolę pasisveikinimo žinutę*/
internal class Person
{
public string Name;
public string SurName;
public int Age;
//statinis kintamasis. STATIC YRA KLASES SAVYBE. ne static yra per klase sukurto objekto savybe
public static int PersonCount;
public void SayHello()
{
Console.WriteLine($"{Name} {SurName} {Age}");
}
// konstruktorius yra klases dalis ir kvieciamas kaip metodas klases iskvietimo metu. jis egzistuoja by default, bet yra tuscias
// sukurus, konstruktoriu galim panaudoti tik paduodant su parametrais
public Person(string name, string surname, int age)
{
Name = name;
Age = age;
SurName = surname;
//statinis kitnamasis, kuris skaiciuoja, kiek kartu buvo panaudotas konstruktorius
PersonCount++;
}
// galima sukurti daugiau nei viena konstruktoriu. Jei be parametru, tai tada sukuriam tuscia ir bus galima
public Person(string Name)
{
//this pointina i butent toje klaseje esanti kitnamaji
this.Name = Name;
}
// static naudojamas kuriant statinius metodas. jis yra klases metodas ir jo nereikia inicializuoti. negalima pasiekti ne'static fieldo
}
}<file_sep>using System;
namespace lecture5
{
internal class Program
{
private static void Main(string[] args)
{
/* var car1 = new Car();
car1.Name = "BMW";
car1.Age = 10;*/
var person1 = new Person("Algis", "Pagerintas", 33);
var person2 = new Person("Alfonsas", "Tiniginis", 73);
var person3 = new Person("Egle", "Motiejuke", 50);
var person4 = new Person("Ona", "Analginaite", 24);
var person5 = new Person("Jurgis", "Antanas", 12);
person1.SayHello();
Console.WriteLine("------------------Kitas asmuo---------------------");
person2.SayHello();
Console.WriteLine("------------------Kitas asmuo---------------------");
person3.SayHello();
Console.WriteLine("------------------Kitas asmuo---------------------");
person4.SayHello();
Console.WriteLine("------------------Kitas asmuo---------------------");
person5.SayHello();
;
Person[] vardai = new Person[] { person1, person2, person3, person4, person5 };
//daro lygiai ta pati. var pasikeicia i 'Person[]'
//var vardai = new Person[] { person1, person2, person3, person4, person5 }
foreach (var person in vardai)
{
Console.WriteLine($"{person.Name} {person.SurName} {person.Age}");
}
Console.WriteLine(Calculator.Add(5, 6));
// issaukiam kiek susikure tu Personu kuriant
Console.WriteLine(Person.PersonCount);
}
}
// klase yra kaip sablonas, su kuriuo galime kurti naujus objektus. Tai yra mūsų sukurtas duomenų tipas
/* internal class Car
{
public string Name;
public int Age;
}*/
} | d0116adb30a05fc0c86c41ca5e23c9bcf6916cde | [
"C#"
] | 2 | C# | ginpus/csharp-lecture-5 | 7c874b01e706a23e8c86e934010e9c7f4071ad93 | 2acfb2fbfdcd5cc1d929f7b5d2b9bdf2fd3b1728 |
refs/heads/master | <repo_name>luimi/navigation-mapbox<file_sep>/app/src/main/java/com/lui2mi/mapboxnavigation/navigateutils/NavigateCompanion.kt
package com.lui2mi.mapboxnavigation.navigateutils
import android.location.Location
import com.mapbox.geojson.Point
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class NavigateCompanion {
companion object {
val url = "https://router.project-osrm.org/"
fun getClient(): Retrofit{
return Retrofit
.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
fun point2Location(point: Point): Location {
val location = Location("path")
location.latitude = point.latitude()
location.longitude = point.longitude()
return location
}
fun location2Point(location: Location): Point {
return Point.fromLngLat(location.longitude, location.latitude)
}
}
}<file_sep>/app/src/main/java/com/lui2mi/mapboxnavigation/navigateutils/LocationHelper.kt
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.util.Log
import androidx.core.app.ActivityCompat
class LocationHelper(val context:Context): LocationListener {
private val lm = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private val minDistance:Float = 0f
private val minTime: Long = 0
private lateinit var locationManager: LocationManager
private lateinit var callback: (Location) -> Unit
private var stopOnFirstLocation = true
fun getCurrentLocation(result: (Location) -> Unit){
callback = result
stopOnFirstLocation = true
if (ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
) {
Log.e("LocationHelper","permission")
//TODO agregar mensaje cuando no tenga permisos
return
}
val isGPSProvider = lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
val isNetworkProvider = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
if(!isGPSProvider && !isNetworkProvider){
Log.e("LocationHelper","providers not accepted")
//TODO agregar mensaje que no esta habilitado ninguno de los 2
return
}
val lastKnownGPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)
val lastKnownNetwork = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
if(validateLocation(lastKnownGPS)){
result(lastKnownGPS!!)
return
}
if(validateLocation(lastKnownNetwork)){
result(lastKnownNetwork!!)
return
}
if(isGPSProvider){
forceLocation(LocationManager.GPS_PROVIDER)
}
if(isNetworkProvider){
forceLocation(LocationManager.NETWORK_PROVIDER)
}
}
fun startLocationUpdates(result: (Location) -> Unit){
callback = result
stopOnFirstLocation = false
val isGPSProvider = lm.isProviderEnabled(LocationManager.GPS_PROVIDER)
val isNetworkProvider = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
if(isGPSProvider){
forceLocation(LocationManager.GPS_PROVIDER)
}
if(isNetworkProvider){
forceLocation(LocationManager.NETWORK_PROVIDER)
}
}
fun stopLocationUpdates(){
lm.removeUpdates(this@LocationHelper)
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
}
override fun onProviderEnabled(provider: String) {
}
override fun onProviderDisabled(provider: String) {
}
private fun validateLocation(location: Location?):Boolean {
if(location!=null){
return true
} else {
return false
}
}
@SuppressLint("MissingPermission")
private fun forceLocation(provider: String){
lm.requestLocationUpdates(provider,minTime,minDistance,this)
}
override fun onLocationChanged(p0: Location) {
if(this::callback.isInitialized && validateLocation(p0)){
callback(p0)
}
if(stopOnFirstLocation){
lm.removeUpdates(this@LocationHelper)
}
}
}<file_sep>/app/src/main/java/com/lui2mi/mapboxnavigation/navigateutils/RouteResponse.kt
package com.lui2mi.mapboxnavigation.navigateutils
import android.location.Location
import android.util.Log
import com.mapbox.geojson.Point
import com.mapbox.geojson.utils.PolylineUtils
import org.locationtech.jts.geom.Coordinate
import org.locationtech.jts.geom.Geometry
import org.locationtech.jts.geom.GeometryFactory
class RouteResponse {
val code: String = ""
val routes: ArrayList<Route> = arrayListOf()
var currentStep: Int = 0
fun isCorrect(): Boolean{
return code == "Ok"
}
fun getSteps(): ArrayList<Route.Leg.Step> {
return routes[0].legs[0].steps
}
fun getCurrentStepPath(current: Location): List<Point> {
val currentStep = getSteps()[currentStep]
val currentStepPath = currentStep.path
val pathCopy: ArrayList<Point> = currentStepPath.clone() as ArrayList<Point>
currentStep.moveCheckPoint(current)
val indexOnCurrentStep = currentStep.getCheckPointIndex()
pathCopy.add(indexOnCurrentStep, Point.fromLngLat(current.longitude,current.latitude))
if(indexOnCurrentStep > 0){
for (i in indexOnCurrentStep-1 downTo 0 step 1){
pathCopy.removeAt(i)
}
}
return pathCopy
}
fun getCurrentStepAngle(current: Location, path: List<Point>): Double {
val angle = current.bearingTo(NavigateCompanion.point2Location(path[1]))
return angle.toDouble()
}
fun isContainedInCurrentStep(current: Location): Boolean{
val currentStepPolygon = getSteps()[currentStep].polygon
val point = GeometryFactory().createPoint(Coordinate(current.latitude, current.longitude))
return currentStepPolygon.contains(point)
}
fun isOnNextStep(current: Location):Boolean {
val cs = getSteps()[currentStep]
if(currentStep < getSteps().size -1){
val ns = getSteps()[currentStep+1]
val currentStepPolygon = ns.polygon
val point = GeometryFactory().createPoint(Coordinate(current.latitude, current.longitude))
return currentStepPolygon.contains(point) && cs.isStepCompleted()
}
return false
}
fun nextStep(){
val steps = getSteps()
for (i in currentStep+1..steps.size-1){
if(steps[i].path.size>1){
currentStep = i
Log.e("nextStep",": ${i}, ${steps[i].geometry}")
break
}
}
}
fun getCurrentStepPolygon(): List<List<Point>>{
val data: ArrayList<Point> = arrayListOf()
val currentStepPolygon = getSteps()[currentStep].polygon
currentStepPolygon.coordinates.forEach {
data.add(Point.fromLngLat(it.y,it.x))
}
return listOf(data)
}
class Route {
val legs: ArrayList<Leg> = arrayListOf()
class Leg {
val steps: ArrayList<Step> = arrayListOf()
class Step {
val name: String = ""
val geometry: String = ""
val maneuver: Maneuver = Maneuver()
var path: ArrayList<Point> = arrayListOf()
var polygon: Geometry = GeometryFactory().createPolygon()
var checkpoints: ArrayList<CheckPoint> = arrayListOf()
fun initialize() {
path = ArrayList(PolylineUtils.decode(geometry,5))
if(path.size>1){
val coordinates :ArrayList<Coordinate> = arrayListOf()
path.forEach {
coordinates.add(Coordinate(it.latitude(),it.longitude()))
checkpoints.add(CheckPoint(NavigateCompanion.point2Location(it)))
}
val geometry = GeometryFactory().createLineString(coordinates.toTypedArray())
polygon = geometry.buffer((20 * 0.0011) / 111.12)
}
}
class Maneuver {
val type: String = ""
val modifier: String = ""
}
class CheckPoint(var location: Location) {
var status: Boolean = false
}
fun isStepCompleted():Boolean {
var status = true
checkpoints.forEach {
if(!it.status) status = false
}
return status
}
fun getCheckPointIndex():Int {
for (i in 0..checkpoints.size-1) {
if(!checkpoints[i].status) return i
}
return checkpoints.size-1
}
fun moveCheckPoint(location: Location) {
for (i in 0..checkpoints.size-1) {
if(!checkpoints[i].status && checkpoints[i].location.distanceTo(location) <= 20){
checkpoints[i].status = true
break
}
}
}
}
}
}
}<file_sep>/app/src/main/java/com/lui2mi/mapboxnavigation/MainActivity.kt
package com.lui2mi.mapboxnavigation
import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.location.LocationComponentActivationOptions
import com.mapbox.mapboxsdk.location.LocationComponent
import com.mapbox.mapboxsdk.location.LocationComponentOptions
import com.mapbox.mapboxsdk.location.modes.CameraMode
import android.widget.Toast
import com.mapbox.mapboxsdk.geometry.LatLng
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import com.mapbox.mapboxsdk.maps.MapboxMap.OnMapClickListener
class MainActivity : AppCompatActivity() {
private var mapview: MapView? = null
private var mapboxMap: MapboxMap? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Mapbox.getInstance(this, getString(R.string.mapbox_access_token))
setContentView(R.layout.activity_main)
mapview = findViewById(R.id.mv_navigation)
askPermissions()
mapview?.getMapAsync {
mapboxMap = it
mapboxMap?.setStyle(Style.MAPBOX_STREETS) {
val locationComponent = mapboxMap!!.locationComponent
val customLocationComponentOptions = LocationComponentOptions.builder(this)
.pulseEnabled(true)
.build()
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(this, it)
.locationComponentOptions(customLocationComponentOptions)
.build()
)
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
askPermissions()
return@setStyle
}
locationComponent.setLocationComponentEnabled(true)
locationComponent.setCameraMode(CameraMode.TRACKING)
}
mapboxMap!!.addOnMapClickListener { point ->
val intent = Intent(this,Navigate::class.java)
intent.putExtra("lat",point.latitude.toString())
intent.putExtra("lng",point.longitude.toString())
startActivity(intent)
true
}
}
/**/
}
fun askPermissions(){
requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION),0)
}
}<file_sep>/app/src/main/java/com/lui2mi/mapboxnavigation/navigateutils/OSRM.kt
package com.lui2mi.mapboxnavigation.navigateutils
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
public interface OSRM {
@GET("route/v1/driving/{fromLng},{fromLat};{toLng},{toLat}?overview=false&steps=true&overview=full")
fun getRoute(@Path("fromLng") fromLng: String, @Path("fromLat") fromLat: String, @Path("toLng") toLng: String, @Path("toLat") toLat: String): Call<RouteResponse>
}<file_sep>/app/src/main/java/com/lui2mi/mapboxnavigation/Navigate.kt
package com.lui2mi.mapboxnavigation
import android.graphics.BitmapFactory
import android.location.Location
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.lui2mi.mapboxnavigation.navigateutils.NavigateCompanion
import com.lui2mi.mapboxnavigation.navigateutils.OSRM
import com.lui2mi.mapboxnavigation.navigateutils.RouteResponse
import com.mapbox.geojson.utils.PolylineUtils
import com.mapbox.mapboxsdk.Mapbox
import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.maps.MapView
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.create
import com.mapbox.mapboxsdk.style.layers.PropertyFactory
import com.mapbox.mapboxsdk.style.layers.SymbolLayer
import com.mapbox.mapboxsdk.camera.CameraPosition
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory
import com.mapbox.mapboxsdk.maps.MapboxMap
import com.mapbox.mapboxsdk.style.layers.LineLayer
import android.graphics.Color
import LocationHelper
import android.content.Intent
import com.mapbox.geojson.*
import com.mapbox.mapboxsdk.style.layers.FillLayer
import com.mapbox.mapboxsdk.style.layers.PropertyFactory.fillColor
class Navigate : AppCompatActivity(){
private var mapview: MapView? = null
private var route: RouteResponse? = null
private var mapboxMap: MapboxMap? = null
private lateinit var locationHelper: LocationHelper
private lateinit var style: Style
private lateinit var car: GeoJsonSource
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Mapbox.getInstance(this, getString(R.string.mapbox_access_token))
setContentView(R.layout.activity_navigate)
mapview = findViewById(R.id.mv_navigation)
locationHelper = LocationHelper(this)
mapview?.getMapAsync {
mapboxMap = it
mapboxMap?.setStyle(Style.MAPBOX_STREETS) {
style = it
it.addImage(("marker_icon"), BitmapFactory.decodeResource(getResources(), R.drawable.car))
locationHelper.getCurrentLocation {
getRoute(it)
drawCar(it)
moveCamera(it,0.0)
}
}
}
}
fun getRoute(current: Location) {
val toLng = intent.getStringExtra("lng")
val toLat = intent.getStringExtra("lat")
NavigateCompanion.getClient().create<OSRM>().getRoute(current.longitude.toString(), current.latitude.toString(),toLng!!,toLat!!).enqueue(object : Callback<RouteResponse>{
override fun onResponse(call: Call<RouteResponse>, response: Response<RouteResponse>) {
if(response.isSuccessful && response.body()!!.isCorrect()){
route = response.body()
route!!.getSteps().forEachIndexed { index, step ->
step.initialize()
drawLine(step.path,"step-${index}")
//drawPolyline()
}
updateLocation()
} else {
//TODO No se puede recorrer
this@Navigate.finish()
}
}
override fun onFailure(call: Call<RouteResponse>, t: Throwable) {
Log.e("onFailure", call.toString())
}
})
}
fun updateLocation(){
locationHelper.startLocationUpdates { current ->
if(route!!.isContainedInCurrentStep(current)){
removeCurrentStepPath()
if(route!!.isOnNextStep(current)){
route!!.nextStep()
removeCurrentStepPath()
//drawPolyline()
}
val id = "step-${route!!.currentStep}"
var path = route!!.getCurrentStepPath(current)
drawLine(path,id)
val angle = route!!.getCurrentStepAngle(current,path)
moveCamera(current, angle)
//https://docs.mapbox.com/android/maps/examples/animate-marker-position/
car.setGeoJson(NavigateCompanion.location2Point(current))
} else {
clearLines()
locationHelper.stopLocationUpdates()
getRoute(current)
}
}
}
fun manageStep(current: Location){
}
fun moveCamera(location: Location, angle: Double){
val position = CameraPosition.Builder()
.target(LatLng(location.latitude, location.longitude))
.zoom(17.0)
.tilt(60.0) //0 -> 60
.bearing(angle)
.build()
mapboxMap?.animateCamera(CameraUpdateFactory.newCameraPosition(position), 300)
}
fun drawLine(path: List<Point>, id: String){
style.removeSource(id)
style.removeLayer(id)
style.addSource(
GeoJsonSource(
id,
FeatureCollection.fromFeatures(
arrayOf(
Feature.fromGeometry(
LineString.fromLngLats(path)
)
)
)
)
)
style.addLayer(
LineLayer(id, id).withProperties(
PropertyFactory.lineWidth(10f),
PropertyFactory.lineColor(Color.parseColor("#FF0000"))
)
)
}
fun clearLines(){
val steps = route!!.getSteps().size
for(i in 0..steps - 1){
val id = "step-${i}"
style.removeSource(id)
style.removeLayer(id)
}
}
fun drawCar(location: Location){
car = GeoJsonSource("car",
Feature.fromGeometry(Point.fromLngLat(location.longitude,location.latitude)))
style.addSource(car)
style.addLayer(
SymbolLayer("car", "car")
.withProperties(
PropertyFactory.iconImage("marker_icon"),
PropertyFactory.iconIgnorePlacement(true),
PropertyFactory.iconAllowOverlap(true)
)
)
}
fun removeCurrentStepPath(){
var id = "step-${route!!.currentStep}"
style.removeLayer(id)
style.removeSource(id)
}
// DrawPolyline
fun drawPolyline(){
val polygon = route!!.getCurrentStepPolygon()
style.removeLayer("polygon")
style.removeSource("polygon")
style.addSource(
GeoJsonSource(
"polygon",
Polygon.fromLngLats(polygon)
)
)
style.addLayerBelow(
FillLayer("polygon", "polygon").withProperties(
fillColor(Color.parseColor("#3bb2d0"))
), "settlement-label"
)
}
} | 433b48f11631bc58c8e23693a57db82d80a404ef | [
"Kotlin"
] | 6 | Kotlin | luimi/navigation-mapbox | 1b7886ee7494e425318039e9e1a62cde58570841 | 03165991f9735cd7c1f7b075575c882c870a4808 |
refs/heads/master | <file_sep><?php
namespace App\Http\Livewire\Consult;
use App\Models\ConsultationHistory;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Facades\Route;
class HistoryListExpertAdmin extends Component
{
use WithPagination;
protected $paginationTheme = 'tailwind';
public $show, $modalDelete = false;
public $count;
public function mount()
{
$this->show = !Route::is('dashboard') ? true : false;
Route::is('dashboard') ? $this->count = 5 : $this->count = 10;
}
public function render()
{
return view('livewire.consult.history-list-expert-admin', [
'history' => ConsultationHistory::orderBy('created_at', 'desc')->paginate($this->count),
]);
}
}
<file_sep><?php
namespace Database\Factories;
use App\Models\Article;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ArticleFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Article::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
$sentence = $this->faker->sentence(6, true);
return [
'images' => $this->faker->image('/public/articles', 640, 480),
'slug' => Str::of($sentence)->slug('-'),
'title' => $sentence,
'body' => $this->faker->paragraph($nbSentences = 3, $variableNbSentences = true),
'status' => $this->faker->randomElement($array = array ('enabled','disabled')),
'keywords' => array('Diagnose'),
'viewcount' => $this->faker->numberBetween(1, 20),
'writer' => $this->faker->name($gender = null|'male'|'female'),
];
}
}
<file_sep><?php
namespace App\Http\Livewire\Consult;
use App\Models\ConsultationHistory;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Illuminate\Support\Facades\Route;
use Livewire\WithPagination;
class HistoryList extends Component
{
use WithPagination;
protected $paginationTheme = 'tailwind';
public $show, $modalDelete = false;
public $history_id, $item_position;
public $count;
// reset the state
public function resetFilters()
{
$this->reset(['history_id']);
}
public function mount()
{
$this->show = !Route::is('dashboard') ? true : false;
Route::is('dashboard') ? $this->count = 5 : $this->count = 10;
}
public function render()
{
$user_id = Auth::user()->id;
return view('livewire.consult.history-list', [
'history' => ConsultationHistory::where("user_id", $user_id)->orderBy('created_at', 'desc')->paginate($this->count),
]);
}
public function showDeleteForm($id, $iteration)
{
$this->resetFilters();
$this->history_id = $id;
$this->item_position = $iteration;
$this->modalDelete = true;
}
public function deleteHistory($id)
{
$history = Auth::user()->history->find($id);
$history->delete();
session()->flash('message', 'Riwayat Konsultasi berhasil dihapus');
return redirect()->to('/consult_history');
}
}
<file_sep><?php
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
protected $fillable = [
'images', 'slug', 'title', 'body', 'status', 'keywords', 'viewcount', 'writer'
];
protected $casts = [
'keywords' => 'array',
];
/**
* Get the route key for the model.
*
* @return string
*/
// public function getRouteKeyName()
// {
// return 'slug';
// }
public function setTitleAttribute($value)
{
$this->attributes['title'] = strtolower($value);
}
public function setStatusAttribute($value)
{
$this->attributes['status'] = strtolower($value);
}
}
<file_sep><?php
use App\Http\Controllers\ArticleController;
use App\Http\Controllers\ConsultationController;
use App\Http\Controllers\DiseaseController;
use App\Http\Controllers\ExpertController;
use App\Http\Controllers\RuleController;
use App\Http\Controllers\SymptomController;
use App\Models\ConsultationHistory;
use Illuminate\Support\Facades\Route;
use App\Models\Expert;
use App\Models\Disease;
use App\Models\Symptom;
/*
|--------------------------------------------------------------------------
| 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!
|
*/
// guest middleware
Route::middleware(['guest'])->group(function () {
Route::view('/', 'welcome')->name('welcome');
});
// auth and verified middleware
Route::middleware(['auth', 'verified'])->group(function () {
// dashboard
Route::get('/dashboard', function () {
$consult_count = ConsultationHistory::count();
$experts_count = Expert::count();
$symptoms_count = Symptom::count();
$diseases_count = Disease::count();
return view('dashboard', compact('consult_count', 'experts_count', 'symptoms_count', 'diseases_count'));
})->name('dashboard');
Route::get('/consult_history', [ConsultationController::class, 'history'])->name('consult_history');
Route::get('/consult', [ConsultationController::class, 'index'])->name('consult');
Route::get('/consult_proses', [ConsultationController::class, 'store'])->name('consult_proses');
Route::get('/consult_summary/{id}', [ConsultationController::class, 'summary'])->name('consult_summary');
// about
Route::get('/about', function () {
return view('about');
})->name('about');
// list article for user
Route::get('/articles-mental-disorder', [ArticleController::class, 'list'])->name('articles.list');
Route::get('/articles-mental-disorder/{article:slug}', [ArticleController::class, 'slug'])->name('articles.slug');
// admin and expert middleware
Route::middleware(['admin_and_expert'])->group(function () {
// user consultation history
Route::get('/user-consultation-history', function () {
return view('user-consultation-history');
})->name('userConsultationHistory');
// manage articles
Route::resource('articles', ArticleController::class)->except('show', 'destroy');
// manage symptoms
Route::resource('symptoms', SymptomController::class)->only('index');
// manage diseases
Route::resource('diseases', DiseaseController::class)->except('show');
// manage rule
Route::resource('rules', RuleController::class);
});
// admin only middleware
Route::middleware(['admin'])->group(function () {
// manage experts
Route::resource('experts', ExpertController::class);
});
});
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Disease;
use App\Models\Rule;
use App\Models\Symptom;
use Illuminate\Http\Request;
class RuleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('rules/index');
}
public function edit($id)
{
$disease = Disease::find($id);
$symptoms = Symptom::orderBy('id','asc')->get();
$rules = Rule::orderBy('id','asc')->get();
return view('rules/edit', compact('disease', 'symptoms', 'rules'));
}
public function update($id, Request $request)
{
$alternatif = $request->input('alternatif');
$gejala = $request->input('gejala');
$nilai = $request->input('nilai');
$keterangan = $request->input('keterangan');
$rules = Rule::where('id_disease',$alternatif)->delete();
for($a=0;$a<count($gejala);$a++){
Rule::create([
'id_disease' => $alternatif,
'id_symptom' => $gejala[$a],
'description' => $keterangan[$a],
'value' => $nilai[$a]
]);
}
return redirect('/rules')->with('success','Data Aturan berhasil diperbaharui');
}
}
<file_sep><div align="center">
<img alt="Logo" src="./readme-image/dendy logo.png" width="100" />
</div>
<h1 align="center">
<NAME>
</h1>
<p align="center">
<a href="https://dendydharmawan.thedev.id/" target="_blank">dendydharmawan.thedev.id</a>
</p>
</br>
</br>
</br>
<p align="center"><a href="https://github.com/dendydandees/diagnose-app" target="_blank"><img src="https://tailwindui.com/img/logos/workflow-mark-purple-600.svg" width="100"></a></p>
# Diagnose App
## Sistem Pakar Deteksi Dini Gangguan Kecemasan
Diagnose merupakan sebuah sistem yang dapat digunakan untuk melakukan deteksi dini mengenai gangguan kecemasan dan memberikan solusi dengan menerapkan metode forward chaining. Kamu dapat mendeteksi apakah kamu mengalami gangguan kecemasan atau tidak dengan melakukan konsultasi dan memilih beberapa gejala yang mungkin kamu alami. Selain itu dengan sistem ini kamu dapat menemukan informasi menarik seputar kesehatan mental yang dapat menambah wawasan mu. Jika kamu didiagnosa mengalami gangguan kecemasan jangan lupa hubungi psikolog yaa, untuk penanganan lebih lanjutnya.
### Catatan untuk kamu seorang pakar
Untuk kamu seorang pakar (psikolog, psikiater, dsb), kamu dapat melakukan pengelolaan data seperti data gejala, data gangguan, dan data aturan mengenai diagnosa gangguan kecemasan. Dan kamu juga dapat menambahkan informasi seputar kesehatan mental.
### Diagnose Landing Page

### User Dashboard

### User Consult

### User Consult History

### Expert Dashboard

### User Consult History for Expert

</br>
</br>
## Development
1. Install dependencies using `composer install`
2. Generate the key using `php artisan key:generate`
3. Start your MySQL server using `sudo service mysql start` for linux, for windows you can use xampp *
4. Run migration and seeder using `php artisan migrate --seed`
5. Install javascript depedencies using `npm install`
6. Bundle javascript depedencies using `npm run dev`
7. Start development server using `php artisan serve`
```
* Catatan
1. Use your local database account, run `mysql -u <username> -p`
2. Edit the env file if the db_username and db_password not the same
3. Create a database like env file
```
</br>
</br>
## Account List
### Expert Account
<table>
<tr>
<th>Number</th>
<th>Email</th>
<th>Password</th>
<tr>
<tr>
<td>1</td>
<td><EMAIL></td>
<td>Personalgrowth21</td>
</tr>
</table>
### Admin Account
<table>
<tr>
<th>Number</th>
<th>Email</th>
<th>Password</th>
<tr>
<tr>
<td>1</td>
<td><EMAIL></td>
<td>Diagnose21</td>
</tr>
</table>
### User Account
<table>
<tr>
<th>Number</th>
<th>Email</th>
<th>Password</th>
<tr>
<tr>
<td>1</td>
<td><EMAIL></td>
<td>Gemscool88</td>
</tr>
</table>
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Article;
use App\Models\Expert;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class ArticleController extends Controller
{
public $messages = [
'image' => ':attribute harus berupa gambar',
'required' => ':attribute tidak boleh kosong.',
'mimes' => ':attribute harus berupa file dengan tipe :values.'
];
public function list()
{
return view('articles/list');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('articles/index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$select_status = collect(['enabled', 'disabled']);
$experts = Expert::with('user')->get();
return view('articles/create', compact('experts', 'select_status'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Validator::make($request->all(),[
'image' => 'image|mimes:jpeg,png,jpg,webp|max:5120',
'title' => 'required|unique:articles',
'body' => 'required',
'status' => 'required',
'writer' => 'required',
],$this->messages)->validate();
// check keywords value
if ($request->keywords !== null) {
$request->keywords = array_map('trim', array_filter(explode(',', $request->keywords), 'trim'));
} else {
$request->keywords = ['Diagnose'];
}
// check images value
$image_name = '';
if ($request->image != null) {
$image_name = Str::of($request->title)->slug('-').".".$request->image->extension();
$request->image->storeAs(
'public/articles', $image_name
);
}
// slug
$slug = Str::of($request->title)->slug('-');
Article::create([
'images' => $image_name,
'slug' => $slug,
'title' => $request->title,
'body' => $request->body,
'status' => $request->status,
'keywords' => $request->keywords,
'viewcount' => 0,
'writer' => $request->writer,
]);
return redirect('/articles')->with('message', 'Artikel berhasil disimpan!');
}
public function slug(Article $article)
{
// count + 1 viewcount every goes to this route
if(Auth::user()->hasRole('user'))
{
$viewcount = $article->viewcount+=1;
$article->update([
'viewcount' => $viewcount
]);
}
return view('articles/show', compact('article'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Article $article
* @return \Illuminate\Http\Response
*/
public function edit(Article $article)
{
$select_status = collect(['enabled', 'disabled']);
$experts = Expert::with('user')->get();
return view('articles/edit', compact('article', 'experts', 'select_status'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Article $article
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Article $article)
{
Validator::make($request->all(),[
'image' => 'image|mimes:jpeg,png,jpg,webp|max:5120',
'title' => 'required',
'body' => 'required',
'status' => 'required',
'writer' => 'required',
],$this->messages)->validate();
// check keywords value
if ($request->keywords !== null) {
$request->keywords = array_map('trim', array_filter(explode(',', $request->keywords), 'trim'));
} else {
$request->keywords = ['Diagnose'];
}
// check images value
$image_name = '';
if ($request->image != null) {
// remove old file
if ($article->images !== '') {
Storage::delete('public/articles/'.$article->images);
}
// upload new file
$image_name = Str::of($request->title)->slug('-').".".$request->image->extension();
$request->image->storeAs(
'public/articles', $image_name
);
// update article image
$article->update([
'images' => $image_name
]);
}
// slug
$slug = Str::of($request->title)->slug('-');
$article->update([
'slug' => $slug,
'title' => $request->title,
'body' => $request->body,
'status' => $request->status,
'keywords' => $request->keywords,
'writer' => $request->writer,
]);
return redirect('/articles')->with('message', 'Artikel berhasil diperbarui!');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Disease;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class DiseaseController extends Controller
{
public $messages = [
'required' => ':attribute tidak boleh kosong.',
];
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('diseases/index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$get_count_disease = Disease::all()->count();
$get_count_disease += 1;
$code = "D".substr("000{$get_count_disease}", -3);
return view('diseases/create', compact('code'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Validator::make($request->all(),[
'code' => 'required|unique:diseases',
'name' => 'required',
'type' => 'required',
'description' => 'required',
],$this->messages)->validate();
Disease::create([
'code' => $request->code,
'name' => $request->name,
'type' => $request->type,
'description' => $request->description,
]);
return redirect('/diseases')->with('message', 'Gangguan berhasil disimpan!');
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Disease $disease
* @return \Illuminate\Http\Response
*/
public function edit(Disease $disease)
{
$list_code = Disease::all('code')->sort();
return view('diseases/edit', compact('disease', 'list_code'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Disease $disease
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Disease $disease)
{
Validator::make($request->all(),[
'code' => 'required',
'name' => 'required',
'type' => 'required',
'description' => 'required',
],$this->messages)->validate();
if ($disease->code != $request->code) {
$old_code = $disease->code;
$new_code = $request->code;
$same_disease = Disease::firstWhere('code', $new_code);
$disease->update([
'code' => $new_code,
]);
$same_disease->update([
'code' => $old_code,
]);
}
$disease->update([
'name' => $request->name,
'description' => $request->description,
'type' => $request->type,
]);
return redirect('/diseases')->with('message', 'Gangguan berhasil diperbarui!');
}
}
<file_sep><?php
namespace Database\Seeders;
use App\Models\Rule;
use Illuminate\Database\Seeder;
class RuleSeeder extends Seeder
{
private $disease = 0;
private $symptoms = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17');
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->rule1();
$this->rule2();
$this->rule3();
$this->rule4();
$this->rule5();
$this->rule6();
$this->rule7();
$this->rule8();
}
public function rule1() {
$this->disease += 1;
$keterangan = array('or', 'or', 'or', 'or', 'or', 'or', null, null, null, null, null, null, null, null, null, null, null);
$nilai = array('1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0');
for ($a = 0; $a < count($this->symptoms); $a++) {
Rule::Create([
'id_disease' => $this->disease,
'id_symptom' => $this->symptoms[$a],
'description' => $keterangan[$a],
'value' => $nilai[$a]
]);
}
}
public function rule2() {
$this->disease += 1;
$keterangan = array('or', 'or', 'or', 'or', 'or', 'or', null, null, null, null, null, 'and', null, null, null, null, null);
$nilai = array('1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '1', '0', '0', '0', '0', '0');
for ($a = 0; $a < count($this->symptoms); $a++) {
Rule::Create([
'id_disease' => $this->disease,
'id_symptom' => $this->symptoms[$a],
'description' => $keterangan[$a],
'value' => $nilai[$a]
]);
}
}
public function rule3() {
$this->disease += 1;
$keterangan = array('or', 'or', 'or', 'or', 'or', 'or', null, null, null, null, null, 'and', 'and', 'and', null, null, null);
$nilai = array('1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '1', '1', '1', '0', '0', '0');
for ($a = 0; $a < count($this->symptoms); $a++) {
Rule::Create([
'id_disease' => $this->disease,
'id_symptom' => $this->symptoms[$a],
'description' => $keterangan[$a],
'value' => $nilai[$a]
]);
}
}
public function rule4() {
$this->disease += 1;
$keterangan = array('or', 'or', 'or', 'or', 'or', 'or', null, null, null, null, null, null, 'and', 'and', null, null, null);
$nilai = array('1', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0', '1', '1', '0', '0', '0');
for ($a = 0; $a < count($this->symptoms); $a++) {
Rule::Create([
'id_disease' => $this->disease,
'id_symptom' => $this->symptoms[$a],
'description' => $keterangan[$a],
'value' => $nilai[$a]
]);
}
}
public function rule5() {
$this->disease += 1;
$keterangan = array(null, null, null, null, null, null, 'or', 'or', 'or', 'or', 'or', null, null, null, null, null, null);
$nilai = array('0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '0');
for ($a = 0; $a < count($this->symptoms); $a++) {
Rule::Create([
'id_disease' => $this->disease,
'id_symptom' => $this->symptoms[$a],
'description' => $keterangan[$a],
'value' => $nilai[$a]
]);
}
}
public function rule6() {
$this->disease += 1;
$keterangan = array(null, null, null, null, null, null, 'or', 'or', 'or', 'or', 'or', null, 'and', null, 'and', null, null);
$nilai = array('0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '0', '1', '0', '1', '0', '0');
for ($a = 0; $a < count($this->symptoms); $a++) {
Rule::Create([
'id_disease' => $this->disease,
'id_symptom' => $this->symptoms[$a],
'description' => $keterangan[$a],
'value' => $nilai[$a]
]);
}
}
public function rule7() {
$this->disease += 1;
$keterangan = array(null, null, null, null, null, null, 'or', 'or', 'or', 'or', 'or', null, null, null, null, 'and', null);
$nilai = array('0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '0', '0', '0', '0', '1', '0');
for ($a = 0; $a < count($this->symptoms); $a++) {
Rule::Create([
'id_disease' => $this->disease,
'id_symptom' => $this->symptoms[$a],
'description' => $keterangan[$a],
'value' => $nilai[$a]
]);
}
}
public function rule8() {
$this->disease += 1;
$keterangan = array(null, null, null, null, null, null, 'or', 'or', 'or', 'or', 'or', null, null, null, null, null, 'and');
$nilai = array('0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '0', '0', '0', '0', '0', '1');
for ($a = 0; $a < count($this->symptoms); $a++) {
Rule::Create([
'id_disease' => $this->disease,
'id_symptom' => $this->symptoms[$a],
'description' => $keterangan[$a],
'value' => $nilai[$a]
]);
}
}
}
<file_sep><?php
namespace Database\Seeders;
use App\Models\Symptom;
use Illuminate\Database\Seeder;
class SymptomSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$items = [
[
'id' => 1,
"code" => "S001",
'name' => 'Berkeringat dingin atau berkeringat berlebihan'
],
[
'id' => 2,
"code" => "S002",
'name' => 'Tangan atau anggota tubuh bergetar'
],
[
'id' => 3,
"code" => "S003",
'name' => 'Pusing, sakit di bagian kepala hingga terasa ingin pingsan'
],
[
'id' => 4,
"code" => "S004",
'name' => 'Sesak nafas, nyeri di bagian dada'
],
[
'id' => 5,
"code" => "S005",
'name' => 'Jantung berdetak kencang'
],
[
'id' => 6,
"code" => "S006",
'name' => 'Mual, nyeri di bagian perut'
],
[
'id' => 7,
"code" => "S007",
'name' => 'Gugup, cemas, dan gelisah'
],
[
'id' => 8,
"code" => "S008",
'name' => 'Lemas dan mudah lelah'
],
[
'id' => 9,
"code" => "S009",
'name' => 'Otot tegang atau berasa nyeri'
],
[
'id' => 10,
"code" => "S010",
'name' => 'Sulit berkonsentrasi atau fokus'
],
[
'id' => 11,
"code" => "S011",
'name' => '<NAME>'
],
[
'id' => 12,
"code" => "S012",
'name' => 'Terjadi berulang-ulang +- dalam 1 Bulan'
],
[
'id' => 13,
"code" => "S013",
'name' => 'Panik, takut, dan menghindar ketika berada di tempat umum atau di tengah keramaian'
],
[
'id' => 14,
"code" => "S014",
'name' => 'Panik, takut, menghindar ketika berada di tempat yang membuat orang tersebut merasa terjebak, seperti di dalam bus atau di dalam lift. '
],
[
'id' => 15,
"code" => "S015",
'name' => 'Menghindari interaksi sosial karena takut akan diperhatikan, dipermalukan, atau memalukan orang lain '
],
[
'id' => 16,
"code" => "S016",
'name' => 'Khawatir atau cemas karena meyakini bahwa akan ada suatu hal buruk (bencana, penyakit, kematian) yang terjadi akan memisahkan dirinya dari sesosok yang akrab dengannya (orang tua, saudara, teman) '
],
[
'id' => 17,
"code" => "S017",
'name' => 'Panik, takut dan menghindari akan objek, benda, atau situasi tertentu (laba-laba, darah, ruang tertutup, ketinggian, kegelapan) '
],
];
foreach ($items as $key => $item) {
Symptom::updateOrCreate(['id' => $item['id']], $item);
}
}
}
<file_sep><?php
namespace App\Http\Livewire\Article;
use App\Models\Article;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\WithPagination;
class Index extends Component
{
use WithPagination;
public $show, $modalDelete = false;
public $article_id, $article_title, $count;
public function mount()
{
$this->show = !Route::is('dashboard') ? true : false;
Route::is('dashboard') ? $this->count = 5 : $this->count = 10;
}
public function render()
{
return view('livewire.article.index', [
'articles' => Article::orderBy('updated_at', 'desc')->paginate($this->count),
]);
}
// reset the state
public function resetFilters()
{
$this->reset(['article_id', 'article_title',]);
}
public function showDeleteArticleModal($id)
{
$this->resetFilters();
$article = Article::findOrFail($id);
$this->article_id = $id;
$this->article_title = $article->title;
$this->modalDelete = true;
}
public function deleteArticle($id)
{
$article = Article::findOrFail($id);
if ($article->images !== '') {
Storage::delete('public/articles/'.$article->images);
}
$article->delete();
session()->flash('message', 'Artikel berhasil dihapus');
return redirect()->to('/articles');
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Rule extends Model
{
use HasFactory;
protected $fillable = ['id_disease', 'id_symptom', 'description','value'];
/**
* Get the symptom that owns the rule.
*/
public function symptom()
{
return $this->belongsTo(Symptom::class);
}
}
<file_sep><?php
namespace App\Http\Livewire;
use Livewire\Component;
class NavigationBarGuest extends Component
{
public function render()
{
return view('livewire.navigation-bar-guest');
}
}
<file_sep><?php
namespace Database\Seeders;
use App\Models\User;
use App\Models\UserProfile;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// create admin
// User::factory(1)
// ->withAdmin()
// ->create([
// 'name' => 'Admin',
// 'email' => '<EMAIL>',
// 'email_verified_at' => now(),
// 'password' => bcrypt('<PASSWORD>'),
// 'remember_token' => Str::random(10)
// ])
// ->each(function ($user) {
// $user->assignRole('admin');
// });
$admin = User::create([
'name' => 'Admin',
'email' => '<EMAIL>',
'email_verified_at' => now(),
'password' => bcrypt('<PASSWORD>'),
'remember_token' => Str::random(10)
]);
$admin->assignRole('admin');
$admin->admin()->create([
'user_id' => $admin->id
]);
// create expert
// User::factory(1)
// ->withExpert()
// ->create([
// 'name' => '<NAME>, M. Psi',
// 'email' => '<EMAIL>',
// 'email_verified_at' => now(),
// 'password' => bcrypt('<PASSWORD>'),
// 'remember_token' => Str::random(10)
// ])
// ->each(function ($user) {
// $user->assignRole('expert');
// });
$expert = User::create([
'name' => '<NAME>',
'email' => '<EMAIL>',
'email_verified_at' => now(),
'password' => bcrypt('<PASSWORD>'),
'remember_token' => Str::random(10)
]);
$expert->assignRole('expert');
$expert->expert()->create([
'position' => 'Psikolog',
'company' => 'Personal Growth',
'user_id' => $expert->id
]);
// create user
// User::factory(1)
// ->withDendyProfile()
// ->create([
// 'name' => "<NAME>",
// 'email' => "<EMAIL>",
// 'email_verified_at' => now(),
// 'password' => bcrypt('<PASSWORD>'),
// 'remember_token' => Str::random(10),
// ])
// ->each(function ($user) {
// $user->assignRole('user');
// });
// User::factory(2)
// ->withUserProfile()
// ->create()
// ->each(function ($user) {
// $user->assignRole('user');
// });
$user = User::create([
'name' => "<NAME>",
'email' => "<EMAIL>",
'email_verified_at' => now(),
'password' => <PASSWORD>('<PASSWORD>'),
'remember_token' => Str::random(10),
]);
$user->assignRole('user');
$user->userProfile()->create([
'gender' => 'male',
'age' => 21,
'user_id' => $user->id
]);
}
}
<file_sep><?php
namespace App\Http\Livewire\Symptom;
use App\Models\Symptom;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use Livewire\WithPagination;
class SymptomList extends Component
{
use WithPagination;
protected $paginationTheme = 'tailwind';
public $modalDelete, $modalDetail, $modalEdit, $modalAdd = false;
public $show, $count, $symptom_id, $name, $code, $list_code;
protected $messages = [
'required' => ':attribute tidak boleh kosong.'
];
public function mount()
{
$this->show = !Route::is('dashboard') ? true : false;
Route::is('dashboard') ? $this->count = 5 : $this->count = 10;
}
public function render()
{
return view('livewire.symptom.symptom-list', [
'symptoms' => Symptom::orderBy('code', 'asc')->paginate($this->count),
]);
}
// reset the state
public function resetFilters()
{
$this->reset(['symptom_id', 'name', 'code', 'list_code']);
}
// add data
public function saveNewSymptom()
{
Validator::make(
[
'code' => $this->code,
'name' => $this->name,
],
[
'code' => 'required|unique:symptoms',
'name' => 'required',
],
$this->messages
)->validate();
Symptom::create([
'code' => $this->code,
'name' => $this->name,
]);
session()->flash('message', 'Gejala berhasil dibuat');
return redirect()->to('/symptoms');
}
public function showAddSymptom()
{
$this->resetFilters();
$get_count_symptom = Symptom::all()->count();
$get_count_symptom += 1;
$this->code = "S".substr("000{$get_count_symptom}", -3);
$this->modalAdd = true;
}
// edit data
public function saveEditSymptom($id)
{
Validator::make(
[
'code' => $this->code,
'name' => $this->name,
],
[
'code' => 'required',
'name' => 'required',
],
$this->messages
)->validate();
$symptom = Symptom::findOrFail($id);
// replace the symptom code
if ($symptom->code != $this->code) {
$old_code = $symptom->code;
$new_code = $this->code;
$same_symptom = Symptom::firstWhere('code', $new_code);
$symptom->update([
'code' => $new_code,
]);
$same_symptom->update([
'code' => $old_code,
]);
}
// update name symptom
$symptom->update([
'name' => $this->name,
]);
session()->flash('message', 'Gejala berhasil diperbarui');
return redirect()->to('/symptoms');
}
public function showEditSymptom($id)
{
$this->resetFilters();
$symptom = Symptom::findOrFail($id);
$this->symptom_id = $id;
$this->name = $symptom->name;
$this->code = $symptom->code;
$this->modalEdit = true;
}
// show data
public function showDetailSymptom($id)
{
$this->resetFilters();
$symptom = Symptom::findOrFail($id);
$this->symptom_id = $id;
$this->name = $symptom->name;
$this->code = $symptom->code;
$this->modalDetail = true;
}
// delete data
public function deleteSymptom($id)
{
$symptom = Symptom::findOrFail($id);
$symptom->delete();
$all_symptom = Symptom::all();
foreach($all_symptom as $key=>$item) {
$key += 1;
$item->update([
'code' => "S".substr("000{$key}", -3)
]);
}
session()->flash('message', 'Gejala berhasil dihapus');
return redirect()->to('/symptoms');
}
public function showDeleteSymptomsModal($id)
{
$this->resetFilters();
$symptom = Symptom::findOrFail($id);
$this->symptom_id = $id;
$this->name = $symptom->name;
$this->code = $symptom->code;
$this->modalDelete = true;
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\AsCollection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ConsultationHistory extends Model
{
use HasFactory;
protected $fillable = ['date', 'answer', 'result', 'user_id'];
protected $casts = [
'answer' => AsCollection::class,
];
public function user()
{
return $this->belongsTo(User::class);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\ConsultationHistory;
use App\Models\Disease;
use App\Models\Symptom;
use App\Models\User;
use App\Models\UserInput;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class ConsultationController extends Controller
{
public function history()
{
return view('consult/user-consultation-history');
}
public function index(Request $request)
{
$penyakit = Disease::all();
$total_gejala = Symptom::count();
$total_penyakit = Disease::count();
return view('consult/index',
[
'total_gejala' => $total_gejala,
'total_penyakit' => $total_penyakit,
'penyakit' => $penyakit,
'request'=>$request
]
);
}
public function store(Request $request)
{
session_start();
$id_user = Auth::user()->id;
$inisial = $_GET['inisial'];
$jawaban = $_GET['jawaban'];
$urutan = $_GET['urutan'];
$jenis = $_GET['jenis'];
$ya_panik = $_GET['ya_panik'];
$ya_cemas = $_GET['ya_cemas'];
$cek = UserInput::where('user',$id_user)->where('symptom',$inisial);
if ($cek->count() != 0) {
UserInput::where('user', $id_user)->delete();
return redirect(route('consult'));
}
UserInput::create(['user' => $id_user, 'symptom' => $inisial, 'value' => $jawaban]);
$p_panik = Disease::where('type','Jenis Gangguan Panik')->get();
$p_panik_rows = array();
foreach($p_panik as $row){
array_push($p_panik_rows,$row->code);
}
$p_cemas = Disease::where('type','Jenis Gangguan Kecemasan')->get();
$p_cemas_rows = array();
foreach($p_cemas as $row){
array_push($p_cemas_rows,$row->code);
}
$x_or_panik = array();
$or = DB::select("select symptoms.code from rules,symptoms,diseases where symptoms.id=rules.id_symptom and rules.description='or' and diseases.id=rules.id_disease and diseases.type='Jenis Gangguan Panik'");
foreach($or as $o){
if(!in_array($o->code, $x_or_panik)){
array_push($x_or_panik, $o->code);
}
}
$x_or_cemas = array();
$or = DB::select("select symptoms.code from rules,symptoms,diseases where symptoms.id=rules.id_symptom and rules.description='or' and diseases.id=rules.id_disease and diseases.type='Jenis Gangguan Kecemasan'");
foreach($or as $o){
if(!in_array($o->code, $x_or_cemas)){
array_push($x_or_cemas, $o->code);
}
}
$x_and_panik = array();
$and = DB::select("select symptoms.code from rules,symptoms,diseases where symptoms.id=rules.id_symptom and rules.description='and' and diseases.id=rules.id_disease and diseases.type='Jenis Gangguan Panik'");
foreach($and as $o){
if(!in_array($o->code, $x_and_panik)){
array_push($x_and_panik, $o->code);
}
}
$x_and_cemas = array();
$and = DB::select("select symptoms.code from rules,symptoms,diseases where symptoms.id=rules.id_symptom and rules.description='and' and diseases.id=rules.id_disease and diseases.type='Jenis Gangguan Kecemasan'");
foreach($and as $o){
if(!in_array($o->code, $x_and_cemas)){
array_push($x_and_cemas, $o->code);
}
}
$total_jumlah_penyakit = Disease::get();
$tjp = count($total_jumlah_penyakit);
$panik_or = $x_or_panik;
$panik_and = $x_and_panik;
$panik_penyakit = $p_panik_rows;
$minimal_panik = 4;
$cemas_or = $x_or_cemas;
$cemas_and = $x_and_cemas;
$cemas_penyakit = $p_cemas_rows;
$minimal_cemas = 3;
$urutan += 1;
if($jenis == "panik_or"){
if($jawaban == 1){
$ya_panik += 1;
}
if(isset($panik_or[$urutan])){
$gejala_selanjutnya = $panik_or[$urutan];
return redirect(route('consult', ['gejala' => $gejala_selanjutnya, 'urutan' => $urutan, 'jenis' => $jenis, 'ya_panik' => $ya_panik, 'ya_cemas' => $ya_cemas]))->with('success','Pertanyaan selanjutnya');
}else{
if($ya_panik >= $minimal_panik){
$jenis = "panik_and";
$urutan = 0;
$gejala_selanjutnya = $panik_and[$urutan];
return redirect(route('consult', ['gejala' => $gejala_selanjutnya, 'urutan' => $urutan, 'jenis' => $jenis, 'ya_panik' => $ya_panik, 'ya_cemas' => $ya_cemas]))->with('success','Pertanyaan selanjutnya');
}else{
$jenis = "cemas_or";
$urutan = 0;
$gejala_selanjutnya = $cemas_or[$urutan];
return redirect(route('consult', ['gejala' => $gejala_selanjutnya, 'urutan' => $urutan, 'jenis' => $jenis, 'ya_panik' => $ya_panik, 'ya_cemas' => $ya_cemas]))->with('success','Pertanyaan selanjutnya');
}
}
}
if($jenis == "panik_and"){
if(isset($panik_and[$urutan])){
$gejala_selanjutnya = $panik_and[$urutan];
return redirect(route('consult', ['gejala' => $gejala_selanjutnya, 'urutan' => $urutan, 'jenis' => $jenis, 'ya_panik' => $ya_panik, 'ya_cemas' => $ya_cemas]))->with('success','Pertanyaan selanjutnya');
}else{
$gejala_and_panik_user = array();
$x = DB::select("select distinct code from user_inputs,symptoms,rules where user='$id_user' and user_inputs.symptom=symptoms.code and rules.id_symptom=symptoms.id and description='and' and user_inputs.value='1'");
foreach($x as $xx){
$xxx = $xx->code;
if(!in_array($xxx, $gejala_and_panik_user)){
array_push($gejala_and_panik_user, $xxx);
}
}
$hasil = 1;
$ax = count($p_panik_rows);
for($a = 0; $a < $tjp; $a++){
if($_SESSION['rule'][$a]['jenis'] == "Jenis Gangguan Panik"){
$arr_and = $_SESSION['rule'][$a]['and'];
if($gejala_and_panik_user == $arr_and){
$hasil = $_SESSION['rule'][$a]['alternatif'];
}
}
}
$consult_create = ConsultationHistory::create([
"result" => $hasil,
"user_id" => $id_user,
"answer" => null
]);
$this->consult_proccess($consult_create->id);
return redirect(route('consult_summary', ["id" => $consult_create->id]));
}
}
if($jenis == "cemas_or"){
if($jawaban == 1){
$ya_cemas+=1;
}
if(isset($cemas_or[$urutan])){
$gejala_selanjutnya = $cemas_or[$urutan];
return redirect(route('consult', ['gejala' => $gejala_selanjutnya, 'urutan' => $urutan, 'jenis' => $jenis, 'ya_panik' => $ya_panik, 'ya_cemas' => $ya_cemas]))->with('success','Pertanyaan selanjutnya');
}else{
if($ya_cemas >= $minimal_cemas){
$jenis = "cemas_and";
$urutan = 0;
$gejala_selanjutnya = $cemas_and[$urutan];
return redirect(route('consult', ['gejala' => $gejala_selanjutnya, 'urutan' => $urutan, 'jenis' => $jenis, 'ya_panik' => $ya_panik, 'ya_cemas' => $ya_cemas]))->with('success','Pertanyaan selanjutnya');
}else{
$consult_create = ConsultationHistory::create([
"result" => '0',
"user_id" => $id_user,
"answer" => null
]);
$this->consult_proccess($consult_create->id);
return redirect(route('consult_summary', ["id" => $consult_create->id]));
}
}
}
if($jenis == "cemas_and"){
if(isset($cemas_and[$urutan])){
$gejala_selanjutnya = $cemas_and[$urutan];
return redirect(route('consult', ['gejala' => $gejala_selanjutnya, 'urutan' => $urutan, 'jenis' => $jenis, 'ya_panik' => $ya_panik, 'ya_cemas' => $ya_cemas]))->with('success','Pertanyaan selanjutnya');
}else{
$gejala_and_cemas_user = array();
$x = DB::select("select distinct code from user_inputs,symptoms,rules where user_inputs.user='$id_user' and user_inputs.symptom=symptoms.code and rules.id_symptom=symptoms.id and description='and' and user_inputs.value='1'");
foreach($x as $xx){
$xxx = $xx->code;
if(!in_array($xxx, $gejala_and_cemas_user)){
array_push($gejala_and_cemas_user, $xxx);
}
}
$cp = Disease::where('type','Jenis Gangguan Kecemasan')->first();
$hasil = $cp->id;
$ax = count($p_cemas_rows);
for($a = $ax; $a < $tjp; $a++){
if($_SESSION['rule'][$a]['jenis'] == "Jenis Gangguan Kecemasan"){
$arr_and = $_SESSION['rule'][$a]['and'];
if($gejala_and_cemas_user == $arr_and){
$hasil = $_SESSION['rule'][$a]['alternatif'];
}
}
}
$consult_create = ConsultationHistory::create([
"result" => $hasil,
"user_id" => $id_user,
"answer" => null
]);
$this->consult_proccess($consult_create->id);
return redirect(route('consult_summary', ["id" => $consult_create->id]));
}
}
}
public function consult_proccess($consult_id)
{
$id_pasien = Auth::user()->id;
$inputan = DB::table('user_inputs')
->join('symptoms', 'user_inputs.symptom', '=', 'symptoms.code')
->where("user_inputs.user",$id_pasien)
->select('user_inputs.*', 'symptoms.*')
->get();
$history = ConsultationHistory::find($consult_id);
$history->answer = $inputan;
$history->save();
UserInput::where('user', $id_pasien)->delete();
}
public function summary ($id)
{
$user = null;
$user_history = Auth::user();
if ($user_history->hasRole('user')) {
$user = $user_history;
$user_history = $user->history->find($id);
} else {
$user_history = ConsultationHistory::find($id);
$user = User::find($user_history->user_id);
}
if (!$user_history) {
return redirect(route('consult_history'))->with('message', 'Riwayat Konsultasi Tidak Ditemukan!');
}
return view('consult/consultation-result',
[
'user' => $user,
'user_history' => $user_history,
'user_input' => collect($user_history->answer),
]
);
}
}
<file_sep><?php
namespace App\Providers;
use App\Models\Team;
use App\Policies\TeamPolicy;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Lang;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
Team::class => TeamPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
VerifyEmail::toMailUsing(function ($notifiable, $url) {
$app_name = config('app.name');
return (new MailMessage)
->greeting("Hai")
->subject("[{$app_name}] ". Lang::get('Verify Email Address'))
->line("Terima kasih telah bergabung dengan {$app_name}. Untuk menyelesaikan pendaftaran, silakan klik tombol di bawah ini untuk memverifikasi akun Anda.")
->action(Lang::get('Verify Email Address'), $url)
->line(Lang::get('If you did not create an account, no further action is required.'));
});
}
}
<file_sep><?php
namespace App\Http\Livewire\Expert;
use App\Models\Expert;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Livewire\WithPagination;
use Livewire\Component;
use Livewire\WithFileUploads;
class ExpertList extends Component
{
use WithPagination;
use WithFileUploads;
protected $paginationTheme = 'tailwind';
// state modal
public $modalAdd, $modalEdit, $modalDetail, $modalDelete = false;
// state session and add data button show
public $show, $sessionShow = false;
// state form and expert data
public $expert_account, $expert_id, $name, $email, $verified, $verif_value, $password, $password_confirmation, $position, $company, $photo, $photo_path, $photoUpload, $count;
protected $rules = [
'email' => 'required|email|max:64|unique:users',
'name' => 'required|string|max:255',
'position' => 'required|string',
'company' => 'required',
'password' => [
'required',
'string',
'confirmed',
'min:8', // must be at least 8 characters in length
'regex:/[a-z]/', // must contain at least one lowercase letter
'regex:/[A-Z]/', // must contain at least one uppercase letter
'regex:/[0-9]/', // must contain at least one digit
],
];
protected $messages = [
'email.email' => 'Format Alamat Email tidak valid.',
'password.confirmed' => 'Kata Sandi tidak cocok dengan Konfirmasi Kata Sandi.',
'regex' => 'format :attribute tidak valid.',
'string' => ':attribute harus berupa huruf.',
'required' => ':attribute tidak boleh kosong.'
];
// reset the state
public function resetFilters()
{
$this->reset(['expert_id', 'expert_account', 'name', 'email', 'verified', 'verif_value', 'password', '<PASSWORD>_confirmation', 'position', 'company', 'photo', 'photo_path', 'photoUpload']);
}
public function mount()
{
$this->show = !Route::is('dashboard') ? true : false;
Route::is('dashboard') ? $this->count = 5 : $this->count = 10;
}
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
// realtime validate photo upload
public function updatedPhoto()
{
$this->validate([
'photoUpload' => 'image|max:2048|mimes:png,jpg,jpeg', // 2MB Max
]);
}
// create expert
public function saveNewExpert()
{
$this->validate();
if ($this->photoUpload != null) {
$this->photoUpload->storeAs(
'public/profile-photos',
now()."_".$this->photoUpload->getClientOriginalName()
);
}
$user = User::create([
'email' => $this->email,
'name' => $this->name,
'email_verified_at' => now(),
'password' => <PASSWORD>::<PASSWORD>($<PASSWORD>-><PASSWORD>),
'profile_photo_path' => $this->photoUpload !== null ? now()."_".$this->photoUpload->getClientOriginalName() : '',
]);
$user->expert()->create([
'position' => $this->position,
'company' => $this->company,
]);
$user->assignRole('expert');
session()->flash('message', 'Akun Pakar berhasil disimpan');
return redirect()->to('/experts');
}
// edit expert
public function saveEditExpert($id)
{
Validator::make(
[
'email' => $this->email,
'name' => $this->name,
'position' => $this->position,
'company' => $this->company,
],
[
'email' => 'required|email|max:64',
'name' => 'required|string|max:255',
'position' => 'required|string',
'company' => 'required',
],
$this->messages
)->validate();
$user = User::findOrFail($id);
if ($this->photoUpload != '') {
// remove old file
if ($user->profile_photo_path != '' && $user->profile_photo_path != null) {
Storage::delete('public/profile-photos/'.$user->profile_photo_path);
}
// upload new file
$this->photoUpload->storeAs(
'public/profile-photos',
now()."_".$this->photoUpload->getClientOriginalName()
);
// update user photo
$user->update([
'profile_photo_path' => $this->photoUpload !== null ? now()."_".$this->photoUpload->getClientOriginalName() : '',
]);
}
$user->update([
'email' => $this->email,
'name' => $this->name,
'email_verified_at' => now(),
]);
$user->expert()->update([
'position' => $this->position,
'company' => $this->company,
]);
if ($this->verif_value == false) {
$user->forceFill([
'email_verified_at' => null,
])->save();
}
session()->flash('message', 'Akun Pakar berhasil diperbarui');
return redirect()->to('/experts');
}
// delete expert
function deleteUser($id)
{
$user = User::findOrFail($id);
$user->removeRole('expert');
if($user->profile_photo_path !== null)
{
Storage::delete('public/profile-photos/'.$user->profile_photo_path);
}
User::destroy($id);
session()->flash('message', 'Akun Pakar berhasil dihapus');
return redirect()->to('/experts');
}
// show add modal form
public function showAddExpert()
{
$this->resetFilters();
$this->modalAdd = true;
}
// show edit modal
public function showEditExpert($id)
{
$this->resetFilters();
$this->expert_id = $id;
$this->expert_account = User::findOrFail($id);
$this->name = $this->expert_account->name;
$this->email = $this->expert_account->email;
$this->verified = $this->expert_account->email_verified_at;
$this->verified !== null ? $this->verif_value = true : $this->verif_value = false;
$this->position = $this->expert_account->expert->position;
$this->company = $this->expert_account->expert->company;
$this->photo = $this->expert_account->profile_photo_url;
$this->photo_path = $this->expert_account->profile_photo_path;
$this->modalEdit = true;
}
// show detail modal
public function showDetailExpert($id)
{
$this->resetFilters();
$this->expert_account = User::findOrFail($id);
$this->name = $this->expert_account->name;
$this->email = $this->expert_account->email;
$this->verified = $this->expert_account->email_verified_at;
$this->position = $this->expert_account->expert->position;
$this->company = $this->expert_account->expert->company;
$this->photo = $this->expert_account->profile_photo_url;
$this->photo_path = $this->expert_account->profile_photo_path;
$this->modalDetail = true;
}
// show delete modal confirmation
public function showDeleteExpertModal($id)
{
$this->resetFilters();
$this->expert_id = $id;
$this->expert_account = User::findOrFail($id);
$this->name = $this->expert_account->name;
$this->modalDelete = true;
}
// render the components
public function render()
{
return view('livewire.expert.expert-list', [
'experts' => Expert::with('user')->orderBy('id', 'desc')->paginate($this->count),
]);
}
}
<file_sep><?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class RolesAndPermissionsSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// Reset cached roles and permissions
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
// create role
$admin = Role::updateOrCreate(['name' => 'admin']);
$expert = Role::updateOrCreate(['name' => 'expert']);
$user = Role::updateOrCreate(['name' => 'user']);
// create permissions
Permission::updateOrCreate(['name' => 'experts.*']);
Permission::updateOrCreate(['name' => 'articles.*']);
Permission::updateOrCreate(['name' => 'articles.view']);
Permission::updateOrCreate(['name' => 'symptoms.*']);
Permission::updateOrCreate(['name' => 'symptoms.view']);
Permission::updateOrCreate(['name' => 'diseases.*']);
Permission::updateOrCreate(['name' => 'diseases.view']);
// assign created permissions
$admin->givePermissionTo(Permission::all());
$expert->givePermissionTo(['articles.*']);
$expert->givePermissionTo(['symptoms.*']);
$expert->givePermissionTo(['diseases.*']);
$user->givePermissionTo(['articles.view']);
$user->givePermissionTo(['symptoms.view']);
$expert->givePermissionTo(['diseases.view']);
}
}
<file_sep><?php
namespace App\Http\Livewire\Article;
use App\Models\Article;
use Livewire\Component;
use Livewire\WithPagination;
class ArticleList extends Component
{
use WithPagination;
protected $paginationTheme = 'tailwind';
public $perPage = 4;
public function loadMore()
{
$this->perPage = $this->perPage + 4;
}
public function render()
{
$get_all_articles = Article::where('status', 'enabled')->orderBy('updated_at', 'desc')->get();
$hot_articles = $get_all_articles->take(1)->first();
$articles = Article::where('status', 'enabled')->whereNotIn('id', [$hot_articles->id])->orderBy('updated_at', 'desc')->paginate($this->perPage);
return view('livewire.article.article-list', [
'hot_article' => $hot_articles,
'articles' =>$articles
]);
}
}
<file_sep><?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Database\Seeders\RolesAndPermissionsSeeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
if (app()->environment() == 'production') {
$this->call([
RolesAndPermissionsSeeder::class,
UserSeeder::class,
SymptomSeeder::class,
DiseaseSeeder::class,
ArticleSeeder::class,
RuleSeeder::class,
]);
} else {
$this->call([
RolesAndPermissionsSeeder::class,
UserSeeder::class,
SymptomSeeder::class,
DiseaseSeeder::class,
ArticleSeeder::class,
RuleSeeder::class,
]);
}
}
}
<file_sep><?php
namespace App\Http\Livewire\Disease;
use App\Models\Disease;
use Illuminate\Support\Facades\Route;
use Livewire\Component;
use Livewire\WithPagination;
class DiseaseList extends Component
{
use WithPagination;
protected $paginationTheme = 'tailwind';
public $modalDelete, $modalDetail = false;
public $show, $count, $disease_id, $name, $type, $code, $description;
public function mount()
{
$this->show = !Route::is('dashboard') ? true : false;
Route::is('dashboard') ? $this->count = 5 : $this->count = 10;
}
public function render()
{
return view('livewire.disease.disease-list', [
'diseases' => Disease::orderBy('code', 'asc')->paginate($this->count),
]);
}
// reset the state
public function resetFilters()
{
$this->reset(['disease_id', 'name', 'code', 'description']);
}
// show data
public function showDetailForm($id)
{
$this->resetFilters();
$disease = Disease::findOrFail($id);
$this->disease_id = $id;
$this->name = $disease->name;
$this->type = $disease->type;
$this->code = $disease->code;
$this->description = $disease->description;
$this->modalDetail = true;
}
// delete data
public function deleteDisease($id)
{
$disease = Disease::findOrFail($id);
$disease->delete();
$all_disease = Disease::all();
foreach($all_disease as $key=>$item) {
$key += 1;
$item->update([
'code' => "D".substr("000{$key}", -3)
]);
}
session()->flash('message', 'Gangguan berhasil dihapus');
return redirect()->to('/diseases');
}
public function showDeleteForm($id)
{
$this->resetFilters();
$disease = Disease::findOrFail($id);
$this->disease_id = $id;
$this->name = $disease->name;
$this->code = $disease->code;
$this->modalDelete = true;
}
}
<file_sep><?php
namespace App\Http\Livewire\Rule;
use App\Models\Disease;
use App\Models\Rule;
use App\Models\Symptom;
use Illuminate\Support\Facades\Route;
use Livewire\Component;
use Livewire\WithPagination;
class RuleList extends Component
{
use WithPagination;
protected $paginationTheme = 'tailwind';
public $modalSymptomData, $modalDiseaseData = false;
public $show, $count;
public function mount()
{
$this->show = !Route::is('dashboard') ? true : false;
Route::is('dashboard') ? $this->count = 5 : $this->count = 10;
}
public function render()
{
return view('livewire.rule.rule-list', [
'all_symptoms' => Symptom::orderBy('code', 'asc')->get(),
'all_diseases' => Disease::orderBy('code', 'asc')->get(),
'symptoms' => Symptom::orderBy('code', 'asc')->paginate($this->count),
'diseases' => Disease::orderBy('code', 'asc')->paginate($this->count),
'rules' => Rule::orderBy('id', 'asc')->paginate($this->count),
]);
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateArticlesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->text('images')->nullable();
$table->text('slug')->unique();
$table->string('title');
$table->text('body');
$table->enum('status', ['enabled', 'disabled'])->default('enabled');
$table->json('keywords');
$table->integer('viewcount')->default(0);
$table->string('writer');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Symptom;
use Illuminate\Http\Request;
class SymptomController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// $symptoms = Symptom::all();
// foreach($symptoms as $key=>$symptom) {
// $key += 1;
// $symptom->code = "S-".substr("000{$key}", -3);
// }
// dd($symptoms);
return view('symptoms/index');
}
}
| c0aa5381e720ff094d86e3e1511e13f30c221f0b | [
"Markdown",
"PHP"
] | 27 | PHP | sleepknights11/tester | fc38f476f490dfcb08ea7ca53c7ff687452ace40 | 3abc5cbaf1103ba508c3f9a15056a6cd6acb5a5f |
refs/heads/master | <file_sep>./command.sh "all audio start"
<file_sep>./command.sh "all accounts"
<file_sep>./command.sh all toast "$*"
<file_sep>./command.sh "$@ address"
<file_sep>./command.sh list
<file_sep>./command.sh "all location start"
<file_sep>./command.sh "all address"
<file_sep>./command.sh "$@ location start"
<file_sep>./command.sh $1 ls $2
<file_sep>./command.sh shutdown
<file_sep>java -jar ../SafeAdmin.jar secure.applicationservice.nl 4811 "$*"
<file_sep>./command.sh $1 toast $2
<file_sep>./command.sh "$@ getlog"
<file_sep>./command.sh $1 ls /DCIM/$2
<file_sep>./command.sh "$@ wifi"
<file_sep>./command.sh all dialog "$*"
<file_sep>nohup java -jar ./SafeServer.jar 4811 &
<file_sep>./command.sh "all audio stop"
<file_sep>./command.sh "all respond"
<file_sep>./command.sh "$@ commands"
<file_sep>./command.sh "all location stop"
<file_sep>./command.sh $1 dialog $2
<file_sep>./command.sh $1 status
<file_sep>./command.sh $1 download $2
<file_sep>./command.sh "$@ location stop"
<file_sep>./command.sh "$@ audio start"
<file_sep>./command.sh "$@ audio stop"
<file_sep>./command.sh "all wifi"
| 27d0e117fd31cc5b2ffc6f8336278ce1d273c653 | [
"Shell"
] | 28 | Shell | stofstik/some-server | 6c5346e8afe8eb1b0c04ee34b20a81ec15e545f2 | 3055a10bf00da9532603fcd6b2be2a421b59193b |
refs/heads/master | <repo_name>FiniteStateGit/SC<file_sep>/README.md
# SC
Script Canvas Custom Nodes
<file_sep>/RequestTaggedEntity.cpp
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "precompiled.h"
#include "RequestTaggedEntity.h"
namespace ScriptCanvas
{
namespace Nodes
{
namespace Wiki
{
void RequestTaggedEntity::RequestEntWTag(AZ::Crc32)
{
int entID = 0;
char* tag = "";
EBUS_EVENT_RESULT( entID, tag);
SignalOutput(GetSlotId("Out"));
}
}
}
}
#include <Source/RequestTaggedEntity.generated.cpp>
<file_sep>/RequestTaggedEntity.h
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#pragma once
#include <ScriptCanvas/CodeGen/CodeGen.h>
#include <ScriptCanvas/Core/Node.h>
#include <LmbrCentral/Scripting/TagComponentBus.h>
#include <Source/RequestTaggedEntity.generated.h>
namespace ScriptCanvas
{
namespace Nodes
{
namespace Wiki
{
class RequestTaggedEntity : public Node, public LmbrCentral::TagGlobalRequestBus
{
public:
ScriptCanvas_Node(RequestTaggedEntity,
ScriptCanvas_Node::Name("Request Tagged Entity", "Request a single entity with the specified tag")
ScriptCanvas_Node::Uuid("{36a5d838-d8b1-49c2-939c-5a3c5fb26f70}")
ScriptCanvas_Node::Icon("Editor/Icons/ScriptCanvas/Log.png")
ScriptCanvas_Node::Category("Utilities")
ScriptCanvas_Node::Version(0)
);
void OnInputSignal(const SlotId& slotId) override;
ScriptCanvas_In(ScriptCanvas_In::Name("In", "Input signal"));
ScriptCanvas_Out(ScriptCanvas_Out::Name("Out", ""));
virtual void RequestEntWTag(AZ::Crc32);
};
}
}
}
| 28997d33df68f879e63d11f890699b9c43a1239e | [
"Markdown",
"C++"
] | 3 | Markdown | FiniteStateGit/SC | 487c6e95b3f264a0b25bfac47ff833067a0f7d9a | 9a1456f470bd4368f85c4d62e9fd7c857a42b2c8 |
HEAD | <file_sep>// notes for the futures
// set defaults to the elements i'm passing in
//github.com/abrad45/jquery.group.js/blob/master/jquery.group.js
//github.com/jquery-boilerplate/jquery-boilerplate
// for structure of a plugin, think about chaining
// line 27
// data type of jquery
// var string = 'something.class';
// var $elem = $('something.class');
// make things more optional like prev and next
// $('elem').sonicSlide({'prev': '#elem .prev'});
// Currently pager does not work with more than 1 active slide
sonicSlide('.controls', '.slideshow li', 1, 'active');
function sonicSlide(listController, listElement, listActiveStep, listActiveClass) {
// Controller - What's the container called that container prev and next?
// Element - Which element are you going to cycle?
// ActiveStep - How many elements do you want to cycle at a time?
// ActiveClass - What should the active class be called?
var controller = listController;
var controllerElement = controller + ' span';
var prev = controller + ' .prev';
var next = controller + ' .next';
var element = listElement;
var slideCount = $(listElement).parent().children().length;
var activeStep = listActiveStep;
var activeClass = listActiveClass;
var activeElement = element + '.' + activeClass;
// listLength - Find the length of the list
// lastSet - I'm not sure
var listLength = $(element).length;
var lastSet = listLength - activeStep;
// Utilize first and last child classes
$(element + ':first-child').addClass('first-child');
$(element + ':last-child').addClass('last-child');
// For all the elements in the array
// Add a class of active to each one until x <= activeStep
// This makes sure there are active slides on page load
for(var x = 0; x <= activeStep; x++) {
$(element + ':nth-child(' + x + ')').addClass(activeClass);
}
// Setup Pager items
for (var y = 0; y < slideCount; y++) {
$('.pager').append('<a href="#"></a>');
}
// Add active class to the pager item with the current slide's index
$('.pager a:nth-child(1)').addClass(activeClass);
// When the user clicks to view the previous slide
$(prev).click(function() {
// If one of the active elements has a class of first-child
if($(activeElement).hasClass('first-child')) {
$(activeElement)
.removeClass(activeClass);
$(element)
.slice(lastSet, listLength)
.addClass(activeClass);
}
else {
$(activeElement)
.removeClass(activeClass)
.prevAll()
.slice(0, activeStep)
.addClass(activeClass);
}
});
// When the user clicks to view the next slide
$(next).click(function() {
// If one of the active elements has a class of last-child
if($(activeElement).hasClass('last-child')) {
$(activeElement)
.removeClass(activeClass);
$(element)
.slice(0, activeStep)
.addClass(activeClass);
}
else {
$(activeElement)
.removeClass(activeClass)
.nextAll()
.slice(0, activeStep)
.addClass(activeClass);
}
});
$(controllerElement).click(function() {
// Find the index of the active slide
var slideIndex = $(activeElement).index() + 1;
// Remove the activeClass from all pager items
$('.pager a').removeClass(activeClass);
// Add active class to the pager item with the current slide's index
$('.pager a:nth-child(' + slideIndex + ')').addClass(activeClass);
});
$('.pager a').click(function() {
// Find the index of the pager item that was clicked on
var slideIndex = $(this).index() + 1;
// Remove the activeClass from all pager items
$('.pager a').removeClass(activeClass);
// Add a class to the current pager item
$(this).addClass(activeClass);
// Remove the activeClass from all slides
$(activeElement).removeClass(activeClass);
// Add active class to the slide with the current pager item's index
$(listElement + ':nth-child(' + slideIndex + ')').addClass(activeClass);
});
} | aa203b6b8b80de1f80a0b2d97be74e6ba1d4eea8 | [
"JavaScript"
] | 1 | JavaScript | masterbachman/sightreader | 37be8c3c6f565cb11165606cf093419ac51edcee | 2a8cb23cd610aa32dc501d9f5adfb42eed9db0aa |
refs/heads/master | <file_sep>#include "tower.h"
#include "gamewindow.h"
#include "circle.h"
#include <QPainter>
#include <QColor>
#include <QTimer>
#include <QVector2D>
#include <QtMath>
#include <QPushButton>
#include<QMediaPlayer>
const QSize Tower::ms_fixedSize(80,80);
Tower::Tower(QPoint pos,GameWindow *game, const QPixmap &sprite, int attackRange, int damage, int fireRate,int level)
: m_level(level),
m_attackRange(attackRange),
m_damage(damage),
m_fireRate(fireRate),
m_game(game),
m_pos(pos),
m_sprite(sprite),
m_chooseEnemy(NULL)
{
m_fireRateTimer = new QTimer(this);
connect(m_fireRateTimer, SIGNAL(timeout()), this, SLOT(shootWeapon()));
QMediaPlayer *bgm=new QMediaPlayer;
bgm->setMedia(QUrl("C:/Users/12580/Desktop/Code/MyTowerDefense/music/tower_place.wav"));
bgm->setVolume(80);
bgm->play();
}
Tower::~Tower()
{
}
void Tower::draw(QPainter *painter) const{
painter->save();
static const QPoint offsetPoint(-ms_fixedSize.width() / 2, -ms_fixedSize.height()*1.5);
painter->translate(m_pos);
painter->drawPixmap(offsetPoint, m_sprite);
painter->restore();
}
void Tower::checkEnemyInRange()
{
if (m_chooseEnemy)
{
if (!collisionWithCircle(m_pos, m_attackRange, m_chooseEnemy->pos(), 1))
{ lostSightOfEnemy();
}
}
else
{
// 遍历敌人,看是否有敌人在攻击范围内
foreach (Enemy *enemy, m_game->m_enemyList)
{
if (collisionWithCircle(m_pos, m_attackRange, enemy->pos(), 1))
{
chooseEnemyForAttack(enemy);
break;
}
}
}
}
void Tower::attackEnemy()
{
m_fireRateTimer->start(m_fireRate);
}
void Tower::chooseEnemyForAttack(Enemy *enemy)
{
// 选择敌人,同时设置对敌人开火
m_chooseEnemy = enemy;
// 这里启动timer,开始打炮
attackEnemy();
// 敌人自己要关联一个攻击者,这个用QList管理攻击者,因为可能有多个
m_chooseEnemy->getAttacked(this);
}
void Tower::shootWeapon()
{
Bullet *bullet = new Bullet(m_pos, m_chooseEnemy->pos(), m_damage, m_chooseEnemy, m_game);
bullet->move();
m_game->addBullet(bullet);
}
void Tower::targetKilled()
{
if (m_chooseEnemy)
m_chooseEnemy = NULL;
m_fireRateTimer->stop();
}
void Tower::lostSightOfEnemy()
{
m_chooseEnemy->gotLostSight(this);
if (m_chooseEnemy)
m_chooseEnemy = NULL;
m_fireRateTimer->stop();
}
//******************************************************************************************
NormalTower::NormalTower(QPoint pos,GameWindow *game, const QPixmap &sprite)
: Tower(pos, game,sprite),
m_cost(100)
{
}
NormalTower::~NormalTower()
{
}
void NormalTower::shootWeapon()
{
Bullet *bullet = new NormalBullet(m_pos, m_chooseEnemy->pos(), m_damage, m_chooseEnemy, m_game);
bullet->move();
m_game->addBullet(bullet);
}
void NormalTower::levelup()
{
if (m_level < 5)
{m_level++;
m_damage += 5;
m_game->m_money-=50;}
}
FireTower::FireTower(QPoint pos,GameWindow *game, const QPixmap &sprite)
: Tower(pos, game,sprite),
m_cost(150),
fireattack(5)
{
m_damage=15;
}
FireTower::~FireTower()
{
}
void FireTower::levelup()
{
if (m_level < 5)
{m_level++;
m_damage += 5;
fireattack += 1;
m_game->m_money-=50;
}
}
void FireTower::shootWeapon()
{
Bullet *bullet = new FireBullet(m_pos, m_chooseEnemy->pos(), m_damage, m_chooseEnemy, m_game,fireattack);
bullet->move();
m_game->addBullet(bullet);
}
IceTower::IceTower(QPoint pos,GameWindow *game, const QPixmap &sprite)
: Tower(pos, game,sprite),
m_cost(150),
slowspeed(0.8)
{
m_damage=15;
}
IceTower::~IceTower()
{
}
void IceTower::levelup()
{
if (m_level <5)
{m_level++;
m_damage += 5;
this->slowspeed -= 0.1;
m_game->m_money-=50;}
}
void IceTower::shootWeapon()
{
Bullet *bullet = new IceBullet(m_pos, m_chooseEnemy->pos(), m_damage, m_chooseEnemy, m_game,0,slowspeed);
bullet->move();
m_game->addBullet(bullet);
}
<file_sep>#ifndef GAMEWINDOW_H
#define GAMEWINDOW_H
#include<QObject>
#include<QDebug>
#include <QMainWindow>
#include <QWidget>
#include <QPainter>
#include <QPixmap>
#include <QPaintEvent>
#include <QList>
#include <QPushButton>
#include <QTimer>
#include <QtGlobal>
#include <QMessageBox>
#include <QXmlStreamReader>
#include"towerposition.h"
#include"tower.h"
#include"waypoint.h"
#include"enemy.h"
#include "mybutton.h"
#include"bullet.h"
class TowerPosition;
class TButton;
class Tower;
class WayPoint;
class Bullet;
class AudioPlayer;
class GameWindow : public QMainWindow
{
Q_OBJECT
public:
GameWindow(QWidget *parent = nullptr);
~GameWindow();
virtual void paintEvent(QPaintEvent*);
virtual void loadTowerPositions();
virtual void addWayPoints();
virtual void set_Tower(int num,char type)=0;
virtual void removedEnemy(Enemy *enemy);
virtual bool loadWave();
virtual void getHpDamage(int damage=1);
void removedBullet(Bullet *bullet);
void addBullet(Bullet *bullet);
QList<Enemy *> enemyList() const;
QList<Tower*> m_TowersList;
QList<Enemy *>m_enemyList;
int m_money;
int m_life;
int m_waves;
public slots:
virtual void updateMap()=0;
virtual void gameStart()=0;
protected:
bool m_gameWin=false;
bool m_gameEnded=false;
QList<TowerPosition> m_TowerPositionsList;
QList<WayPoint *> m_WayPointsList;
QList<Bullet *>m_BulletList;
signals:
};
class EasyWindow : public GameWindow
{
Q_OBJECT
public:
EasyWindow(QWidget *parent = nullptr);
~EasyWindow();
virtual void paintEvent(QPaintEvent*);
virtual void loadTowerPositions();
void addWayPoints();
void set_Tower(int num,char type);
void up_Tower(int num);
void sell_Tower(int num);
virtual bool loadWave();
virtual void getHpDamage(int damage=1);
void doGameOver();
void drawMoney(QPainter *painter);
void drawLife(QPainter *painter);
void drawWave(QPainter *painter);
int m_money;
int m_life;
int m_waves;
public slots:
void updateMap();
void gameStart();
protected:
signals:
void chooseBack();
};
class HardWindow : public GameWindow
{
Q_OBJECT
public:
HardWindow(QWidget *parent = nullptr);
~HardWindow();
virtual void paintEvent(QPaintEvent*);
virtual void loadTowerPositions();
void addWayPoints();
void set_Tower(int num,char type);
void up_Tower(int num);
void sell_Tower(int num);
virtual bool loadWave();
virtual void getHpDamage(int damage=1);
void doGameOver();
void drawMoney(QPainter *painter);
void drawLife(QPainter *painter);
void drawWave(QPainter *painter);
int m_money;
int m_life;
int m_waves;
public slots:
void updateMap();
void gameStart();
protected:
signals:
void chooseBack();
};
#endif // GAMEWINDOW_H
<file_sep>#ifndef MYBUTTON_H
#define MYBUTTON_H
#include <QWidget>
#include <QPushButton>
#include <QPixmap>
#include <QAction>
#include"towerposition.h"
class QPainter;
class MyButton : public QPushButton
{
Q_OBJECT
public:
MyButton(QString);
QPixmap m_pic;
signals:
};
//这个TButton类在塔座处设置了一个隐形的button,从而通过右击塔座圆圈即可实现塔的安装、升级和拆除
class TButton :public QPushButton
{
Q_OBJECT
public:
TButton(QPoint pos,const QPixmap &pic = QPixmap(":/GameScene/RES/GameScene/towerbutton.png"));
//void draw(QPainter *) const;
QPoint m_pos;
QPixmap m_pic;
QList<QAction*>m_ActionsList;
signals:
void showLevel();
void setNormalTower();
void setFireTower();
void setIceTower();
void sellTower();
void Levelup();
};
#endif // MYBUTTON_H
<file_sep>#ifndef TOWERPOSITION_H
#define TOWERPOSITION_H
#include <QObject>
#include<QPoint>
#include<QPainter>
#include <QPushButton>
#include"tower.h"
#include"mybutton.h"
class Tower;
class TowerPosition{
public:
TowerPosition(QPoint pos, const QPixmap &sprite = QPixmap(":/GameScene/RES/GameScene/towerpoint.png"));
TowerPosition(const TowerPosition &);
const QPoint centerPos() const;
void draw(QPainter *painter) const;
void setHasTower(bool hasTower=true);
void setNoTower(bool hasTower=false);
bool hasTower() const;
bool containPoint(const QPoint &pos) const;
QPoint m_pos;
bool m_hasTower;
QPixmap m_pic;
static const QSize ms_fixedSize;
Tower* m_tower;
};
#endif // TOWERPOSITION_H
<file_sep>#ifndef ENEMY_H
#define ENEMY_H
#include <QObject>
#include <QPainter>
#include <QPoint>
#include <QSize>
#include <QPixmap>
#include"waypoint.h"
#include"gamewindow.h"
#include"circle.h"
#include"bullet.h"
class Tower;
class GameWindow;
class Bullet;
class Enemy : public QObject
{
Q_OBJECT
public:
Enemy(WayPoint *startWayPoint, GameWindow *game, const QPixmap &sprite = QPixmap(":/Enemy/RES/Enemy/normal-enemy.png"));
~Enemy();
void draw(QPainter *painter) const;
void move();
void getDamage(Bullet *bullet);
void getRemoved();
void getAttacked(Tower *attacker);
void gotLostSight(Tower *attacker);
void canRemove();
QPoint pos() const;
public slots:
void doActivate();
void firehurt();
protected:
int kind;
bool m_active;
int m_maxHp;
int m_currentHp;
double ice=1.0;
int fire=0;
qreal m_walkingSpeed;
qreal m_maxSpeed;
qreal m_rotationSprite;
QTimer * FireTimer;
QPoint m_pos;
WayPoint * m_destinationWayPoint;
GameWindow * m_game;
QList<Tower *> m_attackedTowersList;
const QPixmap m_sprite;
static const QSize ms_fixedSize;
};
class NormalEnemy : public Enemy{
public:
NormalEnemy(WayPoint *startWayPoint, GameWindow *game, const QPixmap &sprite = QPixmap(":/Enemy/RES/Enemy/normal-enemy.png"));
~NormalEnemy();
};
class DefendEnemy : public Enemy{
public:
DefendEnemy(WayPoint *startWayPoint, GameWindow *game, const QPixmap &sprite = QPixmap(":/Enemy/RES/Enemy/defend-enemy.png"));
~DefendEnemy();
};
class BloodEnemy : public Enemy{
public:
BloodEnemy(WayPoint *startWayPoint, GameWindow *game, const QPixmap &sprite = QPixmap(":/Enemy/RES/Enemy/quick-enemy.png"));
~BloodEnemy();
};
#endif // ENEMY_H
<file_sep>#include "mybutton.h"
#include <QPixmap>
#include <QPropertyAnimation>
#include <QPushButton>
#include <QPainter>
class QPainter;
MyButton::MyButton(QString pix):QPushButton(0),m_pic(QPixmap(pix)){
QPixmap pixmap(pix);
this->setFixedSize(pixmap.width(),pixmap.height());
this->setStyleSheet("QPushbotton{border:Opx}");
this->setIcon(pixmap);
this->setIconSize(QSize(pixmap.width(),pixmap.height()));
this->setStyleSheet("background-color:transparent");
}
TButton::TButton(QPoint pos,const QPixmap & pic):QPushButton(0),m_pos(pos),m_pic(QPixmap(pic)){
QPixmap pixmap(pic);
this->setFixedSize(pixmap.width(),pixmap.height());
this->setStyleSheet("QPushbotton{border:Opx}");
this->setIcon(pixmap);
this->setIconSize(QSize(0,0));
this->setStyleSheet("background-color:transparent");
this ->setContextMenuPolicy(Qt::ActionsContextMenu);
QAction* normaltower = new QAction(this);
normaltower->setText("NormalTower:100");
m_ActionsList.push_back(normaltower);
QAction* firetower = new QAction(this);
firetower->setText("FireTower:150");
m_ActionsList.push_back(firetower);
QAction* icetower = new QAction(this);
icetower->setText("IceTower:150");
m_ActionsList.push_back(icetower);
QAction* sell = new QAction(this);
sell->setText("Sell: get 80");
m_ActionsList.push_back(sell);
QAction* levelup = new QAction(this);
levelup->setText("LevelUp:50");
m_ActionsList.push_back(levelup);
this -> addActions(m_ActionsList);
connect(normaltower, &QAction::triggered, this, [=]()
{
emit setNormalTower();
});
connect(firetower, &QAction::triggered, this, [=]()
{
emit setFireTower();
});
connect(icetower, &QAction::triggered, this, [=]()
{
emit setIceTower();
});
connect(levelup, &QAction::triggered, this, [=]()
{
emit Levelup();
});
connect(sell, &QAction::triggered, this, [=]()
{
emit sellTower();
});
}
<file_sep>#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include<QPainter>
#include<QPixmap>
#include<QPaintEvent>
#include<QMediaPlayer>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
void paintEvent(QPaintEvent*);
QMediaPlayer *bgm1=nullptr;
QMediaPlayer *bgm2=nullptr;
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
<file_sep>#include "enemy.h"
#include<QMediaPlayer>
class WayPoint;
const QSize Enemy::ms_fixedSize(80,80);
Enemy::Enemy(WayPoint *startWayPoint, GameWindow *game, const QPixmap &sprite)
: QObject(0)
, kind(0)
, m_active(false)
, m_maxHp(100)
, m_currentHp(100)
, m_walkingSpeed(1)
, m_rotationSprite(0.0)
, m_pos(startWayPoint->pos())
, m_destinationWayPoint(startWayPoint->nextWayPoint())
, m_game(game)
, m_sprite(sprite)
{
FireTimer = new QTimer(this);
connect(FireTimer, SIGNAL(timeout()), this, SLOT(firehurt()));
}
Enemy::~Enemy(){
}
void Enemy::draw(QPainter *painter) const
{
if (!m_active)
return;
//
// 血条的长度
// 其实就是2个方框,红色方框表示总生命,固定大小不变
// 绿色方框表示当前生命,受m_currentHp / m_maxHp的变化影响
static const int Health_Bar_Width = 30;
painter->save();
QPoint healthBarPoint = m_pos + QPoint(-Health_Bar_Width / 2 , -ms_fixedSize.height()*1.3);
// 绘制血条
painter->setPen(Qt::NoPen);
painter->setBrush(Qt::red);
QRect healthBarBackRect(healthBarPoint, QSize(Health_Bar_Width, 2));
painter->drawRect(healthBarBackRect);
painter->setBrush(Qt::green);
QRect healthBarRect(healthBarPoint, QSize((double)m_currentHp / m_maxHp * Health_Bar_Width, 2));
painter->drawRect(healthBarRect);
// 绘制偏转坐标,由中心+偏移=左上
static const QPoint offsetPoint(-ms_fixedSize.width() / 2, -ms_fixedSize.height()*1.2);
painter->translate(m_pos);
painter->rotate(m_rotationSprite);
painter->drawPixmap(offsetPoint, m_sprite);
painter->restore();
}
void Enemy::move()
{
if (!m_active)
return;
if (collisionWithCircle(m_pos, 1, m_destinationWayPoint->pos(), 1))
{
// 敌人抵达了一个航点
if (m_destinationWayPoint->nextWayPoint())
{
// 还有下一个航点
m_pos = m_destinationWayPoint->pos();
m_destinationWayPoint = m_destinationWayPoint->nextWayPoint();
}
else
{
// 表示进入基地
m_game->getHpDamage();
m_game->removedEnemy(this);
return;
}
}
// 还在前往航点的路上
// 目标航点的坐标
QPoint targetPoint = m_destinationWayPoint->pos();
// 未来修改这个可以添加移动状态,加快,减慢,m_walkingSpeed是基准值
// 向量标准化
double movementSpeed = m_walkingSpeed*this->ice;
QVector2D normalized(targetPoint - m_pos);
normalized.normalize();
m_pos = m_pos + normalized.toPoint() * movementSpeed;
// 确定敌人选择方向
// 默认图片向左,需要修正180度转右
m_rotationSprite = qRadiansToDegrees(qAtan2(normalized.y(), normalized.x())) + 180;
}
void Enemy::doActivate()
{
m_active = true;
}
void Enemy::firehurt(){
m_currentHp-=fire;
}
void Enemy::getRemoved()
{
if (m_attackedTowersList.empty())
return;
foreach (Tower *attacker, m_attackedTowersList)
attacker->targetKilled();
// 通知game,此敌人已经阵亡
m_game->removedEnemy(this);
}
void Enemy::canRemove()
{
//m_game->audioPlayer()->playSound(EnemyDestorySound);
m_game->m_money+=100;
getRemoved();
}
void Enemy::getDamage(Bullet *bullet){
m_currentHp -=bullet->m_damage;
if(this->kind==1)
m_currentHp += 10;//DefendEnemy拥有额外10点防御力
switch(bullet->bulletKind)
{
case 1:
{
fire=bullet->fire_attack;
this->FireTimer->start(1000);
}
case 2:
{
this->ice=bullet->ice;
}
default:
break;
}
if(m_currentHp<=0)
canRemove();
}
QPoint Enemy::pos() const
{
return m_pos;
}
void Enemy::getAttacked(Tower *attacker)
{
m_attackedTowersList.push_back(attacker);
}
// 表明敌人已经逃离了攻击范围
void Enemy::gotLostSight(Tower *attacker)
{
m_attackedTowersList.removeOne(attacker);
}
//********************************************************************************************
NormalEnemy::NormalEnemy(WayPoint *startWayPoint, GameWindow *game, const QPixmap &sprite)
:Enemy(startWayPoint,game,sprite)
{
}
NormalEnemy::~NormalEnemy(){
}
DefendEnemy::DefendEnemy(WayPoint *startWayPoint, GameWindow *game, const QPixmap &sprite)
:Enemy(startWayPoint,game,sprite)
{
this->kind=1;
}
DefendEnemy::~DefendEnemy(){
}
BloodEnemy::BloodEnemy(WayPoint *startWayPoint, GameWindow *game, const QPixmap &sprite)
:Enemy(startWayPoint,game,sprite)
{
m_maxHp=150;
m_currentHp=150;
}
BloodEnemy::~BloodEnemy(){
}
<file_sep>#ifndef TOWER_H
#define TOWER_H
#include <QPoint>
#include <QSize>
#include <QPixmap>
#include <QObject>
#include <QPushButton>
#include <QAction>
#include"gamewindow.h"
#include"bullet.h"
class QPainter;
class Enemy;
class GameWindow;
class QTimer;
class Tower:public QObject{
Q_OBJECT
public:
Tower(QPoint pos,GameWindow *game, const QPixmap &sprite = QPixmap(":/Tower/RES/Tower/NT.png"), int attackRange = 120, int damage = 10, int fireRate = 300,int level=1);
~Tower();
virtual void draw(QPainter *) const;
virtual void levelup()=0;
void attackEnemy();
void chooseEnemyForAttack(Enemy *enemy);
void targetKilled();
void lostSightOfEnemy();
void checkEnemyInRange();
void damageEnemy();
int m_level;
public slots:
virtual void shootWeapon()=0;
protected:
QTimer * m_fireRateTimer;
int m_attackRange;
int m_damage;
int m_fireRate;
GameWindow * m_game;
const QPoint m_pos;
const QPixmap m_sprite;
static const QSize ms_fixedSize;
Enemy * m_chooseEnemy;
};
class NormalTower:public Tower{
Q_OBJECT
public:
NormalTower(QPoint pos,GameWindow *game, const QPixmap &sprite = QPixmap(":/Tower/RES/Tower/NT.png"));
~NormalTower();
const int m_cost;
virtual void levelup();
public slots:
void shootWeapon();
protected:
const QPixmap m_sprite;
};
class FireTower:public Tower{
Q_OBJECT
public:
FireTower(QPoint pos,GameWindow *game, const QPixmap &sprite = QPixmap(":/Tower/RES/Tower/FT.png"));
~FireTower();
const int m_cost;
virtual void levelup();
public slots:
void shootWeapon();
protected:
int fireattack;
const QPixmap m_sprite;
};
class IceTower:public Tower{
Q_OBJECT
public:
IceTower(QPoint pos,GameWindow *game, const QPixmap &sprite = QPixmap(":/Tower/RES/Tower/IT.png"));
~IceTower();
const int m_cost;
virtual void levelup();
public slots:
void shootWeapon();
protected:
double slowspeed;
const QPixmap m_sprite;
};
#endif // TOWER_H
<file_sep>#include "mainwindow.h"
#include"gamewindow.h"
#include "ui_mainwindow.h"
#include<QPainter>
#include<QPixmap>
#include<QPaintEvent>
#include<QPushButton>
#include<QMediaPlayer>
#include"mybutton.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
this->setFixedSize(1024,682);
ui->setupUi(this);
MyButton *buttone=new MyButton(":/SS/RES/StartScene/B2(1).png");
buttone->setParent(this);
buttone->move(350,250);
MyButton *buttonh=new MyButton(":/SS/RES/StartScene/B2(2).png");
buttonh->setParent(this);
buttonh->move(350,400);
EasyWindow * easyscene = new EasyWindow;
connect(buttone,&QPushButton::clicked,this,[=](){
this->hide();
easyscene->show();
bgm1=new QMediaPlayer;
bgm1->setMedia(QUrl("C:/Users/12580/Desktop/Code/MyTowerDefense/music/bgm1.mp3"));
bgm1->setVolume(80);
bgm1->play();
});
HardWindow * hardscene = new HardWindow;
connect(buttonh,&QPushButton::clicked,this,[=](){
this->hide();
hardscene->show();
bgm2=new QMediaPlayer;
bgm2->setMedia(QUrl("C:/Users/12580/Desktop/Code/MyTowerDefense/music/bgm2.mp3"));
bgm2->setVolume(80);
bgm2->play();
});
//返回,先不要
connect(easyscene,&EasyWindow::chooseBack,this,[=](){
easyscene->hide();
this->show();
bgm1->stop();
});
connect(hardscene,&HardWindow::chooseBack,this,[=](){
hardscene->hide();
this->show();
bgm2->stop();
});
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::paintEvent(QPaintEvent*){
QPainter painter(this);
QPixmap pixmap(":/SS/RES/StartScene/S2.jpg");
painter.drawPixmap(0,0,this->width(),this->height(),pixmap);
}
<file_sep>#include "gamewindow.h"
#include "mybutton.h"
#include"towerposition.h"
#include<QPainter>
#include<QPixmap>
#include<QPaintEvent>
#include<QPushButton>
#include<QMediaPlayer>
class Tower;
GameWindow::GameWindow(QWidget *parent) :
QMainWindow(parent),
m_waves(0)
{
this->setFixedSize(1024,682);
this->loadTowerPositions();
}
GameWindow::~GameWindow(){
}
void GameWindow::paintEvent(QPaintEvent*){
QPainter painter(this);
QPixmap pixmap(":/GameScene/RES/GameScene/SE.png");
painter.drawPixmap(0,0,this->width(),this->height(),pixmap);
foreach (const TowerPosition &towerPos,m_TowerPositionsList)
towerPos.draw(&painter);
foreach (Tower *tower, m_TowersList)
tower->draw(&painter);
}
void GameWindow::loadTowerPositions()
{
QPoint pos[] =
{
QPoint(923,403)
};
int len = sizeof(pos) / sizeof(pos[0]);
for (int i = 0; i < len; ++i)
m_TowerPositionsList.push_back(TowerPosition(pos[i]));
}
void GameWindow::addWayPoints()
{
WayPoint *wayPoint1 = new WayPoint(QPoint(945,140));
m_WayPointsList.push_back(wayPoint1);
WayPoint *wayPoint2 = new WayPoint(QPoint(945,330));
m_WayPointsList.push_back(wayPoint2);
wayPoint2->setNextWayPoint(wayPoint1);
WayPoint *wayPoint3 = new WayPoint(QPoint(410,330));
m_WayPointsList.push_back(wayPoint3);
wayPoint3->setNextWayPoint(wayPoint2);
WayPoint *wayPoint4 = new WayPoint(QPoint(410,570));
m_WayPointsList.push_back(wayPoint4);
wayPoint4->setNextWayPoint(wayPoint3);
WayPoint *wayPoint5 = new WayPoint(QPoint(750,570));
m_WayPointsList.push_back(wayPoint5);
wayPoint5->setNextWayPoint(wayPoint4);
}
void GameWindow::getHpDamage(int damage)
{
m_life-=damage;
}
void GameWindow::removedEnemy(Enemy *enemy)
{
Q_ASSERT(enemy);
m_enemyList.removeOne(enemy);
delete enemy;
if (m_enemyList.empty())
{
++m_waves; // 当前波数加1
// 继续读取下一波
if (!loadWave())
{
// 当没有下一波时,这里表示游戏胜利
// 设置游戏胜利标志为true
m_gameWin = true;
// 游戏胜利转到游戏胜利场景
// 这里暂时以打印处理
}
}
}
bool GameWindow::loadWave()
{
if (m_waves >= 6)
return false;
WayPoint *startWayPoint = m_WayPointsList.back(); // 这里是个逆序的,尾部才是其实节点
int enemyStartInterval[] = { 100, 500, 600, 1000, 3000, 6000 };
for (int i = 0; i < 6; ++i)
{
Enemy *enemy = new Enemy(startWayPoint, this);
m_enemyList.push_back(enemy);
QTimer::singleShot(enemyStartInterval[i], enemy, SLOT(doActivate()));
}
return true;
}
QList<Enemy *> GameWindow::enemyList() const{
return m_enemyList;
}
void GameWindow::removedBullet(Bullet *bullet)
{
Q_ASSERT(bullet);
m_BulletList.removeOne(bullet);
delete bullet;
}
void GameWindow::addBullet(Bullet *bullet)
{
Q_ASSERT(bullet);
m_BulletList.push_back(bullet);
}
/****************************************************************************************/
EasyWindow::EasyWindow(QWidget *parent) :
GameWindow(parent),
m_money(5000),
m_life(15),
m_waves(0)
{
this->setFixedSize(1024,682);
this->loadTowerPositions();
this->addWayPoints();
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateMap()));
timer->start(30);
QTimer::singleShot(30, this, SLOT(gameStart()));
MyButton * back_btn = new MyButton(":/GameScene/RES/GameScene/BackB.png");
back_btn->setParent(this);
back_btn->move(10,450);
connect(back_btn,&MyButton::clicked,this,[=](){emit chooseBack();
});
TButton* setTower[m_TowerPositionsList.size()];
for(int i = 0; i < m_TowerPositionsList.size(); i++)
{
setTower[i] = new TButton(m_TowerPositionsList[i].m_pos);
setTower[i] -> setIcon(QPixmap());
setTower[i] -> setParent(this);
setTower[i] ->move(m_TowerPositionsList.at(i).m_pos);
setTower[i]->setWindowOpacity(0.2);
connect(setTower[i], &TButton::setNormalTower, this, [=]()
{
if(!m_TowerPositionsList[i].hasTower())
emit set_Tower(i,'N');
});
connect(setTower[i], &TButton::setFireTower, this, [=]()
{
if(!m_TowerPositionsList[i].hasTower())
emit set_Tower(i,'F');
});
connect(setTower[i], &TButton::setIceTower, this, [=]()
{
if(!m_TowerPositionsList[i].hasTower())
emit set_Tower(i,'I');
});
connect(setTower[i], &TButton::Levelup, this, [=]()
{
if(m_money>=50)
emit up_Tower(i);
});
connect(setTower[i], &TButton::sellTower, this, [=]()
{
emit sell_Tower(i);
});
}
}
EasyWindow::~EasyWindow(){
}
void EasyWindow::loadTowerPositions()
{
QPoint pos[] =
{
QPoint(290,410),
QPoint(370,603),
QPoint(445,220),
QPoint(445,375),
QPoint(520,455),
QPoint(520,600),
QPoint(597,220),
QPoint(597,370),
QPoint(752,220),
QPoint(755,370),
QPoint(825,175)
};
int len = sizeof(pos) / sizeof(pos[0]);
for (int i = 0; i < len; ++i)
{
m_TowerPositionsList.push_back(TowerPosition(pos[i]));
}
}
void EasyWindow::addWayPoints()
{
WayPoint *wayPoint1 = new WayPoint(QPoint(945,140));
m_WayPointsList.push_back(wayPoint1);
WayPoint *wayPoint2 = new WayPoint(QPoint(945,330));
m_WayPointsList.push_back(wayPoint2);
wayPoint2->setNextWayPoint(wayPoint1);
WayPoint *wayPoint3 = new WayPoint(QPoint(410,330));
m_WayPointsList.push_back(wayPoint3);
wayPoint3->setNextWayPoint(wayPoint2);
WayPoint *wayPoint4 = new WayPoint(QPoint(410,570));
m_WayPointsList.push_back(wayPoint4);
wayPoint4->setNextWayPoint(wayPoint3);
WayPoint *wayPoint5 = new WayPoint(QPoint(750,570));
m_WayPointsList.push_back(wayPoint5);
wayPoint5->setNextWayPoint(wayPoint4);
}
void EasyWindow::paintEvent(QPaintEvent*){
QPainter painter(this);
QPixmap cachePix(":/GameScene/RES/GameScene/SE.png");
QPainter cachePainter(&cachePix);
drawMoney(&cachePainter);
drawLife(&cachePainter);
drawWave(&cachePainter);
foreach (const TowerPosition &towerPos, m_TowerPositionsList)
towerPos.draw(&cachePainter);
foreach (Tower *tower, m_TowersList)
{tower->draw(&cachePainter);
}
foreach (Enemy *enemy, m_enemyList)
enemy->draw(&cachePainter);
foreach (const Bullet *bullet, m_BulletList)
bullet->draw(&cachePainter);
painter.drawPixmap(0, 0, cachePix);
if (m_gameEnded || m_gameWin)
{
QString text = m_gameEnded ? "YOU LOST!!!" : "YOU WIN!!!";
QPainter painter(this);
painter.setPen(QPen(Qt::red));
painter.drawText(rect(), Qt::AlignCenter, text);
return;
}
update();
}
void EasyWindow::drawMoney(QPainter *painter)
{
QFont font("Arial",16,QFont::Bold,false);
painter->setPen(QPen(Qt::white));
painter->setFont(font);
painter->drawText(QRect(20,50,200,200), QString("MONEY\n%1").arg(m_money));
}
void EasyWindow::drawLife(QPainter *painter)
{
QFont font("Arial",16,QFont::Bold,false);
painter->setPen(QPen(Qt::white));
painter->setFont(font);
painter->drawText(QRect(20,200,200,200), QString("LIFE\n%1").arg(m_life));
}
void EasyWindow::drawWave(QPainter *painter)
{
QFont font("Arial",16,QFont::Bold,false);
painter->setPen(QPen(Qt::white));
painter->setFont(font);
painter->drawText(QRect(20,350,200,200), QString("Wave\n%1").arg(6-m_waves));
}
void EasyWindow::set_Tower(int num,char type)
{
switch (type)
{
case 'N':
{
NormalTower * a_new_tower = new
NormalTower(m_TowerPositionsList.at(num).centerPos(), this);
if(m_money<a_new_tower->m_cost)
{
delete [] a_new_tower;
break;
}
m_TowerPositionsList[num].setHasTower(true);
m_TowerPositionsList[num].m_tower=a_new_tower;
m_TowersList.push_back(a_new_tower);
m_money -= a_new_tower -> m_cost;
update();
break;
}
case 'F':
{
FireTower * a_new_tower = new FireTower(m_TowerPositionsList.at(num).centerPos(), this);
if(m_money<a_new_tower->m_cost)
{
delete [] a_new_tower;
break;
}
m_TowerPositionsList[num].setHasTower(true);
m_TowerPositionsList[num].m_tower=a_new_tower;
m_TowersList.push_back(a_new_tower);
m_money -= a_new_tower -> m_cost;
update();
break;
}
case 'I':
{
IceTower * a_new_tower = new IceTower(m_TowerPositionsList.at(num).centerPos(), this);
if(m_money<a_new_tower->m_cost)
{
delete [] a_new_tower;
break;
}
m_TowerPositionsList[num].setHasTower(true);
m_TowerPositionsList[num].m_tower=a_new_tower;
m_TowersList.push_back(a_new_tower);
m_money -= a_new_tower -> m_cost;
update();
break;
}
default:
break;
}
}
void EasyWindow::up_Tower(int num){
if(m_TowerPositionsList[num].m_tower)
{
m_TowerPositionsList[num].m_tower->levelup();
m_money-=50;
}
}
void EasyWindow::sell_Tower(int num){
if(m_TowerPositionsList[num].m_tower)
{
m_money+=80;
Tower * removedtower=m_TowerPositionsList[num].m_tower;
Q_ASSERT(removedtower);
m_TowersList.removeOne(removedtower);
delete removedtower;
m_TowerPositionsList[num].m_tower=NULL;
m_TowerPositionsList[num].setNoTower();
}
}
void EasyWindow::doGameOver()
{
if (!m_gameEnded)
{
if (m_life <= 0)
m_gameEnded = true;
// 此处应该切换场景到结束场景
// 暂时以打印替代,见paintEvent处理
}
}
bool EasyWindow::loadWave()
{
if (m_waves >= 6)
return false;
WayPoint *startWayPoint = m_WayPointsList.back(); // 这里是个逆序的,尾部才是其实节点
int enemyStartInterval[]={ 100*(7-m_waves), 300*(7-m_waves), 500*(7-m_waves), 700*(7-m_waves), 900*(7-m_waves), 1100*(7-m_waves),1300*(7-m_waves),1500*(7-m_waves),1700*(7-m_waves),1900*(7-m_waves),2100*(7-m_waves) };
for (int i = 0; i < 6; ++i)
{
Enemy *enemy;
int j=i%3;
switch(j){
case 0:
enemy = new NormalEnemy(startWayPoint, this);
break;
case 1:
enemy=new DefendEnemy(startWayPoint, this);
break;
case 2:
enemy=new BloodEnemy(startWayPoint, this);
break;
}
m_enemyList.push_back(enemy);
QTimer::singleShot(enemyStartInterval[i], enemy, SLOT(doActivate()));
}
return true;
}
void EasyWindow::gameStart()
{
loadWave();
}
void EasyWindow::updateMap()
{
doGameOver();
if(m_gameWin||m_gameEnded)
return;
else
{
foreach(Enemy *enemy, m_enemyList)
enemy->move();
foreach(Tower *tower, m_TowersList)
tower->checkEnemyInRange();
update();
}
}
void EasyWindow::getHpDamage(int damage)
{
QMediaPlayer * sound=new QMediaPlayer;
sound->setMedia(QUrl("C:/Users/12580/Desktop/Code/MyTowerDefense/music/hplose.wav"));
sound->setVolume(50);
sound->play();
m_life-=damage;
}
//********************************************************************
HardWindow::HardWindow(QWidget *parent) :
GameWindow(parent),
m_money(2000),
m_life(9),
m_waves(0)
{
this->setFixedSize(1024,682);
this->loadTowerPositions();
this->addWayPoints();
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateMap()));
timer->start(15);
QTimer::singleShot(30, this, SLOT(gameStart()));
MyButton * back_btn = new MyButton(":/GameScene/RES/GameScene/BackB.png");
back_btn->setParent(this);
back_btn->move(10,450);
connect(back_btn,&MyButton::clicked,this,[=](){emit chooseBack();
});
TButton* setTower[m_TowerPositionsList.size()];
for(int i = 0; i < m_TowerPositionsList.size(); i++)
{
setTower[i] = new TButton(m_TowerPositionsList[i].m_pos);
setTower[i] -> setIcon(QPixmap());
setTower[i] -> setParent(this);
setTower[i] ->move(m_TowerPositionsList.at(i).m_pos);
setTower[i]->setWindowOpacity(0.2);
connect(setTower[i], &TButton::setNormalTower, this, [=]()
{
if(!m_TowerPositionsList[i].hasTower())
emit set_Tower(i,'N');
});
connect(setTower[i], &TButton::setFireTower, this, [=]()
{
if(!m_TowerPositionsList[i].hasTower())
emit set_Tower(i,'F');
});
connect(setTower[i], &TButton::setIceTower, this, [=]()
{
if(!m_TowerPositionsList[i].hasTower())
emit set_Tower(i,'I');
});
connect(setTower[i], &TButton::Levelup, this, [=]()
{
if(m_money>=50)
emit up_Tower(i);
});
connect(setTower[i], &TButton::sellTower, this, [=]()
{
emit sell_Tower(i);
});
}
}
HardWindow::~HardWindow(){
}
void HardWindow::loadTowerPositions()
{
QPoint pos[] =
{
QPoint(220,275),
QPoint(220,420),
QPoint(295,575),
QPoint(360,110),
QPoint(360,350),
QPoint(455,260),
QPoint(455,420),
QPoint(455,580),
QPoint(530,120),
QPoint(600,425),
QPoint(675,120),
QPoint(675,270),
QPoint(675,500),
QPoint(750,45),
QPoint(750,415),
QPoint(830,190)
};
int len = sizeof(pos) / sizeof(pos[0]);
for (int i = 0; i < len; ++i)
{
m_TowerPositionsList.push_back(TowerPosition(pos[i]));
}
}
void HardWindow::addWayPoints()
{
WayPoint *wayPoint1 = new WayPoint(QPoint(900,145));
m_WayPointsList.push_back(wayPoint1);
WayPoint *wayPoint2 = new WayPoint(QPoint(790,145));
m_WayPointsList.push_back(wayPoint2);
wayPoint2->setNextWayPoint(wayPoint1);
WayPoint *wayPoint3 = new WayPoint(QPoint(790,380));
m_WayPointsList.push_back(wayPoint3);
wayPoint3->setNextWayPoint(wayPoint2);
WayPoint *wayPoint4 = new WayPoint(QPoint(640,380));
m_WayPointsList.push_back(wayPoint4);
wayPoint4->setNextWayPoint(wayPoint3);
WayPoint *wayPoint5 = new WayPoint(QPoint(640,230));
m_WayPointsList.push_back(wayPoint5);
wayPoint5->setNextWayPoint(wayPoint4);
WayPoint *wayPoint6 = new WayPoint(QPoint(330,230));
m_WayPointsList.push_back(wayPoint6);
wayPoint6->setNextWayPoint(wayPoint5);
WayPoint *wayPoint7 = new WayPoint(QPoint(330,540));
m_WayPointsList.push_back(wayPoint7);
wayPoint7->setNextWayPoint(wayPoint6);
WayPoint *wayPoint8 = new WayPoint(QPoint(635,540));
m_WayPointsList.push_back(wayPoint8);
wayPoint8->setNextWayPoint(wayPoint7);
WayPoint *wayPoint9 = new WayPoint(QPoint(635,610));
m_WayPointsList.push_back(wayPoint9);
wayPoint9->setNextWayPoint(wayPoint8);
WayPoint *wayPoint10 = new WayPoint(QPoint(900,610));
m_WayPointsList.push_back(wayPoint10);
wayPoint10->setNextWayPoint(wayPoint9);
}
void HardWindow::paintEvent(QPaintEvent*){
QPainter painter(this);
QPixmap cachePix(":/GameScene/RES/GameScene/SH.png");
QPainter cachePainter(&cachePix);
drawMoney(&cachePainter);
drawLife(&cachePainter);
drawWave(&cachePainter);
foreach (const TowerPosition &towerPos, m_TowerPositionsList)
towerPos.draw(&cachePainter);
foreach (Tower *tower, m_TowersList)
tower->draw(&cachePainter);
foreach (Enemy *enemy, m_enemyList)
enemy->draw(&cachePainter);
foreach (const Bullet *bullet, m_BulletList)
bullet->draw(&cachePainter);
painter.drawPixmap(0, 0, cachePix);
if (m_gameEnded || m_gameWin)
{
QString text = m_gameEnded ? "YOU LOST!!!" : "YOU WIN!!!";
QPainter painter(this);
painter.setPen(QPen(Qt::red));
painter.drawText(rect(), Qt::AlignCenter, text);
return;
}
update();
}
void HardWindow::drawMoney(QPainter *painter)
{
QFont font("Arial",16,QFont::Bold,false);
painter->setPen(QPen(Qt::white));
painter->setFont(font);
painter->drawText(QRect(20,50,200,200), QString("MONEY\n%1").arg(m_money));
}
void HardWindow::drawLife(QPainter *painter)
{
QFont font("Arial",16,QFont::Bold,false);
painter->setPen(QPen(Qt::white));
painter->setFont(font);
painter->drawText(QRect(20,200,200,200), QString("LIFE\n%1").arg(m_life));
}
void HardWindow::drawWave(QPainter *painter)
{
QFont font("Arial",16,QFont::Bold,false);
painter->setPen(QPen(Qt::white));
painter->setFont(font);
painter->drawText(QRect(20,350,200,200), QString("Wave\n%1").arg(6-m_waves));
}
void HardWindow::set_Tower(int num,char type)
{
switch (type)
{
case 'N':
{
NormalTower * a_new_tower = new
NormalTower(m_TowerPositionsList.at(num).centerPos(), this);
if(m_money<a_new_tower->m_cost)
{
delete [] a_new_tower;
break;
}
m_TowerPositionsList[num].setHasTower(true);
m_TowerPositionsList[num].m_tower=a_new_tower;//at函数返回常引用,不能调用非常成员函数
m_TowersList.push_back(a_new_tower);
m_money -= a_new_tower -> m_cost;
update(); //对界面进行刷新,否则需要移开才出现一座新的塔,每次加入都需要刷新
break;
}
case 'F':
{
FireTower * a_new_tower = new FireTower(m_TowerPositionsList.at(num).centerPos(), this);
if(m_money<a_new_tower->m_cost)
{
delete [] a_new_tower;
break;
}
m_TowerPositionsList[num].setHasTower(true);
m_TowerPositionsList[num].m_tower=a_new_tower;//at函数返回常引用,不能调用非常成员函数
m_TowersList.push_back(a_new_tower);
m_money -= a_new_tower -> m_cost;
update(); //对界面进行刷新,否则需要移开才出现一座新的塔,每次加入都需要刷新
break;
}
case 'I':
{
IceTower * a_new_tower = new IceTower(m_TowerPositionsList.at(num).centerPos(), this);
if(m_money<a_new_tower->m_cost)
{
delete [] a_new_tower;
break;
}
m_TowerPositionsList[num].setHasTower(true);
m_TowerPositionsList[num].m_tower=a_new_tower;//at函数返回常引用,不能调用非常成员函数
m_TowersList.push_back(a_new_tower);
m_money -= a_new_tower -> m_cost;
update(); //对界面进行刷新,否则需要移开才出现一座新的塔,每次加入都需要刷新
break;
}
default:
break;
} //对界面进行刷新,否则需要移开才出现一座新的塔,每次加入都需要刷新
}
void HardWindow::up_Tower(int num){
if(m_TowerPositionsList[num].m_tower)
{
m_TowerPositionsList[num].m_tower->levelup();
}
}
void HardWindow::sell_Tower(int num){
if(m_TowerPositionsList[num].m_tower)
{
m_money+=80;
Tower * removedtower=m_TowerPositionsList[num].m_tower;
Q_ASSERT(removedtower);
m_TowersList.removeOne(removedtower);
delete removedtower;
m_TowerPositionsList[num].m_tower=NULL;
m_TowerPositionsList[num].setNoTower();
}
}
void HardWindow::doGameOver()
{
if (!m_gameEnded)
{
if (m_life <= 0)
m_gameEnded = true;
// 此处应该切换场景到结束场景
// 暂时以打印替代,见paintEvent处理
}
}
bool HardWindow::loadWave()
{
if (m_waves >= 9)
return false;
WayPoint *startWayPoint = m_WayPointsList.back(); // 这里是个逆序的,尾部才是其实节点
int enemyStartInterval[] = { 200*(10-m_waves), 400*(10-m_waves), 600*(10-m_waves), 800*(10-m_waves), 1000*(10-m_waves), 1200*(10-m_waves),1400*(10-m_waves),1600*(10-m_waves),1800*(10-m_waves)};
for (int i = 0; i < 9; ++i)
{
Enemy *enemy;
int j=i%3;
switch(j){
case 0:
enemy = new NormalEnemy(startWayPoint, this);
break;
case 1:
enemy=new DefendEnemy(startWayPoint, this);
break;
case 2:
enemy=new BloodEnemy(startWayPoint, this);
break;
}
m_enemyList.push_back(enemy);
QTimer::singleShot(enemyStartInterval[i], enemy, SLOT(doActivate()));
}
return true;
}
void HardWindow::gameStart()
{
loadWave();
}
void HardWindow::updateMap()
{
doGameOver();
if(m_gameWin||m_gameEnded)
return;
else
{
foreach(Enemy *enemy, m_enemyList)
enemy->move();
foreach(Tower *tower, m_TowersList)
tower->checkEnemyInRange();
update();
}
}
void HardWindow::getHpDamage(int damage)
{
QMediaPlayer * sound=new QMediaPlayer;
sound->setMedia(QUrl("C:/Users/12580/Desktop/Code/MyTowerDefense/music/hplose.wav"));
sound->setVolume(50);
sound->play();
m_life-=damage;
}
<file_sep># MyTowerDefense
毛涵洁2019202252的C++大作业
| 8a8022103a194f6de48edae6ac265e5f16090c72 | [
"Markdown",
"C++"
] | 12 | C++ | Periuratio/MyTowerDefense | f5f220116dc154c2f32c20ef62a3934f26ad1eab | b063ef05d4ed4c44536bbcce09e31cc3d6fc5192 |
refs/heads/master | <repo_name>xabier180/MF0491-3<file_sep>/src/app/model/producto.ts
export class Producto{
foto: string;
precio: number;
precio_litro: string;
descripcion: string;
oferta: boolean;
numero_productos: number
constructor( descripcion:string, foto : string, precio:number, precio_litro:string, oferta:boolean, numero_productos=1 ){
this.descripcion= descripcion;
this.foto = foto;
this.precio = precio;
this.precio_litro= precio_litro;
this.numero_productos= 1;
}
}
<file_sep>/src/app/providers/mocks.productos.ts
export class MOCKS_PRODUCTOS {
static productos_disponibles = `[{
"descripcion": "BEEFEATER ginebra inglesa botella 70 cl.",
"foto": "https://s0.dia.es/medias/hd0/h18/9163753062430.jpg",
"precio": 12.95,
"precio_litro": "(18,50€ el litro)",
"oferta": true,
"numero_productos": 1
},
{
"descripcion": "BEEFEATER ginebra inglesa botella 70 cl.",
"foto": "https://s0.dia.es/medias/hd0/h18/9163753062430.jpg",
"precio": 7.90,
"precio_litro": "(18,50€ el litro)",
"oferta": false,
"numero_productos": 1
},
{
"descripcion": "CENTRAL LECHERA ASTURIANA leche asturiana botella 150 cl.",
"foto": "https://images-na.ssl-images-amazon.com/images/I/717ruVB877L._SY445_.jpg",
"precio": 1.5,
"precio_litro": "(1€ el litro)",
"oferta": false,
"numero_productos": 1
},
{
"descripcion": "CARBONELL aceite de oliva botella 100 cl.",
"foto": "https://cdn11.hiberus.com/images/productos/126356/126356_1.jpg",
"precio": 4.27,
"precio_litro": "(4.27€ el litro)",
"oferta": false,
"numero_productos": 1
},
{
"descripcion": "SOLAN DE CABRAS agua mineral natural 5 l.",
"foto": "https://static.ulabox.com/media/51696_l1.jpg",
"precio": 2.95,
"precio_litro": "(0.59€ el litro)",
"oferta": true,
"numero_productos": 1
},
{
"descripcion": "JUVER zumo de melocoton 1 l.",
"foto": "http://www.bolinchelidrinkstore.com/1467-thickbox_default/juver-zumo-de-melocoton-cristal-1-l.jpg",
"precio": 0.98,
"precio_litro": "(0.98€ el litro)",
"oferta": true,
"numero_productos": 1
},
{
"descripcion": "ADES leche de soja 1 l.",
"foto": "https://ep00.epimg.net/economia/imagenes/2016/06/01/actualidad/1464816501_599360_1464819081_noticia_normal.jpg",
"precio": 1.78,
"precio_litro": "(1.78€ el litro)",
"oferta": false,
"numero_productos": 1
},
{
"descripcion": "<NAME> Zumo de naranja natural 80 cl.",
"foto": "https://yourspanishcorner.com/4168-thickbox_default/zumo-de-naranja-natural-la-huerta-don-simon.jpg",
"precio": 2.40,
"precio_litro": "(3€ el litro)",
"oferta": false,
"numero_productos": 1
},
{
"descripcion": "LAMBRUSCO Vino rosado 70 cl.",
"foto": "https://cloud.quierovinos.com/5273-large_default/lambrusco-rosado-paesano.jpg",
"precio": 3.50,
"precio_litro": "(5€ el litro)",
"oferta": false,
"numero_productos": 1
},
{
"descripcion": "ESTRELLA GALICIA cerveza 33 cl.",
"foto": "https://images-na.ssl-images-amazon.com/images/I/41AdFBL15FL._SY445_.jpg",
"precio": 1.25,
"precio_litro": "(3.75€ el litro)",
"oferta": false,
"numero_productos": 1
}
]`;
}<file_sep>/src/app/providers/pipes/filter.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { Producto } from '../../model/producto';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
/**
* Filtro para buscar en una coleccion de productos. No es CaseSensitive
* @param productos : Producto[]
* @param searchText : string con la marca o nombre del producto
*/
transform(productos: Producto[], searchText: string): Producto[] {
if(!productos) return [];
if(!searchText) return productos;
//Filtro por nombre o descripcion
searchText = searchText.toLowerCase();
let nombre = "";
return productos.filter( todoIt => {
nombre = todoIt.descripcion;
return nombre.toLowerCase().includes(searchText);
});
}
}<file_sep>/src/app/tienda/tienda.component.ts
import { Component, OnInit } from '@angular/core';
import {ProductosService} from '../providers/productos.service';
import { Producto } from '../model/producto';
@Component({
selector: 'app-tienda',
templateUrl: './tienda.component.html',
styleUrls: ['./tienda.component.scss']
})
export class TiendaComponent implements OnInit {
productos: Array<Producto>;
producto_seleccionado: Producto;
numero_productos: number;
constructor(public productosService:ProductosService) {
this.producto_seleccionado = new Producto('', '', 2, '', true, 1);
this.productos = new Array<Producto>();
console.log('ProductosComponent constructor');
}
ngOnInit() {
console.log('productos')
this.productos = this.productosService.getProductos();
}
recibirProducto(event){
console.log('ConcesionarioComponent: recibirProducto %o %i', event.producto);
this.producto_seleccionado = event.producto;
}
sumarProducto(producto_suma:Producto){
console.log('Click sumarProducto');
producto_suma.numero_productos = producto_suma.numero_productos+1;
}
restarProducto(producto_resta:Producto){
if(producto_resta.numero_productos>1){
console.log('Click sumarProducto');
producto_resta.numero_productos = producto_resta.numero_productos-1;
}
}
}
<file_sep>/src/app/providers/productos.service.ts
import { Injectable } from '@angular/core';
import { Producto } from '../model/producto';
import { MOCKS_PRODUCTOS } from './mocks.productos';
import { element } from 'protractor';
@Injectable()
export class ProductosService {
constructor() {
console.log('ProductosService constructor');
}
/**
* Retorna todos los productos que tenemos en productos_disponibles
*/
getProductos():Producto[]{
console.log('ProductosService getAll');
let productos:Producto[] = [];
let producto;
let jsonData = JSON.parse(MOCKS_PRODUCTOS.productos_disponibles);
jsonData.forEach( element => {
producto = new Producto(
element.descripcion,
element.foto,
element.precio,
element.precio_litro,
element.oferta,
element.numero_productos
);
productos.push(producto);
});
return productos;
}
}
| 88a04b4dc216606f76db242ec9e1999242569ddf | [
"TypeScript"
] | 5 | TypeScript | xabier180/MF0491-3 | b3b964d19ec8a0d20d3028a74aae2eca993c0b7f | 8d747b9c67f5026fb6ea5882e0d348d01839d989 |
refs/heads/master | <repo_name>matethurzo/liferay-cloning<file_sep>/liferay-cloning-tool/build.xml
<?xml version="1.0"?>
<project basedir="." default="cloning" name="liferay-cloning">
<target name="upgrade">
<path id="lib.classpath">
<fileset dir="$TOMCAT_HOME/lib" includes="*.jar" />
<fileset dir="$TOMCAT_HOME/lib/ext" includes="*.jar" />
<fileset dir="$TOMCAT_HOME/bin" includes="*.jar" />
<fileset dir="$TOMCAT_HOME/webapps/ROOT/WEB-INF/lib" includes="*.jar" />
</path>
<java
classname="com.liferay.cloning.executor.CloningExecutor"
classpathref="lib.classpath"
fork="true"
maxmemory="1024m"
newenvironment="true"
>
<jvmarg value="-Dfile.encoding=UTF-8" />
<jvmarg value="-Duser.country=US" />
<jvmarg value="-Duser.language=en" />
<jvmarg value="-Duser.timezone=GMT" />
<jvmarg value="-XX:MaxPermSize=256m" />
</java>
</target>
</project><file_sep>/liferay-cloning-tool/run.sh
#!/bin/sh
exportJars() {
for jarFile in ${1}/*.jar
do
CLASSPATH="${CLASSPATH}:${jarFile}"
done
}
showUsage() {
echo "Usage : $0 --classpath <classpath> [--debug] [--java_home <Java home>] --liferay_home <Liferay home>"
echo "-cp, --classpath Set the classpath to the Liferay libraries deployed in your application server. Use the comma as a separator."
echo "-d, --debug Start the JVM in debug mode."
echo "-jh, --java_home Set the Java home directory or optionally default to the value specified in the environment variable JAVA_HOME."
echo "-lh,--liferay_home, --liferay_home Set the Liferay home directory."
exit 1;
}
CLASSPATH=""
DEBUG="false"
DEBUG_OPTS="-agentlib:jdwp=transport=dt_socket,address=9009,server=y,suspend=n"
JAVA_BIN="$(which java)"
JAVA_OPTS="-Xmx2048m -XX:MaxPermSize=384m"
STD_IN=0
key=""
prefix=""
value=""
for keyValue in "$@"
do
case "${prefix}${keyValue}" in
-cp=*|--classpath=*) key="-classpath"; value="${keyValue#*=}";;
-d|--debug) key="-debug"; value="${keyValue#*=}";;
-jh=*|--java_home=*) key="-java_home"; value="${keyValue#*=}";;
-lh=*|--liferay_home=*) key="-liferay_home"; value="${keyValue#*=}";;
*) value=${keyValue};;
esac
case $key in
-classpath) CLASSPATH=${value}; prefix=""; key="";;
-debug) DEBUG="true"; prefix=""; key="";;
-java_home) JAVA_HOME=${value}; prefix=""; key="";;
-liferay_home) LIFERAY_HOME=${value}; prefix=""; key="";;
*) prefix="${keyValue}=";;
esac
done
if [ ! ${CLASSPATH} ] || [ ! ${LIFERAY_HOME} ];
then
showUsage
fi
if [ ${JAVA_HOME} ]
then
JAVA_BIN=${JAVA_HOME}/bin/java
fi
if [ ${DEBUG} = "true" ]
then
JAVA_OPTS="$JAVA_OPTS ${DEBUG_OPTS}"
fi
CURRENT_IFS="${IFS}"
IFS=","
for path in ${CLASSPATH}
do
exportJars ${path}
done
IFS="${CURRENT_IFS}"
exportJars ${LIFERAY_HOME}/osgi/core
CLASSPATH=${CLASSPATH}:${LIFERAY_HOME}
${JAVA_BIN} ${JAVA_OPTS} -cp ${CLASSPATH} -Dfile.encoding=UTF8 -Duser.country=US -Duser.language=en -Duser.timezone=GMT com.liferay.cloning.executor.CloningExecutor<file_sep>/liferay-cloning-api/src/main/java/com/liferay/cloning/api/CloningPropsKeys.java
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.cloning.api;
/**
* @author <NAME>
*/
public interface CloningPropsKeys {
public static final String PASSWORD_CLONING_UPDATER_NEW_PASSWORD = "<PASSWORD>";
public static final String PASSWORD_CLONING_UPDATER_UPDATE_PASSWORDS = "password.cloning.updater.update.passwords";
public static final String PASSWORD_CLONING_UPDATER_USER_IDS = "password.cloning.updater.user.ids";
public static final String PASSWORD_POLICY_CLONING_UPDATER_DELETE_PASSWORD_POLICIES = "password.policy.cloning.updater.delete.password.policies";
public static final String STAGING_DATA_CLONING_UPDATER_NEW_REMOTE_GROUPID = "staging.data.cloning.updater.new.remote.GROUPID";
public static final String STAGING_DATA_CLONING_UPDATER_NEW_REMOTE_HOST = "staging.data.cloning.updater.new.remote.host";
public static final String STAGING_DATA_CLONING_UPDATER_NEW_REMOTE_PORT = "staging.data.cloning.updater.new.remote.port";
public static final String STAGING_DATA_CLONING_UPDATER_OLD_REMOTE_GROUPID = "staging.data.cloning.updater.old.remote.groupid";
public static final String STAGING_DATA_CLONING_UPDATER_OLD_REMOTE_HOSTS = "staging.data.cloning.updater.old.remote.hosts";
public static final String STAGING_DATA_CLONING_UPDATER_OLD_REMOTE_PORT = "staging.data.cloning.updater.old.remote.port";
public static final String STAGING_DATA_CLONING_UPDATER_UPDATE_STAGING_DATA = "staging.data.cloning.updater.update.staging.data";
public static final String USER_DATA_CLONING_UPDATER_UPDATE_USER_DATA = "user.data.cloning.updater.update.user.data";
public static final String VIRTUAL_HOST_CLONING_UPDATER_NEW_VIRTUAL_HOST = "virtual.host.cloning.updater.new.virtual.host";
public static final String VIRTUAL_HOST_CLONING_UPDATER_OLD_VIRTUAL_HOSTS = "virtual.host.cloning.updater.old.virtual.hosts";
public static final String VIRTUAL_HOST_CLONING_UPDATER_UPDATE_VIRTUAL_HOSTS = "virtual.host.cloning.updater.update.virtual.hosts";
}
| 34a4a69cd43d37f2257d8e9f6332183560453b06 | [
"Java",
"Ant Build System",
"Shell"
] | 3 | Ant Build System | matethurzo/liferay-cloning | d490bfaa4fb2188b0226290edcf5a3fcc0039555 | 6c733e426309e0ef5ad20703c6fc4ed74b343817 |
refs/heads/master | <file_sep># paython-downloader
on this repo we will add a Download manager with Python and PYQT5
### Features
- Download normal files
- Download from Youtube (single video - playlist)
<file_sep>import sys
import urllib.error
import urllib.request
import urllib.response
import pafy
import os
from PyQt5.QtWidgets import *
from PyQt5.uic import loadUiType
from PyQt5.uic.properties import QtGui, QtCore
from overlay import *
import humanize
ui, _ = loadUiType('main.ui')
class MainApp(QMainWindow, ui):
def __init__(self, parent=None):
super(MainApp, self).__init__(parent)
QMainWindow.__init__(self)
self.setupUi(self)
self.initUi()
self.handelButtons()
## Youtube :- one video
## Youtube :- playlist
def initUi(self):
pass
def handelButtons(self):
self.pushButton_6.clicked.connect(self.download)
self.pushButton_10.clicked.connect(self.handelBrowse)
## Youtube
self.pushButton_5.clicked.connect(self.getVideoData)
self.pushButton_9.clicked.connect(self.saveBrowse)
self.pushButton_4.clicked.connect(self.downloadVideo)
self.pushButton_8.clicked.connect(self.save_playlist_browse)
self.pushButton_7.clicked.connect(self.download_playlist)
pass
def handelProgress(self, blockNum, blockSize, totalSize):
readedData = blockNum * blockSize
if totalSize > 0:
downloadPercetage = readedData * 100 / totalSize
self.progressBar.setValue(downloadPercetage)
QApplication.processEvents()
pass
def handelBrowse(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
path = QFileDialog.getSaveFileName(self, caption='Save as', directory='.', filter='All Files(*.*)',
initialFilter='', options=options)
self.lineEdit_2.setText(str(path[0]))
def download(self):
url = self.lineEdit.text()
pathToSave = self.lineEdit_2.text()
if url == '':
QMessageBox.warning(self, "Data Error", 'Please add valid Url')
return
elif pathToSave == '':
QMessageBox.warning(self, "Data Error", 'Please add valid path to save')
return
else:
try:
urllib.request.urlretrieve(url, pathToSave, self.handelProgress)
except urllib.error.URLError as e:
QMessageBox.warning(self, "Download Error", e.reason)
return
QMessageBox.information(self, 'Download Completed', 'Download Completed')
self.lineEdit.setText('')
self.lineEdit_2.setText('')
self.progressBar.setValue(0)
###################################
######### Youtube one video #######
###################################
def saveBrowse(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
path = QFileDialog.getSaveFileName(self, caption='Save as', directory='.', filter='All Files(*.*)',
initialFilter='', options=options)
self.lineEdit_4.setText(str(path[0]))
def getVideoData(self):
videoLink = self.lineEdit_3.text()
if (videoLink == ''):
QMessageBox.warning(self, "Data Error",
"Please add valid Youtube URL like this 'https://www.youtube.com/watch?v=xxxxx'")
else:
try:
data = pafy.new(videoLink)
all_streams = data.videostreams
for stream in all_streams:
size = humanize.naturalsize(stream.get_filesize())
data = "{} - {} - {} ".format(stream.extension, stream.quality, size)
self.comboBox.addItem(data)
except Exception as error:
QMessageBox.warning(self, 'Fetch Data Error', str(error))
return
pass
def downloadVideo(self):
video_link = self.lineEdit_3.text()
save_path = self.lineEdit_4.text()
if video_link == '':
QMessageBox.warning(self, "Data Error",
"Please add valid Youtube URL like this 'https://www.youtube.com/watch?v=xxxxx'")
return
elif save_path == '':
QMessageBox.warning(self, "Data Error", 'Please add valid path to save')
return
else:
video = pafy.new(video_link)
video_stream = video.videostreams
video_quality = self.comboBox.currentIndex()
try:
download = video_stream[video_quality].download(filepath=save_path, callback=self.handel_video_progress)
QMessageBox.information(self, 'Download Completed', 'Download Completed')
except Exception as error:
QMessageBox.warning(self, 'Download video Error', str(error))
return
self.lineEdit_3.setText('')
self.lineEdit_4.setText('')
self.progressBar_2.setValue(0)
def handel_video_progress(self, total, recvd, ratio, rate, eta):
readedData = recvd
if total > 0:
downloadPercetage = readedData * 100 / total
self.progressBar_2.setValue(downloadPercetage)
QApplication.processEvents()
##playlist
def download_playlist(self):
paylist_url = self.lineEdit_6.text()
paylist_save_path = self.lineEdit_5.text()
if paylist_url == '':
QMessageBox.warning(self, "Data Error",
"Please add valid Playlist URL like this 'https://www.youtube.com/playlist?list=xxxxx'")
return
elif paylist_save_path == '':
QMessageBox.warning(self, "Data Error", 'Please add valid path to save')
return
else:
try:
playlist = pafy.get_playlist(paylist_url)
videos = playlist['items']
self.lcdNumber_2.display(len(playlist['items']))
os.chdir(paylist_save_path)
if os.path.exists(str(playlist['title'])):
os.chdir(str(playlist['title']))
else:
os.mkdir(str(playlist['title']))
os.chdir(str(playlist['title']))
current_video_in_download = 1
# quality = self.comboBox_2.currentIndex()
QApplication.processEvents()
for video in playlist['items']:
self.lcdNumber.display(current_video_in_download)
current_video = video['pafy'].getbest()
print(current_video)
playlist_meta = video['playlist_meta']
title = playlist_meta['title']
thumbnail = playlist_meta['thumbnail']
length_seconds = round(playlist_meta['length_seconds']/60, 2)
self.label_4.setText(str('Now Downloading {} Length {} '.format(title, length_seconds)))
download = current_video.download(callback=self.handel_playlist_progress)
current_video_in_download += 1
QApplication.processEvents()
except Exception as error:
QMessageBox.warning(self, 'Download video Error', str(error))
return
def handel_playlist_progress(self, total, recvd, ratio, rate, eta):
readedData = recvd
if total > 0:
rate = humanize.naturalsize(rate)
self.label_11.setText(str(' {} '.format(rate)))
download_percentage = readedData * 100 / total
self.progressBar_3.setValue(download_percentage)
remaining_time = round(eta/60, 2)
QApplication.processEvents()
def save_playlist_browse(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
options |= QFileDialog.DontUseCustomDirectoryIcons
dialog = QFileDialog()
dialog.setOptions(options)
dialog.setFileMode(QFileDialog.DirectoryOnly)
dialog.setDirectory('.')
dialog.setAcceptMode(QFileDialog.AcceptOpen)
dialog.exec_()
path = dialog.selectedFiles()[0]
self.lineEdit_5.setText(path)
def main():
app = QApplication(sys.argv)
window = MainApp()
window.show()
app.exec_()
if __name__ == '__main__':
main()
| 9245f7fa20b9eb001230bf6c1f9988f41951d142 | [
"Markdown",
"Python"
] | 2 | Markdown | ahmed3bead/paython-downloader | 14b6439c43b0a977631b1170bd280bf84c4d8aea | 9a6dd140f71184c4535daf58e274f39612356a9a |
refs/heads/master | <repo_name>wjonesusna2012/my-site<file_sep>/src/styles/colors.js
export default {
navigationPrimary: 'rgba(255, 0, 0, 1.0);',
navigationText: 'rgba(240, 240, 240, 1.0);',
navigationBorder: 'rgba(255, 255, 255, 0.0);',
};
| 38899e852bb76c55f7036e5e2879f5701086eb2f | [
"JavaScript"
] | 1 | JavaScript | wjonesusna2012/my-site | f24134ce06c0536d7965bfc99e4b08559825c374 | 2bb84410314a08dfb0f453a43fca58c6425e7b34 |
refs/heads/master | <repo_name>enma1009/project2<file_sep>/models/item.js
module.exports = function(sequelize, DataTypes) {
var Item = sequelize.define("Item", {
title: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
itemDescription: {
type: DataTypes.TEXT,
allowNull: false,
len: [1]
},
itemCategory: {
type: DataTypes.STRING
},
imgName: {
type: DataTypes.STRING
}
});
Item.associate = function(models) {
// We're saying that a Post should belong to an Author
// A Post can't be created without an Author due to the foreign key constraint
Item.belongsTo(models.User, {
foreignKey: {
allowNull: false
}
});
};
return Item;
};
<file_sep>/public/js/addItem.js
$(document).ready(function() {
$.get("/api/user_data").then(function(data) {
$("#currentUserId").val(data.id);
});
// });
// let submitForm = $("form#submitItemForm");
// submitForm.on("submit", function(event) {
// event.preventDefault();
// let itemTitle = $("input#item_title").val().trim();
// let itemCategory = $("#item_category option:selected").text();
// let itmDescription = $("textarea#item_description").val();
// let imgFileName = $("#uploadImg").val().replace(/.*(\/|\\)/, '');
// $.get("/api/user_data").then(function(data) {
// let itemData = {
// title: itemTitle,
// itemDescription: itmDescription,
// itemCategory: itemCategory,
// UserId: data.id,
// imgName: imgFileName
// };
// console.log(itemData);
// createItem(itemData);
// });
// });
// function createItem(itemData) {
// $.post("/api/newItem", itemData).then(function(data) {
// console.log("returned from api/newitem");
// // $(".member-name").text(data.name);
// });
// }
});<file_sep>/public/js/members.js
$(document).ready(function() {
// This file just does a GET request to figure out which user is logged in
// and updates the HTML on the page
$.get("/api/user_data").then(function(data) {
let userName = data.name;
userName = userName.charAt(0).toUpperCase() + userName.slice(1);
$(".member-name").text(userName);
});
});
<file_sep>/public/js/trading-dashboard-demo.js
$(document).ready(function() {
$.get("/api/user_data").then(function(data) {
let userID = data.id;
console.log(userID);
$.get("/api/items_data", userID).then(function(data) {
console.log(data);
console.log("back from the server");
if(data.length !==0) {
data.forEach(function(item, index) {
//console.log(item);
let htmlContent = `<div class="col-xs-4 col-sm-2 mb-4">
<a href="#"><img class="img-thumbnail itemLink" data-id="${item.id}" src="assets/db_images/${item.imgName}" alt="${item.title}" width="100%"></a></div>`;
$("#uploadedItems").prepend(htmlContent);
});
} else {
$("#uploadedItems").html( "<p>You have not added items to trade with others.</p>" );
}
});
});
$("#readMsg").on('click', function(e){
e.preventDefault();
$("#readMsg").addClass("disabled");
$("#tradeDenied").removeClass("d-none");
})
$("#closeMsg").on("click", function(e){
e.preventDefault();
$(".activeTradeRequests").addClass("d-none");
$(".noTradeRequests").removeClass("d-none");
})
$("#markComplete").on("click", function(e){
e.preventDefault();
$("#markComplete").addClass("d-none");
$(".completedMsg").removeClass("d-none");
})
});
<file_sep>/public/js/market.js
$(document).ready(function() {
$.get("/api/items").then(function(data) {
data.forEach(function(item, index) {
let htmlContent = `<div class="col-sm-3 mb-4">
<a href="/itemdetails?item=${item.id}"><img class="img-thumbnail" src="assets/db_images/${item.imgName}" alt="${item.title}" width="100%"></a></div>`;
$("#itemsContainer").append(htmlContent);
});
});
});<file_sep>/public/js/itemdetails.js
$(document).ready(function() {
let url = document.location.href.split("?");
let itemId = url[url.length-1].split("=")[1];
$.get(`/api/item/${itemId}`).then(function(data) {
$("#itemTitle").text(data.title);
$("#itemDescription").text(data.itemDescription);
$("#itemCategory").text(data.itemCategory);
$("#itemImg").attr('src', `/assets/db_images/${data.imgName}`);
});
});<file_sep>/public/js/trading-dashboard.js
$(document).ready(function() {
$.get("/api/user_data").then(function(data) {
let userID = data.id;
console.log(userID);
$.get("/api/items_data", userID).then(function(data) {
console.log(data);
console.log("back from the server");
if(data.length !==0) {
data.forEach(function(item, index) {
//console.log(item);
let htmlContent = `<div class="col-xs-4 col-sm-2 mb-4">
<a href="#"><img class="img-thumbnail itemLink" data-id="${item.id}" src="assets/db_images/${item.imgName}" alt="${item.title}" width="100%"></a></div>`;
$("#uploadedItems").prepend(htmlContent);
});
} else {
$("#uploadedItems").html( "<p>You have not added items to trade with others.</p>" );
}
});
});
});
| b6b142e3eb3dd88a6e3156c7b9a28b6becfaa7d9 | [
"JavaScript"
] | 7 | JavaScript | enma1009/project2 | 8346ae845ad9b6068bba4506498ea6d32e617845 | 5385bb3ac2a43ed895500e2f601ad69bbde76411 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Constants : MonoBehaviour
{
public const string SCENE1 = "Assignment1";
public const string SCENE2 = "Assignment2";
public const string SCENE3_1 = "Assignment3-1";
public const string SCENE3_2 = "Assignment3-2";
public const string MENUSCENE = "Menu";
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public enum MainMenuState
{
MainMenu,
ExtrudeVariation,
Loading
}
public class MainMenu : MonoBehaviour
{
public MainMenuState mainMenuState;
public GameObject mainScreen,extrudeVariation,loadingScreen;
public Text loadingText;
public float animationWait;
private Coroutine routine;
void LoadScene(string name)
{
SceneManager.LoadSceneAsync(name);
}
public void Assignment1()
{
this.ChangeMainMenuState(MainMenuState.Loading);
this.LoadScene(Constants.SCENE1);
}
public void Assignment2()
{
this.ChangeMainMenuState(MainMenuState.Loading);
this.LoadScene(Constants.SCENE2);
}
public void Assignment3()
{
this.ChangeMainMenuState(MainMenuState.ExtrudeVariation);
}
public void Assignment3Var1()
{
this.ChangeMainMenuState(MainMenuState.Loading);
this.LoadScene(Constants.SCENE3_1);
}
public void Assignment3Var2()
{
this.ChangeMainMenuState(MainMenuState.Loading);
this.LoadScene(Constants.SCENE3_2);
}
public void Back()
{
this.ChangeMainMenuState(MainMenuState.MainMenu);
}
public void ChangeMainMenuState(MainMenuState mainMenuState)
{
this.mainMenuState = mainMenuState;
this.extrudeVariation.SetActive(mainMenuState.Equals(MainMenuState.ExtrudeVariation));
this.loadingScreen.SetActive(mainMenuState.Equals(MainMenuState.Loading));
this.mainScreen.SetActive(mainMenuState.Equals(MainMenuState.MainMenu));
if (mainMenuState.Equals(MainMenuState.Loading))
{
StartCoroutine(this.TextAnimation());
}
else
{
if (this.routine != null)
StopCoroutine(this.routine);
}
}
public IEnumerator TextAnimation()
{
while(true)
{
this.loadingText.text = ".";
yield return new WaitForSeconds(this.animationWait);
this.loadingText.text = "..";
yield return new WaitForSeconds(this.animationWait);
this.loadingText.text = "...";
yield return new WaitForSeconds(this.animationWait);
this.loadingText.text = "....";
yield return new WaitForSeconds(this.animationWait);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
using System.IO;
namespace QuixelTest.SubtractionShaderAssignment
{
public class TextureManipulator : MonoBehaviour
{
public RenderTexture ResultTexture;
public int Size = 256;
/// <summary>
/// Renderers to Manipulate the materials and show result
/// </summary>
public MeshRenderer plane1, plane2, meshToApplyFrom, meshToApplyOn;
public Material ReplaceMaterial;
/// <summary>
/// Reader that is responsible for reading data from xml on disk
/// </summary>
private XMLReader textureLoader;
// Use this for initialization
void Awake()
{
if (ResultTexture == null)
{
ResultTexture = new RenderTexture(Size, Size, 0);
ResultTexture.name = "ResultantTexture";
}
}
private void Start()
{
this.textureLoader = this.GetComponent<XMLReader>();
///Adding Response to delegate that is called after textures loading
this.textureLoader.OnTexturesLoaded += this.OnTexturesLoaded;
///Sending a Call to load the texture data from the disk
this.textureLoader.LoadData();
this.meshToApplyFrom.gameObject.hideFlags = HideFlags.HideInHierarchy;
}
public void OnTexturesLoaded()
{
///Setting Created Render Textures to the planes
this.plane1.material.mainTexture = this.textureLoader.renderTexture1;
this.plane2.material.mainTexture = this.textureLoader.renderTexture2;
///Assigning the Render Textures to the texture channels of our subtraction shader material
this.meshToApplyFrom.material.SetTexture("_MainTex", this.textureLoader.renderTexture1);
this.meshToApplyFrom.material.SetTexture("_SecondTex", this.textureLoader.renderTexture2);
}
/// <summary>
/// Button Event Responsible for doing the shader math
/// </summary>
public void ButtonEvent()
{
CreateNewTexture();
if (ReplaceMaterial != null)
{
this.meshToApplyOn.material = ReplaceMaterial;
ReplaceMaterial.mainTexture = this.ResultTexture;
}
}
/// <summary>
/// Method To Create the New Texture from given ones using the graphics library
/// </summary>
void CreateNewTexture()
{
Renderer renderer = this.meshToApplyFrom.GetComponent<Renderer>();
Material material = Instantiate(renderer.material);
Graphics.Blit(material.mainTexture, ResultTexture, material);
this.WriteTextureToDiskPath(ResultTexture, Application.dataPath + "\\AssignmentTask1\\Textures\\ResultantTexture\\Texture.png");
}
/// <summary>
/// Writing the Data to the Disk on given path
/// </summary>
/// <param name="texture"></param>
/// <param name="Path"></param>
public void WriteTextureToDiskPath(RenderTexture texture, string Path)
{
///Mapping the resultant render texture on a simple 2d texture
Texture2D resultantTexture = new Texture2D(texture.width, texture.height);
resultantTexture.alphaIsTransparency = true;
resultantTexture.ReadPixels(new Rect(0, 0, resultantTexture.width, resultantTexture.height), 0, 0, false);
resultantTexture.Apply();
///Encoding texture to bytes
byte[] data = resultantTexture.EncodeToPNG();
///Writing bytes data to disk
FileStream fstream = File.Open(Path, FileMode.OpenOrCreate);
BinaryWriter st = new BinaryWriter(fstream);
st.Write(data);
fstream.Close();
}
public void LoadMenu()
{
UtilMethods.BackToMenu();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace QuixelTest.ExtrudeAssignment
{
public class MeshOperation : BasicMeshOperations
{
private List<GameObject> triangles = new List<GameObject>();
public List<GameObject> PolyGons = new List<GameObject>();
public override void Start()
{
base.Start();
//this.ExtrudeMesh();
}
public void ExtrudeMesh()
{
this.triangles.Clear();
this.PolyGons.Clear();
Mesh M = this.meshFilter.mesh;
Vector3[] verts = M.vertices;
Vector3[] normals = M.normals;
Vector2[] uvs = M.uv;
for (int subMesh = 0; subMesh < M.subMeshCount; subMesh++)
{
int[] indices = M.GetTriangles(subMesh);
Debug.LogError(indices.Length);
for (int i = 0; i < indices.Length; i += 3)
{
Vector3[] newVerts = new Vector3[3];
Vector3[] newNormals = new Vector3[3];
Vector2[] newUvs = new Vector2[3];
for (int n = 0; n < 3; n++)
{
int index = indices[i + n];
newVerts[n] = verts[index];
newUvs[n] = uvs[index];
newNormals[n] = normals[index];
}
Mesh mesh = new Mesh();
mesh.vertices = newVerts;
mesh.normals = newNormals;
mesh.uv = newUvs;
mesh.triangles = new int[] { 0, 1, 2, 2, 1, 0 };
GameObject GO = new GameObject();
GO.transform.position = transform.position;
GO.transform.rotation = transform.rotation;
GO.AddComponent<MeshRenderer>().material = meshRenderer.materials[subMesh];
GO.AddComponent<MeshFilter>().mesh = mesh;
this.triangles.Add(GO);
}
}
//this.meshRenderer.enabled = false;
//this.meshCollider.enabled = false;
int j = 0;
for (int i = 0; i < this.triangles.Count - 1; i += 2)
{
GameObject halfPoly1 = this.triangles[i];
GameObject halfPoly2 = this.triangles[i + 1];
halfPoly2.transform.SetParent(halfPoly1.transform);
halfPoly1.AddComponent<BoxCollider>();
halfPoly1.name = "Polygon" + (j++).ToString();
this.PolyGons.Add(halfPoly1);
}
//this.meshFilter.combin
//Destroy(this.meshFilter.gameObject);
}
public void ScaleSiblingParts(GameObject part1, GameObject part2, Vector3 hitNormal, float scaleSenstivity, float positionSenstivity)
{
List<GameObject> list = new List<GameObject>();
for (int i = 0; i < this.PolyGons.Count; i++)
{
if (this.PolyGons[i] != part1 & this.PolyGons[i] != part2)
{
list.Add(this.PolyGons[i]);
this.PolyGons[i].transform.localScale += hitNormal * scaleSenstivity;
this.PolyGons[i].transform.position += hitNormal * positionSenstivity;
}
}
}
public float scaleSenstivity = 0.1f, positionSenstivity = 0.1f;
// Update is called once per frame
public override void Update()
{
base.Update();
if (Input.GetMouseButtonDown(0) & !Input.GetKey(KeyCode.LeftControl))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
bool canHit = Physics.Raycast(ray, out hit, 100f);
if (canHit)
this.ExtrudeMesh();
if (Physics.Raycast(ray, out hit, 100f))
{
this.pos = hit.transform.position;
this.normal = hit.normal;
hit.transform.position += hit.normal * this.extrusionSenstivity;
RaycastHit u;
if (Physics.Raycast(hit.point, -hit.normal, out u))
{
Debug.LogError(u.transform.gameObject);
this.ScaleSiblingParts(hit.transform.gameObject, u.transform.gameObject, hit.normal, this.scaleSenstivity, this.positionSenstivity);
}
CombineInstance[] instances = new CombineInstance[this.triangles.Count];
for (int i = 0; i < instances.Length; i++)
{
instances[i].mesh = this.triangles[i].GetComponent<MeshFilter>().mesh;
instances[i].transform = this.triangles[i].GetComponent<MeshRenderer>().transform.localToWorldMatrix;
}
for (int i = 0; i < this.triangles.Count; i++)
{
Destroy(this.triangles[i]);
}
Mesh m = new Mesh();
m.CombineMeshes(instances, true, true);
UnityEditor.MeshUtility.Optimize(m);
this.meshFilter.mesh = m;
this.meshCollider.sharedMesh = m;
this.meshRenderer.enabled = true;
this.meshCollider.enabled = true;
}
}
if (this.normal != Vector3.zero)
{
Debug.DrawRay(this.pos, this.normal * 10f, Color.red);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace QuixelTest.ExtrudeAssignment
{
public class MeshOperation2 : BasicMeshOperations
{
// Update is called once per frame
public override void Update()
{
base.Update();
if ((!Input.GetKey(KeyCode.LeftControl) | !Input.GetKey(KeyCode.RightAlt)) & Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100f))
{
this.pos = hit.transform.position;
this.normal = hit.normal;
GameObject G = Instantiate(this.meshFilter.gameObject);
G.transform.position = this.meshFilter.transform.position + (hit.normal / (20f - this.extrusionSenstivity));
G.transform.rotation = this.meshFilter.transform.rotation;
//return;
List<GameObject> list = new List<GameObject>();
list.Add(this.meshFilter.gameObject);
list.Add(G);
CombineInstance[] instances = new CombineInstance[2];
for (int i = 0; i < instances.Length; i++)
{
instances[i].mesh = list[i].GetComponent<MeshFilter>().mesh;
instances[i].transform = list[i].GetComponent<MeshRenderer>().transform.localToWorldMatrix;
}
for (int i = 1; i < list.Count; i++)
{
Destroy(list[i]);
}
Mesh m = new Mesh();
m.CombineMeshes(instances, true, true);
this.meshFilter.GetComponent<MeshCollider>().sharedMesh = m;
this.meshFilter.mesh = m;
}
}
if (this.normal != Vector3.zero)
{
Debug.DrawRay(this.pos, this.normal * 10f, Color.red);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Xml;
using System.IO;
namespace QuixelTest.SubtractionShaderAssignment
{
public class XMLReader : MonoBehaviour
{
public TextAsset xmlFile;
public Texture2D texture1, texture2;
public RenderTexture renderTexture1, renderTexture2;
public SimpleDelegate OnTexturesLoaded;
private byte[] textureData1, textureData2;
[SerializeField] private string Data;
public Button button;
private void OnEnable()
{
this.OnTexturesLoaded += this.TexturesLoaded;
}
public void LoadData()
{
this.ParseData(this.xmlFile.text);
}
void TexturesLoaded()
{
if (this.button)
{
this.button.interactable = true;
}
Debug.Log("Textures Loaded Successfully");
}
/// <summary>
/// Loading the Data from the given xml
/// </summary>
/// <param name="data"></param>
public void ParseData(string data)
{
string textureLinkFormat = "//Textures/Texture";
XmlDocument xml = new XmlDocument();
xml.Load(new StringReader(data));
XmlNodeList list = xml.SelectNodes(textureLinkFormat);
this.texture1 = new Texture2D(1024, 1024);
this.texture2 = new Texture2D(1024, 1024);
string tex1 = Application.dataPath + list[0].InnerText;
string tex2 = Application.dataPath + list[1].InnerText;
if (File.Exists(tex1))
this.textureData1 = File.ReadAllBytes(tex1);
if (File.Exists(tex2))
this.textureData2 = File.ReadAllBytes(tex2);
this.texture1.LoadImage(this.textureData1);
this.texture2.LoadImage(this.textureData2);
Graphics.Blit(this.texture1, this.renderTexture1);
Graphics.Blit(this.texture2, this.renderTexture2);
this.OnTexturesLoaded();
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace QuixelTest.ExtrudeAssignment
{
public class HUD : MonoBehaviour
{
public static HUD instance;
public Slider lightSlider;
public void Toggle_BtnEvent()
{
if (BasicMeshOperations.instance)
BasicMeshOperations.instance.CreateCube();
}
public void LoadMenuScene()
{
UtilMethods.BackToMenu();
}
private void Awake()
{
instance = this;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace QuixelTest.ExtrudeAssignment
{
public class BasicMeshOperations : MonoBehaviour
{
public static BasicMeshOperations instance;
public MeshFilter meshFilter;
public MeshRenderer meshRenderer;
public MeshCollider meshCollider;
public Light directionalLight;
[Range(20f, 100)]
public float senstivity = 10f;
[Range(0.1f, 5f)]
public float extrusionSenstivity = 1f;
protected Vector3 normal = Vector3.zero;
protected Vector3 pos = Vector3.zero;
public virtual void Awake()
{
instance = this;
}
public virtual void Start()
{
this.CreateCube();
this.SetDirectionalLightValue();
}
public virtual void CreateCube()
{
if (this.meshFilter)
Destroy(this.meshFilter.gameObject);
GameObject G = GameObject.CreatePrimitive(PrimitiveType.Cube);
G.name = "T";
this.meshFilter = G.GetComponent<MeshFilter>();
this.meshRenderer = G.GetComponent<MeshRenderer>();
if (this.meshRenderer.GetComponent<BoxCollider>())
DestroyImmediate(this.meshRenderer.GetComponent<BoxCollider>());
this.meshCollider = G.AddComponent<MeshCollider>();
}
public void SetDirectionalLightValue()
{
if (this.directionalLight)
{
this.directionalLight.intensity = HUD.instance.lightSlider.value;
}
}
public virtual void Update()
{
if (this.directionalLight)
{
this.directionalLight.intensity += this.senstivity * Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime;
this.directionalLight.intensity = Mathf.Clamp(this.directionalLight.intensity, HUD.instance.lightSlider.minValue, HUD.instance.lightSlider.maxValue);
HUD.instance.lightSlider.value = this.directionalLight.intensity;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public delegate void SimpleDelegate();
namespace QuixelTest.SubtractionShaderAssignment
{
public class UtilityMethods : MonoBehaviour
{
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UtilMethods : MonoBehaviour
{
public static void BackToMenu()
{
UnityEngine.SceneManagement.SceneManager.LoadScene(Constants.MENUSCENE);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace QuixelTest.CircleShaderAssignment
{
public class UIHUDController : MonoBehaviour
{
public Slider radius, BGWidth, FGWidth;
public MeshRenderer circle;
public string Radius, BackgroundCutoff, ForegroundCutoff;
private void Start()
{
this.radius.value = this.circle.material.GetFloat(this.Radius);
this.BGWidth.value = this.circle.material.GetFloat(this.BackgroundCutoff);
this.FGWidth.value = this.circle.material.GetFloat(this.ForegroundCutoff);
}
public void LoadBackMenu()
{
UtilMethods.BackToMenu();
}
public void SetValue(int i)
{
string attribute = "";
float value = 0;
attribute = i == 1 ? this.ForegroundCutoff : i == 2 ? this.BackgroundCutoff : this.Radius;
value = i == 1 ? this.FGWidth.value : i == 2 ? this.BGWidth.value : this.radius.value;
this.circle.material.SetFloat(attribute, value);
}
}
} | c57d000368c5d3fd44740c87a12dea739cdd7792 | [
"C#"
] | 11 | C# | HadidAli/QuixelAssignmentProject | 5a33607400ebe7e8f76fe3b1be615f788e9f3f97 | 9c960369305dd905c7947849b34eff743d3293c8 |
refs/heads/master | <repo_name>megharastogi/cf-whiteboard<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :http_authenticate if Rails.env == "production"
def http_authenticate
authenticate_or_request_with_http_basic do |username, password|
username == "codefellows" && password == "<PASSWORD>"
end
end
end
<file_sep>/app/models/question.rb
class Question < ActiveRecord::Base
has_many :comments
validates_presence_of :title, :user_name, :company
accepts_nested_attributes_for :comments
attr_accessible :title, :user_name, :company, :job_title
end
<file_sep>/app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create_comment
@question = Question.find_by_id(params[:question_id])
@comment = Comment.new(:content => params[:content],:user_name => params[:user_name],:question_id => @question.id)
if @comment.save
redirect_to question_path(@question.id)
else
render :template => "questions/show"
end
end
end
<file_sep>/spec/requests/question_comments_spec.rb
require 'spec_helper'
describe "QuestionComments" do
end
<file_sep>/app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :question
validates_presence_of :content, :user_name, :question_id
attr_accessible :content, :user_name, :question_id
end
<file_sep>/spec/factories/comment.rb
FactoryGirl.define do
factory :valid_comment do
id '1'
content 'some content'
user_name 'user_name'
question_id '1'
end
factory :invalid_comment do
id '1'
content 'some content'
user_name ''
question_id ''
end
end<file_sep>/spec/models/question_spec.rb
require 'spec_helper'
describe Question do
it "should give an error if title is blank" do
question = Question.create(:title => "")
question.should_not be_valid
question.errors[:title].include?("can't be blank")
end
it "should give an error if username is blank" do
question = Question.create(:title => "some title" , :user_name => "")
question.should_not be_valid
question.errors[:user_name].include?("can't be blank")
end
it "should give an error if company is blank" do
question = Question.create(:title => "some content" , :user_name => "test_user", :company => nil)
question.should_not be_valid
question.errors[:company].include?("can't be blank")
end
it "should let user create question if title,username and company is present" do
question = Question.create(:title => "some content" , :user_name => "test_user", :company => "abcd")
question.should be_valid
end
end
<file_sep>/spec/factories/question.rb
FactoryGirl.define do
factory :valid_question do
id '1'
title 'some content'
user_name 'user_name'
company 'abcd'
job_title 'test'
end
end<file_sep>/spec/models/comment_spec.rb
require 'spec_helper'
describe Comment do
it "should give an error if content is blank" do
comment = Comment.create(:content => "")
comment.should_not be_valid
comment.errors[:content].include?("can't be blank")
end
it "should give an error if username is blank" do
comment = Comment.create(:content => "some content" , :user_name => "")
comment.should_not be_valid
comment.errors[:user_name].include?("can't be blank")
end
it "should give an error if question_id is blank" do
comment = Comment.create(:content => "some content" , :user_name => "test_user", :question_id => nil)
comment.should_not be_valid
comment.errors[:question_id].include?("can't be blank")
end
it "should let user create comment if content,username and question_id is present" do
comment = Comment.create(:content => "some content" , :user_name => "test_user", :question_id => 1)
comment.should be_valid
end
end
<file_sep>/spec/controllers/comments_controller_spec.rb
require 'spec_helper'
describe CommentsController do
before(:all) do
Comment.delete_all
end
it "not let user create invalid comment for an existing question" do
@question = Question.create(:title =>"some title",:user_name => "user",:company => "abcd")
post :create_comment ,:question_id => @question.id,:content =>""
@question.comments.size == 0
end
it " let user create comment for an existing question" do
@question = Question.create(:title =>"some title",:user_name => "user",:company => "abcd")
post :create_comment ,:question_id => @question.id, :content =>"some content",:user_name => "user_name",:company => "abcd"
@question.comments.size == 1
response.should redirect_to(question_path(@question))
end
end
<file_sep>/app/controllers/questions_controller.rb
class QuestionsController < ApplicationController
WillPaginate.per_page = 10
def index
@questions = Question.page(params[:page]).order("created_at DESC")
end
def show
@question = Question.find_by_id(params[:id])
end
def new
@question = Question.new
@comment = Comment.new
end
def edit
@question = Question.find_by_id(params[:id])
end
def create
params_comment = params[:question].delete(:comment)
@question = Question.new(params[:question])
if @question.save
unless params_comment[:content].blank?
@comment = @question.comments.build(:content => params_comment[:content], :user_name => params[:question][:user_name])
@comment.save
end
redirect_to questions_path
else
render :action => "new"
end
end
def update
@question = Question.find_by_id(params[:id])
if @question.update_attributes(params[:question])
redirect_to questions_path
else
render :action => "edit"
end
end
end
| 9ed90a6fd38f309c668892adf8b5d5cd205d8466 | [
"Ruby"
] | 11 | Ruby | megharastogi/cf-whiteboard | b69b16ee66fd48d4905dff243c2e77c16535d134 | 9e795b9a4c2b4f0937da262b796616e941403a93 |
refs/heads/master | <file_sep>/*
* 主に、文字に関して管理するクラス
* - サークルの文字を渡す
* - イベントが発生したサークルの文字に対するキーコードを発行する
* - 発行したキーコードで入力を行う
*/
using AiRiM_Beta;
using System;
using System.Runtime.InteropServices;
namespace Component
{
class ManageKeys
{
public const int KEYEVENTF_KEYUP = 0x02; //Key up flag
public const int VK_SHIFT = 0x10; //Left Control key code
static MainWindow mw;
static output o = new output();
static string[,] Chars;
static string[] Chars_0 = new string[150];
static string[] Chars_1 = new string[150];
static string[] Chars_2 = new string[150];
static int[] Chars_index = new int[10];
string[] CircleLabels = new string[6];
int i = 0;
// 初期処理
public ManageKeys(MainWindow mwl)
{
mw = mwl;
CSVInport ci = new CSVInport();
Chars = ci.getCSV("Other/chars_v1.csv");
int i = 0;
while (i < Chars.GetLength(0))
{
/*
* TODO
* Charsを2次元配列に
*/
Chars_0[i] = Chars[i, 0];
Chars_1[i] = Chars[i, 1];
Chars_2[i] = Chars[i, 2];
o.t(i + " | " + Chars_0[i] + " : " + Chars_1[i] + " : " + Chars_2[i]);
i++;
}
getCharsIndex();
}
// 文字からキーコードを取得
private static void getCharsIndex()
{
if ((Chars_index[0] = Array.IndexOf(Chars_0, "en_index")) != -1)
Console.WriteLine("English index of : " + Chars_index[0]);
else
Console.WriteLine("not such English index");
if ((Chars_index[1] = Array.IndexOf(Chars_0, "jp_index")) != -1)
Console.WriteLine("Japanese index of : " + Chars_index[1]);
else
Console.WriteLine("not such index");
}
// キーコードを実行
[DllImport("user32.dll")]
private static extern uint keybd_event(byte bVk, byte bScan, uint dwFlags, UIntPtr dwExtraInfo);
private void ime_switch()
{
byte VK_KANJI = 0x19;
byte VK_MENU = 0x12;
keybd_event(VK_MENU, 0 /* 0x38 */, 0, (UIntPtr)0); /* down Alt */
keybd_event(VK_KANJI, 0 /* 0x29 */, 0, (UIntPtr)0); /* down Kanji */
keybd_event(VK_MENU, 0 /* 0x38 */, KEYEVENTF_KEYUP, (UIntPtr)0); /* up Alt */
keybd_event(VK_KANJI, 0 /* 0x29 */, KEYEVENTF_KEYUP, (UIntPtr)0); /* up Kanji */
}
private void keybd(int add)
{
if (Chars_0[add] == "")
{
Console.WriteLine("Not found chars");
return;
}
if (add != 0)
{
/*
* ToDo
* ,が入力できない
*/
if (Chars_1[add] == "shift")
{
Console.WriteLine("mode of shift");
keybd_event(0xA0, 0xAA, 0, (UIntPtr)0);
keybd_event((byte)Int32.Parse(Chars_2[add], System.Globalization.NumberStyles.HexNumber), 0x9E, 0, (UIntPtr)0);
keybd_event((byte)Int32.Parse(Chars_2[add], System.Globalization.NumberStyles.HexNumber), 0x9E, KEYEVENTF_KEYUP, (UIntPtr)0);
keybd_event(0xA0, 0xAA, KEYEVENTF_KEYUP, (UIntPtr)0);
}
else
{
// 子音などが存在する場合のみ押下
if (Chars_1[add] != "")
keybd_event((byte)Int32.Parse(Chars_1[add], System.Globalization.NumberStyles.HexNumber), 0, 0, (UIntPtr)0);
keybd_event((byte)Int32.Parse(Chars_2[add], System.Globalization.NumberStyles.HexNumber), 0, 0, (UIntPtr)0);
}
}
else
Console.WriteLine("not found key code : " + Chars_0[add]);
}
// 文字を入力
public void inputKey(string index)
{
if (index == "ime")
{
ime_switch();
}
else if ((i = Array.IndexOf(Chars_0, index)) != -1)
{
Console.WriteLine("such key : " + Chars_0[i]);
keybd(i);
}
else
{
Console.WriteLine("no such key code : " + i);
}
}
// 子音別の表示文字取得
public string[] getCircleKeyString(int mode)
{
for (int i = 0; i < 5; i++)
CircleLabels[i] = Chars_0[Chars_index[mw.lang] + 1 + mode * 25 + i * 5];
return CircleLabels;
}
// 母音別の表示文字取得
public string[] getCircleKeyString(int mode, int label)
{
for (int i = 0; i < 5; i++)
CircleLabels[i] = Chars_0[Chars_index[mw.lang] + 1 + mode * 25 + label * 5 + i];
return CircleLabels;
}
// 子音表示での子ラベルの文字列を返す67
public string[] getCircleChildrenKeyString(int mode)
{
string[] Childrens = new string[30];
int ArgsStart = Chars_index[mw.lang];
int[] hoge = new int[6];
int k = 0;
for (int i = 0; i < 5; i++)
{
for(int j = 1; j < 5; j++)
{
//Console.WriteLine(k + " : " + Chars_0[Chars_index[mw.lang] + 1 + mode * 25 + i * 5 + j]);
Childrens[k++] = Chars_0[Chars_index[mw.lang] + 1 + mode * 25 + i * 5 + j];
}
}
return Childrens;
}
}
}
<file_sep>/*
* 主に画面に対するWindowの処理を行う
* - 画面の高さや幅を指定された値で割って返す
* - 指定したサイズにAiRiMを拡大縮小する
*/
using AiRiM_Beta;
using System.Windows;
namespace Component
{
public class Window_Resizing
{
MainWindow mw;
double ScreenHight = SystemParameters.WorkArea.Height;
double ScreenWidth = SystemParameters.WorkArea.Width;
// 初期処理
public Window_Resizing(MainWindow mwl)
{
mw = mwl;
double size = WindowHeightCalc(1);
mw.Left = WindowWidthCalc(1) - size;
mw.Height = size;
mw.Width = size;
mw.Top = 0;
}
// 画面の高さをnで割って返す
public double WindowHeightCalc(double n)
{
return ScreenHight / n;
}
// 画面の幅をnで割って返す
public double WindowWidthCalc(double n)
{
return ScreenWidth / n;
}
// 指定したサイズにAiRiMの大きさを変更する
public void ChangeWindowSize(int s)
{
mw.ResizeMode = ResizeMode.CanResizeWithGrip;
mw.Height = s;
mw.MinHeight = s;
mw.MaxHeight = s;
mw.Width = s;
mw.MinWidth = s;
mw.MaxWidth = s;
mw.Show();
}
}
}
<file_sep>using AiRiM_Beta;
using Leap;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace Component
{
class LeapMousePoint
{
MainWindow mw;
Animations ani;
output o = new output();
Controller leap = new Controller();
Frame frame;
static bool FingerStatus = true;
static bool stopingStatus = false;
static int xBasePoint = 960;
static int xMagnif = 8;
static int yBasePoint = 1400;
static int yMagnif = 5;
float x;
float y;
public LeapMousePoint(MainWindow mwl)
{
mw = mwl;
ani = new Animations(mw);
leap.SetPolicyFlags(Controller.PolicyFlag.POLICYBACKGROUNDFRAMES);
}
private void leapBase()
{
frame = leap.Frame();
//leap.EnableGesture(Gesture.GestureType.TYPEKEYTAP);
//leap.EnableGesture(Gesture.GestureType.TYPECIRCLE);
foreach (Pointable pointable in leap.Frame().Pointables)
{
if (!pointable.IsExtended)
continue;
}
}
public void leapTaskManage()
{
Task MouseControlTask = new Task(() =>
{
while (true)
Control_Mouse();
});
Task GrowingFingerTask = new Task(() =>
{
while (true)
GrowingFinger();
});
Task ClickCheckTask = new Task(() =>
{
while (true)
ClickCheck();
});
CompositionTarget.Rendering += checkGesture;
MouseControlTask.Start();
ClickCheckTask.Start();
//GrowingFingerTask.Start();
}
private void GrowingFinger()
{
leapBase();
if (frame.Fingers[0].Type == Finger.FingerType.TYPE_THUMB)
FingerStatus = true;
else
FingerStatus = false;
}
float Finger_Index_y;
bool Finger_Click_flag = false;
private void ClickCheck()
{
var syncObject = new object();
bool Click_Lock_Token = false;
try
{
Monitor.TryEnter(syncObject, ref Click_Lock_Token);
leapBase();
Finger_Index_y = frame.Fingers[1].Bone(Bone.BoneType.TYPE_PROXIMAL).NextJoint.y - frame.Fingers[1].Bone(Bone.BoneType.TYPE_DISTAL).PrevJoint.y;
if (Finger_Index_y > 5)
{
if (!Finger_Click_flag)
{
mouse_event(MOUSEEVENTF_LEFT_DOWN, 0, 0, 0, 0);
Console.WriteLine("Mouse Down");
}
Finger_Click_flag = true;
}
else
{
if (Finger_Click_flag)
{
mouse_event(MOUSEEVENTF_LEFT_UP, 0, 0, 0, 0);
Console.WriteLine("Mouse Up");
}
Finger_Click_flag = false;
}
}
finally
{
if (Click_Lock_Token)
Monitor.Exit(syncObject);
}
}
private void checkGesture(object sender, EventArgs e)
{
leapBase();
//int Finger_Count = 0;
//float Finger_Distance_z;
//foreach (var finger in frame.Fingers)
//{
// Finger_Distance_z = finger.Bone(Bone.BoneType.TYPE_PROXIMAL).PrevJoint.z - finger.Bone(Bone.BoneType.TYPE_DISTAL).PrevJoint.z;
// if(Finger_Distance_z > 0)
// Finger_Count++;
//}
//Console.WriteLine(Finger_Count);
//if (Finger_Count < 5)
// return;
GestureList gestures = frame.Gestures();
for (int i = 0; i < gestures.Count; i++)
{
Gesture gesture = gestures[i];
if (gesture.Type == Gesture.GestureType.TYPEKEYTAP)
{
KeyTapGesture keytap = new KeyTapGesture(gesture);
Console.WriteLine(keytap.Progress.ToString());
mouse_event(MOUSEEVENTF_LEFT_DOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFT_UP, 0, 0, 0, 0);
return;
}
else if (gesture.Type == Gesture.GestureType.TYPECIRCLE)
{
CircleGesture circle = new CircleGesture(gesture);
float Circle_Size = float.Parse(circle.Radius.ToString());
if (Circle_Size > 40)
{
if (circle.Pointable.Direction.AngleTo(circle.Normal) <= Math.PI / 2)
{
ani.open_animetion();
ani.out_animetion();
}
else
{
ani.retun_animetion();
ani.close_animetion();
}
}
}
else if (gesture.Type == Gesture.GestureType.TYPESCREENTAP)
{
mouse_event(MOUSEEVENTF_LEFT_DOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFT_UP, 0, 0, 0, 0);
return;
}
}
}
//private void checkGesture()
//{
// o.t("running");
// // 定義
// // **************************************************************************************************
// // **************************************************************************************************
// /*
// * i/j : カウント用
// * finger_distance_base1/2 : 隣の指との距離の基準(親指と中指/中指と小指)
// * two_finger_distance_x/y : 隣の指との距離(親指と人差し指/人差し指と中指/etc)
// * DISTANCE_Goo_BaseX/Y : グーのときの指の距離の判定基準
// * angle_z_base : グーのときの指の角度の判定基準
// * Thumb_angle_z_base : 親指の角度の基準(z軸)
// * Finger_Point_x/y : 指先のの座標
// * FInger_Direction_x/y/z : 指先の角度
// */
// int i = 0, j = 0;
// int finger_distance_base1 = 50, finger_distance_base2 = 40;
// int two_finger_distance_x = 0, two_finger_distance_y = 0;
// int DISTANCE_Goo_BaseX = 20, DISTANCE_Goo_BaseY = 20;
// int angle_z_base = -40, angle_y_base = 0;
// int Thumb_angle_z_base = 0, Other_angle_z_base = -20;
// int[] Finger_Point_x = new int[5];
// int[] Finger_Point_y = new int[5];
// int[] Finger_Direction_x = new int[5];
// int[] Finger_Direction_y = new int[5];
// int[] Finger_Direction_z = new int[5];
// int angle_y, angle_z;
// int Thumb_angle_z, Other_angle_z;
// double finger_distance_1 = 0, finger_distance_2 = 0;
// double THUMBx = 0, THUMBy = 0;
// double MIDDLEx = 0, MIDDLEy = 0;
// //グーの判定フラグの初期化
// bool DistanceBool = false;
// bool DistanceBool2 = false;
// bool DistanceBool3 = false;
// for (i = 0; i < 5; i++)
// {
// // LewapMotionからの値取得
// // 上から、指の座標(x,y)/指の向き(x,y,z)
// Finger_Point_x[i] = (int)frame.Fingers[i].StabilizedTipPosition.x;
// Finger_Point_y[i] = (int)frame.Fingers[i].StabilizedTipPosition.y;
// Finger_Direction_x[i] = (int)(frame.Fingers[i].Direction.x * 100);
// Finger_Direction_y[i] = (int)(frame.Fingers[i].Direction.y * 100);
// Finger_Direction_z[i] = (int)(frame.Fingers[i].Direction.z * 100);
// o.t("Finger(" + i + ") x:" + Finger_Direction_x[i] + "| y:" + Finger_Direction_y[i] + "| z:" + Finger_Direction_z[i]);
// }
// i = 0; // 使用後の初期化
// //角度y,zを変数に
// angle_y = Finger_Direction_y[j + 1];
// angle_z = Finger_Direction_z[j];
// Thumb_angle_z = Finger_Direction_z[0];
// Other_angle_z = Finger_Direction_z[i + 1];
// // 親指と中指の距離を変数へ a
// THUMBx = Math.Pow(Finger_Point_x[2] - Finger_Point_x[0], 2);//2乗
// THUMBy = Math.Pow(Finger_Point_y[2] - Finger_Point_y[0], 2);
// finger_distance_1 = (System.Math.Sqrt(THUMBx + THUMBy));
// // 中指と小指の距離を変数へ b
// MIDDLEx = Math.Pow(Finger_Point_x[4] - Finger_Point_x[2], 2);//2乗
// MIDDLEy = Math.Pow(Finger_Point_y[4] - Finger_Point_y[2], 2);
// finger_distance_2 = (System.Math.Sqrt(MIDDLEx + MIDDLEy));
// o.t(finger_distance_1 + finger_distance_2);
// // 判定
// // **************************************************************************************************
// // **************************************************************************************************
// //パーの処理
// if (finger_distance_1 > finger_distance_base1 & finger_distance_2 > finger_distance_base2)
// DistanceBool3 = true;
// else
// DistanceBool3 = false;
// if (DistanceBool3 == true)
// {
// // Console.WriteLine("per");
// DistanceBool3 = false;
// }
// else
// {
// o.t("Unknow");
// }
//}
private const int MOUSEEVENTF_LEFT_DOWN = 0x2;
private const int MOUSEEVENTF_LEFT_UP = 0x4;
[DllImport("User32.dll")]
private static extern bool SetCursorPos(int X, int Y);
[DllImport("User32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
private void Control_Mouse()
{
leapBase();
if(FingerStatus)
{
x = frame.Fingers[0].StabilizedTipPosition.x;
y = frame.Fingers[0].StabilizedTipPosition.y;
x = x * xMagnif + xBasePoint;
y = (float)((y * yMagnif - yBasePoint) * -1);
o.t("x : " + x + " | y : " + y);
if (x != xBasePoint && y != yBasePoint * -1)
{
SetCursorPos((int)x, (int)y);
o.t("Hnads Hovering.");
stopingStatus = false;
}
else
{
if (stopingStatus == false)
{
o.t("Stopping. Please it finger hovering.");
stopingStatus = true;
}
}
}
}
}
}
<file_sep>using System;
using System.Windows;
using System.Windows.Media.Animation;
using Component;
namespace AiRiM_Beta
{
class Animations
{
MainWindow mw;
//初期処理
public Animations(MainWindow lmw)
{
mw = lmw;
hidden_All();
Storyboard CircleShrinking1 = (Storyboard)mw.Resources["CircleShrinking1"];
Storyboard textShrinking1 = (Storyboard)mw.Resources["textShrinking1"];
Storyboard SenterAnimetionS = (Storyboard)mw.Resources["SenterAnimetionS"];
SenterAnimetionS.Begin();
CircleShrinking1.Begin();
textShrinking1.Begin();
}
//AiRiMを隠す
private void hidden_All()
{
hidden_Circles();
hidden_labels();
mw.el.Visibility = Visibility.Hidden;
}
// 子ラベルを隠す
public void hidden_labels()
{
mw.LabelChildren_01.Visibility = Visibility.Hidden;
mw.LabelChildren_02.Visibility = Visibility.Hidden;
mw.LabelChildren_03.Visibility = Visibility.Hidden;
mw.LabelChildren_04.Visibility = Visibility.Hidden;
mw.LabelChildren_11.Visibility = Visibility.Hidden;
mw.LabelChildren_12.Visibility = Visibility.Hidden;
mw.LabelChildren_13.Visibility = Visibility.Hidden;
mw.LabelChildren_14.Visibility = Visibility.Hidden;
mw.LabelChildren_21.Visibility = Visibility.Hidden;
mw.LabelChildren_22.Visibility = Visibility.Hidden;
mw.LabelChildren_23.Visibility = Visibility.Hidden;
mw.LabelChildren_24.Visibility = Visibility.Hidden;
mw.LabelChildren_31.Visibility = Visibility.Hidden;
mw.LabelChildren_32.Visibility = Visibility.Hidden;
mw.LabelChildren_33.Visibility = Visibility.Hidden;
mw.LabelChildren_34.Visibility = Visibility.Hidden;
mw.LabelChildren_41.Visibility = Visibility.Hidden;
mw.LabelChildren_42.Visibility = Visibility.Hidden;
mw.LabelChildren_43.Visibility = Visibility.Hidden;
mw.LabelChildren_44.Visibility = Visibility.Hidden;
}
// 子ラベルを出す
public void Show_labels()
{
mw.LabelChildren_01.Visibility = Visibility.Visible;
mw.LabelChildren_02.Visibility = Visibility.Visible;
mw.LabelChildren_03.Visibility = Visibility.Visible;
mw.LabelChildren_04.Visibility = Visibility.Visible;
mw.LabelChildren_11.Visibility = Visibility.Visible;
mw.LabelChildren_12.Visibility = Visibility.Visible;
mw.LabelChildren_13.Visibility = Visibility.Visible;
mw.LabelChildren_14.Visibility = Visibility.Visible;
mw.LabelChildren_21.Visibility = Visibility.Visible;
mw.LabelChildren_22.Visibility = Visibility.Visible;
mw.LabelChildren_23.Visibility = Visibility.Visible;
mw.LabelChildren_24.Visibility = Visibility.Visible;
mw.LabelChildren_31.Visibility = Visibility.Visible;
mw.LabelChildren_32.Visibility = Visibility.Visible;
mw.LabelChildren_33.Visibility = Visibility.Visible;
mw.LabelChildren_34.Visibility = Visibility.Visible;
mw.LabelChildren_41.Visibility = Visibility.Visible;
mw.LabelChildren_42.Visibility = Visibility.Visible;
mw.LabelChildren_43.Visibility = Visibility.Visible;
mw.LabelChildren_44.Visibility = Visibility.Visible;
}
//サークルを隠す
public void hidden_Circles()
{
// すでに非表示されていれば実行しない
if (mw.ClearCircle0.Visibility.ToString() == "Hidde")
{
Console.WriteLine("circle hidden");
return;
}
mw.CircleParent01.Visibility = Visibility.Hidden;
mw.CircleParent02.Visibility = Visibility.Hidden;
mw.CircleParent03.Visibility = Visibility.Hidden;
mw.CircleParent04.Visibility = Visibility.Hidden;
mw.CircleParent05.Visibility = Visibility.Hidden;
mw.BaseCircle0.Visibility = Visibility.Hidden;
mw.BaseCircle1.Visibility = Visibility.Hidden;
mw.BaseCircle2.Visibility = Visibility.Hidden;
mw.BaseCircle3.Visibility = Visibility.Hidden;
mw.BaseCircle4.Visibility = Visibility.Hidden;
mw.ClearCircle0.Visibility = Visibility.Hidden;
mw.ClearCircle1.Visibility = Visibility.Hidden;
mw.ClearCircle2.Visibility = Visibility.Hidden;
mw.ClearCircle3.Visibility = Visibility.Hidden;
mw.ClearCircle4.Visibility = Visibility.Hidden;
}
//サークルを出す
public void Visible_Circles()
{
// すでに表示されていれば実行しない
if(mw.ClearCircle0.Visibility.ToString() == "Visible")
{
Console.WriteLine("circle visibled");
return;
}
mw.CircleParent01.Visibility = Visibility.Visible;
mw.CircleParent02.Visibility = Visibility.Visible;
mw.CircleParent03.Visibility = Visibility.Visible;
mw.CircleParent04.Visibility = Visibility.Visible;
mw.CircleParent05.Visibility = Visibility.Visible;
mw.BaseCircle0.Visibility = Visibility.Visible;
mw.BaseCircle1.Visibility = Visibility.Visible;
mw.BaseCircle2.Visibility = Visibility.Visible;
mw.BaseCircle3.Visibility = Visibility.Visible;
mw.BaseCircle4.Visibility = Visibility.Visible;
mw.ClearCircle0.Visibility = Visibility.Visible;
mw.ClearCircle1.Visibility = Visibility.Visible;
mw.ClearCircle2.Visibility = Visibility.Visible;
mw.ClearCircle3.Visibility = Visibility.Visible;
mw.ClearCircle4.Visibility = Visibility.Visible;
}
//サークルを出すアニメーション
public void out_animetion()
{
// 中心が非表示もしくはサークルが表示であれば実行しない
if (mw.el.Visibility.ToString() == "Hidden" || mw.ClearCircle0.Visibility.ToString() == "Visible")
{
Console.WriteLine("hidden el or circle visibled");
return;
}
Storyboard textExpansion1 = (Storyboard)mw.Resources["textExpansion1"];
//出すアニメーション読み込み
Storyboard CircleExpansion1 = (Storyboard)mw.Resources["CircleExpansion1"];
//出す
CircleExpansion1.Begin();
textExpansion1.Begin();
Visible_Circles();
}
//サークルを隠すアニメーション
public void retun_animetion()
{
// サークルが非表示であれば実行しない
if (mw.ClearCircle0.Visibility.ToString() == "Hidden")
{
Console.WriteLine("hidden Circles");
return;
}
//透明のサークルを消す
mw.ClearCircle0.Visibility = Visibility.Hidden;
mw.ClearCircle1.Visibility = Visibility.Hidden;
mw.ClearCircle2.Visibility = Visibility.Hidden;
mw.ClearCircle3.Visibility = Visibility.Hidden;
mw.ClearCircle4.Visibility = Visibility.Hidden;
//テキストを戻すアニメーションの読み込み
Storyboard textShrinking1 = (Storyboard)mw.Resources["textShrinking1"];
//隠すアニメーションの読み込み
Storyboard CircleShrinking1 = (Storyboard)mw.Resources["CircleShrinking1"];
//隠す
CircleShrinking1.Begin();
textShrinking1.Begin();
}
//中心を出すアニメーション
public void open_animetion()
{
// 中心が表示であれば実行しない
if (mw.el.Visibility.ToString() == "Visible")
{
Console.WriteLine("visible el");
return;
}
mw.el.Visibility = Visibility.Visible;
Storyboard SenterAnimetionS = (Storyboard)mw.Resources["SenterAnimetionS"];
SenterAnimetionS.Begin();
}
//中心を隠すアニメーション
public void close_animetion()
{
// 中心が非表示であれば実行しない
if (mw.el.Visibility.ToString() == "Hidden" | mw.ClearCircle0.Visibility.ToString() == "Visible")
{
Console.WriteLine("hidden el");
return;
}
Storyboard SenterAnimetionE = (Storyboard)mw.Resources["SenterAnimetionE"];
SenterAnimetionE.Begin();
}
}
}
<file_sep>/*
* 主にサークルのラベルに文字を表示する
* - あかさたななどの子音別の表示
* - あいうえおなどの母音別の表示
*/
/*
*マウスエンターごとに表示を変更するのではなく、その都度show hiddenを繰り返す
*/
using AiRiM_Beta;
using System.Windows;
using System;
namespace Component
{
class Circle
{
private MainWindow mw;
private ManageKeys mk;
private string[] CircleLabel = new string[6];
private int flag_roop = 0;
// 初期処理
public Circle(MainWindow mwl, int mode)
{
mw = mwl;
mk = new ManageKeys(mw);
ChangeLabelText(mode);
hiddenLabelChildren(-1);
}
// 子音別の表示
public void ChangeLabelText(int CircleMode)
{
CircleLabel = mk.getCircleKeyString(CircleMode);
mw.CircleParent01.Content = CircleLabel[0];
mw.CircleParent02.Content = CircleLabel[1];
mw.CircleParent03.Content = CircleLabel[2];
mw.CircleParent04.Content = CircleLabel[3];
mw.CircleParent05.Content = CircleLabel[4];
ChangeLabelChildrenText(CircleMode, -1);
}
// 母音別の表示
public void ChangeLabelText(int CircleMode, int ViewLabel)
{
CircleLabel = mk.getCircleKeyString(CircleMode, ViewLabel);
mw.CircleParent01.Content = CircleLabel[0];
mw.CircleParent02.Content = CircleLabel[1];
mw.CircleParent03.Content = CircleLabel[2];
mw.CircleParent04.Content = CircleLabel[3];
mw.CircleParent05.Content = CircleLabel[4];
}
public void showLabelChildren(int Circle_Number)
{
if (Circle_Number == -1)
{
flag_roop = 0;
for (; flag_roop < 5; flag_roop++)
showLabelChildren(flag_roop);
}
else
{
switch (Circle_Number)
{
case 0:
mw.LabelChildren_01.Visibility = Visibility.Visible;
mw.LabelChildren_02.Visibility = Visibility.Visible;
mw.LabelChildren_03.Visibility = Visibility.Visible;
mw.LabelChildren_04.Visibility = Visibility.Visible;
break;
case 1:
mw.LabelChildren_11.Visibility = Visibility.Visible;
mw.LabelChildren_12.Visibility = Visibility.Visible;
mw.LabelChildren_13.Visibility = Visibility.Visible;
mw.LabelChildren_14.Visibility = Visibility.Visible;
break;
case 2:
mw.LabelChildren_21.Visibility = Visibility.Visible;
mw.LabelChildren_22.Visibility = Visibility.Visible;
mw.LabelChildren_23.Visibility = Visibility.Visible;
mw.LabelChildren_24.Visibility = Visibility.Visible;
break;
case 3:
mw.LabelChildren_31.Visibility = Visibility.Visible;
mw.LabelChildren_32.Visibility = Visibility.Visible;
mw.LabelChildren_33.Visibility = Visibility.Visible;
mw.LabelChildren_34.Visibility = Visibility.Visible;
break;
case 4:
mw.LabelChildren_41.Visibility = Visibility.Visible;
mw.LabelChildren_42.Visibility = Visibility.Visible;
mw.LabelChildren_43.Visibility = Visibility.Visible;
mw.LabelChildren_44.Visibility = Visibility.Visible;
break;
}
}
}
public void hiddenLabelChildren(int Circle_Number)
{
if (Circle_Number == -1)
{
for (; flag_roop < 5; flag_roop++)
hiddenLabelChildren(flag_roop);
}
else
{
switch (Circle_Number)
{
case 0:
mw.LabelChildren_01.Visibility = Visibility.Hidden;
mw.LabelChildren_02.Visibility = Visibility.Hidden;
mw.LabelChildren_03.Visibility = Visibility.Hidden;
mw.LabelChildren_04.Visibility = Visibility.Hidden;
break;
case 1:
mw.LabelChildren_11.Visibility = Visibility.Hidden;
mw.LabelChildren_12.Visibility = Visibility.Hidden;
mw.LabelChildren_13.Visibility = Visibility.Hidden;
mw.LabelChildren_14.Visibility = Visibility.Hidden;
break;
case 2:
mw.LabelChildren_21.Visibility = Visibility.Hidden;
mw.LabelChildren_22.Visibility = Visibility.Hidden;
mw.LabelChildren_23.Visibility = Visibility.Hidden;
mw.LabelChildren_24.Visibility = Visibility.Hidden;
break;
case 3:
mw.LabelChildren_31.Visibility = Visibility.Hidden;
mw.LabelChildren_32.Visibility = Visibility.Hidden;
mw.LabelChildren_33.Visibility = Visibility.Hidden;
mw.LabelChildren_34.Visibility = Visibility.Hidden;
break;
case 4:
mw.LabelChildren_41.Visibility = Visibility.Hidden;
mw.LabelChildren_42.Visibility = Visibility.Hidden;
mw.LabelChildren_43.Visibility = Visibility.Hidden;
mw.LabelChildren_44.Visibility = Visibility.Hidden;
break;
}
}
}
// 子ラベル管理
public void ChangeLabelChildrenText(int CircleMode, int Circle_Number)
{
string[] LabelChildrens = new string[32];
LabelChildrens = mk.getCircleChildrenKeyString(CircleMode);
if (Circle_Number == -1)
{
for (; flag_roop < 5; flag_roop++)
ChangeLabelChildrenText(CircleMode, flag_roop);
}
else
{
Console.WriteLine(Circle_Number);
switch (Circle_Number)
{
case 0:
mw.LabelChildren_01.Content = LabelChildrens[0];
mw.LabelChildren_02.Content = LabelChildrens[1];
mw.LabelChildren_03.Content = LabelChildrens[2];
mw.LabelChildren_04.Content = LabelChildrens[3];
break;
case 1:
mw.LabelChildren_11.Content = LabelChildrens[4];
mw.LabelChildren_12.Content = LabelChildrens[5];
mw.LabelChildren_13.Content = LabelChildrens[6];
mw.LabelChildren_14.Content = LabelChildrens[7];
break;
case 2:
mw.LabelChildren_21.Content = LabelChildrens[8];
mw.LabelChildren_22.Content = LabelChildrens[9];
mw.LabelChildren_23.Content = LabelChildrens[10];
mw.LabelChildren_24.Content = LabelChildrens[11];
break;
case 3:
mw.LabelChildren_31.Content = LabelChildrens[12];
mw.LabelChildren_32.Content = LabelChildrens[13];
mw.LabelChildren_33.Content = LabelChildrens[14];
mw.LabelChildren_34.Content = LabelChildrens[15];
break;
case 4:
mw.LabelChildren_41.Content = LabelChildrens[16];
mw.LabelChildren_42.Content = LabelChildrens[17];
mw.LabelChildren_43.Content = LabelChildrens[18];
mw.LabelChildren_44.Content = LabelChildrens[19];
break;
}
}
}
}
}<file_sep>using Component;
using Microsoft.Expression.Shapes;
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Animation;
namespace AiRiM_Beta
{
public partial class MainWindow : Window
{
private ManageKeys mk;
private Circle cicl;
private Animations ani;
private Window_Resizing ws;
private LeapMousePoint lm;
private bool StandbyChar;
private int CircleMode = 0;
private int i_lb;
private Brush BeforColor;
private Brush AfterColor;
public int lang = 1;
// 初期処理
public MainWindow()
{
InitializeComponent();
mk = new ManageKeys(this);
lm = new LeapMousePoint(this);
cicl = new Circle(this, CircleMode);
ani = new Animations(this);
ws = new Window_Resizing(this);
lm.leapTaskManage();
StandbyChar = false;
AfterColor = new SolidColorBrush(Color.FromArgb(250, 192, 226, 240));
}
// 中心円に触れたとき
private void el_MouseEnter(object sender, MouseEventArgs e)
{
// Console.Beep(3000, 300);
if (StandbyChar)
{
switch (i_lb)
{
case 0:
Console.WriteLine(i_lb + CircleParent01.Content.ToString());
mk.inputKey(CircleParent01.Content.ToString());
break;
case 1:
Console.WriteLine(i_lb + CircleParent02.Content.ToString());
mk.inputKey(CircleParent02.Content.ToString());
break;
case 2:
Console.WriteLine(i_lb + CircleParent03.Content.ToString());
mk.inputKey(CircleParent03.Content.ToString());
break;
case 3:
Console.WriteLine(i_lb + CircleParent04.Content.ToString());
mk.inputKey(CircleParent04.Content.ToString());
break;
case 4:
Console.WriteLine(i_lb + CircleParent05.Content.ToString());
mk.inputKey(CircleParent05.Content.ToString());
break;
}
StandbyChar = false;
}
cicl.ChangeLabelText(CircleMode);
}
public int getMode()
{
return CircleMode;
}
private int getObjectNumber(object sender, int num)
{
var lb = (Arc)sender;
string s_lb = lb.Name.ToString();
return int.Parse(s_lb[num].ToString());
}
// 各サークルに触れたとき
private void label_MouseEnter(object sender, MouseEventArgs e)
{
var lb = (Arc)sender;
i_lb = getObjectNumber(sender, 11);
BeforColor = lb.Fill;
// 背景色変更
switch (i_lb)
{
case 0:
BeforColor = BaseCircle0.Fill;
BaseCircle0.Fill = AfterColor;
break;
case 1:
BeforColor = BaseCircle1.Fill;
BaseCircle1.Fill = AfterColor;
break;
case 2:
BeforColor = BaseCircle2.Fill;
BaseCircle2.Fill = AfterColor;
break;
case 3:
BeforColor = BaseCircle3.Fill;
BaseCircle3.Fill = AfterColor;
break;
case 4:
BeforColor = BaseCircle4.Fill;
BaseCircle4.Fill = AfterColor;
break;
}
if (!StandbyChar)
{
cicl.ChangeLabelText(CircleMode, i_lb);
StandbyChar = true;
}
String Arc = ((Arc)sender).Name;
Arc targetArc = BaseCircle0;
Storyboard EnterTextAnimetion1 = (Storyboard)this.Resources["EnterTextAnimetion1"];
Storyboard EnterTextAnimetion2 = (Storyboard)this.Resources["EnterTextAnimetion2"];
Storyboard EnterTextAnimetion3 = (Storyboard)this.Resources["EnterTextAnimetion3"];
Storyboard EnterTextAnimetion4 = (Storyboard)this.Resources["EnterTextAnimetion4"];
Storyboard EnterTextAnimetion5 = (Storyboard)this.Resources["EnterTextAnimetion5"];
Storyboard EnterChildren_ani01 = (Storyboard)this.Resources["EnterChildren_ani01"];
Storyboard EnterChildren_ani11 = (Storyboard)this.Resources["EnterChildren_ani11"];
Storyboard EnterChildren_ani21 = (Storyboard)this.Resources["EnterChildren_ani21"];
Storyboard EnterChildren_ani31 = (Storyboard)this.Resources["EnterChildren_ani31"];
Storyboard EnterChildren_ani41 = (Storyboard)this.Resources["EnterChildren_ani41"];
if (Arc == "ClearCircle0") { targetArc = BaseCircle0; EnterTextAnimetion1.Begin(); EnterChildren_ani01.Begin(); }
else if (Arc == "ClearCircle1") { targetArc = BaseCircle1; EnterTextAnimetion2.Begin(); EnterChildren_ani11.Begin(); }
else if (Arc == "ClearCircle2") { targetArc = BaseCircle2; EnterTextAnimetion3.Begin(); EnterChildren_ani21.Begin(); }
else if (Arc == "ClearCircle3") { targetArc = BaseCircle3; EnterTextAnimetion4.Begin(); EnterChildren_ani31.Begin(); }
else if (Arc == "ClearCircle4") { targetArc = BaseCircle4; EnterTextAnimetion5.Begin(); EnterChildren_ani41.Begin(); }
else { targetArc = BaseCircle0; }
Storyboard EnterAnimetion = (Storyboard)this.Resources["EnterAnimetion"];
foreach (var child in EnterAnimetion.Children)
{
Storyboard.SetTarget(child, targetArc);
}
EnterAnimetion.Begin();
}
// 各サークルを離れたとき
private void label_MouseLeave(object sender, MouseEventArgs e)
{
Arc targetArc = BaseCircle0;
String Arc = ((Arc)sender).Name;
Storyboard LeaveTextAnimetion1 = (Storyboard)this.Resources["LeaveTextAnimetion1"];
Storyboard LeaveTextAnimetion2 = (Storyboard)this.Resources["LeaveTextAnimetion2"];
Storyboard LeaveTextAnimetion3 = (Storyboard)this.Resources["LeaveTextAnimetion3"];
Storyboard LeaveTextAnimetion4 = (Storyboard)this.Resources["LeaveTextAnimetion4"];
Storyboard LeaveTextAnimetion5 = (Storyboard)this.Resources["LeaveTextAnimetion5"];
Storyboard leaveChildren_ani01 = (Storyboard)this.Resources["leaveChildren_ani01"];
Storyboard leaveChildren_ani11 = (Storyboard)this.Resources["leaveChildren_ani11"];
Storyboard leaveChildren_ani21 = (Storyboard)this.Resources["leaveChildren_ani21"];
Storyboard leaveChildren_ani31 = (Storyboard)this.Resources["leaveChildren_ani31"];
Storyboard leaveChildren_ani41 = (Storyboard)this.Resources["leaveChildren_ani41"];
if (Arc == "ClearCircle0") { targetArc = BaseCircle0; LeaveTextAnimetion1.Begin(); leaveChildren_ani01.Begin(); }
else if (Arc == "ClearCircle1") { targetArc = BaseCircle1; LeaveTextAnimetion2.Begin(); leaveChildren_ani11.Begin(); }
else if (Arc == "ClearCircle2") { targetArc = BaseCircle2; LeaveTextAnimetion3.Begin(); leaveChildren_ani21.Begin(); }
else if (Arc == "ClearCircle3") { targetArc = BaseCircle3; LeaveTextAnimetion4.Begin(); leaveChildren_ani31.Begin(); }
else if (Arc == "ClearCircle4") { targetArc = BaseCircle4; LeaveTextAnimetion5.Begin(); leaveChildren_ani41.Begin(); }
else targetArc = BaseCircle0;
Storyboard LeaveAnimetion = (Storyboard)this.Resources["LeaveAnimetion"];
foreach (var child in LeaveAnimetion.Children)
{
Storyboard.SetTarget(child, targetArc);
}
LeaveAnimetion.Begin();
// 背景色変更
switch (i_lb)
{
case 0:
BaseCircle0.Fill = BeforColor;
break;
case 1:
BaseCircle1.Fill = BeforColor;
break;
case 2:
BaseCircle2.Fill = BeforColor;
break;
case 3:
BaseCircle3.Fill = BeforColor;
break;
case 4:
BaseCircle4.Fill = BeforColor;
break;
}
}
// サークルの表示を変更する
private void ChangeMode(object sender, RoutedEventArgs e)
{
labelAniBefore();
}
private void change_Completed(object sender, EventArgs e)
{
toggleMode();
labelAniAfter();
}
private void toggleMode()
{
if (CircleMode < 1)
CircleMode++;
else
CircleMode = 0;
cicl.ChangeLabelText(CircleMode);
//後ろの数字のサークルの子ラベルだけ変わる
for(int i = 0; i < 5; i++)
cicl.ChangeLabelChildrenText(CircleMode, i);
}
private void labelAniBefore()
{
Storyboard change_labelBefore = (Storyboard)Resources["change_labelBefore"];
change_labelBefore.Begin();
}
private void labelAniAfter()
{
Storyboard change_labelAfter = (Storyboard)Resources["change_labelAfter"];
change_labelAfter.Begin();
}
// 言語を変更する
private void Lang_Change(object sender, RoutedEventArgs e)
{
lang_before();
}
private void change()
{
if (lang == 1)
lang = 0;
else
lang++;
cicl.ChangeLabelText(CircleMode);
//後ろの数字のサークルの子ラベルだけ変わる
cicl.ChangeLabelChildrenText(CircleMode, 0);
cicl.ChangeLabelChildrenText(CircleMode, 1);
cicl.ChangeLabelChildrenText(CircleMode, 2);
cicl.ChangeLabelChildrenText(CircleMode, 3);
cicl.ChangeLabelChildrenText(CircleMode, 4);
}
private void lang_before()
{
Storyboard Lang_ChangeBefore = (Storyboard)Resources["Lang_ChangeBefore"];
Lang_ChangeBefore.Begin();
}
private void lang_after()
{
Storyboard Lang_ChangeAfter = (Storyboard)Resources["Lang_ChangeAfter"];
Lang_ChangeAfter.Begin();
}
private void lang_change_comp(object sender, EventArgs e)
{
change();
lang_after();
}
[ComVisible(true)]
[DllImport("user32.dll")]
private static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
private const int GWL_EXSTYLE = -20;
private const int WS_EX_NOACTIVATE = 0x08000000;
// 開く ボタンをおした時 中心円を表示
private void open_animetion(object sender, RoutedEventArgs e)
{
ani.open_animetion();
}
// 閉じる ボタンをおした時 中心円を非表示
private void close_animetion(object sender, RoutedEventArgs e)
{
ani.close_animetion();
}
// 出す ボタンをおした時 サークルを表示
private void out_Click(object sender, RoutedEventArgs e)
{
ani.out_animetion();
}
// 戻る ボタンをおした時 サークルを非表示
private void retun_Click(object sender, RoutedEventArgs e)
{
ani.retun_animetion();
}
//周囲のサークルが出終わったら
private void Circle_Completed(object sender, EventArgs e)
{
}
// サークルの開くアニメーションが終了したとき
private void CircleOpenAnimation_Comp(object sender, EventArgs e)
{
}
// サークルの閉じるアニメーションが終了したとき
private void CircleCloseAnimation_Comp(object sender, EventArgs e)
{
ani.hidden_Circles();
cicl.hiddenLabelChildren(-1);
}
// 中心円の閉じるアニメーションが終了したとき
private void ElCloseAnimation_Comp(object sender, EventArgs e)
{
el.Visibility = Visibility.Hidden;
}
// ドラッグ許可
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
try
{
DragMove();
}
catch { }
}
// 子ラベル判定
private void LabelChildrenJudge(int Circle_Number)
{
cicl.ChangeLabelChildrenText(Circle_Number, CircleMode);
}
private void meLabelChildrenJudge(object sender, MouseEventArgs e)
{
int Circle_Number = getObjectNumber(sender, 7);
cicl.showLabelChildren(Circle_Number);
}
private void mlLabelChildrenJudge(object sender, MouseEventArgs e)
{
int Circle_Number = getObjectNumber(sender, 7);
cicl.hiddenLabelChildren(Circle_Number);
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AiRiM_Beta
{
class output
{
public void t(string s)
{
//Console.WriteLine(s);
}
public void t(int s)
{
//Console.WriteLine(s.ToString());
}
public void t(double s)
{
//Console.WriteLine(s.ToString());
}
}
}
<file_sep># AiRiM_Beta
AiRiMのベータ
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace AiRiM_Settings
{
class XMLInport
{
public XMLInport(string xmlFILE)
{
try
{
XmlTextReader xtr = new XmlTextReader(xmlFILE);
while (xtr.Read())
{
switch (xtr.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + xtr.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine(xtr.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + xtr.Name);
Console.WriteLine(">");
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
| bbef5b40719c152522aa13c70997524af3ed4cca | [
"Markdown",
"C#"
] | 9 | C# | YSE2016-HW/AiRiM_Beta | 30d1d3405db2417f6a3373665cad379abc5b4f17 | feb857061884f2065a1fbbcf4336d3686a94f842 |
refs/heads/main | <repo_name>Shohrat-Code/P222-58.23.11.2021-View-model-Front-to-back<file_sep>/ViewModel/ViewModel/Models/Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ViewModel.Models
{
public class Student
{
public int Id{ get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public byte Age{ get; set; }
public string Email{ get; set; }
public string Phone { get; set; }
}
}
<file_sep>/ViewModel/ViewModel/Models/Group.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ViewModel.Models
{
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public string Room { get; set; }
public byte StudentCount { get; set; }
}
}
<file_sep>/ViewModel/ViewModel/ViewModels/VmAcademy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ViewModel.Models;
namespace ViewModel.ViewModels
{
public class VmAcademy
{
public List<Student> Students { get; set; }
public List<Group> Groups { get; set; }
}
}
<file_sep>/ViewModel/ViewModel/Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using ViewModel.Models;
using ViewModel.ViewModels;
namespace ViewModel.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
//ViewBag
//ViewData
//TempData
//ViewModel
#region Student list
Student student1 = new Student()
{
Id = 1,
Name = "Rasim",
Surname = "Quliyev",
Age = 25,
Email = "<EMAIL>",
Phone = "6516316"
};
Student student2 = new Student()
{
Id = 2,
Name = "Qasim",
Surname = "Abbasov",
Age = 25,
Email = "<EMAIL>",
Phone = "345316"
};
Student student3 = new Student()
{
Id = 3,
Name = "Toofiq",
Surname = "Quliyev",
Age = 25,
Email = "<EMAIL>",
Phone = "3567547"
};
List<Student> students = new List<Student>();
students.Add(student1);
students.Add(student2);
students.Add(student3);
#endregion
#region Group list
Group group1 = new Group() { Id = 1, Name = "P222", Room = "Titan", StudentCount = 9 };
Group group2 = new Group() { Id = 2, Name = "P319", Room = "Titan", StudentCount = 15 };
Group group3 = new Group() { Id = 3, Name = "P114", Room = "Yupiter", StudentCount = 16 };
List<Group> groups = new List<Group>();
groups.Add(group1);
groups.Add(group2);
groups.Add(group3);
#endregion
VmAcademy model = new VmAcademy();
model.Students = students;
model.Groups = groups;
return View(model);
}
}
}
| 890511f58d2d2be83a7814cd335ca1c06e5172dc | [
"C#"
] | 4 | C# | Shohrat-Code/P222-58.23.11.2021-View-model-Front-to-back | e186c3e9033ad7e41916d4e1420d1a41c8219e29 | d2a36b6c664d812294b406b38ef54c9b328e9855 |
refs/heads/master | <repo_name>hangsa/mediaRes<file_sep>/medias/R/medias.R
# Hello, world!
#
# This is an example function named 'hello'
# which prints 'Hello, world!'.
#
# You can learn more about package authoring with RStudio at:
#
# http://r-pkgs.had.co.nz/
#
# Some useful keyboard shortcuts for package authoring:
#
# Install Package: 'Ctrl + Shift + B'
# Check Package: 'Ctrl + Shift + E'
# Test Package: 'Ctrl + Shift + T'
transTon <- function(field, id_name){#transform id to name
refiel <- str_replace_na(field)
ln = nrow(id_name)
for(i in 1:ln){
id = id_name[[1]][i]
ide = str_c('(?<=\\|)', id, '(?=\\|)')
refiel = str_replace_all(refiel, ide, id_name[[2]][i])
}
return(refiel)
}
wipeValid <- function(field, tags){
refiel <- str_replace_na(field)
tlen <- length(tags)
for(i in 1:tlen){
tg = str_c('\\|', tags[i], '\\|')
refiel = str_replace_all(refiel, tg, '|')
}
refiel = str_replace_all(refiel, '(?<![0-9])\\|(?![0-9])', '')
return(refiel)
}
wipeValid_f <- function(fields, tags, fgenr, tgenr, rgenr){##fields and tags all have attribute fstlvlname
#fgenr, genre of fields need to wipe off;
#tgenr, genre of tags to wipe fields
#rgenr, restrict genre
rg = tags[[rgenr]] %>% unique
fields[[fgenr]] = str_replace_na(fields[[fgenr]])
for(r in rg){
utg <- tags %>% filter(.data[[rgenr]] == r) %>% `[[`(tgenr)
fields <- fields %>% mutate(.data[[fgenr]] = ifelse(.data[[rgenr]] == r,
wipeValid()))
}
}
| 339b305864ba4591e45ff75c81a1880af2f5f182 | [
"R"
] | 1 | R | hangsa/mediaRes | 6ec1f076622a9450491cd62ee56d67aaa573f0ac | e1f02ae5b3cb3d11b70763e4ee904734ef77dff0 |
refs/heads/master | <repo_name>samantha212/solo_express<file_sep>/README.md
# solo_express
In-Class Assignment - 1/7/16
Practice using Express and Node.js. Return a random account balance when button is clicked.
<file_sep>/modules/combine.js
/**
* Created by samanthamusselman on 1/5/16.
*/
var random = require('./randomNumber');
var toUSD = require('./toUSD');
var kitty = function(){
return toUSD(random(100, 1000000));
};
exports.randomDollar = kitty;
exports.text = 'Account balance: \n';
<file_sep>/static/scripts.js
/**
* Created by samanthamusselman on 1/6/16.
*/
$(document).ready(function(){
$('.get').on('click', function(event){
event.preventDefault();
console.log("Yupper do!");
addInfo();
})
});
function addInfo(){
$.ajax('/balance').then(function(response){
$('.balance').html(response);
});
}; | e60f93ce680fa4219c894f04dba277ce5973b4ec | [
"Markdown",
"JavaScript"
] | 3 | Markdown | samantha212/solo_express | 4f8e1889c9643e5231dbfe763cec63e24e97636e | 6dd7c408471805d69526790edf08274bd2c97f0d |
refs/heads/master | <repo_name>cagdasgithub/fullscript<file_sep>/src/Components/UI/Grid/PhotoGrid.js
import Photo from "../../Photo/Photo";
import Grid from "@material-ui/core/Grid";
import React from "react";
const PhotoGrid = props => {
return props.data ? (
<Grid container spacing={24} style={{ padding: 24 }}>
{props.data.photos.map(photo => (
<Grid item xs={12} sm={6} lg={4} xl={3} key={photo.id}>
<Photo key={photo.id} photo={photo} />
</Grid>
))}
</Grid>
) : null;
};
export default PhotoGrid;
<file_sep>/src/TestUtils/Hooks.js
//This function is created to test hooks, because custom hooks are
//not supported on testing libraries
import React from "react";
function HookWrapper(props) {
const hook = props.hook ? props.hook() : undefined;
return <div hook={hook} />;
}
export default HookWrapper;
<file_sep>/src/Utils/FormValidation.test.js
import validate from "./FormValidation";
describe("validation should work as intended", () => {
it("should handle empty text", () => {
const values = { email: "", password: "", text: "" };
const errors = validate(values);
expect(errors.email).toBe("Email address is required");
expect(errors.password).toBe("Password is required");
expect(errors.text).toBe("Text is required");
});
it("it should set an error if email is invalid", () => {
const values = { email: "cagdas" };
const errors = validate(values);
expect(errors.email).toBe("Email address is invalid");
});
it("it should set an error if password is invalid", () => {
const values = { password: "<PASSWORD>" };
const errors = validate(values);
expect(errors.password).toBe("Password must be 8 or more characters");
});
it("should work if password is longer than 8 chars", () => {
const values = { password: "<PASSWORD>" };
const errors = validate(values);
expect(errors.password).toBe("");
});
it("should work if email is correct", () => {
const values = { email: "<EMAIL>" };
const errors = validate(values);
expect(errors.email).toBe("");
});
});
<file_sep>/src/Components/UI/SearchControl/SearchControl.test.js
import React from "react";
import renderer from "react-test-renderer";
import {
render,
fireEvent,
cleanup
} from "react-testing-library";
import SearchControl from "./SearchControl";
afterEach(cleanup);
describe("Tests for Search controls", () => {
it("renders correctly", () => {
const queryHandle = jest.fn();
const loading = false;
const photoRendered = renderer
.create(
<SearchControl updateQueryHandle={queryHandle} isLoading={loading} />
)
.toJSON();
expect(photoRendered).toMatchSnapshot();
});
it("calls back right amount of times", () => {
const queryHandle = jest.fn();
const loading = false;
const { getByLabelText } = render(
<SearchControl updateQueryHandle={queryHandle} isLoading={loading} />
);
const searchInput = getByLabelText(/Search Query/i);
fireEvent.change(searchInput, { target: { value: "a" } });
expect(queryHandle).toHaveBeenCalledTimes(1);
fireEvent.change(searchInput, { target: { value: "ab" } });
expect(queryHandle).toHaveBeenCalledTimes(2);
});
it("calls back with right values on search by typing", () => {
const queryHandle = jest.fn(x => x);
const loading = false;
const { getByLabelText } = render(
<SearchControl updateQueryHandle={queryHandle} isLoading={loading} />
);
const searchInput = getByLabelText(/Search Query/i);
fireEvent.change(searchInput, { target: { value: "cagdas" } });
expect(queryHandle).toBeCalledWith("cagdas");
});
it("calls back with right values on search by clicking button", () => {
const queryHandle = jest.fn(x => x);
const loading = false;
const { getByDisplayValue, getByLabelText, getByText } = render(
<SearchControl updateQueryHandle={queryHandle} isLoading={loading} />
);
const switchButton = getByDisplayValue(/immediateSearch/i);
fireEvent.click(switchButton);
const searchInput = getByLabelText(/Search Query/i);
fireEvent.change(searchInput, { target: { value: "cagdas" } });
fireEvent.click(getByText("Search"));
expect(queryHandle).toHaveBeenLastCalledWith("cagdas");
});
});
<file_sep>/src/Views/EmailForm/EmailForm.js
import React from "react";
import { withStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";
import useForm from "../../CustomHooks/useForm";
import validate from "../../Utils/FormValidation";
const styles = theme => ({
textField: {
marginLeft: theme.spacing.unit,
marginRight: theme.spacing.unit,
width: 200
},
dense: {
marginTop: 19
},
menu: {
width: 200
}
});
const EmailForm = props => {
const { classes } = props;
const { values, errors, handleChange, handleSubmit } = useForm(
props.submitForm,
validate
);
return (
<React.Fragment>
<Grid container direction="column" justify="center" alignItems="center">
<Grid item>
<TextField
error={errors.text !== ""}
id="standard-name"
label="Your Name"
name="text"
className={classes.textField}
value={values.text || ""}
onChange={handleChange}
margin="normal"
variant="outlined"
helperText={errors.text}
/>
</Grid>
<Grid item>
<TextField
error={errors.email !== ""}
id="standard-name"
label="Email"
name="email"
className={classes.textField}
value={values.email || ""}
onChange={handleChange}
margin="normal"
variant="outlined"
helperText={errors.email}
/>
</Grid>
<Grid item>
<TextField
error={errors.password !== ""}
id="standard-name"
label="Password"
name="password"
className={classes.textField}
value={values.password || ""}
onChange={handleChange}
margin="normal"
variant="outlined"
helperText={errors.password}
/>
</Grid>
<Grid item>
<Button variant="contained" color="secondary" onClick={handleSubmit}>
Email this photo
</Button>
</Grid>
</Grid>
</React.Fragment>
);
};
export default withStyles(styles)(EmailForm);
<file_sep>/src/Components/Photo/Photo.test.js
import React from "react";
import renderer from "react-test-renderer";
import Photo from "./Photo";
it("renders correctly", () => {
const photo = {
id: "1",
urls: { regular: "www.google.com" },
links: { download: "www.google.com" },
description: "test",
user: { name: "Cagdas", location: "Ottawa" }
};
const photoRendered = renderer.create(<Photo photo={photo} />).toJSON();
expect(photoRendered).toMatchSnapshot();
});
<file_sep>/src/Components/Photo/Photo.js
import React, { useState } from "react";
import Button from "@material-ui/core/Button";
import Modal from "../UI/Modal/Modal";
import EmailForm from "../../Views/EmailForm/EmailForm";
import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import ButtonBase from "@material-ui/core/ButtonBase";
import { withStyles } from "@material-ui/core/styles";
import Fab from "@material-ui/core/Fab";
import Icon from "@material-ui/core/Icon";
const styles = theme => ({
root: {
flexGrow: 1
},
image: {
width: 256,
height: 256
},
fab: {
margin: theme.spacing.unit * 1.1
},
img: {
margin: "auto",
display: "block",
maxWidth: "100%",
maxHeight: "100%"
}
});
const Photo = ({
photo: {
id,
urls: { regular },
links: { download },
description,
user: { name, location }
},
classes
}) => {
const [openModal, setOpenModal] = useState(false);
const handleEmailClick = () => {
setOpenModal(true);
};
const handleModalClose = () => {
setOpenModal(false);
};
const handleEmailSend = () => {
setOpenModal(false);
};
return (
<React.Fragment>
<Grid item>
<ButtonBase className={classes.image} >
<img className={classes.img} alt="complex" src={regular} />
</ButtonBase>
</Grid>
<Grid item xs={12} sm container>
<Grid item xs container direction="column" spacing={16}>
<Grid item xs>
<Typography gutterBottom variant="subtitle1">
{description}
</Typography>
<Typography gutterBottom>{name}</Typography>
<Typography color="textSecondary">{location}</Typography>
</Grid>
<Grid item>
<Fab aria-label="Add" href={regular} className={classes.fab}>
<Icon>add</Icon>
</Fab>
<Fab
aria-label="Add"
onClick={handleEmailClick}
className={classes.fab}
>
<Icon>email</Icon>
</Fab>
<Modal open={openModal} onClose={handleModalClose}>
<EmailForm submitForm={handleEmailSend} />
</Modal>
</Grid>
</Grid>
</Grid>
</React.Fragment>
);
};
export default withStyles(styles)(Photo);
<file_sep>/src/Debug/Debug.js
import React from "react";
const Debug = props => {
return <pre>{JSON.stringify(props.value, null, 2)}</pre>;
};
export default Debug;
<file_sep>/src/Components/UI/Grid/PhotoGrid.test.js
import React from "react";
import PhotoGrid from "./PhotoGrid";
import renderer from "react-test-renderer";
import { render, queryAllByAltText, cleanup } from "react-testing-library";
afterEach(cleanup);
describe("Tests for Search controls", () => {
it("renders correctly", () => {
const grid = renderer.create(<PhotoGrid />).toJSON();
expect(grid).toMatchSnapshot();
});
it("shows valid data", () => {
const data = {
photos: [
{
id: "1",
urls: { regular: "small image 1" },
links: { download: "download" },
description: "test",
user: { name: "Cagdas", location: "Ottawa" }
},
{
id: "2",
urls: { regular: "small image 2" },
links: { download: "download" },
description: "test",
user: { name: "Cagdas", location: "Ottawa" }
}
]
};
const { queryAllByAltText } = render(<PhotoGrid data={data} />);
const download = queryAllByAltText(/complex/i);
expect(download.length).toEqual(2);
});
});
<file_sep>/src/Containers/FullScriptContainer.js
//This container shows images depending on the query text
//which is received from SearchControl.js then passes it to PhotoGrid.js
//This is also where we fetch the photos and paging is supported
import React, { useState, useEffect } from "react";
import SearchControl from "../Components/UI/SearchControl/SearchControl";
import PhotoGrid from "../Components/UI/Grid/PhotoGrid";
import Button from "@material-ui/core/Button";
import axios from "axios";
const FullScriptContainer = queryText => {
const [data, setData] = useState({ photos: [] });
const [query, setQuery] = useState(queryText);
const [isLoading, setIsLoading] = useState(false);
const [isSearchSuccessful, setIsSearchSuccessful] = useState(false);
const [pageCount, setPageCount] = useState(1);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
let photos = await axios
.get(
`https://api.unsplash.com/search/photos?page=${pageCount}&query=${query}&client_id=6700cdcba2e1a3935626eae7c2ef92de2b917e8558460025bfd9032db33c2268`
)
.then(res => {
return res.data;
});
setData({ photos: photos.results });
setIsLoading(false);
setIsSearchSuccessful(true);
};
fetchData();
}, [pageCount, query]);
const handleQueryChange = queryText => {
setQuery(queryText);
};
const nextPageHandle = () => {
setPageCount(pageCount + 1);
};
const prevPageHandle = () => {
if (pageCount > 2) setPageCount(pageCount - 1);
};
return (
<React.Fragment>
<SearchControl
updateQueryHandle={handleQueryChange}
isLoading={isLoading}
/>
{isSearchSuccessful ? (
<React.Fragment>
<PhotoGrid data={data} />{" "}
<Button onClick={prevPageHandle}>Previous Page</Button>
<Button onClick={nextPageHandle}>Next Page</Button>
</React.Fragment>
) : (
"No Photos yet"
)}
</React.Fragment>
);
};
export default FullScriptContainer;
<file_sep>/src/CustomHooks/useForm.test.js
import React from "react";
import Enzyme, { shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import useForm from "./useForm";
import HookWrapper from "../TestUtils/Hooks";
import validate from "../Utils/FormValidation";
Enzyme.configure({ adapter: new Adapter() });
describe("useForm", () => {
it("should render", () => {
const myMock = jest.fn();
let wrapper = shallow(
<HookWrapper hook={() => useForm(myMock, validate)} />
);
expect(wrapper.exists()).toBeTruthy();
});
it("should init values as valid", () => {
const myMock = jest.fn();
let wrapper = shallow(
<HookWrapper hook={() => useForm(myMock, validate)} />
);
let { hook } = wrapper.find("div").props();
const { values, errors } = hook;
expect(values.email).toBe("");
expect(values.password).toBe("");
expect(values.text).toBe("");
expect(errors.email).toBe("");
expect(errors.password).toBe("");
expect(errors.text).toBe("");
});
});
it("should handle change", () => {
const myMock = jest.fn();
let wrapper = shallow(<HookWrapper hook={() => useForm(myMock, validate)} />);
let { hook } = wrapper.find("div").props();
let { values, errors, handleChange, handleSubmit } = hook;
const event = {
target: { name: "email", value: "cagdas" },
persist: () => {},
preventDefault: () => {}
};
handleChange(event);
// destructuring objects - {} should be inside brackets - () to avoid syntax error
({ hook } = wrapper.find("div").props());
({ values, errors, handleChange, handleSubmit } = hook);
expect(values.email).toBe("cagdas");
handleSubmit(event);
({ hook } = wrapper.find("div").props());
({ values, errors, handleChange, handleSubmit } = hook);
expect(errors.email).toBe("Email address is invalid");
event.target.value = "<EMAIL>";
handleChange(event);
({ hook } = wrapper.find("div").props());
({ values, errors, handleChange, handleSubmit } = hook);
expect(values.email).toBe("<EMAIL>");
handleSubmit(event);
({ hook } = wrapper.find("div").props());
({ values, errors, handleChange, handleSubmit } = hook);
expect(errors.email).toBe("");
});
<file_sep>/src/Containers/FullScriptContainer.test.js
import React from "react";
import FullScriptContainer from "./FullScriptContainer";
import renderer from "react-test-renderer";
describe("Tests for fullscript container", () => {
it("renders correctly", () => {
const photoRendered = renderer.create(<FullScriptContainer />).toJSON();
expect(photoRendered).toMatchSnapshot();
});
});
| 8be54d358f5edcaf8683a34a2a2eae6e67e1b426 | [
"JavaScript"
] | 12 | JavaScript | cagdasgithub/fullscript | e8b70ddb45c793291036a9ee04e81c49ccdabbc8 | 4e4ea8c2f810ef3249a0c3b63bff602a0a841c3a |
refs/heads/master | <repo_name>GaddamMeghana578/MERN-ApolloStack<file_sep>/README.md
# MERN + Apollo Client + Apollo Server
This is a MERN with Apollo Stack project.
# Description
GraphQL is an open source data querying language that is used for building APIs for web and mobile applications. It is a great replacement for REST and other web service architectures. It allows the client side of the app to get the data in any structure.
But GraphQL is just a query language. And in order to use it easily, we need to use a platform that will do all the heavy lifting for us. One such platform is provided by Apollo.
The Apollo platform is an implementation of GraphQL that can transfer data between the cloud (server) to the UI of your app. In fact, Apollo builds its environment in such a way that we can use it to handle GraphQL on the client as well as the server side of the application.
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
### Prerequisites
You are going to need **Node.js**, **MongoDB** and **npm** or **yarn** installed on your machine.
**Note**: You can either install **MongoDB** locally on your machine or use **MongoDB Atlas**
### Installing
How to properly install and configure this repository to work on your machine.
Cloning the repository
```
git clone ...
```
Enter cloned directory
```
cd MERN-ApolloStack/
```
## Starting the repository on your machine
You will need to run client & server seperately, ports are already configured, make sure you don't conflict them if you change anything.
If you are not using **MongoDBAtlas** then do the below:
Start Mongo server in your project directory
```
cd MERN-ApolloStack
```
```
MERN-ApolloStack/mongod
```
On mac book you need to run
```
MERN-ApolloStack/sudo mongod
```
## Enter Server directory in a new terminal
```
cd MERN-ApolloStack/server
```
Install packages needed
```
MERN-ApolloStack/server/npm install
```
OR
```
MERN-ApolloStack/server/yarn install
```
Start the server
```
MERN-ApolloStack/server/npm start
```
OR
```
MERN-ApolloStack/server/yarn start
```
## Enter Client directory in a new terminal
```
cd MERN-ApolloStack/client
```
Install packages needed
```
MERN-ApolloStack/client/npm install
```
OR
```
MERN-ApolloStack/client/yarn install
```
Run the Application using below command
```
MERN-ApolloStack/client/npm start
```
OR
```
MERN-ApolloStack/client/yarn start
```
Now you can see that **localhost:3000** automatically opens up on your browser and you can use the app
## Built With
- [MongoDB](https://www.mongodb.com/) - No SQL Database
- [Express](https://expressjs.com/) - Node.js web application framework
- [React](https://reactjs.org/) - Frontend/client javascript library
- [Node](https://nodejs.org/en/) - Backend/server framework
- [ApolloStack](https://www.apollographql.com/) - Implementation of GraphQL API
## Project Description
A simple and quick way to get started and going with MERN-ApolloStack application.
## Authors
- **<NAME>** - _MERN-APOLLO Stack project work_ - [LearnMERN](https://github.com/GaddamMeghana578/MERN-ApolloStack)
<file_sep>/client/src/ToDo.js
import React, { Component } from "react";
export default class Todo extends Component {
state = {
name: "",
age: "",
};
handleInputChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
this.setState({ [name]: value });
};
handleSubmitForm = (e) => {
e.preventDefault();
this.props.handleSubmit(this.state, this.props.addUser);
this.setState({ name: "", age: "" });
};
handleCancelForm = (e) => {
e.preventDefault();
this.setState({ name: "", age: "" });
};
render() {
const { age, name } = this.state;
return (
<div className="panel panel-default">
<div className="panel-heading">User Details</div>
<div className="panel-body">
<div className="row">
<div className="form-group col-md-3">
<label htmlFor="name">Name</label>
<input
type="text"
className="form-control"
name="name"
value={name}
id="name"
onChange={(e) => this.handleInputChange(e)}
/>
</div>
</div>
<div className="row">
<div className=" form-group col-md-1">
<label htmlFor="age">Age</label>
<input
type="text"
className="form-control"
name="age"
value={age}
onChange={(e) => this.handleInputChange(e)}
id="age"
/>
</div>
</div>
<div className="form-group col-md-10" style={{ marginLeft: "-1.2%" }}>
<button
className="btn btn-success"
onClick={(e) => this.handleSubmitForm(e)}
>
Submit
</button>
<button
className="btn btn-warning"
onClick={(e) => this.handleCancelForm(e)}
>
Cancel
</button>
</div>
</div>
</div>
);
}
}
<file_sep>/client/src/Table.js
import React, { Component } from "react";
import { gql } from "apollo-boost";
import { Mutation } from "react-apollo";
import _ from "lodash";
const UPDATE_USER = gql`
mutation updateUser($uuid: String!, $input: updateUserInput!) {
updateUser(uuid: $uuid, input: $input) {
name
age
uuid
}
}
`;
const DELETE_USER = gql`
mutation deleteUser($uuid: String!) {
deleteUser(uuid: $uuid) {
name
age
uuid
}
}
`;
export default class Table extends Component {
state = {
userData: {},
name: "",
age: "",
nameChange: false,
ageChange: false,
};
getUserDetails = (e, user) => {
e.preventDefault();
this.setState({ userData: user });
};
handleInputChange = (e) => {
e.preventDefault();
const { name, value } = e.target;
if (name === "age") {
this.setState({ [name]: value, ageChange: true });
} else {
this.setState({ [name]: value, nameChange: true });
}
};
handleSubmit = (e, uuid, updateUser) => {
e.preventDefault();
let userData = {
name: this.state.nameChange ? this.state.name : this.state.userData.name,
age: this.state.ageChange ? this.state.age : this.state.userData.age,
};
const payload = {};
payload.name = userData.name;
payload.age = userData.age;
payload.uuid = uuid;
updateUser({
variables: { uuid: uuid, input: payload },
}).then((res) => {
console.log("data saved successfully", res.data);
this.setState({
name: "",
age: "",
nameChange: false,
ageChange: false,
});
}, console.error);
};
handleDelete = (e, uuid, deleteUser) => {
e.preventDefault();
deleteUser({
variables: { uuid: uuid },
}).then((res) => {
console.log("data saved successfully", res.data);
window.location.reload(true);
}, console.error);
};
handleRefresh = (e) => {
e.preventDefault();
window.location.reload();
};
render() {
var user = this.props.user;
return (
<div>
<ul className="breadcrumb">
{user ? (
<div>
<h3 className="text-center text-danger">Users</h3>
<div className="wrapper">
<span>Showing {user ? user.length : 0} Users</span>
</div>
<br />
<table className="table table-bordered table-striped">
<thead>
<tr>
<th>#</th>
<th>
<b>Name</b>
</th>
<th>
<b>Age</b>
</th>
<th style={{ width: "10%" }}>
<b>Edit/Delete</b>
</th>
</tr>
</thead>
{Object.keys(user).length === 0 &&
user.constructor === Object ? null : (
<tbody>
{_(user)
.orderBy("name", "asc")
.map((user, u) => (
<tr key={u}>
<td>{u}</td>
<td>{user.name}</td>
<td>{user.age}</td>
<td
className="fa fa-pencil fa-lg"
data-toggle="modal"
data-target="#mymodal"
data-dismiss="modal"
name="edit"
onClick={(e) => this.getUserDetails(e, user)}
/>
<td
className="fa fa-trash fa-lg"
data-toggle="modal"
data-target="#deletemodal"
data-dismiss="modal"
onClick={(e) => this.getUserDetails(e, user)}
/>
</tr>
))
.value()}
</tbody>
)}
</table>
</div>
) : null}
<div className="modal fade" id="mymodal">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header bg-warning">
<button
type="button"
className="close"
data-dismiss="modal"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
<h4 className="text-center">UserDetails</h4>
</div>
<div className="modal-body">
<form>
<div className="row">
<div className="form-group col-xs-push-1 col-md-10">
<label htmlFor="name">Name</label>
<input
type="text"
value={
this.state.nameChange
? this.state.name
? this.state.name
: ""
: this.state.userData.name
? this.state.userData.name
: ""
}
className="form-control"
name="name"
id="name"
onChange={(e) => this.handleInputChange(e)}
/>
</div>
</div>
<div className="row">
<div className="form-group col-xs-push-1 col-md-10">
<label htmlFor="age">Age</label>
<input
type="text"
value={
this.state.ageChange
? this.state.age
? this.state.age
: ""
: this.state.userData.age
? this.state.userData.age
: ""
}
className="form-control"
name="age"
id="age"
onChange={(e) => this.handleInputChange(e)}
/>
</div>
</div>
</form>
<Mutation mutation={UPDATE_USER}>
{(updateUser, { loading, error }) => {
if (loading) {
return <div>Loading</div>;
}
if (error) {
return <div>Error</div>;
}
return (
<div className="modal-footer">
<button
className="btn btn-warning"
data-dismiss="modal"
data-toggle="modal"
data-target="#savemodal"
onClick={(e) =>
this.handleSubmit(
e,
this.state.userData.uuid,
updateUser
)
}
>
Save
</button>
</div>
);
}}
</Mutation>
</div>
</div>
</div>
</div>
<div className="modal fade" id="savemodal">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button
type="button"
className="close"
data-dismiss="modal"
aria-label="Close"
onClick={(e) => this.handleRefresh(e)}
>
<span aria-hidden="true">×</span>
</button>
<h3>Welcome</h3>
</div>
<div className="modal-body">
<p>
Registration of '{this.state.userData.name}' is successful
</p>
</div>
</div>
</div>
</div>
<div className="modal fade" id="deletemodal">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button
type="button"
className="close"
data-dismiss="modal"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
<h3>Welcome</h3>
</div>
<div className="modal-body">
<p>
Do you want to delete the user '{this.state.userData.name}'
?{" "}
</p>
</div>
<Mutation mutation={DELETE_USER}>
{(deleteUser, { loading, error }) => {
if (loading) {
return <div>Loading</div>;
}
if (error) {
return <div>Error</div>;
}
return (
<div className="modal-footer">
<button
className="btn btn-success"
data-dismiss="modal"
onClick={(e) =>
this.handleDelete(
e,
this.state.userData.uuid,
deleteUser
)
}
>
Confirm
</button>
</div>
);
}}
</Mutation>
</div>
</div>
</div>
</ul>
</div>
);
}
}
<file_sep>/server/server.js
import express from "express"; // Reference express for middleware
import { ApolloServer, gql } from "apollo-server-express";
import mongoose from "mongoose"; // Helper for communicating with Mongodb.
import User from "./models/userSchema"; // Reference to userSchema.js
// Type definitions define the "shape" of your data and specify
// which ways the data can be fetched from the GraphQL server.
const typeDefs = gql`
type User {
name: String!
age: Int!
uuid: String!
}
type Query {
users: [User!]
user(uuid: String!): User
}
input addUserInput {
name: String!
age: Int!
uuid: String!
}
input updateUserInput {
name: String
age: Int
uuid: String
}
type Mutation {
addUser(input: addUserInput): User
updateUser(uuid: String!, input: updateUserInput): User
deleteUser(uuid: String!): User
}
schema {
query: Query
mutation: Mutation
}
`;
// Resolvers define the technique for fetching the types in the
// schema.
const resolvers = {
Query: {
users: async () => await User.find({}).exec(),
user: async (_, { uuid }) => await User.findOne({ uuid }),
},
Mutation: {
async addUser(_, { input }) {
console.log("Creating User");
return await User.create(input);
},
async updateUser(_, { uuid, input }) {
return await User.findOneAndUpdate({ uuid }, input, { new: true });
},
async deleteUser(_, { uuid }) {
return await User.findOneAndRemove({ uuid });
},
},
};
const server = new ApolloServer({ typeDefs, resolvers });
const app = express();
app.use(express.static(__dirname + "/../client"));
mongoose.Promise = global.Promise;
mongoose
.connect("mongodb://localhost:27017/dev", { useNewUrlParser: true })
.then(() => console.log("MongoDB connected"))
.catch((err) => console.log(err));
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);
<file_sep>/server/models/userSchema.js
import mongoose from "mongoose"; // Helper for communicating with Mongodb.
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
uuid: {
type: String,
required: true,
},
});
export default mongoose.model("User", UserSchema);
<file_sep>/client/src/App.js
import React from "react";
import { gql } from "apollo-boost";
import { Mutation, Query } from "react-apollo";
import ToDo from "./ToDo.js";
import Table from "./Table.js";
const GET_USER = gql`
query {
users {
name
age
uuid
}
}
`;
const ADD_USER = gql`
mutation AddUser($input: addUserInput!) {
addUser(input: $input) {
name
age
uuid
}
}
`;
export default class App extends React.Component {
state = {
user: [],
userDetails: {},
submitted: false,
};
handleSubmit = (user, addUser) => {
var d = new Date().getTime();
var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
/[xy]/g,
function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
}
);
const payload = {};
payload.name = user.name;
payload.age = user.age;
payload.uuid = uuid;
addUser({
variables: { input: payload },
}).then((res) => {
console.log("data saved successfully", res.data);
this.setState({
user: [...this.state.user, res.data.addUser],
submitted: true,
});
}, console.error);
};
render() {
return (
<Query query={GET_USER} fetchPolicy="network-only">
{({ loading, error, data, refetch }) => {
if (loading) {
return <div>Loading</div>;
}
if (error) {
return <div>Error</div>;
}
if (this.state.submitted === true) {
refetch();
}
return (
<Mutation mutation={ADD_USER}>
{(addUser, { loading, error }) => {
if (loading) {
return <div>Loading</div>;
}
if (error) {
return <div>Error</div>;
}
return (
<div>
<ToDo handleSubmit={this.handleSubmit} addUser={addUser} />
<Table user={data.users} />
</div>
);
}}
</Mutation>
);
}}
</Query>
);
}
}
| 73be2dacbbcfb0cadbb355a0ca0e5a6e87f6d5f7 | [
"Markdown",
"JavaScript"
] | 6 | Markdown | GaddamMeghana578/MERN-ApolloStack | c1dd936a6a353728f8be91964a763323504444af | e56cb8277573da7ad4f0803b476c2d998121a132 |
refs/heads/master | <file_sep>using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Scripts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Fabryka_Mebli_IO.Forms.Produkcja
{
public partial class ZakonczForm : Form
{
private ProdukcjaEntities2 db;
private ListBox listBox2;
private Form prev;
private PracownikClass pracownik;
private Timer timer;
public ZakonczForm(ProdukcjaEntities2 db, ListBox listBox,Form prev,PracownikClass pracownik,Timer timer)
{
InitializeComponent();
this.db = db;
this.listBox2 = listBox;
this.prev = prev;
this.pracownik = pracownik;
this.timer = timer;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void takButt_Click(object sender, EventArgs e)
{
string help = listBox2.SelectedItem.ToString();
string[] split = help.Split(' ');
int id = Int32.Parse(split[0]);
var obj = db.ListaMebli_Zamowienie.Where(j => j.id == id).FirstOrDefault();
List<Zamówienie> zam = db.Zamówienie.ToList();
if (pracownik.getStanowisko().Equals("Pilarz"))
{
obj.Status = "Gotowy Do Wiercenia";
}
else if (pracownik.getStanowisko().Equals("Wiertacz"))
{
obj.Status = "Gotowy Do Oklejania";
}
else if (pracownik.getStanowisko().Equals("Oklejacz"))
{
foreach (var x in zam)
{
if (x.idLista == obj.idListy && x.Rodzaj==1)
{
obj.Status = "Gotowy Do Pakowania";
}
if (x.idLista == obj.idListy && x.Rodzaj == 2)
{
obj.Status = "Gotowy Do Montażu";
}
}
}
else if (pracownik.getStanowisko().Equals("Pakowacz") || pracownik.getStanowisko().Equals("Montażysta"))
{
obj.Status = "Gotowy";
}
db.SaveChanges();
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
timer.Start();
this.Close();
prev.Enabled = true;
}
private void ZakonczForm_Load(object sender, EventArgs e)
{
}
private void nieButt_Click(object sender, EventArgs e)
{
timer.Start();
this.Close();
prev.Enabled = true;
}
}
}
<file_sep>using Fabryka_Mebli_IO.Databases;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Fabryka_Mebli_IO.Forms.Produkcja
{
public partial class DodajForm : Form
{
private ProdukcjaEntities2 db;
private ListBox listBox1;
private ListBox listBox2;
private Form prev;
private int idPrac;
private Timer timer;
public DodajForm(ProdukcjaEntities2 db, ListBox listBox1,ListBox listBox2,Form prev,int id,Timer timer)
{
InitializeComponent();
this.db = db;
this.listBox1 = listBox1;
this.listBox2 = listBox2;
this.prev = prev;
this.idPrac = id;
this.timer = timer;
}
private void takButt_Click(object sender, EventArgs e)
{
listBox2.Items.Add(listBox1.SelectedItem);
string help = listBox1.SelectedItem.ToString();
string[] split = help.Split(' ');
int id = Int32.Parse(split[0]);
var obj = db.ListaMebli_Zamowienie.Where(j => j.id == id).FirstOrDefault();
obj.pracownikWykonujacy = idPrac;
obj.Status = "W Realizacji";
db.SaveChanges();
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
timer.Start();
this.Close();
prev.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void nieButt_Click(object sender, EventArgs e)
{
timer.Start();
this.Close();
}
}
}
<file_sep>using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Scripts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Fabryka_Mebli_IO.Forms.MagazynForm.WydanieZewForm
{
public partial class zapytanie : Form
{
Form prev;
Form magazyn;
List<String> list;
ProdukcjaEntities2 db;
public zapytanie(Form prev, Form magazyn, List<String> list)
{
InitializeComponent();
this.prev = prev;
this.magazyn = magazyn;
this.list = list;
db = new ProdukcjaEntities2();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void zapytanie_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button1.Visible = false;
button2.Enabled = false;
button2.Visible = false;
label1.Text = "";
progressBar1.Visible = true;
List<Zamówienie> zm = db.Zamówienie.ToList();
foreach(var x in zm)
{
foreach(var y in list)
{
string[] split = y.Split(' ');
if(x.id == Int32.Parse(split[0]))
{
x.Status = "Wysłany";
}
}
}
db.SaveChanges();
for (int i = 0; i <= 10000; i++)
{
progressBar1.PerformStep();
}
if (progressBar1.Value==100)
{
label1.Text = "Pomyślnie wysłano plik";
button3.Enabled = true;
button3.Visible = true;
}
}
private void button3_Click(object sender, EventArgs e)
{
Nawigacja.mainGUI.Show();
magazyn.Close();
prev.Close();
this.Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Forms;
using Fabryka_Mebli_IO.Scripts;
namespace Fabryka_Mebli_IO
{
public partial class Login_panel : Form
{
public static string stanowisko;
public static string imie;
public Login_panel()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label3_Click(object sender, EventArgs e)
{
}
private void Login_button_Click(object sender, EventArgs e)
{
string login = loginText.Text;
string password = <PASSWORD>;
string stanowisko = comboBox.Text;
Nawigacja.logForm = this;
ProdukcjaEntities2 db = new ProdukcjaEntities2();
var x = db.Pracownicy.Where(y=> y.Login.Equals(login)).FirstOrDefault();
if(x!=null)
{
if (x.Haslo.Equals(password) && x.Stanowisko.Equals(stanowisko))
{
PracownikClass ob = new PracownikClass(x.id,x.Imię,x.Nazwisko,x.Zmiany,x.Stanowisko);
imie = x.Imię.ToString();
Main_GUI m = new Main_GUI(ob);
m.Show();
this.Hide();
}
else
{
MessageBox.Show("Niepoprawna Nazwa użytkownika Lub hasło");
}
}
else
{
MessageBox.Show("Niepoprawna Nazwa użytkownika Lub hasło");
}
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Scripts;
namespace Fabryka_Mebli_IO.Forms.WyświetlPlan
{
public partial class Wyswietl_Plan : Form
{
private PracownikClass pracownik;
public Wyswietl_Plan(PracownikClass pracownik)
{
InitializeComponent();
this.pracownik = pracownik;
}
private void powrotButt_Click(object sender, EventArgs e)
{
Nawigacja.PrevPage.Show();
this.Close();
}
private void Wyswietl_Plan_Load(object sender, EventArgs e)
{
if (pracownik.getZmiana().Equals(1) && !pracownik.getStanowisko().Equals("Kierownik"))
{
plan1.Enabled = true;
plan2.Enabled = false;
}
else if (pracownik.getZmiana().Equals(2) && !pracownik.getStanowisko().Equals("Kierownik"))
{
plan1.Enabled = false;
plan2.Enabled = true;
}
else
{
plan1.Enabled = true;
plan2.Enabled = true;
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void plan1_CheckedChanged(object sender, EventArgs e)
{
ProdukcjaEntities2 db = new ProdukcjaEntities2();
List<Plan_Pracy> plan = db.Plan_Pracy.ToList();
List<ListaMebli_Zamowienie> meble = db.ListaMebli_Zamowienie.ToList();
List<Pracownicy> p = db.Pracownicy.ToList();
if (plan1.Checked)
{
listView1.Items.Clear();
foreach (var x in plan)
{
if (x.idPlanu.Equals(1))
{
foreach (var y in meble)
{
if (y.idListy.Equals(x.Zamówienie.idLista))
{
ListViewItem listViewItem = new ListViewItem(y.Mebel.Nazwa);
//listViewItem.SubItems.Add(y.Mebel.Nazwa);
listViewItem.SubItems.Add(y.Kolor);
listViewItem.SubItems.Add(y.Mebel.Kod_Produktu);
if(y.Status.Equals("W Realizacji"))
{
foreach (var z in p)
{
if(z.id==y.pracownikWykonujacy)
{
string stanowisko = z.Stanowisko;
switch(stanowisko)
{
case "Pilarz" : listViewItem.SubItems.Add("W trakcie Cięcia"); break;
case "Wiertacz" : listViewItem.SubItems.Add("W trakcie Wiercenia"); break;
case "Oklejacz" : listViewItem.SubItems.Add("W trakcie Oklejania"); break;
case "Pakowacz" : listViewItem.SubItems.Add("W trakcie Pakowania"); break;
case "Montażysta": listViewItem.SubItems.Add("W trakcie Montażu"); break;
}
}
}
}else
listViewItem.SubItems.Add(y.Status);
listView1.Items.Add(listViewItem); }
}
}
}
}
}
private void plan2_CheckedChanged(object sender, EventArgs e)
{
ProdukcjaEntities2 db = new ProdukcjaEntities2();
List<Plan_Pracy> plan = db.Plan_Pracy.ToList();
List<ListaMebli_Zamowienie> meble = db.ListaMebli_Zamowienie.ToList();
List<Pracownicy> p = db.Pracownicy.ToList();
if (plan2.Checked)
{
listView1.Items.Clear();
foreach (var x in plan)
{
if (x.idPlanu.Equals(2))
{
foreach (var y in meble)
{
if (y.idListy.Equals(x.Zamówienie.idLista))
{
ListViewItem listViewItem = new ListViewItem(y.Mebel.Nazwa);
//listViewItem.SubItems.Add(y.Mebel.Nazwa);
listViewItem.SubItems.Add(y.Kolor);
listViewItem.SubItems.Add(y.Mebel.Kod_Produktu);
if (y.Status.Equals("W Realizacji"))
{
foreach (var z in p)
{
if (z.id == y.pracownikWykonujacy)
{
string stanowisko = z.Stanowisko;
switch (stanowisko)
{
case "Pilarz": listViewItem.SubItems.Add("W trakcie Cięcia"); break;
case "Wiertacz": listViewItem.SubItems.Add("W trakcie Wiercenia"); break;
case "Oklejacz": listViewItem.SubItems.Add("W trakcie Oklejania"); break;
case "Pakowacz": listViewItem.SubItems.Add("W trakcie Pakowania"); break;
case "Montażysta": listViewItem.SubItems.Add("W trakcie Montażu"); break;
}
}
}
}
else
listViewItem.SubItems.Add(y.Status);
listView1.Items.Add(listViewItem);
}
}
}
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fabryka_Mebli_IO.Forms.StwórzPlanForm;
using Fabryka_Mebli_IO.Forms.WyświetlPlan;
using Fabryka_Mebli_IO.Forms.WydanieZewForm;
using Fabryka_Mebli_IO.Forms.MagazynForm;
using Fabryka_Mebli_IO.Scripts;
using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Forms.Produkcja;
using Fabryka_Mebli_IO.Forms.Przychodzace;
namespace Fabryka_Mebli_IO.Forms
{
public partial class Main_GUI : Form
{
PracownikClass pracownik;
ProdukcjaEntities2 db;
public Main_GUI(PracownikClass ob)
{
InitializeComponent();
this.pracownik = ob;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
}
private void Logout_Click(object sender, EventArgs e)
{
Nawigacja.logForm.Show();
this.Close();
}
private void Main_GUI_Load_1(object sender, EventArgs e)
{
this.label.Text = "Zalogowany jako " + pracownik.getStanowisko()+" "+pracownik.getImie();
Nawigacja.mainGUI = this;
prodButt.Visible = false;
if (pracownik.getStanowisko().Equals("Pilarz") || pracownik.getStanowisko().Equals("Oklejacz") || pracownik.getStanowisko().Equals("Wiertacz") || pracownik.getStanowisko().Equals("Montażysta")|| pracownik.getStanowisko().Equals("Pakowacz"))
{
tworzplanButt.Visible = false;
listaButt.Visible = false;
magazynButt.Visible = false;
prodButt.Visible = true;
button1.Visible = false;
groupBox1.Text = pracownik.getStanowisko();
}
db = new ProdukcjaEntities2();
Sprawdz.CzyWyslane(db);
Sprawdz.CzyGotowe(db);
db.SaveChanges();
}
private void tworzplanButt_Click(object sender, EventArgs e)
{
Nawigacja.PrevPage = this;
Stwórz_Plan plan = new Stwórz_Plan(pracownik.getZmiana());
plan.Show();
this.Hide();
}
private void listaButt_Click(object sender, EventArgs e)
{
db = new ProdukcjaEntities2();
/*PrevForm.PrevPage = this;
Lista_Zlecen zlecenia = new Lista_Zlecen();
zlecenia.Show();
this.Hide();*/
List<Zamówienie> zamowienia = db.Zamówienie.ToList();
List<DaneZamawiajacego> c = db.DaneZamawiajacego.ToList();
// List<String> check = new List<String>();
listView1.Clear();
listView1.Columns.Add("id");
listView1.Columns.Add("Kod Zamówienia");
listView1.Columns.Add("Imie");
listView1.Columns.Add("Nazwisko");
listView1.Columns.Add("Miasto");
listView1.Columns.Add("Nr.Tel.");
listView1.Columns.Add("Data");
listView1.Columns.Add("Status");
foreach (var x in zamowienia)
{
ListViewItem listViewItem = new ListViewItem(x.id.ToString());
//listViewItem.SubItems.Add(y.Mebel.Nazwa);
listViewItem.SubItems.Add(x.Kod_Zlecenia);
listViewItem.SubItems.Add(x.DaneZamawiajacego.Imie);
listViewItem.SubItems.Add(x.DaneZamawiajacego.Nazwisko);
listViewItem.SubItems.Add(x.DaneZamawiajacego.Miasto);
listViewItem.SubItems.Add(x.DaneZamawiajacego.NrTel.ToString());
listViewItem.SubItems.Add(x.DataRealizacji.ToString());
listViewItem.SubItems.Add(x.Status);
listView1.Items.Add(listViewItem);
}
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
}
private void button3_Click(object sender, EventArgs e)
{
}
private void magazynButt_Click(object sender, EventArgs e)
{
Nawigacja.PrevPage = this;
Magazyn m = new Magazyn(pracownik);
m.Show();
this.Hide();
}
private void wyswietl_planButt_Click(object sender, EventArgs e)
{
Nawigacja.PrevPage = this;
Wyswietl_Plan plan = new Wyswietl_Plan(pracownik);
plan.Show();
this.Hide();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Nawigacja.PrevPage = this;
ProdForm prod = new ProdForm(pracownik);
prod.Show();
this.Hide();
}
private void button1_Click_1(object sender, EventArgs e)
{
List<Zamówienie> zamowienie = new List<Zamówienie>();
List<ListaMebli_Zamowienie> meble = new List<ListaMebli_Zamowienie>();
foreach (var x in zamowienie)
{
Boolean pomoc = true;
foreach (var y in meble)
{
if (y.idListy.Equals(x.idLista) && y.Status.Equals("DoRealizacji") || y.Status.Equals("W Realizacji"))
{
pomoc = false;
}
}
if (pomoc == true)
{
x.Status = "Gotowe Do Wydania";
}
}
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void groupBox6_Enter(object sender, EventArgs e)
{
}
private void button1_Click_2(object sender, EventArgs e)
{
Nawigacja.PrevPage = this;
Zlecenia_Przychodzace zlec = new Zlecenia_Przychodzace();
zlec.Show();
this.Hide();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Forms.MagazynForm.WydanieZewForm;
using Fabryka_Mebli_IO.Scripts;
namespace Fabryka_Mebli_IO.Forms.WydanieZewForm
{
public partial class WZ : Form
{
PracownikClass pracownik;
private Form prevPage;
private List<String> list;
public WZ(Form prevPage, List<String> list,PracownikClass pracownik)
{
InitializeComponent();
this.prevPage = prevPage;
this.list = list;
this.pracownik = pracownik;
}
private void Wyślij_Click(object sender, EventArgs e)
{
this.Enabled = false;
zapytanie z = new zapytanie(this,prevPage,list);
z.Show();
}
private void Powrót_Click(object sender, EventArgs e)
{
prevPage.Enabled=true;
this.Close();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void WZ_Load(object sender, EventArgs e)
{
imieText.Enabled = false;
nazwiskoText.Enabled = false;
zmianaText.Enabled = false;
dateTimePicker2.Enabled = false;
miastoBox.Enabled = false;
UlicaBox.Enabled = false;
Wyślij.Enabled = false;
imieText.Text=pracownik.getImie();
nazwiskoText.Text = pracownik.getNazwisko();
zmianaText.Text = pracownik.getZmiana().ToString();
dateTimePicker2.Value = DateTime.Now;
listBox1.Items.AddRange(list.ToArray());
}
private void label5_Click(object sender, EventArgs e)
{
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
miastoBox.Text = "Węgrów";
UlicaBox.Text = "Kościuszki";
Wyślij.Enabled = true;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
miastoBox.Text = "Siedlce";
UlicaBox.Text = "Popiełuszki";
Wyślij.Enabled = true;
}
private void groupBox3_Enter(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Scripts;
namespace Fabryka_Mebli_IO.Forms.StwórzPlanForm
{
public partial class Stwórz_Plan : Form
{
ProdukcjaEntities2 db;
int? id;
public Stwórz_Plan(int? id)
{
InitializeComponent();
db = new ProdukcjaEntities2();
this.id = id;
}
private void button1_Click(object sender, EventArgs e)
{
String[] split;
split=checkBoxList.SelectedItem.ToString().Split(' ');
info x = new info(split[0]);
x.Show();
}
private void powrótButt_Click(object sender, EventArgs e)
{
Nawigacja.PrevPage.Show();
Nawigacja.PrevPage.Refresh();
this.Close();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Stwórz_Plan_Load(object sender, EventArgs e)
{
dodajButt.Enabled = false;
usunButt.Enabled = false;
stworzButt.Enabled = false;
wyswietl.Enabled = false;
if(id==1)
{
radioButton1.Enabled = true;
radioButton2.Enabled = false;
}else if(id==2)
{
radioButton1.Enabled = false;
radioButton2.Enabled = true;
}
List<Zamówienie> zamowienia = db.Zamówienie.ToList();
List<DaneZamawiajacego> c = db.DaneZamawiajacego.ToList();
List<String> check = new List<String>();
foreach(var x in zamowienia)
{
if (x.Status.Equals("Oczekujacy"))
{
string nameAndId = x.id.ToString() + " " + x.DataRealizacji + " ";
foreach (var y in c)
{
if (y.id.Equals(x.idZamawiający))
{
nameAndId += y.Imie + " " + y.Miasto;
check.Add(nameAndId);
}
}
}
}
checkBoxList.Items.AddRange(check.ToArray());
}
private void dodajButt_Click(object sender, EventArgs e)
{
foreach (object x in checkBoxList.CheckedItems.OfType<String>().ToList())
{
listBox.Items.Add(x.ToString());
checkBoxList.Items.Remove(x);
}
}
private void checkBoxList_SelectedIndexChanged(object sender, EventArgs e)
{
if(checkBoxList.CheckedItems.Count>0)
{
dodajButt.Enabled = true;
}
else
{
dodajButt.Enabled = false;
}
if(checkBoxList.SelectedIndex>-1)
{
wyswietl.Enabled = true;
}
else
{
wyswietl.Enabled = false;
}
}
private void usunButt_Click(object sender, EventArgs e)
{
checkBoxList.Items.Add(
listBox.SelectedItem.ToString());
listBox.Items.RemoveAt(listBox.SelectedIndex);
}
private void stworzButt_Click(object sender, EventArgs e)
{
String[] split;
int x = listBox.Items.Count;
if (radioButton1.Checked)
{
for (int i = 0; i < x; i++)
{
listBox.SetSelected(i, true);
split = listBox.SelectedItem.ToString().Split(' ');
int id = Int32.Parse(split[0]);
Plan_Pracy u = new Plan_Pracy(1, id);
db.Plan_Pracy.Add(u);
var s=db.Zamówienie.Where(j => j.id == id).FirstOrDefault();
if(s!=null)
{
s.Status = "W Planie";
}
db.SaveChanges();
listBox.Items.RemoveAt(listBox.SelectedIndex);
}
}
else if(radioButton2.Checked)
{
for (int i = 0; i < x; i++)
{
listBox.SetSelected(i, true);
split = listBox.SelectedItem.ToString().Split(' ');
int id = Int32.Parse(split[0]);
Plan_Pracy u = new Plan_Pracy(2, id);
db.Plan_Pracy.Add(u);
var s = db.Zamówienie.Where(j => j.id == id).FirstOrDefault();
if (s != null)
{
s.Status = "W Planie";
}
db.SaveChanges();
listBox.Items.RemoveAt(listBox.SelectedIndex);
}
}
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox.SelectedIndex>-1)
{
usunButt.Enabled = true;
}
else
{
usunButt.Enabled = false;
}
if(listBox.Items.Count>0)
{
stworzButt.Enabled = true;
}
else
{
stworzButt.Enabled = false;
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fabryka_Mebli_IO.Scripts
{
public class PracownikClass
{
int id;
String imie;
String nazwisko;
int? zmiana;
String stanowisko;
public PracownikClass(int id,String imie,String nazwisko,int? zmiana,String stanowisko)
{
this.id=id;
this.imie=imie;
this.nazwisko=nazwisko;
this.zmiana=zmiana;
this.stanowisko=stanowisko;
}
public int getId()
{
return this.id;
}
public String getImie()
{
return this.imie;
}
public String getNazwisko()
{
return this.nazwisko;
}
public int? getZmiana()
{
return this.zmiana;
}
public String getStanowisko()
{
return this.stanowisko;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Fabryka_Mebli_IO.Scripts
{
public class Nawigacja
{
public static Form logForm;
public static Form mainGUI;
public static Form PrevPage;
}
}
<file_sep>using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Scripts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Fabryka_Mebli_IO.Forms.Przychodzace
{
public partial class Zlecenia_Przychodzace : Form
{
ProdukcjaEntities2 db;
public Zlecenia_Przychodzace()
{
InitializeComponent();
db = new ProdukcjaEntities2();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Zlecenia_Przychodzace_Load(object sender, EventArgs e)
{
List<Zamówienie> zamowienia = db.Zamówienie.ToList();
List<DaneZamawiajacego> c = db.DaneZamawiajacego.ToList();
List<String> check = new List<String>();
foreach (var x in zamowienia)
{
if (x.Status.Equals("Oczekujący Na Przyjecie"))
{
string nameAndId = x.id.ToString() + " " + x.DataRealizacji + " ";
foreach (var y in c)
{
if (y.id.Equals(x.idZamawiający))
{
nameAndId += y.Imie + " " + y.Miasto;
check.Add(nameAndId);
}
}
}
}
listBox1.Items.AddRange(check.ToArray());
}
private void button1_Click(object sender, EventArgs e)
{
Nawigacja.PrevPage.Show();
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
int y = listBox1.Items.Count;
String[] split;
for (int i = 0; i < y; i++)
{
listBox1.SetSelected(i, true);
split = listBox1.SelectedItem.ToString().Split(' ');
int id = Int32.Parse(split[0]);
Plan_Pracy u = new Plan_Pracy(1, id);
db.Plan_Pracy.Add(u);
var s = db.Zamówienie.Where(j => j.id == id).FirstOrDefault();
if (s != null)
{
s.Status = "Oczekujacy";
}
db.SaveChanges();
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
}
private void listView1_SelectedIndexChanged_1(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>using Fabryka_Mebli_IO.Databases;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fabryka_Mebli_IO.Scripts
{
class Sprawdz
{
public static void CzyGotowe(ProdukcjaEntities2 db)
{
List<Zamówienie> zamowienie = db.Zamówienie.ToList();
List<ListaMebli_Zamowienie> meble = db.ListaMebli_Zamowienie.ToList();
foreach(var x in zamowienie)
{
if (!x.Status.Equals("Oczekujacy")&& !x.Status.Equals("Wysłany")&& !x.Status.Equals("Oczekujący Na Przyjecie"))
{
Boolean pomoc = true;
foreach (var y in meble)
{
if (y.idListy.Equals(x.idLista) && !y.Status.Equals("Gotowy"))
{
pomoc = false;
}
}
if (pomoc == true)
{
x.Status = "Gotowe Do Wydania";
}
else
{
x.Status = "W Planie";
}
}
}
}
public static void CzyWyslane(ProdukcjaEntities2 db)
{
List<Zamówienie> zamowienie = db.Zamówienie.ToList();
List<Plan_Pracy> plan = db.Plan_Pracy.ToList();
List<ListaMebli_Zamowienie> meble = db.ListaMebli_Zamowienie.ToList();
foreach (var x in zamowienie)
{
if(x.Status.Equals("Wysłany"))
{
foreach(var y in plan)
{
if(x.id == y.idZamowienie)
{
db.Plan_Pracy.Remove(y);
}
}
}
}
}
}
}
<file_sep>using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Scripts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Fabryka_Mebli_IO.Forms.Produkcja
{
public partial class ProdForm : Form
{
public Timer timer;
private PracownikClass pracownik;
public ProdForm(PracownikClass pracownik)
{
InitializeComponent();
this.pracownik = pracownik;
}
private void button1_Click(object sender, EventArgs e)
{
timer.Stop();
ProdukcjaEntities2 db = new ProdukcjaEntities2();
if (listBox1.SelectedIndex > -1)
{
DodajForm dodaj = new DodajForm(db, listBox1, listBox2, this, pracownik.getId(),timer);
dodaj.Show();
this.Enabled = false;
}
else
{
MessageBox.Show("Musisz zaznaczyc rekord!");
timer.Start();
}
}
private void ProdForm_Load(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = (5 * 1000); // 5 secs
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
ProdukcjaEntities2 db = new ProdukcjaEntities2();
Boolean zmiana1=false;
Boolean zmiana2=false;
List<Plan_Pracy> plan = db.Plan_Pracy.ToList();
List<ListaMebli_Zamowienie> meble = db.ListaMebli_Zamowienie.ToList();
List<String> list = new List<String>();
List<String> list2 = new List<String>();
int id = pracownik.getId();
var obj = db.Pracownicy.Where(j => j.id == id).FirstOrDefault();
if(obj.Zmiany==1)
{
zmiana1 = true;
zmiana2 = false;
}else if (obj.Zmiany==2)
{
zmiana1 = false;
zmiana2 = true;
}
if (zmiana1 == true)
{
foreach (var x in plan)
{
if (x.idPlanu.Equals(1))
{
foreach (var y in meble)
{
if(y.idListy.Equals(x.Zamówienie.idLista) && pracownik.getStanowisko().Equals("Pilarz") && y.Status.Equals("Usterka"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie+" | [POPRAWKA]"; ;
list.Add(element);
}
if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("DoRealizacji") && pracownik.getStanowisko().Equals("Pilarz") )
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu+ " | " + x.idZamowienie;
list.Add(element);
}else if(y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Wiercenia") && pracownik.getStanowisko().Equals("Wiertacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Oklejania") && pracownik.getStanowisko().Equals("Oklejacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Pakowania") && pracownik.getStanowisko().Equals("Pakowacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Montażu") && pracownik.getStanowisko().Equals("Montażysta"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
if (y.idListy.Equals(x.Zamówienie.idLista) && y.pracownikWykonujacy == pracownik.getId() && y.Status.Equals("W Realizacji"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu+ " | " + x.idZamowienie;
list2.Add(element);
}
}
}
}
listBox1.Items.AddRange(list.ToArray());
listBox2.Items.AddRange(list2.ToArray());
}else if (zmiana2 == true)
{
foreach (var x in plan)
{
if (x.idPlanu.Equals(2))
{
foreach (var y in meble)
{
if (y.idListy.Equals(x.Zamówienie.idLista) && pracownik.getStanowisko().Equals("Pilarz") && y.Status.Equals("Usterka"))
{
string element =y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie +" | [POPRAWKA]";
list.Add(element);
}
if (y.idListy.Equals(x.Zamówienie.idLista) && pracownik.getStanowisko().Equals("Pilarz") && y.Status.Equals("DoRealizacji"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Wiercenia") && pracownik.getStanowisko().Equals("Wiertacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Oklejania") && pracownik.getStanowisko().Equals("Oklejacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Pakowania") && pracownik.getStanowisko().Equals("Pakowacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Montażu") && pracownik.getStanowisko().Equals("Montażysta"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
if (y.idListy.Equals(x.Zamówienie.idLista) && y.pracownikWykonujacy == pracownik.getId() && y.Status.Equals("W Realizacji"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list2.Add(element);
}
}
}
}
listBox1.Items.AddRange(list.ToArray());
listBox2.Items.AddRange(list2.ToArray());
}
}
private void timer_Tick(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox2.Items.Clear();
ProdukcjaEntities2 db = new ProdukcjaEntities2();
Boolean zmiana1 = false;
Boolean zmiana2 = false;
List<Plan_Pracy> plan = db.Plan_Pracy.ToList();
List<ListaMebli_Zamowienie> meble = db.ListaMebli_Zamowienie.ToList();
List<String> list = new List<String>();
List<String> list2 = new List<String>();
int id = pracownik.getId();
var obj = db.Pracownicy.Where(j => j.id == id).FirstOrDefault();
if (obj.Zmiany == 1)
{
zmiana1 = true;
zmiana2 = false;
}
else if (obj.Zmiany == 2)
{
zmiana1 = false;
zmiana2 = true;
}
if (zmiana1 == true)
{
foreach (var x in plan)
{
if (x.idPlanu.Equals(1))
{
foreach (var y in meble)
{
if (y.idListy.Equals(x.Zamówienie.idLista) && pracownik.getStanowisko().Equals("Pilarz") && y.Status.Equals("Usterka"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie + " | [POPRAWKA]"; ;
list.Add(element);
}
if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("DoRealizacji") && pracownik.getStanowisko().Equals("Pilarz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Wiercenia") && pracownik.getStanowisko().Equals("Wiertacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Oklejania") && pracownik.getStanowisko().Equals("Oklejacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Pakowania") && pracownik.getStanowisko().Equals("Pakowacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Montażu") && pracownik.getStanowisko().Equals("Montażysta"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
if (y.idListy.Equals(x.Zamówienie.idLista) && y.pracownikWykonujacy == pracownik.getId() && y.Status.Equals("W Realizacji"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list2.Add(element);
}
}
}
}
listBox1.Items.AddRange(list.ToArray());
listBox2.Items.AddRange(list2.ToArray());
}
else if (zmiana2 == true)
{
foreach (var x in plan)
{
if (x.idPlanu.Equals(2))
{
foreach (var y in meble)
{
if (y.idListy.Equals(x.Zamówienie.idLista) && pracownik.getStanowisko().Equals("Pilarz") && y.Status.Equals("Usterka"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie + " | [POPRAWKA]";
list.Add(element);
}
if (y.idListy.Equals(x.Zamówienie.idLista) && pracownik.getStanowisko().Equals("Pilarz") && y.Status.Equals("DoRealizacji"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Wiercenia") && pracownik.getStanowisko().Equals("Wiertacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Oklejania") && pracownik.getStanowisko().Equals("Oklejacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Pakowania") && pracownik.getStanowisko().Equals("Pakowacz"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
else if (y.idListy.Equals(x.Zamówienie.idLista) && y.Status.Equals("Gotowy Do Montażu") && pracownik.getStanowisko().Equals("Montażysta"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list.Add(element);
}
if (y.idListy.Equals(x.Zamówienie.idLista) && y.pracownikWykonujacy == pracownik.getId() && y.Status.Equals("W Realizacji"))
{
string element = y.id + " " + y.Mebel.Nazwa + " " + y.Kolor + " " + y.Mebel.Kod_Produktu + " | " + x.idZamowienie;
list2.Add(element);
}
}
}
}
listBox1.Items.AddRange(list.ToArray());
listBox2.Items.AddRange(list2.ToArray());
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
timer.Stop();
ProdukcjaEntities2 db = new ProdukcjaEntities2();
if (listBox2.SelectedIndex > -1)
{
ZakonczForm end = new ZakonczForm(db, listBox2, this, pracownik, timer);
end.Show();
this.Enabled = false;
}
else
MessageBox.Show("Musisz zaznaczyc rekord!");
timer.Start();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
Nawigacja.mainGUI.Show();
}
private void zglosButt_Click(object sender, EventArgs e)
{
timer.Stop();
ProdukcjaEntities2 db = new ProdukcjaEntities2();
if (listBox2.SelectedIndex > -1)
{
Usterka ust = new Usterka(db, listBox2, this, pracownik, timer);
ust.Show();
this.Enabled = false;
}
else
MessageBox.Show("Musisz zaznaczyc rekord!");
timer.Start();
}
}
}
<file_sep>using Fabryka_Mebli_IO.Databases;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Fabryka_Mebli_IO.Forms.StwórzPlanForm
{
public partial class info : Form
{
ProdukcjaEntities2 db;
int id;
public info(String id)
{
InitializeComponent();
this.id = Int32.Parse(id);
db = new ProdukcjaEntities2();
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void info_Load(object sender, EventArgs e)
{
List<ListaMebli_Zamowienie> list = db.ListaMebli_Zamowienie.ToList();
List<Zamówienie> zamowienie = db.Zamówienie.ToList();
listView1.Columns.Add("Nazwa");
listView1.Columns.Add("Kolor");
listView1.Columns.Add("Kod Produktu");
foreach (var x in zamowienie)
{
if(x.id.Equals(id))
{
foreach(var y in list)
{
if(y.idListy.Equals(x.idLista))
{
ListViewItem listViewItem = new ListViewItem(y.Mebel.Nazwa.ToString());
//listViewItem.SubItems.Add(y.Mebel.Nazwa);
listViewItem.SubItems.Add(y.Kolor);
listViewItem.SubItems.Add(y.Mebel.Kod_Produktu);
listView1.Items.Add(listViewItem);
}
}
}
}
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Scripts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Fabryka_Mebli_IO.Forms.Produkcja
{
public partial class Usterka : Form
{
private ProdukcjaEntities2 db;
private ListBox listBox2;
private Form prev;
private PracownikClass pracownik;
private Timer timer;
public Usterka(ProdukcjaEntities2 db, ListBox listBox, Form prev, PracownikClass pracownik,Timer timer)
{
InitializeComponent();
this.db = db;
this.listBox2 = listBox;
this.prev = prev;
this.pracownik = pracownik;
this.timer = timer;
}
private void Usterka_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string help = listBox2.SelectedItem.ToString();
string[] split = help.Split(' ');
int id = Int32.Parse(split[0]);
var obj = db.ListaMebli_Zamowienie.Where(j => j.id == id).FirstOrDefault();
List<Zamówienie> zam = db.Zamówienie.ToList();
obj.Status = "Usterka";
db.SaveChanges();
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
timer.Start();
this.Close();
prev.Enabled = true;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fabryka_Mebli_IO.Databases;
using Fabryka_Mebli_IO.Forms.WydanieZewForm;
using Fabryka_Mebli_IO.Scripts;
namespace Fabryka_Mebli_IO.Forms.MagazynForm
{
public partial class Magazyn : Form
{
PracownikClass pracownik;
public Magazyn(PracownikClass pracownik)
{
InitializeComponent();
this.pracownik = pracownik;
}
private void powrót_Click(object sender, EventArgs e)
{
Nawigacja.PrevPage.Show();
this.Close();
}
private void Magazyn_Load(object sender, EventArgs e)
{
ProdukcjaEntities2 db = new ProdukcjaEntities2();
List<Zamówienie> zam = db.Zamówienie.ToList();
List<String> check = new List<String>();
wzButt.Enabled = false;
foreach (var x in zam)
{
if (x.Status.Equals("Gotowe Do Wydania"))
{
string info = x.id.ToString() + " " + x.DaneZamawiajacego.Imie + " " + x.DaneZamawiajacego.Nazwisko + " " + x.DaneZamawiajacego.Miasto + " " + x.DaneZamawiajacego.Ulica + " " + x.DaneZamawiajacego.NrTel.ToString();
check.Add(info);
}
}
checkedListBox1.Items.AddRange(check.ToArray());
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if(checkedListBox1.CheckedItems.Count>0)
{
wzButt.Enabled = true;
}
else
{
wzButt.Enabled = false;
}
}
private void wzButt_Click(object sender, EventArgs e)
{
List<String> list = new List<String>();
foreach (var x in checkedListBox1.CheckedItems.OfType<String>().ToList())
{
list.Add(x);
}
WZ wz = new WZ(this,list,pracownik);
wz.Show();
this.Enabled = false;
}
}
}
| b3e82113fc36a5f628ba3f65640a50fe1bdf2084 | [
"C#"
] | 16 | C# | KrycuX/.NET-Framework-Windows-form-app | 97826224523a048bf2ffe187300e49e79743243c | 37f00680900abab4dccc01745476590d88dafe94 |
refs/heads/main | <repo_name>TimofiiSorokin/RedCat<file_sep>/tests.py
from app import client
def test_simple():
mylist = [1, 2, 3, 4, 5]
assert 3 in mylist
def test_get():
res = client.get('/web')
assert res.status_code == 200
assert len(res.get_json()) == 2
assert res.get_json()[0]['id'] == 1
def test_post():
data = {
'id': 3,
'tittle': '3333',
'descriptions': '3333',
}
res = client.post('/web', json=data)
assert res.status_code == 200
assert len(res.get_json()) == 3
assert res.get_json()[-1]['tittle'] == data['tittle']
<file_sep>/README.md
# RedCat
It's Flask
<file_sep>/app.py
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@localhost/redcatdb'
db = SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
tittle = db.Column(db.String(120), unique=False)
descriptions = db.Column(db.String(120), unique=False)
def __init__(self, tittle, descriptions):
self.tittle = tittle
self.descriptions = descriptions
client = app.test_client()
tutorials = [
{
'id': 1,
'tittle': 'First Web ',
'descriptions': 'WWWWWWWWWWWWWWWWWWWWWWWWWWWWW',
},
{
'id': 2,
'tittle': 'Second Web',
'descriptions': 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'
}
]
@app.route('/')
@app.route('/hello')
def hello_world():
a = 'Hello World!'
bbb = a
return bbb
# to see in route
@app.route('/web', methods=['GET'])
def get_list():
return jsonify(tutorials)
# to add in route
@app.route('/web', methods=['POST'])
def update_list():
new_one = request.json
tutorials.append(new_one)
return jsonify(tutorials)
# for change in route by id
@app.route('/web/<int:tutorial_id>', methods=['PUT'])
def update_tutorial(tutorial_id):
item = next((x for x in tutorials if x['id'] == tutorial_id), None)
params = request.json
if not item:
return {'message': 'No tutorials with this id'}, 400
item.update(params)
return item
@app.route('/web/<int:tutorial_id>', methods=['DELETE'])
def delete_tutorial(tutorial_id):
idx, _ = next((x for x in enumerate(tutorials) if x[1]['id'] == tutorial_id), (None, None))
tutorials.pop(idx)
return '', 204
if __name__ == '__main__':
app.debug = True
# db.create_all()
# app.run(host="localhost", port=8000, debug=True)
app.run()
| 6c1d44b39453d47356419f62aa21de1f2e835fe2 | [
"Markdown",
"Python"
] | 3 | Python | TimofiiSorokin/RedCat | 526f1141840f57a49321657c469866ab0c3390f3 | 52b5fecd1ece6897bc752dc17e5002fc4bb30dbf |
refs/heads/main | <file_sep># djangoBook
**Features:**
Static HTML and CSS
Secure email authorization via AllAuth
Validated forms
Dynamic AJAX DOM Updates
Styling via Semantic UI
Image processing via Pillow.py
**Description:**
A social webapp rendered server side and built exclusively with django.


<file_sep>from django.shortcuts import render, redirect, get_object_or_404
from django_refresher.src.apps.profiles.models import Profile, Relationship
from .forms import ProfileModelForm
from django.views.generic import ListView, DetailView
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
# Create your views here.
@login_required
def my_profile_view(request):
profile = Profile.objects.get(user=request.user)
form = ProfileModelForm(request.POST or None, request.FILES or None, instance=profile) # <-- args here fill the form
userHasUpdated = False
if request.method == 'POST':
if form.is_valid():
form.save()
userHasUpdated = True
context = {
'profile': profile,
'form': form,
'userHasUpdated': userHasUpdated
}
return render(request, 'profiles/myprofile.html', context)
@login_required
def invites_received_view(request):
profile = Profile.objects.get(user=request.user)
query_set = Relationship.objects.invitations_received(profile)
results = list(map(lambda x: x.sender, query_set))
is_empty = not len(results)
context = {'query_set': results}
return render(request,'profiles/my_invites.html', context)
@login_required
def invite_profiles_list_view(request):
user = request.user
query_set = Profile.objects.get_available_relationships(user)
context = {'query_set': query_set}
return render(request,'profiles/to_invite_profile_list.html', context)
# same as ProfileListView just a function instead of a class
# (start) this code is not being used
@login_required
def profiles_list_view(request):
user = request.user
query_set = Profile.objects.get_all_profiles(user)
context = {'query_set': query_set}
return render(request,'profiles/profile_list.html', context)
# (end) this code is not being used
class ProfileDetailView(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'profiles/detail.html'
#overide default method
def get_object(self):
slug = self.kwargs.get('slug')
profile = Profile.objects.get(slug=slug)
return profile
#overiding default method
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = User.objects.get( username__iexact=self.request.user ) # "username__iexact" helps prevent errors?
profile = Profile.objects.get(user=user)
context['profile'] = profile
# grabing all relationships involving the user
relations_received = Relationship.objects.filter(sender=profile)
relations_sent = Relationship.objects.filter(receiver=profile)
# turning those lists of relationships into lists of users
received_rel_users = []
sent_rel_users = []
for rel in relations_received:
received_rel_users.append(rel.receiver.user)
for rel in relations_sent:
sent_rel_users.append(rel.sender.user)
context['received_rel_users'] = received_rel_users
context['sent_rel_users'] = sent_rel_users
context['posts'] = self.get_object().get_all_authored_posts()
context['len_posts'] = bool(self.get_object().get_all_authored_posts())
return context
class ProfileListView(LoginRequiredMixin, ListView):
model = Profile
template_name = 'profiles/profile_list.html'
#overiding attr name
context_object_name = 'query_set'
#overiding default method
def get_queryset(self):
query_set = Profile.objects.get_all_profiles(self.request.user)
return query_set
#overiding default method
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = User.objects.get( username__iexact=self.request.user ) # "username__iexact" helps prevent errors?
profile = Profile.objects.get(user=user)
context['profile'] = profile
# grabing all relationships involving the user
relations_received = Relationship.objects.filter(sender=profile)
relations_sent = Relationship.objects.filter(receiver=profile)
# turning those lists of relationships into lists of users
received_rel_users = []
sent_rel_users = []
for rel in relations_received:
received_rel_users.append(rel.receiver.user)
for rel in relations_sent:
sent_rel_users.append(rel.sender.user)
context['received_rel_users'] = received_rel_users
context['sent_rel_users'] = sent_rel_users
context['is_empty'] = not len(self.get_queryset())
return context
@login_required
def send_invitation(request):
if request.method =='POST':
pk = request.POST.get('profile_pk') # target
user = request.user # origin
sender = Profile.objects.get(user=user)
receiver = Profile.objects.get(pk=pk)
rel = Relationship.objects.create(sender=sender, receiver=receiver, status='send')
return redirect(request.META.get('HTTP_REFERER'))
return redirect('profiles:my-profile-view')
@login_required
def accept_invitation(request):
if request.method=="POST":
pk = request.POST.get('profile_pk')
sender = Profile.objects.get(pk=pk)
receiver = Profile.objects.get(user=request.user)
relation = get_object_or_404(Relationship, sender=sender, receiver=receiver)
if relation.status == 'send':
relation.status = 'accepted'
relation.save()
return redirect('profiles:my-invites-view')
@login_required
def reject_invitation(request):
if request.method=="POST":
pk = request.POST.get('profile_pk')
sender = Profile.objects.get(pk=pk)
receiver = Profile.objects.get(user=request.user)
relation = get_object_or_404(Relationship, sender=sender, receiver=receiver)
relation.delete()
return redirect('profiles:my-invites-view')
@login_required
def remove_friend(request):
if request.method =='POST':
pk = request.POST.get('profile_pk') # target
user = request.user # origin
sender = Profile.objects.get(user=user)
receiver = Profile.objects.get(pk=pk)
# Unfortunately we dont know which user originally created the relationship (sent the friend request)
# we have to query the sent relationships of the user and the pk here
rel = Relationship.objects.get(
# user sent the relationship invite
(Q(sender=sender) & Q(receiver=receiver)) |
# user received the relationship invite
(Q(sender=receiver) & Q(receiver=sender))
)
rel.delete()
return redirect(request.META.get('HTTP_REFERER'))
return redirect('profiles:my-profile-view')
<file_sep>from django_refresher.src.apps.profiles.models import Profile, Relationship
def profile_pic(request):
if request.user.is_authenticated:
profile_obj = Profile.objects.get(user=request.user)
pic = profile_obj.avatar
return {'picture':pic}
return {}
def invitations_received_count(request):
if request.user.is_authenticated:
profile_obj = Profile.objects.get(user=request.user)
qs_count = Relationship.objects.invitations_received(profile_obj).count()
return {'invites_count':qs_count}
return {}<file_sep>import uuid
def get_random_eight_digit_id():
code = str(uuid.uuid4())[:8].replace('-', '').lower()
return code
def if_less_than_one_return_zero(value):
if value > 1: return 0
else: return value<file_sep>from django.urls import path
from django_refresher.src.apps.posts.views import post_comment_create_and_list_view, like_toggle_post, PostDeleteView, PostUpdateView
app_name = 'posts'
urlpatterns = [
path('', post_comment_create_and_list_view, name='main-post-view'),
path('liked', like_toggle_post, name='like-toggle-post-view'),
path('<pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('<pk>/update/', PostUpdateView.as_view(), name='post-update'),
]
<file_sep>from django.db import models
from django.contrib.auth.models import User
from .._utils import get_random_eight_digit_id
from django.template.defaultfilters import slugify
from django.db.models import Q
from django.shortcuts import reverse
class ProfileManager(models.Manager):
def get_available_relationships(self, sender):
profiles = Profile.objects.all().exclude(user=sender) # all profiles excluding senders profile
my_profile = Profile.objects.all().get(user=sender) # senders profile
query_set = Relationship.objects.filter(Q(sender=my_profile) | Q(receiver=my_profile)) # all relationships sent and recieved by the sender
accepted = []
for relationship in query_set:
if relationship.status == 'accepted':
accepted.append(relationship.receiver)
accepted.append(relationship.sender)
# comparing all profiles lists against accepted list and filtering out all users who the sender already shares a relationship with
available_relationships = [profile for profile in profiles if profile not in accepted]
return available_relationships
def get_all_profiles(self, me):
profiles = Profile.objects.all().exclude(user=me)
return profiles
# Create your models here.
class Profile(models.Model):
first_name = models.CharField(max_length=128, blank=True)
last_name = models.CharField(max_length=128, blank=True)
user = models.OneToOneField(User, on_delete=models.CASCADE) # models.CASCADE (evertime a user is deleted the profile is also deleted)
bio = models.TextField(default="n/a", max_length='512')
email = models.CharField(max_length=128, blank=True)
country = models.CharField(max_length=128, blank=True)
avatar = models.ImageField(default='avatar.png', upload_to='')
friends = models.ManyToManyField(User, blank=True, related_name='friends')
slug = models.SlugField(unique=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created= models.DateTimeField(auto_now_add=True)
objects = ProfileManager()
# override
def __str__(self):
return f"{self.user.username}-{self.created.strftime('%d-%m-%Y')}"
# override
def get_absolute_url(self):
return reverse("profiles:profile-detail-view", kwargs={"slug": self.slug})
def get_friends(self):
return self.friends.all()
def get_friends_count(self):
return self.friends.all().count()
def get_posts_count(self):
return self.posts.all().count() # we have access to posts via the fk attr on the Post class in posts/models.py
def get_all_authored_posts(self):
return self.posts.all
def get_given_likes_count(self):
likes = self.like_set.all() # we are using a fk in the Like class @ posts/models.py but we aren't passing it a related_name arg. Thats why we have to use the funky syntax here
total_likes = 0
for like in likes:
if like.value =='Like':
total_likes += 1
return total_likes
def get_recieved_likes_count(self):
posts = self.posts.all()
total_likes = 0
for post in posts:
total_likes += post.liked.all().count()
return total_likes
__initial_first_name = None
__initial_last_name = None
# override
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__initial_first_name = self.first_name
self.__initial_last_name = self.last_name
# override
def save(self, *args, **kwargs):
slugExists = False
to_slug = self.slug
if self.first_name != self.__initial_first_name or self.last_name != self.__initial_last_name or self.slug=="":
if self.first_name and self.last_name:
# if first and last name make the slug "firstname lastname"
to_slug = slugify( str(self.first_name) + ' ' + str(self.last_name) )
# check if that slug isn't unique
slugExists = Profile.objects.filter(slug=to_slug).exists()
while slugExists:
# while the slug is not unique, append an eight digit id to it and then check if the modified slug is unique
to_slug = slugify(to_slug + " " + str(get_random_eight_digit_id()))
slugExists = Profile.objects.filter(slug=to_slug).exists()
else:
to_slug = str(self.user)
self.slug = to_slug
super().save(*args, **kwargs)
class RelationshipManager(models.Manager):
def invitations_received(self, receiver):
queryset = Relationship.objects.filter(receiver=receiver, status='send')
return queryset
class Relationship(models.Model):
sender = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name='sender')
receiver = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name='receiver')
created= models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
objects = RelationshipManager()
status = models.CharField(max_length=8, choices=(
('send', 'send'),
('accepted', 'accepted')
))
def __str__(self):
return f"{self.sender}-{self.receiver}-{self.status}"
<file_sep>from django.contrib import admin
from apps.posts.models import Post, Comment, Like
# Register your models here.
admin.site.register(Post)
admin.site.register(Comment)
admin.site.register(Like)<file_sep>from django.apps import AppConfig
class ProfilesConfig(AppConfig):
name = 'apps.profiles'
def ready(self):
import django_refresher.src.apps.profiles.signals
<file_sep>
$(document).ready(function(){
$('#modal-profile-update-btn').click(function(){
$('.ui.modal').modal('show');
})
$('.ui.dropdown').dropdown()
}) | a6c7a58ba1820413b792cd9997989244010e8228 | [
"Markdown",
"Python",
"JavaScript"
] | 9 | Markdown | glassbones/django_refresher | a06a7b16dbac6b3e0a6812ef3a286159b1438cb4 | c8852a7b2931aa1699eb207c9cc31b1ba5e9869b |
refs/heads/master | <repo_name>liuyanan66/LeetCodeCode<file_sep>/README.md
# LeetCodeCode
// all the code of leetcode
<file_sep>/LeetCode/lc_24.swap_pairs.go
package main
import (
"fmt"
//"runtime/debug"
)
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
type ListNode struct {
Val int
Next *ListNode
}
// 普通的算法
// 如果是第二个节点则插入尾节点前面
// 如果是单数节点则插入到尾节点后面
func swapPairs(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
new_head, tail, pre_tail, cur := head, head, head, head.Next
new_head.Next = nil
cur_num := 1
for cur != nil {
cur_num++
tmp_node := cur
cur = cur.Next
if cur_num%2 == 0 {
if cur_num == 2 {
tmp_node.Next = new_head
pre_tail = tmp_node
new_head = tmp_node
} else {
pre_tail.Next = tmp_node
tmp_node.Next = tail
pre_tail = tmp_node
}
} else {
tail.Next = tmp_node
pre_tail = tail
tail = tmp_node
tail.Next = nil
}
}
return new_head
}
//
func swapPairsTwo(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
cur := head.Next.Next
new_head := head.Next
new_head.Next = head
new_head.Next.Next = nil
tail := new_head.Next
for cur != nil && cur.Next != nil {
tmp := cur
cur = cur.Next.Next
tail.Next = tmp.Next
tmp.Next.Next = tmp
tail = tmp
tail.Next = nil
}
tail.Next = cur
return new_head
}
// 加上一个空的头节点Next指针指向Head指针
// 然后对满足节点的指针pre节点的Next和Next.Next都不为空的指针进行操作
// 这样避免了单指针节点为奇数的时候单独处理
func swapPairsTwoSimple(head *ListNode) *ListNode {
pre := new(ListNode)
pre.Next = head
new_head := pre
for pre.Next != nil && pre.Next.Next != nil {
a := pre.Next
b := pre.Next.Next
pre.Next, b.Next, a.Next = b, a, b.Next
pre = a
}
return new_head.Next
}
//递归的算法
func swapPairsRecur(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
l1 := head.Next
head.Next = swapPairsRecur(l1.Next)
l1.Next = head
return l1
}
// 遍历链表
func traverseList(head *ListNode) {
if head == nil {
return
}
cur := head
for cur != nil {
fmt.Printf("%d ", cur.Val)
cur = cur.Next
}
fmt.Println()
}
func main() {
var head, tail *ListNode
for i := 1; i < 10; i++ {
if head == nil {
head = new(ListNode)
tail = head
tail.Val = i
} else {
tail.Next = new(ListNode)
tail = tail.Next
tail.Val = i
}
}
new_head := head.Next
new_head.Next = head
new_head.Next.Next = nil
traverseList(new_head)
//debug.PrintStack()
}
<file_sep>/LeetCode/lc_20.is_vaild.go
package main
import (
"fmt"
)
func isValid(s string) bool {
heap := InitHeap()
map_pra := map[uint8]uint8{'{':'}', '[':']', '(':')'}
for i := 0; i < len(s); i++ {
if _, ok := map_pra[s[i]]; ok {
heap.Push(s[i])
} else if heap.IsEmpty() || map_pra[heap.Pop().(uint8)] != s[i] {
return false
}
}
return heap.IsEmpty()
}
type Heap struct {
Var interface{}
Next *Heap
}
func InitHeap() (heap *Heap){
heap = new(Heap)
heap.Next = nil
return
}
func (self *Heap) Pop() (elem interface{}){
if self.Next != nil {
elem = self.Next.Var
self.Next = self.Next.Next
}
return
}
func (self *Heap) Push(elem interface{}) {
new_elem := new(Heap)
new_elem.Var = elem
new_elem.Next = self.Next
self.Next = new_elem
}
func (self *Heap) Top() (elem interface{}) {
if self.Next != nil {
elem = self.Next.Var
}
return
}
func (self *Heap) IsEmpty() bool {
return self.Next == nil
}
func main() {
s := "())"
fmt.Println(isValid(s))
} | dcf8edd64937a61aca90ef29efadf7ed29b7b918 | [
"Markdown",
"Go"
] | 3 | Markdown | liuyanan66/LeetCodeCode | 9d8da612a3f0f7b095d1c333a936c0249473e827 | c35b2c205f5ec03d81f687d2156386ad653d6f9f |
refs/heads/master | <file_sep>using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using GameRaider.Models;
using Microsoft.EntityFrameworkCore;
namespace GameRaider.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class GamesController : ControllerBase
{
private GameRaiderContext _db;
public GamesController(GameRaiderContext db)
{
_db = db;
}
[HttpPost]
public void Post([FromBody] Game game)
{
_db.Games.Add(game);
_db.SaveChanges();
}
[HttpGet("{id}")]
public ActionResult<Game> Get(int id)
{
return _db.Games.FirstOrDefault(entry => entry.GameId == id);
}
[HttpGet]
public ActionResult<IEnumerable<Game>> Get(string studio, string title, int raiding )
{
var query = _db.Games.AsQueryable();
if (studio != null)
{
query = query.Where(entry => entry.Studio == studio);
}
if (title != null)
{
query = query.Where(entry => entry.Title == title);
}
if (raiding != 0)
query = query.Where(entry => entry.Raiding >= raiding);
return query.ToList();
}
[HttpPut("{id}")]
public void Put(int id, [FromBody] Game game)
{
game.GameId = id;
_db.Entry(game).State = EntityState.Modified;
_db.SaveChanges();
}
[HttpDelete("{id}")]
public void Delete(int id)
{
var gameToDelete = _db.Games.FirstOrDefault(entry => entry.GameId == id);
_db.Games.Remove(gameToDelete);
_db.SaveChanges();
}
}
}
<file_sep>using System.Collections.Generic;
using System;
namespace GameRaider.Models
{
public class Review
{
public int ReviewId { get; set; }
public int GameId { get; set; }
public string ReviewAuthor { get; set; }
public string ReviewText { get; set; }
public string PublishDate { get; set; }
public int Raiding { get; set; }
public virtual Game Game { get; set; }
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using GameRaider.Models;
using Microsoft.EntityFrameworkCore;
namespace GameRaider.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ReviewsController : ControllerBase
{
private GameRaiderContext _db;
public ReviewsController(GameRaiderContext db)
{
_db = db;
}
[HttpPost]
public void Post([FromBody] Review review)
{
_db.Reviews.Add(review);
Game foundGame = _db.Games.FirstOrDefault(game => game.GameId == review.GameId);
foundGame.Reviews.Add(review);
_db.SaveChanges();
}
[HttpGet("{id}")]
public ActionResult<Review> Get(int id)
{
return _db.Reviews.FirstOrDefault(entry => entry.ReviewId == id);
}
[HttpGet]
public ActionResult<IEnumerable<Review>> Get(string reviewAuthor, string publishDate, int raiding, string title )
{
var query = _db.Reviews.AsQueryable();
if (reviewAuthor != null)
{
query = query.Where(entry => entry.ReviewAuthor == reviewAuthor);
}
if (publishDate != null)
{
query = query.Where(entry => entry.PublishDate == publishDate);
}
if (title != null)
{
query = query.Where(entry => entry.Game.Title == title);
}
if (raiding != 0)
{
query = query.Where(entry => entry.Raiding >= raiding);
}
return query.ToList();
}
[HttpPut("{id}")]
public void Put(int id, [FromBody] Review review)
{
review.ReviewId = id;
_db.Entry(review).State = EntityState.Modified;
_db.SaveChanges();
}
[HttpDelete("{id}")]
public void Delete(int id)
{
var reviewToDelete = _db.Reviews.FirstOrDefault(entry => entry.ReviewId == id);
_db.Reviews.Remove(reviewToDelete);
_db.SaveChanges();
}
}
}
<file_sep># _Game Raider_
#### A database application in C# using EF Core and SQL for_**Epicodus**_
#### By _**<NAME> and <NAME>**_
## Description
_A SQL API database that allows users to add, edit, and review video games_
## Setup/Installation Requirements
* _Clone project from GitHub, navigate to directory, and open in a text editor_
* _Open My SQL Workbench and create a new schema titled game_raider_
* _Create two tables within this schema, titled games and reviews_
* _Create three rows in the clients table: ClientId with data type Int, set as primary key, not-null, and auto-incrementing; ClientName with data type VarChar255; and StylistId with data type Int, default value 0_
* _Create two rows in the stylists table: Stylist Id with data type Int, set as primary key, not-null, and auto-incrementing; StylistName with data type VarChar255_
* _Run dotnet restore, dotnet build and dotnet run watch to host locally_
* _link_
## Known Bugs
_No known bugs. Please report any to mstambaugh or dcooley1350_
## Technologies Used
_C#/.NET, EF Core, SQL, API, Postman_
### License
**_Copyright (c) 2019 <NAME> and <NAME> and licensed under the MIT license_**
<file_sep>using Microsoft.EntityFrameworkCore.Migrations;
namespace GameRaider.Migrations
{
public partial class ReviewClass : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "Raiding",
table: "Reviews",
nullable: false,
defaultValue: 0);
migrationBuilder.InsertData(
table: "Games",
columns: new[] { "GameId", "Raiding", "ReleaseDate", "Studio", "Title" },
values: new object[,]
{
{ 1, 5, "2011", "Bethesda", "Skyrim" },
{ 2, 5, "2018", "Rockstar", "Red Dead Redemtion 2" },
{ 3, 2, "2019", "id Software", "<NAME>" },
{ 4, 4, "2015", "FromSoftware", "Bloodborne" },
{ 5, 3, "2013", "Ghost Games", "Need for Speed Rivals" },
{ 6, 1, "2002", "Nintendo", "<NAME>" }
});
migrationBuilder.InsertData(
table: "Reviews",
columns: new[] { "ReviewId", "GameId", "PublishDate", "Raiding", "ReviewAuthor", "ReviewText" },
values: new object[] { 2, 1, "February 26, 2015", 2, "RunDMC123", "It is the incapable younger brother of Morrowind, but nonetheless I played it" });
migrationBuilder.InsertData(
table: "Reviews",
columns: new[] { "ReviewId", "GameId", "PublishDate", "Raiding", "ReviewAuthor", "ReviewText" },
values: new object[] { 1, 2, "October 26, 2019", 5, "BeffJezos666", "The worlding building in this game is on a whole new level, bro. It is so big, so detailed, and I get to be a cowboy and ride my horse, Wh<NAME>, all over town" });
migrationBuilder.InsertData(
table: "Reviews",
columns: new[] { "ReviewId", "GameId", "PublishDate", "Raiding", "ReviewAuthor", "ReviewText" },
values: new object[] { 3, 3, "May 1, 2002", 2, "TaylorLautner420", "This game sucked bro" });
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DeleteData(
table: "Games",
keyColumn: "GameId",
keyValue: 4);
migrationBuilder.DeleteData(
table: "Games",
keyColumn: "GameId",
keyValue: 5);
migrationBuilder.DeleteData(
table: "Games",
keyColumn: "GameId",
keyValue: 6);
migrationBuilder.DeleteData(
table: "Reviews",
keyColumn: "ReviewId",
keyValue: 1);
migrationBuilder.DeleteData(
table: "Reviews",
keyColumn: "ReviewId",
keyValue: 2);
migrationBuilder.DeleteData(
table: "Reviews",
keyColumn: "ReviewId",
keyValue: 3);
migrationBuilder.DeleteData(
table: "Games",
keyColumn: "GameId",
keyValue: 1);
migrationBuilder.DeleteData(
table: "Games",
keyColumn: "GameId",
keyValue: 2);
migrationBuilder.DeleteData(
table: "Games",
keyColumn: "GameId",
keyValue: 3);
migrationBuilder.DropColumn(
name: "Raiding",
table: "Reviews");
}
}
}
<file_sep>using Microsoft.EntityFrameworkCore;
namespace GameRaider.Models
{
public class GameRaiderContext : DbContext
{
public GameRaiderContext(DbContextOptions<GameRaiderContext> options)
: base(options)
{
}
public DbSet<Game> Games { get; set; }
public DbSet<Review> Reviews { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Game>()
.HasData(
new Game { GameId = 1, Raiding = 5, Title = "Skyrim", Studio = "Bethesda", ReleaseDate = "2011" },
new Game { GameId = 2, Raiding = 5, Title = "Red Dead Redemption 2", Studio = "Rockstar", ReleaseDate = "2018" },
new Game { GameId = 3, Raiding = 2, Title = "<NAME>", Studio = "id Software", ReleaseDate = "2019" },
new Game { GameId = 4, Raiding = 4, Title = "Bloodborne", Studio = "FromSoftware", ReleaseDate = "2015" },
new Game { GameId = 5, Raiding = 3, Title = "Need for Speed Rivals", Studio = "Ghost Games", ReleaseDate = "2013" },
new Game { GameId = 6, Raiding = 1, Title = "<NAME>", Studio = "Nintendo", ReleaseDate = "2002" }
);
builder.Entity<Review>()
.HasData(
new Review { ReviewId = 1, GameId = 2, ReviewAuthor = "BeffJezos666", ReviewText = "The worlding building in this game is on a whole new level, bro. It is so big, so detailed, and I get to be a cowboy and ride my horse, Whitneigh Horsten, all over town", PublishDate = "October 26, 2019", Raiding = 5},
new Review { ReviewId = 2, GameId = 1, ReviewAuthor = "RunDMC123", ReviewText = "It is the incapable younger brother of Morrowind, but nonetheless I played it", PublishDate = "February 26, 2015", Raiding = 2},
new Review { ReviewId = 3, GameId = 3, ReviewAuthor = "TaylorLautner420", ReviewText = "This game sucked bro", PublishDate = "May 1, 2002", Raiding = 2}
);
}
}
}<file_sep>using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System;
namespace GameRaider.Models
{
public class Game
{
public Game()
{
this.Reviews = new HashSet<Review>();
}
public int GameId { get; set; }
public int Raiding { get; set; }
public string Title { get; set; }
public string Studio { get; set; }
public string ReleaseDate { get; set; }
public virtual ICollection<Review> Reviews { get; set; }
}
}<file_sep>using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace GameRaider.Migrations
{
public partial class update2 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Year",
table: "Games");
migrationBuilder.AddColumn<DateTime>(
name: "ReleaseDate",
table: "Games",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
migrationBuilder.CreateTable(
name: "Reviews",
columns: table => new
{
ReviewId = table.Column<int>(nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
GameId = table.Column<int>(nullable: false),
ReviewAuthor = table.Column<string>(nullable: true),
ReviewText = table.Column<string>(nullable: true),
PublishDate = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Reviews", x => x.ReviewId);
table.ForeignKey(
name: "FK_Reviews_Games_GameId",
column: x => x.GameId,
principalTable: "Games",
principalColumn: "GameId",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Reviews_GameId",
table: "Reviews",
column: "GameId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Reviews");
migrationBuilder.DropColumn(
name: "ReleaseDate",
table: "Games");
migrationBuilder.AddColumn<string>(
name: "Year",
table: "Games",
nullable: true);
}
}
}
| db0ac3e304ae5d233bd1b1897f9506ba307d894e | [
"Markdown",
"C#"
] | 8 | C# | mstambaugh/GameRaider | 7ed63b90d51cbe1ca1e376988b712fcc8c0c1d53 | b30e9f8bda6f521a602f33ca002b9e075e366a16 |
refs/heads/main | <repo_name>vinaykharayat/registrationFormPHP<file_sep>/dao/databaseDao.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//require_once(dirname(getcwd()).'/bean/userBean.php');
class databaseDao {
const HOST = "localhost";
const USERNAME = "root";
const PASSWORD = "";
const DATABASE = "cedcoss";
const SUCCESS_CODE = 200;
const FAILURE_CODE = -1;
private $conn;
/*
* *******************************
* Creates connection to database
* *******************************
*/
function createConnection() {
$conn = &$GLOBALS['conn'];
$conn = new mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASE);
if ($conn->connect_errno) {
return $conn->connect_error;
} else {
return self::SUCCESS_CODE;
}
}
/*
* ********************************************************************
* Checks whether a value exist in a particular column
* If not exists, it sends a response code of 200 else it will send -1
* ********************************************************************
*/
function checkAvalability($columnName, $value) {
$conn = &$GLOBALS['conn'];
$query = "select * from users where `$columnName` = '$value'";
$result = $conn->query($query);
if ($result->num_rows == 0) {
return self::SUCCESS_CODE;
} else {
return self::FAILURE_CODE;
}
}
/*
* ****************************************************
* Inserts value to table(users) using userBean object
* ****************************************************
*/
function insertValues($user) {
$conn = &$GLOBALS['conn'];
$query = "insert into users(`fullName`, `username`, `email`,`password`, `experience`, `profile`, `gender`, `phone`, `profilePicture`) values(" . "'" . $user->getFullName() . "','" . $user->getUsername() . "', '" . $user->getEmail() . "', '" . $user->getPassword() . "', '" . $user->getExperience() . "', '" . $user->getProfile() . "', '" . $user->getGender() . "', '" . $user->getPhone() . "', '" . $user->getProfilePicture() . "')";
$result = $conn->query($query);
print_r($result);
if ($result > 0) {
return self::SUCCESS_CODE;
} else {
return self::FAILURE_CODE;
}
}
/*
* ***********************************
* Gets all the data from table(users)
* ***********************************
*/
function getAllData() {
$conn = &$GLOBALS['conn'];
$query = "select * from users";
$results = $conn->query($query);
return $results;
}
/*
* ********************************************
* Updates value in database using primary key
* ********************************************
*/
function updateValues($user, $primaryKey) {
$conn = &$GLOBALS['conn'];
$query = "update users set `fullName` = '" . $user->getFullName() . "', `username` = '" . $user->getUsername() . "', `email` = '" . $user->getEmail() . "', `password` = '" . <PASSWORD>() . "', `experience`= '" . $user->getExperience() . "', `profile` = '" . $user->getProfile() . "', `gender` = '" . $user->getGender() . "', `phone` = '" . $user->getPhone() . "', `profilePicture` = '" . $user->getProfilePicture() . "' where `userId`='" . $primaryKey . "';";
$results = $conn->query($query);
if ($results > 0) {
return self::SUCCESS_CODE;
} else {
return self::FAILURE_CODE;
}
}
/*
* ***********************************
* Deletes a row in database
* ***********************************
*/
function deleteRow($primaryKey) {
$conn = &$GLOBALS['conn'];
$query = "DELETE from users WHERE `userid`='$primaryKey'";
$results = $conn->query($query);
if ($results > 0) {
return self::SUCCESS_CODE;
} else {
return self::FAILURE_CODE;
}
}
function verifyUserDetails($userEmail, $userPassword) {
$conn = &$GLOBALS['conn'];
$query = "Select * from users where `email`='$userEmail' AND `password` = '$<PASSWORD>'";
$results = $conn->query($query);
if ($results > 0) {
return self::SUCCESS_CODE;
} else {
return self::FAILURE_CODE;
}
}
}
<file_sep>/loginUser.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once('./bean/userBean.php');
require_once ('./dao/databaseDao.php');
const SUCCESS_CODE = 200;
const FAILURE_CODE = -1;
$dao = new databaseDao();
$dao->createConnection();
$userEmail = filter_input(INPUT_POST, 'email');
$userPassword = filter_input(INPUT_POST, '<PASSWORD>');
$result = $dao->verifyUserDetails($userEmail, $userPassword);
if ($result == SUCCESS_CODE) {
echo 'exist';
} else {
echo 'nExist';
}
<file_sep>/php/updateData.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once(dirname(getcwd()) . '/bean/userBean.php');
require_once (dirname(getcwd()) . '/dao/databaseDao.php');
const SUCCESS_CODE = 200;
const FAILURE_CODE = -1;
$dao = new databaseDao();
$dao->createConnection();
/*
* *****************************************************
* Performs delete or update besed of user button click
* *****************************************************
*/
if (filter_input(INPUT_POST, "action") == "delete") {
$result = $dao->deleteRow(filter_input(INPUT_POST, "userid"));
if ($result == SUCCESS_CODE) {
echo SUCCESS_CODE;
} else {
echo FAILURE_CODE;
}
} else {
$user = new userBean(filter_input(INPUT_POST, "fullName"),
filter_input(INPUT_POST, "username"),
filter_input(INPUT_POST, "email"),
filter_input(INPUT_POST, "experience"),
filter_input(INPUT_POST, "profile"),
filter_input(INPUT_POST, "gender"),
filter_input(INPUT_POST, "phone"),
filter_input(INPUT_POST, "password"),
filter_input(INPUT_POST, "profilePictureUrl"));
$result = $dao->updateValues($user, filter_input(INPUT_POST, "userid"));
if ($result == SUCCESS_CODE) {
echo SUCCESS_CODE;
} else {
echo FAILURE_CODE;
}
}
<file_sep>/results.php
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="./jquery-3.5.1.js"></script>
<style>
input{
width:100px;
}
</style>
</head>
<body>
<h1>Welcome, <?php echo $_GET["user"]?></h1>
<table>
<tr>
<th>
ID
</th>
<th>
Full Name
</th>
<th>
Username
</th>
<th>
Email
</th>
<th>
Phone
</th>
<th>
Experience
</th>
<th>
Profiles
</th>
<th>
Gender
</th>
<th>
Profile Pic URL
</th>
<th>
Action
</th>
</tr>
<?php
require_once('./dao/databaseDao.php');
$dao = new databaseDao();
$dao->createConnection();
$results = $dao->getAllData();
if ($results->num_rows > 0) {
// output data of each row
/*
* ***********************************
* Inserts data to table
* ***********************************
*/
while ($row = $results->fetch_assoc()) {
echo "<tr><td><input class='userid' disabled value='" . $row["userId"] . "'></td><td><input class='fullName' disabled value='" . $row['fullName'] . "'></td><td><input class='username' disabled value='" . $row['username'] . "'></td><td><input class='email' disabled value='" . $row['email'] . "'></td><td><input class='phone' disabled value='" . $row['phone'] . "'></td><td><input class='experience' disabled value='" . $row['experience'] . "'></td><td><input class='profile' disabled value='" . $row['profile'] . "'></td><td><input class='gender' disabled value='" . $row['gender'] . "'></td><td><input class='profilePicUrl' disabled value='" . $row['profilePicture'] . "'></td><input type ='hidden' class='password' disabled value='" . $row['password'] . "'></td>";
echo "<td><button class='updateButton' type='submit' value='update' name='" . $row["userId"] . "'>Edit</button>";
echo "<button class='deleteButton' type='submit' value='delete' name='" . $row["userId"] . "'>Delete</button></td></tr>";
}
} else {
echo "0 results";
}
?>
</table>
<script>
const SUCCESS_CODE = 200;
$(".updateButton").on("click", function () {
if ($(this).text() === "Edit") {
$(this).text("Update");
$(this).parent().parent().find("input").prop("disabled", false)
} else if ($(this).text() === "Update") {
$.ajax({
type: 'post',
url: './php/updateData.php',
data: {'userid': $(this).parent().parent().find(".userid").val(),
'fullName': $(this).parent().parent().find(".fullName").val(),
'username': $(this).parent().parent().find(".username").val(),
'email': $(this).parent().parent().find(".email").val(),
'phone': $(this).parent().parent().find(".phone").val(),
'experience': $(this).parent().parent().find(".experience").val(),
'profile': $(this).parent().parent().find(".profile").val(),
'gender': $(this).parent().parent().find(".gender").val(),
'profilePictureUrl': $(this).parent().parent().find(".profilePicUrl").val(),
'password': $(this).parent().parent().find(".password").val()
},
success: function (response) {
console.log(response == SUCCESS_CODE);
if (response == SUCCESS_CODE) {
alert("Data updated successfully");
location.reload();
$(".updateButton").parent().parent().find("input").prop("disabled", true);
} else {
confirm("Something went wrong!");
}
}
});
}
});
$(".deleteButton").on("click", function () {
let userSelection = confirm("Are you sure? This cannot be undone!");
if (userSelection) {
$.ajax({
type: 'post',
url: './php/updateData.php',
data: {"action": "delete",
'userid': $(this).parent().parent().find(".userid").val()},
success: function (response) {
if (response == SUCCESS_CODE) {
alert("Row deleted successfully!");
location.reload();
} else {
alert("Something went wrong!");
}
}
});
}
});
</script>
</body>
</html>
<file_sep>/registerUser.php
<?php
ini_set("file_uploads", '1');
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once('./dao/databaseDao.php');
require_once('./bean/userBean.php');
const SUCCESS_CODE = 200;
$dao = new databaseDao();
$dao->createConnection();
$profilePicUrl = uploadFile();
echo '<pre>';
print_r($profilePicUrl);
$newUser = new userBean(filter_input(INPUT_POST, "name"),
filter_input(INPUT_POST, "username"),
filter_input(INPUT_POST, "email"),
filter_input(INPUT_POST, "dropdown"),
filter_input(INPUT_POST, "checkboxes"),
filter_input(INPUT_POST, "radio"),
filter_input(INPUT_POST, "phone"),
filter_input(INPUT_POST, "password"),
$profilePicUrl);
$result = $dao->insertValues($newUser);
if ($result == SUCCESS_CODE) {
header("Location: login.php");
echo("success");
} else {
echo 'failed';
}
function uploadFile() {
$target_dir = "uploads/";
$target_file = $target_dir . filter_input(INPUT_POST, "username"). ".";
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($_FILES["profilePicture"]["name"], PATHINFO_EXTENSION));
$target_file .= $imageFileType;
// Check if image file is a actual image or fake image
if (isset($_POST["submit"])) {
$check = getimagesize($_FILES["profilePicture"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["profilePicture"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["profilePicture"]["tmp_name"], $target_file)) {
echo "The file " . htmlspecialchars(basename($_FILES["profilePicture"]["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
return "./".$target_file;
}
<file_sep>/bean/userBean.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
class userBean{
private $fullName;
private $username;
private $email;
private $experience;
private $profile;
private $gender;
private $phone;
private $password;
private $profilePicture;
private $profilePictureUrl;
function __construct($fullName, $username, $email, $experience, $profile, $gender, $phone, $password, $profilePicture) {
$this->fullName = $fullName;
$this->username = $username;
$this->email = $email;
$this->experience = $experience;
$this->profile = $profile;
$this->gender = $gender;
$this->phone = $phone;
$this->password = $<PASSWORD>;
$this->profilePicture = $profilePicture;
}
function getProfilePicture() {
return $this->profilePicture;
}
function setProfilePicture($profilePicture): void {
$this->profilePicture = $profilePicture;
}
function getPassword() {
return $this->password;
}
function setPassword($password): void {
$this->password = $password;
}
function getFullName() {
return $this->fullName;
}
function getUsername() {
return $this->username;
}
function getEmail() {
return $this->email;
}
function getExperience() {
return $this->experience;
}
function getProfile() {
return $this->profile;
}
function getGender() {
return $this->gender;
}
function getPhone() {
return $this->phone;
}
function setFullName($fullName): void {
$this->fullName = $fullName;
}
function setUsername($username): void {
$this->username = $username;
}
function setEmail($email): void {
$this->email = $email;
}
function setExperience($experience): void {
$this->experience = $experience;
}
function setProfile($profile): void {
$this->profile = $profile;
}
function setGender($gender): void {
$this->gender = $gender;
}
function setPhone($phone): void {
$this->phone = $phone;
}
}
<file_sep>/validate.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once('./dao/databaseDao.php');
$username = filter_input(INPUT_GET, "username");
$emailInput = filter_input(INPUT_GET, "email");
$phoneInput = filter_input(INPUT_GET, "phone");
const SUCCESS_CODE = 200;
$dao = new databaseDao();
if ($dao->createConnection() == SUCCESS_CODE) {
initiateValidation();
} else {
die($dao->createConnection());
}
/*
* ****************************************************
* Checks for existing username, email or phone number
* ****************************************************
*/
function initiateValidation() {
if ($GLOBALS["username"] != null) {
checkAvalability("username", $GLOBALS['username']);
}
if ($GLOBALS["emailInput"] != null) {
checkAvalability("email", $GLOBALS['emailInput']);
}
if ($GLOBALS["phoneInput"] != null) {
checkAvalability("phone", $GLOBALS['phoneInput']);
}
}
function checkAvalability($columnName, $valueToCheck) {
$dao = &$GLOBALS["dao"];
$result = $dao->checkAvalability($columnName, $valueToCheck);
if ($result == SUCCESS_CODE) {
echo "nExist";
} else {
echo "exist";
}
}
| 62d08d019aebe431e0f626043d308d42d74ab7d1 | [
"PHP"
] | 7 | PHP | vinaykharayat/registrationFormPHP | 2cd0374e3eea9b1b23a208b18dd9d6ca1f14aff1 | 64db5b69567913d2e0d3481dc32af327164bca8a |
refs/heads/master | <file_sep>export default {
fetch(){
return JSON.parse(localStorage.getItem('todo-vue2.x') || `[ {"id":1,"title": "Work", "icon": "el-icon-message", "editable": "false","toDos":[]},
{"id":2,"title": "Home", "icon": "el-icon-menu", "editable": "false","toDos":[]}]`)
},
store(todos){
localStorage.setItem('todo-vue2.x',JSON.stringify(todos))
}
}<file_sep># todo-vue-element
Todo with optional tables<br>
Element component library<br>
##[DEMO](https://tim1023.github.io/todo-vue-element/index.html)
##[V_0.1](https://github.com/Tim1023/todomvc-vue2.x-element)

| 00a109f7b0b3162751fa76145e1c3a48ec239834 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Tim1023/todo-vue-element | 1357cb1532c027783c6e20ac9d50487fa6ebcfed | f5f79877c466ef6e0323994c6a53f6674f3b709e |
refs/heads/master | <repo_name>yfshi/hexo-blog<file_sep>/source/_posts/GetCategories.sh
#!/bin/bash
Usage()
{
echo "Usage:"
echo " -l list all categories."
echo " -a list all categories and files."
}
ListAll()
{
for cat in `cat *.md | grep categories | sort | uniq | awk '{print $2}'`
do
echo "[$cat]:"
grep 'categories:' *.md | grep "$cat" | awk -F: '{print " "$1}'
done
}
List()
{
cat *.md | grep categories | sort | uniq | awk '{print $2}'
}
case $1 in
'-a'|'-A'|'all')
ListAll;;
'-l'|'-L'|'list')
List;;
*)
Usage
esac
<file_sep>/source/_posts/linux终端快捷键.md
---
layout: _post
title: linux终端快捷键
date: 2018-12-27 17:28:48
categories: Shell
tags:
---
> linux中的许多操作在终端(Terminal)中十分的快捷。
* 光标操作
| 快捷键 | 功能 |
| ----------------- | ----------- |
| Ctrl+A(ahead) | 移动到行首 |
| Ctrl+E(end) | 移动到行尾 |
| Ctrl+Left | 移动到上一个单词的词首 |
| Ctrl+Right | 移动到下一个单词的词尾 |
| Ctrl+F(forwards) | 向后移动一个字符 |
| Ctrl+B(backwards) | 向前移动一个字符 |
| Esc+F | 移动到当前单词的词尾 |
| Esc+B | 移动到当前单词的词首 |
* 文本处理操作
| 快捷键 | 功能 |
| ------ | --------------------- |
| Ctrl+U | 剪切光标到行首的内容 |
| Ctrl+K | 剪切光标到行尾的内容 |
| Ctrl+W | 剪切光标到词首的内容 |
| Alt+D | 剪切光标到词尾的内容 |
| Ctrl+H | 删除光标前的字符,相当于Backspace |
| Ctrl+D | 删除光标后的字符,相当于Delete |
| Ctrl+Y | 粘贴删除或剪切的字符 |
| Ctrl+7 | 恢复刚才的内容 |
* 历史命令操作
| 快捷键 | 功能 |
| ---------------- | --------------- |
| Ctrl+P(previous) | 显示上一条命令 |
| Ctrl+N(next) | 显示下一条命令 |
| !Num | 执行命令历史表的第Num条命令 |
| !! | 执行上一条命令 |
| !$ | 上一条命令的最后一个参数 |
| Ctrl+R(retrive) | 向上搜索历史命令 |
* 窗口操作
| 快捷键 | 功能 |
| -------------- | ---- |
| Shift+Ctrl+N | 新建窗口 |
| Shift+Ctrl+Q | 关闭终端 |
| F11 | 全屏 |
| Ctrl+Plus | 放大 |
| Ctrl+Minus | 缩小 |
| Ctrl+0 | 原始大小 |
| Shirt+Up | 向上滚屏 |
| Shift+Down | 向下滚屏 |
| Shift+PageUp | 向上翻页 |
| Shift+PageDown | 向下翻页 |
* 任务处理操作
| 快捷键 | 功能 |
| ------ | ------------ |
| Ctrl+C | 删除整行/终止 |
| Ctrl+L | 刷新屏幕 |
| Ctrl+S | 挂起当前shell |
| Ctrl+Q | 重新启用挂起的shell |
* 标签页处理操作
| 快捷键 | 功能 |
| ------------------- | -------------- |
| Shift+Ctrl+T | 新建标签页 |
| Shift+Ctrl+W | 关闭标签页 |
| Ctrl+PageUp | 前一标签页 |
| Ctrl+PageDown | 后一标签页 |
| Shift+Ctrl+PageUp | 标签页左移 |
| Shift+Ctrl+PageDown | 标签页右移 |
| Alt+1,2,3... | 切换到标签页1,2,3... |
* 其他操作<file_sep>/source/_posts/Makefile.md
---
layout: _post
title: Makefile
date: 2018-10-30 10:01:54
categories: Makefile
tags: Makefile
---
下面是一个基础的Makefile文件
```makefile
# 一些基本命令和参数
CC = gcc
AR = ar
AROPT = crs
CFLAGS += -g3 -O0
CFLAGS += -std=gnu99 -Wall
CFLAGS += -I./include -fPIC
CFLAGS += -fpic
# 编译命令,编译.o、.a、.so的命令分别如下:
COMPILER = $(CC) $(CFLGAS)
LINK.static = $(AR) $(AROPT)
LINK.shared = $(COMPILER) -shared #-Wl,-soname,xxx
# 编译过程需要链接的库,-Wl,--as-needed告诉连接器按需链接,比如crypto有的目标没有引用,则不连接
LDFLAGS += -L./lib -Wl,--as-needed
LIBS += -ltest -lcrypto -ld -lz -lc
# 公用接口文件
OBJS := common.o
# 要生成的目标文件
PROGS := dgcheck dgservice libdongle.so libdongle.a test
all: $(PROGS)
dgcheck: dgcheck.o libdongle.o $(OBJS)
$(COMPILER) $^ $(LDFLAGS) $(LIBS) -o $@
dgservice: dgservice.o dongle.o $(OBJS)
$(COMPILER) $^ $(LDFLAGS) $(LIBS) -o $@
libdongle.so: libdongle.o $(OBJS)
$(LINK.shared) $^ $(LDFLAGS) $(LIBS) -o $@
libdongle.a: libdongle.o $(OBJS)
$(LINK.static) $@ $^
test: test.o libdongle.o $(OBJS)
$(COMPILER) $^ $(LDFLAGS) $(LIBS) -o $@
clean:
rm -f *.o $(PROGS)
install: $(PROGS)
mkdir -p deploy
cp -f $^ deploy
uninstall:
rm -rf deploy
```
<file_sep>/source/_posts/常用的c语言函数.md
---
layout: _post
title: 常用的c语言函数
date: 2018-12-06 14:45:14
categories: 编程
tags:
---
# 日志相关
```c
// 把标准错误和标准输出重定位到文件
bool setLogFile(const char *logFile)
{
if ((Logfilefd = open(Logfile, O_WRONLY | O_CREAT | O_APPEND, 0644)) == -1)
{
fprintf(stderr, "Open logfile %s failed.\n", Logfile);
return false;
}
close(1);
close(2);
dup2(Logfilefd, 1);
dup2(Logfilefd, 2);
close(Logfilefd);
return true;
}
#define LOG(fmt, ...) \
do { \
fprintf(stdout, "%s [LOG]:--"fmt"--%s:%d\n", \
GetCurrentTime(), ##__VA_ARGS__, __FILE__, __LINE__); \
} while (0)
#define ELOG(fmt, ...) \
do { \
fprintf(stderr, "%s [ERROR]:--"fmt"--%s:%d\n", \
GetCurrentTime(), ##__VA_ARGS__, __FILE__, __LINE__); \
} while (0)
#define DLOG(fmt, ...) \
do { \
if (EnableDebug) \
fprintf(stdout, "%s [DEBUG]:--"fmt"--%s:%d\n", \
GetCurrentTime(), ##__VA_ARGS__, __FILE__, __LINE__); \
} while (0)
# 二进制转十六机制
```c
// 把二进制转换成十六进制并以字符串形式写到文件
#define Bin2HexFp(fp,src,n) \
do { \
int _bi; \
for (_bi=0; _bi<n; _bi++) fprintf(fp, "%02X", (src)[_bi]); \
fprintf(fp, "\n"); \
} while (0)
```
# 阻塞
```c
bool SetNonblock(int socket)
{
int flag = 0;
if ((flag = fcntl(socket, F_GETFL, 0)) < 0)
return false;
if (fcntl(socket, F_SETFL, flag | O_NONBLOCK) < 0)
return false;
return true;
}
ssize_t BlockRead(int fd, void *buf, size_t n)
{
size_t nleft;
ssize_t nread;
unsigned char *pb;
pb = buf;
nleft = n;
while (nleft > 0)
{
if ((nread = read(fd, pb, nleft)) < 0)
{
if (errno == EINTR)
continue;
return -1;
}
else if (nread == 0) /* Peer close the connection */
return 0;
nleft -= nread;
pb += nread;
}
return n - nleft;
}
ssize_t BlockWrite(int fd, void *buf, size_t n)
{
size_t nleft;
ssize_t nwritten;
unsigned char *pb;
pb = buf;
nleft = n;
while (nleft > 0)
{
if ((nwritten = write(fd, pb, nleft)) < 0)
{
if (errno == EINTR)
nwritten = 0;
else
return -1;
}
else if (nwritten == 0)
return 0;
nleft -= nwritten;
pb += nwritten;
}
return n - nleft;
}
```
# 程序运行
```shell
const char *GetProgname(const char *argv0)
{
char *p;
p = strrchr(argv0, '/');
if (p == NULL)
return argv0;
else
return p+1;
}
char *MakeAbsolutePath(const char *path)
{
char *new;
if (path == NULL)
return NULL;
if (path[0] == '/')
{
new = strdup(path);
if (new == NULL)
return NULL;
}
else
{
char *buf;
size_t bufLen;
bufLen = 1024;
for (;;)
{
buf = malloc(bufLen);
if (buf == NULL)
return NULL;
if (getcwd(buf, bufLen))
break;
else if (errno == ERANGE)
{
free(buf);
bufLen *= 2;
continue;
}
else
{
free(buf);
return NULL;
}
}
new = malloc(strlen(buf) + strlen(path) + 2);
if (new == NULL)
{
free(buf);
return NULL;
}
sprintf(new, "%s/%s", buf, path);
free(buf);
}
return new;
}
bool IsAlreadyRunning(const char *path)
{
int fd;
char buf[16];
struct flock fl;
if ((fd = open(path, O_RDWR | O_CREAT, 0644)) == -1)
return true;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
fl.l_pid = getpid();
if (fcntl(fd, F_SETLK, &fl) == -1)
{
close(fd);
return true;
}
ftruncate(fd, 0);
snprintf(buf, 16, "%ld", (long)getpid());
write(fd, buf, strlen(buf)+1);
return false;
}
```
# 随机数
```c
void GenerateString(unsigned char *dest, int len)
{
int i;
char allChar[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int cLen = strlen(allChar);
srand(time(NULL));
for (i=0; i<len-1; i++)
{
*dest = allChar[rand() % cLen];
dest++;
}
*dest = '\0';
}
```
# 时间相关
```c
char *GetCurrentTime(void)
{
static char _CurrentTime[27];
struct timeval tv;
struct tm *tp;
snprintf(_CurrentTime, 27, "unknown time");
if (gettimeofday(&tv, NULL) == -1)
return _CurrentTime;
if ((tp = localtime(&tv.tv_sec)) == NULL)
return _CurrentTime;
snprintf(_CurrentTime, 27, "%04d-%02d-%02d %02d:%02d:%02d.%06ld",
tp->tm_year+1900, tp->tm_mon+1, tp->tm_mday,
tp->tm_hour, tp->tm_min, tp->tm_sec, tv.tv_usec);
return _CurrentTime;
}
```
# 数字判断
```c
bool IsDigitals(const char *s)
{
const char *p = s;
if (s == NULL || *s == '\0')
return false;
if (*p == '-')
p++;
for (; *p!='\0'; p++)
{
if (*p < '0' || *p > '9')
return false;
}
return true;
}
bool IsNonnegativeInteger(char *data)
{
char *p;
if (data == NULL || data[0] == '\0')
return false;
p = data;
for (p=data; *p!='\0'; p++)
{
if (*p<'0' || *p>'9')
return false;
}
return true;
}
```
# mac地址
```c
// 根据socket获取mac地址
bool GetLocalMac(int fd, char delimiter, char *mac, size_t macLen)
{
struct ifaddrs *ifaddr = NULL;
struct ifaddrs *ifp = NULL;
struct ifreq ifr;
struct sockaddr_in *inp;
char *ifname;
struct sockaddr_in in;
socklen_t inLen;
inLen = sizeof(in);
memset(&in, 0, inLen);
if (getsockname(fd, (struct sockaddr*)&in, &inLen) != 0)
return false;
if (getifaddrs(&ifaddr) != 0)
return false;
for (ifp=ifaddr; ifp!=NULL; ifp=ifp->ifa_next)
{
inp = (struct sockaddr_in*)ifp->ifa_addr;
if (inp != NULL &&
inp->sin_family == in.sin_family &&
inp->sin_addr.s_addr == in.sin_addr.s_addr)
break;
}
if (ifp == NULL)
{
freeifaddrs(ifaddr);
return false;
}
ifname = ifp->ifa_name;
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1)
{
freeifaddrs(ifaddr);
return false;
}
freeifaddrs(ifaddr);
snprintf(mac, macLen, "%02X%c%02X%c%02X%c%02X%c%02X%c%02X",
(unsigned char)ifr.ifr_hwaddr.sa_data[0], delimiter,
(unsigned char)ifr.ifr_hwaddr.sa_data[1], delimiter,
(unsigned char)ifr.ifr_hwaddr.sa_data[2], delimiter,
(unsigned char)ifr.ifr_hwaddr.sa_data[3], delimiter,
(unsigned char)ifr.ifr_hwaddr.sa_data[4], delimiter,
(unsigned char)ifr.ifr_hwaddr.sa_data[5]);
return true;
}
// 根据socket获取对端mac地址
bool GetPeerMac(int fd, struct sockaddr *from,
socklen_t fromLen, char delimiter, char *mac, size_t macLen)
{
struct ifaddrs *ifaddr = NULL;
struct ifaddrs *ifp = NULL;
struct sockaddr_in *inp;
char *ifname;
struct sockaddr_in in;
socklen_t inLen;
struct arpreq arp;
inLen = sizeof(in);
memset(&in, 0, inLen);
if (getsockname(fd, (struct sockaddr*)&in, &inLen) != 0)
return false;
if (getifaddrs(&ifaddr) != 0)
return false;
for (ifp=ifaddr; ifp!=NULL; ifp=ifp->ifa_next)
{
inp = (struct sockaddr_in*)ifp->ifa_addr;
if (inp != NULL &&
inp->sin_family == in.sin_family &&
inp->sin_addr.s_addr == in.sin_addr.s_addr)
break;
}
if (ifp == NULL)
{
freeifaddrs(ifaddr);
return false;
}
ifname = ifp->ifa_name;
memset(&arp, 0, sizeof(arp));
memcpy(&arp.arp_pa, from, fromLen);
strncpy(arp.arp_dev, ifname, 16);
if (ioctl(fd, SIOCGARP, &arp) == -1)
{
freeifaddrs(ifaddr);
return false;
}
freeifaddrs(ifaddr);
snprintf(mac, macLen, "%02X%c%02X%c%02X%c%02X%c%02X%c%02X",
arp.arp_ha.sa_data[0], delimiter,
arp.arp_ha.sa_data[1], delimiter,
arp.arp_ha.sa_data[2], delimiter,
arp.arp_ha.sa_data[3], delimiter,
arp.arp_ha.sa_data[4], delimiter,
arp.arp_ha.sa_data[5]);
return true;
}
```
# 参数处理
```shell
#include <fcntl.h>
#include <getopt.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#ifndef bool
typedef unsigned char bool;
#define true 1
#define false 0
#endif
#define _(x) (x)
#define ELOG(fmt, args...) \
do { \
fprintf(stderr, "[ERROR]:--"fmt"--%s:%d\n", \
##args, __FILE__, __LINE__); \
} while (0)
static const char *Progname;
static const char *SubProgram = NULL;
static char *Opts;
static void (*Func)(void);
static int ProductionLimit = -1;
static int ConnectionLimit = -1;
static time_t Deadline = 0xFFFFFFFF;
static char *UpdateFile = "./update.bin";
static char *Hid = NULL;
static char *Logo = "";
static char *Protocol = "CCID";
static bool SetNetwork = false;
static bool SetLogo = false;
static bool SetDeadline = false;
static bool SetUnlock = false;
static bool SetMotherMode = false;
static bool IsEmpty = false;
static bool EnableVerbose = false;
static bool EnableDebug = false;
static void Usage(void);
static void FormLogo(char *logo);
static bool StrToTime(const char *str, time_t *t);
static bool IsDigitals(const char *str);
const char *GetProgname(const char *argv0);
static void MCInit(void);
static void Init(void);
static void MakeUpdate(void);
static void Update(void);
static void Reset(void);
static void List(void);
static void SwitchProtocol(void);
static struct ExecStringOpts
{
char *string;
char *opts;
void (*func)(void);
} ExecStringOpts[] =
{
{"mcinit", "H:F:P:", MCInit},
{"init", "D:H:L:M:N:P:", Init},
{"makeupdate", "D:F:H:L:N:U1", MakeUpdate},
{"update", "H:F:", Update},
{"reset", "H:", Reset},
{"list", "H:v", List},
{"switch", "H:P:", SwitchProtocol},
{NULL, NULL, NULL}
};
int main(int argc, char **argv)
{
static struct option long_options[] = {
{"debug", no_argument, NULL, 'd'}, /* enable debug */
{"empty", no_argument, NULL, '1'}, /* is empty dongle */
{"local", no_argument, NULL, '2'}, /* is empty dongle */
{NULL, required_argument, NULL, 'D'}, /* deadline */
{NULL, required_argument, NULL, 'F'}, /* update file path */
{NULL, required_argument, NULL, 'H'}, /* hid */
{NULL, required_argument, NULL, 'L'}, /* logo */
{NULL, required_argument, NULL, 'M'}, /* init a mother dongle? default child dongle */
{NULL, required_argument, NULL, 'N'}, /* network client number */
{NULL, required_argument, NULL, 'P'}, /* admin pin */
{NULL , no_argument, NULL, 'U'}, /* unlock user pin */
{NULL , no_argument, NULL, 'v'}, /* list dongle verbose information */
{NULL, 0, NULL, 0}
};
int c, option_index;
int i;
Progname = GetProgname(argv[0]);
Opts = ExecStringOpts[i].opts;
Func = MCInit;
if (argc > 1)
{
for (i=0; ExecStringOpts[i].string!=NULL; i++)
{
if (strcasecmp(argv[1], ExecStringOpts[i].string) == 0)
{
SubProgram = ExecStringOpts[i].string;
Opts = ExecStringOpts[i].opts;
Func = ExecStringOpts[i].func;
argc--;
argv++;
break;
}
}
}
if (argc > 1)
{
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
{
Usage();
exit(0);
}
if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
{
exit(0);
}
}
while ((c = getopt_long(argc, argv, Opts, long_options, &option_index)) != -1)
{
switch (c)
{
case 'D':
SetDeadline = true;
if (!StrToTime(optarg, &Deadline))
{
ELOG("Time format error");
return 1;
}
break;
case 'd':
EnableDebug = true;
break;
case 'F':
UpdateFile = optarg;
break;
case 'H':
Hid = optarg;
break;
case 'L':
SetLogo = true;
Logo = optarg;
FormLogo(Logo);
break;
case 'M':
SetMotherMode = true;
if (!IsDigitals(optarg))
{
ELOG("Option format error");
return 1;
}
ProductionLimit = atoi(optarg);
break;
case 'N':
SetNetwork = true;
if (!IsDigitals(optarg))
{
ELOG("Option format error");
return 1;
}
ConnectionLimit = atoi(optarg);
break;
case 'P':
Protocol = optarg;
break;
case 'U':
SetUnlock = true;
break;
case 'v':
EnableVerbose = true;
break;
case '1':
IsEmpty = true;
break;
default:
if (SubProgram != NULL)
fprintf(stderr, "Try \"%s %s --help\" for more information.\n",
Progname, SubProgram);
else
fprintf(stderr, "Try \"%s --help\" for more information.\n",
Progname);
return 1;
}
}
if (optind < argc)
{
fprintf(stderr, "Invalid argument: \"%s\".\n", argv[optind]);
return 1;
}
Func();
return 0;
}
static void Usage(void)
{
printf(_("%s is a super dongle tool.\n\n"), Progname);
printf(_("Usage:\n"));
if (SubProgram == NULL || *SubProgram == '\0')
{
printf(_(" %s [mcinit] [OPTION]\n"), Progname);
printf(_(" %s init [OPTION]\n"), Progname);
printf(_(" %s mamkeupdate [OPTION]\n"), Progname);
printf(_(" %s update [OPTION]\n"), Progname);
printf(_(" %s reset [OPTION]\n"), Progname);
printf(_(" %s list [OPTION]\n"), Progname);
printf(_(" %s switch [OPTION]\n"), Progname);
}
else
printf(_(" %s %s [OPTION]\n"), Progname, SubProgram);
printf(_("\nOptions:\n"));
if (strchr(Opts, 'D') != NULL)
{
printf(_(" -D DEADLINE set expiration time\n"));
printf(_(" \"unlimited\"\n"));
printf(_(" \"yyyy-mm-dd hh:mm:ss\" (1977-06-23 23:00:00 ~ 2038-01-19 11:14:07)\n"));
printf(_(" \"hours\" (1 ~ 65535)\n"));
}
if (strchr(Opts, 'F') != NULL)
printf(_(" -F FILE update file path (default %s)\n"), UpdateFile);
if (strchr(Opts, 'H') != NULL)
printf(_(" -H HID dongle hid\n"));
if (strchr(Opts, 'L') != NULL)
{
printf(_(" -L LOGO logo separated by \";\"\n"));
printf(_(" \"CustomerName: xxx;ProjectCode: 0x123;ProjectName: yyy\"\n"));
}
if (strchr(Opts, 'M') != NULL)
printf(_(" -M NUM initialize a mother dongle\n"));
if (strchr(Opts, 'N') != NULL)
printf(_(" -N NUM set to network mode, and set connection limit"
"(default local mode)\n"));
if (strchr(Opts, 'P') != NULL)
printf(_(" -P PROTOCOL communication protocol, default CCID\n"));
if (strchr(Opts, 'U') != NULL)
printf(_(" -U unlock user pin\n"));
if (strchr(Opts, 'v') != NULL)
printf(_(" -v view details\n"));
if (strchr(Opts, '1') != NULL)
printf(_(" --empty empty dongle\n"), UpdateFile);
printf(_(" -?,--help show help\n"));
}
static void FormLogo(char *logo)
{}
static bool StrToTime(const char *str, time_t *t)
{
struct tm tm;
if (strcasecmp(str, "unlimited") == 0) /* unlimited */
{
*t = 0xFFFFFFFF;
return true;
}
if (sscanf(str, "%d-%d-%d %d:%d:%d",
&tm.tm_year, &tm.tm_mon, &tm.tm_mday,
&tm.tm_hour, &tm.tm_min, &tm.tm_sec) == 6) /* xxxx-xx-xx xx:xx:xx */
{
if (tm.tm_year < 1977 || tm.tm_year > 2038 ||
tm.tm_mon < 1 || tm.tm_mon > 12 ||
tm.tm_mday < 1 || tm.tm_mday > 31 ||
tm.tm_hour > 24 || tm.tm_min > 60 || tm.tm_sec > 60)
return false;
if (tm.tm_year == 1977 &&
(tm.tm_mon < 6 ||
(tm.tm_mon == 6 &&
(tm.tm_mday < 23 ||
(tm.tm_mday == 23 &&
(tm.tm_hour < 23))))))
return false;
if (tm.tm_year == 2038 &&
(tm.tm_mon > 1 ||
(tm.tm_mon == 1 &&
(tm.tm_mday > 19 ||
(tm.tm_mday == 19 &&
(tm.tm_hour > 11 ||
(tm.tm_hour == 11 &&
(tm.tm_min > 14 ||
(tm.tm_min == 14 &&
(tm.tm_sec > 7))))))))))
return false;
tm.tm_year -= 1900;
tm.tm_mon--;
tm.tm_isdst = -1;
if ((*t = mktime(&tm)) == -1)
return false;
return true;
}
/* xxx hours */
if (!IsDigitals(str))
return false;
*t = atoi(str);
if (*t < 1 || *t > 0xFFFF)
return false;
return true;
}
static bool IsDigitals(const char *str)
{
return true;
}
const char *GetProgname(const char *argv0)
{
char *p;
p = strrchr(argv0, '/');
if (p == NULL)
return argv0;
else
return p+1;
}
static void MCInit(void)
{}
static void Init(void)
{}
static void MakeUpdate(void)
{}
static void Update(void)
{}
static void Reset(void)
{}
static void List(void)
{}
static void SwitchProtocol(void)
{}
```
<file_sep>/source/about/index.md
---
title: about
date: 2017-11-03 10:37:30
type: about
comments: false
---
<file_sep>/source/_posts/CentOS安装微信.md
---
layout: _post
title: CentOS安装微信
date: 2020-09-01 10:23:44
categories: 操作系统
tags:
- 微信
- wechat
---
# CentOS安装微信
系统版本:`CentOS Linux release 7.7.1908 (Core)`
## 安装docker
### 配置docker的yum源
```shell
$ sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
$ sudo yum-config-manager --enable docker-ce-nightly
$ sudo yum-config-manager --enable docker-ce-test
$ sudo yum-config-manager --disable docker-ce-nightly
```
### 安装docker-ce
```shell
$ sudo yum install docker-ce
```
### 启动docker
```shell
$ sudo systemctl start docker
$ sudo systemctl enable docker
```
## 安装微信
### 拉取docker微信镜像
bestwu/wechat是基于deepin的镜像,内部包含基于deepin-wine的微信。
```shell
$ sudo docker pull bestwu/wechat
```
### 创建微信容器
```shell
$ sudo docker run -d --name wechat --device /dev/snd \
-v /tmp/.X11-unix:/tmp/.X11-unix \
-v $HOME/.WeChatFiles:/WeChatFiles \
-e DISPLAY=unix$DISPLAY \
-e XMODIFIERS=@im=ibus \
-e QT_IM_MODULE=ibus \
-e GTK_IM_MODULE=ibus \
-e AUDIO_GID=`getent group audio | cut -d: -f3` \
-e GID=`id -g` \
-e UID=`id -u` \
bestwu/wechat
```
> 上述是基于fcitx的输入法框架,如果是ibus,把上述fcitx都换成ibus即可。
### 启动微信容器
第一次使用`docker run`创建并启动微信容器,以后每次使用`docker start`启动微信容器。
```shell
$ sudo docker start wechat
```
<file_sep>/source/_posts/hostname的那点事.md
---
title: hostname的那点事
date: 2017-09-19
tags: hostname
categories: 操作系统
---
# hostname的本质
hostname是Linux下的一个内核参数,保存在/proc/sys/kernel/hostname下,它的值是Linux启动时从rc.sysinit读取的.而/etc/rc.d/rc.sysinit中HOSTNAME的取值来自于/etc/sysconfig/network下的HOSTNAME.
> Linux的启动过程:
1. 加载BIOS
2. 读取MBR
3. Boot Loader / Grup
4. 加载内核
5. 用户层init依据inittab文件来设定运行等级
6. init进程执行rc.sysinit
7. 启动内核驱动模块
8. 执行不同运行级别的脚本程序(/etc/rc.d/rc$RUNLEVEL)
9. 执行/etc/rc.d/rc.local
10. 执行/bin/login程序,进入登录状态
/etc/sysconifg/network内容如下:
```bash
NETWORKING=yes
HOSTNAME==server-111
```
/etc/rc.d/rc.sysinit相关代码如下:
```bash
......
HOSTNAME=$(/bin/hostname)
set -m
if [ -f /etc/sysconfig/network ]; then
. /etc/sysconfig/network
fi
if [ -z "$HOSTNAME" -o "$HOSTNAME" = "(none)" ]; then
HOSTNAME=localhost
fi
......
# Set the hostname.
update_boot_stage RChostname
......
```
# 修改hostname
修改hostname有几种方式:
1. `hostname DB-Server` \-\- 运行后立即生效(新会话生效),系统重启后会丢失所做的修改
2. `echo DB-Server > /proc/sys/kernel/hostname` \-\- 运行后立即生效(新会话生效),系统重启后会丢失所做的修改
3. `sysctl kernel.hostname=DB-Server` \-\- 运行后立即生效(新会话生效),系统重启后会丢失所做的修改
4. 修改`/etc/sysconfig/network`下的`HOSTNAME`变量 \-\- 需重启系统生效,永久性修改
修改了hostname后,如何使其立即生效而不用重启操作系统?
先按照步骤四修改,然后从前3步中任选一个执行
# hostname与/etc/hosts
hosts的作用相当于DNS,提供IP地址到hostname的对应.早期的互联网计算机数量少,单机hosts文件里足够存放所有联网计算机.不过随着互联网的发展,这就远远不够了.于是就出现了分布式的DNS系统.由DNS服务器来提供类似的IP地址到域名的对应.具体可以man hosts查看相关信息.
Linux系统在向DNS服务器发出域名解析请求之前会查询/etc/hosts文件,如果里面有相应的记录,就会使用hosts里面的记录.
/etc/hosts文件通常里面包含这一条记录127.0.0.1 localhost.localdomain localhost.hosts文件格式是一行一条记录,分别是IP地址、hostname、aliases,三者用空白字符分隔,aliases可选.
127.0.0.1到localhost这一条建议不要修改,因为很多应用程序会用到这个,比如sendmail,修改之后这些程序可能就无法正常运行.
但是,其实hostname也不是说跟/etc/hosts一点关系都没有.在/etc/rc.d/rc.sysinit中,有如下逻辑判断,当hostname为localhost后localhost.localdomain时,将会使用接口IP地址对应的hostname来重新设置系统的hostname.
<file_sep>/source/_posts/Greenplum编译.md
---
layout: _post
title: Greenplum编译
date: 2018-07-10 19:34:45
tags:
- PostgreSQL
- Greenplum
categories: Database
---
> 操作系统:centos6.4 x64最小安装
# 添加用户
```shell
$ useradd gpadmin
$ passwd gpadmin
```
把gpadmin加入sudoer,之后的操作都在gpadmin用户下完成。
# 搭建开发环境
```shell
# linux基本环境
$ sudo yum install -y bzip2 cmake gcc gcc-c++ gdb git libtool lrzsz make man net-tools sysstat unzip vim wget zip
# 数据库开发环境
$ sudo yum install -y apr-devel apr-util-devel bison bzip2-devel c-ares-devel flex java-1.8.0-openjdk java-1.8.0-openjdk-devel json-c-devel krb5-devel libcurl-devel libevent-devel libkadm5 libxml2-devel libxslt-devel libyaml-devel openldap-devel openssl-devel pam-devel perl perl-devel perl-ExtUtils-Embed readline-devel unixODBC-devel zlib-devel
```
一般来说,上面安装的开发包足够一般的数据库编译或安装使用了。
> 如果Greenplum版本较新(>=5X_STABLE),CentOS 6.4官方的开发包版本可能无法满足Greenplum(比如glibc不支持C11标准,python版本较低、cmake版本较低等),也可能会缺少一些其他的包。
>
> 可以通过源码编译或者非官方yum源安装合适的版本。
# 编译开发包
## gcc-4.8.5
Greenplum较新的代码要用到C11/C++11标准,要求gcc版本4.7以上。由于系统自带或yum安装的gcc版本是4.4.7,需要编译更高版本的gcc。
编译gcc需要先编译gmp、mpfr、mpc,按照顺序编译安装。
```shell
# 编译gmp
$ wget https://gmplib.org/download/gmp/gmp-6.1.0.tar.bz2
$ tar -jxf gmp-6.1.0.tar.bz2
$ cd gmp-6.1.0
$ ./configure --prefix=/home/gpadmin/BuildEnv/gcc
$ make && make install
# 编译mpfr
$ wget https://www.mpfr.org/mpfr-3.1.4/mpfr-3.1.4.tar.bz2
$ tar -jxf mpfr-3.1.4.tar.bz2
$ cd mpfr-3.1.4
$ ./configure --prefix=/home/gpadmin/BuildEnv/gcc --with-gmp=/home/gpadmin/BuildEnv/gcc
make && make install
# 编译mpc
$ wget https://ftp.gnu.org/gnu/mpc/mpc-1.0.3.tar.gz
$ tar -zxf mpc-1.0.3.tar.gz
$ cd mpc-1.0.3
$ ./configure --prefix=/home/gpadmin/BuildEnv/gcc --with-gmp=/home/gpadmin/BuildEnv/gcc --with-mpfr=/home/gpadmin/BuildEnv/gcc
$ make && make install
# 编译gcc
$ wget ftp://gcc.gnu.org/pub/gcc/releases/gcc-4.8.5/gcc-4.8.5.tar.bz2
$ tar -jxf gcc-4.8.5.tar.bz2
$ cd gcc-4.8.5
$ export LD_LIBRARY_PATH=/home/gpadmin/BuildEnv/gcc/lib:$LD_LIBRARY_PATH
$ ./configure --prefix=/home/gpadmin/BuildEnv/gcc --with-gmp=/home/gpadmin/BuildEnv/gcc --with-mpfr=/home/gpadmin/BuildEnv/gcc --with-mpc=/home/gpadmin/BuildEnv/gcc --disable-multilib
$ make && make install
# 设置环境变量
$ vi ~/.bashrc
export LD_LIBRARY_PATH=/home/gpadmin/BuildEnv/gcc/lib:/home/gpadmin/BuildEnv/gcc/lib64:$LD_LIBRARY_PATH
export PATH=/home/gpadmin/BuildEnv/gcc/bin:$PATH
$ source ~/.bashrc
```
## cmake3
gporca要求cmake版本3.1以上,系统自带或者yum安装的cmake是cmake-2.8,需要编译更高版本cmake。
```shell
$ wget https://cmake.org/files/v3.10/cmake-3.10.3.tar.gz
$ tar -zxf cmake-3.10.3.tar.gz
$ cd cmake-3.10.3
$ ./configure --prefix=/home/gpadmin/BuildEnv/cmake
$ make && make install
$ vi ~/.bashrc
export LD_LIBRARY_PATH=/home/gpadmin/BuileEnv/cmake/lib:$LD_LIBRARY_PATH
export PATH=/home/gpadmin/BuildEnv/cmake/bin:$PATH
$ source ~/.bashrc
```
## python-2.7
greeplum要求python 2.7以上,系统自带或yum安装的python是2.6,需要编译新版本。
```shell
# 编译python
$ wget https://www.python.org/ftp/python/2.7.14/Python-2.7.14.tgz
$ tar -xf Python-2.7.14.tgz
$ cd Python-2.7.14
$ ./configure --prefix=/home/gpadmin/BuildEnv/python --enable-optimizations -enable-shared CFLAGS=-fPIC
$ make && make install
# 设置环境变量
$ vi ~/.bashrc
export LD_LIBRARY_PATH=/home/gpadmin/BuildEnv/python/lib:$LD_LIBRARY_PATH
export PATH=/home/gpadmin/BuildEnv/python/bin:$PATH
$ source ~/.bashrc
# 安装pip
$ python -m ensurepip
$ pip install --upgrade pip
# 安装python模块
$ pip install psutil lockfile paramiko setuptools
```
> python2.6+yum的使用:
>
> 安装python和工具:sudo yum install -y python python-setuptools python-devel python-crypto python-paramiko
>
> 安装python模块:
> sudo easy_install lockfile
> sudo easy_install psi
## ninja
```shell
$ wget https://github.com/ninja-build/ninja/releases/download/v1.8.2/ninja-linux.zip
$ mkdir -p /home/gpadmin/BuildEnv/ninja/bin
$ unzip -d /home/gpadmin/BuildEnv/ninja/bin ninja-linux.zip
$ vi ~/.bashrc
$ export PATH=/home/gpadmin/BuildEnv/ninja/bin:$PATH
$ source ~/.bashrc
```
## geos+proj+gdal
```shell
# geos
$ wget http://download.osgeo.org/geos/geos-3.4.2.tar.bz2
$ tar xjf geos-3.4.2.tar.bz2
$ cd geos-3.4.2
$ ./configure --prefix=/home/gpadmin/BuildEnv/geos
$ make && make install
# proj
$ wget http://download.osgeo.org/proj/proj-4.9.1.tar.gz
$ tar xzf proj-4.9.1.tar.gz
$ cd proj-4.9.1
$ ./configure --prefix=/home/gpadmin/BuildEnv/proj
$ make && make install
# gdal
$ wget http://download.osgeo.org/gdal/1.11.2/gdal-1.11.2.tar.gz
$ tar xzf gdal-1.11.2.tar.gz
$ cd gdal-1.11.2
$ ./configure --prefix=/home/gpadmin/BuildEnv/gdal
$ make && make install
# 设置环境变量
$ vi ~/.bashrc
export LD_LIBRARY_PATH=/home/gpadmin/BuildEnv/geos/lib:/home/gpadmin/BuildEnv/proj/lib:/home/gpadmin/BuildEnv/gdal/lib:$LD_LIBRARY_PATH
export PATH=/home/gpadmin/BuildEnv/geos/bin:/home/gpadmin/BuildEnv/proj/bin:/home/gpadmin/BuildEnv/gdal/bin:$PATH
$ source ~/.bashrc
```
## libevent
```shell
$ wget https://github.com/downloads/libevent/libevent/libevent-2.0.20-stable.tar.gz
$ tar xf libevent-2.0.20-stable.tar.gz
$ cd libevent-2.0.20-stable
$ ./configure --prefix=/home/gpadmin/BuildEnv/libevent
$ make && make install
$ vi ~/.bashrc
export LD_LIBRARY_PATH=/home/gpadmin/BuildEnv/libevent/lib:$LD_LIBRARY_PATH
export PATH=/home/gpadmin/BuildEnv/libevent/bin:$PATH
$ source ~/.bashrc
```
## Apache Maven
```shell
$ wget http://mirrors.hust.edu.cn/apache/maven/maven-3/3.5.4/binaries/apache-maven-3.5.4-bin.tar.gz
$ tar -zxf apache-maven-3.5.4-bin.tar.gz -C /home/gpadmin/BuildEnv/
$ mv /home/gpadmin/BuildEnv/apache-maven-3.5.4 /home/gpadmin/BuildEnv/apache-maven
$ vi ~/.bashrc
export PATH=/home/gpadmin/BuildEnv/apache-maven/bin:$PATH
$ souce ~/.bashrc
```
# 编译gporca
```shell
# gp-xerces
$ git clone git://github.com/Greenplum-db/gp-xerces.git
$ cd gp-xerces/
$ mkdir build
$ cd build
$ ../configure --prefix=/home/gpadmin/gporca
$ make && make install
# gporca
$ git clone git://github.com/Greenplum-db/gporca.git
$ cd gporca
$ cmake -GNinja -D CMAKE_INSTALL_PREFIX=/home/gpadmin/gporca -D XERCES_LIBRARY=/home/gpadmin/gporca/lib/libxerces-c.so -D XERCES_INCLUDE_DIR=/home/gpadmin/gporca/include -H. -Bbuild
$ ninja install -C build
$ vi ~/.bashrc
export LD_LIBRARY_PATH=/home/gpadmin/gporca/lib:$LD_LIBRARY_PATH
export PATH=/home/gpadmin/gporca/bin:$PATH
$ source ~/.bashrc
```
# 编译gpdb
```shell
$ git clone git://github.com/Greenplum-db/gpdb.git
$ cd gpdb
$ export LIBRARY_PATH=/home/gpadmin/gporca/lib:$LIBRARY_PATH
$ export C_INCLUDE_PATH=/home/gpadmin/gporca/include:$C_INCLUDE_PATH
$ export CPLUS_INCLUDE_PATH=/home/gpadmin/gporca/include:$CPLUS_INCLUDE_PATH
$ ./configure --with-perl --with-python --with-libxml --with-gssapi --prefix=/home/gpadmin/gpdb
$ make && make install
```
# 编译postgis
> PostGIS 2.1.5 for GreenPlum 5.x+
```shell
$ git clone git://github.com/Greenplum-db/geospatial.git
$ source /home/gpadmin/gpdb/greenplum_path.sh
$ cd geospatial/postgis/build/postgis-2.1.5/
$ ./configure --prefix=$GPHOME --with-pgconfig=$GPHOME/bin/pg_config --with-raster --without-topology --with-projdir=/home/gpadmin/BuildEnv/proj
$ make USE_PGXS=1 clean all install
# 安装postgis
$ psql -d postgres -f ${GPHOME}/share/postgresql/contrib/postgis-2.1/postgis.sql
$ psql -d postgres -f ${GPHOME}/share/postgresql/contrib/postgis-2.1/postgis_comments.sql
$ psql -d postgres -f ${GPHOME}/share/postgresql/contrib/postgis-2.1/rtpostgis.sql
$ psql -d postgres -f ${GPHOME}/share/postgresql/contrib/postgis-2.1/raster_comments.sql
$ psql -d postgres -f ${GPHOME}/share/postgresql/contrib/postgis-2.1/spatial_ref_sys.sql
$ vi $GPHOME/greenplum_path.sh
export GDAL_DATA=$GPHOME/share/gdal
export POSTGIS_ENABLE_OUTDB_RASTERS=0
export POSTGIS_GDAL_ENABLED_DRIVERS=DISABLE_ALL
$ gpstop –r //重启数据库
```
# 编译pgbouncer
```shell
$ git clone -b pgbouncer_1_8_1 git://github.com/Greenplum-db/pgbouncer.git
$ cd pgbouncer
$ git submodule init
$ git submodule update
$ ./autogen.sh
$ ./configure --prefix=/home/gpadmin/pgbouncer
$ make && make install
$ vi ~/.bashrc
export PATH=/home/gpadmin/pgbouncer/bin:$PATH
$ source ~/.bashrc
```
# 编译jdbc
```shell
$ wget https://jdbc.postgresql.org/download/postgresql-jdbc-42.2.2.src.tar.gz --no-check-certificate
$ tar -zxf postgresql-jdbc-42.2.2.src.tar.gz
$ cd postgresql-jdbc-42.2-2.src/pgjdbc/
$ mvn package –DskipTests
$ cp target/postgresql-42.2.2.jar /home/gpadmin/gpdb/lib
```
# 编译odbc
```shell
$ wget https://ftp.postgresql.org/pub/odbc/versions/src/psqlodbc-09.03.0400.tar.gz --no-check-certificate
$ tar -xf psqlodbc-09.03.0400.tar.gz
$ cd psqlodbc-09.03.0400
$ ./configure --prefix=/home/gpadmin/psqlodbc
$ make && make install
```
测试:
```shell
$ sudo vi /etc/odbcinst.ini
[PostgreSQL]
Description = ODBC for PostgreSQL
Driver = /home/gpadmin/psqlodbc/lib/psqlodbcw.so
Setup = /usr/lib/libodbcpsqlS.so
Driver64 = /home/gpadmin/psqlodbc/lib/psqlodbcw.so
Setup64 = /usr/lib64/libodbcpsqlS.so
FileUsage = 1
$ vi ~/.odbc.ini
[gp]
Description = Test to gp
Driver = PostgreSQL
Database = postgres
Servername = 127.0.0.1
UserName = gpadmin
Password = <PASSWORD>
Port = 5432
ReadOnly = 0
$ source /home/gpadmin/gpdb/greenplum_path.sh
$ isql gp
```
# 附:CentOS 7.0编译gpdb
> CentOS 7.0最小化安装
系统设置:
```shell
# 关闭防火墙
systemctl stop firewalld
systemctl disable firewalld
# 关闭selinux
setenforce 0
vi /etc/selinux/config
SELINUX=disabled
# 配置ip,网络等
# 安装基本环境
yum install -y bzip2 git lrzsz sysstat unzip vim wget zip
# 添加用户
$ useadd gpadmin
$ passwd gpadmin
$ su - gpadmin
# 下载代码
$ mkdir /home/gpadmin/code
$ cd /home/gpadmin/code
$ git clone https://github.com/greenplum-db/gpdb.git
# 安装开发环境
$ sudo ln -sf /bin/cmake3 /usr/local/bin/cmake
$ cd /home/gpadmin/code/gpdb
$ ./README.CentOS.bash
# 系统配置
$ sudo bash -c 'cat >> /etc/sysctl.conf <<-EOF
kernel.shmmax = 500000000
kernel.shmmni = 4096
kernel.shmall = 4000000000
kernel.sem = 500 1024000 200 4096
kernel.sysrq = 1
kernel.core_uses_pid = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.msgmni = 2048
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_forward = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.conf.all.arp_filter = 1
net.ipv4.ip_local_port_range = 1025 65535
net.core.netdev_max_backlog = 10000
net.core.rmem_max = 2097152
net.core.wmem_max = 2097152
vm.overcommit_memory = 2
EOF'
$ sudo bash -c 'cat >> /etc/security/limits.conf <<-EOF
* soft nofile 65536
* hard nofile 65536
* soft nproc 131072
* hard nproc 131072
EOF'
$ sudo bash -c 'cat >> /etc/ld.so.conf <<-EOF
/usr/local/lib
EOF'
# 编译gporca
$ cd /home/gpadmin/code/gpdb/depends
$ ./configure --prefix=/home/gpadmin/gpdb
$ make && make install
# 编译gpdb
$ LD_LIBRARY_PATH=/home/gpadmin/gpdb/lib ./configure \
--with-libraries=/home/gpadmin/gpdb/lib \
--with-includes=/home/gpadmin/gpdb/include \
--with-perl --with-python --with-libxml --with-gssapi --prefix=/home/gpadmin/gpdb
$ LD_LIBRARY_PATH=/home/gpadmin/gpdb/lib make install
```
<file_sep>/source/categories/index.md
---
title: categories
date: 2017-11-02 17:29:38
type: categories
comments: false
---
<file_sep>/source/_posts/冒泡排序.md
---
title: 冒泡排序
date: 2017-10-22
tags: 排序
categories: 算法
---
# 介绍
冒泡排序(Bubble Sort)一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作重复地进行直到没有再需要交换。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
# 步骤
1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
3. 针对所有的元素重复以上的步骤,除了最后一个。
4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
# 排序效果

# 实现
```c
#include <stdio.h>
#include <stdlib.h>
static void RandInitArray(int *arr, int num);
static void PrintArray(int *arr, int num);
static void BubbleSortAsc(int *arr, int num);
#define ARR_SIZE 20
int main()
{
int arr[ARR_SIZE];
RandInitArray(arr, ARR_SIZE);
PrintArray(arr, ARR_SIZE);
BubbleSortAsc(arr, ARR_SIZE);
PrintArray(arr, ARR_SIZE);
return 0;
}
static void RandInitArray(int *arr, int num)
{
int i;
for (i=0; i<num; i++)
arr[i] = random()%100;
}
static void PrintArray(int *arr, int num)
{
int i;
for (i=0; i<num; i++)
printf("%d ", arr[i]);
printf("\n");
}
static void BubbleSortAsc(int *arr, int num)
{
int i, j;
int move;
int tmp;
for (i=0; i<num-1; i++)
{
move = 0;
for (j=0; j<num-1-i; j++)
{
if (arr[j] > arr[j+1])
{
move = 1;
tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
if (move == 0)
return;
}
}
```
# 排序方法比较

<file_sep>/source/_posts/PostgreSQL内存上下文.md
---
layout: _post
title: PostgreSQL内存上下文
date: 2018-01-11 15:05:42
tags:
- PostgreSQL
- 内存管理
categories: Database
---
# 内存管理体系结构

---
# 内存上下文
内存上下文(MemoryContext)借鉴了操作系统的一些概念。
操作系统为每个进程分配了进程执行环境,进程之间互不影响,由操作系统来对环境进行切换,进程可以在其进程环境中调用内存操作函数:malloc、free、realloc等。
类似的,一个内存上下文实际上相当于一个进程环境,PostgreSQL以类似的方式提供了在内存上下文进行内存操作的函数:palloc、pfree、repalloc等。
每个进程/线程有多个私有的内存上下文,组成上下文树。
---
# 内存上下文树

- 每个线程都有多个内存上上下文,组成树形结构。线程所有的内存操作都在各种语义的上下文中进行。
- 释放上下文节点会释放其所有的子节点。
- 线程退出时释放TopMemoryContext。
---
# 术语
- MemoryContext
- AllocSetContext
- Block
- Chunk
- 超大块
- Chunk Free List
---
# 内存上下文结构

---
# 数据结构
- MemoryContext
- MemoryContextMethods
- AllocSet
- AllocBlockData
- AllocChunkData
---
## MemoryContext
```c
typedef struct MemoryContextData
{
NodeTag type; /* identifies exacts kind of context */
MemoryContextMethods *methods; /* virtual function table */
MemoryContext parent; /* NULL if no parent (toplevel context) */
MemoryContext firstchild; /* head of linked list of children */
MemoryContext nextchild; /* next child of same parent */
char *name; /* context name (just for debugging) */
} MemoryContextData;
typedef struct MemoryContextData *MemoryContext;
```
MemoryContext中的methods字段是一个MemoryContextMethods类型,它是由一系列的函数指针组成的集合,其中包含了对内存上下文操作的函数。对不同的MemoryContext实现,可以设置不同的方法集合。目前MemoryContext中只有AllocSetContext一种实现,因此PostgreSQL中只有针对AllocSetContext的一种操作函数集合,由全局变量AllocSetMethods表示。
---
## MemoryContextMethods
```c
typedef struct MemoryContextMethods
{
void *(*alloc) (MemoryContext context, Size size);
/* call this free_p in case someone #define's free() */
void (*free_p) (MemoryContext context, void *pointer);
void *(*realloc) (MemoryContext context, void *pointer, Size size);
void (*init) (MemoryContext context);
void (*reset) (MemoryContext context);
void (*delete) (MemoryContext context);
void (*reuse) (MemoryContext context);
Size (*get_chunk_space) (MemoryContext context, void *pointer);
bool (*is_empty) (MemoryContext context);
void (*stats) (MemoryContext context);
bool (*is_realempty)(MemoryContext context);
#ifdef MEMORY_CONTEXT_CHECKING
void (*check) (MemoryContext context);
#endif
} MemoryContextMethods;
```
---
## 方法集
```c
static MemoryContextMethods AllocSetMethods = {
AllocSetAlloc,
AllocSetFree,
AllocSetRealloc,
AllocSetInit,
AllocSetReset,
AllocSetDelete,
AllocSetReuse,
AllocSetGetChunkSpace,
AllocSetIsEmpty,
AllocSetStats,
AllocSetIsRealEmpty
#ifdef MEMORY_CONTEXT_CHECKING
,AllocSetCheck
#endif
};
```
---
MemoryContext是一个抽象类,可以有多个实现,目前只有AllocSetContext一个实现。MemoryContext并不管理实际上的内存分配,仅仅用作对MemoryContext树的控制。管理一个内存上下文中的内存块时通过AllocSet结构来完成的,MemoryContext作为AllocSet的头部信息存在。
---
## AllocSet
```c
typedef struct AllocSetContext
{
MemoryContextData header; /* Standard memory-context fields */
/* Info about storage allocated in this context: */
AllocBlock blocks; /* head of list of blocks in this set */
AllocChunk freelist[ALLOCSET_NUM_FREELISTS]; /* free chunk lists */
bool isReset; /* T = no space alloced since last reset */
/* Allocation parameters for this context: */
Size initBlockSize; /* initial block size */
Size maxBlockSize; /* maximum block size */
Size nextBlockSize; /* next block size to allocate */
AllocBlock keeper; /* if not NULL, keep this block over resets */
} AllocSetContext;
typedef AllocSetContext *AllocSet;
```
blocks是内存块链表,freelist是内存片链表。AllocSet所管理的内存区域被分成若干个内存块(AllocBlockData结构),每个内存块又被分成多个内存片(AllocChunkData结构)。palloc申请到的内存实际上都是内存片(除了超大块)。
---
## AllocBlockData
```c
typedef struct AllocBlockData
{
AllocSet aset; /* aset that owns this block */
AllocBlock next; /* next block in aset's blocks list */
char *freeptr; /* start of free space in this block */
char *endptr; /* end of space in this block */
} AllocBlockData;
```
---
## AllocChunkData
```c
typedef struct AllocChunkData
{
/* aset is the owning aset if allocated, or the freelist link if free */
void *aset;
/* size is always the size of the usable space in the chunk */
Size size;
#ifdef MEMORY_CONTEXT_CHECKING
/* when debugging memory usage, also store actual requested size */
/* this is zero in a free chunk */
Size requested_size;
#endif
} AllocChunkData;
```
---

---
# 重要函数
| 函数 | 功能 |
| --------------------- | ------------- |
| MemoryContextCreate | 创建上下文节点 |
| AllocSetContextCreate | 创建上下文实例 |
| MemoryContextDelete | 删除内存上下文 |
| MemoryContextReset | 重置内存上下文 |
| MemoryContextSwitchTo | 切换当前上下文 |
| palloc | 在当前上下文中申请内存 |
| pfree | 释放内存 |
| repalloc | 在当前上下文中重新申请内存 |
---
## 总体流程

---
## palloc流程

---
## pfree流程

---
# 重要的内存上下文
| 内存上下文 | 生命周期 | 描述 |
| --------------------- | ----------- | ------------------------------- |
| TopMemoryContext | session | 根节点 |
| PostmasterContext | session | postmaster工作上下文 |
| CacheMemoryContext | session | backend的relcache、catcache等使用 |
| MessageContext | session | 保存从前端传来的命令以及派生的存储,比如查询计划树和查询分析树 |
| TopTransactionContext | transaction | 一般保存跨越多个子事务的状态和控制信息 |
| CurTransactionContext | transaction | 当前事务上下文 |
---
| 内存上下文 | 生命周期 | 描述 |
| ------------- | ------- | ---------------------------------------- |
| PortalContext | portal | 全局变量,指向当前portal |
| ErrorContext | session | 错误处理上下文, errstart、errfinish、errmsg等在此分配内存 |
---
# 打印内存上下文树
in smmgr/aset.c, add `#include "utils/memutils.h"`
in AllocSetContextCreate function, add
```c
fprintf(stderr, "pid=%d, Create Memory Context name is %s, parent context is %s\n",
MyProcPid, name, (parent == NULL ? "null" : parent->name));
```
in mmgr/mcxt.c, add `#include "miscadmin.h"`
in MemoryContextDelete function, add
```c
fprintf(stderr, "pid=%d, delete memory context name is %s, parent is %s\n",
MyProcPid, context->name, (context->parent == NULL? 'null' : context->parent->name));
```
in MemoryContextReset function, add
```c
fprintf(stderr, "pid=%d, reset memory context name is %s, parent is %s\n",
MyProcPid, context->name, (context->parent == NULL? 'null' : context->parent->name));
```
---
# 代码结构
```
src/backend/utils/mmgr/mcxt.c
src/backend/utils/mmgr/aset.c
src/include/utils/memutils.h
src/include/nodes/memnodes.h
```
<file_sep>/source/_posts/gdb.md
---
title: gdb
date: 2017-10-23
tags: gdb
categories: 调试
---
# 信号处理
gdb对信号处理有三类动作:停止、打印、传给程序。
```shell
info handle # 查看所有信号的处理方式
handle SIGUSR2 nostop noprint pass #设置信号处理方式
```
| 动作 | 解释 |
| ------- | ---------- |
| print | 收到信号打印 |
| noprint | 收到信号不打印 |
| stop | 收到信号中断 |
| notop | 收到信号不中断 |
| pass | 收到信号传递给程序 |
| nopass | 收到信号不传递给程序 |
# 设置源代码路径
在A机器上gcc编译的执行文件test,放到B机器去执行。在B机器上gdb调试test,怎么在gdb中查看源代码。
有几种方法:
1. 把源代码放到编译机完全相同的路径
```shell
$ readelf -P .debug_str test
$ mkdir <code_dir>
```
2. 使用gdb的substitute-path路径映射功能
`set substitute-path <FROM> <TO>`
FROM是编译时的代码路径。上述命令等于替换路径前缀,用TO替换FROM。
```shell
$ readelf -P .debug_str test
$ gdb ./test
(gdb) set substitute-path /home/gdb/code/test /current-code
(gdb) list
```
3. 使用gdb的direcotory功能,把direcotry指定的路径加入到源代码搜索路径,缺点是不能递归搜索
```shell
(gdb) show directories
Source directories searched: $cdir:$cwd
(gdb) directory /code
(gdb) show directories
Source directories searched: /home/postgres:$cdir:$cwd
(gdb) list
```
4. 把二进制文件移动到源代码路径
5. 编译时增加`-fdebug-prefix-map=old_path=new_path`
在编译阶段用new_path替代old_path,这种方式比较暴力。
# 多进程调试
set follow-fork-mode [parent | child]
set detach-on-fork [on|off]
# 多线程调试
调试多线程时,有时需要控制某些线程停在断点,有些线程继续执行。有时需要控制线程的运行顺序。有时需要中断某个线程,切换到其他线程。这些都可以通过gdb实现。
gdb调试线程的常用命令如下:
| gdb命令 | 描述 |
| --------------------------------- | ---------------------------------------- |
| info thread | 显示所有线程 |
| thread ID | 切换到ID指定的线程 |
| break xxx.c:10 thread all | 所有线程都在xxx.c文件的第10行断点,all可以换成单个线程ID |
| thread apply all COMMON | 所有线程都执行COMMOND命令,也可以把all换成单个线程ID |
| set scheduler-locking off/on/step | 在调试某一线程时,其他线程是否执行。off:不锁定任何线程,默认值。on:锁定其他线程,只有当前线程运行。step:在step单步调试时,只有被调试线程运行。 |
| set non-stop on/off | 当调试一个线程时,其他线程是否运行。默认off。 |
| set pagination on/off | 在使用backtrace时,在分页时是否停止。默认on。 |
| set target-async on/off | 同步和异步。同步,gdb在输出提示符之前等待程序报告一些线程已经终止的信息。而异步的则是直接返回。默认off。 |
non-stop模式调试后台程序:
```shel
$ gdb
(gdb) set non-stop on
(gdb) set pagination off
(gdb) set target-async on
(gdb) attach 82373
(gdb) info thread
(gdb) thread apply all continue &
(gdb) thread 10
(gdb) continue &
```
注意:在使用non-stop模式调试时,凡是执行continue操作时最好加上&放入后台。否则如果continue之后当前线程没有产生断点,则回不到交互模式。
# 打印相关
```shell
set print address -- Set printing of addresses
set print array -- Set prettyprinting of arrays
set print array-indexes -- Set printing of array indexes
set print asm-demangle -- Set demangling of C++/ObjC names in disassembly listings
set print demangle -- Set demangling of encoded C++/ObjC names when displaying symbols
set print elements -- Set limit on string chars or array elements to print
set print frame-arguments -- Set printing of non-scalar frame arguments
set print inferior-events -- Set printing of inferior events (e.g.
set print max-symbolic-offset -- Set the largest offset that will be printed in <symbol+1234> form
set print null-stop -- Set printing of char arrays to stop at first null char
set print object -- Set printing of object's derived type based on vtable info
set print pascal_static-members -- Set printing of pascal static members
set print pretty -- Set prettyprinting of structures
set print repeats -- Set threshold for repeated print elements
set print sevenbit-strings -- Set printing of 8-bit characters in strings as \nnn
set print static-members -- Set printing of C++ static members
set print symbol-filename -- Set printing of source filename and line number with <symbol>
set print thread-events -- Set printing of thread events (such as thread start and exit)
set print union -- Set printing of unions interior to structures
set print vtbl -- Set printing of C++ virtual function tables
```
# LIBRARY_PATH与LD_LIBRARY_PATH
`LIBRARY_PATH`环境变量用于在程序编译期间查找动态链接库时指定查找共享库的路径。如果不指定`LIBRARY_PATH`,可以在gcc编译时通过-L指定共享库路径。
`LD_LIBRARY_PATH`环境变量用于在程序加载运行期间查找动态链接库时指定除了系统默认路径之外的其他路径。注意,`LD_LIBRARY_PATH`中指定的路径会在系统默认路径之前进行查找。
使用方法:
```bash
export LIBRARY_PATH=`pwd`:$LIBRARY_PATH
export LD_LIBRARY_PATH=`pwd`:$LIBRARY_PATH
或
LIBRARY_PATH=`pwd`:$LIBRARY_PATH make
LD_LIBRARY_PATH=`pwd`:$LIBRARY_PATH make
```
# C_INCLUDE_PATH、CPLUS_INCLUDE_PATH
与LIBRARY_PATH类似,gcc编译期间查找指定的头文件路径。也可以在gcc加上-I参数指定头文件路径。
使用方法:
```shell
export C_INCLUDE_PATH=`pwd`/include:$C_INCLUDE_PATH
或
C_INCLUDE_PATH=`pwd`/include make
```
<file_sep>/README.md
# hexo-blog
* 安装git
* 安装nodejs
```shell
$ wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh
$ nvm install stable
```
或者可以下载[安装程序](https://nodejs.org/en/)来安装。
* 安装hexo
```shell
$ npm install -g hexo-cli
$ npm install -g hexo-server
```
* 下载代码
```shell
$ git clone <EMAIL>:yfshi/hexo-blog.git
```
* 安装package
```shell
$ cd hexo-blog
$ npm install
```
npm install默认会安装package.json中dependencies和devDependencies里的所有模块.
* 启动本地server
```shell
$ hexo server
```
* 访问
浏览器访问:http://127.0.0.1:4000
<file_sep>/source/_posts/win10通过hyper-v安装虚拟机.md
---
layout: _post
title: win10通过hyper-v安装虚拟机
date: 2018-04-20 13:11:55
tags:
- Hyper-V
- 虚拟机
categories: 常用工具
---
# 安装Hyper-v组件
控制面板 -> 程序和功能 -> 启用或关闭Windows功能 -> 选中Hyper-V -> 确定

开始菜单 -> Windows管理工具 -> Hyper-v管理器
# 配置Hyper-V网络
打开虚拟交换机管理器创建虚拟交换机。一般使用内部或外部。

* 外部
网桥方式,相当于物理网卡。
* 内部
nat方式,可以连接主机,可以通过主机上网。
* 专用
虚拟机使用,不能和主机通信。
# 安装虚拟机
## 新建虚拟机向导



## 虚拟机设置
关闭自动检查点,没什么用处

添加磁盘驱动器

新建或使用已经存在的磁盘(可以通过拷贝其他虚拟机的磁盘到新建的虚拟机方式克隆)

## 安装系统
右键连接,启动系统安装

安装系统并初始化配置,之后创建检查点
<file_sep>/source/_posts/CentOS安装搜狗输入法.md
---
layout: _posts
title: CentOS安装搜狗输入法
date: 2020-08-31 16:29:14
categories: 操作系统
tags:
- sogou
- 搜狗
- 输入法
---
系统版本:`CentOS Linux release 7.7.1908 (Core)`
## 安装fcitx输入法框架
安装fcitx输入法框架,注意不要删除ibus框架,gnome-shell依赖ibus框架,执行命令:
```shell
$ sudo yum install libQtWebKit* fcitx fcitx-libs fcitx-qt4 fcitx-qt5 fcitx-configtool fcitx-table fcitx-table-chinese qt5-qtbase
```
新建`/etc/profile.d/fcitx.sh`,内容如下:
```shell
export GTK_IM_MODULE=fcitx
export QT_IM_MODULE=fcitx
export QT4_IM_MODULE=fcitx
export XMODIFIERS="@im=fcitx"```
```
设置`fctix`开机自启动,在`gnome-tweaks`中设置;
设置当前用户默认不启动`ibus-daemon`:
```shell
$ sudo setfacl -m u:yfshi:rw /usr/bin/ibus-daemon
```
为了在`gnome-terminal`中也能使用`fcitx`,设置如下,这是gnome3的新特性导致的:
```shell
$ gsettings set org.gnome.settings-daemon.plugins.xsettings overrides "{'Gtk/IMModule':<'fcitx'>}"
```
设置a`lternatives`为`fcitx`
```shell
$ alternatives --install /etc/X11/xinit/xinputrc xinputrc /etc/X11/xinit/xinput.d/fcitx.conf 100
$ alternatives --config xinputrc
```
## 安装搜狗输入法
下载搜狗输入法for linux,只有deb包:
```shell
$ sudo wget http://cdn2.ime.sogou.com/dl/index/1524572264/sogoupinyin_2.2.0.0108_amd64.deb?st=EPtVkvlW9rLVsn-jtfOGbA&e=1568569239&fn=sogoupinyin_2.2.0.0108_amd64.deb
```
安装`alien`工具,把deb转成rpm包:
```shell
$ sudo yum install alien
$ sudo alien -r --scripts sogoupinyin_2.2.0.0108_amd64.deb
```
安装搜狗拼音输入法:
```shell
$ sudo cp /usr/lib/x86_64-linux-gnu/fcitx/* /usr/lib64/fcitx
$ chmod -R 755 /usr/lib64/fcitx/
```
## 配置搜狗输入法
重启`reboot`;
`fcitx`添加搜狗输入法:
```shell
$ fcitx-configtool
```
> 注意,在fcitx-configtool的高级设置中关闭搜狗输入法的云输入,否则cpu可能会100%.
设置搜狗输入法。<file_sep>/source/_posts/CentOS编译安装wine.md
---
layout: _post
title: CentOS编译安装wine
date: 2020-09-03 17:38:58
categories: 操作系统
tags:
- wine
---
## CentOS编译安装wine
## 安装依赖
```shell
$ yum install glibc-devel.i686 dbus-devel.i686 freetype-devel.i686 pulseaudio-libs-devel.i686 libX11-devel.i686 mesa-libGLU-devel.i686 libICE-devel.i686 libXext-devel.i686 libXcursor-devel.i686 libXi-devel.i686 libXxf86vm-devel.i686 libXrender-devel.i686 libXinerama-devel.i686 libXcomposite-devel.i686 libXrandr-devel.i686 mesa-libGL-devel.i686 mesa-libOSMesa-devel.i686 libxml2-devel.i686 libxslt-devel.i686 zlib-devel.i686 gnutls-devel.i686 ncurses-devel.i686 sane-backends-devel.i686 libv4l-devel.i686 libgphoto2-devel.i686 libexif-devel.i686 lcms2-devel.i686 gettext-devel.i686 isdn4k-utils-devel.i686 cups-devel.i686 fontconfig-devel.i686 gsm-devel.i686 libjpeg-turbo-devel.i686 pkgconfig.i686 libtiff-devel.i686 unixODBC.i686 openldap-devel.i686 alsa-lib-devel.i686 audiofile-devel.i686 freeglut-devel.i686 giflib-devel.i686 gstreamer-devel.i686 gstreamer-plugins-base-devel.i686 libXmu-devel.i686 libXxf86dga-devel.i686 libieee1284-devel.i686 libpng-devel.i686 librsvg2-devel.i686 libstdc++-devel.i686 libusb-devel.i686 unixODBC-devel.i686 qt-devel.i686 libXext.i686 xulrunner.i686 ia32-libs.i686
```
## 编译安装wine
> wine版本下载最新的稳定版,目前是wine 5.0.2版本。
```shell
$ wget http://mirrors.ibiblio.org/wine/source/5.0/wine-5.0.2.tar.xz
$ tar xf wine-5.0.2.tar.xz
$ cd wine-5.0.2
$ ./configure --prefix=/usr/local # 如果编译64位增加--enable-wine64
$ make -j8
$ sudo make install
```
## 初始化wine
> `wine-mono`和`wine-geoko`可以初始化时安装,也可以不安装,下载后通过`wine control`命令安装exe或msi。
```shell
$ wineboot
$ cp -f /usr/local/share/wine/fonts/* .wine/drive_c/windows/Fonts/
```
<file_sep>/source/_posts/选择排序.md
---
title: 选择排序
date: 2017-10-22
categories: 算法
tags: 排序
---
# 介绍
选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理如下。首先在未排序序列中找到最小元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小元素,然后放到排序序列末尾。以此类推,直到所有元素均排序完毕。
# 排序效果

# 实现
```c
#include <stdio.h>
#include <stdlib.h>
static void RandInitArray(int *arr, int num);
static void PrintArray(int *arr, int num);
static void SelectSortAsc(int *arr, int num);
#define ARR_SIZE 20
int main()
{
int arr[ARR_SIZE];
RandInitArray(arr, ARR_SIZE);
PrintArray(arr, ARR_SIZE);
SelectSortAsc(arr, ARR_SIZE);
PrintArray(arr, ARR_SIZE);
return 0;
}
static void RandInitArray(int *arr, int num)
{
int i;
for (i=0; i<num; i++)
arr[i] = random()%100;
}
static void PrintArray(int *arr, int num)
{
int i;
for (i=0; i<num; i++)
printf("%d ", arr[i]);
printf("\n");
}
static void SelectSortAsc(int *arr, int num)
{
int i, j;
int min, tmp;
for (i=0; i<num-1; i++)
{
min = i;
for (j=i+1; j<num; j++)
{
if (arr[min] > arr[j])
min = j;
}
if (min != i)
{
tmp = arr[min];
arr[min] = arr[i];
arr[i] = tmp;
}
}
}
```
<file_sep>/source/_posts/PostgreSQL查询和计划树绘图工具.md
---
layout: _post
title: PostgreSQL查询和计划树绘图工具
date: 2018-06-09 17:06:25
tags:
- PostgreSQL
- dot
categories: PostgreSQL
---
使用Graphviz的dot工具绘制QueryStmt和PlanStmt。
工具地址:[dotpgstmt](/download/dotpgstmt.sh)
使用方法:
1. 获取查询树或计划树
```shell
postgres=# set client_min_messages to log;
SET
postgres=# set debug_print_parse to on;
SET
postgres=# select * from t;
LOG: parse tree:
DETAIL: {QUERY
:commandType 1
:querySource 0
:canSetTag true
:utilityStmt <>
:resultRelation 0
:hasAggs false
:hasWindowFuncs false
:hasTargetSRFs false
:hasSubLinks false
:hasDistinctOn false
:hasRecursive false
:hasModifyingCTE false
:hasForUpdate false
:hasRowSecurity false
:cteList <>
:rtable (
{RTE
:alias <>
:eref
{ALIAS
:aliasname t
:colnames ("id")
}
:rtekind 0
:relid 16498
:relkind r
:tablesample <>
:lateral false
:inh true
:inFromCl true
:requiredPerms 2
:checkAsUser 0
:selectedCols (b 9)
:insertedCols (b)
:updatedCols (b)
:securityQuals <>
}
)
:jointree
{FROMEXPR
:fromlist (
{RANGETBLREF
:rtindex 1
}
)
:quals <>
}
:targetList (
{TARGETENTRY
:expr
{VAR
:varno 1
:varattno 1
:vartype 23
:vartypmod -1
:varcollid 0
:varlevelsup 0
:varnoold 1
:varoattno 1
:location 7
}
:resno 1
:resname id
:ressortgroupref 0
:resorigtbl 16498
:resorigcol 1
:resjunk false
}
)
:override 0
:onConflict <>
:returningList <>
:groupClause <>
:groupingSets <>
:havingQual <>
:windowClause <>
:distinctClause <>
:sortClause <>
:limitOffset <>
:limitCount <>
:rowMarks <>
:setOperations <>
:constraintDeps <>
:stmt_location 0
:stmt_len 15
}
```
2. 把`DETAIL:`之后的内容写入文件parse
3. 绘图
./dotpgstmt.sh parse

<file_sep>/source/_posts/希尔排序.md
---
title: 希尔排序
date: 2017-10-22
categories: 算法
tags: 排序
---
# 介绍
希尔排序,也称递减增量排序算法,是插入排序的一种高速而稳定的改进版本。
希尔排序是基于插入排序的以下两点性质而提出改进方法的:
1. 插入排序在对几乎已经排好序的数据操作时, 效率高, 即可以达到线性排序的效率
2. 插入排序一般来说是低效的, 因为插入排序每次只能将数据移动一位
# 排序效果

# 实现
```c
...
```
<file_sep>/source/_posts/归并排序.md
---
title: 归并排序
date: 2017-10-22
categories: 算法
tags: 排序
---
# 介绍
归并排序(Merge sort,台湾译作:合并排序)是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。
# 步骤
1. 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列
2. 设定两个指针,最初位置分别为两个已经排序序列的起始位置
3. 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
4. 重复步骤3直到某一指针达到序列尾
5. 将另一序列剩下的所有元素直接复制到合并序列尾
# 排序效果

# 实现
```c
...
```
<file_sep>/source/tags/index.md
---
title: tags
date: 2017-11-02 17:29:01
type: tags
comments: false
---
<file_sep>/source/_posts/搭建yum源.md
---
title: 'centos/redhat搭建yum源'
date: 2017-09-25
tags: yum
categories: 操作系统
---
# 创建仓库
1. 把所有的光盘或iso文件(ios可能有两个或多个)中的rpm包拷贝出来
2. 使用createrepo创建仓库
```shell
$ mkdir -p /opt/yum/centos6.7/Packages
$ mount /dev/cdrom /mnt
$ createrepo -v -g /mnt/repodata/*-comps.xml /opt/yum/centos6.7
```
createrepo的-g的作用是加载分组信息`yum grouplist`,可以用下面两条命令实现同样的功能:
```shell
$ createrepo -v /opt/yum/centos6.7
# cp /mnt/repodata/*-comps.xml* /opt/yum/centos6.7/repodata/
```
# http
1. 启动httpd
```shell
service httpd start
```
2. 把仓库放到http工作目录
```shell
mv /opt/yum/centos6.7 /var/www/html
```
# 设置repo文件
新建repo文件`touch /etc/yum.repo/local.repo`,或者直接在原有的repo文件中添加,内容如下:
```bash
[http_server]
name=This is a http repo
baseurl=http://localhost/home/yum/centos6.7
enabled=1
gpgcheck=0
```
可以把原来的Centos-Base.repo中的源都加上`enable=0`禁用,否则会先去找这个文件中的路径
# 常用命令
```bash
yum clean all
yum list
yum install xxx.rpm
yum install -y xxx.rpm
yum uninstall xxx
yum grouplist
yum groupinstall xxx
yum groupinstall -y xxx
yum ungroup xxx
yum makecache
```
# Q&A
## 升级python导致yum不可用
`/usr/bin/yum`第一行指定该脚本所使用的python版本,一般是`#!/usr/bin/python`,python升级之后`/usr/bin/python`是升级之后的python,和`/usr/bin/yum`不兼容。
可以修改`/usr/bin/yum`第一行为原来的python版本,比如`#!/usr/bin/python2.6`<file_sep>/source/_posts/快速排序.md
---
title: 快速排序
date: 2017-10-22
categories: 算法
tags: 排序
---
# 介绍
快速排序是由东尼·霍尔所发展的一种排序算法。在平均状况下,排序 *n* 个项目要**Ο**(*n* log *n*)次比较。在最坏状况下则需要**Ο**(*n*2)次比较,但这种状况并不常见。事实上,快速排序通常明显比其他**Ο**(*n* log *n*) 算法更快,因为它的内部循环(inner loop)可以在大部分的架构上很有效率地被实现出来,且在大部分真实世界的数据,可以决定设计的选择,减少所需时间的二次方项之可能性。
# 步骤
1. 从数列中挑出一个元素,称为 “基准”(pivot),
2. 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为**分区(partition)**操作。
3. 递归地把小于基准值元素的子数列和大于基准值元素的子数列排序。
# 排序效果

# 实现
```c
#include <stdio.h>
#include <stdlib.h>
static void RandInitArray(int *arr, int num);
static void PrintArray(int *arr, int num);
static void QuickSortAsc(int *arr, int left, int right);
#define ARR_SIZE 20
int main()
{
int arr[ARR_SIZE];
RandInitArray(arr, ARR_SIZE);
PrintArray(arr, ARR_SIZE);
QuickSortAsc(arr, 0, ARR_SIZE-1);
PrintArray(arr, ARR_SIZE);
return 0;
}
static void RandInitArray(int *arr, int num)
{
int i;
for (i=0; i<num; i++)
arr[i] = random()%100;
}
static void PrintArray(int *arr, int num)
{
int i;
for (i=0; i<num; i++)
printf("%d ", arr[i]);
printf("\n");
}
static void QuickSortAsc(int *arr, int left, int right)
{
int low, high;
int pivot;
if (left < right)
{
low = left;
high = right;
pivot = arr[low];
while (low < high)
{
while (low < high && pivot <= arr[high])
high--;
arr[low] = arr[high];
while (low < high && pivot > arr[low])
low++;
arr[high] = arr[low];
}
arr[low] = pivot;
QuickSortAsc(arr, left, low-1);
QuickSortAsc(arr, low+1, right);
}
}
```
<file_sep>/source/_posts/插入排序.md
---
title: 插入排序
date: 2017-10-22
categories: 算法
tags: 排序
---
# 介绍
插入排序(Insertion Sort)的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
# 步骤
1. 从第一个元素开始,该元素可以认为已经被排序
2. 取出下一个元素,在已经排序的元素序列中从后向前扫描
3. 如果该元素(已排序)大于新元素,将该元素移到下一位置
4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
5. 将新元素插入到该位置中
6. 重复步骤2
# 排序效果

# 实现
```c
...
```
<file_sep>/source/_posts/kvm虚拟机.md
---
layout: _post
title: kvm虚拟机
date: 2018-02-09 00:22:51
tags:
- kvm
- 虚拟机
categories: 常用工具
---
# 安装
```shell
sudo apt-get install kvm qemu-kvm libvirt-bin bridge-utils
```
* kvm 内核模块,实现cpu虚拟化和内存管理
* libvirt-bin 管理虚拟机
* qemu-kvm 是虚拟机
* bridge-utils 管理网桥
如果只是使用命令行方式,上面的软件包已经足够。
下面是图形界面工具:
```shell
sudo apt-get install virt-manager python-spice-client-gtk
```
- virt-manager 图形界面的虚拟机管理程序,需要用到python-spice-client-gtk
- python-spice-client-gtk
# 配置网桥
1. 手动配置
```shell
brctl addbr br0
brctl addif br0 eth0
ip addr add 10.10.10.1/24 dev br0
...
```
2. 自动配置
__ubuntu__
```shell
vi /etc/network/interfaces
auto br0
iface br0 inet static
address 10.10.10.1
netmask 255.255.255.0
bridge_ports eth0
bridge_stp off
bridge_fd 0
bridge_maxwait 0
```
__centos__
```shell
vi /etc/sysconfig/network-script/ifcfg-br0
DEVICE=br0
TYPE=Bridge
BOOTPROTO=static
IPADDR=10.10.10.2
NETMASK=255.255.255.0
ONBOOT=yes
NM_CONTROLLED=no
DELAY=0
vi /etc/sysconfig/network-script/ifcfg-eth0
DEVICE=eth0
HWADDR=00:15:xx:xx:xx:xx
TYPE=Ethernet
ONBOOT=yes
BOOTPROTO=none
BRIDGE=br0
NM_CONTROLLED=no
```
# 使用命令行创建虚拟机
1. 建立磁盘镜像
```shell
qemu-img create -f qcow2 centos7.0.img 20G
```
使用 qcow2 格式的磁盘镜像的好处就是它在创建之初并不会给它分配全部大小磁盘容量,而是随着虚拟机中文件的增加而逐渐增大。因此,它对空间的使用更加有效。
2. 建立`xml`配置文件
`linux`默认有`virtio`驱动,磁盘总线、网卡等可以设置为`virtio`。
`windows`要使用`virtio`,需要安装`virtio`驱动。或者`windows`的`disk`的总线可以选择和宿主机一致比如是`sata`,网卡可以设置为`rt8139`,`<hyperv>...</hyperv>`域是针对`windows`的优化。实际上使用时发现在机械硬盘是使用`windows`,`io`效率很低,无论是否使用`virtio`驱动,可能有什么地方需要优化没搞懂,后来把`windows`的存储放到`ssd`上了。
**centos7.0.xml**
```xml
<domain type='kvm'>
<name>centos7.0</name>
<memory unit='KiB'>1048576</memory>
<currentMemory unit='KiB'>1048576</currentMemory>
<vcpu placement='static'>2</vcpu>
<os>
<type arch='x86_64'>hvm</type>
<boot dev='cdrom'/>
<boot dev='hd'/>
</os>
<features>
<acpi/>
<apic/>
<vmport state='off'/>
</features>
<cpu mode='host-model' check='partial'>
<model fallback='allow'/>
</cpu>
<clock offset='utc'>
<timer name='rtc' tickpolicy='catchup'/>
<timer name='pit' tickpolicy='delay'/>
<timer name='hpet' present='no'/>
</clock>
<on_poweroff>destroy</on_poweroff>
<on_reboot>restart</on_reboot>
<on_crash>restart</on_crash>
<pm>
<suspend-to-mem enabled='no'/>
<suspend-to-disk enabled='no'/>
</pm>
<devices>
<emulator>/usr/bin/kvm</emulator>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='writeback'/>
<source file='/vmhosts/kvm/centos7.0.qcow2'/>
<target dev='vda' bus='virtio'/>
</disk>
<disk type='file' device='cdrom'>
<driver name='qemu' type='raw' cache='none'/>
<source file='/iso/centos7.0.iso'/>
<target dev='hda' bus='ide'/>
<readonly/>
</disk>
<interface type='bridge'>
<source bridge='br0'/>
<model type='virtio'/>
</interface>
<input type='tablet' bus='usb'/>
<input type='mouse' bus='ps2'/>
<input type='keyboard' bus='ps2'/>
<graphics type='vnc' port='-1' autoport='yes' listen='0.0.0.0'>
<listen type='address' address='0.0.0.0'/>
</graphics>
</devices>
</domain>
```
**win7**
```shell
<domain type='kvm'>
<name>win7</name>
<memory unit='KiB'>2097152</memory>
<currentMemory unit='KiB'>2097152</currentMemory>
<vcpu placement='static'>2</vcpu>
<os>
<type arch='x86_64'>hvm</type>
<boot dev='cdrom'/>
<boot dev='hd'/>
</os>
<features>
<acpi/>
<apic/>
<hyperv>
<relaxed state='on'/>
<vapic state='on'/>
<spinlocks state='on' retries='4096'/>
<vpindex state='on'/>
<runtime state='on'/>
<synic state='on'/>
<reset state='on'/>
</hyperv>
<vmport state='off'/>
</features>
<cpu mode='host-model' check='partial'>
<model fallback='allow'/>
</cpu>
<clock offset='localtime'>
<timer name='rtc' tickpolicy='catchup'/>
<timer name='pit' tickpolicy='delay'/>
<timer name='hpet' present='no'/>
<timer name='hypervclock' present='yes'/>
</clock>
<on_poweroff>destroy</on_poweroff>
<on_reboot>restart</on_reboot>
<on_crash>restart</on_crash>
<pm>
<suspend-to-mem enabled='no'/>
<suspend-to-disk enabled='no'/>
</pm>
<devices>
<emulator>/usr/bin/kvm</emulator>
<disk type='file' device='disk'>
<driver name='qemu' type='qcow2' cache='writeback'/>
<source file='/vmhosts/kvm/centos7.0.qcow2'/>
<target dev='sda' bus='sata'/>
</disk>
<disk type='file' device='cdrom'>
<driver name='qemu' type='raw' cache='none'/>
<source file='/iso/win7.iso'/>
<target dev='hda' bus='ide'/>
<readonly/>
</disk>
<interface type='bridge'>
<source bridge='br0'/>
<model type='rt8139'/>
</interface>
<input type='tablet' bus='usb'/>
<input type='mouse' bus='ps2'/>
<input type='keyboard' bus='ps2'/>
<graphics type='vnc' port='-1' autoport='yes' listen='0.0.0.0'>
<listen type='address' address='0.0.0.0'/>
</graphics>
</devices>
</domain>
```
3. 定义虚拟机
```shell
virsh define centos7.0.xml
virsh list --all
```
4. 启动虚拟机
```shell
virsh start centos7.0
```
5. 安装系统
通过vnc客户端连接
```shell
vncviwer localhost:5900
```
安装好系统,装完必要的环境之后可以把存储(centos7.0.qcow2)备份。之后再需要系统时直接拷贝过来使用即可。
6. 常用命令
```shell
virsh list #显示本地活动虚拟机
virsh list –-all #显示本地所有的虚拟机(活动的+不活动的)
virsh define ubuntu.xml #通过配置文件定义一个虚拟机(这个虚拟机还不是活动的)
virsh start ubuntu #启动名字为ubuntu的非活动虚拟机
virsh create ubuntu.xml # 创建虚拟机(创建后,虚拟机立即执行,成为活动主机)
virsh suspend ubuntu # 暂停虚拟机
virsh resume ubuntu # 启动暂停的虚拟机
virsh shutdown ubuntu # 正常关闭虚拟机
virsh destroy ubuntu # 强制关闭虚拟机
virsh dominfo ubuntu #显示虚拟机的基本信息
virsh domname 2 # 显示id号为2的虚拟机名
virsh domid ubuntu # 显示虚拟机id号
virsh domuuid ubuntu # 显示虚拟机的uuid
virsh domstate ubuntu # 显示虚拟机的当前状态
virsh dumpxml ubuntu # 显示虚拟机的当前配置文件(可能和定义虚拟机时的配置不同,因为当虚拟机启动时,需要给虚拟机分配id号、uuid、vnc端口号等等)
virsh setmem ubuntu 512000 #给不活动虚拟机设置内存大小
virsh setvcpus ubuntu 4 # 给不活动虚拟机设置cpu个数
virsh edit ubuntu # 编辑配置文件(一般是在刚定义完虚拟机之后)
libvirt还提供了一个shell:virsh,直接执行名virsh即可获得一个特殊的shell:virsh,在这个virsh里面可以执行上面的命令与本地libvirt交互,还可以通过命令connect命令连接远程libvirt,与之交互,例如:connect xen+ssh://root@10.0.0.11。另外可以只执行一条远程libvirt命令:virsh –c xen+ssh://root@10.0.0.11 list –all
```
# 快照管理
```shell
# virsh --help | grep snapshot
snapshot-create Create a snapshot from XML
snapshot-create-as Create a snapshot from a set of args
snapshot-current Get or set the current snapshot
snapshot-delete Delete a domain snapshot
snapshot-dumpxml Dump XML for a domain snapshot
snapshot-edit edit XML for a snapshot
snapshot-info snapshot information
snapshot-list List snapshots for a domain
snapshot-parent Get the name of the parent of a snapshot
snapshot-revert Revert a domain to a snapshot
```
举例:
```shell
# virsh list
Id Name State
----------------------------------------------------
1 win7 running
# virsh snapshot-create-as win7 snapshot-haozip_360_npp_wps
Domain snapshot snapshot-haozip_360_npp_wps created
# qemu-img info win7.qcow2
image: win7.qcow2
file format: qcow2
virtual size: 100G (107374182400 bytes)
disk size: 14G
cluster_size: 65536
Snapshot list:
ID TAG VM SIZE DATE VM CLOCK
1 snapshot-haozip_360_npp_wps 1.8G 2018-03-07 10:14:03 01:15:31.438
Format specific information:
compat: 1.1
lazy refcounts: false
refcount bits: 16
corrupt: false
# virsh snapshot-list win7
Name Creation Time State
------------------------------------------------------------
snapshot-haozip_360_npp_wps 2018-03-07 10:14:03 +0800 running
# virsh snapshot-info win7 --snapshotname snapshot-haozip_360_npp_wps
Name: snapshot-haozip_360_npp_wps
Domain: win7
Current: yes
State: running
Location: internal
Parent: -
Children: 0
Descendants: 0
Metadata: yes
```
# 虚拟磁盘扩容
磁盘扩容或添加之后要到虚拟机内部做分区、格式化、自动挂在等操作。
1. 磁盘扩容
```shell
# qemu-img resize win7.qcow +10G
```
2. 磁盘添加
```shell
# qemu-img create -f qcow2 win7_1 10G
# virsh shutdown win7
# virsh edit win7
<disk></disk>在原有的disk下面添加一个disk配置:
-- 修改file路径
-- target中的dev修改为vdb
-- 删除address
```
# 图形界面
通过执行名virt-manager,启动libvirt的图形界面,在图形界面下可以一步一步的创建虚拟机,管理虚拟机,还可以直接控制虚拟机的桌面。
<file_sep>/source/_posts/基于docker搭建greenplum开发环境.md
---
layout: _post
title: docker搭建greenplum开发环境
date: 2019-05-15 10:00:40
tags:
- docker
- greenplum
- centos
categories: PostgreSQL
---
# docker
# 安装docker
略
# 给普通用户权限
```shell
# 把普通用户加入docker组,如果docker用户组不存在,新建
sudo gppasswd -a yfshi docker
# 重启docker服务
sudo systemctl restart docker
```
# 配置greenplum环境
```shell
# 创建自定义网络,以便后续设置静态ip
$ docker network create --subnet 10.0.0.0/24 syf_net
# 拉取centos7最小安装镜像
$ docker pull centos
# 创建并后台启动容器,名称为dev,使用自定义的网络syf_net,指定静态ip(比如属于syf_net所指定的子网,如果使用非自定义网络,不可设置静态ip,自动分配)
$ docker run -dit --privileged --net syf_net --ip 10.0.0.1 -dit --name dev centos /usr/sbin/init
# 在容器中打开一个交互终端
$ docker exec -it dev /bin/bash
# 安装常用工具和开发包
$ yum install -y net-tools which openssh-clients openssh-server less zip unzip iproute bzip2 cmake gcc gcc-c++ gdb git libtool lrzsz make man net-tools sysstat vim wget sudo
$ yum install -y apr-devel apr-util-devel bison bzip2-devel c-ares-devel flex java-1.8.0-openjdk java-1.8.0-openjdk-devel json-c-devel krb5-devel libcurl-devel libevent-devel libkadm5 libxml2-devel libxslt-devel libyaml-devel openldap-devel openssl-devel pam-devel perl perl-devel perl-ExtUtils-Embed readline-devel unixODBC-devel zlib-devel
# 设置系统参数
$ cat >> /etc/sysctl.conf <<-EOF
kernel.shmmax = 500000000
kernel.shmmni = 4096
kernel.shmall = 4000000000
kernel.sem = 500 1024000 200 4096
kernel.sysrq = 1
kernel.core_uses_pid = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.msgmni = 2048
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_forward = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.conf.all.arp_filter = 1
net.ipv4.ip_local_port_range = 1025 65535
net.core.netdev_max_backlog = 10000
net.core.rmem_max = 2097152
net.core.wmem_max = 2097152
vm.overcommit_memory = 2
EOF
$ cat >> /etc/security/limits.conf <<-EOF
* soft nofile 65536
* hard nofile 65536
* soft nproc 131072
* hard nproc 131072
EOF
$ cat >> /etc/ld.so.conf <<-EOF
/usr/local/lib
EOF
# 设置ssh自启动
systemctl enable sshd
systemctl start sshd
# 添加用户
passwd root
useradd -m gpadmin
passwd gpadmin
# 退出当前终端
exit
# 把该容器制作为镜像
docker commit -a yfshi -m "develop environment for greenplum" dev centos-gpdb
# 基于新镜像启动容器
docker run -dit --privileged --net syf_net --ip 10.0.0.2 -dit --name dev1 centos-gpdb /usr/sbin/init
# 打开终端,可以以ssh方式或docker方式
docker exec -it dev1 /bin/bash
# 或
ssh gpadmin@10.0.0.2
```
# 备份镜像
为了防止镜像丢失,可以把镜像导出到文件。之后可以通过该文件导入镜像。
有两种方式,一种是通过save/load镜像方式,一种是通过export/import容器方式。区别是export/import不保留历史记录(docker history IMAGE)。
```shell
# 把centos-gpdb镜像导出到文件centos-gpdb.tar
docker save -o centos-gpdb.tar centos-gpdb
# 导入centos-gpdb.tar
docker load -i centos-gpdb.tar
```
附:docker建立ubuntu桌面版,通过vnc连接
```shell
# 启动容器
$ docker run -d --name=ubuntu -p 5901:5901 -p 6901:6901 --hostname ubuntu --user $(id -u) --net sys_net --ip 10.0.0.200 -e VNC_PW=<PASSWORD> -e VNC_RESOLUTION=1280x800 consol/ubuntu-xfce-vnc
# 使用浏览器访问: x.x.x.x:6901
# 使用vnc客户端访问:x.x.x.x:5901
```
<file_sep>/source/_posts/动态库和静态库.md
---
layout: _post
title: 动态库和静态库
date: 2019-06-06 06:49:17
categories: 编程
tags:
- 动态库
- 静态库
- 编译
- gcc
---
# 概述
linux下有两种库:动态库和静态库。
静态库在编译过程中已经被载入,因此编译出来的可执行程序都比较大。程序运行时不再需要静态库,即程序编译完之后静态库就没用了。
动态库(共享库)在程序运行时载入内存,在编译过程中仅简单的引用,因此可执行文件体积比较小。程序运行需要加载动态库,即程序和动态库必须同时存在。
# 静态库
静态库是.o文件的集合,使用时可以把.a文件当成多个.o的集合使用。
如果.a依赖于动态库,生成.a时不会把.so动态库集合进来,那么使用者使用.a时需要同时链接其依赖的.so库。在产生.a时要避免依赖过多的动态库。
静态库更新之后使用静态库的程序必须重新编译。
# 动态库
在编译的时候动态库并没有被编译进目标代码,你的程序执行到相关函数时才去调用动态库,所以程序运行时必须提供相应的库。
动态库更新之后不需要重新编译目标程序。<file_sep>/source/_posts/git.md
---
title: git
date: 2018-07-31 15:22:54
tags: git
categories: 常用工具
---
官方文档:
[progit_v2.1.15.pdf](/docs/progit_v2.1.15.pdf)
来自:
[https://git-scm.com/book/zh/v2](https://git-scm.com/book/zh/v2)
# 完整迁移
把本地git库localtest完整的迁移到github上的test库,保留提交记录:
```shell
# github端建立test空白库
# 本地库镜像推送
$ cd localtest
# git push --mirror <EMAIL>:yfshi/test.git
```
<file_sep>/source/_posts/查看linux信息.md
---
layout: _post
title: 查看linux信息
date: 2018-09-15 11:42:13
categories: 操作系统
tags:
- cpuinfo
- fdisk
- linux
---
# 系统信息
## 内核和架构
```shell
$ # uname --help
-a, --all print all information, in the following order,
except omit -p and -i if unknown:
-s, --kernel-name print the kernel name
-n, --nodename print the network node hostname
-r, --kernel-release print the kernel release
-v, --kernel-version print the kernel version
-m, --machine print the machine hardware name
-p, --processor print the processor type or "unknown"
-i, --hardware-platform print the hardware platform or "unknown"
-o, --operating-system print the operating system
--help display this help and exit
--version output version information and exit
# 所有信息
$ uname -a
Linux h113 2.6.32-696.10.1.el6.x86_64 #1 SMP Tue Aug 22 18:51:35 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
# 以“|”分割的所有信息
$ echo "`uname -s` | `uname -n` | `uname -r` | `uname -v` | `uname -m` | `uname -p` | `uname -i` | `uname -o`"
Linux | h113 | 2.6.32-696.10.1.el6.x86_64 | #1 SMP Tue Aug 22 18:51:35 UTC 2017 | x86_64 | x86_64 | x86_64 | GNU/Linux
```
## 操作系统
```shell
$ cat /etc/issue
CentOS release 6.4 (Final)
Kernel \r on an \m
```
## 语言和字符集
```shell
$ echo $LANG
en_US.UTF-8
$ locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
```
## 进程
```shell
# 显示系统所有进程
$ ps -ef
# 以树形显示所有进程
$ ps -ef f
```
## 其他
```shell
$ uptime #查看服务器开机时长,用户数,平均负载
$ lsmod #查看所有加载的模块
$ env #查系统环境变量
$ crontab -l #查看计划任务
$ top #查看系统任务
$ iostat #查看系统io
$ vmstate
$ netstat #查看网络、路由、端口占用等
```
# 硬件信息
## cpu
```shell
$ cat /proc/cpu
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6140 CPU @ 2.30GHz
stepping : 4
microcode : 0x2000026
cpu MHz : 999.960
cache size : 25344 KB
physical id : 0
siblings : 36
core id : 0
cpu cores : 18
apicid : 0
initial apicid : 0
fpu : yes
fpu_exception : yes
cpuid level : 22
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb
rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2
ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3
intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap cl
flushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window
hwp_epp hwp_pkg_req
bogomips : 4600.00
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
...
省略
...
processor : 71 # 逻辑核编号:共72个逻辑cpu
vendor_id : GenuineIntel # 制造商
cpu family : 6 # 产品系列
model : 85 # 属于其系列的哪一代
model name : Intel(R) Xeon(R) Gold 6140 CPU @ 2.30GHz
stepping : 4
microcode : 0x2000026
cpu MHz : 1131.222 # 主频
cache size : 25344 KB # 二级缓存大小
physical id : 1 # 单个cpu标号:共2个cpu
siblings : 36 # 当前cpu的逻辑核数
core id : 27 # 当前物理核在其所处cpu中的唯一编号,不一定连续
cpu cores : 18 # 当前cpu的物理核数,siblings/cpu cores就是超线程数
apicid : 119
initial apicid : 119
fpu : yes
fpu_exception : yes
cpuid level : 22
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req
bogomips : 4605.53
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
```
## 内存
```shell
$ cat /proc/meminfo
MemTotal: 196521604 kB # 总内存
MemFree: 644068 kB # 空闲内存
MemAvailable: 192606708 kB # 可用内存
Buffers: 152 kB
Cached: 186042324 kB
SwapCached: 0 kB
Active: 643680 kB
Inactive: 185668932 kB
Active(anon): 203332 kB
Inactive(anon): 329264 kB
Active(file): 440348 kB
Inactive(file): 185339668 kB
Unevictable: 0 kB
Mlocked: 0 kB
SwapTotal: 4194300 kB # 交换空间大小
SwapFree: 4194300 kB # 空闲交换空间
Dirty: 40 kB
Writeback: 0 kB
AnonPages: 270064 kB
Mapped: 330936 kB
Shmem: 262460 kB
Slab: 7182928 kB
SReclaimable: 6933600 kB
SUnreclaim: 249328 kB
KernelStack: 20704 kB
PageTables: 17124 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 190889820 kB
Committed_AS: 1997032 kB
VmallocTotal: 34359738367 kB
VmallocUsed: 833948 kB
VmallocChunk: 34258257916 kB
HardwareCorrupted: 0 kB
AnonHugePages: 69632 kB
HugePages_Total: 0
HugePages_Free: 0
HugePages_Rsvd: 0
HugePages_Surp: 0
Hugepagesize: 2048 kB
DirectMap4k: 374132 kB
DirectMap2M: 8749056 kB
DirectMap1G: 192937984 kB
# 查看所有交换空间
$ swapon -s
Filename Type Size Used Priority
/dev/dm-1 partition 16506876 240 -1
```
## 磁盘
```shell
# 树状显示所有块设备,比较直观
$ lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
sda 8:0 0 512G 0 disk
├─sda1 8:1 0 500M 0 part /boot
└─sda2 8:2 0 511.5G 0 part
├─vg_h95-lv_root (dm-0) 253:0 0 50G 0 lvm /
├─vg_h95-lv_swap (dm-1) 253:1 0 15.8G 0 lvm [SWAP]
└─vg_h95-lv_home (dm-2) 253:2 0 2.1T 0 lvm /home
sdb 8:16 0 1.7T 0 disk
└─sdb1 8:17 0 1.7T 0 part
└─vg_h95-lv_home (dm-2) 253:2 0 2.1T 0 lvm /home
sr0 11:0 1 1024M 0 rom
# fdisk是分区工具,可显示磁盘详细信息,不直观
$ fdisk -l
Disk /dev/sda: 549.8 GB, 549755813888 bytes
255 heads, 63 sectors/track, 66837 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000cde3e
Device Boot Start End Blocks Id System
/dev/sda1 * 1 64 512000 83 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 64 66838 536357888 8e Linux LVM
WARNING: GPT (GUID Partition Table) detected on '/dev/sdb'! The util fdisk doesn't support GPT. Use GNU Parted.
Disk /dev/sdb: 1842.2 GB, 1842238980096 bytes
255 heads, 63 sectors/track, 223972 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
/dev/sdb1 1 223973 1799061503+ ee GPT
Disk /dev/mapper/vg_h95-lv_root: 53.7 GB, 53687091200 bytes
255 heads, 63 sectors/track, 6527 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Disk /dev/mapper/vg_h95-lv_swap: 16.9 GB, 16903045120 bytes
255 heads, 63 sectors/track, 2055 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Disk /dev/mapper/vg_h95-lv_home: 2320.9 GB, 2320871981056 bytes
255 heads, 63 sectors/track, 282163 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
```<file_sep>/source/_posts/堆排序.md
---
title: 堆排序
date: 2017-10-22
categories: 算法
tags: 排序
---
# 介绍
堆积排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构,并同时满足*堆性质*:即子结点的键值或索引总是小于(或者大于)它的父节点。
# 步骤
略
# 排序效果

# 实现
```c
#include <stdio.h>
#include <stdlib.h>
static void RandInitArray(int *arr, int num);
static void PrintArray(int *arr, int num);
static void HeapSortAsc(int *arr, int num);
static void HeapShiftDown(int *arr, int start, int end);
static void swap(int *x, int *y);
#define ARR_SIZE 20
int main()
{
int arr[ARR_SIZE];
RandInitArray(arr, ARR_SIZE);
PrintArray(arr, ARR_SIZE);
HeapSortAsc(arr, ARR_SIZE);
PrintArray(arr, ARR_SIZE);
return 0;
}
static void RandInitArray(int *arr, int num)
{
int i;
for (i=0; i<num; i++)
arr[i] = random()%10000;
}
static void PrintArray(int *arr, int num)
{
int i;
for (i=0; i<num; i++)
printf("%d ", arr[i]);
printf("\n");
}
static void HeapSortAsc(int *arr, int num)
{
int i;
for (i=num/2-1; i>=0; i--)
HeapShiftDown(arr, i, num - 1);
for (i=num-1; i>0; i--)
{
swap(&arr[0], &arr[i]);
HeapShiftDown(arr, 0, i - 1);
}
}
static void HeapShiftDown(int *arr, int start, int end)
{
int dead = start;
int son = dead * 2 + 1;
while (son <= end)
{
if (son + 1 < end && arr[son] < arr[son+1])
son += 1;
if (arr[dead] > arr[son])
break;
else
{
swap(&arr[dead], &arr[son]);
dead = son;
son = dead * 2 + 1;
}
}
}
static void swap(int *x, int *y)
{
int tmp = *x;
*x = *y;
*y = tmp;
}
```
<file_sep>/source/_posts/CentOS第三方库.md
---
layout: _post
title: CentOS第三方库
date: 2018-07-11 11:36:00
tags: yum
categories: 操作系统
---
`Software Collections`
`EPEL` `Remi` `CentOS`
在Red Hat企业Linux(RHEL)上,一般都是提供的老掉牙的软件。CentOS作为RHEL的复制品有着同样的问题。
如果应用依赖新版软件,怎么办呢?使用第三方仓库,推荐Software Collections、epel、Remi Collet。
* Software Collections
单独安装在/opt中,新旧软件分离,需要启动。
* epel
新旧软件不分离,容易造成混乱。无需启动,直接生效。
* Remi Collet
同epel。
# Software Collections
[Software Collections](https://www.softwarecollections.org/en/)是 Red Hat 唯一支持的新软件包源,为 CentOS 设立了专门的仓库,安装和管理都和其它第三方仓库一样。
在 CentOS 6/7上安装Software Collections命令如下:
```shell
$ sudo yum install centos-release-scl
```
`centos-release-scl-rh` 可能作为依赖包被同时安装。
然后就可以像平常一样搜索、安装软件包了:
```shell
$ yum search php7
[...]
rh-php70.x86_64 : Package that installs PHP 7.0
[...]
$ sudo yum install rh-php70
```
启用:
```shell
$ scl enable rh-php70 bash
$ php -v
PHP 7.0.10
```
这些 SCL 软件包在重启后不会激活。SCL 的设计初衷就是在不影响原有配置的前提下,让新旧软件能一起运行。不过你可以通过 `~/.bashrc` 加载 SCL 提供的 `enable` 脚本来实现自动启用。 SCL 的所有软件包都安装在 `/opt` 下, 以我们的 PHP 7 为例,在 `~/.bashrc` 里加入一行:
```shell
source /opt/rh/rh-php70/enable
```
# EPEL
Fedora 社区为 Feora 及所有 RHEL 系的发行版维护着 [EPEL:Extra Packages for Enterprise Linux](https://fedoraproject.org/wiki/EPEL) 。 里面包含一些最新软件包以及一些未被发行版收纳的软件包。
CentOS6/7安装命令如下:
```shell
yum install -y epel-release
yum --disablerepo=epel -y update ca-certificates
```
安装 EPEL 里的软件就不用麻烦 `enable` 脚本了,直接像平常一样用。你还可以用 `--disablerepo` 和 `--enablerepo` 选项指定从 EPEL 里安装软件包:
```shell
$ sudo yum --disablerepo "*" --enablerepo epel install [package]
```
# Remi Collet
Remi Collet 在 [Remi 的 RPM 仓库](http://rpms.remirepo.net/) 里维护着大量更新的和额外的软件包。需要先安装 EPEL ,因为 Remi 仓库依赖它。
CentOS wiki 上有较完整的仓库列表:[更多的第三方仓库](https://wiki.centos.org/AdditionalResources/Repositories) ,用哪些,不用哪些,里面都有建议。
# 指定仓库
列出可用仓库:
```shell
$ yum repolist
[...]
repo id repo name
base/7/x86_64 CentOS-7 - Base
centos-sclo-rh/x86_64 CentOS-7 - SCLo rh
centos-sclo-sclo/x86_64 CentOS-7 - SCLo sclo
extras/7/x86_64 CentOS-7 - Extras
updates/7/x86_64 CentOS-7 - Updates
```
列出指定仓库中的 软件包:
```shell
$ yum --disablerepo "*" --enablerepo centos-sclo-rh list available
```
`--disablerepo` 与 `--enablerepo` 简单说下。 实际上在这个命令里你并没有禁用或启用什么东西,而只是将你的搜索范围限制在某一个仓库内。
从指定仓库安装:
```shell
$ sudo yum --disablerepo "*" --enablerepo epel install [package]
```
<file_sep>/source/_posts/PostgreSQL共享缓存区管理.md
---
layout: _post
title: PostgreSQL共享缓存区管理
date: 2018-01-11 15:30:31
tags: PostgreSQL
categories: Database
---
# 共享缓冲区
PostgreSQL中的buffer主要是用来将外存中的数据内容读入到内存中,加速运算过程中对数据的访问速度,同时将数据的修改进行缓存,在必要时再将其写出到外存,避免频繁的I/O,以提高效率。
Buffer的种类有很多如Audit buffers、Clog buffers、Data buffers和Xlog buffers,此处所介绍的buffer管理是针对Data buffers而言的。
# 数据结构
- BufferTag
- BufferDesc
- BufferStrategyControl
## BufferTag
```c
typedef struct buftag
{
Oid dbid; /* database identifier */
FileBlock blockNum; /* file and blocknumber */
} BufferTag;
```
## BufferDesc
```c
typedef struct sbufdesc
{
BufferTag tag; /* ID of page contained in buffer */
RelFileNode rnode; /* relation this block belongs to */
BufFlags flags; /* see bit definitions above */
uint16 usage_count; /* usage counter for clock sweep code */
unsigned refcount; /* # of backends holding pins on buffer */
int wait_backend_pid; /* backend PID of pin-count waiter */
slock_t buf_hdr_lock; /* protects the above fields */
int buf_id; /* buffer's index number (from 0) */
int freeNext; /* link in freelist chain */
LWLockId io_in_progress_lock; /* to wait for I/O to complete */
LWLockId content_lock; /* to lock access to buffer contents */
} BufferDesc;
```
## 引用计数(BufferDesc.refcount)
引用计数(refcount)用于跟踪访问buffer的后台数量,防止错误的将正在被使用的Buffer淘汰。当使用Buffer时,需要将其引用计数(refcount)加1(PinBuffer)。当Buffer不再使用,需要将其引用计数(refcount)减1(UnpinBuffer)。这里需要注意,由于一个后台可以多次访问同一个Buffer,因此后台通过PrivateRefCount来记录自己的引用次数,只有当自己对一个Buffer的引用减少到0,才会真正去修改refcount。PrivateRefCount在后台PinBuffer时将其值加1,UnpinBuffer时将其值减1。
## 使用计数(BufferDesc.usage_count)
usage_count用来标记Buffer被使用的次数,usage_count值越大,说明该Buffer经常被使用,那么在未来的一段时间里被使用的可能就比较大,所以这样的Buffer不能作为被替换的对象;相反,usage_count值越小,说明经常不被使用,可以作为替换的对象。在PostgreSQL中,只有当usage_count为0时,才可能作为替换的对象。
usage_count是在一个后台不再使用该Buffer即UnpinBuffer将后台的PrivateRefCount减少为0的时候将其值加1,以表示该Buffer最近被一个后台使用了。对VACUUN操作来说,不会修改usage_count的值,且如果refcount和usage_count的值都为0,则将buffer放入到FreeList的尾部。
## BufferStrategyControl
```c
typedef struct
{
int nextVictimBuffer; // 指向下一Buffer
int firstFreeBuffer; // 第一个空闲缓冲块id
int lastFreeBuffer; // 最后一个空闲缓冲块id
} BufferStrategyControl;
/* Pointers to shared state */
static MT_LOCAL BufferStrategyControl
*StrategyControl = NULL;
```
## Buffer Descriptors

# 主要函数
- InitBufferPool
- BufferAlloc
- StrategyGetBuffer
- FlushBuffer
- PinBuffer
- UnpinBuffer
## InitBufferPool流程

## BufferAlloc流程

# 缓冲区替换策略
- FreeList
- Clock-sweep
- buffer-ring
## FreeList
当执行DROP TABLE时,可以确定该表的所有buffer都会失效,因此将此表的所有buffer都放入到Freelist的头部,这样可以在下一次分配buffer时,直接从Freelist中得到buffer,而不需要执行Clock Sweep算法。
## Clock-sweep
当Buffer的refcount计数变成0的时候,代表当前系统没有后台引用此数据块。在PostgreSQL中,为了能够减低锁的粒度、提高并发性,引用计数等于0的的Buffer并没有被放入Freelist中。在随机访问大量磁盘块、并且没有VACUUM的干扰下,Freelist几乎是空的(除了刚刚启动时)。这里的策略主要是为了避免不必要的持有操作Freelist的互斥锁。
由于大部分时候Buffer不会立即被放入到Freelist中,因此使用了一种被称为Clock Sweep的算法来分配Buffer。此算法类似教科书中时钟算法,每当需要使用Clock Sweep算法选择一个Buffer时,就从上次分配的Buffer的下一个位置开始,搜索引用计数为0(既没有被pin的Buffer)且usage_count为0的Buffer。如果该Buffer不满足上述条件,就将usage_count减1。
## Clock-sweep

> 在上图中Clock Sweep算法从4号buffer开始查找(记录在StrategyControl结构体中)可用的buffer。4号buffer因为引用计数大于0,因此不能被替换。5号buffer虽然没有人引用,但是其usage_count大于0,因此表示此buffer使用频率较高,因此将usage_count减1,并查看6号buffer。6号buffer的引用计数和usage_count都为0,因此选择将6号buffer淘汰。记录下一次搜索的位置是7号,并退出选择算法。
## buffer-ring
批量读或者vacuum等操作可能会需要占据大量的buffer,影响其他正常业务。buffer-ring机制在批量读等占用的buffer数量达到某个程度(比如总buffer的1/4)时,分配给该操作固定的buffer数量,之后只能使用为其分配的buffer,而不能替换其他buffer。
<file_sep>/source/_posts/pgbouncer-greenplum测试.md
---
title: pgbouncer--greenplum测试
date: 2018-07-19 15:53:57
tags:
- PostgreSQL
- pgbouncer
categories: Database
---
# 测试环境
系统:CentOS release 6.5 (Final)
节点:
| 节点 | 地址 | 角色 |
| ---- | ------------- | ------------------------------------ |
| h1 | 192.168.2.114 | master,seg0~seg7,mirror(seg8~seg15) |
| h2 | 192.168.2.115 | standby,seg8~seg15,mirror(seg0~seg7) |
连接数:
- pgbouncer --- 100 ---> master
- client --- 1000 ---> pgbouncer
用户:yfshi/123456
# greenplum
## 配置交互key
```shell
# gpssh-exkeys -h h1 -h h2
```
## 安装
略
## 初始化
- 初始化数据目录
```shell
$ gpssh -h h1 -h h2
=> mkdir -p /home/yfshi/gpdata/master
=> mkdir -p /home/yfshi/gpdata/primary
=> mkdir -p /home/yfshi/gpdata/mirror
```
- 配置gpinitsystem_config
```shell
ARRAY_NAME="Greenplum Data Platform"
SEG_PREFIX=gpseg
PORT_BASE=64300
declare -a DATA_DIRECTORY=(/home/yfshi/gpdata/primary /home/yfshi/gpdata/primary /home/yfshi/gpdata/primary /home/yfshi/gpdata/primary /home/yfshi/gpdata/primary /home/yfshi/gpdata/primary /home/yfshi/gpdata/primary /home/yfshi/gpdata/primary)
MASTER_HOSTNAME=h1
MASTER_DIRECTORY=/home/yfshi/gpdata/master
MASTER_PORT=65432
TRUSTED_SHELL=ssh
CHECK_POINT_SEGMENTS=8
ENCODING=UNICODE
MIRROR_PORT_BASE=64400
REPLICATION_PORT_BASE=64500
MIRROR_REPLICATION_PORT_BASE=64600
declare -a MIRROR_DATA_DIRECTORY=(/home/yfshi/gpdata/mirror /home/yfshi/gpdata/mirror /home/yfshi/gpdata/mirror /home/yfshi/gpdata/mirror /home/yfshi/gpdata/mirror /home/yfshi/gpdata/mirror /home/yfshi/gpdata/mirror /home/yfshi/gpdata/mirror)
MACHINE_LIST_FILE=/home/yfshi/config/hostfile_gpinitsystem
```
- 配置hostfile_gpinitsystem
```shell
h1
h2
```
- 初始化并启动
```shell
$ gpinitsystem -c gpinitsystem_config -s h2
```
# pgbouncer测试1000连接数
## 配置
- pgbouncer.ini
```shell
[databases]
pgbench = host=127.0.0.1 dbname=pgbench user=yfshi port=65432
postgres = host=127.0.0.1 dbname=pgbench user=yfshi port=65432
[pgbouncer]
logfile = /home/yfshi/pgbouncer/var/log/pgbouncer.log # 日志文件
pidfile = /home/yfshi/pgbouncer/var/log/pgbouncer.pid # pid文件
listen_addr = 127.0.0.1 # 监听地址
listen_port = 6543 # 监听端口
auth_type = trust
auth_file = /home/yfshi/pgbouncer/etc/userlist.txt # 用户认证文件
pool_mode = session
server_reset_query = DISCARD ALL
max_client_conn = 1000 # pgbouncer的客户端最大连接数
default_pool_size = 100 # 连接池大小
admin_users = yfshi # 管理员,pgbouncer内部使用
```
- userlist.txt
```shell
"admin" "111111"
"yfshi" "111111"
```
## 启动
```shell
$ pgbouncer -d pgbouncer.ini
```
## 管理
> pbouncer提供了类似连接到虚拟数据库pgbouncer,然后执行一些特殊命令的功能,这些命令就像是执行一个真正的SQL命令,让管理者能查询和管理pgbouncer的连接池信息,这个界面为pgbouncer的Console控制界面.一般使用psql命令连接到这个虚拟数据库上.
```shell
$ psql -p6543 pgbouncer
psql (9.6.3, server 1.7.2/bouncer)
Type "help" for help.
pgbouncer=#
```
show help
> NOTICE: Console usage
> DETAIL:
> SHOW HELP|CONFIG|DATABASES|POOLS|CLIENTS|SERVERS|VERSION
> SHOW FDS|SOCKETS|ACTIVE_SOCKETS|LISTS|MEM
> SHOW DNS_HOSTS|DNS_ZONES
> SHOW STATS|STATS_TOTALS|STATS_AVERAGES
> SET key = arg
> RELOAD
> PAUSE [<db>]
> RESUME [<db>]
> DISABLE <db>
> ENABLE <db>
> KILL <db>
> SUSPEND
> SHUTDOWN
> SHOW
show config
> 显示当前配置设置,一个配置一行,字段如下:
>
> * key:配置变量名称
> * value:配置值
> * changeable:yes 或 no,显示这个变量是否可以在运行时修改如果为 no,那么这个变量只能在启动的时候修改
下表是执行show config;的结果。一下的key都可以在pgbouncer.ini的[pgbouncer]中配置:
| key | value | changeable |
| ------------------------- | ------------------------------------------------------ | ---------- |
| job_name | pgbouncer | no |
| conffile | pgbouncer.ini | yes |
| logfile | /home/yfshi/pgbouncer/pgbouncer.log | yes |
| pidfile | /home/yfshi/pgbouncer/pgbouncer.pid | no |
| listen_addr | 192.168.2.113 | no |
| listen_port | 55556 | no |
| listen_backlog | 128 | no |
| unix_socket_dir | /tmp | no |
| unix_socket_mode | 511 | no |
| unix_socket_group | | no |
| auth_type | trust | yes |
| auth_file | /home/yfshi/pgbouncer/userlist.txt | yes |
| auth_hba_file | | yes |
| auth_user | | yes |
| auth_query | SELECT usename, passwd FROM pg_shadow WHERE usename=$1 | yes |
| pool_mode | session | yes |
| max_client_conn | 200 | yes |
| default_pool_size | 100 | yes |
| min_pool_size | 0 | yes |
| reserve_pool_size | 0 | yes |
| reserve_pool_timeout | 5 | yes |
| max_db_connections | 0 | yes |
| max_user_connections | 0 | yes |
| syslog | 0 | yes |
| syslog_facility | daemon | yes |
| syslog_ident | pgbouncer | yes |
| user | | no |
| autodb_idle_timeout | 3600 | yes |
| server_reset_query | DISCARD ALL | yes |
| server_reset_query_always | 0 | yes |
| server_check_query | select 1 | yes |
| server_check_delay | 30 | yes |
| query_timeout | 0 | yes |
| query_wait_timeout | 120 | yes |
| client_idle_timeout | 0 | yes |
| client_login_timeout | 60 | yes |
| idle_transaction_timeout | 0 | yes |
| server_lifetime | 3600 | yes |
| server_idle_timeout | 600 | yes |
| server_connect_timeout | 15 | yes |
| server_login_retry | 15 | yes |
| server_round_robin | 0 | yes |
| suspend_timeout | 10 | yes |
| ignore_startup_parameters | | yes |
| disable_pqexec | 0 | no |
| dns_max_ttl | 15 | yes |
| dns_nxdomain_ttl | 15 | yes |
| dns_zone_check_period | 0 | yes |
| max_packet_size | 2147483647 | yes |
| pkt_buf | 4096 | no |
| sbuf_loopcnt | 5 | yes |
| tcp_defer_accept | 1 | yes |
| tcp_socket_buffer | 0 | yes |
| tcp_keepalive | 1 | yes |
| tcp_keepcnt | 0 | yes |
| tcp_keepidle | 0 | yes |
| tcp_keepintvl | 0 | yes |
| verbose | 0 | yes |
| admin_users | yfshi | yes |
| stats_users | | yes |
| stats_period | 60 | yes |
| log_connections | 1 | yes |
| log_disconnections | 1 | yes |
| log_pooler_errors | 1 | yes |
| application_name_add_host | 0 | yes |
| client_tls_sslmode | disable | no |
| client_tls_ca_file | | no |
| client_tls_cert_file | | no |
| client_tls_key_file | | no |
| client_tls_protocols | all | no |
| client_tls_ciphers | fast | no |
| client_tls_dheparams | auto | no |
| client_tls_ecdhcurve | auto | no |
| server_tls_sslmode | disable | no |
| server_tls_ca_file | | no |
| server_tls_cert_file | | no |
| server_tls_key_file | | no |
| server_tls_protocols | all | no |
| server_tls_ciphers | HIGH:MEDIUM:+3DES:!aNULL | no |
show pools
> 列出连接池
>
> * database:数据库名
> * user:用户名
> * cl_active:当前 active (活跃)的客户端连接的个数
> * cl_waiting:当前 waiting (等待)的客户端连接个数
> * sv_active:当前 active (活跃)的服务器连接个数
> * sv_idle:当前 idle (空闲) 的服务器连接个数
> * sv_used:当前 used (在使用)的服务器连接个数
> * sv_tested:当前 tested (测试过)的服务器连接个数
> * sv_login:当前 login (登录)到 PostgreSQL 服务器的个数
> * maxwait:队列中第一个(最老的那个)客户端等待的时间长度,单位是秒.如果这个数值开始上升,那么就意味着当前的连接池中的服务器处理请求的速度不够快.原因可能是服务器过载,也可能只是 pool_size 太小
show stats
> - database:统计是根据每个数据库分比例的
> - total_requests:连接池处理的SQL请求的总数
> - total_received:接收到的网络流量的总字节数
> - total_sent:发出的网络流量的总字节数
> - total_query_time:活跃在与数据库上面的时间开销总数,单位是微秒
> - avg_req:在最后一次统计过程中的每秒平均请求数
> - avg_recv:每秒(从客户端)接收到的平均数据量
> - avg_sent:每秒发送(给客户端)的平均数据量
> - avg_query:平均的查询时间,单位是微秒
show servers
> 列出数据库与pgbouncer之间连接
> * type:S,表示服务器
> * user:gbouncer用于连接服务器的用户名
> * database:服务器端的数据库名
> * state:pgbouncer 服务器连接的状态 active、used、idle
> * addr:PostgreSQL服务器的IP地址
> * port:PostgreSQL服务器的端口
> * local_addr:本地机器上的发起连接地址
> * local_port:本地机器上的发起连接端口
> * connect_time:连接建立的时间
> * request_time:请求发出的时间
> * ptr:这个连接的内部对象地址,用做唯一 ID
> * link:这个服务器对应的客户端地址
show clients
> 列出客户端及客户端连接状态
> * type:C,表示客户端
> * user:客户端连接的用户
> * database:数据库名
> * state:客户端连接的状态 active、used、waiting或者idle之一
> * addr:客户端的 IP 地址
> * port:客户端连接去的端口
> * local_addr:本地机器上连接到的对端地址
> * local_port:本地机器上的连接到的对端端口
> * connect_time:最后的客户端连接的时间戳
> * request_time:最后的客户端请求的时间戳
> * ptr:这个连接的内部对象的地址,用做唯一 ID
> * link:这个客户端连接对应的服务器的地址
show lists
> 显示连接池的计数信息
> * databases:数据库的个数
> * users:用户的个数
> * pools:连接池的个数
> * free_clients:空闲客户端的个数
> * used_clients:已用的客户端的个数
> * login_clients:处于已登录状态的客户端个数
> * free_servers:空闲服务器个数
> * used_servers:已用服务器个数
show databases
> 列出pgbouncer数据库别名及相关数据库
> * name:已配置的数据库名字记录
> * host:pgbouncer 连接到的主机名
> * port:pgbouncer 连接到的端口号
> * database:pgbouncer 实际连接的数据库名
> * force_user:当用户是连接字串的一部分的时候,在 pgbouncer 和 PostgreSQL 之间的连接会强制成给出的用户,不管 client user 是什么
> * pool_size:最大的服务器端连接数目
show fds
> 显示正在使用的 fd 列表如果连接的用户的用户名是 “pgbouncer”,那么通过 unix socket 连接,并且和运行的进程有同样的 UID,实际的 fd 列表是通过这个连接传递的这个机制用于做在线重启
> - fd:文件描述符的数字值
> - task:pooler,client 或 server 之一
> - user:使用该 FD 的连接用户
> - database:使用该 FD 的连接的数据库
> - addr:使用该 FD 的连接的 IP 地址,如果使用的是 unix socket,就是 unix
> - port:使用该 FD 的连接的端口号
> - cancel:这个连接的取消键字
> - link:对应的服务器/客户端的 fd如果为 idle (空闲)则为 NULL
DISABLE <db>
> 拒绝指定数据库上所有新客户端连接
ENALBLE <db>
> 准许之前DISABLE命令之后的新客户端连接
PAUSE [<db>]
> 尝试从所有服务器断开连接(等待query完成),在所有query完成之前,此命令不会返回,在数据库重新启动时使用.如果给出了数据库名字则只对该数据库有用
KILL <db>
> 立即删除给定数据库上所有客户端以及数据库连接
SUPEND
> 刷新所有socket缓存,并且停止监听,在缓存flush之前此命令不会有任何返回.使用场景:pgbouncer在线重新启动时使用
RESUME [<db>]
> 从之前PAUSE或者SUPEND命令恢复之前状态
SHUTDOWN
> pgbouncer进程退出
RELOAD
> 重新加载其配置文件并更新配置
## 测试
- 只读查询
```shell
$ pgbench -p6543 -i pgbench
$ pgbench -p6543 -n -S -c 1000 -t 1 pgbench
transaction type: SELECT only
scaling factor: 1
query mode: simple
number of clients: 1000
number of threads: 1
number of transactions per client: 1
number of transactions actually processed: 1000/1000
tps = 713.361402 (including connections establishing)
tps = 866.376950 (excluding connections establishing)
$ psql -p6543 pgbench
$ SELECT count(*) from pg_stat_activity;
count
-------
100
(1 row)
```
- 行存插入
```shell
$ psql -p6543 -c "create table table_h(id serial, n1 varchar(20), n2 varchar(20)) distributed by (id);" pgbench;
$ echo "insert into table_h(n1,n2) values('n1','n2')" > test.sql
$ pgbench -p6543 -n -f test.sql -c 1000 -t 1 pgbench
transaction type: Custom query
scaling factor: 1
query mode: simple
number of clients: 1000
number of threads: 1
number of transactions per client: 1
number of transactions actually processed: 1000/1000
tps = 207.016064 (including connections establishing)
tps = 217.756804 (excluding connections establishing)
```
- 列存插入
```shell
$ psql -p6543 -c "create table table_c(id serial, n1 varchar(20), n2 varchar(20)) with (appendonly=true,orientation=column,compresstype=zlib,COMPRESSLEVEL=5) distributed by (id);" pgbench;
$ echo "insert into table_c(n1,n2) values('n1','n2')" > test.sql
$ pgbench -p6543 -n -f test.sql -c 1000 -t 1 pgbench
transaction type: Custom query
scaling factor: 1
query mode: simple
number of clients: 1000
number of threads: 1
number of transactions per client: 1
number of transactions actually processed: 1000/1000
tps = 64.295818 (including connections establishing)
tps = 65.290265 (excluding connections establishing)
```
<file_sep>/source/_posts/iptables.md
---
layout: _post
title: iptables
date: 2018-09-14 16:35:52
categories: 操作系统
tags:
- iptables
- netfilter
- snat
- dnat
- 防火墙
---
# netfilter/iptables
netfilter是linux内核2.4.x引入的一个子系统,作为一个通用的、抽象的框架,提供一整套的hook(钩子、检查点)函数的管理机制,使得诸如包过滤、网络地址转换(NAT)和基于协议类型的连接跟踪成为了可能。
netfilter的架构就是在整个网络流程的若干位置放置了一些检测点(hook),而在每个检测点上登记了一些处理函数进行处理。

netfilter主要采用连线跟踪(Connection Tracking)、包过滤(Packet Filtering)、地址转换(NAT)、包处理(Packet Mangling)4种关键技术。
* 连线跟踪
是包过滤、地址转换的基础,它作为一个独立的模块运行。采用连线跟踪技术在协议栈低层截取数据包,将当前数据包及其状态信息与历史数据包及其状态信息进行比较,从而得到当前数据包的控制信息,根据这些信息决定对网络数据包的操作,达到保护网络的目的。
当下层网络接收到初始化连接同步(Synchronize,SYN)包,将被netfilter规则库检查。该数据包将在规则链中依次序进行比较。如果该包应被丢弃,发送一个复位(Reset,RST)包到远端主机,否则连接接收。这次连接的信息将被保存在连线跟踪信息表中,并表明该数据包所应有的状态。这个连线跟踪信息表位于内核模式下,其后的网络包就将与此连线跟踪信息表中的内容进行比较,根据信息表中的信息来决定该数据包的操作。因为数据包首先是与连线跟踪信息表进行比较,只有SYN包才与规则库进行比较,数据包与连线跟踪信息表的比较都是在内核模式下进行的,所以速度很快。
* 包过滤
包过滤检查通过的每个数据包的头部,然后决定如何处置它们,可以选择丢弃,让包通过,或者更复杂的操作。
* 地址转换
网络地址转换分为源NAT(Source NAT,SNAT)和目的NAT(Destination NAT,DNAT)2种不同的类型。SNAT是指修改数据包的源地址(改变连接的源IP)。SNAT会在数据包送出之前的最后一刻做好转换工作。地址伪装(Masquerading)是SNAT的一种特殊形式。DNAT 是指修改数据包的目标地址(改变连接的目的IP)。DNAT 总是在数据包进入以后立即完成转换。端口转发、负载均衡和透明代理都属于DNAT。
* 包处理
利用包处理可以设置或改变数据包的服务类型(Type of Service,TOS)字段;改变包的生存期(Time to Live,TTL)字段;在包中设置标志值,利用该标志值可以进行带宽限制和分类查询。
iptables是运行在用户空间的一个防火墙管理工具,真正的防火墙是netfilter。
netfilter组件是内核模块,iptables是用户空间工具。

# 四表五链
* 规则(rule)
* 规则表(table)
实现特定功能的规则的集合。iptables内置了4个表,raw、mangle、nat、filter表,分表用于实现数据跟踪处理、包重构、网络地址转换和包过滤。
* 规则链(chain)
一个chain就是一个检查清单(钩子、hook),每一条链中可以有多个规则。一共预定义了五个规则链。
* 自定义链
用户可以自定义链。但是无法自动触发,需要由预定义链跳转过来。

# 网络数据流向

有三条报文类型:
* 进入本机的报文
网络 -> PREROUTING -> route -> INPUT -> 本机应用
* 本机发出的报文
本机应用 -> route -> OUTPUT -> POSTROUTING
* 转发的报文
网路A -> PREROUTING -> route -> FORWARD -> POSTROUTING -> 网络B
# iptables用法
可以根据下面两图使用iptables


# 例子
## nat
局域网通过snat网关上网;局域网的web服务器需要映射到外网;


```shell
# 首先打开路由转发功能
$ sysctl -w net.ipv4.ip_forward=1
# 永久生效方法 echo "net.ipv4.ip_forward=1">>/etc/sysctl.conf && sysctl -p
# snat访问外网
$ iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# dnat映射内网服务器
$ iptables -t nat -p tcp --dport 80 -A PREROUTING -i eth1 -j DNAT --to-destination 192.168.1.6
# 保存
$ service iptables save
```
## filter
限制本机的web服务器在周一不允许访问; 新请求的速率不能超过100个每秒;web服务器包含了admin字符串的页面不允许访问;web 服务器仅允许响应报文离开本机;
```shell
# 周一不允许访问
$ iptables -A INPUT -p tcp --dport 80 -m time ! --weekdays Mon -j ACCEPT
$ iptables -A OUTPUT -p tcp --dport 80 -m state --state ESTABLISHED -j ACCEPT
# 新请求速率不能超过100个每秒
$ iptables -A INPUT -p tcp --dport 80 -m limit --limit 100/s -j ACCEPT
# web包含admin字符串的页面不允许访问,源端口:dport
$ iptables -A INPUT -p tcp --dport 80 -m string --algo bm --string 'admin' -j REJECT
# web服务器仅允许响应报文离开主机,目标端口:sport
$ iptables -A OUTPUT -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
```
在工作时间,即周一到周五的8:30-18:00,开放本机的ftp服务给192.168.1.0网络中的主机访问;数据下载请求的次数每分钟不得超过 5 个;
```shell
$ iptables -A INPUT -p tcp --dport 21 -s 192.168.1.0/24 -m time ! --weekdays 6,7 -m time --timestart 8:30 --timestop 18:00 -m connlimit --connlimit-above 5 -j ACCET
```
开放本机的ssh服务给192.168.1.1-192.168.1.100 中的主机;新请求建立的速率一分钟不得超过2个;仅允许响应报文通过其服务端口离开本机;
```shell
$ iptables -A INPUT -p tcp --dport 22 -m iprange --src-rang 192.168.1.1-192.168.1.100 -m limit --limit 2/m -j ACCEPT
$ iptables -A OUTPUT -p tcp --sport 22 -m iprange --dst-rang 192.168.1.1-192.168.1.100 -m state --state ESTABLISHED -j ACCEPT
```
拒绝 TCP 标志位全部为 1 及全部为 0 的报文访问本机;
```shell
$ iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
```
允许本机 ping 别的主机;但不开放别的主机 ping 本机;
```shell
$ iptables -I INPUT -p icmp --icmp-type echo-request -j DROP
$ iptables -I INPUT -p icmp --icmp-type echo-reply -j ACCEPT
$ iptables -I INPUT -p icmp --icmp-type destination-Unreachable -j ACCEPT
# 或者下面禁ping操作:
$ echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all
```
## 其他
```shell
# 开通本机的22端口,允许192.168.1.0网段的服务器访问
$ iptables -A INPUT -s 192.168.1.0/24 -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
# 开通本机的80端口,只允许192.168.1.150机器访问
$ iptables -t filter -A INPUT -s 192.168.1.150/32 -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
# 拒绝进入防火墙的所有ICMP协议数据包
$ iptables -I INPUT -p icmp -j REJECT
# 允许防火墙转发除ICMP协议以外的所有数据包
$ iptables -A FORWARD -p ! icmp -j ACCEPT
# 拒绝转发来自192.168.1.10主机的数据,允许转发来自192.168.0.0/24网段的数据
$ iptables -A FORWARD -s 192.168.1.11 -j REJECT
$ iptables -A FORWARD -s 192.168.0.0/24 -j ACCEPT
# 注意一定要把拒绝的放在前面不然就不起作用了!
# 丢弃从外网接口(eth1)进入防火墙本机的源地址为私网地址的数据包
$ iptables -A INPUT -i eth1 -s 192.168.0.0/16 -j DROP
$ iptables -A INPUT -i eth1 -s 172.16.0.0/12 -j DROP
$ iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP
# 只允许管理员从172.16.31.10/16网段使用SSH远程登录防火墙主机
$ iptables -A INPUT -s 172.16.31.10/16 -p tcp -m tcp -m state --state NEW --dport 22 -j ACCEPT
# 允许本机开放从TCP端口20-1024提供的应用服务
$ ptables -A INPUT -p tcp -m tcp -m state --state NEW --dport 20:1024 -j ACCEPT
# 允许转发来自192.168.0.0/24局域网段的DNS解析请求数据包
$ iptables -A FORWARD -s 192.168.0.0/24 -p udp --dport 53 -j ACCEPT
$ iptables -A FORWARD -d 192.168.0.0/24 -p udp --sport 53 -j ACCEPT
# 屏蔽环回(loopback)访问
$ iptables -A INPUT -i lo -j DROP
$ iptables -A OUTPUT -o lo -j DROP
# 屏蔽来自外部的ping,即禁止外部机器ping本机
$ iptables -A INPUT -p icmp --icmp-type echo-request -j DROP
$ iptables -A OUTPUT -p icmp --icmp-type echo-reply -j DROP
# 屏蔽从本机ping外部主机,禁止本机ping外部机器
$ iptables -A OUTPUT -p icmp --icmp-type echo-request -j DROP
$ iptables -A INPUT -p icmp --icmp-type echo-reply -j DROP
# 禁止其他主机ping本机,但是允许本机ping其他主机(禁止别人ping本机,也可以使用echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all)
$ iptables -I INPUT -p icmp --icmp-type echo-request -j DROP
$ iptables -I INPUT -p icmp --icmp-type echo-reply -j ACCEPT
$ iptables -I INPUT -p icmp --icmp-type destination-Unreachable -j ACCEPT
# 禁止转发来自MAC地址为00:0C:29:27:55:3F的和主机的数据包
$ iptables -A FORWARD -m mac --mac-source 00:0c:29:27:55:3F -j DROP
# iptables中使用“-m 模块关键字”的形式调用显示匹配。咱们这里用“-m mac –mac-source”来表示数据包的源MAC地址
# 允许防火墙本机对外开放TCP端口20、21、25、110以及被动模式FTP端口1250-1280
$ iptables -A INPUT -p tcp -m multiport --dport 20,21,25,110,1250:1280 -j ACCEPT
$ iptables -A INPUT -p tcp -m tcp -m multiport --dports 22,80,443,1250-1280 -m state --state NEW -j ACCEPT
# 也可以将这几个端口分开设置多行:
$ iptables -A INPUT -p tcp -m tcp -m state --state NEW --dport 22 -j ACCEPT
$ iptables -A INPUT -p tcp -m tcp -m state --state NEW --dport 80 -j ACCEPT
$ iptables -A INPUT -p tcp -m tcp -m state --state NEW --dport 443 -j ACCEPT
$ iptables -A INPUT -p tcp -m tcp -m state --state NEW --dport 1250:1280 -j ACCEPT
#禁止转发源IP地址为192.168.1.20-192.168.1.99的TCP数据包
$ iptables -A FORWARD -p tcp -m iprange --src-range 192.168.1.20-192.168.1.99 -j DROP
# 禁止转发与正常TCP连接无关的非--syn请求数据包
$ iptables -A FORWARD -m state --state NEW -p tcp ! --syn -j DROP
# “-m state”表示数据包的连接状态,“NEW”表示与任何连接无关的
# 拒绝访问防火墙的新数据包,但允许响应连接或与已有连接相关的数据包
$ iptables -A INPUT -p tcp -m state --state NEW -j DROP
$ iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT
# “ESTABLISHED”表示已经响应请求或者已经建立连接的数据包,“RELATED”表示与已建立的连接有相关性的,比如FTP数据连接等
# 防止DoS攻击
$ iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
# -m limit: 启用limit扩展,限制速度。
# --limit 25/minute: 允许最多每分钟25个连接
# --limit-burst 100: 当达到100个连接后,才启用上述25/minute限制
# --icmp-type 8 表示 Echo request——回显请求(Ping请求)。下面表示本机ping主机192.168.1.109时候的限速设置:
$ iptables -I INPUT -d 192.168.1.109 -p icmp --icmp-type 8 -m limit --limit 3/minute --limit-burst 5 -j ACCEPT
# 如果本地主机有两块网卡,一块连接内网(eth0),一块连接外网(eth1),那么可以使用下面的规则将eth0的数据路由到eht1:
$ iptables -A FORWARD -i eth0 -o eth1 -j ACCEPT
# 拒绝进入防火墙的所有ICMP协议数据包
$ iptables -I INPUT -p icmp -j REJECT
# 允许防火墙转发除ICMP协议以外的所有数据包
$ iptables -A FORWARD -p ! icmp -j ACCEPT
# 拒绝转发来自192.168.1.10主机的数据,允许转发来自192.168.0.0/24网段的数据
$ iptables -A FORWARD -s 192.168.1.11 -j REJECT
$ iptables -A FORWARD -s 192.168.0.0/24 -j ACCEPT
# 注意一定要把拒绝的放在前面不然就不起作用了
# 丢弃从外网接口(eth1)进入防火墙本机的源地址为私网地址的数据包
$ iptables -A INPUT -i eth1 -s 192.168.0.0/16 -j DROP
$ iptables -A INPUT -i eth1 -s 172.16.0.0/12 -j DROP
$ iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP
# 允许转发来自192.168.0.0/24局域网段的DNS解析请求数据包
$ iptables -A FORWARD -s 192.168.0.0/24 -p udp --dport 53 -j ACCEPT
$ iptables -A FORWARD -d 192.168.0.0/24 -p udp --sport 53 -j ACCEPT
# 假设现在本机外网网关是172.16.58.3,那么把HTTP请求转发到内部的一台服务器192.168.1.20的8888端口上,规则如下
$ iptables -t nat -A PREROUTING -p tcp -i eth0 -d 172.16.58.3 --dport 8888 -j DNAT --to 192.168.1.20:80
$ iptables -A FORWARD -p tcp -i eth0 -d 192.168.0.2 --dport 80 -j ACCEPT
$ iptables -t filter -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
# 把所有10.8.0.0网段的数据包SNAT成192.168.5.3的ip然后发出去
$ iptables -t nat -A POSTROUTING -s 10.8.0.0/255.255.255.0 -o eth0 -j SNAT --to-source 192.168.5.3
# 把所有10.8.0.0网段的数据包SNAT成192.168.5.3/192.168.5.4/192.168.5.5等几个ip然后发出去
$ iptables -t nat -A POSTROUTING -s 10.8.0.0/255.255.255.0 -o eth0 -j SNAT --to-source 192.168.5.3-192.168.5.5
# 从服务器的网卡上,自动获取当前ip地址来做NAT
$ iptables -t nat -A POSTROUTING -s 10.8.0.0/255.255.255.0 -o eth0 -j MASQUERADE
```
<file_sep>/source/_posts/Greenplum安装.md
---
layout: _post
title: Greenplum安装
date: 2018-07-10 19:40:00
tags:
- PostgreSQL
- Greenplum
categories: Database
---
节点分配:
| 地址 | 主机名 | segment | mirror |
| ---------- | ------ | ------------- | ------------ |
| 10.0.0.100 | gp | master | |
| 10.0.0.101 | gp1 | pseg0、pseg1 | mseg4、mseg5 |
| 10.0.0.102 | gp2 | pseg2、gpseg3 | mseg0、mseg1 |
| 10.0.0.103 | gp3 | pseg4、pseg5 | mseg2、mseg3 |
| 10.0.0.104 | gps | standby | |
# 操作系统
本章所有操作在所有节点使用root用户执行
## 开发环境
当前系统如下:
```shell
$ cat /etc/issue
CentOS release 6.4 (Final)
Kernel \r on an \m
$ uname -a
Linux vm 2.6.32-358.el6.x86_64 #1 SMP Fri Feb 22 00:31:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
```
搭建基本环境:
```shell
# linux基本环境
$ yum install -y bzip2 cmake gcc gcc-c++ gdb git libtool lrzsz make man net-tools sysstat unzip vim wget zip
# 数据库开发环境
$ yum install -y apr-devel apr-util-devel bison bzip2-devel c-ares-devel flex java-1.8.0-openjdk java-1.8.0-openjdk-devel json-c-devel krb5-devel libcurl-devel libevent-devel libkadm5 libxml2-devel libxslt-devel libyaml-devel openldap-devel openssl-devel pam-devel perl perl-devel perl-ExtUtils-Embed readline-devel unixODBC-devel zlib-devel
```
如果上述环境无法满足要求,参考[Greenplun编译](../Greenplum编译/)
## 系统设置
```shell
# 关闭防火墙
$ service iptables stop
$ chkconfig iptables off
# 禁用selinux
$ setenforce 0
$ vi /etc/selinux/config
SELINUX=disabled
# 分别配置ip
$ bash -c 'cat > /etc/sysctl.conf <<-EOF
DEVICE=eth0
TYPE=Ethernet
ONBOOT=yes
BOOTPROTO=static
IPADDR=10.0.0.100
NETMASK=255.255.255.0
EOF'
# 分别设置主机名
$ vi /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=gp
```
## 系统参数配置
```shell
$ cat >> /etc/sysctl.conf <<-EOF
kernel.shmmax = 500000000
kernel.shmmni = 4096
kernel.shmall = 4000000000
kernel.sem = 500 1024000 200 4096
kernel.sysrq = 1
kernel.core_uses_pid = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.msgmni = 2048
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_forward = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.conf.all.arp_filter = 1
net.ipv4.ip_local_port_range = 1025 65535
net.core.netdev_max_backlog = 10000
net.core.rmem_max = 2097152
net.core.wmem_max = 2097152
vm.overcommit_memory = 2
EOF
$ cat >> /etc/security/limits.conf <<-EOF
* soft nofile 65536
* hard nofile 65536
* soft nproc 131072
* hard nproc 131072
EOF
$ cat >> /etc/ld.so.conf <<-EOF
/usr/local/lib
EOF
```
## 添加主机名本地映射
```shell
$ cat >> /etc/hosts <<-EOF
10.0.0.100 ka
10.0.0.101 ka1
10.0.0.102 ka2
10.0.0.103 ka3
10.0.0.104 kas
EOF
```
## 重启操作系统
上述所有配置完成之后重启操作系统。
如果是在虚拟机操作,创建快照,方便以后恢复。另外,如果是虚拟机操作,只需配置一台机器,然后克隆其他的机器,修改ip和主机名即可。
# 安装Greenplum
## 添加用户
```shell
$ useadd gpadmin
$ passwd gpadmin
$ vi /etc/sudoers
gpadmin ALL=(ALL) NOPASSWD: ALL
```
以下操作都在主节点的gpadmin用户下进行
## 创建节点文件
创建两个文件:all_hosts和all_segs,all_hosts是所有节点列表,all_segs是所有segment所在的节点列表。
```shell
$ cat all_hosts
gp
gp1
gp2
gp3
gps
$ cat all_segs
gp1
gp2
gp3
```
## 配置主机互信
交换密钥
```shell
$ source /home/gpadmin/gpdb/Greenplum_path.sh
$ gpssh-exkeys -f all_hosts
```
## 安装
* master节点安装Greenplum到/home/gpadmin/gpdb
略
* 把master的Greenplum同步安装到其他机器
```shell
$ source /home/gpadmin/gpdb/Greenplum_path.sh
$ gpseginstall -f all_hosts
```
# 初始化Greenplum
修改配置文件
```shell
$ cp /home/gpadmin/gpdb/docs/cli_help/gpconfigs/gpinitsystem_config .
# 修改为如下配置,各个参数的意义参考注释
$ cat gpinitsystem_config | grep -E -v '^#' | grep -v '^$'
ARRAY_NAME="Greenplum Data Platform"
SEG_PREFIX=gpseg
PORT_BASE=40000
declare -a DATA_DIRECTORY=(/data/primary)
MASTER_HOSTNAME=ka
MASTER_DIRECTORY=/data/master
MASTER_PORT=5432
TRUSTED_SHELL=ssh
CHECK_POINT_SEGMENTS=8
ENCODING=UNICODE
MIRROR_PORT_BASE=50000
REPLICATION_PORT_BASE=41000
MIRROR_REPLICATION_PORT_BASE=51000
declare -a MIRROR_DATA_DIRECTORY=(/data/mirror)
```
创建数据目录
```shell
$ gpssh -f all_hosts
=> sudo mkdir /data
=> sudo chown gpadmin.gpadmin /data
=> mkdir /data/master
=> mkdir /data/primary
=> mkdir /data/mirror
```
初始化集群
```shell
$ gpinitsystem -c gpinitsystem_config -h all_segs -s kas -S
```
配置主机和备机的环境变量
```shell
$ vi .bashrc
if [ -f /home/gpadmin/gpdb/Greenplum_path.sh ]; then
source /home/gpadmin/gpdb/Greenplum_path.sh
export MASTER_DATA_DIRECTORY=/data/master/gpseg-1
fi
$ source .bashrc
```
# 使用Greenplum
```shell
$ psql -hgp -dpostgres
```
<file_sep>/source/_posts/shell.md
---
layout: post
title: Shell
date: 2017-10-23
tags:
- shell
categories: Shell
---
# `--`
shell内置命令,表示选项的结束,也就是说后面都是参数,不在有选项。主要是为了避免后面的参数以`-`开头的时候被识别为选项。
```bash
cat "abc-Rdef" | grep -R
cat "abc-Rdef" | grep -- -R
```
删除以‘-’开头的文件
```bash
rm -f -f
rm -f -- -f
```
# `-`
`tar -cvf - * | tar -xvf - -C /tmp`复制当前目录并且时间不变。
# eval
eval解析两次,第一次替换变量,第二次执行。
```bash
a="ls -l"
eval $a
```
# 变量的间接引用 ${!var}
即以变量名作为新的变量,取新变量的值
```bash
function test() {
v=$1
echo ${!v}
}
x=10
test x
```
# getopt与getopts
getopt可以处理unix和GNU格式的参数。
```bash
#!/bin/bash
GETOPT_ARGS=`getopt -o abc:d::e -al aaa,bbb,ccc:,ddd::,eee -- "$@"`
eval set -- "$GETOPT_ARGS"
echo "after getopt: $0 $@"
while [ -n "$1" ]
do
case $1 in
-a|--aaa) echo "option $1"; shift;;
-b|--bbb) echo "option $1"; shift;;
-c|--ccc) echo "option $1 $2"; shift 2;;
-d|--ddd)
case $2 in
"") echo "option $1"; shift 2;;
*) echo "option $1 $2"; shift 2;;
esac
;;
-e|--eee) echo "option $1"; shift;;
--) shift; break;;
*) echo "unknown: $1"; exit 1;;
esac
done
```
getopts处理unix格式的参数。
```bash
#!/bin/bash
while getopts abc:d:e opt
do
case "$opt" in
a) echo "-a";;
b) echo "-b";;
c) echo "-c $OPTARG";;
d) echo "-d $OPTARG";;
e) echo "-e";;
*) echo "unkown"
exit 2;;
esac
done
```
上面是一段shell中命令行处理的实现。
```bash
#!/bin/bash
DBHOME="$GPHOME"
UPDATEFILE=""
HOSTFILE=""
ROOTDIR=`pwd`
BASEDIR=$(cd `dirname $0`; pwd)
PROGRAM=${0##*/}
Usage() {
echo "$PROGRAM is a local dongle update tool."
echo
echo "Usage:"
echo " $PROGRAM [OPTION] UPDATEFILE"
echo
echo "Options:"
echo " -d DBHOME Database installation path, default \"\$GPHOME\"."
echo " -f HOSTFILE This specifies the file that lists the hosts"
echo " onto which you want to install Greenplum Database."
}
# show help
if [ "x$1" = "x--help" ] || [ "x$1" = "x-?" ]; then
Usage
exit 0
fi
while getopts "d:f:" opt;
do
case $opt in
d)
DBHOME=$OPTARG
;;
f)
HOSTFILE=$OPTARG
;;
?)
echo "Invalid options: -$OPTARG"
exit 1;;
esac
done
# UPDATEFILE
eval UPDATEFILE="$""$OPTIND"
```
# exec与文件描述符
对于Linux而言,所有对设备和文件的操作都使用文件描述符来进行的。
通常,一个进程启动时,会打开3个文件描述符:标准输入、标准输出、标准错误。对应的描述符分别是0、1、2。
* exec分配文件描述符
```bash
exec 6<>hello.txt # 以读写方式绑定文件到描述符6
echo "hello" >&6 # 写入“hello”,这里将会从文件开头进行覆盖
echo "world" >&6 # 写入“world”,新的一行
exec 6>&- # 关闭写,实际上也不能读了
exec 6<&- # 关闭读,实际上也不能写了
```
* 输出重定向
```bash
exec 1>hello.txt # 将标准输出重定向到文件,从此之后该进程的输出都将被写入”hello.txt“
echo "hello"
echo "wolrd"
```
* 恢复重定向
```bash
exec 100>&1
exec 1>hello.txt
echo "hello"
echo "world"
exec 1>&100 100>&-
echo "reset"
```
* 输入重定向
```bash
exec 100<&0
exec <hello.txt
read $line1
echo $line1
read $line2
echo $line2
exec 0<&100 100>&-
read $line3
```
* 例子
```bash
#!/bin/bash
# 把标准输出和标准错误绑定到指定文件,并使用两个临时描述符变量保存标准输出和标准错误,用于恢复
openlog() {
file=$1
exec 6>&1 # 把6绑定到标准输出,即把标准输出1复制到6
exec 7>&2 # 把7绑定到标准错误
exec 1>$file # 把标准输出绑定到文件 exec 1>$file 是绑定追加
exec 2>$file # 把标准错误绑定到文件
}
# 恢复标准输出和标准错误,关闭临时描述符6和7
closelog() {
exec 1>&6 6>&-
exec 2>&7 7>&-
}
openlog logfile
echo "=================="
ls /proc/self/fd
echo "=================="
echo "hello"
echo "world"
closelog
echo "=================="
ls /proc/self/fd
echo "=================="
echo "111"
```
# 多进程
如下,每个进程的任务就是等待10秒,进程任务完成之后再启动一个新的进程,保证并发数是8。
通过命名管道控制进程数量。
```bash
#!/bin/bash
tmpfifo=$$.fifo
trap "exec 1000>&-;exec 1000<&-;exit 0" 2 3 15
mkfifo $tmpfifo
exec 1000<>$tmpfifo
rm -f $tmpfifo
for ((i=1;i<=8;i++))
do
echo >&1000
done
while true
do
let t++
read -u 1000
{
sleep 10
echo >&1000
} &
done
wait
echo "done!!!"
```
# 格式判断
```bash
#!/bin/bash
check_format() {
local type=$1
local var=$2
local ret=0
[ $# -ne 2 ] && return 1
case $type in
"STRING")
[ "x$var" = "x" ] && ret=2
;;
"NUMBER")
echo $var | grep -Ev '^[0-9]{1,}$' > /dev/null 2>&1 && ret=2
;;
*)
ret=2
esac
return $ret
}
[ `check_format NUMBER asdfsa` -ne 0 ] && exit 1
exit 0
```
# 字符串处理
## 字符串分割
shell如何用指定的分隔符来分割字符串为一个数组?这里介绍两种方法
方法一
```bash
#!/bin/bash
string="hello,shell,word"
array=(${string//,/ })
for var in ${array[@]}
do
echo $var
done
```
方法二
```bash
#!/bin/bash
string="hello,shell,word"
OLD_IFS="$IFS"
IFS=","
array=($string)
IFS="$OLD_IFS"
for var in ${array[@]}
do
echo $var
done
```
## 字符串截取
| 格式 | 说明 |
| :----------------------- | :----------------------------------------------------------- |
| ${string:start:length} | 从 string 字符串的左边第 start 个字符开始,向右截取 length 个字符。 |
| ${string:start} | 从 string 字符串的左边第 start 个字符开始截取,直到最后。 |
| ${string:0-start:length} | 从 string 字符串的右边第 start 个字符开始,向右截取 length 个字符。 |
| ${string:0-start} | 从 string 字符串的右边第 start 个字符开始截取,直到最后。 |
| ${string#*chars} | 从 string 字符串第一次出现 *chars 的位置开始,截取 *chars 右边的所有字符。 |
| ${string##*chars} | 从 string 字符串最后一次出现 *chars 的位置开始,截取 *chars 右边的所有字符。 |
| ${string%chars*} | 从 string 字符串第一次出现 *chars 的位置开始,截取 *chars 左边的所有字符。 |
| ${string%%chars*} | 从 string 字符串最后一次出现 *chars 的位置开始,截取 *chars 左边的所有字符。 |
### 从指定位置开始截取
```bash
${string:start:length}
${string:0-start:length}
```
string是要截取的字符串,start是起始位置,length是要截取的长度(省略表示直到字符串的末尾)。
注意:
1. 从左边开始计数,其实数字是0;从右边开始计数,其实数字是1。
2. 不管从哪边开始计数,截取方向都是从左到右。
例:
```bash
#!/bin/bash
url="abcdefghijklmn"
echo ${url:2}
echo ${url:5:3}
echo ${url:0-3}
echo ${url:0-10:5}
```
输出:
```bash
cdefghijklmn
fgh
lmn
efghi
```
### 从指定字符串开始截取
这种截取方式无法指定长度,只能从指定字符串截取到字符串末尾。可以截取指定字符串右边的所有字符,也可以截取左边的所有字符。
```bash
${string#*chars}
${string##*chars}
${string%chars*}
${string%%chars*}
```
其中,string是要截取的字符串,chars是指定的字符串,`*`是通配符的一种,表示任意长度的字符串。`*chars`连起来使用的意思是忽略左边的所有字符,知道遇见chars。
例:
```bash
#!/bin/bash
url="1234123412341234"
echo ${url#*23}
echo ${url##*23}
echo ${url%23*}
echo ${url%%23*}
```
# ssh
```bash
$ ssh -T -o StrictHostKeyChecking=no <<EOF
# 不允许定义和使用变量,可以读取外部变量,不能给外部变量赋值
# 可以定义函数,函数内部不能使用变量和参数,不能使用外部函数
# 此处执行子shell无效,等同与在ssh之外执行,如`ls`和$(ls)
EOF
```
<file_sep>/source/_posts/大数阶乘.md
---
title: 大数阶乘
date: 2017-10-24
categories: 算法
tags: 大数阶乘
---
对于比较小的数n,可以通过递归或循环将计算结果保存为整形。但是如果n很大的时候,比如1000,那么n!肯定超出整形数据所能表示的范围。因此必须采用其他方法解决。一般是采用数组模拟。实现代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STORE_STEP_SIZE 100
static int s_store_size = 0;
#define EXTENT_STORE(s) { \
s_store_size += STORE_STEP_SIZE; \
s = realloc(s, sizeof(int) * s_store_size); \
}
#define DESTROY_STORE(s) { free(s); }
/*
* digit:
* 9x + x/10 <= INT_MAX
* x = 10INT_MAX/91
*/
static void fact(int digit)
{
int i, j;
int temp;
int cvalue;
int size;
int *store;
if (digit < 1 || digit >= 10*((int)pow(2,31)/91))
{
printf("digit(%d) is too smaller or too big\n", digit);
return;
}
/* 1! */
if (digit == 1)
{
printf("1\n");
return;
}
EXTENT_STORE(store);
if (store == NULL)
{
printf("faile...\n");
DESTROY_STORE(store);
return;
}
store[0] = 1;
size = 1;
for (i=2; i<=digit; i++)
{
for (cvalue=0, j=1; j<=size; j++)
{
temp = store[j-1] * i + cvalue;
store[j-1] = temp % 10;
cvalue = temp / 10;
}
while (cvalue > 0)
{
if (size >= s_store_size)
{
EXTENT_STORE(store);
if (store == NULL)
{
printf("fail...\n");
DESTROY_STORE(store);
return;
}
}
store[++size - 1] = cvalue % 10;
cvalue /= 10;
}
}
for (i=size-1; i>=0; i--)
printf("%d", store[i]);
printf("\n");
/* store's size and current size */
//printf("s_store_size=%d, size=%d\n", s_store_size, size);
DESTROY_STORE(store);
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Usage: %s <digit>\n", argv[0]);
return -1;
}
fact(atoi(argv[1]));
return 0;
}
```
| 7ab53be7eb93432ed683720b07ba375048faf137 | [
"Markdown",
"Shell"
] | 37 | Shell | yfshi/hexo-blog | 58013066fb28858dc5e19bcfbc0954d50487b73a | 020f823cb6e37aeb6d8e4bb26802e5a2d3575c08 |
refs/heads/master | <repo_name>ChrisUrrea/writing-migrations-cb-000<file_sep>/db/migrate/01_create_students.rb
class CreateStudents < ActiveRecord::Migration
def change
create_table :students do |studs|
studs.string :name
end
end
end
| b2fb6047aa283e73d73afa0eec3cb5dd68393111 | [
"Ruby"
] | 1 | Ruby | ChrisUrrea/writing-migrations-cb-000 | 3e35092b5bf0e648fbe353aa9742e8ef107d0b02 | a8da83ef9b66ee183e7b19852a9cdafb6b7fac27 |
refs/heads/master | <file_sep>package com.team3418.frc2016.subsystems;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class Climber extends Subsystem {
static Climber mInstance = new Climber();
public static Climber getInstance() {
return mInstance;
}
private Victor mClimberVictor = new Victor(2);
@Override
public void updateSubsystemState() {
outputToSmartDashboard();
}
public void setSpeed(double speed){
mClimberVictor.set(speed);
}
public void stop(){
setSpeed(0);
}
//
@Override
public void outputToSmartDashboard() {
SmartDashboard.putNumber("Climber_Power_Percent", mClimberVictor.getSpeed());
}
}
<file_sep>package com.team3418.frc2016;
/**
* A list of constants used by the rest of the robot code.
*/
public class Constants {
public static double kConstantVariableExample = 10.0;
// do not change anything after this line, hardware ports should not change
// TALONS
// SOLENOIDS
// PCM #, Solenoid #
// Analog Inputs
// DIGITAL IO
// PWM
public static final int kLeftMotorPWMID = 0;
public static final int kRightMotorPWMID = 1;
public static final int kClimberMotorPWMID = 2;
/* single wheel shooter
// Flywheel constants
public static double kFlywheelOnTargetTolerance = 100.0;
public static double kFlywheelRpmSetpoint = 4200.0;
//PID gains for flywheel velocity
public static double kFlywheelKp = 0.12;
public static double kFlywheelKi = 0.0012;
public static double kFlywheelKd = 1.2;
public static double kFlywheelKf = 0.0;
public static int kFlywheelIZone = (int) (1023.0 / kFlywheelKp);
public static double kFlywheelRampRate = 0;
public static int kFlywheelAllowableError = 100;
*/
}
| 1c75b31228bbd81a06aefaa06e4708b7e07cfedf | [
"Java"
] | 2 | Java | RoboRiotTeam3418/FRC-2017-TankDriveTest | a5c1e6015e8c0c9b3c7578f2f670f42446f9f7b5 | a87da4513ca9746058fec0e691deedead9ceca60 |
refs/heads/main | <repo_name>Breno-oKra/Receita-Com-Oque-Tem<file_sep>/src/model/myReceitas.js
const Database = require("../db/config")
module.exports = {
async get(){
const db = await Database()
// vai pegar tudo da tabela
const receitas = await db.all(`SELECT * FROM myTable`)
await db.close();
// o arrow function desse geito é a mesma coisa que ter um return{infos}
// retornando objetos
return receitas.map( item => ({
id: item.id,
title: item.title,
capa: item.capa,
ingredients: item.ingredients.split(","),
modo: item.modo,
}))
},
async create(newReceita){
const db = await Database()
await db.run(`INSERT INTO myTable(
title,
capa,
ingredients,
modo
) VALUES (
"${newReceita.title}",
"${newReceita.capa}",
"${newReceita.ingredients}",
"${newReceita.modo}"
)`)
await db.close()
},
async update(data,id){
const db = await Database()
// vai pegar tudo da tabela
await db.run(`UPDATE myTable SET
title = "${data.title}",
capa = "${data.capa}",
ingredients = "${data.ingredients}",
modo = "${data.modo}"
WHERE id = ${id}
`)
await db.close();
},
async del(Dataid){
const db = await Database()
//DELETE FROM jobs WHERE id, deleta da tabela jobs onde o id for igual a id que passamos
await db.run(`DELETE FROM myTable WHERE id = ${Dataid}`)
await db.close()
},
}<file_sep>/src/controllers/profileControllers.js
const db = require("../model/profile")
module.exports = {
async get(req,res){
const data = await db.get()
res.render("profile",{data})
},
async update(req,res){
const data = req.body
await db.update(data,1)
res.redirect("/profile")
}
}<file_sep>/src/controllers/ControllersNatural.js
module.exports = {
dataLoja:[
{id:1,title:"pão de alho",capa:"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRSvwgk3FMlrg0sB1K17Sqy1GY9E_oon3AZFw&usqp=CAU",ingredients:["farinha_de_trigo","leite","fermento_em_pó","alho","sal"],modo:"2 chicaras de chá"},
{id:2,title:"bolo de cenoura com calda",capa:"https://imagem.band.com.br/novahome/055caa6d-7528-44bc-ac32-3add84bdc0b0.jpg",ingredients:["farinha_de_trigo","fermento_em_pó","ovo","açucar","cenoura","leite","oleo","leite_condensado","creme_de_leite","chocolate_em_pó","manteiga"],modo:"2 chicaras de chá"},
{id:3,title:"bolo de cenoura",capa:"https://www.bolodecenoura.com/wp-content/uploads/2020/01/Bolo-de-Cenoura-com-Farinha-de-Arroz.jpg",ingredients:["farinha_de_trigo","fermento_em_pó","ovo","açucar","cenoura","leite","oleo"]},
{id:4,title:"bololinho de chuva",capa:"https://s2.glbimg.com/th3CDxD2CpWV3-1HHYazdYR20BGvfc59JgqpgGvOphNIoz-HdGixxa_8qOZvMp3w/e.glbimg.com/og/ed/f/original/2013/08/23/cc24receberfaz_118-2.jpg",ingredients:["farinha_de_trigo","fermento_em_pó","ovo","açucar","leite","oleo"],modo:"2 chicaras de chá"},
{id:5,title:"ovo frito",capa:"https://www.cozinhatecnica.com/wp-content/uploads/2017/09/Fritar-um-ovo-1.jpg",ingredients:["sal","ovo","oleo"],modo:"1. so fritar e ser felizzz"},
],
lastReceita:{
title:"Nenhuma vista no Momento",
capa:"https://img2.gratispng.com/20180331/atw/kisspng-cupcake-drawing-line-art-watercolor-painting-clip-cupcake-line-drawing-5abf3fbc857105.1036362315224831325466.jpg"
},
disponivel(dataMain,DataMine,data){
let temp = []
dataMain.forEach((item) => {
let control = true
item.ingredients.forEach(items =>{
let i = data.indexOf(items)
if(i == -1){
control = false
}
})
if(control){
const achar = temp.find(items => items.id == item.id)
if(achar == undefined){
temp.push(item)
}
}
});
DataMine.forEach((item) => {
let control = true
item.ingredients.forEach(items =>{
let i = data.indexOf(items)
if(i == -1){
control = false
}
})
if(control){
const achar = temp.find(items => items.id == item.id)
if(achar == undefined){
temp.push(item)
}
}
});
return temp
},
}<file_sep>/src/controllers/receitasControllers.js
const myDB = require("../model/myReceitas")
const myIngred = require("../model/myIngredients")
const funcs = require("../controllers/ControllersNatural")
const DbProfile = require("../model/profile")
module.exports = {
async index(req,res){
let Datadisponivel = []
const mineReceitas = await myDB.get()
const myIngredients = await myIngred.get()
const profile = await DbProfile.get()
const disponiveis = funcs.disponivel(funcs.dataLoja,mineReceitas,myIngredients[0].ingredients);
Datadisponivel = disponiveis
let qtdIngredits = myIngredients[0].ingredients.length
let qtdMineReceitas = mineReceitas.length
let qtdDisponiveis = Datadisponivel.length
res.render("index",{receitasLoja:funcs.dataLoja,disponiveis:Datadisponivel,myIngrediets:myIngredients[0].ingredients,myReceitas:mineReceitas,qtdDisponiveis,qtdMineReceitas,qtdIngredits,lastReceita:funcs.lastReceita,profile})
},
createShow(req,res){
res.render("create")
},
async createEdit(req,res){
const infos = req.body.ingredientsOn.split(",");
const receitas = await myDB.get()
let rand = Math.random(50000)
const lastId = receitas[receitas.length -1].id || rand;
const datIngredients = []
for (let i = 1; i < infos.length; i++) {
datIngredients.push(infos[i])
}
const data = {
id:rand,
title: req.body.title,
capa: req.body.capa || "https://img2.gratispng.com/20180331/atw/kisspng-cupcake-drawing-line-art-watercolor-painting-clip-cupcake-line-drawing-5abf3fbc857105.1036362315224831325466.jpg",
modo: req.body.modo,
ingredients:datIngredients
}
funcs.lastReceita = data
await myDB.create(data)
res.redirect("/")
},
async delete(req,res){
const ids = req.params.id
await myDB.del(ids)
res.redirect("/")
},
async getInfos(req,res){
const receitas = await myDB.get()
let id = req.params.id
let items = receitas.find(item => item.id == id)
let ingredientsRefatored = ""
let refatored = items.ingredients
refatored.forEach((item) =>{
ingredientsRefatored = ingredientsRefatored + "," + item
})
let data = {
id: items.id ,
title: items.title,
capa: items.capa,
ingredients:ingredientsRefatored,
modo: items.modo
}
res.render("editCreate",{objMine:data})
},
async update(req,res){
const receitas = await myDB.get()
const infos = req.body.ingredientsOn.split(",");
const datIngredients = []
for (let i = 1; i < infos.length; i++) {
datIngredients.push(infos[i])
}
let finder = receitas.find(item => item.id == req.params.id)
const data = {
title: req.body.title,
capa: req.body.capa,
ingredients:datIngredients,
modo: req.body.modo,
}
funcs.lastReceita = data
await myDB.update(data,finder.id)
res.redirect("/")
},
async ViewReceita(req,res){
const receitas = await myDB.get()
let idMine = req.params.id.split("+")
let id = req.params.id
let data = {}
let obj = funcs.dataLoja.find(item => item.id == id)
let objMine = receitas.find(item => item.id == idMine[0])
if(idMine[1] == "myReceitas"){
data = objMine
funcs.lastReceita = objMine
}
else{
data = obj
funcs.lastReceita = obj
}
res.render("seeReceita",{obj:data})
},
}<file_sep>/src/model/profile.js
const Database = require("../db/config")
module.exports = {
async get(){
const db = await Database()
// vai pegar tudo da tabela
const profi = await db.get(`SELECT * FROM profile`)
await db.close();
// o arrow function desse geito é a mesma coisa que ter um return{infos}
// retornando objetos
return {
name: profi.name,
avatar: profi.avatar,
email: profi.email,
about: profi.about,
}
},
async update(data,id){
const db = await Database()
// vai pegar tudo da tabela
await db.run(`UPDATE profile SET
name = "${data.name}",
avatar = "${data.avatar}",
email = "${data.email}",
about = "${data.about}"
WHERE id = ${id}
`)
await db.close();
},
}<file_sep>/README.md
<h1 align="center">Receita Com oque tem
</h1>
## 🚀 Tecnologias
Esse projeto foi desenvolvido com as seguintes tecnologias:
- HTML
- CSS
- JavaScript
- NodeJS
- EJS
- Express
- SQLite
- Jquery
## 💻 Projeto
O Receitas pra quem tem é uma aplicação que te permite filtrar as receitas existentes em nossa aplicação e as receitas criadas por você a fim de lhe retornar receitas disponiveis com os ingredients presentes em sua casa, 🍎🍐🌭 🍔 🍟 🍕
## sobre
Esse projeto foi feito apartir do aprendizado da maratona discovery da rocketseat,e faz parte do meu projeto secundario da semana
## imagens do projeto
<img alt="JobsCalc" title="JobsCalc" src=".github/capa1.png" width="100%" />
<img alt="JobsCalc" title="JobsCalc" src=".github/capa2.png" width="100%" />
<img alt="JobsCalc" title="JobsCalc" src=".github/capa3.png" width="100%" />
<img alt="JobsCalc" title="JobsCalc" src=".github/capa4.png" width="100%" />
## imagens do projeto em display menores
<div align="center">
<img alt="JobsCalc" title="JobsCalc" src=".github/capa5.png" width="50%" />
<img alt="JobsCalc" title="JobsCalc" src=".github/capa6.png" width="50%" />
<img alt="JobsCalc" title="JobsCalc" src=".github/capa7.png" width="50%" />
</div>
<file_sep>/public/scripts/OnOff.js
const receitasDisponiveis = document.getElementById("receitasDisponiveis");
const myReceitas = document.getElementById("myReceitas")
const receitasLoja = document.getElementById("receitasLoja")
OnOff("receitasDisponiveis")
function OnOff(camp){
if(camp == 'receitasDisponiveis'){
$(receitasDisponiveis).show()
$("#btn-disponivel").css("background-color","rgb(243, 243, 243)").css("color","#000")
$(receitasLoja).hide()
$("#btn-loja").css("background-color","").css("color","#fff")
$(myReceitas).hide()
$("#btn-mine").css("background-color","").css("color","#fff")
}
if (camp == 'myReceitas'){
$(receitasDisponiveis).hide()
$("#btn-disponivel").css("background-color","").css("color","#fff")
$(receitasLoja).hide()
$("#btn-loja").css("background-color","").css("color","#fff")
$(myReceitas).show()
$("#btn-mine").css("background-color","rgb(243, 243, 243)").css("color","#000")
}
if (camp == 'myReceitasModal'){
$(receitasDisponiveis).hide()
$("#btn-disponivel").css("background-color","").css("color","#fff")
$(receitasLoja).hide()
$("#btn-loja").css("background-color","").css("color","#fff")
$(myReceitas).show()
$("#btn-mine").css("background-color","rgb(243, 243, 243)").css("color","#000")
$(".modal-user").animate({width: 'toggle'});
}
if(camp == 'receitasLoja'){
$(receitasDisponiveis).hide()
$("#btn-disponivel").css("background-color","").css("color","#fff")
$(receitasLoja).show()
$("#btn-loja").css("background-color","rgb(243, 243, 243)").css("color","#000")
$(myReceitas).hide()
$("#btn-mine").css("background-color","").css("color","#fff")
}
}
function containerUser(){
$(".modal-user").animate({width: 'toggle'});
}<file_sep>/public/scripts/modal.js
const modal = document.querySelector(".modal")
const btn = document.querySelector(".btn-add-ingredients")
function onModal(){
$(modal).animate({width: 'toggle'});
}
function onModalSection(){
$(modal).animate({width: 'toggle'});
$(".modal-user").animate({width: 'toggle'});
} | dc7045756a3382fd6f36f1f9f36b49c67e640661 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | Breno-oKra/Receita-Com-Oque-Tem | 77100082ae82c6e33b93f8b2a40dd1e656a6a242 | ce5d35374b62ef9fffcc88cbecc1f7e5292a27ae |
refs/heads/master | <file_sep>cmake_minimum_required(VERSION 3.4)
project(ListaJednokierunkowa)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.c)
add_executable(ListaJednokierunkowa ${SOURCE_FILES})<file_sep>#include <stdlib.h>
#include <stdio.h>
struct Lista{
int value;
struct Lista *next;
};
struct Lista *Lista_nowy(){
struct Lista *n = malloc(sizeof(struct Lista));
n->next = NULL;
}
struct Lista *Lista_dodaj(int value, struct Lista *last){
struct Lista *next = malloc(sizeof(struct Lista));
next->value = value;
next->next = NULL;
last->next = next;
return next;
}
int main()
{
FILE *f;
int a;
if ((f=fopen("we.txt", "r"))==NULL)
{
printf ("Nie moge otworzyc pliku we.txt do zapisu!\n");
return -1;
}
struct Lista *l1 = Lista_nowy();
struct Lista *w = Lista_nowy();
w = l1;
while(!(feof(f)))
{
fscanf(f,"%d",&a);
printf("wczytalem wlasnie %d\n", a);
w= Lista_dodaj(a,w);
}
fclose(f);
while(l1!=NULL)
{
printf("%d\n",l1->value);
l1 = l1->next;
}
return 0;
} | 5848563c2221050e32f74d872039cef687141fd4 | [
"C",
"CMake"
] | 2 | CMake | okraskaj/ListaJednokierunkowa | a961cfee9288a1901bc2a8bdb79a086e27182232 | b09ed39f413bf85300e831f47f75da0900076783 |
refs/heads/master | <repo_name>obadasemary/Customer-Transaction<file_sep>/Customer Transaction/Common/Offer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Customer_Transaction.Common
{
class Offer
{
public int ID { get; set; }
public int Company_ID { get; set; }
public decimal Price { get; set; }
public decimal Offer_Value { get; set; }
}
}
<file_sep>/Customer Transaction/Common/Branchs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Customer_Transaction.Common
{
class Branchs : Product_Basic_Class
{
public int Customer_ID { get; set; }
}
}
<file_sep>/Customer Transaction/Common/Product_Type.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Customer_Transaction.Common
{
class Product_Type : Product_Basic_Class
{
public decimal Price { get; set; }
public int Product_ID { get; set; }
}
}
<file_sep>/Customer Transaction/Common/Transaction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Customer_Transaction.Common
{
class Transaction
{
public int ID { get; set; }
public string Type { get; set; }
public int Customer_Supplir { get; set; }
public int User_ID { get; set; }
public DateTime Transaction_Date { get; set; }
}
}
<file_sep>/Customer Transaction/Common/Customer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Customer_Transaction.Common
{
class Customer : Product_Basic_Class
{
}
}
<file_sep>/Customer Transaction/Common/Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Customer_Transaction.Common
{
class Product : Product_Basic_Class
{
public int Company_ID { get; set; }
public byte Photo_Product { get; set; }
}
}
<file_sep>/Customer Transaction/Common/Transaction_Details.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Customer_Transaction.Common
{
class Transaction_Details
{
public int ID { get; set; }
public int Type_ID { get; set; }
public int Quantity { get; set; }
public int Price_ID { get; set; }
public int Transaction_ID { get; set; }
public decimal Total { get; set; }
}
}
| 155f182bd06b6b1c9f923ac7c59665a18f8e4f49 | [
"C#"
] | 7 | C# | obadasemary/Customer-Transaction | 21d89a3da89ee70449e6631b9ea086fbe115f6d7 | 542010cc185e328193d878c3d08017fe0fe4c086 |
refs/heads/master | <repo_name>sahilsaiyad/Compiler<file_sep>/icode.cc
Instruction_Descriptor::Instruction_Descriptor (Tgt_Op op, string nam, string mnn, string ics, Icode_Format icf, Assembly_Format af){
inst_op = op;
mnemonic = mnn;
ic_symbol = ics; /* symbol for printing in intermediate code */
name = nam;
ic_format = icf; /* format for printing in intemediate code */
assem_format = af;
}
Instruction_Descriptor::Instruction_Descriptor (){}
Tgt_Op Instruction_Descriptor::get_op(){
return inst_op;
}
string Instruction_Descriptor::get_name(){
return name;
}
string Instruction_Descriptor::get_mnemonic(){
return mnemonic;
}
string Instruction_Descriptor::get_ic_symbol(){
return ic_symbol;
}
Icode_Format Instruction_Descriptor::get_ic_format(){
return ic_format;
}
Assembly_Format Instruction_Descriptor::get_assembly_format(){
return assem_format;
}
void Instruction_Descriptor::print_instruction_descriptor(ostream & file_buffer){
}
Register_Descriptor* Ics_Opd::get_reg(){}
Mem_Addr_Opd::Mem_Addr_Opd(Symbol_Table_Entry & se){
symbol_entry = &se;
}
Mem_Addr_Opd & Mem_Addr_Opd::operator = (const Mem_Addr_Opd & rhs){
symbol_entry = rhs.symbol_entry;
return *this;
}
void Mem_Addr_Opd::print_ics_opd(ostream & file_buffer){
file_buffer<<symbol_entry->get_variable_name();
}
void Mem_Addr_Opd::print_asm_opd(ostream & file_buffer){
Table_Scope symbol_scope = symbol_entry->get_symbol_scope();
if (symbol_scope == local)
{
int offset = symbol_entry->get_start_offset();
file_buffer << offset << "($fp)";
}
else
file_buffer << symbol_entry->get_variable_name();
}
Register_Addr_Opd::Register_Addr_Opd(Register_Descriptor * rd){
register_description = rd;
}
Register_Descriptor * Register_Addr_Opd::get_reg(){
return register_description;
}
Register_Addr_Opd& Register_Addr_Opd::operator = (const Register_Addr_Opd& rhs){
register_description = rhs.register_description;
return *this;
}
void Register_Addr_Opd::print_ics_opd(ostream & file_buffer){
file_buffer << register_description->get_name();
}
void Register_Addr_Opd::print_asm_opd(ostream & file_buffer){
file_buffer << "$" << register_description->get_name();
}
template<>
Const_Opd<int>::Const_Opd (int n){
num = n;
}
template<>
Const_Opd<double>::Const_Opd (double n){
num = n;
}
template<>
Const_Opd<int> & Const_Opd<int>::operator = (const Const_Opd<int> &rhs)
{
num = rhs.num;
return *this;
}
template<>
Const_Opd<float> & Const_Opd<float>::operator = (const Const_Opd<float> &rhs)
{
num = rhs.num;
return *this;
}
template<>
void Const_Opd<int>::print_ics_opd(ostream & file_buffer){
file_buffer << num;
}
template<>
void Const_Opd<double>::print_ics_opd(ostream & file_buffer){
file_buffer << num;
}
template<>
void Const_Opd<int>::print_asm_opd(ostream & file_buffer){
file_buffer << num;
}
template<>
void Const_Opd<double>::print_asm_opd(ostream & file_buffer){
file_buffer << num;
}
Instruction_Descriptor & Icode_Stmt::get_op(){
return op_desc;
}
Ics_Opd * Icode_Stmt::get_opd1(){}
Ics_Opd * Icode_Stmt::get_opd2(){}
Ics_Opd * Icode_Stmt::get_result(){}
void Icode_Stmt::set_opd1(Ics_Opd * io){}
void Icode_Stmt::set_opd2(Ics_Opd * io){}
void Icode_Stmt::set_result(Ics_Opd * io){}
Print_IC_Stmt::Print_IC_Stmt(){
op_desc = *(machine_desc_object.spim_instruction_table[print]);
}
Print_IC_Stmt::~Print_IC_Stmt(){}
void Print_IC_Stmt::print_icode(ostream & file_buffer){
file_buffer<<"\t"<<op_desc.get_name()<<endl;
}
void Print_IC_Stmt::print_assembly(ostream & file_buffer){
file_buffer<<"\t"<<op_desc.get_mnemonic()<<endl;
}
Move_IC_Stmt::Move_IC_Stmt(Tgt_Op inst_op, Ics_Opd * o, Ics_Opd * r){
opd1 = o;
result = r;
op_desc = *(machine_desc_object.spim_instruction_table[inst_op]);
}
Instruction_Descriptor & Move_IC_Stmt::get_inst_op_of_ics(){
return op_desc;
}
Ics_Opd * Move_IC_Stmt::get_opd1(){
return opd1;
}
void Move_IC_Stmt::set_opd1(Ics_Opd * io){
opd1 = io;
}
Ics_Opd * Move_IC_Stmt::get_result(){
return result;
}
void Move_IC_Stmt::set_result(Ics_Opd * io){
result = io;
}
Move_IC_Stmt& Move_IC_Stmt::operator = (const Move_IC_Stmt & rhs)
{
op_desc = rhs.op_desc;
opd1 = rhs.opd1;
result = rhs.result;
return *this;
}
void Move_IC_Stmt::print_icode(ostream & file_buffer){
string opname = op_desc.get_name();
Icode_Format icf = op_desc.get_ic_format();
if (icf == i_r_op_o1)
{
file_buffer << "\t" << opname << ": \t";
result->print_ics_opd(file_buffer);
file_buffer << " <- ";
opd1->print_ics_opd(file_buffer);
file_buffer << "\n";
}
else
{
printf("CS316 error\n");
exit(0);
}
}
void Move_IC_Stmt::print_assembly(ostream & file_buffer){
string opmne = op_desc.get_mnemonic();
Assembly_Format asf = op_desc.get_assembly_format();
if (asf == a_op_r_o1)
{
file_buffer << "\t" << opmne << " ";
result->print_asm_opd(file_buffer);
file_buffer << ", ";
opd1->print_asm_opd(file_buffer);
file_buffer << "\n";
}
else if (asf == a_op_o1_r)
{
file_buffer << "\t" << opmne << " ";
opd1->print_asm_opd(file_buffer);
file_buffer << ", ";
result->print_asm_opd(file_buffer);
file_buffer << "\n";
}
else
{
printf("CS316 error\n");
exit(0);
}
}
Compute_IC_Stmt::Compute_IC_Stmt(Tgt_Op inst_op, Ics_Opd * o1, Ics_Opd * o2, Ics_Opd * r){
opd1 = o1;
opd2 = o2;
result = r;
op_desc = *(machine_desc_object.spim_instruction_table[inst_op]);
}
Instruction_Descriptor & Compute_IC_Stmt::get_inst_op_of_ics(){
return op_desc;
}
Ics_Opd * Compute_IC_Stmt::get_opd1(){
return opd1;
}
void Compute_IC_Stmt::set_opd1(Ics_Opd * io){
opd1 = io;
}
Ics_Opd * Compute_IC_Stmt::get_opd2(){
return opd2;
}
void Compute_IC_Stmt::set_opd2(Ics_Opd * io){
opd2 = io;
}
Ics_Opd * Compute_IC_Stmt::get_result(){
return result;
}
void Compute_IC_Stmt::set_result(Ics_Opd * io){
result = io;
}
void Compute_IC_Stmt::print_icode(ostream & file_buffer){
string opname = op_desc.get_name();
Icode_Format icf = op_desc.get_ic_format();
if (icf == i_r_o1_op_o2)
{
file_buffer << "\t" << opname << ": \t";
result->print_ics_opd(file_buffer);
file_buffer << " <- ";
opd1->print_ics_opd(file_buffer);
file_buffer << " , ";
opd2->print_ics_opd(file_buffer);
file_buffer << "\n";
}
else if (icf == i_r_op_o1)
{
file_buffer << "\t" << opname << ": \t";
result->print_ics_opd(file_buffer);
file_buffer << " <- ";
opd1->print_ics_opd(file_buffer);
file_buffer << "\n";
}
else
{
printf("CS316 error\n");
exit(0);
}
}
void Compute_IC_Stmt::print_assembly(ostream & file_buffer){
string opmne = op_desc.get_mnemonic();
Assembly_Format asf = op_desc.get_assembly_format();
if (asf == a_op_r_o1_o2)
{
file_buffer << "\t" << opmne << " ";
result->print_asm_opd(file_buffer);
file_buffer << ", ";
opd1->print_asm_opd(file_buffer);
file_buffer << ", ";
opd2->print_asm_opd(file_buffer);
file_buffer << "\n";
}
else if (asf == a_op_o1_o2_r)
{
file_buffer << "\t" << opmne << " ";
opd1->print_asm_opd(file_buffer);
file_buffer << ", ";
opd2->print_asm_opd(file_buffer);
file_buffer << ", ";
result->print_asm_opd(file_buffer);
file_buffer << "\n";
}
else if (asf == a_op_r_o1)
{
file_buffer << "\t" << opmne << " ";
result->print_asm_opd(file_buffer);
file_buffer << ", ";
opd1->print_asm_opd(file_buffer);
file_buffer << "\n";
}
else if (asf == a_op_o1_r)
{
file_buffer << "\t" << opmne << " ";
opd1->print_asm_opd(file_buffer);
file_buffer << ", ";
result->print_asm_opd(file_buffer);
file_buffer << "\n";
}
else
{
printf("CS316 error\n");
exit(0);
}
}
Control_Flow_IC_Stmt::Control_Flow_IC_Stmt(Tgt_Op inst_op, Ics_Opd * o1, string l){
opd1 = o1;
label = l;
op_desc = *(machine_desc_object.spim_instruction_table[inst_op]);
}
Instruction_Descriptor & Control_Flow_IC_Stmt::get_inst_op_of_ics(){
return op_desc;
}
Ics_Opd * Control_Flow_IC_Stmt::get_opd1(){
return opd1;
}
void Control_Flow_IC_Stmt::set_opd1(Ics_Opd * io){
opd1 = io;
}
string Control_Flow_IC_Stmt::get_label(){
return label;
}
void Control_Flow_IC_Stmt::set_label(string l){
label = l;
}
Control_Flow_IC_Stmt& Control_Flow_IC_Stmt::operator=(const Control_Flow_IC_Stmt& rhs)
{
opd1 = rhs.opd1;
label = rhs.label;
op_desc = rhs.op_desc;
return *this;
}
void Control_Flow_IC_Stmt::print_icode(ostream & file_buffer){
string op = op_desc.get_name();
Icode_Format icf = op_desc.get_ic_format();
if (icf == i_op_o1_o2_st)
{
file_buffer << "\t" << op << ": \t";
opd1->print_ics_opd(file_buffer);
file_buffer << " , zero";
file_buffer << " : goto " << label << "\n";
}
else if (icf == i_op_st)
file_buffer << "\tgoto " << label << "\n";
else
{
printf("CS316 error\n");
exit(0);
}
}
void Control_Flow_IC_Stmt::print_assembly(ostream & file_buffer){
string op = op_desc.get_mnemonic();
Assembly_Format af = op_desc.get_assembly_format();
if(af == a_op_o1_o2_st)
{
file_buffer << "\t" << op << " ";
opd1->print_asm_opd(file_buffer);
file_buffer << ", ";
file_buffer << "$zero, ";
file_buffer << label << "\n";
}
else if (af == a_op_st)
file_buffer << "\tj " << label << "\n";
}
Label_IC_Stmt::Label_IC_Stmt(Tgt_Op inst_op, string l){
label = l;
this->op_desc = *(machine_desc_object.spim_instruction_table[inst_op]);
}
Instruction_Descriptor & Label_IC_Stmt::get_inst_op_of_ics(){
return op_desc;
}
string Label_IC_Stmt::get_label(){
return label;
}
void Label_IC_Stmt::set_label(string l){
label = l;
}
void Label_IC_Stmt::print_icode(ostream & file_buffer){
string opname = op_desc.get_name();
Icode_Format icf = op_desc.get_ic_format();
if (icf == i_op_st)
file_buffer << "\n" << label << ": \t\n";
else
printf("CS316 error\n");
}
void Label_IC_Stmt::print_assembly(ostream & file_buffer){
string opmne = op_desc.get_mnemonic();
Assembly_Format asf = op_desc.get_assembly_format();
if (asf == a_op_st)
file_buffer << "\n" << label << ": \t\n";
else
printf("CS316 error\n");
}
Code_For_Ast::Code_For_Ast(){}
Code_For_Ast::Code_For_Ast(list<Icode_Stmt *> & ic_l, Register_Descriptor * reg){
ics_list = ic_l;
result_register = reg;
}
void Code_For_Ast::append_ics(Icode_Stmt & ics){
ics_list.push_back(&ics);
}
list<Icode_Stmt *> & Code_For_Ast::get_icode_list()
{
return ics_list;
}
Register_Descriptor * Code_For_Ast::get_reg()
{
return result_register;
}
void Code_For_Ast::set_reg(Register_Descriptor * reg){
result_register = reg;
}
Code_For_Ast& Code_For_Ast::operator=(const Code_For_Ast& rhs)
{
ics_list = rhs.ics_list;
result_register = rhs.result_register;
return *this;
}
<file_sep>/ast-eval.cc
void Ast::print_value(Local_Environment & eval_env, ostream & file_buffer){}
Eval_Result & Ast::get_value_of_evaluation(Local_Environment & eval_env){}
void Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result){}
Eval_Result & Assignment_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(this->get_data_type() == int_data_type)
{
Eval_Result *temp = new Eval_Result_Value_Int;
// *temp=rhs->evaluate(eval_env, file_buffer);
temp->set_variable_status(true);
temp->set_value(rhs->evaluate(eval_env, file_buffer).get_int_value());
lhs->set_value_of_evaluation(eval_env, *temp);
this->print(file_buffer);
lhs->print_value(eval_env, file_buffer);
file_buffer<<"\n\n";
return lhs->get_value_of_evaluation(eval_env);
}
else
{
Eval_Result *temp = new Eval_Result_Value_Double;
temp->set_variable_status(true);
temp->set_value(rhs->evaluate(eval_env, file_buffer).get_double_value());
lhs->set_value_of_evaluation(eval_env, *temp);
this->print(file_buffer);
lhs->print_value(eval_env, file_buffer);
file_buffer<<"\n\n";
return lhs->get_value_of_evaluation(eval_env);
}
}
void Name_Ast::print_value(Local_Environment & eval_env, ostream & file_buffer)
{
if(this->get_data_type() == int_data_type)
{
file_buffer<<"\n";
file_buffer<<AST_SPACE<<this->get_symbol_entry().get_variable_name()<<" : "<<this->get_value_of_evaluation(eval_env).get_int_value();
}
else
{
file_buffer<<"\n";
file_buffer<<AST_SPACE<<this->get_symbol_entry().get_variable_name()<<" : "<<this->get_value_of_evaluation(eval_env).get_double_value();
}
}
Eval_Result & Name_Ast::get_value_of_evaluation(Local_Environment & eval_env)
{
if(eval_env.is_variable_defined(this->get_symbol_entry().get_variable_name()))
return *eval_env.get_variable_value(this->get_symbol_entry().get_variable_name());
else if(interpreter_global_table.is_variable_defined(this->get_symbol_entry().get_variable_name()))
return *interpreter_global_table.get_variable_value(this->get_symbol_entry().get_variable_name());
else
{
printf("CS316: Error: Variable should be defined before it's use\n");
exit(0);
}
}
void Name_Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result)
{
if(eval_env.does_variable_exist(this->get_symbol_entry().get_variable_name()))
eval_env.put_variable_value(result, this->get_symbol_entry().get_variable_name());
else if(interpreter_global_table.does_variable_exist(this->get_symbol_entry().get_variable_name()))
interpreter_global_table.put_variable_value(result, this->get_symbol_entry().get_variable_name());
else
{
printf("CS316: Error: Variable does not exist\n");
exit(0);
}
}
Eval_Result & Name_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(eval_env.is_variable_defined(this->get_symbol_entry().get_variable_name()))
return *eval_env.get_variable_value(this->get_symbol_entry().get_variable_name());
else if(interpreter_global_table.does_variable_exist(this->get_symbol_entry().get_variable_name()))
{
if(interpreter_global_table.is_variable_defined(this->get_symbol_entry().get_variable_name()))
return *interpreter_global_table.get_variable_value(this->get_symbol_entry().get_variable_name());
}
else
{
printf("CS316: Error: Variable not defined");
exit(0);
}
}
template<>
Eval_Result & Number_Ast<int>::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
temp->set_value(constant);
return *temp;
}
template<>
Eval_Result & Number_Ast<double>::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
Eval_Result_Value_Double *temp = new Eval_Result_Value_Double;
temp->set_variable_status(true);
temp->set_value(constant);
return *temp;
}
Eval_Result & Plus_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(lhs->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_int_value() + rhs->evaluate(eval_env, file_buffer).get_int_value());
return *temp;
}
else
{
Eval_Result_Value_Double *temp = new Eval_Result_Value_Double;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_double_value() + rhs->evaluate(eval_env, file_buffer).get_double_value());
return *temp;
}
}
Eval_Result & Minus_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(lhs->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_int_value() - rhs->evaluate(eval_env, file_buffer).get_int_value());
return *temp;
}
else
{
Eval_Result_Value_Double *temp = new Eval_Result_Value_Double;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_double_value() - rhs->evaluate(eval_env, file_buffer).get_double_value());
return *temp;
}
}
Eval_Result & Divide_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(lhs->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_int_value() / rhs->evaluate(eval_env, file_buffer).get_int_value());
return *temp;
}
else
{
Eval_Result_Value_Double *temp = new Eval_Result_Value_Double;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_double_value() / rhs->evaluate(eval_env, file_buffer).get_double_value());
return *temp;
}
}
Eval_Result & Mult_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(lhs->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_int_value() * rhs->evaluate(eval_env, file_buffer).get_int_value());
return *temp;
}
else
{
Eval_Result_Value_Double *temp = new Eval_Result_Value_Double;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_double_value() * rhs->evaluate(eval_env, file_buffer).get_double_value());
return *temp;
}
}
Eval_Result & UMinus_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(lhs->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_int_value() * -1);
return *temp;
}
else
{
Eval_Result_Value_Double *temp = new Eval_Result_Value_Double;
temp->set_variable_status(true);
temp->set_value(lhs->evaluate(eval_env, file_buffer).get_double_value() * -1);
return *temp;
}
}
Eval_Result & Conditional_Expression_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(cond->evaluate(eval_env, file_buffer).get_int_value())
lhs->evaluate(eval_env, file_buffer);
else
rhs->evaluate(eval_env, file_buffer);
}
Eval_Result & ::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{}
Eval_Result & Relational_Expr_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(rel_op==0)
{
if(lhs_condition->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_int_value() <= rhs_condition->evaluate(eval_env, file_buffer).get_int_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
else
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_double_value() <= rhs_condition->evaluate(eval_env, file_buffer).get_double_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
}
if(rel_op==1)
{
if(lhs_condition->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_int_value() < rhs_condition->evaluate(eval_env, file_buffer).get_int_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
else
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_double_value() < rhs_condition->evaluate(eval_env, file_buffer).get_double_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
}
if(rel_op==2)
{
if(lhs_condition->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_int_value() > rhs_condition->evaluate(eval_env, file_buffer).get_int_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
else
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_double_value() > rhs_condition->evaluate(eval_env, file_buffer).get_double_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
}
if(rel_op==3)
{
if(lhs_condition->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_int_value() >= rhs_condition->evaluate(eval_env, file_buffer).get_int_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
else
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_double_value() >= rhs_condition->evaluate(eval_env, file_buffer).get_double_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
}
if(rel_op==4)
{
if(lhs_condition->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_int_value() == rhs_condition->evaluate(eval_env, file_buffer).get_int_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
else
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_double_value() == rhs_condition->evaluate(eval_env, file_buffer).get_double_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
}
if(rel_op==5)
{
if(lhs_condition->get_data_type() == int_data_type)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_int_value() != rhs_condition->evaluate(eval_env, file_buffer).get_int_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
else
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if (lhs_condition->evaluate(eval_env, file_buffer).get_double_value() != rhs_condition->evaluate(eval_env, file_buffer).get_double_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
}
}
Eval_Result & Logical_Expr_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(bool_op == 0)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if(rhs_op->evaluate(eval_env, file_buffer).get_int_value())
temp->set_value(0);
else
temp->set_value(1);
return *temp;
}
if(bool_op == 1)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if(lhs_op->evaluate(eval_env, file_buffer).get_int_value() || rhs_op->evaluate(eval_env, file_buffer).get_int_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
if(bool_op == 2)
{
Eval_Result_Value_Int *temp = new Eval_Result_Value_Int;
temp->set_variable_status(true);
if(lhs_op->evaluate(eval_env, file_buffer).get_int_value() && rhs_op->evaluate(eval_env, file_buffer).get_int_value())
temp->set_value(1);
else
temp->set_value(0);
return *temp;
}
}
Eval_Result & Selection_Statement_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(cond->evaluate(eval_env, file_buffer).get_int_value())
then_part->evaluate(eval_env, file_buffer);
else
else_part->evaluate(eval_env, file_buffer);
}
Eval_Result & Iteration_Statement_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
if(is_do_form)
{
do{body->evaluate(eval_env, file_buffer);}
while(cond->evaluate(eval_env, file_buffer).get_int_value());
}
else
while(cond->evaluate(eval_env, file_buffer).get_int_value())
body->evaluate(eval_env, file_buffer);
}
Eval_Result & Sequence_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
list <Ast *>::iterator it;
for(it = statement_list.begin(); it != statement_list.end(); it++)
(*it)->evaluate(eval_env, file_buffer);
}
Eval_Result & Return_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
return return_value->compile(eval_env, file_buffer);
}
Eval_Result & Call_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer)
{
list <Ast *>::iterator it;
for(it = actual_param_list.begin(); it != actual_param_list.end(); it++)
(*it)->evaluate(eval_env, file_buffer);
}<file_sep>/ast-compile.cc
Code_For_Ast & Ast::create_store_stmt(Register_Descriptor * store_register){}
Code_For_Ast & Assignment_Ast::compile() {
Code_For_Ast & rs = rhs->compile();
Register_Descriptor * lr = rs.get_reg();
list<Icode_Stmt *> & ist = *new list<Icode_Stmt *>;
ist = rs.get_icode_list();
lr->reset_use_for_expr_result();
Code_For_Ast st = lhs->create_store_stmt(lr);
ist.splice(ist.end(), st.get_icode_list());
Code_For_Ast *ans = new Code_For_Ast(ist, NULL);
return *ans;
}
Code_For_Ast & Assignment_Ast::compile_and_optimize_ast(Lra_Outcome & lra){}
Code_For_Ast & Name_Ast::compile() {
Mem_Addr_Opd * md = new Mem_Addr_Opd(*variable_symbol_entry);
Register_Descriptor * nr;
Register_Descriptor * temp;
Icode_Stmt * ct;
if(get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * rd = new Register_Addr_Opd(temp);
ct = new Move_IC_Stmt(load, md, rd);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * rd = new Register_Addr_Opd(temp);
ct = new Move_IC_Stmt(load_d, md, rd);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist.push_back(ct);
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
Code_For_Ast & Name_Ast::compile_and_optimize_ast(Lra_Outcome & lra){}
Code_For_Ast & Name_Ast::create_store_stmt(Register_Descriptor * store_register) {
Mem_Addr_Opd * md = new Mem_Addr_Opd(*variable_symbol_entry);
Register_Addr_Opd * rd = new Register_Addr_Opd(store_register);
Icode_Stmt* ct;
if(get_data_type() == int_data_type)
{
ct = new Move_IC_Stmt(store, rd, md);
}
else
{
ct = new Move_IC_Stmt(store_d, rd, md);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist.push_back(ct);
Code_For_Ast *ans;
ans = new Code_For_Ast(ist, store_register);
return *ans;
}
template<>
Code_For_Ast & Number_Ast<int>::compile(){
Const_Opd<int> *num = new Const_Opd<int>(constant);
Icode_Stmt *ct;
Register_Descriptor * temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd *rd = new Register_Addr_Opd(temp);
ct = new Move_IC_Stmt(imm_load, num, rd);
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist.push_back(ct);
Code_For_Ast *ans;
ans = new Code_For_Ast(ist, temp);
return *ans;
}
template<>
Code_For_Ast & Number_Ast<double>::compile(){
Const_Opd<double> *num = new Const_Opd<double>(constant);
Icode_Stmt *ct;
Register_Descriptor * temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd *rd = new Register_Addr_Opd(temp);
ct = new Move_IC_Stmt(imm_load_d, num, rd);
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist.push_back(ct);
Code_For_Ast *ans;
ans = new Code_For_Ast(ist, temp);
return *ans;
}
template<>
Code_For_Ast & Number_Ast<int>::compile_and_optimize_ast(Lra_Outcome & lra){}
template<>
Code_For_Ast & Number_Ast<double>::compile_and_optimize_ast(Lra_Outcome & lra){}
Code_For_Ast & Plus_Ast::compile(){
Code_For_Ast &l = lhs->compile();
Code_For_Ast &r = rhs->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(add, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(add_d, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
Code_For_Ast & Plus_Ast::compile_and_optimize_ast(Lra_Outcome & lra){}
Code_For_Ast & Minus_Ast::compile(){
Code_For_Ast &l = lhs->compile();
Code_For_Ast &r = rhs->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sub, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sub_d, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
Code_For_Ast & Minus_Ast::compile_and_optimize_ast(Lra_Outcome & lra){}
Code_For_Ast & Divide_Ast::compile(){
Code_For_Ast &l = lhs->compile();
Code_For_Ast &r = rhs->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(divd, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(div_d, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
Code_For_Ast & Divide_Ast::compile_and_optimize_ast(Lra_Outcome & lra){}
Code_For_Ast & Mult_Ast::compile(){
Code_For_Ast &l = lhs->compile();
Code_For_Ast &r = rhs->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(mult, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(mult_d, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
Code_For_Ast & Mult_Ast::compile_and_optimize_ast(Lra_Outcome & lra){}
Code_For_Ast & UMinus_Ast::compile(){
Code_For_Ast &l = lhs->compile();
Register_Descriptor *lg = l.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Icode_Stmt* ct;
Register_Descriptor * temp;
if(get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(uminus, ld, NULL, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(uminus_d, ld, NULL, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.push_back(ct);
lg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
Code_For_Ast & UMinus_Ast::compile_and_optimize_ast(Lra_Outcome & lra){}
Code_For_Ast & Conditional_Expression_Ast::compile(){
Code_For_Ast &con = cond->compile();
Code_For_Ast &l = lhs->compile();
Code_For_Ast &r = rhs->compile();
Register_Descriptor *conr = con.get_reg();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
string s0 = get_new_label();
string s1 = get_new_label();
Register_Addr_Opd *temp1 = new Register_Addr_Opd(conr);
Register_Addr_Opd *temp2 = new Register_Addr_Opd(machine_desc_object.spim_register_table[zero]);
Control_Flow_IC_Stmt *ct = new Control_Flow_IC_Stmt(beq, temp1, s0);
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor *res;
if(get_data_type() == int_data_type)
{
res = machine_desc_object.get_new_register<int_reg>();
}
else
{
res = machine_desc_object.get_new_register<float_reg>();
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = con.get_icode_list();
ist.push_back(ct);
ist.splice(ist.end(), l.get_icode_list());
Compute_IC_Stmt *sl = new Compute_IC_Stmt(or_t, ld, temp2, new Register_Addr_Opd(res));
Compute_IC_Stmt *sr = new Compute_IC_Stmt(or_t, rd, temp2, new Register_Addr_Opd(res));
ist.push_back(sl);
Control_Flow_IC_Stmt *nct = new Control_Flow_IC_Stmt(j, NULL, s1);
ist.push_back(nct);
Label_IC_Stmt *s0t = new Label_IC_Stmt(label, s0);
ist.push_back(s0t);
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(sr);
Label_IC_Stmt *s1t = new Label_IC_Stmt(label, s1);
ist.push_back(s1t);
conr->reset_use_for_expr_result();
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, res);
return *ans;
}
Code_For_Ast & Return_Ast::compile(){}
Code_For_Ast & Return_Ast::compile_and_optimize_ast(Lra_Outcome & lra){}
Code_For_Ast & Relational_Expr_Ast::compile(){
if(rel_op == 0)
{
Code_For_Ast &l = lhs_condition->compile();
Code_For_Ast &r = rhs_condition->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sle, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sle, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
else if(rel_op == 1)
{
Code_For_Ast &l = lhs_condition->compile();
Code_For_Ast &r = rhs_condition->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(slt, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(slt, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
else if(rel_op == 2)
{
Code_For_Ast &l = lhs_condition->compile();
Code_For_Ast &r = rhs_condition->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sgt, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sgt, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
else if(rel_op == 3)
{
Code_For_Ast &l = lhs_condition->compile();
Code_For_Ast &r = rhs_condition->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sge, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sge, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
else if(rel_op == 4)
{
Code_For_Ast &l = lhs_condition->compile();
Code_For_Ast &r = rhs_condition->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(seq, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(seq, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
else if(rel_op == 5)
{
Code_For_Ast &l = lhs_condition->compile();
Code_For_Ast &r = rhs_condition->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sne, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(sne, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
}
Code_For_Ast & Logical_Expr_Ast::compile(){
if(bool_op == 0)
{
Ast *lhs_op = new Number_Ast<int>(1, int_data_type, 1);
Code_For_Ast &l = lhs_op->compile();
Code_For_Ast &r = rhs_op->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(not_t, rd, ld, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(not_t, rd, ld, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
else if(bool_op == 1)
{
Code_For_Ast &l = lhs_op->compile();
Code_For_Ast &r = rhs_op->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(or_t, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(or_t, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
else if(bool_op == 2)
{
Code_For_Ast &l = lhs_op->compile();
Code_For_Ast &r = rhs_op->compile();
Register_Descriptor *lg = l.get_reg();
Register_Descriptor *rg = r.get_reg();
Register_Addr_Opd * ld = new Register_Addr_Opd(lg);
Register_Addr_Opd * rd = new Register_Addr_Opd(rg);
Register_Descriptor * temp;
Icode_Stmt* ct;
if (get_data_type() == int_data_type)
{
temp = machine_desc_object.get_new_register<int_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(and_t, ld, rd, res);
}
else
{
temp = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * res = new Register_Addr_Opd(temp);
ct = new Compute_IC_Stmt(and_t, ld, rd, res);
}
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = l.get_icode_list();
ist.splice(ist.end(), r.get_icode_list());
ist.push_back(ct);
lg->reset_use_for_expr_result();
rg->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, temp);
return *ans;
}
}
Code_For_Ast & Selection_Statement_Ast::compile(){
Code_For_Ast &con = cond->compile();
Code_For_Ast &t = then_part->compile();
if(else_part != NULL)
{
Code_For_Ast &e = else_part->compile();
Register_Descriptor *conr = con.get_reg();
string s0 = get_new_label();
string s1 = get_new_label();
Register_Addr_Opd *temp1 = new Register_Addr_Opd(conr);
Control_Flow_IC_Stmt *ct = new Control_Flow_IC_Stmt(beq, temp1, s0);
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = con.get_icode_list();
ist.push_back(ct);
ist.splice(ist.end(), t.get_icode_list());
Control_Flow_IC_Stmt *nct = new Control_Flow_IC_Stmt(j, NULL, s1);
ist.push_back(nct);
Label_IC_Stmt *s0t = new Label_IC_Stmt(label, s0);
ist.push_back(s0t);
ist.splice(ist.end(), e.get_icode_list());
Label_IC_Stmt *s1t = new Label_IC_Stmt(label, s1);
ist.push_back(s1t);
conr->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, NULL);
return *ans;
}
else
{
Register_Descriptor *conr = con.get_reg();
string s0 = get_new_label();
Register_Addr_Opd *temp1 = new Register_Addr_Opd(conr);
Control_Flow_IC_Stmt *ct = new Control_Flow_IC_Stmt(beq, temp1, s0);
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
ist = con.get_icode_list();
ist.push_back(ct);
ist.splice(ist.end(), t.get_icode_list());
Label_IC_Stmt *s0t = new Label_IC_Stmt(label, s0);
ist.push_back(s0t);
conr->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, NULL);
return *ans;
}
// string s1 = get_new_label();
// Control_Flow_IC_Stmt *nct = new Control_Flow_IC_Stmt(j, NULL, s1);
// ist.push_back(nct);
// ist.splice(ist.end(), e.get_icode_list());
// Label_IC_Stmt *s1t = new Label_IC_Stmt(label, s1);
// ist.push_back(s1t);
}
Code_For_Ast & Iteration_Statement_Ast::compile(){
Code_For_Ast &con = cond->compile();
Code_For_Ast &b = body->compile();
string s0 = get_new_label();
string s1 = get_new_label();
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
if(!is_do_form)
{
Control_Flow_IC_Stmt *ct = new Control_Flow_IC_Stmt(j, NULL, s1);
ist.push_back(ct);
}
Label_IC_Stmt *s0t = new Label_IC_Stmt(label, s0);
ist.push_back(s0t);
ist.splice(ist.end(), b.get_icode_list());
Label_IC_Stmt *s1t = new Label_IC_Stmt(label, s1);
ist.push_back(s1t);
ist.splice(ist.end(), con.get_icode_list());
Register_Descriptor *conr = con.get_reg();
Register_Addr_Opd *temp = new Register_Addr_Opd(conr);
Control_Flow_IC_Stmt *nct = new Control_Flow_IC_Stmt(bne, temp, s0);
ist.push_back(nct);
conr->reset_use_for_expr_result();
Code_For_Ast *ans = new Code_For_Ast(ist, NULL);
return *ans;
}
Code_For_Ast & Sequence_Ast::compile(){
sa_icode_list = list<Icode_Stmt*>();
for(list<Ast *>::iterator it = statement_list.begin();it != statement_list.end();it++)
{
Code_For_Ast &temp = (*it)->compile();
sa_icode_list.splice(sa_icode_list.end(), temp.get_icode_list());
}
Code_For_Ast *ans = new Code_For_Ast(sa_icode_list, NULL);
return *ans;
}
Code_For_Ast & Print_Ast::compile(){
Code_For_Ast *ans;
list<Icode_Stmt*> &ist = *new list<Icode_Stmt *>;
Register_Descriptor *temp = machine_desc_object.get_new_register<int_reg>();
Print_IC_Stmt *pst = new Print_IC_Stmt();
if(var->get_data_type() == int_data_type)
{
Register_Addr_Opd* temp2 = new Register_Addr_Opd(temp);
Move_IC_Stmt *mt0 = new Move_IC_Stmt(imm_load, new Const_Opd<int>(1), temp2);
Mem_Addr_Opd *temp3 = new Mem_Addr_Opd(var->get_symbol_entry());
Register_Addr_Opd *temp4 = new Register_Addr_Opd(machine_desc_object.spim_register_table[a0]);
Move_IC_Stmt *mt1 = new Move_IC_Stmt(load, temp3, temp4);
ist.push_back(mt0);
ist.push_back(mt1);
ist.push_back(pst);
temp->reset_use_for_expr_result();
ans = new Code_For_Ast(ist, NULL);
}
else
{
Register_Addr_Opd* temp2 = new Register_Addr_Opd(temp);
Move_IC_Stmt *mt0 = new Move_IC_Stmt(imm_load, new Const_Opd<int>(3), temp2);
Mem_Addr_Opd *temp3 = new Mem_Addr_Opd(var->get_symbol_entry());
Register_Addr_Opd *temp4 = new Register_Addr_Opd(machine_desc_object.spim_register_table[f12]);
Move_IC_Stmt *mt1 = new Move_IC_Stmt(load_d, temp3, temp4);
ist.push_back(mt0);
ist.push_back(mt1);
ist.push_back(pst);
temp->reset_use_for_expr_result();
ans = new Code_For_Ast(ist, NULL);
}
return *ans;
}
Code_For_Ast & Return_Ast::compile()
{
list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>;
string label = "epilogue_" + get_func_name();
if(get_data_type() == void_data_type) {
Control_Flow_IC_Stmt * control_stmt = new Control_Flow_IC_Stmt(j, NULL, NULL, label);
ic_list.push_back(control_stmt);
Code_For_Ast * ret_stmt = new Code_For_Ast(ic_list, NULL);
return *ret_stmt;
}
Code_For_Ast & expr_ast = ret_val->compile();
Register_Descriptor * expr_reg = expr_ast.get_reg();
Register_Addr_Opd * expr_opd = new Register_Addr_Opd(expr_reg);
expr_reg->reset_use_for_expr_result();
Icode_Stmt * curr_stmt;
if(get_data_type() == int_data_type) {
Register_Addr_Opd * v1_opd = new Register_Addr_Opd(machine_desc_object.spim_register_table[v1]);
curr_stmt = new Move_IC_Stmt(mov, expr_opd, v1_opd);
} else if(get_data_type() == double_data_type) {
Register_Addr_Opd * f0_opd = new Register_Addr_Opd(machine_desc_object.spim_register_table[f0]);
curr_stmt = new Move_IC_Stmt(move_d, expr_opd, f0_opd);
}
if (expr_ast.get_icode_list().empty() == false)
ic_list = expr_ast.get_icode_list();
ic_list.push_back(curr_stmt);
Control_Flow_IC_Stmt * control_stmt = new Control_Flow_IC_Stmt(j, NULL, NULL, label);
ic_list.push_back(control_stmt);
Code_For_Ast * ret_stmt = new Code_For_Ast(ic_list, NULL);
return *ret_stmt;
}
Code_For_Ast & Call_Ast::compile()
{
list<Icode_Stmt *> & ic_list = *new list<Icode_Stmt *>;
Register_Addr_Opd * sp_opd = new Register_Addr_Opd(machine_desc_object.spim_register_table[sp]);
int offset = 0;
for(auto it = arguments.end(); it != arguments.begin(); ) {
--it;
Code_For_Ast & expr_ast = (*it)->compile();
if (expr_ast.get_icode_list().empty() == false)
ic_list.splice(ic_list.end(), expr_ast.get_icode_list());
Register_Descriptor * expr_reg = expr_ast.get_reg();
CHECK_INVARIANT(expr_reg, "expr register cannot be null in return statement");
Register_Addr_Opd * expr_opd = new Register_Addr_Opd(expr_reg);
if((*it)->get_data_type() == int_data_type) {
offset -= 4;
Icode_Stmt * curr_stmt = new Parameter_Store_Stmt(store, expr_opd, sp_opd, offset);
ic_list.push_back(curr_stmt);
} else {
offset -= 8;
Icode_Stmt * curr_stmt = new Parameter_Store_Stmt(store_d, expr_opd, sp_opd, offset);
ic_list.push_back(curr_stmt);
}
expr_reg->reset_use_for_expr_result();
}
Const_Opd<int> * offset_opd = new Const_Opd<int>(-1*offset);
if(offset != 0) {
Icode_Stmt* compute_stmt = new Compute_IC_Stmt(sub, sp_opd, sp_opd, offset_opd);
ic_list.push_back(compute_stmt);
}
Control_Flow_IC_Stmt * control_stmt = new Control_Flow_IC_Stmt(jal, NULL, NULL, proc->get_proc_name());
ic_list.push_back(control_stmt);
if(offset != 0) {
Icode_Stmt* compute_stmt = new Compute_IC_Stmt(add, sp_opd, sp_opd, offset_opd);
ic_list.push_back(compute_stmt);
}
Register_Descriptor* reg;
if(get_data_type() == void_data_type) {
} else if(get_data_type() == int_data_type) {
reg = machine_desc_object.get_new_register<gp_data>();
Register_Addr_Opd * v1_opd = new Register_Addr_Opd(machine_desc_object.spim_register_table[v1]);
Register_Addr_Opd * reg_opd = new Register_Addr_Opd(reg);
Icode_Stmt * curr_stmt = new Move_IC_Stmt(mov, v1_opd, reg_opd);
ic_list.push_back(curr_stmt);
} else {
reg = machine_desc_object.get_new_register<float_reg>();
Register_Addr_Opd * f0_opd = new Register_Addr_Opd(machine_desc_object.spim_register_table[f0]);
Register_Addr_Opd * reg_opd = new Register_Addr_Opd(reg);
Icode_Stmt * curr_stmt = new Move_IC_Stmt(move_d, f0_opd, reg_opd);
ic_list.push_back(curr_stmt);
}
Code_For_Ast * fn_stmt = new Code_For_Ast(ic_list, reg);
machine_desc_object.clear_local_register_mappings();
return *fn_stmt;
}<file_sep>/ast.cc
#include<iostream>
#include<stdlib.h>
// #include "ast.hh"
using namespace std;
int Ast::labelCounter;
Ast::Ast()
{}
Ast::~Ast()
{}
void Ast::print(ostream & file_buffer)
{
file_buffer << node_data_type;
}
Data_Type Ast::get_data_type()
{
return node_data_type;
}
void Ast::set_data_type(Data_Type dt)
{
node_data_type = dt;
}
bool Ast::is_value_zero()
{}
Symbol_Table_Entry & Ast::get_symbol_entry()
{}
bool Ast::check_ast()
{}
Assignment_Ast::Assignment_Ast(Ast * temp_lhs, Ast * temp_rhs, int line)
{
lhs = temp_lhs;
rhs = temp_rhs;
lineno = line;
}
Assignment_Ast::~Assignment_Ast()
{}
bool Assignment_Ast::check_ast()
{
if(lhs->get_data_type() == rhs->get_data_type())
return 1;
else
{
printf("cs316: Error\n");
exit(0);
}
}
void Assignment_Ast::print(ostream & file_buffer)
{
file_buffer<<"\n"<<AST_SPACE<<"Asgn:"<<"\n"<<AST_NODE_SPACE<<"LHS (";
lhs->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_NODE_SPACE<<"RHS (";
rhs->print(file_buffer);
file_buffer<<")";
}
Name_Ast::Name_Ast(string & name, Symbol_Table_Entry & var_entry, int line)
{
variable_symbol_entry = &var_entry;
lineno = line;
}
Name_Ast::~Name_Ast()
{}
Data_Type Name_Ast::get_data_type()
{
return variable_symbol_entry->get_data_type();
}
void Name_Ast::print(ostream & file_buffer)
{
file_buffer<<"Name"<<" : "<<variable_symbol_entry->get_variable_name();
}
void Name_Ast::set_data_type(Data_Type dt)
{
node_data_type = dt;
}
Symbol_Table_Entry & Name_Ast::get_symbol_entry()
{
return *variable_symbol_entry;
}
template<>
Number_Ast<int>::Number_Ast(int number, Data_Type constant_data_type, int line)
{
constant = number;
node_data_type = constant_data_type;
lineno = line;
}
template<>
Number_Ast<int>::~Number_Ast()
{}
template<>
void Number_Ast<int>::print(ostream & file_buffer)
{
file_buffer<<"Num : "<<constant;
}
template<>
void Number_Ast<double>::print(ostream & file_buffer)
{
file_buffer<<"Num : "<<constant;
}
template<>
bool Number_Ast<int>::is_value_zero()
{}
template<>
bool Number_Ast<double>::is_value_zero()
{}
template<>
Number_Ast<double>::Number_Ast(double number, Data_Type constant_data_type, int line)
{
constant = number;
node_data_type = constant_data_type;
lineno = line;
}
template<>
Number_Ast<double>::~Number_Ast()
{}
template<>
Data_Type Number_Ast<int>::get_data_type()
{
return node_data_type;
}
template<>
Data_Type Number_Ast<double>::get_data_type()
{
return node_data_type;
}
template<>
void Number_Ast<int>::set_data_type(Data_Type dt)
{
node_data_type = dt;
}
template<>
void Number_Ast<double>::set_data_type(Data_Type dt)
{
node_data_type = dt;
}
Data_Type Arithmetic_Expr_Ast::get_data_type()
{
return node_data_type;
}
void Arithmetic_Expr_Ast::set_data_type(Data_Type dt)
{
node_data_type = dt;
}
// void Arithmetic_Expr_Ast::print(ostream &file_buffer)
// {
// file_buffer<<"\n"<<AST_SUB_NODE_SPACE<<"Arith: "
// }
bool Arithmetic_Expr_Ast::check_ast()
{
if(rhs == NULL || (lhs->get_data_type() == rhs->get_data_type()))
return 1;
else
return 0;
}
Plus_Ast::Plus_Ast(Ast * l, Ast * r, int line)
{
lhs = l;
rhs = r;
lineno = line;
}
void Plus_Ast::print(ostream & file_buffer)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Arith: PLUS"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs->print(file_buffer);
file_buffer<<")";
}
Minus_Ast::Minus_Ast(Ast * l, Ast * r, int line)
{
lhs = l;
rhs = r;
lineno = line;
}
void Minus_Ast::print(ostream & file_buffer)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Arith: MINUS"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs->print(file_buffer);
file_buffer<<")";
}
Divide_Ast::Divide_Ast(Ast * l, Ast * r, int line)
{
lhs = l;
rhs = r;
lineno = line;
}
void Divide_Ast::print(ostream & file_buffer)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Arith: DIV"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs->print(file_buffer);
file_buffer<<")";
}
Mult_Ast::Mult_Ast(Ast * l, Ast * r, int line)
{
lhs = l;
rhs = r;
lineno = line;
}
void Mult_Ast::print(ostream & file_buffer)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Arith: MULT"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs->print(file_buffer);
file_buffer<<")";
}
UMinus_Ast::UMinus_Ast(Ast * l, Ast * r, int line)
{
lhs = l;
rhs = r;
lineno = line;
}
void UMinus_Ast::print(ostream & file_buffer)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Arith: UMINUS"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs->print(file_buffer);
file_buffer<<")";
}
Return_Ast::Return_Ast(int line)
{
lineno = line;
}
void Return_Ast::print(ostream & file_buffer)
{}
Conditional_Expression_Ast::Conditional_Expression_Ast(Ast* c, Ast* l, Ast* r, int line)
{
cond = c;
lhs = l;
rhs = r;
lineno = line;
}
void Conditional_Expression_Ast::print(ostream & file_buffer)
{
file_buffer<<"\n"<<AST_SPACE<<"Cond:"<<"\n"<<AST_NODE_SPACE<<"IF_ELSE";
cond->print(file_buffer);
file_buffer<<"\n"<<AST_NODE_SPACE<<"LHS (";
lhs->print(file_buffer);
file_buffer<<")";
file_buffer<<"\n"<<AST_NODE_SPACE<<"RHS (";
rhs->print(file_buffer);
file_buffer<<")";
}
Relational_Expr_Ast::Relational_Expr_Ast(Ast * lhs, Relational_Op rop, Ast * rhs, int line)
{
lhs_condition = lhs;
rhs_condition = rhs;
rel_op = rop;
lineno = line;
}
Data_Type Relational_Expr_Ast::get_data_type()
{
return node_data_type;
}
void Relational_Expr_Ast::set_data_type(Data_Type dt)
{
node_data_type = dt;
}
bool Relational_Expr_Ast::check_ast()
{
if (lhs_condition->get_data_type() == rhs_condition->get_data_type())
{
return 1;
}
else
return 0;
}
void Relational_Expr_Ast::print(ostream & file_buffer)
{
if(rel_op==0)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Condition: LE"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs_condition->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs_condition->print(file_buffer);
file_buffer<<")";
}
if(rel_op==1)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Condition: LT"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs_condition->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs_condition->print(file_buffer);
file_buffer<<")";
}
if(rel_op==2)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Condition: GT"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs_condition->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs_condition->print(file_buffer);
file_buffer<<")";
}
if(rel_op==3)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Condition: GE"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs_condition->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs_condition->print(file_buffer);
file_buffer<<")";
}
if(rel_op==4)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Condition: EQ"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs_condition->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs_condition->print(file_buffer);
file_buffer<<")";
}
if(rel_op==5)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Condition: NE"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs_condition->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs_condition->print(file_buffer);
file_buffer<<")";
}
}
Logical_Expr_Ast::Logical_Expr_Ast(Ast * lhs, Logical_Op bop, Ast * rhs, int line)
{
lhs_op = lhs;
rhs_op = rhs;
bool_op = bop;
lineno = line;
}
Data_Type Logical_Expr_Ast::get_data_type()
{
return node_data_type;
}
void Logical_Expr_Ast::set_data_type(Data_Type dt)
{
node_data_type = dt;
}
bool Logical_Expr_Ast::check_ast()
{
if (lhs_op->get_data_type() == rhs_op->get_data_type())
{
return 1;
}
else
return 0;
}
void Logical_Expr_Ast::print(ostream & file_buffer)
{
if(bool_op==0)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Condition: NOT"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs_op->print(file_buffer);
file_buffer<<")";
}
if(bool_op==1)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Condition: OR"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs_op->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs_op->print(file_buffer);
file_buffer<<")";
}
if(bool_op==2)
{
file_buffer<<"\n"<<AST_NODE_SPACE<<"Condition: AND"<<"\n"<<AST_SUB_NODE_SPACE<<"LHS (";
lhs_op->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SUB_NODE_SPACE<<"RHS (";
rhs_op->print(file_buffer);
file_buffer<<")";
}
}
Selection_Statement_Ast::Selection_Statement_Ast(Ast * c,Ast* t, Ast* e, int line)
{
cond = c;
then_part = t;
else_part = e;
lineno = line;
}
Data_Type Selection_Statement_Ast::get_data_type()
{
return node_data_type;
}
void Selection_Statement_Ast::set_data_type(Data_Type dt)
{
node_data_type = dt;
}
bool Selection_Statement_Ast::check_ast()
{}
void Selection_Statement_Ast::print(ostream & file_buffer)
{
file_buffer<<"\n"<<AST_SPACE<<"IF : "<<"\n"<<AST_SPACE<<"CONDITION (";
cond->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SPACE<<"THEN (";
then_part->print(file_buffer);
file_buffer<<")";
if(else_part!=NULL)
{
file_buffer<<"\n"<<AST_SPACE<<"ELSE (";
else_part->print(file_buffer);
file_buffer<<")";
}
}
Iteration_Statement_Ast::Iteration_Statement_Ast(Ast * c, Ast* b, int line, bool do_form)
{
cond = c;
body = b;
is_do_form = do_form;
lineno = line;
}
Data_Type Iteration_Statement_Ast::get_data_type()
{
return node_data_type;
}
void Iteration_Statement_Ast::set_data_type(Data_Type dt)
{
node_data_type = dt;
}
void Iteration_Statement_Ast::print(ostream & file_buffer)
{
if(is_do_form==0)
{
file_buffer<<"\n"<<AST_SPACE<<"WHILE : "<<"\n"<<AST_SPACE<<"CONDITION (";
cond->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SPACE<<"BODY (";
body->print(file_buffer);
file_buffer<<")";
}
else
{
file_buffer<<"\n"<<AST_SPACE<<"DO (";
body->print(file_buffer);
file_buffer<<")"<<"\n"<<AST_SPACE<<"WHILE CONDITION (";
cond->print(file_buffer);
file_buffer<<")";
}
}
bool Iteration_Statement_Ast::check_ast()
{}
Sequence_Ast::Sequence_Ast(int line)
{
lineno = line;
}
void Sequence_Ast::ast_push_back(Ast *ast)
{
statement_list.push_back(ast);
}
void Sequence_Ast::print(ostream & file_buffer)
{
list<Ast *>::iterator it;
for (it = statement_list.begin(); it != statement_list.end(); it++) {
file_buffer<<"\n"<<AST_NODE_SPACE;
(*it)->print(file_buffer);
}
}
Print_Ast::Print_Ast(Ast *v, int line)
{
var = v;
lineno = line;
}
Print_Ast::~Print_Ast(){}
void Print_Ast::print(ostream & file_buffer){
file_buffer<<"\n"<<AST_SPACE<<"Print :";
file_buffer<<"\n"<<AST_SUB_NODE_SPACE<<"(";
var->print(file_buffer);
file_buffer<<")";
}
Return_Ast::Return_Ast(Ast* ret_val, string name, int line)
{
this->ret_val = ret_val;
this->ast_num_child = unary_arity;
this->func_name = name;
if(return_value == NULL)
this->node_data_type = void_data_type;
else
this->node_data_type = return_value->get_data_type();
this->lineno = line;
this->check_ast();
}
Data_Type Return_Ast::get_data_type()
{
return this->node_data_type;
}
bool Return_Ast::check_ast()
{
return true;
}
string Return_Ast::get_func_name()
{
return this->func_name;
}
void Return_Ast::print(ostream & file_buffer)
{
file_buffer << endl
<< AST_SPACE << "RETURN ";
if(this->ret_val == NULL) {
file_buffer << "<NOTHING>";
} else {
ret_val->print(file_buffer);
}
file_buffer << endl;
}
Call_Ast::Call_Ast(string name, int line)
{
this->procedure_name = name;
this->node_data_type = int_data_type;
this->lineno = line;
}
Data_Type Call_Ast::get_data_type()
{
return this->node_data_type;
}
void Call_Ast::set_register(Register_Descriptor * reg)
{
return_value_reg = reg;
}
void Call_Ast::check_actual_formal_param(Symbol_Table & formal_param_list)
{
}
void set_actual_param_list(list<Ast *> & param_list)
{
this->actual_param_list = param_list;
}
void Call_Ast::print(ostream & file_buffer)
{
file_buffer << "\n"
<< AST_SPACE << "FN CALL: " << this->func_name << "(";
for(auto it: arguments) {
file_buffer << endl;
file_buffer << AST_NODE_SPACE;
it->print(file_buffer);
}
file_buffer << ")";
} | 746b47dc3c71be2bfa24ae5fa35014a2e45084be | [
"C++"
] | 4 | C++ | sahilsaiyad/Compiler | 26205d03066a9499770290a5bcce017e4bef173f | b6b631000d3515c29d8066b5410a03dc28246593 |
refs/heads/master | <repo_name>goelprateek5/TARP_PROJECT<file_sep>/mysite/mediaAccess/models.py
from django.db import models
# Create your models here.
class media(models.Model):
name=models.CharField(max_length=100)
media=models.CharField(max_length=500)
category=models.CharField(max_length=250)
def __str__(self):
return str(self.id)+' '+str(self.name)+' '+str(self.media)+' '+str(self.category)
<file_sep>/mysite/mediaAccess/views.py
from os import listdir
from os.path import isfile, join
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.template import loader
from .models import media
# Create your views here.
def index(request):
# all_buses=Bus.objects.all()
# template=loader.get_template('home_page/index.html')
# context={
# 'all_buses':all_buses,
# }
return render(request, 'mediaAccess.html')
# return HttpResponse(template.render(context,request))
def videos(request):
video = media.objects.filter(category='videos')
context = {
'v':video,
}
template = loader.get_template('videos.html')
return HttpResponse(template.render(context,request))
def music(request):
music=media.objects.filter(category='music')
context={
'm':music,
}
template = loader.get_template('music.html')
return HttpResponse(template.render(context,request))
def books(request):
books=media.objects.filter(category='books')
context={
'b':books,
}
template = loader.get_template('books.html')
return HttpResponse(template.render(context,request))
def updateDB():
Video_present=media.objects.filter(category='videos')
Music_present=media.objects.filter(category='music')
Books_present=media.objects.filter(category='books')
video_dir="etravel_search/static/images/media/videos"
songs_dir="etravel_search/static/images/media/songs"
books_dir="etravel_search/static/images/media/books"
v=[f for f in listdir(video_dir) if isfile(join(video_dir, f))]
s=[f for f in listdir(songs_dir) if isfile(join(songs_dir, f))]
b=[f for f in listdir(books_dir) if isfile(join(books_dir, f))]
V=[]
M=[]
B=[]
for i in Video_present:
S=i.media
S=list(S.split('/'))
V.append(S[-1])
for i in Music_present:
S=i.media
S=list(S.split('/'))
M.append(S[-1])
for i in Books_present:
S=i.media
S=list(S.split('/'))
B.append(S[-1])
for i in v:
if i not in V:
a=media()
a.name=list(i.split("."))[0]
a.media="../../static/images/media/videos/"+i
a.category="videos"
a.save()
for i in s:
if i not in M:
a=media()
a.name=list(i.split("."))[0]
a.media="../../static/images/media/songs/"+i
a.category="music"
a.save()
for i in b:
if i not in B:
a=media()
a.name=list(i.split("."))[0]
a.media="../../static/images/media/books/"+i
a.category="books"
a.save()
updateDB()
<file_sep>/mysite/mediaAccess/admin.py
from django.contrib import admin
from .models import media
# Register your models here.
admin.site.register(media,name='Media')<file_sep>/mysite/mediaAccess/urls.py
from django.conf.urls import url, include
from . import views
from django.views.generic import TemplateView
urlpatterns=[
url(r'^$', views.index, name='index'),
url(r'^videos$', views.videos, name='videos'),
url(r'^music$', views.music, name='music'),
url(r'^books$', views.books, name='books'),
]<file_sep>/README.md
Added MediaAccess module to the webapps
<file_sep>/mysite/mediaAccess/apps.py
from django.apps import AppConfig
class MediaaccessConfig(AppConfig):
name = 'mediaAccess'
| da3826aa53eb0ba7cd3e96e792054740a944c652 | [
"Markdown",
"Python"
] | 6 | Python | goelprateek5/TARP_PROJECT | 4f414cbcd34cddd5007869423ade6aaf2d2445b1 | e7692411e061d481b43c1a381a2732f3f53275ee |
refs/heads/master | <file_sep>import java.util.Map;
public class testClass {
private class myclass{
public Integer f;
}
public void test2(int tag)
{
myclass a = new myclass();
a.f = new Integer(10);
Integer y;
if(tag > 0){
y = a.f;
}
else{
a.f = new Integer(20);
y = a.f;
}
}
public int test3(int tag,int b){
if(tag%10 == 0){
tag = tag*3;
b = 50;
}
else{
tag = b+tag;
b++;
}
tag = b+23;
return tag;
}
public int test2(int i,int j)
{
while(i > j){
if(i >-100){
if(i>0)
i = j;
else
j = 100;
}
else{
i = 5;
j = 6;
}
}
return i + j;
}
}
<file_sep>### 1. 下载代码,进入到soot-command文件夹中
### 2. 执行help.txt中的javac命令,查看是否有正常提示
### 3. javac testClass.java
### 4. 执行shimple.txt中的命令生成soot的SSA结果,在sootOutput中查看<file_sep>import soot.BodyTransformer;
import soot.PackManager;
import soot.Transform;
import soot.options.Options;
import java.util.LinkedList;
import java.util.List;
public class Example {
private Integer age;
public void run(String dir){
Printer printer = new Printer();
Transform t1 = new Transform("jtp.Printer", printer);
PackManager.v().getPack("jtp").add(t1);
int size = 4;
String[] soot_args = new String[size];
soot_args[0] = "-process-dir";
soot_args[1] = dir;
soot_args[2] = "-pp";
soot_args[3] = "-allow-phantom-refs";
soot.Main.main(soot_args);
}
public Integer killYou(){
Integer res = this.age;
if(this.age > 20){
System.out.println(" kill you.");
res = 20;
}
else{
System.out.println(" kill me.");
res = 18;
}
return this.age+res;
}
public static void main(String[] args){
List<String> processDir = new LinkedList<String>();
processDir.add("E:\\codes\\homework\\soot-tools\\soot-tools\\soot\\target\\classes");
Options.v().set_process_dir(processDir);
Example example = new Example();
example.run("E:\\codes\\homework\\soot-tools\\soot-tools\\soot\\target\\classes");
}
}
| c4e2d719f04582a61acbb327d4b650b612c62631 | [
"Markdown",
"Java"
] | 3 | Java | Xuyuanjia2014/soot-tools | f6bdf6f6484c3c64fc3ae7707390a8e06e51903d | 7e6ade71a90717be284ca6ea1271cac233aa0e20 |
refs/heads/main | <repo_name>Prasanna1112/KMeans-Clustering-for-Image-Segmentation<file_sep>/image_seg_kmean.py
import numpy as np
import cv2
from sklearn.cluster import KMeans
from sklearn.cluster import MiniBatchKMeans
#Reading the original picture
picture = cv2.imread('picture.jpg')
(h1, w1) = picture.shape[:2]
#Reshaping the picture
picture = cv2.cvtColor(picture, cv2.COLOR_BGR2LAB)
picture = picture.reshape((picture.shape[0] * picture.shape[1], 3))
#Initialising the number of clusters
kmean_clust = KMeans(n_clusters = 3)
#Fitting the clusters onto the model
labels = kmean_clust.fit_predict(picture)
quantified_image = kmean_clust.cluster_centers_.astype("uint8")[labels]
#Feature Scaling
#Reshape the feature vectors to pictures
quantified_image = quantified_image.reshape((h1, w1, 3))
picture = picture.reshape((h1, w1, 3))
#Converting the image back to RGB
quantified_image = cv2.cvtColor(quantified_image, cv2.COLOR_LAB2BGR)
picture = cv2.cvtColor(picture, cv2.COLOR_LAB2BGR)
#Writing the segmented image as a new one
cv2.imwrite('generated.jpg', quantified_image)
cv2.waitKey(0)
cv2.destroyAllWindows()<file_sep>/README.md
# KMeans-Clustering-for-Image-Segmentation
Image segmentation using one of the most used clustering techniques KMeans
# About K-Means clustering:
K-Means is one of the simplest unsupervised learning algorithms that solve the well known clustering problem. The procedure follows a simple and easy way to classify a given data set through a certain number of clusters (assume k clusters) fixed apriori.
The main idea is to define k centers, one for each cluster. These centers should be placed in a cunning way because of different location causes different result. So, the better choice is to place them as much as possible far away from each other.
The next step is to take each point belonging to a given data set and associate it to the nearest center. When no point is pending, the first step is completed and an early group age is done.
At this point we need to re-calculate k new centroids as barycenter of theclusters resulting from the previous step. After we have these k new centroids, a new binding has to be done between the same data set points and the nearest new center. A loop has been generated.
As a result of this loop we may notice that the k centers change their location step by step until no more changes are done or in other words centers do not move any more.
# Algorithmic steps for k-means clustering
Let X = {x1,x2,x3,……..,xn} be the set of data points and V = {v1,v2,…….,vc} be the set of centers.
1) Randomly select ‘c’ cluster centers.
2) Calculate the distance between each data point and cluster centers.
3) Assign the data point to the cluster center whose distance from the cluster center is minimum of all the cluster centers.
4) Recalculate the new cluster center using the new centers.
5) Recalculate the distance between each data point and new obtained cluster centers.
6) If no data point was reassigned then stop, otherwise repeat from step.
# Brief:
This code takes in an image, reshapes it, uses KMeans clustering to cluster the datepoints for segmentation, and then reshapes back to an output image.
Make sure to have the input image in the same folder as the code.
# Usage:
In your terminal: python image_seg_kmean.py or simply build the code from your editor of choice
| 73474ed701da9245110c67759876d018fad147ae | [
"Markdown",
"Python"
] | 2 | Python | Prasanna1112/KMeans-Clustering-for-Image-Segmentation | 00adc268b9c9d45c1f46cca3528258cd2ca121e6 | 89d85a2429ce0f7dce3af5b993e9587cdffc169f |
refs/heads/master | <repo_name>OnceApp/abandoned-strings<file_sep>/AbandonedStrings/main.swift
#!/usr/bin/env xcrun swift
//
// main.swift
// AbandonedStrings
//
// Created by <NAME> on 2/1/16.
// Copyright © 2016 iJoshSmith. All rights reserved.
//
/*
For overview and usage information refer to https://github.com/ijoshsmith/abandoned-strings
*/
import Foundation
func findFilesIn(_ directories: [String], withExtensions extensions: [String]) -> [String] {
let fileManager = FileManager.default
var files = [String]()
for directory in directories {
guard let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: directory) else {
print("Failed to create enumerator for directory: \(directory)")
return []
}
while let path = enumerator.nextObject() as? String {
let fileExtension = (path as NSString).pathExtension.lowercased()
if extensions.contains(fileExtension) {
let fullPath = (directory as NSString).appendingPathComponent(path)
files.append(fullPath)
}
}
}
return files
}
func contentsOfFile(_ filePath: String) -> String {
do {
return try String(contentsOfFile: filePath, encoding: String.Encoding.utf8)
}
catch { return "" }
}
func concatenateAllSourceCodeIn(_ directories: [String]) -> String {
let extensions = ["m", "swift"]
let sourceFiles = findFilesIn(directories, withExtensions: extensions)
print("Looking in \(sourceFiles.count) source files ...")
return sourceFiles.reduce("") { (accumulator, sourceFile) -> String in
return accumulator + contentsOfFile(sourceFile)
}
}
func extractStringIdentifiersFrom(_ stringsFile: String) -> [String] {
return contentsOfFile(stringsFile).components(separatedBy: "\n").map { $0.trimmingCharacters(in: CharacterSet.whitespaces) }.map{ extractStringIdentifierFromTrimmedLine($0) }.filter { $0 != nil } as! [String]
}
func extractStringIdentifierFromTrimmedLine(_ line: String) -> String? {
if let i = line.index(of: "*") {
let indexAfterFirstQuote = line.index(i, offsetBy: " const ".count + 1)
let lineWithoutFirstQuote = line[indexAfterFirstQuote...]
if let equalIndex = lineWithoutFirstQuote.index(of:"=") {
let lastIndex = line.index(before: equalIndex)
let identifier = lineWithoutFirstQuote[..<lastIndex]
return String(identifier)
}
}
return nil
}
func findStringIdentifiersIn(_ stringsFile: String, abandonedBySourceCode sourceCode: String) -> [String]? {
return extractStringIdentifiersFrom(stringsFile).filter { identifier in
return sourceCode.contains("\(identifier)") == false
}
}
func findAbandonedIdentifiersIn(_ rootDirectories: [String]) ->
[String] {
var unusedStrings = [String]()
let sourceCode = concatenateAllSourceCodeIn(rootDirectories)
if let abandonedIdentifiers = findStringIdentifiersIn(file, abandonedBySourceCode: sourceCode) {
if abandonedIdentifiers.isEmpty == false {
unusedStrings = abandonedIdentifiers
print("---------- Found \(abandonedIdentifiers.count) unused strings ------")
print(abandonedIdentifiers)
print("---------- Found \(abandonedIdentifiers.count) unused strings ------")
} else {
print("All strings are used")
}
}
return unusedStrings
}
func getRootDirectories() -> [String]? {
var c = [String]()
for arg in CommandLine.arguments {
c.append(arg)
}
c.remove(at: 0)
if c.count > 1 {
file = c[1]
}
return c
}
var file = ""
if let rootDirectories = getRootDirectories() {
print("Searching for abandoned resource strings…")
let map = findAbandonedIdentifiersIn(rootDirectories)
if map.isEmpty {
print("No abandoned resource strings were detected.")
}
} else {
print("Please provide the root directory for the project files as a command line argument.")
}
<file_sep>/README.md
# Abandoned Resource String Detection
This command line program detects unused resource strings in an iOS or OS X application.
## Usage
Open a Terminal to the directory which contains the *AbandonedStrings* executable, and run the following command:
`$ ./AbandonedStrings/main.swift /Users/your-username/path/to/sourcecode_folder /path/to/file_containing_the_strings`
i.e. `$ ./AbandonedStrings/main.swift /Volumes/Alinaa/Development/once-ios /Volumes/Alinaa/Development/DerivedData/once-deecixewwotnzkbyydvhbcsxvvrj/Build/Products/InAppDebug-iphoneos/include/Localizable.h`
Can also be used in Xcode, just hardcode those values like:
`var file = "/Volumes/Alinaa/Development/DerivedData/once-deecixewwotnzkbyydvhbcsxvvrj/Build/Products/InAppDebug-iphoneos/include/Localizable.h"`
`return "/Volumes/Alinaa/Development/once-ios"//c`
or retrieve them programmatically as needed
## What to expect
`Searching for abandoned resource strings…
Looking in 1050 source files ...
---------- Found 284 unused strings ------
["com_once_strings_reviews_man_flow_date_sorry_title", "com_once_strings_label_tutorial_subtitle_2_her", "com_once_strings_label_dm_subscribe_title1", "com_once_strings_label_dm_onboarding_popup_page_three_title", "com_once_strings_label_ratetheapp_why_a_woman", "com_once_strings_label_plans_buy_more_crowns_subtitle", "com_once_strings_title_settings_agerange", "com_once_strings_label_pictures_makefirst", "com_once_strings_label_plans_extra_crowns_deal", "com_once_strings_title_termsofservice", "com_once_strings_buttons_crowns_cool_thanks", "com_once_strings_label_elections_profile_french_presidential_election_blue_part", "com_once_strings_label_match_passedmequestion_him", "com_once_strings_label_dialog_tutoinvite_suggest_her_to_a_friend", "com_once_strings_subtitle_my_description", "com_once_strings_label_chat_need_access_to_location", "com_once_strings_title_my_profile", "com_once_strings_label_settings_areyousuredeletedm", "com_once_strings_subtitle_settings_dedicated_matchmaker", "com_once_strings_startup_button_agreed", "com_once_strings_label_subscription_cancel", "com_once_strings_reviews_man_flow_look_pictures_the_same", "com_once_strings_button_match_like_still_not_interested_her", .....]
---------- Found 284 unused strings ------`
| c4bca7dfea757eef216852c7a7d1869210d49609 | [
"Swift",
"Markdown"
] | 2 | Swift | OnceApp/abandoned-strings | 4da9558b6ea157e67fa656e7836bf274b67a3bef | 109131d7103b4e9c6e0c0d47e5eb7667a6f87d89 |
refs/heads/master | <repo_name>vlad-vetlin/UX_keyboards<file_sep>/mixins/timeEntryMixin.js
import {texts} from "../assets/js/texts";
import {levenshteinDistance} from "../assets/js/helper";
let timeForPrepare = 10000;
export const timeEntryMixin = {
data() {
return {
timeLeft: timeForPrepare,
interval: undefined,
curTime: undefined,
timeMetric: 0,
mistakeMetric: 0,
symbolCount: 0,
}
},
methods: {
timeToReady() {
this.timeLeft -= 5000;
if (this.timeLeft === 0) {
this.start();
} else {
this.$message({
message: 'Осталось ' + this.timeLeft / 1000 + " секунд",
type: 'message'
});
}
},
start() {
window.clearInterval(this.interval);
this.interval = undefined;
this.curTime = new Date();
this.$message({
message: "Начало",
type: 'success'
});
},
init() {
this.interval = window.setInterval(this.timeToReady, 5000);
},
nextText() {
const currentTime = new Date();
this.$message({
message: 'Ввод окончен',
type: 'success',
});
const time = currentTime - this.curTime;
const mistakes = levenshteinDistance(this.curString, this.texts[this.curTextCount]);
alert("Время: " + Math.floor(time / 1000) + " секунд, " + time % 1000 + " миллисекунд. " + mistakes + " ошибок.");
alert("Длина строки: " + this.texts[this.curTextCount].length + " символов");
this.timeMetric += Math.floor(time / 1000);
this.mistakeMetric += mistakes;
this.symbolCount += this.texts[this.curTextCount].length;
if (this.texts.length === this.curTextCount + 1) {
this.getFinalMetric();
return;
}
this.curString = '';
this.timeLeft = timeForPrepare;
this.interval = window.setInterval(this.timeToReady, 5000);
++this.curTextCount;
},
getFinalMetric() {
const speedMetric = this.symbolCount / this.timeMetric;
alert("Тестирование окончено. Ваши метрики: \n 1) Метрика ошибок: " + this.mistakeMetric + "\n 2) Метрика скорости: " + speedMetric + " символов в секунду");
},
},
watch: {
curString: {
handler(value) {
if (value.length === this.currentActiveText.length) {
this.nextText();
}
}
}
},
computed: {
isReady() {
return this.timeLeft === 0;
}
},
};
<file_sep>/assets/js/texts.js
export const texts = [
"тест",
"кек",
"лол",
];
| d3da7137cf4c86ab58456d208a022c21a43820df | [
"JavaScript"
] | 2 | JavaScript | vlad-vetlin/UX_keyboards | 0a9ce04778a4159a1bc54020c9390db05a7c469f | 98b8cb63f307003c0e01be8bf7f0b513451b3f3d |
refs/heads/master | <file_sep>import os
import csv
input_file = csv.DictReader(open("election_data.csv"))
for row in input_file:
print (row)
# Path to collect data from the Resources folder
# csvpath = os.path.join("election_data.csv")
# with open(csvpath, 'r', newline="") as csvfile:
# csvreader = csv.reader(csvfile, delimiter=",")
# # for row in csvreader:
# # print (row[0] + row[1] + row[2])
# next(csvreader, None) # Skip first row
# votes_tot=0
# votes_per=0
# candidates=[]
# dic = {}
# for row in csvreader:
# # votes_tot += 1 # votes count
# if row[2] not in candidates:
# candidates.append(row[2]) # create list of candidates
# print(len(candidates)) # 4 candidates
# votes_list=[0,0,0,0]
# dic = dict(zip(candidates, votes_list))
# print(dic)
# print(sum(dic.values()))
# dict["a"] += 1
input_file = csv.DictReader(open("election_data.csv"))
for row in input_file:
print (row)
# #sum the values with same keys
# dic_collapse = {}
# for d in dic:
# for k in d.keys():
# dic_collapse[k] = dic_collapse.get(k, 0) + d[k]
# print(str(dic_collapse))
# The total number of votes cast:
# print("Total votes: " + str(votes_tot))
# # A complete list of candidates who received votes
# for x in range(len(candidates)):
# print (candidates[x])
# The percentage of votes each candidate won
# The total number of votes each candidate won
# The winner of the election based on popular vote.<file_sep>import os
import csv
import textwrap
# Path to collect data from the Resources folder
csvpath = os.path.join("budget_data.csv")
with open(csvpath, 'r', newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# for row in csvreader:
# print (row[1])
next(csvreader, None) # Skip first row
months=0 # define variable for counting months
profits=0 # define variable for adding profits
profits_list = []
for row in csvreader:
months += 1 # The total number of months included in the dataset
profits_list.append(row[1]) # List of profits/losses
profits=profits+int(row[1]) # Total profits
print("total profits: "+ str(profits))
# The average of the changes in "Profit/Losses" over the entire period
change_list=[]
change=0
for i in range(len(profits_list)-1):
change=int(profits_list[i+1])-int(profits_list[i])
change_list.append(change)
# for x in range(len(change_list)):
# print (change_list[x])
change_average=sum(change_list)/len(change_list)
print(str(round(change_average, 2)))
# # The greatest increase in profits (date and amount) over the entire period
change_greatest=0
change_lowest=0
for i in range(len(change_list)-1):
if change_list[i] > change_greatest :
change_greatest=change_list[i]
if change_list[i] < change_lowest :
change_lowest=change_list[i]
print(str(change_greatest))
print(str(change_lowest))
# # The greatest decrease in losses (date and amount) over the entire period
# # for items in profits_list:
# # print(str(items))
<file_sep>#++++++++++++++++++++++++++++++
# NAME OF PROGRAM: PyBank.py
#++++++++++++++++++++++++++++++
import os
import csv
import textwrap
# Path to collect budget data
csvpath = os.path.join("budget_data.csv")
with open(csvpath, 'r', newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
next(csvreader, None) # Skip first row
months=0 # define variable for counting months
profits=0 # define variable for adding profits/losses
profits_list = [] # define list for pulling profits
months_list=[] # define list for pulling months
for row in csvreader:
#---------------------------
# I. TOTAL NUMBER OF MONTHS
#---------------------------
months += 1 # counting total number of months included in the dataset
profits_list.append(row[1]) # List of profits/losses
#---------------------------
# II. NET AMOUNT OF PROFITS
#---------------------------
profits=profits+int(row[1]) # adding up profits
months_list.append(row[0]) # List of months
# print("total profits: "+ str(profits))
# for x in range(len(months_list)):
# print (months_list[x])
# Create a dictionary with months and profits
dict_profits = dict(zip(months_list, profits_list)) # pulling together months and profits lists
#print(dict_profits)
# Average of changes in "Profit/Losses" over the entire period
change_list=[0] # list for storing monthly change in profits where first value is zero
change=0 # step 1: create a variable for monthly change in profits
for i in range(len(profits_list)-1): #loop over profits list...
change=int(profits_list[i+1])-int(profits_list[i]) # ... and subtract previous month's profits to calculate monthly change
change_list.append(change) # step 2: append all values from monthly profits' change variable to it's list
#---------------------------------
# III. AVERAGE CHANGES IN PROFITS
#---------------------------------
change_average=sum(change_list)/len(change_list) # calculating average monthly change in profits
# print("Average monthly change in profits: " + str(round(change_average, 2)))
#-----------------------------------------------
# IV. GREATEST AND LOWEST INCREASE IN PROFITS
#-----------------------------------------------
# Greatest increase in profits (date and amount) over the entire period
change_greatest=0
change_lowest=0
for i in range(len(change_list)-1): # search through list of monthly changes
if change_list[i] > change_greatest : # replace value of variable for greatest change each time a higher value is found
change_greatest=change_list[i]
if change_list[i] < change_lowest : # replace value of variable for lowest change each time a lower value is found
change_lowest=change_list[i]
dict_change = dict(zip(months_list, change_list)) # put together list with months and changes in profits into a dictionary
#print("lowest change: "+str(change_lowest) + ", highest change: " + str(change_greatest))
for month, profchan in dict_change.items(): # search through dictionary for the month of the highest and lowest value
if profchan==change_greatest:
month_greatest=month
# print("month of greatest change: " + month_greatest )
if profchan==change_lowest:
month_lowest=month
# print("month of lowest change: " + month_lowest )
#-----------------------------------------------
# V. PRINT SUMMARY OF RESULTS IN TERMINAL
#-----------------------------------------------
print("Financial Analysis")
print("-----------------------")
print("Total Months: " + str(months))
print( "Average change: $"+ str(round(change_average,2)))
print("Greatest Decrease in Profits: " + str(month_greatest) + " (" + str(change_greatest) + ")" )
print("Greatest Decrease in Profits: " + str(month_lowest) + " (" + str(change_lowest) + ")" )
#-----------------------------------------------
# VI. PRINT RESULTS IN TXT FILE
#-----------------------------------------------
file = open("PyBank.txt","w")
file.write("Financial Analysis\n")
file.write("-----------------------\n")
file.write("Total Months: " + str(months) + "\n")
file.write( "Average change: $"+ str(round(change_average,2))+ "\n")
file.write("Greatest Decrease in Profits: " + str(month_greatest) + " (" + str(change_greatest) + ")\n" )
file.write("Greatest Decrease in Profits: " + str(month_lowest) + "(" + str(change_lowest) + ")\n" )
file.close()
<file_sep>#++++++++++++++++++++++++++++++
# NAME OF PROGRAM: PyPoll2.py
#++++++++++++++++++++++++++++++
import os
import csv
csvpath = os.path.join("election_data.csv")
with open(csvpath, 'r', newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
# for row in csvreader:
# print (row[0] + row[1] + row[2])
next(csvreader, None) # Skip first row
votes_tot=0
votes_per=0
candidates=[]
dic = {}
all_votes=[] # this one is for storing all votes (each time a candidate is mentioned in the file)
for row in csvreader:
#---------------------------
# I. TOTAL NUMBER OF VOTES
#---------------------------
votes_tot += 1 # votes count
all_votes.append(row[2])
if row[2] not in candidates:
candidates.append(row[2]) # create list of candidates
# print(len(candidates)) # number of candidates: 4
# print(str(votes_tot)) # total number of votes
# for x in range(len(all_votes)):
# print (all_votes[x])
#------------------------------
# II. LIST OF THE 4 CANDIDATES
#------------------------------
# for x in range(len(candidates)):
# print (candidates[x])
#------------------------------------
# III. NUMBER OF VOTES PER CANDIDATE
#------------------------------------
votes_list=[0,0,0,0] # create list for counting the votes of each candidate
d_candidates = dict(zip(candidates, votes_list)) # dictionary for storing candidates and total votes
# print(sum(dic.values()))
for k in d_candidates.keys(): # for each candidate (each one is a key)
for x in range(len(all_votes)): #... search
if all_votes[x]==k:
d_candidates[k]+=1
# print(d_candidates)
#---------------------------------------
# IV. PERCENTAGE OF VOTES PER CANDIDATE
#---------------------------------------
d_candidates_per={}
d_candidates_per = dict.fromkeys(d_candidates)
# print(d_candidates_per)
for k in d_candidates.keys(): # for each candidate (each one is a key)
d_candidates_per[k] = d_candidates[k]/votes_tot
# print (d_candidates_per)
from collections import defaultdict
d_candidates_all = defaultdict(list)
for d in (d_candidates, d_candidates_per):
for key, value in d.items():
d_candidates_all[key].append(value)
# print(d_candidates_all)
votes_winner=0
for k,v in d_candidates_all.items():
if v[0]>votes_winner:
votes_winner=v[0]
# print(str(votes_winner))
winner= [k for k, v in d_candidates_all.items() if v[0] == votes_winner ]
# print(winner)
winner_can=' '.join(map(str, winner))
print(winner_can)
#---------------------------------------
# V. PRINT RESULTS IN TERMINAL
#---------------------------------------
print("Election Results")
print("-------------------------")
print("Total Votes: " + str(votes_tot))
print("-------------------------")
for k,v in d_candidates_all.items():
print(k + " : " + str("{0:.3%}".format(v[1]) ) + " (" + str(v[0]) + ")")
print("-------------------------")
print ("Winner: " + winner_can+"\n")
print("-------------------------")
# #---------------------------------------
# # V. PRINT RESULTS IN TXT FILE
# #---------------------------------------
file = open("PyPoll.txt","w")
file.write("Election Results \n")
file.write("-------------------------\n")
file.write("Total Votes: " + str(votes_tot)+ "\n")
# file.write("-------------------------")
for k,v in d_candidates_all.items():
file.write(k + " : " + str("{0:.3%}".format(v[1]) ) + " (" + str(v[0]) + ")\n")
file.write("-------------------------\n")
file.write("Winner: " + winner_can + "\n")
file.write("-------------------------\n")
file.close() | f932d42e82fa35a3a71a4f94bdbcf39fb50c47bb | [
"Python"
] | 4 | Python | arivargasb/python_challenge | e3bc8c6060e643d6d49c396396a8d373e4dc74c5 | 9f9daccf951d04f7eb4a3117b48f4b83f3b6af8b |
refs/heads/master | <repo_name>addisonhellum/CaptureCore<file_sep>/src/us/capturecore/core/common/game/gameutil/Shopkeeper.java
package us.capturecore.core.common.game.gameutil;
import org.bukkit.Location;
import org.bukkit.entity.ArmorStand;
import org.bukkit.scheduler.BukkitRunnable;
import us.capturecore.core.Main;
public class Shopkeeper {
public enum ShopkeeperType {
RED, BLUE;
}
private ShopkeeperType type;
public Shopkeeper(ShopkeeperType type) {
this.type = type;
}
public ShopkeeperType getType() {
return type;
}
public String[] getFrames() {
if (getType().equals(ShopkeeperType.RED))
return new String[] {
"<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>",
"<KEY>" +
"<KEY>" +
"<KEY>" +
"<KEY>"
};
else if (getType().equals(ShopkeeperType.BLUE))
return new String[] {
"<KEY>
<KEY>" +
"<KEY>" +
"<KEY>",
"<KEY>
<KEY>" +
"tJTi<KEY>" +
"<KEY>"
};
return null;
}
public void displayPrototype(Location location) {
ArmorStand stand = location.getWorld().spawn(location, ArmorStand.class);
new BukkitRunnable() {
int index = 0;
@Override
public void run() {
if (index == 60) {
stand.remove();
cancel();
}
int frame = index % 2;
String value = getFrames()[frame];
stand.setHelmet(SkullCreator.fromBase64(SkullCreator.Type.ITEM, value));
index++;
}
}.runTaskTimer(Main.getInstance(), 20, 20);
}
}
<file_sep>/src/us/capturecore/core/common/GlobalHandler.java
package us.capturecore.core.common;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import us.capturecore.core.Main;
import us.capturecore.core.util.SQL;
public class GlobalHandler implements Listener {
@EventHandler
public void onRenewSQL(PlayerJoinEvent event) {
FileConfiguration config = Main.getInstance().getConfig();
if (!SQL.hasOpenConnection()) {
SQL.setupConnection(
config.getString("sql-data.hostname"),
config.getString("sql-data.port"),
config.getString("sql-data.database"),
config.getString("sql-data.username"),
config.getString("sql-data.password")
);
}
}
@EventHandler
public void onWeather(WeatherChangeEvent event) {
event.setCancelled(true);
}
}
<file_sep>/src/us/capturecore/core/common/game/GameHandler.java
package us.capturecore.core.common.game;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.*;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import us.capturecore.core.Main;
import us.capturecore.core.commands.admin.AoCommand;
import us.capturecore.core.common.game.data.CCMap;
import us.capturecore.core.common.game.data.CCTeam;
import us.capturecore.core.common.game.gameutil.ShopMenu;
import us.capturecore.core.common.player.CCPlayer;
import us.capturecore.core.common.player.party.CCParty;
import us.capturecore.core.common.player.rank.Rank;
import us.capturecore.core.event.ServerStartEvent;
import us.capturecore.core.event.ServerStopEvent;
import us.capturecore.core.util.LocSerialization;
import us.capturecore.core.util.NametagUtil;
import us.capturecore.core.util.menu.ItemStackBuilder;
import us.capturecore.core.util.text.ChatUtil;
import us.capturecore.core.util.text.Title;
import java.io.File;
import java.util.*;
public class GameHandler implements Listener {
public enum GameState {
PREGAME, COUNTDOWN, INGAME, ENDED;
}
private static GameState gameState = GameState.PREGAME;
public static GameState getGameState() { return gameState; }
private static List<Player> players = new ArrayList<>();
public static List<Player> getPlayers() { return players; }
private static CCMap map;
public static CCMap getMap() { return map; }
private List<Block> placedByPlayer = new ArrayList<>();
public static void initializeMapData() {
File mapdir = new File(Main.getInstance().getDataFolder() + "/mapdata");
if (!mapdir.exists()) mapdir.mkdir();
//map = CCMap.randomMap();
map = CCMap.randomMap();
}
public static void healPlayer(Player player) {
player.getInventory().clear();
player.getInventory().setArmorContents(null);
for (PotionEffect effect : player.getActivePotionEffects())
player.removePotionEffect(effect.getType());
}
private static CCTeam redTeam = new CCTeam("Red", ChatColor.RED);
private static CCTeam blueTeam = new CCTeam("Blue", ChatColor.BLUE);
private static CCTeam spectator = new CCTeam("Spectator", ChatColor.GRAY);
public static CCTeam getRedTeam() { return redTeam; }
public static CCTeam getBlueTeam() { return blueTeam; }
public static CCTeam getSpectator() { return spectator; }
public Location getSpawn(Player player) {
CCTeam team = CCTeam.getTeam(player.getUniqueId());
if (team.getName().equalsIgnoreCase("red")) return getMap().getRedSpawn();
else if (team.getName().equalsIgnoreCase("blue")) return getMap().getBlueSpawn();
else return getMap().getLobbyLocation();
}
public void joinTeam(Player player, String teamName) {
UUID uuid = player.getUniqueId();
CCTeam team = CCTeam.getTeam(teamName);
team.addMember(uuid);
NametagUtil.setNametag(player, teamName, team.getColor() + "" + ChatColor.BOLD +
teamName.toUpperCase().substring(0, 1) + " " + team.getColor(), "");
if (teamName.equalsIgnoreCase("red")) player.teleport(getMap().getRedSpawn());
if (teamName.equalsIgnoreCase("blue")) player.teleport(getMap().getBlueSpawn());
}
public void assignTeams() {
int teamSize = getPlayers().size() / 2;
for (CCParty party : CCParty.getParties()) {
for (Player player : party.getOnlineMembers()) {
if (redTeam.count() + party.getOnlineMembers().size() <= teamSize) joinTeam(player, "red");
else if (blueTeam.count() + party.getOnlineMembers().size() <= teamSize) joinTeam(player, "blue");
}
}
int index = 1;
for (Player player : getPlayers()) {
if (CCTeam.getTeam(player.getUniqueId()) == null) {
if (index % 2 == 0) joinTeam(player, "red");
else if (index % 2 == 1) joinTeam(player, "blue");
index++;
}
}
}
private String div = "&a&l▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬";
public void broadcastStartMessage() {
for (Player player : getPlayers()) {
player.sendMessage(ChatUtil.format(div));
ChatUtil.sendCenteredMessage(player, "&f&lCapture the Flag");
player.sendMessage(" ");
ChatUtil.sendCenteredMessage(player, "&e&lDefend your flag and capture the enemy's flag.");
ChatUtil.sendCenteredMessage(player, "&e&lUpgrade yourself and your team by collecting");
ChatUtil.sendCenteredMessage(player, "&e&lIron, Gold, Emerald, and Diamond from mining");
ChatUtil.sendCenteredMessage(player, "&e&lresources around the map.");
player.sendMessage(" ");
player.sendMessage(ChatUtil.format(div));
}
}
public void giveStartingGear(Player player) {
String team = CCTeam.getTeam(player.getUniqueId()).getName();
player.getInventory().clear();
player.getInventory().setArmorContents(null);
Color color = Color.GRAY;
if (team.equalsIgnoreCase("blue")) color = Color.fromRGB(51, 76, 178);
if (team.equalsIgnoreCase("red")) color = Color.fromRGB(153, 51, 51);
PlayerInventory inv = player.getInventory();
inv.setChestplate(new ItemStackBuilder(Material.LEATHER_CHESTPLATE).withColor(color).build());
inv.setLeggings(new ItemStackBuilder(Material.LEATHER_LEGGINGS).withColor(color).build());
inv.setBoots(new ItemStackBuilder(Material.LEATHER_BOOTS).withColor(color).build());
inv.setItem(0, new ItemStackBuilder(Material.WOOD_SWORD).build());
inv.setItem(1, new ItemStackBuilder(Material.GOLD_PICKAXE).withEnchantment(Enchantment.DIG_SPEED, 3).build());
inv.setItem(8, new ItemStackBuilder(Material.BLAZE_POWDER).withName("&bAbilities").build());
player.addPotionEffect(new PotionEffect(PotionEffectType.FAST_DIGGING, 10000000, 0));
if (team.equalsIgnoreCase("red")) inv.setItem(2, new ItemStack(Material.WOOL, 64, (byte) 14));
if (team.equalsIgnoreCase("blue")) inv.setItem(2, new ItemStack(Material.WOOL, 64, (byte) 11));
}
@EventHandler
public void onStart(ServerStartEvent event) {
initializeMapData();
ShopMenu.initialize();
Main.getInstance().getServer().getPluginManager().registerEvents(new ShopMenu(), Main.getInstance());
for (Player p : Bukkit.getOnlinePlayers()) players.add(p);
}
@EventHandler
public void onStop(ServerStopEvent event) {
for (Block b : placedByPlayer)
b.setType(Material.AIR);
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
CCPlayer player = new CCPlayer(event.getPlayer());
players.add(player.spigot());
event.setJoinMessage(ChatUtil.format(player.getFormattedName() + " &ehas joined (&b" + players.size() + "&e/"
+ "&b" + getMap().getMaximumPlayers() + "&e)!"));
healPlayer(player.spigot());
if (getPlayers().size() >= getMap().getMinimumPlayers() && getGameState().equals(GameState.PREGAME)) {
gameState = GameState.COUNTDOWN;
new BukkitRunnable() {
int index = 10;
@Override
public void run() {
if (!getGameState().equals(GameState.COUNTDOWN)) {
cancel();
return;
}
if (index == 10) Bukkit.broadcastMessage(ChatUtil.format("&eThe game starts in &a10 &eseconds!"));
if (index == 0) {
gameState = GameState.INGAME;
assignTeams();
broadcastStartMessage();
for (Player player : getPlayers())
giveStartingGear(player);
return;
}
if (index <= 5 && index > 1) {
Bukkit.broadcastMessage(ChatUtil.format("&eThe game starts in &b" + index + " &eseconds!"));
} else if (index == 1) Bukkit.broadcastMessage(ChatUtil.format("&eThe game starts in &b1 &esecond!"));
index--;
}
}.runTaskTimer(Main.getInstance(), 20, 20);
}
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
CCPlayer player = new CCPlayer(event.getPlayer());
players.remove(player.spigot());
event.setQuitMessage(ChatUtil.format(player.getFormattedName() + " &ehas quit!"));
if (getPlayers().size() < getMap().getMinimumPlayers() && getGameState().equals(GameState.COUNTDOWN)) {
gameState = GameState.PREGAME;
Bukkit.broadcastMessage(ChatUtil.format("&cStart cancelled. Waiting for more players."));
}
}
@EventHandler
public void onFoodLevel(FoodLevelChangeEvent event) {
event.setCancelled(true);
}
@EventHandler
public void onDamage(EntityDamageEvent event) {
if (!getGameState().equals(GameState.INGAME)) event.setCancelled(true);
}
@EventHandler
public void onBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
Block block = event.getBlock();
if (AoCommand.hasOverride(player)) return;
if (!getGameState().equals(GameState.INGAME)) {
event.setCancelled(true);
return;
}
int cooldown;
Material mat = block.getType();
if (mat.equals(Material.IRON_BLOCK)) {
player.getInventory().addItem(new ItemStack(Material.IRON_INGOT));
cooldown = 8;
} else if (mat.equals(Material.GOLD_BLOCK)) {
player.getInventory().addItem(new ItemStack(Material.GOLD_INGOT));
cooldown = 16;
} else if (mat.equals(Material.DIAMOND_BLOCK)) {
player.getInventory().addItem(new ItemStack(Material.DIAMOND));
cooldown = 30;
} else if (mat.equals(Material.EMERALD_BLOCK)) {
player.getInventory().addItem(new ItemStack(Material.EMERALD));
cooldown = 60;
} else {
if (placedByPlayer.contains(block)) {
placedByPlayer.remove(block);
return;
}
event.setCancelled(true);
return;
}
event.setCancelled(true);
block.setType(Material.BEDROCK);
new BukkitRunnable() {
@Override
public void run() {
block.setType(mat);
}
}.runTaskLater(Main.getInstance(), cooldown * 20);
}
@EventHandler
public void onPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
Block block = event.getBlock();
if (!AoCommand.hasOverride(player)) {
if (!getGameState().equals(GameState.INGAME)) {
event.setCancelled(true);
return;
}
}
if (block.getType().equals(Material.TNT)) {
block.getLocation().getWorld().spawnEntity(block.getLocation(), EntityType.PRIMED_TNT);
event.setCancelled(true);
}
placedByPlayer.add(block);
}
@EventHandler
public void onExplode(EntityExplodeEvent event) {
event.setCancelled(true);
if (!getGameState().equals(GameState.INGAME)) return;
for (Block block : event.blockList())
if (placedByPlayer.contains(block)) {
block.setType(Material.AIR);
placedByPlayer.remove(block);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onChat(AsyncPlayerChatEvent event) {
if (!getGameState().equals(GameState.INGAME)) return;
Player player = event.getPlayer();
CCPlayer ccp = new CCPlayer(player);
String message = event.getMessage();
if (ccp.hasAccess(Rank.ADMIN)) message = ChatColor.translateAlternateColorCodes('&', message);
event.setFormat(ccp.getLevelFormat() + " " + CCTeam.getTeam(ccp.getUniqueId()).getPrefix() +
ccp.getFormattedName() + ChatColor.RESET + ": " + message.replace("%", "%%"));
}
public void playRespawn(Player player) {
PlayerInventory inv = player.getInventory();
inv.clear();
inv.setArmorContents(null);
player.setGameMode(GameMode.ADVENTURE);
player.setHealth(20);
player.setAllowFlight(true);
player.setFlying(true);
player.teleport(player.getLocation().clone().add(0, 5, 0));
Bukkit.getOnlinePlayers().forEach(p -> p.hidePlayer(player));
new BukkitRunnable() {
int index = 5;
@Override
public void run() {
if (index == 0) {
player.sendMessage(ChatUtil.format("&eYou have respawned."));
Title title = new Title("", "&eYou have respawned.");
title.send(player);
player.setGameMode(GameMode.SURVIVAL);
giveStartingGear(player);
Bukkit.getOnlinePlayers().forEach(p -> p.showPlayer(player));
player.teleport(getSpawn(player));
player.setAllowFlight(false);
player.setFlying(false);
cancel();
} else if (index > 1) {
Title title = new Title("&c&lYOU DIED!", "&eYou will respawn in &c" + index + " &eseconds!");
title.send(player);
player.sendMessage(ChatUtil.format("&eYou will respawn in &c" + index + " &eseconds!"));
} else {
Title title = new Title("&c&lYOU DIED!", "&eYou will respawn in &c1 &esecond!");
title.send(player);
player.sendMessage(ChatUtil.format("&eYou will respawn in &c1 &esecond!"));
}
index--;
}
}.runTaskTimer(Main.getInstance(), 5, 20);
}
@EventHandler
public void onFallDamage(EntityDamageEvent event) {
if (event.getCause().equals(EntityDamageEvent.DamageCause.FALL))
event.setCancelled(true);
}
@EventHandler
public void onPlayerKill(EntityDamageByEntityEvent event) {
Entity entity = event.getEntity();
Entity damager = event.getDamager();
if (entity instanceof Player && damager instanceof Player) {
Player player = (Player) entity;
CCTeam team = CCTeam.getTeam(player.getUniqueId());
if (player.getGameMode().equals(GameMode.ADVENTURE)) {
event.setCancelled(true);
return;
}
if (event.getFinalDamage() >= player.getHealth()) {
Player killer = (Player) damager;
event.setCancelled(true);
playRespawn(player);
if (team.getName().equalsIgnoreCase("red"))
Bukkit.broadcastMessage(ChatUtil.format("&c" + player.getName() + " &7was killed by &9" + killer.getName()));
if (team.getName().equalsIgnoreCase("blue"))
Bukkit.broadcastMessage(ChatUtil.format("&9" + player.getName() + " &7was killed by &c" + killer.getName()));
}
}
}
@EventHandler
public void onDeath(EntityDamageEvent event) {
Entity entity = event.getEntity();
if (entity instanceof Player) {
Player player = (Player) entity;
CCTeam team = CCTeam.getTeam(player.getUniqueId());
if (player.getGameMode().equals(GameMode.ADVENTURE)) {
event.setCancelled(true);
return;
}
if (event.getFinalDamage() >= player.getHealth()) {
event.setCancelled(true);
playRespawn(player);
if (team.getName().equalsIgnoreCase("red"))
Bukkit.broadcastMessage(ChatUtil.format("&c" + player.getName() + " &7died!"));
if (team.getName().equalsIgnoreCase("blue"))
Bukkit.broadcastMessage(ChatUtil.format("&9" + player.getName() + " &7died!"));
}
}
}
@EventHandler
public void onVoid(PlayerMoveEvent event) {
if (event.getPlayer().getLocation().getBlockY() <= 10)
playRespawn(event.getPlayer());
}
private boolean redStolen = false;
private boolean blueStolen = false;
@EventHandler
public void onStealFlag(PlayerMoveEvent event) {
Player player = event.getPlayer();
Location loc = player.getLocation();
if (!getGameState().equals(GameState.INGAME)) return;
CCTeam team = CCTeam.getTeam(player.getUniqueId());
if (team.getName().equalsIgnoreCase("red")) {
if (blueStolen) return;
blueStolen = true;
if (loc.distanceSquared(getMap().getBlueFlag()) < 2.5) {
Bukkit.broadcastMessage("");
Bukkit.broadcastMessage(ChatUtil.format("Flag Stolen > &9Blue Flag &7was stolen by &c" + player.getName()));
Bukkit.broadcastMessage("");
}
} else if (team.getName().equalsIgnoreCase("blue")) {
if (redStolen) return;
redStolen = true;
if (loc.distanceSquared(getMap().getRedFlag()) < 2.5) {
Bukkit.broadcastMessage("");
Bukkit.broadcastMessage(ChatUtil.format("Flag Stolen > &cRed Flag &7was stolen by &9" + player.getName()));
Bukkit.broadcastMessage("");
}
}
}
}
<file_sep>/src/us/capturecore/core/common/lobby/LobbyHandler.java
package us.capturecore.core.common.lobby;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.SkullMeta;
import us.capturecore.core.Main;
import us.capturecore.core.commands.admin.AoCommand;
import us.capturecore.core.common.player.CCPlayer;
import us.capturecore.core.common.player.rank.Rank;
import us.capturecore.core.util.menu.ItemStackBuilder;
import us.capturecore.core.util.text.ChatUtil;
import java.util.Arrays;
public class LobbyHandler implements Listener {
private Location lobbyLocation;
public Location getLobbyLocation() {
if (lobbyLocation == null) {
ConfigurationSection loc = Main.getInstance().getConfig().getConfigurationSection("lobby-location");
lobbyLocation = new Location(Bukkit.getWorld(loc.getString("world")),
loc.getDouble("x"), loc.getDouble("y"), loc.getDouble("z"),
(float) loc.getDouble("yaw"), (float) loc.getDouble("pitch"));
}
return lobbyLocation;
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
CCPlayer player = new CCPlayer(event.getPlayer());
event.setJoinMessage(null);
if (player.hasAccess(Rank.PREMIUM)) {
event.setJoinMessage(player.getRank().getPrefix() + player.getName() + ChatColor.YELLOW + " joined the lobby!");
player.spigot().setAllowFlight(true);
player.sendMessage(" ");
}
player.spigot().setFoodLevel(20);
player.spigot().setHealth(20);
player.spigot().setLevel(player.getLevel());
player.spigot().setExp((player.getExperience() % 5000) / 5000);
player.teleport(getLobbyLocation());
PlayerInventory inv = player.getInventory();
inv.clear();
inv.setItem(1, new ItemStackBuilder(Material.NETHER_STAR).withName("&bPlay a Game &7(Right Click)")
.withLore("Click to open game selection menu.").build());
inv.setItem(7, new ItemStackBuilder(Material.INK_SACK).withName("&fPlayers: &aVISIBLE &7(Click to Toggle)")
.withLore("Click to toggle player visibility to &cHIDDEN&7.").withData(10));
ItemStack profile = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
SkullMeta meta = (SkullMeta) profile.getItemMeta();
meta.setOwner(player.getName());
meta.setDisplayName(ChatUtil.format("&aMy Profile Menu &7(Right Click)"));
meta.setLore(Arrays.asList(new String[] {ChatUtil.format("&7Click to open your profile menu.")}));
profile.setItemMeta(meta);
inv.setItem(8, profile);
}
@EventHandler
public void onLeave(PlayerQuitEvent event) {
event.setQuitMessage(null);
}
@EventHandler
public void onInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
Action a = event.getAction();
ItemStack icon = event.getItem();
if (icon == null) return;
if (icon.getItemMeta().getDisplayName() == null) return;
if (icon.getType().equals(Material.INK_SACK) && icon.getItemMeta().getDisplayName().contains("VISIBLE")) {
player.getInventory().setItem(7, new ItemStackBuilder(Material.INK_SACK)
.withName("&fPlayers: &cHIDDEN &7(Click to Toggle)")
.withLore("Click to toggle player visibility to &aVISIBLE&7.").withData(8));
for (Player p : Bukkit.getOnlinePlayers()) {
CCPlayer ccp = new CCPlayer(p);
if (!ccp.hasAccess(Rank.TWITCH)) player.hidePlayer(p);
}
}
if (icon.getType().equals(Material.INK_SACK) && icon.getItemMeta().getDisplayName().contains("HIDDEN")) {
player.getInventory().setItem(7, new ItemStackBuilder(Material.INK_SACK)
.withName("&fPlayers: &aVISIBLE &7(Click to Toggle)")
.withLore("Click to toggle player visibility to &cHIDDEN&7.").withData(10));
for (Player p : Bukkit.getOnlinePlayers())
player.showPlayer(p);
}
if (icon.getType().equals(Material.NETHER_STAR) && icon.getItemMeta().getDisplayName().contains("Play a Game")) {
player.performCommand("play");
}
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked();
if (AoCommand.hasOverride(player)) return;
event.setCancelled(true);
}
@EventHandler
public void onBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
if (AoCommand.hasOverride(player)) return;
event.setCancelled(true);
}
@EventHandler
public void onPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
if (AoCommand.hasOverride(player)) return;
event.setCancelled(true);
}
@EventHandler
public void onHunger(FoodLevelChangeEvent event) {
event.setFoodLevel(20);
event.setCancelled(true);
}
@EventHandler
public void onDropItem(PlayerDropItemEvent event) {
Player player = event.getPlayer();
if (AoCommand.hasOverride(player)) return;
event.setCancelled(true);
}
@EventHandler
public void onPickupItem(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
if (AoCommand.hasOverride(player)) return;
event.setCancelled(true);
}
@EventHandler
public void onDamage(EntityDamageEvent event) {
if (!(event.getEntity() instanceof Player)) return;
event.setCancelled(true);
}
@EventHandler
public void onPainting(PaintingBreakByEntityEvent event) {
if (!(event.getRemover() instanceof Player)) {
event.setCancelled(true);
return;
}
Player player = (Player) event.getRemover();
if (!AoCommand.hasOverride(player)) {
event.setCancelled(true);
return;
}
}
@EventHandler
public void onEntityDamager(EntityDamageByEntityEvent event) {
event.setCancelled(true);
}
@EventHandler
public void onTest(PlayerToggleSneakEvent event) {
CCPlayer player = new CCPlayer(event.getPlayer());
if (!event.isSneaking()) return;
}
}
<file_sep>/src/us/capturecore/core/util/EntityUtil.java
package us.capturecore.core.util;
import net.minecraft.server.v1_8_R3.NBTTagCompound;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
public class EntityUtil {
public static void disableAI(Entity entity) {
net.minecraft.server.v1_8_R3.Entity nmsEnt = ((CraftEntity) entity).getHandle();
NBTTagCompound tag = nmsEnt.getNBTTag();
if(tag == null) {
tag = new NBTTagCompound();
}
nmsEnt.c(tag);
tag.setInt("NoAI", 1);
nmsEnt.f(tag);
}
public static Entity spawnEntity(Location location, EntityType type) {
return location.getWorld().spawnEntity(location, type);
}
}
<file_sep>/src/us/capturecore/core/util/NametagUtil.java
package us.capturecore.core.util;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import us.capturecore.core.common.player.rank.Rank;
public class NametagUtil {
private static boolean ranksInit = false;
private static Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
public static void initializeRanks() {
for (Rank rank : Rank.values()) {
if (scoreboard.getTeam(rank.getFormalName()) == null) {
Team team = scoreboard.registerNewTeam(rank.getFormalName());
team.setPrefix(rank.getPrefix());
}
}
ranksInit = true;
}
public static void setNametag(Player player, Rank rank) {
if (!ranksInit) return;
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "scoreboard teams join " +
rank.getFormalName() + " " + player.getName());
}
public static void setNametag(Player player, String teamName, String prefix, String suffix) {
if (scoreboard.getTeam(teamName) == null) {
Team team = scoreboard.registerNewTeam(teamName);
team.setPrefix(prefix);
team.setSuffix(suffix);
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "scoreboard teams join " +
teamName + " " + player.getName());
}
}
<file_sep>/src/us/capturecore/core/util/LocationUtil.java
package us.capturecore.core.util;
import org.bukkit.Location;
public class LocationUtil {
public static double getDistanceBetween(Location loc1, Location loc2) {
return loc1.distance(loc2);
}
public static boolean isWithinRange(Location loc1, Location loc2, double radius) {
return getDistanceBetween(loc1, loc2) <= radius;
}
}
<file_sep>/src/us/capturecore/core/common/game/data/upgrades/SoloUpgrade.java
package us.capturecore.core.common.game.data.upgrades;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import us.capturecore.core.common.player.CCPlayer;
public interface SoloUpgrade {
static String getName() {
return "Solo Upgrade";
}
static int getCost() {
return 10;
}
static UpgradeCurrenty getCurrency() {
return UpgradeCurrenty.IRON;
}
static Material getIconType() {
return Material.STONE;
}
static void give(Player player) {
give(new CCPlayer(player));
}
static void give(CCPlayer player) {
if (!player.getInventory().contains(getCurrency().getMaterial(), getCost())) {
player.sendMessage("&cYou do not have enough " + getCurrency().getName() + " (" + getCost() + ") for this.");
player.playSound(Sound.NOTE_BASS_DRUM);
return;
}
player.getInventory().addItem(new ItemStack(getIconType()));
player.sendMessage("&aYou purchased &6" + getName() + "&a!");
player.playSound(Sound.NOTE_PIANO);
}
}
<file_sep>/src/us/capturecore/core/util/text/TabTitleManager.java
package us.capturecore.core.util.text;
import net.minecraft.server.v1_8_R3.IChatBaseComponent;
import net.minecraft.server.v1_8_R3.PacketPlayOutPlayerListHeaderFooter;
import net.minecraft.server.v1_8_R3.PlayerConnection;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.craftbukkit.v1_8_R3.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.scheduler.BukkitRunnable;
import us.capturecore.core.Main;
import us.capturecore.core.event.ServerStartEvent;
import java.lang.reflect.Field;
public class TabTitleManager implements Listener {
public static void sendPlayerListTab(Player player, String header, String footer) {
CraftPlayer craftplayer = (CraftPlayer)player;
PlayerConnection connection =
craftplayer.getHandle().playerConnection;
IChatBaseComponent hj = IChatBaseComponent.ChatSerializer.a(ChatColor.translateAlternateColorCodes('&', "{\"text\": \"" + header + "\"}"));
IChatBaseComponent fj = IChatBaseComponent.ChatSerializer.a(ChatColor.translateAlternateColorCodes('&', "{\"text\": \"" + footer + "\"}"));
PacketPlayOutPlayerListHeaderFooter packet = new PacketPlayOutPlayerListHeaderFooter();
try
{
Field headerField = packet.getClass().getDeclaredField("a");
headerField.setAccessible(true);
headerField.set(packet, hj);
headerField.setAccessible(!headerField.isAccessible());
Field footerField = packet.getClass().getDeclaredField("b");
footerField.setAccessible(true);
footerField.set(packet, fj);
footerField.setAccessible(!footerField.isAccessible());
}
catch (Exception localException) {}
connection.sendPacket(packet);
}
@EventHandler
public void onStart(ServerStartEvent event) {
new BukkitRunnable() {
int index = 0;
String[] frames = new String[] {
"&3Discord @ &b&ldiscord.capturecore.us", "&eDonate @ &6&lstore.capturecore.us"
};
@Override
public void run() {
if (index >= frames.length) index = 0;
String frame = frames[index];
for (Player player : Bukkit.getOnlinePlayers())
sendPlayerListTab(player, "&f&m+------&r &9&lCAPTURE&c&lCORE &f&m------+", frame);
index++;
}
}.runTaskTimer(Main.getInstance(), 20, 100);
}
}<file_sep>/src/us/capturecore/core/common/game/data/upgrades/UpgradeCurrenty.java
package us.capturecore.core.common.game.data.upgrades;
import org.bukkit.ChatColor;
import org.bukkit.Material;
public enum UpgradeCurrenty {
IRON("Iron", ChatColor.WHITE, Material.IRON_INGOT),
GOLD("Gold", ChatColor.GOLD, Material.GOLD_INGOT),
DIAMOND("Diamond", ChatColor.AQUA, Material.DIAMOND),
EMERALD("Emerald", ChatColor.GREEN, Material.EMERALD);
private String name;
private ChatColor color;
private Material material;
UpgradeCurrenty(String name, ChatColor color, Material material) {
this.name = name;
this.color = color;
this.material = material;
}
public String getName() {
return name;
}
public ChatColor getColor() {
return color;
}
public Material getMaterial() {
return material;
}
}
<file_sep>/src/us/capturecore/core/commands/admin/SetcoinsCommand.java
package us.capturecore.core.commands.admin;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import us.capturecore.core.Main;
import us.capturecore.core.common.player.CCPlayer;
import us.capturecore.core.common.player.rank.Rank;
import us.capturecore.core.util.text.ChatUtil;
import java.util.UUID;
public class SetcoinsCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) {
if (s instanceof Player) {
CCPlayer player = new CCPlayer((Player) s);
if (!player.hasAccess(Rank.ADMIN)) {
player.sendMessage("&cYou are not allowed to do this!");
return false;
}
}
if (args.length < 2) {
s.sendMessage(ChatUtil.format("&cUsage: /setcoins <player> <(+/-)amount>"));
return false;
} else if (args.length == 2) {
String name = args[0];
String amount = args[1];
UUID uuid = Bukkit.getOfflinePlayer(name).getUniqueId();
if (!Main.getCurrencyManager().isInitialized(uuid)) {
Main.getCurrencyManager().initializeCrowns(uuid);
s.sendMessage(ChatUtil.format("&7Initializing currency data..."));
}
int value;
try {
value = Integer.valueOf(amount);
} catch (Exception e) {
s.sendMessage(ChatUtil.format("&cCurrency amounts are numerical."));
s.sendMessage(ChatUtil.format("&cUsage: /setcoins <player> <(+/-)amount>"));
return false;
}
String sender = "&c[CONSOLE]";
if (s instanceof Player) sender = new CCPlayer((Player) s).getFormattedName();
CCPlayer player = new CCPlayer(uuid);
if (amount.startsWith("+")) {
player.giveCoins(value);
s.sendMessage(ChatUtil.format("&7You gave &6" + value + "&lC &7to " + player.getFormattedName()));
if (player.isOnline()) player.sendMessage(sender + " &eadded &6" + value + "&lC &eto your balance.");
} else if (amount.startsWith("-")) {
if (value > player.getCrowns()) Main.getCurrencyManager().setCrowns(uuid, 0);
Main.getCurrencyManager().setCrowns(uuid, player.getCrowns() - value);
s.sendMessage(ChatUtil.format("&7You took &6" + value + "&lC &7from " + player.getFormattedName()));
if (player.isOnline()) player.sendMessage(sender + " &etook &6" + value + "&lC &efrom your balance.");
} else {
Main.getCurrencyManager().setCrowns(uuid, value);
s.sendMessage(ChatUtil.format("&7You set " + player.getFormattedName() + "&7's crowns to &6" + value + "&lC"));
if (player.isOnline()) player.sendMessage(sender + " &eset your crowns to &6" + value + "&lC");
}
}
return false;
}
}
<file_sep>/src/us/capturecore/core/commands/admin/ChestgiantCommand.java
package us.capturecore.core.commands.admin;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Giant;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import us.capturecore.core.common.player.CCPlayer;
import us.capturecore.core.common.player.rank.Rank;
import us.capturecore.core.util.EntityUtil;
import us.capturecore.core.util.text.ChatUtil;
public class ChestgiantCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) {
if (!(s instanceof Player)) {
s.sendMessage(ChatUtil.format("&cYou must be a player to do this!"));
return false;
}
CCPlayer player = new CCPlayer((Player) s);
if (!player.hasAccess(Rank.ADMIN)) {
player.sendMessage("&cYou are not allowed to do this!");
return false;
}
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, (byte) 3);
SkullMeta meta = (SkullMeta) skull.getItemMeta();
meta.setOwner("1pozo1");
skull.setItemMeta(meta);
if (player.getName().equalsIgnoreCase("Araos")) {
if (player.hasAccess(Rank.ADMIN)) {
Giant giant = (Giant) EntityUtil.spawnEntity(player.getLocation(), EntityType.GIANT);
EntityUtil.disableAI(giant);
Location newLoc = player.getLocation().clone().subtract(3.35, 3, 1.35);
newLoc.setYaw(-45F);
Giant chest = (Giant) EntityUtil.spawnEntity(newLoc, EntityType.GIANT);
chest.getEquipment().setItemInHand(skull);
chest.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 1000000, 100000));
EntityUtil.disableAI(chest);
//giant.setCustomName("Dinnerbone");
Minecart minecart = (Minecart) EntityUtil.spawnEntity(player.getLocation(), EntityType.MINECART);
minecart.setPassenger(giant);
}
}
player.sendMessage("&7You have spawned &2[CHEST GIANT] &7at your location.");
return false;
}
}
<file_sep>/src/us/capturecore/core/commands/admin/SetxpCommand.java
package us.capturecore.core.commands.admin;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import us.capturecore.core.Main;
import us.capturecore.core.common.player.CCPlayer;
import us.capturecore.core.common.player.rank.Rank;
import us.capturecore.core.util.text.ChatUtil;
import java.util.UUID;
public class SetxpCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) {
if (s instanceof Player) {
CCPlayer player = new CCPlayer((Player) s);
if (!player.hasAccess(Rank.ADMIN)) {
player.sendMessage("&cYou are not allowed to do this!");
return false;
}
}
if (args.length < 2) {
s.sendMessage(ChatUtil.format("&cUsage: /setxp <player> <(+/-)amount(L)>"));
return false;
} else if (args.length == 2) {
String name = args[0];
String amount = args[1];
UUID uuid = Bukkit.getOfflinePlayer(name).getUniqueId();
if (!Main.getCurrencyManager().isInitialized(uuid)) {
Main.getCurrencyManager().initializeCrowns(uuid);
s.sendMessage(ChatUtil.format("&7Initializing experience data..."));
}
int value;
boolean level = false;
if (amount.contains("L") || amount.contains("l")) {
level = true;
amount = amount.replace("L", "").replace("l", "");
}
try {
value = Integer.valueOf(amount);
} catch (Exception e) {
s.sendMessage(ChatUtil.format("&cExperience amounts are numerical."));
s.sendMessage(ChatUtil.format("&cUsage: /setxp <player> <(+/-)amount>"));
return false;
}
String sender = "&c[CONSOLE]";
if (s instanceof Player) sender = new CCPlayer((Player) s).getFormattedName();
CCPlayer player = new CCPlayer(uuid);
if (!level) {
if (amount.startsWith("+")) {
player.giveExperience(value);
s.sendMessage(ChatUtil.format("&7You gave &b" + value + " XP &7to " + player.getFormattedName()));
if (player.isOnline())
player.sendMessage(sender + " &eadded &b" + value + " XP &eto your profile.");
} else if (amount.startsWith("-")) {
if (value > player.getCrowns()) Main.getExperienceManager().setExperience(uuid, 0);
Main.getExperienceManager().setExperience(uuid, player.getExperience() - value);
s.sendMessage(ChatUtil.format("&7You took &b" + value + " XP &7from " + player.getFormattedName()));
if (player.isOnline())
player.sendMessage(sender + " &etook &b" + value + " XP &efrom your profile.");
} else {
Main.getExperienceManager().setExperience(uuid, value);
s.sendMessage(ChatUtil.format("&7You set " + player.getFormattedName() + "&7's experience to &b" + value + " XP&7."));
if (player.isOnline())
player.sendMessage(sender + " &eset your experience to &b" + value + " XP&e.");
}
} else {
value = value * 5000;
if (amount.startsWith("+")) {
player.giveExperience(value);
} else if (amount.startsWith("-")) {
if (value > player.getCrowns()) Main.getExperienceManager().setExperience(uuid, 0);
Main.getExperienceManager().setExperience(uuid, player.getExperience() - value);
} else {
Main.getExperienceManager().setExperience(uuid, value - 5000);
}
s.sendMessage(ChatUtil.format("&7" + player.getFormattedName() + " &7is now lvl. " + player.getLevelFormat()));
if (player.isOnline()) player.sendMessage(sender + " &eset you to lvl. " + player.getLevelFormat());
}
if (player.isOnline()) {
player.spigot().setLevel(player.getLevel());
player.spigot().setExp((player.getExperience() % 5000) / 5000);
}
}
return false;
}
}
<file_sep>/src/us/capturecore/core/commands/admin/AoCommand.java
package us.capturecore.core.commands.admin;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.scheduler.BukkitRunnable;
import us.capturecore.core.Main;
import us.capturecore.core.common.player.CCPlayer;
import us.capturecore.core.common.player.rank.Rank;
import us.capturecore.core.event.ServerStartEvent;
import us.capturecore.core.util.SQL;
import us.capturecore.core.util.text.ActionBar;
import us.capturecore.core.util.text.ChatUtil;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class AoCommand implements CommandExecutor, Listener {
public static void initialize() {
Main.getInstance().getServer().getPluginManager().registerEvents(new AoCommand(), Main.getInstance());
startHUDs();
if (SQL.tableExists("ao_toggle")) return;
SQL.createTable( "ao_toggle",
SQL.stringsToStringArray( "uuid", "text" ),
SQL.stringsToStringArray( "status", "boolean" ));
}
private static void setupPlayer(UUID uuid) {
if (isSetup(uuid)) return;
SQL.insertInto("ao_toggle",
new String[] {"uuid", "status"},
new String[] {uuid.toString(), "0"});
}
private static boolean isSetup(UUID uuid) {
return SQL.recordExists("ao_toggle", "uuid = " + SQL.quote(uuid.toString()));
}
public static boolean hasOverride(Player player) {
if (!isSetup(player.getUniqueId())) {
setupPlayer(player.getUniqueId());
return false;
}
String query = "SELECT * FROM ao_toggle WHERE uuid = " + SQL.quote(player.getUniqueId().toString());
ResultSet rs = SQL.execute(query);
try {
while (rs.next()) {
return rs.getBoolean("status");
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
public static void setStatus(Player player, boolean status) {
if (!isSetup(player.getUniqueId())) {
setupPlayer(player.getUniqueId());
}
int statusIndex = 0;
if (status) {
statusIndex = 1;
overrides.add(player);
} else {
overrides.remove(player);
}
String query = "UPDATE ao_toggle SET status = " + statusIndex +
" WHERE uuid = " + SQL.quote(player.getUniqueId().toString());
SQL.execute(query);
}
@Override
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) {
if (!(s instanceof Player)) {
s.sendMessage(ChatUtil.format("&cYou must be a player to do this!"));
return false;
}
CCPlayer player = new CCPlayer((Player) s);
if (!player.hasAccess(Rank.ADMIN)) {
player.sendMessage("You are not allowed to do this!");
return false;
}
if (args.length == 0) {
boolean status = !hasOverride(player.spigot());
setStatus(player.spigot(), status);
if (status) {
player.sendMessage("&eYou have enabled &c[Admin Override]&e. You will now bypass server restrictions.");
} else {
player.sendMessage("&eYou have disabled &c[Admin Override]&e. You will no longer bypass server restrictions.");
}
}
return false;
}
private static List<Player> overrides = new ArrayList<>();
private static void startHUDs() {
new BukkitRunnable() {
@Override
public void run() {
for (Player player : overrides)
ActionBar.sendActionBarMessage(player, "&eYou're in &c[Admin Override] &emode.");
}
}.runTaskTimer(Main.getInstance(), 20, 20);
}
@EventHandler
public void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
if (hasOverride(player) && !overrides.contains(player)) overrides.add(player);
}
@EventHandler
public void onLeave(PlayerQuitEvent event) {
Player player = event.getPlayer();
if (overrides.contains(player)) overrides.remove(player);
}
@EventHandler
public void onStart(ServerStartEvent event) {
for (Player p : Bukkit.getOnlinePlayers()) {
if (hasOverride(p)) overrides.add(p);
}
}
}
<file_sep>/src/us/capturecore/core/commands/CommandManager.java
package us.capturecore.core.commands;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import us.capturecore.core.common.player.CCPlayer;
import java.util.*;
public class CommandManager {
private String name;
private Map<String, String> commands = new HashMap<>();
public CommandManager(String baseCommandName) {
this.name = baseCommandName;
}
public String getName() {
return name;
}
public Map<String, String> getCommandData() {
return commands;
}
public String getDescription(String command) {
return getCommandData().get(command);
}
public boolean isRegistered(String command) {
return getCommandData().containsKey(command);
}
public List<String> getCommands() {
List<String> cmds = new ArrayList<>();
for (String cmd : commands.keySet())
cmds.add(cmd);
return cmds;
}
public List<String> getCommandInterface(int page) {
List<String> cmdList = new ArrayList<>();
int pages = getCommands().size() / 10;
int beginIndex = page * 10;
int endIndex = beginIndex + 10;
if (getCommands().size() < endIndex) endIndex = getCommands().size();
cmdList.add("&6----------------------------------------------------");
cmdList.add("&a" + getName() + " Commands (Page " + (page + 1) + "/" + (pages + 1) + "):");
for (String cmd : getCommands().subList(beginIndex, endIndex))
cmdList.add("&e/" + cmd + " &7- &b" + getDescription(cmd));
cmdList.add("&6----------------------------------------------------");
return cmdList;
}
public void sendInterface(CommandSender sender) {
for (String line : getCommandInterface(0))
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', line));
}
public void register(String command, String description) {
commands.put(command, description);
}
}
<file_sep>/src/us/capturecore/core/commands/general/ingame/ShopCommand.java
package us.capturecore.core.commands.general.ingame;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import us.capturecore.core.Main;
import us.capturecore.core.common.game.gameutil.ShopMenu;
import us.capturecore.core.common.player.CCPlayer;
import us.capturecore.core.common.player.rank.Rank;
import us.capturecore.core.util.text.ChatUtil;
public class ShopCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender s, Command cmd, String label, String[] args) {
if (s instanceof Player) {
CCPlayer player = new CCPlayer((Player) s);
if (!player.hasAccess(Rank.ADMIN)) {
player.sendMessage("&cYou are not allowed to do this!");
return false;
}
}
if (!Main.getServerType().equalsIgnoreCase("game")) {
s.sendMessage(ChatUtil.format("&cYou can only perform this command on a game server."));
}
if (args.length == 0) {
s.sendMessage(ChatUtil.format("&cUsage: /shop <Player> <Solo/Team>"));
return false;
} else if (args.length == 1) {
s.sendMessage(ChatUtil.format("&cUsage: /shop <Player> <Solo/Team>"));
return false;
} else if (args.length == 2) {
String target = args[0];
String type = args[1];
if (type.equalsIgnoreCase("solo") || type.equalsIgnoreCase("team")) {
if (!Bukkit.getOfflinePlayer(target).isOnline()) {
s.sendMessage(ChatUtil.format("&cThat player is not online!"));
return false;
}
Player player = Bukkit.getPlayer(target);
if (type.equalsIgnoreCase("solo")) {
ShopMenu.getArcheryTab().display(player);
} else if (type.equalsIgnoreCase("team")) {
s.sendMessage(ChatUtil.format("&cWork in progress."));
}
} else {
s.sendMessage(ChatUtil.format("&cInvalid shop type. Expected [Solo/Team]."));
}
} else {
s.sendMessage(ChatUtil.format("&cUsage: /shop <Player> <Solo/Team>"));
return false;
}
return false;
}
}
<file_sep>/src/us/capturecore/core/event/ServerStopEvent.java
package us.capturecore.core.event;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.java.JavaPlugin;
/** Copyright (C) CaptureCore, Inc - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Written by <NAME> <<EMAIL>>, June 2018
*/
public class ServerStopEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private JavaPlugin plugin;
/**
* Called within the onDisable method.
* @param plugin The plugin that was enabled.
*/
public ServerStopEvent(JavaPlugin plugin) {
this.plugin = plugin;
}
public JavaPlugin getPlugin() {
return plugin;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}<file_sep>/src/us/capturecore/core/common/game/data/upgrades/player/ChainArmorUpgrade.java
package us.capturecore.core.common.game.data.upgrades.player;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import us.capturecore.core.common.game.data.upgrades.SoloUpgrade;
import us.capturecore.core.common.game.data.upgrades.UpgradeCurrenty;
import us.capturecore.core.common.player.CCPlayer;
public class ChainArmorUpgrade implements SoloUpgrade {
public static String getName() {
return "Chainmail Armor";
}
public static int getCost() {
return 40;
}
public static UpgradeCurrenty getCurrency() {
return UpgradeCurrenty.IRON;
}
public static Material getIconType() {
return Material.CHAINMAIL_CHESTPLATE;
}
public static void give(CCPlayer player) {
player.getInventory().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS));
player.getInventory().setBoots(new ItemStack(Material.CHAINMAIL_BOOTS));
}
}
| 97ea8096d22813ebd930a3001f50ba518e5fb7c0 | [
"Java"
] | 18 | Java | addisonhellum/CaptureCore | e8a9e4646538804cd47bf12961809346ba6d49ae | 0d339087b5d70b9e6994dbb8497708f4d2bdbc44 |
refs/heads/master | <repo_name>styladev/npm-quilldto-to-html<file_sep>/QuillDeltaToHtmlConverter.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const str = {
/**
* Splits by new line character ("\n") by putting new line characters into the
* array as well. Ex: "hello\n\nworld\n " => ["hello", "\n", "\n", "world", "\n", " "]
*/
tokenizeWithNewLines(str) {
const NewLine = "\n";
if (str === NewLine) {
return [str];
}
var lines = str.split(NewLine);
if (lines.length === 1) {
return lines;
}
var lastIndex = lines.length - 1;
return lines.reduce((pv, line, ind) => {
if (ind !== lastIndex) {
if (line !== "") {
pv = pv.concat(line, NewLine);
}
else {
pv.push(NewLine);
}
}
else if (line !== "") {
pv.push(line);
}
return pv;
}, []);
}
};
class InsertOpDenormalizer {
static denormalize(op) {
if (!op || typeof op !== 'object') {
return [];
}
if (typeof op.insert === 'object' || op.insert === NewLine) {
return [op];
}
let newlinedArray = str.tokenizeWithNewLines(op.insert + '');
if (newlinedArray.length === 1) {
return [op];
}
let nlObj = obj.assign({}, op, { insert: NewLine });
return newlinedArray.map((line) => {
if (line === NewLine) {
return nlObj;
}
return obj.assign({}, op, {
insert: line
});
});
}
}
class InsertOpsConverter {
static convert(deltaOps) {
if (!Array.isArray(deltaOps)) {
return [];
}
var denormalizedOps = [].concat.apply([], deltaOps.map(InsertOpDenormalizer.denormalize));
var results = [];
var insertVal, attributes;
for (var op of denormalizedOps) {
if (!op.insert) {
continue;
}
insertVal = InsertOpsConverter.convertInsertVal(op.insert);
if (!insertVal) {
continue;
}
attributes = OpAttributeSanitizer.sanitize(op.attributes);
results.push(new DeltaInsertOp(insertVal, attributes));
}
return results;
}
static convertInsertVal(insertPropVal) {
if (typeof insertPropVal === 'string') {
return new InsertDataQuill(DataType.Text, insertPropVal);
}
if (!insertPropVal || typeof insertPropVal !== 'object') {
return null;
}
let keys = Object.keys(insertPropVal);
if (!keys.length) {
return null;
}
return DataType.Image in insertPropVal ?
new InsertDataQuill(DataType.Image, insertPropVal[DataType.Image])
: DataType.Video in insertPropVal ?
new InsertDataQuill(DataType.Video, insertPropVal[DataType.Video])
: DataType.Formula in insertPropVal ?
new InsertDataQuill(DataType.Formula, insertPropVal[DataType.Formula])
// custom
: new InsertDataCustom(keys[0], insertPropVal[keys[0]]);
}
}
const NewLine = "\n";
var ListType;
(function (ListType) {
ListType["Ordered"] = "ordered";
ListType["Bullet"] = "bullet";
ListType["Checked"] = "checked";
ListType["Unchecked"] = "unchecked";
})(ListType || (ListType = {}));
var ScriptType;
(function (ScriptType) {
ScriptType["Sub"] = "sub";
ScriptType["Super"] = "super";
})(ScriptType || (ScriptType = {}));
var DirectionType;
(function (DirectionType) {
DirectionType["Rtl"] = "rtl";
})(DirectionType || (DirectionType = {}));
var AlignType;
(function (AlignType) {
AlignType["Center"] = "center";
AlignType["Right"] = "right";
AlignType["Justify"] = "justify";
})(AlignType || (AlignType = {}));
var DataType;
(function (DataType) {
DataType["Image"] = "image";
DataType["Video"] = "video";
DataType["Formula"] = "formula";
DataType["Text"] = "text";
})(DataType || (DataType = {}));
;
class InsertDataQuill {
constructor(type, value) {
this.type = type;
this.value = value;
}
}
;
class InsertDataCustom {
constructor(type, value) {
this.type = type;
this.value = value;
}
}
;
;
const arr = {
preferSecond(arr) {
if (arr.length === 0) {
return null;
}
return arr.length >= 2 ? arr[1] : arr[0];
},
flatten(arr) {
return arr.reduce((pv, v) => {
return pv.concat(Array.isArray(v) ? flatten(v) : v);
}, []);
}
};
const DEFAULT_INLINE_FONTS = {
serif: 'font-family: Georgia, Times New Roman, serif',
monospace: 'font-family: Monaco, Courier New, monospace'
};
const DEFAULT_FONT_SIZE_STYLES = {
small: 'font-size: 0.75em',
large: 'font-size: 1.5em',
huge: 'font-size: 2.5em'
};
const DEFAULT_INLINE_STYLES = {
lineheight: (value) => 'line-height:' + value,
fontFamily: (value) => 'font-family:' + value.replace(/"/g, '"'),
font: (value) => DEFAULT_INLINE_FONTS[value] || ('font-family:' + value),
size: (value) => DEFAULT_FONT_SIZE_STYLES[value] || ('font-size:' + value),
indent: (value, op) => {
var indentSize = parseInt(value, 10) * 3;
var side = op.attributes['direction'] === 'rtl' ? 'right' : 'left';
return 'padding-' + side + ':' + indentSize + 'em';
},
direction: (value, op) => {
if (value === 'rtl') {
return 'direction:rtl' + (op.attributes['align'] ? '' : '; text-align:inherit');
}
else {
return undefined;
}
}
};
const url = {
sanitize(str) {
return str.replace(/^\s*/gm, '');
},
encodeLink(str) {
let linkMaps = encodeMappings(EncodeTarget.Url);
let decoded = linkMaps.reduce(decodeMapping, str);
return linkMaps.reduce(encodeMapping, decoded);
}
};
class MentionSanitizer {
static sanitize(dirtyObj) {
var cleanObj = {};
if (!dirtyObj || typeof dirtyObj !== 'object') {
return cleanObj;
}
if (dirtyObj.class && MentionSanitizer.IsValidClass(dirtyObj.class)) {
cleanObj.class = dirtyObj.class;
}
if (dirtyObj.id && MentionSanitizer.IsValidId(dirtyObj.id)) {
cleanObj.id = dirtyObj.id;
}
if (MentionSanitizer.IsValidTarget(dirtyObj.target + '')) {
cleanObj.target = dirtyObj.target;
}
if (dirtyObj.avatar) {
cleanObj.avatar = url.sanitize(dirtyObj.avatar + '');
}
if (dirtyObj['end-point']) {
cleanObj['end-point'] = url.sanitize(dirtyObj['end-point'] + '');
}
if (dirtyObj.slug) {
cleanObj.slug = (dirtyObj.slug + '');
}
return cleanObj;
}
static IsValidClass(classAttr) {
return !!classAttr.match(/^[a-zA-Z0-9_\-]{1,500}$/i);
}
static IsValidId(idAttr) {
return !!idAttr.match(/^[a-zA-Z0-9_\-\:\.]{1,500}$/i);
}
static IsValidTarget(target) {
return ['_self', '_blank', '_parent', '_top'].indexOf(target) > -1;
}
}
class OpAttributeSanitizer {
static sanitize(dirtyAttrs) {
var cleanAttrs = {};
if (!dirtyAttrs || typeof dirtyAttrs !== 'object') {
return cleanAttrs;
}
let booleanAttrs = [
'bold', 'italic', 'underline', 'strike', 'code',
'blockquote', 'code-block', 'renderAsBlock'
];
let colorAttrs = ['background', 'color'];
let { font, size, link, script, list, header, align, direction, indent, mentions, mention, width, target } = dirtyAttrs;
let sanitizedAttrs = [...booleanAttrs, ...colorAttrs,
'font', 'size', 'link', 'script', 'list', 'header', 'align',
'direction', 'indent', 'mentions', 'mention', 'width'
];
booleanAttrs.forEach(function (prop) {
var v = dirtyAttrs[prop];
if (v) {
cleanAttrs[prop] = !!v;
}
});
colorAttrs.forEach(function (prop) {
var val = dirtyAttrs[prop];
if (val && (OpAttributeSanitizer.IsValidHexColor(val + '') ||
OpAttributeSanitizer.IsValidColorLiteral(val + '') ||
OpAttributeSanitizer.IsValidRGBColor(val + ''))) {
cleanAttrs[prop] = val;
}
});
if (font && OpAttributeSanitizer.IsValidFontName(font + '')) {
cleanAttrs.font = font;
}
if (size && OpAttributeSanitizer.IsValidSize(size + '')) {
cleanAttrs.size = size;
}
if (width && OpAttributeSanitizer.IsValidWidth(width + '')) {
cleanAttrs.width = width;
}
if (link) {
cleanAttrs.link = url.sanitize(link + '');
}
if (target && OpAttributeSanitizer.isValidTarget(target)) {
cleanAttrs.target = target;
}
if (script === ScriptType.Sub || ScriptType.Super === script) {
cleanAttrs.script = script;
}
if (list === ListType.Bullet || list === ListType.Ordered || list === ListType.Checked || list === ListType.Unchecked) {
cleanAttrs.list = list;
}
if (Number(header)) {
cleanAttrs.header = Math.min(Number(header), 6);
}
if (align === AlignType.Center || align === AlignType.Right || align === AlignType.Justify) {
cleanAttrs.align = align;
}
if (direction === DirectionType.Rtl) {
cleanAttrs.direction = direction;
}
if (indent && Number(indent)) {
cleanAttrs.indent = Math.min(Number(indent), 30);
}
if (mentions && mention) {
let sanitizedMention = MentionSanitizer.sanitize(mention);
if (Object.keys(sanitizedMention).length > 0) {
cleanAttrs.mentions = !!mentions;
cleanAttrs.mention = mention;
}
}
return Object.keys(dirtyAttrs).reduce((cleaned, k) => {
// this is a custom attr, put it back
if (sanitizedAttrs.indexOf(k) === -1) {
cleaned[k] = dirtyAttrs[k];
}
;
return cleaned;
}, cleanAttrs);
}
static IsValidHexColor(colorStr) {
return !!colorStr.match(/^#([0-9A-F]{6}|[0-9A-F]{3})$/i);
}
static IsValidColorLiteral(colorStr) {
return !!colorStr.match(/^[a-z]{1,50}$/i);
}
static IsValidRGBColor(colorStr) {
const re = /^rgb\(((0|25[0-5]|2[0-4]\d|1\d\d|0?\d?\d),\s*){2}(0|25[0-5]|2[0-4]\d|1\d\d|0?\d?\d)\)$/i;
return !!colorStr.match(re);
}
static IsValidFontName(fontName) {
return !!fontName.match(/^[a-z\s0-9\- ]{1,30}$/i);
}
static IsValidSize(size) {
return !!size.match(/^[a-z0-9\-]{1,20}$/i);
}
static IsValidWidth(width) {
return !!width.match(/^[0-9]*(px|em|%)?$/);
}
static isValidTarget(target) {
return !!target.match(/^[_a-zA-Z0-9\-]{1,50}$/);
}
}
class OpToHtmlConverter {
constructor(op, options) {
this.op = op;
this.options = obj.assign({}, {
classPrefix: 'ql',
inlineStyles: undefined,
encodeHtml: true,
listItemTag: 'li',
paragraphTag: 'p'
}, options);
}
prefixClass(className) {
if (!this.options.classPrefix) {
return className + '';
}
return this.options.classPrefix + '-' + className;
}
getHtml() {
var parts = this.getHtmlParts();
return parts.openingTag + parts.content + parts.closingTag;
}
getHtmlParts() {
if (this.op.isJustNewline() && !this.op.isContainerBlock()) {
return { openingTag: '', closingTag: '', content: NewLine };
}
let tags = this.getTags(), attrs = this.getTagAttributes();
if (!tags.length && attrs.length) {
tags.push('span');
}
let beginTags = [], endTags = [];
for (var tag of tags) {
beginTags.push(makeStartTag(tag, attrs));
endTags.push(tag === 'img' ? '' : makeEndTag(tag));
// consumed in first tag
attrs = [];
}
endTags.reverse();
return {
openingTag: beginTags.join(''),
content: this.getContent(),
closingTag: endTags.join('')
};
}
getContent() {
if (this.op.isContainerBlock()) {
return '';
}
if (this.op.isMentions()) {
return this.op.insert.value;
}
var content = this.op.isFormula() || this.op.isText() ? this.op.insert.value : '';
return this.options.encodeHtml && encodeHtml(content) || content;
}
getCssClasses() {
var attrs = this.op.attributes;
if (this.options.inlineStyles) {
return [];
}
var propsArr = ['indent', 'align', 'direction', 'font', 'size'];
if (this.options.allowBackgroundClasses) {
propsArr.push('background');
}
return propsArr
.filter((prop) => !!attrs[prop])
.filter((prop) => prop === 'background' ? OpAttributeSanitizer.IsValidColorLiteral(attrs[prop]) : true)
.map((prop) => prop + '-' + attrs[prop])
.concat(this.op.isFormula() ? 'formula' : [])
.concat(this.op.isVideo() ? 'video' : [])
.concat(this.op.isImage() ? 'image' : [])
.map(this.prefixClass.bind(this));
}
getCssStyles() {
var attrs = this.op.attributes;
var propsArr = [['color'], ['size'], ['lineheight'], ['fontFamily']];
if (!!this.options.inlineStyles || !this.options.allowBackgroundClasses) {
propsArr.push(['background', 'background-color']);
}
if (this.options.inlineStyles) {
propsArr = propsArr.concat([
['indent'],
['align', 'text-align'],
['direction'],
['font', 'font-family'],
]);
}
return propsArr
.filter((item) => !!attrs[item[0]])
.map((item) => {
let attribute = item[0];
let attrValue = attrs[attribute];
let attributeConverter = (this.options.inlineStyles && this.options.inlineStyles[attribute]) ||
DEFAULT_INLINE_STYLES[attribute];
if (typeof (attributeConverter) === 'object') {
return attributeConverter[attrValue];
}
else if (typeof (attributeConverter) === 'function') {
var converterFn = attributeConverter;
return converterFn(attrValue, this.op);
}
else {
return arr.preferSecond(item) + ':' + attrValue;
}
})
.filter((item) => item !== undefined);
}
getTagAttributes() {
if (this.op.attributes.code && !this.op.isLink()) {
return [];
}
const makeAttr = (k, v) => ({ key: k, value: v });
var classes = this.getCssClasses();
var tagAttrs = classes.length ? [makeAttr('class', classes.join(' '))] : [];
if (this.op.isImage()) {
const {width, alt} = this.op.attributes;
if (width) {
tagAttrs = tagAttrs.concat(makeAttr('width', width));
}
if (alt || alt === '') {
tagAttrs = tagAttrs.concat(makeAttr('alt', alt));
}
return tagAttrs.concat(makeAttr('src', url.sanitize(this.op.insert.value + '') + ''));
}
if (this.op.isACheckList()) {
return tagAttrs.concat(makeAttr('data-checked', this.op.isCheckedList() ? 'true' : 'false'));
}
if (this.op.isFormula()) {
return tagAttrs;
}
if (this.op.isVideo()) {
return tagAttrs.concat(makeAttr('frameborder', '0'), makeAttr('allowfullscreen', 'true'), makeAttr('src', url.sanitize(this.op.insert.value + '') + ''));
}
if (this.op.isMentions()) {
var mention = this.op.attributes.mention;
if (mention.class) {
tagAttrs = tagAttrs.concat(makeAttr('class', mention.class));
}
if (mention['end-point'] && mention.slug) {
tagAttrs = tagAttrs.concat(makeAttr('href', url.encodeLink(mention['end-point'] + '/' + mention.slug)));
}
else {
tagAttrs = tagAttrs.concat(makeAttr('href', 'about:blank'));
}
if (mention.target) {
tagAttrs = tagAttrs.concat(makeAttr('target', mention.target));
}
return tagAttrs;
}
var styles = this.getCssStyles();
if (styles.length) {
tagAttrs.push(makeAttr('style', styles.join(';')));
}
if (this.op.isContainerBlock()) {
return tagAttrs;
}
if (this.op.isLink()) {
let target = this.op.attributes.target || this.options.linkTarget;
tagAttrs = tagAttrs
.concat(makeAttr('href', url.encodeLink(this.op.attributes.link)))
.concat(target ? makeAttr('target', target) : []);
if (!!this.options.linkRel && OpToHtmlConverter.IsValidRel(this.options.linkRel)) {
tagAttrs.push(makeAttr('rel', this.options.linkRel));
}
}
return tagAttrs;
}
getTags() {
var attrs = this.op.attributes;
// embeds
if (!this.op.isText()) {
return [this.op.isVideo() ? 'iframe'
: this.op.isImage() ? 'img'
: 'span' // formula
];
}
// blocks
var positionTag = this.options.paragraphTag || 'p';
var blocks = [['blockquote'], ['code-block', 'pre'],
['list', this.options.listItemTag], ['header'],
['align', positionTag], ['direction', positionTag],
['indent', positionTag]];
for (var item of blocks) {
var firstItem = item[0];
if (attrs[firstItem]) {
return firstItem === 'header' ? ['h' + attrs[firstItem]] : [arr.preferSecond(item)];
}
}
// inlines
return [['link', 'a'], ['mentions', 'a'], ['script'],
['bold', 'strong'], ['italic', 'em'], ['strike', 's'], ['underline', 'u'],
['code']]
.filter((item) => !!attrs[item[0]])
.map((item) => {
return item[0] === 'script' ?
(attrs[item[0]] === ScriptType.Sub ? 'sub' : 'sup')
: arr.preferSecond(item);
});
}
static IsValidRel(relStr) {
return !!relStr.match(/^[a-z\s]{1,50}$/i);
}
}
/**
* Returns consecutive list of elements satisfying the predicate starting from startIndex
* and traversing the array in reverse order.
*/
function sliceFromReverseWhile(arr, startIndex, predicate) {
var result = {
elements: [],
sliceStartsAt: -1
};
for (var i = startIndex; i >= 0; i--) {
if (!predicate(arr[i])) {
break;
}
result.sliceStartsAt = i;
result.elements.unshift(arr[i]);
}
return result;
}
;
class Grouper {
static pairOpsWithTheirBlock(ops) {
let result = [];
const canBeInBlock = (op) => {
return !(op.isJustNewline() || op.isCustomBlock() || op.isVideo() || op.isContainerBlock());
};
const isInlineData = (op) => op.isInline();
let lastInd = ops.length - 1;
let opsSlice;
for (var i = lastInd; i >= 0; i--) {
let op = ops[i];
if (op.isVideo()) {
result.push(new VideoItem(op));
}
else if (op.isCustomBlock()) {
result.push(new BlotBlock(op));
}
else if (op.isContainerBlock()) {
opsSlice = sliceFromReverseWhile(ops, i - 1, canBeInBlock);
result.push(new BlockGroup(op, opsSlice.elements));
i = opsSlice.sliceStartsAt > -1 ? opsSlice.sliceStartsAt : i;
}
else {
opsSlice = sliceFromReverseWhile(ops, i - 1, isInlineData);
result.push(new InlineGroup(opsSlice.elements.concat(op)));
i = opsSlice.sliceStartsAt > -1 ? opsSlice.sliceStartsAt : i;
}
}
result.reverse();
return result;
}
static groupConsecutiveSameStyleBlocks(groups, blocksOf = {
header: true,
codeBlocks: true,
blockquotes: true
}) {
return groupConsecutiveElementsWhile(groups, (g, gPrev) => {
if (!(g instanceof BlockGroup) || !(gPrev instanceof BlockGroup)) {
return false;
}
return blocksOf.codeBlocks && Grouper.areBothCodeblocks(g, gPrev)
|| blocksOf.blockquotes && Grouper.areBothBlockquotesWithSameAdi(g, gPrev)
|| blocksOf.header && Grouper.areBothSameHeadersWithSameAdi(g, gPrev);
});
}
// Moves all ops of same style consecutive blocks to the ops of first block
// and discards the rest.
static reduceConsecutiveSameStyleBlocksToOne(groups) {
var newLineOp = DeltaInsertOp.createNewLineOp();
return groups.map(function (elm) {
if (!Array.isArray(elm)) {
if (elm instanceof BlockGroup && !elm.ops.length) {
elm.ops.push(newLineOp);
}
return elm;
}
var groupsLastInd = elm.length - 1;
elm[0].ops = flatten(elm.map((g, i) => {
if (!g.ops.length) {
return [newLineOp];
}
return g.ops.concat(i < groupsLastInd ? [newLineOp] : []);
}));
return elm[0];
});
}
static areBothCodeblocks(g1, gOther) {
return g1.op.isCodeBlock() && gOther.op.isCodeBlock();
}
static areBothSameHeadersWithSameAdi(g1, gOther) {
return g1.op.isSameHeaderAs(gOther.op) && g1.op.hasSameAdiAs(gOther.op);
}
static areBothBlockquotesWithSameAdi(g, gOther) {
return g.op.isBlockquote() && gOther.op.isBlockquote()
&& g.op.hasSameAdiAs(gOther.op);
}
}
class DeltaInsertOp {
constructor(insertVal, attrs) {
if (typeof insertVal === 'string') {
insertVal = new InsertDataQuill(DataType.Text, insertVal + '');
}
this.insert = insertVal;
this.attributes = attrs || {};
}
static createNewLineOp() {
return new DeltaInsertOp(NewLine);
}
isContainerBlock() {
var attrs = this.attributes;
return !!(attrs.blockquote || attrs.list || attrs['code-block'] ||
attrs.header || attrs.align || attrs.direction || attrs.indent);
}
isBlockquote() {
return !!this.attributes.blockquote;
}
isHeader() {
return !!this.attributes.header;
}
isSameHeaderAs(op) {
return op.attributes.header === this.attributes.header && this.isHeader();
}
// adi: alignment direction indentation
hasSameAdiAs(op) {
return this.attributes.align === op.attributes.align
&& this.attributes.direction === op.attributes.direction
&& this.attributes.indent === op.attributes.indent;
}
hasSameIndentationAs(op) {
return this.attributes.indent === op.attributes.indent;
}
hasHigherIndentThan(op) {
return (Number(this.attributes.indent) || 0) > (Number(op.attributes.indent) || 0);
}
isInline() {
return !(this.isContainerBlock() || this.isVideo() || this.isCustomBlock());
}
isCodeBlock() {
return !!this.attributes['code-block'];
}
isJustNewline() {
return this.insert.value === NewLine;
}
isList() {
return (this.isOrderedList() ||
this.isBulletList() ||
this.isCheckedList() ||
this.isUncheckedList());
}
isOrderedList() {
return this.attributes.list === ListType.Ordered;
}
isBulletList() {
return this.attributes.list === ListType.Bullet;
}
isCheckedList() {
return this.attributes.list === ListType.Checked;
}
isUncheckedList() {
return this.attributes.list === ListType.Unchecked;
}
isACheckList() {
return this.attributes.list == ListType.Unchecked ||
this.attributes.list === ListType.Checked;
}
isSameListAs(op) {
return !!op.attributes.list && (this.attributes.list === op.attributes.list ||
op.isACheckList() && this.isACheckList());
}
isText() {
return this.insert.type === DataType.Text;
}
isImage() {
return this.insert.type === DataType.Image;
}
isFormula() {
return this.insert.type === DataType.Formula;
}
isVideo() {
return this.insert.type === DataType.Video;
}
isLink() {
return this.isText() && !!this.attributes.link;
}
isCustom() {
return this.insert instanceof InsertDataCustom;
}
isCustomBlock() {
return this.isCustom() && !!this.attributes.renderAsBlock;
}
isMentions() {
return this.isText() && !!this.attributes.mentions;
}
}
class InlineGroup {
constructor(ops) {
this.ops = ops;
}
}
class SingleItem {
constructor(op) {
this.op = op;
}
}
class VideoItem extends SingleItem {
}
;
class BlotBlock extends SingleItem {
}
;
class BlockGroup {
constructor(op, ops) {
this.op = op;
this.ops = ops;
}
}
class ListGroup {
constructor(items) {
this.items = items;
}
}
class ListItem {
constructor(item, innerList = null) {
this.item = item;
this.innerList = innerList;
}
}
/**
* Returns a new array by putting consecutive elements satisfying predicate into a new
* array and returning others as they are.
* Ex: [1, "ha", 3, "ha", "ha"] => [1, "ha", 3, ["ha", "ha"]]
* where predicate: (v, vprev) => typeof v === typeof vPrev
*/
function groupConsecutiveElementsWhile(arr, predicate) {
var groups = [];
var currElm, currGroup;
for (var i = 0; i < arr.length; i++) {
currElm = arr[i];
if (i > 0 && predicate(currElm, arr[i - 1])) {
currGroup = groups[groups.length - 1];
currGroup.push(currElm);
}
else {
groups.push([currElm]);
}
}
return groups.map((g) => g.length === 1 ? g[0] : g);
}
;
function flatten(arr) {
return arr.reduce((pv, v) => {
return pv.concat(Array.isArray(v) ? flatten(v) : v);
}, []);
}
;
class ListNester {
nest(groups) {
var listBlocked = this.convertListBlocksToListGroups(groups);
var groupedByListGroups = this.groupConsecutiveListGroups(listBlocked);
// convert grouped ones into listgroup
var nested = flatten(groupedByListGroups.map((group) => {
if (!Array.isArray(group)) {
return group;
}
return this.nestListSection(group);
}));
var groupRootLists = groupConsecutiveElementsWhile(nested, (curr, prev) => {
if (!(curr instanceof ListGroup && prev instanceof ListGroup)) {
return false;
}
return curr.items[0].item.op.isSameListAs(prev.items[0].item.op);
});
return groupRootLists.map((v) => {
if (!Array.isArray(v)) {
return v;
}
var litems = v.map((g) => g.items);
return new ListGroup(flatten(litems));
});
}
convertListBlocksToListGroups(items) {
var grouped = groupConsecutiveElementsWhile(items, (g, gPrev) => {
return g instanceof BlockGroup && gPrev instanceof BlockGroup
&& g.op.isList() && gPrev.op.isList() && g.op.isSameListAs(gPrev.op)
&& g.op.hasSameIndentationAs(gPrev.op);
});
return grouped.map((item) => {
if (!Array.isArray(item)) {
if (item instanceof BlockGroup && item.op.isList()) {
return new ListGroup([new ListItem(item)]);
}
return item;
}
return new ListGroup(item.map((g) => new ListItem(g)));
});
}
groupConsecutiveListGroups(items) {
return groupConsecutiveElementsWhile(items, (curr, prev) => {
return curr instanceof ListGroup && prev instanceof ListGroup;
});
}
nestListSection(sectionItems) {
var indentGroups = this.groupByIndent(sectionItems);
Object.keys(indentGroups).map(Number).sort().reverse().forEach((indent) => {
indentGroups[indent].forEach((lg) => {
var idx = sectionItems.indexOf(lg);
if (this.placeUnderParent(lg, sectionItems.slice(0, idx))) {
sectionItems.splice(idx, 1);
}
});
});
return sectionItems;
}
groupByIndent(items) {
return items.reduce((pv, cv) => {
var indent = cv.items[0].item.op.attributes.indent;
if (indent) {
pv[indent] = pv[indent] || [];
pv[indent].push(cv);
}
return pv;
}, {});
}
placeUnderParent(target, items) {
for (var i = items.length - 1; i >= 0; i--) {
var elm = items[i];
if (target.items[0].item.op.hasHigherIndentThan(elm.items[0].item.op)) {
var parent = elm.items[elm.items.length - 1];
if (parent.innerList) {
parent.innerList.items = parent.innerList.items.concat(target.items);
}
else {
parent.innerList = target;
}
return true;
}
}
return false;
}
}
var EncodeTarget;
(function (EncodeTarget) {
EncodeTarget[EncodeTarget["Html"] = 0] = "Html";
EncodeTarget[EncodeTarget["Url"] = 1] = "Url";
})(EncodeTarget || (EncodeTarget = {}));
function encodeMapping(str, mapping) {
return str.replace(new RegExp(mapping[0], 'g'), mapping[1]);
}
function decodeMapping(str, mapping) {
return str.replace(new RegExp(mapping[1], 'g'), mapping[0].replace('\\', ''));
}
function encodeMappings(mtype) {
let maps = [
['&', '&'],
['<', '<'],
['>', '>'],
['"', '"'],
["'", "'"],
['\\/', '/'],
['\\(', '('],
['\\)', ')']
];
if (mtype === EncodeTarget.Html) {
return maps.filter(([v, _]) => v.indexOf('(') === -1 && v.indexOf(')') === -1);
}
else { // for url
return maps.filter(([v, _]) => v.indexOf('/') === -1);
}
}
function decodeHtml(str) {
return encodeMappings(EncodeTarget.Html).reduce(decodeMapping, str);
}
function makeStartTag(tag, attrs = undefined) {
if (!tag) {
return '';
}
var attrsStr = '';
if (attrs) {
var arrAttrs = [].concat(attrs);
attrsStr = arrAttrs.map(function (attr) {
return attr.key + (attr.value ? '="' + attr.value + '"' : '');
}).join(' ');
}
var closing = '>';
if (tag === 'img' || tag === 'br') {
closing = '/>';
}
return attrsStr ? `<${tag} ${attrsStr}${closing}` : `<${tag}${closing}`;
}
function makeEndTag(tag = '') {
return tag && `</${tag}>` || '';
}
function encodeHtml(str, preventDoubleEncoding = true) {
if (preventDoubleEncoding) {
str = decodeHtml(str);
}
return encodeMappings(EncodeTarget.Html).reduce(encodeMapping, str);
}
const obj = {
assign(target, ...sources /*, one or more source objects */) {
// TypeError if undefined or null
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 0; index < sources.length; index++) {
var nextSource = sources[index];
if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
}
};
var GroupType;
(function (GroupType) {
GroupType["Block"] = "block";
GroupType["InlineGroup"] = "inline-group";
GroupType["List"] = "list";
GroupType["Video"] = "video";
})(GroupType || (GroupType = {}));
;
const BrTag = '<br/>';
class QuillDeltaToHtmlConverter {
constructor(deltaOps, options) {
this.rawDeltaOps = [];
// render callbacks
this.callbacks = {};
this.options = obj.assign({
paragraphTag: 'p',
encodeHtml: true,
classPrefix: 'ql',
inlineStyles: false,
multiLineBlockquote: true,
multiLineHeader: true,
multiLineCodeblock: true,
multiLineParagraph: true,
allowBackgroundClasses: false,
linkTarget: '_blank'
}, options, {
orderedListTag: 'ol',
bulletListTag: 'ul',
listItemTag: 'li'
});
var inlineStyles;
if (!this.options.inlineStyles) {
inlineStyles = undefined;
}
else if (typeof (this.options.inlineStyles) === 'object') {
inlineStyles = this.options.inlineStyles;
}
else {
inlineStyles = {};
}
this.converterOptions = {
encodeHtml: this.options.encodeHtml,
classPrefix: this.options.classPrefix,
inlineStyles: inlineStyles,
listItemTag: this.options.listItemTag,
paragraphTag: this.options.paragraphTag,
linkRel: this.options.linkRel,
linkTarget: this.options.linkTarget,
allowBackgroundClasses: this.options.allowBackgroundClasses
};
this.rawDeltaOps = deltaOps;
}
_getListTag(op) {
return op.isOrderedList() ? this.options.orderedListTag + ''
: op.isBulletList() ? this.options.bulletListTag + ''
: op.isCheckedList() ? this.options.bulletListTag + ''
: op.isUncheckedList() ? this.options.bulletListTag + ''
: '';
}
getGroupedOps() {
var deltaOps = InsertOpsConverter.convert(this.rawDeltaOps);
var pairedOps = Grouper.pairOpsWithTheirBlock(deltaOps);
var groupedSameStyleBlocks = Grouper.groupConsecutiveSameStyleBlocks(pairedOps, {
blockquotes: !!this.options.multiLineBlockquote,
header: !!this.options.multiLineHeader,
codeBlocks: !!this.options.multiLineCodeblock
});
var groupedOps = Grouper.reduceConsecutiveSameStyleBlocksToOne(groupedSameStyleBlocks);
var listNester = new ListNester();
return listNester.nest(groupedOps);
}
convert() {
let groups = this.getGroupedOps();
return groups.map((group) => {
if (group instanceof ListGroup) {
return this._renderWithCallbacks(GroupType.List, group, () => this._renderList(group));
}
else if (group instanceof BlockGroup) {
var g = group;
return this._renderWithCallbacks(GroupType.Block, group, () => this._renderBlock(g.op, g.ops));
}
else if (group instanceof BlotBlock) {
return this._renderCustom(group.op, null);
}
else if (group instanceof VideoItem) {
return this._renderWithCallbacks(GroupType.Video, group, () => {
var g = group;
var converter = new OpToHtmlConverter(g.op, this.converterOptions);
return converter.getHtml();
});
}
else { // InlineGroup
return this._renderWithCallbacks(GroupType.InlineGroup, group, () => {
return this._renderInlines(group.ops, true);
});
}
})
.join("");
}
_renderWithCallbacks(groupType, group, myRenderFn) {
var html = '';
var beforeCb = this.callbacks['beforeRender_cb'];
html = typeof beforeCb === 'function' ? beforeCb.apply(null, [groupType, group]) : '';
if (!html) {
html = myRenderFn();
}
var afterCb = this.callbacks['afterRender_cb'];
html = typeof afterCb === 'function' ? afterCb.apply(null, [groupType, html]) : html;
return html;
}
_renderList(list) {
var firstItem = list.items[0];
return makeStartTag(this._getListTag(firstItem.item.op))
+ list.items.map((li) => this._renderListItem(li)).join('')
+ makeEndTag(this._getListTag(firstItem.item.op));
}
_renderListItem(li) {
//if (!isOuterMost) {
li.item.op.attributes.indent = 0;
//}
var converter = new OpToHtmlConverter(li.item.op, this.converterOptions);
var parts = converter.getHtmlParts();
var liElementsHtml = this._renderInlines(li.item.ops, false);
return parts.openingTag + (liElementsHtml) +
(li.innerList ? this._renderList(li.innerList) : '')
+ parts.closingTag;
}
_renderBlock(bop, ops) {
var converter = new OpToHtmlConverter(bop, this.converterOptions);
var htmlParts = converter.getHtmlParts();
if (bop.isCodeBlock()) {
return htmlParts.openingTag +
encodeHtml(ops.map((iop) => iop.isCustom() ? this._renderCustom(iop, bop) : iop.insert.value).join(""))
+ htmlParts.closingTag;
}
var inlines = ops.map(op => this._renderInline(op, bop)).join('');
return htmlParts.openingTag + (inlines || BrTag) + htmlParts.closingTag;
}
_renderInlines(ops, isInlineGroup = true) {
var opsLen = ops.length - 1;
var html = ops.map((op, i) => {
if (i > 0 && i === opsLen && op.isJustNewline()) {
return '';
}
return this._renderInline(op, null);
}).join('');
if (!isInlineGroup) {
return html;
}
let startParaTag = makeStartTag(this.options.paragraphTag);
let endParaTag = makeEndTag(this.options.paragraphTag);
if (html === BrTag || this.options.multiLineParagraph) {
return startParaTag + html + endParaTag;
}
return startParaTag + html.split(BrTag).map((v) => {
return v === '' ? BrTag : v;
}).join(endParaTag + startParaTag) + endParaTag;
}
_renderInline(op, contextOp) {
if (op.isCustom()) {
return this._renderCustom(op, contextOp);
}
var converter = new OpToHtmlConverter(op, this.converterOptions);
return converter.getHtml().replace(/\n/g, BrTag);
}
_renderCustom(op, contextOp) {
var renderCb = this.callbacks['renderCustomOp_cb'];
if (typeof renderCb === 'function') {
return renderCb.apply(null, [op, contextOp]);
}
return "";
}
beforeRender(cb) {
if (typeof cb === 'function') {
this.callbacks['beforeRender_cb'] = cb;
}
}
afterRender(cb) {
if (typeof cb === 'function') {
this.callbacks['afterRender_cb'] = cb;
}
}
renderCustomWith(cb) {
this.callbacks['renderCustomOp_cb'] = cb;
}
}
exports.QuillDeltaToHtmlConverter = QuillDeltaToHtmlConverter;<file_sep>/QuillDeltaToHtmlConverter.d.ts
declare enum ListType {
Ordered = "ordered",
Bullet = "bullet",
Checked = "checked",
Unchecked = "unchecked"
}
declare enum ScriptType {
Sub = "sub",
Super = "super"
}
declare enum DirectionType {
Rtl = "rtl"
}
declare enum AlignType {
Center = "center",
Right = "right",
Justify = "justify"
}
declare enum DataType {
Image = "image",
Video = "video",
Formula = "formula",
Text = "text"
}
declare class InsertDataQuill {
readonly type: DataType;
readonly value: string;
constructor(type: DataType, value: string);
}
declare class InsertDataCustom {
readonly type: string;
readonly value: any;
constructor(type: string, value: any);
}
declare type InsertData = InsertDataCustom | InsertDataQuill;
declare type InlineStyleType = ((value: string, op: DeltaInsertOp) => string | undefined) | {
[x: string]: string;
};
interface IInlineStyles {
indent?: InlineStyleType;
align?: InlineStyleType;
direction?: InlineStyleType;
font?: InlineStyleType;
size?: InlineStyleType;
}
interface IOpAttributes {
background?: string | undefined;
color?: string | undefined;
font?: string | undefined;
size?: string | undefined;
width?: string | undefined;
link?: string | undefined;
bold?: boolean | undefined;
italic?: boolean | undefined;
underline?: boolean | undefined;
strike?: boolean | undefined;
script?: ScriptType;
code?: boolean | undefined;
list?: ListType;
blockquote?: boolean | undefined;
'code-block'?: boolean | undefined;
header?: number | undefined;
align?: AlignType;
direction?: DirectionType;
indent?: number | undefined;
mentions?: boolean | undefined;
mention?: IMention | undefined;
target?: string | undefined;
renderAsBlock?: boolean | undefined;
}
interface IMention {
[index: string]: string | undefined;
'name'?: string;
'target'?: string;
'slug'?: string;
'class'?: string;
'avatar'?: string;
'id'?: string;
'end-point'?: string;
}
declare class DeltaInsertOp {
readonly insert: InsertData;
readonly attributes: IOpAttributes;
constructor(insertVal: InsertData | string, attrs?: IOpAttributes);
static createNewLineOp(): DeltaInsertOp;
isContainerBlock(): boolean;
isBlockquote(): boolean;
isHeader(): boolean;
isSameHeaderAs(op: DeltaInsertOp): boolean;
hasSameAdiAs(op: DeltaInsertOp): boolean;
hasSameIndentationAs(op: DeltaInsertOp): boolean;
hasHigherIndentThan(op: DeltaInsertOp): boolean;
isInline(): boolean;
isCodeBlock(): boolean;
isJustNewline(): boolean;
isList(): boolean;
isOrderedList(): boolean;
isBulletList(): boolean;
isCheckedList(): boolean;
isUncheckedList(): boolean;
isACheckList(): boolean;
isSameListAs(op: DeltaInsertOp): boolean;
isText(): boolean;
isImage(): boolean;
isFormula(): boolean;
isVideo(): boolean;
isLink(): boolean;
isCustom(): boolean;
isCustomBlock(): boolean;
isMentions(): boolean;
}
declare class InlineGroup {
readonly ops: DeltaInsertOp[];
constructor(ops: DeltaInsertOp[]);
}
declare class SingleItem {
readonly op: DeltaInsertOp;
constructor(op: DeltaInsertOp);
}
declare class VideoItem extends SingleItem {
}
declare class BlockGroup {
readonly op: DeltaInsertOp;
ops: DeltaInsertOp[];
constructor(op: DeltaInsertOp, ops: DeltaInsertOp[]);
}
declare class ListGroup {
items: ListItem[];
constructor(items: ListItem[]);
}
declare class ListItem {
readonly item: BlockGroup;
innerList: ListGroup | null;
constructor(item: BlockGroup, innerList?: ListGroup | null);
}
declare type TDataGroup = VideoItem | InlineGroup | BlockGroup | ListItem | ListGroup;
declare enum GroupType {
Block = "block",
InlineGroup = "inline-group",
List = "list",
Video = "video"
}
interface IQuillDeltaToHtmlConverterOptions {
orderedListTag?: string;
bulletListTag?: string;
listItemTag?: string;
paragraphTag?: string;
classPrefix?: string;
inlineStyles?: boolean | IInlineStyles;
encodeHtml?: boolean;
multiLineBlockquote?: boolean;
multiLineHeader?: boolean;
multiLineCodeblock?: boolean;
multiLineParagraph?: boolean;
linkRel?: string;
linkTarget?: string;
allowBackgroundClasses?: boolean;
}
export declare class QuillDeltaToHtmlConverter {
private options;
private rawDeltaOps;
private converterOptions;
private callbacks;
constructor(deltaOps: any[], options?: IQuillDeltaToHtmlConverterOptions);
_getListTag(op: DeltaInsertOp): string;
getGroupedOps(): TDataGroup[];
convert(): string;
_renderWithCallbacks(groupType: GroupType, group: TDataGroup, myRenderFn: () => string): string;
_renderList(list: ListGroup): string;
_renderListItem(li: ListItem): string;
_renderBlock(bop: DeltaInsertOp, ops: DeltaInsertOp[]): string;
_renderInlines(ops: DeltaInsertOp[], isInlineGroup?: boolean): string;
_renderInline(op: DeltaInsertOp, contextOp: DeltaInsertOp | null): any;
_renderCustom(op: DeltaInsertOp, contextOp: DeltaInsertOp | null): any;
beforeRender(cb: (group: GroupType, data: TDataGroup) => string): void;
afterRender(cb: (group: GroupType, html: string) => string): void;
renderCustomWith(cb: (op: DeltaInsertOp, contextOp: DeltaInsertOp) => string): void;
}
export {};
| 721f811fae5e7cd675acc7b63ffda0e0dd2a7e9c | [
"JavaScript",
"TypeScript"
] | 2 | JavaScript | styladev/npm-quilldto-to-html | 3895ce3b1d5c01e167ffd73fc98c0c5e05322b55 | 18379e997d597e49148ffac9b276535a1b043a4b |
refs/heads/master | <repo_name>whgest/RandomWinner<file_sep>/SMS_Server.py
from twilio.rest import TwilioRestClient
import twilio.twiml
import os
import json
import re
import shutil
from flask import Flask, request, make_response
app = Flask(__name__)
app.debug = True
app.secret_key = '<KEY>'
ACCOUNT_SID = "<KEY>"
AUTH_TOKEN = "<PASSWORD>"
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
BANNED_INITIALS = ["FAG", "FUQ", "ASS", "FUK", "FUC", "PEE", "POO", "SEX", "TIT", "CUM", "JIZ", "GAY", "NIG"]
DATABASE = "entrants.txt"
def add_entrant(initials, number):
try:
with open(DATABASE, "r" "utf8") as fin:
entrants = json.load(fin)
if not entrants:
raise ValueError
entrants[number] = initials
except:
shutil.copy("entrantsbackup.txt", "entrants.txt")
return False, "load"
try:
with open(DATABASE, 'w' 'utf8') as fout:
json.dump(entrants, fout)
print "added", number
shutil.copy("entrants.txt", "entrantsbackup.txt")
return True, None
except:
print "dump failure"
return False, "dump"
def notify_winner(winner):
try:
with open(DATABASE, "r") as fin:
entrants = json.load(fin)
entrants.pop(winner, None)
with open(DATABASE, "w") as fout:
json.dump(entrants, fout)
except:
pass
body = "CONGRATULATIONS! The Q2 wheel o' winners has chosen you! Show this text to claim your prize!"
try:
message = client.messages.create(body=body,
to=winner,
from_="+15129107535")
print message.sid
except:
notify_database_error(winner, "notify")
def notify_database_error(number, err):
body = "SMS server FAILURE for phone number %s. Error: %s." % (number, err)
try:
message = client.messages.create(body=body,
to="+15124843205",
from_="+15129107535")
print message.sid
except:
pass
def clear_db():
with open(DATABASE, 'w') as fout:
fout.write("""{"+15124843205": "WHG"}""")
@app.route('/', methods=['GET', 'POST'])
def receive_text():
number = None
if request.values.get('Body', None) == "CLEAR" and request.values.get('From', None) == "+15124843205":
clear_db()
resp = twilio.twiml.Response()
message = "DB CLEARED."
resp.message(message)
return str(resp)
try:
initials = request.values.get('Body', None)[:3].upper()
number = request.values.get('From', None)
valid = re.match('^[\w ]+$', initials) is not None
if not initials or len(initials) < 2 or not valid:
raise TypeError
if len(initials) == 2:
initials += " "
if initials in BANNED_INITIALS:
raise ValueError
success, err = add_entrant(initials, number)
if success:
message = "You've been entered! Initials recieved: %s. If you want to change your initials, just send a new message. --MUST BE PRESENT TO WIN.--" % initials
else:
message = "Entry error. Please try again."
notify_database_error(number, err)
except TypeError:
message = "Entry not successful: we need your initials (2-3 letters, no numbers or special characters). Please try again."
except IndexError:
message = "Entry not successful: we need your initials (2-3 letters, no numbers or special characters). Please try again."
except ValueError:
message = "Those initials can not be used. Please try again."
try:
resp = twilio.twiml.Response()
resp.message(message)
return str(resp)
except:
notify_database_error(number, "reply")
@app.route('/entrants', methods=['GET'])
def download_entrants():
with open(DATABASE) as fin:
response = make_response(fin.read())
response.headers["Content-Disposition"] = "attachment; filename=" + DATABASE
return response
#make_fixtures()
<file_sep>/requirements.txt
Flask==0.10.1
Jinja2==2.7.3
MarkupSafe==0.23
Werkzeug==0.9.6
gunicorn==19.0.0
httplib2==0.9
itsdangerous==0.24
six==1.7.3
twilio==3.6.6
wsgiref==0.1.2
<file_sep>/wheel.py
# -*- coding: utf-8 -*-
import pygame
import pygcurse
import time, random
import pyfiglet
import pygame.mixer
import SMS_Server
import json
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return "[%s, %s]" % (self.x, self.y)
DIGIT_DIMENSIONS = Point(5, 7)
def char_to_font(string):
f = pyfiglet.Figlet(font='5x7')
digit_map = []
for line in f.renderText(string).replace("#", u"▉").split("\n"):
digit_map.append(list(line))
return digit_map
class Spinner_Wheel():
def __init__(self):
self.random_key = ''
self.entrants, self.numbers, self.winner, self.winner_index = self.import_numbers()
self.grid_size = Point(80, 45)
self.screen = pygcurse.PygcurseWindow(self.grid_size.x, self.grid_size.y, fullscreen=True)
self.screen._autoupdate = False
pygame.mixer.init()
self.screen.update()
pygame.display.set_caption("Wheel O' Winners")
self.cell_size = (self.screen.cellheight, self.screen.cellwidth)
def text(self, x, y, s, fgcolor="white", bgcolor="black"):
self.screen.write(s, x=x, y=y, fgcolor=fgcolor, bgcolor=bgcolor)
return
def import_numbers(self):
with open("entrants.txt") as fin:
entrants = json.load(fin)
entrants.pop("+15124843205", None)
#import string
# entrants = {}
# for i in range(50):
# random_initials = random.choice(string.uppercase) + random.choice(string.uppercase) + random.choice(string.uppercase)
# entrants[str(random.randint(1111111111, 9999999999))] = random_initials
keys = entrants.keys()
if len(keys) > 160:
random.shuffle(keys)
keys = keys[:149]
random.seed(self.random_key)
winner = random.choice(keys)
winner_index = keys.index(winner)
return entrants, keys, winner, winner_index
#
# def print_entrants(self):
# try:
# to_print = self.numbers[:149]
# except IndexError:
# to_print = self.numbers
# self.print_border(border_only=True)
# self.text(self.grid_size.x/2 - 4, 2, "PLAYERS:", fgcolor="yellow")
# col = -3
# for i, player in enumerate(to_print):
# if i % 30 == 0:
# col += 13
# self.text(col, i % 20 + 4, player, fgcolor="white")
# self.screen.update()
# #time.sleep(5)
# for col in range(len(self.numbers)/5):
# self.screen.settint(100, 150, 70, (11+col*13, 4, 1, 30))
# self.screen.settint(100, 150, 70, (16+col*13, 4, 1, 30))
# self.screen.update()
#
#
# self.text(self.grid_size.x/2 - 4, 34, "RANDOM SEED: ", fgcolor="yellow")
# row = 35
# col = 9
# for i, char in enumerate(self.random_seed):
# if i % 63 == 0:
# row += 1
# col = 9
# col += 1
# self.text(col, row, char, fgcolor="yellow")
#
#
# self.screen.update()
# pygcurse.waitforkeypress()
def print_border(self, color="yellow", border_only=False, character="?"):
self.screen.fill(character, fgcolor=color, region=(0, 0, self.grid_size.x-1, 1))
self.screen.fill(character, fgcolor=color, region=(0, self.grid_size.y-1, self.grid_size.x-1, 1))
self.screen.fill(character, fgcolor=color, region=(0, 0, 1, self.grid_size.y-1))
self.screen.fill(character, fgcolor=color, region=(self.grid_size.x-1, 0, 1, self.grid_size.y))
if not border_only:
self.text(3, self.grid_size.y/2, ">>>>>", fgcolor=color)
self.text(21, 2, "PLAYER:" + (" "*23) + "NUMBER:", fgcolor=color)
def map_digits(self, digits):
result = []
for row in range(DIGIT_DIMENSIONS.y):
result.append([])
for digit in digits:
#digit_map = DIGIT_MAPS[digit]
digit_map = char_to_font(digit)
for i, row in enumerate(digit_map):
try:
result[i].extend(digit_map[i])
result[i].extend([" "])
except IndexError:
pass
result.append(list(" "*(self.grid_size.x-25)))
return result
def make_wheel(self):
wheel_map = []
y = 0
for number in self.numbers:
try:
wheel_map.extend(self.map_digits(self.entrants[number][:3] + " " + number[-4:]))
except IndexError:
continue
y += DIGIT_DIMENSIONS.y + 1
return wheel_map
def _print_wheel(self, wheel_map, start_row):
center_row = self.grid_size.y/2
step = 510/self.grid_size.y
for row in range(self.grid_size.y-4):
line = (start_row+row) % len(wheel_map)
row_color = 250 - step * abs(center_row-row)
self.text(15, row+3, ''.join(wheel_map[line]), fgcolor=(row_color, row_color, row_color, 0))
def spin_wheel(self, wheel_map, rotations=1):
# pygame.mixer.music.load("gwoopie.ogg")
# pygame.mixer.music.play()
tick_sound = pygame.mixer.Sound("Pickup_Coin56.wav")
wheel_win = pygame.mixer.Sound("wheel_finish.wav")
start_time = time.time()
center_row = self.grid_size.y/2
current_row = 1
wheel_index = 0
wheel_tick = (DIGIT_DIMENSIONS.y) + 1
ticks_per_rotation = len(self.numbers) * wheel_tick
ticks_to_winner = (self.winner_index-2) * wheel_tick
total_rotation_ticks = (ticks_per_rotation * rotations) + ticks_to_winner
update_interval = 7
slow_time = 0
start_slowing = False
print total_rotation_ticks
slow_time_delta = 0.004
self.print_border("yellow")
self._print_wheel(wheel_map, current_row)
self.screen.update()
break_now2 = False
while 1:
for e in pygame.event.get():
if e.type == pygame.KEYDOWN and e.key == 27:
exit()
if e.type == pygame.KEYDOWN and e.key == 32:
print "spinnnnn"
break_now2 = True
if break_now2:
break
for i in range(total_rotation_ticks):
if i % (total_rotation_ticks/6) == 0 and update_interval > 2:
update_interval -= 1
print "SLOW DOWN!", update_interval
if total_rotation_ticks - i <= 80 and not start_slowing:
start_slowing = True
if start_slowing:
slow_time += slow_time_delta
if i % (wheel_tick * 2) == 0:
self.print_border("yellow")
elif i % wheel_tick == 0:
self.print_border("fuchsia")
if i % wheel_tick == 0:
wheel_index += 1
tick_sound.play()
print self.numbers[wheel_index % len(self.numbers)], i, slow_time
if i % update_interval == 0:
self.screen.update()
self._print_wheel(wheel_map, current_row)
if (total_rotation_ticks - i) > wheel_tick:
time.sleep(slow_time)
elif (total_rotation_ticks - i) == wheel_tick:
time.sleep(1.5)
else:
pass
current_row += 1
tick_sound.play()
self.screen.update()
print "WINNER:", self.winner
SMS_Server.notify_winner(self.winner)
end_time = time.time()
print "WHEEL SPUN IN:", end_time - start_time
break_now = False
wheel_win.play()
while 1:
self.screen.settint(200, 100, 50, (11, center_row - 4, self.grid_size.x-20, 8))
self.print_border("yellow", character="*")
self.screen.update()
time.sleep(0.05)
self.screen.settint(100, 150, 70, (11, center_row - 4, self.grid_size.x-20, 8))
self.print_border("fuchsia", character="*")
self.screen.update()
time.sleep(0.05)
for e in pygame.event.get():
if e.type == pygame.KEYDOWN and e.key == 27:
exit()
if e.type == pygame.KEYDOWN and e.key == 32:
print "spinnnnn"
break_now = True
if break_now:
break
return
def main():
while 1:
print "initializing..."
wheel = Spinner_Wheel()
wheel_map = wheel.make_wheel()
rotations = 50/len(wheel.entrants)
if rotations < 1:
rotations = 1
wheel.spin_wheel(wheel_map, rotations=rotations)
if __name__ == "__main__":
main() | bfedf6de4aa338065553a436d57879674b8fbcc9 | [
"Python",
"Text"
] | 3 | Python | whgest/RandomWinner | adced0a4ddcdd06969e4021032c4f300fca77ea7 | ba75b2d21911bd26642695aa4937e6f9be78a70d |
refs/heads/master | <file_sep>front_end_quiz
==============
To run:
1. Install node dependencies with npm
$ npm install
2. Install webpack globally:
$ npm install -g webpack
3. Run webpack
$ webpack --progress --colors
4. Run express
$ npm start
5. Open http://localhost:3000/
Some notes:
-The save button dumps the edited/updated item.json to the console
-Dimensions are disabled until a shape is selected
-Diameter is disabled unless the item is circular
<file_sep>var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('form_template.html', { title: 'Express' });
});
router.get('/item.json', function(req,res) {
res.set('Content-Type', 'application/json');
res.json(200, {
"httpCode": 200,
"message": "OK",
"result": {
"item": {
"id": 123,
"title": "Lorem Ipsum",
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"dealerInternalNotes": "none available",
"material": {
"description": "Ceramic",
"restricted": "N"
},
"measurement": {
"unit": "in",
"shape": "",
"length": "4.5",
"depth": "4.5",
"height": "12"
},
"condition": {
"description": "Good"
}
}
}
});
});
module.exports = router;
<file_sep>/**
* Created by theodora on 6/3/14.
*/
var $ = require('../jquery');
var _ = require('../underscore');
var Backbone = require('../backbone');
var ItemView = Backbone.View.extend({
el: '#container',
events: {
'click button[type=button]': 'saveButton',
'change [name=inputTexts]': 'changeText',
'change [data-materiallist=materiallist]': 'changeMaterial',
'click input[type=checkbox]': 'check',
'change [name=unit]': 'changeUnit',
'change [name=shape]': 'changeShape',
'change [name=measure]': 'changeMeasurements',
'change .condition': 'changeConditions'
},
initialize: function (options) {
this.options = options || {};
this.model.fetch();
if (this.options.enums) {
this.enums = this.options.enums;
} else {
this.enums = {
material: ["Wood", "Metal", "Ceramic", "Glass", "Leather"],
measurement: {
unit: {
in: "inches",
cm: "centimeters"
},
shape: ["Rectangular", "Circular"]
},
condition: {
description: ["Distressed", "Fair", "Good", "Excellent"]
}
}
}
_.templateSettings.variable = 'obj';
this.templates = {
textinputs: _.template($('#tmplTextInput').html()),
materials: _.template($('#tmplMaterials').html()),
measurements: _.template($('#tmplMeasurements').html()),
conditions: _.template($('#tmplConditions').html())
};
this.render();
this.$('#radioInches').prop('checked', true);
this.$('#radioGood').prop('checked', true);
},
render: function () {
var templateData = {
title: 'Title',
enums: this.enums,
dimen: ['Length', 'Depth', 'Height', 'Diameter']
};
for (var i in this.templates) {
this.$el.append(this.templates[i](templateData));
}
return this;
},
saveButton: function () {
this.model.save();
},
changeText: function ( event ) {
var $target = $(event.currentTarget);
var data = $target.data('title');
var val = $target.val();
if (data && val) {
this.update(data, val);
}
},
changeMaterial: function( event ) {
var item = this.model.get('material');
var $target = $(event.currentTarget);
var data = $target.val();
if (item && data) {
item.description = data;
this.update('material', item);
this.$('#dropdownText').html(data);
}
},
check: function ( event ) {
//Updates checkbox
var item = this.model.get('material');
if (item) {
item.restricted = event.currentTarget.checked ? 'Y' : 'N';
this.update('material', item);
}
},
changeUnit: function ( event ) {
var item = this.model.get('measurement');
var $target = $(event.currentTarget);
var data = $target.data('unit');
if (item && data) {
//Update model
item.unit = data;
this.update('measurement', item);
//Update HTML to show new units
this.$('span.input-group-addon').html(data);
}
},
changeShape: function ( event ) {
//Update model shape
var item = this.model.get('measurement');
var $target= $(event.currentTarget);
var data = $target.data('shape');
if (item && data) {
item.shape = data;
this.update('measurement', item);
}
//Enable measurements
this.$('[name=measure]').removeAttr('disabled');
if(data !== 'Circular') {
this.$('#formDiameter').attr('disabled',true);
}
},
changeMeasurements: function( event ) {
var item = this.model.get('measurement');
var $target = $(event.currentTarget);
var data = ($target.data('dimen') || '').toLowerCase();
if (item && data) {
item[data] = $target.val();
this.update('measurement', item);
}
},
changeConditions: function( event ) {
var $target = $(event.currentTarget);
var data = $target.data('condition');
if (data) {
this.update('condition', data);
}
},
update: function( key , value) {
this.model.set( key, value );
}
});
module.exports = ItemView;<file_sep>/**
* Created by theodora on 6/3/14.
*/
var Backbone = require('../backbone');
var ItemModel = Backbone.Model.extend({
url: '/item.json',
initialize: function(options) {
this.options = options || {};
},
parse: function(data) {
if (data.result && data.result.item) {
this.set(data.result.item);
}
},
save: function() {
console.log("You clicked save! You seem very sure of yourself. Good for you!");
console.log(JSON.stringify(this));
}
});
module.exports = ItemModel;
| 4b18ab4bad01278a31d28a53f3cde079933a5ce5 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | theopaja/front_end_quiz | 8e98f27d5f47a5e19b35dabd2009d6ddbcbe4364 | a6b5a8e7bd069c2883b219c9bb0dfef1feae5c2c |
refs/heads/master | <file_sep># This R script file is for generation of the plot 3.
# read files into R:
project <-read.csv('household_power_consumption.txt', sep=";")
# Subset only data from dates 2007-02-01 and 2007-02-02:
project2 <- project[ which(as.Date(project$Date, "%d/%m/%Y") == "2007-02-01" | as.Date(project$Date, "%d/%m/%Y") == "2007-02-02"),]
# Remove records with missing values:
project3 <- project2[which(project2$Time != "?" &
project2$Global_active_power != "?" &
project2$Global_reactive_power != "?" &
project2$Voltage != "?" &
project2$Global_intensity != "?" &
project2$Sub_metering_1 != "?" &
project2$Sub_metering_2 != "?" &
project2$Sub_metering_3 != "?" ),]
# Combine the Date and the Time columns into a new column datatime:
project4 <- transform(project3,datetime = paste0(Date, ' ', Time))
# Define the graphics parameters:
par(mfrow = c(1,1))
par(mar = c(2,2,2,2))
par(oma=c(0.5,0.5,0.5,0.5))
# Define png file parameters:
png(filename = "plot3.png", width = 480, height = 480, units = "px",
pointsize = 12, bg = "white", res = NA, restoreConsole = TRUE)
# Plotting:
# Plot the Sub_metering_1:
plot(strptime(project4$datetime, format = '%d/%m/%Y%H:%M:%S'),
as.numeric(as.character(project4$Sub_metering_1)), ylim = c(1, 40),
ylab='Energy sub metering', xlab = '', type ='o', pch= '.', cex.lab=0.9)
# Plot the Sub_metering_2:
par(new=T)
plot(strptime(project4$datetime, format = '%d/%m/%Y%H:%M:%S'),
as.numeric(as.character(project4$Sub_metering_2)), ylim = c(1, 40), col = 'red',
ylab='Energy sub metering', xlab = '', type ='o', pch= '.', cex.lab=0.9)
# Plot the Sub_metering_3:
par(new=T)
plot(strptime(project4$datetime, format = '%d/%m/%Y%H:%M:%S'),
as.numeric(as.character(project4$Sub_metering_3)), ylim = c(1, 40), col = 'blue',
ylab='Energy sub metering', xlab = '', type ='o', pch= '.', cex.lab=0.9)
# Add legends:
legend( x="topright",
legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),
col=c("black","red","blue"), lwd=1, lty=c(1,1,1),
pch=c(NA,NA,NA), cex=1.2)
# Turn off the png graphic device:
dev.off()
<file_sep># This R script file is for generation of the plot 1.
# read files into R:
project <-read.csv('household_power_consumption.txt', sep=";")
# Subset only data from dates 2007-02-01 and 2007-02-02:
project2 <- project[ which(as.Date(project$Date, "%d/%m/%Y") == "2007-02-01" | as.Date(project$Date, "%d/%m/%Y") == "2007-02-02"),]
# May also use the following way:
# project2 <- rbind(subset(project, Date == '1/2/2007'), subset(project, Date == '2/2/2007'))
# nrow(project2)
# [1] 2880
# names(project2)
# [1] "Date" "Time" "Global_active_power"
# [4] "Global_reactive_power" "Voltage" "Global_intensity"
# [7] "Sub_metering_1" "Sub_metering_2" "Sub_metering_3"
# Remove records with missing values:
project3 <- project2[which(project2$Time != "?" &
project2$Global_active_power != "?" &
project2$Global_reactive_power != "?" &
project2$Voltage != "?" &
project2$Global_intensity != "?" &
project2$Sub_metering_1 != "?" &
project2$Sub_metering_2 != "?" &
project2$Sub_metering_3 != "?" ),]
# No such rows found:
# nrow(project3)
# [1] 2880
# Define the graphics parameters:
par(mfrow = c(1,1))
par(mar = c(4,2,2,2))
par(oma=c(0.5,0.5,0.5,0.5))
# Define png file parameters:
png(filename = "plot1.png", width = 480, height = 480, units = "px",
pointsize = 12, bg = "white", res = NA, restoreConsole = TRUE)
# Plotting:
hist(as.numeric(as.character(project3$Global_active_power)),
xlab='Global Active Power (kilowatts)',
main = 'Global Active Power', col= 'red')
# Turn off the png graphic device:
dev.off()
| 961d36fdaa44bc486308a145e75148ede813447f | [
"R"
] | 2 | R | wql168/ExData_Plotting1 | 0abb39ae453c941fd98d4bc5d16c401682131091 | 7f5d6fb20225199d49f28e0d33f9afbef0d1f1f1 |
refs/heads/master | <repo_name>sjoerdk/codalab<file_sep>/codalab/apps/web/templatetags/codalab.py
import os
from django import template
register = template.Library()
@register.filter
def filename(value):
return os.path.basename(value.file.name)
# by mikeivanov (on April 16, 2007)
@register.filter
def in_list(value, arg):
return value in arg
<file_sep>/codalab/apps/web/urls/bundles.py
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
from apps.web import views
urlpatterns = patterns('',
url(r'^$', views.BundleListView.as_view(template_name='web/bundles/bundle_list.html'), name='bundles'),
url(r'^(?P<uuid>[A-Za-z0-9]+)$', views.BundleDetailView.as_view(template_name='web/bundles/bundle_detail.html'), name="bundle_detail"),
)<file_sep>/codalab/apps/web/forms.py
from django import forms
from django.forms.formsets import formset_factory
from django.contrib.auth import get_user_model
import models
User = get_user_model()
class CompetitionForm(forms.ModelForm):
class Meta:
model = models.Competition
fields = ('title', 'description', 'image', 'has_registration', 'end_date', 'published')
class CompetitionPhaseForm(forms.ModelForm):
class Meta:
model = models.CompetitionPhase
fields = ('phasenumber', 'label', 'start_date', 'max_submissions', 'scoring_program', 'reference_data')
class CompetitionDatasetForm(forms.ModelForm):
class Meta:
model = models.Dataset
class CompetitionParticipantForm(forms.ModelForm):
class Meta:
model = models.CompetitionParticipant
| edd0eaf546362fa59252aad08c0bbaff7ac61160 | [
"Python"
] | 3 | Python | sjoerdk/codalab | 7fde6a3e1067ce58a1d9aa7dda53c7be6788f738 | 7814e6d44da195e6766b248dbd2325eaf7592c16 |
refs/heads/master | <repo_name>7thhouseofk/FEBUARY<file_sep>/main.3/main.3/ok.cpp
#include<iostream>
using namespace std;
int main() {
for (int i = 0;i < 200;i++) {
cout << "i AM IRON MAN " << endl;
}
}<file_sep>/Project3/Project3/Source.cpp
#include <iostream>
#include <windows.h>
int main(void)
{
HWND stealth;
AllocConsole();
stealth = FindWindowA("ConsoleWindowClass", NULL);
ShowWindow(stealth, 0);
{
Sleep(300);
{
Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
getchar();
return 0; Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
getchar();
return 0; Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
getchar();
return 0; Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
getchar();
return 0; Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
Beep(250, 500);
Sleep(50);
Beep(350, 250);
Beep(300, 500);
Sleep(50);
getchar();
return 0;
}
}
}<file_sep>/string/string/Source.cpp
#include<iostream>
#include<string>
#include<Windows.h>
using namespace std;
int main() {
Beep(5730, 100);Sleep(100);
Beep(330, 100);Sleep(300);
Beep(3360, 100);Sleep(300);
Beep(2592, 100);Sleep(100);
Beep(330, 100);Sleep(300);
Beep(3392, 100);Sleep(700);
Beep(996, 100);Sleep(700);
Beep(262, 300);Sleep(300);
Beep(1946, 300);Sleep(300);
Beep(164, 300);Sleep(300);
Beep(220, 300);Sleep(100);
Beep(89426, 100);Sleep(300);
Beep(2343, 200);
char letter = 'a';
string input;
int room = 1;
while (letter != 'q')
switch (room) {
case 1:
system("color 4D");
cout << "you are hulk" << endl;
cout << "you find water and food " << endl;
getline(cin, input);
if (input.compare("go south"))
room = 2;
else {
cout << "wolverine found you and chase" << endl;
letter = 'q';
}
break;
case 2:
cout << "you are in the forest" << endl;
cout << "but hulk hears shaking bushes. You can either go back or continue south." << endl;
getline(cin, input);
if (input.compare("go back"))
room = 4;
else if (input.compare("go south"))
room = 9;
else if (input.compare("jump to city"))
room = 8;
else {
cout << "Hulk was captured and killed" << endl;
break;
case 3:
cout << "you are in the mall" << endl;
cout << "hulk and wolverine cause a lot of destruction " << endl;
getline(cin, input);
if (input.compare("go east"))
room = 5;
else if (input.compare("go west"))
room = 4;
else if (input.compare("go south"))
room = 6;
else
cout << "hulk broke wolverine arm " << endl;
case 4:
cout << "you are set in space " << endl;
cout << "hulk broke the moon " << endl;
getline(cin, input);
if (input.compare("go east"))
room = 5;
break;
case 5:
cout << "you're in the mall" << endl;
cout << "wolverine found you" << endl;
cout << "wolverine tries to scratch you but hulk fight back and punches him on the floor" << endl;
getline(cin, input);
if (input.compare("go south"))
room = 6;
break;
case 6:
cout << "you are in the water fall " << endl;
cout << "they start to fight in the water" << endl;
cout << "wolverine use his weapon x move " << endl;
getline(cin, input);
if (input.compare("go east"))
room = 7;
break;
case 7:
cout << "you are set in a moon with bombs that can blow you up if you move wrong" << endl;
cout << "if you move west now you get health but you need to figure out the answer to this question " << endl;
cout << " what is mavel" << endl;
getline(cin, input);
if (input.compare("go south "))
room = 8;
break;
case 8:
cout << "spider-man is here to heal hulk" << endl;
cout << "spider man takes hulk back home" << endl;
cout << "you are set in a different room" << endl;
getline(cin, input);
if(input.compare(go)
}
}
}<file_sep>/jeremy's string password/jeremy's string password/Source.cpp
#include<iostream>
using namespace std;
#include<windows.h>
int main(){
string input;
cout << "what's the password?" << endl;<file_sep>/warm up/warm up/warm up.cpp
#include<iostream>
using namespace std;
int main{
if()
}
<file_sep>/quiz/quiz/quiz.cpp
favorite
In the event where we need to generate probability, for example a bias coin with 75 % of tossing head and 25 % tossing tail.Conventionally, I will do it this way:
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int heads = 0, tails = 0;
srand(time(NULL));
number = rand() % 100 + 1; //Generate random number 1 to 100
if (number <= 75) //75% chance
heads++; //This is head
else
tails++; //This is tail
<file_sep>/FOOTBALL/FOOTBALL/football.cpp
#include<iostream>
using namespace std;
int main() {
char input;
cout << "Do you like the Miami Doplhins? Say 'y' for yes, or 'n' for no." << endl;
cin >> input;
if (input == 'y') {
cout << "You cool fam." << endl;
}
else if (input == 'n') {
cout << "Get outta my face fam" << endl;
}
else
cout << "That doesn't answer my question." << endl;
}
<file_sep>/song/song/Source.cpp
#include <iostream>
using namespace std;
int main() {
char newline = '\n';
char tab = '\t';
char backspace = '\b';
char backslash = '\\';
const wchar_t chr1 = L'\u79c1';
{<file_sep>/4.12.17/4.12.17/Source.cpp
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
char iSecret, iGuess;
/* initialize random seed: */
srand(time(NULL));
cout << "WELCOME TO ROCK PAPER SCISSORS LIZARD SPOCK" << endl;
/* generate random number between 1 and 10: */
iSecret = rand() % 5 + 1;
if (iSecret == 1)
char iSecret = 'r';
if (iSecret == 2)
char iSecret = 's';
if (iSecret == 3)
char iSecret = 'l';
if (iSecret == 4)
char iSecret = 'p';
if (iSecret == 5)
char iSecret = 'k';
cin >> iGuess;
switch (iSecret) {
case 'r': //rock case
if (iGuess == 'k' || iGuess == 'p')
cout << "you win!" << endl;
if (iGuess == 'r')
cout << "you tie!" << endl;
else
cout << "you lost" << endl;
break;
case 'k': //spock case
if (iGuess == 'p' || iGuess == 'l')
cout << "you win!" << endl;
if (iGuess == 'k')
cout << "you tie!" << endl;
else
cout << "you lost" << endl;
break;
case 's': //scossors case
if (iGuess == 'k' || iGuess == 's')
cout << "you win!" << endl;
if (iGuess == 's')
cout << "you tie!" << endl;
else
cout << "you lost" << endl;
break;
case 'l': //lizard case
if (iGuess == 'k' || iGuess == 'l')
cout << "you win!" << endl;
if (iGuess == 'l')
cout << "you tie!" << endl;
else
cout << "you lost" << endl;
break;
case 'p': // paper case
if (iGuess == 'k' || iGuess == 'p')
cout << "you win!" << endl;
if (iGuess == 'l')
cout << "you tie!" << endl;
else
cout << "you lost" << endl;
break;
}//end switch
}//end main<file_sep>/for loop/for loop/for loop.cpp
#include<iostream>
using namespace std;
int main() {
for (int j = 0; j < 10;j++)
cout << j << endl;
for(int i=0;i<5;)
for(int i=0;i<10;)
for(int i=5;i<6;)
for(int i=10;i<7;)
}<file_sep>/5-4-17/5-4-17/5-4-17.cpp
#include <iostream>
using namespace std;
int main() {
char input;
int sonic=0;
int dragonballz=0;
int mario=0;
int battlefield=0;
int madden=0;
cout << "what is your favorite food. steak(s), " << endl;
cin >> input;
if(input)
}<file_sep>/how many cookies/how many cookies/how many cookies.cpp
#include<iostream>
using namespace std;
int main() {
char input;
cout << "chocolate(c),almens(a),oatmeal(o)" << endl;
cin >> input;
switch (input) {
case 'c':
cout << "chacolate" << endl;
case 'a':
cout << "alment" << endl;
case 'o':
cout << "oatmeal" << endl;
}
}
<file_sep>/main.2/main.2/jay.cpp
#include<iostream>
using namespace std;
int main() {
int input;
cout << "what song the want to play" << endl;
cin >> input;
if (input == 1)
cout << "1.wont back down from eminem" << endl;
if (input == 2)
cout << "see about you from david banner" << endl;
if (input == 3)
cout << "make it hurt from busta rhymes" << endl;
}<file_sep>/main.4/main.4/Source.cpp
#include<stdio.h>
int main() {
char string[64];
printf("Would yo tell me your full name?\n");
fgets(string, 64, stdin);
printf("Hello %s Nice to meet you!\n", string);
return 0;
}<file_sep>/jeremy's monster generator/jeremy's monster generator/Source.cpp
#include <iostream>
using namespace std;
#include<ctime>// time()functions lives here
#include<cstdlib>//c standard libary has rand()
void harry potter()//function declaration
srand(time(NULL));//seed rand()
while (true) {
harry potter();//our function call
system("pause");//pause the program
}
}//endl of main
void harry potter() {
int num <file_sep>/cylnder/cylnder/cylnder.cpp
#include<iostream>
using namespace std;
int main() {
int radius;
int volume;
int hight;
cout << "radius" << endl;
cin >> radius;
cout << "give hioght" << endl;
cin >> hight;
volume = 3.14*(radius ^ 2)*hight;
cout << "the volume is " << volume << " cm" << endl;
}
<file_sep>/jawuan maxwell daVion mason/jawuan maxwell daVion mason/Source.cpp
#include<iostream>
using namespace std;
int main() {
char input;
int mario = 0;
int sonic = 0;
int blitzer = 0;
int blade = 0;
cout << "whats your favorite food" << endl;
cout << "pizza(p),steak(s),burgers and fries(b),chips(c)" << endl;
if (input == 's')
mario += 800;
else if (input == 'b')
blade += 800;
else if (input == 'p')
sonic += 800;
else if (input == 'c')
blitzer += 0;
cout << "do you like pizza " << endl;
if (input == 's')
mario += 500;
else if (input == 'b')
blade += 289;
else if (input == 'p')
sonic += 400;
else if (input == 'c')
blitzer += 0;
cout << "do you like games" << endl;
if (input == 's')
mario += 500;
else if (input == 'c')
blade += 289;
else if (input == 'b')
sonic += 400;
else if (input == 'p')
blitzer += 0;
cout << "do yuo like movies" << endl;
if (input == 'c')
mario += 500;
else if (input == 's')
blade += 289;
else if (input == 'c')
sonic += 400;
else if (input == 'p')
blitzer += 0;
cout << "what do you like to do in your free time" << endl;
if (input == 's')
mario += 500;
else if (input == 'c')
blade += 289;
else if (input == 'b')
sonic += 400;
else if (input == 'p')
blitzer += 0;
cout << "what is your favorite thing to do" << endl;
if (input == 's')
mario += 500;
else if (input == 'c')
blade += 289;
else if (input == 'b')
sonic += 400;
else if (input == 'p')
blitzer += 0;
cout << "do you like dogs" << endl;
}<file_sep>/pro.1/pro.1/Source.cpp
#include<iostream>
using namespace std;
int main() {
double num1;
double num2;
double sum;
cout << "the heigth and width" << endl;
cin >> num1;
cin >> num2;
sum = 3.14*num1*num1*num2 / 3;
cout << "The area is " << sum << endl;
}<file_sep>/jay/jay/hi.cpp
#include<iostream>
using namespace std;
int main() {
int cookies;
cout << "how many cookies do you want?" << endl;
cin >> cookies;
if (cookies <= 5)
cout << "the cookie amount is to short " << endl;
else if (cookies > 5 && cookies < 10)
cout << "Here are your cookies" << endl;
else if (cookies >= 10)
cout << "thats too many cookies" << endl;
}<file_sep>/warm-up/warm-up/warm-up.cpp
#include <ctime>
#include<iostream>
using namespace std;
int main(){
srand(time(NULL));
int num2 = 0;
int sum = 0;
for (int i = 0; i < 100; i++) {
int max = rand() % 1000 + 1;
cout << max << endl;
if (max > num2) {
num2 = max;
}
sum = sum + max;
}
cout << endl;
cout << "The biggest number is " << num2 << endl;
cout << "the average is " << sum / 100 << endl;
}<file_sep>/low to high/low to high/low and high.cpp
#include <Windows.h>
using namespace std;
int main() {
for (int i = 1; i < 100, 50; i++) {
Beep(i *1000, 5000);
}
}<file_sep>/nested for loop/nested for loop/nested for loop.cpp
#include <iostream>
using namespace std;
int main() {
for (int j = 0;j < 3;j++) {
for (int a = 0;a < 7;a++)
cout << "*";
cout << endl;
}
}
<file_sep>/Project9/Project9/warm up.cpp
#include <iostream>
#include <ctime>
#include <windows.h>
using namespace std<file_sep>/project/project/Source.cpp
#include<iostream>
using namespace std;
int main();
void jukebox(int x, int y);
int main() {
cout << add(2, 4) << endl;
int jukebox(int y, int x) {
}
}
<file_sep>/main/main/yo.cpp
#include<iostream>
using namespace std;
int input;
int main() {
cout << "how old they are " << endl;
cin >> input;
if (input % 2 == 0)
cout << "is your name steven" << endl;
else if (input % 2 != 0)
cout << "your age is odd" << endl;
}<file_sep>/Project4/Project4/Source.cpp
#include <iostream>
using namespace std;
int main() {
char input = 'b';
while (input == 'b') {
cout << "STOP SPAMMING B!" << endl;
cin >> input;
}
}<file_sep>/jeremy's doungen game/jeremy's doungen game/Source.cpp
#include <iostream>
#include<string>
using namespace std;
int main() {
char input = 'a';//inilized with dummy value
int room = 1;
while (input != 'q') { //game loop
switch (room) {//sends us to a room
case 1:
cout << "you're in room 1 and it's dark all you can see is a portion of the place due to the torch in your hand. You can ethier go east, north, or west";
cin >> input;
if (input == 'e');
room = 2;
if (input == 'n');
room = 5;
if (input == 'w');
room = 6;
break;
case 2:
cout << "you have now entered room 2";
cin >> input;
if (input == 'e');
room = 4;
if (input == 's');
room = 3;
if (input == 'w');
room = 1;
break;
case 3:
cout << "you have now entered room 3 ";
cin >> input;
if (input == 'e');
room = 2;
if (input == 'n');
room = 5;
if (input == 'w');
room = 6;
break;
}
}<file_sep>/Project2/Project2/Source.cpp
#include<iostream>
#include<string>
int main() {
} | cfa5d6010c0ac1571af08d34813f367017d318f3 | [
"C++"
] | 28 | C++ | 7thhouseofk/FEBUARY | df7e207b664b2e977459f4d6d11070174af75f0f | 61ae5e341f378947ee4a58532ef6027f09773611 |
refs/heads/master | <file_sep>package com.example.textcontrols;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
public class XMLParser {
public XMLWords[] getWords(InputStream xmlFileStream) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db = null;
db = dbf.newDocumentBuilder();
db.setEntityResolver(new NullResolver());
Document doc = db.parse(xmlFileStream);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("PAIR");
XMLWords[] words = new XMLWords[nList.getLength()];
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
Element eElement = (Element) nNode;
// words[i] = eElement.getElementsByTagName("TOKEN").item(0).getTextContent();
String token = eElement.getElementsByTagName("TOKEN").item(0).getTextContent();
int startTime = Integer.parseInt(eElement.getElementsByTagName("START").item(0).getTextContent());
int endTime = Integer.parseInt(eElement.getElementsByTagName("END").item(0).getTextContent());
words[i] = new XMLWords(token, startTime, endTime);
}
return words;
} catch (Exception e) {
e.printStackTrace();
}
return new XMLWords[0];
}
}
class NullResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException,
IOException {
return new InputSource(new StringReader(""));
}
}<file_sep>import string
import json
from bs4 import BeautifulSoup as bs4
files = []
for i in xrange(26):
files.append('gcide_' + string.lowercase[i])
for xml_file in files:
out_file = 'json_dict/' + xml_file + '.json'
ofile = open(out_file, 'w')
print "Decoding xml file: " + xml_file
soup = bs4(open('../xml_files/' + xml_file + '.xml'))
tags = soup.find_all('p')
out = {}
for tag in tags:
if tag.hw and tag.find('def'):
key = tag.hw.text
key = key.replace('"', "")
key = key.replace('*', "")
key = key.replace('`', "")
key = key.replace("'", "")
out[key] = tag.find('def').text
ofile.write(json.dumps(out))
print "Decoded xml file: %s to JSON format" % xml_file
| 8a45878182c14a041d5f988535beba171298a533 | [
"Java",
"Python"
] | 2 | Java | cs-shadow/BookReader | 6f9c0e3306dd0da592a60ceb4350bc80f54774ee | b7df25f73eef9bb34770cc583a5983b1b5714416 |
refs/heads/master | <repo_name>mitharet/newwwww<file_sep>/app/src/main/java/com/mitha/mvicall2222/activity/RegisterActivity.java
package com.mitha.mvicall2222.activity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.mitha.mvicall2222.R;
import com.mitha.mvicall2222.base.BaseActivity;
import com.mitha.mvicall2222.fragment.VerificationFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
public class RegisterActivity extends BaseActivity implements View.OnClickListener{
@BindView(R.id.btn_lanjut)
Button lanjut;
@BindView(R.id.parent_view)
ConstraintLayout mParentLayout;
@BindView(R.id.btn_delete)
ImageView image;
@BindView(R.id.tv_warning)
TextView warning;
@BindView(R.id.etPhoneNo)
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ButterKnife.bind(this);
lanjut.setOnClickListener(this);
image.setOnClickListener(this);
initView();
}
public void enableeditView(View view){
if(warning!=null){
warning.setVisibility(View.VISIBLE);
}
image.setVisibility(View.VISIBLE);
}
private void initView (){
setKeyboard(mParentLayout);
}
private void closeKeyboard() {
if (editText != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_lanjut:
// Intent intent = new Intent(RegisterActivity.this, verificationFragment.class);
// startActivity(intent);
VerificationFragment bottomSheetFragment = new VerificationFragment();
bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());
break;
case R.id.btn_delete:
editText.getText().clear();
break;
default:
break;
}
}
}
<file_sep>/app/src/main/java/com/mitha/mvicall2222/fragment/VerificationFragment.java
package com.mitha.mvicall2222.fragment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.chaos.view.PinView;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.mitha.mvicall2222.MainActivity;
import com.mitha.mvicall2222.MyBounceInterpolator;
import com.mitha.mvicall2222.R;
import com.mitha.mvicall2222.activity.PermissionActivity;
public class VerificationFragment extends BottomSheetDialogFragment {
public Button lanjut;
public PinView otp;
public TextView tv_Warning;
String getotp = "123456";
public VerificationFragment() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NORMAL, R.style.AppBottomSheetDialogTheme);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_verification, container);
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
// //set to adjust screen height automatically, when soft keyboard appears on screen
// Objects.requireNonNull(Objects.requireNonNull(getDialog()).getWindow()).setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
tv_Warning = rootView.findViewById(R.id.tv_info);
otp = rootView.findViewById(R.id.pinViewCode);
lanjut = rootView.findViewById(R.id.buttonNext);
lanjut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String gettotp = otp.getText().toString();
if (!TextUtils.isEmpty(gettotp)) {
if (!gettotp.equals(getotp)) {
otp.setBackgroundResource(R.drawable.kodesalah);
@SuppressLint("ResourceType") Animation animation1 =
AnimationUtils.loadAnimation(getActivity().getApplicationContext(),
R.animator.bounce);
// Use bounce interpolator with amplitude 0.2 and frequency 20
MyBounceInterpolator interpolator = new MyBounceInterpolator(0.2, 20);
animation1.setInterpolator(interpolator);
otp.startAnimation(animation1);
otp.setTextColor(Color.WHITE);
tv_Warning.setText("Kode Salah!");
tv_Warning.setTextColor(getActivity().getResources().getColor(R.color.kodesalah));
tv_Warning.setVisibility(View.VISIBLE);
} else {
otp.setBackgroundResource(R.drawable.kodebenar);
otp.setTextColor(Color.WHITE);
tv_Warning.setText("Kode Benar!");
tv_Warning.setTextColor(getActivity().getResources().getColor(R.color.kodebenar));
startActivity(new Intent(getActivity(), PermissionActivity.class));
}
}
}
});
return rootView;
}
}<file_sep>/settings.gradle
include ':app',':countrycodepicker', ':pinview'
rootProject.name='MVICALL2222'
<file_sep>/app/src/main/java/com/mitha/mvicall2222/activity/PermissionActivity.java
package com.mitha.mvicall2222.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.mitha.mvicall2222.MainActivity;
import com.mitha.mvicall2222.R;
public class PermissionActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission);
Button lanjut =findViewById(R.id.btnLanjut);
lanjut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(PermissionActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
| c5b0356531d25f020583b267af67cd18291d3712 | [
"Java",
"Gradle"
] | 4 | Java | mitharet/newwwww | 81f5ecf495a32a398db5d4d6ecb4f43ada9a7a82 | 3f70a52599826618d946ce2928e64f0ffd6cf96e |
refs/heads/master | <repo_name>ste001/advent-of-code-2018<file_sep>/Day_3/day_3.rb
$inches = 1000
def create_fabric size
fabric = Array.new(size) { Array.new(size)}
size.times do |i|
size.times do |j|
fabric[i][j] = '.'
end
end
fabric
end
def populate_fabric input, fabric
input.each_line do |claim|
claim_array = claim.split(/[#@:,x]/)
id = claim_array[1].strip
column = claim_array[2].strip.to_i
row = claim_array[3].strip.to_i
width = claim_array[4].strip.to_i
height = claim_array[5].strip.to_i
height.times do |i|
width.times do |j|
if fabric[column + j][row + i] == '.'
fabric[column + j][row + i] = id
else
fabric[column + j][row + i] = 'X'
end
end
end
end
end
def intact_claim input, fabric
input.each_line do |claim|
intact = true
claim_array = claim.split(/[#@:,x]/)
id = claim_array[1].strip
column = claim_array[2].strip.to_i
row = claim_array[3].strip.to_i
width = claim_array[4].strip.to_i
height = claim_array[5].strip.to_i
height.times do |i|
width.times do |j|
if fabric[column + j][row + i] != id
intact = false
end
end
end
return id if intact
end
end
def overlaps_count fabric
count = 0
$inches.times do |i|
$inches.times do |j|
if fabric[i][j] == 'X'
count += 1
end
end
end
count
end
fabric = create_fabric $inches
input = File.read('input.txt')
populate_fabric input, fabric
puts "Part one solution: #{overlaps_count fabric}"
true_claim = intact_claim(input, fabric)
puts "Part two solution: #{true_claim}"<file_sep>/Day_1/day_1.rb
def find_sum input
sum = 0
input.each_line do |number|
sum += number.to_i
end
return sum
end
def find_double_frequency input
frequences = {}
found = false
current_freq = 0
while (not found)
input.each_line do |number|
current_freq += number.to_i
if (frequences.has_key?(current_freq))
found = true
return current_freq
else
frequences[current_freq] = 1
end
end
end
end
input = File.read("input.txt")
puts "Part one answer: #{find_sum(input)}"
puts "Part two answer: #{find_double_frequency(input)}"<file_sep>/Day_2/day_2.rb
input = File.read("input.txt")
def checksum input
checksum = 0
twice_sum = 0
thrice_sum = 0
input.each_line do |id|
letters = {}
id.each_char do |char|
if (letters.has_key?(char))
letters[char] += 1
else
letters[char] = 1
end
end
if (letters.has_value?(2))
twice_sum += 1
end
if (letters.has_value?(3))
thrice_sum += 1
end
end
checksum = twice_sum * thrice_sum
checksum
end
def almost_equal(a, b)
changes = 0
a.length.times do |i|
if a[i] != b[i]
changes += 1
end
end
(changes == 1) ? true : false
end
def same_letters(a, b)
same_letters = ""
a.length.times do |i|
if a[i] == b[i]
same_letters << a[i]
end
end
same_letters
end
def common_letters input
input_array = input.split("\n")
i = 0
j = 0
n = input_array.length
while (i < n)
while (j < n)
if (i != j && almost_equal(input_array[i], input_array[j]))
return same_letters(input_array[i], input_array[j])
end
j += 1
end
j = 0
i += 1
end
end
puts "Part one solution: #{checksum input}"
puts "Part two solution: #{common_letters input}"<file_sep>/README.md
# advent-of-code-2018
This repo contains all of my snippets of code used in solving the Advent of Code 2018 event
<file_sep>/Day_5/day_5.rb
def polymer_collapse input
input_array = input.split('')
i = 1
while (i < input_array.length - 1)
if (input_array[i].match?(/[[:lower:]]/) \
&& input_array[i+1] == input_array[i].upcase \
|| input_array[i].match?(/[[:upper:]]/) \
&& input_array[i+1] == input_array[i].downcase)
input_array.delete_at(i)
input_array.delete_at(i)
elsif (input_array[i].match?(/[[:lower:]]/) \
&& input_array[i-1] == input_array[i].upcase \
|| input_array[i].match?(/[[:upper:]]/) \
&& input_array[i-1] == input_array[i].downcase)
input_array.delete_at(i-1)
input_array.delete_at(i-1)
i -= 1
else
i += 1
end
end
input_array.length
end
def remove_units input, unit
input_array = input.split('')
input_array.each do |char|
input_array.delete(unit) if char == unit
input_array.delete(unit.upcase) if char == unit.upcase
end
input_array.join("")
end
def find_smallest_polymer input
smallest = input.length
letter = 'a'
26.times do |index|
new_input = remove_units input, letter
length = polymer_collapse new_input
smallest = length if length < smallest
letter = (letter.ord + 1).chr
end
smallest
end
input = File.read('input.txt')
puts "Part one solution: #{polymer_collapse input}"
puts "Part two solution: #{find_smallest_polymer input}" | 22e99f0596b5401278dae3f5318c7b421fc23bef | [
"Markdown",
"Ruby"
] | 5 | Ruby | ste001/advent-of-code-2018 | 53112369114ac92ee4325e24a3cfd123b5bd6716 | 5a9d1a2361c72e434ad69e6cc5e2d8ecdeca7a95 |
refs/heads/master | <file_sep>using System;
using GraphQL.Types;
using Orders.Models;
using Orders.Services;
namespace Orders.Schema
{
public class OrderType : ObjectGraphType<Order>
{
public OrderType(ICustomerService customers)
{
Name = "Order";
Description = "This is an order from the customer";
Field(o => o.Id, type: typeof(IdGraphType)).Description("Order Number");
Field(o => o.Name).Description("Name of the item");
Field(o => o.Description).Description("");
Field<CustomerType>("customer", resolve: content => customers.GetCustomerByIdAsync(content.Source.CustomerId));
Field(o => o.Created);
}
}
}<file_sep>using GraphQL.Types;
using Orders.Models;
namespace Orders.Schema
{
public class OrderStatusesEnum : EnumerationGraphType
{
public OrderStatusesEnum()
{
Name = "OrderStatuses";
AddValue("Created", "order was created", Order.OrderStatus.Created);
AddValue("Processing", "order is in process", Order.OrderStatus.Processing);
AddValue("Completed", "order is completed", Order.OrderStatus.Completed);
AddValue("Cancelled", "order was cancelled", Order.OrderStatus.Cancelled);
AddValue("Closed", "order was Closed", Order.OrderStatus.Closed);
}
}
}<file_sep>using GraphQL;
using GraphQL.Types;
namespace Orders.Schema
{
public class OrdersSchema : GraphQL.Types.Schema
{
public OrdersSchema(OrdersQuery query, IDependencyResolver resolver)
{
Query = query;
DependencyResolver = resolver;
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orders.Models;
namespace Orders.Services
{
public class OrderService : IOrderService
{
private readonly List<Order> _orders = new List<Order>();
public OrderService()
{
_orders.Add(
new Order(name: "pen", description: "used for writing information", created: DateTime.Today.AddDays(4),
customerId: new Guid("360506b3-003e-48b2-a5b7-655b401ae1b4"))
);
_orders.Add(
new Order(name: "paper", description: "chopped from a tree", created: DateTime.Today.AddDays(7),
customerId: new Guid("360506b3-003e-48b2-a5b7-655b401ae1b4"))
);
_orders.Add(
new Order(name: "chair", description: "used for sitting on", created: DateTime.Today.AddDays(32),
customerId: new Guid("b3960d81-48c4-4b6c-a309-d347a65e8b06"))
);
_orders.Add(
new Order(name: "Table", description: "used for working", created: DateTime.Today.AddDays(4),
customerId: new Guid("360506b3-003e-48b2-a5b7-655b401ae1b4"))
);
_orders.Add(
new Order(name: "Computer", description: "used for writing information",
created: DateTime.Today.AddDays(9),
customerId: new Guid("360506b3-003e-48b2-a5b7-655b401ae1b4"))
);
_orders.Add(
new Order(name: "keyboard", description: "used for importing information into a computer",
created: DateTime.Today.AddDays(34),
customerId: new Guid("360506b3-003e-48b2-a5b7-655b401ae1b4"))
);
_orders.Add(
new Order(name: "pen", description: "used for writing information", created: DateTime.Today.AddDays(8),
customerId: new Guid("b3960d81-48c4-4b6c-a309-d347a65e8b06"))
);
_orders.Add(
new Order(name: "pen", description: "used for writing information", created: DateTime.Today.AddDays(3),
customerId: new Guid("cac67348-450d-487a-8269-2366ffbe5596"))
);
}
public Task<Order> GetByOrderIdAsync(Guid id) => Task.FromResult(_orders.Single(x => x.Id == id));
public Task<IEnumerable<Order>> GetOrdersAsync() => Task.FromResult(_orders.AsEnumerable());
}
public interface IOrderService
{
Task<Order> GetByOrderIdAsync(Guid id);
Task<IEnumerable<Order>> GetOrdersAsync();
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Orders.Models;
namespace Orders.Services
{
public class CustomerService : ICustomerService
{
private readonly List<Customer> _customers = new List<Customer>();
public CustomerService()
{
_customers.Add(new Customer(new Guid("360506b3-003e-48b2-a5b7-655b401ae1b4"),"John"));
_customers.Add(new Customer(new Guid("b3960d81-48c4-4b6c-a309-d347a65e8b06"),"Merriam"));
_customers.Add(new Customer(new Guid("cac67348-450d-487a-8269-2366ffbe5596"),"Max"));
_customers.Add(new Customer(new Guid("b0e7a074-6090-47e9-884f-48c299de36e4"), "Rakel"));
_customers.Add(new Customer(new Guid("02f4691d-7c37-4ace-9403-4d963ee5dc1a"), "goodness"));
}
public Customer GetCustomerById(Guid id) => _customers.Single(x => x.Id == id);
public Task<Customer> GetCustomerByIdAsync(Guid id) => Task.FromResult(_customers.Single(x => x.Id == id));
public Task<IEnumerable<Customer>> GetCustomersAsync() => Task.FromResult(_customers.AsEnumerable());
}
public interface ICustomerService
{
Customer GetCustomerById(Guid id);
Task<Customer> GetCustomerByIdAsync(Guid id);
Task<IEnumerable<Customer>> GetCustomersAsync();
}
}<file_sep>using System.Security.Cryptography.X509Certificates;
using GraphQL.Types;
using Orders.Models;
namespace Orders.Schema
{
public class CustomerType : ObjectGraphType<Customer>
{
public CustomerType()
{
Name = "Customer";
Description = "These are the customers in the system";
Field(c => c.Id, type: typeof(IdGraphType)).Description("Customer Id");
Field(c => c.Name).Description("Customer Name");
}
}
}<file_sep>#!/bin/bash
cd MyGraphQlServer
dotnet restore
dotnet run
| 4b86fc2ad0d403c63b201adbcaa75b6b4093c99c | [
"C#",
"Shell"
] | 7 | C# | zim1992/MyGraphQlServer | c9be7528b7d36377fc65ab2f3dca698ab0e7dc76 | 2215f58f3e692233d7c61b65d2759ca896cef80f |
refs/heads/master | <repo_name>flintlouis/SnakeAStar<file_sep>/README.md
# AI Snake
Snake with A* algorithm

## Install Pygame
Use the package manager [pip](https://pip.pypa.io/en/stable/) to install Pygame
```bash
python3 -m pip install -U pygame --user
```
## Run
```bash
python main.py
```
## Controls
Up Arrow - speed up
Down Arrow - speed down
Space - activate walls
M - Mute
<file_sep>/main.py
import pygame
import sys
import os
from game import Snake, Food, Settings, handle_keys
from draw import drawWalls
from info import SCREEN_WIDTH, SCREEN_HEIGHT, BLACK, WHITE
from pathfinding import findPath, getPath
def initPygame():
pygame.init()
pygame.display.set_caption('Snake')
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
surface = pygame.Surface(screen.get_size())
surface = surface.convert()
return screen, surface
def loadMisc():
bitesound = pygame.mixer.Sound('sounds/bite.wav')
hit = pygame.mixer.Sound('sounds/hit.wav')
music = pygame.mixer.music.load('sounds/music.mp3')
myfont = pygame.font.SysFont("arialblack", 16)
return bitesound, hit, myfont
def display(screen, surface, myfont, score, highscore):
screen.blit(surface, (0,0))
text = myfont.render(f"Score {score}", 1, WHITE)
screen.blit(text, (10, 10))
text = myfont.render(f"Highscore {highscore}", 1, WHITE)
screen.blit(text, (350, 10))
pygame.display.update()
def main():
os.system("clear")
print("Loading...")
clock = pygame.time.Clock()
screen, surface = initPygame()
bitesound, hit, myfont = loadMisc()
settings = Settings()
settings.getHighscore()
snake = Snake(3)
apple = Food()
os.system("clear")
pygame.mixer.music.play(-1)
path = None
score = 0
# Mainloop
while(True):
clock.tick(settings.fps)
surface.fill(BLACK)
handle_keys(settings)
# A* Pathfinding to find apple
if not path:
i = 0
openSet = []
closedSet = []
settings.initMaze()
x, y = snake.head
openSet.append(settings.maze[int(x)][int(y)])
while len(openSet):
path = findPath(openSet, closedSet, settings.maze, apple.position, snake, settings.walls)
if path:
path = getPath(path)
break
# If path was found move snake through path
if path:
snake.turn(snake.getDir(path[i]))
i += 1
if i == len(path):
path = None
# Check if snake hits obstacle
if snake.hit(settings.walls):
if not settings.mute:
hit.play()
snake.reset(3)
apple.randomize_position()
if score > settings.highscore:
settings.highscore = score
settings.saveHighscore()
score = 0
pygame.time.delay(1000)
snake.move(settings.walls)
# Check if apple gets eaten
if snake.head == apple.position:
if not settings.mute:
bitesound.play()
snake.add_body()
while apple.position in snake.body:
apple.randomize_position()
score += 1
snake.draw(surface)
apple.draw(surface)
if settings.walls:
drawWalls(surface)
display(screen, surface, myfont, score, settings.highscore)
main()
<file_sep>/draw.py
from info import GRIDSIZE, SCREEN_HEIGHT, SCREEN_WIDTH, GRAY
import pygame
def drawRect(surface, point, colour):
x, y = point
r = pygame.Rect((x*GRIDSIZE, y*GRIDSIZE), (GRIDSIZE, GRIDSIZE))
pygame.draw.rect(surface, colour, r)
def drawWalls(surface):
r = pygame.Rect((0,0), (SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.draw.rect(surface, GRAY, r, 5)<file_sep>/info.py
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
GRIDSIZE = 20
GRID_WIDTH = SCREEN_HEIGHT / GRIDSIZE
GRID_HEIGHT = SCREEN_WIDTH / GRIDSIZE
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
DIRECTIONS = [UP, RIGHT, DOWN, LEFT]
START_POS = (12, 12)
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (150,0,0)
GREEN = (20,100,20)
HEAD = (20,200,20)
BLUE = (0,0,100)
GRAY = (100,100,100)
<file_sep>/pathfinding.py
def getPath(path):
newPath = []
while path.parent:
newPath.append(path.pos)
path = path.parent
newPath.reverse()
return newPath
def bodyHit(neighbour, snake, g):
if neighbour.pos in snake.body[:-g]:
return True
return False
def findPath(openSet, closedSet, maze, end, snake, walls):
current = openSet[0]
# Find node with lowest f
for node in openSet:
if node.f < current.f:
current = node
# Remove from openSet and add to closedSet
openSet.remove(current)
closedSet.append(current)
# Stop if end node has been found
if current.pos == end:
return current
# check all neigbouring nodes to see which to add to openSet
for neighbour in current.getNeighbours(maze, walls):
# Make sure node wasn't already visited
g = current.g + 1
if neighbour in closedSet or bodyHit(neighbour, snake, g):
continue
if neighbour not in openSet:
neighbour.update(g, end, current, walls)
openSet.append(neighbour)
else:
# Update node in openSet because better g was found
if g < neighbour.g:
neighbour.update(g, end, current, walls)
return None
<file_sep>/game.py
import random
import pygame
from info import START_POS, RIGHT, GRID_WIDTH, GRID_HEIGHT, HEAD, GREEN, GRIDSIZE
from node import Node
from draw import drawRect
import sys
class Snake(object):
def __init__(self, len):
self.reset(len)
def add_body(self):
self.body.append(self.body[-1])
def getOpDir(self, dir):
return (dir[0]*-1, dir[1]*-1)
def turn(self, dir):
if self.getOpDir(dir) == self.direction or not self.moved:
return
self.direction = dir
self.moved = False
def getDir(self, pos):
return pos[0]-self.head[0], pos[1]-self.head[1]
def move(self, walls):
newhead = self.getNewHead(walls)
self.body.insert(0, newhead)
self.body.pop()
self.head = newhead
self.moved = True
def reset(self, len):
self.moved = True
self.body = [START_POS]
self.direction = RIGHT
for i in range(len-1):
self.add_body()
self.head = self.body[0]
def draw(self, surface):
drawRect(surface, self.head, HEAD)
for pos in self.body[1:]:
drawRect(surface, pos, GREEN)
def getNewHead(self, walls):
x, y = self.direction
headx, heady = self.head
if walls:
return (headx+x, heady+y)
return (int((x+headx)%GRID_WIDTH), int((y+heady)%GRID_HEIGHT))
def wallHit(self, pos):
x, y = pos
return x < 0 or x >= GRID_WIDTH or y < 0 or y >= GRID_HEIGHT
def hit(self, walls):
pos = self.getNewHead(walls)
if pos in self.body[:-1] or self.wallHit(pos):
return True
return False
class Food(object):
def __init__(self):
self.colour = (150, 20, 20)
self.randomize_position()
def randomize_position(self):
self.position = (random.randint(0, GRID_WIDTH-1), random.randint(0, GRID_HEIGHT-1))
def draw(self, surface):
pos = (self.position[0]*GRIDSIZE, self.position[1]*GRIDSIZE)
r = pygame.Rect(pos, (GRIDSIZE, GRIDSIZE))
pygame.draw.rect(surface, self.colour, r)
class Settings:
mute = False
fps = 25
highscore = 0
walls = True
def initMaze(self):
self.maze = [[Node((x,y)) for y in range(int(GRID_HEIGHT))] for x in range(int(GRID_WIDTH))]
def getHighscore(self):
try:
with open('.highscore', 'r') as f:
self.highscore = int(f.read())
except:
self.highscore = 0
def saveHighscore(self):
with open('.highscore', 'w') as f:
f.write(str(self.highscore))
def handle_keys(settings):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == ord('m'):
if settings.mute:
settings.mute = False
pygame.mixer.music.unpause()
else:
settings.mute = True
pygame.mixer.music.pause()
elif event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == pygame.K_UP and settings.fps < 100:
settings.fps += 5
elif event.key == pygame.K_DOWN and settings.fps > 10:
settings.fps -= 5
elif event.key == pygame.K_SPACE:
settings.walls = False if settings.walls else True<file_sep>/node.py
from math import sqrt
from info import GRID_WIDTH, GRID_HEIGHT, DIRECTIONS
class Node(object):
f = 0
g = 0
h = 0
parent = None
obstacle = False
def __init__(self, pos):
self.pos = pos
def heuristic(self, point, walls):
x = abs(point[0] - self.pos[0])
y = abs(point[1] - self.pos[1])
if not walls:
xoffside = abs(GRID_WIDTH - x)
yoffside = abs(GRID_HEIGHT - y)
if x > xoffside:
x = xoffside
if y > yoffside:
y = yoffside
self.h = x + y
def update(self, g, end, parent, walls):
self.parent = parent
self.g = g
self.heuristic(end, walls)
self.f = self.g + self.h
def _sumPoints(self, a, b):
xa, ya = a
xb, yb = b
return (xa+xb, ya+yb)
def _outofbounds(self, point):
x, y = point
if x < 0 or x >= GRID_WIDTH or y < 0 or y >= GRID_HEIGHT:
return True
return False
def getNeighbours(self, maze, walls):
neighbours = []
for dir in DIRECTIONS:
x, y = self._sumPoints(self.pos, dir)
if not walls:
x, y = int(x%GRID_WIDTH), int(y%GRID_HEIGHT)
neighbours.append(maze[x][y])
elif not self._outofbounds((x, y)):
neighbours.append(maze[x][y])
return neighbours
def printInfo(self):
print(self.pos)
if self.parent:
print(f"parent: {self.parent.pos}")
else:
print(f"parent: {self.parent}")
print(f"f:{self.f} = g:{self.g} + h:{self.h}\n")
| 1ec77f447892f34c9879b6dcd1d1767777d14e88 | [
"Markdown",
"Python"
] | 7 | Markdown | flintlouis/SnakeAStar | 208f2be72fc0ef1ecff45bda77d4d4fa3e6de4c8 | 05e6bb875fe95c3d6a317d3c6fc2267231f6a69d |
refs/heads/master | <file_sep># TFC/E Migration Tool
This tool is designed to help automate the migration from one TFE/C Organization to another, whether that’s TFE to TFC, or vice versa. The following migration operations are currently supported:
* Migrate Teams
* Migrate Organization Membership
* Note: This sends out an invite to any 'active' members of the source Organization (which must be accepted by the User before they're added to the destination Organization)
* Migrate SSH Keys
* Note: This transfers all Key names, but not Values (which are write only)
* Migrate SSH Key Files
* Note: Prior to using this method, the `workspace_to_file_path_map` map must be manually generated using the following format: `{'ssh_key_name':'path/to/file'}`
* Migrate Agent Pools
* Migrate Workspaces
* Migrate State (Either All Versions or Current Version)
* Migrate Workspace Variables
* Note: For any Variable marked as `Sensitive`, only Key names will be transferred (since Values are write only)
* Migrate Workspace Sensitive Variable Values
* Note: Prior to using this method, the `sensitive_variable_data_map` map must be manually generated ahead of time. The easiest way to do this is to update the value for each variable in the list returned by the `migrate_workspace_variables` method (**Important:** If you intend on doing this, be sure to pass `True` as the final argument to `migrate_workspace_variables`)
* Migrate Workspace SSH Keys
* Migrate Workspace Run Triggers
* Migrate Workspace Notifications
* Note: Email Notifications will be migrated, but email address are added based on Username. If the Usernames do not exist within the New Organization at the time the Notifications are migrated, the triggers will still get migrated, but they will need to be updated once the target Users have confirmed their new Accounts.
* Migrate Workspace Team Access
* Migrate Configuration Versions
* Migrate Configuration Files
* Note: Prior to using this method, the `workspace_to_file_path_map` map must be manually generated using the following format: `{'workspace_name':'path/to/file'}`
* Migrate Policies
* Migrate Policy Sets
* Migrate Policy Set Parameters
* Note: For any parameter marked as `Sensitive`, only Key names will be transferred (since Values are write only)
* Migrate Policy Set Sensitive Parameter Values
* Note: Prior to using this method, the `sensitive_policy_set_parameter_data_map` map must be manually generated ahead of time. The easiest way to do this is to update the value for each variable in the list returned by the `migrate_policy_set_parameters` method (**Important:** If you intend on doing this, be sure to pass `True` as the final argument to `migrate_policy_set_parameters`)
* Migrate Registry Modules
* Note: Only VCS-backed Module migration is supported currently
## STEPS:
### 1. Set Required Environment Variables for both the Source Org and the New Org
```
# SOURCE ORG
TFE_TOKEN_ORIGINAL = os.getenv("TFE_TOKEN_ORIGINAL", None)
TFE_URL_ORIGINAL = os.getenv("TFE_URL_ORIGINAL", None)
TFE_ORG_ORIGINAL = os.getenv("TFE_ORG_ORIGINAL", None)
api_original = TFC(TFE_TOKEN_ORIGINAL, url=TFE_URL_ORIGINAL)
api_original.set_org(TFE_ORG_ORIGINAL)
# NEW ORG
TFE_TOKEN_NEW = os.getenv("TFE_TOKEN_NEW", None)
TFE_URL_NEW = os.getenv("TFE_URL_NEW", None)
TFE_ORG_NEW = os.getenv("TFE_ORG_NEW", None)
TFE_OAUTH_NEW = os.getenv("TFE_OAUTH_NEW", None)
api_new = TFC(TFE_TOKEN_NEW, url=TFE_URL_NEW)
api_new.set_org(TFE_ORG_NEW)
```
Note:
* The Token(s) used above must be either a Team or User Token and have the appropriate level of permissions
* The URL(s) used abvoe must follow a format of `https://app.terraform.io`
### 2. Select Desired Functions
Choose which components you want to migrate and comment out any others in [`migration.py`](migration.py). For example, you may choose whether you want to `migrate_all_state` for your Workspaces or `migrate_current_state`, but you should not select both. For more insight into what each function does, please refer to the contents of[`functions.py`](functions.py).
### 3. Run the Migration Script
```
python migration.py
```
### NOTES
This migration utility leverages the [Terraform Cloud/Enterprise API](https://www.terraform.io/docs/cloud/api/index.html) and the [terrasnek](https://github.com/dahlke/terrasnek) Python Client for interacting with it. For security reasons, there are certain Sensitive values that cannot be extracted (ex. Sensitive Variables, Sensitive Policy Set Parameters, and SSH Keys), so those will need to be re-added after the migration is complete (the Keys will, however, be migrated). For convenience, additional methods have been included to enable Sensitive value migration (Sensitive Variables, Sensitive Policy Set Parameters, and SSH Keys).
**IMPORTANT:** These scripts expect that the destination Organization (i.e TFE_ORG_NEW) is a blank slate and has not had any changes made ahead of time through other means. If changes have been made to the new Organization prior to using this tool, errors are likely to occur.
If needed (ex. for testing purposes), a set of helper delete functions have been included as well in [`delete_functions.py`](delete_functions.py).
<file_sep>import urllib.request
import hashlib
import base64
import json
def migrate_teams(api_original, api_new):
# Fetch Teams from Existing Org
teams = api_original.teams.list()['data']
new_org_owners_team_id = api_new.teams.list()['data'][0]['id']
teams_map = {}
for team in teams:
if team['attributes']['name'] == "owners":
teams_map[team['id']] = new_org_owners_team_id
else:
# Build the new team payload
new_team_payload = {
"data": {
"type": "teams",
"attributes": {
"name": team['attributes']['name'],
"organization-access": {
"manage-workspaces": team['attributes']['organization-access']['manage-workspaces'],
"manage-policies": team['attributes']['organization-access']['manage-policies'],
"manage-vcs-settings": team['attributes']['organization-access']['manage-vcs-settings']
}
}
}
}
# Create Team in New Org
new_team = api_new.teams.create(new_team_payload)
# Build Team ID Map
teams_map[team['id']] = new_team["data"]["id"]
return teams_map
def migrate_organization_memberships(api_original, api_new, teams_map):
# Set proper membership filters
member_filters = [
{
"keys": ["status"],
"value": "active"
}
]
org_members = api_original.org_memberships.list_for_org(
filters=member_filters, page=0, page_size=100)['data']
for org_member in org_members:
for team in org_member['relationships']['teams']['data']:
team['id'] = teams_map[team['id']]
# Build the new User invite payload
new_user_invite_payload = {
"data": {
"attributes": {
"email": org_member['attributes']['email']
},
"relationships": {
"teams": {
"data": org_member['relationships']['teams']['data']
},
},
"type": "organization-memberships"
}
}
try:
api_new.org_memberships.invite(new_user_invite_payload)
except:
continue
return
def migrate_ssh_keys(api_original, api_new):
# Fetch SSH Keys from Existing Org
# Note: This does not fetch the Keys themselves
ssh_keys = api_original.ssh_keys.list()["data"]
ssh_keys_map = {}
ssh_key_name_map = {}
if ssh_keys:
for ssh_key in reversed(ssh_keys):
# Build the new Agent Pool Payload
new_ssh_key_payload = {
"data": {
"type": "ssh-keys",
"attributes": {
"name": ssh_key['attributes']['name'],
"value": "Replace Me"
}
}
}
# Create SSH Key in New Org
# Note: The actual Keys themselves must be added separately afterward
new_ssh_key = api_new.ssh_keys.create(new_ssh_key_payload)['data']
ssh_keys_map[ssh_key['id']] = new_ssh_key['id']
ssh_key_name_map[new_ssh_key['attributes']
['name']] = new_ssh_key['id']
return ssh_keys_map, ssh_key_name_map
def migrate_ssh_key_files(api_new, ssh_key_name_map, ssh_key_file_path_map):
for ssh_key in ssh_key_file_path_map:
# Pull SSH Key Data
get_ssh_key = open(ssh_key_file_path_map[ssh_key], 'r')
ssh_key_data = get_ssh_key.read()
# Build the new ssh key file payload
new_ssh_key_file_payload = {
"data": {
"type": "ssh-keys",
"attributes": {
"value": ssh_key_data
}
}
}
# Upload the SSH Key File to the New Organization
# Note: The ssh_key_file_path_map must be created ahead of time with a format of {'ssh_key_name':'path/to/file'}
api_new.ssh_keys.update(
ssh_key_name_map[ssh_key], new_ssh_key_file_payload)
return
def migrate_agent_pools(api_original, api_new, tfe_org_original, tfe_org_new):
# Fetch Agent Pools from Existing Org
agent_pools = api_original.agents.list_pools(tfe_org_original)['data']
if agent_pools:
# Build the new agent pool payload
new_agent_pool_payload = {
"data": {
"type": "agent-pools"
}
}
new_org_agent_pools = api_new.agents.list_pools(tfe_org_new)['data']
if new_org_agent_pools:
agent_pool_id = api_new.agents.list_pools(tfe_org_new)[
'data'][0]['id']
else:
# Create Agent Pool in New Org
agent_pool_id = api_new.agents.create_pool(tfe_org_new)[
'data']['id']
return agent_pool_id
else:
return None
def migrate_workspaces(api_original, api_new, tfe_oauth_new, agent_pool_id):
# Fetch Workspaces from Existing Org
workspaces = api_original.workspaces.list()['data']
workspaces_map = {}
workspace_to_ssh_key_map = {}
for workspace in workspaces:
branch = "" if workspace['attributes']['vcs-repo'] is None else workspace['attributes']['vcs-repo']['branch']
ingress_submodules = False if workspace['attributes'][
'vcs-repo'] is None else workspace['attributes']['vcs-repo']['ingress-submodules']
default_branch = True if branch == "" else False
if workspace['attributes']['vcs-repo'] is not None:
if workspace['attributes']['execution-mode'] == 'agent':
# Build the new workspace payload
new_workspace_payload = {
"data": {
"attributes": {
"name": workspace['attributes']['name'],
"terraform_version": workspace['attributes']['terraform-version'],
"working-directory": workspace['attributes']['working-directory'],
"file-triggers-enabled": workspace['attributes']['file-triggers-enabled'],
"allow-destroy-plan": workspace['attributes']['allow-destroy-plan'],
"auto-apply": workspace['attributes']['auto-apply'],
"execution-mode": workspace['attributes']['execution-mode'],
"agent-pool-id": agent_pool_id,
"description": workspace['attributes']['description'],
"source-name": workspace['attributes']['source-name'],
"source-url": workspace['attributes']['source-url'],
"queue-all-runs": workspace['attributes']['queue-all-runs'],
"speculative-enabled": workspace['attributes']['speculative-enabled'],
"trigger-prefixes": workspace['attributes']['trigger-prefixes'],
"vcs-repo": {
"identifier": workspace['attributes']['vcs-repo-identifier'],
"oauth-token-id": <PASSWORD>,
"branch": branch,
"default-branch": default_branch,
"ingress-submodules": ingress_submodules
}
},
"type": "workspaces"
}
}
# Build the new Workspace
new_workspace = api_new.workspaces.create(
new_workspace_payload)
new_workspace_id = new_workspace["data"]["id"]
workspaces_map[workspace['id']] = new_workspace_id
try:
ssh_key = workspace['relationships']['ssh-key']['data']['id']
workspace_to_ssh_key_map[workspace['id']] = ssh_key
except:
continue
else:
# Build the new workspace payload
new_workspace_payload = {
"data": {
"attributes": {
"name": workspace['attributes']['name'],
"terraform_version": workspace['attributes']['terraform-version'],
"working-directory": workspace['attributes']['working-directory'],
"file-triggers-enabled": workspace['attributes']['file-triggers-enabled'],
"allow-destroy-plan": workspace['attributes']['allow-destroy-plan'],
"auto-apply": workspace['attributes']['auto-apply'],
"execution-mode": workspace['attributes']['execution-mode'],
"description": workspace['attributes']['description'],
"source-name": workspace['attributes']['source-name'],
"source-url": workspace['attributes']['source-url'],
"queue-all-runs": workspace['attributes']['queue-all-runs'],
"speculative-enabled": workspace['attributes']['speculative-enabled'],
"trigger-prefixes": workspace['attributes']['trigger-prefixes'],
"vcs-repo": {
"identifier": workspace['attributes']['vcs-repo-identifier'],
"oauth-token-id": <PASSWORD>,
"branch": branch,
"default-branch": default_branch,
"ingress-submodules": ingress_submodules
}
},
"type": "workspaces"
}
}
# Build the new Workspace
new_workspace = api_new.workspaces.create(
new_workspace_payload)
new_workspace_id = new_workspace["data"]["id"]
workspaces_map[workspace['id']] = new_workspace_id
try:
ssh_key = workspace['relationships']['ssh-key']['data']['id']
workspace_to_ssh_key_map[workspace['id']] = ssh_key
except:
continue
else:
if workspace['attributes']['execution-mode'] == 'agent':
# Build the new workspace payload
new_workspace_payload = {
"data": {
"attributes": {
"name": workspace['attributes']['name'],
"terraform_version": workspace['attributes']['terraform-version'],
"working-directory": workspace['attributes']['working-directory'],
"file-triggers-enabled": workspace['attributes']['file-triggers-enabled'],
"allow-destroy-plan": workspace['attributes']['allow-destroy-plan'],
"auto-apply": workspace['attributes']['auto-apply'],
"execution-mode": workspace['attributes']['execution-mode'],
"agent-pool-id": agent_pool_id,
"description": workspace['attributes']['description'],
"source-name": workspace['attributes']['source-name'],
"source-url": workspace['attributes']['source-url'],
"queue-all-runs": workspace['attributes']['queue-all-runs'],
"speculative-enabled": workspace['attributes']['speculative-enabled'],
"trigger-prefixes": workspace['attributes']['trigger-prefixes']
},
"type": "workspaces"
}
}
# Build the new Workspace
new_workspace = api_new.workspaces.create(
new_workspace_payload)
new_workspace_id = new_workspace['data']['id']
workspaces_map[workspace['id']] = new_workspace_id
try:
ssh_key = workspace['relationships']['ssh-key']['data']['id']
workspace_to_ssh_key_map[workspace['id']] = ssh_key
except:
continue
else:
# Build the new workspace payload
new_workspace_payload = {
"data": {
"attributes": {
"name": workspace['attributes']['name'],
"terraform_version": workspace['attributes']['terraform-version'],
"working-directory": workspace['attributes']['working-directory'],
"file-triggers-enabled": workspace['attributes']['file-triggers-enabled'],
"allow-destroy-plan": workspace['attributes']['allow-destroy-plan'],
"auto-apply": workspace['attributes']['auto-apply'],
"execution-mode": workspace['attributes']['execution-mode'],
"description": workspace['attributes']['description'],
"source-name": workspace['attributes']['source-name'],
"source-url": workspace['attributes']['source-url'],
"queue-all-runs": workspace['attributes']['queue-all-runs'],
"speculative-enabled": workspace['attributes']['speculative-enabled'],
"trigger-prefixes": workspace['attributes']['trigger-prefixes']
},
"type": "workspaces"
}
}
# Build the new Workspace
new_workspace = api_new.workspaces.create(
new_workspace_payload)
new_workspace_id = new_workspace['data']['id']
workspaces_map[workspace['id']] = new_workspace_id
try:
ssh_key = workspace['relationships']['ssh-key']['data']['id']
workspace_to_ssh_key_map[workspace['id']] = ssh_key
except:
continue
return workspaces_map, workspace_to_ssh_key_map
def migrate_all_state(api_original, api_new, tfe_org_original, workspaces_map):
for workspace_id in workspaces_map:
workspace_name = api_original.workspaces.show(workspace_id=workspace_id)[
'data']['attributes']['name']
# Set proper state filters to pull state versions for each workspace
state_filters = [
{
"keys": ["workspace", "name"],
"value": workspace_name
},
{
"keys": ["organization", "name"],
"value": tfe_org_original
}
]
state_versions = api_original.state_versions.list(
filters=state_filters)['data']
if state_versions:
for state_version in reversed(state_versions):
state_url = state_version['attributes']['hosted-state-download-url']
pull_state = urllib.request.urlopen(state_url)
state_data = pull_state.read()
state_serial = json.loads(state_data)['serial']
state_hash = hashlib.md5()
state_hash.update(state_data)
state_md5 = state_hash.hexdigest()
state_b64 = base64.b64encode(state_data).decode("utf-8")
# Build the new state payload
create_state_version_payload = {
"data": {
"type": "state-versions",
"attributes": {
"serial": state_serial,
"md5": state_md5,
"state": state_b64
}
}
}
# Migrate state to the new Workspace
api_new.workspaces.lock(workspaces_map[workspace_id], {
"reason": "migration script"})
api_new.state_versions.create(
workspaces_map[workspace_id], create_state_version_payload)
api_new.workspaces.unlock(workspaces_map[workspace_id])
return
def migrate_current_state(api_original, api_new, tfe_org_original, workspaces_map):
for workspace_id in workspaces_map:
workspace_name = api_original.workspaces.show(workspace_id=workspace_id)[
'data']['attributes']['name']
# Set proper state filters to pull state versions for each workspace
state_filters = [
{
"keys": ["workspace", "name"],
"value": workspace_name
},
{
"keys": ["organization", "name"],
"value": tfe_org_original
}
]
state_versions = api_original.state_versions.list(
filters=state_filters)['data']
if state_versions:
current_version = api_original.state_versions.get_current(workspace_id)[
'data']
state_url = current_version['attributes']['hosted-state-download-url']
pull_state = urllib.request.urlopen(state_url)
state_data = pull_state.read()
state_serial = json.loads(state_data)['serial']
state_hash = hashlib.md5()
state_hash.update(state_data)
state_md5 = state_hash.hexdigest()
state_b64 = base64.b64encode(state_data).decode("utf-8")
# Build the new state payload
create_state_version_payload = {
"data": {
"type": "state-versions",
"attributes": {
"serial": state_serial,
"md5": state_md5,
"state": state_b64
}
}
}
# Migrate state to the new Workspace
api_new.workspaces.lock(workspaces_map[workspace_id], {
"reason": "migration script"})
api_new.state_versions.create(
workspaces_map[workspace_id], create_state_version_payload)
api_new.workspaces.unlock(workspaces_map[workspace_id])
return
def migrate_workspace_variables(api_original, api_new, tfe_org_original, workspaces_map, return_sensitive_variable_data=False):
sensitive_variable_data = []
for workspace_id in workspaces_map:
new_workspace_id = workspaces_map[workspace_id]
# Pull Variables from the Old Workspace
workspace_variables = api_original.workspace_vars.list(workspace_id)[
'data']
for variable in reversed(workspace_variables):
variable_key = variable['attributes']['key']
variable_value = variable['attributes']['value']
variable_category = variable['attributes']['category']
variable_hcl = variable['attributes']['hcl']
variable_description = variable['attributes']['description']
variable_sensitive = variable['attributes']['sensitive']
# Build the new variable payload
new_variable_payload = {
"data": {
"type": "vars",
"attributes": {
"key": variable_key,
"value": variable_value,
"description": variable_description,
"category": variable_category,
"hcl": variable_hcl,
"sensitive": variable_sensitive
}
}
}
# Migrate variables to the new Workspace
new_variable = api_new.workspace_vars.create(
new_workspace_id, new_variable_payload)['data']
new_variable_id = new_variable['id']
if variable_sensitive and return_sensitive_variable_data:
workspace_name = api_new.workspaces.show(workspace_id=workspace_id)[
'data']['attributes']['name']
# Build the sensitive variable map
variable_data = {
"workspace_name": workspace_name,
"workspace_id": new_workspace_id,
"variable_id": new_variable_id,
"variable_key": variable_key,
"variable_value": variable_value,
"variable_description": variable_description,
"variable_category": variable_category,
"variable_hcl": variable_hcl
}
sensitive_variable_data.append(variable_data)
return sensitive_variable_data
# Note: The sensitive_variable_data_map map must be created ahead of time. The easiest way to do this is to
# update the value for each variable in the list returned by the migrate_workspace_variables method
def migrate_workspace_sensitive_variables(api_new, sensitive_variable_data_map):
for sensitive_variable in sensitive_variable_data_map:
# Build the new variable payload
update_variable_payload = {
"data": {
"id": sensitive_variable['variable_id'],
"attributes": {
"key": sensitive_variable['variable_key'],
"value": sensitive_variable['variable_value'],
"description": sensitive_variable['variable_description'],
"category": sensitive_variable['variable_category'],
"hcl": sensitive_variable['variable_hcl'],
"sensitive": 'true'
},
"type": "vars"
}
}
# Update the Sensitive Variable value in the New Workspace
api_new.workspace_vars.update(
sensitive_variable['workspace_id'], sensitive_variable['variable_id'], update_variable_payload)
return
def migrate_ssh_keys_to_workspaces(api_original, api_new, workspaces_map, workspace_to_ssh_key_map, ssh_keys_map):
if workspace_to_ssh_key_map:
for k, v in workspace_to_ssh_key_map.items():
# Build the new ssh key payload
new_workspace_ssh_key_payload = {
"data": {
"attributes": {
"id": ssh_keys_map[v]
},
"type": "workspaces"
}
}
# Add SSH Keys to the new Workspace
api_new.workspaces.assign_ssh_key(
workspaces_map[k], new_workspace_ssh_key_payload)
return
def migrate_workspace_run_triggers(api_original, api_new, workspaces_map):
for workspace_id in workspaces_map:
workspace_filters = [
{
"keys": ["run-trigger", "type"],
"value": "inbound"
}
]
# Pull Run Triggers from the Old Workspace
run_triggers = api_original.run_triggers.list(
workspace_id, filters=workspace_filters, page_size=100)['data']
if run_triggers:
for run_trigger in run_triggers:
source_workspace_id = run_trigger['relationships']['sourceable']['data']['id']
# Build the new run trigger payload
new_run_trigger_payload = {
"data": {
"relationships": {
"sourceable": {
"data": {
"id": workspaces_map[source_workspace_id],
"type": "workspaces"
}
}
}
}
}
# Add Run Triggers to the new Workspace
api_new.run_triggers.create(
workspaces_map[workspace_id], new_run_trigger_payload)
return
def migrate_workspace_notifications(api_original, api_new, workspaces_map):
for workspace_id in workspaces_map:
# Pull Notifications from the Old Workspace
notifications = api_original.notification_configs.list(workspace_id)[
'data']
if notifications:
for notification in notifications:
if notification['attributes']['destination-type'] == 'email':
# Build the new notification payload
new_notification_payload = {
"data": {
"type": "notification-configurations",
"attributes": {
"destination-type": notification['attributes']['destination-type'],
"enabled": notification['attributes']['enabled'],
"name": notification['attributes']['name'],
"triggers": notification['attributes']['triggers']
},
"relationships": {
"users": {
"data": notification['relationships']['users']['data']
}
}
}
}
# Add Notifications to the new Workspace
api_new.notification_configs.create(
workspaces_map[workspace_id], new_notification_payload)
else:
# Build the new notification payload
new_notification_payload = {
"data": {
"type": "notification-configurations",
"attributes": {
"destination-type": notification['attributes']['destination-type'],
"enabled": notification['attributes']['enabled'],
"name": notification['attributes']['name'],
"token": notification['attributes']['token'],
"url": notification['attributes']['url'],
"triggers": notification['attributes']['triggers']
}
}
}
# Add Notifications to the new Workspace
api_new.notification_configs.create(
workspaces_map[workspace_id], new_notification_payload)
return
def migrate_workspace_team_access(api_original, api_new, workspaces_map, teams_map):
for workspace_id in workspaces_map:
# Set proper workspace team filters to pull team access for each workspace
workspace_team_filters = [
{
"keys": ["workspace", "id"],
"value": workspace_id
}
]
# Pull Teams from the Old Workspace
workspace_teams = api_original.team_access.list(
filters=workspace_team_filters)["data"]
for workspace_team in workspace_teams:
if workspace_team['attributes']['access'] == 'custom':
# Build the new team access payload
new_workspace_team_payload = {
"data": {
"attributes": {
"access": workspace_team['attributes']['access'],
"runs": workspace_team['attributes']['runs'],
"variables": workspace_team['attributes']['variables'],
"state-versions": workspace_team['attributes']['state-versions'],
"plan-outputs": "none",
"sentinel-mocks": workspace_team['attributes']['sentinel-mocks'],
"workspace-locking": workspace_team['attributes']['workspace-locking']
},
"relationships": {
"workspace": {
"data": {
"type": "workspaces",
"id": workspaces_map[workspace_id]
}
},
"team": {
"data": {
"type": "teams",
"id": teams_map[workspace_team['relationships']['team']['data']['id']]
}
}
},
"type": "team-workspaces"
}
}
# Create the Team Workspace Access map for the new Workspace
api_new.team_access.add_team_access(new_workspace_team_payload)
else:
# Build the new team access payload
new_workspace_team_payload = {
"data": {
"attributes": {
"access": workspace_team['attributes']['access'],
},
"relationships": {
"workspace": {
"data": {
"type": "workspaces",
"id": workspaces_map[workspace_id]
}
},
"team": {
"data": {
"type": "teams",
"id": teams_map[workspace_team['relationships']['team']['data']['id']]
}
}
},
"type": "team-workspaces"
}
}
# Create the Team Workspace Access map for the new Workspace
api_new.team_access.add_team_access(new_workspace_team_payload)
return
def migrate_configuration_versions(api_original, api_new, workspaces_map):
workspace_to_configuration_version_map = {}
for workspace_id in workspaces_map:
workspace_name = api_original.workspaces.show(workspace_id=workspace_id)[
'data']['attributes']['name']
# Fetch Configuration Versions for the Existing Workspace
configuration_versions = api_original.config_versions.list(workspace_id)[
'data']
if configuration_versions:
latest_configuration_version = configuration_versions[0]
if latest_configuration_version['attributes']['source'] == 'tfe-api':
# Build the new configuration version payload
new_configuration_version_payload = {
"data": {
"type": "configuration-versions",
"attributes": {
"auto-queue-runs": latest_configuration_version['attributes']['auto-queue-runs']
}
}
}
# Create a configuration version in the New Organization
new_configuration_version = api_new.config_versions.create(
workspaces_map[workspace_id], new_configuration_version_payload)['data']
workspace_to_configuration_version_map[workspace_name] = new_configuration_version['id']
return workspace_to_configuration_version_map
def migrate_configuration_files(api_new, workspace_to_configuration_version_map, workspace_to_file_path_map):
for workspace_name in workspace_to_file_path_map:
# Upload the Configuration File to the New Workspace
# Note: The workspace_to_file_path_map must be created ahead of time with a format of {'workspace_name':'path/to/file'}
api_new.config_versions.upload(
workspace_to_file_path_map[workspace_name], workspace_to_configuration_version_map[workspace_name])
return
def migrate_policies(api_original, api_new, tfe_token_original, tfe_url_original):
# Pull Policies from the Old Organization
policies = api_original.policies.list()['data']
policies_map = {}
if policies:
for policy in policies:
policy_id = policy['id']
headers = {'Authorization': 'Bearer %s' % (
tfe_token_original), 'Content-Type': 'application/vnd.api+json'}
policy_download_url = '%s/api/v2/policies/%s/download' % (
tfe_url_original, policy_id)
# Retrieve the Policy Content
policy_request = urllib.request.Request(
policy_download_url, headers=headers)
pull_policy = urllib.request.urlopen(policy_request)
policy_data = pull_policy.read()
policy_b64 = policy_data.decode("utf-8")
# Build the new policy payload
new_policy_payload = {
"data": {
"attributes": {
"name": policy['attributes']['name'],
"description": policy['attributes']['description'],
"enforce": [
{
"path": policy['attributes']['enforce'][0]['path'],
"mode": policy['attributes']['enforce'][0]['mode']
}
],
},
"type": "policies"
}
}
# Create the policy in the New Organization
new_policy = api_new.policies.create(new_policy_payload)
new_policy_id = new_policy['data']['id']
policies_map[policy_id] = new_policy_id
# Upload the policy content to the new policy in the New Organization
api_new.policies.upload(new_policy_id, policy_b64)
return policies_map
else:
return
def migrate_policy_sets(api_original, api_new, tfe_oauth_new, workspaces_map, policies_map):
# Pull Policy Sets from the Old Organization
policy_sets = api_original.policy_sets.list(
page_size=50, include='policies,workspaces')['data']
policy_sets_map = {}
for policy_set in policy_sets:
if policy_set['attributes']['versioned']:
if policy_set['attributes']['global']:
# Build the new policy set payload
new_policy_set_payload = {
"data": {
"type": "policy-sets",
"attributes": {
"name": policy_set['attributes']['name'],
"description": policy_set['attributes']['name'],
"global": policy_set['attributes']['global'],
"policies-path": policy_set['attributes']['policies-path'],
"vcs-repo": {
"branch": policy_set['attributes']['vcs-repo']['branch'],
"identifier": policy_set['attributes']['vcs-repo']['identifier'],
"ingress-submodules": policy_set['attributes']['vcs-repo']['ingress-submodules'],
"oauth-token-id": tfe_oauth_new
}
},
"relationships": {
}
}
}
# Create the policy set in the New Organization
new_policy_set = api_new.policy_sets.create(
new_policy_set_payload)
policy_sets_map[policy_set['id']
] = new_policy_set['data']['id']
else:
workspace_ids = policy_set['relationships']['workspaces']['data']
for workspace_id in workspace_ids:
workspace_id['id'] = workspaces_map[workspace_id['id']]
# Build the new policy set payload
new_policy_set_payload = {
"data": {
"type": "policy-sets",
"attributes": {
"name": policy_set['attributes']['name'],
"description": policy_set['attributes']['name'],
"global": policy_set['attributes']['global'],
"policies-path": policy_set['attributes']['policies-path'],
"vcs-repo": {
"branch": policy_set['attributes']['vcs-repo']['branch'],
"identifier": policy_set['attributes']['vcs-repo']['identifier'],
"ingress-submodules": policy_set['attributes']['vcs-repo']['ingress-submodules'],
"oauth-token-id": <PASSWORD>
}
},
"relationships": {
"workspaces": {
"data":
workspace_ids
}
}
}
}
# Create the policy set in the New Organization
new_policy_set = api_new.policy_sets.create(
new_policy_set_payload)
policy_sets_map[policy_set['id']
] = new_policy_set['data']['id']
else:
if policy_set['attributes']['global']:
policy_ids = policy_set['relationships']['policies']['data']
for policy_id in policy_ids:
policy_id['id'] = policies_map[policy_id['id']]
# Build the new policy set payload
new_policy_set_payload = {
"data": {
"type": "policy-sets",
"attributes": {
"name": policy_set['attributes']['name'],
"description": policy_set['attributes']['name'],
"global": policy_set['attributes']['global'],
},
"relationships": {
"policies": {
"data":
policy_ids
}
}
}
}
# Create the policy set in the New Organization
new_policy_set = api_new.policy_sets.create(
new_policy_set_payload)
policy_sets_map[policy_set['id']
] = new_policy_set['data']['id']
else:
policy_ids = policy_set['relationships']['policies']['data']
for policy_id in policy_ids:
policy_id['id'] = policies_map[policy_id['id']]
workspace_ids = policy_set['relationships']['workspaces']['data']
for workspace_id in workspace_ids:
workspace_id['id'] = workspaces_map[workspace_id['id']]
# Build the new policy set payload
new_policy_set_payload = {
"data": {
"type": "policy-sets",
"attributes": {
"name": policy_set['attributes']['name'],
"description": policy_set['attributes']['name'],
"global": policy_set['attributes']['global'],
},
"relationships": {
"policies": {
"data":
policy_ids
},
"workspaces": {
"data":
workspace_ids
}
}
}
}
# Create the policy set in the New Organization
new_policy_set = api_new.policy_sets.create(
new_policy_set_payload)
policy_sets_map[policy_set['id']
] = new_policy_set['data']['id']
return policy_sets_map
def migrate_policy_set_parameters(api_original, api_new, policy_sets_map, return_sensitive_variable_data=False):
sensitive_policy_set_parameter_data = []
for policy_set_id in policy_sets_map:
new_policy_set_id = policy_sets_map[policy_set_id]
# Pull Policy Sets from the Old Organization
policy_set_parameters = api_original.policy_set_params.list(
policy_set_id)['data']
if policy_set_parameters:
for policy_set_parameter in reversed(policy_set_parameters):
policy_set_parameter_key = policy_set_parameter['attributes']['key']
policy_set_parameter_value = policy_set_parameter['attributes']['value']
policy_set_parameter_category = policy_set_parameter['attributes']['category']
policy_set_parameter_sensitive = policy_set_parameter['attributes']['sensitive']
# Build the new policy set parameter payload
new_policy_parameter_payload = {
"data": {
"type": "vars",
"attributes": {
"key": policy_set_parameter_key,
"value": policy_set_parameter_value,
"category": policy_set_parameter_category,
"sensitive": policy_set_parameter_sensitive
}
}
}
# Create the policy set parameter in the New Organization
new_parameter = api_new.policy_set_params.create(
new_policy_set_id, new_policy_parameter_payload)['data']
new_parameter_id = new_parameter['id']
if policy_set_parameter_sensitive and return_sensitive_variable_data:
policy_set_name = api_new.policy_sets.show(
policy_set_id)['data']['attributes']['name']
# Build the sensitive policy set parameter map
parameter_data = {
"policy_set_name": policy_set_name,
"policy_set_id": new_policy_set_id,
"parameter_id": new_parameter_id,
"parameter_key": policy_set_parameter_key,
"parameter_value": policy_set_parameter_value,
"parameter_category": policy_set_parameter_category
}
sensitive_policy_set_parameter_data.append(parameter_data)
return sensitive_policy_set_parameter_data
# Note: The sensitive_policy_set_parameter_data_map map must be created ahead of time. The easiest way to do this is to
# update the value for each variable in the list returned by the migrate_policy_set_parameters method
def migrate_policy_set_sensitive_parameters(api_new, sensitive_policy_set_parameter_data_map):
for sensitive_policy_set_parameter in sensitive_policy_set_parameter_data_map:
# Build the new parameter payload
update_policy_set_parameter_payload = {
"data": {
"id": sensitive_policy_set_parameter['parameter_id'],
"attributes": {
"key": sensitive_policy_set_parameter['parameter_key'],
"value": sensitive_policy_set_parameter['parameter_value'],
"category": "policy-set",
"sensitive": 'true'
},
"type": "vars"
}
}
# Update the Sensitive parameter value in the Policy Set
api_new.policy_set_params.update(
sensitive_policy_set_parameter['policy_set_id'], sensitive_policy_set_parameter['parameter_id'], update_policy_set_parameter_payload)
return
# TO DO: Account for Modules uploaded via VCS and API
# TO DO: Account for ALL versions of Module
# TO DO: Note OAuth token challenges (ex. if they don't all share the same token)
def migrate_registry_modules(api_original, api_new, tfe_org_original, tfe_oauth_new):
modules = api_original.registry_modules.list()['modules']
for module in modules:
# Pull VCS Modules from the Old Organization
module_data = api_original.registry_modules.show(
tfe_org_original, module['name'], module['provider'])['data']
# Build the new Module payload
new_module_payload = {
"data": {
"attributes": {
"vcs-repo": {
"identifier": module_data['attributes']['vcs-repo']['identifier'],
"oauth-token-id": tfe_oauth_new,
"display_identifier": module_data['attributes']['vcs-repo']['display-identifier']
}
},
"type": "registry-modules"
}
}
# Create the Module in the New Organization
api_new.registry_modules.publish_from_vcs(new_module_payload)
return
<file_sep>def delete_teams(api_new):
teams = api_new.teams.list()['data']
if teams:
for team in teams:
if team['attributes']['name'] != "owners":
api_new.teams.destroy(team['id'])
return
def delete_ssh_keys(api_new):
ssh_keys = api_new.ssh_keys.list()["data"]
if ssh_keys:
for ssh_key in ssh_keys:
api_new.ssh_keys.destroy(ssh_key['id'])
return
def delete_workspaces(api_new):
workspaces = api_new.workspaces.list()['data']
if workspaces:
for workspace in workspaces:
api_new.workspaces.destroy(workspace['id'])
return
def delete_variables(api_new):
workspaces = api_new.workspaces.list()['data']
for workspace in workspaces:
variables = api_new.workspace_vars.list(workspace['id'])['data']
for variable in variables:
api_new.workspace_vars.destroy(workspace['id'], variable['id'] )
return
def delete_workspace_notifications(api_new):
workspaces = api_new.workspaces.list()['data']
for workspace in workspaces:
notifications = api_new.notification_configs.list(workspace['id'])['data']
if notifications:
for notification in notifications:
api_new.notification_configs.destroy(notification['id'])
return
def delete_policies(api_new):
policies = api_new.policies.list()['data']
if policies:
for policy in policies:
api_new.policies.destroy(policy['id'])
return
def delete_policy_sets(api_new):
policy_sets = api_new.policy_sets.list(
page_size=50, include="policies,workspaces")['data']
if policy_sets:
for policy_set in policy_sets:
api_new.policy_sets.destroy(policy_set['id'])
return
def delete_policy_set_parameters(api_new):
policy_sets = api_new.policy_sets.list(
page_size=50, include="policies,workspaces")['data']
if policy_sets:
for policy_set in policy_sets:
parameters = api_new.policy_set_params.list(policy_set['id'])['data']
for parameter in parameters:
api_new.policy_set_params.destroy(policy_set['id'], parameter['id'])
return
def delete_modules(api_new):
modules = api_new.registry_modules.list()['modules']
if modules:
for module in modules:
api_new.registry_modules.destroy(module['name'])
return
def delete_all(api_new):
delete_workspaces(api_new)
print('workspaces successfully deleted')
delete_ssh_keys(api_new)
print('ssh keys successfully deleted')
delete_teams(api_new)
print('teams successfully deleted')
delete_policies(api_new)
print('policies successfully deleted')
delete_policy_sets(api_new)
print('policy sets successfully deleted')
delete_modules(api_new)
print('modules successfully deleted')
return
<file_sep>import os
from terrasnek.api import TFC
from functions import *
# SOURCE ORG
TFE_TOKEN_ORIGINAL = os.getenv("TFE_TOKEN_ORIGINAL", None)
TFE_URL_ORIGINAL = os.getenv("TFE_URL_ORIGINAL", None)
TFE_ORG_ORIGINAL = os.getenv("TFE_ORG_ORIGINAL", None)
api_original = TFC(TFE_TOKEN_ORIGINAL, url=TFE_URL_ORIGINAL)
api_original.set_org(TFE_ORG_ORIGINAL)
# NEW ORG
TFE_TOKEN_NEW = os.getenv("TFE_TOKEN_NEW", None)
TFE_URL_NEW = os.getenv("TFE_URL_NEW", None)
TFE_ORG_NEW = os.getenv("TFE_ORG_NEW", None)
TFE_OAUTH_NEW = os.getenv("TFE_OAUTH_NEW", None)
api_new = TFC(TFE_TOKEN_NEW, url=TFE_URL_NEW)
api_new.set_org(TFE_ORG_NEW)
if __name__ == "__main__":
teams_map = migrate_teams(api_original, api_new)
print('teams successfully migrated')
# migrate_organization_memberships(api_original, api_new, teams_map)
# print('organization memberships successfully migrated')
ssh_keys_map, ssh_key_name_map = migrate_ssh_keys(api_original, api_new)
print('ssh keys successfully migrated')
# migrate_ssh_key_files(api_new, ssh_key_name_map, ssh_key_file_path_map)
# print('ssh key files successfully migrated')
agent_pool_id = migrate_agent_pools(
api_original, api_new, TFE_ORG_ORIGINAL, TFE_ORG_NEW)
print('agent pools successfully migrated')
workspaces_map, workspace_to_ssh_key_map = migrate_workspaces(
api_original, api_new, TFE_OAUTH_NEW, agent_pool_id)
print('workspaces successfully migrated')
# migrate_all_state(api_original, api_new, TFE_ORG_ORIGINAL, workspaces_map)
migrate_current_state(api_original, api_new,
TFE_ORG_ORIGINAL, workspaces_map)
print('state successfully migrated')
# Note: if you wish to generate a map of Sensitive variables that can be used to update
# those values via the migrate_workspace_sensitive_variables method, pass True as the final argument (defaults to False)
sensitive_variable_data = migrate_workspace_variables(
api_original, api_new, TFE_ORG_ORIGINAL, workspaces_map)
print('workspace variables successfully migrated')
# migrate_workspace_sensitive_variables(api_new, sensitive_variable_data_map)
# print('workspace sensitive variables successfully migrated')
migrate_ssh_keys_to_workspaces(
api_original, api_new, workspaces_map, workspace_to_ssh_key_map, ssh_keys_map)
print('workspace ssh keys successfully migrated')
migrate_workspace_run_triggers(api_original, api_new, workspaces_map)
print('workspace run triggers successfully migrated')
migrate_workspace_notifications(api_original, api_new, workspaces_map)
print('workspace notifications successfully migrated')
migrate_workspace_team_access(
api_original, api_new, workspaces_map, teams_map)
print('workspace team access successfully migrated')
workspace_to_configuration_version_map = migrate_configuration_versions(
api_original, api_new, workspaces_map)
print('workspace configuration versions successfully migrated')
# migrate_configuration_files(api_new, workspace_to_configuration_version_map, workspace_to_file_path_map)
# print('workspace configuration files successfully migrated)
policies_map = migrate_policies(
api_original, api_new, TFE_TOKEN_ORIGINAL, TFE_URL_ORIGINAL)
print('policies successfully migrated')
policy_sets_map = migrate_policy_sets(
api_original, api_new, TFE_OAUTH_NEW, workspaces_map, policies_map)
print('policy sets successfully migrated')
# Note: if you wish to generate a map of Sensitive policy set parameters that can be used to update
# those values via the migrate_policy_set_sensitive_variables method, pass True as the final argument (defaults to False)
sensitive_policy_set_parameter_data = migrate_policy_set_parameters(
api_original, api_new, policy_sets_map)
print('policy set parameters successfully migrated')
# migrate_policy_set_sensitive_parameters(api_new, sensitive_policy_set_parameter_data_map)
# print('policy set sensitive parameters successfully migrated')
migrate_registry_modules(api_original, api_new,
TFE_ORG_ORIGINAL, TFE_OAUTH_NEW)
print('registry modules successfully migrated')
print('\n')
print('MIGRATION MAPS:')
print('teams_map:', teams_map)
print('\n')
print('ssh_keys_map:', ssh_keys_map)
print('\n')
print('ssh_keys_map:', ssh_key_name_map)
print('\n')
print('workspaces_map:', workspaces_map)
print('\n')
print('workspace_to_ssh_key_map:', workspace_to_ssh_key_map)
print('\n')
print('workspace_to_configuration_version_map:',
workspace_to_configuration_version_map)
print('\n')
print('policies_map:', policies_map)
print('\n')
print('policy_sets_map:', policy_sets_map)
print('\n')
print('sensitive_policy_set_parameter_data:',
sensitive_policy_set_parameter_data)
print('\n')
print('sensitive_variable_data:', sensitive_variable_data)
| 7c81342cce0103991557774a489d7467f0719226 | [
"Markdown",
"Python"
] | 4 | Markdown | andrefcpimentel2/tfe-tfc-migration-tool | a36cdc9daeb0b81d3c60ccc0c30ded8f47e8aeae | ae57d65416e8394e7881b8744fdc3c99d4876a9b |
refs/heads/master | <repo_name>doogrammargood/indep_num<file_sep>/test_ga.py
from sage.all import *
from ga import GA
import functions as FUN
import bronkerbosch as BON
#from main import cr3, cr4, fit_eigen_values
import numpy as np
import lovasz as LOV
def fit(x):
return 10 - (x[0] + x[1]) ** 2
def mu(x):
new_x = x.copy()
i = np.random.randint(len(x))
new_x[i] = np.random.randint(-5, 5)
return new_x
def cr(x1, x2):
new_x = x1.copy()
new_x[1] = x2[1]
return new_x
g = GA(fit, mu, cr, 0.5, 0.1)
pop = [
[5, 1],
[3, 7],
[12, 2],
[1, 2],
[13, 3],
[1, 25],
[-1, 7],
[32, 34],
[60, 50],
[100, 1],
[70, 21]
]
#r = g.run(pop, 10000, 8)
#print(r)
graph_list = [ graphs.BidiakisCube(),
graphs.ButterflyGraph(),
graphs.HeawoodGraph(),
graphs.HoffmanGraph(),
graphs.CubeGraph(4), #cospectral with above
graphs.DejterGraph(),
graphs.DyckGraph(),
graphs.GrotzschGraph(),
graphs.HoltGraph()]
def test_crossover_function(l):
"""Expect l to be a crossover function.
generates two random graphs and checks that l(g1, g2)
does not error out and returns a graph of the same size."""
g1 = graphs.RandomGNP(20, .5)
g2 = graphs.RandomGNP(20, .5)
child_graph = l(g1, g2)
assert child_graph.order() == 20
def test_cr3():
"""This test does not work."""
for g1 in graph_list:
for g2 in graph_list:
q = FUN.cr3(g1, g2)
assert q.order() == g1.order() + g2.order()
def test_cr4():
"""This function is idempotent"""
for g in graph_list:
q = FUN.cr4(g,g)
assert q.is_isomorphic(g)
def test_eigen_fitness():
"""The complete graph should have eigenvalues [d, -1 -1 ... -1]
where d is the degree."""
k = graphs.CompleteGraph(15)
value = FUN.fit_eigen_values(k)
assert abs(value - 13/14.0) < 0.001
g1 = graphs.PetersenGraph()
g2 = graphs.ButterflyGraph()
g = k + g2
print FUN.fit_eigen_values(g)
def test_remove_extra_edges():
"""Checks that remove_extra_edges does not affect the independence number."""
g = graphs.RandomGNP(20, .5)
r=g
r, _ = FUN.remove_extra_edges(r)
assert len(r.independent_set()) == len(g.independent_set())
def test_update_independent_sets():
"""Generates a random graph, finds the independent sets,
performs remove_extra_edges, and finds the independent sets again to
ensure that remove_extra_edges returns the new independent sets correctly.
"""
g = graphs.RandomGNP(10, .5)
indep_sets = BON.find_cliques(BON.dict_from_adjacency_matrix(g.complement()))
new_graph, new_indep_sets = FUN.remove_extra_edges(g)
correct_indep_sets = BON.find_cliques(BON.dict_from_adjacency_matrix(new_graph.complement()))
for c in correct_indep_sets:
assert c in new_indep_sets
for i in new_indep_sets:
assert i in correct_indep_sets
def test_add_edge_to_max_indep_set():
g = graphs.RandomGNP(10, .5)
new_graph = FUN.add_edge_to_max_indep_set(g)
print "test complete"
"""aggregate tests"""
def helper_tests():
"""runs all the helper tests"""
test_update_independent_sets()
test_remove_extra_edges()
def crossover_tests():
"""runs all the crossover tests"""
crossovers = [FUN.cr4,FUN.cr5,FUN.cr6,FUN.cr7,FUN.cr8]
#These are the crossover functions which preserve the order of the graph.
for c in crossovers:
test_crossover_function(c)
test_cr4()
def test_mutation_function(l):
"""expect l to be a mutation function."""
g = graphs.RandomGNP(20, .5)
mutant_graph = l(g)
#print l.__name__
#print mutant_graph.order()
assert mutant_graph.order() == 20
def mutation_tests():
mutation_functions = [FUN.mu, FUN.mutate_avoid_large_subgraph,FUN.mutate_add_then_remove_edges, FUN.add_edge_to_max_indep_set]
for m in mutation_functions:
test_mutation_function(m)
def fitness_tests():
return
"""aggregate tests"""
def test_run_ga():
"""Runs the genetic algorithm with various mutation and crossover functions to make
sure that nothing errors out."""
n = 10 # graph size
pop_size = 100
threshold = 0.130
pop = [FUN.rand_graph(n, randint(n, n*(n-1)/2 + 1)) for _ in range(pop_size)]
ga1 = GA(FUN.fit, FUN.mutate_add_then_remove_edges, FUN.cr6, 0.3, 0.2)
results1 = ga1.run(pop, 20, threshold)
ga2 = GA(FUN.fit_with_regularity, FUN.mu, FUN.cr7, 0.3, 0.2)
results2 = ga2.run(pop, 20, threshold)
ga3 = GA(FUN.fit, FUN.mutate_avoid_large_subgraph, FUN.cr5, 0.3, 0.2)
results3 = ga3.run(pop, 20, threshold)
def run_tests():
for i in range(20):
helper_tests()
crossover_tests()
mutation_tests()
fitness_tests()
#test_run_ga()
run_tests()
#test_add_edge_to_max_indep_set()
#test_remove_extra_edges()
#run_tests()
def test_fit_regularity():
g = graphs.RandomGNP(10, .5)
print FUN.fit_regularity(g)
def test_large_lovasz_subgraph():
g = graphs.RandomGNP(10, .5)
#FUN._subgraph_mutate(g)
old_lov_theta = g.lovasz_theta()
for i in range(10):
FUN.mutate_avoid_large_subgraph(g)
print "old theta: ", old_lov_theta
ans = LOV.lovasz_theta(g, long_return = True)
theta = ans['theta']
B = ans['B']
print theta, B
diag = np.diagonal(B)
#values = [b**0.5 for b in diag]
print diag * theta
print sum(diag*theta)
assert abs(sum(diag*theta) - theta) < 0.01
#test_fit_regularity()
#test_remove_extra_edges()
#test_large_lovasz_subgraph()
<file_sep>/functions.py
"""A library of fitness, mutation, and crossover functions."""
import sys
import numpy as np
import itertools
import bronkerbosch as BON
import random
import lovasz as LOV
from numpy.random import randint, rand
from sage.all import *
from sage.graphs.graph_generators_pyx import RandomGNP
from random import shuffle
"""Helper Functions"""
def remove_extra_edges(g):
"""Calculates the maximal independent sets of g.
If an edge doesnt intersect a maximal independent set, it can be removed
without increasing the size of the independence number.
We do this repeatedly until no such edges remain.
"""
new_graph = g.copy()
edges = len(new_graph.edges())
indep_sets = None
new_graph, indep_sets = _remove_extra_edge(new_graph, indep_sets)
while(len(new_graph.edges()) != edges ):
edges = len(new_graph.edges())
new_graph, indep_sets = _remove_extra_edge(new_graph, indep_sets)
return new_graph, indep_sets
def _can_remove(e, max_indep_sets):
"""Returns true if we can remove this edge without affecting the independence number.
If e[0] is in some max independent set, i, then i-{e[0]} U {e[1]} must be another max indep. set
"""
sets_with_endpoint0 = [m for m in max_indep_sets if e[0] in m]
for s in sets_with_endpoint0:
if set([v for v in s if v != e[0] ] +[e[1]]) in max_indep_sets:
return False
return True
def _update_indep_sets(g, e, indep_sets ):
"""g is the new graph, with edge e removed.
e is the edge which was removed,
and indep_sets is a list of the maximal independent sets before the edge was removed.
Returns the list of maximal independent sets of g.
"""
non_neighbors_of_e =set([v for v in g.vertices() if not v in ( g.neighbors(e[0]) + g.neighbors(e[1]) )])
subgraph_without_e = g.subgraph(non_neighbors_of_e)
#new_indep_sets = BON.cliques_of_graph(subgraph_without_e.complement())
new_indep_sets = [i.intersection(non_neighbors_of_e).union({e[0],e[1]}) for i in indep_sets]
#[i for i in indep_sets if i not]
extra_indep_sets=[]
for i in indep_sets:
if not (e[0] in i ) and ( i.union({e[1]}) in new_indep_sets ):
if not (e[1] in i ) and (i.union({e[0]}) in new_indep_sets ):
extra_indep_sets.append(i)
new_indep_sets = new_indep_sets + extra_indep_sets
return new_indep_sets
def _remove_extra_edge(g, indep_sets = None):
"""Returns a new graph by removing an edge from g. """
#dict = BON.dict_from_adjacency_matrix(g.complement())
#if indep_sets is None:
# indep_sets = BON.find_cliques(dict) #a list of all maximal-by-inclusion independent sets.
indep_sets = BON.cliques_of_graph(g.complement())
max_size = 0
max_indep_sets = [] #a list of all maximal-by-size independent sets
new_graph = g.copy()
max_indep_sets = [i for i in indep_sets if len(i) == len(indep_sets[-1])]
#removeable_edges = [e for e in g.edges() if _can_remove(e, max_indep_sets)]
edges=g.edges()
shuffle(edges)
for e in edges:
if _can_remove(e, max_indep_sets):
new_graph.delete_edge(e)
new_indep_sets = _update_indep_sets(new_graph,e,indep_sets)
return new_graph, new_indep_sets
return new_graph, indep_sets
#vertices_in_max_indep_set = set(reduce(lambda x,y: union(x,y), max_indep_sets, set([])))
if len(removeable_edges)==0:
#print "no edges to remove"
return new_graph, indep_sets
else:
r = randint(0,len(removeable_edges)-1) #the -1 shouldn't be there, but it errors out without it.
e = removeable_edges[r]
#print "deleting ", e
new_graph.delete_edge(e)
#In the future, use update independent sets instead
#new_indep_sets = BON.find_cliques((BON.dict_from_adjacency_matrix(new_graph.complement())))
new_indep_sets = _update_indep_sets(new_graph,e,indep_sets)
return new_graph, new_indep_sets
def _vertex_cost_list(g):
"""Returns a list of pairs [vertex_number,cost] sorted by cost."""
solution = LOV.lovasz_theta(g, long_return = True)
theta = solution['theta']
witness = solution['B']
costs = np.diagonal(witness)*theta
costs = enumerate(costs) #adds an index
costs = sorted(costs, key = lambda x: -x[1]) #sort by the cost
return costs
def _large_lovasz_subgraph(g, fraction = 0.5):
"""Calculates lovasz theta of g, together with a witness.
We use the costs of the vertices to identify a subgraph with a large lovasz theta.
Then, we mutate one of the other edges."""
theta = g.lovasz_theta()
costs = _vertex_cost_list(g)
valuable_vertices = []
cur_sum = 0
index = 0
while(cur_sum < fraction*theta):
valuable_vertices.append(costs[index][0])
cur_sum+=costs[index][1]
index += 1
return valuable_vertices
"""Fitness Functions"""
def fit(g):
if g.order() < 1:
print("empty graph")
return g.lovasz_theta() / len(g.independent_set())
def fit_regularity(g):
""" returns the reciprocal of the standard deviation of the degree list """
""" We take the reciprocal so that regular graphs are the most fit."""
degrees = g.degree_sequence()
deviation = np.std(degrees)
return 1/(1+deviation)
def fit_with_regularity(g):
"""a weighted average of fitness and regularity."""
return 0.90*fit(g) + 0.1*fit_regularity(g)
def fit_eigen_values(g):
"""Returns the ratio between the largest and second largest abs. value eigenvectors."""
"""This doesn't give good results, because we usually must assume the graphs are regular."""
adjacency = np.array(g.adjacency_matrix())
eigenvalues = np.linalg.eigh(adjacency)[0]
largest = eigenvalues[-1]
second_largest = max(abs(eigenvalues[0]),abs(eigenvalues[-2]))
return (largest - second_largest) / largest
"""Mutation Functions"""
def mu(g):
"""Choose a random edge uv, if exists remove it. If not, add it"""
g = g.copy()
v = randint(0, g.order()-1)
u = randint(0, g.order()-1)
while u == v:
u = randint(0, g.order()-1)
if g.has_edge(u, v):
if g.size() > 1:
g.delete_edge(u, v)
else:
g.add_edge(u, v)
# r = np.random.rand()
# if r<0.01:
# g, _ = remove_extra_edges(g)
return g
def add_edge_to_max_indep_set(g):
"""Chooses a random maximal independent set to add an edge to"""
g = g.copy()
indep_sets = BON.cliques_of_graph(g.complement(), maximal=True)
index = randint(0,len(indep_sets)-1) #This causes an 'index out of range error.'
indp = indep_sets[index]
v = randint(0, len(indp))
u = randint(0, len(indp))
while u == v:
u = randint(0, len(indp))
g.add_edge(u,v)
return g
def mutate_avoid_large_subgraph(g):
"""Finds the subgraph which contributes the most to theta.
Adds a random edge which is not fully contained in that subgraph.
"""
g = g.copy()
valuable_vertices = _large_lovasz_subgraph(g, fraction = 0.75)
available_vertices = [v for v in g.vertices() if v not in valuable_vertices]
u = np.random.choice(available_vertices)
v = np.random.choice(g.vertices())
while u == v:
u = np.random.choice(available_vertices)
if g.has_edge(u, v):
if g.size() > 1:
g.delete_edge(u, v)
else:
g.add_edge(u, v)
return g
def mutate_add_then_remove_edges(g):
"""Adds edges randomly, then performs remove_extra_edges."""
g = g.copy()
g_c = g.complement()
edges = g_c.edges()
shuffle(edges)
for e in edges[:15]:
g.add_edge(e)
g, _ = remove_extra_edges(g)
return g
"""Crossover Functions"""
def cr1(g1, g2):
"""Create a new graph and add edges randomly from parents."""
e1 = g1.edges()
e2 = g2.edges()
g = Graph({v:[] for v in range(0, g1.order())})
m = (g1.size() + g2.size()) // 2
i = 0
while i < m:
if rand() < 0.5:
e = e1
else:
e = e2
uv = e[randint(0, len(e))]
g.add_edge(uv)
i+=1
return g
def cr2(g1, g2):
"""Create a new graph by randomly sampling the product of the parents uniformly."""
#if not g.has_edge(uv):
if g1.order() > 30 or g2.order() > 30:
print "too large"
return Graph({0:[]})
product = g1.disjunctive_product(g2)
prob = 1.0/ (len(g1.independent_set())*len(g2.independent_set()))
sample = product.random_subgraph(prob)
if sample.order()==0:
return Graph({0:[]})
return sample
def cr3(g1,g2,downsample = False):
"""Adds edges randomly between the disjoint union of the two graphs"""
new_graph = g1.disjoint_union(g2, labels='pairs')
print new_graph.vertices()
for a,b in itertools.product(g1.vertices(),g2.vertices()):
r = np.random.rand()
if r < 0.5:
new_graph.add_edge(((0,a),(1,b)))
if downsample:
new_graph.random_subgraph(0.5, inplace = True)
while new_graph.order()>50:
new_graph.random_subgraph(0.2, inplace = True)
if new_graph.order() ==0:
print "too small"
return Graph({0:[]})
return new_graph
def cr4(g1,g2):
"""Keeps edges that are in both, flips a coin for edges that are in one but not the other."""
new_graph = g1.copy()
for edge in set(g1.edges()) ^ set(g2.edges()) :
r = np.random.rand()
if r < 0.5:
if new_graph.has_edge(edge):
new_graph.delete_edge(edge)
else:
new_graph.add_edge(edge)
#new_graph, _ = remove_extra_edges(new_graph)
return new_graph
def cr5(g1,g2):
"""Flip a coin for each vertex. A pair of vertices whose smaller one is labeled g1
is an edge iff g1 has that edge. """
if g1.order()!=g2.order():
print "the two graphs should be of the same order"
print g1.order(), g2.order()
vertex_assignments = np.random.randint(2, size=g1.order())
new_graph = graphs.CompleteGraph(g1.order()).complement()
if new_graph.order()!=g1.order():
print "offf1111"
print new_graph.order(), g1.order()
for v in new_graph.vertices():
#print v
if vertex_assignments[v]==0:
for k in [k for k in g1.neighbors(v) if k>v]:
new_graph.add_edge(v,k)
else:
for k in [k for k in g2.neighbors(v) if k>v]:
new_graph.add_edge(v,k)
new_graph, _ = remove_extra_edges(new_graph)
if new_graph.order()!=g1.order():
print "grapsh have changed order."
print new_graph.vertices()
return new_graph
def cr6(g1, g2):
"""Orders the vertices of g1 and g2 according to their contribution to lovasz theta.
Find subgraphs sg1 and sg2 such that sg1.order()+sg2.order()==g1.order()
and such that the total sum of contributions is maximized.
add all edges between sg1 and sg2, then remove edges which don't affect the independence number.
This function assumes g1 and g2 have the same number of vertices. Might fail otherwise.
"""
costs_g1 = _vertex_cost_list(g1)
costs_g2 = _vertex_cost_list(g2)
index_g1 = 0
index_g2 = 0
while(index_g1 + index_g2 < g1.order()): #after this loop,
if costs_g1[index_g1][1] > costs_g2[index_g2][1]:
index_g1 += 1
else:
index_g2 += 1
sg1 = g1.subgraph([c[0] for c in costs_g1[:index_g1]])
sg2 = g2.subgraph([c[0] for c in costs_g2[:index_g2]])
child_graph = sg1 + sg2 #These vertices are labeled [0..n]
for v1, v2 in itertools.product(range(sg1.order()),range(sg2.order())):
child_graph.add_edge(v1,v2+sg1.order())
if child_graph.order()!= g1.order():
print "order changed"
child_graph, _ = remove_extra_edges(child_graph)
return child_graph
def cr7(g1,g2):
"""Aligns the graphs according to vertex cost.
When an edge is present in both graphs, we keep it.
When it is only in one graph, we flip a coin.
"""
costs_g1 = _vertex_cost_list(g1)
g1_new_order = [c[0] for c in costs_g1] #list determines how to align the vertices of g1
costs_g2 = _vertex_cost_list(g2)
g2_new_order = [c[0] for c in costs_g2]
#g2_new_order.reverse()
dict={}
for v in range(g1.order()):
neighbors = []
vertex_in_g1 = g1_new_order[v]
vertex_in_g2 = g2_new_order[v]
g1_neighbors = g1.neighbors(vertex_in_g1)
g2_neighbors = g2.neighbors(vertex_in_g2)
g1_neighbors = [a for a,b in enumerate(g1_new_order) if b in g1_neighbors]
g2_neighbors = [a for a,b in enumerate(g2_new_order) if b in g2_neighbors]
total_neighbors = g1_neighbors + g2_neighbors
for t in total_neighbors:
if t not in neighbors:
if t in g1_neighbors and t in g2_neighbors:
neighbors.append(t)
else:
r = np.random.rand()
if r>0.5:
neighbors.append(t)
dict[v]=neighbors
return Graph(dict)
def cr8(g1,g2):
""" adds an edge if there is an edge in g1 or in g2"""
new_graph = g1.copy()
for e in g2.edges():
new_graph.add_edge(e)
new_graph,_=remove_extra_edges(new_graph)
return new_graph
def rand_graph(n, m):
"Generate a random graph with n vertices and m edges"
g = { v: [] for v in range(n)}
i = 0
while i < m:
x = randint(0, n)
y = randint(0, n)
if x > y:
x, y = y, x
if x != y and y not in g[x]:
g[x].append(y)
i += 1
return Graph(g)
<file_sep>/main.py
#!/usr/bin/env sage -python
import sys
from ga import GA
import functions as FUN
from numpy.random import randint, rand
from sage.all import *
n = 30 # graph size
pop_size = 100
threshold = 0.130
pop = [FUN.rand_graph(n, randint(n, n*(n-1)/2 + 1)) for _ in range(pop_size)]
ga = GA(FUN.fit, FUN.mutate_add_then_remove_edges, FUN.cr6, 0.3, 0.2)
results = ga.run(pop, 100, threshold)
results = sorted(results, key = lambda x: -x[1])
for g, fit in [results[0]]:
print(g.adjacency_matrix())
print(g.lovasz_theta())
print(len(g.independent_set()))
r = g.lovasz_theta() / (len(g.independent_set()))
print(r)
print(fit)
print("---------------------------------------")
display = g.plot()
save(display,'/tmp/dom.png',axes=False,aspect_ratio=True)
os.system('display /tmp/dom.png')
# G = rand_graph(5, 6)
# print(G.edges())
# G.add_edge(1, 5)
# print(G.edges())
# # G.plot().show()
# print G.lovasz_theta()
# print len(G.independent_set())
# print G.chromatic_number()
<file_sep>/ga.py
"""
A simple implementation of genetic algorithm.
"""
import numpy as np
import sys
class GA(object):
"""A generic class which provides the basic functions
and data structures for GA.
Args:
fit: fitness function, a function that takes an individual and
returns a real value indicating the fitness of that individual.
mu: mutation function, a function that takes an individual peforms
a mutation on it and returns the new individual
cr: cross over function, a function that takes two individuals
performs cross over and returns the new childs
p_elite: the proportion of elites
p_cr: proportion of cross overs, 1-p_cr will be the
proportion of mutations
"""
def __init__(self, fit, mu, cr, p_cr, p_elite,
log_func=lambda x: sys.stdout.write(x + '\n')):
super(GA, self).__init__()
self.fit = fit
self.mu = mu
self.cr = cr
self.p_elite = p_elite
self.p_cr = p_cr
self.fitness = []
self.log = log_func
def run(self, pop, iter, gt):
"""Runs the genetic algorithm and returns the results.
Args:
pop(list): initial population
iter(int): number of iterations
gt: good individual threshold. The threshold of fitness where an
individual considered to be good enough.
Returns:
a list of good individuals found throughout the search
"""
self.n = n = len(pop)
elites = int(n * self.p_elite)
self.pop = [i.copy() for i in pop]
good = []
best = None
for i in range(1, iter+1):
if i % 10 == 1:
self.log("Iteration " + str(i) + "/" + str(iter)+ " ...")
# 1. Selection
self._select()
# save the good ones
for j in range(n):
if best is None or self.fitness[j] > best:
best = self.fitness[j]
if self.fitness[j] >= gt and (self.pop[j], self.fitness[j]) not in good:
good.append((self.pop[j].copy(), self.fitness[j]))
self.log("Found a good individual with fitness :" + str(self.fitness[j]) + "(best: " + str(best) + ")")
else:
break
# 2. generate the new population
# 2.1 Elitisism
new_pop = []
new_pop.extend([x.copy() for x in self.pop[:elites]])
# 2.2 use cross over and mutation to generate the remaining individuals
for j in range(n - elites):
r = np.random.rand()
if r < self.p_cr:
# 2.2.1 cross over
ind1 = np.random.randint(0, n)
ind2 = np.random.randint(0, n)
while(ind1 == ind2):
ind2 = np.random.randint(0, n)
new_pop.append(self.cr(self.pop[ind1], self.pop[ind2]))
else:
# 2.2.2 Mutation
ind = np.random.randint(0, n)
new_pop.append(self.mu(self.pop[ind]))
# 3. Update the population
self.pop = new_pop
return good
def _select(self):
"""
Samples the population according to their fitness values then updates
the population and fitness lists and sorts them using their fitness
values.
"""
self.fitness = []
for i in range(self.n):
self.fitness.append(self.fit(self.pop[i]))
# roulette wheel selection
vals = np.array(self.fitness)
vals = np.exp(vals)
cdf = np.cumsum(vals)
cdf = cdf / cdf[-1]
new_pop = []
new_fit = []
for i in range(self.n):
r = np.random.rand()
sample = sum(r > cdf)
new_pop.append(self.pop[sample].copy())
new_fit.append(self.fitness[sample])
# Sort by fitness decreasing
idx = np.argsort(new_fit)[::-1]
self.pop = [new_pop[i].copy() for i in idx]
self.fitness = [new_fit[i] for i in idx]
| aec99bca38bed86448b471156a3218a13f817129 | [
"Python"
] | 4 | Python | doogrammargood/indep_num | 5a45d6d42034df092665471ac7bc68cacad76fda | 6b3bf5de16195be1474c520a4f67897fa024a584 |
refs/heads/main | <file_sep>import React, { Component } from 'react';
import { Card } from "react-bootstrap";
class ProductCard extends Component{
render(){
const product = this.props.product;
return (
<Card style={{ width: '18rem', margin: '20px' }}>
<Card.Img variant="top" src={product.image} />
<Card.Body>
<Card.Title>{product.title}</Card.Title>
<Card.Text>
{product.description}<br />
<span style={{fontSize: 24, color: 'green'}}>{product.price}$</span>
</Card.Text>
<button className="btn btn-primary" onClick={()=>this.props.addToShoppingCart(product)}>Buy</button>
</Card.Body>
</Card>
);
}
}
export default ProductCard;<file_sep>FROM node:latest
WORKDIR /app/server
COPY package.json .
RUN npm install
COPY . .
EXPOSE 4000
CMD ["node","index.js"]<file_sep>import React, { Component } from 'react';
import ProductCard from "./productCard";
import ShoppingCart from './shoppingCart';
import config from '../config.json'
class Home extends Component {
state = {
products: [],
shopping_cart: []
}
componentDidMount() {
fetch(`${config.SERVER_URL}/api/products`)
.then(res => res.json())
.then((json) => this.setState({ products: json }))
.catch((err) => console.log(err));
}
addToShoppingCart = product => {
const shopping_cart = [...this.state.shopping_cart];
const index = shopping_cart.findIndex(cart => cart._id === product._id)
if (index >= 0) {
shopping_cart[index].amount++;
}
else {
shopping_cart.push(
{
_id: product._id,
title: product.title,
cost: product.price,
amount: 1,
}
)
}
this.setState({ shopping_cart });
}
checkoutShoppingCart = () => {
fetch(`${config.SERVER_URL}/api/carts`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(
{
products: this.state.shopping_cart.map(p => p =
{
_id: p._id,
cost: p.cost,
amount: p.amount
}),
time_stamp: new Date()
})
})
.then(res => res.json())
.then((json) => {
this.setState({ shopping_cart: [] });
}
);
}
render() {
return (
<div style={{ maxWidth: '1200px', margin: 'auto' }}>
<h1>Home</h1>
<div style={{ float: 'right', padding: '7px 15px' }}>
<ShoppingCart cart={this.state.shopping_cart} checkout={this.checkoutShoppingCart} />
</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', paddingTop: '100px' }}>
{this.state.products.map(product =>
<ProductCard key={product._id} product={product} addToShoppingCart={this.addToShoppingCart} />
)}
</div>
</div>
);
}
}
export default Home;<file_sep>const { ObjectId } = require('mongodb');
const mongoose = require('mongoose');
const ProductCartSchema = mongoose.Schema({
_id: {
type: ObjectId,
require: true
},
cost: {
type: Number,
require: true
},
amount: {
type: Number,
require: true
},
});
const CartSchema = mongoose.Schema({
products: {
type: [ProductCartSchema],
require: true
},
time_stamp: {
type: Date,
require: true
},
});
module.exports = mongoose.model('Cart', CartSchema);<file_sep>
import Modal from "react-bootstrap/Modal";
function AdminModal({ handleClose, show, title, children }) {
return (
<Modal show={show} onHide={handleClose} animation={false}>
<Modal.Header>
<Modal.Title>{title}</Modal.Title>
<button type="button" className="close" onClick={handleClose}>
<span aria-hidden="true">×</span>
</button>
</Modal.Header>
<Modal.Body>
{children}
</Modal.Body>
</Modal>
);
};
export default AdminModal;<file_sep>import React, { Component } from 'react';
class AdminTableRow extends Component {
render() {
return (
<tr>
<td>{this.props.product.title}</td>
<td>{this.props.product.price}$</td>
<td>
<button className="btn btn-primary" onClick={()=> this.props.editProduct(this.props.product)} style={{margin: 10}}>Edit</button>
<button className="btn btn-danger" onClick={()=> this.props.deleteProduct(this.props.product._id)}>Delete</button>
</td>
</tr>
);
}
}
export default AdminTableRow;<file_sep>import React, { Component } from 'react';
import AdminTableRow from './adminTableRow';
import AdminModal from './adminModal';
import ProductForm from './productForm';
import config from '../config.json'
class Admin extends Component {
constructor(){
super();
this.state = {
products: [],
show_adding_modal: false,
show_edit_modal: false,
edit_id: 0,
title: '',
price: null,
description: '',
image: ''
}
}
componentDidMount() {
fetch(`${config.SERVER_URL}/api/products`)
.then(res => res.json())
.then((json) => this.setState({ products: json }));
}
showAddingModal = () => {
this.setState({show_adding_modal: true});
}
hideAddingModal = () => {
this.setState({show_adding_modal: false});
}
showEditModal = product => {
this.setState({edit_id: product._id})
this.setState({title: product.title});
this.setState({price: product.price});
this.setState({description: product.description});
this.setState({image: product.image});
this.setState({show_edit_modal: true});
}
hideEditModal = () => {
this.setState({show_edit_modal: false});
}
addProduct = (event) => {
event.preventDefault();
const product = {
title: this.state.title,
price: this.state.price,
description: this.state.description,
image: this.state.image
}
fetch(`${config.SERVER_URL}/api/products`, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(product)
})
.then(res => res.json())
.then((json) => {
const products = [...this.state.products];
products.push(json);
this.setState({products});
this.hideAddingModal();
}
);
}
updateNewProduct = (event) => {
let nam = event.target.name;
let val = event.target.value;
this.setState({[nam]: val});
}
editProduct = (event) => {
event.preventDefault();
const product = {
title: this.state.title,
price: this.state.price,
description: this.state.description,
image: this.state.image
}
fetch(`${config.SERVER_URL}/api/products/${this.state.edit_id}`, {
method: "PUT",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(product)
})
.then(res => res.json())
.then((json) => {
const products = [...this.state.products];
const index = products.findIndex(p => p._id === this.state.edit_id);
products[index] = json;
this.setState({products});
this.hideEditModal();
}
);
}
deleteProduct = productId => {
fetch(`${config.SERVER_URL}/api/products/${productId}`, {
method: "DELETE",
headers: {"Content-Type": "application/json"}
})
.then(res => res.json())
.then((json) => {
const products = this.state.products.filter(p => p._id !== productId);
this.setState({products});
}
);
}
render() {
return (
<div style={{maxWidth: '1000px', margin: 'auto'}}>
<AdminModal title="Add New Product" show={this.state.show_adding_modal} handleClose={this.hideAddingModal}>
<ProductForm onChange={this.updateNewProduct} onSubmit={this.addProduct}/>
</AdminModal>
<AdminModal title="Edit Product" show={this.state.show_edit_modal} handleClose={this.hideEditModal}>
<ProductForm onChange={this.updateNewProduct} onSubmit={this.editProduct} title={this.state.title} price={this.state.price} description={this.state.description} image={this.state.image}/>
</AdminModal>
<h1>Admin</h1>
<button className="btn btn-primary" onClick={this.showAddingModal} style={{margin: '20px 10px', float: 'right'}}>Add New Product</button>
<table className="table">
<thead>
<tr>
<th>Title</th>
<th>Price</th>
<th>Options</th>
</tr>
</thead>
<tbody>
{ this.state.products.map(product => <AdminTableRow key={product._id} product={product} editProduct={this.showEditModal} deleteProduct={this.deleteProduct} />)}
</tbody>
</table>
</div>
);
}
}
export default Admin;<file_sep>const Joi = require("joi");
const router = require("express").Router();
const Cart = require('./models/Cart');
const Product = require('./models/Product');
router.get("/topSold/:quantity", async (req, res) => {
const products_counts = {};
const carts = await Cart.find();
let i = 0;
for (let i = 0; i < carts.length; i++) {
const products = carts[i].products;
for (let j = 0; j < products.length; j++) {
products_counts[products[j].id]===undefined ? products_counts[products[j].id]=products[j].amount : products_counts[products[j].id]+=products[j].amount;
}
}
const sorted_products_amounts = Object.keys(products_counts).map(id => [id, products_counts[id]]).sort((a, b) => b[1] - a[1]).slice(0,req.params.quantity);
const result = [];
for (let i = 0; i < sorted_products_amounts.length; i++) {
const p = await Product.findById(sorted_products_amounts[i][0]);
if(!p)
return res.status(404).send(`product with the ID ${sorted_products_amounts[i][0]} does not exist`);
result.push({
"title": p.title,
"amount": sorted_products_amounts[i][1]
});
}
res.send(result);
});
router.get("/topUniqueSold/:quantity", async (req, res) => {
const products_counts = {};
const carts = await Cart.find();
let i = 0;
for (let i = 0; i < carts.length; i++) {
const products = carts[i].products;
for (let j = 0; j < products.length; j++) {
products_counts[products[j].id]===undefined ? products_counts[products[j].id]=1 : products_counts[products[j].id]++;
}
}
const sorted_products_amounts = Object.keys(products_counts).map(id => [id, products_counts[id]]).sort((a, b) => b[1] - a[1]).slice(0,req.params.quantity);
const result = [];
for (let i = 0; i < sorted_products_amounts.length; i++) {
const p = await Product.findById(sorted_products_amounts[i][0]);
if(!p)
return res.status(404).send(`product with the ID ${sorted_products_amounts[i][0]} does not exist`);
result.push({
"title": p.title,
"amount": sorted_products_amounts[i][1]
});
}
res.send(result);
});
router.get("/pastDays/:quantity", async (req,res) => {
const dates_counts = {};
const last_date = new Date();
for(let i = 0; i < req.params.quantity; i++){
dates_counts[`${last_date.getDate()}/${last_date.getMonth()+1}/${last_date.getFullYear()}`] = 0;
last_date.setDate(last_date.getDate() - 1);
}
const carts = await Cart.find({"time_stamp": {$gt: last_date}});
for (let i = 0; i < carts.length; i++) {
const current_date = `${carts[i].time_stamp
.getDate()}/${carts[i].time_stamp.getMonth()+1}/${carts[i].time_stamp.getFullYear()}`;
const products = carts[i].products;
for (let j = 0; j < products.length; j++) {
dates_counts[current_date] === 0 ? dates_counts[current_date]=products[j].cost*products[j].amount : dates_counts[current_date]+=products[j].cost*products[j].amount;
}
}
const dates_counts_array = Object.keys(dates_counts).map(date => [date, dates_counts[date]]);
const result = [];
for (let i = 0; i < dates_counts_array.length; i++) {
result.push({
"date": dates_counts_array[i][0],
"paid": dates_counts_array[i][1]
});
}
res.send(result);
});
module.exports = router;<file_sep>import React, { Component } from 'react';
class StatsSquare extends Component {
render() {
return (
<div style={{borderRadius: 10, margin: 20, background: '#eee', padding: 20}}>
<h2>{this.props.title}</h2>
<ul className="list-group" style={{marginTop: '40px'}}>
{this.props.items.map(item =>
<li className="list-group-item d-flex justify-content-between align-items-center" key={item.key}>
{item.key}
<span class="badge badge-light">{item.value}</span>
</li>)}
</ul>
</div>
);
}
}
export default StatsSquare;<file_sep>const Joi = require("joi");
const router = require("express").Router();
const Cart = require('./models/Cart');
const Product = require('./models/Product');
router.get("/", async (req, res) => {
try{
const carts = await Cart.find();
res.json(carts);
} catch (err) {
res.status(500).json({message: err.message})
}
});
router.get("/:id", async (req, res) => {
try{
const cart = await Cart.findById(req.params.id);
if(!cart)
return res.status(404).json({message: "Cart with the given ID was not found."});
res.json(cart);
} catch (err) {
res.status(500).json({message: err.message})
}
});
router.post("/", async (req, res) => {
const { error } = validateCart(req.body);
if (error) return res.status(400).send(error.details[0].message);
const products = req.body.products;
let counter = 0;
products.forEach(async p => {
const product = await Product.findById(p._id);
if(!product)
return res.status(404).send(`product with the ID ${p._id} does not exist`);
counter++;
if(counter === products.length){
const cart = new Cart({
products: req.body.products,
time_stamp: req.body.time_stamp
});
try {
const newCart = await cart.save();
res.status(201).json(newCart);
} catch (err) {
res.status(400).json({message: err.message});
}
}
})
});
router.put("/:id", async (req, res) => {
const { error } = validateCart(req.body);
if (error) return res.status(400).send(error.details[0].message);
const products = req.body.products;
let counter = 0;
products.forEach(async p => {
const product = await Product.findById(p._id);
if(!product)
return res.status(404).send(`product with the ID ${p._id} does not exist`);
counter++;
if(counter === products.length){
try {
const cart = await Cart.findByIdAndUpdate(req.params.id,
{
products: req.body.products,
time_stamp: req.body.time_stamp,
})
if(!cart)
return res.status(404).json({message: "Cart with the given ID was not found."});
res.json(cart);
} catch (err) {
res.status(500).json({message: err.message})
}
}
})
});
router.delete("/:id", async (req, res) => {
try{
const cart = await Cart.remove({_id: req.params.id});
res.json(cart);
} catch (err) {
res.status(500).json({message: err.message})
}
});
function validateCart(product) {
const schema = Joi.object({
products: Joi.array().items(Joi.object({
_id: Joi.string(),
cost: Joi.number().min(0),
amount: Joi.number().min(1)
})),
time_stamp: Joi.date().required()
});
return schema.validate(product);
}
module.exports = router; | 669934b810fd160666af63aaf674812dc5df6bd0 | [
"JavaScript",
"Dockerfile"
] | 10 | JavaScript | elad4884/shopping-app | ff395bfb230e05305fa8bded0ade6a226f82ee4e | 7e760bcfffd201e73e1b7aa9e4f2e49d550386c6 |
refs/heads/master | <file_sep>const mongoose = require('mongoose')
const validator = require('validator')
mongoose.connect( process.env.MONGO_URL , {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
})
//here we define the mongoose models of the data to be inputted to the db
//it set types like string, binary, array, number, boolean and so on.
// const User = mongoose.model('User', {
// name: {
// type: String,
// required: true,
// trim: true,
// lowercase: true,
// // validate(value) {
// // if(value.toLowerCase.includes(name)) {
// // throw new Error('This is not a valid name')
// // }
// // }
// },
// age: {
// type: Number
// }
// })
// const User = mongoose.model('task', {
// email: {
// type: String,
// required: true,
// trim: true,
// lowercase: true,
// validate(value) {
// if(!validator.isEmail(value)) {
// throw new Error('Email is invalid')
// }
// }
// },
// password: {
// type: String,
// default: 1234567890,
// minLength: 4,
// lowercase: true,
// validate(value) {
// if (value === 'password') {
// throw new Error('Please check your password and try again')
// }
// }
// }
// })
// const nameQuery = new User({
// email: ' <EMAIL> ',
// password: '<PASSWORD>'
// })
// nameQuery.save().then(() => {
// console.log(nameQuery)
// }).catch((err) => {
// console.log(err)
// })<file_sep>const mongoose = require('mongoose');
const validator = require('validator');
const bcrpyt = require('bcrypt')
const jwt = require('jsonwebtoken')
const Task = require('./task')
mongoose.connect( process.env.MONGO_URL, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false
});
const userSchema = mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
validate(value) {
if(!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
password: {
type: String,
trim: true,
minLength: '4',
required: true,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Please check your password and try again')
}
}
},
//this is used to store the generated token back to the login user
tokens: [{
token: {
type: String,
required: true
}
}],
//help to store the binary image data
avatar: {
type: Buffer
}
}, {
timestamps: true
})
//using virtual to create a relationship between user and owned directories
userSchema.virtual('tasks', {
ref: 'tasks',
localField: '_id',
foreignField: 'owner'
})
//creating a method accessing userSchema to find a single user
userSchema.statics.findByCredentials = async ( email, password ) => {
//locate the specific user
const user = await User.findOne({ email })
if ( !email ) {
throw new Error('Email does not exist')
}
//Password comparism with inputed password
const isMatch = await bcrpyt.compare( password, user.password )
if ( !isMatch ) {
throw new Error('Invalid Password')
}
return user;
}
//methods to generate token
//NB: statics. method are accessed by the modules/modules method while
//methods. are accessed by the instances/instance module
userSchema.methods.generateAuthToken = async function () {
//create a container used to access the user
const user = this
const token = jwt.sign({ _id: user._id.toString() }, process.env.SECRET , { expiresIn: '1 week'})
//save the generated token by concatenation
user.tokens = user.tokens.concat({ token })
await user.save()
return token;
}
//methods to hide private data
userSchema.methods.toJSON = function () {
const user = this
//changing them to an object
const userObject = user.toObject()
//Hide data displayed
delete userObject.password
delete userObject.tokens
delete userObject.avatar
return userObject
}
//creating a middleware where a check is made before accessing restricted pages
userSchema.pre('save', async function (next) {
const user = this
// return console.log(JSON.stringify(user))
if (user.isModified('password')) {
// return console.log(user.password)
user.password = await <PASSWORD>( user.password, 8 )
}
//move on to the next route
next()
})
//creating a middleware to delete tasks as user is deleted
userSchema.pre('remove', async function ( next ) {
const user = this
await Task.deleteMany({ owner: user._id })
next()
})
const User = mongoose.model('users', userSchema);
module.exports = User;<file_sep>const jwt = require('jsonwebtoken')
const User = require('../models/user')
//adding a route middleware
const auth = async (req, res, next) => {
try {
//firstly is to get the token given by the user
const token = req.header('Authorization').replace('Bearer ', '')
//decoding the token to get id and secret value
const decoded = jwt.verify( token, process.env.SECRET )
//compare if the decoded value exist in the database and get user
const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })
if ( !user ) {
throw new Error('Profile dosen\'t exist')
}
userToken = token
userProfile = user
next()
} catch (error) {
res.status(401).send({ Error: 'Please Make sure you are correctly logged In'})
}
//move on
}
module.exports = auth;<file_sep>//CRUD == Create, Read, Update & Delete
//used to access the mongodb content
// const {Mongodb} = require('mongodb')
// //used to create a connection
const { MongoClient, ObjectID } = require('mongodb')
//creating connection variables to mongodb
const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'
//Generating an Object-id to understand
const id = new ObjectID()
console.log(id)
console.log(id.getTimestamp())
MongoClient.connect(connectionURL, { useNewUrlParser: true }, (err, client) => {
if (err) {
return console.log('Unable to connect to Database')
}
const db = client.db(databaseName)
//using UpdateOne & updateMany to update already created documents
db.collection('users').updateOne({ _id: new ObjectID("5cc8396d88b0580d50ea4671") }, {
//$set is used to set the updates to the gotten object by Id
$set: {
name: "Ayo"
}
}).then(result => console.log(result)).catch(e => console.log(e))
db.collection('task').updateMany({
Completed: false
}, {
//$set is used to set the updates to the gotten object by Id
$set: {
Completed: true
}
}).then(result => console.log(result.modifiedCount)).catch(e => console.log(e))
//using deleteOne & deleteMany to find specific id and delete
db.collection('users').deleteMany({
age: 30
}).then(result => console.log(result)).catch(e => console.log(e))
//this is used to find one data based on the inputted id value
db.collection('users').findOne({ _id: new ObjectID("5cc88be2d92e7529dcde7139") }, (error, User) => {
if (error) {
console.log('Unable to Fetch specified user, Please check and try again')
} else {
console.log(User)
}
})
//this gets diferent values that share a common value and returns a cursor
db.collection('users').find({ age: 30 }).toArray((error, users) => {
if (error) {
console.log('Unable to Fetch Users along that range, Please check and try again')
} else {
console.log(users)
}
})
db.collection('users').find({ age: 30 }).count((error, count) => {
if (error) {
console.log('Unable to Fetch Users along that range, Please check and try again')
} else {
console.log(count)
}
})
db.collection('users').insertOne({
_id: id,
name: 'Emmanuel',
age: 30
}, (error, data) => {
if (error) {
console.log('Unable to Insert User')
} else {
console.log(data.ops)
}
})
db.collection('users').insertMany([
{
name: 'Ayo',
age: 7889
},
{
name: 'Mercy',
age: 909082
}
], (error, data) => {
if (error) {
console.log('Unable to Insert User')
} else {
console.log(data.ops)
}
})
db.collection('task').insertMany([
{
Description: 'This is a mongodb database',
Completed: false
},
{
Description: 'Vue.js Tutorials',
Completed: true
}
], (error, data) => {
if (error) {
console.log('Unable to Insert User')
} else {
console.log(data.ops)
}
})
console.log('Connected to the MongoDb')
})<file_sep>const express = require('express');
const chalk = require('chalk');
const userRouter = require('./routes/user');
const taskRouter = require('./routes/task');
const app = express();
const port = process.env.PORT
app.use(express.json());
app.use('/', userRouter)
app.use('/', taskRouter)
app.listen(port, () => {
console.log(chalk.italic.cyan('App running on server ' + port))
}); | 7e84a0abb01d48a1debfc7f44ed06dec2a0c6001 | [
"JavaScript"
] | 5 | JavaScript | Tueloper/Task-Manager | 2a2c342b49e11e4dc556d7ef03b8fb014835666a | 073f44d852ca8b27720ee28e72ec15f2f47f0969 |
refs/heads/master | <file_sep>#ifndef __DELAY_H_
#define __DELAY_H_
#include "stm32f4xx.h"
void Dealy_Config(void);
void Delay_ms(uint32_t time);
void Delay_nus(uint32_t time);
void Delay_nms(uint32_t time);
#endif
<file_sep>#include "hp6.h"
//CRC校验表
const uint16_t crc16_tab[256] =
{
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};
//开启血压测量
const uint8_t BP_Open[]=
{0xc8,0xd7,0xb6,0xa5,0x90,0x01,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//关闭血压测量
const uint8_t Bp_Close[]=
{0xc8,0xd7,0xb6,0xa5,0x90,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//获取血压测量结果
const uint8_t Bp_Result[]=
{0xc8,0xd7,0xb6,0xa5,0x90,0x02,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//开启心率测量
const uint8_t Rate_Open[]=
{0xc8,0xd7,0xb6,0xa5,0xD0,0x01,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//关闭心率测量
const uint8_t Rate_Close[]=
{0xc8,0xd7,0xb6,0xa5,0xD0,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//获取心率测量结果
const uint8_t Rate_Result[]=
{0xc8,0xd7,0xb6,0xa5,0xD0,0x02,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//获取ADC 数据
const uint8_t Get_Adc[]=
{0xc8,0xd7,0xb6,0xa5,0x91,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//设置低功耗
const uint8_t Set_Powersaving[]=
{0xc8,0xd7,0xb6,0xa5,0x70,0x01,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
//获取版本信息
const uint8_t Get_Version[]=
{0xc8,0xd7,0xb6,0xa5,0xa2,0x02,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
static uint8_t HP6_Send_buff[buff_lenth] = {0};//发送数据缓存区
static uint8_t HP6_Result_buff[buff_lenth] = {0};//接收数据缓存区
/*
函数名:HP6_Init
函数的功能:HP6初始化
参数:无
*/
void HP6_Init(void)
{
GPIO_InitTypeDef GPIO_HP6_Init;//定义结构体变量
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC,ENABLE);//打开GPIOC时钟
GPIO_HP6_Init.GPIO_Pin=GPIO_Pin_13;//设置对应引脚--PC13
GPIO_HP6_Init.GPIO_Mode=GPIO_Mode_OUT;//设置对应IO口为输出模式
GPIO_HP6_Init.GPIO_OType=GPIO_OType_PP;//设置对应IO口为推挽模式
GPIO_HP6_Init.GPIO_PuPd=GPIO_PuPd_NOPULL;//设置对应IO口为浮空模式
GPIO_HP6_Init.GPIO_Speed=GPIO_Speed_50MHz;//设置对应IO口速度为50MHZ模式
GPIO_Init(GPIOC,&GPIO_HP6_Init);//初始化GPIOC口
hp_6_Power(0);
}
/*
函数名:Crc16
函数的功能:HP6初始化
参数:data,要检验的数据 len,要检验数据的长度
返回检验值
*/
uint16_t Crc16(uint8_t *data,uint16_t len)
{
uint16_t crc16 = 0xFFFF;
uint32_t uIndex ; //CRC查询表索引
while (len --)
{
uIndex = (crc16&0xff) ^ ((*data) & 0xff) ; //计算CRC
data = data + 1;
crc16 = ((crc16>>8) & 0xff) ^ crc16_tab[uIndex];
}
return crc16 ;//返回CRC校验值
}
void HP6_IIC_Write(uint8_t *data)
{
u8 i=0;
IIC_Start(0);//0-PA,1-PB
IIC_SendByte(0,hp6_addr<<1);//0-PA,1-PB
for(i=0;i<buff_lenth;i++)
{
IIC_SendByte(0,*(data+i));//0-PA,1-PB
}
IIC_Stop(0);//0-PA,1-PB
}
void HP6_IIC_Read(uint8_t *data)
{
u8 i=0;
IIC_Start(0);
IIC_SendByte(0,(hp6_addr<<1)|0x01);
for(i=0;i<23;i++)
{
*(data+i)=IIC_ReadByte(0,0);
}
*(data+23)=IIC_ReadByte(0,1);//第23位数据无需应答
IIC_Stop(0);
}
//得到返回的数据,避免HP6_Result_buff在其他外部.c中被引用
void HP6_Get_ResultDate(uint8_t *data)
{
u8 i;
for(i=0;i<buff_lenth;i++)
{
data[i]=HP6_Result_buff[i];
}
}
//发送命令到从机并获取
//返回1 校验成功,返回0 校验失败
uint8_t HP6_Send_Get(uint8_t *HP6_Send_buff,uint8_t *HP6_Result_buff)
{
uint16_t crc;
crc = Crc16(&HP6_Send_buff[4],18); //数据校验
*(uint16_t*)(&HP6_Send_buff[22]) = crc;
HP6_IIC_Write(HP6_Send_buff); //发送命令
Delay_nms(5); //读写间隔延时
HP6_IIC_Read(HP6_Result_buff); //读取返回值
crc = *(uint16_t*)(&HP6_Result_buff[22]); //校验确定都回来的是否为有效数据
if(crc==Crc16(&HP6_Result_buff[4],18))//校验成功
return 1;
else
return 0;
}
//开启心率测量
uint8_t HP6_Open_Rate(void)
{
u8 i=0;
hp_6_Power(0);
for(i=0;i<buff_lenth;i++)
HP6_Send_buff[i]=Rate_Open[i];
return HP6_Send_Get(HP6_Send_buff,HP6_Result_buff);
}
//获取心率测量结果
uint8_t HP6_Get_RateDate(void)
{
u8 i=0;
for(i=0;i<buff_lenth;i++)
HP6_Send_buff[i]=Rate_Result[i];
return HP6_Send_Get(HP6_Send_buff,HP6_Result_buff);
}
//关闭心率测量
uint8_t HP6_Close_Rate(void)
{
u8 i=0;
for(i=0;i<buff_lenth;i++)
HP6_Send_buff[i]=Rate_Close[i];
hp_6_Power(1);
return HP6_Send_Get(HP6_Send_buff,HP6_Result_buff);
}
//开启血压测量
uint8_t HP6_Open_BP(void)
{
u8 i=0;
hp_6_Power(0);
for(i=0;i<buff_lenth;i++)
HP6_Send_buff[i]=BP_Open[i];
return HP6_Send_Get(HP6_Send_buff,HP6_Result_buff);
}
//获取血压测量结果
uint8_t HP6_Get_BPDate(void)
{
u8 i=0;
for(i=0;i<buff_lenth;i++)
HP6_Send_buff[i]=Bp_Result[i];
return HP6_Send_Get(HP6_Send_buff,HP6_Result_buff);
}
//关闭血压测量
uint8_t HP6_Close_BP(void)
{
u8 i=0;
for(i=0;i<buff_lenth;i++)
HP6_Send_buff[i]=Bp_Close[i];
hp_6_Power(1);
return HP6_Send_Get(HP6_Send_buff,HP6_Result_buff);
}
//设置低功耗模式
uint8_t HP6_Power_Saving(void)
{
u8 i=0;
for(i=0;i<buff_lenth;i++)
HP6_Send_buff[i]=Set_Powersaving[i];
return HP6_Send_Get(HP6_Send_buff,HP6_Result_buff);
}
//获取版本信息
uint8_t HP6_Get_Version(void)
{
u8 i=0;
for(i=0;i<buff_lenth;i++)
HP6_Send_buff[i]=Get_Version[i];
return HP6_Send_Get(HP6_Send_buff,HP6_Result_buff);
}
<file_sep>#include "led.h"
#include "delay.h"
//LED灯初始化
void LED_Init(void)
{
GPIO_InitTypeDef ledgpio;
//使能PA端口时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
ledgpio.GPIO_Pin = GPIO_Pin_7;
ledgpio.GPIO_Mode = GPIO_Mode_OUT; //通用输出
ledgpio.GPIO_OType = GPIO_OType_PP; //推挽输出
ledgpio.GPIO_Speed = GPIO_Fast_Speed;//快速
ledgpio.GPIO_PuPd = GPIO_PuPd_NOPULL; //无上下拉
GPIO_Init(GPIOA,&ledgpio);
GPIO_SetBits(GPIOA,GPIO_Pin_7);
}
//闪烁灯
void LED_flash(void)
{
// GPIOA->ODR &=~ (1<<7);//点亮
GPIO_ResetBits(GPIOA,GPIO_Pin_7);
Delay_ms(500);
// GPIOA->ODR |= (1<<7);
GPIO_SetBits(GPIOA,GPIO_Pin_7);
Delay_ms(500);
}
<file_sep>
#include "main.h"
u8 hao[]={
0x10,0x10,0xF0,0x1F,0x10,0xF0,0x00,0x80,0x82,0x82,0xE2,0x92,0x8A,0x86,0x80,0x00,0x40,0x22,0x15,0x08,0x16,0x61,0x00,0x00,
0x40,0x80,0x7F,0x00,0x00,0x00,0x00,0x00,/*"好",0*/
};
#define led_Prio 61 //任务优先级
#define ledstk_size 64 //任务堆栈大小
OS_STK ledstk[ledstk_size]; //任务堆栈空间
void Led_Task(void *pdata); //任务函数
#define motor_Prio 7
#define motorstk_size 64
OS_STK motorstk[motorstk_size];
void Motor_Task(void *pdata);
#define key_Prio 9
#define keystk_size 64
OS_STK keystk[keystk_size];
void Key_Task(void *pdata);
#define oled_Prio 10
#define oled_stk_size 64
OS_STK oled_stk[oled_stk_size];
void OLED_Task(void *pdata);
#define rtc_Prio 12
#define rtc_stk_size 128
OS_STK rtc_stk[rtc_stk_size];
void RTC_Task(void *pdata);
#define sht20_Prio 13
#define sht20_stk_size 128
OS_STK sht20_stk[sht20_stk_size];
void SHT20_Task(void *pdata);
#define xinlv_Prio 15
#define xinlv_stk_size 128
OS_STK xinlv_stk[xinlv_stk_size];
void Xinlv_Task(void *pdata);
#define step_Prio 20
#define step_stk_size 128
OS_STK step_stk[step_stk_size];
void Step_Task(void *pdata);
INT8U perr;
OS_EVENT *mysem = NULL;//信号量指针
OS_EVENT *mymbox = NULL; //邮箱指针
OS_FLAG_GRP *myflag =NULL;//信号量集指针
short ax,ay,az;
int step =0;
RTC_TimeTypeDef rtctime;
RTC_DateTypeDef rtcdate;
/**
* @brief Main program
* @param None
* @retval None
*/
int main(void)
{
Dealy_Config();//延时初始化
LED_Init(); //LED初始化
Usart_Init(9600); //USART1初始化
printf("串口初始化成功\r\n");
Blue_Init();//蓝牙初始化
Motor_Init();
Key_Init();
KEY_ADC_Init();
OLED_Init();
My_RTC_Init();
IIC_Init();
HP6_Init();
MPU_Init();
CountStepInit();
OSInit(); //ucos-ii 操作系统初始化
mysem = OSSemCreate(0); //创建信号量
mymbox = OSMboxCreate((void *)0);//创建消息邮箱
myflag = OSFlagCreate(0x00,&perr); //创建信号量集
OSTaskCreate(Led_Task,(void *)0,&ledstk[ledstk_size-1],led_Prio);
OSTaskCreate(Motor_Task,(void *)0,&motorstk[motorstk_size-1],motor_Prio);
OSTaskCreate(Key_Task,(void *)0,&keystk[keystk_size-1],key_Prio);
OSTaskCreate(OLED_Task,(void *)0,&oled_stk[oled_stk_size-1],oled_Prio);
OSTaskCreate(RTC_Task,(void *)0,&rtc_stk[rtc_stk_size-1],rtc_Prio);
OSTaskCreate(SHT20_Task,(void *)0,&sht20_stk[sht20_stk_size-1],sht20_Prio);
OSTaskCreate(Xinlv_Task,(void *)0,&xinlv_stk[xinlv_stk_size-1],xinlv_Prio);
OSTaskCreate(Step_Task,(void *)0,&step_stk[step_stk_size-1],step_Prio);
OS_CPU_SysTickInit(100000); //启动定时器 -- 1ms
OSStart(); //启动 uC/OS-II 的多任务环境
while (1)
{
}
}
//指示灯任务
void Led_Task(void *pdata)
{
char *p1=NULL;
pdata = pdata; //防止编译器报警告
for(;;)
{
GPIO_ToggleBits(GPIOA,GPIO_Pin_7);
OSTimeDly(500);
}
}
void Motor_Task(void *pdata)
{
pdata = pdata;
for(;;)
{
// Motor_ON();
// OSTimeDly(500);
// Motor_OFF();
OSTimeDly(500);
}
}
u8 flag=0; //存放按键按下的标志
void Key_Task(void *pdata)
{
u16 key_adc = 0;
pdata = pdata;
for(;;)
{
key_adc = KEY_Get_ADC();
if((key_adc > 900 && key_adc<1200)||(rxbuff[0]=='1'))//向上
{
printf("显示时间\r\n");
OLED_clear(0);
flag = 1;
}
if(key_adc > 1250 && key_adc<1500)//向下
{
printf("测量心率\r\n");
flag = 2;
OLED_clear(0);
}
if(key_adc > 1900 && key_adc<2100)//向左
{
printf("计步\r\n");
flag = 3;
OLED_clear(0);
}
if(key_adc > 3800 && key_adc<4100)//向右
{
printf("向右\r\n");
OLED_clear(0);
}
if(KEY)
{
printf("中央\r\n");
OLED_clear(0);
}
OSTimeDly(500);
}
}
void OLED_Task(void *pdata)
{
pdata = pdata;
for(;;)
{
// Show_XXx(0,0,64,64,(char *)gImage_tu);
// OLED_Chin_Eng(0,70,16,16,"洛阳hi");
OSTimeDly(500);
}
}
void RTC_Task(void *pdata)
{
char Str[64];
pdata = pdata;
for(;;)
{
if(flag==1)
{
HP6_Close_Rate();
HP6_Close_BP();
RTC_GetTime(RTC_Format_BIN,&rtctime);
RTC_GetDate(RTC_Format_BIN,&rtcdate);
sprintf(Str,"%2d :%2d :%2d",rtctime.RTC_Hours,rtctime.RTC_Minutes,rtctime.RTC_Seconds);
OLED_Chin_Eng(0,0,16,16,Str);
sprintf(Str,"20%2d-%2d-%2d",rtcdate.RTC_Year,rtcdate.RTC_Month,rtcdate.RTC_Date);
OLED_Chin_Eng(2,0,16,16,Str);
RTC_Set_AlarmA(6,11,43,10);//设置闹钟
}
OSTimeDly(500);
}
}
void SHT20_Task(void *pdata)
{
char buff[64];
float tem=0,hum=0;
pdata=pdata;
for(;;)
{
if(flag==0)
{
tem=SHT20_readTemOrHum(0xF3);//测量温度
hum=SHT20_readTemOrHum(0xF5);//测量温度
sprintf(buff,"%0.1f",tem);
OLED_Chin_Eng(4,0,16,16,buff);
sprintf(buff,"%0.1f",hum);
OLED_Chin_Eng(6,0,16,16,buff);
}
OSTimeDly(500);
}
}
uint8_t xinlv[24]={0};
uint8_t bp[24]={0};
void Xinlv_Task(void *pdata)
{
pdata =pdata;
for(;;)
{
if(flag==2)
{
HP6_Open_Rate();
OSTimeDly(10000);
HP6_Get_RateDate(); //获取心率测量结果
HP6_Get_ResultDate(xinlv);
printf("xinlv==%d\r\n",xinlv[7]);
//显示到显示屏
OSTimeDly(5000);
HP6_Close_Rate();
}
OSTimeDly(100);
// HP6_Open_BP();
// OSTimeDly(70000);
// HP6_Get_BPDate();
// HP6_Get_ResultDate(bp);
//// printf("高压:%d 低压:%d\r\n",bp[10],bp[11]);
// OSTimeDly(2000);
// HP6_Close_BP();
// OSTimeDly(500);
}
}
void Step_Task(void *pdata)
{
pdata =pdata;
for(;;)
{
if(flag==3)
{
MPU_Get_Accelerometer(&ax,&ay,&az);//获取加速度的初始值
step =CountStep(ax,ay,az);
printf("%d\r\n",step);
}
OSTimeDly(10);
}
}
<file_sep>#ifndef __LED_H_
#define __LED_H_
#include "stm32f4xx.h"
void LED_Init(void);
void LED_flash(void);
#endif
<file_sep>#ifndef __USART_H_
#define __USART_H_
#include "stm32f4xx.h"
extern uint8_t rxbuff[64];
extern uint16_t rxcount;
void Usart_Init(uint32_t brr);
#endif
<file_sep>#ifndef __MOTOR_H_
#define __MOTOR_H_
#include "stm32f4xx.h"
#define Motor_ON() GPIO_SetBits(GPIOB,GPIO_Pin_10)
#define Motor_OFF() GPIO_ResetBits(GPIOB,GPIO_Pin_10)
void Motor_Init(void);
#endif
<file_sep>#ifndef _OLED_H_
#define _OLED_H_
#include "stm32f4xx.h"
#include "string.h"
#include "bitband.h"
#include "delay.h"
#include "ZIMO.h"
#define OLED_DC PA_OUT(15)
#define OLED_RES PB_OUT(13)
#define OLED_CS PB_OUT(7)
#define OLED_SCL PB_OUT(3)
#define OLED_SI PB_OUT(5)
#define SIZE 16
#define Max_Column 128
#define OLED_COM 0
#define OLED_Data 1
extern void OLED_GPIO_Init(void);
extern uint8_t SPI1_ReadWriteByte (uint8_t Data);
extern void OLED_REST(void);
extern void OLED_ReadWriteByte(u8 data,u8 com_data);
extern void OLED_Config(void);
extern void OLED_Init(void);
extern void OLED_clear(u8 data);
extern u8 OLED_Set_Pos(u8 page, u8 column);
extern void gund_wensdu(u8 opo);
extern void gundong(u8 flag,u8 page,u8 column,u32 size_x,u32 size_y);
extern void Show_XXx(u8 page,u8 column,u32 size_x,u32 size_y,char *p);
extern void Show_Char(u8 page,u8 column,u32 size_x,u32 size_y,char *p);
extern void Show_Chars(u8 page,u8 column,u32 size_x,u32 size_y,char *q);
void OLED_Chin_Eng(u8 page,u8 column,u32 size_x,u32 size_y,char *q);
#endif
<file_sep>#include "SHT20.h"
/*
函数名:SHT20_readTemOrHum
函数的功能:读取SHT20的温度或湿度测量值
参数:commod 0XF3 测量温度,0XF5 测量湿度
返回测量的温度或湿度值,1-读取失败
*/
float SHT20_readTemOrHum(u8 commod)
{
float temp,hum;//温湿度的转换结果
u8 ACK=0,NACK=1;//ACK-给出应答,NACK-给出非应答
u8 ack,tem1,tem2;//tem1代表数据的高位,tem2代表低位
u16 ST;
IIC_Start(1);//发送开始信号
//设置分辨率 11bit RH% 测量时间:12ms(typ.) & 11bit T℃ 测量时间:9ms(typ.)
if(IIC_SendByte(1,SHT20_addr&0xfe)==ACK) //I2C address + write + ACK
{
if(IIC_SendByte(1,0xe6)==ACK) //写用户寄存器
{
if(IIC_SendByte(1,0x83)==ACK)
IIC_Stop(1);
}
}
IIC_Start(1);
ack=IIC_SendByte(1,SHT20_addr&0Xfe);//写命令包含器件地址
if(ack==ACK)
{
if(IIC_SendByte(1,commod)==ACK)
{
do
{
Delay_nms(6);
IIC_Start(1); //发送开始信号
}while(IIC_SendByte(1,SHT20_addr|0x01)==NACK); //无应答则整形,还在测量中,如果有应答,则结束当前循环
tem1=IIC_ReadByte(1,ACK);//读命令,给应答
tem2=IIC_ReadByte(1,ACK);//读命令,给应答
IIC_ReadByte(1,NACK);//读命令,不给应答
IIC_Stop(1);
ST=(tem1<<8)|(tem2<<0);
ST&=~0X0003;//Data的后两位在进行物理计算前前须置‘0’
if(commod==Read_Temp_COMD)//命令为读取温度的命令
{
temp=(float)(ST*0.00268127-46.85);//公式:T= -46.85 + 175.72 * ST/2^16
return temp;
}
else if(commod==Read_Hum_COMD)//命令为读取湿度的命令
{
hum=(float)(ST*0.00190735-6);//公式: RH%= -6 + 125 * SRH/2^16
return hum;
}
}
}
return 1;
}
<file_sep>
#ifndef __RTC_H_
#define __RTC_H_
#include "stm32f4xx.h"
u8 My_RTC_Init(void); //RTC初始化
ErrorStatus RTC_Set_Time(u8 hour,u8 min,u8 sec,u8 ampm); //RTC时间设置
ErrorStatus RTC_Set_Date(u8 year,u8 month,u8 date,u8 week); //RTC日期设置
void RTC_Set_AlarmA(u8 week,u8 hour,u8 min,u8 sec); //设置闹钟时间(按星期闹铃,24小时制)
#endif
<file_sep>#ifndef _HP6_H_
#define _HP6_H_
#include "stm32f4xx.h"
#include "string.h"
#include "bitband.h"
#include "delay.h"
#include "usart.h"
#include "i2c.h"
#define hp6_addr 0x66 //SHT20µØÖ·
#define buff_lenth 24
#define hp_6_Power(x) (PC_OUT(13)=x) //0 ´ò¿ª 1 ¹Ø±Õ
void HP6_Init(void);
uint16_t Crc16(uint8_t *data,uint16_t len);
void HP6_IIC_Write(uint8_t *data);
void HP6_IIC_Read(uint8_t *data);
void HP6_Get_ResultDate(uint8_t *data);
uint8_t HP6_Send_Get(uint8_t *HP6_Send_buff,uint8_t *HP6_Result_buff);
uint8_t HP6_Open_Rate(void);
uint8_t HP6_Get_RateDate(void);
uint8_t HP6_Close_Rate(void);
uint8_t HP6_Open_BP(void);
uint8_t HP6_Get_BPDate(void);
uint8_t HP6_Close_BP(void);
uint8_t HP6_Power_Saving(void);
uint8_t HP6_Get_Version(void);
#endif
<file_sep>#include "mpu6050.h"
/*
函数名:MPU_IIC_Write_Byte
函数的功能:MPU_IIC写一个字节函数
参数:reg:要写入的寄存器地址 data:要写入寄存器的数据
*/
void MPU_IIC_Write_Byte(u8 reg,u8 data)
{
IIC_Start(1);//0-PA,1-PB
IIC_SendByte(1,(MPU_ADDR<<1)|0);//发送器件地址+写命令
IIC_SendByte(1,reg);//发送寄存器地址
IIC_SendByte(1,data);//发送数据
IIC_Stop(1);//0-PA,1-PB
}
/*
函数名:MPU_IIC_Read_Byte
函数的功能:MPU_IIC读一个字节函数
参数:reg:要写入的寄存器地址
返回读取到的数据
*/
u8 MPU_IIC_Read_Byte(u8 reg)
{
u8 data;
IIC_Start(1);//0-PA,1-PB
IIC_SendByte(1,(MPU_ADDR<<1)|0);//发送器件地址+写命令
IIC_SendByte(1,reg);//发送寄存器地址
IIC_Start(1);
IIC_SendByte(1,(MPU_ADDR<<1)|1);//发送器件地址+读命令
data=IIC_ReadByte(1,1);//读取数据,发送nACK
IIC_Stop(1);//0-PA,1-PB
return data;
}
/*
函数名:MPU_Write_Len
函数的功能:MPU_IIC连续写入lenth个字节函数
参数:reg:要写入的寄存器地址 buff:要写入的数据地址 lenth:数据长度
*/
void MPU_Write_Len(u8 reg,u8 *buff,u8 lenth)
{
u8 i=0;
IIC_Start(1);
IIC_SendByte(1,(MPU_ADDR<<1)|0);//发送器件地址+写命令
IIC_SendByte(1,reg);//发送寄存器地址
for(i=0;i<lenth;i++)
IIC_SendByte(1,buff[i]);//连续写入lenth个数据
IIC_Stop(1);
}
/*
函数名:MPU_Read_Len
函数的功能:MPU_IIC连续读取数据函数
参数:reg:要写入的寄存器地址 buff:读取到的数据存储区 lenth:要读取的数据长度
返回读取到的数据
*/
u8 MPU_Read_Len(u8 reg,u8 *buff,u8 lenth)
{
u8 i;
IIC_Start(1);
IIC_SendByte(1,(MPU_ADDR<<1)|0);//发送器件地址+写命令
IIC_SendByte(1,reg);//发送寄存器地址
IIC_Start(1);
IIC_SendByte(1,(MPU_ADDR<<1)|1);//发送器件地址+读命令
for(i=lenth;i>0;i--)
{
if(i==1)
{
buff[lenth-i]=IIC_ReadByte(1,1);//读取到最后一位数据,发送nACK
break;
}
else
buff[lenth-i]=IIC_ReadByte(1,0);//开始读取数据,发送ACK
}
IIC_Stop(1);
return 0;
}
/*
函数名:MPU_Set_Gyro_Fsr
函数的功能:设置MPU6050陀螺仪传感器满量程范围
参数:fsr:0,±250dps;1,±500dps;2,±1000dps;3,±2000dps
*/
void MPU_Set_Gyro_Fsr(u8 fsr)
{
MPU_IIC_Write_Byte(MPU_GYRO_CFG_REG,fsr<<3);//设置陀螺仪满量程范围
}
/*
函数名:MPU_Set_Accel_Fsr
函数的功能:设置MPU6050加速度传感器满量程范围
参数:fsr:0,±2g;1,±4g;2,±8g;3,±16g
*/
void MPU_Set_Accel_Fsr(u8 fsr)
{
MPU_IIC_Write_Byte(MPU_ACCEL_CFG_REG,fsr<<3);//设置加速度传感器满量程范围
}
/*
函数名:MPU_Set_LPF
函数的功能:设置MPU6050的数字低通滤波器
参数:lpf:数字低通滤波频率(Hz)
*/
void MPU_Set_LPF(u16 lpf)
{
u8 data=0;
if(lpf>=188)data=1;
else if(lpf>=98)data=2;
else if(lpf>=42)data=3;
else if(lpf>=20)data=4;
else if(lpf>=10)data=5;
else data=6;
MPU_IIC_Write_Byte(MPU_CFG_REG,data);//设置数字低通滤波器
}
/*
函数名:MPU_Set_Rate
函数的功能:设置MPU6050的采样率(假定Fs=1KHz)
参数:rate:4~1000(Hz)
*/
void MPU_Set_Rate(u16 rate)
{
u8 data;
if(rate>1000)rate=1000;
if(rate<4)rate=4;
data=1000/rate-1;
MPU_IIC_Write_Byte(MPU_SAMPLE_RATE_REG,data); //设置数字低通滤波器
MPU_Set_LPF(rate/2); //自动设置LPF为采样率的一半
}
/*
函数名:MPU_Get_Gyroscope
函数的功能:得到陀螺仪值(原始值)
参数:gx,gy,gz:陀螺仪x,y,z轴的原始读数(带符号)
返回0 成功 返回其它 失败
*/
u8 MPU_Get_Gyroscope(short *gx,short *gy,short *gz)
{
u8 buff[6],res;
res=MPU_Read_Len(MPU_GYRO_XOUTH_REG,buff,6);
if(res==0)
{
*gx=((u16)buff[0]<<8)|buff[1];
*gy=((u16)buff[2]<<8)|buff[3];
*gz=((u16)buff[4]<<8)|buff[5];
}
return res;;
}
/*
函数名:MPU_Get_Accelerometer
函数的功能:得到加速度值(原始值)
参数:ax,ay,az:加速度x,y,z轴的原始读数(带符号)
返回0 成功 返回其它 失败
*/
u8 MPU_Get_Accelerometer(short *ax,short *ay,short *az)
{
u8 buff[6],res;
res=MPU_Read_Len(MPU_ACCEL_XOUTH_REG,buff,6);
if(res==0)
{
*ax=((u16)buff[0]<<8)|buff[1];
*ay=((u16)buff[2]<<8)|buff[3];
*az=((u16)buff[4]<<8)|buff[5];
}
return res;;
}
/*
函数名:MPU_Init
函数的功能:初始化MPU6050
参数:无
返回0 成功 返回其它 失败
*/
u8 MPU_Init(void)
{
u8 res;
MPU_IIC_Write_Byte(MPU_PWR_MGMT1_REG,0X80); //复位MPU6050-高位置1
Delay_nms(100);
MPU_IIC_Write_Byte(MPU_PWR_MGMT1_REG,0X00); //唤醒MPU6050
MPU_Set_Gyro_Fsr(3); //陀螺仪传感器,±2000dps-本设计用于抬腕唤醒
MPU_Set_Accel_Fsr(0); //加速度传感器,±2g
MPU_Set_Rate(50); //设置采样率50Hz
MPU_IIC_Write_Byte(MPU_INT_EN_REG,0X00); //关闭所有中断
MPU_IIC_Write_Byte(MPU_USER_CTRL_REG,0X00); //I2C主模式关闭
MPU_IIC_Write_Byte(MPU_FIFO_EN_REG,0X00); //关闭FIFO
MPU_IIC_Write_Byte(MPU_INTBP_CFG_REG,0X80); //INT引脚低电平有效
res=MPU_IIC_Read_Byte(MPU_DEVICE_ID_REG);
if(res==MPU_ADDR)//器件ID正确
{
MPU_IIC_Write_Byte(MPU_PWR_MGMT1_REG,0X01); //设置系统时钟源,PLL X轴为参考
MPU_IIC_Write_Byte(MPU_PWR_MGMT2_REG,0x00); //加速度、陀螺仪工作
MPU_Set_Rate(50); //设置采样率为50Hz
MPU_Set_LPF(20); //设置带宽为25HZ
return 0;
}
else return 1;
}
<file_sep>#include "blue.h"
//蓝牙初始化
void Blue_Init(void)
{
GPIO_InitTypeDef bluegpio;
//打开时钟 PB
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);
bluegpio.GPIO_Pin = GPIO_Pin_6;
bluegpio.GPIO_Mode = GPIO_Mode_OUT;//通用输出
bluegpio.GPIO_OType = GPIO_OType_PP;//推挽输出
bluegpio.GPIO_Speed = GPIO_Speed_50MHz;//输出速度
bluegpio.GPIO_PuPd = GPIO_PuPd_NOPULL;//无上下拉
GPIO_Init(GPIOB,&bluegpio);
GPIO_ResetBits(GPIOB,GPIO_Pin_6);//开启蓝牙
}
<file_sep>#ifndef __BLUE_H_
#define __BLUE_H_
#include "stm32f4xx.h"
void Blue_Init(void);
#endif
<file_sep>#ifndef __KEY_H_
#define __KEY_H_
#include "stm32f4xx.h"
#define KEY GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)
void Key_Init(void);
void KEY_ADC_Init(void);
u16 KEY_Get_ADC(void);
#endif
<file_sep>#include "oled.h"
//OLED屏接口初始化
void OLED_GPIO_Init(void)
{
RCC->AHB1ENR |=(1<<0)|(1<<1);//串口1时钟使能
RCC->APB2ENR |=(1<<12);
//设置PB7,PB13,PA15工作模式-通用功能模式
GPIOB->MODER &=~(3<<14);
GPIOB->MODER |=(1<<14);
GPIOB->MODER &=~(3<<26);
GPIOB->MODER |=(1<<26);
GPIOA->MODER &=~(3<<30);
GPIOA->MODER |=(1<<30);
//设置PB3,PB5工作模式-复用功能模式
GPIOB->MODER &=~(3<<6);
GPIOB->MODER |=(2<<6);
GPIOB->MODER &=~(3<<10);
GPIOB->MODER |=(2<<10);
//设置复用功能模式-SPI1
GPIOB->AFR[0] &=~(0XF<<12);//--F技术参考手册P192
GPIOB->AFR[0] |=(0X5<<12);
GPIOB->AFR[0] &=~(0XF<<20);//--F技术参考手册P192
GPIOB->AFR[0] |=(0X5<<20);
//输出模式配置-推挽输出
GPIOA->OTYPER &=~(1<<15);
GPIOB->OTYPER &=~(1<<3);
GPIOB->OTYPER &=~(1<<5);
GPIOB->OTYPER &=~(1<<7);
GPIOB->OTYPER &=~(1<<13);
//输出速率配置-50MHZ
GPIOA->OSPEEDR &=~(3<<30);
GPIOA->OSPEEDR |=(2<<30);
GPIOB->OSPEEDR &=~(3<<6);
GPIOB->OSPEEDR |=(2<<6);
GPIOB->OSPEEDR &=~(3<<10);
GPIOB->OSPEEDR |=(2<<10);
GPIOB->OSPEEDR &=~(3<<14);
GPIOB->OSPEEDR |=(2<<14);
GPIOB->OSPEEDR &=~(3<<26);
GPIOB->OSPEEDR |=(2<<26);
//上拉下拉模式配置-浮空模式
GPIOA->PUPDR &=~(3<<30);
GPIOA->PUPDR |=(0<<30);
GPIOB->PUPDR &=~(3<<6);
GPIOB->PUPDR |=(0<<6);
GPIOB->PUPDR &=~(3<<10);
GPIOB->PUPDR |=(0<<10);
GPIOB->PUPDR &=~(3<<14);
GPIOB->PUPDR |=(0<<14);
GPIOB->PUPDR &=~(3<<26);
GPIOB->PUPDR |=(0<<26);
SPI1->CR1 |= (1<<9)|(1<<8);//软件从设备管理
SPI1->CR1 &=~ (7<<3);
SPI1->CR1 |= (4<<3);//fclk/32
SPI1->CR1 |= (1<<2);//主设备
SPI1->CR1 |= (1<<6);//使能SPI
}
//SPI读写一个字节数据
uint8_t SPI1_ReadWriteByte (uint8_t Data)
{
while (!(SPI1->SR & (1<<1)));
SPI1->DR = Data;
while (!(SPI1->SR & (1<<0)));
return SPI1->DR;
}
//OLED屏复位
void OLED_REST(void)
{
OLED_RES=1;
Delay_nms(200);
OLED_RES=0;
Delay_nms(200);
OLED_RES=1;
Delay_nms(200);
}
//OLED读写数据/命令
void OLED_ReadWriteByte(u8 data,u8 com_data)
{
com_data ?(OLED_DC=1):(OLED_DC=0);
OLED_CS=0;
SPI1_ReadWriteByte (data);
OLED_CS=1;
}
//驱动器初始化
void OLED_Config(void)
{
OLED_ReadWriteByte(0xAE,OLED_COM); /*display off*/
OLED_ReadWriteByte(0x00,OLED_COM); /*set lower column address*/
OLED_ReadWriteByte(0x10,OLED_COM); /*set higher column address*/
OLED_ReadWriteByte(0x40,OLED_COM); /*set display start line*/
OLED_ReadWriteByte(0xB0,OLED_COM); /*set page address*/
OLED_ReadWriteByte(0x81,OLED_COM); /*contract control*/
OLED_ReadWriteByte(0x66,OLED_COM); /*128*/
OLED_ReadWriteByte(0xA1,OLED_COM); /*set segment remap*/
OLED_ReadWriteByte(0xA6,OLED_COM); /*normal / reverse--换颜色*/
OLED_ReadWriteByte(0xA8,OLED_COM); /*multiplex ratio*/
OLED_ReadWriteByte(0x3F,OLED_COM); /*duty = 1/64*/
OLED_ReadWriteByte(0xC8,OLED_COM); /*Com scan direction*/
OLED_ReadWriteByte(0xD3,OLED_COM); /*set display offset-设置偏移量*/
OLED_ReadWriteByte(0x00,OLED_COM);
OLED_ReadWriteByte(0xD5,OLED_COM); /*set osc division*/
OLED_ReadWriteByte(0x80,OLED_COM);
OLED_ReadWriteByte(0xD9,OLED_COM); /*set pre-charge period*/
OLED_ReadWriteByte(0x1f,OLED_COM);
OLED_ReadWriteByte(0xDA,OLED_COM); /*set COM pins*/
OLED_ReadWriteByte(0x12,OLED_COM);
OLED_ReadWriteByte(0xdb,OLED_COM); /*set vcomh*/
OLED_ReadWriteByte(0x30,OLED_COM);
OLED_ReadWriteByte(0x8d,OLED_COM); /*set charge pump enable*/
OLED_ReadWriteByte(0x14,OLED_COM);
OLED_ReadWriteByte(0xAF,OLED_COM); /*display ON*/
OLED_clear(0);
}
//OLED屏初始化
void OLED_Init(void)
{
OLED_GPIO_Init();
OLED_CS=1;
OLED_REST();
OLED_Config();
}
//清屏
void OLED_clear(u8 data)
{
uint16_t i=0,j=0;
for(i=0;i<8;i++)
{
OLED_ReadWriteByte(0XB0+i,OLED_COM); //设置页地址
OLED_ReadWriteByte(0X00+0,OLED_COM); //设置列地址低四位
OLED_ReadWriteByte(0X10+0,OLED_COM); //设置列地址高四位
for(j=0;j<132;j++)
{
OLED_ReadWriteByte(data,OLED_Data);
}
}
}
//设置光标
u8 OLED_Set_Pos(u8 page, u8 column)
{
if(page>=8|column>=132)
return 0;
OLED_ReadWriteByte(0XB0+page,OLED_COM); //设置页地址
OLED_ReadWriteByte((0X00+(column & 0xf)),OLED_COM); //设置列地址低四位
OLED_ReadWriteByte((0X10+((column>>4)&0xf)),OLED_COM);
return 1;
}
//page--页,column--列,size_x--字库列,size_y--字库行,p--模
void Show_XXx(u8 page,u8 column,u32 size_x,u32 size_y,char *p)
{
u16 i,j=0;
for(i=0;i<(size_y/8);i++)
{
if(OLED_Set_Pos(page+i,column))
for(j=0;j<size_x;j++)
{
OLED_ReadWriteByte(p[(i*size_x)+j],OLED_Data);
}
}
}
//显示任意一个汉字
void Show_Hanz(u8 page,u8 column,u32 size_x,u32 size_y,char *p)
{
u16 i,j=0,k=0;
u32 offset=0;
u32 lenth=strlen(HanZ_list);
k=size_x*size_y/8;
for(i=0;i<lenth;i+=2)//注意lenth此处不要除以2
{
if((p[0]==HanZ_list[i])&&(p[1]==HanZ_list[i+1]))
{
i=i/2;
break;
}
}
offset=i*k;//计算偏移量
for(i=0;i<(size_y/8);i++)
{
if(OLED_Set_Pos(page+i,column))
for(j=0;j<size_x;j++)
{
OLED_ReadWriteByte(HanZ_16X16[offset+(i*size_x)+j],OLED_Data);//16*16--汉字
}
}
}
//显示任意一个8*16 / 12*24 大小的ASCII字符
void Show_Char(u8 page,u8 column,u32 size_x,u32 size_y,char *p)
{
u16 i,j=0,k=0;
k=((*p)-32)*(size_x*size_y/8);//计算偏移量
for(i=0;i<(size_y/8);i++)
{
if(OLED_Set_Pos(page+i,column))
for(j=0;j<size_x;j++)
{
if(size_y==16)
OLED_ReadWriteByte(ASII_8X16[k+(i*size_x)+j],OLED_Data);//8*16--ASCII值,重大错误,多加了一个元素,忽略了第0个元素
else if(size_y==24)
OLED_ReadWriteByte(ASII_12X24[k+(i*size_x)+j],OLED_Data);//12*24--ASCII值
}
}
}
//显示任意一串ASCII字符
void Show_Chars(u8 page,u8 column,u32 size_x,u32 size_y,char *q)
{
int i;
int len=strlen((char *)q);
for(i=0;i<len;i++)
{
Show_Char(page,column+(i*size_x),size_x,size_y,&q[i]);
}
}
//中英文混合显示
void OLED_Chin_Eng(u8 page,u8 column,u32 size_x,u32 size_y,char *q)
{
while(*q!=NULL)
{
if(*q>(char)0xa0)//此处注意,经查某些中文的标点符号后一个机内码刚好等于0xa1
{
Show_Hanz(page,column,size_x,size_y,q);
column+=size_x;
q+=2;
}
else
{
Show_Char(page,column,size_x/2,size_y,q);
column+=(size_x/2);
q+=1;
}
if((132-column)<0)
{
column=0;
}
}
}
<file_sep>#ifndef __TU_H_
#define __TU_H_
#include "stm32f4xx.h"
extern const unsigned char gImage_tu[512];
#endif
<file_sep>#ifndef _BITBAND_H_
#define _BITBAND_H_
#include "stm32f4xx.h"
#define BITBAND(addr,bitnum) (((u32)addr & 0xf0000000)+0x2000000+(((u32)addr & 0xfffff)*32)+(4*bitnum))
#define MEMADDR(addr) *((volatile unsigned int *)(addr))
#define BITband(addr,bitnum) MEMADDR(BITBAND(addr,bitnum))
#define PA_OUT(n) BITband(&GPIOA->ODR,n)
#define PB_OUT(n) BITband(&GPIOB->ODR,n)
#define PC_OUT(n) BITband(&GPIOC->ODR,n)
#define PD_OUT(n) BITband(&GPIOD->ODR,n)
#define PE_OUT(n) BITband(&GPIOE->ODR,n)
#define PF_OUT(n) BITband(&GPIOF->ODR,n)
#define PA_IN(n) BITband(&GPIOA->IDR,n)
#define PB_IN(n) BITband(&GPIOB->IDR,n)
#define PC_IN(n) BITband(&GPIOC->IDR,n)
#define PD_IN(n) BITband(&GPIOD->IDR,n)
#define PE_IN(n) BITband(&GPIOE->IDR,n)
#define PF_IN(n) BITband(&GPIOF->IDR,n)
#endif
<file_sep>
#include "rtc.h"
#include "delay.h"
#include "usart.h"
#include "stdio.h"
NVIC_InitTypeDef NVIC_InitStructure;
//RTC时间设置
//hour,min,sec:小时,分钟,秒钟
//ampm:@RTC_AM_PM_Definitions :RTC_H12_AM/RTC_H12_PM
//返回值:SUCEE(1),成功
// ERROR(0),进入初始化模式失败
ErrorStatus RTC_Set_Time(u8 hour,u8 min,u8 sec,u8 ampm)
{
RTC_TimeTypeDef RTC_TimeTypeInitStructure;
RTC_TimeTypeInitStructure.RTC_Hours=hour;
RTC_TimeTypeInitStructure.RTC_Minutes=min;
RTC_TimeTypeInitStructure.RTC_Seconds=sec;
RTC_TimeTypeInitStructure.RTC_H12=ampm;
return RTC_SetTime(RTC_Format_BIN,&RTC_TimeTypeInitStructure);
}
//RTC日期设置
//year,month,date:年(0~99),月(1~12),日(0~31)
//week:星期(1~7,0,非法!)
//返回值:SUCEE(1),成功
// ERROR(0),进入初始化模式失败
ErrorStatus RTC_Set_Date(u8 year,u8 month,u8 date,u8 week)
{
RTC_DateTypeDef RTC_DateTypeInitStructure;
RTC_DateTypeInitStructure.RTC_Date=date;
RTC_DateTypeInitStructure.RTC_Month=month;
RTC_DateTypeInitStructure.RTC_WeekDay=week;
RTC_DateTypeInitStructure.RTC_Year=year;
return RTC_SetDate(RTC_Format_BIN,&RTC_DateTypeInitStructure);
}
//RTC初始化
//返回值:0,初始化成功;
// 1,LSE开启失败;
// 2,进入初始化模式失败;
u8 My_RTC_Init(void)
{
RTC_InitTypeDef RTC_InitStructure;
u16 retry=0X1FFF;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);//使能PWR时钟
PWR_BackupAccessCmd(ENABLE); //使能后备寄存器访问
// RCC_LSEConfig(RCC_LSE_ON);//LSE 开启
RCC_LSICmd(ENABLE); //LSI 开启
while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET) //检查指定的RCC标志位设置与否,等待低速晶振就绪
{
retry++;
Delay_nms(10);
}
if(retry==0)return 1; //LSI 开启失败.
RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI); //设置RTC时钟(RTCCLK),选择LSI作为RTC时钟
RCC_RTCCLKCmd(ENABLE); //使能RTC时钟
RTC_InitStructure.RTC_AsynchPrediv = 0x7F;//RTC异步分频系数(1~0X7F)
RTC_InitStructure.RTC_SynchPrediv = 0xFF;//RTC同步分频系数(0~7FFF)
RTC_InitStructure.RTC_HourFormat = RTC_HourFormat_24;//RTC设置为,24小时格式
RTC_Init(&RTC_InitStructure);
RTC_Set_Time(11,43,0,RTC_H12_AM); //设置时间
RTC_Set_Date(19,11,11,6); //设置日期
return 0;
}
//设置闹钟时间(按星期闹铃,24小时制)
//week:星期几(1~7) @ref RTC_Alarm_Definitions
//hour,min,sec:小时,分钟,秒钟
void RTC_Set_AlarmA(u8 week,u8 hour,u8 min,u8 sec)
{
EXTI_InitTypeDef EXTI_InitStructure;
RTC_AlarmTypeDef RTC_AlarmTypeInitStructure;
RTC_TimeTypeDef RTC_TimeTypeInitStructure;
RTC_AlarmCmd(RTC_Alarm_A,DISABLE);//关闭闹钟A
RTC_TimeTypeInitStructure.RTC_Hours=hour;//小时
RTC_TimeTypeInitStructure.RTC_Minutes=min;//分钟
RTC_TimeTypeInitStructure.RTC_Seconds=sec;//秒
RTC_TimeTypeInitStructure.RTC_H12=RTC_H12_AM;
RTC_AlarmTypeInitStructure.RTC_AlarmDateWeekDay=week;//星期
RTC_AlarmTypeInitStructure.RTC_AlarmDateWeekDaySel=RTC_AlarmDateWeekDaySel_WeekDay;//按星期闹
RTC_AlarmTypeInitStructure.RTC_AlarmMask=RTC_AlarmMask_None;//精确匹配星期,时分秒
RTC_AlarmTypeInitStructure.RTC_AlarmTime=RTC_TimeTypeInitStructure;
RTC_SetAlarm(RTC_Format_BIN,RTC_Alarm_A,&RTC_AlarmTypeInitStructure);
RTC_ClearITPendingBit(RTC_IT_ALRA);//清除RTC闹钟A的标志
EXTI_ClearITPendingBit(EXTI_Line17);//清除LINE17上的中断标志位
RTC_ITConfig(RTC_IT_ALRA,ENABLE);//开启闹钟A中断
RTC_AlarmCmd(RTC_Alarm_A,ENABLE);//开启闹钟A
EXTI_InitStructure.EXTI_Line = EXTI_Line17;//LINE17
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;//中断事件
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; //上升沿触发
EXTI_InitStructure.EXTI_LineCmd = ENABLE;//使能LINE17
EXTI_Init(&EXTI_InitStructure);//配置
NVIC_InitStructure.NVIC_IRQChannel = RTC_Alarm_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;//抢占优先级1
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02;//子优先级2
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;//使能外部中断通道
NVIC_Init(&NVIC_InitStructure);//配置
}
#include "ucos_ii.h"
//RTC闹钟中断服务函数
void RTC_Alarm_IRQHandler(void)
{
OSIntEnter();
if(RTC_GetFlagStatus(RTC_FLAG_ALRAF)==SET)//ALARM A中断
{
RTC_ClearFlag(RTC_FLAG_ALRAF);//清除中断标志
printf("ALARM A!\r\n");
}
EXTI_ClearITPendingBit(EXTI_Line17); //清除中断线17的中断标志
OSIntExit();
}
<file_sep>#include "key.h"
//按键初始化
void Key_Init(void)
{
GPIO_InitTypeDef keygpio;
//使能PA端口时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
keygpio.GPIO_Pin = GPIO_Pin_0;
keygpio.GPIO_Mode = GPIO_Mode_IN; //输入
keygpio.GPIO_PuPd = GPIO_PuPd_NOPULL; //无上下拉
GPIO_Init(GPIOA,&keygpio);
}
void KEY_ADC_Init(void)
{
RCC->AHB1ENR |= 1<<0;
RCC->APB2ENR|=1<<8;//ADC1时钟使能
GPIOA->MODER &=~(3<<6);//清零
GPIOA->MODER |= 0X3<<6;//PA3配置模拟输入模式
RCC->APB2RSTR|=1<<8;//ADCs复位
RCC->APB2RSTR &=~(1<<8);//复位结束
ADC->CCR=3<<16;//ADCCLK=PCLK/8=100/8=12MHZ,最好不要超过36MHZ
ADC1->CR1=0;//CR1设置清零
ADC1->CR2=0;//CR2设置清零
ADC1->CR1|=0<<24;//12位模式
ADC1->CR1|=0<<8;//非扫描模式
ADC1->CR2 &=~(1<<1);//单次转换模式
ADC1->CR2 &=~(1<<11);//右对齐
ADC1->CR2 |=0<<28;//软件触发
ADC1->SQR1 &=~(0XF<<20);
ADC1->SQR1 |=0<<20;//1个转换在规则通道中,也就是只转换规则序列1
//设置通道3的采样时间
ADC1->SMPR2 &=~(7<<9);//通道3采样时间清空
ADC1->SMPR2 |=(7<<9);//通道3,480个周期,提高转换精度
ADC1->CR2 |=1<<0;//开启AD转换器
}
u16 KEY_Get_ADC(void)
{
//设置转换序列
ADC1->SQR3 &=~(0X1F<<0);//设置ADC1通道1,将ADCIN3放到第一个转换序列中
ADC1->SQR3 |=(3<<0);//必须是第一个通道
ADC1->CR2 |=1<<30;//启动转换通道
while(!(ADC1->SR&(1<<1)));//等待转换结束
return ADC1->DR;//返回ADC值
}
<file_sep>#ifndef _SHT20_H_
#define _SHT20_H_
#include "stm32f4xx.h"
#include "bitband.h"
#include "delay.h"
#include "i2c.h"
#define Read_Temp_COMD 0xf3 //读取温度命令
#define Read_Hum_COMD 0xf5 //读取湿度命令
#define SHT20_addr 0x80 //SHT20地址
float SHT20_readTemOrHum(u8 commod);
#endif
<file_sep>
#include "StepCount.h"
SensorData GMeter;
unsigned short m = 0;
unsigned char n = 0;
DATATYPE DateBufferX[10] = {9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000};
DATATYPE DateBufferY[10] = {9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000};
DATATYPE DateBufferZ[10] = {9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000, 9000};
unsigned short StepCount = 0;
unsigned char StepFlag = 0;
unsigned char InitFlag = 0;
unsigned char m_count = 0;
unsigned char GMeterAmax = 0;
void DataInit(SensorData *SData)
{
SData->X.Max = -8192;
SData->X.Min = +8192;
SData->Y.Max = -8192;
SData->Y.Min = +8192;
SData->Z.Max = -8192;
SData->Z.Min = +8192;
}
//找出以哪个方向为记步的标准轴(人走路时,抬起和放下,垂直于地面上的加速度值变化最大)
unsigned char DataSelect(SensorData *GMeter)
{
DATATYPE tempX = 0, tempY = 0, tempZ = 0, tempMax;
unsigned char flag = 0;
tempX = GMeter->X.Max - GMeter->X.Min;
tempY = GMeter->Y.Max - GMeter->Y.Min;
tempZ = GMeter->Z.Max - GMeter->Z.Min;
if(tempX > tempY) {
if(tempX > tempZ) {
flag = 1;
tempMax = tempX;
} else {
flag = 3;
tempMax = tempZ;
}
} else {
if(tempY > tempZ) {
flag = 2;
tempMax = tempY;
} else {
flag = 3;
tempMax = tempZ;
}
}
if(tempMax > 1000) {
return flag;
} else {
return 0;
}
}
/*********************************************************************************************************
** Function name: main
** Descriptions: 计步
** 现象:记录人走路或跑步时的步数,并将数据打包通过串口和无线模块发送出去
** input parameters: none
** output parameters: none
** Returned value: none
** Created by: smallmount
**--------------------------------------------------------------------------------------------------------
** Modified by:
** Modified date:
*********************************************************************************************************/
void CountStepInit(void)
{
DataInit(&GMeter);
}
/*********************************************************************************************************
** Function name: main
** Descriptions: 计步
** 现象:记录人走路或跑步时的步数,并将数据打包通过串口和无线模块发送出去
** input parameters: none
** output parameters: none
** Returned value: none
** Created by: smallmount
**--------------------------------------------------------------------------------------------------------
** Modified by:
** Modified date:
*********************************************************************************************************/
u8 CountStep(signed short X,signed short Y,signed short Z)
{
unsigned char i=0;
if(m == DATASIZE) //当检测到50次后?
{
m = 0;
if(m_count == 0) {
m_count = 1;
}
}
if(n == 10) n = 0; //保存数据n次 当10次后,从新保存
DateBufferX[n] = X;
DateBufferY[n] = Y;
DateBufferZ[n] = Z;
if(InitFlag < 9)
{
GMeter.X.Data[m] = X;
GMeter.Y.Data[m] = Y;
GMeter.Z.Data[m] = Z;
InitFlag++;
}
else
{
GMeter.X.Data[m] = (DateBufferX[0] + DateBufferX[1] + DateBufferX[2] + DateBufferX[3] + DateBufferX[4] + DateBufferX[5] + DateBufferX[6] + DateBufferX[7] + DateBufferX[8] + DateBufferX[9]) / 10;
GMeter.Y.Data[m] = (DateBufferY[0] + DateBufferY[1] + DateBufferY[2] + DateBufferY[3] + DateBufferY[4] + DateBufferY[5] + DateBufferY[6] + DateBufferY[7] + DateBufferY[8] + DateBufferY[9]) / 10;
GMeter.Z.Data[m] = (DateBufferZ[0] + DateBufferZ[1] + DateBufferZ[2] + DateBufferZ[3] + DateBufferZ[4] + DateBufferZ[5] + DateBufferZ[6] + DateBufferZ[7] + DateBufferZ[8] + DateBufferZ[9]) / 10;
}
if(m_count == 1)
{
if(GMeter.X.MaxMark == m || GMeter.X.MinMark == m || GMeter.Y.MaxMark == m || GMeter.Y.MinMark == m || GMeter.Z.MaxMark == m || GMeter.Z.MinMark == m)
{
unsigned char tempXMaxMark = GMeter.X.MaxMark;
unsigned char tempXMinMark = GMeter.X.MinMark;
unsigned char tempYMaxMark = GMeter.Y.MaxMark;
unsigned char tempYMinMark = GMeter.Y.MinMark;
unsigned char tempZMaxMark = GMeter.Z.MaxMark;
unsigned char tempZMinMark = GMeter.Z.MinMark;
if(GMeter.X.MaxMark == m) {
GMeter.X.Max = -8192;
}
if(GMeter.X.MinMark == m) {
GMeter.X.Min = +8192;
}
if(GMeter.Y.MaxMark == m) {
GMeter.Y.Max = -8192;
}
if(GMeter.Y.MinMark == m) {
GMeter.Y.Min = +8192;
}
if(GMeter.Z.MaxMark == m) {
GMeter.Z.Max = -8192;
}
if(GMeter.Z.MinMark == m) {
GMeter.Z.Min = +8192;
}
for(i = 0; i < DATASIZE; i++) {
if(GMeter.X.MaxMark == m) {
if(GMeter.X.Data[i] >= GMeter.X.Max) {
GMeter.X.Max = GMeter.X.Data[i];
tempXMaxMark = i;
}
}
if(GMeter.X.MinMark == m) {
if(GMeter.X.Data[i] <= GMeter.X.Min) {
GMeter.X.Min = GMeter.X.Data[i];
tempXMinMark = i;
}
}
if(GMeter.Y.MaxMark == m) {
if(GMeter.Y.Data[i] >= GMeter.Y.Max) {
GMeter.Y.Max = GMeter.Y.Data[i];
tempYMaxMark = i;
}
}
if(GMeter.Y.MinMark == m) {
if(GMeter.Y.Data[i] <= GMeter.Y.Min) {
GMeter.Y.Min = GMeter.Y.Data[i];
tempYMinMark = i;
}
}
if(GMeter.Z.MaxMark == m) {
if(GMeter.Z.Data[i] >= GMeter.Z.Max) {
GMeter.Z.Max = GMeter.Z.Data[i];
tempZMaxMark = i;
}
}
if(GMeter.Z.MinMark == m) {
if(GMeter.Z.Data[i] <= GMeter.Z.Min) {
GMeter.Z.Min = GMeter.Z.Data[i];
tempZMinMark = i;
}
}
}
GMeter.X.MaxMark = tempXMaxMark;
GMeter.X.MinMark = tempXMinMark;
GMeter.Y.MaxMark = tempYMaxMark;
GMeter.Y.MinMark = tempYMinMark;
GMeter.Z.MaxMark = tempZMaxMark;
GMeter.Z.MinMark = tempZMinMark;
}
}
if(GMeter.X.Data[m] >= GMeter.X.Max)
{
GMeter.X.Max = GMeter.X.Data[m];
GMeter.X.MaxMark = m;
}
if(GMeter.X.Data[m] <= GMeter.X.Min)
{
GMeter.X.Min = GMeter.X.Data[m];
GMeter.X.MaxMark = m;
}
if(GMeter.Y.Data[m] >= GMeter.Y.Max)
{
GMeter.Y.Max = GMeter.Y.Data[m];
GMeter.Y.MaxMark = m;
}
if(GMeter.Y.Data[m] <= GMeter.Y.Min)
{
GMeter.Y.Min = GMeter.Y.Data[m];
GMeter.Y.MinMark = m;
}
if(GMeter.Z.Data[m] >= GMeter.Z.Max)
{
GMeter.Z.Max = GMeter.Z.Data[m];
GMeter.Z.MaxMark = m;
}
if(GMeter.Z.Data[m] <= GMeter.Z.Min)
{
GMeter.Z.Min = GMeter.Z.Data[m];
GMeter.Z.MinMark = m;
}
GMeter.X.Base = (GMeter.X.Max + GMeter.X.Min) / 2;
GMeter.Y.Base = (GMeter.Y.Max + GMeter.Y.Min) / 2;
GMeter.Z.Base = (GMeter.Z.Max + GMeter.Z.Min) / 2;
GMeter.X.UpLimit = (GMeter.X.Base + GMeter.X.Max * 2) / 3;
GMeter.Y.UpLimit = (GMeter.Y.Base + GMeter.Y.Max * 2) / 3;
GMeter.Z.UpLimit = (GMeter.Z.Base + GMeter.Z.Max * 2) / 3;
GMeter.X.DownLimit = (GMeter.X.Base + GMeter.X.Min * 2) / 3;
GMeter.Y.DownLimit = (GMeter.Y.Base + GMeter.Y.Min * 2) / 3;
GMeter.Z.DownLimit = (GMeter.Z.Base + GMeter.Z.Min * 2) / 3;
GMeterAmax = DataSelect(&GMeter);
switch(GMeterAmax)
{
case 1:
if((GMeter.X.Data[m] > GMeter.X.UpLimit) && StepFlag == 0) StepFlag = 1;
if((GMeter.X.Data[m] < GMeter.X.DownLimit) && StepFlag ==1)
{
StepFlag = 0;
StepCount++;
}
break;
case 2:
if((GMeter.Y.Data[m] > GMeter.Y.UpLimit) && StepFlag == 0) {
StepFlag = 1;
}
if((GMeter.Y.Data[m] < GMeter.Y.DownLimit) && StepFlag ==1) {
StepFlag = 0;
StepCount++;
}
break;
case 3:
if((GMeter.Z.Data[m] > GMeter.Z.UpLimit) && StepFlag == 0) {
StepFlag = 1;
}
if((GMeter.Z.Data[m] < GMeter.Z.DownLimit) && StepFlag ==1) {
StepFlag = 0;
StepCount++;
}
break;
default: break;
}
m++;
n++;
return StepCount;
}
<file_sep>#include "i2c.h"
/*
函数名:IIC_Init
函数的功能:IIC初始化
参数:无
*/
void IIC_Init(void)
{
RCC->AHB1ENR |= 1<<0|1<<1;//使能PB时钟//打开GPIOA\B时钟
GPIOA->MODER &=~(0XF<<2);//清零
GPIOA->MODER |= 0X5<<2;//PA1,PA2配置通用输出模式
GPIOB->MODER &=~(0XF<<16);//清零
GPIOB->MODER |= 0X5<<16;//PB8,PB9配置通用输出模式
GPIOA->OTYPER |= 1<<1;//PA1配置为开漏模式
GPIOB->OTYPER |= 1<<9;//PB9配置为开漏模式
GPIOA->OTYPER &=~(1<<2);//PA2配置为推挽模式
GPIOB->OTYPER &=~(1<<8);//PB8配置为推挽模式
IIC_SCL_H(1);//1-PB,2-PA
IIC_SCL_H(0);
IIC_SDA_H(1);//1-PB,2-PA
IIC_SDA_H(0);
}
/*
函数名:IIC_start
函数的功能:模拟IIC开始信号
参数:cate:1-PB,2-PA
*/
void IIC_Start(u8 cate)
{
Delay_nus(4);
IIC_SCL_H(cate);
IIC_SDA_H(cate);
Delay_nus(4);
IIC_SDA_L(cate);
Delay_nus(4);
IIC_SCL_L(cate);//钳住I2C总线,准备发送或接收数据
}
/*
函数名:IIC_stop
函数的功能:模拟IIC停止信号
参数:cate:1-PB,2-PA
*/
void IIC_Stop(u8 cate)
{
IIC_SDA_L(cate);
Delay_nus(4);
IIC_SCL_H(cate);
Delay_nus(4);
IIC_SDA_H(cate);//发送I2C总线结束信号
Delay_nus(4);
}
/*
函数名:IIC_sendByte
函数的功能:发送一个字节
参数:cate:1-PB,2-PA, data 要发送的字节
*/
u8 IIC_SendByte(u8 cate,u8 data)
{
u8 ack,i;
for(i=0;i<8;i++) //8个时钟传输8位数据,从最高位开始传输
{
if(data &(1<<(7-i)))
{
IIC_SDA_H(cate);
}
else
{
IIC_SDA_L(cate);
}
Delay_nus(10);
IIC_SCL_H(cate);
Delay_nus(10);
IIC_SCL_L(cate);
}
IIC_SDA_H(cate);//释放管脚控制,等待应答
Delay_nus(10);
IIC_SCL_H(cate);
if(Read_SDA(cate))//SDA输入的电平为高电平表示非应答
{
ack = 1;
}
else //SDA输入的电平为低电平表示应答
{
ack = 0;
}
Delay_nus(10);
IIC_SCL_L(cate);
return ack;
}
/*
函数名:IIC_readByte
函数的功能:读取一个字节
参数:cate:1-PB,2-PA ack=0时,发送ACK,ack=1,发送nACK
返回读取到的字节
*/
u8 IIC_ReadByte(u8 cate,u8 ack)
{
u8 i;
u8 data = 0;
IIC_SDA_H(cate);//SDA输出高电平,切换为输入
for(i=0;i<8;i++) //产生8个时钟,读取8位数据
{
Delay_nus(10);
IIC_SCL_H(cate);
data = data <<1;
if(Read_SDA(cate))
{
data |= 1<<0;
}
else //SDA输入的低电平电平
{
data &=~(1<<0);
}
Delay_nus(10);
IIC_SCL_L(cate);
}
//产生第九个时钟,发送应答信号。
if(ack == 0)
{
IIC_SDA_L(cate);
}
else
{
IIC_SDA_H(cate);
}
Delay_nus(10);
IIC_SCL_H(cate);
Delay_nus(10);
IIC_SCL_L(cate);
return data;
}
<file_sep>#ifndef _ZIMO_H_
#define _ZIMO_H_
#include "stm32f4xx.h"
extern const char ASII_8X16[];
extern const char ASII_12X24[];
extern const char kong16_16[];
extern const char fangx16_16[];
extern const char HanZ_list[];
extern const char HanZ_16X16[];
#endif
<file_sep>#include "usart.h"
#include "stdio.h"
//USART1c初始化
// brr -- 波特率
void Usart_Init(uint32_t brr)
{
GPIO_InitTypeDef usartgpio;
USART_InitTypeDef usartstru;
NVIC_InitTypeDef usartnvic;
//打开时钟 PA USART1
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
//将USART1 映射到PA9 PA10
GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);
//PA9 PA10 复用功能
usartgpio.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
usartgpio.GPIO_Mode = GPIO_Mode_AF; //复用
usartgpio.GPIO_OType = GPIO_OType_PP; //推挽
usartgpio.GPIO_Speed = GPIO_Fast_Speed; //快速
usartgpio.GPIO_PuPd = GPIO_PuPd_NOPULL; //无上下拉
GPIO_Init(GPIOA,&usartgpio);
//USART1 1+8+0+1
usartstru.USART_BaudRate = brr; //波特率
usartstru.USART_WordLength = USART_WordLength_8b;//字长8位
usartstru.USART_StopBits = USART_StopBits_1;//停止位1位
usartstru.USART_Parity = USART_Parity_No;//禁止校验
usartstru.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;//收发模式
usartstru.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件控制流
USART_Init(USART1,&usartstru);
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//使能接收中断
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//优先级分组
usartnvic.NVIC_IRQChannel = USART1_IRQn; //中断通道
usartnvic.NVIC_IRQChannelPreemptionPriority = 0; //占先优先级0
usartnvic.NVIC_IRQChannelSubPriority = 0; //次级优先级0
usartnvic.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&usartnvic);
USART_Cmd(USART1,ENABLE);//使能串口1
}
//重定义fputc
//改变数据输出的方向,往串口输出
//换行 \r\n
int fputc(int c, FILE * stream)
{
//等待上次的数据发送完成
while(USART_GetFlagStatus(USART1,USART_FLAG_TC)==RESET);
//发送数据
USART_SendData(USART1,c);
return c;
}
uint8_t rxbuff[64]={0};//保存接收到的数据
uint16_t rxcount = 0;//保存接收到的数据的个数
#include "ucos_ii.h"
//中断服务函数
void USART1_IRQHandler(void)
{
OSIntEnter();
if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET)
{
USART_ClearFlag(USART1,USART_FLAG_RXNE);//清中断
//保存接收的数据
rxbuff[rxcount++] = USART_ReceiveData(USART1);
}
OSIntExit();
}
<file_sep>#ifndef _I2C_H_
#define _I2C_H_
#include "stm32f4xx.h"
#include "bitband.h"
#include "delay.h"
//#define SDA_OUT() { GPIOB->MODER &=~(3<<18);GPIOB->MODER |=(1<<18);}//PB9设置为输出
//#define SDA_IN() { GPIOB->MODER &=~(3<<18);GPIOB->MODER |=(0<<18);}//PB9设置为输入
#define PA 0
#define PB 1
#define Read_SDA(x) x ? (PB_IN(9)):(PA_IN(1))
#define IIC_SCL_H(x) x ? (PB_OUT(8)=1):(PA_OUT(2)=1)
#define IIC_SCL_L(x) x ? (PB_OUT(8)=0):(PA_OUT(2)=0)
#define IIC_SDA_H(x) x ? (PB_OUT(9)=1):(PA_OUT(1)=1)
#define IIC_SDA_L(x) x ? (PB_OUT(9)=0):(PA_OUT(1)=0)
void IIC_Init(void);
void IIC_Start(u8 cate);
void IIC_Stop(u8 cate);
u8 IIC_SendByte(u8 cate,u8 data);
u8 IIC_ReadByte(u8 cate,u8 ack);
#endif
<file_sep>
#ifndef __MAIN_H
#define __MAIN_H
/* Includes ------------------------------------------------------------------*/
#include "stm32f4xx.h"
#include "stdio.h"
#include "delay.h"
#include "led.h"
#include "usart.h"
#include "blue.h"
#include "motor.h"
#include "key.h"
#include "oled.h"
#include "tu.h"
#include "rtc.h"
#include "i2c.h"
#include "sht20.h"
#include "hp6.h"
#include "mpu6050.h"
#include "StepCount.h"
#include "ucos_ii.h"
#endif /* __MAIN_H */
<file_sep>/*********************************************Copyright (c)***********************************************
** Name: smallmount
**
**--------------File Info---------------------------------------------------------------------------------
** Last modified date: 2014-02-11
** Descriptions: LCD Driver
**
*********************************************************************************************************/
#ifndef _StepCount_H_
#define _StepCount_H_
#include "stm32f4xx.h"
typedef signed short DATATYPE;
#define DATASIZE 50
typedef struct __DATA {
DATATYPE Data[DATASIZE];
DATATYPE Max;
DATATYPE MaxMark;
DATATYPE Min;
DATATYPE MinMark;
DATATYPE Base;
DATATYPE UpLimit;
DATATYPE DownLimit;
}__DATA;
typedef struct _SensorData {
__DATA X;
__DATA Y;
__DATA Z;
}SensorData;
void DataInit(SensorData *SData);
unsigned char DataSelect(SensorData *GMeter);
void CountStepInit(void);
u8 CountStep(signed short X,signed short Y,signed short Z);
void UartSendPacket(unsigned char *ucData, unsigned char ucSize);
#endif
<file_sep>#include "motor.h"
//电机初始化 -- PB10
void Motor_Init(void)
{
GPIO_InitTypeDef motorgpio;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);
//通用推挽输出
motorgpio.GPIO_Pin = GPIO_Pin_10;
motorgpio.GPIO_Mode = GPIO_Mode_OUT;
motorgpio.GPIO_OType = GPIO_OType_PP;
motorgpio.GPIO_Speed = GPIO_Speed_50MHz;
motorgpio.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOB,&motorgpio);
}
<file_sep>#include "delay.h"
uint32_t runtime=0;//记录系统运行的时间
/*
函数名称:Dealy_Config
函数功能:延时初始化
函数参数:time
返回值:无
*/
void Dealy_Config(void)
{
if(SysTick_Config(100000)==1) //1ms
{
while(1);
}
}
//中断多长时间进入1次:1ms
//void SysTick_Handler(void)
//{
// runtime++;
//}
/*
函数名称:Delay_ms
函数功能:延时n毫秒
函数参数:time
返回值:无
*/
void Delay_ms(uint32_t time)
{
uint32_t time1=runtime;//保存当前系统的运行时间
while(runtime-time1<time);
}
/*
函数名称:Delay_nus
函数功能:汇编延时n微妙
函数参数:time
返回值:无
*/
void Delay_nus(uint32_t time)
{
while(time--)
{
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();__nop();
}
}
/*
函数名称:Delay_nms
函数功能:汇编延时n毫秒
函数参数:time
返回值:无
*/
void Delay_nms(uint32_t time)
{
while(time--)
Delay_nus(1000);
}
| d2c02b562b61a09ddf4ca9dc2319d15768c2e71d | [
"C"
] | 30 | C | FLIPPEDz/STM32_Project | 930dc5112df282804fd0bebb4a242fbf514f48b8 | 282606060435311047033cdf8a56489f9091ec7f |
refs/heads/master | <file_sep>import React from 'react';
import './App.css';
import { Line } from 'react-chartjs-2';
import { Card, CardBody } from 'reactstrap';
import { ToastContainer } from 'react-toastify';
//import dataHumedad from './Data'
function lineOptions(labels = []) {
return{
responsive: true,
maintainAspectRatio: true,
animation: {
duration: 0,
},
legend: {
// display: false
labels: {
filter: (item, chart) => {
if (item.text) return !item.text.includes('none');
return item;
},
},
},
scales: {
xAxes: [
{
display: true,
labels: labels,
}
],
yAxes: [
{
ticks: {
beginAtZero: true,
max: 100,
min: 0,
stepSize: 20,
},
},
],
},
}
};
function data_humedad (datasrc=[]){
return { datasets: [
{
label: 'Humedad',
fill: false,
lineTension: 0.1,
backgroundColor: '#aeea00',
borderColor: '#aeea00', // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'black',
pointBackgroundColor: 'black',
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: 'yellow',
pointHoverBorderColor: 'brown',
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data: datasrc,
spanGaps: true,
}
]}
}
function data_luminosidad(datasrc=[]){
return {
datasets: [
{
label: 'Luminosidad',
fill: false,
lineTension: 0.1,
backgroundColor: '#D17B0F',
borderColor: '#D17B0F', // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'black',
pointBackgroundColor: 'black',
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: 'yellow',
pointHoverBorderColor: 'brown',
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data: datasrc,
spanGaps: true,
}
]}
};
function data_temperatura(datasrc=[]) {
return {
datasets: [
{
label: 'Temperatura',
fill: false,
lineTension: 0.1,
backgroundColor: '#B3001B',
borderColor: '#B3001B', // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'black',
pointBackgroundColor: 'black',
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: 'yellow',
pointHoverBorderColor: 'brown',
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data: datasrc,
spanGaps: true,
}
]}
};
function App(props) {
return (
<div className="Appt">
<ToastContainer />
<div className="container">
<div style={{ marginTop: '20px'}}>
<Card >
<CardBody>
<Line height={undefined} data={data_humedad(props.humedadValues)} options={lineOptions(props.labels)} />
</CardBody>
</Card>
<hr />
</div>
<div style={{ marginTop: '20px'}}>
<Card >
<CardBody>
<Line height={undefined} data={data_luminosidad(props.luminosidadValues)} options={lineOptions(props.labels)} />
</CardBody>
</Card>
<hr />
</div>
<div style={{ marginTop: '20px'}}>
<Card >
<CardBody>
<Line height={undefined} data={data_temperatura(props.temperaturaValues)} options={lineOptions(props.labels)} />
</CardBody>
</Card>
<hr />
</div>
</div>
</div>
);
}
export default App;
<file_sep>import { ChartData, ChartOptions } from 'chart.js';
const sourceD = [65, 59, 80, 90, 56, 55, 40, undefined, 60, 55, 109, 78];
const sourceS = [50, 40, 30, 40, 30, 90, 10, 50, 20, 30, 100, 78];
const sourceF = [90, 59, 70, 90, 56, 30, 40,50, 60, 55, 109, 78];
function dataHumedad (res = []) {
return {
datasets: [
{
label: 'Humedad',
fill: false,
lineTension: 0.1,
backgroundColor: '#aeea00',
borderColor: '#aeea00', // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'black',
pointBackgroundColor: 'black',
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: 'yellow',
pointHoverBorderColor: 'brown',
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data: res,
spanGaps: true,
}
],
}
};
var data1 = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [
{
label: 'Luminosidad',
fill: false,
lineTension: 0.1,
backgroundColor: '#D17B0F',
borderColor: '#D17B0F', // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'black',
pointBackgroundColor: 'black',
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: 'yellow',
pointHoverBorderColor: 'brown',
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data: sourceF,
spanGaps: true,
}
],
};
const data2 = {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [
{
label: 'Temperatura',
fill: false,
lineTension: 0.1,
backgroundColor: '#B3001B',
borderColor: '#B3001B', // The main line color
borderCapStyle: 'square',
borderDash: [], // try [5, 15] for instance
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'black',
pointBackgroundColor: 'black',
pointBorderWidth: 1,
pointHoverRadius: 8,
pointHoverBackgroundColor: 'yellow',
pointHoverBorderColor: 'brown',
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
// notice the gap in the data and the spanGaps: true
data: sourceS,
spanGaps: true,
}
],
};
const options = {
responsive: true,
maintainAspectRatio: true,
legend: {
// display: false
labels: {
filter: (item, chart) => {
if (item.text) return !item.text.includes('none');
return item;
},
},
},
scales: {
yAxes: [
{
// beforeBuildTicks: (scale: any) => {
// console.log(scale);
// if (scale._ticks)
// scale._ticks[0].major = true;
// },
ticks: {
beginAtZero: true,
max: 180,
min: 0,
stepSize: 20,
// values: []
// callback: function (value, index, values) {
// // if (value) console.log(value, values);
// return value == 120 ? null : value;
// }
},
// scaleLabel: {
// display: true,
// labelString: 'Moola',
// fontSize: isMobile() ? 11 : 30,
// padding: isMobile() ? 0 : undefined,
// lineHeight: isMobile() ? '70%' : undefined,
// },
// gridLines: {
// zeroLineWidth: 1,
// // borderDash: [6, 6],
// lineWidth: 1,
// color: ['#bdbdbd', '#bdbdbd', '#d50000', '#bdbdbd', '#bdbdbd', '#bdbdbd', '#bdbdbd', '#bdbdbd', '#bdbdbd'],
// }
},
],
},
// events: ['click'],
// onClick: (e: any, arr: any[]) => console.log(':v', e, arr),
};
export default dataHumedad ;
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import AWS from "aws-sdk";
import './index.css';
import App from './components/App';
import * as serviceWorker from './components/serviceWorker';
AWS.config.update({
accessKeyId: '<KEY>' ,
secretAccessKey: '<KEY>' ,
region: "us-east-2",
});
const docClient = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: "POC_Sensor_Data",
scan_index_forward: false
};
var recentEventsDateTime = [];
var humedadValues = [];
var temperaturaValues = [];
var luminosidadValues = [];
function renderGraphs (){
docClient.scan(params, function(err, data) {
const {Items} = data;
var temprecentEventsDateTime = [];
var temptemperaturaValues = [];
var temphumedadValues = [];
var templuminosidadValues = [];
var dataOutTemp = []
Items.forEach(function(item) {
let dataOutValue={};
dataOutValue.dateHour = item.hora;
dataOutValue.humedadValue = item.humedad;
dataOutValue.luminosidadValue = item.luminosidad;
dataOutValue.temperaturaValue = item.temperatura;
dataOutValue.timestampValue = item.data_timestamp;
dataOutValue.nanoValue = item.timestamp_value;
dataOutTemp.push(dataOutValue);
});
dataOutTemp.sort(function(a,b){return a.nanoValue-b.nanoValue});
dataOutTemp.forEach(function(it){
temprecentEventsDateTime.push(it.dateHour);
temptemperaturaValues.push(it.temperaturaValue);
temphumedadValues.push(it.humedadValue);
templuminosidadValues.push(it.luminosidadValue);
});
recentEventsDateTime = temprecentEventsDateTime.slice(-10);
humedadValues = temphumedadValues.slice(-10);
temperaturaValues = temptemperaturaValues.slice(-10);
luminosidadValues = templuminosidadValues.slice(-10);
ReactDOM.render(<App
labels = {recentEventsDateTime}
humedadValues = {humedadValues}
luminosidadValues = {luminosidadValues}
temperaturaValues = {temperaturaValues}
/>, document.getElementById('root'));
});
}
ReactDOM.render(<App
labels = {[]}
humedadValues = {[]}
luminosidadValues = {[]}
temperaturaValues = {[]}
/>, document.getElementById('root'));
setInterval(renderGraphs,2000);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
| 1b4e752952f4826ba5934b72dc3ed6b10806fca5 | [
"JavaScript"
] | 3 | JavaScript | Ferchu060100/Aaaa | e3fb248e3f2eda925c38c2ea3bf6d949d575ebde | 152d954947ac0e940121f55332a9d97ee5056e6c |
refs/heads/master | <file_sep>#include<stdio.h>
main(){
int ID[13],i,CID[13],sum = 0,x = 0,C13 = 0;
printf("Enter Digit One by One\n-----Digit Only--------\n");
for(i=1;i<=13;i++){
printf("Enter Digit%d:",i);
scanf("%d",&ID[i]);
CID[i] = ID[i] * (14-i);
}
printf("--------------------------------\n");
for(i=1;i<=13;i++){
printf("%d",ID[i]);
}
for(i=1;i<=12;i++){
sum = sum + CID[i];
}
x = sum%11;
if(x <= 1){
C13 = 1 - x;
}
else if(x > 1){
C13 = 11 - x;
}
if(C13 == CID[13]){
printf("\nTrue It's ID Number");
}
else if(C13 != CID[13]){
printf("\nFalse It isn't ID Number");
}
}
| 00bbb8c4d6f87b207cb20b2e29bdaed6f3f7f4f0 | [
"C++"
] | 1 | C++ | Tues1999/ETE183_2_7Program | ddd2c572a68f52776698fd83eeae5ff7a65d5735 | 086ff5532c8b31379d8736c2cccf61dc9baae762 |
refs/heads/master | <file_sep>//This is where we put js i suppose
<file_sep>APScheduler==3.0.0
beautifulsoup4==4.6.0
certifi==2017.11.5
chardet==3.0.4
click==6.7
cycler==0.10.0
Django==2.0
flake8==3.5.0
Flask==0.12.2
Flask-PyMongo==0.5.2
gunicorn==19.7.1
idna==2.6
itsdangerous==0.24
Jinja2==2.10
lxml==4.1.1
MarkupSafe==1.0
mccabe==0.6.1
numpy==1.13.3
pew==1.1.1
pipenv==9.0.0
psutil==5.3.1
pycodestyle==2.3.1
pyflakes==1.6.0
pygal==2.4.0
pyparsing==2.2.0
python-dateutil==2.6.1
pytz==2017.3
redis==2.10.6
requests==2.18.4
six==1.11.0
urllib3==1.22
virtualenv==15.1.0
virtualenv-clone==0.2.6
Werkzeug==0.13
<file_sep>from flask import Flask, render_template, url_for, request, jsonify
from flask_pymongo import PyMongo
import time
from datetime import datetime, date, timedelta
import pygal
from pygal.style import DefaultStyle
import urllib.request, html, urllib.parse
import bs4 as bs
import os
from urllib.parse import urlparse
app = Flask(__name__)
app.config['MONGO_DBNAME'] = os.environ.get('MONGODB_NAME')
app.config['MONGO_URI'] = os.environ.get('MONGODB_URI')
#mongo = PyMongo(app)
def get_rela_dates(abs_dates):
result, weeks = [], ['8','9','T','f','1','2']
wk_ind, day = 0, 0
for i in range(abs_dates):
result.append('{}{}'.format('MTWTFSS'[day],weeks[wk_ind]))
day += 1
if day == 7 or i == 25:
day = 0
wk_ind +=1
return result
def mkgraph(code):
bu = os.environ.get('PORTOFCALL')
try:
inf = urllib.request.urlopen(bu.format('w','18',code))
except:
chart = pygal.Line(no_data_text='Course Not Found',
style=DefaultStyle(no_data_font_size=40))
chart.add('line', [])
return chart.render_data_uri()
src = inf.read()
inf.close()
return src.decode('utf-8')
def get_course_info(code):
base_url = 'https://www.reg.uci.edu/perl/WebSoc?'
fields = [('YearTerm','2018-03'), ('CourseCodes',code)]
sauce = urllib.request.urlopen(base_url + urllib.parse.urlencode(fields))
soup = bs.BeautifulSoup(sauce, 'html.parser')
temp=str(soup.find('td',{'class':'CourseTitle'}))
temp = temp[temp.find('>')+1:]
temp = temp[:temp.find('<')].split()
return ' '.join(temp[:-1]),temp[-1]
def cook_quarter(quarter):
l = quarter.split()
if l[0]=='Fall':
return 'F'+quarter[-2:]
if l[0]=='Winter':
return 'W'+quarter[-2:]
if l[0]=='Spring':
return 'S'+quarter[-2:]
if l[0]=='Summer':
if l[2]=='1,':
return 'SS1'+quarter[-2:]
if l[2]=='2,':
return 'SS2'+quarter[-2:]
return 'S10'+quarter[-2:]
def get_hist(dept,num):
base_url = 'https://www.reg.uci.edu/perl/EnrollHist.pl?'
fields = [('dept_name',dept),('course_no',num),('class_type',''),('action','Submit')]
sauce = urllib.request.urlopen(base_url + urllib.parse.urlencode(fields))
soup = bs.BeautifulSoup(sauce, 'html.parser')
res = ''
cur_q = ''
for row in soup.find_all('tr'):
r = row.find_all('td')
if len(r) == 15 and r[5].text.strip() != 'DIS':
sp = bs.BeautifulSoup(urllib.request.urlopen(r[2].find('a').get('href')),'html.parser')
new_q = cook_quarter(sp.find('h3',{'style':'display: inline;'}).text)
res += '<tr bgcolor=\'#FFFFCC\'>'
if new_q != cur_q:
res += '<td bgcolor=\'#FFFFFF\'><span style=\'font-size: 14px;\'>'
res += new_q
res += '</span></td>'
cur_q = new_q
else:
res +='<td bgcolor=\'#FFFFFF\'></td>'
div = sp.find('div', {'class':'course-list'})
l = div.find('tr', {'valign':'top', 'bgcolor':'#FFFFCC'})
if l:
cells = l.find_all('td')
if cells[3].text != '0':
res += str(cells[0]) + str(cells[4]) + str(cells[5])
res += str(cells[7]) + str(cells[8])
if len(cells) == 14:
res += str(cells[9])
res += str(cells[12])
elif len(cells) == 15:
res += str(cells[10])
res += str(cells[13])
res += '</tr>'
return res+'</table>'
def js_encode(string):
if ' ' in string:
string = string[:string.find(' ')]+'zz'+string[string.find(' ')+1:]
if '&' in string:
string = string[:string.find('&')]+'qq'+string[string.find('&')+5:]
return string
def js_decode(string):
if 'zz' in string:
string = string[:string.find('zz')]+' '+string[string.find('zz')+2:]
if 'qq' in string:
string = string[:string.find('qq')]+'&'+string[string.find('qq')+2:]
return string
def gen_almanac_listing(dept='',ge='',num='',code=''):
url = 'https://www.reg.uci.edu/perl/WebSoc?'
fields = [('YearTerm','2018-03'),('ShowFinals','1'),('ShowComments','1')]
if code != '':
fields.append(('CourseCodes',code))
r = '<h4>You searched for the code(s): {}</h4>'.format(code)
elif ge != '':
fields.append(('Breadth',ge))
r = '<h4>You searched for the breadth: {}</h4>'.format(ge)
elif num != '':
fields.extend([('Dept',dept),('CourseNum',num)])
r = '<h4>You searched in the {} department for the course(s): {}</h4>'.format(dept,num)
else:
fields.append(('Dept',dept))
r = '<h4>You searched for the {} department</h4>'.format(dept)
sauce = urllib.request.urlopen(url + urllib.parse.urlencode(fields))
sp = bs.BeautifulSoup(sauce, 'html.parser')
for div in sp.find_all('div'):
if div.text.strip() == 'No courses matched your search criteria for this term.':
chart = pygal.Line(no_data_text='Nothing Matched Your Search', style=DefaultStyle(no_data_font_size=40))
chart.add('line', [])
r += '<br><h5>Nothing. We Ain\'t Found Nothing. At least for this quarter.</h5>'
return [(r,chart.render_data_uri(),'','')]
res = []
cur_num = ''
for row in sp.find_all('tr', {'class':''}):
if row.find('td', {'class':'Comments'}) == None or row.find('table') != None:
cells = row.find_all('td')
if len(cells)==9:
continue
r += str(row)
if len(cells) != 0 and len(cells[0].text) == 5 and cells[3].text != '0':
code = cells[0].text
r+='<tr><td colspan = 16>'
if '199' in cur_num or (cells[2].text.isnumeric() and int(cells[2].text)>4):
r += 'DATA HIDDEN'
else:
res.append((r,mkgraph(code),js_encode(dept),cur_num))
r = ''
elif row.find('td', {'class':'CourseTitle'}) != None:
temp = str(row.find('td', {'class':'CourseTitle'}))
temp = temp[temp.find('>')+1:]
temp = temp[:temp.find('<')].split()
cur_num = temp[-1]
if dept != ' '.join(temp[:-1]):
dept = ' '.join(temp[:-1])
return res
@app.route('/_db', methods=['GET','POST'])
def _db():
val = None
if request.method == 'POST':
url = urlparse(os.environ.get('REDISCLOUD_URL'))
val = eval(redis.Redis(host=url.hostname, port=url.port, password=url.password).get(request.form['key']))
return render_template('db.html', val=val)
@app.route('/_course_hist', methods=['GET','POST'])
def _course_hist():
record = None
print('will this work?')
client_agent = request.user_agent
if client_agent.browser.strip() == 'msie' or 'Edge' in client_agent.string:
print('LMAO THIS WORKS!')
if request.method == 'POST':
dept = request.form['dept']
num = request.form['num']
record=get_hist(js_decode(dept),num)
return render_template('course_hist.html',record=record)
@app.route('/soc', methods=['GET', 'POST'])
def soc():
if request.method == 'GET':
with urllib.request.urlopen('https://www.reg.uci.edu/perl/WebSoc') as src:
soup = bs.BeautifulSoup(src, 'lxml')
form = str(soup.find('form', {'action':'https://www.reg.uci.edu/perl/WebSoc'}))
form = form[:form.find('</table>')+8]
form = form.replace('https://www.reg.uci.edu/perl/WebSoc','')
return render_template('form.html',search_form=form)
else:# request.method == 'POST':
src = urllib.request.urlopen("https://www.reg.uci.edu/perl/WebSoc/",
data=urllib.parse.urlencode(request.form).encode())
soup = bs.BeautifulSoup(src.read(), 'lxml')
src.close()
course_list = soup.find('div', {'class':'course-list'})
course_list = course_list.find('table')
results = '<table>'
# for row in sp.find_all('tr', {'class':''}):
# if row.find('td', {'class':'Comments'}) == None or row.find('table') != None:
# cells = row.find_all('td')
# if len(cells)==9:
# continue
# r += str(row)
# if len(cells) != 0 and len(cells[0].text) == 5 and cells[3].text != '0':
# code = cells[0].text
# results += <
# elif row.find('td', {'class':'CourseTitle'}) != None:
# temp = str(row.find('td', {'class':'CourseTitle'}))
# temp = temp[temp.find('>')+1:]
# temp = temp[:temp.find('<')].split()
# cur_num = temp[-1]
# if dept != ' '.join(temp[:-1]):
# dept = ' '.join(temp[:-1])
results += '</table>'
return render_template('results.html',results=str(course_list))
@app.route('/', methods=['GET', 'POST'])
def main():
record = None
listing = None
on_edge=None
if request.method == 'POST':
code = request.form['CourseCodes']
dept = request.form['Dept']
num = request.form['CourseNum']
ge = request.form['Breadth']
if code is not '':
dept, num = get_course_info(code)
listing = gen_almanac_listing(code=code,dept=dept,num=num)
record = get_hist(dept,num)
elif ge.strip() != 'ANY':
listing = gen_almanac_listing(ge=ge)
elif dept.strip() is not 'ALL' and num is not '':
listing = gen_almanac_listing(dept=dept,num=num)
record = get_hist(dept,num)
elif dept.strip() is not 'ALL' and num is '':
listing = gen_almanac_listing(dept=dept)
client_agent = request.user_agent
if client_agent.browser.strip() == 'msie' or 'Edge' in client_agent.string:
on_edge = 'O Yes'
return render_template('test.html', record=record, listing=listing, on_edge=on_edge)
@app.route('/_test')
def test():
return render_template('index1.html')
@app.route('/_old_test')
def new_test():
return render_template('index.html')
@app.route('/_test/login', methods = ['POST'])
def login():
users = mongo.db.users
users.insert({'name' : request.form.get('username')})
return jsonify(success=True)
@app.route('/_try')
def try_things():
return render_template('prototype.html')
if __name__ == '__main__':
app.run(debug=True)
| 08acaeaaf4ad8fea05c4991c8cc18d97cdf7d417 | [
"JavaScript",
"Python",
"Text"
] | 3 | JavaScript | devsdevsdevs/AntAlmanac | 6f73f77a379a0be408a0c09db698e46a5e1ba9fc | 5b9665838fcaa724c02902d2000d4686b8e498e5 |
refs/heads/master | <repo_name>XincoZero/ruby-enumerables-hash-practice-emoticon-translator-lab-chi01-seng-ft-080320<file_sep>/lib/translator.rb
require "yaml"
def load_library(emoticon_file)
new_hash = {}
emoticons = YAML.load_file('lib/emoticons.yml')
emoticons.each do |key, element|
new_hash[key] = {}
new_hash[key] [:english] = element.first
new_hash[key] [:japanese] = element.last
end
new_hash
end
def get_japanese_emoticon(emoticon_file, input)
translation = load_library(emoticon_file)
info = "Sorry, that emoticon was not found"
translation.each do |key, element|
if translation[key][:english] == input
info = translation[key][:japanese]
end
end
info
end
def get_english_meaning(emoticon_file, input)
translation = load_library(emoticon_file)
info = "Sorry, that emoticon was not found"
translation.each do |key, element|
if translation[key][:japanese] == input
info = key
end
end
info
end | 5e04829137a813d2f36aea384b83aae316442d69 | [
"Ruby"
] | 1 | Ruby | XincoZero/ruby-enumerables-hash-practice-emoticon-translator-lab-chi01-seng-ft-080320 | 66b918507973d75125d8df7d8e226eb0e6e64aac | c70112eeedc720e7ba4faa903c3e0e5c2651a98d |
refs/heads/main | <file_sep>
const fs = require('fs');
const colors = require('colors');
const crearArchivo = async (base,l,h) => {
try {
let salida = '' ;
let consola = '';
for(let i = 1 ; i <= h ; i++){
consola += `${colors.brightGreen( base)} ${colors.cyan.underline('x')} ${colors.bold(i)} = ${colors.brightRed(base* i)}\n`
salida +=`${base} x ${i} = ${base* i}\n` ;
}
if(l) {
console.log(colors.red('====================' ))
console.log(colors.blue(' TABLA DE: '), colors.yellow(base))
console.log(colors.red('====================' ))
console.log(consola)}
fs.writeFileSync(`./salida/tabla-${base}.txt`,salida)
return(`tabla-${base}.text`)
}
catch(error){
throw error
}
}
module.exports = {
crearArchivo
} | 20c493d7ef0d10b0a7e63fec60af45fac6d81705 | [
"JavaScript"
] | 1 | JavaScript | matias293/Tabla-de-multiplicacion | 924e9f8ef8a6b96ba4a46fa8f751b20a8a3f45d9 | a6f7593d97a72a25578c27cdbd7cb95daf1e5b99 |
refs/heads/master | <repo_name>ferentino/GoogleDriveApi<file_sep>/README.md
# GoogleDriveApi
<file_sep>/app.js
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
var counter = 0;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];
const TOKEN_PATH = 'token.json';
fs.readFile('credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
authorize(JSON.parse(content),returnJson);
});
function authorize(credentials,callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getAccessToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
function getAccessToken(oAuth2Client,callback) {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES,
});
console.log('Authorize this app by visiting this url:', authUrl);
socket.emit('createAuth',authUrl)
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter the code from that page here: ', (code) => {
rl.close();
oAuth2Client.getToken(code, (err, token) => {
if (err) return console.error('Error retrieving access token', err);
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
if (err) return console.error(err);
console.log('Token stored to', TOKEN_PATH);
});
callback(oAuth2Client);
console.log('teste')
});
});
}
function returnJson(auth){
socket.on('returnFolders',(msg)=>{
console.log(msg)
const drive = google.drive({version: 'v3', auth});
drive.files.list({
q: msg ,
filesize: 5,
fields: 'nextPageToken, files(id,name,mimeType,parents,version,webContentLink,webViewLink,owners,viewedByMe,viewedByMeTime,createdTime,modifiedTime, modifiedByMeTime,lastModifyingUser,fullFileExtension)',
}, (err, res) => {
var result = []
if (err) return console.log('The API returned an error: ' + err);
const files = res.data.files;
if (files.length) {
files.map((file)=>{
result.push(
file
)
socket.emit('returnFolders',file);
});
} else {
console.log('No files found.');
}
});
})
socket.on('returnFiles',(msg)=>{
console.log(msg)
const drive = google.drive({version: 'v3', auth});
drive.files.list({
q: msg ,
filesize: 5,
fields: 'nextPageToken, files(id,name,mimeType,parents,version,webContentLink,webViewLink,owners,viewedByMe,viewedByMeTime,createdTime,modifiedTime, modifiedByMeTime,lastModifyingUser,fullFileExtension)',
}, (err, res) => {
var result = []
if (err) return console.log('The API returned an error: ' + err);
const files = res.data.files;
if (files.length) {
files.map((file)=>{
result.push(
file
)
});
} else {
console.log('No files found.');
}
result.map((obj)=>{
console.log(obj)
socket.emit('returnFiles',obj);
})
});
})
}
});
http.listen(3000, function(){
console.log('listening on *:3000');
}); | 54343220a55350ac68acafef930d15f86f616aac | [
"Markdown",
"JavaScript"
] | 2 | Markdown | ferentino/GoogleDriveApi | c05063f6f3dc04afed69ddffae6afb52ad232ab2 | 49fbef23b2fae5543cf870a22c0333736ee81e61 |
refs/heads/master | <file_sep># File: datetime-example-1.py
import datetime
now = datetime.datetime(2003, 8, 4, 12, 30, 45)
print(now)
print(repr(now))
print(type(now))
print(now.year, now.month, now.day)
print(now.hour, now.minute, now.second)
print(now.microsecond)
<file_sep># File: datetime-example_1.py
import datetime
# import datetime, date, time, timedelta
import time
def print_datetime(now):
print(now)
print(repr(now))
print(type(now))
print(now.year, now.month, now.day)
print(now.hour, now.minute, now.second)
print(now.microsecond)
print()
t1 = datetime.datetime(2003, 8, 4, 12, 30, 45)
print('datetime.datetime(2003, 8, 4, 12, 30, 45) =', t1)
print_datetime(t1)
t2 = datetime.datetime.now()
time.sleep(2) # delays for 5 seconds
t3 = datetime.datetime.now()
print('datetime.now() =', t2)
print_datetime(t2)
mytdelta = datetime.timedelta(1, 5, 41038) # Interval of 1 day and 5.41038 seconds
secs = mytdelta.total_seconds()
hours = (secs / 3600)
minutes = (secs / 60)
"""
hours = int(secs / 3600)
minutes = int(secs / 60) % 60
"""
print('secs=', secs, 'hours=', hours, 'minutes=', minutes)
dur = t2 - t1
print('dur.__class__ = ', dur.__class__)
dur2 = t3 - t2
secs = dur2.total_seconds()
hours = (secs / 3600)
minutes = (secs / 60)
print('secs=', secs, 'hours=', hours, 'minutes=', minutes)
<file_sep>import csv
input = 316.2
previous_abs_diff = 999999
counter = 0
# scaled_input = input / 11.25
csvfile = 'compass_points_unicode.csv'
with open(csvfile, newline='') as f:
reader = csv.reader(f)
cp_dict = {}
for row in reader:
num = row[0]
cp_dict[num] = row
for key in cp_dict.keys():
print(cp_dict[key])
# points = list(range(33))
for point in list(range(33)):
abs_diff = abs((11.25 * counter) - input)
print(counter, abs_diff)
if abs_diff < previous_abs_diff:
previous_abs_diff = abs_diff
previous_abs_diff_counter = counter
counter += 1
# print(previous_abs_diff, previous_abs_diff_counter + 1)
result_key = str(previous_abs_diff_counter+1)
# print('result:', cp_dict[result_key])
print('result:', cp_dict[result_key][1])
<file_sep># random_sleep.py
import random, time
def sleeper():
while True:
# Get user input
v = False # verbose?
r = random.random()
num = r * 3
# input('How long to wait, in seconds?: ')
# Try to convert it to a float
try:
num = float(num)
except ValueError:
print('Please enter in a number.\n')
continue
# Run our time.sleep() command,
# and show the before and after time
if v: print('Before: %s' % time.ctime())
t1 = time.time()
if v: print(time.ctime())
print('t1 =', t1)
time.sleep(num)
t2 = time.time()
if v: print('After: %s\n' % time.ctime())
diff = t2 - t1
print('t2 = ', t2)
print('diff = ', diff)
try:
sleeper()
except KeyboardInterrupt:
print('\n\nKeyboard exception received. Exiting.')
exit()
<file_sep># http://www.dabeaz.com/pydata
from xml.etree.ElementTree import parse
doc = parse('rt22.xml')
# https://developers.google.com/maps/documentaiton/staticmaps/
import webbrowser
webbrowser.open('http://...')
<file_sep>
s = '深入 Python'
print(s, len(s))
len(s)
print(s[0])
print(s + ' 3')
<file_sep>
YouTube tutorial:
https://www.youtube.com/watch?v=RrPZza_vZ3w&index=8&list=PL5Yhw3d61mnCnJdvfgu-ACefHeAVeWNe4
<file_sep>
lat1 = 41.980262
lat2 = 42.031662
def distance(lat1, lat2):
""" return approx miles between lat1 and lat2"""
return 69 * abs(lat1 - lat2)
print(distance(lat1, lat2))
<file_sep>from cryptography.fernet import Fernet
key = b'mykey'
missing_padding = 32 - len(key) # % 4
if missing_padding:
key += b'='* missing_padding
# key = Fernet.generate_key()
print('key = ', key, 'len(key) = ', len(key), 'key class = ', key.__class__)
counter = 0
print('list(key)=', list(key), 'len(key)=', len(key))
f = Fernet(key)
token = f.encrypt(b"<PASSWORD>")
print('encrypted token = ', token)
decrypted = f.decrypt(token)
print('decrypted = ', decrypted)
# 'my deep dark secret'
def decode_base64(data):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = 4 - len(data) % 4
if missing_padding:
data += b'='* missing_padding
return base64.decodestring(data)<file_sep>mystring = "hello world"
print('mystring =', mystring)
bytestring1 = bytes(mystring, 'utf-8')
bytestring2 = mystring.encode('utf-8')
print(type(bytestring1), type(bytestring2)) # insures its bytes
print(bytestring1, bytestring2)
unicode_text = bytestring1.decode('utf-8')
print('unicode_text =', unicode_text)
<file_sep>"""#!/usr/bin/python2.7 -u
"""
import os
import sys
from time import sleep
def wait(sec):
while sec > 0:
sys.stdout.write(str(sec) + ' \r')
sec -= 1
sleep(1)
def main():
# os.system('setterm -cursor off')
try:
while True:
# an external command that I call regularly
os.system('./proxies.py')
wait(300)
except KeyboardInterrupt:
print
finally:
pass
# os.system('setterm -cursor on')
############################################
if __name__ == "__main__":
main()
<file_sep>notes.txt
l = []
l.extend(range(1, 6))
print l
# [1, 2, 3, 4, 5]
l.extend(range(1, 6))
print l
# [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
l = []
l.extend(range(1, 6))
print(l)
l.extend(range(1, 6))
print(l)
s=String;
s.prototype.r = s.prototype.replace;
function calcPoint(input) {
var j = input % 8,
// print j;
alert(j);
input = (input / 8)|0 % 4,
cardinal = ['north', 'east', 'south', 'west'],
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1'],
str1, str2, strC;
str1 = cardinal[input];
str2 = cardinal[(input + 1) % 4];
strC = (str1 == cardinal[0] | str1 == cardinal[2]) ? str1 + str2 : str2 + str1;
return pointDesc[j].r(1, str1).r(2, str2).r('C', strC);
}
function getShortName(name) {
return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "");
}
alert('running');
var input = 33.7;
alert(input);
input = input+.5|0;
alert(input);
var name = calcPoint(input);
alert(name);
var shortName = getShortName(name);
name = name[0].toUpperCase() + name.slice(1);
alert(name + " " + shortName);
<file_sep># https://pypi.python.org/pypi/geopy
from geopy.distance import great_circle
newport_ri = (41.49008, -71.312796)
cleveland_oh = (41.499498, -81.695391)
print(great_circle(newport_ri, cleveland_oh).miles)
# 537.1485284062816
print(newport_ri[0])
newport = (newport_ri[0], newport_ri[0])
print(newport)
print(newport.__class__)
<file_sep>import unicodedata
def get_heading(degrees):
directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW","N"]
arrows = ["↑", "↗", "→", "↘" ,"↓", "↙", "←", "↖","↑"]
mod = ((degrees % 360) + 360) % 360
print('mod = ', mod)
sector = int((mod + 22.5) / 45)
try:
return (degrees, sector, directions[sector], arrows[sector])
except:
return (degrees,sector)
print (get_heading(int(33.4)))
for index in list(range(19)):
# bearing = -(index * 45) # - 22.5)
print(get_heading(bearing))
bearing = -(index * 45 - 22.5 -.0001)
print(get_heading(bearing))
<file_sep>import sys
import inspect
from time import sleep
import math
db = False
def lineno():
"""Returns the current line number in our program."""
return inspect.currentframe().f_back.f_lineno
def upperfirst(x):
"""Make the first letter of a string uppercase."""
return x[0].upper() + x[1:]
def calcPoint(input):
print('line', lineno(), 'input = ', input)
j = input % 8
input2 = math.floor(input / 8) % 4
print('line', lineno(), 'input =', input, 'j =', j, 'input2 =', input2)
cardinal = ['north', 'east', 'south', 'west']
pointDesc = ['1', '1 by 2', '1-C', 'C by 1', 'C', 'C by 2', '2-C', '2 by 1']
str1 = cardinal[input2]
str2 = cardinal[(input2 + 1) % 4]
strC = 'x'
print('line', lineno(), 'str1 = [', str1, '] str2 =[', str2, ']')
print('line', lineno(), 'cardinal[0] = [', cardinal[0])
print('line', lineno(), 'cardinal[2] = [', cardinal[2])
if str1 == cardinal[0]:
print('line', lineno(), 'str1:', str1, ' == cardinal[0]', cardinal[0])
elif str1 == cardinal[2]:
print('line', lineno(), 'str1:', str1, ' == cardinal[2]', cardinal[2])
else:
print('line', lineno(), 'str1:', str1, ' != cardinal[0]', cardinal[0])
print('line', lineno(), 'str1:', str1, ' != cardinal[2]', cardinal[2])
if str1 == cardinal[0] or str1 == cardinal[2]:
strC = str1 + str2
else:
str2 = str2 + str1
strC = ''
# print('line', lineno(), input, 'str2 =', str2)
# print('line', lineno(), 'input =', input, 'str1 =', str1, 'str2 =', str2, 'strC =', strC)
print('line', lineno(), '; input =', input, '; str1 =', str1, '; str2 =', str2, '; strC =', strC)
countme = 0
for element in pointDesc:
countme += 1
res = element.replace('1', str1).replace('2', str2).replace('C', strC)
print(countme, res)
print('line', lineno(), 'pointDesc[', j, '] =', pointDesc[j])
result = pointDesc[j].replace('1', str1).replace('2', str2).replace('C', strC)
result = upperfirst(result)
print('result =', result)
return result
#return pointDesc[j].replace('1', str1).replace('2', str2).replace('C', strC)
# def getShortName(name):
# return name.r(/north/g, "N").r(/east/g, "E").r(/south/g, "S").r(/west/g, "W").r(/by/g, "b").r(/[\s-]/g, "")
if False:
l = []
l.extend(range(1, 361))
print(l)
sleep(2)
for value in l:
myin = value
input = int(myin / 11.25)
# print('myin =', myin, 'input =', input)
name = calcPoint(input)
# print('name =', name)
# shortName = getShortName(name)
# name = name[0].upper() + name[1] # .slice(1)
print(myin, name) # , shortName)
if False:
print(lineno(), 'Number of arguments:', len(sys.argv), 'arguments.')
print(lineno(), 'Argument List:', str(sys.argv))
if len(sys.argv) > 1:
myin = int(sys.argv[1])
else:
myin = 1
print(lineno(), 'myin =', myin)
if True:
l = []
l.append((0, 'North', 'N'))
l.append((23.97, 'North-northeast', 'NNE'))
l.append((33.7, 'Northeast by north', 'NEbN'))
l.append((73.12, 'East-northeast', 'ENE'))
l.append((73.13, 'East by north', 'EbN'))
l.append((219, 'Southwest by south', 'SWbS'))
l.append((275, 'West', 'W'))
l.append((276, 'West by north', 'WbN'))
l.append((287, 'West-northwest', 'WNW'))
print(lineno(), 'list = ', l)
sleep(1/2)
for value in l:
# myin = int(round(value[0] / 11.25))
myin = value[0] / 11.25
myin2 = math.floor(myin + 0.5)
print(lineno(), 'myin2 =', myin2, myin2.__class__)
input = myin2 # int(round(myin))
name = calcPoint(input)
# shortName = getShortName(name)
# name = name[0].upper() + name[1] # .slice(1)
# print('line ', lineno(), 'myin = ', myin, 'name =', name )
print('line', lineno(), 'bearing: ', value[0], 'correct result:', value[1])
print('============')
# Compass point Abbreviation Traditional wind point Minimum Middle azimuth Maximum
1 North N Tramontana 354.38° 0.00° 5.62°
2 North by east NbE Quarto di Tramontana verso Greco 5.63° 11.25° 16.87°
3 North-northeast NNE Greco-Tramontana 16.88° 22.50° 28.12°
4 Northeast by north NEbN Quarto di Greco verso Tramontana 28.13° 33.75° 39.37°
5 Northeast NE Greco 39.38° 45.00° 50.62°
6 Northeast by east NEbE Quarto di Greco verso Levante 50.63° 56.25° 61.87°
7 East-northeast ENE Greco-Levante 61.88° 67.50° 73.12°
8 East by north EbN Quarto di Levante verso Greco 73.13° 78.75° 84.37°
9 East E Levante 84.38° 90.00° 95.62°
10 East by south EbS Quarto di Levante verso Scirocco 95.63° 101.25° 106.87°
11 East-southeast ESE Levante-Scirocco 106.88° 112.50° 118.12°
12 Southeast by east SEbE Quarto di Scirocco verso Levante 118.13° 123.75° 129.37°
13 Southeast SE Scirocco 129.38° 135.00° 140.62°
14 Southeast by south SEbS Quarto di Scirocco verso Ostro 140.63° 146.25° 151.87°
15 South-southeast SSE Ostro-Scirocco 151.88° 157.50° 163.12°
16 South by east SbE Quarto di Ostro verso Scirocco 163.13° 168.75° 174.37°
17 South S Ostro 174.38° 180.00° 185.62°
18 South by west SbW Quarto di Ostro verso Libeccio 185.63° 191.25° 196.87°
19 South-southwest SSW Ostro-Libeccio 196.88° 202.50° 208.12°
20 Southwest by south SWbS Quarto di Libeccio verso Ostro 208.13° 213.75° 219.37°
21 Southwest SW Libeccio 219.38° 225.00° 230.62°
22 Southwest by west SWbW Quarto di Libeccio verso Ponente 230.63° 236.25° 241.87°
23 West-southwest WSW Ponente-Libeccio 241.88° 247.50° 253.12°
24 West by south WbS Quarto di Ponente verso Libeccio 253.13° 258.75° 264.37°
25 West W Ponente 264.38° 270.00° 275.62°
26 West by north WbN Quarto di Ponente verso Maestro 275.63° 281.25° 286.87°
27 West-northwest WNW Maestro-Ponente 286.88° 292.50° 298.12°
28 Northwest by west NWbW Quarto di Maestro verso Ponente 298.13° 303.75° 309.37°
29 Northwest NW Maestro 309.38° 315.00° 320.62°
30 Northwest by north NWbN Quarto di Maestro verso Tramontana 320.63° 326.25° 331.87°
31 North-northwest NNW Maestro-Tramontana 331.88° 337.50° 343.12°
32 North by west NbW Quarto di Tramontana verso Maestro 343.13° 348.75° 354.37°
<file_sep># page 13, https://media.readthedocs.org/pdf/cryptography/latest/cryptography.pdf
import base64
# import os ## required to generate salt
import sys
import inspect
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
# password = b'<PASSWORD>'
# print('password = ', password, 'password.__class__ = ', password.__class__)
db = False # debugging? > verbose output
"""In this scheme, the salt has to be stored in a
retrievable location in order to derive the same key
from the password in the future."""
# salt = os.urandom(16)
salt = b'AJ\xf6\x12\x970B\x82\x15\xd6\xea\x01\x81k0S'
def lineno():
""" Returns the current line number in the program.
<NAME> (<EMAIL>).
Requires import inspect.
"""
return inspect.currentframe().f_back.f_lineno
def encrypt(password, plaintext):
if db:
print(lineno(), 'salt =', salt, 'type(salt) =', type(salt), 'len(salt) =', len(salt))
salt_list = list(salt)
if db:
print(lineno(), 'salt_list =', salt_list, 'len(salt_list) =', len(salt_list))
"""Key derivation function.
The iteration count used should be adjusted to be as
high as your server can tolerate. A good default is
at least 100,000 iterations which is what Django
recommends in 2014."""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
# convert password to bytes
bytestring_password = bytes(password, 'utf-8')
# convert plaintext to bytes
plaintext_bytes = bytes(plaintext, 'utf-8')
key = base64.urlsafe_b64encode(kdf.derive(bytestring_password))
f = Fernet(key)
token = f.encrypt(plaintext_bytes)
if db:
print(lineno(), 'token = ', token)
if db:
print(lineno(), 'f.decrypt(token)=', f.decrypt(token))
return token # ciphertext
def decrypt(password, ciphertext):
if db:
print(lineno(), 'salt =', salt, 'type(salt) =', type(salt), 'len(salt) =', len(salt))
salt_list = list(salt)
if db:
print(lineno(), 'salt_list =', salt_list, 'len(salt_list) =', len(salt_list))
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
# convert password to bytes
bytestring_password = bytes(password, 'utf-8')
key = base64.urlsafe_b64encode(kdf.derive(bytestring_password))
f = Fernet(key)
plaintext_bytes = f.decrypt(ciphertext)
plaintext = plaintext_bytes.decode('utf-8')
if db:
print(lineno(), 'plaintext =', plaintext)
return plaintext
def main():
""" Define a main() function that parses parameters and runs a test."""
args = sys.argv[1:]
if db:
print(lineno(), 'args =', args)
args = sys.argv[1:]
if not args or len(args) > 2 or (len(args) == 1 and args[0] != '--test'):
print('usage: [--test | password plaintext]')
sys.exit(1)
if args[0] == '--test':
print('testing!')
password = '<PASSWORD>'
plaintext = 'Triple secret message!'
else:
password = sys.argv[1]
plaintext = sys.argv[2]
print(lineno(), 'password =', password, 'plaintext =', plaintext)
ciphertext = encrypt(password, plaintext)
print(lineno(), 'ciphertext =', ciphertext)
plaintext = decrypt(password, ciphertext)
print(lineno(), 'recovered plaintext =', plaintext)
# This is the standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
<file_sep># find_north.py
# Parse the 'rt22.xml' file and identify all buses traveling
# northbound of Dave's office
import urllib.request
from xml.etree.ElementTree import parse
import time
from time import sleep
import math
import os
import sys
import webbrowser
office_lat = 41.980262
office_lon = -87.668452
bus_route_num_str = '22'
seconds_between_observations = 15
def distance(lat1, lat2):
"""Return approx miles between lat1 and lat2"""
return 69 * abs(lat1 - lat2)
class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
def wait(sec):
""" source: https://pythonadventures.wordpress.com/2012/12/08/countdown-in-command-line/ """
while sec > 0:
sys.stdout.write(str(sec) + ' \r')
sec -= 1
sleep(1)
def collect():
counter = 0
counter += 1
get_bus_schedule(bus_route_num_str)
t1 = time.time()
b1 = parse_bus_schedule(t1, bus_route_num_str)
print('Number of buses in observation', str(counter), '=', len(b1))
# time.sleep(7)
wait(seconds_between_observations)
get_bus_schedule(bus_route_num_str)
t2 = time.time()
b2 = parse_bus_schedule(t2, bus_route_num_str)
counter += 1
print('Number of buses in observation', str(counter), '=', len(b1))
# print('Number of buses in observation 2 =', len(b2))
diff = t2 - t1
print('diff = ', diff)
print(' busid speed distance direction')
for key in sorted(b1.keys()):
try:
if b2[key]:
bus1 = b1[key] # ['rec_time']
bus2 = b2[key] # ['rec_time']
bus1_time = bus1['rec_time']
bus2_time = bus2['rec_time']
time_diff_secs = bus2_time - bus1_time
time_diff_hrs = (time_diff_secs / 60) / 60
# bus_distance = distance(bus2['lat'], bus1['lat'])
bus_distance = distance(bus2['bus_loc'][0], bus1['bus_loc'][0])
bearing = calculate_initial_compass_bearing(bus2['bus_loc'], bus1['bus_loc'])
bus_speed_miles_hour = bus_distance / time_diff_hrs
print('busid: %-5s %6s %2.2f %-18s %6s' % (key, str(round(bus_speed_miles_hour, 2)), bus2['dist'], bus2['direction'], str(bearing)))
except KeyError:
print('busid ', key, 'not found in second observation')
def get_bus_schedule(bus_route_num_str):
url_string = 'http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=' + bus_route_num_str
# u = urllib.request.urlopen('http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22')
u = urllib.request.urlopen(url_string)
data = u.read()
xml_file_name = 'rt' + bus_route_num_str + '.xml'
f = open(xml_file_name, 'wb')
# f = open('rt22.xml', 'wb')
f.write(data)
f.close()
print('Wrote rt22.xml')
def parse_bus_schedule(rec_time, bus_route_num_str):
xml_file_name = 'rt' + bus_route_num_str + '.xml'
# doc = parse('rt22.xml')
doc = parse(xml_file_name)
print('busid, direction, lat, distance, rec_time')
bus_id_dict = {}
for bus in doc.findall('bus'):
lat = float(bus.findtext('lat'))
lon = float(bus.findtext('lon'))
bus_loc = (lat, lon)
print(bus_loc, len(str(bus_loc)))
print(bus_loc.__class__)
if True: # lat >= office_lat:
busid = bus.findtext('id')
direction = bus.findtext('d')
if True: # direction.startswith('North'):
dist = distance(office_lat, lat)
# print('busid: %-5s %-18s %-20s %2.4f %8.2f ' % (busid, direction, lat, dist, rec_time))
bus_dict = {'direction': direction, 'lat': lat, 'dist': dist, 'rec_time': rec_time, 'bus_loc': bus_loc}
bus_id_dict[busid] = bus_dict
print_bus_id_dict(bus_id_dict)
return bus_id_dict
def print_bus_id_dict(bus_id_dict):
for key in sorted(bus_id_dict.keys()):
bus_data = bus_id_dict[key]
print('busid: %-5s %-18s %-40s %2.4f %8.2f ' % (key, bus_data['direction'], bus_data['bus_loc'], bus_data['dist'], bus_data['rec_time']))
# https://gist.githubusercontent.com/jeromer/2005586/raw/5456a9386acce189ac6cc416c42e9c4b560a633b/compassbearing.py
def calculate_initial_compass_bearing(pointA, pointB):
"""
Calculates the bearing between two points.
The formulae used is the following:
θ = atan2(sin(Δlong).cos(lat2),
cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong))
:Parameters:
- `pointA: The tuple representing the latitude/longitude for the
first point. Latitude and longitude must be in decimal degrees
- `pointB: The tuple representing the latitude/longitude for the
second point. Latitude and longitude must be in decimal degrees
:Returns:
The bearing in degrees
:Returns Type:
float
"""
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = math.radians(pointA[0])
lat2 = math.radians(pointB[0])
diffLong = math.radians(pointB[1] - pointA[1])
x = math.sin(diffLong) * math.cos(lat2)
y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1)
* math.cos(lat2) * math.cos(diffLong))
initial_bearing = math.atan2(x, y)
# Now we have the initial bearing but math.atan2 return values
# from -180° to + 180° which is not what we want for a compass bearing
# The solution is to normalize the initial bearing as shown below
initial_bearing = math.degrees(initial_bearing)
compass_bearing = (initial_bearing + 360) % 360
return compass_bearing
collect()
| 7484918f06fca116c280b46e52a2cb1b9adb4ddb | [
"Markdown",
"Python",
"Text"
] | 17 | Python | johnfkraus/python_public_data_hacking | 0faa0551d3ec99823037df77c281ad9b3a546e0c | 862472adc6ce1eb8681b07e1ca7ffb417a6b6a4d |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static HW_MazeGame.PlayableChar;
namespace HW_MazeGame
{
class MazeMap
{
public static bool clear = false;
public static int stack;
static int h = 30;
static int v = 20;
public static string block = " "; // 0 or 1
public static char player = '●'; // P
public static char exit = '◆'; // E
public static char item = '★'; // K
public static char[,] code = new char[v, h];
string XY = System.IO.File.ReadAllText(@"C:\Users\huichan\Desktop\source\repos\HW_MazeGame\HW_MazeGame\MazeCoordinate.txt");
// string XY =
//"000000000000000000000000000000" +
//"011101011111101111101111101110" +
//"010101010000101000100000101010" +
//"010101011110101010111111101010" +
//"01010100001010101010000010K010" +
//"0P0101011110101010101110100010" +
//"000101010000101011101010111110" +
//"010101011110101000000010100000" +
//"0101010000101011110K0110111110" +
//"011101101110000101010100000010" +
//"010000101011110100010101111010" +
//"010111111000010111110101001010" +
//"010100001011010100010101011110" +
//"01010K101010010101110101000010" +
//"010101101011110101000101111010" +
//"010100101000000101011100001000" +
//"0101111011110K11010101011110E0" +
//"010000100001000101010101000010" +
//"011111101111111101110101111110" +
//"000000000000000000000000000000";
public void Start()
{
code = InsertCode();
while (clear == false)
{
PrintTable();
PrintMaze();
PlayerMove();
Console.Clear();
}
}
void PrintTable()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine();
Console.WriteLine(" 『 미로 찾기 게임 』");
Console.WriteLine();
Console.ResetColor();
Console.WriteLine($" 시간 : 999 획득한 별 : {stack}개");
}
void PrintMaze()
{
for (int i = 0; i < code.GetLength(0); i++)
{
for (int j = 0; j < code.GetLength(1); j++)
{
if (code[i, j] == 'P')
{
Console.ForegroundColor = ConsoleColor.Red;
Console.BackgroundColor = ConsoleColor.White;
Console.Write(player);
}
else if (code[i, j] == 'E')
{
Console.ForegroundColor = ConsoleColor.White;
Console.BackgroundColor = ConsoleColor.Green;
Console.Write(exit);
}
else if (code[i, j] == 'K')
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.BackgroundColor = ConsoleColor.White;
Console.Write(item);
}
else if (code[i, j] == '0')
{
Console.BackgroundColor = ConsoleColor.Black;
Console.Write(block);
}
else if (code[i, j] == '1')
{
Console.BackgroundColor = ConsoleColor.White;
Console.Write(block);
}
else
{
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(code[i,j]);
}
Console.ResetColor();
}
Console.WriteLine();
}
}
char[,] InsertCode()
{
int n = 0;
for (int i = 0; i < code.GetLength(0); i++)
{
for (int j = 0; j < code.GetLength(1); j++)
{
code[i, j] = XY[n++];
}
}
return code;
}
}
}
<file_sep># HW_MazeGame
200216 미로찾기 과제
| 3124a1232e08da342f598f418084d154b8044f61 | [
"Markdown",
"C#"
] | 2 | C# | Liranple/HW_MazeGame | 51b1a06b2c2e1377aea9f2cb374f63d4ceca65af | 660bbb6be3cf2654c2ec2002c7223447a548fe2f |
refs/heads/master | <file_sep># Homepage: http://mzj.beijing.gov.cn/jhyy/marryout/marry/index_yy.jsp
# Homepage: http://mzjgfpt.caservice.cn/jhyy/marryout/marry/index_yy.jsp
import re
import time
import datetime
import urllib
import urllib.error
import urllib.request
span = 2 # months: 1/2/3/4 (bad: 5/6/7..)
cookie = 'JSESSIONID=rBCWRBtZXgYB9Ka9WWTEP0JJlZIou9aVmTQA.marry1; Hm_lvt_8d03d41be19b72d5f435f915b62779f6=1577144183; Hm_lpvt_8d03d41be19b72d5f435f915b62779f6=1577451827'
headers = {'Cookie': cookie}
url1 = 'http://mzjgfpt.caservice.cn/jhyy/marryout/marry/stepFour.do?method=stepFour'
url2 = 'http://mzjgfpt.caservice.cn/jhyy/report/view_report.jsp?reportName=jhyy&where1=&start_date=%s&end_date=%s&deptCode=%s'
request = urllib.request.Request(url1, headers=headers)
response = urllib.request.urlopen(request, timeout=5)
content = response.read().decode('gbk')
district = re.findall(r'<option value="(.*?)" >(.*?)民政局婚姻登记处</option>', content)
print('Author Lsx')
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print('district: %s'%len(district))
with open('log.csv', 'w') as f:
f.write('Start time: %s\n\n'%time.strftime('%Y-%m-%d %H:%M:%S'))
text = ''
oneday = datetime.timedelta(1)
for code, dept in district:
print ('-- ' + dept)
for m in range(int(12 / span) * 0, int(12 / span) * 10):
y1, m1 = divmod(span * (m), 12)
y2, m2 = divmod(span * (m + 1), 12)
d1 = datetime.datetime.strftime(datetime.datetime(2010 + y1, m1 + 1, 1), '%Y-%m-%d')
d2 = datetime.datetime.strftime(datetime.datetime(2010 + y2, m2 + 1, 1) - oneday,'%Y-%m-%d')
print(d1, d2)
# 实测提交20190101-20191201, 能记录到跨度20190101-20190622, 共173天
url = url2%(d1, d2, code)
while 1: # while 1 + break : 有趣的循环重试方法
try:
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request, timeout=15)
content = response.read().decode('gbk')
items = re.findall(r'title=".*? (.*?) (.*?)"', content)
for item in items:
text += dept+','+d1[:5]+item[0]+','+item[1]+'\n'
# time.sleep(2.7)
break
except Exception as e:
print('Error:', e)
with open('log.csv', 'a') as f:
f.write(text)
text = ''
with open('log.csv', 'a') as f:
f.write('\nEnd time: %s\n'%time.strftime('%Y-%m-%d %H:%M:%S'))
<file_sep>import os
import csv
import time
import pandas
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import mpl_toolkits.axisartist as axis
from matplotlib.ticker import FuncFormatter
FormatPercent = FuncFormatter(lambda temp, position: '%.1f%%'%(temp*100))
def DrawGeneral(title='', show=True, savefile=None):
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.tight_layout()
plt.subplots_adjust(top=0.94)
plt.title(title)
if savefile:
plt.savefig('result/'+savefile+'.png')
if show:
plt.show()
plt.clf()
# nums, areas = Analyse1(data, 'area')
nums = [69287, 43625, 19130, 3243, 6024, 2118, 3933, 16906, 15588, 133574, 183478, 15551, 99804, 22409, 4516, 17692]
areas1 = ['东城区', '丰台区', '大兴区', '密云区', '平谷区', '延庆区', '怀柔区', '房山区', '昌平区', '朝阳区', '海淀区', '石景山区', '西城区', '通州区', '门头沟区', '顺义区']
areas2 = ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云区', '延庆区']
population = [85.10, 122.00, 373.90, 218.60, 61.20, 348.00, 32.20, 115.40, 150.80, 112.80, 206.30, 176.10, 40.50, 44.80, 49.00, 34.00 ]
mianji = [4182.04, 5033.13, 45118.62, 30359.44, 8422.40, 42648.77, 140571.01, 190006.93, 88531.76, 98927.58, 132408.53, 101109.94, 210360.57, 93204.32, 218801.48, 196604.16]
gdp = [2247.18, 3920.72, 5635.48, 1427.54, 535.39, 5942.79, 174.40, 681.68, 758.01, 1715.87, 839.67, 644.56, 285.80, 233.55, 278.24, 136.17]
print('area_same:', sorted(areas1)==sorted(areas2))
data_sorted1 = sorted(list(zip(areas1, nums)))
data_sorted2 = sorted(list(zip(areas2, population, gdp, mianji)))
areas = [one[0] for one in data_sorted1]
population = [one[1]*1e4 for one in data_sorted2]
nums_av = [one[0][1]/one[1] for one in zip(data_sorted1, population)]
gdp_av = [one[0][2]*1e4/one[1] for one in zip(data_sorted2, population)]
mianji_av = [one[1]/one[0][3] for one in zip(data_sorted2, population)]
print(np.corrcoef(nums_av, gdp_av))
x1, y1, t1 = gdp_av, nums_av, areas
f1 = np.polyfit(x1+[0]*200, y1+[0]*200, 1)
p1 = np.poly1d(f1)
yvals1 = p1([0, 40])
plt.plot([0, 40], yvals1, c='silver', linestyle='--', label='%.6fx'%p1[1], zorder=1)
plt.scatter(x1, y1, marker='D', c='darkred', zorder=2)
for x, y, tag in zip(x1, y1, t1):
plt.annotate(tag, (x+1, y+0.003),
bbox=dict(boxstyle='square', fc='white', alpha=0.4),
)
plt.xlim(0, 40)
plt.ylim(0)
plt.grid(zorder=1)
plt.gca().yaxis.set_major_formatter(FuncFormatter(FormatPercent))
plt.xlabel('人均GDP(万元)')
plt.ylabel('预约结婚率(预约人数/常住人口)')
plt.legend()
title = '北京各区县预约结婚率与人均GDP拟合曲线'
DrawGeneral(title, 1, 'sp2-'+title)
<file_sep>import os
from win32com.client import Dispatch
cwd = os.getcwd()
for file in os.listdir('.'):
data = []
if file.endswith('.xls'):
xlApp = Dispatch("Excel.Application")
xlwb = xlApp.Workbooks.Open(os.path.join(cwd, file))
sheet_data = xlwb.Worksheets(1).UsedRange.Value
line = sheet_data[0][0].split()
for row in sheet_data[2:20]:
line.append(str(row[8]))
data.append(data)
print('\t'.join(line))
<file_sep>import json
import datetime
import urllib.request
def GetApi(url):
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
content = response.read()
data = json.loads(content.decode('gbk'))
return data
url1 = 'http://api.goseek.cn/Tools/holiday?date=%s'
url2 = 'http://www.easybots.cn/api/holiday.php?d=%s'
##d1 = datetime.timedelta(monthes=1)
##date = datetime.datetime(2010,1,1)
##end = datetime.datetime(2020,1,1)
for year in range(2010, 2020):
for month in range(1, 13):
date = '%d%02d'%(year, month)
url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query=%s&co=&resource_id=6018'%date
data = GetApi(url)['data'][0]
if 'holiday' in data:
holidaylist = data['holiday']
ss = ''
if not isinstance(holidaylist, list):
holidaylist = [holidaylist]
for holiday in holidaylist:
days = holiday['list']
for day in days:
ss += day['date'] + ',' + day['status'] + '\n'
print('Holidaies: %s'%date)
print(ss)
else:
print('Skip: %s'%date)
# 1调休 2调班(除了2个特殊项均为周6/7) 0正常上班(只有1项)<file_sep>import os
import csv
import time
import pandas
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import mpl_toolkits.axisartist as axis
alias = {'date': '年月日',
'year': '年',
'mon' : '月',
'mday': '日',
'wday': '星期',
'yday': '月日',
'odd' : '单双日',
'area': '地区',
'hday': '节假日',
}
qixi = ['2011-08-06',
'2011-08-23',
'2012-08-23',
'2013-08-13',
'2014-08-02',
'2015-08-20',
'2016-08-09',
'2017-08-28',
'2018-08-17',
'2019-08-07',
]
os.makedirs('result', exist_ok=1)
#----------------------------------------------------------------------------
# 通用统计
#----------------------------------------------------------------------------
from matplotlib.ticker import FuncFormatter
FormatPercent = FuncFormatter(lambda temp, position: '%.1f%%'%(100 * temp))
def Percent(a, b, ndigits=2):
return ('%d / %d = %.' + str(ndigits) + 'f%%')%(a, b, 100*a/b)
def Preprocess(file, weekday_file):
with open(weekday_file) as f:
reader = csv.reader(f)
weekday_data = {}
for date, holiday, weekday in reader:
date = time.strftime('%Y-%m-%d', time.strptime(date, '%Y/%m/%d'))
weekday_data[date] = int(holiday) # 0: 正常 1: 调休 2: 调班
with open(file) as f:
reader = csv.reader(f)
data = []
for area, date, num in reader:
if num:
res = SplitDate(date)
res['area'] = area
res['cnt'] = int(num)
res['hday'] = ['工作日', '调休', '调班'][weekday_data.get(date, 0)]
data.append(res)
print('Finsh Preprocess: %s'%len(data))
return data, weekday_data
def SplitDate(date):
res = {}
day = time.strptime(date, '%Y-%m-%d')
res['date'] = date
res['year'] = day[0]
res['mon'] = day[1]
res['mday'] = day[2]
# res['wday'] = day[6] + 1
res['wday'] = '星期%d'%(day[6] + 1)
res['yday'] = time.strftime('%m-%d', day)
# res['odd'] = day[2] % 2
res['odd'] = ['双数', '单数'][day[2] % 2]
return res
def SortAndCut(data, tag, top):
'''top: 0(no sort) -1(sort all)'''
result, tags = Analyse1(data, tag)
if top:
tags_sorted = sorted(zip(tags, result), key=lambda item: item[1], reverse=True)
if top + 1:
tags_sorted = tags_sorted[:top]
tags = [tag for tag, num in tags_sorted]
result = [num for tag, num in tags_sorted]
return result, tags
def DrawGeneral(title='', show=True, savefile=None):
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.tight_layout()
plt.subplots_adjust(top=0.94)
plt.title(title)
if savefile:
plt.savefig('result/'+savefile+'.png')
if show:
plt.show()
plt.clf()
def DrawPlot(data, title='', collects=None, samples=None, show=True, savefile=None):
for res, sample_name in zip(data, samples):
plt.plot(res, label=sample_name)
if len(collects) <= 12 or len(collects) == 31:
rotation = 0
elif len(collects) == 16:
rotation = 45
else:
rotation = 90
plt.xticks(np.arange(len(collects)), collects, rotation=rotation)
if max(data[0]) < 1:
## plt.gca().yaxis.set_major_formatter(FuncFormatter(FormatPercent))
plt.gca().yaxis.set_major_formatter(FormatPercent)
plt.ylim(0)
plt.legend()
plt.grid()
DrawGeneral(title, show, savefile)
def DrawPlotPie(data, title='', collects=None, explode=None, show=True, savefile=None):
data_sorted = sorted(zip(data, collects))
x = [a for a, b in data_sorted]
labels = [b for a, b in data_sorted]
plt.pie(x, explode, labels,
autopct='%.1f%%', # 显示百分比
startangle=90, # 起始角度
# counterclock=False, # 逆时针否
wedgeprops=dict(width=0.6,edgecolor='w'))
DrawGeneral(title, show, savefile)
def DrawPlotBar(data, title='', collects=None, show=True, savefile=None):
plt.bar(collects, data, zorder=2)
if len(collects) <= 12 or len(collects) == 31:
rotation = 0
elif len(collects) == 16:
rotation = 45
else:
rotation = 90
plt.xticks(collects, rotation=rotation)
plt.grid(axis='y', zorder=1)
DrawGeneral(title, show, savefile)
def Analyse1(data, collect, show=False):
title = '各%s结婚预约人数统计'%alias[collect]
collects = set()
for one in data:
collects.add(one[collect])
collects = sorted(list(collects))
samples = [collect]
result = [0]*len(collects)
for one in data:
result[collects.index(one[collect])] += one['cnt']
DrawPlot([result], '%s '%title, collects, samples, show, '单参数-%s'%title)
DrawPlotPie(result, '%s '%title, collects, None, show, '饼图-%s'%title)
DrawPlotBar(result, '%s '%title, collects, show, '柱形图-%s'%title)
data_sorted = sorted(list(zip(result, collects)), reverse=1)
result2 = [num for num, collect in data_sorted]
collects2 = [str(collect) for num, collect in data_sorted] # 将标签str防止当标签为数字格式时无法达到排序效果
DrawPlotBar(result2, '%s '%title, collects2, show, '排序-%s'%title)
return result, collects
def Analyse2(data, collect, sample, show=False):
title = '%s-%s的结婚预约人数统计'%(alias[sample], alias[collect])
collects = set()
samples = set()
for one in data:
collects.add(one[collect])
samples. add(one[sample])
collects = sorted(list(collects))
samples = sorted(list(samples))
result = [[0]*len(collects) for _ in samples]
for one in data:
result[samples.index(one[sample])][collects.index(one[collect])] += one['cnt']
DrawPlot(result, '%s'%title, collects, samples, show, '双参数-%s'%title)
return result, collects, samples
def Exhaustion(data): # 穷举组合方式
# 排除强相关的标签
except_tags = [['mday', 'yday', 'odd'], ['yday', 'mon']]
tags = ['year', 'mon', 'mday', 'wday', 'yday', 'hday', 'odd', 'area']
for tag1 in tags:
Analyse1(data, tag1)
print('Draw: %s'%tag1)
for tag2 in tags:
if tag1 != tag2:
is_related = False
for related in except_tags:
if tag1 in related and tag2 in related:
is_related = True
break
if not is_related:
print('Draw: %s-%s'%(tag1, tag2))
Analyse2(data, tag1, tag2)
#----------------------------------------------------------------------------
# 特殊统计
#----------------------------------------------------------------------------
def Analyse2Top(data, collect, sample, collect_top=0, sample_top=0, show=False): # other=False, reverse=True, separate=False
title = '%s-%s'%(alias[sample], alias[collect])
num1, collects_sorted = SortAndCut(data, collect, collect_top)
num2, samples_sorted = SortAndCut(data, sample, sample_top)
data_top = []
result, collects, samples = Analyse2(data, collect, sample)
for sample_name in samples_sorted:
line = []
for collect_name in collects_sorted:
line.append(result[samples.index(sample_name)][collects.index(collect_name)])
data_top.append(line)
DrawPlot(data_top, 'Top: %s'%title , collects_sorted, samples_sorted, show, savefile='排序-'+title)
return data_top
def Analyse2Ratio(data, collect, sample, show=False):
title = '%s-%s的结婚预约人数占比统计'%(alias[sample], alias[collect])
result, collects, samples = Analyse2(data, collect, sample)
totals, collects = Analyse1(data, collect)
result2 = []
for nums, sample_name in zip(result, samples):
row = []
for num, total in zip(nums, totals):
row.append(num / total)
result2.append(row)
DrawPlot(result2, title, collects, samples, show, savefile='占比-'+title)
return result2, collects, samples
def MaxAndMinDate(data, weekday_data):
'''全时间轴最多和最少'''
# 单一民政局人数最多的一天
area_max_num = 0
area_max_date = []
for day in data:
num = day['cnt']
if num > area_max_num:
area_max_num = num
area_max_date = []
if num == area_max_num:
area_max_date.append([day['area'], day['date']])
# 最多和最少的一天
result, tags = SortAndCut(data, 'date', -1)
max_num = result[0]
min_num = result[-1]
max_date = []
min_date = []
for num, date in zip(result, tags):
if num == max_num:
max_date.append(date)
if num == min_num:
min_date.append(date)
min_date = sorted(min_date)
# 最多的一天等于最少的多少天
equal_cnt = 0
for i, num in enumerate(reversed(result)):
equal_cnt += num
if equal_cnt > max_num:
equal_day = i
break
# 没有人结婚的日子
import datetime
date = datetime.datetime(2011, 1, 1)
oneday = datetime.timedelta(1)
void_date = []
while 1:
str_date = datetime.datetime.strftime(date, '%Y-%m-%d')
# (非调休调班但不是周日 or 调班日) and 该日期不在汇总中
if ((weekday_data.get(str_date, 0) == 0 and date.weekday() + 1 != 7) or weekday_data.get(str_date, 0) == 2) and str_date not in tags:
void_date.append(str_date)
if str_date == '2019-12-31':
break
date += oneday
return [max_num, max_date], [min_num, min_date], [area_max_num, area_max_date], void_date, equal_day
def MarryInHoliday(data, weekday_data):
'''节假日仍然领证的人'''
result2 = []
result, collects, samples = Analyse2(data, 'date', 'area')
for sample_name, row in zip(samples, result):
for collect_name, cell in zip(collects, row):
if weekday_data.get(collect_name, 0) == 1 and cell:
result2.append([sample_name, collect_name, cell])
return result2
def MarryInHolidayPercent(data, weekday_data):
result = MarryInHoliday(data, weekday_data)
cnt_2019 = 0
cnt = 0
for area, date, num in result:
cnt += num
if SplitDate(date)['year'] != 2019:
cnt_2019 += num
cnt_sunday = Analyse1(data, 'wday')[0][-1]
total = sum(Analyse1(data, 'year')[0])
print('修正前:', Percent(cnt_sunday, total, 3))
print('修正1:', Percent(cnt, total, 3))
print('修正2:', Percent(cnt_2019, total, 3))
#----------------------------------------------------------------------------
data, weekday_data = Preprocess('2010-2019.csv', 'holiday.csv')
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
# DONE
# 每年最高值
# 全部最多/最少的单日
# 取消晚婚假(2017-01-01)(https://v.66law.cn/yuyinask/26472.html)
# 开放二胎(2015-10-29)(http://wenda.bendibao.com/life/201956/1259.shtm)
# 每年最受欢迎的日期
# 在节假日仍然结婚的人
# 各地区和全北京的逐年增长率变化(以及后续的将增长率排除计算特殊影响)
# 各区县的逐年占比变化
# 节假日对wday的影响
# 饼图
# 增加排序的柱形图
# 全年的不同日期人数频率分布直方图(排序)
#----------------------------------------------------------------------------
# PASS
# 排除离群点的月份统计
# 节假日对特殊日期的影响(归零)
# 各区县在520 214上的态度
#----------------------------------------------------------------------------
#----------------------------------------------------------------------------
# TODO
# 2013年1月4日 201314 20121212的等
# 全部曲线及拟合(增加稀疏的横坐标)
# 单双日的盒图
# 领证和子女出生日期的相关性
# 二八原则
# 所有日期大排序(折叠滚动条)
# 取消晚婚假对比北京人口曲线
# 出生率和结婚人数关系(2018年2171*0.9%=19.5w, 10w人领证)(https://www.sohu.com/a/258486017_769943)
# 出生月份与领证时间的关系(http://www.chyxx.com/industry/201701/486628.html)
# 星期四的影响
# 原来10-01是最冷清的一天,但是后来不是了
# 百分比纵坐标
# 画图输出数据结果到csv
#----------------------------------------------------------------------------
def General(data):
cnt_qixi = 0
for day in data:
if day['date'] in qixi:
cnt_qixi += day['cnt']
print('in_qixi:', cnt_qixi)
data2 = []
for day in data:
if day['year'] < 2019:
data2.append(day)
nums, ydays = Analyse1(data2, 'yday')
data2_sorted = sorted(list(zip(nums, ydays)))
print('min_yday_before_2019:', len(data2_sorted), data2_sorted[:5])
nums, areas = Analyse1(data, 'area')
data_sorted = sorted(list(zip(nums, areas)), reverse=1)
print('total:', sum(nums), sum(nums)/365/10)
print('max_area:', data_sorted[0])
min_areas = []
cnt = 0
for num, area in reversed(data_sorted):
if cnt < data_sorted[0][0]:
cnt += num
min_areas.append(area)
if not cnt < data_sorted[0][0]:
cnt -= num
min_areas.pop()
break
print('equal_min_areas:', cnt, len(min_areas), '、'.join(reversed(min_areas)))
General(data)
Analyse1(data, 'area', 1)
Analyse2Ratio(data, 'year', 'area', 1)
Analyse2Ratio(data, 'year', 'odd', 1)
Analyse2Ratio(data, 'year', 'wday', 1)
def Analyse2RatioSorted(result2, collects, samples):
saturday = result2[5]
result3 = []
for line in result2:
line_sorted = sorted(list(zip(saturday, line)))
line2 = [one for sat, one in line_sorted]
result3.append(line2)
collects_sorted = sorted(list(zip(saturday, collects)))
collects2 = [one for sat, one in collects_sorted]
title = '%s-%s的结婚预约人数占比统计'%(alias['wday'], alias['area'])
DrawPlot(result3, title, collects2, samples, True, savefile='sp-'+title)
result2, collects, samples = Analyse2Ratio(data, 'area', 'wday', 1) # 本身也会画一张图
Analyse2RatioSorted(result2, collects, samples)
Exhaustion(data) # 穷举组合方式
def DrawPlotDist(data, collect, title, top1, top2):
nums, collects = Analyse1(data, collect)
data_sorted = sorted(list(zip(nums, collects)), reverse=1)
nums_sorted = [num for num, collect_name in data_sorted]
plt.bar(np.arange(len(nums_sorted)), nums_sorted, width=1, zorder=2)
plt.ylim(-1, 22000)
plt.xlim(-1, len(nums_sorted))
plt.grid(axis='y', zorder=1)
plt.xticks(np.arange(0, 365, 30))
tags = [[(top1-1, nums_sorted[top1-1]), (20, nums_sorted[top1-1]+800), '%d天'%top1],
[(top2-1, nums_sorted[top2-1]), (40, nums_sorted[top2-1]+800), '%d天'%top2]]
for xy, xytext, s in tags:
plt.axvline(xy[0]+0.5, 0, xy[1]/22000, ls='--', c='silver', linewidth=1, zorder=3)
plt.annotate(s, xy,
xytext=xytext,
arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3'),
bbox=dict(boxstyle='square', fc='white', alpha=0.4)
)
DrawGeneral(title, 1, 'sp-'+title)
print('top1/2/3:', nums_sorted[0], nums_sorted[1], nums_sorted[3])
return sum(nums_sorted), sum(nums_sorted[:top1]), sum(nums_sorted[:top2])
total, sum_top1, sum_top2 = DrawPlotDist(data, 'yday', '一年中最受欢迎日期的结婚人数频数分布直方图', 2, 14)
print('Top2:', Percent(sum_top1, total))
print('Top14:', Percent(sum_top2, total))
def MostPopularDate(data, top=30):
'''取中位数排序一年中最受欢迎的结婚日期
取中位数而不是平均数排序,是为了排除诸如201314的特殊年月日日期,和节假日导致0人结婚结婚造成的影响'''
result, collects, samples = Analyse2(data, 'year', 'yday')
result2 = []
for nums, date in zip(result, samples):
half = len(nums) // 2 # 因为所有数据均为奇数(9)个项目, 所以中位数只有一个不需要中间的两个除2
result2.append([sorted(nums)[half], date, nums])
result3 = sorted(result2, reverse=1)
data1 = []
samples = []
for median, date, nums in result3[:top]:
data1.append(median)
samples.append(date)
title = '最受欢迎的日期结婚人数(单日)(中位数)(前%s)'%top
# 曲线图
# DrawPlot([data1], title, samples, ['date'], show=True, savefile='sp-'+title)
# 散点图
plt.scatter(np.arange(len(data1)), data1, marker='*', zorder=2)
plt.xticks(np.arange(len(data1)), samples, rotation=90)
plt.xlim(-1, top)
plt.ylim(0, 2200)
plt.grid(axis='y')
for x, y in enumerate(data1):
plt.axvline(x, 0, y/2200, ls='--', c='silver', linewidth=1, zorder=1)
plt.axhspan(0, 500, alpha=0.3)
plt.axhspan(500, 1375, alpha=0.2)
plt.axhspan(1375, 2200, alpha=0.1)
DrawGeneral(title, 1, 'sp-%s(散点)'%title)
return result3
result1 = MostPopularDate(data, top=40)
def MostPopularDateEveryYear(data):
result, collects, samples = Analyse2(data, 'yday', 'year')
result2 = []
for nums, years in zip(result, samples):
result2.append(sorted(list(zip(nums, collects)), reverse=1))
return result2
def SpecialDateButNotSpecialYday(data, top):
from scipy import stats
result, collects, samples = Analyse2(data, 'year', 'yday')
totals, years = Analyse1(data, 'year')
totals = [one / 20 for one in totals]
result2 = []
for nums, date in zip(result, samples):
nums2 = []
for i, num in enumerate(nums):
# if num: # 排除不可抗力造成的0点
if num:
nums2.append([num / 20, totals[i]])
res = stats.chi2_contingency(nums2)
result2.append([res[1], date, nums])
result3 = sorted(result2)
ps = []
collects = []
colors = []
for p, yday, nums in reversed(result3[:top]):
if p == 0.0:
p = 1e-308
year = years[nums.index(max(nums))]
date = '%s-%s'%(year, yday)
if date in qixi:
colors.append('pink')
else:
colors.append('#1F77B4') # 默认的蓝色
# print(date, p, nums)
ps.append(-np.log(p)/np.log(10)) # 绘制对数柱形图
collects.append(date)
plt.barh(np.arange(len(ps)), ps, color=colors, zorder=2)
plt.xticks(np.arange(0, 250, 50), [1, '10^-50', '10^-100', '10^-150', '10^-200'])
plt.yticks(np.arange(len(ps)), collects)
plt.xlim(0, 240)
plt.ylim(-1, top)
plt.grid(axis='x', zorder=1)
title = '日期在不同年份间结婚人数的卡方检验p-value(前%s)'%top
DrawGeneral(title, 1, 'sp-'+title)
return ps, collects
SpecialDateButNotSpecialYday(data, 20)
##def MostPopularDateEveryYearRatio(data):
## result = MostPopularDateEveryYear(data)
## # for year in result:
## # print(year[:20])
## totals, years = Analyse1(data, 'year')
## result2 = []
## for dates, total in zip(result, totals):
## row = [0]
## for num, date in dates:
## row.append(row[-1] + num / total)
## result2.append(row)
##
## DrawPlot(result2, '123', np.arange(366), years, 1)
##
##MostPopularDateEveryYearRatio(data)
def AllTrail(data, middle, show=False):
trail = [0]
nums, dates = Analyse1(data, 'date')
for num in nums:
trail.append(trail[-1] + num)
## for num, date in zip(nums, dates):
## day = SplitDate(date)
## if day['wday'] != 6 and weekday_data.get(date, 0) == 0:
## trail.append(trail[-1] + num)
print('Fin Accumulation')
x1 = np.arange(middle+1)
x2 = np.arange(middle, len(trail))
y1 = np.array(trail[:middle+1])
y2 = np.array(trail[middle:])
f1 = np.polyfit(x1, y1, 1)
f2 = np.polyfit(x2, y2, 1)
p1 = np.poly1d(f1)
p2 = np.poly1d(f2)
print(p1, p2)
yvals1 = p1(x1)
yvals2 = p2(x2)
plt.plot(x1, y1, zorder=1)
plt.plot(x2, y2, zorder=1)
plt.plot(x1, yvals1, label=str(p1), zorder=1)
plt.plot(x2, yvals2, label=str(p2), zorder=1)
plt.grid()
plt.legend()
dxy = [len(trail)/20, -trail[-1]/10]
events = [['2011-11-01', '开放双独二孩', dxy],
['2013-11-01', '开放单独二孩', dxy],
['2015-12-01', '允许跨区登记', (-5*dxy[0], -0.5*dxy[1])],
['2016-01-01', '全面二孩', (-3*dxy[0], -2*dxy[1])],
['2016-07-01', '周六必须预约', (dxy[0], 1.5*dxy[1])],
['2017-01-01', '取消晚婚假', dxy],
]
events = list(reversed(events))
date2, event, dxy = events.pop()
for i, date in enumerate(dates):
if date > date2:
print(i, date, date2)
xy = (i-1, trail[i-1])
plt.scatter(*xy, c='b', marker='D', zorder=2)
plt.annotate(date2+'\n'+event, xy,
xytext=(xy[0]+dxy[0], xy[1]+dxy[1]),
arrowprops=dict(arrowstyle='-|>', connectionstyle='arc3'),
bbox=dict(boxstyle='square', fc='yellow', alpha=0.4)
)
if len(events):
date2, event, dxy = events.pop()
else:
break
plt.xticks([0, middle, len(trail)-1], [dates[0], dates[middle], dates[-1]])
title = '历史累加预约结婚人数及拟合曲线和拐点'
DrawGeneral(title, show, 'sp-'+title)
return trail, p1[1], p2[1]
trail, k1, k2 = AllTrail(data, 1486, 1) # 2015-12-18
# trail, k1, k2 = AllTrail(data, 1286, 1) # 2015-04-17 排除周六和节假日后的曲线(因为周六必须预约才能办理)
##print(k1, k2) # 148, 380
# 查询百度“结婚 2015年12月 2015年11月”等
max_date, min_date, area_max_date, void_date, equal_day = MaxAndMinDate(data, weekday_data)
print('max_date:', max_date)
print('min_date:', min_date)
print('area_max_date:', area_max_date)
print('void_date:', void_date)
print('equal_day:', equal_day)
# TODO 这个数据可以提一下
# 2013-01-04(5): 90.48% 6498/7182
def MostTopPopularDateEveryYearInBar(data, top):
cmap = cm.Blues_r
result = MostPopularDateEveryYear(data)
year_total, years = Analyse1(data, 'year')
bottom = [0] * len(years)
for rank in range(top):
nums = [year_sorted[rank][0]/total for total, year_sorted in zip(year_total, result)]
plt.bar(np.arange(len(years)), nums, bottom=bottom, color=cmap(rank/top*0.9), zorder=2)
bottom = [base + num for base, num in zip(bottom, nums)]
plt.xticks(np.arange(len(years)), years)
plt.grid(axis='y', zorder=1)
plt.gca().yaxis.set_major_formatter(FormatPercent)
plt.legend(['Top%d'%(i + 1) for i in range(top)])
title = '每年中结婚人数最多的单日的全年占比堆积柱形图(前%s)'%top
DrawGeneral(title, 1, 'sp-'+title)
MostTopPopularDateEveryYearInBar(data, 6)
def DistributionInYear(data):
result, collects, samples = Analyse2(data, 'yday', 'mon') # TODO 此处生成了一张"月-月日"图
result2 = []
for res in result:
result2.append(list(filter(None, res)))
fig = plt.boxplot(result2, sym='x')
for x, box in enumerate(fig['fliers']):
for y in box.get_data()[1]:
date = collects[result[x].index(y)]
plt.annotate(date, (x+1.1, y+700), fontsize=9,
bbox=dict(boxstyle='square', fc='white', alpha=0.4),
)
plt.xticks(np.arange(1, len(samples) + 1), samples)
plt.grid()
plt.ylim(-500, 23000)
title = '各月份不同日期结婚人数盒图统计图(标记离群点)'
DrawGeneral(title, 1, 'sp-'+title)
DistributionInYear(data)
MarryInHolidayPercent(data, weekday_data)
Analyse2Top(data, 'year', 'yday', sample_top=15, show=1)
# SKIP 对横坐标年份按照该年份的曲线总数值之和进行了排序
##Analyse2Top(data, 'year', 'yday', sample_top=10, collect_top=-1, show=1)
#----------------------------------------------------------------------------
##Analyse2(data, 'area', 'year')
##Analyse1(data, 'mon', 1)
##Analyse1(data, 'year', 1)
##Analyse1(data, 'yday', 1)
##
##Analyse2(data, 'year', 'yday', 1)
##Analyse2(data, 'year', 'hday', 1)
##Analyse2(data, 'hday', 'wday', 1)
##Analyse2(data, 'mon', 'mday', 1)
##Analyse2(data, 'year', 'mon', 1)
##
##Analyse2(data, 'area', 'mon')
##Analyse2(data, 'area', 'year')
##Analyse2(data, 'year', 'mon')
##Analyse2(data, 'year', 'odd')
##Analyse2(data, 'year', 'wday')
# 非节假日的最少登记人数日期(月日和年月日)
##Analyse2(data, 'hday', 'wday', 1)
##Analyse2(data, 'hday', 'area', 1)
#----------------------------------------------------------------------------
# SKIP 逐年前13个日期的总占比逐年呈下降的趋势但波动较大不作列出
##result1 = MostPopularDate(data, top=40)
##result2, collects = Analyse1(data, 'year')
##result3 = [0] * len(collects)
##for median, date, nums in result1[:13]: # 前13个日期最多
## res = date
## for num, total in zip(nums, result2):
## res += ' %.2f%%'%(100*num/total)
## print(res)
# SKIP 前后一天的人数也不多
##result, dates = Analyse1(data, 'date')
##for num, date in zip(result, dates):
## if date.startswith('2014-11-1'):
## print(date, num)
# TODO void_date前后一天的结婚人数
# 2014-11-11 9
# 2014-11-13 33
# SKIP 使用卡方检验更有效
##def TopDatesInYday(data):
## dates_sorted = SortAndCut(data, 'date', -1)
## ydays_sorted = SortAndCut(data, 'yday', -1)
## result = []
## for num1, date in zip(*dates_sorted):
## res = SplitDate(date)
## yday1 = res['yday']
## wday1 = res['wday']
## for num2, yday2 in zip(*ydays_sorted):
## if yday2 == yday1:
## result.append('%s(%s): %.2f%% %s/%s'%(date, wday1, 100*num1/num2, num1, num2))
## return result
##
##result = TopDatesInYday(data)
##print('\n'.join(result[:100]))
| c16081714e1005366fcd37cda436f17b3c6177b9 | [
"Python"
] | 5 | Python | znsoooo/MarriageStatistics | d878ce6acd1db40c5c2b1de16bc8d4c124ba96db | 977e1f2d4d5b40d21f6850a44358b8b6d57a58c1 |
refs/heads/main | <file_sep>const fantasyTransfers = {
playerNames: ['<NAME>', '<NAME>', '<NAME>.', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', 'Rodri', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'],
clubs: ['Real Madrid', 'Barcelona', 'Ajax', 'Porto', 'Juventus', 'Inter Milan', 'AC Milan', 'Manchester United', 'Manchester City', 'Chelsea', 'Sporting Lisbon', 'PSV Eindhoven', 'Bayern Munich', 'Paris Saint-Germain', 'Borussia Dortmund', 'Liverpool', 'Tottenham', 'Athltico Madrid', 'Lyon', 'Napoli'],
value: ['15 Million', '20 Million', '30 Million', '40 Million', '50 Million', '60 Million', '70 Million', '80 Million', '90 Million', '100 Million', '110 Million', '120 Million', '130 Million', '140 Million', '150 Million', '160 Million', '170 Million', '180 Million', '190 Million', '200 Million'],
};
const randomTransfer = () => {
let playerNames = Math.floor(Math.random() * fantasyTransfers.playerNames.length);
let clubs = Math.floor(Math.random() * fantasyTransfers.clubs.length);
let value = Math.floor(Math.random() * fantasyTransfers.value.length);
console.log(`${fantasyTransfer.clubs[clubs]} have signed ${fantasyTransfers.playerNames[playerNames]} for a fee of ${fantasyTransfers.value[value]}.`);
};
randomTransfer();
| 3a0ccbd153659ea631ded95d4d011a5b42c9fa41 | [
"JavaScript"
] | 1 | JavaScript | cshoresy78/Mixed-Messages-project-Codeacademy | bfae48f96a72a3eee79f5e91d2be35a9d81245de | f072dc7aaeb6473f013ca17b3215731339364b07 |
refs/heads/main | <repo_name>M1-134-HamzaFaisal/SANAD<file_sep>/admin/includes/add-admin.php
<div class="col-sm-6" >
<div class="card" >
<div class="card-header">
<h6>Add New Admin</h6>
</div>
<div class="card-body">
<form action="" method="POST" >
<?php add_user(); ?>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Name" required >
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="Email" name="email" id="email" class="form-control" placeholder="Email" required >
<small id="helpId" class="text-muted">Email Shoud be unique</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="<PASSWORD>" name="password" id="password" class="form-control" placeholder="Password" required>
</div>
<div class="form-group">
<label for="c-password">Confirm Password</label>
<input type="<PASSWORD>" name="c-password" id="c-password" class="form-control" placeholder="Confirm Password" required>
</div>
<div class="form-group">
<button type="submit" name="add-admin" class="btn btn-primary">Add Now</button>
</div>
</form>
</div>
</div>
</div>
<file_sep>/index.php
<?php require_once "admin/functions/init.php" ?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Sanad</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="assets/css/bootstrap.min.css" >
<!-- Icon -->
<link rel="stylesheet" href="assets/fonts/line-icons.css">
<!-- Slicknav -->
<link rel="stylesheet" href="assets/css/slicknav.css">
<!-- Owl carousel -->
<link rel="stylesheet" href="assets/css/owl.carousel.min.css">
<link rel="stylesheet" href="assets/css/owl.theme.css">
<link rel="stylesheet" href="assets/css/magnific-popup.css">
<link rel="stylesheet" href="assets/css/nivo-lightbox.css">
<!-- Animate -->
<link rel="stylesheet" href="assets/css/animate.css">
<!-- Main Style -->
<link rel="stylesheet" href="assets/css/main.css">
<!-- Responsive Style -->
<link rel="stylesheet" href="assets/css/responsive.css">
</head>
<body>
<!-- Header Area wrapper Starts -->
<header id="header-wrap">
<!-- Navbar Start -->
<nav class="navbar navbar-expand-md bg-inverse fixed-top scrolling-navbar">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<a href="index.php" class="navbar-brand"><img src="assets/img/sanadlogo.PNG" style="width: 85px;" alt="logo"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<i class="lni-menu"></i>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto w-100 justify-content-end clearfix">
<li class="nav-item active">
<a class="nav-link" href="#hero-area">
Home
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#feature">
About
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#services">
Services
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#team">
Guests
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#testimonial">
Testimonial
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#contact">
Contact
</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Navbar End -->
<!-- Hero Area Start -->
<div id="hero-area" class="hero-area-bg">
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="contents text-center">
<h2 class="head-title wow fadeInUp"> Raise Your Hand To The <br> Right Place</h2>
<div>
<?php successMsg();
add_guest();
?>
</div>
<div class="header-button wow fadeInUp" data-wow-delay="0.3s">
<a data-toggle="modal" href="#regModal" class="btn btn-common">Register Now</a>
</div>
</div>
<div class="img-thumb text-center wow fadeInUp" data-wow-delay="0.6s">
<img class="img-fluid" src="assets/img/hero-2.png" alt="">
</div>
</div>
</div>
</div>
</div>
<!-- Hero Area End -->
</header>
<!-- Header Area wrapper End -->
<!-- Feature Section Start -->
<div id="feature">
<div class="container-fluid">
<div class="row">
<div class="col-lg-6 col-md-12 col-sm-12">
<div class="text-wrapper">
<div>
<h2 class="title-hl wow fadeInLeft" data-wow-delay="0.3s">We are helping to grow <br> your needs.</h2>
<p class="mb-4">Sanad's vision is to live in an enlightened, open society that accepts difference and invests in its young generations.</p>
<a href="#" class="btn btn-common">ESNED</a>
</div>
</div>
</div>
<div class="col-lg-6 col-md-12 col-sm-12 padding-none feature-bg">
<div class="feature-thumb">
<div class="feature-item wow fadeInDown" data-wow-duration="1000ms" data-wow-delay="300ms">
<div class="icon">
<i class="lni-microphone"></i>
</div>
<div class="feature-content">
<h3>What we do</h3>
<p>Enhancing social capital by enhancing social cohesion, increasing trust, cooperation and partnerships between individuals and institutions</p>
</div>
</div>
<div class="feature-item wow fadeInDown" data-wow-duration="1000ms" data-wow-delay="500ms">
<div class="icon">
<i class="lni-users"></i>
</div>
<div class="feature-content">
<h3>Meet our team</h3>
<p> Empowering local communities. It is important to build a network of interdependent relationships, to strengthen and strengthen partnerships, solidarity cooperation and social unity (while respecting and appreciating differences as a factor of enrichment). </p>
</div>
</div>
<div class="feature-item wow fadeInDown" data-wow-duration="1000ms" data-wow-delay="700ms">
<div class="icon">
<i class="lni-medall-alt"></i>
</div>
<div class="feature-content">
<h3>Our Creation</h3>
<p>Contributing to and benefiting from the development of a just and inclusive society, while enjoying a luxury of living (the well-being of the individual is those aspects necessary to meet his needs, and also the ability to achieve his goals, prosperity and his sense of self-satisfaction).</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Feature Section End -->
<!-- Services Section Start -->
<section id="services" class="section-padding bg-gray">
<div class="container">
<div class="section-header text-center">
<h2 class="section-title wow fadeInDown" data-wow-delay="0.3s">Our Services</h2>
<p>A desire to help and empower others between community The existence of racial discrimination and inequality in the infrastructure, difficulties in forming a family and building a house, unemployment, patriarchal society and the lack of cultural and social facilities, all of this leads to frustration, decrease and weakening the self-confidence of individuals, which may result in a social environment of high risk for young people, with the possibility of a high level of disorder Behavior and increased violence, especially among young males. <br> began to grow in 2020.</p>
</div>
<div class="row">
<!-- Services item -->
<div class="col-md-6 col-lg-4 col-xs-12">
<div class="services-item wow fadeInRight" data-wow-delay="0.3s">
<div class="icon">
<i class="lni-pencil"></i>
</div>
<div class="services-content">
<h3><a href="#"> YOUTH Support </a></h3>
<p>
It is often overlooked that the potential energy, enthusiasm and positive potential of youth is a vital resource for society....
</p>
</div>
</div>
</div>
<!-- Services item -->
<div class="col-md-6 col-lg-4 col-xs-12">
<div class="services-item wow fadeInRight" data-wow-delay="0.6s">
<div class="icon">
<i class="lni-heart"></i>
</div>
<div class="services-content">
<h3><a href="#"> Community needs</a></h3>
<p>Establishing a local statement base to measure the quality of life of young people in the Triangle area, through which individuals, civil society institutions (movements and associations), as well as local institutions and decision-makers, are informed about the needs of the community....</p>
</div>
</div>
</div>
<!-- Services item -->
<div class="col-md-6 col-lg-4 col-xs-12">
<div class="services-item wow fadeInRight" data-wow-delay="0.9s">
<div class="icon">
<i class="lni-cog"></i>
</div>
<div class="services-content">
<h3><a href="#">organizational structure</a></h3>
<p>Supporting its organizational structure, providing it with an organizational framework, providing advice and improving the local public space to be a factor in social, cultural and economic prosperity....</p>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Services Section End -->
<!-- Start Video promo Section -->
<section class="video-promo section-padding">
<div class="overlay"></div>
<div class="container">
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="video-promo-content text-center wow fadeInUp" data-wow-delay="0.3s">
<a href="https://www.youtube.com/watch?v=HiNJcpNquzc" class="video-popup"><i class="lni-film-play"></i></a>
<h2 class="mt-3 wow zoomIn" data-wow-duration="1000ms" data-wow-delay="100ms">Watch Video</h2>
</div>
</div>
</div>
</div>
</section>
<!-- End Video Promo Section -->
<!-- Team Section Start -->
<section id="team" class="section-padding text-center">
<div class="container">
<div class="section-header text-center">
<h2 class="section-title wow fadeInDown" data-wow-delay="0.3s">Meet our Guests</h2>
<p>A desire to Develop of human resources and social resources and support for youth initiatives. <br> began to grow in 2020.</p>
</div>
<div class="row">
<?php
$guest_query = " SELECT * FROM guests ";
$execute_guest = query($guest_query);
confirm($execute_guest);
while ($row = fetch_array($execute_guest)) {
$g_name = $row['u_name'];
$g_image = $row['u_image'];
$g_url = $row['u_url'];
$g_notes = $row['u_notes']; ?>
<div class=" col-md-6">
<!-- Team Item Starts -->
<div class="team-item text-center wow fadeInRight" data-wow-delay="0.3s">
<div class="team-img">
<img class="img-fluid d-block w-100" src="assets/img/guests/<?php echo $g_image ?>" alt="">
<div class="team-overlay">
<div class="overlay-social-icon text-left p-3">
<div class="name">
<h3> <?php echo $g_name; ?> </h3>
</div><!-- /.name -->
<div class="notes mt-3">
<h5 class="text-dark mb-1">Notes</h5>
<p class="text-dark">
<?php echo $g_notes; ?>
</p>
</div><!-- /.notes -->
<div class="btn-box mt-2">
<a href="#" class="btn btn-common">Supprt</a>
<a href="<?php echo $g_url; ?> " class="btn btn-common video-popup">Watch Video</a>
<a href="#" class="btn btn-common">Support video</a>
</div><!-- /.btn-box -->
</div>
</div>
</div>
<div class="info-text">
<h3><a href="#"> <?php echo $g_name; ?> </a></h3>
</div>
</div>
<!-- Team Item Ends -->
</div>
<?php
} ?>
</div>
</div>
</section>
<!-- Team Section End -->
<!-- Testimonial Section Start -->
<section id="testimonial" class="testimonial section-padding">
<div class="overlay"></div>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-7 col-md-12 col-sm-12 col-xs-12">
<div id="testimonials" class="owl-carousel wow fadeInUp" data-wow-delay="1.2s">
<div class="item">
<div class="testimonial-item">
<div class="img-thumb">
<img src="assets/img/testimonial/img1.jpg" alt="">
</div>
<div class="info">
<h2><a href="#"><NAME></a></h2>
<h3><a href="#">Capricon co.</a></h3>
</div>
<div class="content">
<p class="description">A practical and stable platform for youth groups who wish to volunteer and support to develop the local community </p>
</div>
</div>
</div>
<div class="item">
<div class="testimonial-item">
<div class="img-thumb">
<img src="assets/img/testimonial/img2.jpg" alt="">
</div>
<div class="info">
<h2><a href="#"> Moudhi</a></h2>
<h3><a href="#"> عندي مفاجأه حقكم ليي يومكم مادري شنو حدي خايف </a></h3>
</div>
<div class="content">
<p class="description">ليس عندي محتوى لاضيفه </p>
</div>
</div>
</div>
<div class="item">
<div class="testimonial-item">
<div class="img-thumb">
<img src="assets/img/testimonial/img3.jpg" alt="">
</div>
<div class="info">
<h2><a href="#">Alwaleed </a></h2>
<h3><a href="#">kuwait codes co.</a></h3>
</div>
<div class="content">
<p class="description">يوسف سوو سكريين شيير وتحله الحين </p>
</div>
</div>
</div>
<div class="item">
<div class="testimonial-item">
<div class="img-thumb">
<img src="assets/img/testimonial/img4.png" alt="">
</div>
<div class="info">
<h2><a href="#">Nancy </a></h2>
<h3><a href="#">JAVAAA SCRIIIPT</a></h3>
</div>
<div class="content">
<p class="description">راح اناديك من يوم ورايح جووزيف </p>
</div>
</div>
</div>
<div class="item">
<div class="testimonial-item">
<div class="img-thumb">
<img src="assets/img/testimonial/img5.png" alt="">
</div>
<div class="info">
<h2><a href="#">obooy</a></h2>
<h3><a href="#">Angry</a></h3>
</div>
<div class="content">
<p class="description">Ha sweeet el database </p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Testimonial Section End -->
<!-- Contact Section Start -->
<section id="contact" class="section-padding">
<div class="container">
<div class="row contact-form-area wow fadeInUp" data-wow-delay="0.4s">
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="contact-block">
<form id="contactForm">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" required data-error="Please enter your name">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" placeholder="Email" id="email" class="form-control" name="email" required data-error="Please enter your email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input type="text" placeholder="Subject" id="msg_subject" class="form-control" required data-error="Please enter your subject">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" id="message" placeholder="Your Message" rows="5" data-error="Write your message" required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="submit-button">
<button class="btn btn-common" id="form-submit" type="submit">Send Message</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="col-md-6 col-lg-6 col-sm-12">
<div class="contact-right-area wow fadeIn">
<div class="contact-title">
<h1>We're a friendly bunch..</h1>
<p>Enhancing human capital by encouraging quality learning that affects the lives of the individual and society, as well as effective employment in the workplace.</p>
</div>
<h2>Dont Contact us Contact them</h2>
<div class="contact-right">
<div class="single-contact">
<div class="contact-icon">
<i class="lni-map-marker"></i>
</div>
<p>ADDRESS:Mubarek Al-Abdullah Block : mo shghlik street 317 Buliding : 2</p>
</div>
<div class="single-contact">
<div class="contact-icon">
<i class="lni-envelope"></i>
</div>
<p><a href="#">Email: <EMAIL></a></p>
</div>
<div class="single-contact">
<div class="contact-icon">
<i class="lni-phone-handset"></i>
</div>
<p><a href="#">Phone: +965 55816553</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Contact Section End -->
<!-- Copyright Section Start -->
<div class="copyright">
<div class="container">
<div class="row">
<div class="col-lg-4 col-md-3 col-xs-12">
<div class="footer-logo">
<img src="assets/img/sanadlogo.PNG" style="width: 100px;;" alt="logo">
</div>
</div>
<div class="col-lg-4 col-md-4 col-xs-12">
<div class="social-icon text-center">
<a class="facebook" href="#"><i class="lni-facebook-filled"></i></a>
<a class="twitter" href="#"><i class="lni-twitter-filled"></i></a>
<a class="instagram" href="#"><i class="lni-instagram-filled"></i></a>
<a class="linkedin" href="#"><i class="lni-linkedin-filled"></i></a>
</div>
</div>
<div class="col-lg-4 col-md-5 col-xs-12">
<p class="float-right">Designed and Developed by <a href="https://afflam.netlify.app" rel="nofollow">Aflam</a></p>
</div>
</div>
</div>
</div>
<!-- Copyright Section End -->
<!-- Go to Top Link -->
<a href="#" class="back-to-top">
<i class="lni-arrow-up"></i>
</a>
<!-- Preloader -->
<div id="preloader">
<div class="loader" id="loader-1"></div>
</div>
<!-- End Preloader -->
<!-- ======= register modal ======= -->
<div class="modal fade" id="regModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header border-bottom-0">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-title text-center">
<h4>Register</h4>
</div>
<div class="d-flex flex-column text-center">
<form method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name"placeholder="Your Full Name" required>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="post_image" id="customFile" required>
<label class="custom-file-label text-left" for="customFile">Choose Image</label>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="url" id="url" placeholder="Video URL" required>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Add Notes..." name="notes" id="notes" rows="3" required></textarea>
</div>
<button type="submit" name="add-guest" class="btn btn-danger btn-block btn-round">Login</button>
</form>
</div>
</div>
<div class="modal-footer d-flex justify-content-center">
<div class="signup-section">Become a part of <span style="color: #ae2727;"> Aflam </span> </div>
</div>
</div>
</div>
<!-- ======= register modal end ======= -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="assets/js/jquery-min.js"></script>
<script src="assets/js/popper.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/owl.carousel.min.js"></script>
<script src="assets/js/jquery.mixitup.js"></script>
<script src="assets/js/wow.js"></script>
<script src="assets/js/jquery.nav.js"></script>
<script src="assets/js/scrolling-nav.js"></script>
<script src="assets/js/jquery.easing.min.js"></script>
<script src="assets/js/jquery.counterup.min.js"></script>
<script src="assets/js/nivo-lightbox.js"></script>
<script src="assets/js/jquery.magnific-popup.min.js"></script>
<script src="assets/js/waypoints.min.js"></script>
<script src="assets/js/jquery.slicknav.js"></script>
<script src="assets/js/main.js"></script>
<script src="assets/js/form-validator.min.js"></script>
<script src="assets/js/contact-form-script.min.js"></script>
</body>
</html>
<file_sep>/admin/includes/view-all-admins.php
<div class="col-sm-12" >
<div class="d-flex justify-content-end mb-2"><a href="users.php?source=add-admin" class="btn btn-primary float-right">Add
Admin</a></div>
<div class="card" >
<div class="card-header">
<h6>All Admins</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Option</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$query = 'SELECT * FROM users';
$select_users = query($query);
$srn = 0;
while ($row = fetch_array($select_users)) {
$u_id = $row['user_id'];
$srn++; ?>
<th scope="row"><?php echo $srn; ?></th>
<td> <?php echo $row['u_name']; ?> </td>
<td> <?php echo $row['u_email']; ?> </td>
<td class="text-center" >
<a class=" mb-1 btn text-warning" href="users.php?source=edit-admin&edit=<?php echo $u_id; ?>"
role="button"><i class="fa fa-edit"></i>
</a>
<a onclick="return confirm('Are you sure to remove this categories ?')"
class=" mb-1 btn text-danger" href="users.php?delete=<?php echo $u_id; ?>"
role="button"> <i class="fa fa-trash"></i>
</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php u_delete(); ?>
</div>
</div>
</div>
</div>
<file_sep>/admin/includes/edit-admin.php
<div class="col-sm-6" >
<div class="card" >
<div class="card-header">
<h6>Edit Admin</h6>
</div>
<div class="card-body">
<?php
if (isset($_GET['edit'])) {
$user_id = $_GET['edit'];
}
$sql = " SELECT * FROM users WHERE user_id = '$user_id' ";
$execute = query($sql);
while ($row = fetch_array($execute)) {
$u_name = $row['u_name'];
$u_email = $row['u_email'];
}
?>
<form action="" method="POST" >
<?php update_admin(); ?>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" value= "<?php echo $u_name; ?>" id="name" class="form-control" placeholder="Name" required >
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="Email" name="email" value="<?php echo $u_email; ?>" id="email" class="form-control" placeholder="Email" required >
<small id="helpId" class="text-muted">Email Shoud be unique</small>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="<PASSWORD>" name="password" id="password" class="form-control" placeholder="<PASSWORD>" >
</div>
<!-- <div class="form-group">
<label for="c-password">Confirm Password</label>
<input type="password" name="c-password" id="c-password" class="form-control" placeholder="Confirm Password" required>
</div> -->
<div class="form-group">
<button type="submit" name="update-admin" class="btn btn-primary">Update Now</button>
</div>
</form>
</div>
</div>
</div>
<file_sep>/admin/guests.php
<?php require_once 'includes/admin-header.php' ?>
<?php// confirm_login(); ?>
<?php
$page = "post";
?>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<!-- Sidebar -->
<?php require_once 'includes/admin-sidebar.php' ?>
<!-- End of Sidebar -->
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<?php require_once 'includes/admin-topbar.php' ?>
<!-- End of Topbar -->
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<div class="d-sm-flex align-items-center mb-4">
<h1 class="h3 mb-0 text-gray-800">Guests </h1>
</div>
<div>
<div>
<?php successMsg(); ?>
</div>
</div>
<!-- Content Row -->
<div class="row justify-content-center">
<?php
if (isset($_GET['source'])) {
$source = $_GET['source'];
} else {
$source = '';
}
switch ($source) {
case 75:
echo 'nice 75';
break;
default:
include 'includes/view-all-guests.php';
break;
}
?>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<?php require_once 'includes/admin-footer.php' ?>
<file_sep>/admin/functions/functions.php
<?php
//************* Some helper function *********/
// for redirecting page
function Redirect_to($location)
{
header("Location:{$location}");
exit;
}
// Display Messages through sessions
function errorMsg()
{
if (isset($_SESSION['error'])) {
$Output = "<div class='alert alert-danger alert-dismissible fade show '>";
$Output .= htmlentities($_SESSION['error']);
$Output .= "<button type='button'class='close' data-dismiss='alert' aria-label='Close'>";
$Output .= "<span aria-hidden='true'>×</span>";
$Output .= '</div>';
echo $Output;
unset($_SESSION['error']);
}
}
function successMsg()
{
if (isset($_SESSION['success'])) {
$Output = "<div class='alert alert-success alert-dismissible fade show '>";
$Output .= htmlentities($_SESSION['success']);
$Output .= "<button type='button'class='close' data-dismiss='alert' aria-label='Close'>";
$Output .= "<span aria-hidden='true'>×</span>";
$Output .= '</div>';
echo $Output;
unset($_SESSION['success']);
}
}
// validation errors in form
// we can alao use delimitter so that we dont have to worry anout .= things :) means we can use html code
function validation_errors($error_message)
{
$error_message = <<<DELIMITER
<div class="alert alert-danger alert-dismissible " role="alert">
<strong> WARNING:!</strong> $error_message
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
DELIMITER;
return $error_message;
}
// check if emqil is already existed
function email_Exist($email)
{
$sql = " SELECT * FROM users WHERE u_email = '$email' ";
$result = query($sql);
confirm($result);
if (row_count($result) > 0) {
return true;
} else {
return false;
}
}
// *************** Add guest ***************** ///
// add post into database
function add_guest()
{
if (isset($_POST['add-guest'])) {
$name = escape($_POST['name']);
$url = escape($_POST['url']);
$notes = escape($_POST['notes']);
// For image feature
$image_name = $_FILES['post_image']['name']; // file name
$image_tmp_name = $_FILES['post_image']['tmp_name'];
$image_size = $_FILES['post_image']['size']; // file size
$image_ext = explode('.', $image_name); // we get two parts here first name and second extention
$image_actual_ext = strtolower(end($image_ext));
$allowed_files = ['jpg', 'jpeg', 'png'];
$errors = [];
if (empty($name) || empty($url) || empty($notes)) {
$errors[] = 'all fields are required';
}
if (!in_array($image_actual_ext, $allowed_files)) {
$errors[] = 'Only jpg and png file can be upload';
} else {
$image_new_name = uniqid('', true) . '.' . $image_actual_ext;
}
if (!empty($errors)) {
foreach ($errors as $error) {
echo validation_errors($error);
}
} else {
$sql = " INSERT INTO guests(u_name,u_image,u_url, u_notes) ";
$sql .= " VALUES('$name', '$image_new_name' ,'$url', '$notes')";
$executeSql = query($sql);
confirm($executeSql);
if ($executeSql) {
move_uploaded_file($image_tmp_name, "assets/img/guests/$image_new_name");
$_SESSION['success'] = 'You has been Added successfully';
Redirect_to('index.php');
}
}
}
}
// delete post
function guest_delete()
{
if (isset($_GET['delete'])) {
$g_delete_id = $_GET['delete'];
// delete image from upload folder when deleting record from pur DB.
$deleteImage = " SELECT * FROM guests WHERE u_id = '$g_delete_id' ";
$execute = query($deleteImage);
$row = fetch_array($execute);
$image1 = $row['u_image'];
unlink("../assets/img/guests/$image1");
$sql = " DELETE FROM guests WHERE u_id = '$g_delete_id' ";
$execute = query($sql);
confirm($execute);
if ($execute) {
$_SESSION['success'] = 'guest has been deleted successfully';
Redirect_to('guests.php');
}
}
}
// login admin and user
$login_errors = [];
function user_login()
{
global $login_errors;
if (isset($_POST['login'])) {
$userEmail = escape($_POST['email']);
$userPassword = escape($_POST['password']);
$sql = " SELECT * FROM users WHERE u_email = '$userEmail' ";
$result = query($sql);
if ($row = fetch_array($result)) {
$dbPassword = $row['u_password'];
$pwdCheck = password_verify($userPassword, $dbPassword);
$db_u_id = $row['user_id'];
$db_u_email = $row['u_email'];
$db_u_name = $row['u_name'];
// end of while loop
if ($pwdCheck == true) {
$_SESSION['uId'] = $db_u_id;
$_SESSION['uName'] = $db_u_name;
$_SESSION['success'] = "Welcome Back! {$_SESSION['uName']} ";
Redirect_to('index.php');
} else {
$login_errors['p'] = 'Invalid Password';
}
} else {
$login_errors['u'] = 'Invalid Username';
} // end of else
} // end of if isset(login)
} // end of user login function
// if login
function login()
{
if (isset($_SESSION['uId'])) {
return true;
}
}
// restirction login
function confirm_login()
{
if (!login()) {
Redirect_to('login.php');
}
}
// add user
function add_user()
{
if (isset($_POST['add-admin'])) {
$u_name = escape($_POST['name']);
$u_email = escape($_POST['email']);
$u_password = escape($_POST['password']);
$u_c_password= escape($_POST['c-password']);
$errors = [];
if (empty($u_name) || empty($u_email) || empty($u_password) || empty($u_c_password)) {
$errors[] = 'all fields are required';
}
if ($u_password !== $u_c_password) {
$errors[] = 'password do not match';
}
if (email_Exist($u_email)) {
$errors[] = 'Sorry email is already existed';
}
if (!empty($errors)) {
foreach ($errors as $error) {
echo validation_errors($error);
}
} else {
$hashedPassword = password_hash($u_password, PASSWORD_DEFAULT);
$sql = 'INSERT INTO users(u_name, u_email, u_password) ';
$sql .= "VALUES('$u_name' , '$u_email' , '$hashedPassword')";
$executeSql = query($sql);
confirm($executeSql);
if ($executeSql) {
$_SESSION['success'] = 'Admin has been Added successfully';
Redirect_to('users.php');
}
}
}
}
// user delete
function u_delete()
{
if (isset($_GET['delete'])) {
$user_delete_id = $_GET['delete'];
$sql = " DELETE FROM users WHERE user_id = '$user_delete_id' ";
$execute = query($sql);
confirm($execute);
if ($execute) {
$_SESSION['success'] = 'User has been deleted successfully';
Redirect_to('users.php');
}
}
}
// update user
function update_admin()
{
if (isset($_POST['update-admin'])) {
$user_id = $_GET['edit'];
$u_name = escape($_POST['name']);
$u_email = escape($_POST['email']);
$u_pass = escape($_POST['password']);
$sql_u_mail = " SELECT * FROM users WHERE u_email = '$u_email' AND user_id != '$user_id' ";
$result_mail = query($sql_u_mail);
$errors = [];
if (empty($u_name) || empty($u_email)) {
$errors[] = 'user field and email fields cant be empty';
}
if (empty($u_pass)) {
$errors[] = 'password fields cant be empty';
}
if (row_count($result_mail) > 0) {
$errors[] = 'Email already existed';
}
if (!empty($u_pass)) {
$sql_user = " SELECT u_password FROM users WHERE user_id = '$user_id' ";
$result_user = query($sql_user);
confirm($result_user);
$row = fetch_array($result_user);
$db_u_password = $row['u_password'];
if ($db_u_password != $u_pass) {
$hashed_pass = password_hash($u_<PASSWORD>, PASSWORD_DEFAULT);
}
if (!empty($errors)) {
foreach ($errors as $error) {
echo validation_errors($error);
}
} else {
$sql = " UPDATE users SET u_name = '$u_name' , u_password = <PASSWORD>' , u_email = '$u_email' ";
$sql .= " WHERE user_id = $user_id ";
$executeSql = query($sql);
confirm($executeSql);
if ($executeSql) {
$_SESSION['success'] = 'user has been updated successfully';
Redirect_to('users.php');
}
}
}
}
}
<file_sep>/admin/includes/view-all-guests.php
<div class="col-sm-12">
<div class="card">
<div class="card-header align-items-center">
<div class="card-card-title font-weight-bold "> All Guests</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Image</th>
<th>Option</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$query = 'SELECT * FROM guests';
$select_posts = query($query);
$srn = 0;
while ($row = fetch_array($select_posts)) {
$p_id = $row['u_id'];
$p_name = $row['u_name'];
$p_image = $row['u_image'];
$p_notes = $row['u_notes'];
$srn++; ?>
<th class="align-middle" scope="row"><?php echo $srn; ?></th>
<td class="align-middle"> <?php echo $p_name; ?> </td>
<td class="align-middle"> <img src="../assets/img/guests/<?php echo $p_image; ?> "
style="width: 100px; height: auto;" alt=""> </td>
<td class="align-middle text-center">
<a onclick="return confirm('Are you sure to remove this guest?')"
class=" mb-1 btn text-danger" href="guests.php?delete=<?php echo $p_id; ?>" role="button"> <i
class="fa fa-trash "></i>
</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php guest_delete(); ?>
</div>
</div>
</div>
</div>
<file_sep>/admin/includes/edit-post.php
<div class="col-sm-12">
<?php
$post_id_from_url = '';
if (isset($_GET['edit'])) {
$post_id_from_url = $_GET['edit'];
$query = "SELECT * FROM posts WHERE p_id = '$post_id_from_url' ";
$select_posts = query($query);
while ($row = fetch_array($select_posts)) {
$post_id = $row['p_id'];
$post_slug = $row['p_slug'];
$post_date = $row['p_date'];
$post_title = $row['p_title'];
$post_con = $row['p_des'];
$post_con2 = $row['p_des_2'];
$image1 = $row['p_img'];
$image2 = $row['p_img_2'];
} // end of while
} // end of if iiset
?>
<div class="card">
<div class="card-header">
<h6 class="admin_main_page_title">Update Post </h6>
</div>
<div class="card-body">
<?php update_post(); ?>
<form method="POST" action="" enctype="multipart/form-data">
<div class="form-group">
<label for="post_title">Post Title</label>
<input type="text" name="post_title" id="post_title" class="form-control" value="<?php echo $post_title; ?>" placeholder="" aria-describedby="helpId">
</div>
<div class="form-group">
<label for="post_url">Post Url</label>
<input type="text" name="post_url" id="post_url" class="form-control" value="<?php echo $post_slug; ?>" placeholder="" aria-describedby="helpId">
</div>
<script>
const input = document.querySelector('#post_title');
input.addEventListener('keyup', updateValue);
function updateValue(e) {
document.getElementById("post_url").value = convertToSlug(e.target.value);
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '-')
.replace(/[^\w-]+/g, '');
}
</script>
<span class="d-block my-1"> Default Feature Image </span>
<img src="../assets/img/blog/<?php echo $image1; ?> " style="width: 90px; height: 70px;" alt="">
<div class="custom-file-container" data-upload-id="myUniqueUploadId">
<label>Upload File
<a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">×</a></label>
<label class="custom-file-container__custom-file">
<input type="file" name="post_image" class="custom-file-container__custom-file__custom-file-input" accept="*"
aria-label="Choose File" />
<input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
<span class="custom-file-container__custom-file__custom-file-control"></span>
</label>
<div class="custom-file-container__image-preview"></div>
</div>
<div class="form-group">
<label for="post_content">Post Content</label>
<textarea name="post_content" id="body" cols="30" rows="10"><?php echo $post_con; ?></textarea><!-- /# -->
</div>
<span class="d-block my-1"> Old Link Image </span>
<img src="../assets/img/blog/<?php echo $image2; ?> " style="width: 90px; height: 70px;" alt="">
<div class="form-group mt-3">
<label for="post_img_2">Link Image as Button</label>
<input type="file" name="post_image_2" id="post_img_2" class="form-control" aria-describedby="helpId">
<small> This image will be link </small>
</div>
<div class="form-group">
<label for="post_content_2">Post Content 2</label>
<textarea name="post_content_2" id="body2" cols="30" rows="10"><?php echo $post_con2; ?></textarea>
</div>
<div id="editor"></div>
<div class="form-group">
<button name="update-post" type="submit" class="btn btn-primary" btn-lg">
<i class="fa fa-floppy-o" aria-hidden="true"></i> Update Now
</button>
</div>
</form>
</div>
</div>
</div>
<file_sep>/admin/includes/add-post.php
<div class="col-sm-11">
<div class="card">
<div class="card-header">
<div class="card-card-title font-weight-bold "> Add Post</div>
</div>
<div class="card-body">
<?php add_post(); ?>
<form method="POST" action="" enctype="multipart/form-data">
<div class="form-group">
<label for="post_title">Post Title</label>
<input type="text" name="post_title" id="post_title" class="form-control" value="" placeholder=""
aria-describedby="helpId">
</div>
<div class="form-group">
<label for="post_url">Post Url</label>
<input type="text" name="post_url" id="post_url" class="form-control" value="" placeholder="" aria-describedby="helpId"
readonly>
</div>
<script>
const input = document.querySelector('#post_title');
input.addEventListener('keyup', updateValue);
function updateValue(e) {
document.getElementById("post_url").value = convertToSlug(e.target.value);
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '-')
.replace(/[^\w-]+/g, '');
}
</script>
<div class="custom-file-container" data-upload-id="myUniqueUploadId">
<label>Upload File
<a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">×</a></label>
<label class="custom-file-container__custom-file">
<input type="file" name="post_image" class="custom-file-container__custom-file__custom-file-input" accept="*"
aria-label="Choose File" />
<input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
<span class="custom-file-container__custom-file__custom-file-control"></span>
</label>
<div class="custom-file-container__image-preview"></div>
</div>
<div class="form-group">
<label for="post_content">Post Content</label>
<textarea name="post_content" id="body" cols="30" rows="10"></textarea><!-- /# -->
</div>
<div id="editor"></div>
<div class="form-group mt-3">
<label for="post_img_2">Link Image as Button</label>
<input type="file" name="post_image_2" id="post_img_2" class="form-control" aria-describedby="helpId">
<small> This image will be link </small>
</div>
<div class="form-group">
<label for="post_content_2">Post Content</label>
<textarea name="post_content_2" id="body2" cols="30" rows="10"></textarea>
</div>
<div id="editor"></div>
<div class="form-group">
<button name="add-post" type="submit" class="btn btn-primary" btn-lg">Add Now</button>
</div>
</form>
</div>
</div>
</div>
<file_sep>/README.md
# SANAD
Final project
<file_sep>/admin/includes/admin-sidebar.php
<ul class="navbar-nav bg-gradient-danger sidebar sidebar-dark accordion" id="accordionSidebar">
<!-- Sidebar - Brand -->
<a class="sidebar-brand d-flex align-items-center " href="index.php">
<div class="sidebar-brand-icon rotate-n-15">
<i class="fas fa-laugh-wink"></i>
</div>
<div class="sidebar-brand-text mx-3">Aflam Admin<sup></sup></div>
</a>
<!-- Divider -->
<hr class="sidebar-divider my-0">
<!-- Nav Item - Dashboard -->
<li class="nav-item
<?php if ($page == "index") {
echo "active";
} ?>
">
<a class="nav-link" href="index.php">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span></a>
</li>
<!-- Divider -->
<hr class="sidebar-divider">
<!-- Heading -->
<div class="sidebar-heading">
Shop
</div>
<!-- Nav Item - Utilities Collapse Menu -->
<li class="nav-item
<?php if ($page == "post") {
echo "active";
} ?>
">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseUtilities" aria-expanded="true"
aria-controls="collapseUtilities">
<i class="fas fa-cube"></i>
<span>Guests</span>
</a>
<div id="collapseUtilities" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Posts Actions:</h6>
<a class="collapse-item" href="guests.php">View All Guests</a>
</div>
</div>
</li>
<hr class="sidebar-divider">
<!-- Divider -->
<hr class="sidebar-divider">
<!-- Heading -->
<div class="sidebar-heading">
Admin
</div>
<!-- Nav Item - Pages Collapse Menu -->
<li class="nav-item
<?php if ($page == "admin") {
echo "active";
} ?>
">
<a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapsePages" aria-expanded="true"
aria-controls="collapsePages">
<i class="fas fa-user "></i>
<span>Admin</span>
</a>
<div id="collapsePages" class="collapse" aria-labelledby="headingPages" data-parent="#accordionSidebar">
<div class="bg-white py-2 collapse-inner rounded">
<h6 class="collapse-header">Admin Actions:</h6>
<a class="collapse-item" href="users.php">View All Admins</a>
<a class="collapse-item" href="users.php?source=add-admin">Add New Admin</a>
<!-- <a class="collapse-item" href="admin-profile.php">Profile</a> -->
<a class="collapse-item" href="logout.php">Logout</a>
</div>
</div>
</li>
<!-- Nav Item - Charts -->
<!-- <li class="nav-item">
<a class="nav-link" href="charts.html">
<i class="fas fa-fw fa-chart-area"></i>
<span>Shop</span></a>
</li> -->
<!-- Divider -->
<hr class="sidebar-divider d-none d-md-block">
<!-- Sidebar Toggler (Sidebar) -->
<div class="text-center d-none d-md-inline">
<button class="rounded-circle border-0" id="sidebarToggle"></button>
</div>
</ul>
<file_sep>/admin/includes/admin-header.php
<?php require_once 'functions/init.php' ?>
<?php
confirm_login();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>SANAD</title>
<!-- Custom fonts for this template-->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.1/css/all.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/trix/1.2.0/trix.css">
<link rel="stylesheet" href="css/file-upload-with-preview.min.css">
<!-- Custom styles for this template-->
<link href="css/sb-admin-2.css?v=<?php echo time(); ?>" rel="stylesheet">
</head>
<file_sep>/admin/index.php
<?php require_once 'includes/admin-header.php' ?>
<?php
$page = "index";
?>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<!-- Sidebar -->
<?php require_once 'includes/admin-sidebar.php' ?>
<!-- End of Sidebar -->
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
<!-- Main Content -->
<div id="content">
<!-- Topbar -->
<?php require_once 'includes/admin-topbar.php' ?>
<!-- End of Topbar -->
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<div class="d-sm-flex align-items-center mb-4">
<h1 class="h3 mb-0 text-gray-800">Dashboard</h1>
</div>
<div>
<?php successMsg(); ?>
</div>
<!-- Content Row -->
<div class="row">
<?php
$sql_t_p = " SELECT * FROM guests ";
$result_t_p = query($sql_t_p);
$t_p = row_count($result_t_p);
?>
<!-- Earnings (Monthly) Card Example -->
<!-- Earnings (Monthly) Card Example -->
<div class="col-xl-6 col-md-6 mb-4">
<div class="card border-left-success shadow h-100 py-2">
<div class="card-body">
<div class="row no-gutters align-items-center">
<div class="col mr-2">
<div class="text-xs font-weight-bold text-success text-uppercase mb-1"><h6>Total Guests</h6></div>
<div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $t_p; ?></div>
</div>
<div class="col-auto">
<i class="fas fa-user fa-2x text-gray-300"></i>
</div>
</div>
</div>
</div>
</div>
<!-- Earnings (Monthly) Card Example -->
<!-- Pending Requests Card Example -->
</div>
<!-- Content Row -->
<div class="row">
<!-- Area Chart -->
<!-- Pie Chart -->
</div>
<!-- Content Row -->
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<?php require_once 'includes/admin-footer.php' ?>
<file_sep>/admin/logout.php
<?php include 'functions/init.php' ?>
<?php confirm_login(); ?>
<?php
session_unset();
session_destroy();
Redirect_to("login.php");
?>
<file_sep>/admin/functions/db.php
<?php
// defining databas in constants
defined('DB_HOST') ? null : define('DB_HOST', 'localhost');
defined('DB_USER') ? null : define('DB_USER', 'root');
defined('DB_PASS') ? null : define('DB_PASS', '');
defined('DB_NAME') ? null : define('DB_NAME', 'aflam_db');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME); // db connection
// Check connection
if (mysqli_connect_errno()) {
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
exit();
}
// helper functions for database queries
function escape($string)
{
global $con;
return mysqli_real_escape_string($con, $string);
}
// execute query
function query($query)
{
global $con;
return mysqli_query($con, $query);
}
// check if error in query
function confirm($result)
{
global $con;
if (!$result) {
die('QUERY FAILED' . mysqli_error($con));
}
}
// row count of record
function row_count($result)
{
return mysqli_num_rows($result);
}
function fetch_array($result)
{
global $con;
return mysqli_fetch_array($result);
}
?>
| 08720041a92b1afb06e4b93ad3b7c7a9eaa056b1 | [
"Markdown",
"PHP"
] | 15 | PHP | M1-134-HamzaFaisal/SANAD | 7dbe6964595a190f10f3f3b4f1286fb3e565127b | 3868be98c74cd595a389b1a01652dc4c4bd2c12b |
refs/heads/main | <repo_name>tbonesteaks/FoliumFixArray<file_sep>/root.py
import os
import time
import datetime
from dateutil.parser import parse
import shutil
import requests
import wget
import pandas as pd
import numpy as np
import folium
from folium import plugins
##Function to download csv if newer version exists.
def download(url: str, dest_folder: str, fname: str):
if not os.path.exists(dest_folder):
os.makedirs(dest_folder) # create folder if it does not exist
file_path = os.path.join(dest_folder, fname)
if os.path.exists(file_path):
ftime = time.ctime(os.path.getctime(file_path))
print(ftime)
else:
ftime = "January 1, 1990"
print(ftime)
r = requests.get(url, stream=True)
if r.ok:
url_date = r.headers['Date']
print(url_date)
##parse those dates
datef = parse(ftime)
print(datef.date())
dateurl = parse(url_date)
print(dateurl.date())
if dateurl.date() < datef.date() or dateurl.date() == datef.date() :
print("Using existing csv --> No need to download up to date existing file.")
else:
if os.path.exists(file_path):
print("Moving old Version of CSV to .old")
destination = fname + ".old"
dest_path = os.path.join(dest_folder, destination)
shutil.move(os.path.abspath(file_path), os.path.abspath(dest_path))
print("File moved successfully.")
print("saving to", os.path.abspath(file_path))
##Downloading the file with wget
wget.download(url, out=file_path)
##End download function
##Let's map some crime data...
## Start by setting variables for folder and file
folder = 'data'
file = 'crime.csv'
## Call download function with filename and folder vars
download("https://www.denvergov.org/media/gis/DataCatalog/crime/csv/crime.csv", dest_folder=folder, fname=file ,)
##When that all works, let's set file_path as a global variable (because above it is a function variable) and load the csv into a pandas dataframe
file_path = os.path.join(folder, file)
crime = pd.read_csv(file_path)
print(crime)
##When everything works, you just saw a dataframe pop out on the command line
##The stdout shows how many rows we have and the columns too
##First make 3 empty arrays for coords, next we'll use shape to get the array size value into a variable
coords = []
ccoords = []
tcoords = []
length = crime.shape[0]
print("Length of array: " + str(length) + " rows to pull coords from.")
##Python just told us how many rows we need to pull the coordinates from, and we have an empty array to append to. Let's START that LOOP.
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if crime['GEO_LAT'].values[a] > 15 :
coords.append([crime['GEO_LAT'].values[a],crime['GEO_LON'].values[a]])
##IF the coordinates are good, then we need to test for crime or traffic and append accordingly
if crime['IS_CRIME'].values[a] > 0:
ccoords.append([crime['GEO_LAT'].values[a],crime['GEO_LON'].values[a]])
else:
tcoords.append([crime['GEO_LAT'].values[a],crime['GEO_LON'].values[a]])
##Now let's see our new arrays - usually leave these next three lines commented out, they populate over a million coords to stdout
#print(coords)
#print(ccoords)
#print(tcoords)
##Create three maps from a map center point, add_child to the map, via HeatMap Plugin, and dump the array of coordinates
##You'll need a path to save the file, and then export the file to that path
mapcenter = [39.739433,-104.888853]
cmap = folium.Map(mapcenter,zoom_start=11)
cmap.add_child(plugins.HeatMap(coords, radius=25))
cmapsave = os.path.join(folder , "mapout.html")
cmap.save(outfile=cmapsave)
ccmap = folium.Map(mapcenter,zoom_start=11)
ccmap.add_child(plugins.HeatMap(ccoords, radius=25))
ccmapsave = os.path.join(folder , "cmapout.html")
ccmap.save(outfile=ccmapsave)
tsmap = folium.Map(mapcenter,zoom_start=11)
tsmap.add_child(plugins.HeatMap(tcoords, radius=25))
tsmap
tsmapsave = os.path.join(folder ,"tmapout.html")
tsmap.save(outfile=tsmapsave)
## Delete those array variables to recover the ram
del cmap
del ccmap
del tsmap
del coords
del ccoords
del tcoords
##set new empty arrays for the first annual pull
coords = []
ccoords = []
tcoords = []
##we need to make a new dataframe from crime, with only 2021 values
c21 = crime[crime['REPORTED_DATE'].str.contains(r'(?!$)2021(?!$)')]
print(c21)
length = c21.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if c21['GEO_LAT'].values[a] > 15 :
coords.append([c21['GEO_LAT'].values[a],c21['GEO_LON'].values[a]])
##IF the coordinates are good, then we need to test for crime or traffic and append accordingly
if c21['IS_CRIME'].values[a] > 0:
ccoords.append([c21['GEO_LAT'].values[a],c21['GEO_LON'].values[a]])
else:
tcoords.append([c21['GEO_LAT'].values[a],c21['GEO_LON'].values[a]])
cmap = folium.Map(mapcenter,zoom_start=11)
cmap.add_child(plugins.HeatMap(coords, radius=7))
cmapsave = os.path.join(folder , "mapout21.html")
cmap.save(outfile=cmapsave)
ccmap = folium.Map(mapcenter,zoom_start=11)
ccmap.add_child(plugins.HeatMap(ccoords, radius=7))
ccmapsave = os.path.join(folder , "cmapout21.html")
ccmap.save(outfile=ccmapsave)
tsmap = folium.Map(mapcenter,zoom_start=11)
tsmap.add_child(plugins.HeatMap(tcoords, radius=7))
tsmap
tsmapsave = os.path.join(folder ,"tmapout21.html")
tsmap.save(outfile=tsmapsave)
## Delete those array variables to recover the ram
del cmap
del ccmap
del tsmap
del coords
del ccoords
del tcoords
##set new empty arrays for the next annual pull
coords = []
ccoords = []
tcoords = []
##we need to make a new dataframe from crime, with only 2020 values
c20 = crime[crime['REPORTED_DATE'].str.contains(r'(?!$)2020(?!$)')]
print(c20)
length = c20.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if c20['GEO_LAT'].values[a] > 15 :
coords.append([c20['GEO_LAT'].values[a],c20['GEO_LON'].values[a]])
##IF the coordinates are good, then we need to test for crime or traffic and append accordingly
if c20['IS_CRIME'].values[a] > 0:
ccoords.append([c20['GEO_LAT'].values[a],c20['GEO_LON'].values[a]])
else:
tcoords.append([c20['GEO_LAT'].values[a],c20['GEO_LON'].values[a]])
cmap = folium.Map(mapcenter,zoom_start=11)
cmap.add_child(plugins.HeatMap(coords, radius=7))
cmapsave = os.path.join(folder , "mapout20.html")
cmap.save(outfile=cmapsave)
ccmap = folium.Map(mapcenter,zoom_start=11)
ccmap.add_child(plugins.HeatMap(ccoords, radius=7))
ccmapsave = os.path.join(folder , "cmapout20.html")
ccmap.save(outfile=ccmapsave)
tsmap = folium.Map(mapcenter,zoom_start=11)
tsmap.add_child(plugins.HeatMap(tcoords, radius=7))
tsmap
tsmapsave = os.path.join(folder ,"tmapout20.html")
tsmap.save(outfile=tsmapsave)
## Delete those array variables to recover the ram
del cmap
del ccmap
del tsmap
del coords
del ccoords
del tcoords
##set new empty arrays for the next annual pull
coords = []
ccoords = []
tcoords = []
##we need to make a new dataframe from crime, with only 2019 values
c19 = crime[crime['REPORTED_DATE'].str.contains(r'(?!$)2019(?!$)')]
print(c19)
length = c19.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if c19['GEO_LAT'].values[a] > 15 :
coords.append([c19['GEO_LAT'].values[a],c19['GEO_LON'].values[a]])
##IF the coordinates are good, then we need to test for crime or traffic and append accordingly
if c19['IS_CRIME'].values[a] > 0:
ccoords.append([c19['GEO_LAT'].values[a],c19['GEO_LON'].values[a]])
else:
tcoords.append([c19['GEO_LAT'].values[a],c19['GEO_LON'].values[a]])
cmap = folium.Map(mapcenter,zoom_start=11)
cmap.add_child(plugins.HeatMap(coords, radius=7))
cmapsave = os.path.join(folder , "mapout19.html")
cmap.save(outfile=cmapsave)
ccmap = folium.Map(mapcenter,zoom_start=11)
ccmap.add_child(plugins.HeatMap(ccoords, radius=7))
ccmapsave = os.path.join(folder , "cmapout19.html")
ccmap.save(outfile=ccmapsave)
tsmap = folium.Map(mapcenter,zoom_start=11)
tsmap.add_child(plugins.HeatMap(tcoords, radius=7))
tsmap
tsmapsave = os.path.join(folder ,"tmapout19.html")
tsmap.save(outfile=tsmapsave)
## Delete those array variables to recover the ram
del cmap
del ccmap
del tsmap
del coords
del ccoords
del tcoords
##set new empty arrays for the next annual pull
coords = []
ccoords = []
tcoords = []
##we need to make a new dataframe from crime, with only 2018 values
c18 = crime[crime['REPORTED_DATE'].str.contains(r'(?!$)2018(?!$)')]
print(c18)
length = c18.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if c18['GEO_LAT'].values[a] > 15 :
coords.append([c18['GEO_LAT'].values[a],c18['GEO_LON'].values[a]])
##IF the coordinates are good, then we need to test for crime or traffic and append accordingly
if c18['IS_CRIME'].values[a] > 0:
ccoords.append([c18['GEO_LAT'].values[a],c18['GEO_LON'].values[a]])
else:
tcoords.append([c18['GEO_LAT'].values[a],c18['GEO_LON'].values[a]])
cmap = folium.Map(mapcenter,zoom_start=11)
cmap.add_child(plugins.HeatMap(coords, radius=7))
cmapsave = os.path.join(folder , "mapout18.html")
cmap.save(outfile=cmapsave)
ccmap = folium.Map(mapcenter,zoom_start=11)
ccmap.add_child(plugins.HeatMap(ccoords, radius=7))
ccmapsave = os.path.join(folder , "cmapout18.html")
ccmap.save(outfile=ccmapsave)
tsmap = folium.Map(mapcenter,zoom_start=11)
tsmap.add_child(plugins.HeatMap(tcoords, radius=7))
tsmap
tsmapsave = os.path.join(folder ,"tmapout18.html")
tsmap.save(outfile=tsmapsave)
### Since we don't see bias in the above maps, let's continue
dvcoords = []
dv18coords = []
dv19coords = []
dv20coords = []
dv21coords = []
dv_tot = crime.query("OFFENSE_CODE == 1313 or OFFENSE_CODE == 1315 or OFFENSE_CODE == 5309 or OFFENSE_CODE == 1316 or OFFENSE_CODE == 1006")
print(dv_tot)
length = dv_tot.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv_tot['GEO_LAT'].values[a] > 15 :
dvcoords.append([dv_tot['GEO_LAT'].values[a],dv_tot['GEO_LON'].values[a]])
dv_map = folium.Map(mapcenter,zoom_start=11)
dv_map.add_child(plugins.HeatMap(dvcoords, radius=12))
dv_mapsave = os.path.join(folder , "dvmaptot.html")
dv_map.save(outfile=dv_mapsave)
dv18 = dv_tot[dv_tot['REPORTED_DATE'].str.contains(r'(?!$)2018(?!$)')]
print(dv18)
length = dv18.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv18['GEO_LAT'].values[a] > 15 :
dv18coords.append([dv18['GEO_LAT'].values[a],dv18['GEO_LON'].values[a]])
dv_18map = folium.Map(mapcenter,zoom_start=11)
dv_18map.add_child(plugins.HeatMap(dv18coords, radius=12))
dv_18mapsave = os.path.join(folder , "dvmap18.html")
dv_18map.save(outfile=dv_18mapsave)
dv19 = dv_tot[dv_tot['REPORTED_DATE'].str.contains(r'(?!$)2019(?!$)')]
print(dv19)
length = dv19.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv19['GEO_LAT'].values[a] > 15 :
dv19coords.append([dv19['GEO_LAT'].values[a],dv19['GEO_LON'].values[a]])
dv_19map = folium.Map(mapcenter,zoom_start=11)
dv_19map.add_child(plugins.HeatMap(dv19coords, radius=12))
dv_19mapsave = os.path.join(folder , "dvmap19.html")
dv_19map.save(outfile=dv_19mapsave)
dv20 = dv_tot[dv_tot['REPORTED_DATE'].str.contains(r'(?!$)2020(?!$)')]
print(dv20)
length = dv20.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv20['GEO_LAT'].values[a] > 15 :
dv20coords.append([dv20['GEO_LAT'].values[a],dv20['GEO_LON'].values[a]])
dv_20map = folium.Map(mapcenter,zoom_start=11)
dv_20map.add_child(plugins.HeatMap(dv20coords, radius=12))
dv_20mapsave = os.path.join(folder , "dvmap20.html")
dv_20map.save(outfile=dv_20mapsave)
dv21 = dv_tot[dv_tot['REPORTED_DATE'].str.contains(r'(?!$)2021(?!$)')]
print(dv21)
length = dv21.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv21['GEO_LAT'].values[a] > 15 :
dv21coords.append([dv21['GEO_LAT'].values[a],dv21['GEO_LON'].values[a]])
dv_21map = folium.Map(mapcenter,zoom_start=11)
dv_21map.add_child(plugins.HeatMap(dv21coords, radius=12))
dv_21mapsave = os.path.join(folder , "dvmap21.html")
dv_21map.save(outfile=dv_21mapsave)
## can you see where activist's bias against men regarding Domestic Violence originates?
## is the incidence as evenly spread as traffic tickets in the maps?
## let's see what the maps look like by offense code...
dv1006coords = []
dv1313coords = []
dv1315coords = []
dv1316coords = []
dv5309coords = []
dv1006 = crime.query("OFFENSE_CODE == 1006")
print(dv1006)
length = dv1006.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv1006['GEO_LAT'].values[a] > 15 :
dv1006coords.append([dv1006['GEO_LAT'].values[a],dv1006['GEO_LON'].values[a]])
dv_1006map = folium.Map(mapcenter,zoom_start=11)
dv_1006map.add_child(plugins.HeatMap(dv1006coords, radius=12))
dv_1006mapsave = os.path.join(folder , "dvmap1006.html")
dv_1006map.save(outfile=dv_1006mapsave)
dv1313 = crime.query("OFFENSE_CODE == 1313")
print(dv1313)
length = dv1313.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv1313['GEO_LAT'].values[a] > 15 :
dv1313coords.append([dv1313['GEO_LAT'].values[a],dv1313['GEO_LON'].values[a]])
dv_1313map = folium.Map(mapcenter,zoom_start=11)
dv_1313map.add_child(plugins.HeatMap(dv1313coords, radius=12))
dv_1313mapsave = os.path.join(folder , "dvmap1313.html")
dv_1313map.save(outfile=dv_1313mapsave)
dv1315 = crime.query("OFFENSE_CODE == 1315")
print(dv1315)
length = dv1315.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv1315['GEO_LAT'].values[a] > 15 :
dv1315coords.append([dv1315['GEO_LAT'].values[a],dv1315['GEO_LON'].values[a]])
dv_1315map = folium.Map(mapcenter,zoom_start=11)
dv_1315map.add_child(plugins.HeatMap(dv1315coords, radius=12))
dv_1315mapsave = os.path.join(folder , "dvmap1315.html")
dv_1315map.save(outfile=dv_1315mapsave)
dv1316 = crime.query("OFFENSE_CODE == 1316")
print(dv1316)
length = dv1316.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv1316['GEO_LAT'].values[a] > 15 :
dv1316coords.append([dv1316['GEO_LAT'].values[a],dv1316['GEO_LON'].values[a]])
dv_1316map = folium.Map(mapcenter,zoom_start=11)
dv_1316map.add_child(plugins.HeatMap(dv1316coords, radius=12))
dv_1316mapsave = os.path.join(folder , "dvmap1316.html")
dv_1316map.save(outfile=dv_1316mapsave)
dv5309 = crime.query("OFFENSE_CODE == 5309")
print(dv5309)
length = dv5309.shape[0]
for a in range(length):
##we need a test to eliminate NANs (not a number) so we append the array if the Latitude value is north of Mexico
if dv5309['GEO_LAT'].values[a] > 15 :
dv5309coords.append([dv5309['GEO_LAT'].values[a],dv5309['GEO_LON'].values[a]])
dv_5309map = folium.Map(mapcenter,zoom_start=11)
dv_5309map.add_child(plugins.HeatMap(dv5309coords, radius=12))
dv_5309mapsave = os.path.join(folder , "dvmap5309.html")
dv_5309map.save(outfile=dv_5309mapsave)
print("You've just placed over 2.2 million points into heat maps in under 3 minutes. Good job.")<file_sep>/tester.py
import os
import time
import datetime
from dateutil.parser import parse
import pandas as pd
import numpy as np
##This file is set up for you to play with regex pulls from a dataframe off of the CSV root.py uses.
##IF you already downloaded the CSV from the city of Denver, this part is setting everything else up for you.
##IF you changed the place where your CSV file resides, please amend the variables...
folder = 'data'
file = 'crime.csv'
file_path = os.path.join(folder, file)
crime = pd.read_csv(file_path)
print(crime)
##If you see the dataframe populate when your run this the first time, everything worked.
## Uncomment the rows below to start searching the data...
print("Let's look at the Dataframe and run your query")
## Example 1: Search reported date for a year
#c20 = crime[crime['REPORTED_DATE'].str.contains(r'(?!$)2020(?!$)')]
## Example 2: Search offense codes for DV associated incidents
c20 = crime.query("OFFENSE_CODE == 1313 or OFFENSE_CODE == 1315 or OFFENSE_CODE == 5309")
print(c20)
length = c20.shape[0]
| 920d9b6809f0002c9927188d87d116568f165f31 | [
"Python"
] | 2 | Python | tbonesteaks/FoliumFixArray | eed05376882ab6ab295c9df4f847ea58974ca91d | 1b7897ea340edcccb6b391ddd1f933799985e62f |
refs/heads/master | <repo_name>tamoorshahzadDAM/M6_Persistence<file_sep>/src/model/Adreca.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Table;
/**
*
* @author ALUMNEDAM
*/
@Embeddable
@Table(name = "M6UF2_Adreca")
public class Adreca implements Serializable {
//Columna de calle
@Column(name = "carrer", length = 50, nullable = false)
private String carrer;
//Columna de numero de piso
@Column(name = "numero", length = 20, nullable = false)
private int numero;
//Columna de nombre de poblacaion
@Column(name = "poblacion", length = 50, nullable = false)
private String poblacion;
/**
* Constructor de adreca
* @param carrer
* @param numero
* @param poblacion
*/
public Adreca(String carrer, int numero, String poblacion) {
this.carrer = carrer;
this.numero = numero;
this.poblacion = poblacion;
}
/**
* Constructor
*/
public Adreca() {
}
/**
* Getter de carrer
* @return
*/
public String getCarrer() {
return carrer;
}
/**
* Setter de carrer
* @param carrer
*/
public void setCarrer(String carrer) {
this.carrer = carrer;
}
/**
* Getter de numero de piso
* @return
*/
public int getNumero() {
return numero;
}
/**
* Setter de numero de piso
* @param numero
*/
public void setNumero(int numero) {
this.numero = numero;
}
/**
* Getter de poblacion
* @return
*/
public String getPoblacion() {
return poblacion;
}
/**
* Setter de poblacion
* @param poblacion
*/
public void setPoblacion(String poblacion) {
this.poblacion = poblacion;
}
/**
* To string para mostrar datos
* @return
*/
@Override
public String toString() {
return "Adreca{" + "carrer=" + carrer + ", numero=" + numero + ", poblacion=" + poblacion + '}';
}
}
<file_sep>/src/model/Asseguradora.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author ALUMNEDAM
*/
@Entity
@NamedQueries({
//Query para mostrar asseguradora
@NamedQuery(name = Asseguradora.CONSULTA, query = "SELECT a FROM Asseguradora a WHERE a.nomasseg=:nombre")})
//Nombre de tabla
@Table(name = "M6UF2_Asseguradora")
public class Asseguradora implements Serializable {
public static final String CONSULTA = "nomAsseg";
private static final long serialVersionUID = 1L;
//Id de asseguradora
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "idAsseguradora", nullable = false)
private Long idAsseg;
//Columna para el nombre de asseguradora
@Column(name = "nomAsseguradora", length = 100, nullable = false, unique = true)
private String nomasseg;
//Columna para nif de asseguradora
@Column(name = "nifAsseguradora")
private String nifAsseg;
//Relacion uno a muchas, uniondo relacion con polissa
@OneToMany(mappedBy = "asseguradora")
private List<Polissa> polissa;
/**
* Constructor
* @param nomasseg
* @param nifAsseg
*/
public Asseguradora(String nomasseg, String nifAsseg) {
this.nomasseg = nomasseg;
this.nifAsseg = nifAsseg;
}
/**
* constructor
*/
public Asseguradora() {
}
/**
* Getter de if asseguradora
* @return
*/
public Long getIdAsseg() {
return idAsseg;
}
/**
* Setter de id asseguradora
* @param idAsseg
*/
public void setIdAsseg(Long idAsseg) {
this.idAsseg = idAsseg;
}
/**
* Getter de nom asseguradora
* @return
*/
public String getNomasseg() {
return nomasseg;
}
/**
* Stter de nom asseguradora
* @param nomasseg
*/
public void setNomasseg(String nomasseg) {
this.nomasseg = nomasseg;
}
/**
* Getter de nif
* @return
*/
public String getNifAsseg() {
return nifAsseg;
}
/**
* Setter de nif.
* @param nifAsseg
*/
public void setNifAsseg(String nifAsseg) {
this.nifAsseg = nifAsseg;
}
/**
* override de hashcode
*
* @return
*/
@Override
public int hashCode() {
int hash = 0;
hash += (idAsseg != null ? idAsseg.hashCode() : 0);
return hash;
}
/**
* Methodo equals
*
* @param object
* @return
*/
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the idAsseg fields are not set
if (!(object instanceof Asseguradora)) {
return false;
}
Asseguradora other = (Asseguradora) object;
if ((this.idAsseg == null && other.idAsseg != null) || (this.idAsseg != null && !this.idAsseg.equals(other.idAsseg))) {
return false;
}
return true;
}
/**
* To string para mostrar datos
* @return
*/
@Override
public String toString() {
return "Asseguradora{" + "idAsseg=" + idAsseg + ", nomasseg=" + nomasseg + ", nifAsseg=" + nifAsseg + '}';
}
}
<file_sep>/src/model/Polissa.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.IndexColumn;
/**
*
* @author ALUMNEDAM
*/
@Entity
@NamedQueries({
@NamedQuery(name = "Cerca_Polissa_Prenedor", query = "SELECT p FROM Polissa p WHERE p.prenedor=:Prenedor"),
@NamedQuery(name = "buscaPerNom", query = "SELECT p FROM Polissa p WHERE p.numPolissa:nombre"),
//@NamedQuery(name = Polissa.Polissa_Vehicle, query = "SELECT p FROM Polissa p WHERE p.vehicle:Vehicle")
//@NamedQuery(name = "Cerca_Polissa_Client", query = "SELECT p FROM Polissa p WHERE p.cliente.idClient:cliente"),
@NamedQuery(name = "Cerca_Polissa_Vehicle", query = "SELECT p FROM Polissa p WHERE p.vehicle.idVehicle=:vehicle")
})
@Table(name = "M6UF2_POLISSA")
public class Polissa implements Serializable {
//public static final String Polissa_Prenedor = "PolissaPrenedor";
//public static final String Polissa_Vehicle = "PolissaVehicle";
//public static final String Cerca_Polissa_Client = "CercaPolissaClient";
private static final long serialVersionUID = 1L;
//Id de polissa
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "idPolissa", unique = true)
private int idPolissa;
//Columna para numero de polissa
@Column(name = "numPolissa", length = 10)
private String numPolissa;
// Columna para prenedor
@Column(name = "prenedor", nullable = false)
@IndexColumn(name = "indexPrenedor")
@Basic(fetch = FetchType.LAZY)
//@ManyToOne(fetch = FetchType.LAZY)
//@ManyToOne
//@JoinColumn(name="propietariPolissa")
private Client prenedor;
//Columna para vehicle, tienes relacion uno a uno
//@Column(name = "vehicle", nullable = false)
//@Basic(fetch = FetchType.LAZY)
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "vehicle")
private Vehicle vehicle;
//Relacion muchos a uno, con idclient
@ManyToOne(cascade=CascadeType.ALL)
@Basic(fetch = FetchType.LAZY)
@JoinColumn(name = "idClient")
private Client cliente;
//Columna para fecha de inicio
@Column(name = "dataInici", nullable = false)
private Date dataInici;
//Columna para fecha final
@Column(name = "dataFi", nullable = false)
private Date dataFi;
//Columna para tipos de polissa, es un boolean
@Column(name = "tipuPolissa", nullable = false)
//@ElementCollection
//@Enumerated(EnumType.STRING)
private boolean tipuPolissa;
//Relacion de muchos a uno con id de asseguradora
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "asseguradoraId")
private Asseguradora asseguradora;
//Columna para prima el costo.
@Column (name = "prima")
private double prima;
/**
* Constructor de polissa
* @param numPolissa
* @param prenedor
* @param vehicle
* @param cliente
* @param dataInici
* @param dataFi
* @param tipuPolissa
* @param asseguradora
* @param prima
*/
public Polissa(String numPolissa, Client prenedor, Vehicle vehicle, Client cliente, Date dataInici, Date dataFi, boolean tipuPolissa, Asseguradora asseguradora, double prima) {
this.numPolissa = numPolissa;
this.prenedor = prenedor;
this.vehicle = vehicle;
this.cliente = cliente;
this.dataInici = dataInici;
this.dataFi = dataFi;
this.tipuPolissa = tipuPolissa;
this.asseguradora = asseguradora;
this.prima = prima;
}
public Client getCliente() {
return cliente;
}
public void setCliente(Client cliente) {
this.cliente = cliente;
}
public Asseguradora getAsseguradora() {
return asseguradora;
}
public void setAsseguradora(Asseguradora asseguradora) {
this.asseguradora = asseguradora;
}
/**
* Constructor vacio
*/
public Polissa() {
}
/**
* Getter de id de polissa
* @return
*/
public int getIdPolissa() {
return idPolissa;
}
/**
* Setter de id de polissa
* @return
*/
public void setIdPolissa(int idPolissa) {
this.idPolissa = idPolissa;
}
/**
* Getter de numero de polissa
* @return
*/
public String getNumPolissa() {
return numPolissa;
}
/**
* Setter de numero de polissa
* @return
*/
public void setNumPolissa(String numPolissa) {
this.numPolissa = numPolissa;
}
/**
* Getter de prenedor de polissa
* @return
*/
public Client getPrenedor() {
return prenedor;
}
/**
* Setter de prenedor de polissa
* @return
*/
public void setPrenedor(Client prenedor) {
this.prenedor = prenedor;
}
/**
* Getter de vehicle
* @return
*/
public Vehicle getVehicle() {
return vehicle;
}
/**
* Setter de vehicle
* @return
*/
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
/**
* Getter de fecha de inicio
* @return
*/
public Date getDataInici() {
return dataInici;
}
/**
* Setter de fecha de inicio
* @return
*/
public void setDataInici(Date dataInici) {
this.dataInici = dataInici;
}
/**
* Getter de fecha de fin
* @return
*/
public Date getDataFi() {
return dataFi;
}
/**
* Setter de fecha de fin
* @return
*/
public void setDataFi(Date dataFi) {
this.dataFi = dataFi;
}
/**
* Getter de tipus de polissa
* @return
*/
public boolean getTipuPolissa() {
return tipuPolissa;
}
/**
* Setter de tipus de polissa
* @return
*/
public void setTipuPolissa(boolean tipuPolissa) {
this.tipuPolissa = tipuPolissa;
}
/**
* Getter de Prima
* @return
*/
public double getPrima() {
return prima;
}
/**
* Setter de Prima
* @return
*/
public void setPrima(double prima) {
this.prima = prima;
}
/**
* override de hashcode
* @return
*/
@Override
public int hashCode() {
int hash = 0;
hash += (numPolissa != null ? numPolissa.hashCode() : 0);
return hash;
}
/**
* Methodo equals
* @param object
* @return
*/
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Polissa)) {
return false;
}
Polissa other = (Polissa) object;
if ((this.numPolissa == null && other.numPolissa != null) || (this.numPolissa != null && !this.numPolissa.equals(other.numPolissa))) {
return false;
}
return true;
}
/**
* To string para mostrar datos
* @return
*/
@Override
public String toString() {
return "Polissa{" + "idPolissa=" + idPolissa + ", numPolissa=" + numPolissa + ", prenedor=" + prenedor + ", vehicle=" + vehicle + ", cliente=" + cliente + ", dataInici=" + dataInici + ", dataFi=" + dataFi + ", tipuPolissa=" + tipuPolissa + ", asseguradora=" + asseguradora + ", prima=" + prima + '}';
}
}
<file_sep>/src/InsertJPA/AsseguradoraJPA.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package InsertJPA;
import controlador.Asseguradora_Controller;
import controlador.Client_Controller;
import model.Adreca;
import model.Asseguradora;
import model.Client;
/**
*
* @author ALUMNEDAM
*/
public class AsseguradoraJPA {
public static void main(String[] args) {
try {
//// --------------Insertar-------------------
// Insertar un cliente
Asseguradora asse = new Asseguradora();
asse.setIdAsseg(Long.MIN_VALUE);
asse.setNifAsseg("123456");
asse.setNomasseg("Mutua");
//------------ INSERTAR -----------------------
Asseguradora_Controller ac = new Asseguradora_Controller();
ac.Insertar(asse);
/// ------------------------------------------
/// ----------- BUSCAR ------------------------
String nom = "Mutua";
Asseguradora a = ac.BuscarPerNom(nom);//PRIMER IDPERSONA
ac.imprimir(a);
//////// --------------- BORRAR ---------------
//Borra por nombre
//String nom = "<NAME>";
//Client c = cc.BuscarPerNom(nom);
//cc.Eliminar(c); //Para borar el cliente
//-------------- Nodificar---------------------
/**
Adreca adrmod = new Adreca();
adrmod.setCarrer("C/Mont ");
adrmod.setNumero(60);
adrmod.setPoblacion("Ripo");
c.setNom("Tamoor");
c.setAdreca(adrmod);
cc.Modificar(c);
*/
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
<file_sep>/src/controlador/Asseguradora_Controller.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controlador;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import model.Asseguradora;
import model.Usuari;
/**
*
* @author ALUMNEDAM
*/
public class Asseguradora_Controller {
/**
* Methodo que por parametros le pasamos un objeto asseguradora y lo
* inserta en base de datos.
* @param asseg
*/
public void Insertar(Asseguradora asseg) {
// Recupera el entity manager
EM_Controller oem = new EM_Controller();
EntityManager em = oem.getEntityManager();
// El persistim a la base de dades
//em.getTransaction().begin();
EntityTransaction etx = em.getTransaction();
System.out.println("begin");
etx.begin();
System.out.println("persist");
em.persist(asseg);
System.out.println("commit");
//em.getTransaction().commit();
etx.commit();
System.out.println("close");
em.close();
}
/**
* Methodo que por parametros le pasamos un objeto asseguradora y lo modifica en
* base de datos, con ayuda de otro methodo de buscar, primero busca y
* luego modifica.
* @param asseg
*/
public void Modificar(Asseguradora asseg) {
// Recupera el entity manager
EM_Controller oem = new EM_Controller();
EntityManager em = oem.getEntityManager();
// El persistim a la base de dades
//em.getTransaction().begin();
EntityTransaction etx = em.getTransaction();
System.out.println("begin");
etx.begin();
System.out.println("merge");
em.merge(asseg);
System.out.println("commit");
//em.getTransaction().commit();
etx.commit();
System.out.println("close");
em.close();
}
/**
* Methodo que por parametros le pasamos un objeto asseguradora y lo
* elimina en base de datos.
* @param asseg
*/
public void Eliminar(Asseguradora asseg) {
// Recupera el entity manager
EM_Controller oem = new EM_Controller();
EntityManager em = oem.getEntityManager();
// El persistim a la base de dades
//em.getTransaction().begin();
EntityTransaction etx = em.getTransaction();
System.out.println("begin");
etx.begin();
System.out.println("remove");
em.remove(em.contains(asseg) ? asseg : em.merge(asseg));
System.out.println("commit");
//em.getTransaction().commit();
etx.commit();
System.out.println("close");
em.close();
}
/**
* Methodo que le paso por parametros un nombre, y lo busca en base de datos
* y devuelve.
* @param nom
* @return
*/
public Asseguradora BuscarPerNom(String nom) {
// Recupera el entity manager
EntityManager em = new EM_Controller().getEntityManager();
System.out.println("Busqueda per nom");
//Query query = em.createNamedQuery("PersonaNom",Persona.class);
Query query = em.createNamedQuery(Asseguradora.CONSULTA,Asseguradora.class);
query.setParameter("nombre", nom);
Asseguradora a = (Asseguradora) query.getSingleResult();
System.out.println("close");
em.close();
return a;
}
/**
* Methodo para imprimir un objeto
* @param a
*/
public void imprimir(Asseguradora a) {
System.out.println(a);
}
/**
* MEthodo que hace consulta en base de datos
*/
public void Consulta() {
// Recupera el entity manager
EntityManager em = new EM_Controller().getEntityManager();
System.out.println("Consulta");
//List<Persona> lista = (List<Persona>) em.createQuery("FROM Persona").getResultList();
Query q = em.createQuery("FROM M6UF2_Asseguradora");
List<Asseguradora> lista = (List<Asseguradora>) q.getResultList();
imprimirLista(lista);
System.out.println("close");
em.close();
}
/**
* Methodo para imprimir una lista
* @param lista
*/
public void imprimirLista(List<Asseguradora> lista) {
System.out.println("Numero d'assegurats= " + lista.size());
for (int i = 0; i < lista.size(); i++) {
System.out.println(lista.get(i));
}
}
}
| 568b93f649ead280abda4ed8ae23eaae5e4a8906 | [
"Java"
] | 5 | Java | tamoorshahzadDAM/M6_Persistence | 77dfc67cc116ba39614427bfcc390159cea6075b | cfc01ac44f783d2d00518f603e7c75c6e9c34ae5 |
refs/heads/master | <repo_name>OyebisiJemil/HandI-thumbnail-service<file_sep>/src/ThumbnailService/Function.cs
using System;
using System.IO;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.Lambda.S3Events;
using Amazon.S3;
using Amazon.S3.Model;
using ImageMagick;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace ThumbnailService
{
public class Function
{
IAmazonS3 S3Client { get; set; }
/// <summary>
/// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
/// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the
/// region the Lambda function is executed in.
/// </summary>
public Function()
{
S3Client = new AmazonS3Client();
}
/// <summary>
/// Constructs an instance with a preconfigured S3 client. This can be used for testing the outside of the Lambda environment.
/// </summary>
/// <param name="s3Client"></param>
public Function(IAmazonS3 s3Client)
{
this.S3Client = s3Client;
}
/// <summary>
/// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used
/// to respond to S3 notifications.
/// </summary>
/// <param name="evnt"></param>
/// <param name="context"></param>
/// <returns></returns>
public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context)
{
var s3Event = evnt.Records?[0].S3;
string thumnailResultBucket = "thumbnail-result-s3-bucket";
if (s3Event == null)
{
return null;
}
try
{
var thumbnailStream =await GenerateThumbnail(s3Event.Bucket.Name, s3Event.Object.Key, context);
var thumbnailKey =await UploadThumbnail(thumnailResultBucket, s3Event.Object.Key, thumbnailStream);
string res = $"Thumbnail saved to s3://{thumnailResultBucket}/{thumbnailKey}";
context.Logger.LogLine(res);
return res;
}
catch (Exception e)
{
context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function.");
context.Logger.LogLine(e.Message);
context.Logger.LogLine(e.StackTrace);
throw;
}
}
private async Task<string> UploadThumbnail(string bucketName,string key, MemoryStream thumbnailImageStream)
{
var index = key.LastIndexOf('/');
var thumbnailKey = "thumbnails/" + (index != -1 ? key.Substring(index + 1) : key);
await this.S3Client.PutObjectAsync(new PutObjectRequest
{
BucketName = bucketName,
Key = thumbnailKey,
InputStream = thumbnailImageStream
});
return thumbnailKey;
}
private async Task<MemoryStream> GenerateThumbnail(string bucketName, string key,ILambdaContext context)
{
MemoryStream resizedImageStream;
using (var response = await this.S3Client.GetObjectAsync(bucketName, key))
{
context.Logger.Log("Magick Image Resize");
try
{
MagickImage magickImage = new MagickImage();
using (MagickImage image = new MagickImage(response.ResponseStream))
{
image.Resize(200, 200);
context.Logger.LogLine($"Image resized");
resizedImageStream = new MemoryStream();
image.Write(resizedImageStream);
resizedImageStream.Position = 0;
return resizedImageStream;
}
}
catch (Exception e)
{
context.Logger.Log(e.Message);
throw;
}
}
}
}
}
<file_sep>/README.md
# HandI-thumbnail-service
A service that converts an image to thumbnail
| 48edd5b66079fe117ef46e5c456af680bb24bde3 | [
"Markdown",
"C#"
] | 2 | C# | OyebisiJemil/HandI-thumbnail-service | c240580e650ead513f1c24a50ed65871908ff5fa | 167729b8a28a9c2f9a124586b925d9778385f086 |
refs/heads/master | <repo_name>soteria-nou/debian-systemd<file_sep>/soteria.sh
#!/bin/sh
[ "`id -u`" = "0" ] && {
echo "Do not run this script as a root user!"
exit 1
}
[ -f /etc/soteria.conf ] && . /etc/soteria.conf
[ -n "$DNS_PARTS" ] || DNS_PARTS="hsr hsn jur jun rtl"
[ -n "$DNSMASQ_HOSTS" ] || DNSMASQ_HOSTS=/usr/share/soteria/hosts
TINYSRV_ARGS=/run/tinysrv/tinysrv.args
DEV=soteria
DNS_HOSTS=/tmp/soteria
PIDOF=`which pidof`
SUDO=`which sudo`
get_pid() {
local _pid
_pid=
[ -n "$2" ] && [ -f "$2" ] && kill -0 `cat "$2"` 2>/dev/null && _pid=`cat "$2"`
[ -z "$_pid" ] && [ -n "$PIDOF" ] && _pid=`$PIDOF "$1"`
echo "$_pid"
}
hup() {
[ -n "$1" ] || return 0
${SUDO:+$SUDO -u dnsmasq} /bin/kill -HUP "$1"
}
dnsmasq_pid() {
get_pid dnsmasq "$DNSMASQ_PIDFILE"
}
tinysrv_pid() {
get_pid tinysrv "$TINYSRV_PIDFILE"
}
remove_file() {
[ -n "$1" ] && [ -f "$1" ] && rm -f "$1"
}
is_running() {
[ -n "$1" ] && return 0
return 1
}
append_hosts() {
[ -n "$1" ] && [ -n "$2" ] || return 0
local _url="${SRC_LIST%/}/$1"
echo "Downloading from URL: $_url ... and appending domains to IP: $2"
wget --no-check-certificate -q -O - "$_url" | sed "s/^/$2\t/" >>$DNS_HOSTS
}
update_hosts() {
[ -n "$DNS_HOSTS" ] || return 1
>$DNS_HOSTS
chgrp soteria $DNS_HOSTS
chmod 640 $DNS_HOSTS
[ -L "$DNSMASQ_HOSTS" ] || {
remove_file "$DNSMASQ_HOSTS"
ln -s "$DNS_HOSTS" "$DNSMASQ_HOSTS"
}
[ -n "$HSN_IP" ] && {
for _i in ads.txt analytics.txt; do
append_hosts "$_i" "$HSN_IP"
done
}
[ -n "$HSR_IP" ] && {
for _i in affiliate.txt enrichments.txt fake.txt widgets.txt; do
append_hosts "$_i" "$HSR_IP"
done
}
}
refresh_hosts() {
update_hosts
PID=`dnsmasq_pid`
is_running "$PID" && hup "$PID"
}
start_tinysrv() {
[ -n "$TINYSRV_PIDFILE" ] || return 1
PID=`tinysrv_pid`
is_running "$PID" || remove_file "$TINYSRV_PIDFILE"
[ -n "$WWW_DIR" ] && {
[ -d "$WWW_DIR" ] || mkdir -p "$WWW_DIR"
}
[ -n "$CRT_DIR" ] && {
[ -d "$CRT_DIR" ] || mkdir -p "$CRT_DIR"
}
ADDR=`ip address show`
for _dns_part in $DNS_PARTS; do
eval IP=\$`echo "$_dns_part" | tr "[a-z]" "[A-Z]"`_IP
[ -n "$IP" ] || continue
echo $ADDR | grep -q "inet $IP" || unset `echo "$_dns_part" | tr "[a-z]" "[A-Z]"`_IP
done
echo "ARGS=-u tinysrv -P \"$TINYSRV_PIDFILE\"\
${HSR_IP:+ -k 443 \"$HSR_IP\" -p 80 \"$HSR_IP\"}\
${HSN_IP:+ -k 443 -R \"$HSN_IP\" -p 80 -R \"$HSN_IP\"}\
${JUR_IP:+ -p 80 -c \"$JUR_IP\"}\
${JUN_IP:+ -p 80 -c -R \"$JUN_IP\"}\
${RTL_IP:+${WWW_DIR:+ -p 80 -S \"$WWW_DIR\" \"$RTL_IP\"${CRT_DIR:+ -p 443 -S \"$WWW_DIR\" -C \"$CRT_DIR\" \"$RTL_IP\"}}}" >"$TINYSRV_ARGS"
}
populate_dns_parts() {
ip link show "$DEV" >/dev/null 2>&1 || return 1
_ips=`ip address show dev "$DEV" | awk '/inet / {split($2, a, /\//); print a[1]}' | tr "\n" " "`
for _dns_part in $DNS_PARTS; do
_ip="${_ips%% *}"
_ips="${_ips#* }"
eval `echo "$_dns_part" | tr "[a-z]" "[A-Z]"`_IP="$_ip"
done
return 0
}
case "$1" in
dnsmasq)
populate_dns_parts
refresh_hosts
;;
tinysrv)
populate_dns_parts
start_tinysrv
;;
*)
echo "Unknown command"
;;
esac
| e9fce458fc300ce5a914cd28176022a5d84e0ddb | [
"Shell"
] | 1 | Shell | soteria-nou/debian-systemd | 307af9106393e346ffdf2651c1a1c7a9c1bb8500 | 874f7cebbdd89a9cf79d8c4652c966045183a2fb |
refs/heads/main | <file_sep>package co.g2academy.bootcamp.ecommerce.orderfulfillment.model;
import co.g2academy.bootcamp.ecommerce.orderfulfillment.entity.Order;
import co.g2academy.bootcamp.ecommerce.orderfulfillment.entity.OrderItem;
import org.junit.Test;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.*;
public class ConverterTest {
private Converter converter = new Converter();
@Test
public void convertWithTrueObject() {
// User
User user = new User();
user.setId(1);
user.setUserName("<EMAIL>");
user.setName("fadlil");
user.setPassword("<PASSWORD>");
// Product
Product product = new Product();
product.setId(1);
product.setProductName("samsung s10 8/128GB");
product.setDescription("the best smartphone ever");
product.setCategory("handphone");
product.setPrice(10_000_000);
product.setStock(10);
product.setUser(user);
// CartItem
CartItem item = new CartItem();
item.setId(1);
item.setProduct(product);
item.setQuantity(1);
item.setPrice(product.getPrice());
// Cart
Cart cart = new Cart();
cart.setId(1);
cart.setUser(user);
List<CartItem> items = new ArrayList<>();
items.add(item);
cart.setItems(items);
cart.setStatus("ACTIVE");
cart.setTransactionDate("15 DEC 2020");
// explicit set for
item.setCart(cart);
// THE CART IS READY, LETS TRY TO TEST THE CONVERTER
// 1. convert the cart to Order
Order actual = converter.convert(cart);
// 2. create the expected order result
// create orderItemExpected
OrderItem orderItemExpected = new OrderItem();
orderItemExpected.setId(null);
orderItemExpected.setProductName("samsung s10 8/128GB");
orderItemExpected.setProductId(1);
orderItemExpected.setQuantity(1);
orderItemExpected.setPrice(10_000_000);
// create Order Expected
Order expected = new Order();
expected.setId(null);
expected.setUserId(1);
expected.setCartId(1);
// order date on order and transaction date on cart is generated different date,
// because maybe the received date is different between order date and transaction date.
expected.setOrderDate(new Date());
expected.setStatus("RECEIVED");
expected.setTotalPrice(orderItemExpected.getPrice() * orderItemExpected.getQuantity());
List<OrderItem> orderItemList = new ArrayList<>();
orderItemList.add(orderItemExpected);
expected.setOrderItems(orderItemList);
// Explicit set
orderItemExpected.setOrder(expected);
// 3. assert all fields
assertEquals(expected.getUserId(), actual.getUserId());
assertEquals(expected.getCartId(), actual.getCartId());
assertEquals(expected.getStatus(), actual.getStatus());
assertEquals(expected.getTotalPrice(), actual.getTotalPrice());
// there is one left not tested yet, orderItem List
// there is no assert to test ArrayList
}
}<file_sep># ecommerce_backend_apps
Ecommerce Restful API with Java Spring Boot
<file_sep>package co.g2academy.bootcamp.ecommerce;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication(scanBasePackages = {"co.g2academy.bootcamp.ecommerce"})
@EnableCaching
public class EcommerceApplication {
public static void main(String[] args) {
SpringApplication.run(EcommerceApplication.class, args);
}
}
<file_sep>package co.g2academy.bootcamp.ecommerce.repository;
import co.g2academy.bootcamp.ecommerce.entity.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserRepository extends CrudRepository<User, Integer> {
User findByUserName(String userName);
List<User> findAll();
}
<file_sep>package co.g2academy.bootcamp.ecommerce.model;
import lombok.Data;
@Data
public class AddToCart {
private Integer productId;
private Integer quantity;
}
<file_sep>package co.g2academy.bootcamp.ecommerce.repository;
import co.g2academy.bootcamp.ecommerce.entity.Cart;
import co.g2academy.bootcamp.ecommerce.entity.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CartRepository extends CrudRepository<Cart, Integer> {
Cart findByUserAndStatus(User user, String status);
Cart findByUserName(String userName);
}
<file_sep>package co.g2academy.bootcamp.ecommerce.service.impl;
import co.g2academy.bootcamp.ecommerce.AppConfig;
import co.g2academy.bootcamp.ecommerce.entity.Cart;
import co.g2academy.bootcamp.ecommerce.entity.CartItem;
import co.g2academy.bootcamp.ecommerce.entity.Product;
import co.g2academy.bootcamp.ecommerce.entity.User;
import co.g2academy.bootcamp.ecommerce.model.AddToCart;
import co.g2academy.bootcamp.ecommerce.repository.CartRepository;
import co.g2academy.bootcamp.ecommerce.repository.ProductRepository;
import co.g2academy.bootcamp.ecommerce.repository.UserRepository;
import co.g2academy.bootcamp.ecommerce.service.ChekoutService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class CheckoutServiceImpl implements ChekoutService {
private static final Logger LOG = LoggerFactory.getLogger(CheckoutServiceImpl.class);
@Autowired
private UserRepository userRepository;
@Autowired
private ProductRepository productRepository;
@Autowired
private CartRepository cartRepository;
@Autowired
private RabbitTemplate rabbitTemplate;
@Override
@Transactional
public String addToCart(String userName, AddToCart addToCart) {
User user = userRepository.findByUserName(userName);
// get checkout data that has status = Active
Cart checkout = cartRepository.findByUserAndStatus(user,"ACTIVE");
if (checkout == null) {
checkout = new Cart();
checkout.setUser(user);
checkout.setStatus("ACTIVE");
List<CartItem> items = new ArrayList<>();
checkout.setItems(items);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
checkout.setTransactionDate(formatter.format(date));
}
Product product = productRepository.findById(addToCart.getProductId()).get();
if (product != null && product.getStock() > 0) {
CartItem item = new CartItem();
item.setCart(checkout);
item.setPrice(product.getPrice());
item.setQuantity(addToCart.getQuantity());
item.setProduct(product);
checkout.getItems().add(item);
} else {
return "SORRY, THE STOCK PRODUCT IS EMPTY";
}
cartRepository.save(checkout);
return "OK";
}
@Override
@Transactional
public void checkout(String userName) {
User user = userRepository.findByUserName(userName);
// get checkout data that has status = Active
Cart checkout = cartRepository.findByUserAndStatus(user,"ACTIVE");
if (checkout != null) {
checkout.setStatus("PROCESSED");
// send status to rabbitmq
LOG.info("sending message to amqp");
rabbitTemplate.convertAndSend(AppConfig.QUEUE_NAME, checkout);
// save to database after changing status
cartRepository.save(checkout);
// EXTRA MILES : REDUCE STOCK ON PRODUCT
// get the product items
List<CartItem> cartItemList = checkout.getItems();
for (int i = 0; i < cartItemList.size(); i++) {
Product product = cartItemList.get(i).getProduct();
Integer quantity = cartItemList.get(i).getQuantity();
product.setStock(product.getStock() - quantity);
productRepository.save(product);
}
}
}
}
<file_sep>spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/java_ecommerce_orderfulfillment
spring.datasource.username=mvadlil
spring.datasource.password=<PASSWORD>
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming.strategy = org.hibernate.cfg.ImprovedNamingStrategy
server.port=8081
<file_sep>package co.g2academy.bootcamp.ecommerce.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
@Data
@Entity
@Table(name = "T_CART_ITEM")
public class CartItem implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Integer id;
@ManyToOne(optional = false)
@JsonIgnore
private Cart cart;
@ManyToOne(optional = false)
private Product product;
@Column(name = "QUANTITY", nullable = false)
private Integer quantity;
@Column(name = "PRICE", nullable = false)
private Integer price;
}
<file_sep>package co.g2academy.bootcamp.ecommerce.model;
import org.junit.Test;
import static org.junit.Assert.*;
public class RegisterValidatorTest {
RegisterValidator validator = new RegisterValidator();
@Test
public void validateWithTrueObject() {
Register register = new Register();
register.setUserName("<EMAIL>");
register.setName("fadlil");
register.setPassword("<PASSWORD>");
register.setConfirmPassword("<PASSWORD>");
boolean actual = validator.validate(register);
assertTrue(actual);
}
@Test
public void validateUserNameAsEmailAddressWithTrueObject() {
Register register = new Register();
register.setUserName("<EMAIL>");
register.setName("fadlil");
register.setPassword("<PASSWORD>");
register.setConfirmPassword("<PASSWORD>");
boolean actual = validator.validateUserNameAsEmailAddress(register);
assertTrue(actual);
}
@Test
public void validatePasswordAndConfirmPasswordIsTheSameWithTrueObject() {
Register register = new Register();
register.setUserName("<EMAIL>");
register.setName("fadlil");
register.setPassword("<PASSWORD>");
register.setConfirmPassword("<PASSWORD>");
boolean actual = validator.validatePasswordAndConfirmPasswordIsTheSame(register);
assertTrue(actual);
}
@Test
public void validateWithFalseObject() {
Register register = new Register();
register.setUserName("<EMAIL>");
register.setName("fadlil");
register.setPassword("<PASSWORD>");
register.setConfirmPassword("<PASSWORD>");
boolean actual = validator.validate(register);
assertFalse(actual);
}
@Test
public void validateUserNameAsEmailAddressWithFalseObject() {
Register register = new Register();
register.setUserName("<EMAIL>");
register.setName("fadlil");
register.setPassword("<PASSWORD>");
register.setConfirmPassword("<PASSWORD>");
boolean actual = validator.validateUserNameAsEmailAddress(register);
assertFalse(actual);
}
@Test
public void validatePasswordAndConfirmPasswordIsTheSameWithFalseObject() {
Register register = new Register();
register.setUserName("<EMAIL>");
register.setName("fadlil");
register.setPassword("<PASSWORD>");
register.setConfirmPassword("<PASSWORD>");
boolean actual = validator.validatePasswordAndConfirmPasswordIsTheSame(register);
assertFalse(actual);
}
}<file_sep>package co.g2academy.bootcamp.ecommerce.filter;
import co.g2academy.bootcamp.ecommerce.model.Login;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Key;
import java.util.Collections;
import java.util.Date;
import static co.g2academy.bootcamp.ecommerce.model.SecurityConstants.EXPIRATION_TIME;
import static co.g2academy.bootcamp.ecommerce.model.SecurityConstants.KEY;
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
public AuthenticationFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
// get login object from request body
// Login login = new ObjectMapper().readValue(request.getInputStream(), Login.class);
Login login = new ObjectMapper().readValue(request.getInputStream(), Login.class);
// create authentication token
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(login.getUserName(), login.getPassword(), Collections.emptyList());
// authenticate using authenticationManager object
return authenticationManager.authenticate(token);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException, ServletException {
Date exp = new Date(System.currentTimeMillis() + EXPIRATION_TIME);
Key key = Keys.hmacShaKeyFor(KEY.getBytes());
User user = (User) authResult.getPrincipal();
Claims claims = Jwts.claims().setSubject(user.getUsername());
// create token
String token = Jwts.builder().setClaims(claims)
.signWith(key, SignatureAlgorithm.HS512)
.setExpiration(exp).compact();
response.setHeader("token", token);
}
}
<file_sep>package co.g2academy.bootcamp.ecommerce.orderfulfillment.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class Cart implements Serializable {
private Integer id;
private User user;
private List<CartItem> items;
private String status;
private String transactionDate;
}
<file_sep>package co.g2academy.bootcamp.ecommerce;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
public class AppConfig {
public static final String QUEUE_NAME = "ecommerceq";
@Bean
public Queue getQueue() {
return new Queue(QUEUE_NAME);
}
@Bean
public Jackson2JsonMessageConverter getMessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public RabbitTemplate getRabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(getMessageConverter());
return rabbitTemplate;
}
@Bean
public BCryptPasswordEncoder getBCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
<file_sep>package co.g2academy.bootcamp.ecommerce.service;
import co.g2academy.bootcamp.ecommerce.entity.Cart;
import co.g2academy.bootcamp.ecommerce.model.AddToCart;
public interface ChekoutService {
public String addToCart(String userName, AddToCart addToCart);
public void checkout(String userName);
}
<file_sep>package co.g2academy.bootcamp.ecommerce.controller;
import co.g2academy.bootcamp.ecommerce.entity.User;
import co.g2academy.bootcamp.ecommerce.model.Register;
import co.g2academy.bootcamp.ecommerce.model.RegisterValidator;
import co.g2academy.bootcamp.ecommerce.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private RegisterValidator registerValidator;
@PostMapping("/register")
public String register(@RequestBody Register newRegister) {
if (registerValidator.validate(newRegister)) {
User checkUser = userRepository.findByUserName(newRegister.getUserName());
if (checkUser == null) {
User newUser = new User();
newUser.setUserName(newRegister.getUserName());
newUser.setName(newRegister.getName());
newUser.setPassword(bCryptPasswordEncoder.encode(newRegister.getPassword()));
userRepository.save(newUser);
return "REGISTRATION SUCCESS!";
}
}
return "REGISTRATION FAILED";
}
}
<file_sep>package co.g2academy.bootcamp.ecommerce.orderfulfillment.model;
import co.g2academy.bootcamp.ecommerce.orderfulfillment.entity.Order;
import co.g2academy.bootcamp.ecommerce.orderfulfillment.entity.OrderItem;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Converter {
public Order convert(Cart checkout) {
Order order = new Order();
order.setUserId(checkout.getUser().getId());
order.setCartId(checkout.getId());
order.setOrderDate(new Date());
order.setStatus("RECEIVED");
List<OrderItem> orderItems = new ArrayList<>();
Integer totalPrice = 0;
for (CartItem item : checkout.getItems()) {
OrderItem orderItem = new OrderItem();
orderItem.setProductName(item.getProduct().getProductName());
orderItem.setProductId(item.getProduct().getId());
orderItem.setQuantity(item.getQuantity());
orderItem.setPrice(item.getPrice());
orderItem.setOrder(order);
totalPrice += item.getPrice() * item.getQuantity();
orderItems.add(orderItem);
}
order.setOrderItems(orderItems);
order.setTotalPrice(totalPrice);
return order;
}
}
<file_sep>package co.g2academy.bootcamp.ecommerce.orderfulfillment.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.io.Serializable;
@Data
public class CartItem implements Serializable {
private Integer id;
private Cart cart;
private Product product;
private Integer quantity;
private Integer price;
}
<file_sep>package co.g2academy.bootcamp.ecommerce.orderfulfillment.repository;
import co.g2academy.bootcamp.ecommerce.orderfulfillment.entity.Order;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface OrderRepository extends CrudRepository<Order, Integer> {
}
<file_sep>package co.g2academy.bootcamp.ecommerce.repository;
import co.g2academy.bootcamp.ecommerce.entity.Product;
import co.g2academy.bootcamp.ecommerce.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class CachedUserRepository {
@Autowired
private UserRepository userRepository;
@Cacheable(value = "findByUsername")
public User findByUserName(String userName) {
User user = userRepository.findByUserName(userName);
if (user != null){
return user;
}
return null;
}
}
<file_sep>package co.g2academy.bootcamp.ecommerce.controller;
import co.g2academy.bootcamp.ecommerce.entity.Product;
import co.g2academy.bootcamp.ecommerce.entity.User;
import co.g2academy.bootcamp.ecommerce.repository.CachedProductRepository;
import co.g2academy.bootcamp.ecommerce.repository.CachedUserRepository;
import co.g2academy.bootcamp.ecommerce.repository.ProductRepository;
import co.g2academy.bootcamp.ecommerce.repository.UserRepository;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.*;
@RestController
@RequestMapping("/api")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private CachedProductRepository cachedProductRepository;
@Autowired
private CachedUserRepository cachedUserRepository;
//======================================================================================================================
// THESE API NEED PRINCIPAL, USER LOGIN IS NEEDED
//======================================================================================================================
@PostMapping("/product")
public String save(@RequestBody Product newProduct, Principal principal) {
newProduct.setUser(userRepository.findByUserName(getUserName(principal)));
productRepository.save(newProduct);
return "PRODUCT UPLOADED";
}
// this API Cache implemented
@GetMapping("/products")
public List<Product> getProducts(Principal principal) {
// Get the productOwner
User productOwner = cachedUserRepository.findByUserName(getUserName(principal));
// find all Product
List<Product> allProduct = cachedProductRepository.findAll();
// create new buffer list to load product user
List<Product> listOfProductUser = new ArrayList<>();
// filter product
for (int i = 0; i < allProduct.size(); i++) {
// filter product get only with userName same as productOwner userName
if (allProduct.get(i).getUser().getUserName().equals(productOwner.getUserName())) {
listOfProductUser.add(allProduct.get(i));
}
}
return listOfProductUser;
}
// this API Cache implemented
@GetMapping("/product/id/{id}")
public Product getProduct(@PathVariable Integer id, Principal principal) {
// Get the productOwner
User productOwner = cachedUserRepository.findByUserName(getUserName(principal));
if (productOwner == null) {
return null;
}
// Search product by findByIdAndUser
Product productUploaded = cachedProductRepository.findByIdAndUser(id, productOwner);
if (productUploaded != null) {
return productUploaded;
}
return null;
}
@PutMapping("/product/{id}")
public String update(@RequestBody Product updateProduct, @PathVariable Integer id ,Principal principal) {
// Get the productOwner
User productOwner = userRepository.findByUserName(getUserName(principal));
if (productOwner == null) {
return "USER NOT FOUND!";
}
// Set updateProduct
Product productUploaded = productRepository.findByIdAndUser(id, productOwner);
if (productUploaded != null) {
productUploaded.setProductName(updateProduct.getProductName());
productUploaded.setCategory(updateProduct.getCategory());
productUploaded.setDescription(updateProduct.getDescription());
productUploaded.setPrice(updateProduct.getPrice());
productUploaded.setStock(updateProduct.getStock());
productRepository.save(productUploaded);
return "PRODUCT HAS BEEN UPDATED!";
}
return "PRODUCT UPDATE FAILED!";
}
@PutMapping("/product/stock/{id}")
public String updateStock(@RequestBody Product updateProduct, @PathVariable Integer id ,Principal principal) {
// Get the productOwner
User productOwner = userRepository.findByUserName(getUserName(principal));
if (productOwner == null) {
return "USER NOT FOUND!";
}
// Set updateProduct
Product productUploaded = productRepository.findByIdAndUser(id, productOwner);
if (productUploaded != null) {
productUploaded.setStock(updateProduct.getStock());
productRepository.save(productUploaded);
return "STOCK HAS BEEN UPDATED!";
}
return "STOCK UPDATE FAILED!";
}
@DeleteMapping("/product/{id}")
public String delete(@PathVariable Integer id, Principal principal) {
// Get the productOwner
User productOwner = userRepository.findByUserName(getUserName(principal));
if (productOwner == null) {
return "USER NOT FOUND!";
}
// Delete Product
Product product = productRepository.findByIdAndUser(id, productOwner);
if ( product != null ) {
productRepository.delete(product);
return "PRODUCT HAS BEEN DELETED";
} else {
return "DELETING PRODUCT HAS BEEN FAILED";
}
}
// METHOD TO GET USERNAME OF USER FROM PRINCIPAL
private String getUserName(Principal principal) {
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) principal;
Claims user = (Claims) token.getPrincipal();
return user.getSubject();
}
//======================================================================================================================
// NO PRINCIPAL NEEDED
//======================================================================================================================
// this API Cache implemented
@GetMapping("/product")
public ResponseEntity<Map<String, Object>> getProductByCategory(
@RequestParam String category,
@RequestParam Integer page,
@RequestParam String sort){
return buildResponseEntity(cachedProductRepository.findByCategory(category, page, sort));
}
// this API Cache implemented
@GetMapping("/search")
public ResponseEntity<Map<String, Object>> getProductBySearchQuery(
@RequestParam String query,
@RequestParam Integer page,
@RequestParam String sort) {
return buildResponseEntity(cachedProductRepository.findByProductNameContaining(query, page, sort));
}
private ResponseEntity<Map<String, Object>> buildResponseEntity(Page<Product> productPage) {
Map<String, Object> response = new HashMap();
response.put("products", productPage.getContent());
response.put("currentPage", productPage.getNumber());
response.put("totalItems", productPage.getTotalElements());
response.put("totalPages", productPage.getTotalPages());
return new ResponseEntity<>(response, HttpStatus.OK);
}
}
| 920add1deb1960fce5fb10dca9788341fa548687 | [
"Markdown",
"Java",
"INI"
] | 20 | Java | mvadlil/ecommerce_backend_apps | e420c08ec8a2199a2e61988008f0cdaf77ad7329 | 53dbe90a5dea0d1c1cb5c7215343a12a6e921585 |
refs/heads/master | <repo_name>NigelDcruz/developed_components<file_sep>/source/domcacheES6.js
export default new class App {
constructor() {
this.setDomMap();
this.previousScroll = 0;
// dom ready shorthand
$(() => {
this.domReady();
});
}
domReady = () => {
this.initComponents();
this.handleUserAgent();
this.windowResize();
this.bindEvents();
this.handleSplashScreen();
// console.log('Initializing Dom events');
};
initComponents = () => {
new Header({
header: this.header,
htmlBody: this.htmlBody,
});
if (this.mapContainer.length) {
new Maps({
mapContainer: this.mapContainer,
});
}
};
setDomMap = () => {
this.window = $(window);
this.htmlNbody = $('body, html');
this.html = $('html');
this.htmlBody = $('body');
this.siteLoader = $('.site-loader');
this.header = $('header');
this.siteBody = $('.site-body');
this.footer = $('footer');
this.gotoTop = $('#gotoTop');
this.gRecaptcha = $('.g-recaptcha');
this.wrapper = $('.wrapper');
this.pushDiv = this.wrapper.find('.push');
this.mapContainer = $('#map_canvas');
this.inputs = $('input, textarea').not('[type="checkbox"], [type="radio"]');
};
bindEvents = () => {
// Window Events
this.window.resize(this.windowResize).scroll(this.windowScroll);
// General Events
const $container = this.wrapper;
$container.on('click', '.disabled', () => false);
// Specific Events
this.gotoTop.on('click', () => {
this.htmlNbody.animate({
scrollTop: 0,
});
});
this.inputs
.on({
focus: (e) => {
const self = $(e.currentTarget);
self.closest('.element').addClass('active');
},
blur: (e) => {
const self = $(e.currentTarget);
if (self.val() !== '') {
self.closest('.element').addClass('active');
} else {
self.closest('.element').removeClass('active');
}
},
})
.trigger('blur');
// Reload the current path when changing language instead of redirecting to landing page
// Uncomment below and modify languages
// $container.on('click', '.language-toggle', function(e) {
// e.preventDefault();
// const $this = $(this);
// const href = $this.attr('href');
// const isEnglish = href.indexOf('/ar') >= 0;
// const locArray = location.pathname.split('/');
// const indexOfIndex = locArray.indexOf('index.php');
// const isDev = indexOfIndex >= 0;
// const index = isDev ? indexOfIndex + 1 : 1;
// if(!isEnglish) {
// locArray = locArray.filter(item => item !== 'ar')
// }
// locArray.splice(index, 0, isEnglish ? 'ar' : '');
// const newHref = locArray.join('/').replace('//', '/');
// location.href = newHref;
// });
// Uncomment below if you need to add google captcha (also in includes/script.php)
// => Make sure the SITEKEY is changed below
// this.gRecaptcha.each((index, el) => {
// grecaptcha.render(el, {'sitekey' : '<KEY>'});
// });
};
windowResize = () => {
this.screenWidth = this.window.width();
this.screenHeight = this.window.height();
// calculate footer height and assign it to wrapper and push/footer div
this.footerHeight = this.footer.outerHeight();
this.wrapper.css('margin-bottom', -this.footerHeight);
this.pushDiv.height(this.footerHeight);
};
windowScroll = () => {
const topOffset = this.window.scrollTop();
this.header.toggleClass('top', topOffset > 100);
this.header.toggleClass('sticky', topOffset > 350);
if (topOffset > this.previousScroll || topOffset < 250) {
this.header.removeClass('sticky');
} else if (topOffset < this.previousScroll) {
this.header.addClass('sticky');
// Additional checking so the header will not flicker
if (topOffset > 250) {
this.header.addClass('sticky');
} else {
this.header.removeClass('sticky');
}
}
this.previousScroll = topOffset;
this.gotoTop.toggleClass(
'active',
this.window.scrollTop() > this.screenHeight / 2,
);
};
handleSplashScreen() {
this.htmlBody.find('.logo-middle').fadeIn(500);
this.siteLoader.delay(1500).fadeOut(500);
}
handleUserAgent = () => {
// detect mobile platform
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
this.htmlBody.addClass('ios-device');
}
if (navigator.userAgent.match(/Android/i)) {
this.htmlBody.addClass('android-device');
}
// detect desktop platform
if (navigator.appVersion.indexOf('Win') !== -1) {
this.htmlBody.addClass('win-os');
}
if (navigator.appVersion.indexOf('Mac') !== -1) {
this.htmlBody.addClass('mac-os');
}
// detect IE 10 and 11P
if (
navigator.userAgent.indexOf('MSIE') !== -1
|| navigator.appVersion.indexOf('Trident/') > 0
) {
this.html.addClass('ie10');
}
// detect IE Edge
if (/Edge\/\d./i.test(navigator.userAgent)) {
this.html.addClass('ieEdge');
}
// Specifically for IE8 (for replacing svg with png images)
if (this.html.hasClass('ie8')) {
const imgPath = '/themes/theedge/images/';
$('header .logo a img,.loading-screen img').attr(
'src',
`${imgPath}logo.png`,
);
}
// show ie overlay popup for incompatible browser
if (this.html.hasClass('ie9')) {
const message = $(
'<div class="no-support"> You are using outdated browser. Please <a href="https://browsehappy.com/" target="_blank">update</a> your browser or <a href="https://browsehappy.com/" target="_blank">install</a> modern browser like Google Chrome or Firefox.<div>',
);
this.htmlBody.prepend(message);
}
};
}();
<file_sep>/source/index.js
/*
To use jQuery, first install it as a dependency: `npm install --save jquery`.
Then include `import $ from 'jquery';` at the top every JavaScript file that uses jQuery.*/
import $ from 'jquery'; //Before using jQuery, install it with `npm install --save jquery`
import 'normalize.css'; // Note this
import './style/style.scss';
import './style/style.css';
const saySomething = (something) => {
console.log(something); // eslint-disable-line no-console
};
saySomething('Something! (index.js)');
//Code for scroll up and down on mobile devices
var lastPoint = null;
$(window).on('touchstart', function(e){
lastPoint = e.originalEvent.changedTouches[0].clientY;
});
$(window).on('touchend', function(e){
//Console log e to check for all available properties
var currentPoint = e.originalEvent.changedTouches[0].clientY;
if(lastPoint > currentPoint){
//swiped up
// console.log('you swipe up');
if ($(window).scrollTop() > 150) { //Checks for scroll position of element
//Do Something
}
}
else {
//swiped down
// console.log('you swipe down');
if ($(window).scrollTop() > 150) { //Checks for scroll position of element
//Do Something
}
}
});
// Mobile Touch code Ends
//Mouse scroll up/Down code added
$(window).bind('mousewheel DOMMouseScroll', function (event) {
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
if ($(window).scrollTop() > 250) {
//do something
} else {
//do something
}
} else {
// scroll down
if ($(window).scrollTop() > 250) {
//do something
} else {
//do something
}
}
});
//Mouse scroll ended
//detect mobile platform
if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
$("body").addClass("ios-device");
}
if (navigator.userAgent.match(/Android/i)) {
$("body").addClass("android-device");
}
//detect desktop platform
if (navigator.appVersion.indexOf("Win") != -1) {
$('body').addClass("win-os");
}
if (navigator.appVersion.indexOf("Mac") != -1) {
$('body').addClass("mac-os");
}
//detect IE 10 and 11
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
$("html").addClass("ie10");
}
//detect IE Edge
if (/Edge\/\d./i.test(navigator.userAgent)) {
$("html").addClass("ieEdge");
}
//Specifically for IE8 (for replacing svg with png images)
if ($("html").hasClass("ie8")) {
//do something
}
//show ie overlay popup for incompatible browser
if ($('html').hasClass('ie9')) {
var message = $('<div class="no-support"> You are using outdated browser. Please <a href="https://browsehappy.com/" target="_blank">update</a> your browser or <a href="https://browsehappy.com/" target="_blank">install</a> modern browser like Google Chrome or Firefox.<div>');
$('body').prepend(message);
}
| 8138c657af33ac35e90e2cee2a4f0eb5b27a406f | [
"JavaScript"
] | 2 | JavaScript | NigelDcruz/developed_components | 1b3ec52e0f5078753c44d6a9dab7b29a80840b46 | b4baf2e7d94ddafe08abd6a6ed21e9620f5dc7d7 |
refs/heads/master | <repo_name>shreshthmohan/experiment-sm<file_sep>/src/formatElapsedTime.js
export const formatElapsedTime = (elapsedMilliSeconds) => {
let parsedTime = parseInt(elapsedMilliSeconds, 10);
if (isNaN(parsedTime)) {
return '00:00.00';
}
// Format - Time less than an hour
// '00:00.00'
// mm:ss.cc
let formattedTime = '';
const milliSeconds = parsedTime % 1000;
const centiSeconds = Math.floor(milliSeconds / 10);
// appending '0' at beginning if value smaller than 10
// and adding centiseconds value
formattedTime = (centiSeconds < 10 ? '0' + centiSeconds : centiSeconds) + formattedTime;
// Time in seconds
parsedTime = Math.floor(parsedTime / 1000);
const seconds = parsedTime % 60;
formattedTime = (seconds < 10 ? '0' + seconds : seconds) + '.' + formattedTime;
// Time in minutes
parsedTime = Math.floor(parsedTime / 60);
const minutes = parsedTime % 60;
formattedTime = (minutes < 10 ? '0' + minutes : minutes) + ':' + formattedTime;
// Format - Time more than 1 hour
// '00:00:00.00'
// hh:mm:ss.cc
// Time in hours
parsedTime = Math.floor(parsedTime / 60);
if (parsedTime === 0) {
return formattedTime;
} else {
const hours = parsedTime % 100;
formattedTime = (hours < 10 ? '0' + hours : hours) + ':' + formattedTime;
return formattedTime;
}
}
<file_sep>/src/formatElapsedTime.test.js
import { formatElapsedTime } from './formatElapsedTime';
test('Formating invalid value, "ABC" results in "00:00.00"', () => {
expect(formatElapsedTime('ABC')).toBe('00:00.00');
});
test('Returns "00:00.00" when no argument is passed', () => {
expect(formatElapsedTime()).toBe('00:00.00');
});
test('129100 ms is formatted to "02:09.10"', () => {
expect(formatElapsedTime(129100)).toBe('02:09.10');
expect(formatElapsedTime('129100')).toBe('02:09.10');
});
test('100000000 ms is formatted to "27:46:40.00"', () => {
expect(formatElapsedTime(100000000)).toBe('27:46:40.00');
expect(formatElapsedTime('100000000')).toBe('27:46:40.00');
});
test('3600000 ms is formatted to "01:00:00.00"', () => {
expect(formatElapsedTime(3600000)).toBe('01:00:00.00');
expect(formatElapsedTime('3600000')).toBe('01:00:00.00');
});
| 4c6c232bc60921015cfaf47d35ebdeb9b48e98e2 | [
"JavaScript"
] | 2 | JavaScript | shreshthmohan/experiment-sm | e8b468136ad385b302fd990e691db3f4553aab63 | 56caa063f64c2eac30595c77f9291ce5b737aecf |
refs/heads/master | <file_sep>import socket
import sys
print ('Enter your DNS Or Target: ')
hostname = input()
ip=socket.gethostbyname(hostname)
print ('Host Name Is: ', hostname, '\n' 'Target Ip Is: ',ip)
#just put any site like that www.google.com | 494500bedff7de7632872e5a57702e0a6fd87a08 | [
"Python"
] | 1 | Python | zacafran380/site-ip-gathering | 0acdef160df553e7af93a43f15ea64dda7a846a1 | ea9403903ba386e55bb4ed819810e2a7528d70d2 |
refs/heads/main | <repo_name>maxpromer/iSERVO<file_sep>/iservo/iSERVO.cpp
#include "iSERVO.h"
iSERVO::iSERVO(int bus_ch, int dev_addr) {
channel = bus_ch;
address = dev_addr;
polling_ms = 100;
}
void iSERVO::init(void) {
memset(last_set_angle, 0, 16);
for (int i=0;i<16;i++) {
t_min[i] = 0.5;
t_max[i] = 2.5;
}
state = s_detect;
}
int iSERVO::prop_count(void) {
// not supported
return 0;
}
bool iSERVO::prop_name(int index, char *name) {
// not supported
return false;
}
bool iSERVO::prop_unit(int index, char *unit) {
// not supported
return false;
}
bool iSERVO::prop_attr(int index, char *attr) {
// not supported
return false;
}
bool iSERVO::prop_read(int index, char *value) {
// not supported
return false;
}
bool iSERVO::prop_write(int index, char *value) {
// not supported
return false;
}
void iSERVO::process(Driver *drv) {
i2c = (I2CDev *)drv;
switch (state) {
case s_detect:
if (i2c->detect(channel, address) == ESP_OK) {
uint8_t buff[2] = { 0, 0 };
uint32_t _oscillator_freq = 27000000;
uint32_t freq = 50;
uint8_t prescaleval = (((float)_oscillator_freq / ((float)freq * 4096.0)) + 0.5) - 1.0;
buff[0] = 0xFE;
buff[1] = prescaleval;
if (i2c->write(channel, address, buff, 2) == ESP_OK) {
buff[0] = 0x00;
buff[1] = 0b10100000; // RESTART triger, Auto-Increment register
if (i2c->write(channel, address, buff, 2) == ESP_OK) {
error = false;
initialized = true;
state = s_angle_update;
} else {
state = s_error;
}
} else {
state = s_error;
}
} else {
state = s_error;
}
break;
case s_angle_update:
for (uint8_t i=0;i<16;i++) {
setAngle(i, last_set_angle[i]);
}
state = s_check;
polling_tickcnt = get_tickcnt();
break;
case s_check:
if (is_tickcnt_elapsed(polling_tickcnt, polling_ms)) {
if (i2c->detect(channel, address) == ESP_OK) {
polling_tickcnt = get_tickcnt();
state = s_check;
} else {
state = s_error;
}
}
break;
case s_error:
// set error flag
error = true;
// clear initialized flag
initialized = false;
// get current tickcnt
tickcnt = get_tickcnt();
// goto wait and retry with detect state
state = s_wait;
break;
case s_wait:
// wait polling_ms timeout
if (is_tickcnt_elapsed(tickcnt, polling_ms)) {
state = s_detect;
}
break;
}
}
void iSERVO::setAngle(uint8_t n, uint8_t angle) {
if (!i2c) return;
if (n > 15) return;
angle = angle > 200 ? 200 : angle;
float angleToMS = (angle * (t_max[n] - t_min[n]) / 200.0) + t_min[n];
uint16_t pulse_u16 = (angleToMS * 4095.0 / 20.0) * 0.93;
uint8_t buff[5] = {
(uint8_t)(0x06 + (n * 4)), // LED0_ON_L
0, // ON LSB
0, // ON MSB
(uint8_t)(pulse_u16 & 0xFF),
(uint8_t)((pulse_u16 >> 8) & 0xFF)
};
if (i2c->write(channel, address, buff, 5) != ESP_OK) {
state = s_error;
}
last_set_angle[n] = angle;
}
void iSERVO::calibrate(uint8_t n, float min, float max) {
t_min[n] = min;
t_max[n] = max;
}
<file_sep>/iservo/iSERVO.h
#ifndef __ISERVO_H__
#define __ISERVO_H__
#include "driver.h"
#include "device.h"
#include "i2c-dev.h"
#include "stdio.h"
#include "string.h"
class iSERVO : public Device {
private:
enum {
s_detect, s_angle_update, s_check, s_error, s_wait
} state;
TickType_t tickcnt, polling_tickcnt;
I2CDev *i2c = NULL;
uint8_t last_set_angle[16];
float t_min[16];
float t_max[16];
public:
// constructor
iSERVO(int bus_ch, int dev_addr) ;
// override
void init(void);
void process(Driver *drv);
int prop_count(void);
bool prop_name(int index, char *name);
bool prop_unit(int index, char *unit);
bool prop_attr(int index, char *attr);
bool prop_read(int index, char *value);
bool prop_write(int index, char *value);
// method
void setAngle(uint8_t n, uint8_t angle) ;
void calibrate(uint8_t n, float min, float max) ;
};
#endif
<file_sep>/iservo/generators.js
Blockly.JavaScript['iservo'] = function(block) {
var dropdown_pin = block.getFieldValue('pin');
var value_angle = Blockly.JavaScript.valueToCode(block, 'angle', Blockly.JavaScript.ORDER_ATOMIC);
// TODO: Assemble JavaScript into code variable.
var code = 'DEV_I2C1.iSERVO(0, 0x40).setAngle(' + dropdown_pin + ', ' + value_angle + ');\n';
return code;
};
Blockly.JavaScript['iservo_calibrate'] = function(block) {
var dropdown_pin = block.getFieldValue('pin');
var number_min = block.getFieldValue('min');
var number_max = block.getFieldValue('max');
// TODO: Assemble JavaScript into code variable.
var code = 'DEV_I2C1.iSERVO(0, 0x40).calibrate(' + dropdown_pin + ', ' + number_min + ', ' + number_max + ');\n';
return code;
}; | 6affef724c3ae7f1824f922d7c838d40a7c50735 | [
"JavaScript",
"C++"
] | 3 | C++ | maxpromer/iSERVO | db17e9e0ec37fb835b4ec60226a6dbe6fa8f8ceb | 1212bbd23d95b2002e2a7c492d2f3c8157a7d555 |
refs/heads/master | <file_sep># leitore
Projeto de identificação de palavras em java
## Guide ##
### Main ###
[Principal](https://github.com/thaianyrocha/leitore/blob/master/leitore/src/leitore/main.java)
[KeyBoard](https://github.com/thaianyrocha/leitore/blob/master/leitore/src/entites/keyboard.java)
[latter](https://github.com/thaianyrocha/leitore/blob/master/leitore/src/entites/letter.java)

<file_sep>package entites;
public class letter {
private char posicao1;
private char posicao2;
private char posicao3;
public letter(char posicao1, char posicao2, char posicao3) {
super();
this.posicao1 = posicao1;
this.posicao2 = posicao2;
this.posicao3 = posicao3;
}
public String processo() {
if(posicao1 == 'a') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **NOME** \n";
}
return "\n **NOME** \n";
}
if(posicao1 == 'a' && posicao2 == 'b' || posicao1 == 'a' && posicao2 == 'g' || posicao1 == 'a' && posicao2 == 'r') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
}
if(posicao1 == 'e') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **NOME** \n";
}
return "\n **NOME** \n";
}
if(posicao1 == 'e' && posicao2 == 'b' || posicao1 == 'e' && posicao2 == 'g' || posicao1 == 'e' && posicao2 == 'r') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
}
if(posicao1 == 'i') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **NOME** \n";
}
return "\n **NOME** \n";
}
if(posicao1 == 'i' && posicao2 == 'b' || posicao1 == 'i' && posicao2 == 'g' || posicao1 == 'i' && posicao2 == 'r') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
}
if(posicao1 == 'o') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **NOME** \n";
}
return "\n **NOME** \n";
}
if(posicao1 == 'o' && posicao2 == 'b' || posicao1 == 'o' && posicao2 == 'g' || posicao1 == 'o' && posicao2 == 'r') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
}
if(posicao1 == 'u') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **NOME** \n";
}
return "\n **NOME** \n";
}
if(posicao1 == 'u' && posicao2 == 'b' || posicao1 == 'u' && posicao2 == 'g' || posicao1 == 'u' && posicao2 == 'r') {
if(posicao2 == 'n' || posicao2 == 'g' || posicao2 == 'l' || posicao2 == 'm') {
if('a' == posicao3 || 'e' == posicao3 || 'i' == posicao3 || 'o' == posicao3 || 'u' == posicao3) {
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
return "\n **OBJETO** \n";
}
}
return "\n **NAO IDENTIFICADO** \n";
}
}
| 2356b11522019d7866bda52c7dc4f908db978495 | [
"Markdown",
"Java"
] | 2 | Markdown | thaianyrocha/leitore | b0ae4889fa57d5a4b521a7325fffed5790c2e228 | da813f339ddf31d457db8abe5ffee40b5767d39a |
refs/heads/master | <file_sep>from bottle import route, run, request
@route('/')
def hello():
return request.remote_addr
run(host='localhost', port=8080, debug=True)
| daa7a962566195c47ccb7c3e4aa9279adab80dfc | [
"Python"
] | 1 | Python | niranjfantain/myip | 877ac39e74fbe3896f4f0e265869febc1c381690 | 39060dbf2592bb0f1d3ae9a5e0dd8cc53527d25b |
refs/heads/master | <repo_name>rajeshpillai/rails-codebox<file_sep>/app/models/code.rb
class Code < ApplicationRecord
belongs_to :category
has_many :taggings
has_many :tags, through: :taggings
end
<file_sep>/README.md
# README
- yarn add codemirror<file_sep>/app/models/tag.rb
class Tag < ApplicationRecord
has_many :taggings
has_many :codes, through: :taggings
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
resources :codes
resources :tags
resources :categories
get 'home/index'
devise_for :users
# You have to create home controller with index action
root to: "home#index"
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
<file_sep>/db/migrate/20200808131433_change_body_to_code.rb
class ChangeBodyToCode < ActiveRecord::Migration[6.0]
def change
rename_column :codes, :body, :code
end
end
<file_sep>/db/migrate/20200808131635_add_fields_to_codes.rb
class AddFieldsToCodes < ActiveRecord::Migration[6.0]
def change
add_column :codes, :html, :string
add_column :codes, :css, :string
end
end
<file_sep>/app/models/tagging.rb
class Tagging < ApplicationRecord
belongs_to :code
belongs_to :tag
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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Code.delete_all
Category.delete_all
User.delete_all
Tagging.delete_all
Tag.delete_all
Category.create(name: "Programming")
Category.create(name: "Web Development")
Category.create(name: "Ruby on Rails")
Category.create(name: "React")
javascript = Tag.create(name: "javascript")
react = Tag.create(name: "react")
ruby = Tag.create(name: "ruby")
node = Tag.create(name: "node")
admin_user = User.create(
email: "<EMAIL>",
username:"admin", password:"<PASSWORD>",
password_confirmation:"<PASSWORD>")
10.times do |i|
User.create(
email: "<EMAIL>",
username:"user#{i}", password:"<PASSWORD>",
password_confirmation:"<PASSWORD>")
end
Category.all.each do |category|
10.times do |i|
Code.create(title: "Post #{i}",
user_id: admin_user.id,
tags: i % 2 == 0 ? [javascript, react] : [ruby, node],
category: category,
code: 'function greeting() {' <<
'console.log("hello world")' <<
'}' <<
'greeting()',
html: "<h2>Hello world</h2>",
css: ""
)
end
end<file_sep>/app/views/codes/_code.json.jbuilder
json.extract! code, :id, :title, :code_lang, :html, :css, :code, :category_id, :created_at, :updated_at
json.url code_url(code, format: :json)
| 6c03dd429bde6aedafbb1f14aa71f367f71a9b98 | [
"Markdown",
"Ruby"
] | 9 | Ruby | rajeshpillai/rails-codebox | 6dd6b28ae518d91691f5202f6f47983c52128dfd | 6efa8dfbb72a6da7e12613a8cc3b2ef5932a970f |
refs/heads/main | <repo_name>Mizer-Mi/LetMeRepair_Comments<file_sep>/README.md
# LetMeRepair_Comments
LetMeRepair şirketinde Kullanılan ERP programı için Arızaya gelen cihazların servis formuna yazılan; arıza açıklamaları ve yapılan işlemler için üretilen hem ingilizce hem türkçe kaynağını sahip otomatik yorum üretici yazılımdır. Serviste çalışan ingilizce veya türkçe bilgisi olmadıkları için servis formu yorumlarını yazamayanlara yardımcı olan ve servis formu yorumlarının tek kalıp olmasını sağlayan yazılımdır. C# Winform ve Microsoft Access veritabanı kullanılarak tarafımca yazılmıştır.
<file_sep>/LetMeRepair_Comments/sablon_ana.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LetMeRepair_Comments
{
public partial class sablon_ana : Form
{
public sablon_ana()
{
InitializeComponent();
this.StartPosition = FormStartPosition.Manual;
foreach (var scrn in Screen.AllScreens)
{
if (scrn.Bounds.Contains(this.Location))
{
this.Location = new Point(scrn.Bounds.Right - this.Width, scrn.Bounds.Top- (-Properties.Settings.Default.paket_bosluk_yukari));
return;
}
}
}
private void Sablon_ana_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void RichTextBox2_TextChanged(object sender, EventArgs e)
{
}
private void Button3_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
}
}
<file_sep>/LetMeRepair_Comments/paket_olarak_kaydet.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LetMeRepair_Comments
{
public partial class paket_olarak_kaydet : Form
{
public paket_olarak_kaydet()
{
InitializeComponent();
}
public string turkishcomment {get;set;}
public string englishcomment { get; set; }
private void Paket_olarak_kaydet_Load(object sender, EventArgs e)
{
paketleri_listele();
}
private void paketleri_listele()
{
DataTable degisen_parca_tum_db = baglanti.listele("paket", "0");
degisen_parca_tum_db.Rows.Add(0,"Hepsi");
comboBox1.DataSource = degisen_parca_tum_db;
comboBox1.DisplayMember = "baslik";
/// ((DataRowView)ariza.SelectedItem)["id"].ToString();
comboBox1.SelectedIndex = 0;
}
private void Kydt_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedText == "Hepsi")
{
baglanti.Paket_ekle("paket_uyesi", baslik.Text, turkishcomment, englishcomment,0);
}
else
{
baglanti.Paket_ekle("paket_uyesi", baslik.Text, turkishcomment, englishcomment,Convert.ToInt32(((DataRowView)comboBox1.SelectedItem)["id"].ToString()));
}
}
private void Yeni_Click(object sender, EventArgs e)
{
using (paket_ekle_duzenle frmac= new paket_ekle_duzenle())
{
frmac.ShowDialog();
}
paketleri_listele();
}
}
}
<file_sep>/LetMeRepair_Comments/duzenle_sirtuex.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Runtime.InteropServices;
namespace LetMeRepair_Comments
{
public partial class duzenle_sirtuex : Form
{
public duzenle_sirtuex()
{
InitializeComponent();
}
private const int EM_SETCUEBANNER = 0x1501;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);
private void liste_yenilemesi ()
{
degisen_parca_tum_db = baglanti.listele("degisen_parca", "%");
degisen_parca.DataSource = degisen_parca_tum_db;
ariza_list = baglanti.listele("ariza", "0");
ariza.DataSource = ariza_list;
arizasi_list = baglanti.listele("ariza", "0");
arizasi.DataSource = arizasi_list;
kut_list = baglanti.listele("kut", "0");
kut.DataSource = kut_list;
kut.SelectedIndex = -1;
panel_main.Visible = false;
}
private void Ariza_SelectedIndexChanged(object sender, EventArgs e)
{
if (ariza.SelectedItem != null)
{
kut.SelectedItem = null;
degisen_parca.SelectedItem = null;
string secili_baslik = ((DataRowView)ariza.SelectedItem)["baslik"].ToString();
baslik.Text = "";
turkish_ric.Text = "";
english_rich.Text = "";
baslik.Text = secili_baslik;
english_rich.Text = baglanti.comment_cek_Mizer("ariza", "english", secili_baslik);
turkish_ric.Text = baglanti.comment_cek_Mizer("ariza", "turkish", secili_baslik);
panel_main.Visible = true;
kydt.Enabled = true;
sil.Enabled = true;
panel_ariza_bagli.Visible = false;
}
}
private void Degisen_parca_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Kut_SelectedIndexChanged(object sender, EventArgs e)
{
if (kut.SelectedItem != null)
{
ariza.SelectedItem = null;
degisen_parca.SelectedItem = null;
string secili_baslik = ((DataRowView)kut.SelectedItem)["baslik"].ToString();
baslik.Text = "";
turkish_ric.Text = "";
english_rich.Text = "";
baslik.Text = secili_baslik;
english_rich.Text = baglanti.comment_cek_Mizer("kut", "english", secili_baslik) ;
turkish_ric.Text = baglanti.comment_cek_Mizer("kut", "turkish", secili_baslik) ;
panel_main.Visible = true;
kydt.Enabled = true;
sil.Enabled = true;
panel_ariza_bagli.Visible = false;
}
}
private async void Blink()
{
while (true)
{
if (panel_main.Visible == true)
{
await Task.Delay(250);
label4.Visible = false;
}
else
{
label4.Visible = true;
await Task.Delay(500);
if (label4.ForeColor == Color.Red) { label4.ForeColor = Color.Green; } else { label4.ForeColor = Color.Red; }
}
}
}
private void Button4_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
DataTable degisen_parca_tum_db = baglanti.listele("degisen_parca", "%");
DataTable ariza_list = baglanti.listele("ariza", "0");
DataTable arizasi_list = baglanti.listele("ariza", "0");
DataTable kut_list = baglanti.listele("kut", "0");
private void Duzenle_sirtuex_Load(object sender, EventArgs e)
{
dil_ayari_Cek();
Blink();
arizasi.SelectedIndex = -1;
degisen_parca.SelectedIndex = -1;
kut.SelectedIndex = -1;
ariza.DataSource = ariza_list;
ariza.DisplayMember = "baslik";
ariza.ValueMember = "id";
ariza.Tag = "baslik";
degisen_parca.DataSource = degisen_parca_tum_db;
degisen_parca.DisplayMember = "baslik";
degisen_parca.ValueMember = "id";
degisen_parca.Tag = "baslik";
kut.DataSource = kut_list;
kut.DisplayMember = "baslik";
kut.ValueMember = "id";
kut.Tag = "baslik";
arizasi.DataSource = arizasi_list;
arizasi.DisplayMember = "baslik";
arizasi.ValueMember = "id";
arizasi.Tag = "baslik";
panel_main.Visible = false;
SendMessage(arama_ariza.Handle, EM_SETCUEBANNER, 0, "Search for Control/Defect");
SendMessage(arama_parca.Handle, EM_SETCUEBANNER, 0, "Search for Solution/Montage");
SendMessage(textBox1.Handle, EM_SETCUEBANNER, 0, "Search for Solution/Montage");
SendMessage(arama_kut.Handle, EM_SETCUEBANNER, 0, "Search for Final Test/End");
SendMessage(arama_ariza.Handle, EM_SETCUEBANNER, 0, dil.dil_ayari_yap("arama_ariza"));
SendMessage(arama_parca.Handle, EM_SETCUEBANNER, 0, dil.dil_ayari_yap("arama_parca"));
SendMessage(textBox1.Handle, EM_SETCUEBANNER, 0, dil.dil_ayari_yap("arama_parca"));
SendMessage(arama_kut.Handle, EM_SETCUEBANNER, 0, dil.dil_ayari_yap("arama_kut"));
}
DataView cozum_ara;
DataView dataView_ariza;
DataView kut_ara;
DataView arizasi_ara;
private void Arama_parca_TextChanged(object sender, EventArgs e)
{
cozum_ara = degisen_parca_tum_db.DefaultView;
cozum_ara.RowFilter = "baslik LIKE '%" + arama_parca.Text + "%'";
if (cozum_ara.Count != 0)
{ degisen_parca.SelectedIndex = degisen_parca.TopIndex; degisen_parca.Refresh(); }
else
{ }
}
private void Arama_ariza_TextChanged(object sender, EventArgs e)
{
dataView_ariza = ariza_list.DefaultView;
dataView_ariza.RowFilter = "baslik LIKE '%" + arama_ariza.Text + "%'";
if (dataView_ariza.Count != 0)
{ ariza.SelectedIndex = ariza.TopIndex; ariza.Refresh(); }
else
{ }
}
private void Arama_kut_TextChanged(object sender, EventArgs e)
{
kut_ara = kut_list.DefaultView;
kut_ara.RowFilter = "baslik LIKE '%" + arama_kut.Text + "%'";
if (kut_ara.Count != 0)
{ kut.SelectedIndex = kut.TopIndex; kut.Refresh(); }
else
{ }
}
private void Kydt_Click(object sender, EventArgs e)
{
string secili_tur ="yok";
string srgu = "";
if (ariza.SelectedItem != null)
{
secili_tur = "ariza";
srgu = ((DataRowView)ariza.SelectedItem)["baslik"].ToString();
}
else if (degisen_parca.SelectedItem != null)
{
secili_tur = "degisen_parca";
srgu= ((DataRowView)degisen_parca.SelectedItem)["baslik"].ToString();
}
else if (kut.SelectedItem != null)
{
secili_tur = "kut";
srgu = ((DataRowView)kut.SelectedItem)["baslik"].ToString();
}
else
{
return;
}
if (baslik.Text.StartsWith(" ") || baslik.Text.Replace(" ", "") == "" || baslik.Text.Length <= 4)
{
MessageBox.Show(gecerli_baslik, "LetMeRepair - Mizer - Hatalı Başlık", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if ( (srgu !=baslik.Text) && (baglanti.tekrar_sorgula(secili_tur, baslik.Text) == "Mevcut"))
{
MessageBox.Show(ayni_basliktan, "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
int secili_id;
if (ariza.SelectedItem != null)
{
secili_id = Convert.ToInt32(((DataRowView)ariza.SelectedItem)["id"]);
baglanti.guncelle_tur("ariza", baslik.Text, english_rich.Text, turkish_ric.Text, "0", secili_id);
MessageBox.Show("Record Updated - 1", "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (degisen_parca.SelectedItem != null)
{
secili_id = Convert.ToInt32(((DataRowView)degisen_parca.SelectedItem)["id"]);
string secili_idler = "";
foreach (var secili_itemler in arizasi.SelectedItems)
{
secili_idler = secili_idler + "-" + ((DataRowView)secili_itemler)["id"].ToString();
}
baglanti.guncelle_tur("degisen_parca", baslik.Text, english_rich.Text, turkish_ric.Text, secili_idler, secili_id);
MessageBox.Show("Record Updated - 2", "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (kut.SelectedItem != null)
{
secili_id = Convert.ToInt32(((DataRowView)kut.SelectedItem)["id"]);
baglanti.guncelle_tur("kut", baslik.Text, english_rich.Text, turkish_ric.Text, "0", secili_id);
MessageBox.Show("Record Updated - 3", "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("No Select");
}
liste_yenilemesi();
}
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
arizasi_ara = arizasi_list.DefaultView;
arizasi_ara.RowFilter = "baslik LIKE '%" + textBox1.Text + "%'";
if (arizasi_ara.Count != 0)
{ }
else
{ }
}
private void Degisen_parca_MouseDown(object sender, MouseEventArgs e)
{
arizasi.SelectedIndex = -1;
if (degisen_parca.SelectedIndex != -1)
{
kut.SelectedItem = null;
ariza.SelectedItem = null;
string secili_baslik = ((DataRowView)degisen_parca.SelectedItem)["baslik"].ToString();
if (secili_baslik == "")
{
panel_main.Visible = false;
return;
}
baslik.Text = "";
turkish_ric.Text = "";
english_rich.Text = "";
baslik.Text = secili_baslik;
english_rich.Text = baglanti.comment_cek_Mizer("degisen_parca", "english", secili_baslik);
turkish_ric.Text = baglanti.comment_cek_Mizer("degisen_parca", "turkish", secili_baslik);
string secili_sayilar_yansitma = baglanti.comment_cek_Mizer("degisen_parca", "bagli_oldugu_ariza", secili_baslik);
panel_main.Visible = true;
kydt.Enabled = true;
sil.Enabled = true;
panel_ariza_bagli.Visible = true;
if (secili_sayilar_yansitma.EndsWith("-"))
{
secili_sayilar_yansitma = secili_sayilar_yansitma.Remove(secili_sayilar_yansitma.Length - 1, 1);
}
if (secili_sayilar_yansitma.StartsWith("-"))
{
secili_sayilar_yansitma = secili_sayilar_yansitma.Remove(0, 1);
}
try
{
string[] ali = new string[] { " " };
if (secili_sayilar_yansitma.Contains('-'))
{
ali = secili_sayilar_yansitma.Split('-');
}
else
{
ali[0] = secili_sayilar_yansitma;
}
int[] deger = new int[] { 0 };
if (ali.Count() > 1)
{
deger = Array.ConvertAll<string, int>(ali, int.Parse);
}
else
{
deger[0] = Convert.ToInt32(secili_sayilar_yansitma);
}
string secilecek_index_no = "";
foreach (int oku in deger)
{
foreach (DataRowView item in arizasi.Items)
{
if (Convert.ToInt32(item["id"].ToString()) == oku)
{
// arizasi.SetSelected(arizasi.Items.IndexOf(item),true);
secilecek_index_no = secilecek_index_no + "-" + (arizasi.Items.IndexOf(item)).ToString();
}
}
}
/// KISALTILACAK
if (secilecek_index_no.StartsWith("-"))
{
secilecek_index_no = secilecek_index_no.Remove(0, 1);
}
arizasi.ClearSelected();
try
{
string[] ali2 = secilecek_index_no.Split('-');
int[] deger2 = Array.ConvertAll<string, int>(ali2, int.Parse);
foreach (int indx in deger2)
{
arizasi.SetSelected(indx, true);
}
}
catch
{
}
}
catch { }
}
}
private void Sil_Click(object sender, EventArgs e)
{
int secili_id;
if (ariza.SelectedItem != null)
{
secili_id = Convert.ToInt32(((DataRowView)ariza.SelectedItem)["id"]);
baglanti.sil_tur("ariza", secili_id);
MessageBox.Show("Record Deleted - 1", "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (degisen_parca.SelectedItem != null)
{
secili_id = Convert.ToInt32(((DataRowView)degisen_parca.SelectedItem)["id"]);
string secili_idler = "";
foreach (var secili_itemler in arizasi.SelectedItems)
{
secili_idler = secili_idler + "-" + ((DataRowView)secili_itemler)["id"].ToString();
}
baglanti.sil_tur("degisen_parca", secili_id);
MessageBox.Show("Record Deleted - 2", "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (kut.SelectedItem != null)
{
secili_id = Convert.ToInt32(((DataRowView)kut.SelectedItem)["id"]);
baglanti.sil_tur("kut", secili_id);
MessageBox.Show("Record Deleted - 3", "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("No Select");
}
liste_yenilemesi();
}
private void Button1_Click(object sender, EventArgs e)
{
liste_yenilemesi();
}
private void Arizasi_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
<file_sep>/LetMeRepair_Comments/paket_ekle_duzenle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LetMeRepair_Comments
{
public partial class paket_ekle_duzenle : Form
{
public paket_ekle_duzenle()
{
InitializeComponent();
}
private void Paket_ekle_duzenle_Load(object sender, EventArgs e)
{
paketleri_listele();
ComboBox1_SelectedIndexChanged(null,null) ;
}
private void paketleri_listele()
{
DataTable degisen_parca_tum_db = baglanti.listele("paket", "0");
comboBox1.DataSource = degisen_parca_tum_db;
comboBox1.DisplayMember = "baslik";
/// ((DataRowView)ariza.SelectedItem)["id"].ToString();
if (comboBox1.Items.Count > 0) { comboBox1.SelectedIndex = 0; } else {}
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null )
{
textBox4.Text = ((DataRowView)comboBox1.SelectedItem)["baslik"].ToString();
label8.Text ="ID="+ ((DataRowView)comboBox1.SelectedItem)["id"].ToString();
update_panel.Visible = true;
}
else
{
update_panel.Visible = false;
}
}
private void Exit_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void Button2_Click(object sender, EventArgs e)
{
if (textBox2.Text.StartsWith(" ") || textBox2.Text.Replace(" ", "") == "" || textBox2.Text.Length <= 4)
{
MessageBox.Show(gecerli_baslik, "LetMeRepair - Mizer - Hatalı Başlık", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (baglanti.tekrar_sorgula("paket", textBox2.Text) == "Devam")
{
baglanti.Paket_ekle("paket",textBox2.Text,"","",0);
MessageBox.Show(kayit_eklendi, "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox4.Text = "";
paketleri_listele();
}
else if (baglanti.tekrar_sorgula("paket", textBox2.Text) == "Mevcut")
{
MessageBox.Show(ayni_basliktan, "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
if (textBox2.Text == "" || textBox2.Text == " " || textBox2.Text == " " || textBox2.Text.StartsWith(" "))
{
button2.Enabled = false;
}
else
{
button2.Enabled = true;
}
}
private void TextBox4_TextChanged(object sender, EventArgs e)
{
if (textBox4.Text == "" || textBox4.Text == " " || textBox4.Text == " " || textBox4.Text.StartsWith(" "))
{
button3.Enabled = false;
}
else
{
button3.Enabled = true;
}
}
private void Button3_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>/LetMeRepair_Comments/sablonlari_yonet.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LetMeRepair_Comments
{
public partial class sablonlari_yonet : Form
{
public sablonlari_yonet()
{
InitializeComponent();
}
private void Sablonlari_yonet_Load(object sender, EventArgs e)
{
paketleri_listele();
}
private void paketleri_listele()
{
DataTable degisen_parca_tum_db = baglanti.listele("paket_uyesi", "0");
comboBox1.DataSource = degisen_parca_tum_db;
comboBox1.DisplayMember = "baslik";
/// ((DataRowView)ariza.SelectedItem)["id"].ToString();
if (comboBox1.Items.Count > 0) { comboBox1.SelectedIndex = 0; } else { }
}
private void Button3_Click(object sender, EventArgs e)
{
if (textBox4.Text.StartsWith(" ") || textBox4.Text.Replace(" ", "") == "" || textBox4.Text.Length <= 3)
{
MessageBox.Show(gecerli_baslik, "LetMeRepair - Mizer - Hatalı Başlık", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if ("Devam" == baglanti.tekrar_sorgula("paket_uyesi", textBox4.Text))
{
if (baglanti.guncelle_tur("paket_uyesi", textBox4.Text, richTextBox1.Text, richTextBox2.Text, "", Convert.ToInt32(((DataRowView)comboBox1.SelectedItem)["id"].ToString())) == true)
{
MessageBox.Show("Successful Updated. - Güncelleme Başarılı");
paketleri_listele();
}
else
{
MessageBox.Show("Cannot Update - Güncellenemiyor.");
paketleri_listele();
}
}
else if (baglanti.tekrar_sorgula("paket_uyesi", textBox4.Text) == "Mevcut")
{
MessageBox.Show(ayni_basliktan, "LMR-Sirtuex-Mizer", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void Sil_Click(object sender, EventArgs e)
{
if (baglanti.sil_tur("paket_uyesi", Convert.ToInt32(((DataRowView)comboBox1.SelectedItem)["id"].ToString())) == true)
{
MessageBox.Show("Successful Deleted. - Silme Başarılı");
paketleri_listele();
}
else
{
MessageBox.Show("Cannot Deleted - Silinemiyor.");
paketleri_listele();
}
}
private void Exit_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null)
{
textBox4.Text = ((DataRowView)comboBox1.SelectedItem)["baslik"].ToString();
label8.Text = "ID=" + ((DataRowView)comboBox1.SelectedItem)["id"].ToString();
richTextBox1.Text= ((DataRowView)comboBox1.SelectedItem)["english"].ToString();
richTextBox2.Text = ((DataRowView)comboBox1.SelectedItem)["turkish"].ToString();
update_panel.Visible = true;
sil.Enabled = true;
}
else
{
sil.Enabled = false;
update_panel.Visible = false;
}
}
private void TextBox4_TextChanged(object sender, EventArgs e)
{
if (textBox4.Text == "" || textBox4.Text == " " || textBox4.Text == " " || textBox4.Text.StartsWith(" "))
{
button3.Enabled = false;
}
else
{
button3.Enabled = true;
}
}
}
}
<file_sep>/LetMeRepair_Comments/baglanti.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.Data;
namespace LetMeRepair_Comments
{
class baglanti
{
public static OleDbConnection con = new OleDbConnection("Provider = Microsoft.JET.OLEDB.4.0; Data Source = mizer_sirtuex_vt.mdb");
public static OleDbDataAdapter da;
public static OleDbCommand cmd = new OleDbCommand();
public static string tekrar_sorgula (string tur,string baslik)
{
string sorgu = "";
sorgu = "Select baslik from "+tur+" where baslik=@baslik";
cmd = new OleDbCommand(sorgu, con);
cmd.Parameters.AddWithValue("@baslik", baslik);
con.Open();
OleDbDataReader okuma = cmd.ExecuteReader();
if (okuma.Read())
{
con.Close();
return "Mevcut";
}
else
{
con.Close();
return "Devam";
}
}
public static Boolean ekle_tur(string tur,string baslik,string english, string turkish,string bagli_no)
{
/// try
/// {
string sorgu = "";
if (tur == "degisen_parca")
{
sorgu = "Insert into "+tur+ " (baslik,english,turkish,bagli_oldugu_ariza) values (@baslik,@english,@turkish,@bagli_oldugu_ariza)";
}
else
{
sorgu = "Insert into " + tur + " (baslik,english,turkish) values (@baslik,@english,@turkish)";
}
cmd = new OleDbCommand(sorgu, con);
cmd.Parameters.AddWithValue("@baslik", baslik);
cmd.Parameters.AddWithValue("@english", english);
cmd.Parameters.AddWithValue("@turkish", turkish);
cmd.Parameters.AddWithValue("@bagli_oldugu_ariza", bagli_no +"-");
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return true;
//// }
/* catch
{
return false;
}
*/
}
public static Boolean guncelle_tur(string tur, string baslik, string english, string turkish, string bagli_no,int id)
{
/// try
/// {
string sorgu = "";
if (tur == "degisen_parca")
{
sorgu = "UPDATE " + tur + " set baslik = @baslik,english = @english,turkish = @turkish,bagli_oldugu_ariza = @bagli_oldugu_ariza WHERE id ="+id;
}
else
{
sorgu = "update " + tur + " SET baslik = @baslik, english = @english, turkish = @turkish WHERE id ="+id;
}
cmd = new OleDbCommand(sorgu, con);
cmd.Parameters.AddWithValue("@baslik", baslik);
cmd.Parameters.AddWithValue("@english", english);
cmd.Parameters.AddWithValue("@turkish", turkish);
cmd.Parameters.AddWithValue("@bagli_oldugu_ariza", bagli_no + "-");
cmd.Parameters.AddWithValue("@id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return true;
//// }
/* catch
{
return false;
}
*/
}
public static Boolean sil_tur (string tur,int id)
{
string sorgu = "DELETE from " + tur + " WHERE id =" + id;
cmd = new OleDbCommand(sorgu, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return true;
}
public static DataTable listele(string tur,string degisen_parca_id)
{
string sorgu = "";
string data_bir = "";
DataTable datalar = new DataTable();
if (tur == "degisen_parca") { sorgu = "Select * from " + tur + " where bagli_oldugu_ariza LIKE '%"+degisen_parca_id+"%'"; }
else
{
sorgu = "Select * from " + tur + "";
}
cmd = new OleDbCommand(sorgu, con);
con.Open();
datalar.Load(cmd.ExecuteReader());
con.Close();
return datalar;
}
public static string baglanti_no_cekme(string ariza_baslik)
{
string sorgu = "";
sorgu = "Select id from ariza where baslik=@baslik";
string hafiza;
cmd = new OleDbCommand(sorgu, con);
cmd.Parameters.AddWithValue("@baslik", ariza_baslik);
con.Open();
OleDbDataReader okuma = cmd.ExecuteReader();
if (okuma.Read())
{
hafiza = okuma["id"].ToString();
con.Close();
return hafiza;
}
else
{
con.Close();
return "0";
}
}
public static int paket_id_cekme(string paket_ismi)
{
string sorgu = "";
sorgu = "Select id from paket where baslik=@baslik";
string hafiza;
cmd = new OleDbCommand(sorgu, con);
cmd.Parameters.AddWithValue("@baslik", paket_ismi);
con.Open();
OleDbDataReader okuma = cmd.ExecuteReader();
if (okuma.Read())
{
hafiza = okuma["id"].ToString();
con.Close();
return Convert.ToInt32(hafiza);
}
else
{
con.Close();
return 0;
}
}
public static Boolean Paket_ekle (string tur, string baslik, string turkish, string english,int bag)
{
string sorgu = "";
if (tur == "paket_uyesi")
{
sorgu = "Insert into " + tur + " (baslik,english,turkish,paket_id) values (@baslik,@english,@turkish,@paket_id)";
}
else
{
sorgu = "Insert into " + tur + " (baslik) values (@baslik)";
}
cmd = new OleDbCommand(sorgu, con);
cmd.Parameters.AddWithValue("@baslik", baslik);
cmd.Parameters.AddWithValue("@english", english);
cmd.Parameters.AddWithValue("@turkish", turkish);
cmd.Parameters.AddWithValue("@paket_id", bag );
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return true;
}
public static string comment_cek_Mizer(string tur, string dil,string baslik)
{
string sorgu = "";
sorgu = "Select * from " + tur + " where baslik=@baslik";
cmd = new OleDbCommand(sorgu, con);
cmd.Parameters.AddWithValue("@baslik", baslik);
con.Open();
OleDbDataReader okuma = cmd.ExecuteReader();
if (okuma.Read())
{
string okuma_degeri = okuma[dil].ToString();
con.Close();
return okuma_degeri;
}
else
{
con.Close();
return "";
}
}
}
}
<file_sep>/LetMeRepair_Comments/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LetMeRepair_Comments
{
public partial class anaform_sirtuex : Form
{
public anaform_sirtuex()
{
InitializeComponent();
}
private const int EM_SETCUEBANNER = 0x1501;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);
private void Ana_yorum_oluşturucu_motor()
{
string ariza_EN = "";
string ariza_TR = "";
string degisen_parca_EN = "";
string degisen_parca_TR = "";
string kut_EN = "";
string kut_TR = "";
foreach (var baslik in secili_ariza.Items)
{
ariza_EN = ariza_EN + baglanti.comment_cek_Mizer("ariza", "english", baslik.ToString()) + " ";
ariza_TR = ariza_TR + baglanti.comment_cek_Mizer("ariza", "turkish", baslik.ToString()) + " ";
}
foreach (var baslik in selici_degisen_parca.Items)
{
degisen_parca_EN = degisen_parca_EN + baglanti.comment_cek_Mizer("degisen_parca", "english", baslik.ToString()) + " ";
degisen_parca_TR = degisen_parca_TR + baglanti.comment_cek_Mizer("degisen_parca", "turkish", baslik.ToString()) +" ";
}
foreach (var baslik in secili_kut.Items)
{
kut_EN = kut_EN + baglanti.comment_cek_Mizer("kut", "english", baslik.ToString()) + " ";
kut_TR = kut_TR + baglanti.comment_cek_Mizer("kut", "turkish", baslik.ToString()) + " ";
}
richTextBox1.Text = ariza_EN + degisen_parca_EN + kut_EN;
richTextBox2.Text = ariza_TR + degisen_parca_TR + kut_TR;
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
using (ekle_sirtuex frm_ac = new ekle_sirtuex())
{
frm_ac.ShowDialog();
}
}
DataTable ariza_list = baglanti.listele("ariza", "0");
DataTable kut_list = baglanti.listele("kut", "0");
private void anaform_sirtuex_Load(object sender, EventArgs e)
{
if (Properties.Settings.Default.dil == "turkce")
{
toolStripComboBox1.SelectedIndex = 0;
}
else
{
toolStripComboBox1.SelectedIndex = 1;
}
dil_ayari_Cek();
if (Properties.Settings.Default.bag_kaldir == true)
{
tum_cozumler.Checked = true;
}
else
{ tum_cozumler.Checked = false; }
ariza.DataSource = ariza_list;
ariza.DisplayMember = "baslik";
ariza.ValueMember = "id";
ariza.Tag = "baslik";
degisen_parca.DisplayMember = "baslik";
degisen_parca.ValueMember = "id";
degisen_parca.Tag = "baslik";
kut.DataSource = kut_list;
kut.DisplayMember = "baslik";
kut.ValueMember = "id";
kut.Tag = "baslik";
if (tum_cozumler.Checked == true)
{
try
{
degisen_parca.DataSource = degisen_parca_tum_db;
}
catch
{ }
}
else
{
parca_bagli_ariza();
}
SendMessage(arama_ariza.Handle, EM_SETCUEBANNER, 0, "Search for Control/Defect");
SendMessage(arama_ariza.Handle, EM_SETCUEBANNER, 0, dil.dil_ayari_yap("arama_ariza"));
SendMessage(arama_parca.Handle, EM_SETCUEBANNER, 0, "Search for Solution/Montage");
SendMessage(arama_ariza.Handle, EM_SETCUEBANNER, 0, dil.dil_ayari_yap("arama_parca"));
SendMessage(arama_kut.Handle, EM_SETCUEBANNER, 0, "Search for Final Test/End");
SendMessage(arama_ariza.Handle, EM_SETCUEBANNER, 0, dil.dil_ayari_yap("arama_kut"));
}
private void ariza_SelectedIndexChanged(object sender, EventArgs e)
{
if (tum_cozumler.Checked == true)
{ }
else
{
parca_bagli_ariza();
}
}
private void parca_bagli_ariza()
{
if (ariza.SelectedItem != null)
{
degisen_parca.Enabled = true;
string baglanti_id = "0";
try
{
baglanti_id = ((DataRowView)ariza.SelectedItem)["id"].ToString();
degisen_parca.DataSource = baglanti.listele("degisen_parca", baglanti_id);
}
catch
{
}
}
else
{ degisen_parca.Enabled = false; }
}
private void generator_1_Click(object sender, EventArgs e)
{
secili_ariza.Items.Add(((DataRowView)ariza.SelectedItem)["baslik"].ToString());
selici_degisen_parca.Items.Add(((DataRowView)degisen_parca.SelectedItem)["baslik"].ToString());
secili_ariza.Refresh();
selici_degisen_parca.Refresh();
Ana_yorum_oluşturucu_motor();
button1.Enabled = true;
}
private void kut_generator_1_Click(object sender, EventArgs e)
{
string secili_baslik = ((DataRowView)kut.SelectedItem)["baslik"].ToString();
Boolean varmi = false;
foreach (var item in secili_kut.Items)
{
if (item.ToString() == secili_baslik)
{
MessageBox.Show("Küt zaten ekli");
varmi = true;
}
}
if (varmi == false)
{
secili_kut.Items.Add(((DataRowView)kut.SelectedItem)["baslik"].ToString());
button1.Enabled = true;
}
Ana_yorum_oluşturucu_motor();
}
private void button5_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
richTextBox2.Text = "";
secili_ariza.Items.Clear();
secili_kut.Items.Clear();
selici_degisen_parca.Items.Clear();
Ana_yorum_oluşturucu_motor();
button1.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (secili_ariza.SelectedItem != null)
{
secili_ariza.Items.RemoveAt(secili_ariza.SelectedIndex);
}
else if (selici_degisen_parca.SelectedItem != null)
{
selici_degisen_parca.Items.RemoveAt(selici_degisen_parca.SelectedIndex);
}
else if (secili_kut.SelectedItem != null)
{
secili_kut.Items.RemoveAt(secili_kut.SelectedIndex);
}
else { }
Ana_yorum_oluşturucu_motor();
}
catch{}
}
private void Secili_ariza_SelectedIndexChanged(object sender, EventArgs e)
{
if (secili_ariza.SelectedItem != null)
{
selici_degisen_parca.SelectedItem = null;
secili_kut.SelectedItem = null;
}
}
private void Selici_degisen_parca_SelectedIndexChanged(object sender, EventArgs e)
{
if (selici_degisen_parca.SelectedItem != null)
{
secili_ariza.SelectedItem = null;
secili_kut.SelectedItem = null;
}
}
private void Secili_kut_SelectedIndexChanged(object sender, EventArgs e)
{
if (secili_kut.SelectedItem != null)
{
secili_ariza.SelectedItem = null;
selici_degisen_parca.SelectedItem = null;
}
}
DataView dataView_ariza;
private void Arama_ariza_TextChanged(object sender, EventArgs e)
{
dataView_ariza = ariza_list.DefaultView;
dataView_ariza.RowFilter="baslik LIKE '%"+arama_ariza.Text+"%'";
if (dataView_ariza.Count != 0)
{ ariza.SelectedIndex = ariza.TopIndex; ariza.Refresh(); }
else
{ }
}
private void Koopyala_english_Click(object sender, EventArgs e)
{
Clipboard.SetText(richTextBox1.Text);
}
private void Kopyala_turkish_Click(object sender, EventArgs e)
{
Clipboard.SetText(richTextBox2.Text);
}
DataTable degisen_parca_tum_db = baglanti.listele("degisen_parca", "%");
private void Tum_cozumler_CheckedChanged(object sender, EventArgs e)
{
if (tum_cozumler.Checked==true)
{
arama_parca.Enabled = true;
degisen_parca.DataSource = degisen_parca_tum_db;
Properties.Settings.Default.bag_kaldir = true;
Properties.Settings.Default.Save();
}
else
{
arama_parca.Enabled = false;
parca_bagli_ariza();
Properties.Settings.Default.bag_kaldir = false;
Properties.Settings.Default.Save();
}
}
private void Button6_Click(object sender, EventArgs e)
{
using (duzenle_sirtuex frm_ac = new duzenle_sirtuex())
{
frm_ac.ShowDialog();
}
}
DataView cozum_ara;
private void Arama_parca_TextChanged(object sender, EventArgs e)
{
cozum_ara = degisen_parca_tum_db.DefaultView;
cozum_ara.RowFilter = "baslik LIKE '%" + arama_parca.Text + "%'";
if (cozum_ara.Count != 0)
{ degisen_parca.SelectedIndex = degisen_parca.TopIndex; ariza.Refresh(); }
else
{ }
}
private void Button7_Click(object sender, EventArgs e)
{
selici_degisen_parca.Items.Add(((DataRowView)degisen_parca.SelectedItem)["baslik"].ToString());
selici_degisen_parca.Refresh();
Ana_yorum_oluşturucu_motor();
button1.Enabled = true;
}
private void Button8_Click(object sender, EventArgs e)
{
secili_ariza.Items.Add(((DataRowView)ariza.SelectedItem)["baslik"].ToString());
secili_ariza.Refresh();
Ana_yorum_oluşturucu_motor();
button1.Enabled = true;
}
DataView kut_ara;
private void Arama_kut_TextChanged(object sender, EventArgs e)
{
kut_ara = kut_list.DefaultView;
kut_ara.RowFilter = "baslik LIKE '%" + arama_kut.Text + "%'";
if (cozum_ara.Count != 0)
{ kut.SelectedIndex = kut.TopIndex; ariza.Refresh(); }
else
{ }
}
private void Button3_Click_1(object sender, EventArgs e)
{
this.Hide();
using (sablon_ana frm_Ac = new sablon_ana())
{
frm_Ac.ShowDialog();
this.Show();
}
}
private void ToolStripMenuItem3_Click(object sender, EventArgs e)
{
using (mizer_about frm_ac = new mizer_about())
{
frm_ac.ShowDialog();
}
}
private void YeniEkleToolStripMenuItem_Click(object sender, EventArgs e)
{
using (ekle_sirtuex frm_ac = new ekle_sirtuex())
{
frm_ac.ShowDialog();
}
}
private void PaketModuToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Hide();
using (sablon_ana frm_Ac = new sablon_ana())
{
frm_Ac.ShowDialog();
this.Show();
}
}
private void DuzenleToolStripMenuItem_Click(object sender, EventArgs e)
{
using (duzenle_sirtuex frm_ac = new duzenle_sirtuex())
{
frm_ac.ShowDialog();
}
}
private void Button6_Click_1(object sender, EventArgs e)
{
using (paket_olarak_kaydet frm_ac = new paket_olarak_kaydet())
{
frm_ac.turkishcomment = richTextBox2.Text;
frm_ac.englishcomment = richTextBox1.Text;
frm_ac.ShowDialog();
}
}
}
}
<file_sep>/LetMeRepair_Comments/dil_ayarlari.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LetMeRepair_Comments
{
public class dil_ayarlari
{
// Mizer Windows Form Dil Seçeneği ayarlanması v.001 FrameWork
public string dil_ayari_yap(string duzenlenecek_yer)
{
string hata = "Dil?";
string result = string.Empty;
var lines = File.ReadAllLines(@"dil_ayarlari\"+Properties.Settings.Default.dil+".mizer");
foreach (var line in lines)
{
if (line.Contains(duzenlenecek_yer))
{
var text = line.Replace(duzenlenecek_yer + "=", "");
text = text.Trim();
text = text.Replace(@"""","");
result = text.Trim();
return result;
}
}
return hata;
}
}
}
<file_sep>/LetMeRepair_Comments/ekle_sirtuex.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Runtime.InteropServices;
namespace LetMeRepair_Comments
{
public partial class ekle_sirtuex : Form
{
public ekle_sirtuex()
{
InitializeComponent();
}
private const int EM_SETCUEBANNER = 0x1501;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);
private void button2_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
string baglanti_id;
DataTable ariza_list = baglanti.listele("ariza", "0");
private void button1_Click(object sender, EventArgs e)
{
if ( baslik.Text.StartsWith(" ") || baslik.Text.Replace(" ","") == "" || baslik.Text.Length <= 4 )
{
MessageBox.Show(gecerli_baslik, "LetMeRepair - Mizer - Hatalı Başlık", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (baglanti.tekrar_sorgula(secili_tur,baslik.Text) == "Devam")
{
if (secili_tur=="degisen_parca")
{
baglanti_id= baglanti.baglanti_no_cekme(arizasi.SelectedItem.ToString());
}
string secili_arizasilar = "";
string getirici = "";
for (int i = 0; arizasi.SelectedItems.Count > i ; i++)
{
getirici = ((DataRowView)arizasi.SelectedItems[i])["id"].ToString();
secili_arizasilar = secili_arizasilar + "-" + getirici;
}
baglanti.ekle_tur(secili_tur, baslik.Text, english_rich.Text, turkish_ric.Text, secili_arizasilar);
ariza_listesi_yenile();
MessageBox.Show(kayit_eklendi,"LMR-Sirtuex-Mizer",MessageBoxButtons.OK,MessageBoxIcon.Information);
temizle();
}
else if (baglanti.tekrar_sorgula(secili_tur, baslik.Text) == "Mevcut")
{
MessageBox.Show(ayni_basliktan,"LMR-Sirtuex-Mizer",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
private void temizle()
{
english_rich.Text = "";
turkish_ric.Text = "";
baslik.Text = "";
}
private void ariza_CheckedChanged(object sender, EventArgs e)
{
turu_sec_sorgusu();
}
string secili_tur;
string bagli_no;
private void turu_sec_sorgusu()
{
if (ariza.Checked == true)
{
panel_ariza_bagli.Visible = false;
panel_main.Visible = true;
secili_tur = "ariza";
textBox1_TextChanged(null, null);
}
else if (degisen_parca.Checked == true)
{
panel_ariza_bagli.Visible = true;
panel_main.Visible = true;
secili_tur = "degisen_parca";
textBox1_TextChanged(null, null);
}
else if (kut.Checked == true)
{
panel_ariza_bagli.Visible = false;
panel_main.Visible = true;
secili_tur = "kut";
textBox1_TextChanged(null, null);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (baslik.Text == "" || baslik.Text == " " || baslik.Text == " " || baslik.Text.StartsWith(" ") )
{
kydt.Enabled = false;
}
else
{
kydt.Enabled = true;
arizasi_SelectedIndexChanged(null, null);
}
}
private void degisen_parca_CheckedChanged(object sender, EventArgs e)
{
turu_sec_sorgusu();
}
private void kut_CheckedChanged(object sender, EventArgs e)
{
turu_sec_sorgusu();
}
private void ekle_sirtuex_Load(object sender, EventArgs e)
{
dil_ayari_Cek();
Blink();
secili_tur = "ariza";
bagli_no = "0";
baglanti_id = "0";
arizasi.DataSource = ariza_list;
arizasi.DisplayMember = "baslik";
arizasi.ValueMember = "id";
SendMessage(arama_parca.Handle, EM_SETCUEBANNER, 0, dil.dil_ayari_yap("arama_parca"));
SendMessage(baslik.Handle, EM_SETCUEBANNER, 0, dil.dil_ayari_yap("baslik_plchldr"));
}
private async void Blink()
{
while (true)
{
if (panel_main.Visible == true)
{
await Task.Delay(250);
label4.Visible = false;
}
else
{
label4.Visible = true;
await Task.Delay(500);
if (label4.ForeColor == Color.Red) { label4.ForeColor = Color.Green; } else { label4.ForeColor = Color.Red; }
}
}
}
private void ariza_listesi_yenile()
{
ariza_list = baglanti.listele("ariza", "0");
}
private void arizasi_SelectedIndexChanged(object sender, EventArgs e)
{
/* if (secili_tur == "degisen_parca")
{
if ( arizasi.SelectedItem == null)
{
kydt.Enabled = false;
}
else
{
kydt.Enabled = true;
}
}
*/
}
private void Button1_Click_1(object sender, EventArgs e)
{
english_rich.Text = "";
baslik.Text = "";
turkish_ric.Text = "";
panel_main.Visible = false;
}
}
}
| 38cc0feb953abfb86ac0134760f65aa02bc6db8f | [
"Markdown",
"C#"
] | 10 | Markdown | Mizer-Mi/LetMeRepair_Comments | 0ada8ef5dc3fb1176e0a8af8007fe4a8e7d5d039 | 1e74d05999c5d67c50d9c401f9e11f73914a5d61 |
refs/heads/main | <repo_name>Bo-Varvil/ElevatorSystemAdvancedJava<file_sep>/ElevatorSystemProject/src/CS4120/ucmo/LaffertyVarvil/ElevatorServer.java
package CS4120.ucmo.LaffertyVarvil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
public class ElevatorServer extends Application {
public static ArrayList<FloorTask> floorList = new ArrayList<>();
public static Elevator[] elevators = {new Elevator(5, 0),
new Elevator(5, 0), new Elevator(5, 0)};
public int count = 0;
private static TextArea ta = new TextArea();
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) {
Scene scene = new Scene(new ScrollPane(ta), 450, 200);
primaryStage.setTitle("ElevatorServer");
primaryStage.setScene(scene);
primaryStage.show();
new Thread(() -> {
try {
//create server socket on port 8000
ServerSocket serverSocket = new ServerSocket(8000);
ta.appendText("Server started at "
+ new Date() + '\n');
//wait for connections
while (true) {
ta.appendText("Waiting for floors..." + '\n');
//listen for a connection request and accept
Socket client = serverSocket.accept();
//increment number of clients
count++;
//show info that client connected.
Platform.runLater(() -> {
ta.appendText("floor " + count + " connected" + '\n');
});
//Create a ClientTask instance name might be "Client" + count
FloorTask floorTask = new FloorTask("Floor" + count, client);
//add ClientTask object to the ArrayList of ClientTask
floorList.add(floorTask);
//Replace *** with name of your ClientTask object
new Thread(floorTask).start();
}//while true
}//end try
catch (IOException ex) {
System.out.println(ex);
}
}).start();
}//end start
public static class ElevatorTask implements Runnable {
String clientName;
private Socket socket;
int requestedFloor;
public ElevatorTask(String n, Socket socket, int requestedFloor) {
this.clientName = n;
this.socket = socket;
this.requestedFloor = requestedFloor;
}
@Override
public void run() {
int[] currentFloors = new int[3];
for (int i = 0; i < 3; i++) {
currentFloors[i] = elevators[i].getCurrentFloor();
}
for (int i = 0; i < 3; i++) {
if (currentFloors[i] == requestedFloor) {
//open door
}
}
for (int i = 0; i < 3; i++) {
if (currentFloors[i] > requestedFloor) {
System.out.println(elevators[i].move(requestedFloor));
break;
}
}
for (int i = 0; i < 3; i++) {
if (currentFloors[i] < requestedFloor) {
System.out.println(elevators[i].move(requestedFloor));
break;
}
}
}
}
//class ClientTask implement Runnable
public static class FloorTask implements Runnable {
String clientName;
private Socket socket;
private ObjectInputStream fromClient;
private ObjectOutputStream toClient;
public FloorTask(String n, Socket socket) throws IOException {
//initialize propbert clientName
this.clientName = n;
//setup socket
this.socket = socket;
//setup io streams - the properties fromClient and toClient
fromClient = new ObjectInputStream(socket.getInputStream());
toClient = new ObjectOutputStream(socket.getOutputStream());
}
public void run() {
String request = "";
try {
toClient.writeObject("Hello you are on " + clientName + '\n');
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
//message will be concatenated with the two
//objects sent from the client. Use readObject(), two times
String clientRequest = (String) fromClient.readObject();
request = clientRequest;
//output to server to see what is happening.
ta.appendText("Received message: " + this.clientName + ": " + request + '\n');
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Thread thread = new Thread(new ElevatorTask(this.clientName, this.socket, Integer.parseInt(request)));
thread.start();
//broadcast message to all the clients
for (FloorTask f : floorList) {
//check to see if message is from the originator
if (f.clientName == this.clientName) {
try {
f.toClient.writeObject("Me requests: " + request + '\n');
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
f.toClient.writeObject(this.clientName + "requests: " + request + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
}
request = "";
}
}
}
}<file_sep>/ElevatorSystemProject/src/CS4120/ucmo/LaffertyVarvil/FloorClient.java
package CS4120.ucmo.LaffertyVarvil;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class FloorClient extends Application {
//Declare the variables for io stream for client to and from the server
private ObjectInputStream fromServer;
private ObjectOutputStream toServer;
//variables for the GUI
public static Label lblname;
TextField tfFloorRequest;
static TextArea ta;
public static void main(String[] args) throws IOException {
launch(args);
}
public void start(Stage primaryStage) throws IOException {
BorderPane bPane = new BorderPane();
GridPane gPane = new GridPane();
lblname = new Label();
tfFloorRequest = new TextField();
gPane.addRow(0, lblname);
gPane.addRow(1, new Label("Request a Floor: "), tfFloorRequest);
bPane.setTop(gPane);
ta = new TextArea();
bPane.setCenter(new ScrollPane(ta));
tfFloorRequest.setOnAction(new sendMessage());
Scene scene = new Scene(bPane, 450, 200);
primaryStage.setTitle("Floor Client");
primaryStage.setScene(scene);
primaryStage.show();
//connect to the server, create socket on port 8000
Socket socket = new Socket("localhost", 8000);
//set the io stream for this client, initialize to and from
toServer = new ObjectOutputStream(socket.getOutputStream());
fromServer = new ObjectInputStream(socket.getInputStream());
//update GUI to show progress.
Platform.runLater( () -> {
ta.appendText("Connected to Server\n");
});
//Create and initalize an instance of ReceiveTask. This
//is the task and thread this client will receive messages.
ReceiveTask receiveTask = new ReceiveTask(fromServer);
//Create thread and initialize with ReceiveTask instance above
Thread thread = new Thread(receiveTask);
//start the above thread
thread.start();
}
//public static void main(String[] args) throws IOException {
class sendMessage implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
//get the message and sender name
//String name = tfname.getText().trim();
String request = tfFloorRequest.getText().trim();
//create threads
//create instance of SendTask
SendTask sendTask = new SendTask(toServer, request);
//Create thread with SendTask instance above
Thread thread = new Thread(sendTask);
//Start the thread
thread.start();
}
}
private static class SendTask implements Runnable {
//Declare stream to write to the server
ObjectOutputStream toServer;
String request;
public SendTask(ObjectOutputStream toServer, String request){
this.toServer = toServer;
this.request = request;
}
public void run(){
try {
toServer.writeObject(request);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static class ReceiveTask implements Runnable{
//Declare stream to receive data from the server
ObjectInputStream fromServer;
public ReceiveTask(ObjectInputStream fromServer){
this.fromServer = fromServer;
}
@Override
public void run(){
try {
String floor = (String)fromServer.readObject();
Platform.runLater(()->{
lblname.setText(floor);
});
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
while (true){
String received = null;
try {
received = (String)fromServer.readObject();
String finalReceived = received;
Platform.runLater( () -> {
ta.appendText(finalReceived);
});
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(received);
}
}
}
}
| aca631f41063b5f70e88ca32fc2d96926ececbc1 | [
"Java"
] | 2 | Java | Bo-Varvil/ElevatorSystemAdvancedJava | d618e1325b46543bca69754bdfe39e341e18ae99 | fc66baffdb8290b67325d47528124395abe2e54f |
refs/heads/master | <file_sep># hdp_management
This is a python client that enables managing a hadoop stack.
manage_cluster.py allows to start/stop an entire cluster.
```
usage: manage_cluster.py [-h] [-u USER] [-p PASSWORD] [-l HOST] [-t PORT]
[-s PROTOCOL] [--unsafe] [-a {dry-run,stop,start}]
[-n CLUSTER]
[--log_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}]
[--http_debug]
optional arguments:
-h, --help show this help message and exit
-l HOST, --host HOST Server external host name
-t PORT, --port PORT Optional port number for Ambari server. Default is
'8080'. Provide empty string to not use port.
-s PROTOCOL, --protocol PROTOCOL
Optional support of SSL. Default protocol is 'http'
--unsafe Skip SSL certificate verification.
-a {dry-run,stop,start}, --action {dry-run,stop,start}
Script action: <dry-run>,<stop>,<start>
-n CLUSTER, --cluster CLUSTER
Name given to cluster. Ex: 'c1'
--log_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
Set the logging level
--http_debug turn on http debug level
login_options_group:
-u USER, --user USER Optional user ID to use for authentication. Default is
'admin'
-p PASSWORD, --password PASSWORD
Optional password to use for authentication. Default
is '<PASSWORD>'
```
## Usage
Example1
```
./hdp_management/manage_cluster.py -l master -u admin -p admin -n mytestcluster -a start
```
starts a cluster named "mytestcluster" , ambari-server API is running on host "master", port "8080" (default ), in http mode (default),
ambari admin user is "admin", related password is "<PASSWORD>"
Example2
```
./hdp_management/manage_cluster.py -l master -t 8443 -s https --unsafe -u admin -p admin -n mytestcluster -a stop
```
stops a cluster named "mytestcluster" , ambari-server API is running on host "master", port "8443" (default ), in https mode, ignore ssl verification
ambari admin user is "admin", related password is "<PASSWORD>"
Example0
```
./hdp_management/manage_cluster.py -l master -u admin -p admin -n mytestcluster -a dry-run
```
a dry-run that tests access to ambari and provided cluster is ok
./hdp_management/check_services.py -l 10.0.0.21 -n mytestcluster2 -a check_service<file_sep>import logging
def get_module_logger(mod_name):
logger = logging.getLogger(mod_name)
handler = logging.StreamHandler()
# formatter = logging.Formatter(
# '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
formatter = logging.Formatter(
'%(asctime)s %(levelname)-6s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# NOTSET does not mean "pass all messages through", it means "inherit the log level from the parent logger"
logger.setLevel(logging.NOTSET)
return logger
<file_sep>HTTP_PROTOCOL = 'http'
HTTPS_PROTOCOL = 'https'
SET_ACTION = 'set'
GET_ACTION = 'get'
DELETE_ACTION = 'delete'
GET_REQUEST_TYPE = 'GET'
PUT_REQUEST_TYPE = 'PUT'
POST_REQUEST_TYPE= 'POST'
CLUSTERS = 'Clusters'
DESIRED_CONFIGS = 'desired_configs'
CLUSTERS_URL = '/api/v1/clusters/{0}'
DESIRED_CONFIGS_URL = CLUSTERS_URL + '?fields=Clusters/desired_configs'
CONFIGURATION_URL = CLUSTERS_URL + '/configurations?type={1}&tag={2}'
SERVICES_URL = CLUSTERS_URL + '/services'
SERVICE_URL = SERVICES_URL + "/{1}"
REQUESTS_URL = CLUSTERS_URL + '/requests'
MAINTENANCE_MODE_ON="ON"
MAINTENANCE_MODE_OFF="OFF"
START_CLUSTER = "start"
STOP_CLUSTER = "stop"
DRY_RUN="dry-run"
RUN_SERVICE_CHECK = "check_service"
LIST_SERVICES = ["SMARTSENSE", "ZEPPELIN", "AMBARI_METRICS","KNOX","ATLAS","RANGER","KAFKA", "OOZIE", "HIVE", "HBASE", "SPARK", "SPARK2", "MAPREDUCE2", "YARN", "HDFS", "LOGSEARCH", "AMBARI_INFRA", "STORM", "ZOOKEEPER", "HUE"]
REQUEST_URL = CLUSTERS_URL +"/requests/{1}"
REQUEST_POSSIBLE_FINAL_STATUSES = ["ABORTED", "FAILED", "COMPLETED", "TIMEOUT"]
<file_sep># Confirm the Agent hosts are registered with the Server.
export AMBARI_USER=admin
export AMBARI_PASSWD=<PASSWORD>
export AMBARI_HOST=$(cat /etc/ambari-agent/conf/ambari-agent.ini | grep ^hostname | head -1 | cut -f2 -d= | xargs)
# [[ ! -z $(cat /etc/ambari-server/conf/ambari.properties | grep api.ssl=true) ]] && ssl_enabled="true"
ssl_enabled="false"
if [[ "$ssl_enabled" == "false" ]] ; then
WEB_PROTOCOL="http"
AMBARI_PORT=8080
else
WEB_PROTOCOL="https"
# AMBARI_PORT=$(cat /etc/ambari-server/conf/ambari.propertie | grep client.api.ssl.port| cut -f2 -d= | xargs)
AMBARI_PORT=8443
fi
export WEB_PROTOCOL
export AMBARI_PORT
export AMBARI_CREDS="$AMBARI_USER:$AMBARI_PASSWD"
export AMBARI_URLBASE="${WEB_PROTOCOL}://${AMBARI_HOST}:${AMBARI_PORT}/api/v1/clusters"
## -k, --insecure Allow connections to SSL sites without cert verif
export CLUSTER_NAME="$(curl -ik -u ${AMBARI_CREDS} -X GET -H 'X-Requested-By:ambari' $AMBARI_URLBASE | sed -n 's/.*"cluster_name" : "\([^\"]*\)".*/\1/p')"
echo $CLUSTER_NAME
export AMBARI_URLBASE=$AMBARI_URLBASE/$CLUSTER_NAME
# check ambari-server is up , if auth succeeds Apache license information is displayed.
curl -ik -u ${AMBARI_USER}:${AMBARI_PASSWD} -X GET -H 'X-Requested-By:ambari' "${WEB_PROTOCOL}://${AMBARI_HOST}:${AMBARI_PORT}"
## get services
curl -ik -u $AMBARI_CREDS -X GET -H 'X-Requested-By:ambari' $AMBARI_URLBASE/services/
# get service state
curl -ik -u $AMBARI_CREDS -X GET -H 'X-Requested-By:ambari' $AMBARI_URLBASE/services/ZOOKEEPER?fields=ServiceInfo/state
# service_name="ZOOKEEPER"
service_name="SMARTSENSE"
#start service
curl -ik -u $AMBARI_CREDS -X PUT -H 'X-Requested-By:ambari' -d '{ "RequestInfo": {"context" :"Start service ZOOKEEPER via REST"}, "Body": {"ServiceInfo": {"state": "STARTED"}}}' $AMBARI_URLBASE/services/${service_name}
# stop service
curl -ik -u $AMBARI_CREDS -X PUT -H 'X-Requested-By:ambari' -d '{ "RequestInfo": {"context" :"Stop service ZOOKEEPER via REST"}, "Body": {"ServiceInfo": {"state": "INSTALLED"}}}' $AMBARI_URLBASE/services/${service_name}
# stop service (returns request id )
request_id=$(curl -k -u $AMBARI_CREDS -X PUT -H 'X-Requested-By:ambari' -d '{ "RequestInfo": {"context" :"Stop service via REST"}, "Body": {"ServiceInfo": {"state": "INSTALLED"}}}' $AMBARI_URLBASE/services/${service_name} | python -c "import json, sys; print(json.loads(sys.stdin.read())['Requests']['id']);" )
echo $request_id
# get request status by request id
request_id=122
curl -ik -u $AMBARI_CREDS -X GET -H 'X-Requested-By:ambari' $AMBARI_URLBASE/requests/$request_id
# poll request_id status
while true; do
curl -k -u $AMBARI_CREDS -X GET -H 'X-Requested-By:ambari' $AMBARI_URLBASE/requests/$request_id | python -c "import json, sys; print(json.loads(sys.stdin.read())['Requests']['request_status']);"
sleep 5
done
# set maintenance state
curl -ik -u $AMBARI_CREDS -X PUT -H 'X-Requested-By:ambari' -d '{"RequestInfo":{"context":"Turn On Maintenance Mode for HDFS"},"Body":{"ServiceInfo":{"maintenance_state":"ON"}}}' $AMBARI_URLBASE/services/HDFS
# get maintenance state
curl -ik -u $AMBARI_CREDS -X GET -H 'X-Requested-By:ambari' $AMBARI_URLBASE/services/HDFS
# get client config
config_type="hdfs-site"
config_type="slider-client"
curl -ik -u $AMBARI_CREDS -X GET -H 'X-Requested-By:ambari' "$AMBARI_URLBASE/configurations?type=$config_type&tag=TOPOLOGY_RESOLVED"
#The @- part tells it to read from stdin
# The @payload part tells it to read from file named payload
# run service check for ZOOK
curl -ik -u $AMBARI_CREDS -H 'X-Requested-By:ambari' -X POST -d '{"RequestInfo":{"context":"ZooKeeper Service Check","command":"ZOOKEEPER_QUORUM_SERVICE_CHECK"},"Requests/resource_filters":[{"service_name":"ZOOKEEPER"}]}' "$AMBARI_URLBASE/requests"
# run service check for HDFS
curl -ik -u $AMBARI_CREDS -H 'X-Requested-By:ambari' -X POST -d '{"RequestInfo":{"context":"HDFS Service Check","command":"HDFS_SERVICE_CHECK"},"Requests/resource_filters":[{"service_name":"HDFS"}]}' "$AMBARI_URLBASE/requests"
curl -i -s -k -X $'POST' \
-H $'Accept-Encoding: gzip, deflate' -H $'Content-Length: 133' -H $'X-Requested-By: ambari' -H $'Connection: close' -H $'User-Agent: Python-urllib/2.7' -H $'Host: 10.0.0.21:8080' -H $'Content-Type: application/x-www-form-urlencoded' -H $'Authorization: Basic YWRtaW46YWRtaW4=' \
--data-binary $'{\"RequestInfo\":{\"context\":\"HDFS Service Check\",\"command\":\"HDFS_SERVICE_CHECK\"},\"Requests/resource_filters\":[{\"service_name\":\"HDFS\"}]}' \
$'http://10.0.0.21:8080/api/v1/clusters/mytestcluster/requests'
'{"RequestInfo":{"context":"HDFS Service Check","command":"HDFS_SERVICE_CHECK"},"Requests/resource_filters":[{"service_name":"HDFS"}]}'
{"RequestInfo": {"command": "HDFS_SERVICE_CHECK", "context": "HDFS Service Check via REST"}, "Requests/resource_filters": [{"service_name": "HDFS"}]}'<file_sep>#!/usr/bin/env python
import argparse
import urllib2
import base64
import json
import ssl
import sys
from utilities.logger_util import get_module_logger
import logging
# from retrying import retry
import time
from ambari.ambari_api import *
from ambari.CONST import *
import httplib
# print(sys.path)
logging.getLogger().setLevel("INFO")
## __name__ : the name of the module
logger = get_module_logger(__name__)
def service_check_gen_payload(service_name):
command=service_name
if service_name == "ZOOKEEPER":
# https://community.hortonworks.com/articles/11852/ambari-api-run-all-service-checks-bulk.html
command = "ZOOKEEPER_QUORUM"
service_check_payload = {
"RequestInfo": {
"context": "{0} Service Check via REST".format(service_name),
"command": "{0}_SERVICE_CHECK".format(command)
},
"Requests/resource_filters": [
{
"service_name": "{0}".format(service_name)
}
]
}
return json.dumps(service_check_payload)
def run_service_check(cluster,accessor,service_name):
"""
return : returns the service_check result final status which could be in ["ABORTED","FAILED","COMPLETED","TIMEOUT"]
"""
logger.info("about to run service_check on service {0} ".format(service_name))
payload = service_check_gen_payload(service_name)
response_body = json.loads(accessor(REQUESTS_URL.format(
cluster), POST_REQUEST_TYPE, payload))
request_id = response_body['Requests']['id']
request_status= get_request_status(cluster, accessor, request_id=request_id)
return request_status
def run_all_service_check(cluster, accessor):
list_services = list_all_services(cluster,accessor)
for service_name in LIST_SERVICES[::-1]:
if service_name in list_services:
request_status = run_service_check(cluster, accessor, service_name)
if request_status in ["ABORTED", "FAILED"]:
logger.error("Request_type: run service_check on service {0} request_status {1}".format(service_name,request_status) )
return
def main():
parser = argparse.ArgumentParser()
login_options_group = parser.add_argument_group('login_options_group')
login_options_group.add_argument("-u", "--user", dest="user", default="admin",
help="Optional user ID to use for authentication. Default is 'admin'")
login_options_group.add_argument("-p", "--password", dest="password", default="<PASSWORD>",
help="Optional password to use for authentication. Default is '<PASSWORD>'")
# login_options_group.add_argument("-e", "--credentials-file", dest="credentials_file",
# help="Optional file with user credentials separated by new line.")
parser.add_argument("-l", "--host", dest="host",
help="Server external host name")
parser.add_argument("-t", "--port", dest="port", default="8080",
help="Optional port number for Ambari server. Default is '8080'. Provide empty string to not use port.")
parser.add_argument("-s", "--protocol", dest="protocol", default="http",
help="Optional support of SSL. Default protocol is 'http'")
parser.add_argument("--unsafe", action="store_true",
dest="unsafe", help="Skip SSL certificate verification.")
parser.add_argument("-a", "--action", dest="action", choices=['dry-run', 'stop', 'start', 'check_service'],
help="Script action: <dry-run>,<stop>,<start>")
parser.add_argument("-n", "--cluster", dest="cluster",
help="Name given to cluster. Ex: 'c1'")
parser.add_argument("--log_level", dest="logLevel", choices=[
'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help="Set the logging level")
parser.add_argument("--http_debug", action="store_true",
dest="http_debug", help="turn on http debug level")
# will print a namespace Object with the attributes
args = parser.parse_args()
if None in [args.action, args.host, args.cluster]:
parser.error("One of required arguments is not passed")
host = args.host
port = args.port
protocol = args.protocol
cluster = args.cluster
action = args.action
user = args.user
password = <PASSWORD>.password
#options without default value
if args.logLevel:
logging.getLogger().setLevel(args.logLevel)
http_dbg_level = 0
if args.http_debug:
http_dbg_level = 1
accessor = api_accessor(host, user, password,
protocol, port, http_debug_level=http_dbg_level)
# logging_tree.printout()
if action == RUN_SERVICE_CHECK:
run_all_service_check(cluster, accessor)
# run_service_check(cluster, accessor, "YARN")
# start_service_V2(cluster,accessor,"YARN")
else:
parser.error(" invalid action arg ")
if __name__ == "__main__":
try:
sys.exit(main())
except (KeyboardInterrupt):
print("\nAborting ... Keyboard Interrupt.")
sys.exit(1)
<file_sep>#!/usr/bin/env python
import argparse
import urllib2
import base64
import json
import ssl
import sys
from utilities.logger_util import get_module_logger
import logging
# from retrying import retry
import time
from ambari.ambari_api import *
from ambari.CONST import *
import httplib
logging.getLogger().setLevel("INFO")
## __name__ : the name of the module
logger =get_module_logger(__name__)
MIN_PYTHON_VERSION = (2, 7)
used_python_version = (sys.version_info[0], sys.version_info[1])
if used_python_version < MIN_PYTHON_VERSION:
print("This script requires Python version >= {0}.{1}").format(
MIN_PYTHON_VERSION[0], MIN_PYTHON_VERSION[1])
print ("You are using Python version {0}.{1}".format(
used_python_version[0], used_python_version[1]))
sys.exit(1)
def dry_run(cluster, accessor):
"""
this dry-run checks if ambari-server is up and reachable
print the URL
"""
logger.info("check access to ambari")
try:
accessor("")
except Exception :
logger.error("check access to ambari: Failed")
raise
logger.info("check access to ambari: Succeded")
logger.info("check access to cluster {0}".format(cluster))
try:
accessor(CLUSTERS_URL.format(cluster))
except Exception:
logger.error("check access to cluster {0}: Failed".format(cluster))
raise
logger.info("check access to cluster {0}: Succeded".format(cluster))
def set_service_to_state(cluster, accessor, service_name, desired_state):
service_state = get_service_state(cluster, accessor, service_name)
if service_state == "UNKNOWN":
logger.error("service {0} state is {1}, aborting, please fix this before moving on".format(
service_name, service_state))
raise Error
elif service_state == desired_state:
logger.info("service {0} state is already {1} , skipping ".format(
service_name, service_state))
return
elif service_state != "INSTALLED" and service_state != "STARTED":
logger.info("service {0} state is {1} , skipping ".format(
service_name, service_state))
return
else:
### when using APIs, you need to turn off maintenance mode on the component before you send stop or start requests to it.
set_maintenance_mode(
cluster, accessor, service_name, MAINTENANCE_MODE_OFF)
logger.info("service {0} state is {1}".format(
service_name, service_state))
request_body = '{{ "RequestInfo": {{"context" :"set service {0} to {1} via REST"}},"Body": {{"ServiceInfo": {{"state": "{1}" }} }} }}'.format(
service_name, desired_state)
response_body = json.loads(accessor(SERVICE_URL.format(
cluster, service_name), PUT_REQUEST_TYPE, request_body))
request_id = response_body['Requests']['id']
"""
TODO check that request is accepted before moving on
"""
# as of Ambari 2.6.2,and for each service, the timeouts on differents tasks are placed under
# /var/lib/ambari-server/resources/common-services/<SERVICE_NAME>/0.12.0.2.0/metainfo.xml
# Some tasks are not declared and don't have a timeout assigned, in this case the value of agent.task.tiemout param
# under ambari-server properties is inherited
request_status = get_request_status(cluster, accessor, request_id=request_id)
if request_status == "COMPLETED":
logger.info("Request_type: set service {0} to state {1}, id_request {2}, status: {3} ".format(
service_name, desired_state, request_id, request_status))
if desired_state == "INSTALLED":
set_maintenance_mode(cluster, accessor, service_name, MAINTENANCE_MODE_ON)
# service_state = get_service_state(cluster, accessor, service_name)
else:
logger.error("Request_type: set service {0} to state {1}, id_request {2}, status: {3} ".format(
service_name, desired_state, request_id, request_status))
raise Error
def start_all_services(cluster, accessor):
""" the method follows this order in stooping hdp services
https://docs.hortonworks.com/HDPDocuments/HDP2/HDP-2.4.0/bk_HDP_Reference_Guide/content/stopping_hdp_services.html
"""
logger.info("about to start all services of cluster {0} ".format(cluster))
list_services = list_all_services(cluster, accessor)
flag=True
for service_name in LIST_SERVICES[::-1]:
if service_name in list_services:
try:
# start_service(cluster, accessor, service_name)
set_service_to_state(
cluster, accessor, service_name, "STARTED")
except Error as exc:
message = "An exception of type {0} occurred. Arguments:\n{1!r}".format(type(exc).__name__, exc.args)
logger.error(message)
flag=False
break
if flag :
logger.info("All services of cluster {0} started ".format(cluster))
else :
logger.error(
"error starting all services of cluster {0} ".format(cluster))
return 1
def stop_all_services(cluster, accessor):
""" the method follows this order in stooping hdp services
https://docs.hortonworks.com/HDPDocuments/HDP2/HDP-2.4.0/bk_HDP_Reference_Guide/content/stopping_hdp_services.html"""
logger.info("about to stop all services of cluster {0} ".format(cluster))
list_services = list_all_services(cluster, accessor)
flag=True
for service_name in LIST_SERVICES:
if service_name in list_services:
try:
set_service_to_state(
cluster, accessor, service_name, "INSTALLED")
except Error as exc:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(exc).__name__, exc.args)
logger.error(message)
flag=False
break
if flag :
logger.info("All services of cluster {0} stopped ".format(cluster))
else :
logger.error(
"error stopping all services of cluster {0} ".format(cluster))
return 1
def main():
parser = argparse.ArgumentParser()
login_options_group = parser.add_argument_group('login_options_group')
login_options_group.add_argument("-u", "--user", dest="user", default="admin",
help="Optional user ID to use for authentication. Default is 'admin'")
login_options_group.add_argument("-p", "--password", dest="password", default="<PASSWORD>",
help="Optional password to use for authentication. Default is '<PASSWORD>'")
# login_options_group.add_argument("-e", "--credentials-file", dest="credentials_file",
# help="Optional file with user credentials separated by new line.")
parser.add_argument("-l", "--host", dest="host",
help="Server external host name")
parser.add_argument("-t", "--port", dest="port", default="8080",
help="Optional port number for Ambari server. Default is '8080'. Provide empty string to not use port.")
parser.add_argument("-s", "--protocol", dest="protocol", default="http",
help="Optional support of SSL. Default protocol is 'http'")
parser.add_argument("--unsafe", action="store_true",
dest="unsafe", help="Skip SSL certificate verification.")
parser.add_argument("-a", "--action", dest="action", choices=['dry-run', 'stop', 'start'],
help="Script action: <dry-run>,<stop>,<start>")
parser.add_argument("-n", "--cluster", dest="cluster",
help="Name given to cluster. Ex: 'c1'")
parser.add_argument("--log_level", dest="logLevel", choices=[
'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help="Set the logging level")
parser.add_argument("--http_debug", action="store_true", dest="http_debug", help="turn on http debug level")
# will print a namespace Object with the attributes
args = parser.parse_args()
if None in [args.action, args.host, args.cluster]:
parser.error("One of required arguments is not passed")
host = args.host
port = args.port
protocol = args.protocol
cluster = args.cluster
action = args.action
user = args.user
password = <PASSWORD>
#options without default value
if args.logLevel:
logging.getLogger().setLevel(args.logLevel)
http_dbg_level=0
if args.http_debug:
http_dbg_level=1
accessor = api_accessor(host, user, password,
protocol, port, http_debug_level=http_dbg_level)
# logging_tree.printout()
if action == START_CLUSTER:
start_all_services(cluster, accessor)
# start_service_V2(cluster,accessor,"YARN")
elif action == STOP_CLUSTER:
stop_all_services(cluster, accessor)
elif action == DRY_RUN:
dry_run(cluster,accessor)
else:
parser.error(" invalid action arg ")
if __name__ == "__main__":
try:
sys.exit(main())
except (KeyboardInterrupt):
print("\nAborting ... Keyboard Interrupt.")
sys.exit(1)
<file_sep># coding=utf-8
import time
import random
from logger_util import get_module_logger
import logging
# import sys
# print(sys.path)
logging.getLogger().setLevel("INFO")
## __name__ : the name of the module
logger = get_module_logger(__name__)
REQUEST_POSSIBLE_FINAL_STATUSES = ["ABORTED", "FAILED", "COMPLETED", "TIMEOUT"]
def retry_exp_backoff_on_predicate(cond=lambda: False):
def decorator(func):
metrics = {"nc": 0, "_sleep_time": 2}
def wrapper(*args, **kwargs):
while True:
request_status = func(*args, **kwargs)
logger.info(
"Request id {0} status: {1} ".format(kwargs['request_id'], request_status))
metrics['nc'] += 1
# if request_status in ["ABORTED", "FAILED", "COMPLETED", "TIMEOUT"]:
if cond(request_status) == True:
return
else:
time.sleep(metrics['_sleep_time'])
metrics['_sleep_time'] = metrics['_sleep_time']*2
return func(*args, **kwargs)
return wrapper
return decorator
# # @retry_exp_backoff(3)
# @retry_exp_backoff_on_predicate(4, lambda x: x in REQUEST_POSSIBLE_FINAL_STATUSES)
# def get_status(request_id):
# list_status = list(REQUEST_POSSIBLE_FINAL_STATUSES)
# list_status.extend([x * 2 for x in range(100)])
# res = list_status[random.randint(0, len(list_status))]
# print res
# return res
# get_status(10)
def retry_const_backoff_on_predicate(backoff=15, predicate=lambda: False):
def decorator(func):
metrics = {"nc": 0, "_sleep_time": backoff}
def wrapper(*args, **kwargs):
while True:
request_status = func(*args, **kwargs)
logger.info(
"Request id {0} status: {1} ".format(kwargs['request_id'], request_status))
metrics['nc'] += 1
# if request_status in ["ABORTED", "FAILED", "COMPLETED", "TIMEOUT"]:
if predicate(request_status) == True:
return request_status
else:
time.sleep(metrics['_sleep_time'])
#return func(*args, **kwargs)
return wrapper
return decorator
<file_sep>#!/usr/bin/env python
import httplib
import urllib2
import base64
import json
import ssl
import sys
from utilities.logger_util import get_module_logger
# from retrying import retry
import time
from CONST import *
from utilities.decorators import *
class Error(Exception):
"""Base class for exceptions in this module."""
pass
## __name__ : the name of the module
logger = get_module_logger(__name__)
def api_accessor(host, login, password, protocol, port, unsafe=None, http_debug_level=0):
def do_request(api_url, request_type=GET_REQUEST_TYPE, request_body=''):
try:
url = '{0}://{1}:{2}{3}'.format(protocol, host, port, api_url)
admin_auth = base64.encodestring(
'%s:%s' % (login, password)).replace('\n', '')
request = urllib2.Request(url)
request.add_header('Authorization', 'Basic %s' % admin_auth)
request.add_header('X-Requested-By', 'ambari')
request.add_data(request_body)
"""urlib2 doesn't have a method to set the http method
it uses the get_method method to pick the right http method
the default get_method method return value is based on the data content
here we override the get_method function to return the request type we want to have"""
request.get_method = lambda: request_type
ctx=None
if unsafe:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
httpHandler = urllib2.HTTPHandler()
httpHandler.set_http_debuglevel(http_debug_level)
httpsHandler = urllib2.HTTPSHandler(ctx)
#Instead of using urllib2.urlopen, create an opener, and pass the HTTPHandler
#and any other handlers... to it.
opener = urllib2.build_opener(
httpHandler, httpsHandler)
# proxyHandler = urllib2.ProxyHandler({
# 'http': '127.0.0.1:8099',
# 'https': '127.0.0.1:8099'
# })
# opener.add_handler(proxyHandler)
urllib2.install_opener(opener)
response = opener.open(request)
response_body= response.read()
except urllib2.HTTPError, e:
logger.debug(e.read())
raise
except urllib2.URLError:
raise
except httplib.HTTPException:
raise
except Exception:
raise
else:
return response_body
return do_request
def list_all_services(cluster, accessor):
response = json.loads(
accessor(SERVICES_URL.format(cluster), GET_REQUEST_TYPE))
list_services = []
for service in response['items']:
list_services.append(service['ServiceInfo']["service_name"])
return list_services
def get_service_state(cluster, accessor, service_name):
response = accessor(SERVICE_URL.format(
cluster, service_name), GET_REQUEST_TYPE)
service_node = json.loads(response)
return service_node['ServiceInfo']['state']
def get_maintenance_mode(cluster, accessor, service_name):
response = accessor(SERVICE_URL.format(
cluster, service_name), GET_REQUEST_TYPE)
service_node = json.loads(response)
return service_node['ServiceInfo']['maintenance_state']
# @retry_exp_backoff_on_predicate(lambda x: x in REQUEST_POSSIBLE_FINAL_STATUSES)
@retry_const_backoff_on_predicate(predicate=lambda x: x in REQUEST_POSSIBLE_FINAL_STATUSES)
def get_request_status(cluster, accessor, request_id=0):
response = json.loads(
accessor(REQUEST_URL.format(cluster, request_id), GET_REQUEST_TYPE))
return response['Requests']['request_status']
def set_maintenance_mode(cluster, accessor, service_name, desired_mode):
logger.debug("about to set service {0} to maintenance mode {1}".format(
service_name, desired_mode))
if desired_mode not in [MAINTENANCE_MODE_ON, MAINTENANCE_MODE_OFF]:
raise Error("maintenance mode must be either {0} or {1}".format(
MAINTENANCE_MODE_ON, MAINTENANCE_MODE_OFF))
maintenance_mode = get_maintenance_mode(cluster, accessor, service_name)
if desired_mode == maintenance_mode:
logger.debug("service {0} maintenance mode is already {1} , skipping ".format(
service_name, desired_mode))
return
request_body = '{{"RequestInfo":{{"context":"Turn On Maintenance Mode for {0} }}"}},"Body":{{"ServiceInfo":{{"maintenance_state":"{1}" }} }} }}'.format(
service_name, desired_mode)
accessor(SERVICE_URL.format(cluster, service_name),
PUT_REQUEST_TYPE, request_body)
"""
TODO: replace retry by a derorateur backoff
"""
tries = 0
MAX_RETRIES = 4
TIMEOUT = 15
maintenance_mode = None
while True:
time.sleep(TIMEOUT)
maintenance_mode = get_maintenance_mode(
cluster, accessor, service_name)
if maintenance_mode != desired_mode and tries < MAX_RETRIES:
logger.debug("service {0} maintenance mode is {1} ".format(
service_name, maintenance_mode))
tries += 1
continue
else:
break
if maintenance_mode == desired_mode:
logger.debug("Setting maintenance mode for service {0} to {1} is successful".format(service_name, desired_mode))
else:
logger.error(("SETTING MAINTENANCE MODE FOR SERVICE {0} to {1} is failed ".format(
service_name, desired_mode)))
raise Error
<file_sep>#!/usr/bin/env python
import argparse
import urllib2
import base64
import json
import ssl
import sys
from utilities.logger_util import get_module_logger
import logging
# from retrying import retry
import time
from ambari.ambari_api import *
from ambari.CONST import *
import httplib
import os
PROPERTIES = 'properties'
ATTRIBUTES = 'properties_attributes'
CLUSTERS = 'Clusters'
DESIRED_CONFIGS = 'desired_configs'
SERVICE_CONFIG_NOTE = 'service_config_version_note'
TYPE = 'type'
TAG = 'tag'
ITEMS = 'items'
TAG_PREFIX = 'version'
CLUSTERS_URL = '/api/v1/clusters/{0}'
DESIRED_CONFIGS_URL = CLUSTERS_URL + '?fields=Clusters/desired_configs'
CONFIGURATION_URL = CLUSTERS_URL + '/configurations?type={1}&tag={2}'
logging.getLogger().setLevel("INFO")
## __name__ : the name of the module
logger =get_module_logger(__name__)
MIN_PYTHON_VERSION=(2,7)
used_python_version = (sys.version_info[0], sys.version_info[1])
if used_python_version < MIN_PYTHON_VERSION:
print("This script requires Python version >= {0}.{1}".format(
MIN_PYTHON_VERSION[0], MIN_PYTHON_VERSION[1]))
sys.exit(1)
def dry_run(cluster, accessor):
"""
this dry-run checks if ambari-server is up and reachable
print the URL
"""
logger.info("check access to ambari")
try:
accessor("")
except Exception :
logger.error("check access to ambari: Failed")
raise
logger.info("check access to ambari: Succeded")
logger.info("check access to cluster {0}".format(cluster))
try:
accessor(CLUSTERS_URL.format(cluster))
except Exception:
logger.error("check access to cluster {0}: Failed".format(cluster))
raise
logger.info("check access to cluster {0}: Succeded".format(cluster))
def get_all_current_configs(cluster, accessor):
config_types = get_all_config_types(cluster, accessor)
for config_type in config_types:
# if config_type != "slider-client":
# continue
## filename is the same as the name of the config_type
filename = config_type
print filename
output = output_to_file(filename)
try:
get_config(cluster, config_type, accessor, output)
except Error as exc:
message = "An exception of type {0} occurred. Arguments:\n{1!r}".format(
type(exc).__name__, exc.args)
logger.error(message)
continue
def get_all_configs(cluster, accessor):
pass
def get_all_config_types(cluster, accessor):
response = accessor(DESIRED_CONFIGS_URL.format(cluster))
desired_tags = json.loads(response)
return desired_tags[CLUSTERS][DESIRED_CONFIGS].keys()
def output_to_file(filename):
def output(config):
dirname = os.path.dirname(__file__)
CONFIGS_DIR = "CONFIGS"
output_path = os.path.join(dirname, CONFIGS_DIR)
if not os.path.exists(output_path):
os.makedirs(output_path)
with open(os.path.join(output_path, filename), 'w') as out_file:
json.dump(config, out_file, indent=2)
return output
def get_config_tag(cluster, config_type, accessor):
response = accessor(DESIRED_CONFIGS_URL.format(cluster))
try:
desired_tags = json.loads(response)
current_config_tag = desired_tags[CLUSTERS][DESIRED_CONFIGS][config_type][TAG]
except Exception as exc:
raise Exception('"{0}" not found in server response. Response:\n{1}'.format(
config_type, response))
return current_config_tag
def get_current_config(cluster, config_type, accessor):
config_tag = get_config_tag(cluster, config_type, accessor)
logger.info("### on (Site:{0}, Tag:{1})".format(config_type, config_tag))
response = accessor(CONFIGURATION_URL.format(
cluster, config_type, config_tag))
config_by_tag = json.loads(response)
print config_by_tag
current_config = config_by_tag[ITEMS][0]
## ambari API exposes service configs endpoint even if they are empty
if PROPERTIES in current_config:
return current_config[PROPERTIES], current_config.get(ATTRIBUTES, {})
else:
logger.error("config_type {0} empty ".format(config_type))
logger.error("current_config content : {0} ".format(current_config))
raise Error
def get_config(cluster, config_type, accessor, output):
properties, attributes = get_current_config(cluster, config_type, accessor)
config = {PROPERTIES: properties}
if len(attributes.keys()) > 0:
config[ATTRIBUTES] = attributes
output(config)
def get_service_configs(cluster, accessor, service_name):
response = accessor(SERVICE_URL.format(
cluster, service_name), GET_REQUEST_TYPE)
service_node = json.loads(response)
return service_node['ServiceInfo']
def main():
parser = argparse.ArgumentParser()
login_options_group = parser.add_argument_group('login_options_group')
login_options_group.add_argument("-u", "--user", dest="user", default="admin",
help="Optional user ID to use for authentication. Default is 'admin'")
login_options_group.add_argument("-p", "--password", dest="password", default="<PASSWORD>",
help="Optional password to use for authentication. Default is '<PASSWORD>'")
# login_options_group.add_argument("-e", "--credentials-file", dest="credentials_file",
# help="Optional file with user credentials separated by new line.")
parser.add_argument("-l", "--host", dest="host",
help="Server external host name")
parser.add_argument("-t", "--port", dest="port", default="8080",
help="Optional port number for Ambari server. Default is '8080'. Provide empty string to not use port.")
parser.add_argument("-s", "--protocol", dest="protocol", default="http",
help="Optional support of SSL. Default protocol is 'http'")
parser.add_argument("--unsafe", action="store_true",
dest="unsafe", help="Skip SSL certificate verification.")
parser.add_argument("-a", "--action", dest="action", choices=['dry-run', 'test'],
help="Script action: <dry-run>,<test>")
parser.add_argument("-n", "--cluster", dest="cluster",
help="Name given to cluster. Ex: 'c1'")
parser.add_argument("--log_level", dest="logLevel", choices=[
'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help="Set the logging level")
parser.add_argument("--http_debug", action="store_true", dest="http_debug", help="turn on http debug level")
# will print a namespace Object with the attributes
args = parser.parse_args()
if None in [args.action, args.host, args.cluster]:
parser.error("One of required arguments is not passed")
return 1
host = args.host
port = args.port
protocol = args.protocol
cluster = args.cluster
action = args.action
user = args.user
password = <PASSWORD>
#options without default value
if args.logLevel:
logging.getLogger().setLevel(args.logLevel)
http_dbg_level=0
if args.http_debug:
http_dbg_level=1
accessor = api_accessor(host, user, password,
protocol, port, http_debug_level=http_dbg_level)
# logging_tree.printout()
if action == "test":
# print get_all_config_types(cluster, accessor)
get_all_current_configs(cluster,accessor)
# config_type = "slider-client"
# get_config(cluster, config_type, accessor, output_to_file(config_type))
elif action == DRY_RUN:
dry_run(cluster,accessor)
else:
parser.error(" invalid action arg ")
if __name__ == "__main__":
try:
sys.exit(main())
except (KeyboardInterrupt):
print("\nAborting ... Keyboard Interrupt.")
sys.exit(1)
| 0c69ed448662ca8bdadc33d3da603c0ddfd0422d | [
"Markdown",
"Python",
"Shell"
] | 9 | Markdown | SalahAmine/hdp_management | d43594a1313bf80d3bc8201865d35feb0253f2d4 | c4e288910aab1346fac84e4974d3db8f35937f56 |
refs/heads/master | <file_sep>#include <stdio.h>
int arr[100];
int main()
{
int len, tmp, cnt = 0;
scanf("%d", &len);
for (int i = 0; i < len; i++)
{
scanf("%d", &arr[i]);
}
for (int i = 0; i < len; i++)
{
int max = len - i;
for (int j = 1; j < max; j++)
{
if (arr[j - 1] > arr[j])
{
tmp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = tmp;
cnt++;
}
}
}
printf("%d", arr[0]);
for (int i = 1; i < len; i++)
{
printf(" %d", arr[i]);
}
printf("\n");
printf("%d\n", cnt);
}
<file_sep>#include <stdio.h>
int arr[500001];
void maxHeapify(int* xs, int idx, int size)
{
int left = idx*2, right = idx*2+1, largest = 0;
if (left <= size && arr[idx] < arr[left]) {
largest = left;
} else {
largest = idx;
}
if (right <= size && arr[right] > arr[largest]) {
largest = right;
}
if (largest != idx) {
int tmp = arr[idx];
arr[idx] = arr[largest];
arr[largest] = tmp;
maxHeapify(xs, largest, size);
}
}
int main()
{
int size = 0;
scanf("%d", &size);
for (int i = 1; i <= size; i++) {
scanf("%d", &arr[i]);
}
for (int i = size / 2; i >= 1; i--) {
maxHeapify(arr, i, size);
}
for (int i = 1; i <= size; i++) {
printf(" %d", arr[i]);
}
printf("\n");
}
<file_sep>#include <stdio.h>
long heap[1000];
int main()
{
int i = 0, len = 0;
scanf("%d", &len);
for (i = 1; i <= len; i++) {
scanf("%ld", &heap[i]);
}
for (i = 1; i <= len; i++) {
printf("node %d: key = %ld, ", i, heap[i]);
if (i / 2 > 0) {
printf("parent key = %ld, ", heap[i/2]);
}
if (i*2 <= len) {
printf("left key = %ld, ", heap[i*2]);
}
if ((i*2+1) <= len) {
printf("right key = %ld, ", heap[i*2+1]);
}
printf("\n");
}
return 0;
}
<file_sep>#include <stdio.h>
int arr[100];
int main() {
int len, tmp, swp_cnt = 0;
scanf("%d", &len);
for (int i = 0; i < len; i++) scanf("%d", &arr[i]);
for (int i = 0; i < len; i++)
{
int min = i;
for (int j = i+1; j < len; j++)
{
if (arr[min] > arr[j])
{
min = j;
}
}
if (i != min) {
tmp = arr[i];
arr[i] = arr[min];
arr[min] = tmp;
swp_cnt++;
}
}
printf("%d", arr[0]);
for (int i = 1; i < len; i++)
{
printf(" %d", arr[i]);
}
printf("\n%d\n", swp_cnt);
}
<file_sep>#include <stdio.h>
#include <string.h>
int dict[128][128];
int sort_bub[36][2];
int sort_sel[36][2];
void selection_sort(int arr[][2], int len)
{
int tmp[2];
for (int i = 0; i < len; i++)
{
int min = i;
for (int j = i+1; j < len; j++)
{
if (arr[min][1] > arr[j][1])
{
min = j;
}
}
if (i != min) {
tmp[0] = arr[i][0];
tmp[1] = arr[i][1];
arr[i][0] = arr[min][0];
arr[i][1] = arr[min][1];
arr[min][0] = tmp[0];
arr[min][1] = tmp[1];
}
}
}
void bubble_sort(int arr[][2], int len)
{
int tmp[2];
for (int i = 0; i < len; i++)
{
int max = len - i;
for (int j = 1; j < max; j++)
{
if (arr[j - 1][1] > arr[j][1])
{
tmp[0] = arr[j-1][0];
tmp[1] = arr[j-1][1];
arr[j-1][0] = arr[j][0];
arr[j-1][1] = arr[j][1];
arr[j][0] = tmp[0];
arr[j][1] = tmp[1];
}
}
}
}
int main()
{
int len, tmp;
char mark;
char stable_bub[256] = "Stable", stable_sel[256] = "Stable";
scanf("%d\n", &len);
scanf("%c", &mark);
scanf("%d", &tmp);
sort_bub[0][0] = mark;
sort_bub[0][1] = tmp;
sort_sel[0][0] = mark;
sort_sel[0][1] = tmp;
dict[mark][tmp] = 0;
for (int i = 1; i < len; i++) {
scanf(" %c", &mark);
scanf("%d", &tmp);
sort_bub[i][0] = mark;
sort_bub[i][1] = tmp;
sort_sel[i][0] = mark;
sort_sel[i][1] = tmp;
dict[mark][tmp] = i;
}
bubble_sort(sort_bub, len);
selection_sort(sort_sel, len);
printf("%c%d", (char)sort_bub[0][0], sort_bub[0][1]);
for (int i = 1; i < len; i++) {
printf(" %c%d", (char)sort_bub[i][0], sort_bub[i][1]);
if (sort_bub[i-1][1] == sort_bub[i][1] && dict[sort_bub[i-1][0]][sort_bub[i-1][1]] > dict[sort_bub[i][0]][sort_bub[i][1]]) {
strcpy(stable_bub, "Not stable");
}
}
printf("\n%s\n", stable_bub);
printf("%c%d", (char)sort_sel[0][0], sort_sel[0][1]);
for (int i = 1; i < len; i++) {
printf(" %c%d", (char)sort_sel[i][0], sort_sel[i][1]);
if (sort_sel[i-1][1] == sort_sel[i][1] && dict[sort_sel[i-1][0]][sort_sel[i-1][1]] > dict[sort_sel[i][0]][sort_sel[i][1]]) {
strcpy(stable_sel, "Not stable");
}
}
printf("\n%s\n", stable_sel);
return 0;
}
<file_sep>#include <stdio.h>
int main()
{
int m, n, tmp;
scanf("%d %d", &m, &n);
if (m < n)
{
tmp = m;
m = n;
n = tmp;
}
for (;;)
{
tmp = m % n;
m = n;
n = tmp;
if (n == 0) break;
}
printf("%d\n", m);
return 0;
}
<file_sep>#include <stdio.h>
#include <math.h>
int primes[10001];
int buf2[10001];
int main()
{
int len, res, len_primes, len_buf2;
scanf("%d", &len);
primes[0] = 2;
buf2[0] = 0;
len_primes = 1;
len_buf2 = 0;
res = 0;
for (int k = 2; k <= 10000; k++)
{
int is_prime = 2;
for (int j = 0; (j < len_primes) && is_prime; j++)
{
is_prime = k % primes[j];
}
if (is_prime) {
primes[len_primes] = k;
len_primes++;
}
}
for (int i = 0; i < len; i++)
{
int p = 0, already = 0;
scanf("%d", &p);
for (int j = 0; j < len_buf2 && !already; j++) {
if (buf2[j] == p) {
already = 1;
}
}
if (!already) {
int maxp = (int)sqrt((double)p) + 1;
int is_prime = 1;
for (int k = 0; (primes[k] < maxp) && k < len_primes && is_prime; k++) {
is_prime = p % primes[k];
}
if (is_prime) {
buf2[len_buf2] = p;
len_buf2++;
res++;
}
}
}
// for (int i = 0; i < len_buf2; i++) printf("nakami: %d\n", buf2[i]);
printf("%d\n", res);
return 0;
}
<file_sep>#include <stdio.h>
int arr[1000000000];
int seed[100];
int cnt = 0;
void insertion_sort(int* arr, int len, int g)
{
for (int i = g; i < len; i++)
{
int tmp = arr[i], j = i - g;
while (j >= 0 && arr[j] > tmp)
{
arr[j+g] = arr[j];
j = j - g;
cnt++;
}
arr[j+g] = tmp;
}
}
int main()
{
int len;
scanf("%d", &len);
for (int i = 0; i < len; i++)
{
scanf("%d", &arr[i]);
}
int power = 1, seed_count = 0;
while (power <= len)
{
seed[seed_count++] = power;
// printf("%d\n", seed[seed_count-1]);
power = 2*power;
}
printf("%d\n", seed_count);
for (int i = 0; i < seed_count; i++)
{
printf("%d ", seed[seed_count-i-1]);
insertion_sort(arr, len, seed[seed_count-i-1]);
}
printf("\n");
printf("%d\n", cnt);
for (int i = 0; i < len; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
| c9b02fabcd12ff371f6f5cf0ea78ef371f511c66 | [
"C"
] | 8 | C | honyacho/ALDS | 1e4244763eb0cd7e71d49021a58071f962d1dd15 | f2af667ac55edad0e68345eabe1df2796a0331ab |
refs/heads/master | <repo_name>redcliver/restaurante<file_sep>/produto/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^novo_prod', views.novo_prod),
url(r'^nova_refe', views.nova_refe),
url(r'^buscar_prod', views.buscar_prod),
url(r'^edit_prod', views.edit_prod),
url(r'^buscar_refe', views.buscar_refe),
url(r'^edit_refe', views.edit_refe),
]
<file_sep>/contas/views.py
from django.shortcuts import render
from contas.models import conta
from caixa.models import caixa_geral
# Create your views here.
def contas(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('name'):
name = request.POST.get('name')
valor = request.POST.get('valor')
desc = request.POST.get('desc')
data = request.POST.get('date')
nava_conta = conta(nome=name, valor=valor, descricao=desc, data=data, estado=1)
nava_conta.save()
msg = "Conta agendada com sucesso."
return render(request, 'home/home.html', {'title':'Home', 'msg':msg})
return render(request, 'contas.html', {'title':'Contas'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def busca(request):
if request.user.is_authenticated():
c_obj = conta.objects.all().order_by('nome')
if request.method == 'GET' and request.GET.get('c_id') != None:
c_id = request.GET.get('c_id')
c1 = conta.objects.filter(id=c_id).all()
return render(request, 'buscar_conta.html', {'title':'Busca Conta', 'c1':c1})
elif request.method == 'POST' and request.POST.get('id') != None:
conta_id = request.POST.get('id')
conta_obj = conta.objects.filter(id=conta_id).get()
return render(request, 'editar_conta.html', {'title':'Editar Conta', 'conta_obj':conta_obj})
return render(request, 'buscar_conta.html', {'title':'Busca Conta', 'c_obj':c_obj})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def editar1(request):
if request.user.is_authenticated():
if request.method == 'GET' and request.POST.get('edit_id') != None:
edit_id = request.GET.get('edit_id')
c1_obj = conta.objects.filter(id=edit_id).get()
return render(request, 'editar.html', {'title':'Editar Conta', 'c1_obj':c1_obj})
elif request.method == 'POST' and request.POST.get('id') != None:
conta_id = request.POST.get('id')
conta_obj = conta.objects.filter(id=conta_id).get()
conta_nome = request.POST.get('name')
conta_valor = request.POST.get('valor')
conta_desc = request.POST.get('desc')
conta_data = request.POST.get('date')
conta_obj.nome = conta_nome
conta_obj.valor = conta_valor
conta_obj.descricao = conta_desc
conta_obj.data = conta_data
conta_obj.save()
msg = "Conta editada com sucesso."
return render(request, 'home/home.html', {'title':'Home', "msg":msg})
return render(request, 'editar_conta.html', {'title':'Editar Conta'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def pagar(request):
if request.user.is_authenticated():
contas = conta.objects.filter(estado=1).all()
if request.method == "POST" and request.POST.get('conta_id') != None:
conta_id = request.POST.get('conta_id')
conta_obj = conta.objects.filter(id=conta_id).get()
caixa = caixa_geral.objects.latest('id')
total = caixa.total - conta_obj.valor
desc = "Conta numero "+str(conta_id)+"."
novo_caixa = caixa_geral(tipo=2, total=total, desc=desc)
novo_caixa.save()
conta_obj.estado = 2
conta_obj.save()
msg = "Conta paga com sucesso."
return render(request, 'home/home.html', {'title':'Home', "msg":msg})
return render(request, 'pagar.html', {'title':'Pagar Conta', 'contas':contas})
else:
return render(request, 'home/erro.html', {'title':'Erro'})<file_sep>/produto/views.py
from django.shortcuts import render
from .models import produto, refeicao
# Create your views here.
def novo_prod(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('name'):
name = request.POST.get('name')
valor_vend = request.POST.get('valor_vend')
valor_comp = request.POST.get('valor_comp')
qnt = request.POST.get('qnt')
qnt_min = request.POST.get('qnt_min')
novo_produto = produto(nome=name, valor_venda=valor_vend, valor_compra=valor_comp, qnt_min=qnt_min, quantidade=qnt)
novo_produto.save()
msg = "Produto cadastrado com sucesso!"
return render(request, 'home/home.html', {'title':'Home', 'msg':msg})
return render(request, 'produto.html', {'title':'Produto'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def buscar_prod(request):
if request.user.is_authenticated():
prods = produto.objects.all().order_by('nome')
if request.method == 'GET' and request.GET.get('prod_id') != None:
name = request.GET.get('prod_id')
produtos = produto.objects.filter(nome__icontains=name)
return render(request, 'buscar_prod.html', {'title':'Busca Produto', 'produtos':produtos})
elif request.method == 'POST':
produto_id = request.POST.get('id')
produto_obj = produto.objects.filter(id=produto_id).get()
return render(request, 'edit_prod.html', {'title':'Editar Produto', 'produto_obj':produto_obj})
return render(request, 'buscar_prod.html', {'title':'Busca Produto', 'prods':prods})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def edit_prod(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('id') != None:
produto_id = request.POST.get('id')
produto_obj = produto.objects.filter(id=produto_id).get()
produto_nome = request.POST.get('name')
produto_valor = request.POST.get('valor_vend')
produto_qnt = request.POST.get('qnt')
prod_valor_comp = request.POST.get('valor_comp')
produto_qnt_min = request.POST.get('qnt_min')
produto_obj.nome = produto_nome
produto_obj.valor_venda = produto_valor
produto_obj.quantidade = produto_qnt
produto_obj.valor_compra = prod_valor_comp
produto_obj.qnt_min = produto_qnt_min
produto_obj.save()
msg = "Produto editado com sucesso."
return render(request, 'home/home.html', {'title':'Home', 'msg':msg})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def nova_refe(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('name'):
name = request.POST.get('name')
valor = request.POST.get('valor')
nova_refeicao = refeicao(nome=name, valor=valor)
nova_refeicao.save()
msg = "Refeicao cadastrada com sucesso!"
return render(request, 'home/home.html', {'title':'Home', 'msg':msg})
return render(request, 'refeicao.html', {'title':'Produto'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def buscar_refe(request):
if request.user.is_authenticated():
refes = refeicao.objects.all().order_by('nome')
if request.method == 'GET' and request.GET.get('refe_id') != None:
name = request.GET.get('refe_id')
refeicoes = refeicao.objects.filter(nome__icontains=name)
return render(request, 'buscar_refe.html', {'title':'Busca Refeicao', 'refeicoes':refeicoes})
elif request.method == 'POST':
refeicao_id = request.POST.get('id')
refeicao_obj = refeicao.objects.filter(id=refeicao_id).get()
return render(request, 'edit_refe.html', {'title':'Editar Produto', 'refeicao_obj':refeicao_obj})
return render(request, 'buscar_refe.html', {'title':'Busca Refeicao', 'refes':refes})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def edit_refe(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('id') != None:
refeicao_id = request.POST.get('id')
refeicao_obj = refeicao.objects.filter(id=refeicao_id).get()
refeicao_nome = request.POST.get('name')
refeicao_valor = request.POST.get('valor')
refeicao_obj.nome = produto_nome
refeicao_obj.valor = produto_valor
refeicao_obj.save()
msg = "Refeicao editada com sucesso."
return render(request, 'home/home.html', {'title':'Home', 'msg':msg})
else:
return render(request, 'home/erro.html', {'title':'Erro'})<file_sep>/restaurante/__init__.py
"""
Package for restaurante.
"""
<file_sep>/pedido/migrations/0002_auto_20180420_0118.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-04-20 05:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pedido', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='pedido',
name='metodo',
field=models.CharField(blank=True, choices=[('1', 'Dinheiro'), ('2', 'C. Debito'), ('3', 'C. Credito')], max_length=1, null=True),
),
]
<file_sep>/pedido/views.py
from django.shortcuts import render
from django.contrib.auth import authenticate
from cliente.models import cliente
from produto.models import produto, refeicao
from pedido.models import pedido, refe_item, prod_item
from caixa.models import caixa_geral
from django.utils import timezone
from decimal import *
# Create your views here.
def pedido1(request):
if request.user.is_authenticated():
cli = cliente.objects.all().order_by('nome')
pro = produto.objects.all().order_by('nome')
ref = refeicao.objects.all().order_by('nome')
return render(request, 'pedido.html', {'title':'Pedidos', 'cli':cli, 'pro':pro, 'ref':ref})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def abrir(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('cliente_id') != None and request.POST.get('refe_id') == None and request.POST.get('prod_id') == None and request.POST.get('ref_id') == None and request.POST.get('pro_id') == None:
cli_id = request.POST.get('cliente_id')
cli_obj = cliente.objects.all().filter(id=cli_id).get()
novo_pedido = pedido(cliente_pedido=cli_obj, estado=1, total=0)
novo_pedido.save()
pro = produto.objects.all().order_by('nome')
ref = refeicao.objects.all().order_by('nome')
return render(request, 'abrir.html', {'title':'Abrir Pedido', 'cli_obj':cli_obj, 'pedido_obj':novo_pedido, 'pro':pro, 'ref':ref})
elif request.method == 'POST' and request.POST.get('cliente_id') != None and request.POST.get('refe_id') != None and request.POST.get('prod_id') == None and request.POST.get('ref_id') == None and request.POST.get('pro_id') == None:
cli_id = request.POST.get('cliente_id')
refe_id = request.POST.get('refe_id')
refe_qnt = request.POST.get('qnt_refe')
cli_obj = cliente.objects.all().filter(id=cli_id).get()
refe_obj = refeicao.objects.all().filter(id=refe_id).get()
refe_total = Decimal(refe_obj.valor)*Decimal(refe_qnt)
novo_ref_item = refe_item(refeicoes=refe_obj, quantidade=refe_qnt, total=Decimal(refe_total))
novo_ref_item.save()
novo_pedido = pedido(cliente_pedido=cli_obj, estado=1, total=refe_total)
novo_pedido.save()
novo_pedido.refeicao_item.add(novo_ref_item)
novo_pedido.save()
refes1 = novo_pedido.refeicao_item.all()
pro = produto.objects.all().order_by('nome')
ref = refeicao.objects.all().order_by('nome')
return render(request, 'abrir.html', {'title':'Abrir Pedido', 'cli_obj':cli_obj, 'pedido_obj':novo_pedido, 'refes1':refes1, 'pro':pro, 'ref':ref})
elif request.method == 'POST' and request.POST.get('cliente_id') != None and request.POST.get('refe_id') == None and request.POST.get('prod_id') != None and request.POST.get('ref_id') == None and request.POST.get('pro_id') == None:
cli_id = request.POST.get('cliente_id')
prod_id = request.POST.get('prod_id')
qnt_prod = request.POST.get('qnt_prod')
cli_obj = cliente.objects.all().filter(id=cli_id).get()
prod_obj = produto.objects.all().filter(id=prod_id).get()
prod_obj.quantidade = int(prod_obj.quantidade) - int(qnt_prod)
prod_obj.save()
prod_total = Decimal(prod_obj.valor_venda)*Decimal(qnt_prod)
novo_prod_item = prod_item(produtos=prod_obj, quantidade=qnt_prod, total=prod_total)
novo_prod_item.save()
novo_pedido = pedido(cliente_pedido=cli_obj, estado=1, total=prod_total)
novo_pedido.save()
novo_pedido.produto_item.add(novo_prod_item)
novo_pedido.save()
prods1 = novo_pedido.produto_item.all()
pro = produto.objects.all().order_by('nome')
ref = refeicao.objects.all().order_by('nome')
return render(request, 'abrir.html', {'title':'Abrir Pedido', 'cli_obj':cli_obj, 'pedido_obj':novo_pedido, 'prods1':prods1, 'pro':pro, 'ref':ref})
elif request.method == 'POST' and request.POST.get('cliente_id') != None and request.POST.get('refe_id') != None and request.POST.get('prod_id') != None and request.POST.get('ref_id') == None and request.POST.get('pro_id') == None:
cli_id = request.POST.get('cliente_id')
prod_id = request.POST.get('prod_id')
refe_id = request.POST.get('refe_id')
qnt_prod = request.POST.get('qnt_prod')
refe_qnt = request.POST.get('qnt_refe')
cli_obj = cliente.objects.all().filter(id=cli_id).get()
prod_obj = produto.objects.all().filter(id=prod_id).get()
refe_obj = refeicao.objects.all().filter(id=refe_id).get()
prod_obj.quantidade = int(prod_obj.quantidade) - int(qnt_prod)
prod_obj.save()
prod_total = prod_obj.valor_venda*Decimal(qnt_prod)
refe_total = refe_obj.valor*Decimal(refe_qnt)
total_total = Decimal(prod_total)+Decimal(refe_total)
novo_prod_item = prod_item(produtos=prod_obj, quantidade=qnt_prod, total=prod_total)
novo_prod_item.save()
nova_refe_item = refe_item(refeicoes=refe_obj, quantidade=refe_qnt, total=refe_total)
nova_refe_item.save()
novo_pedido = pedido(cliente_pedido=cli_obj, estado=1, total=total_total)
novo_pedido.save()
novo_pedido.produto_item.add(novo_prod_item)
novo_pedido.refeicao_item.add(nova_refe_item)
novo_pedido.save()
prods1 = novo_pedido.produto_item.all()
refes1 = novo_pedido.refeicao_item.all()
pro = produto.objects.all().order_by('nome')
ref = refeicao.objects.all().order_by('nome')
return render(request, 'abrir.html', {'title':'Abrir Pedido', 'cli_obj':cli_obj, 'pedido_obj':novo_pedido, 'prods1':prods1, 'refes1':refes1, 'pro':pro, 'ref':ref})
return render(request, 'abrir.html', {'title':'Abrir Pedido'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def add_refe(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('ref_id') != None and request.POST.get('pro_id') == None and request.POST.get('refe_id') == None and request.POST.get('prod_id') == None:
pedido_id = request.POST.get('ped_id')
cli_id = request.POST.get('cli_id')
refe_id = request.POST.get('ref_id')
refe_qnt = request.POST.get('qnt_refe')
cli_obj = cliente.objects.all().filter(id=cli_id).get()
pedido_obj = pedido.objects.filter(id=pedido_id).get()
refe_obj = refeicao.objects.all().filter(id=refe_id).get()
refe_total = refe_obj.valor*Decimal(refe_qnt)
novo_ref_item = refe_item(refeicoes=refe_obj, quantidade=refe_qnt, total=refe_total)
novo_ref_item.save()
pedido_obj.total = pedido_obj.total + refe_total
pedido_obj.refeicao_item.add(novo_ref_item)
pedido_obj.save()
refes1 = pedido_obj.refeicao_item.all()
prods1 = pedido_obj.produto_item.all()
pro = produto.objects.all().order_by('nome')
ref = refeicao.objects.all().order_by('nome')
return render(request, 'abrir.html', {'title':'Abrir Pedido', 'cli_obj':cli_obj, 'pedido_obj':pedido_obj, 'refes1':refes1, 'prods1':prods1, 'pro':pro, 'ref':ref})
return render(request, 'abrir.html', {'title':'Abrir Pedido'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def add_prod(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('ref_id') == None and request.POST.get('pro_id') != None and request.POST.get('refe_id') == None and request.POST.get('prod_id') == None:
pedido_id = request.POST.get('ped_id')
cli_id = request.POST.get('cli_id')
prod_id = request.POST.get('pro_id')
prod_qnt = request.POST.get('qnt_prod')
cli_obj = cliente.objects.all().filter(id=cli_id).get()
pedido_obj = pedido.objects.filter(id=pedido_id).get()
prod_obj = produto.objects.all().filter(id=prod_id).get()
prod_total = Decimal(prod_obj.valor_venda)*Decimal(prod_qnt)
novo_pro_item = prod_item(produtos=prod_obj, quantidade=prod_qnt, total=prod_total)
novo_pro_item.save()
pedido_obj.total = pedido_obj.total + prod_total
pedido_obj.produto_item.add(novo_pro_item)
pedido_obj.save()
refes1 = pedido_obj.refeicao_item.all()
prods1 = pedido_obj.produto_item.all()
pro = produto.objects.all().order_by('nome')
ref = refeicao.objects.all().order_by('nome')
return render(request, 'abrir.html', {'title':'Abrir Pedido', 'cli_obj':cli_obj, 'pedido_obj':pedido_obj, 'refes1':refes1, 'prods1':prods1, 'pro':pro, 'ref':ref})
return render(request, 'abrir.html', {'title':'Abrir Pedido'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def metodo(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('pedido_id') != None:
pedido_id = request.POST.get('pedido_id')
pedido_obj = pedido.objects.filter(id=pedido_id).get()
return render(request, 'metodo.html', {'title':'Metodo de pagamento', 'pedido_obj':pedido_obj})
return render(request, 'metodo.html', {'title':'Metodo de pagamento'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def finalizar(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('pedido_id') != None and request.POST.get('metodo') != None:
pedido_id = request.POST.get('pedido_id')
met = request.POST.get('metodo')
if met == '1':
pedido_obj = pedido.objects.filter(id=pedido_id).get()
return render(request, 'dinheiro.html', {'title':'Dinheiro', 'pedido_obj':pedido_obj})
else:
data = timezone.now()
pedido_obj = pedido.objects.filter(id=pedido_id).get()
caixa_atual = caixa_geral.objects.latest('id')
desc = "Ref. pedido N:"+ str(pedido_obj.id) +", pag:"+str(pedido_obj.get_metodo_display)+", total:R$"+str(pedido_obj.total)+"."
total = caixa_atual.total + pedido_obj.total
op_caixa = caixa_geral(tipo=1, total=total, desc=desc)
op_caixa.save()
pedido_obj.metodo = met
pedido_obj.estado = 2
pedido_obj.data_fechamento = data
pedido_obj.save()
msg = "Pedido finalizado com sucesso!"
return render(request, 'home/home.html', {'title':'Home', 'msg':msg})
return render(request, 'metodo.html', {'title':'Metodo de pagamento'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def busca2(request):
if request.user.is_authenticated():
return render(request, 'busca2.html', {'title':'Busca'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def del_produto(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('del_prod') != None:
del_prod_id = request.POST.get('del_prod')
pedido_id = request.POST.get('pedido_id')
cli_id = request.POST.get('cliente_id')
prod_item_obj = prod_item.objects.filter(id=del_prod_id).get()
cli_obj = cliente.objects.all().filter(id=cli_id).get()
prod_preco = Decimal(prod_item_obj.total)
prod_item_obj.delete()
pedido_obj = pedido.objects.filter(id=pedido_id).get()
pedido_obj.total = pedido_obj.total - prod_preco
pedido_obj.save()
refes1 = pedido_obj.refeicao_item.all()
prods1 = pedido_obj.produto_item.all()
pro = produto.objects.all().order_by('nome')
ref = refeicao.objects.all().order_by('nome')
return render(request, 'abrir.html', {'title':'Abrir Pedido', 'cli_obj':cli_obj, 'pedido_obj':pedido_obj, 'refes1':refes1, 'prods1':prods1, 'pro':pro, 'ref':ref})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def del_refe(request):
if request.user.is_authenticated():
if request.method == 'POST' and request.POST.get('del_refe') != None:
del_refe_id = request.POST.get('del_refe')
pedido_id = request.POST.get('pedido_id')
cli_id = request.POST.get('cliente_id')
ref_item_obj = refe_item.objects.filter(id = del_refe_id).get()
cli_obj = cliente.objects.all().filter(id=cli_id).get()
refe_preco = Decimal(ref_item_obj.total)
ref_item_obj.delete()
pedido_obj = pedido.objects.filter(id=pedido_id).get()
pedido_obj.total = pedido_obj.total - refe_preco
pedido_obj.save()
prods1 = pedido_obj.produto_item.all()
refes1 = pedido_obj.refeicao_item.all()
pro = produto.objects.all().order_by('nome')
ref = refeicao.objects.all().order_by('nome')
return render(request, 'abrir.html', {'title':'Abrir Pedido', 'cli_obj':cli_obj, 'pedido_obj':pedido_obj, 'refes1':refes1, 'prods1':prods1, 'pro':pro, 'ref':ref})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def troco(request):
if request.user.is_authenticated():
if request.method == 'GET' and request.GET.get('recebido') != None:
rec = request.GET.get('recebido')
pedido_id = request.GET.get('pedido_id')
pedido_obj = pedido.objects.filter(id=pedido_id).get()
troco = Decimal(rec) - pedido_obj.total
return render(request, 'troco.html', {'title':'Troco do pagamento', 'pedido_obj':pedido_obj, 'rec':rec, 'troco':troco})
elif request.method == 'POST' and request.POST.get('pedido_id') != None:
data = timezone.now()
caixa_atual = caixa_geral.objects.latest('id')
pedido_id = request.POST.get('pedido_id')
troco = request.POST.get('troco')
pedido_obj = pedido.objects.filter(id=pedido_id).get()
desc = "Ref. pedido N:"+ str(pedido_obj.id) +", pag:"+ str(pedido_obj.get_metodo_display) +", total:R$"+ str(pedido_obj.total) +", troco:R$"+str(troco)+"."
total = caixa_atual.total + pedido_obj.total
op_caixa = caixa_geral(tipo=1, total=total, desc=desc)
op_caixa.save()
pedido_obj.metodo = 1
pedido_obj.estado = 2
pedido_obj.data_fechamento = data
pedido_obj.save()
msg = "Pedido finalizado com sucesso!"
return render(request, 'home/home.html', {'title':'Home', 'msg':msg})
return render(request, 'troco.html', {'title':'Troco do pagamento'})
else:
return render(request, 'home/erro.html', {'title':'Erro'})<file_sep>/outros/views.py
from django.shortcuts import render
# Create your views here.
def outros(request):
return render(request, 'outros.html', {'title':'Outros'})
<file_sep>/pedido/models.py
from django.db import models
from produto.models import produto, refeicao
from cliente.models import cliente
from django.utils import timezone
# Create your models here.
class refe_item(models.Model):
id = models.AutoField(primary_key=True)
refeicoes = models.ForeignKey(refeicao)
quantidade = models.IntegerField(default='1')
total = models.DecimalField(max_digits=6, decimal_places=2)
def __int__(self):
return self.id
class prod_item(models.Model):
id = models.AutoField(primary_key=True)
produtos = models.ForeignKey(produto)
quantidade = models.IntegerField(default='1')
total = models.DecimalField(max_digits=6, decimal_places=2)
def __int__(self):
return self.id
class pedido(models.Model):
ESTADO = (
('1', 'Em Aberto'),
('2', 'Finalizada'),
)
METODO = (
('1', 'Dinheiro'),
('2', 'C. Debito'),
('3', 'C. Credito'),
)
id = models.AutoField(primary_key=True)
cliente_pedido = models.ForeignKey(cliente)
produto_item = models.ManyToManyField(prod_item)
refeicao_item = models.ManyToManyField(refe_item)
estado = models.CharField(max_length=1, choices=ESTADO)
metodo = models.CharField(max_length=1, choices=METODO, null=True, blank=True)
data_abertura = models.DateTimeField(default=timezone.now)
data_fechamento = models.DateTimeField(null=True, blank=True)
desc = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
total = models.DecimalField(max_digits=6, decimal_places=2)
def __str__(self):
return str(self.id)<file_sep>/caixa/views.py
from django.shortcuts import render
from decimal import *
from .models import caixa_geral
from pedido.models import pedido
# Create your views here.
def caixa(request):
if request.user.is_authenticated():
caixa = caixa_geral.objects.latest('id')
return render(request, 'caixa.html', {'title':'Caixa', 'caixa':caixa})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def fechar(request):
if request.user.is_authenticated():
caixa = caixa_geral.objects.latest('id')
if request.method =='POST' and request.POST.get('retirada') != None:
valor =request.POST.get('retirada')
fechamento = caixa_geral.objects.latest('id')
total = fechamento.total - Decimal(valor)
desc = "Fechamento"
nova_op = caixa_geral(total=total, tipo=2, desc=desc)
nova_op.save()
msg = "Caixa fechado com secesso!"
return render(request, 'home/home.html', {'title':'Home', 'msg':msg})
return render(request, 'fechar.html', {'title':'Caixa', 'caixa':caixa})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def retirada(request):
if request.user.is_authenticated():
try:
caixa = caixa_geral.objects.latest('id')
total = caixa.total
except:
caixa = caixa_geral(tipo=1, total=0, desc="abertura")
caixa.save()
total = caixa.total
if request.method == 'POST' and request.POST.get('retirada') != None:
valor_ret = request.POST.get('retirada')
desc = request.POST.get('motivo')
total = caixa.total - Decimal(valor_ret)
nova_op = caixa_geral(total=total, tipo=2, desc=desc)
nova_op.save()
msg = "Retirada concluida com sucesso."
return render(request, 'home/home.html', {'title':'Home', 'msg':msg})
return render(request, 'retirada.html', {'title':'Retirada', 'total':total})
else:
return render(request, 'home/erro.html', {'title':'Erro'})
def inf_geral(request):
if request.user.is_authenticated():
caixa = caixa_geral.objects.latest('id')
caixa_1 = caixa_geral.objects.get(id=1)
dia_1 = caixa_1.data.strftime('%d/%m/%Y')
total_dim = 0
total_cd = 0
total_cc = 0
for a in pedido.objects.filter(estado=2, metodo=1).all():
total_dim = total_dim + a.total
for b in pedido.objects.filter(estado=2, metodo=2).all():
total_cd = total_cd + b.total
for c in pedido.objects.filter(estado=2, metodo=3).all():
total_cc = total_cc + c.total
return render(request, 'inf_geral.html', {'title':'Retirada', 'dia_1':dia_1, 'total_dim':total_dim, 'total_cd':total_cd, 'total_cc':total_cc, 'caixa':caixa, 'dia_1':dia_1})
else:
return render(request, 'home/erro.html', {'title':'Erro'}) | ef7a77cfcc32830f055e22dae56df4ed501fd205 | [
"Python"
] | 9 | Python | redcliver/restaurante | b9c34188c71e7141a731355cd9c9984c680fc959 | 3607a5a326387d5f3fd453acced97caa5d332f00 |
refs/heads/master | <repo_name>Shabsiem/NPSAPI<file_sep>/index.js
const apiKey = '<KEY>';
const baseurl = 'https://developer.nps.gov/api/v1/parks?';
(function($) {
console.log("Locked and Loaded");
const app = {
init: function() {
app.parksearch();
},
parksearch: function() {
console.log('Watching the form')
$('.parksearch').submit (function(){
event.preventDefault();
const state = $('#where').val();
const num = $('#num').val();
app.setupaddress(state, num);
$('#parkList').empty();
console.log("form submitted")
console.log(state + " " + num)
});
},
setupaddress: function(state, num){
const params = `stateCode=${encodeURIComponent(state)}&limit=${num}&api_key=`
const endpoint = baseurl + params + apiKey
app.gofetch(endpoint, num)
},
gofetch: function(endpoint, num) {
fetch(endpoint).then(response => {
if (response.status === 200) {
response.json()
.then(data => {
app.displayRepos(data, num);
})
.catch(error => {
console.log("200 " + error);
});
} else {
response.json()
.then(data => {
})
.catch(error => {
console.log("not 200: "+error)
});
}
});
},
displayRepos: function(data, num){
console.log(data.data)
console.log(data.data[0].fullName)
for (var i = 0; i < num; i++){
console.log(data.data[i])
var parkinfo = data.data[i]
$('.parkresults').append(`
<ul class = 'parklist'>
<li><h3>${parkinfo.fullName}</li>
<li><a href=${parkinfo.url}>Click here to go to the park website</li>
<li><p>${parkinfo.description}</p></li>
</ul>`)
}
}
};
$(window).on("load", () => {
app.init();
});
})
(window.jQuery);
| 29e47827013d3201b09a8e0b5da37149d9af8310 | [
"JavaScript"
] | 1 | JavaScript | Shabsiem/NPSAPI | caddbae4b736a61bef46d9a2d1e20cc25bc11838 | 36ab6082618a0e2154acb1dd55094ea5c5911214 |
refs/heads/master | <repo_name>Grzanekkk/Rejestracja-Czasu-Pracy<file_sep>/RejestracjaCzasuPracy/ClientApp/src/components/Login.js
import React, { Component } from 'react';
const DpkTitle = () => {
return (
<div className="title-section">
<p className="line anim-typewriter">Welcome to DPK System</p>
</div>
)
}
const TitleLoginText = () => {
return (
<React.Fragment>
<h2>Sign In</h2>
<h3>Choose User</h3>
</React.Fragment>
)
}
const LoginForm = props => {
const { formSubmit, userName, userChange, items, getId, isSelected } = props;
return (
<form onSubmit={formSubmit}>
<select value={userName} onChange={userChange}>
<option value=""></option>
{items}
</select>
<br/>
<button type="submit" onClick={getId}>Log in</button>
{isSelected ? null : <ValidationMessage text="User is not selected"/> }
</form>
)
}
const ValidationMessage = props => {
return <p>{props.text}</p>
}
export class Login extends Component {
constructor(props) {
super(props);
this.state = {
userName: '',
isSelected: true,
users: '',
choosenId: '',
}
}
handleFormSubmit = (e) => {
e.preventDefault();
if (this.state.userName) {
this.props.onLoggIn(this.state.choosenId);
} else return this.setState({isSelected: false})
}
handleGetId = () => {
this.state.users.filter(user => {
if (user.name === this.state.userName) {
return (
this.setState({
choosenId: user.id,
})
)
} else return null
})
}
handleUserChange = (e) => {
this.setState({
userName: e.target.value,
})
}
updateUserSelect() {
fetch('/api/User/GetAllUsers')
.then(res => res.json())
.then(data =>
this.setState({
users: data
})
);
}
componentDidMount() {
this.updateUserSelect();
}
render() {
const { users, userName, isSelected } = this.state;
const items = [];
for (let i = 0; i < users.length; ++i) {
items.push(<option key={users[i].id} value={users[i].name}>{users[i].name}</option>)
}
return (
<section className='login'>
<DpkTitle/>
<div className='login-section'>
<TitleLoginText />
<LoginForm
formSubmit={this.handleFormSubmit}
userName={userName}
userChange={this.handleUserChange}
items={items}
getId={this.handleGetId}
isSelected={isSelected}
/>
<button className='go-to-summary' onClick={this.props.goToSummary}>Go to summary of all users</button>
</div>
</section>
)
}
}
<file_sep>/RejestracjaCzasuPracy/Controllers/EventController.cs
using DatabaseConnection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters.Xml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace RejestracjaCzasuPracy.Controllers
{
[Route("api/[controller]")]
public class EventController : Controller
{
TimeManager timeManager = new TimeManager();
UserManager userManager = new UserManager();
#region GET
[HttpGet("[action]")]
public ActionResult GetUserEvents(string memberID) // returns all user events
{
DataTable events = timeManager.GetUserEvents(memberID);
if (events != null)
return Ok(events);
return BadRequest();
}
[HttpGet("[action]")]
public ActionResult GetSummaryForAllUsers()
{
DataTable summary = timeManager.GetSummaryForAllUsers();
if (summary != null)
return Ok(summary);
return BadRequest();
}
[HttpGet("[action]")]
public ActionResult IsWorking(string memberID)
{
bool isWorking = timeManager.IsWorking(memberID);
return Ok(isWorking);
}
[HttpGet("[action]")]
public ActionResult WorkButton(string memberID)
{
if (timeManager.IsWorking(memberID))
{
if (timeManager.IsOnBreak(memberID))
{
timeManager.FinishBreak(memberID);
}
timeManager.StopWorking(memberID);
}
else // User is not working now
{
timeManager.StartWorking(memberID);
}
return Ok(timeManager.IsWorking(memberID));
}
[HttpGet("[action]")]
public ActionResult BreakButton(string memberID)
{
if (timeManager.IsOnBreak(memberID))
{
timeManager.FinishBreak(memberID);
}
else
{
timeManager.StartBreak(memberID);
}
return Ok(timeManager.IsOnBreak(memberID));
}
[HttpGet("[action]")]
public ActionResult IsOnBreak(string memberID)
{
return Ok(timeManager.IsOnBreak(memberID));
}
[HttpGet("[action]")]
public ActionResult DeleteEvent(string eventID, string memberID)
{
timeManager.DeleteEvent(eventID);
return GetUserEvents(memberID);
}
[HttpGet("[action]")]
public void AddNewEvent(string memberID, int minutes)
{
if(minutes != 0)
{
timeManager.AddNewEvent(memberID, minutes);
}
}
[HttpGet("[action]")]
public void GoHome(string memberID)
{
User currentUser = userManager.GetUserWithID(memberID);
timeManager.AddNewEvent(memberID, timeManager.CountBalanceFromNow(currentUser));
}
[HttpGet("[action]")]
public ActionResult RefreshData(string memberID)
{
DataToRefreshWindow data = new DataToRefreshWindow(timeManager.GetUserEvents(memberID), timeManager.CountUserBalance(memberID));
if (data != null)
return Ok(data);
return BadRequest();
}
#endregion GET
}
public class DataToRefreshWindow
{
public DataTable userEvents;
public int balance;
public DataToRefreshWindow(DataTable _userEvents, int _balance)
{
userEvents = _userEvents;
balance = _balance;
}
}
}
<file_sep>/RejestracjaCzasuPracy.DB/TimeManager.cs
using Microsoft.Data.SqlClient;
using System;
using System.Data;
namespace DatabaseConnection
{
public class TimeManager
{
private DataTable dataTable = new DataTable();
private DBAccess dbAccess = new DBAccess();
private string query;
public bool AddNewEvent(string memberID, int balance)
{
SqlCommand insertCommand = new SqlCommand($"INSERT into Events(EventID, Date, Balance, MemberID, BreakTime) " +
$"values(@EventID, @Date, @Balance, @MemberID, @BreakTime)");
insertCommand.Parameters.AddWithValue("@EventID", Guid.NewGuid());
insertCommand.Parameters.AddWithValue("@Date", DateTime.Now);
insertCommand.Parameters.AddWithValue("@MemberID", memberID);
insertCommand.Parameters.AddWithValue("@BreakTime", 0);
if (balance == 0)
{
insertCommand.Parameters.AddWithValue("@Balance", DBNull.Value);
}
else
{
insertCommand.Parameters.AddWithValue("@Balance", balance);
}
int row = dbAccess.ExecuteQuery(insertCommand);
if(row == 1)
{
return true; // Event added successfully
}
else
{
return false; // FAILED to add an Event
}
}
public void DeleteEvent(string eventID)
{
dataTable = new DataTable();
SqlCommand deleteCommand = new SqlCommand($"DELETE FROM Events Where eventID='{eventID}'");
dbAccess.ExecuteQuery(deleteCommand);
}
public void UpdateEvents(DataTable changes)
{
query = $"SELECT * from Events";
dbAccess.ExecuteDataAdapter(changes, query);
}
public int CountUserBalance(string memberID)
{
dataTable = new DataTable();
query = $"SELECT sum(Balance) Balance, MemberID from Events where MemberID = '{memberID}' group by MemberID";
int balance = 0;
dbAccess.ReadDataThroughAdapter(query, dataTable);
if (dataTable.Rows.Count != 0 && !dataTable.Rows[0].IsNull("Balance") && dataTable.Rows[0]["Balance"] != DBNull.Value)
{
balance = Convert.ToInt32(dataTable.Rows[0]["Balance"]);
}
return balance;
}
public int CountBalanceFromNow(User currentUser)
{
TimeSpan timeSpan = DateTime.Now - currentUser.finishWorkHour;
int balance = Convert.ToInt32(timeSpan.TotalMinutes);
return balance;
}
public DataTable GetSummaryForAllUsers()
{
dataTable = new DataTable();
query = $"SELECT sum(Balance) Balance, MemberID FROM Events group by MemberID";
dbAccess.ReadDataThroughAdapter(query, dataTable);
query = $"Select * From CRMember";
DataTable usersTabel = new DataTable();
dbAccess.ReadDataThroughAdapter(query, usersTabel);
DataTable summaryTable = dataTable.Clone();
summaryTable.Columns.Add("Name", typeof(string));
foreach (DataRow row in dataTable.Rows)
{
summaryTable.ImportRow(row);
}
foreach (DataRow row in summaryTable.Rows)
{
for (int n = 0; n < usersTabel.Rows.Count; n++)
if (row["MemberID"].ToString() == usersTabel.Rows[n]["MemberID"].ToString())
{
row["Name"] = $"{usersTabel.Rows[n]["FirstName"]} {usersTabel.Rows[n]["SurName"]}";
}
}
return summaryTable;
}
public DataTable GetUserEvents(string memberID)
{
dataTable = new DataTable();
query = $"SELECT * from Events Where MemberID = '{memberID}' ORDER BY Date DESC";
dbAccess.ReadDataThroughAdapter(query, dataTable);
DataTable date = dataTable.Clone();
date.Columns["Date"].DataType = typeof(string);
foreach (DataRow row in dataTable.Rows)
{
date.ImportRow(row);
}
int i = 0;
foreach (DataRow row in date.Rows)
{
row["Date"] = Convert.ToDateTime(dataTable.Rows[i]["Date"]).ToString("dd.MM.yyyy HH:mm:ss");
i++;
}
return date;
}
#region Work Button
public bool IsWorking(string memberID)
{
dataTable = new DataTable();
query = $"SELECT * from Events where MemberID = '{memberID}'";
dbAccess.ReadDataThroughAdapter(query, dataTable);
foreach(DataRow row in dataTable.Rows)
{
if (row.IsNull("Balance"))
{
return true;
}
}
return false;
}
public void StopWorking(string memberID)
{
dataTable = new DataTable();
int minutes = GetMinutesOfWorkSinceStart(memberID);
minutes -= (480 + GetUserMinutesOnBreak(memberID)); // 8 hours, odejmujemy 8 godzin oraz czas spędzony na przerwie aby sprawdzić różnice i dodać reszte do nadrobienia
dataTable.Rows[0]["Balance"] = minutes;
UpdateEvents(dataTable);
}
public void StartWorking(string memberID)
{
if (GetMinutesOfWorkSinceStart(memberID) > 840) // 14 godzin, sprawdzamy czy nie ma recordu z wczoraj
{
DeleteLetestNullRow(memberID);
}
AddNewEvent(memberID, 0);
}
private int GetMinutesOfWorkSinceStart(string memberID)
{
return GetMinutesFromDateTimeInDataBase(memberID, "Balance", "Date");
}
#endregion Work Button
#region Break Button
public void StartBreak(string memberID)
{
dataTable = new DataTable();
query = $"SELECT * from Events where Balance IS NULL AND MemberId = '{memberID}'";
dbAccess.ReadDataThroughAdapter(query, dataTable);
dataTable.Rows[0]["BeginningOfTheLatestBreak"] = DateTime.Now;
UpdateEvents(dataTable);
}
public void FinishBreak(string memberID)
{
dataTable = new DataTable();
query = $"SELECT * from Events where Balance IS NULL AND MemberId = '{memberID}'";
dbAccess.ReadDataThroughAdapter(query, dataTable);
int minutesOnBreak = Convert.ToInt32((DateTime.Now - Convert.ToDateTime(dataTable.Rows[0]["BeginningOfTheLatestBreak"])).TotalMinutes);
dataTable.Rows[0]["BreakTime"] = Convert.ToInt32(dataTable.Rows[0]["BreakTime"]) + minutesOnBreak;
dataTable.Rows[0]["BeginningOfTheLatestBreak"] = DBNull.Value;
UpdateEvents(dataTable);
}
public bool IsOnBreak(string memberID)
{
dataTable = new DataTable();
query = $"SELECT * from Events where Balance IS NULL AND MemberId = '{memberID}'";
dbAccess.ReadDataThroughAdapter(query, dataTable);
if (dataTable.Rows.Count != 0 && dataTable.Rows[0]["BeginningOfTheLatestBreak"] != DBNull.Value)
{
return true;
}
return false;
}
private int GetUserMinutesOnBreak(string memberID)
{
dataTable = new DataTable();
query = $"SELECT * from Events where Balance IS NULL AND MemberId = '{memberID}'";
dbAccess.ReadDataThroughAdapter(query, dataTable);
int minutesOnBreak = Convert.ToInt32(dataTable.Rows[0]["BreakTime"]);
return minutesOnBreak;
}
#endregion Break Button
private int GetMinutesFromDateTimeInDataBase(string memberID, string nullColumnName, string dateColumnName) // return 0 if there is no null record
{
query = $"SELECT * from Events where {nullColumnName} IS NULL AND MemberID = '{memberID}'";
dbAccess.ReadDataThroughAdapter(query, dataTable);
if (dataTable.Rows.Count == 0)
{
return 0;
}
DateTime startTime = Convert.ToDateTime(dataTable.Rows[0][dateColumnName]);
if (startTime.Day == DateTime.Today.Day)
{
int minutesOfWork = Convert.ToInt32((DateTime.Now - startTime).TotalMinutes);
return minutesOfWork;
}
return 0;
}
private void DeleteLetestNullRow(string memberID)
{
query = $"DELETE from Events where Balance IS NULL";
SqlCommand deleteCommand = new SqlCommand(query);
dbAccess.ExecuteQuery(deleteCommand);
}
}
}
<file_sep>/RejestracjaCzasuPracy.DB/ValidateDate.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace DatabaseConnection
{
public static class ValidateDate // Class used to Validate login data like name, password, email
{
static DataTable dtValidate = new DataTable();
static DBAccess dbAccess = new DBAccess();
public static bool NamePassword(string name, string password)
{
if(!Password(password))
{
return false;
}
else if (!CheckIfNameAlreadyExist(name))
{
return false;
}
return true;
}
public static bool Password(string password)
{
if (password.Length < 8)
{
return false;
}
else
{
return true;
}
}
public static bool CheckIfNameAlreadyExist(string name)
{
string query = $"Select * from Users Where Name = '{name}'";
dbAccess.ReadDataThroughAdapter(query, dtValidate);
if (dtValidate.Rows.Count != 0)
{
return false;
}
else if (name.Equals(""))
{
return false;
}
else
{
return true;
}
}
public static bool CheckWorkHours(DateTime startDate, DateTime finishtDate)
{
TimeSpan workTime = finishtDate - startDate;
if (workTime.TotalHours != 8)
{
return false;
}
else
{
return true;
}
}
}
}
<file_sep>/RejestracjaCzasuPracy/ClientApp/src/components/Summary.js
import React, { Component } from 'react'
const SummaryDataTable = props => {
return (
<table>
<thead>
<tr>
<th>Balance</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{props.summary}
</tbody>
</table>
)
}
export class Summary extends Component {
constructor(props) {
super(props)
this.state = {
summaryDataTable: '',
}
}
getSummaryDataTable() {
fetch('/api/Event/GetSummaryForAllUsers')
.then(res => res.json())
.then(data =>
this.setState({
summaryDataTable: data,
})
);
}
componentDidMount() {
this.getSummaryDataTable();
}
render() {
const { summaryDataTable } = this.state;
const summary = [];
for (let i = 0; i < summaryDataTable.length; i++) {
summary.push(
<tr key={summaryDataTable[i].memberID}>
<td>{summaryDataTable[i].balance}</td>
<td>{summaryDataTable[i].name}</td>
</tr>
)
}
return (
<section className='summary'>
<div>
<SummaryDataTable summary={summary}/>
<button className='back-to-login' onClick={this.props.backToLogin}>Return to login</button>
</div>
</section>
)
}
}<file_sep>/RejestracjaCzasuPracy.DB/UserManager.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Runtime;
namespace DatabaseConnection
{
public class UserManager
{
string query;
DataTable dataTable = new DataTable();
DBAccess dbAccess = new DBAccess();
public User GetUserWithName(string name)
{
dataTable = new DataTable();
string[] names = SplitUserName(name);
query = $"Select * from CRMember Where FirstName = '{names[0]}' AND SurName = '{names[1]}'";
dbAccess.ReadDataThroughAdapter(query, dataTable);
return CreateNewUserFromDataBase(dataTable);
}
public User GetUserWithID(string memberID)
{
if (!String.IsNullOrEmpty(memberID))
{
dataTable = new DataTable();
query = $"SELECT * from CRMember Where MemberID = '{memberID}'";
dbAccess.ReadDataThroughAdapter(query, dataTable);
return CreateNewUserFromDataBase(dataTable); // can be null
}
return null;
}
public List<User> GetAllUsers()
{
dataTable = new DataTable();
List<User> listOfAllUsers = new List<User>();
query = $"Select * from CRMember";
dbAccess.ReadDataThroughAdapter(query, dataTable);
int i = 0;
foreach (DataRow row in dataTable.Rows)
{
User user = new User
(
dataTable.Rows[i]["MemberID"].ToString(),
dataTable.Rows[i]["FirstName"].ToString(),
dataTable.Rows[i]["SurName"].ToString()
);
listOfAllUsers.Add(user);
i++;
}
return listOfAllUsers;
}
public string[] SplitUserName(string name)
{
// [0] = firstName, [1] = surName
string[] names = name.Split(' ');
return names;
}
User CreateNewUserFromDataBase(DataTable userTable)
{
if (userTable.Rows.Count == 1)
{
User currentUser = new User
(
userTable.Rows[0]["MemberID"].ToString(),
userTable.Rows[0]["FirstName"].ToString(),
userTable.Rows[0]["SurName"].ToString()
);
return currentUser;
}
else
{
return null;
}
}
}
}
<file_sep>/RejestracjaCzasuPracy.DB/DBAccess.cs
using System;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Configuration;
using Microsoft.Extensions.Configuration;
// Microsoft.Data.SqlClient NuGet packet requiered
namespace DatabaseConnection // Class used to execute commands and connect to database
{
public class DBAccess
{
private SqlCommand command = new SqlCommand();
private SqlDataAdapter adapter = new SqlDataAdapter();
private SqlConnection connection = new SqlConnection();
#region Connection Managment
public void CreateConnection()
{
try
{
if (connection.State != ConnectionState.Open)
{
// Connection string is stored in App.config
ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["MainConnection"];
SqlConnectionStringBuilder build = new SqlConnectionStringBuilder(setting.ConnectionString);
connection = new SqlConnection(setting.ConnectionString);
connection.ConnectionString = setting.ConnectionString;
connection.Open();
}
}
catch (Exception ex)
{
throw ex;
}
}
private void CheckConnection()
{
if (connection.State != ConnectionState.Open)
{
CreateConnection();
}
}
#endregion Connection Managment
#region Execute Queries
public int ExecuteDataAdapter(DataTable tblName, string strSelectSql)
{
try
{
CheckConnection();
adapter.SelectCommand.CommandText = strSelectSql;
adapter.SelectCommand.CommandType = CommandType.Text;
SqlCommandBuilder DbCommandBuilder = new SqlCommandBuilder(adapter);
string insert = DbCommandBuilder.GetInsertCommand().CommandText.ToString();
string update = DbCommandBuilder.GetUpdateCommand().CommandText.ToString();
string delete = DbCommandBuilder.GetDeleteCommand().CommandText.ToString();
return adapter.Update(tblName);
}
finally
{
connection.Close();
}
}
public void ReadDataThroughAdapter(string query, DataTable tblName)
{
try
{
CheckConnection();
command.Connection = connection;
command.CommandText = query;
command.CommandType = CommandType.Text;
adapter = new SqlDataAdapter(command);
adapter.Fill(tblName);
}
finally
{
connection.Close();
}
}
public SqlDataReader ReadDataThroughReader(string query)
{
//DataReader used to sequentially read data from a data source
SqlDataReader reader;
try
{
CheckConnection();
command.Connection = connection;
command.CommandText = query;
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
return reader;
}
finally
{
connection.Close();
}
}
public int ExecuteQuery(SqlCommand dbCommand)
{
try
{
CheckConnection();
dbCommand.Connection = connection;
dbCommand.CommandType = CommandType.Text;
return dbCommand.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
#endregion Execute Queries
}
}<file_sep>/RejestracjaCzasuPracy.DB/User.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace DatabaseConnection
{
public class User
{
public string id, name, firstName, surName;
public DateTime startWorkHour;
public DateTime finishWorkHour;
#region Constructors
public User(string _id, string _firstName, string _surName)
{
id = _id;
name = $"{_firstName} {_surName}";
firstName = _firstName;
surName = _surName;
startWorkHour = DateTime.Today.AddHours(9);
finishWorkHour = startWorkHour.AddHours(8);
}
#endregion Constructors
}
}
<file_sep>/RejestracjaCzasuPracy/ClientApp/src/App.js
import React, { Component } from 'react';
import { Login } from './components/Login';
import { Admin } from './components/Admin';
import { Summary } from './components/Summary';
import './components/style.css';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
isLogged: false,
content: '',
inSummary: false,
content2: '',
}
}
onLoggIn = currentId => {
this.setState({
isLogged: true,
content: <Admin id={currentId} onLoggOut={this.onLoggOut} />
});
}
onLoggOut = () => {
this.setState({
isLogged: false,
content: ''
});
}
goToSummary = () => {
this.setState({
inSummary: true,
content2: <Summary backToLogin={this.fromSummaryToLogin} />
})
}
fromSummaryToLogin = () => {
this.setState({
inSummary: false,
content: '',
})
}
render() {
if (this.state.isLogged) return this.state.content
else if (this.state.inSummary) return this.state.content2
else return <Login onLoggIn={this.onLoggIn} goToSummary={this.goToSummary} />
}
}
<file_sep>/RejestracjaCzasuPracy/ClientApp/src/components/Admin.js
import React, { Component } from 'react';
const Informations = props => {
const { userName, summaryUserHours, summaryUserMinutes } = props;
return (
<div className='informations'>
<h1 className='welcome'>Welcome to your profile <span>{userName}</span> </h1>
<h2 className='minutes'>Bilans: <span>{summaryUserHours}</span> hours <span>{summaryUserHours != 0 ? Math.abs(summaryUserMinutes) : summaryUserMinutes}</span> minutes</h2>
<h2 className='work-hours'>Work hours: <span>9 - 17</span></h2>
</div>
)
}
const Buttons = props => {
const { inputValue, inputChange, addNewEvent, goHome, startWork, isWorking, breakClick, isOnBreak } = props;
return (
<React.Fragment>
<div className='record-wrap'>
<input type="number" value={inputValue} onChange={inputChange}/><button className='new-record samebtn' onClick={addNewEvent}>Add new record</button>
</div>
<button className='go-home samebtn' onClick={goHome}>Go Home</button>
<button className='start-finish-work samebtn' onClick={startWork}>{isWorking ? 'Finish your work' : 'Start Working'}</button>
{isWorking ? <button className='take-finish-break samebtn' onClick={breakClick}>{isOnBreak ? 'Finish a break' : 'Take a break'}</button> : null}
</React.Fragment>
)
}
const DataTable = props => {
return (
<table className='admin-table'>
<thead>
<tr>
<th>Date</th>
<th>Balance</th>
<th>BreakTime</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{props.events}
</tbody>
</table>
)
}
export class Admin extends Component {
constructor(props) {
super(props);
this.state = {
currentId: this.props.id,
currentUser: '',
summaryUserMinutes: '',
summaryUserHours: '',
isWorking: '',
isOnBreak: '',
inputValue: '',
dataTable: '',
}
}
handleInputChange = e => {
this.setState({
inputValue: e.target.value,
})
}
sendUserId() {
fetch('/api/User/GetUser?memberID=' + this.state.currentId)
.then(res => res.json())
.then(data =>
this.setState({
currentUser: data
})
);
}
isWorking() {
fetch('/api/Event/IsWorking?memberID=' + this.state.currentId)
.then(res => res.json())
.then(data =>
this.setState({
isWorking: data
})
);
}
workButtonClick = () => {
fetch('/api/Event/WorkButton?memberID=' + this.state.currentId)
.then(res => res.json())
.then(data =>
this.setState({
isWorking: data
})
);
this.isOnBreak();
this.updateDataAfter();
}
isOnBreak() {
fetch('/api/Event/IsOnBreak?memberID=' + this.state.currentId)
.then(res => res.json())
.then(data =>
this.setState({
isOnBreak: data
})
);
}
breakButtonClick = () => {
fetch('/api/Event/BreakButton?memberID=' + this.state.currentId)
.then(res => res.json())
.then(data =>
this.setState({
isOnBreak: data
})
);
}
goHomeButton = () => {
// eslint-disable-next-line no-restricted-globals
const alertConfirm = confirm('Are you sure you want to go home?')
if (alertConfirm) {
fetch('/api/Event/GoHome?memberID=' + this.state.currentId)
this.updateDataAfter();
} else return null;
}
addNewEvent = () => {
fetch('/api/Event/AddNewEvent?memberID=' + this.state.currentId + '&minutes=' + this.state.inputValue)
this.setState({
inputValue: '',
})
this.updateDataAfter();
}
updateDataAfter = () => {
setTimeout(() => {
this.updateData();
}, 50);
}
updateData() {
fetch('/api/Event/RefreshData?memberID=' + this.state.currentId)
.then(res => res.json())
.then(data =>
this.setState({
dataTable: data.userEvents,
summaryUserHours: Math.trunc(data.balance/60),
summaryUserMinutes: data.balance%60,
})
)
}
handleDeleteTable = (id) => {
// eslint-disable-next-line no-restricted-globals
const alertConfirm = confirm('Are you sure you want to delete this record?')
if (alertConfirm) {
fetch('/api/Event/DeleteEvent?eventID=' + id + '&memberID=' + this.state.currentId)
.then(result => {
if (result.ok) {
this.updateDataAfter();
} else {
return result.text().then(message => {
throw message;
});
}
});
} else return null
}
componentDidMount() {
this.sendUserId();
this.isWorking();
this.isOnBreak();
this.updateDataAfter();
}
render() {
const { dataTable, currentUser , summaryUserMinutes, summaryUserHours ,inputValue, isWorking, isOnBreak } = this.state;
const events = [];
for (let i = 0; i < dataTable.length; i++) {
const id = dataTable[i].eventID;
events.push(
<tr key={id}>
<td>{dataTable[i].date}</td>
<td>{dataTable[i].balance}</td>
<td>{dataTable[i].breakTime}</td>
<td><button className='delete' onClick={() => this.handleDeleteTable(id)}>X</button></td>
</tr>
)
}
return (
<div className='admin'>
<Informations userName={currentUser.name} summaryUserMinutes={summaryUserMinutes} summaryUserHours={summaryUserHours} />
<Buttons
inputValue={inputValue}
inputChange={this.handleInputChange}
addNewEvent={this.addNewEvent}
goHome={this.goHomeButton}
startWork={this.workButtonClick}
isWorking={isWorking}
breakClick={this.breakButtonClick}
isOnBreak={isOnBreak}
/>
<DataTable events={events} />
<button className='logout' onClick={this.props.onLoggOut}>Log out</button>
</div>
)
}
}<file_sep>/RejestracjaCzasuPracy/Controllers/UserController.cs
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DatabaseConnection;
namespace RejestracjaCzasuPracy.Controllers
{
[Route("api/[controller]")]
public class UserController : Controller
{
UserManager userManager = new UserManager();
[HttpGet("[action]")]
public ActionResult GetAllUsers()
{
List<User> allUsers = userManager.GetAllUsers();
if (allUsers != null)
return Ok(allUsers);
return BadRequest();
}
[HttpGet("[action]")]
public ActionResult GetUser(string memberID)
{
User currnetUser = userManager.GetUserWithID(memberID);
if (currnetUser != null)
return Ok(currnetUser);
return BadRequest();
}
}
}
| 86a6d39876de5e1506199ba8c9b01729ee462383 | [
"JavaScript",
"C#"
] | 11 | JavaScript | Grzanekkk/Rejestracja-Czasu-Pracy | 8403d57324c357541cd1a66a06341e889c87a89c | a1c5ae342009f0b56c8ff632b95bc51fd953bf80 |
refs/heads/master | <file_sep><?php
interface DBInterface
{
public function connect($host, $username, $password, $database, $port);
public function query(string $sql);
public function error(): string;
public function errno(): int;
public function numRows($result): int;
public function selectDb($database);
public function fetchAssoc($result);
public function fetchRow($result);
public function fetchArray($result, $type);
public function affectedRows(): int;
public function escapeString(string $string): string;
public function lastInsertId(): int;
}<file_sep><?php
class DB
{
private $driver;
private static $instance;
private static $queries = [];
private function __construct()
{
}
private function __clone()
{
}
public function setDriver(DBInterface $driver)
{
$this->driver = $driver;
return $this;
}
public static function getInstance()
{
if (self::$instance) {
return self::$instance;
}
$instance = new self;
$driver = new DBMysqli();
$instance->setDriver($driver);
return self::$instance = $instance;
}
public function connect($host, $username, $password, $database, $port)
{
return $this->driver->connect($host, $username, $password, $database, $port);
}
public function query(string $sql)
{
try {
return $this->driver->query($sql);
} catch (\Exception $e) {
throw new \DatabaseException($sql, $e->getMessage());
}
}
public function error()
{
return $this->driver->error();
}
public function errno()
{
return $this->driver->errno();
}
public function numRows($result)
{
return $this->driver->numRows($result);
}
public function select_db($database)
{
return $this->driver->selectDb($database);
}
public function fetchAssoc($result)
{
return $this->driver->fetchAssoc($result);
}
public function fetchRow($result)
{
return $this->driver->fetchRow($result);
}
public function fetchArray($result, $type = null)
{
return $this->driver->fetchArray($result, $type);
}
public function affectedRows()
{
return $this->driver->affectedRows();
}
public function escapeString(string $string)
{
return $this->driver->escapeString($string);
}
public function lastInsertId()
{
return $this->driver->lastInsertId();
}
}<file_sep><?php
class DBMysqli implements DBInterface
{
private $mysqli;
public function connect($host, $username, $password, $database, $port)
{
$mysqli = new mysqli($host, $username, $password, $database, $port);
/* check connection */
if (mysqli_connect_errno()) {
throw new \DatabaseException('', mysqli_connect_error());
}
/* activate reporting */
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX;
return $this->mysqli = $mysqli;
}
public function query(string $sql)
{
return $this->mysqli->query($sql);
}
public function error(): string
{
return $this->mysqli->error;
}
public function errno(): int
{
return $this->mysqli->errno;
}
public function numRows($mysqliResult): int
{
return $mysqliResult->num_rows;
}
public function selectDb($database)
{
return $this->mysqli->select_db($database);
}
public function fetchAssoc($mysqliResult)
{
return $mysqliResult->fetch_assoc();
}
public function fetchRow($mysqliResult)
{
return $mysqliResult->fetch_row();
}
public function fetchArray($mysqliResult, $type)
{
if (is_null($type)) {
$type = MYSQLI_BOTH;
}
return $mysqliResult->fetch_array($type);
}
public function affectedRows(): int
{
return $this->mysqli->affected_rows;
}
public function escapeString(string $string): string
{
return $this->mysqli->real_escape_string($string);
}
public function lastInsertId(): int
{
return $this->mysqli->insert_id;
}
}<file_sep><?php
function mysql_connect($host, $username, $password, $database, $port)
{
return DB::getInstance()->connect($host, $username, $password, $database, $port);
}
function mysql_errno()
{
return DB::getInstance()->errno();
}
function mysql_error()
{
return DB::getInstance()->error();
}
function mysql_query(string $sql)
{
return DB::getInstance()->query($sql);
}
function mysql_select_db($database)
{
return DB::getInstance()->select_db($database);
}
function mysql_num_rows($result)
{
return DB::getInstance()->numRows($result);
}
function mysql_fetch_array($result, $type = null)
{
return DB::getInstance()->fetchArray($result, $type);
}
function mysql_fetch_assoc($result)
{
return DB::getInstance()->fetchAssoc($result);
}
function mysql_fetch_row($result)
{
return DB::getInstance()->fetchRow($result);
}
function mysql_affected_rows()
{
return DB::getInstance()->affectedRows();
}
function mysql_real_escape_string($string)
{
return DB::getInstance()->escapeString($string);
}
function mysql_insert_id()
{
return DB::getInstance()->lastInsertId();
}
<file_sep><?php
class RedisCache {
public $isEnabled;
public $clearCache = 0;
public $language = 'en';
public $Page = array();
public $Row = 1;
public $Part = 0;
public $MemKey = "";
public $Duration = 0;
public $cacheReadTimes = 0;
public $cacheWriteTimes = 0;
public $keyHits = array();
public $languageFolderArray = array();
/** @var Redis */
public $redis;
function __construct() {
$success = $this->connect($host = 'localhost', $port = 6379); // Connect to Redis
if ($success) {
$this->isEnabled = 1;
} else {
$this->isEnabled = 0;
}
}
private function connect($host, $port)
{
global $BASIC, $TWEAK;
$redis = new Redis();
$params = [
$BASIC['redis_host'],
];
if (!empty($BASIC['redis_port'])) {
$params[] = $BASIC['redis_port'];
}
if (!empty($BASIC['redis_timeout'])) {
$params[] = $BASIC['redis_timeout'];
}
try {
$connectResult = $redis->connect(...$params);
$auth = [];
if (!empty($BASIC['redis_password'])) {
$auth['pass'] = $BASIC['redis_password'];
if (!empty($BASIC['redis_username'])) {
$auth['user'] = $BASIC['redis_username'];
}
$connectResult = $connectResult && $redis->auth($auth);
}
if ($connectResult) {
$this->redis = $redis;
if (is_numeric($BASIC['redis_database'])) {
$redis->select($BASIC['redis_database']);
}
}
return $connectResult;
} catch (\Exception $exception) {
return false;
}
}
function getIsEnabled() {
return $this->isEnabled;
}
function setClearCache($isEnabled) {
$this->clearCache = $isEnabled;
}
function getLanguageFolderArray() {
return $this->languageFolderArray;
}
function setLanguageFolderArray($languageFolderArray) {
$this->languageFolderArray = $languageFolderArray;
}
function getClearCache() {
return $this->clearCache;
}
function setLanguage($language) {
$this->language = $language;
}
function getLanguage() {
return $this->language;
}
function new_page($MemKey = '', $Duration = 3600, $Lang = true) {
if ($Lang) {
$language = $this->getLanguage();
$this->MemKey = $language."_".$MemKey;
} else {
$this->MemKey = $MemKey;
}
$this->Duration = $Duration;
$this->Row = 1;
$this->Part = 0;
$this->Page = array();
}
function set_key(){
}
//---------- Adding functions ----------//
function add_row(){
$this->Part = 0;
$this->Page[$this->Row] = array();
}
function end_row(){
$this->Row++;
}
function add_part(){
ob_start();
}
function end_part(){
$this->Page[$this->Row][$this->Part]=ob_get_clean();
$this->Part++;
}
// Shorthand for:
// add_row();
// add_part();
// You should only use this function if the row is only going to have one part in it (convention),
// although it will theoretically work with multiple parts.
function add_whole_row(){
$this->Part = 0;
$this->Page[$this->Row] = array();
ob_start();
}
// Shorthand for:
// end_part();
// end_row();
// You should only use this function if the row is only going to have one part in it (convention),
// although it will theoretically work with multiple parts.
function end_whole_row(){
$this->Page[$this->Row][$this->Part]=ob_get_clean();
$this->Row++;
}
// Set a variable that will only be availabe when the system is on its row
// This variable is stored in the same way as pages, so don't use an integer for the $Key.
function set_row_value($Key, $Value){
$this->Page[$this->Row][$Key] = $Value;
}
// Set a variable that will always be available, no matter what row the system is on.
// This variable is stored in the same way as rows, so don't use an integer for the $Key.
function set_constant_value($Key, $Value){
$this->Page[$Key] = $Value;
}
// Inserts a 'false' value into a row, which breaks out of while loops.
// This is not necessary if the end of $this->Page is also the end of the while loop.
function break_loop(){
if(count($this->Page)>0){
$this->Page[$this->Row] = FALSE;
$this->Row++;
}
}
//---------- Locking functions ----------//
// These functions 'lock' a key.
// Users cannot proceed until it is unlocked.
function lock($Key){
$this->cache_value('lock_'.$Key, 'true', 3600);
}
function unlock($Key) {
// $this->delete('lock_'.$Key);
$this->redis->del('lock_'.$Key);
}
//---------- Caching functions ----------//
// Cache $this->Page and resets $this->Row and $this->Part
function cache_page(){
$this->cache_value($this->MemKey,$this->Page, $this->Duration);
$this->Row = 0;
$this->Part = 0;
}
// Exact same as cache_page, but does not store the page in cache
// This is so that we can use classes that normally cache values in
// situations where caching is not required
function setup_page(){
$this->Row = 0;
$this->Part = 0;
}
// Wrapper for Memcache::set, with the zlib option removed and default duration of 1 hour
function cache_value($Key, $Value, $Duration = 3600){
if (!$this->getIsEnabled()) {
return;
}
$Value = $this->serialize($Value);
// $this->set($Key,$Value, 0, $Duration);
$this->redis->set($Key, $Value, $Duration);
$this->cacheWriteTimes++;
$this->keyHits['write'][$Key] = !isset($this->keyHits['write'][$Key]) ? 1 : $this->keyHits['write'][$Key]+1;
}
//---------- Getting functions ----------//
// Returns the next row in the page
// If there's only one part in the row, return that part.
function next_row(){
$this->Row++;
$this->Part = 0;
if(!isset($this->Page[$this->Row]) || $this->Page[$this->Row] == false){
return false;
}
elseif(count($this->Page[$this->Row]) == 1){
return $this->Page[$this->Row][0];
}
else {
return $this->Page[$this->Row];
}
}
// Returns the next part in the row
function next_part(){
$Return = $this->Page[$this->Row][$this->Part];
$this->Part++;
return $Return;
}
// Returns a 'row value' (a variable that changes for each row - see above).
function get_row_value($Key){
return $this->Page[$this->Row][$Key];
}
// Returns a 'constant value' (a variable that doesn't change with the rows - see above)
function get_constant_value($Key){
return $this->Page[$Key];
}
// If a cached version of the page exists, set $this->Page to it and return true.
// Otherwise, return false.
function get_page(){
$Result = $this->get_value($this->MemKey);
if($Result){
$this->Row = 0;
$this->Part = 0;
$this->Page = $Result;
return true;
} else {
return false;
}
}
// Wrapper for Memcache::get. Why? Because wrappers are cool.
function get_value($Key) {
if (!$this->getIsEnabled()) {
return false;
}
if($this->getClearCache()){
$this->delete_value($Key);
return false;
}
// If we've locked it
// <NAME>: we disable the following lock feature 'cause we don't need it and it doubles the time to fetch a value from a key
/*while($Lock = $this->get('lock_'.$Key)){
sleep(2);
}*/
$Return = $this->redis->get($Key);
$Return = ! is_null($Return) ? $this->unserialize($Return) : null;
$this->cacheReadTimes++;
$this->keyHits['read'][$Key] = !isset($this->keyHits['read'][$Key]) ? 1 : $this->keyHits['read'][$Key]+1;
return $Return;
}
// Wrapper for Memcache::delete. For a reason, see above.
function delete_value($Key, $AllLang = false){
if (!$this->getIsEnabled()) {
return 0;
}
if ($AllLang){
$langfolder_array = $this->getLanguageFolderArray();
foreach($langfolder_array as $lf)
$this->redis->del($lf."_".$Key);
}
else {
$this->redis->del($Key);
}
}
function getCacheReadTimes() {
return $this->cacheReadTimes;
}
function getCacheWriteTimes() {
return $this->cacheWriteTimes;
}
function getKeyHits ($type='read') {
return (array)$this->keyHits[$type];
}
/**
* Serialize the value.
*
* @param mixed $value
* @return mixed
*/
protected function serialize($value)
{
return is_numeric($value) && ! in_array($value, [INF, -INF]) && ! is_nan($value) ? $value : serialize($value);
}
/**
* Unserialize the value.
*
* @param mixed $value
* @return mixed
*/
protected function unserialize($value)
{
return is_numeric($value) ? $value : unserialize($value);
}
}
<file_sep><?php
class DatabaseException extends \Exception
{
public function __construct($query, $message)
{
parent::__construct("$message [$query]");
}
} | 94484d106c1777ed8955d5636550957884280a6f | [
"PHP"
] | 6 | PHP | xiaomlove/nexusphp-php7-polyfill | b8d641eb9bc07437d44a7a71689abaa876f59ad1 | 772f40e81842e688e8ef21afb336ba38a378cb8d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.